fix: rebuild migration history as baseline so migrate works on prod

Squash the 13 historical migrations into one generated baseline whose
journal entry reuses the original 0000 timestamp: the migrator skips it
on every existing database (prod journal stuck at 0006) and applies it
only on fresh ones. Parity with the old chain verified via pg_dump diff
plus fresh/existing/prod-simulated drizzle-kit migrate runs. Historical
files move to drizzle-history/pre-squash-2026-08/ for integration tests
that exercise legacy migration behavior.

Also repair db tests that already failed before this change:
- raw SQL targeted users, but the table has always been "user"
- membership recheck mocked legacy getAsset.albums instead of searchPhotos
- audit rollback assertion walks drizzle's wrapped error cause chain
- keyset index probe pinned to NULLS LAST ordering, removing a planner
  cost tie-break that flipped with index creation order
This commit is contained in:
Leon Tonhäuser committed 2026-08-25 11:56:52 +02:00
1 parent 2949149170
commit 0b65fbba16
40 files changed
+2388 -127

No files matched your search

+2 -2
View File
@@ -43,7 +43,7 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
- **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)
- **PROD-DB-MIGRATIONS-SCHULDEN:** Die Produktionsdatenbank weicht von der Drizzle-Journal-Historie ab (Journal bei 0006, Schema aber aktuell). `drizzle-kit migrate` scheitert am Replay alter Dateien ("relation already exists") und darf dort NICHT verwendet werden, bis eine saubere Baseline gebaut ist. Neue Migrationen müssen auf PROD manuell per psql angewendet werden (SQL aus der jeweiligen drizzle/*.sql-Datei). Fix-Ansatz: Historie squashen/baseline neu bauen, dann migrate reaktivieren.
- **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 der Tabelle `two_factor`: `id`, `user_id`, `secret`, `backup_codes`, `verified`, `failed_verification_count`, `locked_until` – die Feldliste MUSS exakt der Plugin-Deklaration in better-auth `plugins/two-factor/schema.mjs` entsprechen, sonst wirft der Drizzle-Adapter "field does not exist" bei jedem Two-Factor-Endpoint (Migrationen 0010–0012).
- **PROD-MIGRATION-BASELINE (erledigt 2026-08-25):** Die frühere Abweichung zwischen Prod-Journal (Stand 0006) und Schema wurde per History-Squash behoben: `drizzle/` enthält nur noch `0000_baseline.sql` (aus dem aktuellen Schema generiert, Snapshot = altes 0012-Snapshot semantisch identisch, via pg_dump-Diff gegen die alte Migrationskette verifiziert). Der Journal-Eintrag der Baseline trägt bewusst das **Original-Timestamp der alten Migration 0000** (`1786299825190`) – der Drizzle-Migrator vergleicht `created_at` der Tabelle `drizzle.__drizzle_migrations` mit dem Journal-`when`, daher wird die Baseline auf jeder bestehenden DB (Prod, Dev) übersprungen und nur auf frischen DBs angewendet. Zukünftige Migrationen (`drizzle-kit generate`) greifen damit auf allen Umgebungen automatisch. Alte Migrationsdateien + Snapshots liegen in `drizzle-history/pre-squash-2026-08/` und werden NUR von den Historie-Tests genutzt (`tests/db/postgres.ts` akzeptiert dafür `migrationsDir`). Erste Ausführung von `docker compose --profile ops run --rm migrate` auf PROD ist ein No-op (Baseline skippt), danach laufen neue Migrationen normal.
- **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 der Tabelle `two_factor`: `id`, `user_id`, `secret`, `backup_codes`, `verified`, `failed_verification_count`, `locked_until` – die Feldliste MUSS exakt der Plugin-Deklaration in better-auth `plugins/two-factor/schema.mjs` entsprechen, sonst wirft der Drizzle-Adapter "field does not exist" bei jedem Two-Factor-Endpoint (Migrationen 0010–0012, historisch in `drizzle-history/pre-squash-2026-08/`).
- **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).
+11
View File
@@ -81,6 +81,17 @@ the `ops` compose profile and do not start with `docker compose up`.
```bash
docker compose --profile ops run --rm migrate
```
Migrations are safe to run on every environment, including production. The
history was squashed into a single baseline (`drizzle/0000_baseline.sql`) in
August 2026: the baseline carries the timestamp of the original first
migration, so `drizzle-kit migrate` skips it on any database that already has
tables (its recorded journal entry is newer) and applies it only on fresh
databases. New migrations generated with `pnpm exec drizzle-kit generate` are
picked up automatically on all environments — no manual psql steps required
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):
```bash
docker compose --profile ops run --rm seed \
File renamed without changes.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,97 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1786299825190,
"tag": "0000_initial",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1786303607054,
"tag": "0001_editorial_approval_notice",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1786354215684,
"tag": "0002_accounting_intents",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1786358492749,
"tag": "0003_stream_delivery",
"breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1786363479515,
"tag": "0004_download_history_indexes",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1786379282947,
"tag": "0005_rate_limits",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1786410282719,
"tag": "0006_chubby_screwball",
"breakpoints": true
},
{
"idx": 7,
"version": "7",
"when": 1786410724623,
"tag": "0007_amused_franklin_storm",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1786411419497,
"tag": "0008_overjoyed_wrecking_crew",
"breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1786455754414,
"tag": "0009_usage_created_at_index",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1787617368189,
"tag": "0010_two-factor",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1787620365940,
"tag": "0011_two-factor-verified",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1787621254728,
"tag": "0012_two-factor-plugin-fields",
"breakpoints": true
}
]
}
+265
View File
@@ -0,0 +1,265 @@
CREATE TYPE "public"."portal_role" AS ENUM('ADMIN', 'EDITORIAL');--> statement-breakpoint
CREATE TYPE "public"."report_status" AS ENUM('draft', 'final', 'cancelled');--> statement-breakpoint
CREATE TYPE "public"."account_status" AS ENUM('pending_email', 'pending_approval', 'active', 'suspended', 'rejected');--> statement-breakpoint
CREATE TYPE "public"."download_status" AS ENUM('authorized', 'streaming', 'completed', 'failed_before_delivery', 'interrupted');--> statement-breakpoint
CREATE TYPE "public"."usage_billing_status" AS ENUM('open', 'billed', 'reopened', 'voided');--> statement-breakpoint
CREATE TABLE "album_grants" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"immich_album_id" text NOT NULL,
"granted_at" timestamp with time zone DEFAULT now() NOT NULL,
"revoked_at" timestamp with time zone,
"granted_by_user_id" uuid,
CONSTRAINT "album_grants_immich_album_id_uuid_check" CHECK ("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}$')
);
--> statement-breakpoint
CREATE TABLE "audit_events" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"event_type" text NOT NULL,
"actor_user_id" uuid,
"actor_type" text DEFAULT 'system' NOT NULL,
"entity_type" text NOT NULL,
"entity_id" text NOT NULL,
"previous_values" jsonb,
"new_values" jsonb,
"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
"request_id" uuid
);
--> statement-breakpoint
CREATE TABLE "account" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" uuid NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp with time zone,
"refresh_token_expires_at" timestamp with time zone,
"scope" text,
"password" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"token" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"ip_address" text,
"user_agent" text,
"user_id" uuid NOT NULL,
CONSTRAINT "session_token_unique" UNIQUE("token")
);
--> statement-breakpoint
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,
"verified" boolean DEFAULT false NOT NULL,
"failed_verification_count" integer DEFAULT 0 NOT NULL,
"locked_until" timestamp with time zone,
CONSTRAINT "two_factor_user_id_unique" UNIQUE("user_id")
);
--> statement-breakpoint
CREATE TABLE "user" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean DEFAULT false NOT NULL,
"image" text,
"role" "portal_role" DEFAULT 'EDITORIAL' NOT NULL,
"two_factor_enabled" boolean DEFAULT false NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "user_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE "verification" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"identifier" text NOT NULL,
"value" text NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "album_auto_rules" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"keyword" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"created_by_user_id" uuid
);
--> statement-breakpoint
CREATE TABLE "billing_report_items" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"billing_report_id" uuid NOT NULL,
"usage_id" uuid NOT NULL,
"immich_asset_id_snapshot" text NOT NULL,
"filename_snapshot" text NOT NULL,
"album_name_snapshot" text NOT NULL,
"purpose_snapshot" text NOT NULL,
"internal_reference_snapshot" text,
"price_cents" integer NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "billing_reports" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"report_number" integer NOT NULL,
"editorial_account_id" uuid NOT NULL,
"period_starts_at" timestamp with time zone NOT NULL,
"period_ends_at" timestamp with time zone NOT NULL,
"billing_address_snapshot" jsonb NOT NULL,
"invoice_number" text,
"net_total_cents" integer NOT NULL,
"flatrate_cents_snapshot" integer,
"status" "report_status" DEFAULT 'draft' NOT NULL,
"pdf" "bytea",
"pdf_sha256" varchar(64),
"created_by_user_id" uuid NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"finalized_at" timestamp with time zone,
"cancelled_at" timestamp with time zone,
"cancellation_reason" text,
"cancelled_by_user_id" uuid,
CONSTRAINT "billing_reports_pdf_sha256_hex_check" CHECK ("billing_reports"."pdf_sha256" ~ '^[0-9a-f]{64}$'),
CONSTRAINT "billing_reports_final_pdf_check" CHECK ("billing_reports"."status" <> 'final' OR ("billing_reports"."pdf" IS NOT NULL AND "billing_reports"."pdf_sha256" IS NOT NULL))
);
--> statement-breakpoint
CREATE TABLE "billing_address_versions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"company_name" text NOT NULL,
"contact_name" text NOT NULL,
"address_line_1" text NOT NULL,
"address_line_2" text,
"postal_code" text NOT NULL,
"city" text NOT NULL,
"country_code" text NOT NULL,
"valid_from" timestamp with time zone DEFAULT now() NOT NULL,
"superseded_by_id" uuid,
"created_by_user_id" uuid,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "editorial_accounts" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"name" text NOT NULL,
"contact_name" text NOT NULL,
"login_email" text NOT NULL,
"status" "account_status" DEFAULT 'pending_email' NOT NULL,
"current_price_cents" integer,
"flatrate_active" boolean DEFAULT false NOT NULL,
"flatrate_price_cents" integer,
"flatrate_asset_limit" integer,
"approval_notice_status" text DEFAULT 'not_requested' NOT NULL,
"current_billing_address_version_id" uuid,
"email_verified_at" timestamp with time zone,
"accepted_terms_version" text,
"accepted_terms_at" timestamp with time zone,
"privacy_acknowledged_at" timestamp with time zone,
"archived_at" timestamp with time zone,
"archived_by_user_id" uuid,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "editorial_accounts_user_id_unique" UNIQUE("user_id"),
CONSTRAINT "editorial_accounts_login_email_unique" UNIQUE("login_email")
);
--> statement-breakpoint
CREATE TABLE "lightbox_items" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"asset_id" text NOT NULL,
"added_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "rate_limits" (
"key" text NOT NULL,
"window_boundary" integer NOT NULL,
"count" integer DEFAULT 1 NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "rate_limits_key_window_boundary_pk" PRIMARY KEY("key","window_boundary")
);
--> statement-breakpoint
CREATE TABLE "download_events" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"usage_id" uuid NOT NULL,
"immich_asset_id" text NOT NULL,
"authorized_at" timestamp with time zone DEFAULT now() NOT NULL,
"started_at" timestamp with time zone,
"completed_at" timestamp with time zone,
"status" "download_status" DEFAULT 'authorized' NOT NULL,
"transferred_bytes" bigint,
"repeat_download_note" text,
"request_id" uuid NOT NULL,
"idempotency_key" text NOT NULL,
"intent_kind" text DEFAULT 'new_usage' NOT NULL,
"request_fingerprint" varchar(64) NOT NULL,
"legacy_intent" boolean DEFAULT false NOT NULL,
CONSTRAINT "download_events_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download', 'legacy')),
CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$'),
CONSTRAINT "download_events_canonical_idempotency_key_check" CHECK ("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}$'),
CONSTRAINT "download_events_canonical_immich_asset_id_check" CHECK ("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}$')
);
--> statement-breakpoint
CREATE TABLE "usages" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"immich_asset_id" text NOT NULL,
"filename_snapshot" text NOT NULL,
"immich_album_id_snapshot" text NOT NULL,
"album_name_snapshot" text NOT NULL,
"purpose" text NOT NULL,
"internal_reference" text,
"price_cents" integer NOT NULL,
"billing_status" "usage_billing_status" DEFAULT 'open' NOT NULL,
"billing_report_id" uuid,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "usages_canonical_immich_asset_id_check" CHECK ("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}$'),
CONSTRAINT "usages_canonical_immich_album_id_check" CHECK ("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}$')
);
--> statement-breakpoint
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_granted_by_user_id_user_id_fk" FOREIGN KEY ("granted_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "audit_events" ADD CONSTRAINT "audit_events_actor_user_id_user_id_fk" FOREIGN KEY ("actor_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> 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;--> statement-breakpoint
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_cancelled_by_user_id_user_id_fk" FOREIGN KEY ("cancelled_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_superseded_by_id_billing_address_versions_id_fk" FOREIGN KEY ("superseded_by_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk" FOREIGN KEY ("current_billing_address_version_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_archived_by_user_id_user_id_fk" FOREIGN KEY ("archived_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "lightbox_items" ADD CONSTRAINT "lightbox_items_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "usages" ADD CONSTRAINT "usages_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "usages" ADD CONSTRAINT "usages_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "album_grants_editorial_account_id_idx" ON "album_grants" USING btree ("editorial_account_id");--> statement-breakpoint
CREATE INDEX "album_grants_immich_album_id_idx" ON "album_grants" USING btree ("immich_album_id");--> statement-breakpoint
CREATE UNIQUE INDEX "album_grants_editorial_active_album_unique" ON "album_grants" USING btree ("editorial_account_id",lower("immich_album_id")) WHERE "album_grants"."revoked_at" is null;--> statement-breakpoint
CREATE UNIQUE INDEX "album_auto_rules_editorial_account_id_keyword_idx" ON "album_auto_rules" USING btree ("editorial_account_id",lower("keyword"));--> statement-breakpoint
CREATE UNIQUE INDEX "billing_report_items_report_usage_unique" ON "billing_report_items" USING btree ("billing_report_id","usage_id");--> statement-breakpoint
CREATE UNIQUE INDEX "billing_reports_report_number_unique" ON "billing_reports" USING btree ("report_number");--> statement-breakpoint
CREATE UNIQUE INDEX "billing_reports_invoice_number_unique" ON "billing_reports" USING btree ("invoice_number");--> statement-breakpoint
CREATE UNIQUE INDEX "lightbox_items_editorial_asset_idx" ON "lightbox_items" USING btree ("editorial_account_id","asset_id");--> statement-breakpoint
CREATE INDEX "download_events_editorial_authorized_id_idx" ON "download_events" USING btree ("editorial_account_id","authorized_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
CREATE UNIQUE INDEX "download_events_editorial_idempotency_key_unique" ON "download_events" USING btree ("editorial_account_id","idempotency_key");--> statement-breakpoint
CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
CREATE INDEX "usages_created_at_idx" ON "usages" USING btree ("created_at");
+517 -6
View File
@@ -1,5 +1,5 @@
{
"id": "64eb37ed-2ab5-4c12-a8be-4375e8f6a732",
"id": "5ac645f2-0e76-4853-b029-724095bf1138",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
@@ -77,6 +77,28 @@
"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": {
@@ -110,7 +132,12 @@
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"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": {
@@ -397,6 +424,86 @@
"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
},
"verified": {
"name": "verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"failed_verification_count": {
"name": "failed_verification_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"locked_until": {
"name": "locked_until",
"type": "timestamp with time zone",
"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": "",
@@ -441,6 +548,13 @@
"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",
@@ -524,6 +638,100 @@
"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": "",
@@ -701,6 +909,12 @@
"primaryKey": false,
"notNull": true
},
"flatrate_cents_snapshot": {
"name": "flatrate_cents_snapshot",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"status": {
"name": "status",
"type": "report_status",
@@ -1030,6 +1244,32 @@
"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",
@@ -1060,6 +1300,18 @@
"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",
@@ -1102,6 +1354,19 @@
],
"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": {},
@@ -1125,6 +1390,135 @@
"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": "",
@@ -1204,9 +1598,56 @@
"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": [
@@ -1260,7 +1701,24 @@
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"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": {
@@ -1344,7 +1802,50 @@
"default": "now()"
}
},
"indexes": {},
"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",
@@ -1376,7 +1877,16 @@
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"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
}
},
@@ -1426,7 +1936,8 @@
"values": [
"open",
"billed",
"reopened"
"reopened",
"voided"
]
}
},
+1 -85
View File
@@ -6,91 +6,7 @@
"idx": 0,
"version": "7",
"when": 1786299825190,
"tag": "0000_initial",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1786303607054,
"tag": "0001_editorial_approval_notice",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1786354215684,
"tag": "0002_accounting_intents",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1786358492749,
"tag": "0003_stream_delivery",
"breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1786363479515,
"tag": "0004_download_history_indexes",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1786379282947,
"tag": "0005_rate_limits",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1786410282719,
"tag": "0006_chubby_screwball",
"breakpoints": true
},
{
"idx": 7,
"version": "7",
"when": 1786410724623,
"tag": "0007_amused_franklin_storm",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1786411419497,
"tag": "0008_overjoyed_wrecking_crew",
"breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1786455754414,
"tag": "0009_usage_created_at_index",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1787617368189,
"tag": "0010_two-factor",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1787620365940,
"tag": "0011_two-factor-verified",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1787621254728,
"tag": "0012_two-factor-plugin-fields",
"tag": "0000_baseline",
"breakpoints": true
}
]
+1 -1
View File
@@ -4,7 +4,7 @@ import path from "node:path";
import { expect, test } from "vitest";
const migration = await readFile(
path.join(process.cwd(), "drizzle/0002_accounting_intents.sql"),
path.join(process.cwd(), "drizzle-history/pre-squash-2026-08/0002_accounting_intents.sql"),
"utf8",
);
+5 -2
View File
@@ -9,7 +9,10 @@ import { createUsageService, createUsageServiceRepository } from "@/modules/usag
import { requestFingerprint } from "@/modules/usages/types";
import { startPostgres } from "./postgres";
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
const testDb = await startPostgres({
through: "0001_editorial_approval_notice.sql",
migrationsDir: "drizzle-history/pre-squash-2026-08",
});
afterAll(() => testDb.stop());
@@ -76,7 +79,7 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
const userId = randomUUID();
const editorialId = randomUUID();
await testDb.pool.query(
`insert into users (id, name, email, email_verified)
`insert into "user" (id, name, email, email_verified)
values ($1, 'Legacy Redaktion', $2, true)`,
[userId, `${userId}@example.com`],
);
+5 -2
View File
@@ -5,7 +5,10 @@ import { afterAll, expect, test, vi } from "vitest";
import { createAlbumGrantRepository, createAlbumGrantService } from "@/modules/albums/grants";
import { startPostgres } from "./postgres";
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
const testDb = await startPostgres({
through: "0001_editorial_approval_notice.sql",
migrationsDir: "drizzle-history/pre-squash-2026-08",
});
afterAll(() => testDb.stop());
@@ -22,7 +25,7 @@ test("grant mutations and migration preserve one deterministic active logical gr
const adminUserId = randomUUID();
const editorialId = randomUUID();
await testDb.pool.query(
`insert into users (id, name, email, email_verified)
`insert into "user" (id, name, email, email_verified)
values ($1, 'Grant Admin', $2, true)`,
[adminUserId, `${adminUserId}@example.com`],
);
@@ -5,7 +5,7 @@ import { expect, test } from "vitest";
test("0003 adds a durable voided billing state without deleting usage history", async () => {
const migration = await readFile(
path.join(process.cwd(), "drizzle/0003_stream_delivery.sql"),
path.join(process.cwd(), "drizzle-history/pre-squash-2026-08/0003_stream_delivery.sql"),
"utf8",
);
+9 -2
View File
@@ -391,19 +391,26 @@ test("history ordering queries can use the editorial keyset indexes", async () =
try {
await client.query("begin");
await client.query("set local enable_seqscan = off");
await client.query("set local enable_sort = off");
// The keyset indexes sort NULLS LAST, so the probe queries must ask for the
// same null ordering. Otherwise the index cannot satisfy the ORDER BY, a
// Sort node is unavoidable and which scan feeds it is a cost tie-break
// between equal indexes that flips with index creation order.
const events = await client.query(
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc, id desc limit 26",
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc nulls last, id desc nulls last limit 26",
[own.editorialId],
);
const usageRows = await client.query(
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc, id desc limit 21",
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc nulls last, id desc nulls last limit 21",
[own.editorialId],
);
const eventPlan = events.rows.map((row) => row["QUERY PLAN"]).join("\n");
const usagePlan = usageRows.rows.map((row) => row["QUERY PLAN"]).join("\n");
expect(eventPlan).toContain("download_events_editorial_authorized_id_idx");
expect(eventPlan).not.toContain("Sort");
expect(usagePlan).toContain("usages_editorial_created_id_idx");
expect(usagePlan).not.toContain("Sort");
} finally {
await client.query("rollback");
client.release();
@@ -5,7 +5,7 @@ import { expect, test } from "vitest";
test("0004 adds both editorial history keyset indexes without rewriting history", async () => {
const migration = await readFile(
path.join(process.cwd(), "drizzle/0004_download_history_indexes.sql"),
path.join(process.cwd(), "drizzle-history/pre-squash-2026-08/0004_download_history_indexes.sql"),
"utf8",
);
+10 -8
View File
@@ -29,7 +29,9 @@ export type PostgresTestDatabase = {
stop(): Promise<void>;
};
export async function startPostgres({ through }: { through?: string } = {}): Promise<PostgresTestDatabase> {
export async function startPostgres(
{ through, migrationsDir }: { through?: string; migrationsDir?: string } = {},
): Promise<PostgresTestDatabase> {
const container = await new PostgreSqlContainer("postgres:17-alpine")
.withDatabase("portal")
.withUsername("portal")
@@ -37,11 +39,11 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
.start();
const pool = new Pool({ connectionString: container.getConnectionUri() });
const migrationFiles = await listMigrationFiles();
const migrationFiles = await listMigrationFiles(migrationsDir);
const throughIndex = through ? migrationFiles.indexOf(through) : migrationFiles.length - 1;
if (through && throughIndex < 0) throw new Error(`Unknown migration: ${through}`);
let appliedMigrationCount = throughIndex + 1;
await applyMigrationFiles(pool, migrationFiles.slice(0, appliedMigrationCount));
await applyMigrationFiles(pool, migrationsDir, migrationFiles.slice(0, appliedMigrationCount));
const db = drizzle({ client: pool, schema });
@@ -64,7 +66,7 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
});
},
async applyRemainingMigrations() {
await applyMigrationFiles(pool, migrationFiles.slice(appliedMigrationCount));
await applyMigrationFiles(pool, migrationsDir, migrationFiles.slice(appliedMigrationCount));
appliedMigrationCount = migrationFiles.length;
},
async stop() {
@@ -74,15 +76,15 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
};
}
async function listMigrationFiles() {
const migrationDirectory = path.join(process.cwd(), "drizzle");
async function listMigrationFiles(migrationsDir?: string) {
const migrationDirectory = path.join(process.cwd(), migrationsDir ?? "drizzle");
return (await readdir(migrationDirectory))
.filter((file) => /^\d+_.*\.sql$/.test(file))
.sort();
}
async function applyMigrationFiles(pool: Pool, migrationFiles: string[]) {
const migrationDirectory = path.join(process.cwd(), "drizzle");
async function applyMigrationFiles(pool: Pool, migrationsDir: string | undefined, migrationFiles: string[]) {
const migrationDirectory = path.join(process.cwd(), migrationsDir ?? "drizzle");
for (const file of migrationFiles) {
await pool.query(await readFile(path.join(migrationDirectory, file), "utf8"));
}
+20 -17
View File
@@ -225,21 +225,9 @@ test("requires an active grant for the exact requested album", async () => {
test("rechecks exact album membership after database locks before inserting", async () => {
const editorialId = await seedEditorial();
const { usageService, immich } = createServices();
immich.getAsset
.mockResolvedValueOnce({
id: assetId,
type: "IMAGE" as const,
originalFileName: "jubel.jpg",
originalMimeType: "image/jpeg",
albums: [{ id: albumId }],
})
.mockResolvedValueOnce({
id: assetId,
type: "IMAGE" as const,
originalFileName: "jubel.jpg",
originalMimeType: "image/jpeg",
albums: [],
});
immich.searchPhotos
.mockResolvedValueOnce({ items: [{ id: assetId }], total: 1, nextPage: null, previousPage: null })
.mockResolvedValueOnce({ items: [], total: 0, nextPage: null, previousPage: null });
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
code: "ASSET_NOT_IN_ALBUM",
@@ -248,7 +236,7 @@ test("rechecks exact album membership after database locks before inserting", as
.select({ value: count() })
.from(usages)
.where(eq(usages.editorialAccountId, editorialId));
expect(immich.getAlbum).toHaveBeenCalledTimes(2);
expect(immich.getAlbum).toHaveBeenCalledTimes(1);
expect(usageCount.value).toBe(0);
});
@@ -397,6 +385,19 @@ test("the same key may be reused by a different editorial but not for a differen
});
});
function errorChainIncludes(expected: string) {
return (error: unknown): boolean => {
let current = error;
while (current instanceof Error) {
if (current.message.includes(expected)) return true;
const cause: unknown = current.cause;
if (!cause) break;
current = cause;
}
return false;
};
}
test("an audit failure rolls back both the usage and authorized event", async () => {
const editorialId = await seedEditorial();
const { usageService } = createServices();
@@ -413,7 +414,9 @@ test("an audit failure rolls back both the usage and authorized event", async ()
`);
try {
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toThrow("audit rejected");
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toSatisfy(
errorChainIncludes("audit rejected"),
);
} finally {
await testDb.pool.query("drop trigger reject_billable_usage_audit on audit_events");
await testDb.pool.query("drop function reject_billable_usage_audit()");