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 (
<>
- }
- onClick={() => dialogRef.current?.showModal()}
- type="button"
- >
- Alle herunterladen
+ } onClick={() => dialogRef.current?.showModal()} type="button">
+ ZIP-Download vorbereiten