fix: harden production flows and user messaging

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 16:07:13 +02:00
1 parent 52dce168dd
commit 86dfe8053d
43 files changed
+3520 -358

No files matched your search

+10 -1
View File
@@ -1,5 +1,6 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { env } from "@/config/env";
import { registerEditorial } from "@/modules/auth/auth";
@@ -11,6 +12,7 @@ import {
RegistrationForm,
type RegistrationFormState,
} from "@/modules/auth/public-forms";
import { RateLimitExceededError } from "@/modules/security/rate-limit-guard";
export default function RegistrationPage() {
return (
@@ -62,8 +64,15 @@ async function registerAction(
actsForBusiness: formData.has("actsForBusiness"),
termsVersion: formData.has("termsAccepted") ? CURRENT_TERMS_VERSION : "",
privacyAcknowledged: formData.has("privacyAcknowledged"),
});
}, await headers());
} catch (error) {
if (error instanceof RateLimitExceededError) {
return {
errors: {
form: "Es wurden zu viele Registrierungsversuche gesendet. Bitte versuchen Sie es später erneut.",
},
};
}
if (error instanceof RegistrationValidationError) {
return { errors: { [error.field]: error.message } };
}
+39 -2
View File
@@ -6,14 +6,21 @@ beforeEach(() => {
const mocks = vi.hoisted(() => ({
approveEditorial: vi.fn(),
dbSet: vi.fn(),
dbWhere: vi.fn(),
headers: vi.fn(),
requireAdmin: vi.fn(),
revalidatePath: vi.fn(),
}));
mocks.dbSet.mockReturnValue({ where: mocks.dbWhere });
vi.mock("next/headers", () => ({ headers: mocks.headers }));
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
vi.mock("@/db/client", () => ({
db: { update: vi.fn(() => ({ set: mocks.dbSet })) },
}));
vi.mock("@/modules/editorials/service", () => ({
editorialService: { approveEditorial: mocks.approveEditorial },
EditorialServiceError: class EditorialServiceError extends Error {
@@ -23,7 +30,7 @@ vi.mock("@/modules/editorials/service", () => ({
},
}));
import { approveEditorialAction } from "./actions";
import { approveEditorialAction, updateFlatrateAction } from "./actions";
const initial = { ok: true, message: "" };
@@ -97,4 +104,34 @@ test("the approve action translates a service error into a German message", asyn
ok: false,
message: "Bitte weisen Sie zuerst mindestens ein Album zu.",
});
});
});
test("an active flatrate cannot be persisted without a positive price", async () => {
mocks.headers.mockResolvedValue(new Headers());
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
const formData = new FormData();
formData.set("flatrateActive", "on");
await expect(
updateFlatrateAction("00000000-0000-4000-8000-000000000001", formData),
).rejects.toThrow("INVALID_FLATRATE_PRICE");
expect(mocks.dbSet).not.toHaveBeenCalled();
});
test("an active flatrate persists a positive cents price and optional limit", async () => {
mocks.headers.mockResolvedValue(new Headers());
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
mocks.dbWhere.mockResolvedValue(undefined);
const formData = new FormData();
formData.set("flatrateActive", "on");
formData.set("flatratePriceEuros", "149,50");
formData.set("flatrateAssetLimit", "20");
await updateFlatrateAction("00000000-0000-4000-8000-000000000001", formData);
expect(mocks.dbSet).toHaveBeenCalledWith({
flatrateActive: true,
flatratePriceCents: 14_950,
flatrateAssetLimit: 20,
});
});
@@ -98,6 +98,9 @@ export async function updateFlatrateAction(editorialId: string, formData: FormDa
flatratePriceCents = price.cents;
}
}
if (flatrateActive && flatratePriceCents === null) {
throw new Error("INVALID_FLATRATE_PRICE");
}
let flatrateAssetLimit: number | null = null;
const rawLimit = formData.get("flatrateAssetLimit");
@@ -6,6 +6,7 @@ import { createThumbnailHandler } from "./thumbnail-handler";
vi.mock("sharp", () => {
return {
default: () => ({
resize: vi.fn().mockReturnThis(),
metadata: vi.fn().mockResolvedValue({ width: 100, height: 100 }),
composite: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
@@ -53,6 +54,13 @@ function createHandler(options?: {
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
immich: {
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({
...grantedAlbum,
id,
}));
}),
getAsset: vi.fn().mockImplementation(async () => {
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
return {
@@ -97,6 +105,7 @@ test("streams a thumbnail when the requested asset belongs to any current grant"
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");
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
});
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
@@ -105,7 +114,7 @@ test("refuses a thumbnail immediately after its last grant is revoked", async ()
const response = await call(handler);
expect(response.status).toBe(404);
expect(dependencies.immich.getAsset).not.toHaveBeenCalled();
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
@@ -164,8 +173,8 @@ test("uses one asset-album membership lookup for a 60-photo gallery regardless o
const response = await call(handler);
expect(response.status).toBe(200);
expect(dependencies.immich.getAsset).toHaveBeenCalledTimes(1);
expect(dependencies.immich.getAsset).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
});
@@ -12,7 +12,7 @@ type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>;
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
getThumbnail(assetId: string): Promise<ImmichBinary>;
};
@@ -37,7 +37,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
const access = await authorizeRequest(dependencies, request.headers);
const authorized =
access.kind === "admin"
? true
? await isAdminAlbumCover(
dependencies.immich,
assetId,
requestedUrl.searchParams.get("albumId"),
)
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
if (!authorized) {
return genericNotFound();
@@ -74,21 +78,27 @@ async function authorizeRequest(
async function isGrantedEditorialAsset(
dependencies: ThumbnailHandlerDependencies,
editorialId: string,
assetId: string, // unused but kept for signature
assetId: string,
): Promise<boolean> {
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(editorialId);
// If they have access to at least one album, we allow them to see the watermarked thumbnail.
// UUIDs are unguessable (128-bit entropy), so an editorial user can only request thumbnails
// for assets they already discovered through their granted albums.
// We cannot reliably check asset.albums via getAsset because it is empty for older Immich assets.
return grantedAlbumIds.length > 0;
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<boolean> {
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, max-age=86400, stale-while-revalidate=604800",
"cache-control": "private, no-store",
"content-type": thumbnail.contentType,
"x-content-type-options": "nosniff",
"etag": `"${assetId}"`,
@@ -100,7 +110,10 @@ function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
}
function genericNotFound(): Response {
return new Response(null, { status: 404 });
return new Response(null, {
status: 404,
headers: { "cache-control": "private, no-store" },
});
}
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: string): Promise<Response> {
@@ -158,7 +171,7 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: st
}
const responseHeaders = new Headers({
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
"cache-control": "private, no-store",
"content-type": "image/webp",
"content-length": String(watermarked.length),
"x-content-type-options": "nosniff",
+22 -2
View File
@@ -3,6 +3,12 @@ import { z } from "zod";
import { createRepeatDownload } from "@/modules/downloads/service";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { downloadIntentsPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
import { createNewUsage } from "@/modules/usages/service";
import { UsageAccountingError } from "@/modules/usages/types";
@@ -32,6 +38,7 @@ type IntentHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial;
createNewUsage: typeof createNewUsage;
createRepeatDownload: typeof createRepeatDownload;
consumeRateLimit: ConsumeRateLimit;
};
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
@@ -39,6 +46,11 @@ export function createDownloadIntentHandler(dependencies: IntentHandlerDependenc
try {
assertSameOrigin(request);
const principal = await dependencies.requireActiveEditorial(request.headers);
await enforceRateLimit(
dependencies.consumeRateLimit,
`download-intent:${principal.editorialId}`,
downloadIntentsPolicy,
);
const payload = intentPayload.safeParse(await readJson(request));
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
@@ -85,6 +97,11 @@ async function readJson(request: Request): Promise<unknown> {
}
function mappedError(error: unknown): Response {
if (error instanceof RateLimitExceededError) {
return errorResponse(429, "RATE_LIMITED", {
"retry-after": String(error.retryAfterSeconds),
});
}
if (error instanceof CrossOriginRequestError) {
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
}
@@ -115,10 +132,12 @@ function mappedError(error: unknown): Response {
return errorResponse(500, "REQUEST_FAILED");
}
function errorResponse(status: number, code: string): Response {
function errorResponse(status: number, code: string, extraHeaders?: HeadersInit): Response {
const headers = new Headers(extraHeaders);
headers.set("cache-control", "private, no-store");
return Response.json(
{ code },
{ status, headers: { "cache-control": "private, no-store" } },
{ status, headers },
);
}
@@ -126,4 +145,5 @@ export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
requireActiveEditorial,
createNewUsage,
createRepeatDownload,
consumeRateLimit,
});
@@ -30,6 +30,7 @@ function dependencies() {
status: "authorized",
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
}),
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
};
}
@@ -138,3 +139,23 @@ test("passes one submitted idempotency key through unchanged", async () => {
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
});
test("returns retry-after without creating an intent when the editorial limit is exhausted", async () => {
const deps = dependencies();
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 23 });
const response = await post(createDownloadIntentHandler(deps), {
kind: "new_usage",
assetId,
albumId,
purpose: "Titelgeschichte",
idempotencyKey,
});
expect(response.status).toBe(429);
expect(response.headers.get("retry-after")).toBe("23");
expect(deps.consumeRateLimit).toHaveBeenCalledWith(
`download-intent:${editorialId}`,
expect.any(Object),
);
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
@@ -0,0 +1,139 @@
import { PassThrough, type Readable as NodeReadable } from "node:stream";
import { expect, test, vi } from "vitest";
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
const editorialId = "11111111-1111-4111-8111-111111111111";
const assetId = "22222222-2222-4222-8222-222222222222";
const albumId = "33333333-3333-4333-8333-333333333333";
const downloadId = "44444444-4444-4444-8444-444444444444";
const secondAssetId = "66666666-6666-4666-8666-666666666666";
function fakeArchive(): BulkArchive {
let destination: PassThrough | undefined;
const pending: Promise<void>[] = [];
return {
pipe(target) {
destination = target;
},
append(source: NodeReadable) {
pending.push(
new Promise((resolve, reject) => {
source.on("data", (chunk) => destination?.write(chunk));
source.once("end", resolve);
source.once("error", reject);
}),
);
},
async finalize() {
await Promise.all(pending);
destination?.end();
},
abort() {
destination?.destroy(new Error("aborted"));
},
};
}
function dependencies() {
return {
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
getGrantedAlbumIds: vi.fn().mockResolvedValue([albumId]),
searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: assetId }] }),
getAsset: vi.fn().mockResolvedValue({ id: assetId, originalFileName: "foto.jpg" }),
getOriginal: vi.fn().mockResolvedValue({
body: new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
filename: "foto.jpg",
contentType: "image/jpeg",
contentLength: 3,
}),
listPriorUsages: vi.fn().mockResolvedValue([]),
createNewUsage: vi.fn().mockResolvedValue({ id: downloadId }),
createRepeatDownload: vi.fn(),
repository: {
claimAuthorized: vi.fn().mockResolvedValue({
outcome: "claimed",
download: {
id: downloadId,
usageId: "55555555-5555-4555-8555-555555555555",
assetId,
filename: "foto.jpg",
intentKind: "new_usage",
},
}),
failBeforeDelivery: vi.fn().mockResolvedValue(true),
markCompleted: vi.fn().mockResolvedValue(true),
markInterrupted: vi.fn().mockResolvedValue(true),
},
createArchive: vi.fn(fakeArchive),
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
};
}
function request(origin = "http://portal.test", assetIds = [assetId]) {
return new Request("http://portal.test/api/lightbox/bulk-download", {
method: "POST",
headers: { "content-type": "application/json", host: "portal.test", origin },
body: JSON.stringify({ assetIds, purpose: "Titelgeschichte" }),
});
}
test("rejects cross-origin archive requests before authentication or accounting", async () => {
const deps = dependencies();
const response = await createBulkDownloadHandler(deps)(request("https://attacker.test"));
expect(response.status).toBe(403);
expect(deps.requireActiveEditorial).not.toHaveBeenCalled();
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
test("streams a private archive and completes accounting after response consumption", async () => {
const deps = dependencies();
const incoming = request();
const response = await createBulkDownloadHandler(deps)(incoming);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("private, no-store");
expect(response.headers.get("x-content-type-options")).toBe("nosniff");
expect(deps.repository.markCompleted).not.toHaveBeenCalled();
await response.arrayBuffer();
expect(deps.getOriginal).toHaveBeenCalledWith(assetId, incoming.signal);
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
expect(deps.repository.failBeforeDelivery).not.toHaveBeenCalled();
});
test("rate-limits bulk creation before usages are opened", async () => {
const deps = dependencies();
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 31 });
const response = await createBulkDownloadHandler(deps)(request());
expect(response.status).toBe(429);
expect(response.headers.get("retry-after")).toBe("31");
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
test("settles an already claimed first item when preparation of a later item fails", async () => {
const deps = dependencies();
deps.searchPhotos.mockResolvedValue({ items: [{ id: assetId }, { id: secondAssetId }] });
deps.getAsset.mockImplementation(async (id: string) => ({ id, originalFileName: `${id}.jpg` }));
deps.createNewUsage
.mockResolvedValueOnce({ id: downloadId })
.mockRejectedValueOnce(new Error("accounting unavailable"));
const response = await createBulkDownloadHandler(deps)(
request("http://portal.test", [assetId, secondAssetId]),
);
expect(response.status).toBe(500);
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: true,
});
});
@@ -0,0 +1,343 @@
import { randomUUID } from "node:crypto";
import { basename } from "node:path";
import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import {
createBulkDeliveryAccounting,
streamBulkArchiveWithAccounting,
} from "@/modules/downloads/bulk-accounting";
import type { DownloadDeliveryRepository } from "@/modules/downloads/stream";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { downloadIntentsPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
import { UsageAccountingError } from "@/modules/usages/types";
export type BulkArchive = {
pipe(destination: PassThrough): unknown;
append(source: NodeReadable, options: { name: string }): unknown;
finalize(): Promise<unknown> | unknown;
abort(): unknown;
};
type BulkDownloadHandlerDependencies = {
requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>;
getGrantedAlbumIds(editorialId: string): Promise<string[]>;
searchPhotos(input: {
albumIds: string[];
type: "IMAGE";
page: number;
size: number;
withExif: false;
}): Promise<{ items: Array<{ id: string }> }>;
getAsset(assetId: string): Promise<{ id: string; originalFileName: string }>;
getOriginal(
assetId: string,
signal?: AbortSignal,
): Promise<{ body: ReadableStream<Uint8Array> }>;
listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>;
createNewUsage(input: {
editorialId: string;
assetId: string;
albumId: string;
purpose: string;
reference?: string;
idempotencyKey: string;
}): Promise<{ id: string }>;
createRepeatDownload(input: {
editorialId: string;
usageId: string;
idempotencyKey: string;
}): Promise<{ id: string }>;
repository: DownloadDeliveryRepository;
createArchive(): BulkArchive;
consumeRateLimit: ConsumeRateLimit;
};
type PreparedDownload = {
assetId: string;
downloadId: string;
filename: string;
};
export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDependencies) {
return async function POST(request: Request): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireActiveEditorial(request.headers);
await enforceRateLimit(
dependencies.consumeRateLimit,
`bulk-download:${principal.editorialId}`,
downloadIntentsPolicy,
);
const payload = await parsePayload(request);
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId);
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds);
const accounting = createBulkDeliveryAccounting(dependencies.repository);
let downloads: PreparedDownload[];
try {
downloads = await prepareDownloads(
dependencies,
principal.editorialId,
payload,
assetToGrantedAlbum,
async (item) => {
const claim = await dependencies.repository.claimAuthorized(
principal.editorialId,
item.downloadId,
);
if (claim.outcome !== "claimed") {
throw new Error("Fresh bulk-download intent could not be claimed");
}
accounting.track({
downloadId: item.downloadId,
intentKind: claim.download.intentKind,
});
},
);
} catch (error) {
await accounting.failArchive().catch(() => undefined);
throw error;
}
if (downloads.length === 0) return plainError(404, "No valid assets found for download");
const passThrough = new PassThrough();
const archive = dependencies.createArchive();
archive.pipe(passThrough);
const abortArchive = () => {
try {
archive.abort();
} catch {
// The archive may already be finalized.
}
passThrough.destroy(new Error("Archive request aborted"));
};
request.signal.addEventListener("abort", abortArchive, { once: true });
passThrough.once("close", () => request.signal.removeEventListener("abort", abortArchive));
void produceArchive({
archive,
passThrough,
downloads,
requestSignal: request.signal,
getOriginal: dependencies.getOriginal,
accounting,
});
const body = streamBulkArchiveWithAccounting(
Readable.toWeb(passThrough) as ReadableStream<Uint8Array>,
accounting,
);
const date = new Date().toISOString().slice(0, 10);
return new Response(body, {
headers: {
"cache-control": "private, no-store",
"content-disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
"content-type": "application/zip",
"x-content-type-options": "nosniff",
},
});
} catch (error) {
console.error("[bulk-download] failed:", error);
return mappedBulkError(error);
}
};
}
async function produceArchive({
archive,
passThrough,
downloads,
requestSignal,
getOriginal,
accounting,
}: {
archive: BulkArchive;
passThrough: PassThrough;
downloads: PreparedDownload[];
requestSignal: AbortSignal;
getOriginal: BulkDownloadHandlerDependencies["getOriginal"];
accounting: ReturnType<typeof createBulkDeliveryAccounting>;
}) {
try {
for (const item of downloads) {
if (requestSignal.aborted) throw new Error("Archive request aborted");
const original = await getOriginal(item.assetId, requestSignal);
const source = Readable.fromWeb(
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
);
source.on("data", (chunk: Buffer) => accounting.addBytes(item.downloadId, chunk.length));
const ended = new Promise<void>((resolve, reject) => {
source.once("end", resolve);
source.once("error", reject);
});
archive.append(source, { name: safeArchiveFilename(item.filename) });
await ended;
accounting.markEntryReady(item.downloadId);
}
await archive.finalize();
} catch (error) {
await accounting.failArchive().catch(() => undefined);
try {
archive.abort();
} catch {
// Ignore cleanup errors; the accounting state is already terminal.
}
passThrough.destroy(error instanceof Error ? error : new Error("Archive failed"));
}
}
async function grantedAssetMap(
dependencies: BulkDownloadHandlerDependencies,
grantedAlbumIds: string[],
) {
const result = new Map<string, string>();
const albums = await Promise.all(
grantedAlbumIds.map(async (albumId) => {
try {
const page = await dependencies.searchPhotos({
albumIds: [albumId],
type: "IMAGE",
page: 1,
size: 1_000,
withExif: false,
});
return { albumId, items: page.items };
} catch {
return { albumId, items: [] };
}
}),
);
for (const album of albums) {
for (const asset of album.items) {
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
}
}
return result;
}
async function prepareDownloads(
dependencies: BulkDownloadHandlerDependencies,
editorialId: string,
payload: { assetIds: string[]; purpose: string },
assetToGrantedAlbum: Map<string, string>,
onPrepared: (item: PreparedDownload) => Promise<void>,
) {
const assets = await Promise.all(
payload.assetIds.map(async (assetId) => {
try {
return await dependencies.getAsset(assetId);
} catch {
return null;
}
}),
);
const downloads: PreparedDownload[] = [];
for (const asset of assets) {
if (!asset) continue;
const albumId = assetToGrantedAlbum.get(asset.id);
if (!albumId) continue;
const prior = await dependencies.listPriorUsages(editorialId, asset.id);
const intent = prior[0]
? await dependencies.createRepeatDownload({
editorialId,
usageId: prior[0].id,
idempotencyKey: randomUUID(),
})
: await dependencies.createNewUsage({
editorialId,
assetId: asset.id,
albumId,
purpose: payload.purpose,
reference: undefined,
idempotencyKey: randomUUID(),
});
const prepared = {
assetId: asset.id,
downloadId: intent.id,
filename: asset.originalFileName,
};
await onPrepared(prepared);
downloads.push(prepared);
}
return downloads;
}
async function parsePayload(request: Request) {
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown };
if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) {
throw new BulkInputError();
}
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
if (body.assetIds.some((value) => typeof value !== "string" || !uuid.test(value))) {
throw new BulkInputError();
}
if (typeof body.purpose !== "string" || body.purpose.trim().length === 0 || body.purpose.trim().length > 500) {
throw new BulkInputError();
}
return { assetIds: body.assetIds as string[], purpose: body.purpose.trim() };
}
class BulkInputError extends Error {}
function safeArchiveFilename(value: string) {
const cleaned = basename(value)
.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_")
.trim()
.slice(0, 180);
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto";
}
function plainError(status: number, message: string) {
return new Response(message, {
status,
headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" },
});
}
function mappedBulkError(error: unknown): Response {
if (error instanceof RateLimitExceededError) {
return jsonError(429, "RATE_LIMITED", {
"retry-after": String(error.retryAfterSeconds),
});
}
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
if (error instanceof BulkInputError) return jsonError(400, "INVALID_INPUT");
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
if (error instanceof UsageAccountingError) {
const statusByCode: Record<UsageAccountingError["code"], number> = {
INVALID_INPUT: 400,
IDEMPOTENCY_CONFLICT: 409,
ALBUM_NOT_GRANTED: 404,
ASSET_NOT_FOUND: 404,
ASSET_NOT_IN_ALBUM: 404,
ASSET_NOT_IMAGE: 422,
USAGE_NOT_FOUND: 404,
IMMICH_UNAVAILABLE: 503,
EDITORIAL_NOT_ACTIVE: 403,
INVALID_PRICE: 409,
};
return jsonError(statusByCode[error.code] ?? 500, error.code);
}
return jsonError(500, "REQUEST_FAILED");
}
function jsonError(status: number, code: string, extraHeaders?: HeadersInit) {
const headers = new Headers(extraHeaders);
headers.set("cache-control", "private, no-store");
headers.set("x-content-type-options", "nosniff");
return Response.json(
{ code },
{
status,
headers,
},
);
}
+21 -227
View File
@@ -1,231 +1,25 @@
import { NextRequest } from "next/server";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { usageService } from "@/modules/usages/service";
import { createRepeatDownload } from "@/modules/downloads/service";
import { UsageAccountingError } from "@/modules/usages/types";
import { immichClient } from "@/modules/immich/client";
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
import { albumGrantService } from "@/modules/albums/grants";
// 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, PassThrough } from "stream";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { createRepeatDownload } from "@/modules/downloads/service";
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
import { immichClient } from "@/modules/immich/client";
import { consumeRateLimit } from "@/modules/security/rate-limit";
import { usageService } from "@/modules/usages/service";
export async function POST(request: NextRequest) {
try {
const principal = await requireActiveEditorial(request.headers);
const { assetIds, purpose } = await request.json();
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
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 });
}
}
const archiver = require("archiver") as { ZipArchive: new (options: unknown) => BulkArchive };
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);
// Build a map of assetId -> a granted album that contains it. Immich's
// GET /albums/:id no longer returns assets (metadata only), so fetch each
// granted album's assets via /search/metadata instead.
// ponytail: ceiling of 1000 assets per album; tail assets beyond that
// won't map and are skipped from bulk download. Raise if needed.
const assetToGrantedAlbum = new Map<string, string>();
const albumAssets = await Promise.all(
grantedAlbumIds.map(async (albumId) => {
try {
const page = await immichClient.searchPhotos({
albumIds: [albumId],
type: "IMAGE",
page: 1,
size: 1000,
withExif: false,
});
return { albumId, items: page.items };
} catch (err) {
console.error("Failed to fetch granted album assets", albumId, err);
return { albumId, items: [] };
}
}),
);
for (const { albumId, items } of albumAssets) {
for (const asset of items) {
if (!assetToGrantedAlbum.has(asset.id)) {
assetToGrantedAlbum.set(asset.id, albumId);
}
}
}
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
// 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. 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 validAlbumId = assetToGrantedAlbum.get(assetId);
if (!validAlbumId) continue; // Editorial does not have access
// Check for prior usages to avoid double charging
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
const isRepeat = priorUsages.length > 0;
let downloadId: string;
if (isRepeat) {
// Create a repeat-download intent against the existing usage so the
// delivery claim (claimAuthorized, which looks up download_events.id)
// finds a valid intent. Reusing the usage id directly never matches.
const repeatIntent = await createRepeatDownload({
editorialId: principal.editorialId,
usageId: priorUsages[0].id,
idempotencyKey: crypto.randomUUID(),
});
downloadId = repeatIntent.id;
} else {
const idempotencyKey = crypto.randomUUID();
const newUsage = await usageService.createNewUsage({
editorialId: principal.editorialId,
assetId,
albumId: validAlbumId,
purpose: trimmedPurpose,
reference: undefined,
idempotencyKey,
});
downloadId = newUsage.id;
}
downloadsToProcess.push({
assetId,
downloadId,
filename: asset.originalFileName,
intentKind: isRepeat ? "repeat" : "new_usage",
});
}
if (downloadsToProcess.length === 0) {
return new Response("No valid assets found for download", { status: 404 });
}
const passThrough = new PassThrough();
// archiver v8 exports class constructors ({ ZipArchive, ... }), not a
// callable. The old `archiver('zip', opts)` form throws TypeError at
// runtime — which was masked until the membership fix populated the map
// and this line was actually reached (before, the route 404'd early).
const archive = new archiver.ZipArchive({ zlib: { level: 0 } });
archive.pipe(passThrough);
// Start appending files asynchronously
(async () => {
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);
await new Promise<void>((resolve, reject) => {
const nodeStream = Readable.fromWeb(original.body as any);
let transferredBytes = 0;
nodeStream.on('data', (chunk) => {
transferredBytes += chunk.length;
});
nodeStream.on('end', () => {
downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes)
.then(() => resolve())
.catch(reject);
});
nodeStream.on('error', (err) => reject(err));
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();
}
})();
const date = new Date().toISOString().split('T')[0];
return new Response(Readable.toWeb(passThrough) as any, {
headers: {
"Content-Type": "application/zip",
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
},
});
} catch (err) {
// Surface the real cause. Without this, any UsageAccountingError from
// createNewUsage/createRepeatDownload (e.g. IMMICH_UNAVAILABLE under load)
// became an opaque 500 and the user only saw "Download fehlgeschlagen".
console.error("[bulk-download] failed:", err);
return mappedBulkError(err);
}
}
function mappedBulkError(error: unknown): Response {
if (error instanceof PrincipalAuthorizationError) {
return Response.json(
{ code: "FORBIDDEN" },
{ status: error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, headers: { "cache-control": "private, no-store" } },
);
}
if (error instanceof UsageAccountingError) {
const statusByCode: Record<UsageAccountingError["code"], number> = {
INVALID_INPUT: 400,
IDEMPOTENCY_CONFLICT: 409,
ALBUM_NOT_GRANTED: 404,
ASSET_NOT_FOUND: 404,
ASSET_NOT_IN_ALBUM: 404,
ASSET_NOT_IMAGE: 422,
USAGE_NOT_FOUND: 404,
IMMICH_UNAVAILABLE: 503,
EDITORIAL_NOT_ACTIVE: 403,
INVALID_PRICE: 409,
};
const status = statusByCode[error.code] ?? 500;
return Response.json(
{ code: error.code },
{ status, headers: { "cache-control": "private, no-store" } },
);
}
return Response.json(
{ code: "REQUEST_FAILED" },
{ status: 500, headers: { "cache-control": "private, no-store" } },
);
}
export const POST = createBulkDownloadHandler({
requireActiveEditorial,
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId),
searchPhotos: (input) => immichClient.searchPhotos(input),
getAsset: (assetId) => immichClient.getAsset(assetId),
getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal),
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
createNewUsage: (input) => usageService.createNewUsage(input),
createRepeatDownload,
repository: downloadDeliveryRepository,
createArchive: () => new archiver.ZipArchive({ zlib: { level: 0 } }),
consumeRateLimit,
});
+5 -2
View File
@@ -158,7 +158,10 @@ async function loadAlbumPage({
const lightboxAssetIds = new Set(lightboxItems.map((i) => i.assetId));
return { album, page: resultPage, currentPage, downloadOptions, lightboxAssetIds, unavailable: false as const };
} catch (error) {
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
if (
error instanceof AlbumCatalogError &&
(error.code === "IMMICH_UNAVAILABLE" || error.code === "RATE_LIMITED")
) {
return { album: null, page: null, currentPage: 1, downloadOptions: undefined, lightboxAssetIds: new Set<string>(), unavailable: true as const };
}
throw error;
@@ -190,4 +193,4 @@ function ImmichUnavailable() {
</PageHeader>
</section>
);
}
}
+25 -5
View File
@@ -23,11 +23,19 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
const jahr = singleValue(rawSearchParams.jahr);
if (query) {
const results = await albumCatalog.searchVisiblePhotos(principal.editorialId, {
description: query,
page: 1,
size: SEARCH_FETCH_SIZE,
});
let results;
try {
results = await albumCatalog.searchVisiblePhotos(principal.editorialId, {
description: query,
page: 1,
size: SEARCH_FETCH_SIZE,
});
} catch (error) {
if (error instanceof AlbumCatalogError && error.code === "RATE_LIMITED") {
return <SearchRateLimited query={query} format={format} jahr={jahr} />;
}
throw error;
}
const filtered = filterPhotos(results.items, { format, jahr });
const { result: page, currentPage } = paginatePhotos(filtered, singleValue(rawSearchParams.page), PHOTO_PAGE_SIZE);
@@ -86,6 +94,18 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
);
}
function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) {
return (
<div className="space-y-6 max-w-7xl" aria-labelledby="albums-title">
<PageHeader kicker="Bildarchiv · Suche" title="Bitte kurz warten" titleId="albums-title" />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<p className="bg-muted p-4 rounded-md" role="status">
Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut.
</p>
</div>
);
}
function GlobalSearchForm({ query, format, jahr }: { query: string; format?: string; jahr?: string; }) {
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 10 }, (_, i) => currentYear - i);
+5 -7
View File
@@ -8,20 +8,18 @@ import { expect, test } from "vitest";
import { PortalShell } from "@/components/layout/portal-shell";
import { BrandLogo } from "./logo";
test("uses the supplied logo's true intrinsic dimensions and renders both light and dark variants", () => {
test("lets CSS constrain both supplied logo variants without oversized intrinsic attributes", () => {
render(<BrandLogo />);
const logos = screen.getAllByAltText("Leon Tonhäuser Sportfotografie");
expect(logos).toHaveLength(2);
// Light mode logo
expect(logos[0].getAttribute("width")).toBe("1000");
expect(logos[0].getAttribute("height")).toBe("1000");
expect(logos[0].getAttribute("width")).toBeNull();
expect(logos[0].getAttribute("height")).toBeNull();
expect(logos[0].className).toContain("brand-logo-light");
// Dark mode logo
expect(logos[1].getAttribute("width")).toBe("1000");
expect(logos[1].getAttribute("height")).toBe("1000");
expect(logos[1].getAttribute("width")).toBeNull();
expect(logos[1].getAttribute("height")).toBeNull();
expect(logos[1].className).toContain("brand-logo-dark");
});
+3 -4
View File
@@ -6,8 +6,7 @@ import { authClient } from "@/modules/auth/client";
import { Button } from "@/components/ui/button";
// Renders into the portal masthead. Better Auth's signOut clears the session
// cookie server-side; we then hard-navigate to the login page so no stale
// session remains in the client router cache.
// cookie server-side; a hard replacement clears any stale router cache.
export function LogoutButton() {
const [pending, setPending] = useState(false);
@@ -16,7 +15,7 @@ export function LogoutButton() {
try {
await authClient.signOut();
} finally {
window.location.assign("/anmelden");
window.location.replace("/anmelden");
}
}
@@ -31,4 +30,4 @@ export function LogoutButton() {
{pending ? "…" : "Abmelden"}
</Button>
);
}
}
+4 -13
View File
@@ -1,31 +1,22 @@
"use client"
import * as React from "react"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
export function ThemeToggle() {
const { theme, setTheme } = useTheme()
const [mounted, setMounted] = React.useState(false)
// Avoid hydration mismatch
React.useEffect(() => setMounted(true), [])
if (!mounted) return <div className="w-9 h-9" /> // Placeholder to prevent layout shift
const { resolvedTheme, setTheme } = useTheme()
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
title="Design umschalten"
>
{theme === "light" ? (
<Sun className="h-[1.2rem] w-[1.2rem] transition-all" />
) : (
<Moon className="h-[1.2rem] w-[1.2rem] transition-all" />
)}
<Sun className="h-[1.2rem] w-[1.2rem] transition-all dark:hidden" />
<Moon className="hidden h-[1.2rem] w-[1.2rem] transition-all dark:block" />
<span className="sr-only">Design umschalten</span>
</Button>
)
+14 -1
View File
@@ -28,11 +28,13 @@ function createCatalog(options?: {
return { items: [], total: 0, nextPage: null, previousPage: null };
}),
};
const consumeRateLimit = vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 });
return {
catalog: createAlbumCatalog({ grants, immich }),
catalog: createAlbumCatalog({ grants, immich, consumeRateLimit }),
grants,
immich,
consumeRateLimit,
};
}
@@ -141,3 +143,14 @@ test("does not expose a caller-controlled asset type in the catalog contract", a
expect(immich.searchPhotos).toHaveBeenCalledWith(expect.objectContaining({ type: "IMAGE" }));
});
test("rate-limits description searches per authenticated editorial", async () => {
const { catalog, consumeRateLimit, immich } = createCatalog();
consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 19 });
await expect(
catalog.searchVisiblePhotos("editorial-1", { description: "Tor", page: 1 }),
).rejects.toMatchObject({ code: "RATE_LIMITED", retryAfterSeconds: 19 });
expect(consumeRateLimit).toHaveBeenCalledWith("search:editorial-1", expect.any(Object));
expect(immich.searchPhotos).not.toHaveBeenCalled();
});
+24 -3
View File
@@ -3,6 +3,12 @@ import "server-only";
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary, ImmichClient, ImmichSearchPage } from "@/modules/immich/types";
import { consumeRateLimit, searchPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
export const PHOTO_PAGE_SIZE = 60;
export const MAX_PHOTO_PAGE = 1_000;
@@ -20,17 +26,21 @@ export type SearchVisiblePhotosInput = {
export type AlbumCatalogDependencies = {
grants: Pick<typeof albumGrantService, "getGrantedAlbumIds">;
immich: Pick<ImmichClient, "listAlbums" | "searchPhotos">;
consumeRateLimit: ConsumeRateLimit;
};
export class AlbumCatalogError extends Error {
readonly name = "AlbumCatalogError";
constructor(readonly code: "IMMICH_UNAVAILABLE") {
constructor(
readonly code: "IMMICH_UNAVAILABLE" | "RATE_LIMITED",
readonly retryAfterSeconds?: number,
) {
super(code);
}
}
export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies) {
export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }: AlbumCatalogDependencies) {
return {
async getVisibleAlbums(editorialId: string): Promise<VisibleAlbum[]> {
const [grantedAlbumIds, albums] = await Promise.all([
@@ -45,12 +55,22 @@ export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies)
editorialId: string,
input: SearchVisiblePhotosInput,
): Promise<ImmichSearchPage> {
const description = normalizeDescription(input.description);
if (description) {
try {
await enforceRateLimit(consume, `search:${editorialId}`, searchPolicy);
} catch (error) {
if (error instanceof RateLimitExceededError) {
throw new AlbumCatalogError("RATE_LIMITED", error.retryAfterSeconds);
}
throw error;
}
}
const grantedAlbumIds = await currentGrantIds(grants, editorialId);
if (grantedAlbumIds.length === 0) {
return emptySearchPage();
}
const description = normalizeDescription(input.description);
const page = normalizePage(input.page);
const size = input.size ?? PHOTO_PAGE_SIZE;
@@ -169,4 +189,5 @@ async function loadAlbums(
export const albumCatalog = createAlbumCatalog({
grants: albumGrantService,
immich: immichClient,
consumeRateLimit,
});
+63 -1
View File
@@ -3,7 +3,7 @@ import { expect, test, vi } from "vitest";
import { POST } from "@/app/api/auth/[...all]/route";
import { createPortalAuth } from "./auth";
import { createPortalAuth, createRegistrationIngress } from "./auth";
import { CURRENT_TERMS_VERSION } from "./registration";
test("allows the trusted registration service ingress while rejecting public direct sign-up", async () => {
@@ -59,3 +59,65 @@ test("allows the trusted registration service ingress while rejecting public dir
expect(response.status).toBe(403);
});
test("rate-limits registration by a hashed email and proxy identity before sign-up", async () => {
const register = vi.fn();
const consume = vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 120 });
const ingress = createRegistrationIngress({ register, consumeRateLimit: consume });
await expect(
ingress(
{
companyName: "Beispiel GmbH",
contactName: "Max Beispiel",
email: "Redaktion@Example.com",
password: "sicheres-passwort-123",
billingAddress: {
addressLine1: "Presseweg 1",
postalCode: "10115",
city: "Berlin",
countryCode: "DE",
},
actsForBusiness: true,
termsVersion: CURRENT_TERMS_VERSION,
privacyAcknowledged: true,
},
new Headers({ "x-real-ip": "203.0.113.8" }),
),
).rejects.toMatchObject({ name: "RateLimitExceededError", retryAfterSeconds: 120 });
expect(consume).toHaveBeenCalledWith(expect.stringMatching(/^registration:[a-f0-9]{64}$/), expect.any(Object));
expect(register).not.toHaveBeenCalled();
});
test("keeps Better Auth login limits separate for clients forwarded by Zoraxy", async () => {
const registrationRepository = {
createEditorial: vi.fn(),
markPendingApproval: vi.fn(),
removeUnverifiedAuthIdentity: vi.fn(),
recordRegistrationCompensationFailure: vi.fn(),
recordVerificationInconsistency: vi.fn(),
canCreateSession: vi.fn().mockResolvedValue(false),
};
const { auth } = createPortalAuth({
database: memoryAdapter({ user: [], account: [], session: [], verification: [] }),
mailerService: { sendPasswordReset: vi.fn(), sendVerification: vi.fn() },
registrationRepository,
});
const signIn = (forwardedFor: string) =>
auth.handler(
new Request("http://localhost:3000/api/auth/sign-in/email", {
method: "POST",
headers: {
"content-type": "application/json",
"x-forwarded-for": forwardedFor,
},
body: JSON.stringify({ email: "nobody@example.com", password: "invalid-password" }),
}),
);
for (let attempt = 0; attempt < 5; attempt += 1) await signIn("203.0.113.10");
const otherClient = await signIn("203.0.113.11");
expect(otherClient.status).not.toBe(429);
});
+45 -3
View File
@@ -7,6 +7,12 @@ import { env } from "@/config/env";
import { db } from "@/db/client";
import { accounts, sessions, users, verifications } from "@/db/schema";
import { mailer } from "@/modules/mail/mailer";
import { consumeRateLimit, registrationPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
hashedRequestIdentity,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
import {
createEditorialRegistrationRepository,
@@ -14,6 +20,19 @@ import {
type RegistrationInput,
} from "./registration";
export const portalAuthRateLimitOptions = {
enabled: true,
storage: "memory",
window: 60,
max: 100,
customRules: {
"/sign-in/email": { window: 15 * 60, max: 5 },
"/request-password-reset": { window: 60 * 60, max: 5 },
"/reset-password": { window: 60 * 60, max: 5 },
"/send-verification-email": { window: 60 * 60, max: 5 },
},
} satisfies NonNullable<BetterAuthOptions["rateLimit"]>;
export function createPortalAuth({
database,
mailerService,
@@ -29,11 +48,16 @@ export function createPortalAuth({
baseURL: env.BETTER_AUTH_URL,
secret: env.BETTER_AUTH_SECRET,
database,
rateLimit: portalAuthRateLimitOptions,
// All id columns are typed `uuid`; Better Auth's default id generator emits
// a nanoid-style string that Postgres rejects with "invalid input syntax
// for type uuid". Generate real UUIDs so inserts (signUp, sessions,
// verifications) match the schema.
advanced: { database: { generateId: () => crypto.randomUUID() } },
advanced: {
database: { generateId: () => crypto.randomUUID() },
// The reverse proxy must overwrite this header; see docs/operations.md.
ipAddress: { ipAddressHeaders: ["x-forwarded-for", "x-real-ip"] },
},
// `role` is a custom column on `users` (portalRole enum: ADMIN | EDITORIAL).
// Better Auth's parseUserOutput filters the session user to declared fields
// only, so without this the drizzle adapter selects `role` but it is then
@@ -123,6 +147,24 @@ const portalAuth = createPortalAuth({
export const auth = portalAuth.auth;
export const registrationService = portalAuth.registrationService;
export function registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }> {
return registrationService.register(input);
export function createRegistrationIngress({
register,
consumeRateLimit: consume,
}: {
register(input: RegistrationInput): Promise<{ status: "pending_email" }>;
consumeRateLimit: ConsumeRateLimit;
}) {
return async function registrationIngress(input: RegistrationInput, headers = new Headers()) {
await enforceRateLimit(
consume,
hashedRequestIdentity("registration", input.email, headers),
registrationPolicy,
);
return register(input);
};
}
export const registerEditorial = createRegistrationIngress({
register: (input) => registrationService.register(input),
consumeRateLimit,
});
+40 -3
View File
@@ -1,9 +1,16 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { RegistrationForm } from "./public-forms";
const { resetPassword } = vi.hoisted(() => ({ resetPassword: vi.fn() }));
vi.mock("./client", () => ({
authClient: { resetPassword },
}));
import { PasswordResetForm, RegistrationForm } from "./public-forms";
afterEach(cleanup);
test("registration presents separate B2B, terms, and privacy acknowledgements", () => {
render(
@@ -40,3 +47,33 @@ test("registration presents separate B2B, terms, and privacy acknowledgements",
);
expect(document.querySelector('input[name="termsVersion"]')).toBeNull();
});
test("confirms a successful password reset and links directly to login", async () => {
resetPassword.mockResolvedValueOnce({ data: { status: true }, error: null });
render(<PasswordResetForm token="valid-token" />);
fireEvent.change(screen.getByLabelText(/neues passwort/i), {
target: { value: "neues-passwort-123" },
});
fireEvent.submit(screen.getByRole("button", { name: /passwort aktualisieren/i }).closest("form")!);
expect(await screen.findByText(/passwort wurde erfolgreich aktualisiert/i)).toBeTruthy();
expect(screen.getByRole("link", { name: /jetzt anmelden/i }).getAttribute("href")).toBe(
"/anmelden",
);
});
test("does not claim success when the reset link is invalid", async () => {
resetPassword.mockResolvedValueOnce({ data: null, error: { code: "INVALID_TOKEN" } });
render(<PasswordResetForm token="invalid-token" />);
fireEvent.change(screen.getByLabelText(/neues passwort/i), {
target: { value: "neues-passwort-123" },
});
fireEvent.submit(screen.getByRole("button", { name: /passwort aktualisieren/i }).closest("form")!);
await waitFor(() =>
expect(screen.getByRole("alert").textContent).toMatch(/link.*ungültig|abgelaufen/i),
);
expect(screen.queryByText(/erfolgreich aktualisiert/i)).toBeNull();
});
+22 -7
View File
@@ -228,27 +228,41 @@ export function PasswordResetRequestForm() {
}
export function PasswordResetForm({ token }: { token?: string }) {
const [message, setMessage] = useState<string>();
const [success, setSuccess] = useState(false);
const [error, setError] = useState<string>();
const [pending, setPending] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setPending(true);
setError(undefined);
const formData = new FormData(event.currentTarget);
try {
await authClient.resetPassword({ newPassword: readText(formData, "password"), token });
const result = await authClient.resetPassword({
newPassword: readText(formData, "password"),
token,
});
if (result.error) {
setError("Der Link ist ungültig oder abgelaufen. Bitte fordern Sie einen neuen Link an.");
return;
}
setSuccess(true);
} catch {
setError("Der Link ist ungültig oder abgelaufen. Bitte fordern Sie einen neuen Link an.");
} finally {
setMessage("Wenn der Link gültig war, wurde Ihr Passwort aktualisiert.");
setPending(false);
}
}
if (message) {
if (success) {
return (
<p className="form-note" role="status">
{message}
</p>
<div className="form-note" role="status">
<p>Ihr Passwort wurde erfolgreich aktualisiert. Sie können sich jetzt damit anmelden.</p>
<a className="primary-action" href="/anmelden">
Jetzt anmelden
</a>
</div>
);
}
@@ -258,6 +272,7 @@ export function PasswordResetForm({ token }: { token?: string }) {
Neues Passwort
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
</label>
<FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit">
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
</button>
+9 -2
View File
@@ -1,6 +1,6 @@
import { expect, test } from "vitest";
import { monthPeriod, quarterPeriod, type BillingPeriod } from "./period";
import { berlinMonthPeriodAt, monthPeriod, quarterPeriod, type BillingPeriod } from "./period";
test("converts a Berlin month to an exclusive UTC range", () => {
expect(monthPeriod(2026, 3)).toEqual({
@@ -9,6 +9,13 @@ test("converts a Berlin month to an exclusive UTC range", () => {
});
});
test("selects the Berlin calendar month at a UTC month-edge instant", () => {
expect(berlinMonthPeriodAt(new Date("2026-03-31T22:30:00.000Z"))).toEqual({
fromUtc: new Date("2026-03-31T22:00:00.000Z"),
toUtcExclusive: new Date("2026-04-30T22:00:00.000Z"),
});
});
test("converts a Berlin month in full summer (CEST) to an exclusive UTC range", () => {
expect(monthPeriod(2026, 8)).toEqual({
fromUtc: new Date("2026-07-31T22:00:00.000Z"),
@@ -68,4 +75,4 @@ test("supports an explicit timezone override", () => {
fromUtc: new Date("2026-03-01T05:00:00.000Z"),
toUtcExclusive: new Date("2026-04-01T04:00:00.000Z"),
});
});
});
+8 -1
View File
@@ -35,6 +35,13 @@ export function monthPeriod(year: number, month: number, zone = "Europe/Berlin")
return toBillingPeriod(startPlain, endPlain, zone);
}
export function berlinMonthPeriodAt(instant: Date): BillingPeriod {
const zoned = Temporal.Instant.fromEpochMilliseconds(instant.getTime()).toZonedDateTimeISO(
"Europe/Berlin",
);
return monthPeriod(zoned.year, zoned.month, "Europe/Berlin");
}
/**
* Returns the half-open UTC range for the given calendar quarter in the
* given IANA time zone (default `Europe/Berlin`).
@@ -71,4 +78,4 @@ function toBillingPeriod(
function addMonths(year: number, month: number, count: number): { year: number; month: number } {
const total = year * 12 + (month - 1) + count;
return { year: Math.floor(total / 12), month: (total % 12) + 1 };
}
}
+32 -3
View File
@@ -56,7 +56,7 @@ function selectedUsage(id: string, status: "open" | "reopened" = "open"): Select
// In-memory mock repository
// ---------------------------------------------------------------------------
function createMockRepo() {
function createMockRepo(options?: { flatratePriceCents?: number | null }) {
const usageStatuses = new Map<string, string>([
["u1", "open"],
["u2", "open"],
@@ -71,7 +71,12 @@ function createMockRepo() {
},
async getEditorialFlatrate() {
return { flatrateActive: false, flatratePriceCents: null, flatrateAssetLimit: null };
const flatratePriceCents = options?.flatratePriceCents ?? null;
return {
flatrateActive: flatratePriceCents !== null,
flatratePriceCents,
flatrateAssetLimit: null,
};
},
async getSelectedUsages(_editorialId, usageIds) {
@@ -247,6 +252,30 @@ test("previewReport returns PDF bytes without persisting or billing", async () =
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]);
});
test("uses the server-read flatrate snapshot consistently in PDF, total, and persistence", async () => {
const { repo, reports } = createMockRepo({ flatratePriceCents: 12_500 });
const finalizeInTransaction = vi.spyOn(repo, "finalizeInTransaction");
const { service, render } = createService(repo);
const result = await service.finalizeReport(validSelection);
expect(render).toHaveBeenCalledWith(
expect.objectContaining({
flatrateCentsSnapshot: 12_500,
netTotalCents: 18_500,
}),
);
expect(finalizeInTransaction).toHaveBeenCalledWith(
expect.objectContaining({
flatrateCentsSnapshot: 12_500,
netTotalCents: 18_500,
}),
);
await expect(repo.getReport(result.reportId)).resolves.toMatchObject({
netTotalCents: 18_500,
});
});
test("finalizeReport rejects when a selected usage is already billed", async () => {
const mock = createMockRepo();
const { repo } = mock;
@@ -273,4 +302,4 @@ test("cancelReport rejects a reason longer than 500 characters", async () => {
await expect(
service.cancelReport({ reportId: "r1", reason: "x".repeat(501), adminUserId: "a1" }),
).rejects.toThrow();
});
});
+18 -8
View File
@@ -227,8 +227,13 @@ export function createReportService({
* bytes. No database writes are performed — the preview is not persisted.
*/
async previewReport(input: PreviewReportInput): Promise<Buffer> {
const { usages: selectedUsages, address, repeatDownloads, netTotalCents } =
await buildSnapshot(repo, input);
const {
usages: selectedUsages,
address,
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot,
} = await buildSnapshot(repo, input);
// Preview uses report number 0 and a "VORSCHAU" invoice number — the
// preview is not persisted, so these placeholder values never collide
@@ -238,7 +243,7 @@ export function createReportService({
selectedPositions: selectedUsages.map(toReportPosition),
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
flatrateCentsSnapshot,
reportNumber: 0,
invoiceNumber: "VORSCHAU",
period: input.period,
@@ -264,8 +269,13 @@ export function createReportService({
* If the render fails, nothing is written.
*/
async finalizeReport(input: FinalizeReportInput): Promise<FinalizeResult> {
const { usages: selectedUsages, address, repeatDownloads, netTotalCents } =
await buildSnapshot(repo, input);
const {
usages: selectedUsages,
address,
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot,
} = await buildSnapshot(repo, input);
const reportNumber = await repo.allocateReportNumber();
const invoiceNumber = buildInvoiceNumber(reportNumber, input.period);
@@ -277,7 +287,7 @@ export function createReportService({
selectedPositions: selectedUsages.map(toReportPosition),
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
flatrateCentsSnapshot,
reportNumber,
invoiceNumber,
period: input.period,
@@ -303,7 +313,7 @@ export function createReportService({
address,
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
flatrateCentsSnapshot,
pdfBytes: rendered.bytes,
pdfSha256: rendered.sha256,
documentId,
@@ -759,4 +769,4 @@ export const reportService = createReportService({
export const previewReport = reportService.previewReport;
export const finalizeReport = reportService.finalizeReport;
export const cancelReport = reportService.cancelReport;
export const getReportPdf = reportService.getReportPdf;
export const getReportPdf = reportService.getReportPdf;
@@ -0,0 +1,110 @@
import { expect, test, vi } from "vitest";
import {
createBulkDeliveryAccounting,
streamBulkArchiveWithAccounting,
} from "./bulk-accounting";
function repository() {
return {
failBeforeDelivery: vi.fn().mockResolvedValue(true),
markCompleted: vi.fn().mockResolvedValue(true),
markInterrupted: vi.fn().mockResolvedValue(true),
};
}
test("defers completion until the complete archive response has finished", async () => {
const repo = repository();
const accounting = createBulkDeliveryAccounting(repo);
accounting.track({ downloadId: "d1", intentKind: "new_usage" });
accounting.addBytes("d1", 4);
accounting.markEntryReady("d1");
expect(repo.markCompleted).not.toHaveBeenCalled();
await accounting.completeArchive();
expect(repo.markCompleted).toHaveBeenCalledWith("d1", 4);
expect(repo.markInterrupted).not.toHaveBeenCalled();
});
test("voids a new usage when the archive fails before its first source byte", async () => {
const repo = repository();
const accounting = createBulkDeliveryAccounting(repo);
accounting.track({ downloadId: "d1", intentKind: "new_usage" });
await accounting.failArchive();
expect(repo.failBeforeDelivery).toHaveBeenCalledWith("d1", { voidNewUsage: true });
expect(repo.markCompleted).not.toHaveBeenCalled();
});
test("records an interrupted attempt when an archive fails after source bytes", async () => {
const repo = repository();
const accounting = createBulkDeliveryAccounting(repo);
accounting.track({ downloadId: "d1", intentKind: "repeat_download" });
accounting.addBytes("d1", 7);
await accounting.failArchive();
expect(repo.markInterrupted).toHaveBeenCalledWith("d1", 7);
expect(repo.failBeforeDelivery).not.toHaveBeenCalled();
});
test("settles every tracked event at most once across competing terminal signals", async () => {
const repo = repository();
const accounting = createBulkDeliveryAccounting(repo);
accounting.track({ downloadId: "d1", intentKind: "new_usage" });
accounting.addBytes("d1", 3);
accounting.markEntryReady("d1");
await Promise.all([accounting.completeArchive(), accounting.failArchive()]);
expect(
repo.markCompleted.mock.calls.length +
repo.markInterrupted.mock.calls.length +
repo.failBeforeDelivery.mock.calls.length,
).toBe(1);
});
test("completes accounting only after the archive response is fully consumed", async () => {
const completeArchive = vi.fn().mockResolvedValue(undefined);
const failArchive = vi.fn().mockResolvedValue(undefined);
const stream = streamBulkArchiveWithAccounting(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([1, 2]));
controller.close();
},
}),
{ completeArchive, failArchive },
);
expect(completeArchive).not.toHaveBeenCalled();
await new Response(stream).arrayBuffer();
expect(completeArchive).toHaveBeenCalledOnce();
expect(failArchive).not.toHaveBeenCalled();
});
test("interrupts accounting when the client cancels the archive response", async () => {
const cancel = vi.fn().mockResolvedValue(undefined);
const completeArchive = vi.fn().mockResolvedValue(undefined);
const failArchive = vi.fn().mockResolvedValue(undefined);
const stream = streamBulkArchiveWithAccounting(
new ReadableStream({
pull(controller) {
controller.enqueue(new Uint8Array([1]));
},
cancel,
}),
{ completeArchive, failArchive },
);
const reader = stream.getReader();
await reader.read();
await reader.cancel("client aborted");
expect(cancel).toHaveBeenCalled();
expect(failArchive).toHaveBeenCalledOnce();
expect(completeArchive).not.toHaveBeenCalled();
});
+125
View File
@@ -0,0 +1,125 @@
import type { DownloadDeliveryRepository } from "./stream";
type BulkAccountingRepository = Pick<
DownloadDeliveryRepository,
"failBeforeDelivery" | "markCompleted" | "markInterrupted"
>;
type TrackedDownload = {
downloadId: string;
intentKind: "new_usage" | "repeat_download" | "legacy";
transferredBytes: number;
entryReady: boolean;
};
export function createBulkDeliveryAccounting(repository: BulkAccountingRepository) {
const tracked = new Map<string, TrackedDownload>();
let terminal: Promise<void> | undefined;
function track(input: Pick<TrackedDownload, "downloadId" | "intentKind">) {
if (tracked.has(input.downloadId)) {
throw new Error(`Download ${input.downloadId} is already tracked`);
}
tracked.set(input.downloadId, { ...input, transferredBytes: 0, entryReady: false });
}
function get(downloadId: string) {
const item = tracked.get(downloadId);
if (!item) throw new Error(`Download ${downloadId} is not tracked`);
return item;
}
function addBytes(downloadId: string, count: number) {
if (!Number.isSafeInteger(count) || count < 0) {
throw new Error("Transferred byte count must be a non-negative safe integer");
}
const item = get(downloadId);
item.transferredBytes += count;
if (!Number.isSafeInteger(item.transferredBytes)) {
throw new Error("Transferred byte count exceeds the supported range");
}
}
function markEntryReady(downloadId: string) {
get(downloadId).entryReady = true;
}
function settle(outcome: "completed" | "failed") {
terminal ??= Promise.all(
[...tracked.values()].map(async (item) => {
if (outcome === "completed" && item.entryReady) {
await repository.markCompleted(item.downloadId, item.transferredBytes);
return;
}
if (item.transferredBytes > 0) {
await repository.markInterrupted(item.downloadId, item.transferredBytes);
return;
}
await repository.failBeforeDelivery(item.downloadId, {
voidNewUsage: item.intentKind === "new_usage",
});
}),
).then(() => undefined);
return terminal;
}
return {
track,
addBytes,
markEntryReady,
completeArchive: () => settle("completed"),
failArchive: () => settle("failed"),
};
}
type BulkArchiveAccounting = {
completeArchive(): Promise<void>;
failArchive(): Promise<void>;
};
export function streamBulkArchiveWithAccounting(
upstream: ReadableStream<Uint8Array>,
accounting: BulkArchiveAccounting,
): ReadableStream<Uint8Array> {
const reader = upstream.getReader();
let stopped = false;
return new ReadableStream<Uint8Array>({
async pull(controller) {
if (stopped) return;
try {
const { done, value } = await reader.read();
if (done) {
stopped = true;
await accounting.completeArchive();
reader.releaseLock();
controller.close();
return;
}
controller.enqueue(value);
} catch (error) {
if (!stopped) {
stopped = true;
await accounting.failArchive().catch(() => undefined);
}
try {
reader.releaseLock();
} catch {
// A pending read can retain the lock while the stream is failing.
}
controller.error(error);
}
},
async cancel(reason) {
if (!stopped) {
stopped = true;
await Promise.allSettled([reader.cancel(reason), accounting.failArchive()]);
}
try {
reader.releaseLock();
} catch {
// Cancellation may race an active read.
}
},
});
}
@@ -0,0 +1,13 @@
import { expect, test } from "vitest";
import { billingReportMessage } from "./billing-report-message";
test("labels the attachment as a usage record and explicitly distinguishes it from the invoice", () => {
const message = billingReportMessage("Juli 2026");
expect(message.subject).toContain("Nutzungsnachweis");
expect(message.text).toMatch(/keine Rechnung/i);
expect(message.text).toMatch(/Rechnung.*separat/i);
expect(message.htmlContent).toMatch(/keine Rechnung/i);
expect(message.htmlContent).toMatch(/Rechnung.*separat/i);
});
@@ -0,0 +1,21 @@
export function billingReportMessage(reportMonth: string) {
return {
subject: `Ihr Nutzungsnachweis für ${reportMonth}`,
text: `Hallo,
anbei erhalten Sie den Nutzungsnachweis für ${reportMonth} als PDF-Dokument.
Wichtiger Hinweis: Dieses Dokument ist keine Rechnung. Die Rechnung erhalten Sie separat.
Viele Grüße,
Ihr Redaktions-Team`,
htmlContent: `Hallo,
anbei erhalten Sie den Nutzungsnachweis für ${reportMonth} als PDF-Dokument.
Wichtiger Hinweis: Dieses Dokument ist keine Rechnung. Die Rechnung erhalten Sie separat.
Viele Grüße,
Ihr Redaktions-Team`,
};
}
+6 -4
View File
@@ -1,6 +1,7 @@
import "server-only";
import nodemailer from "nodemailer";
import { env } from "@/config/env";
import { billingReportMessage } from "./billing-report-message";
const transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
@@ -74,14 +75,15 @@ function buildHtml(title: string, content: string, button?: { text: string, url:
export const emailService = {
async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) {
const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
const filename = "Nutzungsnachweis-" + invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
const message = billingReportMessage(reportMonth);
await transporter.sendMail({
from: env.SMTP_FROM,
to: toEmail,
subject: `Ihre Abrechnung für ${reportMonth}`,
text: `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat ${reportMonth} als PDF-Dokument.\n\nViele Grüße,\nIhr Redaktions-Team`,
html: buildHtml("Ihre Abrechnung ist da", `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat **${reportMonth}** bequem als PDF-Dokument angehängt.\n\nViele Grüße,\nIhr Redaktions-Team`),
subject: message.subject,
text: message.text,
html: buildHtml("Ihr Nutzungsnachweis", message.htmlContent),
attachments: [
{
filename,
+6 -4
View File
@@ -11,14 +11,15 @@ test("sends a verification link through the configured SMTP boundary", async ()
verificationUrl: "https://portal.example.com/api/auth/verify-email?token=secret-token",
});
expect(transport.sendMail).toHaveBeenCalledWith({
expect(transport.sendMail).toHaveBeenCalledWith(expect.objectContaining({
from: "portal@example.com",
to: "editorial@example.com",
subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse",
text: expect.stringContaining(
"https://portal.example.com/api/auth/verify-email?token=secret-token",
),
});
html: expect.stringContaining("Jetzt bestätigen"),
}));
});
test("sends an approval notice without leaking SMTP credentials", async () => {
@@ -27,10 +28,11 @@ test("sends an approval notice without leaking SMTP credentials", async () => {
await mailer.sendApprovalNotice({ to: "editorial@example.com", editorialName: "Neue Redaktion" });
expect(transport.sendMail).toHaveBeenCalledWith({
expect(transport.sendMail).toHaveBeenCalledWith(expect.objectContaining({
from: "portal@example.com",
to: "editorial@example.com",
subject: "Ihr Zugang zum Redaktionsportal ist freigegeben",
text: expect.stringContaining("Neue Redaktion"),
});
html: expect.stringContaining("Account freigegeben"),
}));
});
@@ -0,0 +1,42 @@
import { expect, test, vi } from "vitest";
import {
enforceRateLimit,
hashedRequestIdentity,
RateLimitExceededError,
} from "./rate-limit-guard";
test("uses a non-reversible bounded key for email and proxy identity", () => {
const key = hashedRequestIdentity(
"registration",
" Redaktion@Example.com ",
new Headers({ "x-real-ip": "203.0.113.4" }),
);
expect(key).toMatch(/^registration:[a-f0-9]{64}$/);
expect(key).not.toContain("redaktion@example.com");
expect(key).not.toContain("203.0.113.4");
});
test("uses the proxy-appended final X-Forwarded-For hop instead of a spoofed prefix", () => {
const fromRealIp = hashedRequestIdentity(
"registration",
"redaktion@example.com",
new Headers({ "x-real-ip": "203.0.113.4" }),
);
const fromZoraxy = hashedRequestIdentity(
"registration",
"redaktion@example.com",
new Headers({ "x-forwarded-for": "198.51.100.99, 203.0.113.4" }),
);
expect(fromZoraxy).toBe(fromRealIp);
});
test("throws a typed error with the retry interval when a policy is exhausted", async () => {
const consume = vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 47 });
await expect(
enforceRateLimit(consume, "download:editorial", { maxAttempts: 1, windowSeconds: 60 }),
).rejects.toEqual(new RateLimitExceededError(47));
});
+42
View File
@@ -0,0 +1,42 @@
import { createHash } from "node:crypto";
import { isIP } from "node:net";
import type { RateLimitPolicy, RateLimitResult } from "./rate-limit";
export type ConsumeRateLimit = (
key: string,
policy: RateLimitPolicy,
) => Promise<RateLimitResult>;
export class RateLimitExceededError extends Error {
readonly name = "RateLimitExceededError";
constructor(readonly retryAfterSeconds: number) {
super("Rate limit exceeded");
}
}
export async function enforceRateLimit(
consume: ConsumeRateLimit,
key: string,
policy: RateLimitPolicy,
) {
const result = await consume(key, policy);
if (!result.allowed) throw new RateLimitExceededError(result.retryAfterSeconds);
}
export function hashedRequestIdentity(scope: string, identity: string, headers: Headers) {
const normalizedIdentity = identity.trim().toLocaleLowerCase("en-US");
const address = safeProxyAddress(headers) ?? "unknown";
const digest = createHash("sha256")
.update(`${scope}\0${normalizedIdentity}\0${address}`, "utf8")
.digest("hex");
return `${scope}:${digest}`;
}
function safeProxyAddress(headers: Headers) {
const realIp = headers.get("x-real-ip")?.trim();
if (realIp && isIP(realIp)) return realIp;
const forwarded = headers.get("x-forwarded-for")?.split(",").at(-1)?.trim();
return forwarded && isIP(forwarded) ? forwarded : null;
}
+11 -5
View File
@@ -14,6 +14,7 @@ import {
usages,
} from "@/db/schema";
import type * as schema from "@/db/schema";
import { berlinMonthPeriodAt } from "@/modules/billing/period";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
import { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility";
@@ -141,6 +142,7 @@ export function createUsageServiceRepository(
status: editorialAccounts.status,
currentPriceCents: editorialAccounts.currentPriceCents,
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
@@ -174,13 +176,17 @@ export function createUsageServiceRepository(
let priceCents = editorial.currentPriceCents!;
if (editorial.flatrateActive) {
if (
!Number.isSafeInteger(editorial.flatratePriceCents) ||
(editorial.flatratePriceCents ?? 0) <= 0
) {
throw new UsageAccountingError("INVALID_PRICE");
}
if (editorial.flatrateAssetLimit === null) {
priceCents = 0; // Unlimited flatrate
} else {
// Limited flatrate - check how many usages this month
const now = new Date();
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999));
const period = berlinMonthPeriodAt(new Date());
const [{ count }] = await transaction
.select({ count: sql<number>`cast(count(*) as integer)` })
@@ -188,8 +194,8 @@ export function createUsageServiceRepository(
.where(
and(
eq(usages.editorialAccountId, input.editorialId),
sql`${usages.createdAt} >= ${startOfMonth}`,
sql`${usages.createdAt} <= ${endOfMonth}`,
sql`${usages.createdAt} >= ${period.fromUtc}`,
sql`${usages.createdAt} < ${period.toUtcExclusive}`,
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
// For flatrate, we only count usages that were originally free via the flatrate
// so we compare against priceCents = 0. Wait, any usage counts towards the limit?