From 0d939593c8b96b675ca14488865c376ae004cba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Tue, 25 Aug 2026 02:30:58 +0200 Subject: [PATCH] feat: enforce admin 2FA, step-up auth, stronger password policy Implements OWASP audit recommendations P1-P3: P1 - Two-factor authentication (TOTP) mandatory for admins: - better-auth twoFactor plugin; new two_factor table + user flag (migration 0010, MUST run before deploying the app) - requireAdmin throws TWO_FACTOR_REQUIRED without a finished setup; pages redirect to the new /zwei-faktor wizard which uses a weak guard (allowWithoutTwoFactor) so admins can never lock themselves out. Wizard lives outside /admin to avoid layout redirect loops. - login flow handles twoFactorRedirect and asks for the TOTP code; backup codes are shown once during enablement P2 - Step-up for destructive operations (ASVS 2.5.4): - hardDeleteEditorialAction and resetUsageDataAction reject sessions older than 15 minutes (SESSION_STALE) with actionable German messages instead of throwing opaque digests P3 - Password policy (NIST 800-63B): - minimum length raised from 8 to 12 plus common-password denylist, enforced for registration AND reset/change via a before-hook --- AI_MEMORY.md | 5 + drizzle/0010_two-factor.sql | 10 + drizzle/meta/0010_snapshot.json | 1934 ++++++++++++++++++ drizzle/meta/_journal.json | 9 +- src/app/admin/access.ts | 3 +- src/app/admin/redaktionen/[id]/actions.ts | 58 +- src/app/zwei-faktor/access.ts | 17 + src/app/zwei-faktor/page.tsx | 33 + src/app/zwei-faktor/wizard.tsx | 207 ++ src/db/schema/auth.ts | 15 + src/modules/auth/auth.ts | 53 +- src/modules/auth/client.ts | 5 +- src/modules/auth/page-access.ts | 15 +- src/modules/auth/principal.test.ts | 47 + src/modules/auth/principal.ts | 49 +- src/modules/auth/public-forms.tsx | 53 +- src/modules/auth/registration.ts | 9 +- src/modules/editorials/DangerZone.tsx | 17 +- src/modules/security/password-policy.test.ts | 27 + src/modules/security/password-policy.ts | 76 + 20 files changed, 2613 insertions(+), 29 deletions(-) create mode 100644 drizzle/0010_two-factor.sql create mode 100644 drizzle/meta/0010_snapshot.json create mode 100644 src/app/zwei-faktor/access.ts create mode 100644 src/app/zwei-faktor/page.tsx create mode 100644 src/app/zwei-faktor/wizard.tsx create mode 100644 src/modules/security/password-policy.test.ts create mode 100644 src/modules/security/password-policy.ts diff --git a/AI_MEMORY.md b/AI_MEMORY.md index 511860b..e1ec8e2 100644 --- a/AI_MEMORY.md +++ b/AI_MEMORY.md @@ -41,3 +41,8 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her ## 6. Admin-Bereich & Freigaben - **Redaktions-Freigabe:** Wenn eine Redaktion den Status `pending_approval` hat, wird sie im Admin-Detail-Dashboard über die `ApproveForm` freigegeben. In diesem Schritt *muss* der Admin zwingend einen individuellen Nettopreis für die Redaktion festlegen. Ohne das Setzen des Preises bleibt die Redaktion gesperrt. + +## 7. Auth-Härtung (Stand 2026) +- **Zwei-Faktor (TOTP) für Admins Pflicht:** Better-Auth-`twoFactor`-Plugin aktiviert; `requireAdmin` (principal.ts) wirft `TWO_FACTOR_REQUIRED`, wenn `user.two_factor_enabled` false ist. `requirePageAccess` leitet dann auf `/zwei-faktor` weiter (Wizard LIEGT AUSSERHALB von `/admin`, sonst Redirect-Loop mit dem Layout-Guard). Der Wizard nutzt den schwachen Guard `requireAdminForSetup`/`requireTwoFactorSetupPage` (`allowWithoutTwoFactor: true`). Login-Challenge: `signIn.email` antwortet mit `twoFactorRedirect: true` → LoginForm fragt TOTP-Code ab (`authClient.twoFactor.verifyTotp`). Schema: Tabelle `two_factor` + Spalte `user.two_factor_enabled` (Migration 0010). +- **Step-up für destruktive Aktionen:** `hardDeleteEditorialAction` und `resetUsageDataAction` verlangen Sessions jünger als `DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS` (15 min), sonst `SESSION_STALE` → deutsche Meldung im UI. Beide Actions geben `{ok,message}` zurück statt zu werfen. +- **Passwort-Policy:** `MIN_PASSWORD_LENGTH = 12` + Common-Password-Denylist in `src/modules/security/password-policy.ts`. Gilt für Registrierung (validateRegistration) UND Passwort-Reset/-Änderung (Better-Auth-`hooks.before`-Middleware in auth.ts; wirft APIError BAD_REQUEST mit deutscher Message). diff --git a/drizzle/0010_two-factor.sql b/drizzle/0010_two-factor.sql new file mode 100644 index 0000000..bc4c98a --- /dev/null +++ b/drizzle/0010_two-factor.sql @@ -0,0 +1,10 @@ +CREATE TABLE "two_factor" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" uuid NOT NULL, + "secret" text NOT NULL, + "backup_codes" text, + CONSTRAINT "two_factor_user_id_unique" UNIQUE("user_id") +); +--> statement-breakpoint +ALTER TABLE "user" ADD COLUMN "two_factor_enabled" boolean DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE "two_factor" ADD CONSTRAINT "two_factor_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action; \ No newline at end of file diff --git a/drizzle/meta/0010_snapshot.json b/drizzle/meta/0010_snapshot.json new file mode 100644 index 0000000..907d16a --- /dev/null +++ b/drizzle/meta/0010_snapshot.json @@ -0,0 +1,1934 @@ +{ + "id": "cd360b53-1792-46ce-8d67-8e359c344db5", + "prevId": "6cdb9f0f-04af-4cee-a915-117b10beeead", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album_grants": { + "name": "album_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_album_id": { + "name": "immich_album_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "granted_by_user_id": { + "name": "granted_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_grants_editorial_account_id_idx": { + "name": "album_grants_editorial_account_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_grants_immich_album_id_idx": { + "name": "album_grants_immich_album_id_idx", + "columns": [ + { + "expression": "immich_album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_grants_editorial_active_album_unique": { + "name": "album_grants_editorial_active_album_unique", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"immich_album_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"album_grants\".\"revoked_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "album_grants_editorial_account_id_editorial_accounts_id_fk": { + "name": "album_grants_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "album_grants", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "album_grants_granted_by_user_id_user_id_fk": { + "name": "album_grants_granted_by_user_id_user_id_fk", + "tableFrom": "album_grants", + "tableTo": "user", + "columnsFrom": [ + "granted_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "album_grants_immich_album_id_uuid_check": { + "name": "album_grants_immich_album_id_uuid_check", + "value": "\"album_grants\".\"immich_album_id\" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + } + }, + "isRLSEnabled": false + }, + "public.audit_events": { + "name": "audit_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "previous_values": { + "name": "previous_values", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "new_values": { + "name": "new_values", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "audit_events_actor_user_id_user_id_fk": { + "name": "audit_events_actor_user_id_user_id_fk", + "tableFrom": "audit_events", + "tableTo": "user", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.two_factor": { + "name": "two_factor", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "backup_codes": { + "name": "backup_codes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "two_factor_user_id_user_id_fk": { + "name": "two_factor_user_id_user_id_fk", + "tableFrom": "two_factor", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "two_factor_user_id_unique": { + "name": "two_factor_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "portal_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'EDITORIAL'" + }, + "two_factor_enabled": { + "name": "two_factor_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_auto_rules": { + "name": "album_auto_rules", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "keyword": { + "name": "keyword", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_auto_rules_editorial_account_id_keyword_idx": { + "name": "album_auto_rules_editorial_account_id_keyword_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"keyword\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "album_auto_rules_editorial_account_id_editorial_accounts_id_fk": { + "name": "album_auto_rules_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "album_auto_rules", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "album_auto_rules_created_by_user_id_user_id_fk": { + "name": "album_auto_rules_created_by_user_id_user_id_fk", + "tableFrom": "album_auto_rules", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.billing_report_items": { + "name": "billing_report_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "billing_report_id": { + "name": "billing_report_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id_snapshot": { + "name": "immich_asset_id_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename_snapshot": { + "name": "filename_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "album_name_snapshot": { + "name": "album_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose_snapshot": { + "name": "purpose_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_reference_snapshot": { + "name": "internal_reference_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "billing_report_items_report_usage_unique": { + "name": "billing_report_items_report_usage_unique", + "columns": [ + { + "expression": "billing_report_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "billing_report_items_billing_report_id_billing_reports_id_fk": { + "name": "billing_report_items_billing_report_id_billing_reports_id_fk", + "tableFrom": "billing_report_items", + "tableTo": "billing_reports", + "columnsFrom": [ + "billing_report_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_report_items_usage_id_usages_id_fk": { + "name": "billing_report_items_usage_id_usages_id_fk", + "tableFrom": "billing_report_items", + "tableTo": "usages", + "columnsFrom": [ + "usage_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.billing_reports": { + "name": "billing_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "report_number": { + "name": "report_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "period_starts_at": { + "name": "period_starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "period_ends_at": { + "name": "period_ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "billing_address_snapshot": { + "name": "billing_address_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "invoice_number": { + "name": "invoice_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "net_total_cents": { + "name": "net_total_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "flatrate_cents_snapshot": { + "name": "flatrate_cents_snapshot", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "pdf": { + "name": "pdf", + "type": "bytea", + "primaryKey": false, + "notNull": false + }, + "pdf_sha256": { + "name": "pdf_sha256", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finalized_at": { + "name": "finalized_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancellation_reason": { + "name": "cancellation_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cancelled_by_user_id": { + "name": "cancelled_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "billing_reports_report_number_unique": { + "name": "billing_reports_report_number_unique", + "columns": [ + { + "expression": "report_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "billing_reports_invoice_number_unique": { + "name": "billing_reports_invoice_number_unique", + "columns": [ + { + "expression": "invoice_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "billing_reports_editorial_account_id_editorial_accounts_id_fk": { + "name": "billing_reports_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "billing_reports", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_reports_created_by_user_id_user_id_fk": { + "name": "billing_reports_created_by_user_id_user_id_fk", + "tableFrom": "billing_reports", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_reports_cancelled_by_user_id_user_id_fk": { + "name": "billing_reports_cancelled_by_user_id_user_id_fk", + "tableFrom": "billing_reports", + "tableTo": "user", + "columnsFrom": [ + "cancelled_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "billing_reports_pdf_sha256_hex_check": { + "name": "billing_reports_pdf_sha256_hex_check", + "value": "\"billing_reports\".\"pdf_sha256\" ~ '^[0-9a-f]{64}$'" + }, + "billing_reports_final_pdf_check": { + "name": "billing_reports_final_pdf_check", + "value": "\"billing_reports\".\"status\" <> 'final' OR (\"billing_reports\".\"pdf\" IS NOT NULL AND \"billing_reports\".\"pdf_sha256\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.billing_address_versions": { + "name": "billing_address_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_name": { + "name": "contact_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address_line_1": { + "name": "address_line_1", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address_line_2": { + "name": "address_line_2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "postal_code": { + "name": "postal_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "city": { + "name": "city", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "country_code": { + "name": "country_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "valid_from": { + "name": "valid_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "superseded_by_id": { + "name": "superseded_by_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "billing_address_versions_editorial_account_id_editorial_accounts_id_fk": { + "name": "billing_address_versions_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_address_versions_superseded_by_id_billing_address_versions_id_fk": { + "name": "billing_address_versions_superseded_by_id_billing_address_versions_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "billing_address_versions", + "columnsFrom": [ + "superseded_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_address_versions_created_by_user_id_user_id_fk": { + "name": "billing_address_versions_created_by_user_id_user_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.editorial_accounts": { + "name": "editorial_accounts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_name": { + "name": "contact_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "login_email": { + "name": "login_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "account_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending_email'" + }, + "current_price_cents": { + "name": "current_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "flatrate_active": { + "name": "flatrate_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "flatrate_price_cents": { + "name": "flatrate_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "flatrate_asset_limit": { + "name": "flatrate_asset_limit", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "approval_notice_status": { + "name": "approval_notice_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'not_requested'" + }, + "current_billing_address_version_id": { + "name": "current_billing_address_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_terms_version": { + "name": "accepted_terms_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "accepted_terms_at": { + "name": "accepted_terms_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "privacy_acknowledged_at": { + "name": "privacy_acknowledged_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "archived_by_user_id": { + "name": "archived_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "editorial_accounts_user_id_user_id_fk": { + "name": "editorial_accounts_user_id_user_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk": { + "name": "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "billing_address_versions", + "columnsFrom": [ + "current_billing_address_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "editorial_accounts_archived_by_user_id_user_id_fk": { + "name": "editorial_accounts_archived_by_user_id_user_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "user", + "columnsFrom": [ + "archived_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "editorial_accounts_user_id_unique": { + "name": "editorial_accounts_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + }, + "editorial_accounts_login_email_unique": { + "name": "editorial_accounts_login_email_unique", + "nullsNotDistinct": false, + "columns": [ + "login_email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.lightbox_items": { + "name": "lightbox_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "lightbox_items_editorial_asset_idx": { + "name": "lightbox_items_editorial_asset_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "lightbox_items_editorial_account_id_editorial_accounts_id_fk": { + "name": "lightbox_items_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "lightbox_items", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.rate_limits": { + "name": "rate_limits", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_boundary": { + "name": "window_boundary", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "rate_limits_key_window_boundary_pk": { + "name": "rate_limits_key_window_boundary_pk", + "columns": [ + "key", + "window_boundary" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.download_events": { + "name": "download_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id": { + "name": "immich_asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "authorized_at": { + "name": "authorized_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "download_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'authorized'" + }, + "transferred_bytes": { + "name": "transferred_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "repeat_download_note": { + "name": "repeat_download_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "intent_kind": { + "name": "intent_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new_usage'" + }, + "request_fingerprint": { + "name": "request_fingerprint", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "legacy_intent": { + "name": "legacy_intent", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "download_events_editorial_authorized_id_idx": { + "name": "download_events_editorial_authorized_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "authorized_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "download_events_editorial_idempotency_key_unique": { + "name": "download_events_editorial_idempotency_key_unique", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "download_events_editorial_account_id_editorial_accounts_id_fk": { + "name": "download_events_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "download_events", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "download_events_usage_id_usages_id_fk": { + "name": "download_events_usage_id_usages_id_fk", + "tableFrom": "download_events", + "tableTo": "usages", + "columnsFrom": [ + "usage_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "download_events_intent_kind_check": { + "name": "download_events_intent_kind_check", + "value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download', 'legacy')" + }, + "download_events_request_fingerprint_hex_check": { + "name": "download_events_request_fingerprint_hex_check", + "value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'" + }, + "download_events_canonical_idempotency_key_check": { + "name": "download_events_canonical_idempotency_key_check", + "value": "\"download_events\".\"legacy_intent\" OR \"download_events\".\"idempotency_key\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + }, + "download_events_canonical_immich_asset_id_check": { + "name": "download_events_canonical_immich_asset_id_check", + "value": "\"download_events\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + } + }, + "isRLSEnabled": false + }, + "public.usages": { + "name": "usages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id": { + "name": "immich_asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename_snapshot": { + "name": "filename_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "immich_album_id_snapshot": { + "name": "immich_album_id_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "album_name_snapshot": { + "name": "album_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_reference": { + "name": "internal_reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "billing_status": { + "name": "billing_status", + "type": "usage_billing_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "billing_report_id": { + "name": "billing_report_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usages_editorial_created_id_idx": { + "name": "usages_editorial_created_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usages_created_at_idx": { + "name": "usages_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usages_editorial_account_id_editorial_accounts_id_fk": { + "name": "usages_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "usages", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "usages_billing_report_id_billing_reports_id_fk": { + "name": "usages_billing_report_id_billing_reports_id_fk", + "tableFrom": "usages", + "tableTo": "billing_reports", + "columnsFrom": [ + "billing_report_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usages_canonical_immich_asset_id_check": { + "name": "usages_canonical_immich_asset_id_check", + "value": "\"usages\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + }, + "usages_canonical_immich_album_id_check": { + "name": "usages_canonical_immich_album_id_check", + "value": "\"usages\".\"immich_album_id_snapshot\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + } + }, + "isRLSEnabled": false + } + }, + "enums": { + "public.portal_role": { + "name": "portal_role", + "schema": "public", + "values": [ + "ADMIN", + "EDITORIAL" + ] + }, + "public.report_status": { + "name": "report_status", + "schema": "public", + "values": [ + "draft", + "final", + "cancelled" + ] + }, + "public.account_status": { + "name": "account_status", + "schema": "public", + "values": [ + "pending_email", + "pending_approval", + "active", + "suspended", + "rejected" + ] + }, + "public.download_status": { + "name": "download_status", + "schema": "public", + "values": [ + "authorized", + "streaming", + "completed", + "failed_before_delivery", + "interrupted" + ] + }, + "public.usage_billing_status": { + "name": "usage_billing_status", + "schema": "public", + "values": [ + "open", + "billed", + "reopened", + "voided" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 9a7cc17..2014c2a 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -71,6 +71,13 @@ "when": 1786455754414, "tag": "0009_usage_created_at_index", "breakpoints": true + }, + { + "idx": 10, + "version": "7", + "when": 1787617368189, + "tag": "0010_two-factor", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/src/app/admin/access.ts b/src/app/admin/access.ts index e501f13..b489d7a 100644 --- a/src/app/admin/access.ts +++ b/src/app/admin/access.ts @@ -5,8 +5,9 @@ import { cache } from "react"; import { headers } from "next/headers"; import { requirePageAccess } from "@/modules/auth/page-access"; -import { requireAdmin } from "@/modules/auth/principal"; +import { requireAdmin, requireAdminForSetup } from "@/modules/auth/principal"; +/** Strict guard: valid admin session with finished two-factor setup. */ export const requireAdminPage = cache(async () => requirePageAccess(async () => requireAdmin(new Headers(await headers()))), ); diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts index 51fd5b9..8678c84 100644 --- a/src/app/admin/redaktionen/[id]/actions.ts +++ b/src/app/admin/redaktionen/[id]/actions.ts @@ -7,7 +7,7 @@ import { eq } from "drizzle-orm"; import { db } from "@/db/client"; import { editorialAccounts } from "@/db/schema"; -import { requireAdmin } from "@/modules/auth/principal"; +import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal"; import { editorialService, EditorialServiceError } from "@/modules/editorials/service"; // Returned to the client form so failures surface as inline German text @@ -65,23 +65,65 @@ export async function unarchiveEditorialAction(editorialId: string): Promise { - await requireAdmin(new Headers(await headers())); - await editorialService.hardDeleteEditorial(editorialId); +export type ResetUsageResult = { ok: boolean; message: string }; + +/** + * Step-up guard for irreversible operations (OWASP ASVS 2.5.4): the session + * must be recent, otherwise the admin re-authenticates first. + */ +async function freshAdminPrincipal(): Promise< + Awaited> | ResetUsageResult +> { + try { + return await requireAdmin(new Headers(await headers()), { + maxSessionAgeSeconds: DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS, + }); + } catch (error) { + if (error instanceof PrincipalAuthorizationError) { + return { ok: false, message: adminGuardMessage(error.code) }; + } + throw error; + } +} + +function adminGuardMessage(code: PrincipalAuthorizationError["code"]): string { + switch (code) { + case "SESSION_STALE": + return "Aus Sicherheitsgründen ist Ihre Sitzung zu alt für diese Aktion. Bitte melden Sie sich erneut an und wiederholen Sie den Schritt."; + case "TWO_FACTOR_REQUIRED": + return "Für diese Aktion ist Zwei-Faktor-Authentifizierung erforderlich."; + default: + return "Die Aktion ist fehlgeschlagen."; + } +} + +function isPrincipal(result: unknown): result is Awaited> { + return typeof result === "object" && result !== null && "userId" in result; +} + +export async function hardDeleteEditorialAction(editorialId: string): Promise { + const safeEditorialId = requiredId(editorialId); + const principal = await freshAdminPrincipal(); + if (!isPrincipal(principal)) { + return principal; + } + + await editorialService.hardDeleteEditorial(safeEditorialId); revalidatePath("/admin/redaktionen"); redirect("/admin/redaktionen"); } -export type ResetUsageResult = { ok: boolean; message: string }; - export async function resetUsageDataAction(editorialId: string): Promise { - const admin = await requireAdmin(new Headers(await headers())); const safeEditorialId = requiredId(editorialId); + const principal = await freshAdminPrincipal(); + if (!isPrincipal(principal)) { + return principal; + } try { const result = await editorialService.resetUsageData({ editorialId: safeEditorialId, - adminUserId: admin.userId, + adminUserId: principal.userId, }); revalidatePath(`/admin/redaktionen/${safeEditorialId}`); revalidatePath("/admin/redaktionen"); diff --git a/src/app/zwei-faktor/access.ts b/src/app/zwei-faktor/access.ts new file mode 100644 index 0000000..068529c --- /dev/null +++ b/src/app/zwei-faktor/access.ts @@ -0,0 +1,17 @@ +import "server-only"; + +import { cache } from "react"; + +import { headers } from "next/headers"; + +import { requirePageAccess } from "@/modules/auth/page-access"; +import { requireAdminForSetup } from "@/modules/auth/principal"; + +/** + * Weak guard for the two-factor wizard only: an authenticated ADMIN without + * a finished TOTP setup must be able to reach /zwei-faktor. Everything else + * in the portal uses requireAdminPage / requireAdmin (strict). + */ +export const requireTwoFactorSetupPage = cache(async () => + requirePageAccess(async () => requireAdminForSetup(new Headers(await headers()))), +); diff --git a/src/app/zwei-faktor/page.tsx b/src/app/zwei-faktor/page.tsx new file mode 100644 index 0000000..f8dbd99 --- /dev/null +++ b/src/app/zwei-faktor/page.tsx @@ -0,0 +1,33 @@ +import { headers } from "next/headers"; + +import { PageHeader } from "@/components/ui/page-header"; +import { auth } from "@/modules/auth/auth"; + +import { requireTwoFactorSetupPage } from "./access"; +import { TwoFactorWizard } from "./wizard"; + +export default async function TwoFactorSetupPage() { + await requireTwoFactorSetupPage(); + + const session = await auth.api.getSession({ headers: new Headers(await headers()) }); + const enabled = + (session?.user as { twoFactorEnabled?: unknown } | undefined)?.twoFactorEnabled === true; + + return ( +
+ + {enabled ? ( +

+ Zwei-Faktor ist aktiviert. Administrator-Bereiche erfordern bei der Anmeldung zusätzlich + einen Code Ihrer Authenticator-App. +

+ ) : ( +
+ Für Administrator-Konten ist die Zwei-Faktor-Authentifizierung Pflicht. Richten Sie sie + jetzt ein, um auf den Admin-Bereich zuzugreifen. +
+ )} + +
+ ); +} diff --git a/src/app/zwei-faktor/wizard.tsx b/src/app/zwei-faktor/wizard.tsx new file mode 100644 index 0000000..ec6b845 --- /dev/null +++ b/src/app/zwei-faktor/wizard.tsx @@ -0,0 +1,207 @@ +"use client"; + +import { type FormEvent, useState } from "react"; + +import { Button } from "@/components/ui/button"; +import { authClient } from "@/modules/auth/client"; + +type WizardStep = "password" | "scan" | "done"; + +export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolean }) { + const [enabled, setEnabled] = useState(initiallyEnabled); + const [step, setStep] = useState("password"); + const [secret, setSecret] = useState(); + const [backupCodes, setBackupCodes] = useState([]); + const [error, setError] = useState(); + const [pending, setPending] = useState(false); + + async function startSetup(event: FormEvent) { + event.preventDefault(); + setPending(true); + setError(undefined); + const password = readPassword(event.currentTarget); + + try { + const result = await authClient.twoFactor.enable({ password }); + if (result.error) { + setError(twoFactorErrorMessage(result.error.code)); + return; + } + const uri = result.data?.totpURI; + setSecret(uri ? new URL(uri).searchParams.get("secret") ?? undefined : undefined); + setBackupCodes(result.data?.backupCodes ?? []); + setStep("scan"); + } catch { + setError("Das Einrichten ist fehlgeschlagen. Bitte versuchen Sie es erneut."); + } finally { + setPending(false); + } + } + + async function confirmCode(event: FormEvent) { + event.preventDefault(); + setPending(true); + setError(undefined); + + try { + const formData = new FormData(event.currentTarget); + const code = String(formData.get("code") ?? "").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."); + return; + } + setEnabled(true); + setStep("done"); + } catch { + setError("Der Code konnte nicht geprüft werden. Bitte versuchen Sie es erneut."); + } finally { + setPending(false); + } + } + + async function disable(event: FormEvent) { + event.preventDefault(); + setPending(true); + setError(undefined); + + try { + const password = readPassword(event.currentTarget); + const result = await authClient.twoFactor.disable({ password }); + if (result.error) { + setError("Das Deaktivieren ist fehlgeschlagen. Passwort prüfen und erneut versuchen."); + return; + } + setEnabled(false); + setStep("password"); + } catch { + setError("Das Deaktivieren ist fehlgeschlagen. Bitte versuchen Sie es erneut."); + } finally { + setPending(false); + } + } + + return ( +
+ {!enabled && step === "password" && ( +
+ + +
+ )} + + {step === "scan" && secret && ( +
+
    +
  1. Öffnen Sie Ihre Authenticator-App (z. B. Google Authenticator, Aegis, 1Password).
  2. +
  3. + Fügen Sie einen neuen Eintrag hinzu und geben Sie diesen Schlüssel manuell ein: + + {secret} + + + Typ: zeitbasiert (TOTP) · 6 Ziffern · alle 30 Sekunden. + +
  4. +
  5. Bestätigen Sie mit dem aktuell angezeigten Code.
  6. +
+ + {backupCodes.length > 0 && ( +
+

Einmal-Codes (ersatzweise gültig, je einmal nutzbar)

+
+ {backupCodes.map((code) => ( + {code} + ))} +
+

+ Bewahren Sie diese Codes sicher auf – sie werden nur jetzt angezeigt. +

+
+ )} + +
+ + +
+
+ )} + + {step === "done" && ( +
+ Zwei-Faktor-Authentifizierung ist aktiviert. Sie können sich ab jetzt nur noch mit + Passwort und Authenticator-Code anmelden. + + Weiter zum Admin-Bereich + +
+ )} + + {enabled && step !== "done" && ( +
+

+ Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die + Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind. +

+ + +
+ )} + + {error && ( +

+ {error} +

+ )} +
+ ); +} + +function readPassword(form: HTMLFormElement): string { + const value = new FormData(form).get("password"); + return typeof value === "string" ? value : ""; +} + +function twoFactorErrorMessage(code: string | undefined): string { + switch (code) { + case "INVALID_PASSWORD": + return "Das Passwort ist nicht korrekt."; + case "TWO_FACTOR_ALREADY_ENABLED": + return "Zwei-Faktor ist für dieses Konto bereits aktiviert."; + default: + return "Das Einrichten ist fehlgeschlagen. Bitte versuchen Sie es erneut."; + } +} diff --git a/src/db/schema/auth.ts b/src/db/schema/auth.ts index 42c003f..7fb11bf 100644 --- a/src/db/schema/auth.ts +++ b/src/db/schema/auth.ts @@ -10,10 +10,25 @@ export const users = pgTable("user", { emailVerified: boolean("email_verified").notNull().default(false), image: text("image"), role: portalRole("role").notNull().default("EDITORIAL"), + // Better Auth two-factor plugin; secrets live in the two_factor table. + twoFactorEnabled: boolean("two_factor_enabled").notNull().default(false), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); +// Better Auth two-factor plugin model ("twoFactor"). `secret` and +// `backupCodes` are stored encrypted by Better Auth (derived from +// BETTER_AUTH_SECRET). +export const twoFactors = pgTable("two_factor", { + id: uuid("id").defaultRandom().primaryKey(), + userId: uuid("user_id") + .notNull() + .unique() + .references(() => users.id, { onDelete: "restrict" }), + secret: text("secret").notNull(), + backupCodes: text("backup_codes"), +}); + export const accounts = pgTable("account", { id: uuid("id").defaultRandom().primaryKey(), accountId: text("account_id").notNull(), diff --git a/src/modules/auth/auth.ts b/src/modules/auth/auth.ts index e7ef677..7c039c4 100644 --- a/src/modules/auth/auth.ts +++ b/src/modules/auth/auth.ts @@ -1,12 +1,19 @@ import "server-only"; +import { APIError } from "better-auth"; +import { createAuthMiddleware } from "better-auth/api"; import { drizzleAdapter } from "@better-auth/drizzle-adapter"; import { betterAuth, type BetterAuthOptions } from "better-auth"; +import { twoFactor } from "better-auth/plugins"; import { env } from "@/config/env"; import { db } from "@/db/client"; -import { accounts, sessions, users, verifications } from "@/db/schema"; +import { accounts, sessions, twoFactors, users, verifications } from "@/db/schema"; import { mailer } from "@/modules/mail/mailer"; +import { + validatePasswordPolicy, + MIN_PASSWORD_LENGTH, +} from "@/modules/security/password-policy"; import { consumeRateLimit, registrationPolicy } from "@/modules/security/rate-limit"; import { enforceRateLimit, @@ -74,12 +81,29 @@ export function createPortalAuth({ defaultValue: "EDITORIAL", input: false, }, + twoFactorEnabled: { + type: "boolean", + required: false, + defaultValue: false, + input: false, + }, }, }, + 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). + }), + ], + hooks: { + before: createPasswordPolicyHook(), + }, emailAndPassword: { enabled: true, requireEmailVerification: true, autoSignIn: false, + minPasswordLength: MIN_PASSWORD_LENGTH, resetPasswordTokenExpiresIn: 60 * 60, revokeSessionsOnPasswordReset: true, async sendResetPassword({ user, url }) { @@ -129,6 +153,32 @@ export function createPortalAuth({ return { auth, registrationService }; } +export function createPasswordPolicyHook() { + // 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 !== "/reset-password" && ctx.path !== "/change-password") { + return; + } + const body = (ctx.body ?? {}) as { newPassword?: unknown; password?: unknown }; + const candidate = + typeof body.newPassword === "string" + ? body.newPassword + : typeof body.password === "string" + ? body.password + : undefined; + if (candidate === undefined) { + return; + } + const result = validatePasswordPolicy(candidate); + if (!result.ok) { + throw new APIError("BAD_REQUEST", { message: result.reason }); + } + }); +} + const registrationRepository = createEditorialRegistrationRepository(db); const portalAuth = createPortalAuth({ database: drizzleAdapter(db, { @@ -138,6 +188,7 @@ const portalAuth = createPortalAuth({ account: accounts, session: sessions, verification: verifications, + twoFactor: twoFactors, }, }), mailerService: mailer, diff --git a/src/modules/auth/client.ts b/src/modules/auth/client.ts index 2f75fd4..e228778 100644 --- a/src/modules/auth/client.ts +++ b/src/modules/auth/client.ts @@ -1,5 +1,8 @@ "use client"; import { createAuthClient } from "better-auth/react"; +import { twoFactorClient } from "better-auth/client/plugins"; -export const authClient = createAuthClient(); +export const authClient = createAuthClient({ + plugins: [twoFactorClient()], +}); diff --git a/src/modules/auth/page-access.ts b/src/modules/auth/page-access.ts index a72fdbd..bcde1ab 100644 --- a/src/modules/auth/page-access.ts +++ b/src/modules/auth/page-access.ts @@ -10,11 +10,16 @@ export async function requirePageAccess( try { return await loadPrincipal(); } catch (error) { - if ( - error instanceof PrincipalAuthorizationError && - error.code === "AUTHENTICATION_REQUIRED" - ) { - redirect("/anmelden"); + if (error instanceof PrincipalAuthorizationError) { + if (error.code === "AUTHENTICATION_REQUIRED") { + redirect("/anmelden"); + } + // Admins without a finished two-factor setup are routed to the wizard + // instead of an error page (the wizard itself uses the weak guard and + // lives outside the guarded /admin layout to avoid a redirect loop). + if (error.code === "TWO_FACTOR_REQUIRED") { + redirect("/zwei-faktor"); + } } throw error; } diff --git a/src/modules/auth/principal.test.ts b/src/modules/auth/principal.test.ts index 02e1a33..36f4019 100644 --- a/src/modules/auth/principal.test.ts +++ b/src/modules/auth/principal.test.ts @@ -4,6 +4,7 @@ import { createPrincipalGuard } from "./principal"; const editorialSession = { user: { id: "editorial-user", role: "EDITORIAL" as const }, + session: { createdAt: new Date() }, }; test("rejects a suspended editorial after session authentication", async () => { @@ -44,3 +45,49 @@ test("rejects non-admin users from the admin guard", async () => { await expect(guard.requireAdmin(new Headers())).rejects.toMatchObject({ code: "ADMIN_REQUIRED" }); }); + +test("rejects an admin session without finished two-factor setup", async () => { + const guard = createPrincipalGuard({ + getSession: async () => ({ + user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: false }, + session: { createdAt: new Date() }, + }), + getAccount: async () => null, + }); + + await expect(guard.requireAdmin(new Headers())).rejects.toMatchObject({ + code: "TWO_FACTOR_REQUIRED", + }); + // The setup wizard uses the weak guard so admins can configure TOTP. + await expect( + guard.requireAdmin(new Headers(), { allowWithoutTwoFactor: true }), + ).resolves.toMatchObject({ userId: "admin-user" }); +}); + +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() }, + }), + getAccount: async () => null, + }); + + await expect(guard.requireAdmin(new Headers())).resolves.toMatchObject({ userId: "admin-user" }); +}); + +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) }, + }), + getAccount: async () => null, + }); + + await expect( + guard.requireAdmin(new Headers(), { maxSessionAgeSeconds: 15 * 60 }), + ).rejects.toMatchObject({ code: "SESSION_STALE" }); + // Without the freshness requirement the same session is fine. + await expect(guard.requireAdmin(new Headers())).resolves.toMatchObject({ userId: "admin-user" }); +}); diff --git a/src/modules/auth/principal.ts b/src/modules/auth/principal.ts index b344578..8cda609 100644 --- a/src/modules/auth/principal.ts +++ b/src/modules/auth/principal.ts @@ -16,9 +16,15 @@ export type PortalPrincipal = { status: AccountStatus; }; -type Session = { user: { id: string; role: "ADMIN" | "EDITORIAL" } } | null; +type Session = { + user: { id: string; role: "ADMIN" | "EDITORIAL"; twoFactorEnabled?: boolean }; + session: { createdAt?: Date }; +} | null; type EditorialAccount = { id: string; status: AccountStatus } | null; +/** Sessions older than this must re-authenticate before destructive actions. */ +export const DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS = 15 * 60; + export type PrincipalGuardDependencies = { getSession(requestHeaders: Headers): Promise; getAccount(userId: string): Promise; @@ -31,6 +37,8 @@ export class PrincipalAuthorizationError extends Error { readonly code: | "AUTHENTICATION_REQUIRED" | "ADMIN_REQUIRED" + | "TWO_FACTOR_REQUIRED" + | "SESSION_STALE" | "EDITORIAL_ACCOUNT_NOT_FOUND" | "ACCOUNT_PENDING_EMAIL" | "ACCOUNT_PENDING_APPROVAL" @@ -51,11 +59,30 @@ export function createPrincipalGuard({ getSession, getAccount }: PrincipalGuardD } return { - async requireAdmin(requestHeaders: Headers): Promise { + /** + * Admin guard. Enforces two-factor authentication once configured + * (setup stays reachable via requireAdminForSetup to avoid lockout). + * Pass `maxSessionAgeSeconds` for step-up semantics on destructive + * operations (OWASP ASVS 2.5.4): older sessions are rejected. + */ + async requireAdmin( + requestHeaders: Headers, + options: { maxSessionAgeSeconds?: number; allowWithoutTwoFactor?: boolean } = {}, + ): Promise { const session = await getAuthenticatedSession(requestHeaders); if (session.user.role !== "ADMIN") { throw new PrincipalAuthorizationError("ADMIN_REQUIRED"); } + if (!options.allowWithoutTwoFactor && !session.user.twoFactorEnabled) { + throw new PrincipalAuthorizationError("TWO_FACTOR_REQUIRED"); + } + if (options.maxSessionAgeSeconds !== undefined && session.session.createdAt) { + const ageSeconds = + (Date.now() - new Date(session.session.createdAt).getTime()) / 1000; + if (ageSeconds > options.maxSessionAgeSeconds) { + throw new PrincipalAuthorizationError("SESSION_STALE"); + } + } return { userId: session.user.id, @@ -114,7 +141,15 @@ export const principalGuard = createPrincipalGuard({ if (role !== "ADMIN" && role !== "EDITORIAL") { return null; } - return { user: { id: session.user.id, role } }; + return { + user: { + id: session.user.id, + role, + twoFactorEnabled: + (session.user as { twoFactorEnabled?: unknown }).twoFactorEnabled === true, + }, + session: { createdAt: session.session.createdAt }, + }; }, async getAccount(userId) { @@ -129,3 +164,11 @@ export const principalGuard = createPrincipalGuard({ export const requireAdmin = principalGuard.requireAdmin; export const requireActiveEditorial = principalGuard.requireActiveEditorial; + +/** + * Weak admin guard for the two-factor setup surface only: an authenticated + * ADMIN without a finished TOTP setup must be able to reach the wizard. + * Everything else uses requireAdmin (which enforces two-factor). + */ +export const requireAdminForSetup: typeof principalGuard.requireAdmin = (headers, options) => + principalGuard.requireAdmin(headers, { ...options, allowWithoutTwoFactor: true }); diff --git a/src/modules/auth/public-forms.tsx b/src/modules/auth/public-forms.tsx index e143bfa..ab74b69 100644 --- a/src/modules/auth/public-forms.tsx +++ b/src/modules/auth/public-forms.tsx @@ -67,7 +67,7 @@ export function RegistrationForm({