Secure Sakani portal and show full album titles
This commit is contained in:
1 parent
c40ccf77cf
commit
69264ce165
49 files changed
+1362
-601
No files matched your search
@@ -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
@@ -6,13 +6,17 @@ RUN corepack enable && corepack prepare pnpm@10.34.5 --activate
|
||||
|
||||
FROM base AS dependencies
|
||||
WORKDIR /app
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
FROM base AS builder
|
||||
WORKDIR /app
|
||||
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
|
||||
ENV NODE_ENV=production
|
||||
|
||||
+3
-4
@@ -70,16 +70,15 @@ services:
|
||||
- portal-internal
|
||||
profiles: ["ops"]
|
||||
|
||||
# One-shot: seed the first admin. Override the command to pass credentials:
|
||||
# docker compose --profile ops run --rm seed \
|
||||
# pnpm tsx scripts/create-admin.ts admin@example.de "Password!" "Name"
|
||||
# One-shot: create a new admin. See docs/operations.md for the stdin workflow.
|
||||
seed:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
target: builder
|
||||
environment: *portal-env
|
||||
command: ["pnpm", "tsx", "scripts/create-admin.ts"]
|
||||
entrypoint: ["node", "--conditions=react-server", "--import", "tsx", "scripts/create-admin.ts"]
|
||||
command: []
|
||||
depends_on:
|
||||
portal-db:
|
||||
condition: service_healthy
|
||||
|
||||
+12
-3
@@ -92,11 +92,20 @@ the `ops` compose profile and do not start with `docker compose up`.
|
||||
anymore. Historical (pre-squash) migration files live in
|
||||
`drizzle-history/pre-squash-2026-08/` and are referenced by integration tests
|
||||
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
|
||||
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):
|
||||
```bash
|
||||
docker compose --profile ops run --rm preflight
|
||||
|
||||
+2
-3
@@ -16,9 +16,8 @@ const nextConfig: NextConfig = {
|
||||
// ponytail: Next.js App Router injects inline scripts (RSC flight
|
||||
// data + bootstrap) to hydrate client components. Without
|
||||
// 'unsafe-inline' or a nonce in script-src the browser blocks them,
|
||||
// hydration never runs, and every client form (login, registration,
|
||||
// reset) falls back to a native GET submit. 'unsafe-inline' for
|
||||
// scripts is the pragmatic fix; upgrade path is per-request nonces
|
||||
// client forms cannot hydrate. 'unsafe-inline' for scripts is
|
||||
// the pragmatic fix; upgrade path is per-request nonces
|
||||
// via middleware (Next attaches the nonce to its inline scripts).
|
||||
value: [
|
||||
"default-src 'self'",
|
||||
|
||||
+17
-37
@@ -1,44 +1,24 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { auth } from "../src/modules/auth/auth";
|
||||
import { db } from "../src/db/client";
|
||||
import { users } from "../src/db/schema";
|
||||
import { text } from "node:stream/consumers";
|
||||
|
||||
import { insertAdminCredential, seedAdmin } from "../src/modules/auth/admin-bootstrap";
|
||||
|
||||
async function main() {
|
||||
const email = process.argv[2] || "mail@leon-tonhaeuser.de";
|
||||
const password = process.argv[3] || "AdminPassword123!";
|
||||
const name = process.argv[4] || "Leon Tonhäuser";
|
||||
|
||||
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.`);
|
||||
}
|
||||
const [email, name, ...extra] = process.argv.slice(2);
|
||||
if (!email || !name || extra.length > 0 || process.stdin.isTTY) {
|
||||
throw new Error("Supply email and name as arguments and the password on stdin");
|
||||
}
|
||||
|
||||
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) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
main().catch(() => {
|
||||
console.error("Admin seed failed. Check the input, database connectivity and whether the email is already registered.");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { assertOriginalAccess } from "@/modules/albums/photo-access";
|
||||
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
@@ -10,6 +11,7 @@ type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string
|
||||
type DownloadFileHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
repository: typeof downloadDeliveryRepository;
|
||||
assertOriginalAccess: typeof assertOriginalAccess;
|
||||
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
|
||||
};
|
||||
|
||||
@@ -35,6 +37,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
|
||||
|
||||
let original: ImmichBinary;
|
||||
try {
|
||||
await dependencies.assertOriginalAccess(
|
||||
principal.editorialId, claim.download.assetId, claim.download.albumId,
|
||||
);
|
||||
original = await dependencies.immich.getOriginal(
|
||||
claim.download.assetId,
|
||||
request.signal,
|
||||
@@ -163,5 +168,6 @@ function jsonError(status: number, code: string): Response {
|
||||
export const authorizedDownloadFileHandler = createDownloadFileHandler({
|
||||
requireActiveEditorial,
|
||||
repository: downloadDeliveryRepository,
|
||||
assertOriginalAccess,
|
||||
immich: immichClient,
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { contentDisposition, createDownloadFileHandler } from "./download-handle
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherEditorialId = "22222222-2222-4222-8222-222222222222";
|
||||
const albumId = "66666666-6666-4666-8666-666666666666";
|
||||
const downloadId = "33333333-3333-4333-8333-333333333333";
|
||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||
const assetId = "55555555-5555-4555-8555-555555555555";
|
||||
@@ -48,6 +49,7 @@ function dependencies(options: {
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
albumId,
|
||||
filename: "snapshot.jpg",
|
||||
intentKind: options.intentKind ?? "new_usage",
|
||||
},
|
||||
@@ -63,6 +65,7 @@ function dependencies(options: {
|
||||
return { editorialId };
|
||||
}),
|
||||
repository,
|
||||
assertOriginalAccess: vi.fn().mockResolvedValue(undefined),
|
||||
immich: {
|
||||
getOriginal: vi.fn().mockImplementation(async () => {
|
||||
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(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 { expect, test, vi } from "vitest";
|
||||
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
@@ -37,10 +39,9 @@ function fakeArchive(): BulkArchive {
|
||||
|
||||
function dependencies() {
|
||||
return {
|
||||
assertOriginalAccess: vi.fn().mockResolvedValue(undefined),
|
||||
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue([albumId]),
|
||||
searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: assetId }] }),
|
||||
getAsset: vi.fn().mockResolvedValue({ id: assetId, originalFileName: "foto.jpg" }),
|
||||
findAttempt: vi.fn().mockResolvedValue(undefined),
|
||||
getOriginal: vi.fn().mockResolvedValue({
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
@@ -62,6 +63,7 @@ function dependencies() {
|
||||
id: downloadId,
|
||||
usageId: "55555555-5555-4555-8555-555555555555",
|
||||
assetId,
|
||||
albumId,
|
||||
filename: "foto.jpg",
|
||||
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", {
|
||||
method: "POST",
|
||||
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 () => {
|
||||
const deps = dependencies();
|
||||
deps.searchPhotos.mockResolvedValue({ items: [{ id: assetId }, { id: secondAssetId }] });
|
||||
deps.getAsset.mockImplementation(async (id: string) => ({ id, originalFileName: `${id}.jpg` }));
|
||||
deps.createNewUsage
|
||||
.mockResolvedValueOnce({ id: downloadId })
|
||||
.mockRejectedValueOnce(new Error("accounting unavailable"));
|
||||
@@ -137,3 +146,88 @@ test("settles an already claimed first item when preparation of a later item fai
|
||||
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();
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { basename } from "node:path";
|
||||
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 {
|
||||
createBulkDeliveryAccounting,
|
||||
@@ -15,7 +17,11 @@ import {
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} 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 = {
|
||||
pipe(destination: PassThrough): unknown;
|
||||
@@ -24,41 +30,35 @@ export type BulkArchive = {
|
||||
abort(): unknown;
|
||||
};
|
||||
|
||||
type BulkAttempt = {
|
||||
id: string;
|
||||
assetId: string;
|
||||
usageId: string;
|
||||
kind: string;
|
||||
purpose: string;
|
||||
status: string;
|
||||
transferredBytes: number | null;
|
||||
billingStatus: string;
|
||||
};
|
||||
|
||||
type BulkDownloadHandlerDependencies = {
|
||||
findAttempt(editorialId: string, key: string): Promise<BulkAttempt | undefined>;
|
||||
assertOriginalAccess: typeof assertOriginalAccess;
|
||||
requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>;
|
||||
getGrantedAlbumIds(editorialId: string): Promise<string[]>;
|
||||
searchPhotos(input: {
|
||||
albumIds: string[];
|
||||
type: "IMAGE";
|
||||
page: number;
|
||||
size: number;
|
||||
withExif: false;
|
||||
}): Promise<{ items: Array<{ id: string }> }>;
|
||||
getAsset(assetId: string): Promise<{ id: string; originalFileName: string }>;
|
||||
getOriginal(
|
||||
assetId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ body: ReadableStream<Uint8Array> }>;
|
||||
listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>;
|
||||
createNewUsage(input: {
|
||||
editorialId: string;
|
||||
assetId: string;
|
||||
albumId: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
idempotencyKey: string;
|
||||
}): Promise<{ id: string }>;
|
||||
createRepeatDownload(input: {
|
||||
editorialId: string;
|
||||
usageId: string;
|
||||
idempotencyKey: string;
|
||||
}): Promise<{ id: string }>;
|
||||
createNewUsage(input: CreateNewUsageInput): Promise<{ id: string }>;
|
||||
createRepeatDownload(input: CreateRepeatDownloadInput): Promise<{ id: string }>;
|
||||
repository: DownloadDeliveryRepository;
|
||||
createArchive(): BulkArchive;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
type PreparedDownload = {
|
||||
albumId: string;
|
||||
assetId: string;
|
||||
downloadId: string;
|
||||
filename: string;
|
||||
@@ -75,37 +75,28 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const payload = await parsePayload(request);
|
||||
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId);
|
||||
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds);
|
||||
const items = [];
|
||||
for (const item of payload.items) {
|
||||
const idempotencyKey = await resolveRetryKey(dependencies, principal.editorialId, item);
|
||||
items.push({ ...item, idempotencyKey });
|
||||
}
|
||||
const accounting = createBulkDeliveryAccounting(dependencies.repository);
|
||||
let downloads: PreparedDownload[];
|
||||
const downloads: PreparedDownload[] = [];
|
||||
try {
|
||||
downloads = await prepareDownloads(
|
||||
dependencies,
|
||||
principal.editorialId,
|
||||
payload,
|
||||
assetToGrantedAlbum,
|
||||
async (item) => {
|
||||
const claim = await dependencies.repository.claimAuthorized(
|
||||
principal.editorialId,
|
||||
item.downloadId,
|
||||
);
|
||||
if (claim.outcome !== "claimed") {
|
||||
throw new Error("Fresh bulk-download intent could not be claimed");
|
||||
}
|
||||
accounting.track({
|
||||
downloadId: item.downloadId,
|
||||
intentKind: claim.download.intentKind,
|
||||
});
|
||||
},
|
||||
);
|
||||
for (const item of items) {
|
||||
const intent = await createIntent(dependencies, principal.editorialId, item, payload.maxPriceCents);
|
||||
const claim = await dependencies.repository.claimAuthorized(principal.editorialId, intent.id);
|
||||
if (claim.outcome !== "claimed") throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
|
||||
const { albumId, assetId, filename, intentKind } = claim.download;
|
||||
accounting.track({ downloadId: intent.id, intentKind });
|
||||
downloads.push({ albumId, assetId, filename, downloadId: intent.id });
|
||||
}
|
||||
} catch (error) {
|
||||
await accounting.failArchive().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (downloads.length === 0) return plainError(404, "No valid assets found for download");
|
||||
|
||||
const passThrough = new PassThrough();
|
||||
const archive = dependencies.createArchive();
|
||||
archive.pipe(passThrough);
|
||||
@@ -125,7 +116,10 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
|
||||
passThrough,
|
||||
downloads,
|
||||
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,
|
||||
});
|
||||
|
||||
@@ -143,7 +137,6 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[bulk-download] failed:", error);
|
||||
return mappedBulkError(error);
|
||||
}
|
||||
};
|
||||
@@ -161,13 +154,13 @@ async function produceArchive({
|
||||
passThrough: PassThrough;
|
||||
downloads: PreparedDownload[];
|
||||
requestSignal: AbortSignal;
|
||||
getOriginal: BulkDownloadHandlerDependencies["getOriginal"];
|
||||
getOriginal(item: PreparedDownload, signal: AbortSignal): Promise<{ body: ReadableStream<Uint8Array> }>;
|
||||
accounting: ReturnType<typeof createBulkDeliveryAccounting>;
|
||||
}) {
|
||||
try {
|
||||
for (const item of downloads) {
|
||||
if (requestSignal.aborted) throw new Error("Archive request aborted");
|
||||
const original = await getOriginal(item.assetId, requestSignal);
|
||||
const original = await getOriginal(item, requestSignal);
|
||||
const source = Readable.fromWeb(
|
||||
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
|
||||
);
|
||||
@@ -192,99 +185,77 @@ async function produceArchive({
|
||||
}
|
||||
}
|
||||
|
||||
async function grantedAssetMap(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
grantedAlbumIds: string[],
|
||||
) {
|
||||
const result = new Map<string, string>();
|
||||
const albums = await Promise.all(
|
||||
grantedAlbumIds.map(async (albumId) => {
|
||||
try {
|
||||
const page = await dependencies.searchPhotos({
|
||||
albumIds: [albumId],
|
||||
type: "IMAGE",
|
||||
page: 1,
|
||||
size: 1_000,
|
||||
withExif: false,
|
||||
});
|
||||
return { albumId, items: page.items };
|
||||
} catch {
|
||||
return { albumId, items: [] };
|
||||
}
|
||||
const uuid = z.uuid().transform((value) => value.toLowerCase());
|
||||
const selectionFields = { assetId: uuid, idempotencyKey: uuid };
|
||||
const bulkPayload = z.strictObject({
|
||||
items: z.array(z.union([
|
||||
z.strictObject({ ...selectionFields, usageId: uuid }),
|
||||
z.strictObject({
|
||||
...selectionFields,
|
||||
albumId: uuid,
|
||||
purpose: z.string().trim().refine((value) => [...value].length >= 3 && [...value].length <= 200),
|
||||
}),
|
||||
);
|
||||
for (const album of albums) {
|
||||
for (const asset of album.items) {
|
||||
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
])).min(1).max(100),
|
||||
maxPriceCents: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
async function prepareDownloads(
|
||||
type Selection = z.output<typeof bulkPayload>["items"][number];
|
||||
|
||||
async function resolveRetryKey(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
editorialId: string,
|
||||
payload: { assetIds: string[]; purpose: string },
|
||||
assetToGrantedAlbum: Map<string, string>,
|
||||
onPrepared: (item: PreparedDownload) => Promise<void>,
|
||||
item: Selection,
|
||||
) {
|
||||
const assets = await Promise.all(
|
||||
payload.assetIds.map(async (assetId) => {
|
||||
try {
|
||||
return await dependencies.getAsset(assetId);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
const downloads: PreparedDownload[] = [];
|
||||
for (const asset of assets) {
|
||||
if (!asset) continue;
|
||||
const albumId = assetToGrantedAlbum.get(asset.id);
|
||||
if (!albumId) continue;
|
||||
const prior = await dependencies.listPriorUsages(editorialId, asset.id);
|
||||
const intent = prior[0]
|
||||
? await dependencies.createRepeatDownload({
|
||||
editorialId,
|
||||
usageId: prior[0].id,
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
: await dependencies.createNewUsage({
|
||||
editorialId,
|
||||
assetId: asset.id,
|
||||
albumId,
|
||||
purpose: payload.purpose,
|
||||
reference: undefined,
|
||||
idempotencyKey: randomUUID(),
|
||||
});
|
||||
const prepared = {
|
||||
assetId: asset.id,
|
||||
downloadId: intent.id,
|
||||
filename: asset.originalFileName,
|
||||
};
|
||||
await onPrepared(prepared);
|
||||
downloads.push(prepared);
|
||||
let key = item.idempotencyKey;
|
||||
for (let attempt = 0; attempt < 16; attempt += 1) {
|
||||
const existing = await dependencies.findAttempt(editorialId, key);
|
||||
if (!existing) return key;
|
||||
|
||||
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);
|
||||
if (sameSelection && existing.status === "authorized") return key;
|
||||
|
||||
if (!sameSelection || existing.status !== "failed_before_delivery" ||
|
||||
existing.transferredBytes !== 0 || (!repeat && existing.billingStatus !== "voided")) {
|
||||
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
}
|
||||
// Everyone retrying the same voided attempt converges on one new key.
|
||||
key = existing.id;
|
||||
}
|
||||
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) {
|
||||
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown };
|
||||
if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) {
|
||||
throw new BulkInputError();
|
||||
const parsed = bulkPayload.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) throw new UsageAccountingError("INVALID_INPUT");
|
||||
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;
|
||||
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() };
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
class BulkInputError extends Error {}
|
||||
|
||||
function safeArchiveFilename(value: string) {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_")
|
||||
@@ -293,13 +264,6 @@ function safeArchiveFilename(value: string) {
|
||||
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto";
|
||||
}
|
||||
|
||||
function plainError(status: number, message: string) {
|
||||
return new Response(message, {
|
||||
status,
|
||||
headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" },
|
||||
});
|
||||
}
|
||||
|
||||
function mappedBulkError(error: unknown): Response {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return jsonError(429, "RATE_LIMITED", {
|
||||
@@ -307,7 +271,6 @@ function mappedBulkError(error: unknown): Response {
|
||||
});
|
||||
}
|
||||
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||
if (error instanceof BulkInputError) return jsonError(400, "INVALID_INPUT");
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
|
||||
@@ -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 { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
@@ -12,9 +16,24 @@ const archiver = require("archiver") as { ZipArchive: new (options: unknown) =>
|
||||
|
||||
export const POST = createBulkDownloadHandler({
|
||||
requireActiveEditorial,
|
||||
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId),
|
||||
searchPhotos: (input) => immichClient.searchPhotos(input),
|
||||
getAsset: (assetId) => immichClient.getAsset(assetId),
|
||||
async findAttempt(editorialId, key) {
|
||||
const [attempt] = await db.select({
|
||||
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),
|
||||
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
|
||||
createNewUsage: (input) => usageService.createNewUsage(input),
|
||||
|
||||
@@ -71,11 +71,10 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
{formatCount(result.page.total, "Foto")} gefunden
|
||||
</p>
|
||||
<PhotoGallery
|
||||
albumId={result.album.id}
|
||||
albumName={result.album.albumName}
|
||||
items={result.page.items}
|
||||
downloadOptions={result.downloadOptions}
|
||||
lightboxAssetIds={[...result.lightboxAssetIds]}
|
||||
lightboxAssetIds={result.page.items.filter(({ id }) => result.lightboxAssetIds.has(id)).map(({ id }) => id)}
|
||||
/>
|
||||
<PhotoPagination
|
||||
albumId={result.album.id}
|
||||
|
||||
@@ -60,7 +60,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
albumName="Alle Alben"
|
||||
items={page.items}
|
||||
downloadOptions={downloadOptions}
|
||||
lightboxAssetIds={[...lightboxAssetIds]}
|
||||
lightboxAssetIds={page.items.filter(({ id }) => lightboxAssetIds.has(id)).map(({ id }) => id)}
|
||||
showAlbumName
|
||||
/>
|
||||
<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";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Button, Input } from "@sakaniui/react";
|
||||
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 dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const [purpose, setPurpose] = useState("");
|
||||
const [choices, setChoices] = useState<Record<string, Choice>>({});
|
||||
const [commonPurpose, setCommonPurpose] = useState("");
|
||||
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();
|
||||
|
||||
async function handleBulkDownload(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!purpose.trim() || assetIds.length === 0) return;
|
||||
const selected = photos.filter(({ assetId }) => {
|
||||
const selection = choices[assetId]?.selection;
|
||||
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);
|
||||
setError(null);
|
||||
|
||||
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", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assetIds, purpose }),
|
||||
body: JSON.stringify({ items, maxPriceCents: options.priceCents }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Surface the server's error code instead of a generic message so the
|
||||
// real cause (e.g. IMMICH_UNAVAILABLE, REQUEST_FAILED) is visible in the
|
||||
// browser console — the bulk handler maps UsageAccountingError to codes.
|
||||
let code: string | undefined;
|
||||
try {
|
||||
code = (await response.clone().json()).code;
|
||||
} catch {
|
||||
/* non-JSON body (e.g. plain 500) — code stays undefined */
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (payload?.code === "INVALID_PRICE") {
|
||||
router.refresh();
|
||||
throw new Error("Der Tarif hat sich geändert. Bitte prüfen Sie den aktualisierten Preis.");
|
||||
}
|
||||
const status = response.status;
|
||||
console.error("[bulk-download] server error:", { status, code });
|
||||
throw new Error(`Download fehlgeschlagen (${status}${code ? ` ${code}` : ""})`);
|
||||
if (payload?.code === "IDEMPOTENCY_CONFLICT") {
|
||||
router.refresh();
|
||||
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 url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `leuchtkasten-${new Date().toISOString().split("T")[0]}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "leuchtkasten.zip";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
intentKeys.current.clear();
|
||||
dialogRef.current?.close();
|
||||
setPurpose("");
|
||||
router.refresh(); // Refresh to update usage history
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Download fehlgeschlagen";
|
||||
setError(`Bulk-Download fehlgeschlagen: ${message}`);
|
||||
console.error(err);
|
||||
setChoices({});
|
||||
setCommonPurpose("");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={assetIds.length === 0}
|
||||
leftIcon={<IconDownload size={16} />}
|
||||
onClick={() => dialogRef.current?.showModal()}
|
||||
type="button"
|
||||
>
|
||||
Alle herunterladen
|
||||
<Button leftIcon={<IconDownload size={16} />} onClick={() => dialogRef.current?.showModal()} type="button">
|
||||
ZIP-Download vorbereiten
|
||||
</Button>
|
||||
|
||||
<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}>
|
||||
<h2 id="bulk-download-title" className="text-xl font-semibold">Verwendungszweck angeben</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>
|
||||
<form className="flex flex-col gap-4 p-6" method="post" onSubmit={handleBulkDownload}>
|
||||
<h2 id="bulk-download-title" className="text-xl font-semibold">Nutzungen für ZIP-Download</h2>
|
||||
<Input
|
||||
disabled={loading}
|
||||
id="purpose"
|
||||
label="Verwendungszweck"
|
||||
onChange={(e) => setPurpose(e.target.value)}
|
||||
placeholder="z.B. Webseite, Social Media"
|
||||
required
|
||||
type="text"
|
||||
value={purpose}
|
||||
label="Gemeinsamer Zweck für neue Nutzungen"
|
||||
maxLength={200}
|
||||
onChange={(event) => setCommonPurpose(event.target.value)}
|
||||
value={commonPurpose}
|
||||
/>
|
||||
{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">
|
||||
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={loading || !purpose.trim()} type="submit">
|
||||
{loading ? "Wird verpackt …" : "Download starten (ZIP)"}
|
||||
<Button disabled={loading || !ready} type="submit">
|
||||
{loading ? "Wird verpackt …" : newPhotos.length ? "Nutzungen bestätigen und laden" : "ZIP herunterladen"}
|
||||
</Button>
|
||||
</div>
|
||||
</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);
|
||||
});
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
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 { lightboxService } from "@/modules/lightbox/service";
|
||||
|
||||
@@ -12,7 +14,11 @@ export async function toggleLightboxItem(assetId: string) {
|
||||
if (isInLightbox) {
|
||||
await lightboxService.removeLightboxItem(principal.editorialId, assetId);
|
||||
} 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
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, EmptyState } from "@/components/ui/sakani";
|
||||
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 { RemoveLightboxItemButton } from "./RemoveLightboxItemButton";
|
||||
import { DownloadLightboxForm } from "./DownloadLightboxForm";
|
||||
@@ -13,13 +14,34 @@ export default async function LightboxPage() {
|
||||
const principal = await requireEditorial();
|
||||
const items = await lightboxService.getLightboxItems(principal.editorialId);
|
||||
|
||||
// Fetch asset details for all items in the lightbox
|
||||
const assets = items.length > 0
|
||||
? await Promise.all(items.map(i => immichClient.getAsset(i.assetId).catch(() => null)))
|
||||
: [];
|
||||
|
||||
const validAssets = assets.filter((a): a is NonNullable<typeof a> => a !== null);
|
||||
const assetMap = new Map(validAssets.map(a => [a.id, a]));
|
||||
const photos = new Map<string, NonNullable<Awaited<ReturnType<typeof findGrantedPhoto>>>>();
|
||||
const lookupDeadline = AbortSignal.timeout(15_000);
|
||||
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 downloadable = items.flatMap(({ assetId }) => {
|
||||
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 (
|
||||
<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)]">
|
||||
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
|
||||
</p>
|
||||
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
|
||||
{downloadOptions && <DownloadLightboxForm photos={downloadable} options={downloadOptions} />}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<ul className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
|
||||
{items.map((item) => {
|
||||
const asset = assetMap.get(item.assetId);
|
||||
if (!asset) return null;
|
||||
const albumId = asset.albums?.[0]?.id;
|
||||
const href = albumId
|
||||
? `/redaktion/alben/${encodeURIComponent(albumId)}?suche=${encodeURIComponent(asset.originalFileName)}`
|
||||
: '#';
|
||||
const photo = photos.get(item.assetId);
|
||||
if (!photo) {
|
||||
return (
|
||||
<li key={item.assetId} className="flex items-center justify-between gap-2 rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] p-3">
|
||||
<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 (
|
||||
<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)]">
|
||||
<div className="aspect-[3/2] w-full overflow-hidden bg-[var(--color-bg-subtle)]">
|
||||
<img
|
||||
alt={asset.originalFileName ?? "Bild"}
|
||||
alt={photo.filename}
|
||||
className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105"
|
||||
loading="lazy"
|
||||
src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`}
|
||||
/>
|
||||
</div>
|
||||
<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}>
|
||||
{asset.originalFileName ?? "Unbekannt"}
|
||||
<span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={photo.filename}>
|
||||
{photo.filename}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
@@ -46,8 +46,8 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const code = String(formData.get("code") ?? "").replace(/\s+/g, "");
|
||||
const input = event.currentTarget.querySelector<HTMLInputElement>("#mfa-code");
|
||||
const code = input?.value.replace(/\s+/g, "") ?? "";
|
||||
const result = await authClient.twoFactor.verifyTotp({ code });
|
||||
if (result.error) {
|
||||
setError("Der Code ist ungültig. Bitte prüfen Sie Ihre Authenticator-App.");
|
||||
@@ -86,12 +86,12 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{!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">
|
||||
<Input
|
||||
autoComplete="current-password"
|
||||
label="Passwort bestätigen, um die Einrichtung zu starten"
|
||||
name="password"
|
||||
id="mfa-password"
|
||||
required
|
||||
type="password"
|
||||
/>
|
||||
@@ -132,14 +132,14 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
|
||||
</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">
|
||||
<Input
|
||||
autoComplete="one-time-code"
|
||||
inputMode="numeric"
|
||||
label="Code aus der App"
|
||||
maxLength={6}
|
||||
name="code"
|
||||
id="mfa-code"
|
||||
pattern="[0-9]*"
|
||||
required
|
||||
type="text"
|
||||
@@ -165,13 +165,13 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
|
||||
)}
|
||||
|
||||
{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)]">
|
||||
Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die
|
||||
Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind.
|
||||
</p>
|
||||
<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>
|
||||
<Button variant="outline" disabled={pending} type="submit">
|
||||
{pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"}
|
||||
@@ -185,8 +185,7 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
|
||||
}
|
||||
|
||||
function readPassword(form: HTMLFormElement): string {
|
||||
const value = new FormData(form).get("password");
|
||||
return typeof value === "string" ? value : "";
|
||||
return form.querySelector<HTMLInputElement>("#mfa-password")?.value ?? "";
|
||||
}
|
||||
|
||||
function twoFactorErrorMessage(code: string | undefined): string {
|
||||
|
||||
@@ -12,6 +12,7 @@ vi.mock("next/navigation", () => ({
|
||||
vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "light", setTheme: vi.fn() }) }));
|
||||
vi.mock("@/modules/auth/client", () => ({ authClient: { signOut: vi.fn() } }));
|
||||
|
||||
import { authClient } from "@/modules/auth/client";
|
||||
import { AppShell } from "./app-shell";
|
||||
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}`) }));
|
||||
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");
|
||||
});
|
||||
@@ -63,6 +63,7 @@ export function AppShell({
|
||||
const { resolvedTheme, setTheme } = useTheme();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
const [signOutFailed, setSignOutFailed] = useState(false);
|
||||
const [notesOpen, setNotesOpen] = useState(false);
|
||||
|
||||
const active = NAV.filter(({ href }) => pathname === href || pathname.startsWith(`${href}/`))
|
||||
@@ -91,11 +92,18 @@ export function AppShell({
|
||||
|
||||
async function signOut() {
|
||||
setSigningOut(true);
|
||||
setSignOutFailed(false);
|
||||
try {
|
||||
await authClient.signOut();
|
||||
} finally {
|
||||
window.location.replace("/anmelden");
|
||||
const result = await authClient.signOut();
|
||||
if (result.data?.success === true && !result.error) {
|
||||
window.location.replace("/anmelden");
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// A failed request leaves the session status unconfirmed.
|
||||
}
|
||||
setSignOutFailed(true);
|
||||
setSigningOut(false);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -146,6 +154,11 @@ export function AppShell({
|
||||
<Button variant="ghost" size="sm" leftIcon={<IconLogout size={16} />} loading={signingOut} onClick={signOut}>
|
||||
Abmelden
|
||||
</Button>
|
||||
{signOutFailed && (
|
||||
<p className="px-3 text-sm text-[var(--color-danger-fg)]" role="alert">
|
||||
Abmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Sidebar>
|
||||
</div>
|
||||
|
||||
@@ -33,12 +33,12 @@ test("renders granted albums as labelled contact-sheet links", () => {
|
||||
|
||||
const photo = {
|
||||
id: "asset-1",
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "tor-des-sieges.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: "2026-08-08T18:42:00.000Z",
|
||||
fileCreatedAt: null,
|
||||
albums: [{ id: "heimspiel" }],
|
||||
filename: "tor-des-sieges.jpg",
|
||||
takenAt: "2026-08-08T18:42:00.000Z",
|
||||
width: null,
|
||||
height: null,
|
||||
albumId: "heimspiel",
|
||||
albumName: "Heimspiel gegen Nord",
|
||||
};
|
||||
|
||||
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", () => {
|
||||
render(
|
||||
<PhotoGallery
|
||||
albumId="33333333-3333-4333-8333-333333333333"
|
||||
albumName="Heimspiel gegen Nord"
|
||||
downloadOptions={{
|
||||
priceCents: 1_500,
|
||||
@@ -68,13 +67,10 @@ test("renders the server-scoped download choices for a catalog photo", () => {
|
||||
}}
|
||||
items={[
|
||||
{
|
||||
...photo,
|
||||
id: "22222222-2222-4222-8222-222222222222",
|
||||
type: "IMAGE",
|
||||
originalFileName: "tor.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
albums: [{ id: "33333333-3333-4333-8333-333333333333" }],
|
||||
filename: "tor.jpg",
|
||||
albumId: "33333333-3333-4333-8333-333333333333",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
@@ -91,7 +87,7 @@ test("offers the existing download workflow on a global search result and its li
|
||||
items={[{
|
||||
...photo,
|
||||
id: "22222222-2222-4222-8222-222222222222",
|
||||
albums: [{ id: "33333333-3333-4333-8333-333333333333" }],
|
||||
albumId: "33333333-3333-4333-8333-333333333333",
|
||||
}]}
|
||||
showAlbumName
|
||||
/>,
|
||||
@@ -107,8 +103,8 @@ test("opens a full-screen lightbox when a photo tile is clicked", () => {
|
||||
<PhotoGallery
|
||||
albumName="Heimspiel gegen Nord"
|
||||
items={[
|
||||
{ ...photo, id: "a", originalFileName: "first.jpg" },
|
||||
{ ...photo, id: "b", originalFileName: "second.jpg" },
|
||||
{ ...photo, id: "a", filename: "first.jpg" },
|
||||
{ ...photo, id: "b", filename: "second.jpg" },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { VisibleAlbum } from "./catalog";
|
||||
|
||||
export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) {
|
||||
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) => (
|
||||
<li key={album.id}>
|
||||
<Link
|
||||
@@ -37,7 +37,7 @@ export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[]
|
||||
</div>
|
||||
)}
|
||||
<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>
|
||||
</figcaption>
|
||||
</figure>
|
||||
@@ -62,7 +62,7 @@ export function PhotoPagination({
|
||||
}: Readonly<{
|
||||
albumId: string;
|
||||
currentPage: number;
|
||||
page: ImmichSearchPage;
|
||||
page: Pick<ImmichSearchPage, "nextPage" | "previousPage">;
|
||||
query: string;
|
||||
format?: string;
|
||||
jahr?: string;
|
||||
|
||||
@@ -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 });
|
||||
|
||||
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"] });
|
||||
immich.searchPhotos.mockResolvedValue({
|
||||
items: [{
|
||||
@@ -94,6 +94,8 @@ test("moves the queried granted album to the active gallery context without losi
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
originalPath: "/private/photos/tor.jpg",
|
||||
exifInfo: { exifImageWidth: 1200, exifImageHeight: 800, latitude: 12 },
|
||||
albums: [
|
||||
{ id: "other", albumName: "Anderes 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 });
|
||||
|
||||
expect(result.items[0]?.albums).toEqual([
|
||||
{ id: "allowed", albumName: "Erlaubtes Album" },
|
||||
{ id: "other", albumName: "Anderes Album" },
|
||||
]);
|
||||
expect(result.items).toEqual([{
|
||||
id: "asset-1",
|
||||
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 () => {
|
||||
|
||||
@@ -16,6 +16,18 @@ const MAX_DESCRIPTION_LENGTH = 200;
|
||||
|
||||
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 = {
|
||||
requestedAlbumId?: string;
|
||||
description?: unknown;
|
||||
@@ -54,7 +66,7 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
|
||||
async searchVisiblePhotos(
|
||||
editorialId: string,
|
||||
input: SearchVisiblePhotosInput,
|
||||
): Promise<ImmichSearchPage> {
|
||||
): Promise<GalleryPage> {
|
||||
const description = normalizeDescription(input.description);
|
||||
if (description) {
|
||||
try {
|
||||
@@ -91,10 +103,10 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
|
||||
// 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
|
||||
// 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(
|
||||
grantedAlbumIds.filter((id) => visibleIds.has(id))
|
||||
.map((albumId) => searchAlbum(immich, [albumId], description, page, size)),
|
||||
grantedAlbumIds.filter((id) => visibleAlbums.has(id))
|
||||
.map((albumId) => searchAlbum(immich, [albumId], description, page, size, visibleAlbums.get(albumId))),
|
||||
);
|
||||
return mergeSearchPages(pages);
|
||||
},
|
||||
@@ -107,7 +119,8 @@ async function searchAlbum(
|
||||
description: string | undefined,
|
||||
page: number,
|
||||
size: number,
|
||||
): Promise<ImmichSearchPage> {
|
||||
albumName: string | null = null,
|
||||
): Promise<GalleryPage> {
|
||||
try {
|
||||
const searchPage = await immich.searchPhotos({
|
||||
albumIds,
|
||||
@@ -116,25 +129,24 @@ async function searchAlbum(
|
||||
page,
|
||||
size,
|
||||
});
|
||||
const queriedAlbumId = albumIds[0];
|
||||
return {
|
||||
...searchPage,
|
||||
items: queriedAlbumId
|
||||
? searchPage.items.map((asset) => {
|
||||
const queriedAlbum = asset.albums.find(({ id }) => id === queriedAlbumId) ?? { id: queriedAlbumId };
|
||||
return {
|
||||
...asset,
|
||||
albums: [queriedAlbum, ...asset.albums.filter(({ id }) => id !== queriedAlbumId)],
|
||||
};
|
||||
})
|
||||
: searchPage.items,
|
||||
items: searchPage.items.map((asset) => ({
|
||||
id: asset.id,
|
||||
filename: asset.originalFileName,
|
||||
takenAt: asset.localDateTime ?? asset.fileCreatedAt,
|
||||
width: asset.exifInfo?.exifImageWidth ?? null,
|
||||
height: asset.exifInfo?.exifImageHeight ?? null,
|
||||
albumId: albumIds[0],
|
||||
albumName,
|
||||
})),
|
||||
};
|
||||
} catch {
|
||||
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
|
||||
// paginatePhotos, which recomputes both from the merged item count.
|
||||
return {
|
||||
@@ -145,7 +157,7 @@ function mergeSearchPages(pages: ImmichSearchPage[]): ImmichSearchPage {
|
||||
};
|
||||
}
|
||||
|
||||
function emptySearchPage(): ImmichSearchPage {
|
||||
function emptySearchPage(): GalleryPage {
|
||||
return { items: [], total: 0, nextPage: null, previousPage: null };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
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 {
|
||||
id: overrides.id,
|
||||
type: "IMAGE",
|
||||
originalFileName: overrides.originalFileName ?? `${overrides.id}.jpg`,
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: overrides.localDateTime ?? null,
|
||||
fileCreatedAt: overrides.fileCreatedAt ?? null,
|
||||
albums: overrides.albums ?? [],
|
||||
exifInfo: overrides.exifInfo ?? null,
|
||||
filename: `${overrides.id}.jpg`,
|
||||
takenAt: null,
|
||||
width: null,
|
||||
height: null,
|
||||
albumId: "album",
|
||||
albumName: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("matchesOrientation distinguishes landscape from portrait via EXIF dimensions", () => {
|
||||
const landscape = photo({ id: "l", exifInfo: { exifImageWidth: 1600, exifImageHeight: 900 } });
|
||||
const portrait = photo({ id: "p", exifInfo: { exifImageWidth: 900, exifImageHeight: 1600 } });
|
||||
const square = photo({ id: "s", exifInfo: { exifImageWidth: 1000, exifImageHeight: 1000 } });
|
||||
const landscape = photo({ id: "l", width: 1600, height: 900 });
|
||||
const portrait = photo({ id: "p", width: 900, height: 1600 });
|
||||
const square = photo({ id: "s", width: 1000, height: 1000 });
|
||||
|
||||
expect(matchesOrientation(landscape, "quer")).toBe(true);
|
||||
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", () => {
|
||||
const unknown = photo({ id: "u", exifInfo: null });
|
||||
const unknown = photo({ id: "u" });
|
||||
expect(matchesOrientation(unknown, "quer")).toBe(false);
|
||||
expect(matchesOrientation(unknown, "hoch")).toBe(false);
|
||||
});
|
||||
|
||||
test("matchesYear compares against localDateTime then fileCreatedAt", () => {
|
||||
expect(matchesYear(photo({ id: "a", localDateTime: "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: "c", localDateTime: null, fileCreatedAt: "2026-01-01T00:00:00.000Z" }), "2026")).toBe(true);
|
||||
expect(matchesYear(photo({ id: "d", localDateTime: null, fileCreatedAt: null }), "2026")).toBe(false);
|
||||
test("matchesYear compares against the gallery date", () => {
|
||||
expect(matchesYear(photo({ id: "a", takenAt: "2026-05-01T10:00:00.000Z" }), "2026")).toBe(true);
|
||||
expect(matchesYear(photo({ id: "b", takenAt: "2025-12-31T23:00:00.000Z" }), "2026")).toBe(false);
|
||||
expect(matchesYear(photo({ id: "c", takenAt: "2026-01-01T00:00:00.000Z" }), "2026")).toBe(true);
|
||||
expect(matchesYear(photo({ id: "d", takenAt: null }), "2026")).toBe(false);
|
||||
});
|
||||
|
||||
test("filterPhotos applies format and jahr together across the full set", () => {
|
||||
const items = [
|
||||
photo({ id: "l26", originalFileName: "land26", localDateTime: "2026-03-01", exifInfo: { exifImageWidth: 2, exifImageHeight: 1 } }),
|
||||
photo({ id: "p26", originalFileName: "port26", localDateTime: "2026-03-01", exifInfo: { exifImageWidth: 1, exifImageHeight: 2 } }),
|
||||
photo({ id: "l25", originalFileName: "land25", localDateTime: "2025-03-01", exifInfo: { exifImageWidth: 2, exifImageHeight: 1 } }),
|
||||
photo({ id: "l26", filename: "land26", takenAt: "2026-03-01", width: 2, height: 1 }),
|
||||
photo({ id: "p26", filename: "port26", takenAt: "2026-03-01", width: 1, height: 2 }),
|
||||
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"]);
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import type { ImmichAsset } from "@/modules/immich/types";
|
||||
|
||||
import { normalizePage } from "./catalog";
|
||||
import { normalizePage, type GalleryPhoto } from "./catalog";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export function matchesOrientation(asset: ImmichAsset, format: string): boolean {
|
||||
const width = asset.exifInfo?.exifImageWidth ?? 0;
|
||||
const height = asset.exifInfo?.exifImageHeight ?? 0;
|
||||
export function matchesOrientation(asset: GalleryPhoto, format: string): boolean {
|
||||
const width = asset.width ?? 0;
|
||||
const height = asset.height ?? 0;
|
||||
// Unknown dimensions can't satisfy a format filter — exclude rather than
|
||||
// show a portrait under "Querformat" (the original bug). `withExif: true`
|
||||
// keeps this rare in practice.
|
||||
// show a portrait under "Querformat".
|
||||
if (width <= 0 || height <= 0) return false;
|
||||
const isLandscape = width >= height;
|
||||
return format === "quer" ? isLandscape : !isLandscape;
|
||||
}
|
||||
|
||||
export function matchesYear(asset: ImmichAsset, jahr: string): boolean {
|
||||
const value = asset.localDateTime ?? asset.fileCreatedAt;
|
||||
export function matchesYear(asset: GalleryPhoto, jahr: string): boolean {
|
||||
const value = asset.takenAt;
|
||||
return value !== null && value.startsWith(jahr);
|
||||
}
|
||||
|
||||
export function filterPhotos(
|
||||
items: ImmichAsset[],
|
||||
items: GalleryPhoto[],
|
||||
filters: { format?: string; jahr?: string },
|
||||
): ImmichAsset[] {
|
||||
): GalleryPhoto[] {
|
||||
let filtered = items;
|
||||
if (filters.format) {
|
||||
filtered = filtered.filter((asset) => matchesOrientation(asset, filters.format!));
|
||||
@@ -43,14 +40,14 @@ export function filterPhotos(
|
||||
}
|
||||
|
||||
export type InAppPage = {
|
||||
items: ImmichAsset[];
|
||||
items: GalleryPhoto[];
|
||||
total: number;
|
||||
nextPage: number | null;
|
||||
previousPage: number | null;
|
||||
};
|
||||
|
||||
export function paginatePhotos(
|
||||
items: ImmichAsset[],
|
||||
items: GalleryPhoto[],
|
||||
page: unknown,
|
||||
pageSize: number,
|
||||
): { result: InAppPage; currentPage: number } {
|
||||
|
||||
@@ -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" });
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -9,14 +9,13 @@ import { IconChevronLeft, IconChevronRight, IconX } from "@sakaniui/react/icons"
|
||||
import { UsageDialog } from "@/components/download/usage-dialog";
|
||||
import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton";
|
||||
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";
|
||||
|
||||
type PhotoGalleryProps = Readonly<{
|
||||
albumId?: string;
|
||||
albumName: string;
|
||||
items: ImmichAsset[];
|
||||
items: GalleryPhoto[];
|
||||
downloadOptions?: EditorialDownloadOptions;
|
||||
/** Pre-selected asset ids, passed as a plain array (Sets don't cross the RSC boundary). */
|
||||
lightboxAssetIds?: string[];
|
||||
@@ -24,7 +23,6 @@ type PhotoGalleryProps = Readonly<{
|
||||
}>;
|
||||
|
||||
export function PhotoGallery({
|
||||
albumId,
|
||||
albumName,
|
||||
items,
|
||||
downloadOptions,
|
||||
@@ -70,18 +68,17 @@ export function PhotoGallery({
|
||||
<>
|
||||
<ul className="photo-gallery" aria-label={`Fotos aus ${albumName}`}>
|
||||
{items.map((asset, index) => {
|
||||
const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined);
|
||||
return (
|
||||
<li key={asset.id} className="photo-tile">
|
||||
<li key={`${asset.albumId}:${asset.id}`} className="photo-tile">
|
||||
<figure className="photo-tile-frame">
|
||||
<button
|
||||
className="photo-tile-trigger"
|
||||
type="button"
|
||||
onClick={() => setOpenIndex(index)}
|
||||
aria-label={`${asset.originalFileName} vergrößern`}
|
||||
aria-label={`${asset.filename} vergrößern`}
|
||||
>
|
||||
<img
|
||||
alt={asset.originalFileName}
|
||||
alt={asset.filename}
|
||||
className="photo-tile-image"
|
||||
loading="lazy"
|
||||
src={thumbnailUrl(asset.id)}
|
||||
@@ -90,17 +87,17 @@ export function PhotoGallery({
|
||||
</button>
|
||||
<div className="photo-tile-overlay">
|
||||
<figcaption className="photo-tile-caption">
|
||||
<span className="photo-tile-name">{asset.originalFileName}</span>
|
||||
{showAlbumName ? renderAlbumName(asset) : null}
|
||||
<span className="photo-tile-date">{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span>
|
||||
<span className="photo-tile-name">{asset.filename}</span>
|
||||
{showAlbumName && asset.albumName ? <span className="photo-tile-album">{asset.albumName}</span> : null}
|
||||
<span className="photo-tile-date">{formatDate(asset.takenAt)}</span>
|
||||
</figcaption>
|
||||
<div className="photo-tile-actions">
|
||||
<LightboxToggleButton assetId={asset.id} initialInLightbox={inLightbox.has(asset.id)} />
|
||||
{activeAlbumId && downloadOptions ? (
|
||||
{downloadOptions ? (
|
||||
<UsageDialog
|
||||
albumId={activeAlbumId}
|
||||
albumId={asset.albumId}
|
||||
assetId={asset.id}
|
||||
filename={asset.originalFileName}
|
||||
filename={asset.filename}
|
||||
newUsagePriceCents={downloadOptions.priceCents}
|
||||
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
|
||||
/>
|
||||
@@ -116,7 +113,6 @@ export function PhotoGallery({
|
||||
{openIndex !== null ? (
|
||||
<PhotoLightbox
|
||||
asset={items[openIndex]}
|
||||
albumId={albumId}
|
||||
downloadOptions={downloadOptions}
|
||||
inLightbox={inLightbox.has(items[openIndex].id)}
|
||||
hasPrev={openIndex > 0}
|
||||
@@ -131,8 +127,7 @@ export function PhotoGallery({
|
||||
}
|
||||
|
||||
type PhotoLightboxProps = Readonly<{
|
||||
asset: ImmichAsset;
|
||||
albumId?: string;
|
||||
asset: GalleryPhoto;
|
||||
downloadOptions?: EditorialDownloadOptions;
|
||||
inLightbox: boolean;
|
||||
hasPrev: boolean;
|
||||
@@ -144,7 +139,6 @@ type PhotoLightboxProps = Readonly<{
|
||||
|
||||
function PhotoLightbox({
|
||||
asset,
|
||||
albumId,
|
||||
downloadOptions,
|
||||
inLightbox,
|
||||
hasPrev,
|
||||
@@ -153,9 +147,8 @@ function PhotoLightbox({
|
||||
onPrev,
|
||||
onNext,
|
||||
}: PhotoLightboxProps) {
|
||||
const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined);
|
||||
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" />
|
||||
{hasPrev ? (
|
||||
<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" />
|
||||
) : null}
|
||||
<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">
|
||||
<span className="photo-tile-name">{asset.originalFileName}</span>
|
||||
<span className="photo-tile-date">{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span>
|
||||
<span className="photo-tile-name">{asset.filename}</span>
|
||||
<span className="photo-tile-date">{formatDate(asset.takenAt)}</span>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<div className="lightbox-actions">
|
||||
<LightboxToggleButton assetId={asset.id} initialInLightbox={inLightbox} />
|
||||
{activeAlbumId && downloadOptions ? (
|
||||
{downloadOptions ? (
|
||||
<UsageDialog
|
||||
albumId={activeAlbumId}
|
||||
albumId={asset.albumId}
|
||||
assetId={asset.id}
|
||||
filename={asset.originalFileName}
|
||||
filename={asset.filename}
|
||||
newUsagePriceCents={downloadOptions.priceCents}
|
||||
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
|
||||
/>
|
||||
@@ -186,17 +179,8 @@ function PhotoLightbox({
|
||||
);
|
||||
}
|
||||
|
||||
function aspectStyle(asset: ImmichAsset): CSSProperties {
|
||||
const width = asset.exifInfo?.exifImageWidth ?? 0;
|
||||
const height = asset.exifInfo?.exifImageHeight ?? 0;
|
||||
function aspectStyle(asset: GalleryPhoto): CSSProperties {
|
||||
const width = asset.width ?? 0;
|
||||
const height = asset.height ?? 0;
|
||||
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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -1,80 +1,49 @@
|
||||
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 { z } from "zod";
|
||||
|
||||
import { users } from "@/db/schema";
|
||||
import { accounts, users } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { validatePasswordPolicy } from "@/modules/security/password-policy";
|
||||
|
||||
export type AdminBootstrapInput = {
|
||||
email: string;
|
||||
name: string;
|
||||
password: string;
|
||||
};
|
||||
type AdminInput = { email: string; name: string; password: string };
|
||||
type AdminCredential = Omit<AdminInput, "password"> & { passwordHash: string };
|
||||
|
||||
export type AdminBootstrapAuth = {
|
||||
signUpEmail(input: { email: string; name: string; password: string }): Promise<{ user: { id: string } }>;
|
||||
sendVerificationEmail(input: { email: string }): Promise<void>;
|
||||
};
|
||||
export async function seedAdmin(
|
||||
input: AdminInput,
|
||||
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 = {
|
||||
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" };
|
||||
},
|
||||
};
|
||||
await insert({ email, name, passwordHash: await hashPassword(input.password) });
|
||||
}
|
||||
|
||||
export function createAdminBootstrapRepository(database: NodePgDatabase<typeof schema>): AdminBootstrapRepository {
|
||||
return {
|
||||
async countAdmins() {
|
||||
const [result] = await database
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(users)
|
||||
.where(eq(users.role, "ADMIN"));
|
||||
return result.count;
|
||||
},
|
||||
async findUserByEmail(email) {
|
||||
const [user] = await database
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(eq(users.email, email))
|
||||
.limit(1);
|
||||
return user;
|
||||
},
|
||||
async promoteUserToAdmin(userId) {
|
||||
await database
|
||||
.update(users)
|
||||
.set({ role: "ADMIN", updatedAt: new Date() })
|
||||
.where(eq(users.id, userId));
|
||||
},
|
||||
};
|
||||
export function insertAdminCredential(database: NodePgDatabase<typeof schema>, credential: AdminCredential) {
|
||||
return database.transaction(async (transaction) => {
|
||||
const [existing] = await transaction.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(sql`lower(${users.email}) = ${credential.email}`)
|
||||
.limit(1);
|
||||
if (existing) throw new Error("Admin seed email is already registered");
|
||||
|
||||
const [user] = await transaction
|
||||
.insert(users)
|
||||
.values({ email: credential.email, name: credential.name, role: "ADMIN", emailVerified: true })
|
||||
.returning({ id: users.id });
|
||||
|
||||
await transaction.insert(accounts).values({
|
||||
userId: user.id,
|
||||
accountId: user.id,
|
||||
providerId: "credential",
|
||||
password: credential.passwordHash,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -121,3 +121,85 @@ test("keeps Better Auth login limits separate for clients forwarded by Zoraxy",
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import "server-only";
|
||||
|
||||
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 { betterAuth, type BetterAuthOptions } from "better-auth";
|
||||
import { twoFactor } from "better-auth/plugins";
|
||||
@@ -27,6 +27,13 @@ import {
|
||||
type RegistrationInput,
|
||||
} 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 = {
|
||||
enabled: true,
|
||||
storage: "memory",
|
||||
@@ -91,13 +98,19 @@ export function createPortalAuth({
|
||||
},
|
||||
plugins: [
|
||||
twoFactor({
|
||||
// TOTP + backup codes only: without `otpOptions.sendOTP` no OTP-e-mail
|
||||
// surface exists, and trust-device stays off to keep the attack area
|
||||
// small. Backup codes stay encrypted (plugin default).
|
||||
// TOTP + backup codes only. Expire new trust-device records immediately.
|
||||
trustDeviceMaxAge: 0,
|
||||
}),
|
||||
],
|
||||
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: {
|
||||
enabled: true,
|
||||
@@ -127,8 +140,12 @@ export function createPortalAuth({
|
||||
databaseHooks: {
|
||||
session: {
|
||||
create: {
|
||||
async before(session) {
|
||||
return registrationRepository.canCreateSession(session.userId);
|
||||
async before(session, ctx) {
|
||||
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 };
|
||||
}
|
||||
|
||||
export function createPasswordPolicyHook() {
|
||||
function createAuthSecurityHook() {
|
||||
// Applies the shared policy to password-reset and change-password flows,
|
||||
// which bypass the registration validation. Registration is covered by
|
||||
// validateRegistration(); sign-up additionally enforces Better Auth's
|
||||
// minPasswordLength.
|
||||
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") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ test("accepts an admin session with two-factor enabled", async () => {
|
||||
const guard = createPrincipalGuard({
|
||||
getSession: async () => ({
|
||||
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,
|
||||
});
|
||||
@@ -80,7 +80,7 @@ test("rejects stale sessions for destructive operations (step-up)", async () =>
|
||||
const guard = createPrincipalGuard({
|
||||
getSession: async () => ({
|
||||
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,
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import "server-only";
|
||||
|
||||
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 { editorialAccounts } from "@/db/schema";
|
||||
import { accountStatuses } from "@/db/schema/editorials";
|
||||
@@ -18,7 +18,7 @@ export type PortalPrincipal = {
|
||||
|
||||
type Session = {
|
||||
user: { id: string; role: "ADMIN" | "EDITORIAL"; twoFactorEnabled?: boolean };
|
||||
session: { createdAt?: Date };
|
||||
session: { createdAt?: Date; token?: string };
|
||||
} | null;
|
||||
type EditorialAccount = { id: string; status: AccountStatus } | null;
|
||||
|
||||
@@ -73,6 +73,9 @@ export function createPrincipalGuard({ getSession, getAccount }: PrincipalGuardD
|
||||
if (session.user.role !== "ADMIN") {
|
||||
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) {
|
||||
throw new PrincipalAuthorizationError("TWO_FACTOR_REQUIRED");
|
||||
}
|
||||
@@ -148,7 +151,7 @@ export const principalGuard = createPrincipalGuard({
|
||||
twoFactorEnabled:
|
||||
(session.user as { twoFactorEnabled?: unknown }).twoFactorEnabled === true,
|
||||
},
|
||||
session: { createdAt: session.session.createdAt },
|
||||
session: { createdAt: session.session.createdAt, token: session.session.token },
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
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", () => ({
|
||||
authClient: { resetPassword, signIn: { email: signInEmail } },
|
||||
authClient: { resetPassword, signIn: { email: signInEmail }, twoFactor: { enable: enableTwoFactor } },
|
||||
}));
|
||||
|
||||
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")!);
|
||||
|
||||
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(
|
||||
"/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")!);
|
||||
|
||||
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.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([]);
|
||||
});
|
||||
@@ -114,11 +114,9 @@ export function LoginForm() {
|
||||
setPending(true);
|
||||
setError(undefined);
|
||||
|
||||
const formData = new FormData(event.currentTarget);
|
||||
|
||||
if (awaitingTwoFactor) {
|
||||
const result = await authClient.twoFactor.verifyTotp({
|
||||
code: readText(formData, "totp").replace(/\s+/g, ""),
|
||||
code: readText(event.currentTarget, "totp").replace(/\s+/g, ""),
|
||||
});
|
||||
if (result.error) {
|
||||
setError("Der Code ist ungültig oder abgelaufen. Bitte erneut versuchen.");
|
||||
@@ -130,8 +128,8 @@ export function LoginForm() {
|
||||
}
|
||||
|
||||
const result = await authClient.signIn.email({
|
||||
email: readText(formData, "email").trim().toLowerCase(),
|
||||
password: readText(formData, "password"),
|
||||
email: readText(event.currentTarget, "email").trim().toLowerCase(),
|
||||
password: readText(event.currentTarget, "password"),
|
||||
callbackURL: "/",
|
||||
});
|
||||
|
||||
@@ -156,11 +154,11 @@ export function LoginForm() {
|
||||
// TOTP field and would show the typed password in clear text.
|
||||
if (awaitingTwoFactor) {
|
||||
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)]">
|
||||
Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein.
|
||||
</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} />
|
||||
<Button disabled={pending} type="submit">
|
||||
{pending ? "Code wird geprüft …" : "Anmelden"}
|
||||
@@ -170,9 +168,9 @@ export function LoginForm() {
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-4" key="credentials" onSubmit={submit}>
|
||||
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" />
|
||||
<Input label="Passwort" autoComplete="current-password" name="password" required type="password" />
|
||||
<form className="flex flex-col gap-4" key="credentials" method="post" onSubmit={submit}>
|
||||
<Input label="E-Mail-Adresse" autoComplete="email" id="email" required type="email" />
|
||||
<Input label="Passwort" autoComplete="current-password" id="password" required type="password" />
|
||||
<FieldError message={error} />
|
||||
<Button disabled={pending} type="submit">
|
||||
{pending ? "Anmeldung wird geprüft …" : "Anmelden"}
|
||||
@@ -188,11 +186,9 @@ export function PasswordResetRequestForm() {
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
|
||||
try {
|
||||
await authClient.requestPasswordReset({
|
||||
email: readText(formData, "email").trim().toLowerCase(),
|
||||
email: readText(event.currentTarget, "email").trim().toLowerCase(),
|
||||
redirectTo: `${window.location.origin}/passwort-zuruecksetzen`,
|
||||
});
|
||||
} finally {
|
||||
@@ -210,8 +206,8 @@ export function PasswordResetRequestForm() {
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-4" onSubmit={submit}>
|
||||
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" />
|
||||
<form className="flex flex-col gap-4" method="post" onSubmit={submit}>
|
||||
<Input label="E-Mail-Adresse" autoComplete="email" id="email" required type="email" />
|
||||
<Button disabled={pending} type="submit">
|
||||
{pending ? "Anfrage wird gesendet …" : "Link anfordern"}
|
||||
</Button>
|
||||
@@ -228,11 +224,9 @@ export function PasswordResetForm({ token }: { token?: string }) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
setError(undefined);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
|
||||
try {
|
||||
const result = await authClient.resetPassword({
|
||||
newPassword: readText(formData, "password"),
|
||||
newPassword: readText(event.currentTarget, "password"),
|
||||
token,
|
||||
});
|
||||
if (result.error) {
|
||||
@@ -262,8 +256,8 @@ export function PasswordResetForm({ token }: { token?: string }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-4" onSubmit={submit}>
|
||||
<Input label="Neues Passwort" autoComplete="new-password" minLength={12} name="password" required type="password" />
|
||||
<form action="/passwort-zuruecksetzen" className="flex flex-col gap-4" method="post" onSubmit={submit}>
|
||||
<Input label="Neues Passwort" autoComplete="new-password" minLength={12} id="password" required type="password" />
|
||||
<FieldError message={error} />
|
||||
<Button disabled={pending} type="submit">
|
||||
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
|
||||
@@ -299,7 +293,8 @@ function FieldError({ message }: { message?: string }) {
|
||||
return message ? <Alert color="danger" description={message} /> : null;
|
||||
}
|
||||
|
||||
function readText(formData: FormData, name: string): string {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : "";
|
||||
function readText(form: HTMLFormElement, id: string): string {
|
||||
// The inputs have IDs for the SDK flow and no names for native submission.
|
||||
const input = form.elements.namedItem(id);
|
||||
return input instanceof HTMLInputElement ? input.value : "";
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
createRegistrationService,
|
||||
type RegistrationInput,
|
||||
} from "./registration";
|
||||
import { createAdminBootstrapService } from "./admin-bootstrap";
|
||||
|
||||
const validRegistration: RegistrationInput = {
|
||||
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" });
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { assertOriginalAccess } from "@/modules/albums/photo-access";
|
||||
import { db } from "@/db/client";
|
||||
import { downloadEvents, editorialAccounts, usages } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
@@ -60,12 +61,13 @@ export function createDownloadService({ repository }: { repository: RepeatDownlo
|
||||
|
||||
export function createRepeatDownloadRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
assertAccess: typeof assertOriginalAccess,
|
||||
): RepeatDownloadRepository {
|
||||
return {
|
||||
async createRepeatIntent(input) {
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
try {
|
||||
return await createRepeatIntentTransaction(database, input);
|
||||
return await createRepeatIntentTransaction(database, input, assertAccess);
|
||||
} catch (error) {
|
||||
if (!(error instanceof RepeatIdempotencyRaceError) || attempt === 1) throw error;
|
||||
}
|
||||
@@ -78,6 +80,7 @@ export function createRepeatDownloadRepository(
|
||||
async function createRepeatIntentTransaction(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
input: RepeatIntentInput,
|
||||
assertAccess: typeof assertOriginalAccess,
|
||||
): Promise<PersistedRepeatIntent> {
|
||||
return database.transaction(async (transaction) => {
|
||||
await lockEditorialAccounting(transaction, input.editorialId);
|
||||
@@ -108,6 +111,7 @@ async function createRepeatIntentTransaction(
|
||||
.select({
|
||||
id: usages.id,
|
||||
assetId: usages.immichAssetId,
|
||||
albumId: usages.immichAlbumIdSnapshot,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(usages)
|
||||
@@ -128,6 +132,7 @@ async function createRepeatIntentTransaction(
|
||||
if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) {
|
||||
throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
}
|
||||
await assertAccess(input.editorialId, usage.assetId, usage.albumId, transaction);
|
||||
if (existing) return asRepeatIntent(existing);
|
||||
|
||||
const authorizedAt = new Date();
|
||||
@@ -185,7 +190,7 @@ function asRepeatIntent(intent: PersistedDownloadIntent): PersistedRepeatIntent
|
||||
class RepeatIdempotencyRaceError extends Error {}
|
||||
|
||||
export const downloadService = createDownloadService({
|
||||
repository: createRepeatDownloadRepository(db),
|
||||
repository: createRepeatDownloadRepository(db, assertOriginalAccess),
|
||||
});
|
||||
|
||||
export const createRepeatDownload = downloadService.createRepeatDownload;
|
||||
@@ -24,6 +24,7 @@ export type ClaimedDownload = {
|
||||
id: string;
|
||||
usageId: string;
|
||||
assetId: string;
|
||||
albumId: string;
|
||||
filename: string;
|
||||
intentKind: "new_usage" | "repeat_download" | "legacy";
|
||||
};
|
||||
@@ -160,6 +161,8 @@ export function createDownloadDeliveryRepository(
|
||||
const [usage] = await transaction
|
||||
.select({
|
||||
filename: usages.filenameSnapshot,
|
||||
assetId: usages.immichAssetId,
|
||||
albumId: usages.immichAlbumIdSnapshot,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(usages)
|
||||
@@ -171,7 +174,7 @@ export function createDownloadDeliveryRepository(
|
||||
)
|
||||
.for("update")
|
||||
.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 deliveredOriginal =
|
||||
@@ -208,6 +211,7 @@ export function createDownloadDeliveryRepository(
|
||||
id: candidate.id,
|
||||
usageId: candidate.usageId,
|
||||
assetId: candidate.assetId,
|
||||
albumId: usage.albumId,
|
||||
filename: usage.filename,
|
||||
intentKind,
|
||||
},
|
||||
@@ -603,6 +607,7 @@ export function createEditorialDownloadOptionsLoader(
|
||||
return async function loadOptions(
|
||||
editorialId: string,
|
||||
assetIds: string[],
|
||||
allowPriorUsage?: (assetId: string, albumId: string) => Promise<boolean>,
|
||||
): Promise<EditorialDownloadOptions> {
|
||||
const normalizedEditorialId = normalizeUuid(editorialId);
|
||||
const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))];
|
||||
@@ -636,6 +641,7 @@ export function createEditorialDownloadOptionsLoader(
|
||||
id: usages.id,
|
||||
assetId: usages.immichAssetId,
|
||||
purpose: usages.purpose,
|
||||
albumId: usages.immichAlbumIdSnapshot,
|
||||
createdAt: usages.createdAt,
|
||||
})
|
||||
.from(usages)
|
||||
@@ -650,7 +656,13 @@ export function createEditorialDownloadOptionsLoader(
|
||||
.orderBy(desc(usages.createdAt), desc(usages.id))
|
||||
.limit(DOWNLOAD_OPTIONS_MAX_USAGES);
|
||||
const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {};
|
||||
const allowed = new Map<string, boolean>();
|
||||
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({
|
||||
id: row.id,
|
||||
purpose: row.purpose,
|
||||
|
||||
@@ -374,9 +374,6 @@ export function createImmichClient({
|
||||
size: input.size,
|
||||
// Default on: exifImageWidth/exifImageHeight populate the
|
||||
// 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,
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db } from "@/db/client";
|
||||
import { lightboxItems } from "@/db/schema";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichAsset } from "@/modules/immich/types";
|
||||
|
||||
export type LightboxItem = {
|
||||
assetId: string;
|
||||
addedAt: Date;
|
||||
asset?: ImmichAsset; // populated if joined
|
||||
};
|
||||
|
||||
export const lightboxService = {
|
||||
|
||||
@@ -39,10 +39,13 @@ function createRepository() {
|
||||
) {
|
||||
const key = `${input.editorialId}:${input.idempotencyKey}`;
|
||||
const existing = intents.get(key);
|
||||
if (existing) return existing;
|
||||
if (status !== "active") {
|
||||
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
||||
}
|
||||
if (existing) {
|
||||
await refreshCurrentAsset?.();
|
||||
return existing;
|
||||
}
|
||||
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
|
||||
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(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 () => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import "server-only";
|
||||
|
||||
import { isAssetInAlbum } from "@/modules/albums/photo-access";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, desc, eq, exists, inArray, isNull, sql } from "drizzle-orm";
|
||||
@@ -44,6 +46,7 @@ export type BillableIntentInput = {
|
||||
filename: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
maxPriceCents?: number;
|
||||
idempotencyKey: string;
|
||||
requestFingerprint: string;
|
||||
};
|
||||
@@ -88,10 +91,11 @@ export function createUsageService({
|
||||
albumId: input.albumId,
|
||||
purpose: input.purpose,
|
||||
reference: input.reference ?? null,
|
||||
maxPriceCents: input.maxPriceCents,
|
||||
});
|
||||
|
||||
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 album = await loadRequestedAlbum(immich, input.assetId, input.albumId);
|
||||
@@ -120,7 +124,7 @@ export function createUsageService({
|
||||
export function createUsageServiceRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): UsageRepository {
|
||||
return {
|
||||
const repository: UsageRepository = {
|
||||
findIntent(editorialId, idempotencyKey) {
|
||||
return findPersistedIntent(database, editorialId, idempotencyKey);
|
||||
},
|
||||
@@ -134,7 +138,10 @@ export function createUsageServiceRepository(
|
||||
input.editorialId,
|
||||
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
|
||||
.select({
|
||||
@@ -152,13 +159,6 @@ export function createUsageServiceRepository(
|
||||
if (!editorial || editorial.status !== "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
|
||||
.select({ id: albumGrants.id })
|
||||
.from(albumGrants)
|
||||
@@ -172,6 +172,17 @@ export function createUsageServiceRepository(
|
||||
.for("update")
|
||||
.limit(1);
|
||||
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!;
|
||||
|
||||
@@ -210,9 +221,10 @@ export function createUsageServiceRepository(
|
||||
}
|
||||
}
|
||||
|
||||
// This is the last cross-system authorization snapshot available to the
|
||||
// portal. Immich may still change after it returns, but no portal work is
|
||||
// allowed between this refresh and the accounting inserts.
|
||||
if (input.maxPriceCents !== undefined && priceCents > input.maxPriceCents) {
|
||||
throw new UsageAccountingError("INVALID_PRICE");
|
||||
}
|
||||
// Refresh Immich membership immediately before inserting the accounting records.
|
||||
const currentAsset = await refreshCurrentAsset();
|
||||
|
||||
const createdAt = new Date();
|
||||
@@ -285,7 +297,7 @@ export function createUsageServiceRepository(
|
||||
input.editorialId,
|
||||
input.idempotencyKey,
|
||||
);
|
||||
if (existing) return existing;
|
||||
if (existing) return repository.createBillableIntent(input, refreshCurrentAsset);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -321,18 +333,24 @@ export function createUsageServiceRepository(
|
||||
return rows.map((row) => ({ ...row, reference: row.reference ?? undefined }));
|
||||
},
|
||||
};
|
||||
return repository;
|
||||
}
|
||||
|
||||
function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput {
|
||||
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
|
||||
const purpose = normalizeRequiredText(input.purpose, 3, 200);
|
||||
const reference = normalizeOptionalText(input.reference, 200);
|
||||
if (input.maxPriceCents !== undefined &&
|
||||
(!Number.isSafeInteger(input.maxPriceCents) || input.maxPriceCents < 0)) {
|
||||
throw new UsageAccountingError("INVALID_INPUT");
|
||||
}
|
||||
return {
|
||||
editorialId: normalizeUuid(input.editorialId),
|
||||
assetId: normalizeUuid(input.assetId),
|
||||
albumId: normalizeUuid(input.albumId),
|
||||
purpose,
|
||||
...(reference === undefined ? {} : { reference }),
|
||||
...(input.maxPriceCents === undefined ? {} : { maxPriceCents: input.maxPriceCents }),
|
||||
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) {
|
||||
let asset: Awaited<ReturnType<UsageImmich["getAsset"]>>;
|
||||
try {
|
||||
|
||||
@@ -6,6 +6,7 @@ export type CreateNewUsageInput = {
|
||||
albumId: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
maxPriceCents?: number;
|
||||
idempotencyKey: string;
|
||||
};
|
||||
|
||||
@@ -67,6 +68,7 @@ type FingerprintPayload =
|
||||
albumId: string;
|
||||
purpose: string;
|
||||
reference: string | null;
|
||||
maxPriceCents?: number;
|
||||
}
|
||||
| {
|
||||
kind: "repeat_download";
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
@@ -66,7 +66,7 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a
|
||||
});
|
||||
|
||||
const repeats = createDownloadService({
|
||||
repository: createRepeatDownloadRepository(testDb.database),
|
||||
repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
|
||||
});
|
||||
await expect(
|
||||
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 () => {
|
||||
const seed = await testDb.seedEditorialWithUsage();
|
||||
const repeats = createDownloadService({
|
||||
repository: createRepeatDownloadRepository(testDb.database),
|
||||
repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
|
||||
});
|
||||
|
||||
await expect(
|
||||
@@ -106,7 +106,7 @@ test.each(["completed", "interrupted"] as const)(
|
||||
await delivery.markInterrupted(originalId, 80);
|
||||
}
|
||||
const repeats = createDownloadService({
|
||||
repository: createRepeatDownloadRepository(testDb.database),
|
||||
repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
|
||||
});
|
||||
|
||||
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.claimAuthorized(seed.editorialId, failingNewId);
|
||||
const repeats = createDownloadService({
|
||||
repository: createRepeatDownloadRepository(testDb.database),
|
||||
repository: createRepeatDownloadRepository(testDb.database, async () => undefined),
|
||||
});
|
||||
const repeatKey = randomUUID();
|
||||
const repeatInput = {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
createDownloadService,
|
||||
createRepeatDownloadRepository,
|
||||
} from "@/modules/downloads/service";
|
||||
import { assertOriginalAccess } from "@/modules/albums/photo-access";
|
||||
import { requestFingerprint } from "@/modules/usages/types";
|
||||
import { startPostgres } from "./postgres";
|
||||
|
||||
@@ -59,7 +60,8 @@ function createServices() {
|
||||
immich,
|
||||
}),
|
||||
downloadService: createDownloadService({
|
||||
repository: createRepeatDownloadRepository(database),
|
||||
repository: createRepeatDownloadRepository(database, (editorialId, assetId, albumId, tx) =>
|
||||
assertOriginalAccess(editorialId, assetId, albumId, tx, immich)),
|
||||
}),
|
||||
immich,
|
||||
};
|
||||
@@ -240,7 +242,7 @@ test("rechecks exact album membership after database locks before inserting", as
|
||||
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 input = newInput(editorialId);
|
||||
const immich = createServices().immich;
|
||||
@@ -267,7 +269,7 @@ test("returns a winner committed while waiting before later mutable state is che
|
||||
try {
|
||||
const pending = usageService.createNewUsage(input);
|
||||
await fastMiss;
|
||||
const winner = await insertWinner(
|
||||
await insertWinner(
|
||||
locker,
|
||||
input,
|
||||
requestFingerprint({
|
||||
@@ -284,12 +286,7 @@ test("returns a winner committed while waiting before later mutable state is che
|
||||
]);
|
||||
await locker.query("commit");
|
||||
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
id: winner.eventId,
|
||||
usageId: winner.usageId,
|
||||
authorizedAt: winner.authorizedAt,
|
||||
billable: true,
|
||||
});
|
||||
await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" });
|
||||
expect(immich.getAlbum).toHaveBeenCalledTimes(1);
|
||||
expect(immich.getAsset).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
@@ -494,7 +491,7 @@ test("rechecks suspension after an idempotent repeat winner commits", async () =
|
||||
idempotencyKey: randomUUID(),
|
||||
};
|
||||
const downloadService = createDownloadService({
|
||||
repository: createRepeatDownloadRepository(database),
|
||||
repository: createRepeatDownloadRepository(database, async () => undefined),
|
||||
});
|
||||
const eventId = randomUUID();
|
||||
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));
|
||||
}
|
||||
|
||||
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 });
|
||||
});
|
||||
Reference in new issue
Block a user