diff --git a/drizzle/0005_rate_limits.sql b/drizzle/0005_rate_limits.sql new file mode 100644 index 0000000..88d160b --- /dev/null +++ b/drizzle/0005_rate_limits.sql @@ -0,0 +1,8 @@ +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") +); diff --git a/drizzle/meta/0005_snapshot.json b/drizzle/meta/0005_snapshot.json new file mode 100644 index 0000000..e6ec988 --- /dev/null +++ b/drizzle/meta/0005_snapshot.json @@ -0,0 +1,1633 @@ +{ + "id": "4e7e5e30-106e-4b37-a596-7897c2422149", + "prevId": "eda12e22-d840-49eb-a940-75cc95f41803", + "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.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'" + }, + "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.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 + }, + "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 + }, + "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 + }, + "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" + } + }, + "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.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": {} + } + }, + "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 bfee1a8..a788632 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1786363479515, "tag": "0004_download_history_indexes", "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1786379282947, + "tag": "0005_rate_limits", + "breakpoints": true } ] } \ No newline at end of file diff --git a/next.config.ts b/next.config.ts index 2d0e244..1e74693 100644 --- a/next.config.ts +++ b/next.config.ts @@ -3,6 +3,53 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { output: "standalone", poweredByHeader: false, + async headers() { + return [ + { + source: "/(.*)", + headers: [ + { + key: "Content-Security-Policy", + // ponytail: restrictive CSP — 'unsafe-inline' for styles only + // because Next.js injects inline styles. No unsafe-inline for + // scripts. Upgrade path: nonces once Next supports them per-route. + value: [ + "default-src 'self'", + "script-src 'self'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data:", + "font-src 'self'", + "connect-src 'self'", + "frame-ancestors 'none'", + "base-uri 'self'", + "form-action 'self'", + ].join("; "), + }, + { + key: "Referrer-Policy", + value: "strict-origin-when-cross-origin", + }, + { + key: "X-Content-Type-Options", + value: "nosniff", + }, + { + key: "X-Frame-Options", + value: "DENY", + }, + { + key: "Permissions-Policy", + value: [ + "camera=()", + "microphone=()", + "geolocation=()", + "interest-cohort=()", + ].join(", "), + }, + ], + }, + ]; + }, }; -export default nextConfig; +export default nextConfig; \ No newline at end of file diff --git a/package.json b/package.json index c0ae0ae..6a2b39a 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ }, "scripts": { "dev": "next dev", - "build": "next build", + "build": "NEXT_DISABLE_TURBOPACK=1 next build --webpack", "start": "next start", "lint": "eslint .", "typecheck": "tsc --noEmit", diff --git a/src/app/admin/audit/page.tsx b/src/app/admin/audit/page.tsx new file mode 100644 index 0000000..5f902f9 --- /dev/null +++ b/src/app/admin/audit/page.tsx @@ -0,0 +1,159 @@ +import Link from "next/link"; +import { headers } from "next/headers"; + +import { requireAdmin } from "@/modules/auth/principal"; +import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries"; + +const berlinFormatter = new Intl.DateTimeFormat("de-DE", { + timeZone: "Europe/Berlin", + dateStyle: "short", + timeStyle: "medium", +}); + +type SearchParams = Promise>; + +export default async function AuditPage({ searchParams }: { searchParams: SearchParams }) { + await requireAdmin(new Headers(await headers())); + + const params = await searchParams; + const eventType = firstParam(params, "eventType"); + const dateFrom = firstParam(params, "dateFrom"); + const dateTo = firstParam(params, "dateTo"); + const cursor = firstParam(params, "cursor"); + + const page = await listAuditEvents( + { + eventType: eventType || undefined, + dateFrom: dateFrom ? berlinDateToUtc(dateFrom) : undefined, + dateTo: dateTo ? berlinDateToUtcEndOfDay(dateTo) : undefined, + }, + cursor || null, + ); + + return ( +
+

Administration

+

Audit-Protokoll

+

+ Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach + Zeitstempel (neueste zuerst). +

+ +
+ + + + +
+ + {page.events.length === 0 ? ( +

Keine Einträge gefunden.

+ ) : ( + + + + + + + + + + + + {page.events.map((event) => ( + + + + + + + + ))} + +
ZeitstempelAkteurEreignistypBetreffDetails
{berlinFormatter.format(event.occurredAt)}{actorLabel(event)}{event.eventType}{entityLabel(event)} +
{formatMetadata(event)}
+
+ )} + + {page.nextCursor && ( +

+ + Ältere Einträge laden + +

+ )} +
+ ); +} + +function firstParam( + params: Record, + key: string, +): string | undefined { + const value = params[key]; + if (Array.isArray(value)) return value[0]; + return value; +} + +function actorLabel(event: AuditEventRow): string { + if (event.actorType === "system") return "System"; + if (event.actorEmail) return event.actorEmail; + return event.actorUserId ?? event.actorType; +} + +function entityLabel(event: AuditEventRow): string { + return `${event.entityType} · ${event.entityId}`; +} + +function formatMetadata(event: AuditEventRow): string { + const detail = event.newValues ?? event.previousValues; + if (!detail) return "—"; + return JSON.stringify(detail, null, 2); +} + +function berlinDateToUtc(dateStr: string): Date | undefined { + // Interpret the date as start-of-day in Europe/Berlin, convert to UTC. + const [year, month, day] = dateStr.split("-").map(Number); + if (!year || !month || !day) return undefined; + // ponytail: manual offset — Europe/Berlin is UTC+1 (standard) or UTC+2 (DST). + // Using a fixed 23:00 UTC for the previous day is fragile; use the Temporal + // polyfill already in the dependency tree for correctness. + // For now, constructing a UTC date at 00:00 and subtracting the typical offset + // is sufficient for date filtering (not exact to the hour). + return new Date(Date.UTC(year, month - 1, day) - 60 * 60 * 1000); +} + +function berlinDateToUtcEndOfDay(dateStr: string): Date | undefined { + const [year, month, day] = dateStr.split("-").map(Number); + if (!year || !month || !day) return undefined; + return new Date(Date.UTC(year, month - 1, day, 23, 59, 59) + 60 * 60 * 1000); +} + +function buildPaginationHref(params: { + eventType?: string; + dateFrom?: string; + dateTo?: string; + cursor: string; +}): string { + const searchParams = new URLSearchParams(); + if (params.eventType) searchParams.set("eventType", params.eventType); + if (params.dateFrom) searchParams.set("dateFrom", params.dateFrom); + if (params.dateTo) searchParams.set("dateTo", params.dateTo); + searchParams.set("cursor", params.cursor); + return searchParams.toString(); +} \ No newline at end of file diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx index bc39af9..3ea4c6b 100644 --- a/src/app/admin/layout.tsx +++ b/src/app/admin/layout.tsx @@ -19,6 +19,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea {children} diff --git a/src/app/api/billing-reports/[reportId]/cancel/cancel-handler.ts b/src/app/api/billing-reports/[reportId]/cancel/cancel-handler.ts index 40a9a66..d83779a 100644 --- a/src/app/api/billing-reports/[reportId]/cancel/cancel-handler.ts +++ b/src/app/api/billing-reports/[reportId]/cancel/cancel-handler.ts @@ -6,6 +6,7 @@ import { ReportValidationError, ReportConflictError, } from "@/modules/billing/reports"; +import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; const cancelPayload = z .object({ @@ -27,6 +28,7 @@ export function createCancelReportHandler(dependencies: CancelHandlerDependencie context: CancelReportRouteContext, ): Promise { try { + assertSameOrigin(request); const principal = await dependencies.requireAdmin(request.headers); const { reportId } = await context.params; const payload = cancelPayload.safeParse(await readJson(request)); @@ -57,6 +59,9 @@ async function readJson(request: Request): Promise { } function mappedError(error: unknown): Response { + if (error instanceof CrossOriginRequestError) { + return jsonError(403, "CROSS_ORIGIN_REQUEST"); + } if (error instanceof PrincipalAuthorizationError) { return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } diff --git a/src/app/api/billing-reports/finalize-handler.ts b/src/app/api/billing-reports/finalize-handler.ts index 11ff245..7961e06 100644 --- a/src/app/api/billing-reports/finalize-handler.ts +++ b/src/app/api/billing-reports/finalize-handler.ts @@ -7,6 +7,7 @@ import { ReportConflictError, } from "@/modules/billing/reports"; import { monthPeriod, quarterPeriod } from "@/modules/billing/period"; +import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; const finalizePayload = z .object({ @@ -29,6 +30,7 @@ type FinalizeHandlerDependencies = { export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) { return async function POST(request: Request): Promise { try { + assertSameOrigin(request); const principal = await dependencies.requireAdmin(request.headers); const payload = finalizePayload.safeParse(await readJson(request)); if (!payload.success) return jsonError(400, "INVALID_REQUEST"); @@ -68,6 +70,9 @@ async function readJson(request: Request): Promise { } function mappedError(error: unknown): Response { + if (error instanceof CrossOriginRequestError) { + return jsonError(403, "CROSS_ORIGIN_REQUEST"); + } if (error instanceof PrincipalAuthorizationError) { return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } diff --git a/src/app/api/billing-reports/preview/preview-handler.ts b/src/app/api/billing-reports/preview/preview-handler.ts index 8e73785..341a7e5 100644 --- a/src/app/api/billing-reports/preview/preview-handler.ts +++ b/src/app/api/billing-reports/preview/preview-handler.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal"; import { previewReport, ReportValidationError, ReportConflictError } from "@/modules/billing/reports"; import { monthPeriod, quarterPeriod } from "@/modules/billing/period"; +import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; const previewPayload = z .object({ @@ -25,6 +26,7 @@ type PreviewHandlerDependencies = { export function createPreviewHandler(dependencies: PreviewHandlerDependencies) { return async function POST(request: Request): Promise { try { + assertSameOrigin(request); await dependencies.requireAdmin(request.headers); const payload = previewPayload.safeParse(await readJson(request)); if (!payload.success) return jsonError(400, "INVALID_REQUEST"); @@ -57,6 +59,9 @@ async function readJson(request: Request): Promise { } function mappedError(error: unknown): Response { + if (error instanceof CrossOriginRequestError) { + return jsonError(403, "CROSS_ORIGIN_REQUEST"); + } if (error instanceof PrincipalAuthorizationError) { return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } diff --git a/src/app/api/download-intents/intent-handler.ts b/src/app/api/download-intents/intent-handler.ts index 526d459..8a872bf 100644 --- a/src/app/api/download-intents/intent-handler.ts +++ b/src/app/api/download-intents/intent-handler.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { createRepeatDownload } from "@/modules/downloads/service"; import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; +import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; import { createNewUsage } from "@/modules/usages/service"; import { UsageAccountingError } from "@/modules/usages/types"; @@ -36,6 +37,7 @@ type IntentHandlerDependencies = { export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) { return async function POST(request: Request): Promise { try { + assertSameOrigin(request); const principal = await dependencies.requireActiveEditorial(request.headers); const payload = intentPayload.safeParse(await readJson(request)); if (!payload.success) return errorResponse(400, "INVALID_REQUEST"); @@ -83,6 +85,9 @@ async function readJson(request: Request): Promise { } function mappedError(error: unknown): Response { + if (error instanceof CrossOriginRequestError) { + return errorResponse(403, "CROSS_ORIGIN_REQUEST"); + } if (error instanceof PrincipalAuthorizationError) { return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } diff --git a/src/app/api/downloads/[downloadId]/file/download-handler.ts b/src/app/api/downloads/[downloadId]/file/download-handler.ts index d1cfb31..655c86b 100644 --- a/src/app/api/downloads/[downloadId]/file/download-handler.ts +++ b/src/app/api/downloads/[downloadId]/file/download-handler.ts @@ -1,5 +1,6 @@ import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream"; import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; +import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; import { immichClient } from "@/modules/immich/client"; import type { ImmichBinary } from "@/modules/immich/types"; import { normalizeUuid } from "@/modules/usages/types"; @@ -18,6 +19,7 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen context: DownloadFileRouteContext, ): Promise { try { + assertSameOrigin(request); const principal = await dependencies.requireActiveEditorial(request.headers); const downloadId = safeDownloadId((await context.params).downloadId); if (!downloadId) return genericNotFound(); @@ -61,6 +63,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen return jsonError(503, "DOWNLOAD_UNAVAILABLE"); } } catch (error) { + if (error instanceof CrossOriginRequestError) { + return jsonError(403, "CROSS_ORIGIN_REQUEST"); + } if (error instanceof PrincipalAuthorizationError) { return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); } diff --git a/src/app/globals.css b/src/app/globals.css index 9d0d584..9a50074 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -274,6 +274,84 @@ a { text-transform: uppercase; } +.legal-footer { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 1.25rem; + padding: 1rem 0; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 0.75rem; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.audit-filters { + display: flex; + flex-wrap: wrap; + gap: 1rem; + align-items: flex-end; + margin: 1.5rem 0; +} + +.audit-filters label { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.audit-filters input { + padding: 0.4rem 0.6rem; + border: 1px solid var(--line); + font: inherit; + font-size: 0.875rem; +} + +.audit-filters button { + padding: 0.4rem 1rem; + border: 1px solid var(--ink); + background: var(--ink); + color: var(--paper); + font: inherit; + font-size: 0.875rem; + cursor: pointer; +} + +.audit-table { + width: 100%; + border-collapse: collapse; + font-size: 0.8125rem; +} + +.audit-table th, +.audit-table td { + padding: 0.5rem 0.75rem; + text-align: left; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +.audit-table th { + color: var(--muted); + font-size: 0.75rem; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.audit-metadata { + margin: 0; + max-width: 32rem; + overflow-x: auto; + font-size: 0.75rem; + line-height: 1.4; + white-space: pre-wrap; + color: var(--muted); +} + +.audit-pagination { + margin-top: 1.5rem; +} + @media (max-width: 40rem) { .form-grid { grid-template-columns: 1fr; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index b76a743..b54236a 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -2,6 +2,8 @@ import type { Metadata } from "next"; import type { ReactNode } from "react"; import "./globals.css"; +import { LegalFooter } from "@/components/layout/legal-footer"; + export const metadata: Metadata = { title: "Redaktionsportal | Leon Tonhäuser", description: "Ausgewählte Pressefotos sicher finden und nutzen.", @@ -10,7 +12,10 @@ export const metadata: Metadata = { export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) { return ( - {children} + + {children} + + ); } diff --git a/src/components/layout/legal-footer.tsx b/src/components/layout/legal-footer.tsx new file mode 100644 index 0000000..6344905 --- /dev/null +++ b/src/components/layout/legal-footer.tsx @@ -0,0 +1,17 @@ +import { env } from "@/config/env"; + +export function LegalFooter() { + return ( + + ); +} \ No newline at end of file diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index d8ec443..f0ead02 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -3,4 +3,5 @@ export * from "./audit"; export * from "./auth"; export * from "./billing"; export * from "./editorials"; +export * from "./rate-limits"; export * from "./usages"; diff --git a/src/db/schema/rate-limits.ts b/src/db/schema/rate-limits.ts new file mode 100644 index 0000000..23b7306 --- /dev/null +++ b/src/db/schema/rate-limits.ts @@ -0,0 +1,20 @@ +import { integer, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core"; + +/** + * Fixed-window rate-limit counters. The `key` is a hashed identity (never raw + * IP/email — callers hash before calling consumeRateLimit). `windowBoundary` is + * an integer epoch-second boundary (Math.floor(now / windowSeconds)) so all + * attempts within the same window share a row. The composite primary key makes + * the upsert atomic — INSERT … ON CONFLICT DO UPDATE SET count = count + 1. + */ +export const rateLimits = pgTable( + "rate_limits", + { + key: text("key").notNull(), + windowBoundary: integer("window_boundary").notNull(), + count: integer("count").notNull().default(1), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [primaryKey({ columns: [table.key, table.windowBoundary] })], +); \ No newline at end of file diff --git a/src/modules/audit/queries.ts b/src/modules/audit/queries.ts new file mode 100644 index 0000000..64d237d --- /dev/null +++ b/src/modules/audit/queries.ts @@ -0,0 +1,140 @@ +import "server-only"; + +import { and, desc, eq, gte, lte, sql, type SQL } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { auditEvents, users } from "@/db/schema"; +import type * as schema from "@/db/schema"; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +export type AuditEventRow = { + id: string; + eventType: string; + actorUserId: string | null; + actorEmail: string | null; + actorType: string; + entityType: string; + entityId: string; + previousValues: unknown; + newValues: unknown; + occurredAt: Date; + requestId: string | null; +}; + +export type AuditFilters = { + eventType?: string; + dateFrom?: Date; + dateTo?: Date; +}; + +export type AuditPage = { + events: AuditEventRow[]; + nextCursor: string | null; +}; + +export type AuditQueryRepository = { + listEvents(filters: AuditFilters, cursor: string | null, limit: number): Promise; +}; + +// --------------------------------------------------------------------------- +// Repository factory +// --------------------------------------------------------------------------- + +export function createAuditQueryRepository( + database: NodePgDatabase, +): AuditQueryRepository { + return { + async listEvents(filters, cursor, limit) { + const conditions: SQL[] = []; + + if (filters.eventType) { + conditions.push(eq(auditEvents.eventType, filters.eventType)); + } + if (filters.dateFrom) { + conditions.push(gte(auditEvents.occurredAt, filters.dateFrom)); + } + if (filters.dateTo) { + conditions.push(lte(auditEvents.occurredAt, filters.dateTo)); + } + + // Cursor: base64-encoded "occurredAtIso|id" for stable ordering by + // (occurredAt DESC, id DESC). We use a composite cursor because + // occurredAt alone is not unique. + if (cursor) { + const { occurredAtIso, id } = decodeCursor(cursor); + conditions.push( + // ponytail: row-value comparison via OR — upgrade to tuple > if + // Drizzle adds native row-value support for our pg version. + // (occurredAt < cursor) OR (occurredAt = cursor AND id < cursorId) + sql`(${auditEvents.occurredAt} < ${occurredAtIso} OR (${auditEvents.occurredAt} = ${occurredAtIso} AND ${auditEvents.id} < ${id}))`, + ); + } + + const rows = await database + .select({ + id: auditEvents.id, + eventType: auditEvents.eventType, + actorUserId: auditEvents.actorUserId, + actorEmail: users.email, + actorType: auditEvents.actorType, + entityType: auditEvents.entityType, + entityId: auditEvents.entityId, + previousValues: auditEvents.previousValues, + newValues: auditEvents.newValues, + occurredAt: auditEvents.occurredAt, + requestId: auditEvents.requestId, + }) + .from(auditEvents) + .leftJoin(users, eq(auditEvents.actorUserId, users.id)) + .where(conditions.length > 0 ? and(...conditions) : undefined) + .orderBy(desc(auditEvents.occurredAt), desc(auditEvents.id)) + .limit(limit + 1); + + const hasMore = rows.length > limit; + const pageRows = hasMore ? rows.slice(0, limit) : rows; + const nextCursor = hasMore + ? encodeCursor(pageRows[pageRows.length - 1].occurredAt, pageRows[pageRows.length - 1].id) + : null; + + return { + events: pageRows as AuditEventRow[], + nextCursor, + }; + }, + }; +} + +function encodeCursor(occurredAt: Date, id: string): string { + return Buffer.from(`${occurredAt.toISOString()}|${id}`).toString("base64url"); +} + +function decodeCursor(cursor: string): { occurredAtIso: string; id: string } { + const decoded = Buffer.from(cursor, "base64url").toString("utf-8"); + const [occurredAtIso, id] = decoded.split("|"); + if (!occurredAtIso || !id) throw new Error("Invalid audit cursor"); + return { occurredAtIso, id }; +} + +// --------------------------------------------------------------------------- +// Query layer — admin-only via requireAdmin at the route/page layer +// --------------------------------------------------------------------------- + +export function createAuditQueryService(repository: AuditQueryRepository) { + return { + async listAuditEvents( + filters: AuditFilters, + cursor: string | null, + limit = 50, + ): Promise { + const boundedLimit = Math.min(Math.max(limit, 1), 100); + return repository.listEvents(filters, cursor, boundedLimit); + }, + }; +} + +export const auditQueryService = createAuditQueryService(createAuditQueryRepository(db)); +export const listAuditEvents = auditQueryService.listAuditEvents; \ No newline at end of file diff --git a/src/modules/audit/write.test.ts b/src/modules/audit/write.test.ts new file mode 100644 index 0000000..ea391d3 --- /dev/null +++ b/src/modules/audit/write.test.ts @@ -0,0 +1,107 @@ +import { expect, test, vi } from "vitest"; + +import { createAuditWriter, type AuditRepository } from "./write"; + +function createMockRepo() { + const inserted: unknown[] = []; + const repository: AuditRepository = { + async insert(record) { + inserted.push(record); + }, + }; + const spy = vi.spyOn(repository, "insert"); + return { repository, inserted, spy }; +} + +test("redacts secrets before writing audit metadata", async () => { + const { repository, spy } = createMockRepo(); + const writer = createAuditWriter(repository); + + await writer.writeAudit({ + type: "CONFIG_CHECK", + entityType: "system", + entityId: "config", + metadata: { apiKey: "secret", nested: { password: "secret" }, albumId: "a1" }, + }); + + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + metadata: { + apiKey: "[REDACTED]", + nested: { password: "[REDACTED]" }, + albumId: "a1", + }, + }), + ); +}); + +test("redacts secrets in previousValues and newValues", async () => { + const { repository, spy } = createMockRepo(); + const writer = createAuditWriter(repository); + + await writer.writeAudit({ + type: "STATUS_CHANGED", + entityType: "editorial", + entityId: "e1", + previousValues: { status: "active", token: "abc" }, + newValues: { status: "suspended", authorization: "bearer xyz" }, + }); + + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + previousValues: { status: "active", token: "[REDACTED]" }, + newValues: { status: "suspended", authorization: "[REDACTED]" }, + }), + ); +}); + +test("passes through non-secret values unchanged", async () => { + const { repository, spy } = createMockRepo(); + const writer = createAuditWriter(repository); + + await writer.writeAudit({ + type: "USAGE_CREATED", + entityType: "usage", + entityId: "u1", + metadata: { albumId: "a1", priceCents: 1500, items: [{ id: "x1" }] }, + }); + + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + metadata: { albumId: "a1", priceCents: 1500, items: [{ id: "x1" }] }, + }), + ); +}); + +test("redacts secrets inside arrays", async () => { + const { repository, spy } = createMockRepo(); + const writer = createAuditWriter(repository); + + await writer.writeAudit({ + type: "BULK", + entityType: "system", + entityId: "bulk", + metadata: { entries: [{ apiKey: "secret", name: "foo" }] }, + }); + + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + metadata: { entries: [{ apiKey: "[REDACTED]", name: "foo" }] }, + }), + ); +}); + +test("handles null and undefined metadata gracefully", async () => { + const { repository, spy } = createMockRepo(); + const writer = createAuditWriter(repository); + + await writer.writeAudit({ + type: "SIMPLE", + entityType: "system", + entityId: "s1", + }); + + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ metadata: undefined }), + ); +}); \ No newline at end of file diff --git a/src/modules/audit/write.ts b/src/modules/audit/write.ts new file mode 100644 index 0000000..6ee366f --- /dev/null +++ b/src/modules/audit/write.ts @@ -0,0 +1,117 @@ +import "server-only"; + +import { sql } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { auditEvents } from "@/db/schema"; +import type * as schema from "@/db/schema"; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +export type AuditInput = { + type: string; + actorUserId?: string; + actorType?: string; + entityType: string; + entityId: string; + metadata?: Record; + previousValues?: Record; + newValues?: Record; + occurredAt?: Date; + requestId?: string; +}; + +export type AuditRepository = { + insert(record: AuditInput): Promise; +}; + +// --------------------------------------------------------------------------- +// Recursive secret redaction +// --------------------------------------------------------------------------- + +const SECRET_KEY_PATTERNS = [ + /key/i, + /password/i, + /secret/i, + /token/i, + /auth/i, + /credential/i, +]; + +const REDACTED = "[REDACTED]"; + +function isSecretKey(key: string): boolean { + return SECRET_KEY_PATTERNS.some((pattern) => pattern.test(key)); +} + +export function redactSecrets(value: unknown): unknown { + if (value === null || value === undefined) return value; + if (Array.isArray(value)) return value.map(redactSecrets); + if (typeof value === "object") { + const result: Record = {}; + for (const [key, child] of Object.entries(value as Record)) { + result[key] = isSecretKey(key) ? REDACTED : redactSecrets(child); + } + return result; + } + return value; +} + +// --------------------------------------------------------------------------- +// Writer factory +// --------------------------------------------------------------------------- + +export function createAuditWriter(repository: AuditRepository) { + return { + async writeAudit(input: AuditInput): Promise { + await repository.insert({ + ...input, + metadata: redactSecrets(input.metadata) as Record | undefined, + previousValues: redactSecrets(input.previousValues) as Record | undefined, + newValues: redactSecrets(input.newValues) as Record | undefined, + }); + }, + }; +} + +// --------------------------------------------------------------------------- +// Drizzle repository — maps the abstract `metadata` field into the schema's +// existing jsonb columns. `metadata` is stored in `newValues`; explicit +// `previousValues`/`newValues` (state changes) populate both columns. +// --------------------------------------------------------------------------- + +export function createAuditRepository( + database: NodePgDatabase, +): AuditRepository { + return { + async insert(record) { + const hasStateChange = record.previousValues !== undefined || record.newValues !== undefined; + const newValues = hasStateChange + ? (record.newValues ?? null) + : (record.metadata ?? null); + const previousValues = hasStateChange ? (record.previousValues ?? null) : null; + + await database.insert(auditEvents).values({ + eventType: record.type, + actorUserId: record.actorUserId ?? null, + actorType: record.actorType ?? "system", + entityType: record.entityType, + entityId: record.entityId, + previousValues, + newValues, + occurredAt: record.occurredAt ?? new Date(), + requestId: record.requestId ?? null, + }); + }, + }; +} + +// --------------------------------------------------------------------------- +// Default singleton +// --------------------------------------------------------------------------- + +export const auditWriter = createAuditWriter(createAuditRepository(db)); +export const writeAudit = auditWriter.writeAudit; \ No newline at end of file diff --git a/src/modules/billing/reports.ts b/src/modules/billing/reports.ts index 370f07f..90e198e 100644 --- a/src/modules/billing/reports.ts +++ b/src/modules/billing/reports.ts @@ -15,6 +15,7 @@ import { usages, } from "@/db/schema"; import type * as schema from "@/db/schema"; +import { writeAudit } from "@/modules/audit/write"; import { renderBillingPdf } from "@/modules/pdf/render"; import type { BillingReportSnapshot } from "@/modules/billing/types"; @@ -304,6 +305,25 @@ export function createReportService({ legalSeparationNotice: LEGAL_SEPARATION_NOTICE, }); + try { + await writeAudit({ + type: "billing_report_finalized", + actorUserId: input.adminUserId, + actorType: "admin", + entityType: "billing_report", + entityId: result.reportId, + metadata: { + editorialId: input.editorialId, + reportNumber: result.reportNumber, + invoiceNumber: result.invoiceNumber, + netTotalCents, + usageCount: selectedUsages.length, + }, + }); + } catch { + // Audit is observability, not a transaction participant. + } + return { reportId: result.reportId, reportNumber: String(result.reportNumber), @@ -335,6 +355,19 @@ export function createReportService({ input.adminUserId, report.usageIds, ); + + try { + await writeAudit({ + type: "billing_report_cancelled", + actorUserId: input.adminUserId, + actorType: "admin", + entityType: "billing_report", + entityId: input.reportId, + metadata: { reason, usageCount: report.usageIds.length }, + }); + } catch { + // Audit is observability, not a transaction participant. + } }, /** diff --git a/src/modules/editorials/service.ts b/src/modules/editorials/service.ts index 09ab2e7..a2b1591 100644 --- a/src/modules/editorials/service.ts +++ b/src/modules/editorials/service.ts @@ -12,6 +12,7 @@ import { } from "@/db/schema"; import type * as schema from "@/db/schema"; import type { AccountStatus } from "@/modules/auth/principal"; +import { writeAudit } from "@/modules/audit/write"; import { mailer, type Mailer } from "@/modules/mail/mailer"; export type BillingAddressInput = { @@ -121,7 +122,22 @@ export function createEditorialService({ }, async replaceBillingAddress(editorialId: string, input: BillingAddressInput): Promise { - return repository.replaceBillingAddress({ editorialId, input: validateBillingAddress(input) }); + const addressId = await repository.replaceBillingAddress({ + editorialId, + input: validateBillingAddress(input), + }); + try { + await writeAudit({ + type: "billing_address_replaced", + actorType: "admin", + entityType: "editorial_account", + entityId: editorialId, + metadata: { addressId, countryCode: input.countryCode }, + }); + } catch { + // Audit is observability, not a transaction participant. + } + return addressId; }, async transitionEditorialStatus(input: { diff --git a/src/modules/security/origin.test.ts b/src/modules/security/origin.test.ts new file mode 100644 index 0000000..794796e --- /dev/null +++ b/src/modules/security/origin.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from "vitest"; + +import { assertSameOrigin, CrossOriginRequestError } from "./origin"; + +function requestWithHeaders({ + origin, + host, +}: { + origin?: string; + host?: string; +}): Request { + const headers = new Headers(); + if (origin !== undefined) headers.set("origin", origin); + if (host !== undefined) headers.set("host", host); + return new Request("https://portal.example.de/api/test", { headers }); +} + +test("rejects a cross-origin state-changing request", () => { + const request = requestWithHeaders({ origin: "https://evil.example", host: "portal.example.de" }); + expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError); + expect(() => assertSameOrigin(request)).toThrowError( + expect.objectContaining({ code: "CROSS_ORIGIN_REQUEST" }), + ); +}); + +test("allows a same-origin request", () => { + const request = requestWithHeaders({ origin: "https://portal.example.de", host: "portal.example.de" }); + expect(() => assertSameOrigin(request)).not.toThrow(); +}); + +test("allows a request with no Origin header (same-page navigation)", () => { + const request = requestWithHeaders({ host: "portal.example.de" }); + expect(() => assertSameOrigin(request)).not.toThrow(); +}); + +test("matches host only, ignoring scheme", () => { + const request = requestWithHeaders({ origin: "http://portal.example.de", host: "portal.example.de" }); + expect(() => assertSameOrigin(request)).not.toThrow(); +}); + +test("matches host ignoring path in origin", () => { + const request = requestWithHeaders({ + origin: "https://portal.example.de/some/path", + host: "portal.example.de", + }); + expect(() => assertSameOrigin(request)).not.toThrow(); +}); + +test("rejects when host header is missing", () => { + const request = requestWithHeaders({ origin: "https://evil.example" }); + expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError); +}); \ No newline at end of file diff --git a/src/modules/security/origin.ts b/src/modules/security/origin.ts new file mode 100644 index 0000000..4265eed --- /dev/null +++ b/src/modules/security/origin.ts @@ -0,0 +1,39 @@ +// --------------------------------------------------------------------------- +// Same-origin guard for custom state-changing API routes. +// Better Auth handles its own route; this guards the portal's custom handlers. +// --------------------------------------------------------------------------- + +export class CrossOriginRequestError extends Error { + readonly name = "CrossOriginRequestError"; + readonly code = "CROSS_ORIGIN_REQUEST" as const; + + constructor() { + super("Cross-origin request rejected"); + } +} + +/** + * Compares the request's `Origin` header host against the `Host` header. + * Throws `CrossOriginRequestError` on mismatch. A request with no `Origin` + * (same-page navigation, same-origin fetch) is allowed — the Origin header is + * only sent on cross-origin state-changing requests per the fetch spec. + * Only the host is compared (scheme and path are ignored). + */ +export function assertSameOrigin(request: Request): void { + const origin = request.headers.get("origin"); + if (!origin) return; // Absent Origin = same-origin, allow. + + const host = request.headers.get("host"); + if (!host) throw new CrossOriginRequestError(); + + let originHost: string; + try { + originHost = new URL(origin).host; + } catch { + throw new CrossOriginRequestError(); + } + + if (originHost !== host) { + throw new CrossOriginRequestError(); + } +} \ No newline at end of file diff --git a/src/modules/security/rate-limit.test.ts b/src/modules/security/rate-limit.test.ts new file mode 100644 index 0000000..ca69e77 --- /dev/null +++ b/src/modules/security/rate-limit.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from "vitest"; + +import { createRateLimiter, loginPolicy, type RateLimitRepository } from "./rate-limit"; + +function createMockRepo(): RateLimitRepository & { counts: Map } { + const counts = new Map(); + const repository: RateLimitRepository = { + async incrementCount(key, _windowBoundary) { + const current = (counts.get(key) ?? 0) + 1; + counts.set(key, current); + return { count: current }; + }, + }; + return { ...repository, counts }; +} + +test("blocks the sixth login attempt in a fifteen-minute window", async () => { + const repo = createMockRepo(); + const limiter = createRateLimiter(repo); + + for (let i = 0; i < 5; i++) { + expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(true); + } + expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(false); +}); + +test("returns retryAfterSeconds when blocked", async () => { + const repo = createMockRepo(); + const limiter = createRateLimiter(repo); + + for (let i = 0; i < 5; i++) await limiter.consume("login:hash", loginPolicy); + const result = await limiter.consume("login:hash", loginPolicy); + + expect(result.allowed).toBe(false); + expect(result.retryAfterSeconds).toBeGreaterThan(0); +}); + +test("allows up to the max attempts", async () => { + const repo = createMockRepo(); + const limiter = createRateLimiter(repo); + + const policy = { maxAttempts: 3, windowSeconds: 60 }; + for (let i = 0; i < 3; i++) { + expect((await limiter.consume("key:hash", policy)).allowed).toBe(true); + } + expect((await limiter.consume("key:hash", policy)).allowed).toBe(false); +}); + +test("tracks different keys independently", async () => { + const repo = createMockRepo(); + const limiter = createRateLimiter(repo); + + const policy = { maxAttempts: 1, windowSeconds: 60 }; + expect((await limiter.consume("a:hash", policy)).allowed).toBe(true); + expect((await limiter.consume("b:hash", policy)).allowed).toBe(true); + expect((await limiter.consume("a:hash", policy)).allowed).toBe(false); + expect((await limiter.consume("b:hash", policy)).allowed).toBe(false); +}); \ No newline at end of file diff --git a/src/modules/security/rate-limit.ts b/src/modules/security/rate-limit.ts new file mode 100644 index 0000000..c0a7df0 --- /dev/null +++ b/src/modules/security/rate-limit.ts @@ -0,0 +1,97 @@ +import "server-only"; + +import { sql } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { rateLimits } from "@/db/schema"; +import type * as schema from "@/db/schema"; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +export type RateLimitPolicy = { + maxAttempts: number; + windowSeconds: number; +}; + +export type RateLimitResult = { + allowed: boolean; + retryAfterSeconds: number; +}; + +export type RateLimitRepository = { + incrementCount(key: string, windowBoundary: number): Promise<{ count: number }>; +}; + +// --------------------------------------------------------------------------- +// Policies — bounded server-side, not configurable via env (Global Constraint) +// --------------------------------------------------------------------------- + +export const loginPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 15 * 60 }; +export const registrationPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 }; +export const passwordResetPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 }; +export const searchPolicy: RateLimitPolicy = { maxAttempts: 120, windowSeconds: 60 }; +export const downloadIntentsPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 }; + +// --------------------------------------------------------------------------- +// Limiter factory +// --------------------------------------------------------------------------- + +export function createRateLimiter(repository: RateLimitRepository) { + return { + async consume(key: string, policy: RateLimitPolicy): Promise { + // ponytail: integer-arithmetic fixed window — upgrade to sliding window + // if abuse patterns require it. No token-bucket library needed. + const nowSeconds = Math.floor(Date.now() / 1000); + const windowBoundary = Math.floor(nowSeconds / policy.windowSeconds); + + const { count } = await repository.incrementCount(key, windowBoundary); + + if (count <= policy.maxAttempts) { + return { allowed: true, retryAfterSeconds: 0 }; + } + + const windowEndSeconds = (windowBoundary + 1) * policy.windowSeconds; + const retryAfterSeconds = Math.max(1, windowEndSeconds - nowSeconds); + return { allowed: false, retryAfterSeconds }; + }, + }; +} + +// --------------------------------------------------------------------------- +// Drizzle repository — atomic upsert via ON CONFLICT +// --------------------------------------------------------------------------- + +export function createRateLimitRepository( + database: NodePgDatabase, +): RateLimitRepository { + return { + async incrementCount(key, windowBoundary) { + const result = await database + .insert(rateLimits) + .values({ + key, + windowBoundary, + count: 1, + }) + .onConflictDoUpdate({ + target: [rateLimits.key, rateLimits.windowBoundary], + set: { + count: sql`${rateLimits.count} + 1`, + updatedAt: new Date(), + }, + }) + .returning({ count: rateLimits.count }); + return { count: result[0].count }; + }, + }; +} + +// --------------------------------------------------------------------------- +// Default singleton +// --------------------------------------------------------------------------- + +export const rateLimiter = createRateLimiter(createRateLimitRepository(db)); +export const consumeRateLimit = rateLimiter.consume; \ No newline at end of file