From 69264ce165412a4fd759e5f0ecf6edb6624bbaa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Mon, 30 Nov 2026 19:14:57 +0100 Subject: [PATCH] Secure Sakani portal and show full album titles --- .dockerignore | 54 ++++ Dockerfile | 8 +- compose.yaml | 7 +- docs/operations.md | 15 +- next.config.ts | 5 +- scripts/create-admin.ts | 54 ++-- .../[downloadId]/file/download-handler.ts | 6 + .../downloads/[downloadId]/file/route.test.ts | 18 ++ .../bulk-download/bulk-handler.test.ts | 108 +++++++- .../lightbox/bulk-download/bulk-handler.ts | 245 ++++++++---------- src/app/api/lightbox/bulk-download/route.ts | 27 +- src/app/redaktion/alben/[albumId]/page.tsx | 3 +- src/app/redaktion/alben/page.tsx | 2 +- .../DownloadLightboxForm.test.tsx | 55 ++++ .../leuchtkasten/DownloadLightboxForm.tsx | 194 ++++++++++---- .../redaktion/leuchtkasten/access.test.tsx | 79 ++++++ src/app/redaktion/leuchtkasten/actions.ts | 8 +- src/app/redaktion/leuchtkasten/page.tsx | 62 +++-- src/app/zwei-faktor/wizard.tsx | 19 +- src/components/layout/app-shell.test.tsx | 20 ++ src/components/layout/app-shell.tsx | 19 +- src/modules/albums/catalog-content.test.tsx | 28 +- src/modules/albums/catalog-content.tsx | 6 +- src/modules/albums/catalog.test.ts | 19 +- src/modules/albums/catalog.ts | 46 ++-- src/modules/albums/filter.test.ts | 43 ++- src/modules/albums/filter.ts | 25 +- src/modules/albums/photo-access.test.ts | 57 ++++ src/modules/albums/photo-access.ts | 94 +++++++ src/modules/albums/photo-gallery.tsx | 60 ++--- src/modules/auth/admin-bootstrap.test.ts | 27 ++ src/modules/auth/admin-bootstrap.ts | 107 +++----- src/modules/auth/auth.test.ts | 82 ++++++ src/modules/auth/auth.ts | 40 ++- src/modules/auth/principal.test.ts | 4 +- src/modules/auth/principal.ts | 9 +- src/modules/auth/public-forms.test.tsx | 38 ++- src/modules/auth/public-forms.tsx | 41 ++- src/modules/auth/registration.test.ts | 30 --- src/modules/downloads/service.ts | 9 +- src/modules/downloads/stream.ts | 14 +- src/modules/immich/client.ts | 3 - src/modules/lightbox/service.ts | 3 - src/modules/usages/service.test.ts | 7 +- src/modules/usages/service.ts | 65 +++-- src/modules/usages/types.ts | 2 + tests/db/admin-seed.test.ts | 35 +++ tests/db/download-delivery.test.ts | 8 +- tests/db/usage-accounting.test.ts | 53 +++- 49 files changed, 1362 insertions(+), 601 deletions(-) create mode 100644 .dockerignore create mode 100644 src/app/redaktion/leuchtkasten/DownloadLightboxForm.test.tsx create mode 100644 src/app/redaktion/leuchtkasten/access.test.tsx create mode 100644 src/modules/albums/photo-access.test.ts create mode 100644 src/modules/albums/photo-access.ts create mode 100644 src/modules/auth/admin-bootstrap.test.ts create mode 100644 tests/db/admin-seed.test.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9c0f6a7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,54 @@ +** +!Dockerfile +!package.json +!pnpm-lock.yaml +!pnpm-workspace.yaml +!next.config.ts +!next-env.d.ts +!postcss.config.mjs +!tsconfig.json +!drizzle.config.ts +!src/ +!src/**/*.ts +!src/**/*.tsx +!src/**/*.css +!src/modules/pdf/fonts/*.ttf +!src/modules/pdf/fonts/LICENSE.txt +!public/ +!public/brand/ +!public/brand/logo-black.png +!public/brand/logo-white.png +!drizzle/ +!drizzle/0000_baseline.sql +!drizzle/0001_add_announcements.sql +!drizzle/meta/ +!drizzle/meta/_journal.json +!scripts/ +!scripts/backup-db.sh +!scripts/check-smtp.ts +!scripts/create-admin.ts +!scripts/preflight.ts +**/.* +**/.*/** +**/*.env +**/worktrees +**/worktrees/** +**/*credentials* +**/secrets +**/secrets.* +**/*.pem +**/*.key +**/*.p12 +**/*.pfx +**/*.sql +!drizzle/0000_baseline.sql +!drizzle/0001_add_announcements.sql +**/*.dump +**/*.backup +**/*.bak +**/*.tar +**/*.gz +**/*.zip +**/*.sqlite* +**/backup +**/backups diff --git a/Dockerfile b/Dockerfile index 175189d..fc63efb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,13 +6,17 @@ RUN corepack enable && corepack prepare pnpm@10.34.5 --activate FROM base AS dependencies WORKDIR /app -COPY package.json pnpm-lock.yaml ./ +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ RUN pnpm install --frozen-lockfile FROM base AS builder WORKDIR /app COPY --from=dependencies /app/node_modules ./node_modules -COPY . . +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml next.config.ts next-env.d.ts tsconfig.json postcss.config.mjs drizzle.config.ts ./ +COPY src ./src +COPY public ./public +COPY drizzle ./drizzle +COPY scripts ./scripts # Set build-time dummy env vars required for static layout evaluation during next build ENV NODE_ENV=production diff --git a/compose.yaml b/compose.yaml index 2a0799b..95a34e8 100644 --- a/compose.yaml +++ b/compose.yaml @@ -70,16 +70,15 @@ services: - portal-internal profiles: ["ops"] - # One-shot: seed the first admin. Override the command to pass credentials: - # docker compose --profile ops run --rm seed \ - # pnpm tsx scripts/create-admin.ts admin@example.de "Password!" "Name" + # One-shot: create a new admin. See docs/operations.md for the stdin workflow. seed: build: context: . dockerfile: Dockerfile target: builder environment: *portal-env - command: ["pnpm", "tsx", "scripts/create-admin.ts"] + entrypoint: ["node", "--conditions=react-server", "--import", "tsx", "scripts/create-admin.ts"] + command: [] depends_on: portal-db: condition: service_healthy diff --git a/docs/operations.md b/docs/operations.md index 6a14c74..bb2d5a6 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -92,11 +92,20 @@ the `ops` compose profile and do not start with `docker compose up`. anymore. Historical (pre-squash) migration files live in `drizzle-history/pre-squash-2026-08/` and are referenced by integration tests only; do not point `drizzle.config.ts` at that folder. -- **Seed the first admin** (override the command to pass credentials): +- **Seed a new admin** after migrations. In Bash, enter a unique password of + at least 12 characters at the hidden prompt. Compose forwards it on standard + input. The email and display name are the two arguments. ```bash - docker compose --profile ops run --rm seed \ - pnpm tsx scripts/create-admin.ts admin@example.de "AdminPassword!" "Name" + ( + set +x + read -rs -p 'Admin password: ' seed_password || exit 1 + printf '\n' >&2 + printf '%s\n' "$seed_password" | docker compose --profile ops run --rm -i -T seed \ + admin@example.de "Portal Admin" + ) ``` + The seed creates a verified account. An existing email or a failed insert + exits with an error. After the first sign-in, complete the TOTP setup. - **Smoke-test env + connectivity** (DB, Better Auth, SMTP, Immich): ```bash docker compose --profile ops run --rm preflight diff --git a/next.config.ts b/next.config.ts index 2cfdc50..2f87c9e 100644 --- a/next.config.ts +++ b/next.config.ts @@ -16,9 +16,8 @@ const nextConfig: NextConfig = { // ponytail: Next.js App Router injects inline scripts (RSC flight // data + bootstrap) to hydrate client components. Without // 'unsafe-inline' or a nonce in script-src the browser blocks them, - // hydration never runs, and every client form (login, registration, - // reset) falls back to a native GET submit. 'unsafe-inline' for - // scripts is the pragmatic fix; upgrade path is per-request nonces + // client forms cannot hydrate. 'unsafe-inline' for scripts is + // the pragmatic fix; upgrade path is per-request nonces // via middleware (Next attaches the nonce to its inline scripts). value: [ "default-src 'self'", diff --git a/scripts/create-admin.ts b/scripts/create-admin.ts index 03616bd..e1132b8 100644 --- a/scripts/create-admin.ts +++ b/scripts/create-admin.ts @@ -1,44 +1,24 @@ -import { eq } from "drizzle-orm"; -import { auth } from "../src/modules/auth/auth"; -import { db } from "../src/db/client"; -import { users } from "../src/db/schema"; +import { text } from "node:stream/consumers"; + +import { insertAdminCredential, seedAdmin } from "../src/modules/auth/admin-bootstrap"; async function main() { - const email = process.argv[2] || "mail@leon-tonhaeuser.de"; - const password = process.argv[3] || "AdminPassword123!"; - const name = process.argv[4] || "Leon Tonhäuser"; - - console.log(`Creating Admin user: ${email}...`); - - try { - const res = await auth.api.signUpEmail({ - body: { - email, - name, - password, - }, - }); - - const userId = res.user.id; - await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, userId)); - - console.log(`Successfully created Admin account!`); - console.log(`Email: ${email}`); - console.log(`Password: ${password}`); - } catch (error) { - console.error("Error creating admin user:", error); - // If user already exists, update to admin - const [existing] = await db.select().from(users).where(eq(users.email, email)); - if (existing) { - await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, existing.id)); - console.log(`Updated existing user ${email} to ADMIN role.`); - } + const [email, name, ...extra] = process.argv.slice(2); + if (!email || !name || extra.length > 0 || process.stdin.isTTY) { + throw new Error("Supply email and name as arguments and the password on stdin"); } - process.exit(0); + const password = (await text(process.stdin)).replace(/\r?\n$/, ""); + const { db, pool } = await import("../src/db/client"); + try { + await seedAdmin({ email, name, password }, (credential) => insertAdminCredential(db, credential)); + } finally { + await pool.end(); + } + console.log("Admin account created."); } -main().catch((err) => { - console.error("Fatal error:", err); - process.exit(1); +main().catch(() => { + console.error("Admin seed failed. Check the input, database connectivity and whether the email is already registered."); + process.exitCode = 1; }); diff --git a/src/app/api/downloads/[downloadId]/file/download-handler.ts b/src/app/api/downloads/[downloadId]/file/download-handler.ts index 655c86b..203ac1f 100644 --- a/src/app/api/downloads/[downloadId]/file/download-handler.ts +++ b/src/app/api/downloads/[downloadId]/file/download-handler.ts @@ -1,3 +1,4 @@ +import { assertOriginalAccess } from "@/modules/albums/photo-access"; import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream"; import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; @@ -10,6 +11,7 @@ type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string type DownloadFileHandlerDependencies = { requireActiveEditorial: typeof requireActiveEditorial; repository: typeof downloadDeliveryRepository; + assertOriginalAccess: typeof assertOriginalAccess; immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise }; }; @@ -35,6 +37,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen let original: ImmichBinary; try { + await dependencies.assertOriginalAccess( + principal.editorialId, claim.download.assetId, claim.download.albumId, + ); original = await dependencies.immich.getOriginal( claim.download.assetId, request.signal, @@ -163,5 +168,6 @@ function jsonError(status: number, code: string): Response { export const authorizedDownloadFileHandler = createDownloadFileHandler({ requireActiveEditorial, repository: downloadDeliveryRepository, + assertOriginalAccess, immich: immichClient, }); diff --git a/src/app/api/downloads/[downloadId]/file/route.test.ts b/src/app/api/downloads/[downloadId]/file/route.test.ts index 2a4c2cb..0273e31 100644 --- a/src/app/api/downloads/[downloadId]/file/route.test.ts +++ b/src/app/api/downloads/[downloadId]/file/route.test.ts @@ -5,6 +5,7 @@ import { contentDisposition, createDownloadFileHandler } from "./download-handle const editorialId = "11111111-1111-4111-8111-111111111111"; const otherEditorialId = "22222222-2222-4222-8222-222222222222"; +const albumId = "66666666-6666-4666-8666-666666666666"; const downloadId = "33333333-3333-4333-8333-333333333333"; const usageId = "44444444-4444-4444-8444-444444444444"; const assetId = "55555555-5555-4555-8555-555555555555"; @@ -48,6 +49,7 @@ function dependencies(options: { id: downloadId, usageId, assetId, + albumId, filename: "snapshot.jpg", intentKind: options.intentKind ?? "new_usage", }, @@ -63,6 +65,7 @@ function dependencies(options: { return { editorialId }; }), repository, + assertOriginalAccess: vi.fn().mockResolvedValue(undefined), immich: { getOriginal: vi.fn().mockImplementation(async () => { if (options.originalError) throw options.originalError; @@ -226,3 +229,18 @@ test("returns stable authentication semantics without exposing guard details", a expect(second.status).toBe(403); expect(await second.text()).not.toContain("SUSPENDED"); }); + +test.each(["new_usage", "repeat_download"] as const)( + "denies a previously authorized %s after album access is lost", + async (intentKind) => { + const deps = dependencies({ intentKind }); + deps.assertOriginalAccess.mockRejectedValue(new Error("access lost")); + const response = await call(createDownloadFileHandler(deps)); + expect(response.status).toBe(503); + expect(deps.assertOriginalAccess).toHaveBeenCalledWith(editorialId, assetId, albumId); + expect(deps.immich.getOriginal).not.toHaveBeenCalled(); + expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { + voidNewUsage: intentKind === "new_usage", + }); + }, +); diff --git a/src/app/api/lightbox/bulk-download/bulk-handler.test.ts b/src/app/api/lightbox/bulk-download/bulk-handler.test.ts index d89081a..5988c3b 100644 --- a/src/app/api/lightbox/bulk-download/bulk-handler.test.ts +++ b/src/app/api/lightbox/bulk-download/bulk-handler.test.ts @@ -1,6 +1,8 @@ import { PassThrough, type Readable as NodeReadable } from "node:stream"; import { expect, test, vi } from "vitest"; +import { UsageAccountingError } from "@/modules/usages/types"; + import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler"; const editorialId = "11111111-1111-4111-8111-111111111111"; @@ -37,10 +39,9 @@ function fakeArchive(): BulkArchive { function dependencies() { return { + assertOriginalAccess: vi.fn().mockResolvedValue(undefined), requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }), - getGrantedAlbumIds: vi.fn().mockResolvedValue([albumId]), - searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: assetId }] }), - getAsset: vi.fn().mockResolvedValue({ id: assetId, originalFileName: "foto.jpg" }), + findAttempt: vi.fn().mockResolvedValue(undefined), getOriginal: vi.fn().mockResolvedValue({ body: new ReadableStream({ start(controller) { @@ -62,6 +63,7 @@ function dependencies() { id: downloadId, usageId: "55555555-5555-4555-8555-555555555555", assetId, + albumId, filename: "foto.jpg", intentKind: "new_usage", }, @@ -75,11 +77,20 @@ function dependencies() { }; } -function request(origin = "http://portal.test", assetIds = [assetId]) { +const usageId = "55555555-5555-4555-8555-555555555555"; + +function request(origin = "http://portal.test", assetIds = [assetId], repeatUsageId?: string) { return new Request("http://portal.test/api/lightbox/bulk-download", { method: "POST", headers: { "content-type": "application/json", host: "portal.test", origin }, - body: JSON.stringify({ assetIds, purpose: "Titelgeschichte" }), + body: JSON.stringify({ + items: assetIds.map((id) => ({ + assetId: id, + idempotencyKey: id, + ...(repeatUsageId ? { usageId: repeatUsageId } : { purpose: "Titelgeschichte", albumId }), + })), + maxPriceCents: 1500, + }), }); } @@ -122,8 +133,6 @@ test("rate-limits bulk creation before usages are opened", async () => { test("settles an already claimed first item when preparation of a later item fails", async () => { const deps = dependencies(); - deps.searchPhotos.mockResolvedValue({ items: [{ id: assetId }, { id: secondAssetId }] }); - deps.getAsset.mockImplementation(async (id: string) => ({ id, originalFileName: `${id}.jpg` })); deps.createNewUsage .mockResolvedValueOnce({ id: downloadId }) .mockRejectedValueOnce(new Error("accounting unavailable")); @@ -137,3 +146,88 @@ test("settles an already claimed first item when preparation of a later item fai voidNewUsage: true, }); }); + +test("denies original bytes when a ZIP entry loses album access after preparation", async () => { + const deps = dependencies(); + deps.assertOriginalAccess.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("grant revoked")); + const response = await createBulkDownloadHandler(deps)(request()); + await expect(response.arrayBuffer()).rejects.toThrow(); + expect(deps.assertOriginalAccess).toHaveBeenNthCalledWith(2, editorialId, assetId, albumId); + expect(deps.getOriginal).not.toHaveBeenCalled(); + expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { + voidNewUsage: true, + }); +}); + +test("books a new purpose when explicitly selected despite an eligible older usage", async () => { + const deps = dependencies(); + deps.listPriorUsages.mockResolvedValue([{ id: usageId }]); + const response = await createBulkDownloadHandler(deps)(request()); + await response.arrayBuffer(); + expect(deps.createRepeatDownload).not.toHaveBeenCalled(); + expect(deps.createNewUsage).toHaveBeenCalledWith({ + editorialId, assetId, albumId, purpose: "Titelgeschichte", maxPriceCents: 1500, + idempotencyKey: assetId, + }); +}); + +test("uses a specifically selected previous usage for a free repeat", async () => { + const deps = dependencies(); + deps.listPriorUsages.mockResolvedValue([{ id: "other-usage" }, { id: usageId }]); + deps.createRepeatDownload.mockResolvedValue({ id: downloadId }); + const response = await createBulkDownloadHandler(deps)(request(undefined, undefined, usageId)); + await response.arrayBuffer(); + expect(deps.createNewUsage).not.toHaveBeenCalled(); + expect(deps.createRepeatDownload).toHaveBeenCalledWith({ editorialId, usageId, idempotencyKey: assetId }); +}); + +test("rejects a repeat that does not belong to the selected editorial and image", async () => { + const deps = dependencies(); + deps.listPriorUsages.mockResolvedValue([{ id: "other-usage" }]); + const response = await createBulkDownloadHandler(deps)(request(undefined, undefined, usageId)); + expect(response.status).toBe(404); + expect(deps.listPriorUsages).toHaveBeenCalledWith(editorialId, assetId); + expect(deps.createRepeatDownload).not.toHaveBeenCalled(); + expect(deps.getOriginal).not.toHaveBeenCalled(); +}); + +test("rejects duplicate image selections before any bookings", async () => { + const deps = dependencies(); + const response = await createBulkDownloadHandler(deps)(request(undefined, [assetId, assetId])); + expect(response.status).toBe(400); + expect(deps.createNewUsage).not.toHaveBeenCalled(); +}); + +test("retries a confirmed zero-byte void with a stable successor key", async () => { + const deps = dependencies(); + deps.findAttempt.mockResolvedValueOnce({ + id: downloadId, assetId, usageId, kind: "new_usage", purpose: "Titelgeschichte", + status: "failed_before_delivery", transferredBytes: 0, billingStatus: "voided", + }); + const response = await createBulkDownloadHandler(deps)(request()); + expect(response.status).toBe(200); + await response.arrayBuffer(); + expect(deps.createNewUsage).toHaveBeenCalledWith(expect.objectContaining({ idempotencyKey: downloadId })); + expect(deps.findAttempt).toHaveBeenNthCalledWith(2, editorialId, downloadId); +}); + +test("keeps an interrupted delivery booked and does not retry it as a new usage", async () => { + const deps = dependencies(); + deps.findAttempt.mockResolvedValueOnce({ + id: downloadId, assetId, usageId, kind: "new_usage", purpose: "Titelgeschichte", + status: "interrupted", transferredBytes: 100, billingStatus: "open", + }); + const response = await createBulkDownloadHandler(deps)(request()); + expect(response.status).toBe(409); + expect(deps.createNewUsage).not.toHaveBeenCalled(); + expect(deps.getOriginal).not.toHaveBeenCalled(); +}); + +test("does not create a new booking for a ZIP album that is no longer granted", async () => { + const deps = dependencies(); + deps.assertOriginalAccess.mockRejectedValue(new UsageAccountingError("ALBUM_NOT_GRANTED")); + const response = await createBulkDownloadHandler(deps)(request()); + expect(response.status).toBe(404); + expect(deps.createNewUsage).not.toHaveBeenCalled(); + expect(deps.getOriginal).not.toHaveBeenCalled(); +}); diff --git a/src/app/api/lightbox/bulk-download/bulk-handler.ts b/src/app/api/lightbox/bulk-download/bulk-handler.ts index 547fa03..1360670 100644 --- a/src/app/api/lightbox/bulk-download/bulk-handler.ts +++ b/src/app/api/lightbox/bulk-download/bulk-handler.ts @@ -1,7 +1,9 @@ -import { randomUUID } from "node:crypto"; import { basename } from "node:path"; import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream"; +import { z } from "zod"; + +import type { assertOriginalAccess } from "@/modules/albums/photo-access"; import { PrincipalAuthorizationError } from "@/modules/auth/principal"; import { createBulkDeliveryAccounting, @@ -15,7 +17,11 @@ import { RateLimitExceededError, type ConsumeRateLimit, } from "@/modules/security/rate-limit-guard"; -import { UsageAccountingError } from "@/modules/usages/types"; +import { + UsageAccountingError, + type CreateNewUsageInput, + type CreateRepeatDownloadInput, +} from "@/modules/usages/types"; export type BulkArchive = { pipe(destination: PassThrough): unknown; @@ -24,41 +30,35 @@ export type BulkArchive = { abort(): unknown; }; +type BulkAttempt = { + id: string; + assetId: string; + usageId: string; + kind: string; + purpose: string; + status: string; + transferredBytes: number | null; + billingStatus: string; +}; + type BulkDownloadHandlerDependencies = { + findAttempt(editorialId: string, key: string): Promise; + assertOriginalAccess: typeof assertOriginalAccess; requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>; - getGrantedAlbumIds(editorialId: string): Promise; - searchPhotos(input: { - albumIds: string[]; - type: "IMAGE"; - page: number; - size: number; - withExif: false; - }): Promise<{ items: Array<{ id: string }> }>; - getAsset(assetId: string): Promise<{ id: string; originalFileName: string }>; getOriginal( assetId: string, signal?: AbortSignal, ): Promise<{ body: ReadableStream }>; listPriorUsages(editorialId: string, assetId: string): Promise>; - createNewUsage(input: { - editorialId: string; - assetId: string; - albumId: string; - purpose: string; - reference?: string; - idempotencyKey: string; - }): Promise<{ id: string }>; - createRepeatDownload(input: { - editorialId: string; - usageId: string; - idempotencyKey: string; - }): Promise<{ id: string }>; + createNewUsage(input: CreateNewUsageInput): Promise<{ id: string }>; + createRepeatDownload(input: CreateRepeatDownloadInput): Promise<{ id: string }>; repository: DownloadDeliveryRepository; createArchive(): BulkArchive; consumeRateLimit: ConsumeRateLimit; }; type PreparedDownload = { + albumId: string; assetId: string; downloadId: string; filename: string; @@ -75,37 +75,28 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen downloadIntentsPolicy, ); const payload = await parsePayload(request); - const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId); - const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds); + const items = []; + for (const item of payload.items) { + const idempotencyKey = await resolveRetryKey(dependencies, principal.editorialId, item); + items.push({ ...item, idempotencyKey }); + } const accounting = createBulkDeliveryAccounting(dependencies.repository); - let downloads: PreparedDownload[]; + const downloads: PreparedDownload[] = []; try { - downloads = await prepareDownloads( - dependencies, - principal.editorialId, - payload, - assetToGrantedAlbum, - async (item) => { - const claim = await dependencies.repository.claimAuthorized( - principal.editorialId, - item.downloadId, - ); - if (claim.outcome !== "claimed") { - throw new Error("Fresh bulk-download intent could not be claimed"); - } - accounting.track({ - downloadId: item.downloadId, - intentKind: claim.download.intentKind, - }); - }, - ); + for (const item of items) { + const intent = await createIntent(dependencies, principal.editorialId, item, payload.maxPriceCents); + const claim = await dependencies.repository.claimAuthorized(principal.editorialId, intent.id); + if (claim.outcome !== "claimed") throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + + const { albumId, assetId, filename, intentKind } = claim.download; + accounting.track({ downloadId: intent.id, intentKind }); + downloads.push({ albumId, assetId, filename, downloadId: intent.id }); + } } catch (error) { await accounting.failArchive().catch(() => undefined); throw error; } - if (downloads.length === 0) return plainError(404, "No valid assets found for download"); - const passThrough = new PassThrough(); const archive = dependencies.createArchive(); archive.pipe(passThrough); @@ -125,7 +116,10 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen passThrough, downloads, requestSignal: request.signal, - getOriginal: dependencies.getOriginal, + async getOriginal(item, signal) { + await dependencies.assertOriginalAccess(principal.editorialId, item.assetId, item.albumId); + return dependencies.getOriginal(item.assetId, signal); + }, accounting, }); @@ -143,7 +137,6 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen }, }); } catch (error) { - console.error("[bulk-download] failed:", error); return mappedBulkError(error); } }; @@ -161,13 +154,13 @@ async function produceArchive({ passThrough: PassThrough; downloads: PreparedDownload[]; requestSignal: AbortSignal; - getOriginal: BulkDownloadHandlerDependencies["getOriginal"]; + getOriginal(item: PreparedDownload, signal: AbortSignal): Promise<{ body: ReadableStream }>; accounting: ReturnType; }) { try { for (const item of downloads) { if (requestSignal.aborted) throw new Error("Archive request aborted"); - const original = await getOriginal(item.assetId, requestSignal); + const original = await getOriginal(item, requestSignal); const source = Readable.fromWeb( original.body as unknown as import("node:stream/web").ReadableStream, ); @@ -192,99 +185,77 @@ async function produceArchive({ } } -async function grantedAssetMap( - dependencies: BulkDownloadHandlerDependencies, - grantedAlbumIds: string[], -) { - const result = new Map(); - const albums = await Promise.all( - grantedAlbumIds.map(async (albumId) => { - try { - const page = await dependencies.searchPhotos({ - albumIds: [albumId], - type: "IMAGE", - page: 1, - size: 1_000, - withExif: false, - }); - return { albumId, items: page.items }; - } catch { - return { albumId, items: [] }; - } +const uuid = z.uuid().transform((value) => value.toLowerCase()); +const selectionFields = { assetId: uuid, idempotencyKey: uuid }; +const bulkPayload = z.strictObject({ + items: z.array(z.union([ + z.strictObject({ ...selectionFields, usageId: uuid }), + z.strictObject({ + ...selectionFields, + albumId: uuid, + purpose: z.string().trim().refine((value) => [...value].length >= 3 && [...value].length <= 200), }), - ); - for (const album of albums) { - for (const asset of album.items) { - if (!result.has(asset.id)) result.set(asset.id, album.albumId); - } - } - return result; -} + ])).min(1).max(100), + maxPriceCents: z.number().int().nonnegative(), +}); -async function prepareDownloads( +type Selection = z.output["items"][number]; + +async function resolveRetryKey( dependencies: BulkDownloadHandlerDependencies, editorialId: string, - payload: { assetIds: string[]; purpose: string }, - assetToGrantedAlbum: Map, - onPrepared: (item: PreparedDownload) => Promise, + item: Selection, ) { - const assets = await Promise.all( - payload.assetIds.map(async (assetId) => { - try { - return await dependencies.getAsset(assetId); - } catch { - return null; - } - }), - ); - const downloads: PreparedDownload[] = []; - for (const asset of assets) { - if (!asset) continue; - const albumId = assetToGrantedAlbum.get(asset.id); - if (!albumId) continue; - const prior = await dependencies.listPriorUsages(editorialId, asset.id); - const intent = prior[0] - ? await dependencies.createRepeatDownload({ - editorialId, - usageId: prior[0].id, - idempotencyKey: randomUUID(), - }) - : await dependencies.createNewUsage({ - editorialId, - assetId: asset.id, - albumId, - purpose: payload.purpose, - reference: undefined, - idempotencyKey: randomUUID(), - }); - const prepared = { - assetId: asset.id, - downloadId: intent.id, - filename: asset.originalFileName, - }; - await onPrepared(prepared); - downloads.push(prepared); + let key = item.idempotencyKey; + for (let attempt = 0; attempt < 16; attempt += 1) { + const existing = await dependencies.findAttempt(editorialId, key); + if (!existing) return key; + + const repeat = "usageId" in item; + const sameSelection = existing.assetId === item.assetId && (repeat + ? existing.kind === "repeat_download" && existing.usageId === item.usageId + : existing.kind === "new_usage" && existing.purpose === item.purpose); + if (sameSelection && existing.status === "authorized") return key; + + if (!sameSelection || existing.status !== "failed_before_delivery" || + existing.transferredBytes !== 0 || (!repeat && existing.billingStatus !== "voided")) { + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + } + // Everyone retrying the same voided attempt converges on one new key. + key = existing.id; } - return downloads; + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); +} + +async function createIntent( + dependencies: BulkDownloadHandlerDependencies, + editorialId: string, + item: Selection, + maxPriceCents: number, +) { + if ("usageId" in item) { + const prior = await dependencies.listPriorUsages(editorialId, item.assetId); + if (!prior.some(({ id }) => id === item.usageId)) throw new UsageAccountingError("USAGE_NOT_FOUND"); + return dependencies.createRepeatDownload({ + editorialId, usageId: item.usageId, idempotencyKey: item.idempotencyKey, + }); + } + + await dependencies.assertOriginalAccess(editorialId, item.assetId, item.albumId); + return dependencies.createNewUsage({ ...item, editorialId, maxPriceCents }); } async function parsePayload(request: Request) { - const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown }; - if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) { - throw new BulkInputError(); + const parsed = bulkPayload.safeParse(await request.json().catch(() => null)); + if (!parsed.success) throw new UsageAccountingError("INVALID_INPUT"); + const { items } = parsed.data; + if (new Set(items.map(({ assetId }) => assetId)).size !== items.length || + new Set(items.map(({ idempotencyKey }) => idempotencyKey)).size !== items.length) { + throw new UsageAccountingError("INVALID_INPUT"); } - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; - if (body.assetIds.some((value) => typeof value !== "string" || !uuid.test(value))) { - throw new BulkInputError(); - } - if (typeof body.purpose !== "string" || body.purpose.trim().length === 0 || body.purpose.trim().length > 500) { - throw new BulkInputError(); - } - return { assetIds: body.assetIds as string[], purpose: body.purpose.trim() }; + return parsed.data; } -class BulkInputError extends Error {} - function safeArchiveFilename(value: string) { const cleaned = basename(value) .replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_") @@ -293,13 +264,6 @@ function safeArchiveFilename(value: string) { return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto"; } -function plainError(status: number, message: string) { - return new Response(message, { - status, - headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" }, - }); -} - function mappedBulkError(error: unknown): Response { if (error instanceof RateLimitExceededError) { return jsonError(429, "RATE_LIMITED", { @@ -307,7 +271,6 @@ function mappedBulkError(error: unknown): Response { }); } if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST"); - if (error instanceof BulkInputError) return jsonError(400, "INVALID_INPUT"); if (error instanceof PrincipalAuthorizationError) { return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } diff --git a/src/app/api/lightbox/bulk-download/route.ts b/src/app/api/lightbox/bulk-download/route.ts index 06111d5..5f61e46 100644 --- a/src/app/api/lightbox/bulk-download/route.ts +++ b/src/app/api/lightbox/bulk-download/route.ts @@ -1,4 +1,8 @@ -import { albumGrantService } from "@/modules/albums/grants"; +import { and, eq } from "drizzle-orm"; + +import { db } from "@/db/client"; +import { downloadEvents, usages } from "@/db/schema"; +import { assertOriginalAccess } from "@/modules/albums/photo-access"; import { requireActiveEditorial } from "@/modules/auth/principal"; import { createRepeatDownload } from "@/modules/downloads/service"; import { downloadDeliveryRepository } from "@/modules/downloads/stream"; @@ -12,9 +16,24 @@ const archiver = require("archiver") as { ZipArchive: new (options: unknown) => export const POST = createBulkDownloadHandler({ requireActiveEditorial, - getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId), - searchPhotos: (input) => immichClient.searchPhotos(input), - getAsset: (assetId) => immichClient.getAsset(assetId), + async findAttempt(editorialId, key) { + const [attempt] = await db.select({ + id: downloadEvents.id, + assetId: downloadEvents.immichAssetId, + usageId: downloadEvents.usageId, + kind: downloadEvents.intentKind, + purpose: usages.purpose, + status: downloadEvents.status, + transferredBytes: downloadEvents.transferredBytes, + billingStatus: usages.billingStatus, + }) + .from(downloadEvents) + .innerJoin(usages, and(eq(usages.id, downloadEvents.usageId), eq(usages.editorialAccountId, editorialId))) + .where(and(eq(downloadEvents.editorialAccountId, editorialId), eq(downloadEvents.idempotencyKey, key))) + .limit(1); + return attempt; + }, + assertOriginalAccess, getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal), listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId), createNewUsage: (input) => usageService.createNewUsage(input), diff --git a/src/app/redaktion/alben/[albumId]/page.tsx b/src/app/redaktion/alben/[albumId]/page.tsx index 2559bf2..eab0b41 100644 --- a/src/app/redaktion/alben/[albumId]/page.tsx +++ b/src/app/redaktion/alben/[albumId]/page.tsx @@ -71,11 +71,10 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps {formatCount(result.page.total, "Foto")} gefunden

result.lightboxAssetIds.has(id)).map(({ id }) => id)} /> lightboxAssetIds.has(id)).map(({ id }) => id)} showAlbumName /> diff --git a/src/app/redaktion/leuchtkasten/DownloadLightboxForm.test.tsx b/src/app/redaktion/leuchtkasten/DownloadLightboxForm.test.tsx new file mode 100644 index 0000000..676451d --- /dev/null +++ b/src/app/redaktion/leuchtkasten/DownloadLightboxForm.test.tsx @@ -0,0 +1,55 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, expect, test, vi } from "vitest"; + +import { DownloadLightboxForm } from "./DownloadLightboxForm"; + +vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn() }) })); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +test("confirms new and previous uses separately and preserves the keys after a failed request", async () => { + const fetch = vi.fn().mockRejectedValue(new Error("connection lost")); + vi.stubGlobal("fetch", fetch); + render(); + fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" })); + expect((screen.getByRole("button", { name: "ZIP herunterladen" }) as HTMLButtonElement).disabled).toBe(true); + + fireEvent.change(screen.getByRole("combobox", { name: "first.jpg" }), { target: { value: "new" } }); + fireEvent.change(screen.getByRole("combobox", { name: "second.jpg" }), { target: { value: "prior" } }); + const submit = screen.getByRole("button", { name: "Nutzungen bestätigen und laden" }); + expect(submit.disabled).toBe(true); + fireEvent.change(screen.getByLabelText("Gemeinsamer Zweck für neue Nutzungen"), { + target: { value: "Neuer Artikel" }, + }); + expect(screen.getByRole("status").textContent).toMatch(/1 neue Nutzung.*15,00/); + fireEvent.click(submit); + await waitFor(() => expect(submit.disabled).toBe(false)); + fireEvent.click(submit); + await waitFor(() => expect(submit.disabled).toBe(false)); + + const payload = JSON.parse(fetch.mock.calls[0][1].body); + expect(payload).toEqual({ + maxPriceCents: 1500, + items: [ + { assetId: "first", albumId: "allowed", purpose: "Neuer Artikel", idempotencyKey: expect.any(String) }, + { assetId: "second", usageId: "prior", idempotencyKey: expect.any(String) }, + ], + }); + expect(JSON.parse(fetch.mock.calls[1][1].body)).toEqual(payload); +}); diff --git a/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx b/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx index 8137891..68d4196 100644 --- a/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx +++ b/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx @@ -1,103 +1,189 @@ "use client"; -import { useState, useRef } from "react"; +import { useRef, useState, type FormEvent } from "react"; import { useRouter } from "next/navigation"; import { Alert, Button, Input } from "@sakaniui/react"; import { IconDownload } from "@sakaniui/react/icons"; -export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) { +import { formatBerlinDate } from "@/modules/downloads/format"; +import type { EditorialDownloadOptions } from "@/modules/downloads/stream"; + +type Photo = { assetId: string; albumId: string; filename: string }; +type Choice = { selection: string; purpose?: string }; + +const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }); + +export function DownloadLightboxForm({ + photos, + options, +}: { + photos: Photo[]; + options: EditorialDownloadOptions; +}) { const [loading, setLoading] = useState(false); - const dialogRef = useRef(null); - const [purpose, setPurpose] = useState(""); + const [choices, setChoices] = useState>({}); + const [commonPurpose, setCommonPurpose] = useState(""); const [error, setError] = useState(null); + const dialogRef = useRef(null); + const inFlight = useRef(false); + const intentKeys = useRef(new Map()); const router = useRouter(); - async function handleBulkDownload(e: React.FormEvent) { - e.preventDefault(); - if (!purpose.trim() || assetIds.length === 0) return; + const selected = photos.filter(({ assetId }) => { + const selection = choices[assetId]?.selection; + return Boolean(selection && selection !== "skip"); + }); + const newPhotos = selected.filter(({ assetId }) => choices[assetId].selection === "new"); + const price = priceFormatter.format(options.priceCents / 100); + const ready = selected.length > 0 && selected.length <= 100 && + photos.every(({ assetId }) => currentSelection(assetId)) && + newPhotos.every(({ assetId }) => [...purposeFor(choices[assetId])].length >= 3); + function currentSelection(assetId: string) { + const selection = choices[assetId]?.selection; + if (selection === "new" || selection === "skip") return selection; + return options.priorUsagesByAsset[assetId]?.find(({ id }) => id === selection)?.id ?? ""; + } + + function purposeFor(choice: Choice) { + return choice.purpose?.trim() || commonPurpose.trim(); + } + + async function handleBulkDownload(event: FormEvent) { + event.preventDefault(); + if (!ready || inFlight.current) return; + inFlight.current = true; setLoading(true); setError(null); try { + const items = selected.map(({ assetId, albumId }) => { + const choice = choices[assetId]; + const purpose = choice.selection === "new" ? purposeFor(choice) : undefined; + const key = JSON.stringify([assetId, choice.selection, purpose]); + let idempotencyKey = intentKeys.current.get(key); + if (!idempotencyKey) { + idempotencyKey = crypto.randomUUID(); + intentKeys.current.set(key, idempotencyKey); + } + return purpose + ? { assetId, albumId, purpose, idempotencyKey } + : { assetId, usageId: choice.selection, idempotencyKey }; + }); + const response = await fetch("/api/lightbox/bulk-download", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ assetIds, purpose }), + body: JSON.stringify({ items, maxPriceCents: options.priceCents }), }); if (!response.ok) { - // Surface the server's error code instead of a generic message so the - // real cause (e.g. IMMICH_UNAVAILABLE, REQUEST_FAILED) is visible in the - // browser console — the bulk handler maps UsageAccountingError to codes. - let code: string | undefined; - try { - code = (await response.clone().json()).code; - } catch { - /* non-JSON body (e.g. plain 500) — code stays undefined */ + const payload = await response.json().catch(() => null); + if (payload?.code === "INVALID_PRICE") { + router.refresh(); + throw new Error("Der Tarif hat sich geändert. Bitte prüfen Sie den aktualisierten Preis."); } - const status = response.status; - console.error("[bulk-download] server error:", { status, code }); - throw new Error(`Download fehlgeschlagen (${status}${code ? ` ${code}` : ""})`); + if (payload?.code === "IDEMPOTENCY_CONFLICT") { + router.refresh(); + throw new Error("Der Downloadversuch ist bereits erfasst. Prüfen Sie Ihre Nutzungen, bevor Sie einen neuen Zweck buchen."); + } + throw new Error("Bitte prüfen Sie die Auswahl und versuchen Sie es erneut."); } - // Download the ZIP file const blob = await response.blob(); const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `leuchtkasten-${new Date().toISOString().split("T")[0]}.zip`; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); + const link = document.createElement("a"); + link.href = url; + link.download = "leuchtkasten.zip"; + link.click(); URL.revokeObjectURL(url); + intentKeys.current.clear(); dialogRef.current?.close(); - setPurpose(""); - router.refresh(); // Refresh to update usage history - } catch (err) { - const message = err instanceof Error ? err.message : "Download fehlgeschlagen"; - setError(`Bulk-Download fehlgeschlagen: ${message}`); - console.error(err); + setChoices({}); + setCommonPurpose(""); + router.refresh(); + } catch (error) { + setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut."); } finally { + inFlight.current = false; setLoading(false); } } return ( <> - -
-

Verwendungszweck angeben

-

- Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen. -

+ +

Nutzungen für ZIP-Download

setPurpose(e.target.value)} - placeholder="z.B. Webseite, Social Media" - required - type="text" - value={purpose} + label="Gemeinsamer Zweck für neue Nutzungen" + maxLength={200} + onChange={(event) => setCommonPurpose(event.target.value)} + value={commonPurpose} /> - {error ? : null} +
    + {photos.map(({ assetId, filename }) => { + const choice = choices[assetId]; + return ( +
  • + + {choice?.selection === "new" && ( + { + const purpose = event.target.value; + setChoices((previous) => ({ ...previous, [assetId]: { selection: "new", purpose } })); + }} + value={choice.purpose ?? ""} + /> + )} +
  • + ); + })} +
+ {newPhotos.length > 0 && ( +

+ {newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} · bis{" "} + {priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto. + Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet. +

+ )} + {selected.length > 100 && } + {error && }
-
diff --git a/src/app/redaktion/leuchtkasten/access.test.tsx b/src/app/redaktion/leuchtkasten/access.test.tsx new file mode 100644 index 0000000..143cb9f --- /dev/null +++ b/src/app/redaktion/leuchtkasten/access.test.tsx @@ -0,0 +1,79 @@ +// @vitest-environment jsdom + +import { render, screen, cleanup } from "@testing-library/react"; +import { afterEach, expect, test, vi } from "vitest"; + +const { lightboxService, findGrantedPhoto, assertOriginalAccess, getAsset, options, zipForm } = vi.hoisted(() => ({ + lightboxService: { + getLightboxItems: vi.fn(), + addLightboxItem: vi.fn(), + removeLightboxItem: vi.fn(), + isAssetInLightbox: vi.fn(), + }, + findGrantedPhoto: vi.fn(), + assertOriginalAccess: vi.fn(), + getAsset: vi.fn(), + options: vi.fn(), + zipForm: vi.fn(), +})); + +const editorialId = "55555555-5555-4555-8555-555555555555"; +const photoId = "22222222-2222-4222-8222-222222222222"; +const revokedId = "33333333-3333-4333-8333-333333333333"; + +vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })); +vi.mock("next/headers", () => ({ headers: () => new Headers() })); +vi.mock("../access", () => ({ requireEditorial: async () => ({ editorialId }) })); +vi.mock("@/modules/auth/principal", () => ({ + requireActiveEditorial: async () => ({ editorialId }), +})); +vi.mock("@/modules/lightbox/service", () => ({ lightboxService })); +vi.mock("@/modules/albums/photo-access", () => ({ findGrantedPhoto, assertOriginalAccess })); +vi.mock("@/modules/immich/client", () => ({ immichClient: { getAsset } })); +vi.mock("@/modules/downloads/stream", () => ({ + DOWNLOAD_OPTIONS_MAX_ASSETS: 60, + loadEditorialDownloadOptions: options, +})); +vi.mock("./DownloadLightboxForm", () => ({ DownloadLightboxForm: zipForm })); + +import { toggleLightboxItem } from "./actions"; +import LightboxPage from "./page"; + +afterEach(() => { + cleanup(); + vi.resetAllMocks(); +}); + +test("rejects a new bookmark without current access and can remove the old bookmark", async () => { + lightboxService.isAssetInLightbox.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + findGrantedPhoto.mockResolvedValue(null); + await expect(toggleLightboxItem(revokedId)).rejects.toThrow(); + expect(lightboxService.addLightboxItem).not.toHaveBeenCalled(); + await expect(toggleLightboxItem(revokedId)).resolves.toMatchObject({ isNowInLightbox: false }); + expect(lightboxService.removeLightboxItem).toHaveBeenCalledWith(editorialId, revokedId); + expect(findGrantedPhoto).toHaveBeenCalledTimes(1); +}); + +test("shows a removable placeholder and excludes a revoked bookmark from ZIP options", async () => { + lightboxService.getLightboxItems.mockResolvedValue([{ assetId: photoId }, { assetId: revokedId }]); + findGrantedPhoto.mockResolvedValueOnce({ albumId: "allowed-album", filename: "allowed.jpg" }) + .mockResolvedValueOnce(null); + getAsset.mockResolvedValue({ + id: revokedId, originalFileName: "private.jpg", albums: [{ id: "private-album" }], + }); + options.mockResolvedValue({ priceCents: 1500, priorUsagesByAsset: {} }); + zipForm.mockReturnValue(null); + + render(await LightboxPage()); + + expect(getAsset).not.toHaveBeenCalled(); + expect(screen.queryByText("private.jpg")).toBeNull(); + expect(screen.getByText("Foto derzeit nicht verfügbar")).toBeTruthy(); + expect(screen.getAllByRole("button", { name: "Aus Merkzettel entfernen" })).toHaveLength(2); + expect(options).toHaveBeenCalledWith(editorialId, [photoId], expect.any(Function)); + expect(zipForm.mock.calls[0][0].photos).toEqual([{ assetId: photoId, albumId: "allowed-album", filename: "allowed.jpg" }]); + const allowPrior = options.mock.calls[0][2]; + assertOriginalAccess.mockRejectedValue(new Error("previous album revoked")); + await expect(allowPrior(photoId, "allowed-album")).resolves.toBe(true); + await expect(allowPrior(photoId, "revoked-album")).resolves.toBe(false); +}); diff --git a/src/app/redaktion/leuchtkasten/actions.ts b/src/app/redaktion/leuchtkasten/actions.ts index b77f243..aaf1d2b 100644 --- a/src/app/redaktion/leuchtkasten/actions.ts +++ b/src/app/redaktion/leuchtkasten/actions.ts @@ -2,6 +2,8 @@ import { revalidatePath } from "next/cache"; import { headers } from "next/headers"; +import { findGrantedPhoto } from "@/modules/albums/photo-access"; +import { normalizeUuid } from "@/modules/usages/types"; import { requireActiveEditorial } from "@/modules/auth/principal"; import { lightboxService } from "@/modules/lightbox/service"; @@ -12,7 +14,11 @@ export async function toggleLightboxItem(assetId: string) { if (isInLightbox) { await lightboxService.removeLightboxItem(principal.editorialId, assetId); } else { - await lightboxService.addLightboxItem(principal.editorialId, assetId); + const normalizedAssetId = normalizeUuid(assetId); + if (!(await findGrantedPhoto(principal.editorialId, normalizedAssetId))) { + throw new Error("Foto nicht verfügbar"); + } + await lightboxService.addLightboxItem(principal.editorialId, normalizedAssetId); } // Revalidate routes where lightbox state is shown diff --git a/src/app/redaktion/leuchtkasten/page.tsx b/src/app/redaktion/leuchtkasten/page.tsx index 528f9b8..929135a 100644 --- a/src/app/redaktion/leuchtkasten/page.tsx +++ b/src/app/redaktion/leuchtkasten/page.tsx @@ -3,7 +3,8 @@ import { PageHeader } from "@/components/ui/page-header"; import { Card, EmptyState } from "@/components/ui/sakani"; import { lightboxService } from "@/modules/lightbox/service"; -import { immichClient } from "@/modules/immich/client"; +import { assertOriginalAccess, findGrantedPhoto } from "@/modules/albums/photo-access"; +import { DOWNLOAD_OPTIONS_MAX_ASSETS, loadEditorialDownloadOptions } from "@/modules/downloads/stream"; import Link from "next/link"; import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton"; import { DownloadLightboxForm } from "./DownloadLightboxForm"; @@ -13,13 +14,34 @@ export default async function LightboxPage() { const principal = await requireEditorial(); const items = await lightboxService.getLightboxItems(principal.editorialId); - // Fetch asset details for all items in the lightbox - const assets = items.length > 0 - ? await Promise.all(items.map(i => immichClient.getAsset(i.assetId).catch(() => null))) - : []; - - const validAssets = assets.filter((a): a is NonNullable => a !== null); - const assetMap = new Map(validAssets.map(a => [a.id, a])); + const photos = new Map>>>(); + const lookupDeadline = AbortSignal.timeout(15_000); + for (let start = 0; start < items.length && !lookupDeadline.aborted; start += 8) { + await Promise.all(items.slice(start, start + 8).map(async ({ assetId }) => { + const photo = await findGrantedPhoto(principal.editorialId, assetId, lookupDeadline).catch(() => null); + if (photo) photos.set(assetId, photo); + })); + } + + const downloadable = items.flatMap(({ assetId }) => { + const photo = photos.get(assetId); + return photo ? [{ assetId, ...photo }] : []; + }); + let downloadOptions: Awaited> | undefined; + for (let start = 0; start < downloadable.length; start += DOWNLOAD_OPTIONS_MAX_ASSETS) { + const batch = downloadable.slice(start, start + DOWNLOAD_OPTIONS_MAX_ASSETS); + const options = await loadEditorialDownloadOptions( + principal.editorialId, + batch.map(({ assetId }) => assetId), + async (assetId, albumId) => { + if (photos.get(assetId)?.albumId === albumId) return true; + if (lookupDeadline.aborted) return false; + return assertOriginalAccess(principal.editorialId, assetId, albumId).then(() => true, () => false); + }, + ); + downloadOptions ??= options; + Object.assign(downloadOptions.priorUsagesByAsset, options.priorUsagesByAsset); + } return (
@@ -37,33 +59,37 @@ export default async function LightboxPage() {

{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt

- i.assetId)} /> + {downloadOptions && }
    {items.map((item) => { - const asset = assetMap.get(item.assetId); - if (!asset) return null; - const albumId = asset.albums?.[0]?.id; - const href = albumId - ? `/redaktion/alben/${encodeURIComponent(albumId)}?suche=${encodeURIComponent(asset.originalFileName)}` - : '#'; + const photo = photos.get(item.assetId); + if (!photo) { + return ( +
  • + Foto derzeit nicht verfügbar + +
  • + ); + } + const href = `/redaktion/alben/${encodeURIComponent(photo.albumId)}?suche=${encodeURIComponent(photo.filename)}`; return (
  • {asset.originalFileName
    - - {asset.originalFileName ?? "Unbekannt"} + + {photo.filename}
    diff --git a/src/app/zwei-faktor/wizard.tsx b/src/app/zwei-faktor/wizard.tsx index 683c69c..dfa04e7 100644 --- a/src/app/zwei-faktor/wizard.tsx +++ b/src/app/zwei-faktor/wizard.tsx @@ -46,8 +46,8 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea setError(undefined); try { - const formData = new FormData(event.currentTarget); - const code = String(formData.get("code") ?? "").replace(/\s+/g, ""); + const input = event.currentTarget.querySelector("#mfa-code"); + const code = input?.value.replace(/\s+/g, "") ?? ""; const result = await authClient.twoFactor.verifyTotp({ code }); if (result.error) { setError("Der Code ist ungültig. Bitte prüfen Sie Ihre Authenticator-App."); @@ -86,12 +86,12 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea return (
    {!enabled && step === "password" && ( -
    +
    @@ -132,14 +132,14 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
    )} - +
    +

    Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind.

    - +
    + {signOutFailed && ( +

    + Abmeldung fehlgeschlagen. Bitte versuchen Sie es erneut. +

    + )}
    diff --git a/src/modules/albums/catalog-content.test.tsx b/src/modules/albums/catalog-content.test.tsx index 0b33b46..332b0d1 100644 --- a/src/modules/albums/catalog-content.test.tsx +++ b/src/modules/albums/catalog-content.test.tsx @@ -33,12 +33,12 @@ test("renders granted albums as labelled contact-sheet links", () => { const photo = { id: "asset-1", - type: "IMAGE" as const, - originalFileName: "tor-des-sieges.jpg", - originalMimeType: "image/jpeg", - localDateTime: "2026-08-08T18:42:00.000Z", - fileCreatedAt: null, - albums: [{ id: "heimspiel" }], + filename: "tor-des-sieges.jpg", + takenAt: "2026-08-08T18:42:00.000Z", + width: null, + height: null, + albumId: "heimspiel", + albumName: "Heimspiel gegen Nord", }; test("renders the gallery list labelled by album name", () => { @@ -52,7 +52,6 @@ test("renders the gallery list labelled by album name", () => { test("renders the server-scoped download choices for a catalog photo", () => { render( { }} items={[ { + ...photo, id: "22222222-2222-4222-8222-222222222222", - type: "IMAGE", - originalFileName: "tor.jpg", - originalMimeType: "image/jpeg", - localDateTime: null, - fileCreatedAt: null, - albums: [{ id: "33333333-3333-4333-8333-333333333333" }], + filename: "tor.jpg", + albumId: "33333333-3333-4333-8333-333333333333", }, ]} />, @@ -91,7 +87,7 @@ test("offers the existing download workflow on a global search result and its li items={[{ ...photo, id: "22222222-2222-4222-8222-222222222222", - albums: [{ id: "33333333-3333-4333-8333-333333333333" }], + albumId: "33333333-3333-4333-8333-333333333333", }]} showAlbumName />, @@ -107,8 +103,8 @@ test("opens a full-screen lightbox when a photo tile is clicked", () => { , ); diff --git a/src/modules/albums/catalog-content.tsx b/src/modules/albums/catalog-content.tsx index a6030a5..77f111d 100644 --- a/src/modules/albums/catalog-content.tsx +++ b/src/modules/albums/catalog-content.tsx @@ -11,7 +11,7 @@ import type { VisibleAlbum } from "./catalog"; export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) { return ( -
      +
        {albums.map((album) => (
      • )}
        - {album.albumName} + {album.albumName} {formatCount(album.assetCount, "Foto")}
        @@ -62,7 +62,7 @@ export function PhotoPagination({ }: Readonly<{ albumId: string; currentPage: number; - page: ImmichSearchPage; + page: Pick; query: string; format?: string; jahr?: string; diff --git a/src/modules/albums/catalog.test.ts b/src/modules/albums/catalog.test.ts index 503eb7f..5a68748 100644 --- a/src/modules/albums/catalog.test.ts +++ b/src/modules/albums/catalog.test.ts @@ -81,10 +81,10 @@ test("restores the queried granted album when Immich omits an asset album associ const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 }); - expect(result.items[0]?.albums).toEqual([{ id: "allowed" }]); + expect(result.items[0]?.albumId).toBe("allowed"); }); -test("moves the queried granted album to the active gallery context without losing metadata", async () => { +test("projects only display fields and the queried granted album for the client gallery", async () => { const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] }); immich.searchPhotos.mockResolvedValue({ items: [{ @@ -94,6 +94,8 @@ test("moves the queried granted album to the active gallery context without losi originalMimeType: "image/jpeg", localDateTime: null, fileCreatedAt: null, + originalPath: "/private/photos/tor.jpg", + exifInfo: { exifImageWidth: 1200, exifImageHeight: 800, latitude: 12 }, albums: [ { id: "other", albumName: "Anderes Album" }, { id: "allowed", albumName: "Erlaubtes Album" }, @@ -106,10 +108,15 @@ test("moves the queried granted album to the active gallery context without losi const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 }); - expect(result.items[0]?.albums).toEqual([ - { id: "allowed", albumName: "Erlaubtes Album" }, - { id: "other", albumName: "Anderes Album" }, - ]); + expect(result.items).toEqual([{ + id: "asset-1", + filename: "tor.jpg", + takenAt: null, + width: 1200, + height: 800, + albumId: "allowed", + albumName: "Heimspiel gegen Nord", + }]); }); test("global search keeps hits when a granted album is no longer visible in Immich", async () => { diff --git a/src/modules/albums/catalog.ts b/src/modules/albums/catalog.ts index 6d78434..7a5152c 100644 --- a/src/modules/albums/catalog.ts +++ b/src/modules/albums/catalog.ts @@ -16,6 +16,18 @@ const MAX_DESCRIPTION_LENGTH = 200; export type VisibleAlbum = ImmichAlbumSummary; +export type GalleryPhoto = { + id: string; + filename: string; + takenAt: string | null; + width: number | null; + height: number | null; + albumId: string; + albumName: string | null; +}; + +type GalleryPage = Omit & { items: GalleryPhoto[] }; + export type SearchVisiblePhotosInput = { requestedAlbumId?: string; description?: unknown; @@ -54,7 +66,7 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume } async searchVisiblePhotos( editorialId: string, input: SearchVisiblePhotosInput, - ): Promise { + ): Promise { const description = normalizeDescription(input.description); if (description) { try { @@ -91,10 +103,10 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume } // grant count and narrowed by the description filter, so per-album results // are small. If a huge-grant editorial makes this slow, cap the fan-out // and accept partial coverage. - const visibleIds = new Set((await loadAlbums(immich)).map(({ id }) => id)); + const visibleAlbums = new Map((await loadAlbums(immich)).map(({ id, albumName }) => [id, albumName])); const pages = await Promise.all( - grantedAlbumIds.filter((id) => visibleIds.has(id)) - .map((albumId) => searchAlbum(immich, [albumId], description, page, size)), + grantedAlbumIds.filter((id) => visibleAlbums.has(id)) + .map((albumId) => searchAlbum(immich, [albumId], description, page, size, visibleAlbums.get(albumId))), ); return mergeSearchPages(pages); }, @@ -107,7 +119,8 @@ async function searchAlbum( description: string | undefined, page: number, size: number, -): Promise { + albumName: string | null = null, +): Promise { try { const searchPage = await immich.searchPhotos({ albumIds, @@ -116,25 +129,24 @@ async function searchAlbum( page, size, }); - const queriedAlbumId = albumIds[0]; return { ...searchPage, - items: queriedAlbumId - ? searchPage.items.map((asset) => { - const queriedAlbum = asset.albums.find(({ id }) => id === queriedAlbumId) ?? { id: queriedAlbumId }; - return { - ...asset, - albums: [queriedAlbum, ...asset.albums.filter(({ id }) => id !== queriedAlbumId)], - }; - }) - : searchPage.items, + items: searchPage.items.map((asset) => ({ + id: asset.id, + filename: asset.originalFileName, + takenAt: asset.localDateTime ?? asset.fileCreatedAt, + width: asset.exifInfo?.exifImageWidth ?? null, + height: asset.exifInfo?.exifImageHeight ?? null, + albumId: albumIds[0], + albumName, + })), }; } catch { throw new AlbumCatalogError("IMMICH_UNAVAILABLE"); } } -function mergeSearchPages(pages: ImmichSearchPage[]): ImmichSearchPage { +function mergeSearchPages(pages: GalleryPage[]): GalleryPage { // nextPage/previousPage are unused by callers — they paginate in-app via // paginatePhotos, which recomputes both from the merged item count. return { @@ -145,7 +157,7 @@ function mergeSearchPages(pages: ImmichSearchPage[]): ImmichSearchPage { }; } -function emptySearchPage(): ImmichSearchPage { +function emptySearchPage(): GalleryPage { return { items: [], total: 0, nextPage: null, previousPage: null }; } diff --git a/src/modules/albums/filter.test.ts b/src/modules/albums/filter.test.ts index 66b9ea4..7872d09 100644 --- a/src/modules/albums/filter.test.ts +++ b/src/modules/albums/filter.test.ts @@ -1,25 +1,24 @@ import { expect, test } from "vitest"; import { filterPhotos, matchesOrientation, matchesYear, paginatePhotos } from "./filter"; -import type { ImmichAsset } from "@/modules/immich/types"; +import type { GalleryPhoto } from "./catalog"; -function photo(overrides: Partial & { id: string }): ImmichAsset { +function photo(overrides: Partial & { id: string }): GalleryPhoto { return { - id: overrides.id, - type: "IMAGE", - originalFileName: overrides.originalFileName ?? `${overrides.id}.jpg`, - originalMimeType: "image/jpeg", - localDateTime: overrides.localDateTime ?? null, - fileCreatedAt: overrides.fileCreatedAt ?? null, - albums: overrides.albums ?? [], - exifInfo: overrides.exifInfo ?? null, + filename: `${overrides.id}.jpg`, + takenAt: null, + width: null, + height: null, + albumId: "album", + albumName: null, + ...overrides, }; } test("matchesOrientation distinguishes landscape from portrait via EXIF dimensions", () => { - const landscape = photo({ id: "l", exifInfo: { exifImageWidth: 1600, exifImageHeight: 900 } }); - const portrait = photo({ id: "p", exifInfo: { exifImageWidth: 900, exifImageHeight: 1600 } }); - const square = photo({ id: "s", exifInfo: { exifImageWidth: 1000, exifImageHeight: 1000 } }); + const landscape = photo({ id: "l", width: 1600, height: 900 }); + const portrait = photo({ id: "p", width: 900, height: 1600 }); + const square = photo({ id: "s", width: 1000, height: 1000 }); expect(matchesOrientation(landscape, "quer")).toBe(true); expect(matchesOrientation(landscape, "hoch")).toBe(false); @@ -30,23 +29,23 @@ test("matchesOrientation distinguishes landscape from portrait via EXIF dimensio }); test("matchesOrientation excludes assets with unknown dimensions instead of matching either format", () => { - const unknown = photo({ id: "u", exifInfo: null }); + const unknown = photo({ id: "u" }); expect(matchesOrientation(unknown, "quer")).toBe(false); expect(matchesOrientation(unknown, "hoch")).toBe(false); }); -test("matchesYear compares against localDateTime then fileCreatedAt", () => { - expect(matchesYear(photo({ id: "a", localDateTime: "2026-05-01T10:00:00.000Z" }), "2026")).toBe(true); - expect(matchesYear(photo({ id: "b", localDateTime: "2025-12-31T23:00:00.000Z" }), "2026")).toBe(false); - expect(matchesYear(photo({ id: "c", localDateTime: null, fileCreatedAt: "2026-01-01T00:00:00.000Z" }), "2026")).toBe(true); - expect(matchesYear(photo({ id: "d", localDateTime: null, fileCreatedAt: null }), "2026")).toBe(false); +test("matchesYear compares against the gallery date", () => { + expect(matchesYear(photo({ id: "a", takenAt: "2026-05-01T10:00:00.000Z" }), "2026")).toBe(true); + expect(matchesYear(photo({ id: "b", takenAt: "2025-12-31T23:00:00.000Z" }), "2026")).toBe(false); + expect(matchesYear(photo({ id: "c", takenAt: "2026-01-01T00:00:00.000Z" }), "2026")).toBe(true); + expect(matchesYear(photo({ id: "d", takenAt: null }), "2026")).toBe(false); }); test("filterPhotos applies format and jahr together across the full set", () => { const items = [ - photo({ id: "l26", originalFileName: "land26", localDateTime: "2026-03-01", exifInfo: { exifImageWidth: 2, exifImageHeight: 1 } }), - photo({ id: "p26", originalFileName: "port26", localDateTime: "2026-03-01", exifInfo: { exifImageWidth: 1, exifImageHeight: 2 } }), - photo({ id: "l25", originalFileName: "land25", localDateTime: "2025-03-01", exifInfo: { exifImageWidth: 2, exifImageHeight: 1 } }), + photo({ id: "l26", filename: "land26", takenAt: "2026-03-01", width: 2, height: 1 }), + photo({ id: "p26", filename: "port26", takenAt: "2026-03-01", width: 1, height: 2 }), + photo({ id: "l25", filename: "land25", takenAt: "2025-03-01", width: 2, height: 1 }), ]; expect(filterPhotos(items, { format: "quer" }).map((p) => p.id)).toEqual(["l26", "l25"]); diff --git a/src/modules/albums/filter.ts b/src/modules/albums/filter.ts index a160418..30b11cf 100644 --- a/src/modules/albums/filter.ts +++ b/src/modules/albums/filter.ts @@ -1,6 +1,4 @@ -import type { ImmichAsset } from "@/modules/immich/types"; - -import { normalizePage } from "./catalog"; +import { normalizePage, type GalleryPhoto } from "./catalog"; /** * Filter + paginate a photo set in-app, used by the album detail and the @@ -12,26 +10,25 @@ import { normalizePage } from "./catalog"; * page silently dropped matching photos and reported the unfiltered total. */ -export function matchesOrientation(asset: ImmichAsset, format: string): boolean { - const width = asset.exifInfo?.exifImageWidth ?? 0; - const height = asset.exifInfo?.exifImageHeight ?? 0; +export function matchesOrientation(asset: GalleryPhoto, format: string): boolean { + const width = asset.width ?? 0; + const height = asset.height ?? 0; // Unknown dimensions can't satisfy a format filter — exclude rather than - // show a portrait under "Querformat" (the original bug). `withExif: true` - // keeps this rare in practice. + // show a portrait under "Querformat". if (width <= 0 || height <= 0) return false; const isLandscape = width >= height; return format === "quer" ? isLandscape : !isLandscape; } -export function matchesYear(asset: ImmichAsset, jahr: string): boolean { - const value = asset.localDateTime ?? asset.fileCreatedAt; +export function matchesYear(asset: GalleryPhoto, jahr: string): boolean { + const value = asset.takenAt; return value !== null && value.startsWith(jahr); } export function filterPhotos( - items: ImmichAsset[], + items: GalleryPhoto[], filters: { format?: string; jahr?: string }, -): ImmichAsset[] { +): GalleryPhoto[] { let filtered = items; if (filters.format) { filtered = filtered.filter((asset) => matchesOrientation(asset, filters.format!)); @@ -43,14 +40,14 @@ export function filterPhotos( } export type InAppPage = { - items: ImmichAsset[]; + items: GalleryPhoto[]; total: number; nextPage: number | null; previousPage: number | null; }; export function paginatePhotos( - items: ImmichAsset[], + items: GalleryPhoto[], page: unknown, pageSize: number, ): { result: InAppPage; currentPage: number } { diff --git a/src/modules/albums/photo-access.test.ts b/src/modules/albums/photo-access.test.ts new file mode 100644 index 0000000..9740960 --- /dev/null +++ b/src/modules/albums/photo-access.test.ts @@ -0,0 +1,57 @@ +import { drizzle } from "drizzle-orm/node-postgres"; +import type { Pool } from "pg"; +import { expect, test, vi } from "vitest"; + +import * as schema from "@/db/schema"; + +import { assertOriginalAccess } from "./photo-access"; + +const editorialId = "11111111-1111-4111-8111-111111111111"; +const assetId = "22222222-2222-4222-8222-222222222222"; +const albumId = "33333333-3333-4333-8333-333333333333"; + +function dependencies() { + const query = vi.fn().mockResolvedValue({ rows: [[albumId]] }); + const database = drizzle({ client: { query } as unknown as Pool, schema }); + const searchPhotos = vi.fn().mockResolvedValue({ items: [{ id: assetId }] }); + return { + query, + searchPhotos, + check: () => assertOriginalAccess(editorialId, assetId, albumId, database, { searchPhotos }), + }; +} + +test("checks active editorial and exact grant both before and after checking photo membership", async () => { + const { check, query, searchPhotos } = dependencies(); + await expect(check()).resolves.toBeUndefined(); + expect(query).toHaveBeenCalledTimes(2); + const [statement, values] = query.mock.calls[0]; + expect(statement.text).toContain('"editorial_accounts"."status"'); + expect(statement.text).toContain('"album_grants"."revoked_at" is null'); + expect(values).toEqual([editorialId, "active", albumId]); + expect(searchPhotos).toHaveBeenCalledWith( + { albumIds: [albumId], id: assetId, type: "IMAGE", withExif: false, page: 1, size: 1 }, + undefined, + ); +}); + +test("does not load photo metadata from an already revoked album", async () => { + const { check, query, searchPhotos } = dependencies(); + query.mockResolvedValueOnce({ rows: [] }); + await expect(check()).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" }); + expect(searchPhotos).not.toHaveBeenCalled(); +}); + +test("fails closed if the grant is revoked while looking up membership", async () => { + const { check, query } = dependencies(); + query.mockResolvedValueOnce({ rows: [[albumId]] }).mockResolvedValueOnce({ rows: [] }); + await expect(check()).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" }); +}); + +test("rejects when membership cannot be verified", async () => { + const { check, searchPhotos } = dependencies(); + searchPhotos.mockResolvedValueOnce({ items: [{ id: "another-photo" }] }); + await expect(check()).rejects.toMatchObject({ code: "ASSET_NOT_IN_ALBUM" }); + searchPhotos.mockRejectedValueOnce(new Error("upstream unavailable")); + await expect(check()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" }); +}); diff --git a/src/modules/albums/photo-access.ts b/src/modules/albums/photo-access.ts new file mode 100644 index 0000000..b15e15f --- /dev/null +++ b/src/modules/albums/photo-access.ts @@ -0,0 +1,94 @@ +import "server-only"; + +import { and, eq, isNull, sql } from "drizzle-orm"; + +import { db } from "@/db/client"; +import { albumGrants, editorialAccounts } from "@/db/schema"; +import { immichClient } from "@/modules/immich/client"; +import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types"; + +type PhotoSearch = { + searchPhotos(input: { + albumIds: string[]; + id: string; + type: "IMAGE"; + withExif: false; + page: number; + size: number; + }, signal?: AbortSignal): Promise<{ items: Asset[] }>; +}; + +export async function isAssetInAlbum(immich: PhotoSearch, assetId: string, albumId: string) { + return Boolean(await findPhotoInAlbum(immich, assetId, albumId)); +} + +async function findPhotoInAlbum( + immich: PhotoSearch, assetId: string, albumId: string, signal?: AbortSignal, +) { + try { + const result = await immich.searchPhotos({ + albumIds: [albumId], + id: assetId, + type: "IMAGE", + withExif: false, + page: 1, + size: 1, + }, signal); + return result.items.find((asset) => asset.id === assetId); + } catch { + throw new UsageAccountingError("IMMICH_UNAVAILABLE"); + } +} + +export async function assertOriginalAccess( + editorialId: string, + assetId: string, + albumId: string, + database = db, + immich: PhotoSearch = immichClient, +) { + if ((await activeAlbumIds(editorialId, database, albumId)).length === 0) { + throw new UsageAccountingError("ALBUM_NOT_GRANTED"); + } + if (!(await isAssetInAlbum(immich, assetId, albumId))) { + throw new UsageAccountingError("ASSET_NOT_IN_ALBUM"); + } + if ((await activeAlbumIds(editorialId, database, albumId)).length === 0) { + throw new UsageAccountingError("ALBUM_NOT_GRANTED"); + } +} + +async function activeAlbumIds(editorialId: string, database: typeof db, albumId?: string) { + const grants = await database + .select({ albumId: albumGrants.immichAlbumId }) + .from(albumGrants) + .innerJoin(editorialAccounts, eq(editorialAccounts.id, albumGrants.editorialAccountId)) + .where(and( + eq(editorialAccounts.id, editorialId), + eq(editorialAccounts.status, "active"), + albumId === undefined ? undefined : sql`lower(${albumGrants.immichAlbumId}) = ${albumId.toLowerCase()}`, + isNull(albumGrants.revokedAt), + )); + return [...new Set(grants.map((grant) => grant.albumId.toLowerCase()))]; +} + +export async function findGrantedPhoto( + editorialId: string, assetId: string, signal = AbortSignal.timeout(15_000), +) { + signal.throwIfAborted(); + const normalizedAssetId = normalizeUuid(assetId); + const granted = await activeAlbumIds(editorialId, db); + let unavailable = false; + for (const albumId of granted) { + signal.throwIfAborted(); + const asset = await findPhotoInAlbum(immichClient, normalizedAssetId, albumId, signal).catch(() => { + unavailable = true; + return undefined; + }); + if (asset && (await activeAlbumIds(editorialId, db, albumId)).length > 0) { + return { albumId, filename: asset.originalFileName }; + } + } + if (unavailable) throw new UsageAccountingError("IMMICH_UNAVAILABLE"); + return null; +} diff --git a/src/modules/albums/photo-gallery.tsx b/src/modules/albums/photo-gallery.tsx index ca6a974..9ee413f 100644 --- a/src/modules/albums/photo-gallery.tsx +++ b/src/modules/albums/photo-gallery.tsx @@ -9,14 +9,13 @@ import { IconChevronLeft, IconChevronRight, IconX } from "@sakaniui/react/icons" import { UsageDialog } from "@/components/download/usage-dialog"; import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton"; import type { EditorialDownloadOptions } from "@/modules/downloads/stream"; -import type { ImmichAsset } from "@/modules/immich/types"; +import type { GalleryPhoto } from "./catalog"; import { formatDate, thumbnailUrl } from "./catalog-content"; type PhotoGalleryProps = Readonly<{ - albumId?: string; albumName: string; - items: ImmichAsset[]; + items: GalleryPhoto[]; downloadOptions?: EditorialDownloadOptions; /** Pre-selected asset ids, passed as a plain array (Sets don't cross the RSC boundary). */ lightboxAssetIds?: string[]; @@ -24,7 +23,6 @@ type PhotoGalleryProps = Readonly<{ }>; export function PhotoGallery({ - albumId, albumName, items, downloadOptions, @@ -70,18 +68,17 @@ export function PhotoGallery({ <>
          {items.map((asset, index) => { - const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined); return ( -
        • +
        • @@ -228,11 +224,9 @@ export function PasswordResetForm({ token }: { token?: string }) { event.preventDefault(); setPending(true); setError(undefined); - const formData = new FormData(event.currentTarget); - try { const result = await authClient.resetPassword({ - newPassword: readText(formData, "password"), + newPassword: readText(event.currentTarget, "password"), token, }); if (result.error) { @@ -262,8 +256,8 @@ export function PasswordResetForm({ token }: { token?: string }) { } return ( - - + +