feat: stream originals with download accounting

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:10:13 +02:00
1 parent c400167b8f
commit 8871e4794a
28 files changed
+4081 -8

No files matched your search

@@ -0,0 +1,124 @@
import { z } from "zod";
import { createRepeatDownload } from "@/modules/downloads/service";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { createNewUsage } from "@/modules/usages/service";
import { UsageAccountingError } from "@/modules/usages/types";
const newUsagePayload = z
.object({
kind: z.literal("new_usage"),
assetId: z.string(),
albumId: z.string(),
purpose: z.string(),
reference: z.string().optional(),
idempotencyKey: z.string(),
})
.strict();
const repeatDownloadPayload = z
.object({
kind: z.literal("repeat_download"),
usageId: z.string(),
note: z.string().optional(),
idempotencyKey: z.string(),
})
.strict();
const intentPayload = z.discriminatedUnion("kind", [newUsagePayload, repeatDownloadPayload]);
type IntentHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial;
createNewUsage: typeof createNewUsage;
createRepeatDownload: typeof createRepeatDownload;
};
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
return async function POST(request: Request): Promise<Response> {
try {
const principal = await dependencies.requireActiveEditorial(request.headers);
const payload = intentPayload.safeParse(await readJson(request));
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
const intent =
payload.data.kind === "new_usage"
? await dependencies.createNewUsage({
editorialId: principal.editorialId,
assetId: payload.data.assetId,
albumId: payload.data.albumId,
purpose: payload.data.purpose,
...(payload.data.reference === undefined
? {}
: { reference: payload.data.reference }),
idempotencyKey: payload.data.idempotencyKey,
})
: await dependencies.createRepeatDownload({
editorialId: principal.editorialId,
usageId: payload.data.usageId,
...(payload.data.note === undefined ? {} : { note: payload.data.note }),
idempotencyKey: payload.data.idempotencyKey,
});
return Response.json(
{
downloadId: intent.id,
fileUrl: `/api/downloads/${encodeURIComponent(intent.id)}/file`,
priceCents: intent.priceCents,
billable: intent.billable,
},
{ status: 201, headers: { "cache-control": "private, no-store" } },
);
} catch (error) {
return mappedError(error);
}
};
}
async function readJson(request: Request): Promise<unknown> {
try {
return await request.json();
} catch {
return null;
}
}
function mappedError(error: unknown): Response {
if (error instanceof PrincipalAuthorizationError) {
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
if (error instanceof UsageAccountingError) {
switch (error.code) {
case "INVALID_INPUT":
return errorResponse(400, "INVALID_REQUEST");
case "IDEMPOTENCY_CONFLICT":
return errorResponse(409, "IDEMPOTENCY_CONFLICT");
case "ALBUM_NOT_GRANTED":
case "ASSET_NOT_FOUND":
case "ASSET_NOT_IN_ALBUM":
case "USAGE_NOT_FOUND":
return errorResponse(404, "NOT_FOUND");
case "IMMICH_UNAVAILABLE":
return errorResponse(503, "UPSTREAM_UNAVAILABLE");
case "ASSET_NOT_IMAGE":
return errorResponse(422, "INVALID_ASSET");
case "EDITORIAL_NOT_ACTIVE":
return errorResponse(403, "FORBIDDEN");
case "INVALID_PRICE":
return errorResponse(409, "ACCOUNTING_UNAVAILABLE");
}
}
return errorResponse(500, "REQUEST_FAILED");
}
function errorResponse(status: number, code: string): Response {
return Response.json(
{ code },
{ status, headers: { "cache-control": "private, no-store" } },
);
}
export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
requireActiveEditorial,
createNewUsage,
createRepeatDownload,
});
+140
View File
@@ -0,0 +1,140 @@
import { expect, test, vi } from "vitest";
import { createDownloadIntentHandler } from "./intent-handler";
const editorialId = "11111111-1111-4111-8111-111111111111";
const assetId = "22222222-2222-4222-8222-222222222222";
const albumId = "33333333-3333-4333-8333-333333333333";
const usageId = "44444444-4444-4444-8444-444444444444";
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
const downloadId = "66666666-6666-4666-8666-666666666666";
function dependencies() {
return {
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
createNewUsage: vi.fn().mockResolvedValue({
id: downloadId,
usageId,
assetId,
priceCents: 1_500,
billable: true,
status: "authorized",
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
}),
createRepeatDownload: vi.fn().mockResolvedValue({
id: downloadId,
usageId,
assetId,
priceCents: 0,
billable: false,
status: "authorized",
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
}),
};
}
function post(handler: ReturnType<typeof createDownloadIntentHandler>, body: unknown) {
return handler(
new Request("http://portal.test/api/download-intents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}),
);
}
test("derives editorial scope and billable price exclusively on the server", async () => {
const deps = dependencies();
const response = await post(createDownloadIntentHandler(deps), {
kind: "new_usage",
assetId,
albumId,
purpose: "Titelgeschichte",
idempotencyKey,
});
expect(response.status).toBe(201);
await expect(response.json()).resolves.toEqual({
downloadId,
fileUrl: `/api/downloads/${downloadId}/file`,
priceCents: 1_500,
billable: true,
});
expect(deps.createNewUsage).toHaveBeenCalledWith({
editorialId,
assetId,
albumId,
purpose: "Titelgeschichte",
idempotencyKey,
});
});
test("creates a zero-cost repeat intent scoped to the authenticated editorial", async () => {
const deps = dependencies();
const response = await post(createDownloadIntentHandler(deps), {
kind: "repeat_download",
usageId,
note: "erneuter Abruf",
idempotencyKey,
});
expect(response.status).toBe(201);
expect(deps.createRepeatDownload).toHaveBeenCalledWith({
editorialId,
usageId,
note: "erneuter Abruf",
idempotencyKey,
});
await expect(response.json()).resolves.toMatchObject({ priceCents: 0, billable: false });
});
test.each([
{ field: "editorialId", value: "77777777-7777-4777-8777-777777777777" },
{ field: "priceCents", value: 1 },
])("rejects a client-controlled $field before any accounting side effect", async ({ field, value }) => {
const deps = dependencies();
const response = await post(createDownloadIntentHandler(deps), {
kind: "new_usage",
assetId,
albumId,
purpose: "Titelgeschichte",
idempotencyKey,
[field]: value,
});
expect(response.status).toBe(400);
expect(deps.createNewUsage).not.toHaveBeenCalled();
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
});
test("rejects mixed new and repeat fields as an invalid discriminated payload", async () => {
const deps = dependencies();
const response = await post(createDownloadIntentHandler(deps), {
kind: "repeat_download",
usageId,
assetId,
idempotencyKey,
});
expect(response.status).toBe(400);
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
});
test("passes one submitted idempotency key through unchanged", async () => {
const deps = dependencies();
const handler = createDownloadIntentHandler(deps);
const body = {
kind: "new_usage",
assetId,
albumId,
purpose: "Titelgeschichte",
idempotencyKey,
};
const [first, retry] = await Promise.all([post(handler, body), post(handler, body)]);
expect(first.status).toBe(201);
expect(retry.status).toBe(201);
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
});
+3
View File
@@ -0,0 +1,3 @@
import { authorizedDownloadIntentHandler } from "./intent-handler";
export const POST = authorizedDownloadIntentHandler;
@@ -0,0 +1,162 @@
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types";
import { normalizeUuid } from "@/modules/usages/types";
type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string }> }>;
type DownloadFileHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial;
repository: typeof downloadDeliveryRepository;
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
};
export function createDownloadFileHandler(dependencies: DownloadFileHandlerDependencies) {
return async function GET(
request: Request,
context: DownloadFileRouteContext,
): Promise<Response> {
try {
const principal = await dependencies.requireActiveEditorial(request.headers);
const downloadId = safeDownloadId((await context.params).downloadId);
if (!downloadId) return genericNotFound();
const claim = await dependencies.repository.claimAuthorized(
principal.editorialId,
downloadId,
);
if (claim.outcome === "not_found") return genericNotFound();
if (claim.outcome === "not_authorized") {
return jsonError(409, "DOWNLOAD_NOT_AVAILABLE");
}
let original: ImmichBinary;
try {
original = await dependencies.immich.getOriginal(
claim.download.assetId,
request.signal,
);
} catch {
await failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind);
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
}
try {
const body = streamWithAccounting({
downloadId,
upstream: original.body,
voidNewUsageOnFailure: claim.download.intentKind === "new_usage",
repository: dependencies.repository,
});
return new Response(body, {
headers: downloadHeaders(original, claim.download.filename),
});
} catch {
const cancellation = Promise.resolve().then(() => original.body.cancel());
await Promise.allSettled([
cancellation,
failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind),
]);
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
}
} catch (error) {
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
}
};
}
async function failClaimBeforeDelivery(
dependencies: DownloadFileHandlerDependencies,
downloadId: string,
intentKind: "new_usage" | "repeat_download" | "legacy",
) {
await dependencies.repository
.failBeforeDelivery(downloadId, { voidNewUsage: intentKind === "new_usage" })
.catch(() => undefined);
}
function safeDownloadId(value: string): string | null {
try {
return normalizeUuid(value);
} catch {
return null;
}
}
function downloadHeaders(original: ImmichBinary, snapshotFilename: string): Headers {
const headers = new Headers({
"cache-control": "private, no-store",
"content-disposition": contentDisposition(original.filename || snapshotFilename),
"content-type": safeContentType(original.contentType),
"x-content-type-options": "nosniff",
});
if (
original.contentLength !== null &&
Number.isSafeInteger(original.contentLength) &&
original.contentLength >= 0
) {
headers.set("content-length", String(original.contentLength));
}
return headers;
}
export function contentDisposition(filename: string): string {
const cleaned = cleanFilename(filename);
const fallback = asciiFilename(cleaned);
const encoded = encodeURIComponent(cleaned).replace(/[!'()*]/g, (character) =>
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
);
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`;
}
function cleanFilename(filename: string): string {
const cleaned = [...filename.normalize("NFC").replace(/[\uD800-\uDFFF]/gu, "_")]
.slice(0, 180)
.join("")
.replace(/[\\/]/g, "_")
.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
.trim();
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "download";
}
function asciiFilename(filename: string): string {
const fallback = filename
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^A-Za-z0-9._ ()+-]/g, "_")
.replace(/[";]/g, "_")
.trim();
return fallback && fallback !== "." && fallback !== ".." ? fallback : "download";
}
function safeContentType(value: string): string {
return /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:[ \t]*;[ \t]*[A-Za-z0-9!#$&^_.+-]+=[A-Za-z0-9!#$&^_.+"'()-]+)*$/.test(
value,
)
? value
: "application/octet-stream";
}
function genericNotFound(): Response {
return new Response(null, {
status: 404,
headers: { "cache-control": "private, no-store" },
});
}
function jsonError(status: number, code: string): Response {
return Response.json(
{ code },
{ status, headers: { "cache-control": "private, no-store" } },
);
}
export const authorizedDownloadFileHandler = createDownloadFileHandler({
requireActiveEditorial,
repository: downloadDeliveryRepository,
immich: immichClient,
});
@@ -0,0 +1,228 @@
import { expect, test, vi } from "vitest";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { contentDisposition, createDownloadFileHandler } from "./download-handler";
const editorialId = "11111111-1111-4111-8111-111111111111";
const otherEditorialId = "22222222-2222-4222-8222-222222222222";
const downloadId = "33333333-3333-4333-8333-333333333333";
const usageId = "44444444-4444-4444-8444-444444444444";
const assetId = "55555555-5555-4555-8555-555555555555";
function binary(overrides: Partial<{
body: ReadableStream<Uint8Array>;
contentType: string;
contentLength: number | null;
filename: string;
}> = {}) {
return {
body: new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
contentType: "image/jpeg",
contentLength: 3,
filename: "heimspiel.jpg",
...overrides,
};
}
function dependencies(options: {
claim?: "claimed" | "not_found" | "not_authorized";
editorialError?: Error;
original?: ReturnType<typeof binary>;
originalError?: Error;
intentKind?: "new_usage" | "repeat_download";
} = {}) {
const repository = {
claimAuthorized: vi.fn().mockResolvedValue(
options.claim === "not_found"
? { outcome: "not_found" }
: options.claim === "not_authorized"
? { outcome: "not_authorized" }
: {
outcome: "claimed",
download: {
id: downloadId,
usageId,
assetId,
filename: "snapshot.jpg",
intentKind: options.intentKind ?? "new_usage",
},
},
),
failBeforeDelivery: vi.fn().mockResolvedValue(true),
markCompleted: vi.fn().mockResolvedValue(true),
markInterrupted: vi.fn().mockResolvedValue(true),
};
const values = {
requireActiveEditorial: vi.fn().mockImplementation(async () => {
if (options.editorialError) throw options.editorialError;
return { editorialId };
}),
repository,
immich: {
getOriginal: vi.fn().mockImplementation(async () => {
if (options.originalError) throw options.originalError;
return options.original ?? binary();
}),
},
};
return values;
}
function call(
handler: ReturnType<typeof createDownloadFileHandler>,
id = downloadId,
signal?: AbortSignal,
) {
return handler(new Request(`http://portal.test/api/downloads/${id}/file`, { signal }), {
params: Promise.resolve({ downloadId: id }),
});
}
test("claims an owned authorized event before requesting and streaming the original", async () => {
const deps = dependencies();
const handler = createDownloadFileHandler(deps);
const response = await call(handler);
expect(response.status).toBe(200);
expect(deps.repository.claimAuthorized).toHaveBeenCalledWith(editorialId, downloadId);
expect(deps.immich.getOriginal).toHaveBeenCalledWith(assetId, expect.any(AbortSignal));
expect(await response.arrayBuffer()).toEqual(new Uint8Array([1, 2, 3]).buffer);
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
});
test("returns the same generic 404 for an invalid id, missing event, and another editorial's event", async () => {
const invalid = dependencies();
const missing = dependencies({ claim: "not_found" });
const foreign = dependencies({ claim: "not_found" });
foreign.requireActiveEditorial.mockResolvedValue({ editorialId: otherEditorialId });
const responses = await Promise.all([
call(createDownloadFileHandler(invalid), "not-a-uuid"),
call(createDownloadFileHandler(missing)),
call(createDownloadFileHandler(foreign)),
]);
const results = await Promise.all(
responses.map(async (response) => ({ status: response.status, body: await response.text() })),
);
expect(results[1]).toEqual(results[0]);
expect(results[2]).toEqual(results[0]);
expect(invalid.repository.claimAuthorized).not.toHaveBeenCalled();
expect(foreign.immich.getOriginal).not.toHaveBeenCalled();
});
test.each(["streaming", "completed", "interrupted", "failed_before_delivery"])(
"denies reuse of a %s attempt before reaching Immich",
async () => {
const deps = dependencies({ claim: "not_authorized" });
const response = await call(createDownloadFileHandler(deps));
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({ code: "DOWNLOAD_NOT_AVAILABLE" });
expect(deps.immich.getOriginal).not.toHaveBeenCalled();
},
);
test("marks a pre-response Immich failure failed and voids a new usage", async () => {
const deps = dependencies({ originalError: new Error("IMMICH_UNAVAILABLE") });
const response = await call(createDownloadFileHandler(deps));
expect(response.status).toBe(503);
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: true,
});
});
test("a repeat pre-response failure retains the original usage", async () => {
const deps = dependencies({
originalError: new Error("IMMICH_UNAVAILABLE"),
intentKind: "repeat_download",
});
await call(createDownloadFileHandler(deps));
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: false,
});
});
test("accounts for a claimed attempt when the upstream body cannot be consumed", async () => {
const original = binary();
const lock = original.body.getReader();
const deps = dependencies({ original });
const response = await call(createDownloadFileHandler(deps));
expect(response.status).toBe(503);
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: true,
});
lock.releaseLock();
});
test("emits only safe download headers for an injected Unicode filename", async () => {
const deps = dependencies({
original: binary({
filename: "../München\r\nX-Internal: secret\\final.jpg",
contentType: "image/jpeg",
contentLength: 3,
}),
});
const response = await call(createDownloadFileHandler(deps));
const disposition = response.headers.get("content-disposition") ?? "";
expect(response.headers.get("cache-control")).toBe("private, no-store");
expect(response.headers.get("content-type")).toBe("image/jpeg");
expect(response.headers.get("content-length")).toBe("3");
expect(response.headers.has("x-api-key")).toBe(false);
expect(disposition).not.toMatch(/[\r\n\\/]/);
expect(disposition).toContain("filename*=UTF-8''");
expect(disposition).toContain("M%C3%BCnchen");
});
test("falls back from an untrustworthy media type and length without forwarding header injection", async () => {
const deps = dependencies({
original: binary({
contentType: "image/jpeg;\r\nx-api-key=secret",
contentLength: -1,
}),
});
const response = await call(createDownloadFileHandler(deps));
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("application/octet-stream");
expect(response.headers.has("content-length")).toBe(false);
expect(response.headers.has("x-api-key")).toBe(false);
});
test("builds a standards-safe disposition for malformed Unicode", () => {
expect(() => contentDisposition("foto-\ud800.jpg")).not.toThrow();
expect(contentDisposition("foto-\ud800.jpg")).toContain("filename*=UTF-8''foto-_.jpg");
});
test("returns stable authentication semantics without exposing guard details", async () => {
const unauthenticated = dependencies({
editorialError: new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
});
const inactive = dependencies({
editorialError: new PrincipalAuthorizationError("ACCOUNT_SUSPENDED"),
});
const [first, second] = await Promise.all([
call(createDownloadFileHandler(unauthenticated)),
call(createDownloadFileHandler(inactive)),
]);
expect(first.status).toBe(401);
expect(second.status).toBe(403);
expect(await second.text()).not.toContain("SUSPENDED");
});
@@ -0,0 +1,3 @@
import { authorizedDownloadFileHandler } from "./download-handler";
export const GET = authorizedDownloadFileHandler;