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"; import fs from "node:fs/promises"; import path from "node:path"; type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>; type ThumbnailImmich = { getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>; listAlbumsForAsset(assetId: string): Promise>; 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, assetId); } return thumbnailResponse(thumbnail, assetId); } 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.size === 0) return false; const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId); return assetAlbums.some((album) => grantedAlbumIds.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, assetId: string): Response { const responseHeaders = new Headers({ "cache-control": "private, no-store", "content-type": thumbnail.contentType, "x-content-type-options": "nosniff", "etag": `"${assetId}"`, }); 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, headers: { "cache-control": "private, no-store" }, }); } async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: string): 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); // Skaliere das Bild auf 480px Breite (wie vom User gewünscht) // Skaliere das Bild so, dass es in eine 800x800 Box passt (damit Hoch- und Querformat korrekt skaliert werden) const targetSize = 800; const resizedBuffer = await sharp(buffer) .resize({ width: targetSize, height: targetSize, fit: "inside", withoutEnlargement: true }) .toBuffer(); let watermarked = resizedBuffer; try { const logoPath = path.join(process.cwd(), "public", "brand", "logo-white.png"); const logoBuffer = await fs.readFile(logoPath); const { width, height } = await sharp(resizedBuffer).metadata(); // Berechne Wasserzeichen-Größe (50% der Bildbreite, max 400px) const logoTargetWidth = Math.min(Math.floor((width ?? targetSize) * 0.5), 400); const resizedLogo = await sharp(logoBuffer) .resize({ width: logoTargetWidth, withoutEnlargement: true }) .toBuffer(); const logoMetadata = await sharp(resizedLogo).metadata(); const logoBase64 = resizedLogo.toString("base64"); const logoWidth = logoMetadata.width ?? logoTargetWidth; const logoHeight = logoMetadata.height ?? (logoTargetWidth / 2); // XLink wird für librsvg (welches von sharp genutzt wird) zwingend benötigt const svgOverlay = ` `; watermarked = await sharp(resizedBuffer) .composite([{ input: Buffer.from(svgOverlay), gravity: "center" }]) .webp({ quality: 80 }) .toBuffer(); } catch (err) { console.error("Watermark logo error:", err); // Fallback falls logo-white.png nicht existiert watermarked = await sharp(resizedBuffer).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", "etag": `"${assetId}-watermark"`, }); 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, });