fix: harden production flows and user messaging
This commit is contained in:
1 parent
52dce168dd
commit
86dfe8053d
43 files changed
+3520
-358
No files matched your search
@@ -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,
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user