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"; import sharp from "sharp"; type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>; type ThumbnailImmich = { listAlbumsForAsset(assetId: string): Promise>; getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>; getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>; getThumbnail(assetId: string): Promise; }; 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 { try { const requestedUrl = new URL(request.url); 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, requestedUrl.searchParams.get("albumId"), ) : await isGrantedEditorialAsset(dependencies, access.editorialId, assetId); if (!authorized) { return genericNotFound(); } const thumbnail = await dependencies.immich.getThumbnail(assetId); if (access.kind === "editorial") { return watermarkedThumbnailResponse(thumbnail); } return thumbnailResponse(thumbnail); } catch (err) { return genericNotFound(); } }; } async function authorizeRequest( dependencies: ThumbnailHandlerDependencies, requestHeaders: Headers, ): Promise { 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 { const grantedAlbumIds = [...new Set(await dependencies.getGrantedAlbumIds(editorialId))]; if (grantedAlbumIds.length === 0) { return false; } const asset = await dependencies.immich.getAsset(assetId); const assetAlbums = asset.albums; const granted = new Set(grantedAlbumIds); return assetAlbums.some((album) => granted.has(album.id)); } async function isAdminAlbumCover( immich: ThumbnailImmich, assetId: string, albumId: string | null, ): Promise { if (!albumId || !isSafeAssetId(albumId)) { return false; } const album = await immich.getAlbum(albumId); return 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 }); } async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise { const reader = thumbnail.body.getReader(); const chunks: Uint8Array[] = []; while (true) { const { done, value } = await reader.read(); if (done) break; if (value) chunks.push(value); } const buffer = Buffer.concat(chunks); const metadata = await sharp(buffer).metadata(); const width = metadata.width ?? 400; const height = metadata.height ?? 300; const svgText = ` PREVIEW `; const watermarked = await sharp(buffer) .composite([ { input: Buffer.from(svgText), gravity: "center", }, ]) .webp({ quality: 80 }) .toBuffer(); const responseHeaders = new Headers({ "cache-control": "private, no-store", "content-type": "image/webp", "content-length": String(watermarked.length), "x-content-type-options": "nosniff", }); return new Response(watermarked, { headers: responseHeaders }); } 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, });