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, streamBulkArchiveWithAccounting, } from "@/modules/downloads/bulk-accounting"; import type { DownloadDeliveryRepository } from "@/modules/downloads/stream"; import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; import { downloadIntentsPolicy } from "@/modules/security/rate-limit"; import { enforceRateLimit, RateLimitExceededError, type ConsumeRateLimit, } from "@/modules/security/rate-limit-guard"; import { UsageAccountingError, type CreateNewUsageInput, type CreateRepeatDownloadInput, } from "@/modules/usages/types"; export type BulkArchive = { pipe(destination: PassThrough): unknown; append(source: NodeReadable, options: { name: string }): unknown; finalize(): Promise | unknown; 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 }>; getOriginal( assetId: string, signal?: AbortSignal, ): Promise<{ body: ReadableStream }>; listPriorUsages(editorialId: string, assetId: string): Promise>; 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; }; export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDependencies) { return async function POST(request: Request): Promise { try { assertSameOrigin(request); const principal = await dependencies.requireActiveEditorial(request.headers); await enforceRateLimit( dependencies.consumeRateLimit, `bulk-download:${principal.editorialId}`, downloadIntentsPolicy, ); const payload = await parsePayload(request); 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); const downloads: PreparedDownload[] = []; try { for (const item of items) { const intent = await createIntent(dependencies, principal.editorialId, item, payload.maxPriceCents, payload.collab === true); 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; } const passThrough = new PassThrough(); const archive = dependencies.createArchive(); archive.pipe(passThrough); const abortArchive = () => { try { archive.abort(); } catch { // The archive may already be finalized. } passThrough.destroy(new Error("Archive request aborted")); }; request.signal.addEventListener("abort", abortArchive, { once: true }); passThrough.once("close", () => request.signal.removeEventListener("abort", abortArchive)); void produceArchive({ archive, passThrough, downloads, requestSignal: request.signal, async getOriginal(item, signal) { await dependencies.assertOriginalAccess(principal.editorialId, item.assetId, item.albumId); return dependencies.getOriginal(item.assetId, signal); }, accounting, }); const body = streamBulkArchiveWithAccounting( Readable.toWeb(passThrough) as ReadableStream, accounting, ); const date = new Date().toISOString().slice(0, 10); return new Response(body, { headers: { "cache-control": "private, no-store", "content-disposition": `attachment; filename="leuchtkasten-${date}.zip"`, "content-type": "application/zip", "x-content-type-options": "nosniff", }, }); } catch (error) { return mappedBulkError(error); } }; } async function produceArchive({ archive, passThrough, downloads, requestSignal, getOriginal, accounting, }: { archive: BulkArchive; passThrough: PassThrough; downloads: PreparedDownload[]; requestSignal: AbortSignal; 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, requestSignal); const source = Readable.fromWeb( original.body as unknown as import("node:stream/web").ReadableStream, ); source.on("data", (chunk: Buffer) => accounting.addBytes(item.downloadId, chunk.length)); const ended = new Promise((resolve, reject) => { source.once("end", resolve); source.once("error", reject); }); archive.append(source, { name: safeArchiveFilename(item.filename) }); await ended; accounting.markEntryReady(item.downloadId); } await archive.finalize(); } catch (error) { await accounting.failArchive().catch(() => undefined); try { archive.abort(); } catch { // Ignore cleanup errors; the accounting state is already terminal. } passThrough.destroy(error instanceof Error ? error : new Error("Archive failed")); } } 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), }), ])).min(1).max(100), maxPriceCents: z.number().int().nonnegative(), collab: z.boolean().optional(), }); type Selection = z.output["items"][number]; async function resolveRetryKey( dependencies: BulkDownloadHandlerDependencies, editorialId: string, item: Selection, ) { 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; } throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); } async function createIntent( dependencies: BulkDownloadHandlerDependencies, editorialId: string, item: Selection, maxPriceCents: number, collab: boolean, ) { 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, ...(collab ? { collab: true } : {}), }); } async function parsePayload(request: Request) { 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"); } return parsed.data; } function safeArchiveFilename(value: string) { const cleaned = basename(value) .replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_") .trim() .slice(0, 180); return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto"; } function mappedBulkError(error: unknown): Response { if (error instanceof RateLimitExceededError) { return jsonError(429, "RATE_LIMITED", { "retry-after": String(error.retryAfterSeconds), }); } if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST"); if (error instanceof PrincipalAuthorizationError) { return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } if (error instanceof UsageAccountingError) { const statusByCode: Record = { INVALID_INPUT: 400, IDEMPOTENCY_CONFLICT: 409, ALBUM_NOT_GRANTED: 404, ASSET_NOT_FOUND: 404, ASSET_NOT_IN_ALBUM: 404, ASSET_NOT_IMAGE: 422, USAGE_NOT_FOUND: 404, IMMICH_UNAVAILABLE: 503, EDITORIAL_NOT_ACTIVE: 403, COLLAB_NOT_ENABLED: 403, INVALID_PRICE: 409, }; return jsonError(statusByCode[error.code] ?? 500, error.code); } return jsonError(500, "REQUEST_FAILED"); } function jsonError(status: number, code: string, extraHeaders?: HeadersInit) { const headers = new Headers(extraHeaders); headers.set("cache-control", "private, no-store"); headers.set("x-content-type-options", "nosniff"); return Response.json( { code }, { status, headers, }, ); }