Secure Sakani portal and show full album titles #1

Merged
leon merged 1 commits from codex/sakani-security into main 2026-11-30 19:18:12 +01:00
49 changed files with 1361 additions and 600 deletions
Showing only changes of commit 69264ce165 - Show all commits

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
**
!Dockerfile
!package.json
!pnpm-lock.yaml
!pnpm-workspace.yaml
!next.config.ts
!next-env.d.ts
!postcss.config.mjs
!tsconfig.json
!drizzle.config.ts
!src/
!src/**/*.ts
!src/**/*.tsx
!src/**/*.css
!src/modules/pdf/fonts/*.ttf
!src/modules/pdf/fonts/LICENSE.txt
!public/
!public/brand/
!public/brand/logo-black.png
!public/brand/logo-white.png
!drizzle/
!drizzle/0000_baseline.sql
!drizzle/0001_add_announcements.sql
!drizzle/meta/
!drizzle/meta/_journal.json
!scripts/
!scripts/backup-db.sh
!scripts/check-smtp.ts
!scripts/create-admin.ts
!scripts/preflight.ts
**/.*
**/.*/**
**/*.env
**/worktrees
**/worktrees/**
**/*credentials*
**/secrets
**/secrets.*
**/*.pem
**/*.key
**/*.p12
**/*.pfx
**/*.sql
!drizzle/0000_baseline.sql
!drizzle/0001_add_announcements.sql
**/*.dump
**/*.backup
**/*.bak
**/*.tar
**/*.gz
**/*.zip
**/*.sqlite*
**/backup
**/backups
+6 -2
View File
@@ -6,13 +6,17 @@ RUN corepack enable && corepack prepare pnpm@10.34.5 --activate
FROM base AS dependencies FROM base AS dependencies
WORKDIR /app WORKDIR /app
COPY package.json pnpm-lock.yaml ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
RUN pnpm install --frozen-lockfile RUN pnpm install --frozen-lockfile
FROM base AS builder FROM base AS builder
WORKDIR /app WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules COPY --from=dependencies /app/node_modules ./node_modules
COPY . . COPY package.json pnpm-lock.yaml pnpm-workspace.yaml next.config.ts next-env.d.ts tsconfig.json postcss.config.mjs drizzle.config.ts ./
COPY src ./src
COPY public ./public
COPY drizzle ./drizzle
COPY scripts ./scripts
# Set build-time dummy env vars required for static layout evaluation during next build # Set build-time dummy env vars required for static layout evaluation during next build
ENV NODE_ENV=production ENV NODE_ENV=production
+3 -4
View File
@@ -70,16 +70,15 @@ services:
- portal-internal - portal-internal
profiles: ["ops"] profiles: ["ops"]
# One-shot: seed the first admin. Override the command to pass credentials: # One-shot: create a new admin. See docs/operations.md for the stdin workflow.
# docker compose --profile ops run --rm seed \
# pnpm tsx scripts/create-admin.ts admin@example.de "Password!" "Name"
seed: seed:
build: build:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
target: builder target: builder
environment: *portal-env environment: *portal-env
command: ["pnpm", "tsx", "scripts/create-admin.ts"] entrypoint: ["node", "--conditions=react-server", "--import", "tsx", "scripts/create-admin.ts"]
command: []
depends_on: depends_on:
portal-db: portal-db:
condition: service_healthy condition: service_healthy
+12 -3
View File
@@ -92,11 +92,20 @@ the `ops` compose profile and do not start with `docker compose up`.
anymore. Historical (pre-squash) migration files live in anymore. Historical (pre-squash) migration files live in
`drizzle-history/pre-squash-2026-08/` and are referenced by integration tests `drizzle-history/pre-squash-2026-08/` and are referenced by integration tests
only; do not point `drizzle.config.ts` at that folder. only; do not point `drizzle.config.ts` at that folder.
- **Seed the first admin** (override the command to pass credentials): - **Seed a new admin** after migrations. In Bash, enter a unique password of
at least 12 characters at the hidden prompt. Compose forwards it on standard
input. The email and display name are the two arguments.
```bash ```bash
docker compose --profile ops run --rm seed \ (
pnpm tsx scripts/create-admin.ts admin@example.de "AdminPassword!" "Name" set +x
read -rs -p 'Admin password: ' seed_password || exit 1
printf '\n' >&2
printf '%s\n' "$seed_password" | docker compose --profile ops run --rm -i -T seed \
admin@example.de "Portal Admin"
)
``` ```
The seed creates a verified account. An existing email or a failed insert
exits with an error. After the first sign-in, complete the TOTP setup.
- **Smoke-test env + connectivity** (DB, Better Auth, SMTP, Immich): - **Smoke-test env + connectivity** (DB, Better Auth, SMTP, Immich):
```bash ```bash
docker compose --profile ops run --rm preflight docker compose --profile ops run --rm preflight
+2 -3
View File
@@ -16,9 +16,8 @@ const nextConfig: NextConfig = {
// ponytail: Next.js App Router injects inline scripts (RSC flight // ponytail: Next.js App Router injects inline scripts (RSC flight
// data + bootstrap) to hydrate client components. Without // data + bootstrap) to hydrate client components. Without
// 'unsafe-inline' or a nonce in script-src the browser blocks them, // 'unsafe-inline' or a nonce in script-src the browser blocks them,
// hydration never runs, and every client form (login, registration, // client forms cannot hydrate. 'unsafe-inline' for scripts is
// reset) falls back to a native GET submit. 'unsafe-inline' for // the pragmatic fix; upgrade path is per-request nonces
// scripts is the pragmatic fix; upgrade path is per-request nonces
// via middleware (Next attaches the nonce to its inline scripts). // via middleware (Next attaches the nonce to its inline scripts).
value: [ value: [
"default-src 'self'", "default-src 'self'",
+17 -37
View File
@@ -1,44 +1,24 @@
import { eq } from "drizzle-orm"; import { text } from "node:stream/consumers";
import { auth } from "../src/modules/auth/auth";
import { db } from "../src/db/client"; import { insertAdminCredential, seedAdmin } from "../src/modules/auth/admin-bootstrap";
import { users } from "../src/db/schema";
async function main() { async function main() {
const email = process.argv[2] || "mail@leon-tonhaeuser.de"; const [email, name, ...extra] = process.argv.slice(2);
const password = process.argv[3] || "AdminPassword123!"; if (!email || !name || extra.length > 0 || process.stdin.isTTY) {
const name = process.argv[4] || "Leon Tonhäuser"; throw new Error("Supply email and name as arguments and the password on stdin");
console.log(`Creating Admin user: ${email}...`);
try {
const res = await auth.api.signUpEmail({
body: {
email,
name,
password,
},
});
const userId = res.user.id;
await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, userId));
console.log(`Successfully created Admin account!`);
console.log(`Email: ${email}`);
console.log(`Password: ${password}`);
} catch (error) {
console.error("Error creating admin user:", error);
// If user already exists, update to admin
const [existing] = await db.select().from(users).where(eq(users.email, email));
if (existing) {
await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, existing.id));
console.log(`Updated existing user ${email} to ADMIN role.`);
}
} }
process.exit(0); const password = (await text(process.stdin)).replace(/\r?\n$/, "");
const { db, pool } = await import("../src/db/client");
try {
await seedAdmin({ email, name, password }, (credential) => insertAdminCredential(db, credential));
} finally {
await pool.end();
}
console.log("Admin account created.");
} }
main().catch((err) => { main().catch(() => {
console.error("Fatal error:", err); console.error("Admin seed failed. Check the input, database connectivity and whether the email is already registered.");
process.exit(1); process.exitCode = 1;
}); });
@@ -1,3 +1,4 @@
import { assertOriginalAccess } from "@/modules/albums/photo-access";
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream"; import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
@@ -10,6 +11,7 @@ type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string
type DownloadFileHandlerDependencies = { type DownloadFileHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial; requireActiveEditorial: typeof requireActiveEditorial;
repository: typeof downloadDeliveryRepository; repository: typeof downloadDeliveryRepository;
assertOriginalAccess: typeof assertOriginalAccess;
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> }; immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
}; };
@@ -35,6 +37,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
let original: ImmichBinary; let original: ImmichBinary;
try { try {
await dependencies.assertOriginalAccess(
principal.editorialId, claim.download.assetId, claim.download.albumId,
);
original = await dependencies.immich.getOriginal( original = await dependencies.immich.getOriginal(
claim.download.assetId, claim.download.assetId,
request.signal, request.signal,
@@ -163,5 +168,6 @@ function jsonError(status: number, code: string): Response {
export const authorizedDownloadFileHandler = createDownloadFileHandler({ export const authorizedDownloadFileHandler = createDownloadFileHandler({
requireActiveEditorial, requireActiveEditorial,
repository: downloadDeliveryRepository, repository: downloadDeliveryRepository,
assertOriginalAccess,
immich: immichClient, immich: immichClient,
}); });
@@ -5,6 +5,7 @@ import { contentDisposition, createDownloadFileHandler } from "./download-handle
const editorialId = "11111111-1111-4111-8111-111111111111"; const editorialId = "11111111-1111-4111-8111-111111111111";
const otherEditorialId = "22222222-2222-4222-8222-222222222222"; const otherEditorialId = "22222222-2222-4222-8222-222222222222";
const albumId = "66666666-6666-4666-8666-666666666666";
const downloadId = "33333333-3333-4333-8333-333333333333"; const downloadId = "33333333-3333-4333-8333-333333333333";
const usageId = "44444444-4444-4444-8444-444444444444"; const usageId = "44444444-4444-4444-8444-444444444444";
const assetId = "55555555-5555-4555-8555-555555555555"; const assetId = "55555555-5555-4555-8555-555555555555";
@@ -48,6 +49,7 @@ function dependencies(options: {
id: downloadId, id: downloadId,
usageId, usageId,
assetId, assetId,
albumId,
filename: "snapshot.jpg", filename: "snapshot.jpg",
intentKind: options.intentKind ?? "new_usage", intentKind: options.intentKind ?? "new_usage",
}, },
@@ -63,6 +65,7 @@ function dependencies(options: {
return { editorialId }; return { editorialId };
}), }),
repository, repository,
assertOriginalAccess: vi.fn().mockResolvedValue(undefined),
immich: { immich: {
getOriginal: vi.fn().mockImplementation(async () => { getOriginal: vi.fn().mockImplementation(async () => {
if (options.originalError) throw options.originalError; if (options.originalError) throw options.originalError;
@@ -226,3 +229,18 @@ test("returns stable authentication semantics without exposing guard details", a
expect(second.status).toBe(403); expect(second.status).toBe(403);
expect(await second.text()).not.toContain("SUSPENDED"); expect(await second.text()).not.toContain("SUSPENDED");
}); });
test.each(["new_usage", "repeat_download"] as const)(
"denies a previously authorized %s after album access is lost",
async (intentKind) => {
const deps = dependencies({ intentKind });
deps.assertOriginalAccess.mockRejectedValue(new Error("access lost"));
const response = await call(createDownloadFileHandler(deps));
expect(response.status).toBe(503);
expect(deps.assertOriginalAccess).toHaveBeenCalledWith(editorialId, assetId, albumId);
expect(deps.immich.getOriginal).not.toHaveBeenCalled();
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: intentKind === "new_usage",
});
},
);
@@ -1,6 +1,8 @@
import { PassThrough, type Readable as NodeReadable } from "node:stream"; import { PassThrough, type Readable as NodeReadable } from "node:stream";
import { expect, test, vi } from "vitest"; import { expect, test, vi } from "vitest";
import { UsageAccountingError } from "@/modules/usages/types";
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler"; import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
const editorialId = "11111111-1111-4111-8111-111111111111"; const editorialId = "11111111-1111-4111-8111-111111111111";
@@ -37,10 +39,9 @@ function fakeArchive(): BulkArchive {
function dependencies() { function dependencies() {
return { return {
assertOriginalAccess: vi.fn().mockResolvedValue(undefined),
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }), requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
getGrantedAlbumIds: vi.fn().mockResolvedValue([albumId]), findAttempt: vi.fn().mockResolvedValue(undefined),
searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: assetId }] }),
getAsset: vi.fn().mockResolvedValue({ id: assetId, originalFileName: "foto.jpg" }),
getOriginal: vi.fn().mockResolvedValue({ getOriginal: vi.fn().mockResolvedValue({
body: new ReadableStream({ body: new ReadableStream({
start(controller) { start(controller) {
@@ -62,6 +63,7 @@ function dependencies() {
id: downloadId, id: downloadId,
usageId: "55555555-5555-4555-8555-555555555555", usageId: "55555555-5555-4555-8555-555555555555",
assetId, assetId,
albumId,
filename: "foto.jpg", filename: "foto.jpg",
intentKind: "new_usage", intentKind: "new_usage",
}, },
@@ -75,11 +77,20 @@ function dependencies() {
}; };
} }
function request(origin = "http://portal.test", assetIds = [assetId]) { const usageId = "55555555-5555-4555-8555-555555555555";
function request(origin = "http://portal.test", assetIds = [assetId], repeatUsageId?: string) {
return new Request("http://portal.test/api/lightbox/bulk-download", { return new Request("http://portal.test/api/lightbox/bulk-download", {
method: "POST", method: "POST",
headers: { "content-type": "application/json", host: "portal.test", origin }, headers: { "content-type": "application/json", host: "portal.test", origin },
body: JSON.stringify({ assetIds, purpose: "Titelgeschichte" }), body: JSON.stringify({
items: assetIds.map((id) => ({
assetId: id,
idempotencyKey: id,
...(repeatUsageId ? { usageId: repeatUsageId } : { purpose: "Titelgeschichte", albumId }),
})),
maxPriceCents: 1500,
}),
}); });
} }
@@ -122,8 +133,6 @@ test("rate-limits bulk creation before usages are opened", async () => {
test("settles an already claimed first item when preparation of a later item fails", async () => { test("settles an already claimed first item when preparation of a later item fails", async () => {
const deps = dependencies(); const deps = dependencies();
deps.searchPhotos.mockResolvedValue({ items: [{ id: assetId }, { id: secondAssetId }] });
deps.getAsset.mockImplementation(async (id: string) => ({ id, originalFileName: `${id}.jpg` }));
deps.createNewUsage deps.createNewUsage
.mockResolvedValueOnce({ id: downloadId }) .mockResolvedValueOnce({ id: downloadId })
.mockRejectedValueOnce(new Error("accounting unavailable")); .mockRejectedValueOnce(new Error("accounting unavailable"));
@@ -137,3 +146,88 @@ test("settles an already claimed first item when preparation of a later item fai
voidNewUsage: true, voidNewUsage: true,
}); });
}); });
test("denies original bytes when a ZIP entry loses album access after preparation", async () => {
const deps = dependencies();
deps.assertOriginalAccess.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("grant revoked"));
const response = await createBulkDownloadHandler(deps)(request());
await expect(response.arrayBuffer()).rejects.toThrow();
expect(deps.assertOriginalAccess).toHaveBeenNthCalledWith(2, editorialId, assetId, albumId);
expect(deps.getOriginal).not.toHaveBeenCalled();
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
voidNewUsage: true,
});
});
test("books a new purpose when explicitly selected despite an eligible older usage", async () => {
const deps = dependencies();
deps.listPriorUsages.mockResolvedValue([{ id: usageId }]);
const response = await createBulkDownloadHandler(deps)(request());
await response.arrayBuffer();
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
expect(deps.createNewUsage).toHaveBeenCalledWith({
editorialId, assetId, albumId, purpose: "Titelgeschichte", maxPriceCents: 1500,
idempotencyKey: assetId,
});
});
test("uses a specifically selected previous usage for a free repeat", async () => {
const deps = dependencies();
deps.listPriorUsages.mockResolvedValue([{ id: "other-usage" }, { id: usageId }]);
deps.createRepeatDownload.mockResolvedValue({ id: downloadId });
const response = await createBulkDownloadHandler(deps)(request(undefined, undefined, usageId));
await response.arrayBuffer();
expect(deps.createNewUsage).not.toHaveBeenCalled();
expect(deps.createRepeatDownload).toHaveBeenCalledWith({ editorialId, usageId, idempotencyKey: assetId });
});
test("rejects a repeat that does not belong to the selected editorial and image", async () => {
const deps = dependencies();
deps.listPriorUsages.mockResolvedValue([{ id: "other-usage" }]);
const response = await createBulkDownloadHandler(deps)(request(undefined, undefined, usageId));
expect(response.status).toBe(404);
expect(deps.listPriorUsages).toHaveBeenCalledWith(editorialId, assetId);
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
expect(deps.getOriginal).not.toHaveBeenCalled();
});
test("rejects duplicate image selections before any bookings", async () => {
const deps = dependencies();
const response = await createBulkDownloadHandler(deps)(request(undefined, [assetId, assetId]));
expect(response.status).toBe(400);
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
test("retries a confirmed zero-byte void with a stable successor key", async () => {
const deps = dependencies();
deps.findAttempt.mockResolvedValueOnce({
id: downloadId, assetId, usageId, kind: "new_usage", purpose: "Titelgeschichte",
status: "failed_before_delivery", transferredBytes: 0, billingStatus: "voided",
});
const response = await createBulkDownloadHandler(deps)(request());
expect(response.status).toBe(200);
await response.arrayBuffer();
expect(deps.createNewUsage).toHaveBeenCalledWith(expect.objectContaining({ idempotencyKey: downloadId }));
expect(deps.findAttempt).toHaveBeenNthCalledWith(2, editorialId, downloadId);
});
test("keeps an interrupted delivery booked and does not retry it as a new usage", async () => {
const deps = dependencies();
deps.findAttempt.mockResolvedValueOnce({
id: downloadId, assetId, usageId, kind: "new_usage", purpose: "Titelgeschichte",
status: "interrupted", transferredBytes: 100, billingStatus: "open",
});
const response = await createBulkDownloadHandler(deps)(request());
expect(response.status).toBe(409);
expect(deps.createNewUsage).not.toHaveBeenCalled();
expect(deps.getOriginal).not.toHaveBeenCalled();
});
test("does not create a new booking for a ZIP album that is no longer granted", async () => {
const deps = dependencies();
deps.assertOriginalAccess.mockRejectedValue(new UsageAccountingError("ALBUM_NOT_GRANTED"));
const response = await createBulkDownloadHandler(deps)(request());
expect(response.status).toBe(404);
expect(deps.createNewUsage).not.toHaveBeenCalled();
expect(deps.getOriginal).not.toHaveBeenCalled();
});
+104 -141
View File
@@ -1,7 +1,9 @@
import { randomUUID } from "node:crypto";
import { basename } from "node:path"; import { basename } from "node:path";
import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream"; import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream";
import { z } from "zod";
import type { assertOriginalAccess } from "@/modules/albums/photo-access";
import { PrincipalAuthorizationError } from "@/modules/auth/principal"; import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { import {
createBulkDeliveryAccounting, createBulkDeliveryAccounting,
@@ -15,7 +17,11 @@ import {
RateLimitExceededError, RateLimitExceededError,
type ConsumeRateLimit, type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard"; } from "@/modules/security/rate-limit-guard";
import { UsageAccountingError } from "@/modules/usages/types"; import {
UsageAccountingError,
type CreateNewUsageInput,
type CreateRepeatDownloadInput,
} from "@/modules/usages/types";
export type BulkArchive = { export type BulkArchive = {
pipe(destination: PassThrough): unknown; pipe(destination: PassThrough): unknown;
@@ -24,41 +30,35 @@ export type BulkArchive = {
abort(): unknown; abort(): unknown;
}; };
type BulkAttempt = {
id: string;
assetId: string;
usageId: string;
kind: string;
purpose: string;
status: string;
transferredBytes: number | null;
billingStatus: string;
};
type BulkDownloadHandlerDependencies = { type BulkDownloadHandlerDependencies = {
findAttempt(editorialId: string, key: string): Promise<BulkAttempt | undefined>;
assertOriginalAccess: typeof assertOriginalAccess;
requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>; 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( getOriginal(
assetId: string, assetId: string,
signal?: AbortSignal, signal?: AbortSignal,
): Promise<{ body: ReadableStream<Uint8Array> }>; ): Promise<{ body: ReadableStream<Uint8Array> }>;
listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>; listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>;
createNewUsage(input: { createNewUsage(input: CreateNewUsageInput): Promise<{ id: string }>;
editorialId: string; createRepeatDownload(input: CreateRepeatDownloadInput): Promise<{ id: 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; repository: DownloadDeliveryRepository;
createArchive(): BulkArchive; createArchive(): BulkArchive;
consumeRateLimit: ConsumeRateLimit; consumeRateLimit: ConsumeRateLimit;
}; };
type PreparedDownload = { type PreparedDownload = {
albumId: string;
assetId: string; assetId: string;
downloadId: string; downloadId: string;
filename: string; filename: string;
@@ -75,37 +75,28 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
downloadIntentsPolicy, downloadIntentsPolicy,
); );
const payload = await parsePayload(request); const payload = await parsePayload(request);
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId); const items = [];
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds); for (const item of payload.items) {
const idempotencyKey = await resolveRetryKey(dependencies, principal.editorialId, item);
items.push({ ...item, idempotencyKey });
}
const accounting = createBulkDeliveryAccounting(dependencies.repository); const accounting = createBulkDeliveryAccounting(dependencies.repository);
let downloads: PreparedDownload[]; const downloads: PreparedDownload[] = [];
try { try {
downloads = await prepareDownloads( for (const item of items) {
dependencies, const intent = await createIntent(dependencies, principal.editorialId, item, payload.maxPriceCents);
principal.editorialId, const claim = await dependencies.repository.claimAuthorized(principal.editorialId, intent.id);
payload, if (claim.outcome !== "claimed") throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
assetToGrantedAlbum,
async (item) => { const { albumId, assetId, filename, intentKind } = claim.download;
const claim = await dependencies.repository.claimAuthorized( accounting.track({ downloadId: intent.id, intentKind });
principal.editorialId, downloads.push({ albumId, assetId, filename, downloadId: intent.id });
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) { } catch (error) {
await accounting.failArchive().catch(() => undefined); await accounting.failArchive().catch(() => undefined);
throw error; throw error;
} }
if (downloads.length === 0) return plainError(404, "No valid assets found for download");
const passThrough = new PassThrough(); const passThrough = new PassThrough();
const archive = dependencies.createArchive(); const archive = dependencies.createArchive();
archive.pipe(passThrough); archive.pipe(passThrough);
@@ -125,7 +116,10 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
passThrough, passThrough,
downloads, downloads,
requestSignal: request.signal, requestSignal: request.signal,
getOriginal: dependencies.getOriginal, async getOriginal(item, signal) {
await dependencies.assertOriginalAccess(principal.editorialId, item.assetId, item.albumId);
return dependencies.getOriginal(item.assetId, signal);
},
accounting, accounting,
}); });
@@ -143,7 +137,6 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
}, },
}); });
} catch (error) { } catch (error) {
console.error("[bulk-download] failed:", error);
return mappedBulkError(error); return mappedBulkError(error);
} }
}; };
@@ -161,13 +154,13 @@ async function produceArchive({
passThrough: PassThrough; passThrough: PassThrough;
downloads: PreparedDownload[]; downloads: PreparedDownload[];
requestSignal: AbortSignal; requestSignal: AbortSignal;
getOriginal: BulkDownloadHandlerDependencies["getOriginal"]; getOriginal(item: PreparedDownload, signal: AbortSignal): Promise<{ body: ReadableStream<Uint8Array> }>;
accounting: ReturnType<typeof createBulkDeliveryAccounting>; accounting: ReturnType<typeof createBulkDeliveryAccounting>;
}) { }) {
try { try {
for (const item of downloads) { for (const item of downloads) {
if (requestSignal.aborted) throw new Error("Archive request aborted"); if (requestSignal.aborted) throw new Error("Archive request aborted");
const original = await getOriginal(item.assetId, requestSignal); const original = await getOriginal(item, requestSignal);
const source = Readable.fromWeb( const source = Readable.fromWeb(
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>, original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
); );
@@ -192,99 +185,77 @@ async function produceArchive({
} }
} }
async function grantedAssetMap( const uuid = z.uuid().transform((value) => value.toLowerCase());
dependencies: BulkDownloadHandlerDependencies, const selectionFields = { assetId: uuid, idempotencyKey: uuid };
grantedAlbumIds: string[], const bulkPayload = z.strictObject({
) { items: z.array(z.union([
const result = new Map<string, string>(); z.strictObject({ ...selectionFields, usageId: uuid }),
const albums = await Promise.all( z.strictObject({
grantedAlbumIds.map(async (albumId) => { ...selectionFields,
try { albumId: uuid,
const page = await dependencies.searchPhotos({ purpose: z.string().trim().refine((value) => [...value].length >= 3 && [...value].length <= 200),
albumIds: [albumId],
type: "IMAGE",
page: 1,
size: 1_000,
withExif: false,
});
return { albumId, items: page.items };
} catch {
return { albumId, items: [] };
}
}), }),
); ])).min(1).max(100),
for (const album of albums) { maxPriceCents: z.number().int().nonnegative(),
for (const asset of album.items) { });
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
}
}
return result;
}
async function prepareDownloads( type Selection = z.output<typeof bulkPayload>["items"][number];
async function resolveRetryKey(
dependencies: BulkDownloadHandlerDependencies, dependencies: BulkDownloadHandlerDependencies,
editorialId: string, editorialId: string,
payload: { assetIds: string[]; purpose: string }, item: Selection,
assetToGrantedAlbum: Map<string, string>,
onPrepared: (item: PreparedDownload) => Promise<void>,
) { ) {
const assets = await Promise.all( let key = item.idempotencyKey;
payload.assetIds.map(async (assetId) => { for (let attempt = 0; attempt < 16; attempt += 1) {
try { const existing = await dependencies.findAttempt(editorialId, key);
return await dependencies.getAsset(assetId); if (!existing) return key;
} catch {
return null; const repeat = "usageId" in item;
} const sameSelection = existing.assetId === item.assetId && (repeat
}), ? existing.kind === "repeat_download" && existing.usageId === item.usageId
); : existing.kind === "new_usage" && existing.purpose === item.purpose);
const downloads: PreparedDownload[] = []; if (sameSelection && existing.status === "authorized") return key;
for (const asset of assets) {
if (!asset) continue; if (!sameSelection || existing.status !== "failed_before_delivery" ||
const albumId = assetToGrantedAlbum.get(asset.id); existing.transferredBytes !== 0 || (!repeat && existing.billingStatus !== "voided")) {
if (!albumId) continue; throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
const prior = await dependencies.listPriorUsages(editorialId, asset.id); }
const intent = prior[0] // Everyone retrying the same voided attempt converges on one new key.
? await dependencies.createRepeatDownload({ key = existing.id;
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; throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
async function createIntent(
dependencies: BulkDownloadHandlerDependencies,
editorialId: string,
item: Selection,
maxPriceCents: number,
) {
if ("usageId" in item) {
const prior = await dependencies.listPriorUsages(editorialId, item.assetId);
if (!prior.some(({ id }) => id === item.usageId)) throw new UsageAccountingError("USAGE_NOT_FOUND");
return dependencies.createRepeatDownload({
editorialId, usageId: item.usageId, idempotencyKey: item.idempotencyKey,
});
}
await dependencies.assertOriginalAccess(editorialId, item.assetId, item.albumId);
return dependencies.createNewUsage({ ...item, editorialId, maxPriceCents });
} }
async function parsePayload(request: Request) { async function parsePayload(request: Request) {
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown }; const parsed = bulkPayload.safeParse(await request.json().catch(() => null));
if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) { if (!parsed.success) throw new UsageAccountingError("INVALID_INPUT");
throw new BulkInputError(); const { items } = parsed.data;
if (new Set(items.map(({ assetId }) => assetId)).size !== items.length ||
new Set(items.map(({ idempotencyKey }) => idempotencyKey)).size !== items.length) {
throw new UsageAccountingError("INVALID_INPUT");
} }
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; return parsed.data;
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) { function safeArchiveFilename(value: string) {
const cleaned = basename(value) const cleaned = basename(value)
.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_") .replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_")
@@ -293,13 +264,6 @@ function safeArchiveFilename(value: string) {
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto"; 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 { function mappedBulkError(error: unknown): Response {
if (error instanceof RateLimitExceededError) { if (error instanceof RateLimitExceededError) {
return jsonError(429, "RATE_LIMITED", { return jsonError(429, "RATE_LIMITED", {
@@ -307,7 +271,6 @@ function mappedBulkError(error: unknown): Response {
}); });
} }
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST"); if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
if (error instanceof BulkInputError) return jsonError(400, "INVALID_INPUT");
if (error instanceof PrincipalAuthorizationError) { if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
} }
+23 -4
View File
@@ -1,4 +1,8 @@
import { albumGrantService } from "@/modules/albums/grants"; import { and, eq } from "drizzle-orm";
import { db } from "@/db/client";
import { downloadEvents, usages } from "@/db/schema";
import { assertOriginalAccess } from "@/modules/albums/photo-access";
import { requireActiveEditorial } from "@/modules/auth/principal"; import { requireActiveEditorial } from "@/modules/auth/principal";
import { createRepeatDownload } from "@/modules/downloads/service"; import { createRepeatDownload } from "@/modules/downloads/service";
import { downloadDeliveryRepository } from "@/modules/downloads/stream"; import { downloadDeliveryRepository } from "@/modules/downloads/stream";
@@ -12,9 +16,24 @@ const archiver = require("archiver") as { ZipArchive: new (options: unknown) =>
export const POST = createBulkDownloadHandler({ export const POST = createBulkDownloadHandler({
requireActiveEditorial, requireActiveEditorial,
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId), async findAttempt(editorialId, key) {
searchPhotos: (input) => immichClient.searchPhotos(input), const [attempt] = await db.select({
getAsset: (assetId) => immichClient.getAsset(assetId), id: downloadEvents.id,
assetId: downloadEvents.immichAssetId,
usageId: downloadEvents.usageId,
kind: downloadEvents.intentKind,
purpose: usages.purpose,
status: downloadEvents.status,
transferredBytes: downloadEvents.transferredBytes,
billingStatus: usages.billingStatus,
})
.from(downloadEvents)
.innerJoin(usages, and(eq(usages.id, downloadEvents.usageId), eq(usages.editorialAccountId, editorialId)))
.where(and(eq(downloadEvents.editorialAccountId, editorialId), eq(downloadEvents.idempotencyKey, key)))
.limit(1);
return attempt;
},
assertOriginalAccess,
getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal), getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal),
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId), listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
createNewUsage: (input) => usageService.createNewUsage(input), createNewUsage: (input) => usageService.createNewUsage(input),
+1 -2
View File
@@ -71,11 +71,10 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
{formatCount(result.page.total, "Foto")} gefunden {formatCount(result.page.total, "Foto")} gefunden
</p> </p>
<PhotoGallery <PhotoGallery
albumId={result.album.id}
albumName={result.album.albumName} albumName={result.album.albumName}
items={result.page.items} items={result.page.items}
downloadOptions={result.downloadOptions} downloadOptions={result.downloadOptions}
lightboxAssetIds={[...result.lightboxAssetIds]} lightboxAssetIds={result.page.items.filter(({ id }) => result.lightboxAssetIds.has(id)).map(({ id }) => id)}
/> />
<PhotoPagination <PhotoPagination
albumId={result.album.id} albumId={result.album.id}
+1 -1
View File
@@ -60,7 +60,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
albumName="Alle Alben" albumName="Alle Alben"
items={page.items} items={page.items}
downloadOptions={downloadOptions} downloadOptions={downloadOptions}
lightboxAssetIds={[...lightboxAssetIds]} lightboxAssetIds={page.items.filter(({ id }) => lightboxAssetIds.has(id)).map(({ id }) => id)}
showAlbumName showAlbumName
/> />
<GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} /> <GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} />
@@ -0,0 +1,55 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { DownloadLightboxForm } from "./DownloadLightboxForm";
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn() }) }));
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
test("confirms new and previous uses separately and preserves the keys after a failed request", async () => {
const fetch = vi.fn().mockRejectedValue(new Error("connection lost"));
vi.stubGlobal("fetch", fetch);
render(<DownloadLightboxForm
photos={[
{ assetId: "first", albumId: "allowed", filename: "first.jpg" },
{ assetId: "second", albumId: "allowed", filename: "second.jpg" },
]}
options={{
priceCents: 1500,
priorUsagesByAsset: {
second: [{ id: "prior", purpose: "Früherer Artikel", createdAt: "2026-11-01T12:00:00Z" }],
},
}}
/>);
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
expect((screen.getByRole("button", { name: "ZIP herunterladen" }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.change(screen.getByRole("combobox", { name: "first.jpg" }), { target: { value: "new" } });
fireEvent.change(screen.getByRole("combobox", { name: "second.jpg" }), { target: { value: "prior" } });
const submit = screen.getByRole<HTMLButtonElement>("button", { name: "Nutzungen bestätigen und laden" });
expect(submit.disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Gemeinsamer Zweck für neue Nutzungen"), {
target: { value: "Neuer Artikel" },
});
expect(screen.getByRole("status").textContent).toMatch(/1 neue Nutzung.*15,00/);
fireEvent.click(submit);
await waitFor(() => expect(submit.disabled).toBe(false));
fireEvent.click(submit);
await waitFor(() => expect(submit.disabled).toBe(false));
const payload = JSON.parse(fetch.mock.calls[0][1].body);
expect(payload).toEqual({
maxPriceCents: 1500,
items: [
{ assetId: "first", albumId: "allowed", purpose: "Neuer Artikel", idempotencyKey: expect.any(String) },
{ assetId: "second", usageId: "prior", idempotencyKey: expect.any(String) },
],
});
expect(JSON.parse(fetch.mock.calls[1][1].body)).toEqual(payload);
});
@@ -1,103 +1,189 @@
"use client"; "use client";
import { useState, useRef } from "react"; import { useRef, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Alert, Button, Input } from "@sakaniui/react"; import { Alert, Button, Input } from "@sakaniui/react";
import { IconDownload } from "@sakaniui/react/icons"; import { IconDownload } from "@sakaniui/react/icons";
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) { import { formatBerlinDate } from "@/modules/downloads/format";
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
type Photo = { assetId: string; albumId: string; filename: string };
type Choice = { selection: string; purpose?: string };
const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
export function DownloadLightboxForm({
photos,
options,
}: {
photos: Photo[];
options: EditorialDownloadOptions;
}) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const dialogRef = useRef<HTMLDialogElement>(null); const [choices, setChoices] = useState<Record<string, Choice>>({});
const [purpose, setPurpose] = useState(""); const [commonPurpose, setCommonPurpose] = useState("");
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const dialogRef = useRef<HTMLDialogElement>(null);
const inFlight = useRef(false);
const intentKeys = useRef(new Map<string, string>());
const router = useRouter(); const router = useRouter();
async function handleBulkDownload(e: React.FormEvent) { const selected = photos.filter(({ assetId }) => {
e.preventDefault(); const selection = choices[assetId]?.selection;
if (!purpose.trim() || assetIds.length === 0) return; return Boolean(selection && selection !== "skip");
});
const newPhotos = selected.filter(({ assetId }) => choices[assetId].selection === "new");
const price = priceFormatter.format(options.priceCents / 100);
const ready = selected.length > 0 && selected.length <= 100 &&
photos.every(({ assetId }) => currentSelection(assetId)) &&
newPhotos.every(({ assetId }) => [...purposeFor(choices[assetId])].length >= 3);
function currentSelection(assetId: string) {
const selection = choices[assetId]?.selection;
if (selection === "new" || selection === "skip") return selection;
return options.priorUsagesByAsset[assetId]?.find(({ id }) => id === selection)?.id ?? "";
}
function purposeFor(choice: Choice) {
return choice.purpose?.trim() || commonPurpose.trim();
}
async function handleBulkDownload(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!ready || inFlight.current) return;
inFlight.current = true;
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
const items = selected.map(({ assetId, albumId }) => {
const choice = choices[assetId];
const purpose = choice.selection === "new" ? purposeFor(choice) : undefined;
const key = JSON.stringify([assetId, choice.selection, purpose]);
let idempotencyKey = intentKeys.current.get(key);
if (!idempotencyKey) {
idempotencyKey = crypto.randomUUID();
intentKeys.current.set(key, idempotencyKey);
}
return purpose
? { assetId, albumId, purpose, idempotencyKey }
: { assetId, usageId: choice.selection, idempotencyKey };
});
const response = await fetch("/api/lightbox/bulk-download", { const response = await fetch("/api/lightbox/bulk-download", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ assetIds, purpose }), body: JSON.stringify({ items, maxPriceCents: options.priceCents }),
}); });
if (!response.ok) { if (!response.ok) {
// Surface the server's error code instead of a generic message so the const payload = await response.json().catch(() => null);
// real cause (e.g. IMMICH_UNAVAILABLE, REQUEST_FAILED) is visible in the if (payload?.code === "INVALID_PRICE") {
// browser console — the bulk handler maps UsageAccountingError to codes. router.refresh();
let code: string | undefined; throw new Error("Der Tarif hat sich geändert. Bitte prüfen Sie den aktualisierten Preis.");
try {
code = (await response.clone().json()).code;
} catch {
/* non-JSON body (e.g. plain 500) — code stays undefined */
} }
const status = response.status; if (payload?.code === "IDEMPOTENCY_CONFLICT") {
console.error("[bulk-download] server error:", { status, code }); router.refresh();
throw new Error(`Download fehlgeschlagen (${status}${code ? ` ${code}` : ""})`); throw new Error("Der Downloadversuch ist bereits erfasst. Prüfen Sie Ihre Nutzungen, bevor Sie einen neuen Zweck buchen.");
}
throw new Error("Bitte prüfen Sie die Auswahl und versuchen Sie es erneut.");
} }
// Download the ZIP file
const blob = await response.blob(); const blob = await response.blob();
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const a = document.createElement("a"); const link = document.createElement("a");
a.href = url; link.href = url;
a.download = `leuchtkasten-${new Date().toISOString().split("T")[0]}.zip`; link.download = "leuchtkasten.zip";
document.body.appendChild(a); link.click();
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
intentKeys.current.clear();
dialogRef.current?.close(); dialogRef.current?.close();
setPurpose(""); setChoices({});
router.refresh(); // Refresh to update usage history setCommonPurpose("");
} catch (err) { router.refresh();
const message = err instanceof Error ? err.message : "Download fehlgeschlagen"; } catch (error) {
setError(`Bulk-Download fehlgeschlagen: ${message}`); setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
console.error(err);
} finally { } finally {
inFlight.current = false;
setLoading(false); setLoading(false);
} }
} }
return ( return (
<> <>
<Button <Button leftIcon={<IconDownload size={16} />} onClick={() => dialogRef.current?.showModal()} type="button">
disabled={assetIds.length === 0} ZIP-Download vorbereiten
leftIcon={<IconDownload size={16} />}
onClick={() => dialogRef.current?.showModal()}
type="button"
>
Alle herunterladen
</Button> </Button>
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md"> <dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
<form className="flex flex-col gap-4 p-6" onSubmit={handleBulkDownload}> <form className="flex flex-col gap-4 p-6" method="post" onSubmit={handleBulkDownload}>
<h2 id="bulk-download-title" className="text-xl font-semibold">Verwendungszweck angeben</h2> <h2 id="bulk-download-title" className="text-xl font-semibold">Nutzungen für ZIP-Download</h2>
<p className="text-sm text-[var(--color-fg-muted)]">
Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen.
</p>
<Input <Input
disabled={loading} disabled={loading}
id="purpose" label="Gemeinsamer Zweck für neue Nutzungen"
label="Verwendungszweck" maxLength={200}
onChange={(e) => setPurpose(e.target.value)} onChange={(event) => setCommonPurpose(event.target.value)}
placeholder="z.B. Webseite, Social Media" value={commonPurpose}
required
type="text"
value={purpose}
/> />
{error ? <Alert color="danger" description={error} /> : null} <ul className="flex flex-col gap-4">
{photos.map(({ assetId, filename }) => {
const choice = choices[assetId];
return (
<li key={assetId} className="flex flex-col gap-2">
<label className="flex flex-col gap-1 text-sm font-medium">
{filename}
<select
className="rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-2 text-[var(--color-fg-default)]"
disabled={loading}
onChange={(event) => {
const selection = event.target.value;
setChoices((previous) => ({ ...previous, [assetId]: { selection } }));
}}
value={currentSelection(assetId)}
>
<option value="">Nutzung auswählen</option>
<option value="new">Neue Nutzung · bis {price} netto</option>
{(options.priorUsagesByAsset[assetId] ?? []).map((usage) => (
<option key={usage.id} value={usage.id}>
{usage.purpose} ({formatBerlinDate(new Date(usage.createdAt))}) · kostenlos wiederholen
</option>
))}
<option value="skip">Bild auslassen</option>
</select>
</label>
{choice?.selection === "new" && (
<Input
disabled={loading}
label={`Eigener Zweck für ${filename}`}
maxLength={200}
onChange={(event) => {
const purpose = event.target.value;
setChoices((previous) => ({ ...previous, [assetId]: { selection: "new", purpose } }));
}}
value={choice.purpose ?? ""}
/>
)}
</li>
);
})}
</ul>
{newPhotos.length > 0 && (
<p className="text-sm" role="status">
{newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} · bis{" "}
{priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto.
Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet.
</p>
)}
{selected.length > 100 && <Alert color="warning" description="Wählen Sie höchstens 100 Bilder pro ZIP aus." />}
{error && <Alert color="danger" description={error} />}
<div className="mt-4 flex justify-end gap-3"> <div className="mt-4 flex justify-end gap-3">
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost"> <Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
Abbrechen Abbrechen
</Button> </Button>
<Button disabled={loading || !purpose.trim()} type="submit"> <Button disabled={loading || !ready} type="submit">
{loading ? "Wird verpackt …" : "Download starten (ZIP)"} {loading ? "Wird verpackt …" : newPhotos.length ? "Nutzungen bestätigen und laden" : "ZIP herunterladen"}
</Button> </Button>
</div> </div>
</form> </form>
@@ -0,0 +1,79 @@
// @vitest-environment jsdom
import { render, screen, cleanup } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
const { lightboxService, findGrantedPhoto, assertOriginalAccess, getAsset, options, zipForm } = vi.hoisted(() => ({
lightboxService: {
getLightboxItems: vi.fn(),
addLightboxItem: vi.fn(),
removeLightboxItem: vi.fn(),
isAssetInLightbox: vi.fn(),
},
findGrantedPhoto: vi.fn(),
assertOriginalAccess: vi.fn(),
getAsset: vi.fn(),
options: vi.fn(),
zipForm: vi.fn(),
}));
const editorialId = "55555555-5555-4555-8555-555555555555";
const photoId = "22222222-2222-4222-8222-222222222222";
const revokedId = "33333333-3333-4333-8333-333333333333";
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
vi.mock("next/headers", () => ({ headers: () => new Headers() }));
vi.mock("../access", () => ({ requireEditorial: async () => ({ editorialId }) }));
vi.mock("@/modules/auth/principal", () => ({
requireActiveEditorial: async () => ({ editorialId }),
}));
vi.mock("@/modules/lightbox/service", () => ({ lightboxService }));
vi.mock("@/modules/albums/photo-access", () => ({ findGrantedPhoto, assertOriginalAccess }));
vi.mock("@/modules/immich/client", () => ({ immichClient: { getAsset } }));
vi.mock("@/modules/downloads/stream", () => ({
DOWNLOAD_OPTIONS_MAX_ASSETS: 60,
loadEditorialDownloadOptions: options,
}));
vi.mock("./DownloadLightboxForm", () => ({ DownloadLightboxForm: zipForm }));
import { toggleLightboxItem } from "./actions";
import LightboxPage from "./page";
afterEach(() => {
cleanup();
vi.resetAllMocks();
});
test("rejects a new bookmark without current access and can remove the old bookmark", async () => {
lightboxService.isAssetInLightbox.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
findGrantedPhoto.mockResolvedValue(null);
await expect(toggleLightboxItem(revokedId)).rejects.toThrow();
expect(lightboxService.addLightboxItem).not.toHaveBeenCalled();
await expect(toggleLightboxItem(revokedId)).resolves.toMatchObject({ isNowInLightbox: false });
expect(lightboxService.removeLightboxItem).toHaveBeenCalledWith(editorialId, revokedId);
expect(findGrantedPhoto).toHaveBeenCalledTimes(1);
});
test("shows a removable placeholder and excludes a revoked bookmark from ZIP options", async () => {
lightboxService.getLightboxItems.mockResolvedValue([{ assetId: photoId }, { assetId: revokedId }]);
findGrantedPhoto.mockResolvedValueOnce({ albumId: "allowed-album", filename: "allowed.jpg" })
.mockResolvedValueOnce(null);
getAsset.mockResolvedValue({
id: revokedId, originalFileName: "private.jpg", albums: [{ id: "private-album" }],
});
options.mockResolvedValue({ priceCents: 1500, priorUsagesByAsset: {} });
zipForm.mockReturnValue(null);
render(await LightboxPage());
expect(getAsset).not.toHaveBeenCalled();
expect(screen.queryByText("private.jpg")).toBeNull();
expect(screen.getByText("Foto derzeit nicht verfügbar")).toBeTruthy();
expect(screen.getAllByRole("button", { name: "Aus Merkzettel entfernen" })).toHaveLength(2);
expect(options).toHaveBeenCalledWith(editorialId, [photoId], expect.any(Function));
expect(zipForm.mock.calls[0][0].photos).toEqual([{ assetId: photoId, albumId: "allowed-album", filename: "allowed.jpg" }]);
const allowPrior = options.mock.calls[0][2];
assertOriginalAccess.mockRejectedValue(new Error("previous album revoked"));
await expect(allowPrior(photoId, "allowed-album")).resolves.toBe(true);
await expect(allowPrior(photoId, "revoked-album")).resolves.toBe(false);
});
+7 -1
View File
@@ -2,6 +2,8 @@
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { findGrantedPhoto } from "@/modules/albums/photo-access";
import { normalizeUuid } from "@/modules/usages/types";
import { requireActiveEditorial } from "@/modules/auth/principal"; import { requireActiveEditorial } from "@/modules/auth/principal";
import { lightboxService } from "@/modules/lightbox/service"; import { lightboxService } from "@/modules/lightbox/service";
@@ -12,7 +14,11 @@ export async function toggleLightboxItem(assetId: string) {
if (isInLightbox) { if (isInLightbox) {
await lightboxService.removeLightboxItem(principal.editorialId, assetId); await lightboxService.removeLightboxItem(principal.editorialId, assetId);
} else { } else {
await lightboxService.addLightboxItem(principal.editorialId, assetId); const normalizedAssetId = normalizeUuid(assetId);
if (!(await findGrantedPhoto(principal.editorialId, normalizedAssetId))) {
throw new Error("Foto nicht verfügbar");
}
await lightboxService.addLightboxItem(principal.editorialId, normalizedAssetId);
} }
// Revalidate routes where lightbox state is shown // Revalidate routes where lightbox state is shown
+43 -17
View File
@@ -3,7 +3,8 @@
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Card, EmptyState } from "@/components/ui/sakani"; import { Card, EmptyState } from "@/components/ui/sakani";
import { lightboxService } from "@/modules/lightbox/service"; import { lightboxService } from "@/modules/lightbox/service";
import { immichClient } from "@/modules/immich/client"; import { assertOriginalAccess, findGrantedPhoto } from "@/modules/albums/photo-access";
import { DOWNLOAD_OPTIONS_MAX_ASSETS, loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import Link from "next/link"; import Link from "next/link";
import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton"; import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton";
import { DownloadLightboxForm } from "./DownloadLightboxForm"; import { DownloadLightboxForm } from "./DownloadLightboxForm";
@@ -13,13 +14,34 @@ export default async function LightboxPage() {
const principal = await requireEditorial(); const principal = await requireEditorial();
const items = await lightboxService.getLightboxItems(principal.editorialId); const items = await lightboxService.getLightboxItems(principal.editorialId);
// Fetch asset details for all items in the lightbox const photos = new Map<string, NonNullable<Awaited<ReturnType<typeof findGrantedPhoto>>>>();
const assets = items.length > 0 const lookupDeadline = AbortSignal.timeout(15_000);
? await Promise.all(items.map(i => immichClient.getAsset(i.assetId).catch(() => null))) for (let start = 0; start < items.length && !lookupDeadline.aborted; start += 8) {
: []; await Promise.all(items.slice(start, start + 8).map(async ({ assetId }) => {
const photo = await findGrantedPhoto(principal.editorialId, assetId, lookupDeadline).catch(() => null);
if (photo) photos.set(assetId, photo);
}));
}
const validAssets = assets.filter((a): a is NonNullable<typeof a> => a !== null); const downloadable = items.flatMap(({ assetId }) => {
const assetMap = new Map(validAssets.map(a => [a.id, a])); const photo = photos.get(assetId);
return photo ? [{ assetId, ...photo }] : [];
});
let downloadOptions: Awaited<ReturnType<typeof loadEditorialDownloadOptions>> | undefined;
for (let start = 0; start < downloadable.length; start += DOWNLOAD_OPTIONS_MAX_ASSETS) {
const batch = downloadable.slice(start, start + DOWNLOAD_OPTIONS_MAX_ASSETS);
const options = await loadEditorialDownloadOptions(
principal.editorialId,
batch.map(({ assetId }) => assetId),
async (assetId, albumId) => {
if (photos.get(assetId)?.albumId === albumId) return true;
if (lookupDeadline.aborted) return false;
return assertOriginalAccess(principal.editorialId, assetId, albumId).then(() => true, () => false);
},
);
downloadOptions ??= options;
Object.assign(downloadOptions.priorUsagesByAsset, options.priorUsagesByAsset);
}
return ( return (
<section className="flex flex-col gap-6"> <section className="flex flex-col gap-6">
@@ -37,33 +59,37 @@ export default async function LightboxPage() {
<p className="text-sm font-medium text-[var(--color-fg-muted)]"> <p className="text-sm font-medium text-[var(--color-fg-muted)]">
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt {items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
</p> </p>
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} /> {downloadOptions && <DownloadLightboxForm photos={downloadable} options={downloadOptions} />}
</div> </div>
</Card> </Card>
<ul className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4"> <ul className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
{items.map((item) => { {items.map((item) => {
const asset = assetMap.get(item.assetId); const photo = photos.get(item.assetId);
if (!asset) return null; if (!photo) {
const albumId = asset.albums?.[0]?.id; return (
const href = albumId <li key={item.assetId} className="flex items-center justify-between gap-2 rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] p-3">
? `/redaktion/alben/${encodeURIComponent(albumId)}?suche=${encodeURIComponent(asset.originalFileName)}` <span className="text-sm text-[var(--color-fg-muted)]">Foto derzeit nicht verfügbar</span>
: '#'; <RemoveLightboxItemButton assetId={item.assetId} />
</li>
);
}
const href = `/redaktion/alben/${encodeURIComponent(photo.albumId)}?suche=${encodeURIComponent(photo.filename)}`;
return ( return (
<li key={item.assetId} className="group relative overflow-hidden rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] transition-shadow hover:shadow-[var(--shadow-md)]"> <li key={item.assetId} className="group relative overflow-hidden rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] transition-shadow hover:shadow-[var(--shadow-md)]">
<Link href={href} className="block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"> <Link href={href} className="block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]">
<div className="aspect-[3/2] w-full overflow-hidden bg-[var(--color-bg-subtle)]"> <div className="aspect-[3/2] w-full overflow-hidden bg-[var(--color-bg-subtle)]">
<img <img
alt={asset.originalFileName ?? "Bild"} alt={photo.filename}
className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105" className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105"
loading="lazy" loading="lazy"
src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`} src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`}
/> />
</div> </div>
<div className="border-t border-[var(--color-border-subtle)] p-3"> <div className="border-t border-[var(--color-border-subtle)] p-3">
<span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={asset.originalFileName}> <span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={photo.filename}>
{asset.originalFileName ?? "Unbekannt"} {photo.filename}
</span> </span>
</div> </div>
</Link> </Link>
+9 -10
View File
@@ -46,8 +46,8 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
setError(undefined); setError(undefined);
try { try {
const formData = new FormData(event.currentTarget); const input = event.currentTarget.querySelector<HTMLInputElement>("#mfa-code");
const code = String(formData.get("code") ?? "").replace(/\s+/g, ""); const code = input?.value.replace(/\s+/g, "") ?? "";
const result = await authClient.twoFactor.verifyTotp({ code }); const result = await authClient.twoFactor.verifyTotp({ code });
if (result.error) { if (result.error) {
setError("Der Code ist ungültig. Bitte prüfen Sie Ihre Authenticator-App."); setError("Der Code ist ungültig. Bitte prüfen Sie Ihre Authenticator-App.");
@@ -86,12 +86,12 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
return ( return (
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-6">
{!enabled && step === "password" && ( {!enabled && step === "password" && (
<form onSubmit={startSetup} className="flex flex-col items-start gap-4"> <form method="post" onSubmit={startSetup} className="flex flex-col items-start gap-4">
<div className="w-full"> <div className="w-full">
<Input <Input
autoComplete="current-password" autoComplete="current-password"
label="Passwort bestätigen, um die Einrichtung zu starten" label="Passwort bestätigen, um die Einrichtung zu starten"
name="password" id="mfa-password"
required required
type="password" type="password"
/> />
@@ -132,14 +132,14 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
</div> </div>
)} )}
<form onSubmit={confirmCode} className="flex flex-col items-start gap-4"> <form method="post" onSubmit={confirmCode} className="flex flex-col items-start gap-4">
<div className="w-48"> <div className="w-48">
<Input <Input
autoComplete="one-time-code" autoComplete="one-time-code"
inputMode="numeric" inputMode="numeric"
label="Code aus der App" label="Code aus der App"
maxLength={6} maxLength={6}
name="code" id="mfa-code"
pattern="[0-9]*" pattern="[0-9]*"
required required
type="text" type="text"
@@ -165,13 +165,13 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
)} )}
{enabled && step !== "done" && ( {enabled && step !== "done" && (
<form onSubmit={disable} className="flex flex-col items-start gap-4 border-t border-[var(--color-border-subtle)] pt-6"> <form method="post" onSubmit={disable} className="flex flex-col items-start gap-4 border-t border-[var(--color-border-subtle)] pt-6">
<p className="text-sm text-[var(--color-fg-muted)]"> <p className="text-sm text-[var(--color-fg-muted)]">
Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die
Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind. Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind.
</p> </p>
<div className="w-full"> <div className="w-full">
<Input aria-label="Passwort" autoComplete="current-password" name="password" placeholder="Passwort" required type="password" /> <Input aria-label="Passwort" autoComplete="current-password" id="mfa-password" placeholder="Passwort" required type="password" />
</div> </div>
<Button variant="outline" disabled={pending} type="submit"> <Button variant="outline" disabled={pending} type="submit">
{pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"} {pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"}
@@ -185,8 +185,7 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
} }
function readPassword(form: HTMLFormElement): string { function readPassword(form: HTMLFormElement): string {
const value = new FormData(form).get("password"); return form.querySelector<HTMLInputElement>("#mfa-password")?.value ?? "";
return typeof value === "string" ? value : "";
} }
function twoFactorErrorMessage(code: string | undefined): string { function twoFactorErrorMessage(code: string | undefined): string {
+20
View File
@@ -12,6 +12,7 @@ vi.mock("next/navigation", () => ({
vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "light", setTheme: vi.fn() }) })); vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "light", setTheme: vi.fn() }) }));
vi.mock("@/modules/auth/client", () => ({ authClient: { signOut: vi.fn() } })); vi.mock("@/modules/auth/client", () => ({ authClient: { signOut: vi.fn() } }));
import { authClient } from "@/modules/auth/client";
import { AppShell } from "./app-shell"; import { AppShell } from "./app-shell";
import { RELEASE } from "./release-notes"; import { RELEASE } from "./release-notes";
@@ -74,3 +75,22 @@ test("release notes pop up once per version and reopen from the sidebar", async
fireEvent.click(screen.getByRole("button", { name: new RegExp(`Was ist neu · v${RELEASE.version}`) })); fireEvent.click(screen.getByRole("button", { name: new RegExp(`Was ist neu · v${RELEASE.version}`) }));
expect(await screen.findByRole("dialog", { name: "Was ist neu?" })).toBeTruthy(); expect(await screen.findByRole("dialog", { name: "Was ist neu?" })).toBeTruthy();
}); });
test.each(["rejected", "error response"])("failed sign-out (%s) stays on the page and can be retried", async (kind) => {
const signOut = vi.mocked(authClient.signOut);
const error = { error: { status: 503, statusText: "Unavailable" }, data: null };
signOut.mockReset();
if (kind === "rejected") signOut.mockRejectedValueOnce(new Error("network failure"));
else signOut.mockResolvedValueOnce(error);
signOut.mockResolvedValueOnce(error);
render(<AppShell area="redaktion" legal={legal}>Inhalt</AppShell>);
fireEvent.click(screen.getByRole("button", { name: "Abmelden" }));
expect((await screen.findByRole("alert")).textContent).toMatch(/fehlgeschlagen/i);
expect(screen.getByText("Inhalt")).toBeTruthy();
const retry = screen.getByRole("button", { name: "Abmelden" });
expect((retry as HTMLButtonElement).disabled).toBe(false);
fireEvent.click(retry);
expect(signOut).toHaveBeenCalledTimes(2);
await screen.findByRole("alert");
});
+16 -3
View File
@@ -63,6 +63,7 @@ export function AppShell({
const { resolvedTheme, setTheme } = useTheme(); const { resolvedTheme, setTheme } = useTheme();
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [signingOut, setSigningOut] = useState(false); const [signingOut, setSigningOut] = useState(false);
const [signOutFailed, setSignOutFailed] = useState(false);
const [notesOpen, setNotesOpen] = useState(false); const [notesOpen, setNotesOpen] = useState(false);
const active = NAV.filter(({ href }) => pathname === href || pathname.startsWith(`${href}/`)) const active = NAV.filter(({ href }) => pathname === href || pathname.startsWith(`${href}/`))
@@ -91,11 +92,18 @@ export function AppShell({
async function signOut() { async function signOut() {
setSigningOut(true); setSigningOut(true);
setSignOutFailed(false);
try { try {
await authClient.signOut(); const result = await authClient.signOut();
} finally { if (result.data?.success === true && !result.error) {
window.location.replace("/anmelden"); window.location.replace("/anmelden");
return;
}
} catch {
// A failed request leaves the session status unconfirmed.
} }
setSignOutFailed(true);
setSigningOut(false);
} }
return ( return (
@@ -146,6 +154,11 @@ export function AppShell({
<Button variant="ghost" size="sm" leftIcon={<IconLogout size={16} />} loading={signingOut} onClick={signOut}> <Button variant="ghost" size="sm" leftIcon={<IconLogout size={16} />} loading={signingOut} onClick={signOut}>
Abmelden Abmelden
</Button> </Button>
{signOutFailed && (
<p className="px-3 text-sm text-[var(--color-danger-fg)]" role="alert">
Abmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.
</p>
)}
</div> </div>
</Sidebar> </Sidebar>
</div> </div>
+12 -16
View File
@@ -33,12 +33,12 @@ test("renders granted albums as labelled contact-sheet links", () => {
const photo = { const photo = {
id: "asset-1", id: "asset-1",
type: "IMAGE" as const, filename: "tor-des-sieges.jpg",
originalFileName: "tor-des-sieges.jpg", takenAt: "2026-08-08T18:42:00.000Z",
originalMimeType: "image/jpeg", width: null,
localDateTime: "2026-08-08T18:42:00.000Z", height: null,
fileCreatedAt: null, albumId: "heimspiel",
albums: [{ id: "heimspiel" }], albumName: "Heimspiel gegen Nord",
}; };
test("renders the gallery list labelled by album name", () => { test("renders the gallery list labelled by album name", () => {
@@ -52,7 +52,6 @@ test("renders the gallery list labelled by album name", () => {
test("renders the server-scoped download choices for a catalog photo", () => { test("renders the server-scoped download choices for a catalog photo", () => {
render( render(
<PhotoGallery <PhotoGallery
albumId="33333333-3333-4333-8333-333333333333"
albumName="Heimspiel gegen Nord" albumName="Heimspiel gegen Nord"
downloadOptions={{ downloadOptions={{
priceCents: 1_500, priceCents: 1_500,
@@ -68,13 +67,10 @@ test("renders the server-scoped download choices for a catalog photo", () => {
}} }}
items={[ items={[
{ {
...photo,
id: "22222222-2222-4222-8222-222222222222", id: "22222222-2222-4222-8222-222222222222",
type: "IMAGE", filename: "tor.jpg",
originalFileName: "tor.jpg", albumId: "33333333-3333-4333-8333-333333333333",
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "33333333-3333-4333-8333-333333333333" }],
}, },
]} ]}
/>, />,
@@ -91,7 +87,7 @@ test("offers the existing download workflow on a global search result and its li
items={[{ items={[{
...photo, ...photo,
id: "22222222-2222-4222-8222-222222222222", id: "22222222-2222-4222-8222-222222222222",
albums: [{ id: "33333333-3333-4333-8333-333333333333" }], albumId: "33333333-3333-4333-8333-333333333333",
}]} }]}
showAlbumName showAlbumName
/>, />,
@@ -107,8 +103,8 @@ test("opens a full-screen lightbox when a photo tile is clicked", () => {
<PhotoGallery <PhotoGallery
albumName="Heimspiel gegen Nord" albumName="Heimspiel gegen Nord"
items={[ items={[
{ ...photo, id: "a", originalFileName: "first.jpg" }, { ...photo, id: "a", filename: "first.jpg" },
{ ...photo, id: "b", originalFileName: "second.jpg" }, { ...photo, id: "b", filename: "second.jpg" },
]} ]}
/>, />,
); );
+3 -3
View File
@@ -11,7 +11,7 @@ import type { VisibleAlbum } from "./catalog";
export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) { export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) {
return ( return (
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-label="Freigegebene Fotoalben"> <ul className="grid auto-rows-fr grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-label="Freigegebene Fotoalben">
{albums.map((album) => ( {albums.map((album) => (
<li key={album.id}> <li key={album.id}>
<Link <Link
@@ -37,7 +37,7 @@ export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[]
</div> </div>
)} )}
<figcaption className="flex items-baseline justify-between gap-3"> <figcaption className="flex items-baseline justify-between gap-3">
<span className="truncate text-base font-medium text-[var(--color-fg-default)]">{album.albumName}</span> <span className="min-w-0 wrap-anywhere text-base font-medium text-[var(--color-fg-default)]">{album.albumName}</span>
<span className="shrink-0 text-sm tabular-nums text-[var(--color-fg-muted)]">{formatCount(album.assetCount, "Foto")}</span> <span className="shrink-0 text-sm tabular-nums text-[var(--color-fg-muted)]">{formatCount(album.assetCount, "Foto")}</span>
</figcaption> </figcaption>
</figure> </figure>
@@ -62,7 +62,7 @@ export function PhotoPagination({
}: Readonly<{ }: Readonly<{
albumId: string; albumId: string;
currentPage: number; currentPage: number;
page: ImmichSearchPage; page: Pick<ImmichSearchPage, "nextPage" | "previousPage">;
query: string; query: string;
format?: string; format?: string;
jahr?: string; jahr?: string;
+13 -6
View File
@@ -81,10 +81,10 @@ test("restores the queried granted album when Immich omits an asset album associ
const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 }); const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 });
expect(result.items[0]?.albums).toEqual([{ id: "allowed" }]); expect(result.items[0]?.albumId).toBe("allowed");
}); });
test("moves the queried granted album to the active gallery context without losing metadata", async () => { test("projects only display fields and the queried granted album for the client gallery", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] }); const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
immich.searchPhotos.mockResolvedValue({ immich.searchPhotos.mockResolvedValue({
items: [{ items: [{
@@ -94,6 +94,8 @@ test("moves the queried granted album to the active gallery context without losi
originalMimeType: "image/jpeg", originalMimeType: "image/jpeg",
localDateTime: null, localDateTime: null,
fileCreatedAt: null, fileCreatedAt: null,
originalPath: "/private/photos/tor.jpg",
exifInfo: { exifImageWidth: 1200, exifImageHeight: 800, latitude: 12 },
albums: [ albums: [
{ id: "other", albumName: "Anderes Album" }, { id: "other", albumName: "Anderes Album" },
{ id: "allowed", albumName: "Erlaubtes Album" }, { id: "allowed", albumName: "Erlaubtes Album" },
@@ -106,10 +108,15 @@ test("moves the queried granted album to the active gallery context without losi
const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 }); const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 });
expect(result.items[0]?.albums).toEqual([ expect(result.items).toEqual([{
{ id: "allowed", albumName: "Erlaubtes Album" }, id: "asset-1",
{ id: "other", albumName: "Anderes Album" }, filename: "tor.jpg",
]); takenAt: null,
width: 1200,
height: 800,
albumId: "allowed",
albumName: "Heimspiel gegen Nord",
}]);
}); });
test("global search keeps hits when a granted album is no longer visible in Immich", async () => { test("global search keeps hits when a granted album is no longer visible in Immich", async () => {
+29 -17
View File
@@ -16,6 +16,18 @@ const MAX_DESCRIPTION_LENGTH = 200;
export type VisibleAlbum = ImmichAlbumSummary; export type VisibleAlbum = ImmichAlbumSummary;
export type GalleryPhoto = {
id: string;
filename: string;
takenAt: string | null;
width: number | null;
height: number | null;
albumId: string;
albumName: string | null;
};
type GalleryPage = Omit<ImmichSearchPage, "items"> & { items: GalleryPhoto[] };
export type SearchVisiblePhotosInput = { export type SearchVisiblePhotosInput = {
requestedAlbumId?: string; requestedAlbumId?: string;
description?: unknown; description?: unknown;
@@ -54,7 +66,7 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
async searchVisiblePhotos( async searchVisiblePhotos(
editorialId: string, editorialId: string,
input: SearchVisiblePhotosInput, input: SearchVisiblePhotosInput,
): Promise<ImmichSearchPage> { ): Promise<GalleryPage> {
const description = normalizeDescription(input.description); const description = normalizeDescription(input.description);
if (description) { if (description) {
try { try {
@@ -91,10 +103,10 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
// grant count and narrowed by the description filter, so per-album results // grant count and narrowed by the description filter, so per-album results
// are small. If a huge-grant editorial makes this slow, cap the fan-out // are small. If a huge-grant editorial makes this slow, cap the fan-out
// and accept partial coverage. // and accept partial coverage.
const visibleIds = new Set((await loadAlbums(immich)).map(({ id }) => id)); const visibleAlbums = new Map((await loadAlbums(immich)).map(({ id, albumName }) => [id, albumName]));
const pages = await Promise.all( const pages = await Promise.all(
grantedAlbumIds.filter((id) => visibleIds.has(id)) grantedAlbumIds.filter((id) => visibleAlbums.has(id))
.map((albumId) => searchAlbum(immich, [albumId], description, page, size)), .map((albumId) => searchAlbum(immich, [albumId], description, page, size, visibleAlbums.get(albumId))),
); );
return mergeSearchPages(pages); return mergeSearchPages(pages);
}, },
@@ -107,7 +119,8 @@ async function searchAlbum(
description: string | undefined, description: string | undefined,
page: number, page: number,
size: number, size: number,
): Promise<ImmichSearchPage> { albumName: string | null = null,
): Promise<GalleryPage> {
try { try {
const searchPage = await immich.searchPhotos({ const searchPage = await immich.searchPhotos({
albumIds, albumIds,
@@ -116,25 +129,24 @@ async function searchAlbum(
page, page,
size, size,
}); });
const queriedAlbumId = albumIds[0];
return { return {
...searchPage, ...searchPage,
items: queriedAlbumId items: searchPage.items.map((asset) => ({
? searchPage.items.map((asset) => { id: asset.id,
const queriedAlbum = asset.albums.find(({ id }) => id === queriedAlbumId) ?? { id: queriedAlbumId }; filename: asset.originalFileName,
return { takenAt: asset.localDateTime ?? asset.fileCreatedAt,
...asset, width: asset.exifInfo?.exifImageWidth ?? null,
albums: [queriedAlbum, ...asset.albums.filter(({ id }) => id !== queriedAlbumId)], height: asset.exifInfo?.exifImageHeight ?? null,
}; albumId: albumIds[0],
}) albumName,
: searchPage.items, })),
}; };
} catch { } catch {
throw new AlbumCatalogError("IMMICH_UNAVAILABLE"); throw new AlbumCatalogError("IMMICH_UNAVAILABLE");
} }
} }
function mergeSearchPages(pages: ImmichSearchPage[]): ImmichSearchPage { function mergeSearchPages(pages: GalleryPage[]): GalleryPage {
// nextPage/previousPage are unused by callers — they paginate in-app via // nextPage/previousPage are unused by callers — they paginate in-app via
// paginatePhotos, which recomputes both from the merged item count. // paginatePhotos, which recomputes both from the merged item count.
return { return {
@@ -145,7 +157,7 @@ function mergeSearchPages(pages: ImmichSearchPage[]): ImmichSearchPage {
}; };
} }
function emptySearchPage(): ImmichSearchPage { function emptySearchPage(): GalleryPage {
return { items: [], total: 0, nextPage: null, previousPage: null }; return { items: [], total: 0, nextPage: null, previousPage: null };
} }
+21 -22
View File
@@ -1,25 +1,24 @@
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { filterPhotos, matchesOrientation, matchesYear, paginatePhotos } from "./filter"; import { filterPhotos, matchesOrientation, matchesYear, paginatePhotos } from "./filter";
import type { ImmichAsset } from "@/modules/immich/types"; import type { GalleryPhoto } from "./catalog";
function photo(overrides: Partial<ImmichAsset> & { id: string }): ImmichAsset { function photo(overrides: Partial<GalleryPhoto> & { id: string }): GalleryPhoto {
return { return {
id: overrides.id, filename: `${overrides.id}.jpg`,
type: "IMAGE", takenAt: null,
originalFileName: overrides.originalFileName ?? `${overrides.id}.jpg`, width: null,
originalMimeType: "image/jpeg", height: null,
localDateTime: overrides.localDateTime ?? null, albumId: "album",
fileCreatedAt: overrides.fileCreatedAt ?? null, albumName: null,
albums: overrides.albums ?? [], ...overrides,
exifInfo: overrides.exifInfo ?? null,
}; };
} }
test("matchesOrientation distinguishes landscape from portrait via EXIF dimensions", () => { test("matchesOrientation distinguishes landscape from portrait via EXIF dimensions", () => {
const landscape = photo({ id: "l", exifInfo: { exifImageWidth: 1600, exifImageHeight: 900 } }); const landscape = photo({ id: "l", width: 1600, height: 900 });
const portrait = photo({ id: "p", exifInfo: { exifImageWidth: 900, exifImageHeight: 1600 } }); const portrait = photo({ id: "p", width: 900, height: 1600 });
const square = photo({ id: "s", exifInfo: { exifImageWidth: 1000, exifImageHeight: 1000 } }); const square = photo({ id: "s", width: 1000, height: 1000 });
expect(matchesOrientation(landscape, "quer")).toBe(true); expect(matchesOrientation(landscape, "quer")).toBe(true);
expect(matchesOrientation(landscape, "hoch")).toBe(false); expect(matchesOrientation(landscape, "hoch")).toBe(false);
@@ -30,23 +29,23 @@ test("matchesOrientation distinguishes landscape from portrait via EXIF dimensio
}); });
test("matchesOrientation excludes assets with unknown dimensions instead of matching either format", () => { test("matchesOrientation excludes assets with unknown dimensions instead of matching either format", () => {
const unknown = photo({ id: "u", exifInfo: null }); const unknown = photo({ id: "u" });
expect(matchesOrientation(unknown, "quer")).toBe(false); expect(matchesOrientation(unknown, "quer")).toBe(false);
expect(matchesOrientation(unknown, "hoch")).toBe(false); expect(matchesOrientation(unknown, "hoch")).toBe(false);
}); });
test("matchesYear compares against localDateTime then fileCreatedAt", () => { test("matchesYear compares against the gallery date", () => {
expect(matchesYear(photo({ id: "a", localDateTime: "2026-05-01T10:00:00.000Z" }), "2026")).toBe(true); expect(matchesYear(photo({ id: "a", takenAt: "2026-05-01T10:00:00.000Z" }), "2026")).toBe(true);
expect(matchesYear(photo({ id: "b", localDateTime: "2025-12-31T23:00:00.000Z" }), "2026")).toBe(false); expect(matchesYear(photo({ id: "b", takenAt: "2025-12-31T23:00:00.000Z" }), "2026")).toBe(false);
expect(matchesYear(photo({ id: "c", localDateTime: null, fileCreatedAt: "2026-01-01T00:00:00.000Z" }), "2026")).toBe(true); expect(matchesYear(photo({ id: "c", takenAt: "2026-01-01T00:00:00.000Z" }), "2026")).toBe(true);
expect(matchesYear(photo({ id: "d", localDateTime: null, fileCreatedAt: null }), "2026")).toBe(false); expect(matchesYear(photo({ id: "d", takenAt: null }), "2026")).toBe(false);
}); });
test("filterPhotos applies format and jahr together across the full set", () => { test("filterPhotos applies format and jahr together across the full set", () => {
const items = [ const items = [
photo({ id: "l26", originalFileName: "land26", localDateTime: "2026-03-01", exifInfo: { exifImageWidth: 2, exifImageHeight: 1 } }), photo({ id: "l26", filename: "land26", takenAt: "2026-03-01", width: 2, height: 1 }),
photo({ id: "p26", originalFileName: "port26", localDateTime: "2026-03-01", exifInfo: { exifImageWidth: 1, exifImageHeight: 2 } }), photo({ id: "p26", filename: "port26", takenAt: "2026-03-01", width: 1, height: 2 }),
photo({ id: "l25", originalFileName: "land25", localDateTime: "2025-03-01", exifInfo: { exifImageWidth: 2, exifImageHeight: 1 } }), photo({ id: "l25", filename: "land25", takenAt: "2025-03-01", width: 2, height: 1 }),
]; ];
expect(filterPhotos(items, { format: "quer" }).map((p) => p.id)).toEqual(["l26", "l25"]); expect(filterPhotos(items, { format: "quer" }).map((p) => p.id)).toEqual(["l26", "l25"]);
+11 -14
View File
@@ -1,6 +1,4 @@
import type { ImmichAsset } from "@/modules/immich/types"; import { normalizePage, type GalleryPhoto } from "./catalog";
import { normalizePage } from "./catalog";
/** /**
* Filter + paginate a photo set in-app, used by the album detail and the * Filter + paginate a photo set in-app, used by the album detail and the
@@ -12,26 +10,25 @@ import { normalizePage } from "./catalog";
* page silently dropped matching photos and reported the unfiltered total. * page silently dropped matching photos and reported the unfiltered total.
*/ */
export function matchesOrientation(asset: ImmichAsset, format: string): boolean { export function matchesOrientation(asset: GalleryPhoto, format: string): boolean {
const width = asset.exifInfo?.exifImageWidth ?? 0; const width = asset.width ?? 0;
const height = asset.exifInfo?.exifImageHeight ?? 0; const height = asset.height ?? 0;
// Unknown dimensions can't satisfy a format filter — exclude rather than // Unknown dimensions can't satisfy a format filter — exclude rather than
// show a portrait under "Querformat" (the original bug). `withExif: true` // show a portrait under "Querformat".
// keeps this rare in practice.
if (width <= 0 || height <= 0) return false; if (width <= 0 || height <= 0) return false;
const isLandscape = width >= height; const isLandscape = width >= height;
return format === "quer" ? isLandscape : !isLandscape; return format === "quer" ? isLandscape : !isLandscape;
} }
export function matchesYear(asset: ImmichAsset, jahr: string): boolean { export function matchesYear(asset: GalleryPhoto, jahr: string): boolean {
const value = asset.localDateTime ?? asset.fileCreatedAt; const value = asset.takenAt;
return value !== null && value.startsWith(jahr); return value !== null && value.startsWith(jahr);
} }
export function filterPhotos( export function filterPhotos(
items: ImmichAsset[], items: GalleryPhoto[],
filters: { format?: string; jahr?: string }, filters: { format?: string; jahr?: string },
): ImmichAsset[] { ): GalleryPhoto[] {
let filtered = items; let filtered = items;
if (filters.format) { if (filters.format) {
filtered = filtered.filter((asset) => matchesOrientation(asset, filters.format!)); filtered = filtered.filter((asset) => matchesOrientation(asset, filters.format!));
@@ -43,14 +40,14 @@ export function filterPhotos(
} }
export type InAppPage = { export type InAppPage = {
items: ImmichAsset[]; items: GalleryPhoto[];
total: number; total: number;
nextPage: number | null; nextPage: number | null;
previousPage: number | null; previousPage: number | null;
}; };
export function paginatePhotos( export function paginatePhotos(
items: ImmichAsset[], items: GalleryPhoto[],
page: unknown, page: unknown,
pageSize: number, pageSize: number,
): { result: InAppPage; currentPage: number } { ): { result: InAppPage; currentPage: number } {
+57
View File
@@ -0,0 +1,57 @@
import { drizzle } from "drizzle-orm/node-postgres";
import type { Pool } from "pg";
import { expect, test, vi } from "vitest";
import * as schema from "@/db/schema";
import { assertOriginalAccess } from "./photo-access";
const editorialId = "11111111-1111-4111-8111-111111111111";
const assetId = "22222222-2222-4222-8222-222222222222";
const albumId = "33333333-3333-4333-8333-333333333333";
function dependencies() {
const query = vi.fn().mockResolvedValue({ rows: [[albumId]] });
const database = drizzle({ client: { query } as unknown as Pool, schema });
const searchPhotos = vi.fn().mockResolvedValue({ items: [{ id: assetId }] });
return {
query,
searchPhotos,
check: () => assertOriginalAccess(editorialId, assetId, albumId, database, { searchPhotos }),
};
}
test("checks active editorial and exact grant both before and after checking photo membership", async () => {
const { check, query, searchPhotos } = dependencies();
await expect(check()).resolves.toBeUndefined();
expect(query).toHaveBeenCalledTimes(2);
const [statement, values] = query.mock.calls[0];
expect(statement.text).toContain('"editorial_accounts"."status"');
expect(statement.text).toContain('"album_grants"."revoked_at" is null');
expect(values).toEqual([editorialId, "active", albumId]);
expect(searchPhotos).toHaveBeenCalledWith(
{ albumIds: [albumId], id: assetId, type: "IMAGE", withExif: false, page: 1, size: 1 },
undefined,
);
});
test("does not load photo metadata from an already revoked album", async () => {
const { check, query, searchPhotos } = dependencies();
query.mockResolvedValueOnce({ rows: [] });
await expect(check()).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" });
expect(searchPhotos).not.toHaveBeenCalled();
});
test("fails closed if the grant is revoked while looking up membership", async () => {
const { check, query } = dependencies();
query.mockResolvedValueOnce({ rows: [[albumId]] }).mockResolvedValueOnce({ rows: [] });
await expect(check()).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" });
});
test("rejects when membership cannot be verified", async () => {
const { check, searchPhotos } = dependencies();
searchPhotos.mockResolvedValueOnce({ items: [{ id: "another-photo" }] });
await expect(check()).rejects.toMatchObject({ code: "ASSET_NOT_IN_ALBUM" });
searchPhotos.mockRejectedValueOnce(new Error("upstream unavailable"));
await expect(check()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" });
});
+94
View File
@@ -0,0 +1,94 @@
import "server-only";
import { and, eq, isNull, sql } from "drizzle-orm";
import { db } from "@/db/client";
import { albumGrants, editorialAccounts } from "@/db/schema";
import { immichClient } from "@/modules/immich/client";
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types";
type PhotoSearch<Asset extends { id: string } = { id: string }> = {
searchPhotos(input: {
albumIds: string[];
id: string;
type: "IMAGE";
withExif: false;
page: number;
size: number;
}, signal?: AbortSignal): Promise<{ items: Asset[] }>;
};
export async function isAssetInAlbum(immich: PhotoSearch, assetId: string, albumId: string) {
return Boolean(await findPhotoInAlbum(immich, assetId, albumId));
}
async function findPhotoInAlbum<Asset extends { id: string }>(
immich: PhotoSearch<Asset>, assetId: string, albumId: string, signal?: AbortSignal,
) {
try {
const result = await immich.searchPhotos({
albumIds: [albumId],
id: assetId,
type: "IMAGE",
withExif: false,
page: 1,
size: 1,
}, signal);
return result.items.find((asset) => asset.id === assetId);
} catch {
throw new UsageAccountingError("IMMICH_UNAVAILABLE");
}
}
export async function assertOriginalAccess(
editorialId: string,
assetId: string,
albumId: string,
database = db,
immich: PhotoSearch = immichClient,
) {
if ((await activeAlbumIds(editorialId, database, albumId)).length === 0) {
throw new UsageAccountingError("ALBUM_NOT_GRANTED");
}
if (!(await isAssetInAlbum(immich, assetId, albumId))) {
throw new UsageAccountingError("ASSET_NOT_IN_ALBUM");
}
if ((await activeAlbumIds(editorialId, database, albumId)).length === 0) {
throw new UsageAccountingError("ALBUM_NOT_GRANTED");
}
}
async function activeAlbumIds(editorialId: string, database: typeof db, albumId?: string) {
const grants = await database
.select({ albumId: albumGrants.immichAlbumId })
.from(albumGrants)
.innerJoin(editorialAccounts, eq(editorialAccounts.id, albumGrants.editorialAccountId))
.where(and(
eq(editorialAccounts.id, editorialId),
eq(editorialAccounts.status, "active"),
albumId === undefined ? undefined : sql`lower(${albumGrants.immichAlbumId}) = ${albumId.toLowerCase()}`,
isNull(albumGrants.revokedAt),
));
return [...new Set(grants.map((grant) => grant.albumId.toLowerCase()))];
}
export async function findGrantedPhoto(
editorialId: string, assetId: string, signal = AbortSignal.timeout(15_000),
) {
signal.throwIfAborted();
const normalizedAssetId = normalizeUuid(assetId);
const granted = await activeAlbumIds(editorialId, db);
let unavailable = false;
for (const albumId of granted) {
signal.throwIfAborted();
const asset = await findPhotoInAlbum(immichClient, normalizedAssetId, albumId, signal).catch(() => {
unavailable = true;
return undefined;
});
if (asset && (await activeAlbumIds(editorialId, db, albumId)).length > 0) {
return { albumId, filename: asset.originalFileName };
}
}
if (unavailable) throw new UsageAccountingError("IMMICH_UNAVAILABLE");
return null;
}
+22 -38
View File
@@ -9,14 +9,13 @@ import { IconChevronLeft, IconChevronRight, IconX } from "@sakaniui/react/icons"
import { UsageDialog } from "@/components/download/usage-dialog"; import { UsageDialog } from "@/components/download/usage-dialog";
import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton"; import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton";
import type { EditorialDownloadOptions } from "@/modules/downloads/stream"; import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
import type { ImmichAsset } from "@/modules/immich/types"; import type { GalleryPhoto } from "./catalog";
import { formatDate, thumbnailUrl } from "./catalog-content"; import { formatDate, thumbnailUrl } from "./catalog-content";
type PhotoGalleryProps = Readonly<{ type PhotoGalleryProps = Readonly<{
albumId?: string;
albumName: string; albumName: string;
items: ImmichAsset[]; items: GalleryPhoto[];
downloadOptions?: EditorialDownloadOptions; downloadOptions?: EditorialDownloadOptions;
/** Pre-selected asset ids, passed as a plain array (Sets don't cross the RSC boundary). */ /** Pre-selected asset ids, passed as a plain array (Sets don't cross the RSC boundary). */
lightboxAssetIds?: string[]; lightboxAssetIds?: string[];
@@ -24,7 +23,6 @@ type PhotoGalleryProps = Readonly<{
}>; }>;
export function PhotoGallery({ export function PhotoGallery({
albumId,
albumName, albumName,
items, items,
downloadOptions, downloadOptions,
@@ -70,18 +68,17 @@ export function PhotoGallery({
<> <>
<ul className="photo-gallery" aria-label={`Fotos aus ${albumName}`}> <ul className="photo-gallery" aria-label={`Fotos aus ${albumName}`}>
{items.map((asset, index) => { {items.map((asset, index) => {
const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined);
return ( return (
<li key={asset.id} className="photo-tile"> <li key={`${asset.albumId}:${asset.id}`} className="photo-tile">
<figure className="photo-tile-frame"> <figure className="photo-tile-frame">
<button <button
className="photo-tile-trigger" className="photo-tile-trigger"
type="button" type="button"
onClick={() => setOpenIndex(index)} onClick={() => setOpenIndex(index)}
aria-label={`${asset.originalFileName} vergrößern`} aria-label={`${asset.filename} vergrößern`}
> >
<img <img
alt={asset.originalFileName} alt={asset.filename}
className="photo-tile-image" className="photo-tile-image"
loading="lazy" loading="lazy"
src={thumbnailUrl(asset.id)} src={thumbnailUrl(asset.id)}
@@ -90,17 +87,17 @@ export function PhotoGallery({
</button> </button>
<div className="photo-tile-overlay"> <div className="photo-tile-overlay">
<figcaption className="photo-tile-caption"> <figcaption className="photo-tile-caption">
<span className="photo-tile-name">{asset.originalFileName}</span> <span className="photo-tile-name">{asset.filename}</span>
{showAlbumName ? renderAlbumName(asset) : null} {showAlbumName && asset.albumName ? <span className="photo-tile-album">{asset.albumName}</span> : null}
<span className="photo-tile-date">{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span> <span className="photo-tile-date">{formatDate(asset.takenAt)}</span>
</figcaption> </figcaption>
<div className="photo-tile-actions"> <div className="photo-tile-actions">
<LightboxToggleButton assetId={asset.id} initialInLightbox={inLightbox.has(asset.id)} /> <LightboxToggleButton assetId={asset.id} initialInLightbox={inLightbox.has(asset.id)} />
{activeAlbumId && downloadOptions ? ( {downloadOptions ? (
<UsageDialog <UsageDialog
albumId={activeAlbumId} albumId={asset.albumId}
assetId={asset.id} assetId={asset.id}
filename={asset.originalFileName} filename={asset.filename}
newUsagePriceCents={downloadOptions.priceCents} newUsagePriceCents={downloadOptions.priceCents}
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []} priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
/> />
@@ -116,7 +113,6 @@ export function PhotoGallery({
{openIndex !== null ? ( {openIndex !== null ? (
<PhotoLightbox <PhotoLightbox
asset={items[openIndex]} asset={items[openIndex]}
albumId={albumId}
downloadOptions={downloadOptions} downloadOptions={downloadOptions}
inLightbox={inLightbox.has(items[openIndex].id)} inLightbox={inLightbox.has(items[openIndex].id)}
hasPrev={openIndex > 0} hasPrev={openIndex > 0}
@@ -131,8 +127,7 @@ export function PhotoGallery({
} }
type PhotoLightboxProps = Readonly<{ type PhotoLightboxProps = Readonly<{
asset: ImmichAsset; asset: GalleryPhoto;
albumId?: string;
downloadOptions?: EditorialDownloadOptions; downloadOptions?: EditorialDownloadOptions;
inLightbox: boolean; inLightbox: boolean;
hasPrev: boolean; hasPrev: boolean;
@@ -144,7 +139,6 @@ type PhotoLightboxProps = Readonly<{
function PhotoLightbox({ function PhotoLightbox({
asset, asset,
albumId,
downloadOptions, downloadOptions,
inLightbox, inLightbox,
hasPrev, hasPrev,
@@ -153,9 +147,8 @@ function PhotoLightbox({
onPrev, onPrev,
onNext, onNext,
}: PhotoLightboxProps) { }: PhotoLightboxProps) {
const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined);
return ( return (
<div className="photo-lightbox" role="dialog" aria-modal="true" aria-label={asset.originalFileName}> <div className="photo-lightbox" role="dialog" aria-modal="true" aria-label={asset.filename}>
<IconButton className="lightbox-close" icon={IconX} variant="secondary" onClick={onClose} aria-label="Schließen" /> <IconButton className="lightbox-close" icon={IconX} variant="secondary" onClick={onClose} aria-label="Schließen" />
{hasPrev ? ( {hasPrev ? (
<IconButton className="lightbox-nav lightbox-prev" icon={IconChevronLeft} variant="secondary" size="lg" onClick={onPrev} aria-label="Vorheriges Bild" /> <IconButton className="lightbox-nav lightbox-prev" icon={IconChevronLeft} variant="secondary" size="lg" onClick={onPrev} aria-label="Vorheriges Bild" />
@@ -164,19 +157,19 @@ function PhotoLightbox({
<IconButton className="lightbox-nav lightbox-next" icon={IconChevronRight} variant="secondary" size="lg" onClick={onNext} aria-label="Nächstes Bild" /> <IconButton className="lightbox-nav lightbox-next" icon={IconChevronRight} variant="secondary" size="lg" onClick={onNext} aria-label="Nächstes Bild" />
) : null} ) : null}
<figure className="lightbox-figure"> <figure className="lightbox-figure">
<img alt={asset.originalFileName} className="lightbox-image" src={thumbnailUrl(asset.id)} /> <img alt={asset.filename} className="lightbox-image" src={thumbnailUrl(asset.id)} />
<figcaption className="lightbox-caption"> <figcaption className="lightbox-caption">
<span className="photo-tile-name">{asset.originalFileName}</span> <span className="photo-tile-name">{asset.filename}</span>
<span className="photo-tile-date">{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span> <span className="photo-tile-date">{formatDate(asset.takenAt)}</span>
</figcaption> </figcaption>
</figure> </figure>
<div className="lightbox-actions"> <div className="lightbox-actions">
<LightboxToggleButton assetId={asset.id} initialInLightbox={inLightbox} /> <LightboxToggleButton assetId={asset.id} initialInLightbox={inLightbox} />
{activeAlbumId && downloadOptions ? ( {downloadOptions ? (
<UsageDialog <UsageDialog
albumId={activeAlbumId} albumId={asset.albumId}
assetId={asset.id} assetId={asset.id}
filename={asset.originalFileName} filename={asset.filename}
newUsagePriceCents={downloadOptions.priceCents} newUsagePriceCents={downloadOptions.priceCents}
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []} priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
/> />
@@ -186,17 +179,8 @@ function PhotoLightbox({
); );
} }
function aspectStyle(asset: ImmichAsset): CSSProperties { function aspectStyle(asset: GalleryPhoto): CSSProperties {
const width = asset.exifInfo?.exifImageWidth ?? 0; const width = asset.width ?? 0;
const height = asset.exifInfo?.exifImageHeight ?? 0; const height = asset.height ?? 0;
return width > 0 && height > 0 ? { aspectRatio: `${width} / ${height}` } : {}; return width > 0 && height > 0 ? { aspectRatio: `${width} / ${height}` } : {};
} }
// `ImmichAsset.albums` is typed as `{ id }[]` but the `/search/metadata`
// response (parsed with `.passthrough()`) also carries `albumName`, which the
// cross-album search view surfaces. Read it via an unknown cast so the typed
// contract stays honest while still rendering the field when Immich sends it.
function renderAlbumName(asset: ImmichAsset) {
const first = (asset as unknown as { albums?: Array<{ albumName?: string }> }).albums?.[0];
return first?.albumName ? <span className="photo-tile-album">{first.albumName}</span> : null;
}
+27
View File
@@ -0,0 +1,27 @@
import { verifyPassword } from "better-auth/crypto";
import { expect, test, vi } from "vitest";
import { seedAdmin } from "./admin-bootstrap";
const input = { email: " Admin@example.test ", name: " Portal Admin ", password: "test seed password" };
test.each(["email", "name", "password"] as const)("rejects a missing %s before writing", async (field) => {
const insert = vi.fn();
await expect(seedAdmin({ ...input, [field]: "" }, insert)).rejects.toThrow();
expect(insert).not.toHaveBeenCalled();
});
test("passes only a compatible credential hash to the atomic insert", async () => {
const insert = vi.fn<(input: { email: string; name: string; passwordHash: string }) => Promise<void>>();
await seedAdmin(input, insert);
const [created] = insert.mock.calls[0];
expect(created).toMatchObject({ email: "admin@example.test", name: "Portal Admin" });
expect(created.passwordHash).not.toContain(input.password);
await expect(verifyPassword({ hash: created.passwordHash, password: input.password })).resolves.toBe(true);
});
test.each(["duplicate account", "database unavailable"])("propagates a failed insert (%s)", async (message) => {
const insert = vi.fn().mockRejectedValue(new Error(message));
await expect(seedAdmin(input, insert)).rejects.toThrow(message);
expect(insert).toHaveBeenCalledTimes(1);
});
+38 -69
View File
@@ -1,80 +1,49 @@
import "server-only"; import "server-only";
import { eq, sql } from "drizzle-orm"; import { hashPassword } from "better-auth/crypto";
import { sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { z } from "zod";
import { users } from "@/db/schema"; import { accounts, users } from "@/db/schema";
import type * as schema from "@/db/schema"; import type * as schema from "@/db/schema";
import { validatePasswordPolicy } from "@/modules/security/password-policy";
export type AdminBootstrapInput = { type AdminInput = { email: string; name: string; password: string };
email: string; type AdminCredential = Omit<AdminInput, "password"> & { passwordHash: string };
name: string;
password: string;
};
export type AdminBootstrapAuth = { export async function seedAdmin(
signUpEmail(input: { email: string; name: string; password: string }): Promise<{ user: { id: string } }>; input: AdminInput,
sendVerificationEmail(input: { email: string }): Promise<void>; insert: (credential: AdminCredential) => Promise<void>,
}; ) {
const email = input.email.trim().toLowerCase();
const name = input.name.trim();
if (!z.email().safeParse(email).success || !name ||
input.password.length > 128 || !validatePasswordPolicy(input.password).ok) {
throw new Error("Invalid admin seed input");
}
export type AdminBootstrapRepository = { await insert({ email, name, passwordHash: await hashPassword(input.password) });
countAdmins(): Promise<number>;
findUserByEmail(email: string): Promise<{ id: string } | undefined>;
promoteUserToAdmin(userId: string): Promise<void>;
};
export function createAdminBootstrapService({
auth,
repo,
}: {
auth: AdminBootstrapAuth;
repo: AdminBootstrapRepository;
}) {
return {
async bootstrap(input: AdminBootstrapInput): Promise<{ status: "created" | "already_configured" }> {
if ((await repo.countAdmins()) > 0) {
return { status: "already_configured" };
}
const email = input.email.trim().toLowerCase();
const existingUser = await repo.findUserByEmail(email);
const user =
existingUser ??
(await auth.signUpEmail({
email,
name: input.name.trim(),
password: input.password,
})).user;
await repo.promoteUserToAdmin(user.id);
await auth.sendVerificationEmail({ email });
return { status: "created" };
},
};
} }
export function createAdminBootstrapRepository(database: NodePgDatabase<typeof schema>): AdminBootstrapRepository { export function insertAdminCredential(database: NodePgDatabase<typeof schema>, credential: AdminCredential) {
return { return database.transaction(async (transaction) => {
async countAdmins() { const [existing] = await transaction.select({ id: users.id })
const [result] = await database .from(users)
.select({ count: sql<number>`count(*)::int` }) .where(sql`lower(${users.email}) = ${credential.email}`)
.from(users) .limit(1);
.where(eq(users.role, "ADMIN")); if (existing) throw new Error("Admin seed email is already registered");
return result.count;
}, const [user] = await transaction
async findUserByEmail(email) { .insert(users)
const [user] = await database .values({ email: credential.email, name: credential.name, role: "ADMIN", emailVerified: true })
.select({ id: users.id }) .returning({ id: users.id });
.from(users)
.where(eq(users.email, email)) await transaction.insert(accounts).values({
.limit(1); userId: user.id,
return user; accountId: user.id,
}, providerId: "credential",
async promoteUserToAdmin(userId) { password: credential.passwordHash,
await database });
.update(users) });
.set({ role: "ADMIN", updatedAt: new Date() })
.where(eq(users.id, userId));
},
};
} }
+82
View File
@@ -121,3 +121,85 @@ test("keeps Better Auth login limits separate for clients forwarded by Zoraxy",
expect(otherClient.status).not.toBe(429); expect(otherClient.status).not.toBe(429);
}); });
test("Better Auth grants admin access only to the session that completed MFA", async () => {
const password = "dummy-admin-password";
const email = "mfa-admin@example.test";
const userId = crypto.randomUUID();
const { hashPassword, symmetricDecrypt } = await import("better-auth/crypto");
const { createPrincipalGuard } = await import("./principal");
const state = {
user: [{ id: userId, email, name: "Test Admin", role: "ADMIN" as const, emailVerified: true,
twoFactorEnabled: false, createdAt: new Date(), updatedAt: new Date() }],
account: [{ id: crypto.randomUUID(), userId, providerId: "credential", accountId: userId,
password: await hashPassword(password), createdAt: new Date(), updatedAt: new Date() }],
session: [],
verification: [],
twoFactor: [] as Array<{ secret: string }>,
};
const { auth } = createPortalAuth({
database: memoryAdapter(state),
mailerService: { sendPasswordReset: vi.fn(), sendVerification: vi.fn() },
registrationRepository: {
createEditorial: vi.fn(), markPendingApproval: vi.fn(), removeUnverifiedAuthIdentity: vi.fn(),
recordRegistrationCompensationFailure: vi.fn(), recordVerificationInconsistency: vi.fn(),
canCreateSession: vi.fn().mockResolvedValue(true),
},
});
const post = (path: string, body: object, cookie?: string) =>
auth.handler(new Request(`http://localhost:3000/api/auth/${path}`, {
method: "POST",
headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
body: JSON.stringify(body),
}));
function responseCookie(response: Response, name: string) {
const header = response.headers.getSetCookie().find((value) => value.startsWith(`better-auth.${name}=`));
expect(header).toBeDefined();
return header!.split(";")[0];
}
const headers = (cookie: string) => new Headers({ cookie });
const guard = createPrincipalGuard({
async getSession(requestHeaders) {
const session = await auth.api.getSession({ headers: requestHeaders });
return session?.user.role === "ADMIN"
? { ...session, user: { ...session.user, role: "ADMIN", twoFactorEnabled: session.user.twoFactorEnabled === true } }
: null;
},
getAccount: async () => null,
});
const login = () => post("sign-in/email", { email, password });
const first = responseCookie(await login(), "session_token");
const second = responseCookie(await login(), "session_token");
expect(first).not.toEqual(second);
const setup = await post("two-factor/enable", { password }, first);
expect(setup.status).toBe(200);
const { backupCodes } = await setup.json();
const secret = await symmetricDecrypt({
key: (await auth.$context).secretConfig, data: state.twoFactor[0].secret,
});
const { code } = await auth.api.generateTOTP({ body: { secret } });
const verified = await post("two-factor/verify-totp", { code }, first);
expect(verified.status).toBe(200);
const rotated = responseCookie(verified, "session_token");
await expect(guard.requireAdmin(headers(rotated))).resolves.toMatchObject({ userId });
await expect(guard.requireAdmin(headers(second))).rejects.toMatchObject({ code: "AUTHENTICATION_REQUIRED" });
expect((await post("two-factor/disable", { password }, second)).status).toBe(401);
const challenge = await login();
expect(await challenge.clone().json()).toMatchObject({ twoFactorRedirect: true });
const challengeCookie = responseCookie(challenge, "two_factor");
const signedIn = await post("two-factor/verify-totp", { code }, challengeCookie);
expect(signedIn.status).toBe(200);
const signedInCookie = responseCookie(signedIn, "session_token");
await expect(guard.requireAdmin(headers(signedInCookie))).resolves.toMatchObject({ userId });
const backupChallenge = responseCookie(await login(), "two_factor");
const backup = await post("two-factor/verify-backup-code", { code: backupCodes[0] }, backupChallenge);
expect(backup.status).toBe(200);
await expect(guard.requireAdmin(headers(responseCookie(backup, "session_token"))))
.resolves.toMatchObject({ userId });
expect((await post("two-factor/disable", { password }, signedInCookie)).status).toBe(200);
expect(await auth.api.getSession({ headers: headers(rotated) })).toBeNull();
});
+32 -8
View File
@@ -1,7 +1,7 @@
import "server-only"; import "server-only";
import { APIError } from "better-auth"; import { APIError } from "better-auth";
import { createAuthMiddleware } from "better-auth/api"; import { createAuthMiddleware, getSessionFromCtx } from "better-auth/api";
import { drizzleAdapter } from "@better-auth/drizzle-adapter"; import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth, type BetterAuthOptions } from "better-auth"; import { betterAuth, type BetterAuthOptions } from "better-auth";
import { twoFactor } from "better-auth/plugins"; import { twoFactor } from "better-auth/plugins";
@@ -27,6 +27,13 @@ import {
type RegistrationInput, type RegistrationInput,
} from "./registration"; } from "./registration";
export const MFA_SESSION_TOKEN_PREFIX = "mfa-";
const mfaVerificationPaths = new Set([
"/two-factor/verify-totp",
"/two-factor/verify-backup-code",
]);
export const portalAuthRateLimitOptions = { export const portalAuthRateLimitOptions = {
enabled: true, enabled: true,
storage: "memory", storage: "memory",
@@ -91,13 +98,19 @@ export function createPortalAuth({
}, },
plugins: [ plugins: [
twoFactor({ twoFactor({
// TOTP + backup codes only: without `otpOptions.sendOTP` no OTP-e-mail // TOTP + backup codes only. Expire new trust-device records immediately.
// surface exists, and trust-device stays off to keep the attack area trustDeviceMaxAge: 0,
// small. Backup codes stay encrypted (plugin default).
}), }),
], ],
hooks: { hooks: {
before: createPasswordPolicyHook(), before: createAuthSecurityHook(),
after: createAuthMiddleware(async (ctx) => {
if (ctx.path !== "/two-factor/disable" || !ctx.context.newSession) return;
const { session, user } = ctx.context.newSession;
const sessions = await ctx.context.internalAdapter.listSessions(user.id);
const otherTokens = sessions.filter(({ token }) => token !== session.token).map(({ token }) => token);
if (otherTokens.length > 0) await ctx.context.internalAdapter.deleteSessions(otherTokens);
}),
}, },
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
@@ -127,8 +140,12 @@ export function createPortalAuth({
databaseHooks: { databaseHooks: {
session: { session: {
create: { create: {
async before(session) { async before(session, ctx) {
return registrationRepository.canCreateSession(session.userId); if (!(await registrationRepository.canCreateSession(session.userId))) return false;
// These endpoints issue a new session only after verifying the factor.
if (ctx?.path && mfaVerificationPaths.has(ctx.path)) {
return { data: { ...session, token: MFA_SESSION_TOKEN_PREFIX + session.token } };
}
}, },
}, },
}, },
@@ -153,12 +170,19 @@ export function createPortalAuth({
return { auth, registrationService }; return { auth, registrationService };
} }
export function createPasswordPolicyHook() { function createAuthSecurityHook() {
// Applies the shared policy to password-reset and change-password flows, // Applies the shared policy to password-reset and change-password flows,
// which bypass the registration validation. Registration is covered by // which bypass the registration validation. Registration is covered by
// validateRegistration(); sign-up additionally enforces Better Auth's // validateRegistration(); sign-up additionally enforces Better Auth's
// minPasswordLength. // minPasswordLength.
return createAuthMiddleware(async (ctx) => { return createAuthMiddleware(async (ctx) => {
if (ctx.path?.startsWith("/two-factor/") && !mfaVerificationPaths.has(ctx.path)) {
const current = await getSessionFromCtx(ctx);
if ((current?.user as { twoFactorEnabled?: boolean } | undefined)?.twoFactorEnabled &&
!current?.session.token.startsWith(MFA_SESSION_TOKEN_PREFIX)) {
throw new APIError("UNAUTHORIZED");
}
}
if (ctx.path !== "/reset-password" && ctx.path !== "/change-password") { if (ctx.path !== "/reset-password" && ctx.path !== "/change-password") {
return; return;
} }
+2 -2
View File
@@ -68,7 +68,7 @@ test("accepts an admin session with two-factor enabled", async () => {
const guard = createPrincipalGuard({ const guard = createPrincipalGuard({
getSession: async () => ({ getSession: async () => ({
user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: true }, user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: true },
session: { createdAt: new Date() }, session: { token: "mfa-dummy-token", createdAt: new Date() },
}), }),
getAccount: async () => null, getAccount: async () => null,
}); });
@@ -80,7 +80,7 @@ test("rejects stale sessions for destructive operations (step-up)", async () =>
const guard = createPrincipalGuard({ const guard = createPrincipalGuard({
getSession: async () => ({ getSession: async () => ({
user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: true }, user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: true },
session: { createdAt: new Date(Date.now() - 30 * 60 * 1000) }, session: { token: "mfa-dummy-token", createdAt: new Date(Date.now() - 30 * 60 * 1000) },
}), }),
getAccount: async () => null, getAccount: async () => null,
}); });
+6 -3
View File
@@ -2,7 +2,7 @@ import "server-only";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { auth } from "@/modules/auth/auth"; import { auth, MFA_SESSION_TOKEN_PREFIX } from "@/modules/auth/auth";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema"; import { editorialAccounts } from "@/db/schema";
import { accountStatuses } from "@/db/schema/editorials"; import { accountStatuses } from "@/db/schema/editorials";
@@ -18,7 +18,7 @@ export type PortalPrincipal = {
type Session = { type Session = {
user: { id: string; role: "ADMIN" | "EDITORIAL"; twoFactorEnabled?: boolean }; user: { id: string; role: "ADMIN" | "EDITORIAL"; twoFactorEnabled?: boolean };
session: { createdAt?: Date }; session: { createdAt?: Date; token?: string };
} | null; } | null;
type EditorialAccount = { id: string; status: AccountStatus } | null; type EditorialAccount = { id: string; status: AccountStatus } | null;
@@ -73,6 +73,9 @@ export function createPrincipalGuard({ getSession, getAccount }: PrincipalGuardD
if (session.user.role !== "ADMIN") { if (session.user.role !== "ADMIN") {
throw new PrincipalAuthorizationError("ADMIN_REQUIRED"); throw new PrincipalAuthorizationError("ADMIN_REQUIRED");
} }
if (session.user.twoFactorEnabled && !session.session.token?.startsWith(MFA_SESSION_TOKEN_PREFIX)) {
throw new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED");
}
if (!options.allowWithoutTwoFactor && !session.user.twoFactorEnabled) { if (!options.allowWithoutTwoFactor && !session.user.twoFactorEnabled) {
throw new PrincipalAuthorizationError("TWO_FACTOR_REQUIRED"); throw new PrincipalAuthorizationError("TWO_FACTOR_REQUIRED");
} }
@@ -148,7 +151,7 @@ export const principalGuard = createPrincipalGuard({
twoFactorEnabled: twoFactorEnabled:
(session.user as { twoFactorEnabled?: unknown }).twoFactorEnabled === true, (session.user as { twoFactorEnabled?: unknown }).twoFactorEnabled === true,
}, },
session: { createdAt: session.session.createdAt }, session: { createdAt: session.session.createdAt, token: session.session.token },
}; };
}, },
+36 -2
View File
@@ -3,9 +3,11 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest"; import { afterEach, expect, test, vi } from "vitest";
const { resetPassword, signInEmail } = vi.hoisted(() => ({ resetPassword: vi.fn(), signInEmail: vi.fn() })); const { resetPassword, signInEmail, enableTwoFactor } = vi.hoisted(() => ({
resetPassword: vi.fn(), signInEmail: vi.fn(), enableTwoFactor: vi.fn(),
}));
vi.mock("./client", () => ({ vi.mock("./client", () => ({
authClient: { resetPassword, signIn: { email: signInEmail } }, authClient: { resetPassword, signIn: { email: signInEmail }, twoFactor: { enable: enableTwoFactor } },
})); }));
import { LoginForm, PasswordResetForm, RegistrationForm } from "./public-forms"; import { LoginForm, PasswordResetForm, RegistrationForm } from "./public-forms";
@@ -58,6 +60,7 @@ test("confirms a successful password reset and links directly to login", async (
fireEvent.submit(screen.getByRole("button", { name: /passwort aktualisieren/i }).closest("form")!); fireEvent.submit(screen.getByRole("button", { name: /passwort aktualisieren/i }).closest("form")!);
expect(await screen.findByText(/passwort wurde erfolgreich aktualisiert/i)).toBeTruthy(); expect(await screen.findByText(/passwort wurde erfolgreich aktualisiert/i)).toBeTruthy();
expect(resetPassword).toHaveBeenCalledWith({ newPassword: "neues-passwort-123", token: "valid-token" });
expect(screen.getByRole("link", { name: /jetzt anmelden/i }).getAttribute("href")).toBe( expect(screen.getByRole("link", { name: /jetzt anmelden/i }).getAttribute("href")).toBe(
"/anmelden", "/anmelden",
); );
@@ -87,5 +90,36 @@ test("the two-factor step starts with an empty code field, never the typed passw
fireEvent.submit(screen.getByLabelText("Passwort").closest("form")!); fireEvent.submit(screen.getByLabelText("Passwort").closest("form")!);
const code = (await screen.findByLabelText("Zwei-Faktor-Code")) as HTMLInputElement; const code = (await screen.findByLabelText("Zwei-Faktor-Code")) as HTMLInputElement;
expect(signInEmail).toHaveBeenCalledWith({
email: "admin@example.test", password: "geheim-passwort", callbackURL: "/",
});
expect(code.value).toBe(""); expect(code.value).toBe("");
expect(code.form?.method).toBe("post");
});
test("server-rendered login and reset forms use POST for native submissions", async () => {
const { renderToString } = await import("react-dom/server");
const { TwoFactorWizard } = await import("@/app/zwei-faktor/wizard");
for (const markup of [
renderToString(<LoginForm />),
renderToString(<PasswordResetForm token="dummy-token" />),
renderToString(<TwoFactorWizard initiallyEnabled={false} />),
renderToString(<TwoFactorWizard initiallyEnabled />),
]) {
const document = new DOMParser().parseFromString(markup, "text/html");
const password = document.querySelector<HTMLInputElement>("input[type=password]");
const form = password?.form;
expect(form?.method).toBe("post");
expect([...new FormData(form!).keys()]).toEqual([]);
}
});
test("the enrollment confirmation code form uses POST", async () => {
const { TwoFactorWizard } = await import("@/app/zwei-faktor/wizard");
enableTwoFactor.mockResolvedValueOnce({ data: { totpURI: "otpauth://totp/dummy?secret=DUMMY", backupCodes: [] } });
render(<TwoFactorWizard initiallyEnabled={false} />);
fireEvent.submit(screen.getByRole("button", { name: "Einrichtung starten" }).closest("form")!);
const field = await screen.findByLabelText<HTMLInputElement>("Code aus der App");
expect(field.form?.method).toBe("post");
expect([...new FormData(field.form!).keys()]).toEqual([]);
}); });
+18 -23
View File
@@ -114,11 +114,9 @@ export function LoginForm() {
setPending(true); setPending(true);
setError(undefined); setError(undefined);
const formData = new FormData(event.currentTarget);
if (awaitingTwoFactor) { if (awaitingTwoFactor) {
const result = await authClient.twoFactor.verifyTotp({ const result = await authClient.twoFactor.verifyTotp({
code: readText(formData, "totp").replace(/\s+/g, ""), code: readText(event.currentTarget, "totp").replace(/\s+/g, ""),
}); });
if (result.error) { if (result.error) {
setError("Der Code ist ungültig oder abgelaufen. Bitte erneut versuchen."); setError("Der Code ist ungültig oder abgelaufen. Bitte erneut versuchen.");
@@ -130,8 +128,8 @@ export function LoginForm() {
} }
const result = await authClient.signIn.email({ const result = await authClient.signIn.email({
email: readText(formData, "email").trim().toLowerCase(), email: readText(event.currentTarget, "email").trim().toLowerCase(),
password: readText(formData, "password"), password: readText(event.currentTarget, "password"),
callbackURL: "/", callbackURL: "/",
}); });
@@ -156,11 +154,11 @@ export function LoginForm() {
// TOTP field and would show the typed password in clear text. // TOTP field and would show the typed password in clear text.
if (awaitingTwoFactor) { if (awaitingTwoFactor) {
return ( return (
<form className="flex flex-col gap-4" key="totp" onSubmit={submit}> <form className="flex flex-col gap-4" key="totp" method="post" onSubmit={submit}>
<p className="text-sm text-[var(--color-fg-muted)]"> <p className="text-sm text-[var(--color-fg-muted)]">
Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein. Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein.
</p> </p>
<Input label="Zwei-Faktor-Code" autoComplete="one-time-code" inputMode="numeric" maxLength={6} name="totp" pattern="[0-9]*" required type="text" /> <Input label="Zwei-Faktor-Code" autoComplete="one-time-code" inputMode="numeric" maxLength={6} id="totp" pattern="[0-9]*" required type="text" />
<FieldError message={error} /> <FieldError message={error} />
<Button disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Anmelden"} {pending ? "Code wird geprüft …" : "Anmelden"}
@@ -170,9 +168,9 @@ export function LoginForm() {
} }
return ( return (
<form className="flex flex-col gap-4" key="credentials" onSubmit={submit}> <form className="flex flex-col gap-4" key="credentials" method="post" onSubmit={submit}>
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" /> <Input label="E-Mail-Adresse" autoComplete="email" id="email" required type="email" />
<Input label="Passwort" autoComplete="current-password" name="password" required type="password" /> <Input label="Passwort" autoComplete="current-password" id="password" required type="password" />
<FieldError message={error} /> <FieldError message={error} />
<Button disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Anmeldung wird geprüft …" : "Anmelden"} {pending ? "Anmeldung wird geprüft …" : "Anmelden"}
@@ -188,11 +186,9 @@ export function PasswordResetRequestForm() {
async function submit(event: FormEvent<HTMLFormElement>) { async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); event.preventDefault();
setPending(true); setPending(true);
const formData = new FormData(event.currentTarget);
try { try {
await authClient.requestPasswordReset({ await authClient.requestPasswordReset({
email: readText(formData, "email").trim().toLowerCase(), email: readText(event.currentTarget, "email").trim().toLowerCase(),
redirectTo: `${window.location.origin}/passwort-zuruecksetzen`, redirectTo: `${window.location.origin}/passwort-zuruecksetzen`,
}); });
} finally { } finally {
@@ -210,8 +206,8 @@ export function PasswordResetRequestForm() {
} }
return ( return (
<form className="flex flex-col gap-4" onSubmit={submit}> <form className="flex flex-col gap-4" method="post" onSubmit={submit}>
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" /> <Input label="E-Mail-Adresse" autoComplete="email" id="email" required type="email" />
<Button disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Anfrage wird gesendet …" : "Link anfordern"} {pending ? "Anfrage wird gesendet …" : "Link anfordern"}
</Button> </Button>
@@ -228,11 +224,9 @@ export function PasswordResetForm({ token }: { token?: string }) {
event.preventDefault(); event.preventDefault();
setPending(true); setPending(true);
setError(undefined); setError(undefined);
const formData = new FormData(event.currentTarget);
try { try {
const result = await authClient.resetPassword({ const result = await authClient.resetPassword({
newPassword: readText(formData, "password"), newPassword: readText(event.currentTarget, "password"),
token, token,
}); });
if (result.error) { if (result.error) {
@@ -262,8 +256,8 @@ export function PasswordResetForm({ token }: { token?: string }) {
} }
return ( return (
<form className="flex flex-col gap-4" onSubmit={submit}> <form action="/passwort-zuruecksetzen" className="flex flex-col gap-4" method="post" onSubmit={submit}>
<Input label="Neues Passwort" autoComplete="new-password" minLength={12} name="password" required type="password" /> <Input label="Neues Passwort" autoComplete="new-password" minLength={12} id="password" required type="password" />
<FieldError message={error} /> <FieldError message={error} />
<Button disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"} {pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
@@ -299,7 +293,8 @@ function FieldError({ message }: { message?: string }) {
return message ? <Alert color="danger" description={message} /> : null; return message ? <Alert color="danger" description={message} /> : null;
} }
function readText(formData: FormData, name: string): string { function readText(form: HTMLFormElement, id: string): string {
const value = formData.get(name); // The inputs have IDs for the SDK flow and no names for native submission.
return typeof value === "string" ? value : ""; const input = form.elements.namedItem(id);
return input instanceof HTMLInputElement ? input.value : "";
} }
-30
View File
@@ -6,7 +6,6 @@ import {
createRegistrationService, createRegistrationService,
type RegistrationInput, type RegistrationInput,
} from "./registration"; } from "./registration";
import { createAdminBootstrapService } from "./admin-bootstrap";
const validRegistration: RegistrationInput = { const validRegistration: RegistrationInput = {
companyName: "Neue Redaktion GmbH", companyName: "Neue Redaktion GmbH",
@@ -226,32 +225,3 @@ describe("editorial registration", () => {
}); });
}); });
}); });
test("bootstraps the first admin only once", async () => {
const auth = {
signUpEmail: vi.fn().mockResolvedValue({ user: { id: "admin-1" } }),
sendVerificationEmail: vi.fn().mockResolvedValue(undefined),
};
const repo = {
countAdmins: vi.fn().mockResolvedValue(0),
findUserByEmail: vi.fn().mockResolvedValue(undefined),
promoteUserToAdmin: vi.fn().mockResolvedValue(undefined),
};
const service = createAdminBootstrapService({ auth, repo });
await expect(
service.bootstrap({
email: "ADMIN@EXAMPLE.COM",
name: "Portal Admin",
password: "sicheres-passwort-123",
}),
).resolves.toEqual({ status: "created" });
expect(auth.signUpEmail).toHaveBeenCalledWith({
email: "admin@example.com",
name: "Portal Admin",
password: "sicheres-passwort-123",
});
expect(repo.promoteUserToAdmin).toHaveBeenCalledWith("admin-1");
expect(auth.sendVerificationEmail).toHaveBeenCalledWith({ email: "admin@example.com" });
});
+7 -2
View File
@@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { assertOriginalAccess } from "@/modules/albums/photo-access";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { downloadEvents, editorialAccounts, usages } from "@/db/schema"; import { downloadEvents, editorialAccounts, usages } from "@/db/schema";
import type * as schema from "@/db/schema"; import type * as schema from "@/db/schema";
@@ -60,12 +61,13 @@ export function createDownloadService({ repository }: { repository: RepeatDownlo
export function createRepeatDownloadRepository( export function createRepeatDownloadRepository(
database: NodePgDatabase<typeof schema>, database: NodePgDatabase<typeof schema>,
assertAccess: typeof assertOriginalAccess,
): RepeatDownloadRepository { ): RepeatDownloadRepository {
return { return {
async createRepeatIntent(input) { async createRepeatIntent(input) {
for (let attempt = 0; attempt < 2; attempt += 1) { for (let attempt = 0; attempt < 2; attempt += 1) {
try { try {
return await createRepeatIntentTransaction(database, input); return await createRepeatIntentTransaction(database, input, assertAccess);
} catch (error) { } catch (error) {
if (!(error instanceof RepeatIdempotencyRaceError) || attempt === 1) throw error; if (!(error instanceof RepeatIdempotencyRaceError) || attempt === 1) throw error;
} }
@@ -78,6 +80,7 @@ export function createRepeatDownloadRepository(
async function createRepeatIntentTransaction( async function createRepeatIntentTransaction(
database: NodePgDatabase<typeof schema>, database: NodePgDatabase<typeof schema>,
input: RepeatIntentInput, input: RepeatIntentInput,
assertAccess: typeof assertOriginalAccess,
): Promise<PersistedRepeatIntent> { ): Promise<PersistedRepeatIntent> {
return database.transaction(async (transaction) => { return database.transaction(async (transaction) => {
await lockEditorialAccounting(transaction, input.editorialId); await lockEditorialAccounting(transaction, input.editorialId);
@@ -108,6 +111,7 @@ async function createRepeatIntentTransaction(
.select({ .select({
id: usages.id, id: usages.id,
assetId: usages.immichAssetId, assetId: usages.immichAssetId,
albumId: usages.immichAlbumIdSnapshot,
billingStatus: usages.billingStatus, billingStatus: usages.billingStatus,
}) })
.from(usages) .from(usages)
@@ -128,6 +132,7 @@ async function createRepeatIntentTransaction(
if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) { if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) {
throw new UsageAccountingError("USAGE_NOT_FOUND"); throw new UsageAccountingError("USAGE_NOT_FOUND");
} }
await assertAccess(input.editorialId, usage.assetId, usage.albumId, transaction);
if (existing) return asRepeatIntent(existing); if (existing) return asRepeatIntent(existing);
const authorizedAt = new Date(); const authorizedAt = new Date();
@@ -185,7 +190,7 @@ function asRepeatIntent(intent: PersistedDownloadIntent): PersistedRepeatIntent
class RepeatIdempotencyRaceError extends Error {} class RepeatIdempotencyRaceError extends Error {}
export const downloadService = createDownloadService({ export const downloadService = createDownloadService({
repository: createRepeatDownloadRepository(db), repository: createRepeatDownloadRepository(db, assertOriginalAccess),
}); });
export const createRepeatDownload = downloadService.createRepeatDownload; export const createRepeatDownload = downloadService.createRepeatDownload;
+13 -1
View File
@@ -24,6 +24,7 @@ export type ClaimedDownload = {
id: string; id: string;
usageId: string; usageId: string;
assetId: string; assetId: string;
albumId: string;
filename: string; filename: string;
intentKind: "new_usage" | "repeat_download" | "legacy"; intentKind: "new_usage" | "repeat_download" | "legacy";
}; };
@@ -160,6 +161,8 @@ export function createDownloadDeliveryRepository(
const [usage] = await transaction const [usage] = await transaction
.select({ .select({
filename: usages.filenameSnapshot, filename: usages.filenameSnapshot,
assetId: usages.immichAssetId,
albumId: usages.immichAlbumIdSnapshot,
billingStatus: usages.billingStatus, billingStatus: usages.billingStatus,
}) })
.from(usages) .from(usages)
@@ -171,7 +174,7 @@ export function createDownloadDeliveryRepository(
) )
.for("update") .for("update")
.limit(1); .limit(1);
if (!usage) return { outcome: "not_found" } as const; if (!usage || usage.assetId !== candidate.assetId) return { outcome: "not_found" } as const;
const intentKind = claimedIntentKind(candidate.intentKind); const intentKind = claimedIntentKind(candidate.intentKind);
const deliveredOriginal = const deliveredOriginal =
@@ -208,6 +211,7 @@ export function createDownloadDeliveryRepository(
id: candidate.id, id: candidate.id,
usageId: candidate.usageId, usageId: candidate.usageId,
assetId: candidate.assetId, assetId: candidate.assetId,
albumId: usage.albumId,
filename: usage.filename, filename: usage.filename,
intentKind, intentKind,
}, },
@@ -603,6 +607,7 @@ export function createEditorialDownloadOptionsLoader(
return async function loadOptions( return async function loadOptions(
editorialId: string, editorialId: string,
assetIds: string[], assetIds: string[],
allowPriorUsage?: (assetId: string, albumId: string) => Promise<boolean>,
): Promise<EditorialDownloadOptions> { ): Promise<EditorialDownloadOptions> {
const normalizedEditorialId = normalizeUuid(editorialId); const normalizedEditorialId = normalizeUuid(editorialId);
const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))]; const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))];
@@ -636,6 +641,7 @@ export function createEditorialDownloadOptionsLoader(
id: usages.id, id: usages.id,
assetId: usages.immichAssetId, assetId: usages.immichAssetId,
purpose: usages.purpose, purpose: usages.purpose,
albumId: usages.immichAlbumIdSnapshot,
createdAt: usages.createdAt, createdAt: usages.createdAt,
}) })
.from(usages) .from(usages)
@@ -650,7 +656,13 @@ export function createEditorialDownloadOptionsLoader(
.orderBy(desc(usages.createdAt), desc(usages.id)) .orderBy(desc(usages.createdAt), desc(usages.id))
.limit(DOWNLOAD_OPTIONS_MAX_USAGES); .limit(DOWNLOAD_OPTIONS_MAX_USAGES);
const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {}; const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {};
const allowed = new Map<string, boolean>();
for (const row of rows) { for (const row of rows) {
if (allowPriorUsage) {
const scope = `${row.assetId}:${row.albumId}`;
if (!allowed.has(scope)) allowed.set(scope, await allowPriorUsage(row.assetId, row.albumId));
if (!allowed.get(scope)) continue;
}
(priorUsagesByAsset[row.assetId] ??= []).push({ (priorUsagesByAsset[row.assetId] ??= []).push({
id: row.id, id: row.id,
purpose: row.purpose, purpose: row.purpose,
-3
View File
@@ -374,9 +374,6 @@ export function createImmichClient({
size: input.size, size: input.size,
// Default on: exifImageWidth/exifImageHeight populate the // Default on: exifImageWidth/exifImageHeight populate the
// orientation filter (hoch/quer) and the masonry aspect ratios. // orientation filter (hoch/quer) and the masonry aspect ratios.
// Bulk-download's membership map passes withExif:false — it only
// needs asset ids, and the EXIF payload across every granted album
// is large enough to time Immich out under load.
withExif: input.withExif ?? true, withExif: input.withExif ?? true,
}), }),
}, },
-3
View File
@@ -1,13 +1,10 @@
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { lightboxItems } from "@/db/schema"; import { lightboxItems } from "@/db/schema";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAsset } from "@/modules/immich/types";
export type LightboxItem = { export type LightboxItem = {
assetId: string; assetId: string;
addedAt: Date; addedAt: Date;
asset?: ImmichAsset; // populated if joined
}; };
export const lightboxService = { export const lightboxService = {
+5 -2
View File
@@ -39,10 +39,13 @@ function createRepository() {
) { ) {
const key = `${input.editorialId}:${input.idempotencyKey}`; const key = `${input.editorialId}:${input.idempotencyKey}`;
const existing = intents.get(key); const existing = intents.get(key);
if (existing) return existing;
if (status !== "active") { if (status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
} }
if (existing) {
await refreshCurrentAsset?.();
return existing;
}
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
throw new UsageAccountingError("INVALID_PRICE"); throw new UsageAccountingError("INVALID_PRICE");
} }
@@ -142,7 +145,7 @@ test("returns the exact persisted intent for an equivalent idempotent retry", as
expect(second).toEqual(first); expect(second).toEqual(first);
expect(usages).toHaveLength(1); expect(usages).toHaveLength(1);
expect(immich.getAsset).toHaveBeenCalledTimes(2); expect(immich.getAsset).toHaveBeenCalledTimes(4);
}); });
test("canonicalizes every UUID before fingerprinting, lookup, Immich calls, and persistence", async () => { test("canonicalizes every UUID before fingerprinting, lookup, Immich calls, and persistence", async () => {
+32 -33
View File
@@ -1,5 +1,7 @@
import "server-only"; import "server-only";
import { isAssetInAlbum } from "@/modules/albums/photo-access";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { and, desc, eq, exists, inArray, isNull, sql } from "drizzle-orm"; import { and, desc, eq, exists, inArray, isNull, sql } from "drizzle-orm";
@@ -44,6 +46,7 @@ export type BillableIntentInput = {
filename: string; filename: string;
purpose: string; purpose: string;
reference?: string; reference?: string;
maxPriceCents?: number;
idempotencyKey: string; idempotencyKey: string;
requestFingerprint: string; requestFingerprint: string;
}; };
@@ -88,10 +91,11 @@ export function createUsageService({
albumId: input.albumId, albumId: input.albumId,
purpose: input.purpose, purpose: input.purpose,
reference: input.reference ?? null, reference: input.reference ?? null,
maxPriceCents: input.maxPriceCents,
}); });
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey); const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
if (existing) return resolveIntent(existing, fingerprint, "new_usage"); if (existing) resolveIntent(existing, fingerprint, "new_usage");
const asset = await getValidatedAsset(immich, input.assetId); const asset = await getValidatedAsset(immich, input.assetId);
const album = await loadRequestedAlbum(immich, input.assetId, input.albumId); const album = await loadRequestedAlbum(immich, input.assetId, input.albumId);
@@ -120,7 +124,7 @@ export function createUsageService({
export function createUsageServiceRepository( export function createUsageServiceRepository(
database: NodePgDatabase<typeof schema>, database: NodePgDatabase<typeof schema>,
): UsageRepository { ): UsageRepository {
return { const repository: UsageRepository = {
findIntent(editorialId, idempotencyKey) { findIntent(editorialId, idempotencyKey) {
return findPersistedIntent(database, editorialId, idempotencyKey); return findPersistedIntent(database, editorialId, idempotencyKey);
}, },
@@ -134,7 +138,10 @@ export function createUsageServiceRepository(
input.editorialId, input.editorialId,
input.idempotencyKey, input.idempotencyKey,
); );
if (existing) return existing; if (existing && (existing.kind !== "new_usage" ||
existing.requestFingerprint !== input.requestFingerprint)) {
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
}
const [editorial] = await transaction const [editorial] = await transaction
.select({ .select({
@@ -152,13 +159,6 @@ export function createUsageServiceRepository(
if (!editorial || editorial.status !== "active") { if (!editorial || editorial.status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
} }
if (
!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0
) {
throw new UsageAccountingError("INVALID_PRICE");
}
const [grant] = await transaction const [grant] = await transaction
.select({ id: albumGrants.id }) .select({ id: albumGrants.id })
.from(albumGrants) .from(albumGrants)
@@ -172,6 +172,17 @@ export function createUsageServiceRepository(
.for("update") .for("update")
.limit(1); .limit(1);
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED"); if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
if (existing) {
await refreshCurrentAsset();
return existing;
}
if (
!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0
) {
throw new UsageAccountingError("INVALID_PRICE");
}
let priceCents = editorial.currentPriceCents!; let priceCents = editorial.currentPriceCents!;
@@ -210,9 +221,10 @@ export function createUsageServiceRepository(
} }
} }
// This is the last cross-system authorization snapshot available to the if (input.maxPriceCents !== undefined && priceCents > input.maxPriceCents) {
// portal. Immich may still change after it returns, but no portal work is throw new UsageAccountingError("INVALID_PRICE");
// allowed between this refresh and the accounting inserts. }
// Refresh Immich membership immediately before inserting the accounting records.
const currentAsset = await refreshCurrentAsset(); const currentAsset = await refreshCurrentAsset();
const createdAt = new Date(); const createdAt = new Date();
@@ -285,7 +297,7 @@ export function createUsageServiceRepository(
input.editorialId, input.editorialId,
input.idempotencyKey, input.idempotencyKey,
); );
if (existing) return existing; if (existing) return repository.createBillableIntent(input, refreshCurrentAsset);
throw error; throw error;
} }
}, },
@@ -321,18 +333,24 @@ export function createUsageServiceRepository(
return rows.map((row) => ({ ...row, reference: row.reference ?? undefined })); return rows.map((row) => ({ ...row, reference: row.reference ?? undefined }));
}, },
}; };
return repository;
} }
function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput { function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput {
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT"); if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
const purpose = normalizeRequiredText(input.purpose, 3, 200); const purpose = normalizeRequiredText(input.purpose, 3, 200);
const reference = normalizeOptionalText(input.reference, 200); const reference = normalizeOptionalText(input.reference, 200);
if (input.maxPriceCents !== undefined &&
(!Number.isSafeInteger(input.maxPriceCents) || input.maxPriceCents < 0)) {
throw new UsageAccountingError("INVALID_INPUT");
}
return { return {
editorialId: normalizeUuid(input.editorialId), editorialId: normalizeUuid(input.editorialId),
assetId: normalizeUuid(input.assetId), assetId: normalizeUuid(input.assetId),
albumId: normalizeUuid(input.albumId), albumId: normalizeUuid(input.albumId),
purpose, purpose,
...(reference === undefined ? {} : { reference }), ...(reference === undefined ? {} : { reference }),
...(input.maxPriceCents === undefined ? {} : { maxPriceCents: input.maxPriceCents }),
idempotencyKey: normalizeUuid(input.idempotencyKey), idempotencyKey: normalizeUuid(input.idempotencyKey),
}; };
} }
@@ -358,25 +376,6 @@ async function loadRequestedAlbum(
} }
} }
async function isAssetInAlbum(
immich: UsageImmich,
assetId: string,
albumId: string,
): Promise<boolean> {
try {
const result = await immich.searchPhotos({
albumIds: [albumId],
id: assetId,
type: "IMAGE",
page: 1,
size: 1,
});
return result.items.some((asset) => asset.id === assetId);
} catch {
throw new UsageAccountingError("IMMICH_UNAVAILABLE");
}
}
async function getValidatedAsset(immich: UsageImmich, assetId: string) { async function getValidatedAsset(immich: UsageImmich, assetId: string) {
let asset: Awaited<ReturnType<UsageImmich["getAsset"]>>; let asset: Awaited<ReturnType<UsageImmich["getAsset"]>>;
try { try {
+2
View File
@@ -6,6 +6,7 @@ export type CreateNewUsageInput = {
albumId: string; albumId: string;
purpose: string; purpose: string;
reference?: string; reference?: string;
maxPriceCents?: number;
idempotencyKey: string; idempotencyKey: string;
}; };
@@ -67,6 +68,7 @@ type FingerprintPayload =
albumId: string; albumId: string;
purpose: string; purpose: string;
reference: string | null; reference: string | null;
maxPriceCents?: number;
} }
| { | {
kind: "repeat_download"; kind: "repeat_download";
+35
View File
@@ -0,0 +1,35 @@
import { eq } from "drizzle-orm";
import { afterAll, expect, test } from "vitest";
import { users } from "@/db/schema";
import { insertAdminCredential, seedAdmin } from "@/modules/auth/admin-bootstrap";
import { startPostgres } from "./postgres";
const testDb = await startPostgres();
afterAll(() => testDb.stop());
const input = { email: "existing@example.test", name: "Admin", password: "dummy seed password" };
const seed = (email: string) =>
seedAdmin({ ...input, email }, (credential) => insertAdminCredential(testDb.database, credential));
test("fails for an existing address without changing its role or verification", async () => {
const [{ id }] = await testDb.database.insert(users)
.values({ email: "Existing@example.test", name: "Editorial" })
.returning({ id: users.id });
await expect(seed(input.email)).rejects.toThrow("email is already registered");
const [account] = await testDb.database.select().from(users).where(eq(users.id, id));
expect(account).toMatchObject({ role: "EDITORIAL", emailVerified: false, name: "Editorial" });
});
test("rolls back the admin user when its credential insert fails", async () => {
const email = "rollback@example.test";
await testDb.pool.query("alter table account add constraint test_reject_credential check (provider_id <> 'credential')");
try {
await expect(seed(email)).rejects.toThrow();
const found = await testDb.database.select().from(users).where(eq(users.email, email));
expect(found).toEqual([]);
} finally {
await testDb.pool.query("alter table account drop constraint test_reject_credential");
}
});
+4 -4
View File
@@ -66,7 +66,7 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a
}); });
const repeats = createDownloadService({ const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database), repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
}); });
await expect( await expect(
repeats.createRepeatDownload({ repeats.createRepeatDownload({
@@ -80,7 +80,7 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a
test("rejects a free repeat until a new-usage original delivered bytes", async () => { test("rejects a free repeat until a new-usage original delivered bytes", async () => {
const seed = await testDb.seedEditorialWithUsage(); const seed = await testDb.seedEditorialWithUsage();
const repeats = createDownloadService({ const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database), repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
}); });
await expect( await expect(
@@ -106,7 +106,7 @@ test.each(["completed", "interrupted"] as const)(
await delivery.markInterrupted(originalId, 80); await delivery.markInterrupted(originalId, 80);
} }
const repeats = createDownloadService({ const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database), repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
}); });
const repeat = await repeats.createRepeatDownload({ const repeat = await repeats.createRepeatDownload({
@@ -136,7 +136,7 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async
await delivery.markCompleted(originalId, 120); await delivery.markCompleted(originalId, 120);
await delivery.claimAuthorized(seed.editorialId, failingNewId); await delivery.claimAuthorized(seed.editorialId, failingNewId);
const repeats = createDownloadService({ const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database), repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
}); });
const repeatKey = randomUUID(); const repeatKey = randomUUID();
const repeatInput = { const repeatInput = {
+43 -10
View File
@@ -20,6 +20,7 @@ import {
createDownloadService, createDownloadService,
createRepeatDownloadRepository, createRepeatDownloadRepository,
} from "@/modules/downloads/service"; } from "@/modules/downloads/service";
import { assertOriginalAccess } from "@/modules/albums/photo-access";
import { requestFingerprint } from "@/modules/usages/types"; import { requestFingerprint } from "@/modules/usages/types";
import { startPostgres } from "./postgres"; import { startPostgres } from "./postgres";
@@ -59,7 +60,8 @@ function createServices() {
immich, immich,
}), }),
downloadService: createDownloadService({ downloadService: createDownloadService({
repository: createRepeatDownloadRepository(database), repository: createRepeatDownloadRepository(database, (editorialId, assetId, albumId, tx) =>
assertOriginalAccess(editorialId, assetId, albumId, tx, immich)),
}), }),
immich, immich,
}; };
@@ -240,7 +242,7 @@ test("rechecks exact album membership after database locks before inserting", as
expect(usageCount.value).toBe(0); expect(usageCount.value).toBe(0);
}); });
test("returns a winner committed while waiting before later mutable state is checked", async () => { test("rejects an otherwise equivalent winner when the editorial is suspended while waiting", async () => {
const editorialId = await seedEditorial(); const editorialId = await seedEditorial();
const input = newInput(editorialId); const input = newInput(editorialId);
const immich = createServices().immich; const immich = createServices().immich;
@@ -267,7 +269,7 @@ test("returns a winner committed while waiting before later mutable state is che
try { try {
const pending = usageService.createNewUsage(input); const pending = usageService.createNewUsage(input);
await fastMiss; await fastMiss;
const winner = await insertWinner( await insertWinner(
locker, locker,
input, input,
requestFingerprint({ requestFingerprint({
@@ -284,12 +286,7 @@ test("returns a winner committed while waiting before later mutable state is che
]); ]);
await locker.query("commit"); await locker.query("commit");
await expect(pending).resolves.toMatchObject({ await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" });
id: winner.eventId,
usageId: winner.usageId,
authorizedAt: winner.authorizedAt,
billable: true,
});
expect(immich.getAlbum).toHaveBeenCalledTimes(1); expect(immich.getAlbum).toHaveBeenCalledTimes(1);
expect(immich.getAsset).toHaveBeenCalledTimes(1); expect(immich.getAsset).toHaveBeenCalledTimes(1);
} finally { } finally {
@@ -494,7 +491,7 @@ test("rechecks suspension after an idempotent repeat winner commits", async () =
idempotencyKey: randomUUID(), idempotencyKey: randomUUID(),
}; };
const downloadService = createDownloadService({ const downloadService = createDownloadService({
repository: createRepeatDownloadRepository(database), repository: createRepeatDownloadRepository(database, async () => undefined),
}); });
const eventId = randomUUID(); const eventId = randomUUID();
const authorizedAt = new Date("2026-08-09T11:00:00.000Z"); const authorizedAt = new Date("2026-08-09T11:00:00.000Z");
@@ -584,3 +581,39 @@ async function markDelivered(downloadId: string): Promise<void> {
}) })
.where(eq(downloadEvents.id, downloadId)); .where(eq(downloadEvents.id, downloadId));
} }
test("revocation blocks an idempotent new intent and an eligible repeat while retaining the usage", async () => {
const editorialId = await seedEditorial();
const { usageService, downloadService } = createServices();
const input = newInput(editorialId);
const intent = await usageService.createNewUsage(input);
await database.update(downloadEvents).set({ status: "completed", transferredBytes: 8 })
.where(eq(downloadEvents.id, intent.id));
const repeatInput = { editorialId, usageId: intent.usageId, idempotencyKey: randomUUID() };
await expect(downloadService.createRepeatDownload(repeatInput)).resolves.toMatchObject({ priceCents: 0 });
await database.update(albumGrants).set({ revokedAt: new Date() })
.where(eq(albumGrants.editorialAccountId, editorialId));
await expect(usageService.createNewUsage(input)).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" });
await expect(downloadService.createRepeatDownload(repeatInput)).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" });
await expect(usageService.listPriorUsages(editorialId, assetId)).resolves.toEqual([
expect.objectContaining({ id: intent.usageId, purpose: input.purpose }),
]);
});
test("calculates ZIP pricing server-side and refuses a price above the confirmed cap", async () => {
const editorialId = await seedEditorial({ priceCents: 1500 });
const { usageService } = createServices();
const input = newInput(editorialId);
await expect(usageService.createNewUsage({ ...input, maxPriceCents: 1499 }))
.rejects.toMatchObject({ code: "INVALID_PRICE" });
await database.update(editorialAccounts).set({
flatrateActive: true, flatratePriceCents: 10000, flatrateAssetLimit: 1,
}).where(eq(editorialAccounts.id, editorialId));
await expect(usageService.createNewUsage({ ...input, maxPriceCents: 1499 }))
.resolves.toMatchObject({ priceCents: 0 });
await expect(usageService.createNewUsage({ ...newInput(editorialId), maxPriceCents: 1500 }))
.resolves.toMatchObject({ priceCents: 1500 });
});