feat: add branded editorial photo catalog

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 22:22:31 +02:00
1 parent f6e6018cc1
commit 66f0599653
20 files changed
+1299 -36

No files matched your search

@@ -0,0 +1,131 @@
import { expect, test, vi } from "vitest";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { createThumbnailHandler } from "./thumbnail-handler";
const grantedAlbum = {
id: "allowed",
albumName: "Freigegebenes Heimspiel",
description: null,
albumThumbnailAssetId: "cover-1",
assetCount: 1,
};
function thumbnail() {
return {
body: new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
contentType: "image/jpeg",
contentLength: 3,
filename: "tor.jpg",
};
}
function createHandler(options?: {
editorialError?: Error;
grantedAlbumIds?: string[];
albumAssets?: Array<{ id: string; type: "IMAGE"; albums: Array<{ id: string }> }>;
albumError?: Error;
adminAlbums?: typeof grantedAlbum[];
}) {
const dependencies = {
requireActiveEditorial: vi
.fn()
.mockImplementation(async () => {
if (options?.editorialError) throw options.editorialError;
return { editorialId: "editorial-1" };
}),
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
immich: {
listAlbums: vi.fn().mockResolvedValue(options?.adminAlbums ?? [grantedAlbum]),
getAlbum: vi.fn().mockImplementation(async () => {
if (options?.albumError) throw options.albumError;
return {
...grantedAlbum,
assets: options?.albumAssets ?? [
{ id: "asset-1", type: "IMAGE", albums: [{ id: "allowed" }] },
],
};
}),
getThumbnail: vi.fn().mockResolvedValue(thumbnail()),
},
};
return { handler: createThumbnailHandler(dependencies), dependencies };
}
function call(handler: ReturnType<typeof createThumbnailHandler>, assetId = "asset-1") {
return handler(new Request("http://portal.test/api/assets/asset-1/thumbnail"), {
params: Promise.resolve({ assetId }),
});
}
test("streams a thumbnail when the requested asset belongs to any current grant", async () => {
const { handler, dependencies } = createHandler({
albumAssets: [{ id: "asset-1", type: "IMAGE", albums: [{ id: "other" }, { id: "allowed" }] }],
});
const response = await call(handler);
expect(response.status).toBe(200);
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");
});
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
const { handler, dependencies } = createHandler({ grantedAlbumIds: [] });
const response = await call(handler);
expect(response.status).toBe(404);
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
test("uses an identical generic 404 for forbidden and missing assets", async () => {
const forbidden = createHandler({ albumAssets: [{ id: "different", type: "IMAGE", albums: [{ id: "allowed" }] }] });
const missing = createHandler({ albumError: new Error("IMMICH_NOT_FOUND") });
const [forbiddenResponse, missingResponse] = await Promise.all([
call(forbidden.handler),
call(missing.handler),
]);
expect({ status: forbiddenResponse.status, body: await forbiddenResponse.text() }).toEqual({
status: missingResponse.status,
body: await missingResponse.text(),
});
expect(forbidden.dependencies.immich.getThumbnail).not.toHaveBeenCalled();
expect(missing.dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
test("allows an admin only to load an existing Immich album cover", async () => {
const { handler, dependencies } = createHandler({
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
adminAlbums: [grantedAlbum],
});
const response = await call(handler, "cover-1");
expect(response.status).toBe(200);
expect(dependencies.requireAdmin).toHaveBeenCalledTimes(1);
expect(dependencies.getGrantedAlbumIds).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("cover-1");
});
test("does not let an admin proxy an arbitrary non-cover asset", async () => {
const { handler, dependencies } = createHandler({
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
adminAlbums: [grantedAlbum],
});
const response = await call(handler, "asset-not-a-cover");
expect(response.status).toBe(404);
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
@@ -0,0 +1,3 @@
import { authorizedThumbnailHandler } from "./thumbnail-handler";
export const GET = authorizedThumbnailHandler;
@@ -0,0 +1,115 @@
import "server-only";
import { requireActiveEditorial, requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
listAlbums(): Promise<Array<{ albumThumbnailAssetId: string | null }>>;
getAlbum(albumId: string): Promise<{ assets: Array<{ id: string; type: "IMAGE" }> }>;
getThumbnail(assetId: string): Promise<ImmichBinary>;
};
export type ThumbnailHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial;
requireAdmin: typeof requireAdmin;
getGrantedAlbumIds: typeof albumGrantService.getGrantedAlbumIds;
immich: ThumbnailImmich;
};
type Access = { kind: "admin" } | { kind: "editorial"; editorialId: string };
export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencies) {
return async function GET(request: Request, context: ThumbnailRouteContext): Promise<Response> {
try {
const { assetId } = await context.params;
if (!isSafeAssetId(assetId)) {
return genericNotFound();
}
const access = await authorizeRequest(dependencies, request.headers);
const authorized =
access.kind === "admin"
? await isAdminAlbumCover(dependencies.immich, assetId)
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
if (!authorized) {
return genericNotFound();
}
const thumbnail = await dependencies.immich.getThumbnail(assetId);
return thumbnailResponse(thumbnail);
} catch {
return genericNotFound();
}
};
}
async function authorizeRequest(
dependencies: ThumbnailHandlerDependencies,
requestHeaders: Headers,
): Promise<Access> {
try {
const principal = await dependencies.requireActiveEditorial(requestHeaders);
return { kind: "editorial", editorialId: principal.editorialId };
} catch (error) {
if (!(error instanceof PrincipalAuthorizationError) || error.code !== "ADMIN_REQUIRED") {
throw error;
}
}
await dependencies.requireAdmin(requestHeaders);
return { kind: "admin" };
}
async function isGrantedEditorialAsset(
dependencies: ThumbnailHandlerDependencies,
editorialId: string,
assetId: string,
): Promise<boolean> {
const grantedAlbumIds = [...new Set(await dependencies.getGrantedAlbumIds(editorialId))];
if (grantedAlbumIds.length === 0) {
return false;
}
const grantedAlbums = await Promise.all(
grantedAlbumIds.map((albumId) => dependencies.immich.getAlbum(albumId)),
);
return grantedAlbums.some((album) =>
album.assets.some((asset) => asset.id === assetId && asset.type === "IMAGE"),
);
}
async function isAdminAlbumCover(immich: ThumbnailImmich, assetId: string): Promise<boolean> {
const albums = await immich.listAlbums();
return albums.some((album) => album.albumThumbnailAssetId === assetId);
}
function thumbnailResponse(thumbnail: ImmichBinary): Response {
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"content-type": thumbnail.contentType,
"x-content-type-options": "nosniff",
});
if (thumbnail.contentLength !== null) {
responseHeaders.set("content-length", String(thumbnail.contentLength));
}
return new Response(thumbnail.body, { headers: responseHeaders });
}
function genericNotFound(): Response {
return new Response(null, { status: 404 });
}
function isSafeAssetId(assetId: string): boolean {
return /^[A-Za-z0-9_-]{1,200}$/.test(assetId);
}
export const authorizedThumbnailHandler = createThumbnailHandler({
requireActiveEditorial,
requireAdmin,
getGrantedAlbumIds: albumGrantService.getGrantedAlbumIds,
immich: immichClient,
});