74 lines
2.5 KiB
TypeScript
74 lines
2.5 KiB
TypeScript
// P4 Files (AK-P4a) §6 — auth-proxy media route (AD-23). The bucket is private;
|
|
// this is the ONLY delivery path. An authorized request is redirected (302) to a
|
|
// short-lived signed URL. Denied (no access / foreign file) -> 404 (not 403).
|
|
// Not-yet-clean (scanStatus pending/infected) -> 404, fail-closed.
|
|
//
|
|
// Variants: original | preview | thumb -> selects the matching storage key.
|
|
|
|
import type { LoaderFunctionArgs } from "react-router";
|
|
import { redirect } from "react-router";
|
|
import { assertFileKeyBelongsToTenant } from "@toolctrl/storage";
|
|
import { loadFilesContext } from "~/utils/integrations/fileAccess.server";
|
|
import { getVisibleFileOrThrow } from "~/utils/integrations/fileService.server";
|
|
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
|
|
|
|
type MediaVariant = "original" | "preview" | "thumb";
|
|
|
|
function notFound(): Response {
|
|
return new Response("Not Found", { status: 404 });
|
|
}
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const variant = params.variant as MediaVariant | undefined;
|
|
if (variant !== "original" && variant !== "preview" && variant !== "thumb") {
|
|
return notFound();
|
|
}
|
|
const fileId = params.fileId;
|
|
if (!fileId) {
|
|
return notFound();
|
|
}
|
|
|
|
let ctx;
|
|
try {
|
|
// Module off / unauthenticated -> not deliverable.
|
|
ctx = await loadFilesContext({ request, params, requireModule: true });
|
|
} catch {
|
|
return notFound();
|
|
}
|
|
|
|
let file;
|
|
try {
|
|
file = await getVisibleFileOrThrow(ctx.tenantId, fileId, { userId: ctx.userId, permissions: ctx.permissions });
|
|
} catch {
|
|
// CatalogError(notFound) for missing/invisible -> 404, no info leak.
|
|
return notFound();
|
|
}
|
|
|
|
// Fail-closed: only deliver once the scan verdict is clean (or scanning was
|
|
// skipped in dev). Pending/infected -> refuse.
|
|
if (file.scanStatus !== "clean" && file.scanStatus !== "skipped") {
|
|
return notFound();
|
|
}
|
|
|
|
const key =
|
|
variant === "preview"
|
|
? file.previewStorageKey
|
|
: variant === "thumb"
|
|
? file.thumbnailStorageKey
|
|
: file.storageKey;
|
|
if (!key) {
|
|
// Preview/thumb may not be generated yet (or not_supported) -> 404.
|
|
return notFound();
|
|
}
|
|
|
|
// Defense in depth: the key must belong to this tenant before we sign it.
|
|
try {
|
|
assertFileKeyBelongsToTenant(ctx.tenantId, key, "download");
|
|
} catch {
|
|
return notFound();
|
|
}
|
|
|
|
const url = await createMediaDownloadUrl({ key, filename: variant === "original" ? file.displayName : undefined });
|
|
return redirect(url, 302);
|
|
};
|