fix: comprehensive portal audit - bugfixes, performance, security, logo

Critical bugs:
- Fix bulk-download: UUID idempotency key, input validation, error handling, parallel asset validation
- Fix leuchtkasten 404 link -> album page with search
- Fix revalidatePath [id] -> [albumId]
- Fix PDF crash on null invoiceNumber

Logo:
- Fix dimensions (1000x1000), dark mode support (logo-white.png), max-height constraint

UI bugs:
- Fix unsafe Date method calls (6 files)
- Fix album UUID shown instead of name in catalog
- Fix global search downloads (albumId from asset)
- Add null guard for lightbox asset map

Performance:
- Parallelize admin dashboard queries (Promise.all)
- Lazy-load recharts via next/dynamic
- Add thumbnail caching headers (24h + ETag)
- Reduce duplicate Immich API calls in usage service
- Add DB index on usages(createdAt)
- Add optimizePackageImports for lucide-react, recharts

Security:
- Input validation on bulk-download (max 100 items, UUID format, purpose length)
- Verify security headers present in next.config.ts
This commit is contained in:
Leon Tonhäuser committed 2026-08-11 11:50:12 +02:00
1 parent 0576d946c5
commit d9d69ed861
21 files changed
+229 -153

No files matched your search

@@ -47,9 +47,9 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
const thumbnail = await dependencies.immich.getThumbnail(assetId);
if (access.kind === "editorial") {
return watermarkedThumbnailResponse(thumbnail);
return watermarkedThumbnailResponse(thumbnail, assetId);
}
return thumbnailResponse(thumbnail);
return thumbnailResponse(thumbnail, assetId);
} catch (err) {
return genericNotFound();
}
@@ -101,11 +101,12 @@ async function isAdminAlbumCover(
return album.albumThumbnailAssetId === assetId;
}
function thumbnailResponse(thumbnail: ImmichBinary): Response {
function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
"content-type": thumbnail.contentType,
"x-content-type-options": "nosniff",
"etag": `"${assetId}"`,
});
if (thumbnail.contentLength !== null) {
responseHeaders.set("content-length", String(thumbnail.contentLength));
@@ -117,7 +118,7 @@ function genericNotFound(): Response {
return new Response(null, { status: 404 });
}
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Response> {
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: string): Promise<Response> {
const reader = thumbnail.body.getReader();
const chunks: Uint8Array[] = [];
while (true) {
@@ -150,10 +151,11 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Re
.toBuffer();
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
"content-type": "image/webp",
"content-length": String(watermarked.length),
"x-content-type-options": "nosniff",
"etag": `"${assetId}-watermark"`,
});
return new Response(watermarked, { headers: responseHeaders });
@@ -20,7 +20,7 @@ export function createGetReportHandler(dependencies: GetHandlerDependencies) {
const report = await dependencies.getReportPdf(reportId);
if (!report) return notFound();
const filename = buildFilename(report.invoiceNumber);
const filename = buildFilename(report.invoiceNumber, reportId);
return new Response(new Uint8Array(report.bytes), {
status: 200,
headers: {
@@ -38,7 +38,10 @@ export function createGetReportHandler(dependencies: GetHandlerDependencies) {
};
}
function buildFilename(invoiceNumber: string): string {
function buildFilename(invoiceNumber: string | null, reportId: string): string {
if (!invoiceNumber) {
return `entwurf-${reportId}.pdf`;
}
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
return `${safe || "nutzungsnachweis"}.pdf`;
}
@@ -26,7 +26,7 @@ export async function GET(
const reportPdf = await getReportPdf(reportId);
if (!reportPdf) return notFound();
const filename = buildFilename(reportPdf.invoiceNumber);
const filename = buildFilename(reportPdf.invoiceNumber, reportId);
return new Response(new Uint8Array(reportPdf.bytes), {
status: 200,
headers: {
@@ -43,7 +43,10 @@ export async function GET(
}
}
function buildFilename(invoiceNumber: string): string {
function buildFilename(invoiceNumber: string | null, reportId: string): string {
if (!invoiceNumber) {
return `entwurf-${reportId}.pdf`;
}
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
return `${safe || "nutzungsnachweis"}.pdf`;
}
+89 -57
View File
@@ -4,7 +4,9 @@ import { usageService } from "@/modules/usages/service";
import { immichClient } from "@/modules/immich/client";
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
import { albumGrantService } from "@/modules/albums/grants";
const archiver = require("archiver");
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
const archiver: any = require("archiver");
import * as crypto from "crypto";
import { Readable } from "stream";
export async function POST(request: NextRequest) {
@@ -12,49 +14,73 @@ export async function POST(request: NextRequest) {
const principal = await requireActiveEditorial(request.headers);
const { assetIds, purpose } = await request.json();
if (!Array.isArray(assetIds) || assetIds.length === 0 || !purpose) {
return new Response("Invalid request", { status: 400 });
if (!Array.isArray(assetIds) || assetIds.length === 0 || assetIds.length > 100) {
return new Response("Invalid request: assetIds must be an array of 1 to 100 items", { status: 400 });
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
for (const assetId of assetIds) {
if (typeof assetId !== "string" || !uuidRegex.test(assetId)) {
return new Response(`Invalid request: assetId ${assetId} is not a valid UUID format`, { status: 400 });
}
}
if (typeof purpose !== "string" || purpose.trim().length === 0 || purpose.trim().length > 500) {
return new Response("Invalid request: purpose must be a non-empty string up to 500 characters", { status: 400 });
}
const trimmedPurpose = purpose.trim();
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId);
const grantedSet = new Set(grantedAlbumIds);
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
for (const assetId of assetIds) {
// 1. Fetch asset to find its albums
let asset;
try {
asset = await immichClient.getAsset(assetId);
} catch (err) {
console.error("Asset fetch failed", assetId, err);
continue; // Skip unavailable assets
}
// 1. Fetch assets and validate in parallel
const assetResults = await Promise.all(
assetIds.map(async (assetId) => {
try {
const asset = await immichClient.getAsset(assetId);
return { assetId, asset };
} catch (err) {
console.error("Asset fetch failed", assetId, err);
return { assetId, asset: null };
}
})
);
// 2. Find the first album the editorial has access to
const validAlbum = asset.albums.find(a => grantedSet.has(a.id));
// 2. Process usages serially to avoid idempotency race conditions
for (const { assetId, asset } of assetResults) {
if (!asset) continue;
// Find the first album the editorial has access to
const validAlbum = asset.albums.find((a: any) => grantedSet.has(a.id));
if (!validAlbum) continue; // Editorial does not have access
// 3. Check for prior usages to avoid double charging
// Check for prior usages to avoid double charging
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
const isRepeat = priorUsages.length > 0;
// 4. Create new usage (or repeat download if prior usages exist)
// Since createNewUsage handles idempotent repeats automatically, we just need to pass an idempotency key.
const idempotencyKey = `${principal.editorialId}-${assetId}-${purpose}`;
const newUsage = await usageService.createNewUsage({
editorialId: principal.editorialId,
assetId,
albumId: validAlbum.id,
purpose,
reference: undefined,
idempotencyKey,
});
let downloadId: string;
if (isRepeat) {
// Skip usage creation for repeat downloads
downloadId = priorUsages[0].id;
} else {
const idempotencyKey = crypto.randomUUID();
const newUsage = await usageService.createNewUsage({
editorialId: principal.editorialId,
assetId,
albumId: validAlbum.id,
purpose: trimmedPurpose,
reference: undefined,
idempotencyKey,
});
downloadId = newUsage.id;
}
downloadsToProcess.push({
assetId,
downloadId: newUsage.id,
downloadId,
filename: asset.originalFileName,
intentKind: isRepeat ? "repeat" : "new_usage",
});
@@ -76,38 +102,44 @@ export async function POST(request: NextRequest) {
// Start appending files asynchronously
(async () => {
for (const download of downloadsToProcess) {
// Claim the download to verify it's authorized
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
if (claim.outcome !== "claimed") continue;
try {
for (const download of downloadsToProcess) {
// Claim the download to verify it's authorized
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
if (claim.outcome !== "claimed") continue;
try {
const original = await immichClient.getOriginal(download.assetId);
// Track bytes read for accounting
let transferredBytes = 0;
const trackingTransform = new TransformStream({
transform(chunk, controller) {
transferredBytes += chunk.length;
controller.enqueue(chunk);
},
async flush() {
await downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes);
}
});
const trackedStream = original.body.pipeThrough(trackingTransform);
const nodeStream = Readable.fromWeb(trackedStream as any);
archive.append(nodeStream, { name: download.filename });
} catch (err) {
console.error("Failed to append original for asset", download.assetId, err);
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
voidNewUsage: download.intentKind === "new_usage"
});
try {
const original = await immichClient.getOriginal(download.assetId);
// Track bytes read for accounting
let transferredBytes = 0;
const trackingTransform = new TransformStream({
transform(chunk, controller) {
transferredBytes += chunk.length;
controller.enqueue(chunk);
},
async flush() {
await downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes);
}
});
const trackedStream = original.body.pipeThrough(trackingTransform);
const nodeStream = Readable.fromWeb(trackedStream as any);
archive.append(nodeStream, { name: download.filename });
} catch (err) {
console.error("Failed to append original for asset", download.assetId, err);
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
voidNewUsage: download.intentKind === "new_usage"
});
}
}
} catch (err) {
console.error("Archive stream failed", err);
archive.abort();
} finally {
archive.finalize();
}
archive.finalize();
})();
const date = new Date().toISOString().split('T')[0];