fix: harden production flows and user messaging

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 16:07:13 +02:00
1 parent 52dce168dd
commit 86dfe8053d
43 files changed
+3520 -358

No files matched your search

@@ -6,6 +6,7 @@ import { createThumbnailHandler } from "./thumbnail-handler";
vi.mock("sharp", () => {
return {
default: () => ({
resize: vi.fn().mockReturnThis(),
metadata: vi.fn().mockResolvedValue({ width: 100, height: 100 }),
composite: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
@@ -53,6 +54,13 @@ function createHandler(options?: {
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
immich: {
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({
...grantedAlbum,
id,
}));
}),
getAsset: vi.fn().mockImplementation(async () => {
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
return {
@@ -97,6 +105,7 @@ test("streams a thumbnail when the requested asset belongs to any current grant"
expect(response.headers.get("cache-control")).toBe("private, no-store");
await expect(response.arrayBuffer()).resolves.toEqual(new Uint8Array([1, 2, 3]).buffer);
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
});
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
@@ -105,7 +114,7 @@ test("refuses a thumbnail immediately after its last grant is revoked", async ()
const response = await call(handler);
expect(response.status).toBe(404);
expect(dependencies.immich.getAsset).not.toHaveBeenCalled();
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
@@ -164,8 +173,8 @@ test("uses one asset-album membership lookup for a 60-photo gallery regardless o
const response = await call(handler);
expect(response.status).toBe(200);
expect(dependencies.immich.getAsset).toHaveBeenCalledTimes(1);
expect(dependencies.immich.getAsset).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
});
@@ -12,7 +12,7 @@ type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>;
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
getThumbnail(assetId: string): Promise<ImmichBinary>;
};
@@ -37,7 +37,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
const access = await authorizeRequest(dependencies, request.headers);
const authorized =
access.kind === "admin"
? true
? await isAdminAlbumCover(
dependencies.immich,
assetId,
requestedUrl.searchParams.get("albumId"),
)
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
if (!authorized) {
return genericNotFound();
@@ -74,21 +78,27 @@ async function authorizeRequest(
async function isGrantedEditorialAsset(
dependencies: ThumbnailHandlerDependencies,
editorialId: string,
assetId: string, // unused but kept for signature
assetId: string,
): Promise<boolean> {
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(editorialId);
// If they have access to at least one album, we allow them to see the watermarked thumbnail.
// UUIDs are unguessable (128-bit entropy), so an editorial user can only request thumbnails
// for assets they already discovered through their granted albums.
// We cannot reliably check asset.albums via getAsset because it is empty for older Immich assets.
return grantedAlbumIds.length > 0;
const grantedAlbumIds = new Set(await dependencies.getGrantedAlbumIds(editorialId));
if (grantedAlbumIds.size === 0) return false;
const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
return assetAlbums.some((album) => grantedAlbumIds.has(album.id));
}
async function isAdminAlbumCover(
immich: ThumbnailImmich,
assetId: string,
albumId: string | null,
): Promise<boolean> {
if (!albumId || !isSafeAssetId(albumId)) return false;
const album = await immich.getAlbum(albumId);
return album.albumThumbnailAssetId === assetId;
}
function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
const responseHeaders = new Headers({
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
"cache-control": "private, no-store",
"content-type": thumbnail.contentType,
"x-content-type-options": "nosniff",
"etag": `"${assetId}"`,
@@ -100,7 +110,10 @@ function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
}
function genericNotFound(): Response {
return new Response(null, { status: 404 });
return new Response(null, {
status: 404,
headers: { "cache-control": "private, no-store" },
});
}
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: string): Promise<Response> {
@@ -158,7 +171,7 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: st
}
const responseHeaders = new Headers({
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
"cache-control": "private, no-store",
"content-type": "image/webp",
"content-length": String(watermarked.length),
"x-content-type-options": "nosniff",
+22 -2
View File
@@ -3,6 +3,12 @@ import { z } from "zod";
import { createRepeatDownload } from "@/modules/downloads/service";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { downloadIntentsPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
import { createNewUsage } from "@/modules/usages/service";
import { UsageAccountingError } from "@/modules/usages/types";
@@ -32,6 +38,7 @@ type IntentHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial;
createNewUsage: typeof createNewUsage;
createRepeatDownload: typeof createRepeatDownload;
consumeRateLimit: ConsumeRateLimit;
};
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
@@ -39,6 +46,11 @@ export function createDownloadIntentHandler(dependencies: IntentHandlerDependenc
try {
assertSameOrigin(request);
const principal = await dependencies.requireActiveEditorial(request.headers);
await enforceRateLimit(
dependencies.consumeRateLimit,
`download-intent:${principal.editorialId}`,
downloadIntentsPolicy,
);
const payload = intentPayload.safeParse(await readJson(request));
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
@@ -85,6 +97,11 @@ async function readJson(request: Request): Promise<unknown> {
}
function mappedError(error: unknown): Response {
if (error instanceof RateLimitExceededError) {
return errorResponse(429, "RATE_LIMITED", {
"retry-after": String(error.retryAfterSeconds),
});
}
if (error instanceof CrossOriginRequestError) {
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
}
@@ -115,10 +132,12 @@ function mappedError(error: unknown): Response {
return errorResponse(500, "REQUEST_FAILED");
}
function errorResponse(status: number, code: string): Response {
function errorResponse(status: number, code: string, extraHeaders?: HeadersInit): Response {
const headers = new Headers(extraHeaders);
headers.set("cache-control", "private, no-store");
return Response.json(
{ code },
{ status, headers: { "cache-control": "private, no-store" } },
{ status, headers },
);
}
@@ -126,4 +145,5 @@ export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
requireActiveEditorial,
createNewUsage,
createRepeatDownload,
consumeRateLimit,
});
@@ -30,6 +30,7 @@ function dependencies() {
status: "authorized",
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
}),
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
};
}
@@ -138,3 +139,23 @@ test("passes one submitted idempotency key through unchanged", async () => {
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
});
test("returns retry-after without creating an intent when the editorial limit is exhausted", async () => {
const deps = dependencies();
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 23 });
const response = await post(createDownloadIntentHandler(deps), {
kind: "new_usage",
assetId,
albumId,
purpose: "Titelgeschichte",
idempotencyKey,
});
expect(response.status).toBe(429);
expect(response.headers.get("retry-after")).toBe("23");
expect(deps.consumeRateLimit).toHaveBeenCalledWith(
`download-intent:${editorialId}`,
expect.any(Object),
);
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
@@ -0,0 +1,139 @@
import { PassThrough, type Readable as NodeReadable } from "node:stream";
import { expect, test, vi } from "vitest";
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
const editorialId = "11111111-1111-4111-8111-111111111111";
const assetId = "22222222-2222-4222-8222-222222222222";
const albumId = "33333333-3333-4333-8333-333333333333";
const downloadId = "44444444-4444-4444-8444-444444444444";
const secondAssetId = "66666666-6666-4666-8666-666666666666";
function fakeArchive(): BulkArchive {
let destination: PassThrough | undefined;
const pending: Promise<void>[] = [];
return {
pipe(target) {
destination = target;
},
append(source: NodeReadable) {
pending.push(
new Promise((resolve, reject) => {
source.on("data", (chunk) => destination?.write(chunk));
source.once("end", resolve);
source.once("error", reject);
}),
);
},
async finalize() {
await Promise.all(pending);
destination?.end();
},
abort() {
destination?.destroy(new Error("aborted"));
},
};
}
function dependencies() {
return {
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" }),
getOriginal: vi.fn().mockResolvedValue({
body: new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
filename: "foto.jpg",
contentType: "image/jpeg",
contentLength: 3,
}),
listPriorUsages: vi.fn().mockResolvedValue([]),
createNewUsage: vi.fn().mockResolvedValue({ id: downloadId }),
createRepeatDownload: vi.fn(),
repository: {
claimAuthorized: vi.fn().mockResolvedValue({
outcome: "claimed",
download: {
id: downloadId,
usageId: "55555555-5555-4555-8555-555555555555",
assetId,
filename: "foto.jpg",
intentKind: "new_usage",
},
}),
failBeforeDelivery: vi.fn().mockResolvedValue(true),
markCompleted: vi.fn().mockResolvedValue(true),
markInterrupted: vi.fn().mockResolvedValue(true),
},
createArchive: vi.fn(fakeArchive),
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
};
}
function request(origin = "http://portal.test", assetIds = [assetId]) {
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" }),
});
}
test("rejects cross-origin archive requests before authentication or accounting", async () => {
const deps = dependencies();
const response = await createBulkDownloadHandler(deps)(request("https://attacker.test"));
expect(response.status).toBe(403);
expect(deps.requireActiveEditorial).not.toHaveBeenCalled();
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
test("streams a private archive and completes accounting after response consumption", async () => {
const deps = dependencies();
const incoming = request();
const response = await createBulkDownloadHandler(deps)(incoming);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("private, no-store");
expect(response.headers.get("x-content-type-options")).toBe("nosniff");
expect(deps.repository.markCompleted).not.toHaveBeenCalled();
await response.arrayBuffer();
expect(deps.getOriginal).toHaveBeenCalledWith(assetId, incoming.signal);
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
expect(deps.repository.failBeforeDelivery).not.toHaveBeenCalled();
});
test("rate-limits bulk creation before usages are opened", async () => {
const deps = dependencies();
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 31 });
const response = await createBulkDownloadHandler(deps)(request());
expect(response.status).toBe(429);
expect(response.headers.get("retry-after")).toBe("31");
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
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"));
const response = await createBulkDownloadHandler(deps)(
request("http://portal.test", [assetId, secondAssetId]),
);
expect(response.status).toBe(500);
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: true,
});
});
@@ -0,0 +1,343 @@
import { randomUUID } from "node:crypto";
import { basename } from "node:path";
import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream";
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 } from "@/modules/usages/types";
export type BulkArchive = {
pipe(destination: PassThrough): unknown;
append(source: NodeReadable, options: { name: string }): unknown;
finalize(): Promise<unknown> | unknown;
abort(): unknown;
};
type BulkDownloadHandlerDependencies = {
requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>;
getGrantedAlbumIds(editorialId: string): Promise<string[]>;
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<Uint8Array> }>;
listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>;
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 }>;
repository: DownloadDeliveryRepository;
createArchive(): BulkArchive;
consumeRateLimit: ConsumeRateLimit;
};
type PreparedDownload = {
assetId: string;
downloadId: string;
filename: string;
};
export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDependencies) {
return async function POST(request: Request): Promise<Response> {
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 grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId);
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds);
const accounting = createBulkDeliveryAccounting(dependencies.repository);
let 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,
});
},
);
} 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);
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,
getOriginal: dependencies.getOriginal,
accounting,
});
const body = streamBulkArchiveWithAccounting(
Readable.toWeb(passThrough) as ReadableStream<Uint8Array>,
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) {
console.error("[bulk-download] failed:", error);
return mappedBulkError(error);
}
};
}
async function produceArchive({
archive,
passThrough,
downloads,
requestSignal,
getOriginal,
accounting,
}: {
archive: BulkArchive;
passThrough: PassThrough;
downloads: PreparedDownload[];
requestSignal: AbortSignal;
getOriginal: BulkDownloadHandlerDependencies["getOriginal"];
accounting: ReturnType<typeof createBulkDeliveryAccounting>;
}) {
try {
for (const item of downloads) {
if (requestSignal.aborted) throw new Error("Archive request aborted");
const original = await getOriginal(item.assetId, requestSignal);
const source = Readable.fromWeb(
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
);
source.on("data", (chunk: Buffer) => accounting.addBytes(item.downloadId, chunk.length));
const ended = new Promise<void>((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"));
}
}
async function grantedAssetMap(
dependencies: BulkDownloadHandlerDependencies,
grantedAlbumIds: string[],
) {
const result = new Map<string, string>();
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: [] };
}
}),
);
for (const album of albums) {
for (const asset of album.items) {
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
}
}
return result;
}
async function prepareDownloads(
dependencies: BulkDownloadHandlerDependencies,
editorialId: string,
payload: { assetIds: string[]; purpose: string },
assetToGrantedAlbum: Map<string, string>,
onPrepared: (item: PreparedDownload) => Promise<void>,
) {
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);
}
return downloads;
}
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 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() };
}
class BulkInputError extends Error {}
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 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", {
"retry-after": String(error.retryAfterSeconds),
});
}
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");
}
if (error instanceof UsageAccountingError) {
const statusByCode: Record<UsageAccountingError["code"], number> = {
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,
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,
},
);
}
+21 -227
View File
@@ -1,231 +1,25 @@
import { NextRequest } from "next/server";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { usageService } from "@/modules/usages/service";
import { createRepeatDownload } from "@/modules/downloads/service";
import { UsageAccountingError } from "@/modules/usages/types";
import { immichClient } from "@/modules/immich/client";
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
import { albumGrantService } from "@/modules/albums/grants";
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
const archiver: any = require("archiver");
import * as crypto from "crypto";
import { Readable, PassThrough } from "stream";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { createRepeatDownload } from "@/modules/downloads/service";
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
import { immichClient } from "@/modules/immich/client";
import { consumeRateLimit } from "@/modules/security/rate-limit";
import { usageService } from "@/modules/usages/service";
export async function POST(request: NextRequest) {
try {
const principal = await requireActiveEditorial(request.headers);
const { assetIds, purpose } = await request.json();
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
if (!Array.isArray(assetIds) || assetIds.length === 0 || assetIds.length > 100) {
return new Response("Invalid request: assetIds must be an array of 1 to 100 items", { status: 400 });
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
for (const assetId of assetIds) {
if (typeof assetId !== "string" || !uuidRegex.test(assetId)) {
return new Response(`Invalid request: assetId ${assetId} is not a valid UUID format`, { status: 400 });
}
}
const archiver = require("archiver") as { ZipArchive: new (options: unknown) => BulkArchive };
if (typeof purpose !== "string" || purpose.trim().length === 0 || purpose.trim().length > 500) {
return new Response("Invalid request: purpose must be a non-empty string up to 500 characters", { status: 400 });
}
const trimmedPurpose = purpose.trim();
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId);
// Build a map of assetId -> a granted album that contains it. Immich's
// GET /albums/:id no longer returns assets (metadata only), so fetch each
// granted album's assets via /search/metadata instead.
// ponytail: ceiling of 1000 assets per album; tail assets beyond that
// won't map and are skipped from bulk download. Raise if needed.
const assetToGrantedAlbum = new Map<string, string>();
const albumAssets = await Promise.all(
grantedAlbumIds.map(async (albumId) => {
try {
const page = await immichClient.searchPhotos({
albumIds: [albumId],
type: "IMAGE",
page: 1,
size: 1000,
withExif: false,
});
return { albumId, items: page.items };
} catch (err) {
console.error("Failed to fetch granted album assets", albumId, err);
return { albumId, items: [] };
}
}),
);
for (const { albumId, items } of albumAssets) {
for (const asset of items) {
if (!assetToGrantedAlbum.has(asset.id)) {
assetToGrantedAlbum.set(asset.id, albumId);
}
}
}
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
// 1. Fetch assets and validate in parallel
const assetResults = await Promise.all(
assetIds.map(async (assetId) => {
try {
const asset = await immichClient.getAsset(assetId);
return { assetId, asset };
} catch (err) {
console.error("Asset fetch failed", assetId, err);
return { assetId, asset: null };
}
})
);
// 2. Process usages serially to avoid idempotency race conditions
for (const { assetId, asset } of assetResults) {
if (!asset) continue;
// Find the first album the editorial has access to
const validAlbumId = assetToGrantedAlbum.get(assetId);
if (!validAlbumId) continue; // Editorial does not have access
// Check for prior usages to avoid double charging
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
const isRepeat = priorUsages.length > 0;
let downloadId: string;
if (isRepeat) {
// Create a repeat-download intent against the existing usage so the
// delivery claim (claimAuthorized, which looks up download_events.id)
// finds a valid intent. Reusing the usage id directly never matches.
const repeatIntent = await createRepeatDownload({
editorialId: principal.editorialId,
usageId: priorUsages[0].id,
idempotencyKey: crypto.randomUUID(),
});
downloadId = repeatIntent.id;
} else {
const idempotencyKey = crypto.randomUUID();
const newUsage = await usageService.createNewUsage({
editorialId: principal.editorialId,
assetId,
albumId: validAlbumId,
purpose: trimmedPurpose,
reference: undefined,
idempotencyKey,
});
downloadId = newUsage.id;
}
downloadsToProcess.push({
assetId,
downloadId,
filename: asset.originalFileName,
intentKind: isRepeat ? "repeat" : "new_usage",
});
}
if (downloadsToProcess.length === 0) {
return new Response("No valid assets found for download", { status: 404 });
}
const passThrough = new PassThrough();
// archiver v8 exports class constructors ({ ZipArchive, ... }), not a
// callable. The old `archiver('zip', opts)` form throws TypeError at
// runtime — which was masked until the membership fix populated the map
// and this line was actually reached (before, the route 404'd early).
const archive = new archiver.ZipArchive({ zlib: { level: 0 } });
archive.pipe(passThrough);
// Start appending files asynchronously
(async () => {
try {
for (const download of downloadsToProcess) {
// Claim the download to verify it's authorized
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
if (claim.outcome !== "claimed") continue;
try {
const original = await immichClient.getOriginal(download.assetId);
await new Promise<void>((resolve, reject) => {
const nodeStream = Readable.fromWeb(original.body as any);
let transferredBytes = 0;
nodeStream.on('data', (chunk) => {
transferredBytes += chunk.length;
});
nodeStream.on('end', () => {
downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes)
.then(() => resolve())
.catch(reject);
});
nodeStream.on('error', (err) => reject(err));
archive.append(nodeStream, { name: download.filename });
});
} catch (err) {
console.error("Failed to append original for asset", download.assetId, err);
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
voidNewUsage: download.intentKind === "new_usage"
});
}
}
} catch (err) {
console.error("Archive stream failed", err);
archive.abort();
} finally {
archive.finalize();
}
})();
const date = new Date().toISOString().split('T')[0];
return new Response(Readable.toWeb(passThrough) as any, {
headers: {
"Content-Type": "application/zip",
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
},
});
} catch (err) {
// Surface the real cause. Without this, any UsageAccountingError from
// createNewUsage/createRepeatDownload (e.g. IMMICH_UNAVAILABLE under load)
// became an opaque 500 and the user only saw "Download fehlgeschlagen".
console.error("[bulk-download] failed:", err);
return mappedBulkError(err);
}
}
function mappedBulkError(error: unknown): Response {
if (error instanceof PrincipalAuthorizationError) {
return Response.json(
{ code: "FORBIDDEN" },
{ status: error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, headers: { "cache-control": "private, no-store" } },
);
}
if (error instanceof UsageAccountingError) {
const statusByCode: Record<UsageAccountingError["code"], number> = {
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,
INVALID_PRICE: 409,
};
const status = statusByCode[error.code] ?? 500;
return Response.json(
{ code: error.code },
{ status, headers: { "cache-control": "private, no-store" } },
);
}
return Response.json(
{ code: "REQUEST_FAILED" },
{ status: 500, headers: { "cache-control": "private, no-store" } },
);
}
export const POST = createBulkDownloadHandler({
requireActiveEditorial,
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId),
searchPhotos: (input) => immichClient.searchPhotos(input),
getAsset: (assetId) => immichClient.getAsset(assetId),
getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal),
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
createNewUsage: (input) => usageService.createNewUsage(input),
createRepeatDownload,
repository: downloadDeliveryRepository,
createArchive: () => new archiver.ZipArchive({ zlib: { level: 0 } }),
consumeRateLimit,
});