Secure Sakani portal and show full album titles
This commit is contained in:
1 parent
c40ccf77cf
commit
69264ce165
49 files changed
+1362
-601
No files matched your search
@@ -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<BulkAttempt | undefined>;
|
||||
assertOriginalAccess: typeof assertOriginalAccess;
|
||||
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 }>;
|
||||
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<Uint8Array> }>;
|
||||
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 original = await getOriginal(item, requestSignal);
|
||||
const source = Readable.fromWeb(
|
||||
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
|
||||
);
|
||||
@@ -192,99 +185,77 @@ async function produceArchive({
|
||||
}
|
||||
}
|
||||
|
||||
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: [] };
|
||||
}
|
||||
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<typeof bulkPayload>["items"][number];
|
||||
|
||||
async function resolveRetryKey(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
editorialId: string,
|
||||
payload: { assetIds: string[]; purpose: string },
|
||||
assetToGrantedAlbum: Map<string, string>,
|
||||
onPrepared: (item: PreparedDownload) => Promise<void>,
|
||||
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");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user