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

+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?