diff --git a/README.md b/README.md index 222df64..bc7ab2a 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,36 @@ The bot's socket.io client authenticates with its service token in `auth.token` The IdP notifies `POST /internal/events` when access changes; the backend also polls the snapshot every 30 s. The last good signing keys and snapshot are stored in `common_idp_state`, so a restart during an IdP outage resumes from them. Permission checks deny once the snapshot is more than an hour old. Configuration is in `.env.example`. +## Audit log + +`common_audit_events` records who used which permission to change what through the backend. The tRPC audit middleware +(`src/audit`) writes one event per mutation: the action (the procedure path), the caller from the token, the target, +the outcome (`success`, `failure` when an error is thrown or returned, `denied` when the policy refuses the caller), the +request id shared by the calls of one HTTP request, and when. Calls without a valid token are not recorded. + +Every mutation declares how it is recorded in its procedure meta, and a test walks the router so that none ships +without one, like its policy: + +- `.meta(audit.full())`: also the input, the reason and the states before and after that the handler adds with + `ctx.audit.set(...)`. `fields` keeps only those fields of the input, for inputs that carry personal data or free + text not worth keeping; a dotted field (`output.driveId`) keeps one field of a nested object. +- `.meta(audit.minimal({ target }))`: only the actor, the action, the target and the outcome, for areas that keep their + own history behind their own permissions. People records each change in the person's activity history, and the + Libro Soci in `soci_activity`. +- `.meta(audit.none(why))`: not recorded, e.g. the bot's ingestion, or Telegram moderation, which `tg_audit_log` keeps + under its own retention rules. + +Handlers call `ctx.audit.skip()` when a call changed nothing. Inputs and states are stored without secrets +(`password`, `token`, `ticket`, `code`, `*Key`, `*Secret` fields) or file contents, and are cut when too large. Denied +calls keep no input. + +Events are deleted 24 months after they were written (`AUDIT_EVENTS_RETENTION_MONTHS`). Dashboard users with the IdP +permission `audit:read` read the log with `audit.list`, newest first, paged by `cursor` and filtered by area, outcome, +target, actor, date or text. + +Changes made outside the backend's tRPC procedures are not in the log: directly in Telegram or WhatsApp, the cron jobs, +the e-signing agent endpoints (each request keeps its own history) and roles and permissions in the IdP. + ## People The `people` router is the admin dashboard's register of Group Admins, Capo Admins and team members. Each person diff --git a/drizzle/0040_audit_events.sql b/drizzle/0040_audit_events.sql new file mode 100644 index 0000000..e02b998 --- /dev/null +++ b/drizzle/0040_audit_events.sql @@ -0,0 +1,26 @@ +CREATE TABLE "common_audit_events" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "common_audit_events_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "action" text NOT NULL, + "request_id" uuid, + "actor_kind" varchar(16) NOT NULL, + "actor_sub" text, + "actor_tg_id" bigint, + "actor_client" text, + "target_type" text, + "target_id" text, + "target_label" text, + "reason" text, + "outcome" varchar(16) NOT NULL, + "error" text, + "input" jsonb, + "before" jsonb, + "after" jsonb, + "created_at" timestamp (3) with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE INDEX "common_audit_events_action_idx" ON "common_audit_events" USING btree ("action");--> statement-breakpoint +CREATE INDEX "common_audit_events_actor_sub_idx" ON "common_audit_events" USING btree ("actor_sub");--> statement-breakpoint +CREATE INDEX "common_audit_events_actor_tg_id_idx" ON "common_audit_events" USING btree ("actor_tg_id");--> statement-breakpoint +CREATE INDEX "common_audit_events_target_idx" ON "common_audit_events" USING btree ("target_type","target_id");--> statement-breakpoint +CREATE INDEX "common_audit_events_request_id_idx" ON "common_audit_events" USING btree ("request_id");--> statement-breakpoint +CREATE INDEX "common_audit_events_created_at_idx" ON "common_audit_events" USING btree ("created_at"); \ No newline at end of file diff --git a/drizzle/meta/0040_snapshot.json b/drizzle/meta/0040_snapshot.json new file mode 100644 index 0000000..3a8a1b3 --- /dev/null +++ b/drizzle/meta/0040_snapshot.json @@ -0,0 +1,6811 @@ +{ + "id": "ac5296a1-c544-4a5a-8b72-c7a673d158e3", + "prevId": "81933ec6-6410-441f-8f8d-77f4baeedae8", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.common_audit_events": { + "name": "common_audit_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "common_audit_events_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_tg_id": { + "name": "actor_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "actor_client": { + "name": "actor_client", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_label": { + "name": "target_label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "input": { + "name": "input", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "before": { + "name": "before", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "after": { + "name": "after", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "common_audit_events_action_idx": { + "name": "common_audit_events_action_idx", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "common_audit_events_actor_sub_idx": { + "name": "common_audit_events_actor_sub_idx", + "columns": [ + { + "expression": "actor_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "common_audit_events_actor_tg_id_idx": { + "name": "common_audit_events_actor_tg_id_idx", + "columns": [ + { + "expression": "actor_tg_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "common_audit_events_target_idx": { + "name": "common_audit_events_target_idx", + "columns": [ + { + "expression": "target_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "common_audit_events_request_id_idx": { + "name": "common_audit_events_request_id_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "common_audit_events_created_at_idx": { + "name": "common_audit_events_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.common_group_labels": { + "name": "common_group_labels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "common_group_labels_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "label": { + "name": "label", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "varchar(7)", + "primaryKey": false, + "notNull": true, + "default": "'#ffffff'" + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "common_group_labels_label_unique": { + "name": "common_group_labels_label_unique", + "nullsNotDistinct": false, + "columns": [ + "label" + ] + } + }, + "policies": {}, + "checkConstraints": { + "common_group_labels_creator_check": { + "name": "common_group_labels_creator_check", + "value": "\"common_group_labels\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"common_group_labels\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.common_idp_state": { + "name": "common_idp_state", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.common_webhook_deliveries": { + "name": "common_webhook_deliveries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "common_webhook_deliveries_received_idx": { + "name": "common_webhook_deliveries_received_idx", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_documents": { + "name": "esign_documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "pages": { + "name": "pages", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_documents_request_version_idx": { + "name": "esign_documents_request_version_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"esign_documents\".\"request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_documents_request_id_esign_requests_id_fk": { + "name": "esign_documents_request_id_esign_requests_id_fk", + "tableFrom": "esign_documents", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_drive_access": { + "name": "esign_drive_access", + "schema": "", + "columns": { + "drive_id": { + "name": "drive_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "request_roles": { + "name": "request_roles", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "request_permissions": { + "name": "request_permissions", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "sign_roles": { + "name": "sign_roles", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "sign_permissions": { + "name": "sign_permissions", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "updated_by_sub": { + "name": "updated_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_events": { + "name": "esign_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "esign_events_request_idx": { + "name": "esign_events_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_events_request_id_esign_requests_id_fk": { + "name": "esign_events_request_id_esign_requests_id_fk", + "tableFrom": "esign_events", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_jobs": { + "name": "esign_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "ticket_hash": { + "name": "ticket_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "signer_id": { + "name": "signer_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "base_version": { + "name": "base_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "places": { + "name": "places", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "step": { + "name": "step", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "prepared": { + "name": "prepared", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "prepared_pdf": { + "name": "prepared_pdf", + "type": "bytea", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seen_at": { + "name": "seen_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_jobs_request_idx": { + "name": "esign_jobs_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_jobs_request_id_esign_requests_id_fk": { + "name": "esign_jobs_request_id_esign_requests_id_fk", + "tableFrom": "esign_jobs", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "esign_jobs_signer_id_esign_signers_id_fk": { + "name": "esign_jobs_signer_id_esign_signers_id_fk", + "tableFrom": "esign_jobs", + "tableTo": "esign_signers", + "columnsFrom": [ + "signer_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "esign_jobs_ticket_hash_unique": { + "name": "esign_jobs_ticket_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "ticket_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_profiles": { + "name": "esign_profiles", + "schema": "", + "columns": { + "sub": { + "name": "sub", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fiscal_code": { + "name": "fiscal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_subject": { + "name": "certificate_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_requests": { + "name": "esign_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'in_progress'" + }, + "ordered": { + "name": "ordered", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "delivery": { + "name": "delivery", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "drives": { + "name": "drives", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_requests_status_idx": { + "name": "esign_requests_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_requests_created_by_idx": { + "name": "esign_requests_created_by_idx", + "columns": [ + { + "expression": "created_by_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_signers": { + "name": "esign_signers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "places": { + "name": "places", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "signatures_done": { + "name": "signatures_done", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "signed_at": { + "name": "signed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "fiscal_code": { + "name": "fiscal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_subject": { + "name": "certificate_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_issuer": { + "name": "certificate_issuer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_signers_request_idx": { + "name": "esign_signers_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_signers_sub_idx": { + "name": "esign_signers_sub_idx", + "columns": [ + { + "expression": "sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_signers_request_position_idx": { + "name": "esign_signers_request_position_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_signers_request_id_esign_requests_id_fk": { + "name": "esign_signers_request_id_esign_requests_id_fk", + "tableFrom": "esign_signers", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_activity": { + "name": "people_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "people_activity_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "people_activity_person_idx": { + "name": "people_activity_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_activity_person_id_people_persons_id_fk": { + "name": "people_activity_person_id_people_persons_id_fk", + "tableFrom": "people_activity", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_assignments": { + "name": "people_assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team": { + "name": "team", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_role": { + "name": "team_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capo_scope": { + "name": "capo_scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capo_of_reference_id": { + "name": "capo_of_reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fields": { + "name": "fields", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "since": { + "name": "since", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ended_on": { + "name": "ended_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "change": { + "name": "change", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refusal": { + "name": "refusal", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "command_id": { + "name": "command_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_assignments_person_idx": { + "name": "people_assignments_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_assignments_current_idx": { + "name": "people_assignments_current_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"team\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"people_assignments\".\"ended_on\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_assignments_person_id_people_persons_id_fk": { + "name": "people_assignments_person_id_people_persons_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "people_assignments_capo_of_reference_id_people_persons_id_fk": { + "name": "people_assignments_capo_of_reference_id_people_persons_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_persons", + "columnsFrom": [ + "capo_of_reference_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "people_assignments_command_id_people_role_commands_id_fk": { + "name": "people_assignments_command_id_people_role_commands_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_role_commands", + "columnsFrom": [ + "command_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_assignments_kind_check": { + "name": "people_assignments_kind_check", + "value": "\"people_assignments\".\"kind\" in ('admin', 'capo', 'team')" + }, + "people_assignments_team_check": { + "name": "people_assignments_team_check", + "value": "(\"people_assignments\".\"kind\" = 'team') = (\"people_assignments\".\"team\" is not null and \"people_assignments\".\"team_role\" in ('member', 'lead'))" + }, + "people_assignments_capo_ref_check": { + "name": "people_assignments_capo_ref_check", + "value": "\"people_assignments\".\"kind\" = 'admin' or \"people_assignments\".\"capo_of_reference_id\" is null" + }, + "people_assignments_change_check": { + "name": "people_assignments_change_check", + "value": "\"people_assignments\".\"change\" in ('start', 'end')" + }, + "people_assignments_status_check": { + "name": "people_assignments_status_check", + "value": "\"people_assignments\".\"status\" in ('pending', 'sent', 'applied', 'refused')" + }, + "people_assignments_sent_check": { + "name": "people_assignments_sent_check", + "value": "(\"people_assignments\".\"status\" = 'sent') = (\"people_assignments\".\"command_id\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.people_counters": { + "name": "people_counters", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_invites": { + "name": "people_invites", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_by": { + "name": "sent_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_by": { + "name": "accepted_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_invites_person_idx": { + "name": "people_invites_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_invites_person_id_people_persons_id_fk": { + "name": "people_invites_person_id_people_persons_id_fk", + "tableFrom": "people_invites", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_invites_token_hash_unique": { + "name": "people_invites_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_mail": { + "name": "people_mail", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to": { + "name": "to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempted_at": { + "name": "attempted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "people_mail_person_id_people_persons_id_fk": { + "name": "people_mail_person_id_people_persons_id_fk", + "tableFrom": "people_mail", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_persons": { + "name": "people_persons", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_sub": { + "name": "account_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "linked_at": { + "name": "linked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "linked_by": { + "name": "linked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link_method": { + "name": "link_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_persons_account_sub_unique": { + "name": "people_persons_account_sub_unique", + "nullsNotDistinct": false, + "columns": [ + "account_sub" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_role_commands": { + "name": "people_role_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request": { + "name": "request", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'roles'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_role_commands_queued_idx": { + "name": "people_role_commands_queued_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"people_role_commands\".\"status\" = 'queued'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_role_commands_person_id_people_persons_id_fk": { + "name": "people_role_commands_person_id_people_persons_id_fk", + "tableFrom": "people_role_commands", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_role_commands_status_check": { + "name": "people_role_commands_status_check", + "value": "\"people_role_commands\".\"status\" in ('queued', 'applied', 'refused')" + }, + "people_role_commands_purpose_check": { + "name": "people_role_commands_purpose_check", + "value": "\"people_role_commands\".\"purpose\" in ('roles', 'unlink')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_assignments": { + "name": "regulations_assignments", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_sub": { + "name": "user_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user": { + "name": "user", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "regulations_assignments_user_idx": { + "name": "regulations_assignments_user_idx", + "columns": [ + { + "expression": "user_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_assignments_draft_id_regulations_drafts_id_fk": { + "name": "regulations_assignments_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_assignments", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "regulations_assignments_draft_id_user_sub_pk": { + "name": "regulations_assignments_draft_id_user_sub_pk", + "columns": [ + "draft_id", + "user_sub" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_assignments_role_check": { + "name": "regulations_assignments_role_check", + "value": "\"regulations_assignments\".\"role\" in ('editor', 'commenter', 'viewer')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_blobs": { + "name": "regulations_blobs", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_collab_tickets": { + "name": "regulations_collab_tickets", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user": { + "name": "user", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "read_only": { + "name": "read_only", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_collab_tickets_expiry_idx": { + "name": "regulations_collab_tickets_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_collab_tickets_draft_id_regulations_drafts_id_fk": { + "name": "regulations_collab_tickets_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_collab_tickets", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_comments": { + "name": "regulations_comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "anchor_start": { + "name": "anchor_start", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "anchor_end": { + "name": "anchor_end", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quote": { + "name": "quote", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author": { + "name": "author", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "edited_at": { + "name": "edited_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_by": { + "name": "resolved_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_comments_draft_idx": { + "name": "regulations_comments_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_comments_draft_id_regulations_drafts_id_fk": { + "name": "regulations_comments_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_comments", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_comments_parent_id_regulations_comments_id_fk": { + "name": "regulations_comments_parent_id_regulations_comments_id_fk", + "tableFrom": "regulations_comments", + "tableTo": "regulations_comments", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_comments_anchor_check": { + "name": "regulations_comments_anchor_check", + "value": "(\"regulations_comments\".\"parent_id\" is null) = (\"regulations_comments\".\"file\" is not null and \"regulations_comments\".\"anchor_start\" is not null and \"regulations_comments\".\"anchor_end\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.regulations_compile_refs": { + "name": "regulations_compile_refs", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_compile_refs_draft_id_regulations_drafts_id_fk": { + "name": "regulations_compile_refs_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_compile_refs", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "regulations_compile_refs_draft_id_hash_pk": { + "name": "regulations_compile_refs_draft_id_hash_pk", + "columns": [ + "draft_id", + "hash" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_compiles": { + "name": "regulations_compiles", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ok": { + "name": "ok", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "pdf_blob": { + "name": "pdf_blob", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "errors": { + "name": "errors", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "log": { + "name": "log", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_deleghe": { + "name": "regulations_deleghe", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "grantee_sub": { + "name": "grantee_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "grantee": { + "name": "grantee", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "document_key": { + "name": "document_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "granted_by": { + "name": "granted_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_deleghe_grantee_idx": { + "name": "regulations_deleghe_grantee_idx", + "columns": [ + { + "expression": "grantee_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_deleghe_document_key_regulations_documents_key_fk": { + "name": "regulations_deleghe_document_key_regulations_documents_key_fk", + "tableFrom": "regulations_deleghe", + "tableTo": "regulations_documents", + "columnsFrom": [ + "document_key" + ], + "columnsTo": [ + "key" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_delibere": { + "name": "regulations_delibere", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "date": { + "name": "date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "verbale_url": { + "name": "verbale_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "recorded_by": { + "name": "recorded_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "recorded_at": { + "name": "recorded_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "delega_id": { + "name": "delega_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "on_behalf_of": { + "name": "on_behalf_of", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "withdrawn_at": { + "name": "withdrawn_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "withdrawn_by": { + "name": "withdrawn_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_delibere_current_idx": { + "name": "regulations_delibere_current_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"regulations_delibere\".\"withdrawn_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "regulations_delibere_draft_idx": { + "name": "regulations_delibere_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_delibere_draft_id_regulations_drafts_id_fk": { + "name": "regulations_delibere_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_delibere", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_delibere_delega_id_regulations_deleghe_id_fk": { + "name": "regulations_delibere_delega_id_regulations_deleghe_id_fk", + "tableFrom": "regulations_delibere", + "tableTo": "regulations_deleghe", + "columnsFrom": [ + "delega_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_delibere_kind_check": { + "name": "regulations_delibere_kind_check", + "value": "\"regulations_delibere\".\"kind\" in ('approvazione', 'rettifica')" + }, + "regulations_delibere_body_check": { + "name": "regulations_delibere_body_check", + "value": "(\"regulations_delibere\".\"kind\" = 'approvazione') = (\"regulations_delibere\".\"body\" in ('consiglio_direttivo', 'assemblea'))" + } + }, + "isRLSEnabled": false + }, + "public.regulations_diffs": { + "name": "regulations_diffs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "base_label": { + "name": "base_label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "articles": { + "name": "articles", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "other_changes": { + "name": "other_changes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "categories": { + "name": "categories", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pdf_blob": { + "name": "pdf_blob", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_by": { + "name": "requested_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_diffs_generation_idx": { + "name": "regulations_diffs_generation_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_diffs_draft_id_regulations_drafts_id_fk": { + "name": "regulations_diffs_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_diffs", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_diffs_status_check": { + "name": "regulations_diffs_status_check", + "value": "\"regulations_diffs\".\"status\" in ('pending', 'ready', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_documents": { + "name": "regulations_documents", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dir": { + "name": "dir", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entry": { + "name": "entry", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sources": { + "name": "sources", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "outputs": { + "name": "outputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "tag_prefix": { + "name": "tag_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "procedure": { + "name": "procedure", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_draft_compiles": { + "name": "regulations_draft_compiles", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_good_hash": { + "name": "last_good_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "compiled_at": { + "name": "compiled_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_draft_compiles_draft_id_regulations_drafts_id_fk": { + "name": "regulations_draft_compiles_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_draft_compiles", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_drafts": { + "name": "regulations_drafts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "document_key": { + "name": "document_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "base_version_id": { + "name": "base_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_draft_id": { + "name": "base_draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_files": { + "name": "base_files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "frozen_files": { + "name": "frozen_files", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "parses": { + "name": "parses", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "state_changed_at": { + "name": "state_changed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "emanated_at": { + "name": "emanated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_drafts_document_idx": { + "name": "regulations_drafts_document_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "regulations_drafts_in_approval_idx": { + "name": "regulations_drafts_in_approval_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"regulations_drafts\".\"state\" = 'in_approvazione' and \"regulations_drafts\".\"deleted_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_drafts_document_key_regulations_documents_key_fk": { + "name": "regulations_drafts_document_key_regulations_documents_key_fk", + "tableFrom": "regulations_drafts", + "tableTo": "regulations_documents", + "columnsFrom": [ + "document_key" + ], + "columnsTo": [ + "key" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_drafts_base_version_id_regulations_versions_id_fk": { + "name": "regulations_drafts_base_version_id_regulations_versions_id_fk", + "tableFrom": "regulations_drafts", + "tableTo": "regulations_versions", + "columnsFrom": [ + "base_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_drafts_base_draft_id_regulations_drafts_id_fk": { + "name": "regulations_drafts_base_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_drafts", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "base_draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_drafts_kind_check": { + "name": "regulations_drafts_kind_check", + "value": "\"regulations_drafts\".\"kind\" in ('modifica', 'rettifica')" + }, + "regulations_drafts_state_check": { + "name": "regulations_drafts_state_check", + "value": "\"regulations_drafts\".\"state\" in ('bozza', 'in_approvazione', 'approvata', 'emanata')" + }, + "regulations_drafts_base_check": { + "name": "regulations_drafts_base_check", + "value": "(\"regulations_drafts\".\"base_version_id\" is null) <> (\"regulations_drafts\".\"base_draft_id\" is null)" + } + }, + "isRLSEnabled": false + }, + "public.regulations_emanations": { + "name": "regulations_emanations", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "merge_sha": { + "name": "merge_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "release_id": { + "name": "release_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "version_id": { + "name": "version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "steps": { + "name": "steps", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "started_by": { + "name": "started_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_emanations_draft_id_regulations_drafts_id_fk": { + "name": "regulations_emanations_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_emanations", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_emanations_version_id_regulations_versions_id_fk": { + "name": "regulations_emanations_version_id_regulations_versions_id_fk", + "tableFrom": "regulations_emanations", + "tableTo": "regulations_versions", + "columnsFrom": [ + "version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_emanations_status_check": { + "name": "regulations_emanations_status_check", + "value": "\"regulations_emanations\".\"status\" in ('running', 'waiting', 'done', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_merges": { + "name": "regulations_merges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "target_draft_id": { + "name": "target_draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_kind": { + "name": "source_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_files": { + "name": "source_files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "resolutions": { + "name": "resolutions", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "merged_by": { + "name": "merged_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "merged_at": { + "name": "merged_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "regulations_merges_pair_idx": { + "name": "regulations_merges_pair_idx", + "columns": [ + { + "expression": "target_draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "merged_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_merges_target_draft_id_regulations_drafts_id_fk": { + "name": "regulations_merges_target_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_merges", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "target_draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_notifications": { + "name": "regulations_notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "delega_id": { + "name": "delega_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipients": { + "name": "recipients", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_notifications_draft_idx": { + "name": "regulations_notifications_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_notifications_draft_id_regulations_drafts_id_fk": { + "name": "regulations_notifications_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_notifications", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_notifications_delega_id_regulations_deleghe_id_fk": { + "name": "regulations_notifications_delega_id_regulations_deleghe_id_fk", + "tableFrom": "regulations_notifications", + "tableTo": "regulations_deleghe", + "columnsFrom": [ + "delega_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "regulations_notifications_key_unique": { + "name": "regulations_notifications_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": { + "regulations_notifications_channel_check": { + "name": "regulations_notifications_channel_check", + "value": "\"regulations_notifications\".\"channel\" in ('email', 'telegram')" + }, + "regulations_notifications_status_check": { + "name": "regulations_notifications_status_check", + "value": "\"regulations_notifications\".\"status\" in ('pending', 'sent', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_snapshots": { + "name": "regulations_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "regulations_snapshots_draft_idx": { + "name": "regulations_snapshots_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_snapshots_draft_id_regulations_drafts_id_fk": { + "name": "regulations_snapshots_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_snapshots", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_snapshots_kind_check": { + "name": "regulations_snapshots_kind_check", + "value": "\"regulations_snapshots\".\"kind\" in ('base', 'auto', 'named', 'state', 'restore', 'merge')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_versions": { + "name": "regulations_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "document_key": { + "name": "document_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "commit_sha": { + "name": "commit_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "release_url": { + "name": "release_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pdf_blob": { + "name": "pdf_blob", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assets_blob": { + "name": "assets_blob", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_versions_document_idx": { + "name": "regulations_versions_document_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "regulations_versions_tag_idx": { + "name": "regulations_versions_tag_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_versions_document_key_regulations_documents_key_fk": { + "name": "regulations_versions_document_key_regulations_documents_key_fk", + "tableFrom": "regulations_versions", + "tableTo": "regulations_documents", + "columnsFrom": [ + "document_key" + ], + "columnsTo": [ + "key" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_versions_draft_id_regulations_drafts_id_fk": { + "name": "regulations_versions_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_versions", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_ydocs": { + "name": "regulations_ydocs", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "compacted_through": { + "name": "compacted_through", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_ydocs_draft_id_regulations_drafts_id_fk": { + "name": "regulations_ydocs_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_ydocs", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_yupdates": { + "name": "regulations_yupdates", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "regulations_yupdates_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "update": { + "name": "update", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "regulations_yupdates_draft_idx": { + "name": "regulations_yupdates_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_yupdates_draft_id_regulations_drafts_id_fk": { + "name": "regulations_yupdates_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_yupdates", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.soci_activity": { + "name": "soci_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_activity_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_activity_member_idx": { + "name": "soci_activity_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_activity_member_id_soci_members_id_fk": { + "name": "soci_activity_member_id_soci_members_id_fk", + "tableFrom": "soci_activity", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.soci_fees": { + "name": "soci_fees", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_fees_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "transfer_date": { + "name": "transfer_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "declared_cents": { + "name": "declared_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reviewed_by": { + "name": "reviewed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "rejection_reason": { + "name": "rejection_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "paid_on": { + "name": "paid_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "recorded_by": { + "name": "recorded_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_fees_member_year_idx": { + "name": "soci_fees_member_year_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "year", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "soci_fees_year_idx": { + "name": "soci_fees_year_idx", + "columns": [ + { + "expression": "year", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_fees_member_id_soci_members_id_fk": { + "name": "soci_fees_member_id_soci_members_id_fk", + "tableFrom": "soci_fees", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "soci_fees_file_id_soci_files_id_fk": { + "name": "soci_fees_file_id_soci_files_id_fk", + "tableFrom": "soci_fees", + "tableTo": "soci_files", + "columnsFrom": [ + "file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "soci_fees_status_check": { + "name": "soci_fees_status_check", + "value": "\"soci_fees\".\"status\" in ('due', 'uploaded', 'paid', 'exempt')" + }, + "soci_fees_method_check": { + "name": "soci_fees_method_check", + "value": "\"soci_fees\".\"method\" in ('transfer', 'admission', 'other')" + }, + "soci_fees_paid_check": { + "name": "soci_fees_paid_check", + "value": "(\"soci_fees\".\"status\" = 'paid') = (\"soci_fees\".\"paid_on\" is not null and \"soci_fees\".\"method\" is not null and \"soci_fees\".\"recorded_by\" is not null)" + }, + "soci_fees_upload_check": { + "name": "soci_fees_upload_check", + "value": "\"soci_fees\".\"status\" <> 'uploaded' or (\"soci_fees\".\"file_id\" is not null and \"soci_fees\".\"transfer_date\" is not null and \"soci_fees\".\"declared_cents\" is not null and \"soci_fees\".\"uploaded_at\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.soci_files": { + "name": "soci_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_files_member_idx": { + "name": "soci_files_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_files_member_id_soci_members_id_fk": { + "name": "soci_files_member_id_soci_members_id_fk", + "tableFrom": "soci_files", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "soci_files_type_check": { + "name": "soci_files_type_check", + "value": "\"soci_files\".\"content_type\" in ('application/pdf', 'image/png', 'image/jpeg')" + } + }, + "isRLSEnabled": false + }, + "public.soci_mail": { + "name": "soci_mail", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "to": { + "name": "to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempted_at": { + "name": "attempted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "soci_mail_status_idx": { + "name": "soci_mail_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_mail_member_id_soci_members_id_fk": { + "name": "soci_mail_member_id_soci_members_id_fk", + "tableFrom": "soci_mail", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "soci_mail_status_check": { + "name": "soci_mail_status_check", + "value": "\"soci_mail\".\"status\" in ('pending', 'sending', 'sent', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.soci_members": { + "name": "soci_members", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_members_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "entra_object_id": { + "name": "entra_object_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mailbox": { + "name": "mailbox", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "alias": { + "name": "alias", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "codice_fiscale": { + "name": "codice_fiscale", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "birth_date": { + "name": "birth_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "birth_place": { + "name": "birth_place", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "residence": { + "name": "residence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admitted_on": { + "name": "admitted_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ended_on": { + "name": "ended_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "end_note": { + "name": "end_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_state": { + "name": "account_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "account_deleted_on": { + "name": "account_deleted_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_members_active_codice_fiscale_idx": { + "name": "soci_members_active_codice_fiscale_idx", + "columns": [ + { + "expression": "codice_fiscale", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"soci_members\".\"ended_on\" is null and \"soci_members\".\"codice_fiscale\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "soci_members_number_unique": { + "name": "soci_members_number_unique", + "nullsNotDistinct": false, + "columns": [ + "number" + ] + }, + "soci_members_entra_object_id_unique": { + "name": "soci_members_entra_object_id_unique", + "nullsNotDistinct": false, + "columns": [ + "entra_object_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "soci_members_end_check": { + "name": "soci_members_end_check", + "value": "(\"soci_members\".\"ended_on\" is null) = (\"soci_members\".\"end_reason\" is null) and (\"soci_members\".\"ended_on\" is not null or \"soci_members\".\"end_note\" is null)" + }, + "soci_members_end_reason_check": { + "name": "soci_members_end_reason_check", + "value": "\"soci_members\".\"end_reason\" in ('lapsed', 'resigned', 'expelled', 'deceased', 'other')" + }, + "soci_members_account_state_check": { + "name": "soci_members_account_state_check", + "value": "\"soci_members\".\"account_state\" in ('active', 'pending_deletion', 'deleted')" + }, + "soci_members_account_deleted_check": { + "name": "soci_members_account_deleted_check", + "value": "(\"soci_members\".\"account_state\" = 'deleted') = (\"soci_members\".\"account_deleted_on\" is not null)" + }, + "soci_members_number_check": { + "name": "soci_members_number_check", + "value": "\"soci_members\".\"number\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.soci_numbers": { + "name": "soci_numbers", + "schema": "", + "columns": { + "number": { + "name": "number", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_numbers_member_idx": { + "name": "soci_numbers_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_numbers_member_id_soci_members_id_fk": { + "name": "soci_numbers_member_id_soci_members_id_fk", + "tableFrom": "soci_numbers", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_messages": { + "name": "tg_messages", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "varchar(8704)", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tg_messages_chat_author_timestamp_idx": { + "name": "tg_messages_chat_author_timestamp_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "tg_messages_chat_id_message_id_pk": { + "name": "tg_messages_chat_id_message_id_pk", + "columns": [ + "chat_id", + "message_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_grants": { + "name": "tg_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_grants_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "valid_since": { + "name": "valid_since", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "valid_until": { + "name": "valid_until", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "granted_by_sub": { + "name": "granted_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_via_client": { + "name": "granted_via_client", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "interrupted_at": { + "name": "interrupted_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "interrupted_by_sub": { + "name": "interrupted_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "interrupted_by_tg_id": { + "name": "interrupted_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tg_grants_telegram_user_id_idx": { + "name": "tg_grants_telegram_user_id_idx", + "columns": [ + { + "expression": "telegram_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "tg_grants_validity_check": { + "name": "tg_grants_validity_check", + "value": "\"tg_grants\".\"valid_since\" < \"tg_grants\".\"valid_until\"" + } + }, + "isRLSEnabled": false + }, + "public.tg_groups": { + "name": "tg_groups", + "schema": "", + "columns": { + "telegram_id": { + "name": "telegram_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tg_groups_link_unique": { + "name": "tg_groups_link_unique", + "nullsNotDistinct": false, + "columns": [ + "link" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_group_label_relations": { + "name": "tg_group_label_relations", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "tg_group_label_relations_group_id_tg_groups_telegram_id_fk": { + "name": "tg_group_label_relations_group_id_tg_groups_telegram_id_fk", + "tableFrom": "tg_group_label_relations", + "tableTo": "tg_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "telegram_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tg_group_label_relations_label_id_common_group_labels_id_fk": { + "name": "tg_group_label_relations_label_id_common_group_labels_id_fk", + "tableFrom": "tg_group_label_relations", + "tableTo": "common_group_labels", + "columnsFrom": [ + "label_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "tg_group_label_relations_group_id_label_id_pk": { + "name": "tg_group_label_relations_group_id_label_id_pk", + "columns": [ + "group_id", + "label_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_test": { + "name": "tg_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_test_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "text": { + "name": "text", + "type": "varchar", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_audit_log": { + "name": "tg_audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_audit_log_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "target_id": { + "name": "target_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "until": { + "name": "until", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_tg_id": { + "name": "actor_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "client": { + "name": "client", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "basis": { + "name": "basis", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "default": "'legacy'" + }, + "review": { + "name": "review", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "auditlog_actor_tg_id_idx": { + "name": "auditlog_actor_tg_id_idx", + "columns": [ + { + "expression": "actor_tg_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "auditlog_idempotency_key_idx": { + "name": "auditlog_idempotency_key_idx", + "columns": [ + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_users": { + "name": "tg_users", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false + }, + "username": { + "name": "username", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "is_bot": { + "name": "is_bot", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "lang_code": { + "name": "lang_code", + "type": "varchar(35)", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wa_group_label_relations": { + "name": "wa_group_label_relations", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "wa_group_label_relations_group_id_wa_groups_group_id_fk": { + "name": "wa_group_label_relations_group_id_wa_groups_group_id_fk", + "tableFrom": "wa_group_label_relations", + "tableTo": "wa_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "group_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "wa_group_label_relations_label_id_common_group_labels_id_fk": { + "name": "wa_group_label_relations_label_id_common_group_labels_id_fk", + "tableFrom": "wa_group_label_relations", + "tableTo": "common_group_labels", + "columnsFrom": [ + "label_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "wa_group_label_relations_group_id_label_id_pk": { + "name": "wa_group_label_relations_group_id_label_id_pk", + "columns": [ + "group_id", + "label_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wa_groups": { + "name": "wa_groups", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "wa_groups_group_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "wa_groups_link_unique": { + "name": "wa_groups_link_unique", + "nullsNotDistinct": false, + "columns": [ + "link" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_projects": { + "name": "web_projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_projects_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link": { + "name": "link", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'general'" + }, + "order": { + "name": "order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_projects_creator_check": { + "name": "web_projects_creator_check", + "value": "\"web_projects\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_projects\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_group_link_reports": { + "name": "web_group_link_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_group_link_reports_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "varchar(2)", + "primaryKey": false, + "notNull": false + }, + "report_type": { + "name": "report_type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "reported_link": { + "name": "reported_link", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "label": { + "name": "label", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "details": { + "name": "details", + "type": "varchar(500)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_faq_categories": { + "name": "web_faq_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_faq_categories_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "title_it": { + "name": "title_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title_en": { + "name": "title_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_faq_categories_creator_check": { + "name": "web_faq_categories_creator_check", + "value": "\"web_faq_categories\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_faq_categories\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_faqs": { + "name": "web_faqs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_faqs_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "title_it": { + "name": "title_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title_en": { + "name": "title_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "web_faqs_category_id_web_faq_categories_id_fk": { + "name": "web_faqs_category_id_web_faq_categories_id_fk", + "tableFrom": "web_faqs", + "tableTo": "web_faq_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_faqs_creator_check": { + "name": "web_faqs_creator_check", + "value": "\"web_faqs\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_faqs\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_freshman_cards": { + "name": "web_freshman_cards", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "href": { + "name": "href", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_freshman_cards_creator_check": { + "name": "web_freshman_cards_creator_check", + "value": "\"web_freshman_cards\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_freshman_cards\".\"created_by_sub\" IS NOT NULL" + }, + "web_freshman_cards_slot_check": { + "name": "web_freshman_cards_slot_check", + "value": "\"web_freshman_cards\".\"id\" in ('featured-1', 'featured-2', 'guides-1', 'guides-2', 'guides-3', 'guides-4', 'guides-5', 'materials-1', 'tools-1', 'tools-2', 'telegram-1', 'telegram-2', 'telegram-3', 'telegram-4', 'telegram-5', 'telegram-6', 'telegram-7', 'telegram-8')" + }, + "web_freshman_cards_icon_check": { + "name": "web_freshman_cards_icon_check", + "value": "\"web_freshman_cards\".\"icon\" in ('chart', 'monitor', 'book', 'map', 'news', 'money', 'folder', 'repeat', 'refresh', 'bell', 'user', 'users', 'cart', 'home')" + } + }, + "isRLSEnabled": false + }, + "public.web_freshman_faqs": { + "name": "web_freshman_faqs", + "schema": "", + "columns": { + "position": { + "name": "position", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "faq_id": { + "name": "faq_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "web_freshman_faqs_faq_id_web_faqs_id_fk": { + "name": "web_freshman_faqs_faq_id_web_faqs_id_fk", + "tableFrom": "web_freshman_faqs", + "tableTo": "web_faqs", + "columnsFrom": [ + "faq_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_freshman_faqs_faq_id_unique": { + "name": "web_freshman_faqs_faq_id_unique", + "nullsNotDistinct": false, + "columns": [ + "faq_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_freshman_faqs_creator_check": { + "name": "web_freshman_faqs_creator_check", + "value": "\"web_freshman_faqs\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_freshman_faqs\".\"created_by_sub\" IS NOT NULL" + }, + "web_freshman_faqs_position_check": { + "name": "web_freshman_faqs_position_check", + "value": "\"web_freshman_faqs\".\"position\" between 0 and 4" + } + }, + "isRLSEnabled": false + }, + "public.web_guides_matricole": { + "name": "web_guides_matricole", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_guides_matricole_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_guides_matricole_version_unique": { + "name": "web_guides_matricole_version_unique", + "nullsNotDistinct": false, + "columns": [ + "version" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_guides_matricole_creator_check": { + "name": "web_guides_matricole_creator_check", + "value": "\"web_guides_matricole\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_guides_matricole\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_test": { + "name": "web_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_test_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "text": { + "name": "text", + "type": "varchar", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_associations": { + "name": "web_associations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_associations_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "website": { + "name": "website", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "facebook": { + "name": "facebook", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "instagram": { + "name": "instagram", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tiktok": { + "name": "tiktok", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "x": { + "name": "x", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "youtube": { + "name": "youtube", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram": { + "name": "telegram", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "linkedin": { + "name": "linkedin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "spotify": { + "name": "spotify", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_associations_creator_check": { + "name": "web_associations_creator_check", + "value": "\"web_associations\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_associations\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_document_categories": { + "name": "web_document_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_document_categories_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_document_categories_slug_unique": { + "name": "web_document_categories_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_document_categories_creator_check": { + "name": "web_document_categories_creator_check", + "value": "\"web_document_categories\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_document_categories\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_document_versions": { + "name": "web_document_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_document_versions_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "document_id": { + "name": "document_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "web_document_versions_document_id_web_documents_id_fk": { + "name": "web_document_versions_document_id_web_documents_id_fk", + "tableFrom": "web_document_versions", + "tableTo": "web_documents", + "columnsFrom": [ + "document_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_document_versions_document_id_version_unique": { + "name": "web_document_versions_document_id_version_unique", + "nullsNotDistinct": false, + "columns": [ + "document_id", + "version" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_document_versions_creator_check": { + "name": "web_document_versions_creator_check", + "value": "\"web_document_versions\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_document_versions\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_documents": { + "name": "web_documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_documents_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "category_id": { + "name": "category_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "web_documents_category_id_idx": { + "name": "web_documents_category_id_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "web_documents_category_id_web_document_categories_id_fk": { + "name": "web_documents_category_id_web_document_categories_id_fk", + "tableFrom": "web_documents", + "tableTo": "web_document_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_documents_slug_unique": { + "name": "web_documents_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_documents_creator_check": { + "name": "web_documents_creator_check", + "value": "\"web_documents\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_documents\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": { + "public.groups_view": { + "columns": { + "telegram_id": { + "name": "telegram_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "definition": "(select \"telegram_id\", \"title\", \"link\", \"hide\", 'tg' as \"type\" from \"tg_groups\") union all (select \"group_id\", \"title\", \"link\", \"hide\", 'wa' as \"type\" from \"wa_groups\")", + "name": "groups_view", + "schema": "public", + "isExisting": false, + "materialized": false + }, + "public.group_label_relations_view": { + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "definition": "(select \"group_id\", \"label_id\", 'tg' as \"type\" from \"tg_group_label_relations\") union all (select \"group_id\", \"label_id\", 'wa' as \"type\" from \"wa_group_label_relations\")", + "name": "group_label_relations_view", + "schema": "public", + "isExisting": false, + "materialized": false + } + }, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index ec61f80..7004a0b 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -281,6 +281,13 @@ "when": 1794708980775, "tag": "0039_webhook_deliveries", "breakpoints": true + }, + { + "idx": 40, + "version": "7", + "when": 1794930019920, + "tag": "0040_audit_events", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/audit/index.ts b/src/audit/index.ts new file mode 100644 index 0000000..7ecbc18 --- /dev/null +++ b/src/audit/index.ts @@ -0,0 +1,249 @@ +import type { TRPCError } from "@trpc/server" +import { ZodError } from "zod/v4" +import { + AUDIT_ACTOR_KIND, + AUDIT_OUTCOME, + type AuditJson, + type auditEvents, + type TAuditActorKind, + type TAuditOutcome, +} from "@/db/schema/common/audit-events" +import type { RequestAuth } from "@/idp/auth" +import type { AuditOption, AuditTarget } from "./option" + +export type AuditEvent = typeof auditEvents.$inferInsert +export { type AuditOption, type AuditTarget, type AuditTargetOf, audit } from "./option" + +export type AuditActor = { kind: TAuditActorKind; sub?: string | null; tgId?: number | null; client?: string | null } + +/** What only the handler knows about its change. Each call adds to or replaces the previous fields. */ +export type AuditNote = { + /** Replaces the procedure path. */ + action?: string + target?: AuditTarget + before?: unknown + after?: unknown + reason?: string | null +} + +export type AuditRecorder = { + set: (note: AuditNote) => void + /** Records nothing for this call, e.g. a retry that changed nothing. */ + skip: () => void +} + +/** For a mutation without an option, which the router test keeps from shipping: the option that stores the least. */ +export const UNDECLARED: AuditOption = { capture: "minimal" } + +/** Handed to queries, which change nothing. */ +export const noAudit: AuditRecorder = { set: () => {}, skip: () => {} } + +/** A fresh recorder for one mutation, with the note it collects and whether the handler skipped the event. */ +export function auditRecorder() { + const note: AuditNote = {} + let skipped = false + const recorder: AuditRecorder = { + set: (next) => Object.assign(note, next), + skip: () => { + skipped = true + }, + } + return { recorder, note, skipped: () => skipped } +} + +/** Field names that hold secrets: whole names, or the last word of a camelCase name (`idempotencyKey`). */ +const SECRET_KEY = /^(pass(word)?|passwd|secret|token|ticket|otp|code|key)$|(Pass(word)?|Secret|Token|Ticket|Otp|Key)$/ +/** Names that end like a secret but hold a public identifier, such as a regulation's `documentKey`. */ +const NOT_SECRET = new Set(["documentKey"]) +const isSecret = (key: string) => SECRET_KEY.test(key) && !NOT_SECRET.has(key) +const MAX_STRING = 2000 +const MAX_ITEMS = 100 +const MAX_DEPTH = 8 +/** A copy larger than this many bytes, as UTF-8 JSON, is replaced by a note of its size. */ +const MAX_JSON = 64 * 1024 + +function copyOf(value: unknown, depth: number): AuditJson { + if (value === null || value === undefined) return null + if (typeof value === "string") + return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}… (${value.length} characters)` : value + if (typeof value === "number") return Number.isFinite(value) ? value : String(value) + if (typeof value === "boolean") return value + if (typeof value === "bigint") return value.toString() + if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString() + if (value instanceof File) return { file: value.name, type: value.type, size: value.size } + if (value instanceof Blob) return { file: null, type: value.type, size: value.size } + if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return `(${value.byteLength} bytes)` + if (depth >= MAX_DEPTH) return "(nested too deep)" + if (value instanceof FormData) return copyOf(Object.fromEntries(value.entries()), depth) + if (value instanceof Map) return copyOf(Object.fromEntries(value), depth) + if (value instanceof Set) return copyOf([...value], depth) + if (Array.isArray(value)) { + const items = value.slice(0, MAX_ITEMS).map((item) => copyOf(item, depth + 1)) + return value.length > MAX_ITEMS ? [...items, `(${value.length - MAX_ITEMS} more)`] : items + } + if (typeof value === "object") { + const entries = Object.entries(value).filter(([, item]) => item !== undefined && typeof item !== "function") + const copy: { [key: string]: AuditJson } = {} + for (const [key, item] of entries.slice(0, MAX_ITEMS)) + copy[key] = isSecret(key) ? "(hidden)" : copyOf(item, depth + 1) + if (entries.length > MAX_ITEMS) copy["(more)"] = `${entries.length - MAX_ITEMS} more fields` + return copy + } + return null +} + +/** + * A JSON copy of an input or a row, safe to keep: secrets are replaced, files and bytes are described instead of copied, + * and long strings, arrays, objects and copies are cut. + */ +export function auditJson(value: unknown): AuditJson { + const copy = copyOf(value, 0) + const size = Buffer.byteLength(JSON.stringify(copy) ?? "", "utf8") + return size > MAX_JSON ? `(${size} bytes, too large to keep)` : copy +} + +/** The caller from the verified token; null without one, so such calls are not recorded. */ +function actorOf(auth: RequestAuth | undefined): AuditActor | null { + if (auth?.kind !== "token") return null + const { actor } = auth + if (actor.kind === "service") return { kind: AUDIT_ACTOR_KIND.SERVICE, client: actor.client } + return { + kind: actor.kind, + sub: actor.sub, + tgId: actor.telegramId === null ? null : Number(actor.telegramId), + client: actor.client, + } +} + +/** An error a handler returned instead of throwing, e.g. `{ error: "NOT_FOUND" }`, `{ success: false }` or `false`. */ +function returnedError(data: unknown): string | null { + if (data === false) return "Nothing changed" + if (data === null || typeof data !== "object" || Array.isArray(data)) return null + if ("error" in data && typeof data.error === "string") return data.error + if ("success" in data && data.success === false) return "Not successful" + return null +} + +const DENIED_CODES = new Set(["UNAUTHORIZED", "FORBIDDEN"]) + +type Result = { ok: true; data: unknown } | { ok: false; error: TRPCError } + +/** Whether the caller lacked the scope or the permission. */ +export const isDenied = (result: Result) => !result.ok && DENIED_CODES.has(result.error.code) + +/** Target ids, labels and reasons can come from the caller, so they are cut like strings in copies. */ +const cut = (value: string | null) => (value === null ? null : (copyOf(value, 0) as string)) + +const MAX_ERROR = 500 + +/** + * The root cause's message, on one line: a database error then reads "violates foreign key constraint …" rather than + * the failed query with its parameters, and an invalid input lists its issues rather than their JSON. + */ +function errorMessage(error: Error) { + let cause = error + while (cause.cause instanceof Error) cause = cause.cause + if (cause instanceof ZodError) + return cause.issues + .map((issue) => (issue.path.length ? `${issue.path.join(".")}: ${issue.message}` : issue.message)) + .join("; ") + .slice(0, MAX_ERROR) + return (cause.message.split("\n")[0] ?? "").slice(0, MAX_ERROR) +} + +/** Success, failure or denial, from a thrown error or an error the handler returned. */ +function outcomeOf(result: Result): { outcome: TAuditOutcome; error: string | null } { + if (!result.ok) + return { + outcome: DENIED_CODES.has(result.error.code) ? AUDIT_OUTCOME.DENIED : AUDIT_OUTCOME.FAILURE, + error: errorMessage(result.error), + } + const error = returnedError(result.data) + return error === null ? { outcome: AUDIT_OUTCOME.SUCCESS, error: null } : { outcome: AUDIT_OUTCOME.FAILURE, error } +} + +/** Whether an allowlisted field holds a value that is kept as it is: objects and arrays could carry anything. */ +const isScalar = (value: unknown) => + value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" + +/** + * Select declared input fields before redaction and size limits are applied. Only scalar values are kept; a dotted + * field (`output.driveId`) reaches into a nested object, and a null object stays null. + */ +function onlyFields(input: unknown, fields: readonly string[] | undefined): unknown { + if (!fields) return input + if (input instanceof FormData || input instanceof Map) input = Object.fromEntries(input.entries()) + if (input === null || typeof input !== "object" || Array.isArray(input)) return {} + const record = input as Record + const nested = new Map() + const picked: Record = {} + for (const field of fields) { + const dot = field.indexOf(".") + if (dot === -1) { + if (Object.hasOwn(record, field) && isScalar(record[field])) picked[field] = record[field] + continue + } + const head = field.slice(0, dot) + nested.set(head, [...(nested.get(head) ?? []), field.slice(dot + 1)]) + } + for (const [head, rest] of nested) { + if (!Object.hasOwn(record, head)) continue + const value = record[head] + if (value === null) picked[head] = null + else if (typeof value === "object" && !Array.isArray(value)) picked[head] = onlyFields(value, rest) + } + return picked +} + +/** + * The event for one mutation, or null when there is nothing worth keeping: calls refused before an actor was known + * (no token, an invalid token) would let anyone fill the log. + */ +export function auditEvent(options: { + path: string + option?: AuditOption + auth: RequestAuth | undefined + requestId?: string | null + rawInput: unknown + note: AuditNote + result: Result +}): AuditEvent | null { + const { path, note, result } = options + const option = options.option ?? UNDECLARED + if (option.capture === "none") return null + const actor = actorOf(options.auth) + if (!actor) return null + const { outcome, error } = outcomeOf(result) + + // What the handler names wins over the option's target, which only sees the raw input and the result. + const target = + note.target ?? option.target?.({ input: options.rawInput, data: result.ok ? result.data : undefined }) ?? undefined + const targetId = target?.id == null ? null : String(target.id) + const event: AuditEvent = { + action: note.action ?? option.action ?? path, + requestId: options.requestId ?? null, + actorKind: actor.kind, + actorSub: actor.sub ?? null, + actorTgId: actor.tgId ?? null, + actorClient: actor.client ?? null, + targetType: target?.type ?? null, + targetId: cut(targetId), + targetLabel: cut(target?.label ?? null), + reason: null, + outcome, + error, + input: null, + before: null, + after: null, + } + if (option.capture === "minimal") return event + + return { + ...event, + reason: cut(note.reason ?? null), + // A refused call changed nothing, and its input is whatever the caller chose to send. + input: outcome === AUDIT_OUTCOME.DENIED ? null : auditJson(onlyFields(options.rawInput, option.fields)), + before: note.before === undefined ? null : auditJson(note.before), + after: note.after === undefined ? null : auditJson(note.after), + } +} diff --git a/src/audit/names.ts b/src/audit/names.ts new file mode 100644 index 0000000..18e2a79 --- /dev/null +++ b/src/audit/names.ts @@ -0,0 +1,56 @@ +import { inArray } from "drizzle-orm" +import { DB, SCHEMA } from "@/db" +import { idp } from "@/idp" +import { logger } from "@/logger" +import { decryptUser } from "@/utils/users" + +const DIRECTORY_TTL_MS = 5 * 60_000 +let directory: { at: number; names: Map } | null = null + +/** The IdP directory's names by subject, cached for `DIRECTORY_TTL_MS`; empty without a directory. */ +async function directoryNames(): Promise> { + if (!idp?.directory) return new Map() + if (directory && Date.now() - directory.at < DIRECTORY_TTL_MS) return directory.names + try { + const people = await idp.directory() + directory = { at: Date.now(), names: new Map(people.map((person) => [person.sub, person.name])) } + } catch (error) { + logger.warn({ err: error }, "[AUDIT] cannot read the IdP directory") + // Keeps the last names and waits a full TTL before asking again, rather than on every read. + directory = { at: Date.now(), names: directory?.names ?? new Map() } + } + return directory.names +} + +/** Display names of IdP subjects: from the IdP's directory, else from the profiles Signatures keeps. */ +export async function userNames(subs: string[]): Promise> { + const names = new Map() + if (subs.length === 0) return names + const profiles = SCHEMA.ESIGN.profiles + for (const profile of await DB.select({ sub: profiles.sub, name: profiles.name }) + .from(profiles) + .where(inArray(profiles.sub, subs))) + names.set(profile.sub, profile.name) + const known = await directoryNames() + for (const sub of subs) { + const name = known.get(sub) + if (name) names.set(sub, name) + } + return names +} + +/** Display names of Telegram users the backend has seen, e.g. "Ada Lovelace (@ada)". */ +export async function telegramNames(ids: number[]): Promise> { + const names = new Map() + if (ids.length === 0) return names + const rows = await DB.select().from(SCHEMA.TG.users).where(inArray(SCHEMA.TG.users.userId, ids)) + await Promise.all( + rows.map(async (row) => { + const user = await decryptUser(row).catch(() => null) + if (!user) return + const name = [user.firstName, user.lastName].filter(Boolean).join(" ") + names.set(row.userId, user.username ? `${name} (@${user.username})` : name) + }) + ) + return names +} diff --git a/src/audit/option.ts b/src/audit/option.ts new file mode 100644 index 0000000..c8a32d5 --- /dev/null +++ b/src/audit/option.ts @@ -0,0 +1,42 @@ +// No imports: routers declare their audit options with this module without loading the database schema. + +/** + * What a change was made to; `label` is a readable name, kept as it was at the time. `id` is null when the call acts + * on several records, which are then named in the input. + */ +export type AuditTarget = { type: string; id: string | number | null; label?: string | null } + +/** + * The target of a call, from its input and, once it succeeded, its result. The input is the raw one, not yet validated + * (and undefined for denied calls, whose body is not read), so a target function checks what it takes from it. + */ +export type AuditTargetOf = (call: { input: unknown; data: unknown }) => AuditTarget | null + +/** + * How a mutation is recorded, declared in its procedure meta with `.meta(audit.full())` and the like. A test walks the + * router so that every mutation declares one. + */ +export type AuditOption = + /** Not recorded; `why` says why, e.g. the bot's ingestion or an area that keeps its own log. */ + | { capture: "none"; why: string } + /** + * The actor, the action, the target and the outcome, without the input, the states or the reason: for areas that + * keep their own history, readable with their own permissions. + */ + | { capture: "minimal"; target?: AuditTargetOf; action?: string } + /** + * Also the input, the states the handler adds and the reason. `fields` keeps only those fields of the input, for + * inputs that carry personal data or free text not worth keeping; `"output.driveId"` keeps one field of a nested object. + */ + | { capture: "full"; fields?: readonly string[]; target?: AuditTargetOf; action?: string } + +/** Procedure meta for each way of recording a mutation. */ +export const audit = { + full: (options: Omit, "capture"> = {}) => ({ + audit: { capture: "full", ...options } satisfies AuditOption, + }), + minimal: (options: Omit, "capture"> = {}) => ({ + audit: { capture: "minimal", ...options } satisfies AuditOption, + }), + none: (why: string) => ({ audit: { capture: "none", why } satisfies AuditOption }), +} diff --git a/src/audit/store.ts b/src/audit/store.ts new file mode 100644 index 0000000..d3a71bd --- /dev/null +++ b/src/audit/store.ts @@ -0,0 +1,7 @@ +import { DB, SCHEMA } from "@/db" +import type { AuditEvent } from "." + +/** Kept apart from `src/audit` so that importing the tRPC setup does not open the database. */ +export async function writeAuditEvent(event: AuditEvent) { + await DB.insert(SCHEMA.COMMON.auditEvents).values(event) +} diff --git a/src/constants.ts b/src/constants.ts index 26d0949..8e0e82e 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -6,3 +6,8 @@ export const MESSAGES_RETENTION_DAYS = 7 export const MODERATION_RETENTION_MONTHS = 24 /** How long revocations of permanent measures stay in the moderation audit log; see `endedMeasures`. */ export const ENDED_MODERATION_RETENTION_DAYS = 1 +/** + * Events in the backend audit log (`common_audit_events`) are deleted this many months after they were written. It + * matches the moderation records' retention; the privacy policy should state it. + */ +export const AUDIT_EVENTS_RETENTION_MONTHS = 24 diff --git a/src/cron.ts b/src/cron.ts index 7c78586..5c568b8 100644 --- a/src/cron.ts +++ b/src/cron.ts @@ -1,6 +1,6 @@ import { Cron } from "croner" import { lt } from "drizzle-orm" -import { MESSAGES_RETENTION_DAYS } from "./constants" +import { AUDIT_EVENTS_RETENTION_MONTHS, MESSAGES_RETENTION_DAYS } from "./constants" import { DB, SCHEMA } from "./db" import { env } from "./env" import { logger } from "./logger" @@ -12,6 +12,7 @@ export function cron() { logger.info("[CRON] start") await cleanMessages() await cleanAuditLog() + await cleanAuditEvents() logger.info("[CRON] end") }) @@ -105,3 +106,19 @@ export async function cleanAuditLog() { logger.error(err, "[CRON] cleanAuditLog") } } + +/** Deletes the backend audit events past their retention. */ +export async function cleanAuditEvents(now = new Date()) { + logger.info(`[CRON] START(cleanAuditEvents) retention months = ${AUDIT_EVENTS_RETENTION_MONTHS}`) + + const cutoff = new Date(now) + cutoff.setMonth(cutoff.getMonth() - AUDIT_EVENTS_RETENTION_MONTHS) + try { + const deleted = await DB.delete(SCHEMA.COMMON.auditEvents) + .where(lt(SCHEMA.COMMON.auditEvents.createdAt, cutoff)) + .returning({ id: SCHEMA.COMMON.auditEvents.id }) + logger.info(`[CRON] END(cleanAuditEvents) deleted ${deleted.length} audit event(s).`) + } catch (err) { + logger.error(err, "[CRON] cleanAuditEvents") + } +} diff --git a/src/db/schema/common/audit-events.ts b/src/db/schema/common/audit-events.ts new file mode 100644 index 0000000..aa49856 --- /dev/null +++ b/src/db/schema/common/audit-events.ts @@ -0,0 +1,63 @@ +import { sql } from "drizzle-orm" +import { bigint, index, jsonb, text, timestamp, uuid, varchar } from "drizzle-orm/pg-core" +import { createTable } from "../create-table" + +/** Who made a change: the kinds of RFC v3 actors. */ +export const AUDIT_ACTOR_KIND = { + USER: "user", + TELEGRAM: "telegram", + SERVICE: "service", +} as const +export type TAuditActorKind = (typeof AUDIT_ACTOR_KIND)[keyof typeof AUDIT_ACTOR_KIND] + +export const AUDIT_OUTCOME = { + SUCCESS: "success", + /** The call ran but changed nothing: an error was thrown or returned. */ + FAILURE: "failure", + /** The caller lacked the scope or permission. */ + DENIED: "denied", +} as const +export type TAuditOutcome = (typeof AUDIT_OUTCOME)[keyof typeof AUDIT_OUTCOME] + +/** JSON as stored in the event: inputs and states are copied without secrets or file contents. */ +export type AuditJson = null | boolean | number | string | AuditJson[] | { [key: string]: AuditJson } + +/** + * Who used which permission to change what through the backend: one row per mutation, written by the tRPC audit + * middleware (`src/audit`). Areas with their own history (People, Telegram moderation) keep the details there. + */ +export const auditEvents = createTable.common( + "audit_events", + { + id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(), + /** The procedure path, e.g. `web.faqs.editFaqs`. */ + action: text("action").notNull(), + /** Shared by the events of one HTTP request, to match them with what the request asked of other systems. */ + requestId: uuid("request_id"), + actorKind: varchar("actor_kind", { length: 16 }).$type().notNull(), + actorSub: text("actor_sub"), + actorTgId: bigint("actor_tg_id", { mode: "number" }), + /** The OAuth client that made the call, e.g. `admin-dashboard`; null for legacy callers. */ + actorClient: text("actor_client"), + targetType: text("target_type"), + targetId: text("target_id"), + /** A readable name for the target when the event was written, e.g. a FAQ's title. */ + targetLabel: text("target_label"), + reason: text("reason"), + outcome: varchar("outcome", { length: 16 }).$type().notNull(), + error: text("error"), + input: jsonb("input").$type(), + before: jsonb("before").$type(), + after: jsonb("after").$type(), + createdAt: timestamp("created_at", { precision: 3, withTimezone: true }).default(sql`now()`).notNull(), + }, + (t) => [ + index("common_audit_events_action_idx").on(t.action), + index("common_audit_events_actor_sub_idx").on(t.actorSub), + index("common_audit_events_actor_tg_id_idx").on(t.actorTgId), + index("common_audit_events_target_idx").on(t.targetType, t.targetId), + index("common_audit_events_request_id_idx").on(t.requestId), + // The retention cron deletes by age. + index("common_audit_events_created_at_idx").on(t.createdAt), + ] +) diff --git a/src/db/schema/common/index.ts b/src/db/schema/common/index.ts index 9c1cf12..40bff29 100644 --- a/src/db/schema/common/index.ts +++ b/src/db/schema/common/index.ts @@ -1,8 +1,10 @@ +import * as auditEvents from "./audit-events" import * as groupLabels from "./group-labels" import * as idpState from "./idp-state" import * as webhookDeliveries from "./webhook-deliveries" export const schema = { + ...auditEvents, ...groupLabels, ...idpState, ...webhookDeliveries, diff --git a/src/esign/service.ts b/src/esign/service.ts index d15e3a6..9e5068c 100644 --- a/src/esign/service.ts +++ b/src/esign/service.ts @@ -889,13 +889,10 @@ export function createEsignService(options: ServiceOptions) { roles: [...new Set(r.roles.map((k) => k.trim()).filter(Boolean))].sort(), permissions: [...new Set(r.permissions.map((k) => k.trim()).filter(Boolean))].sort(), }) - await store.setDriveAccess({ - driveId, - request: clean(rule.request), - sign: clean(rule.sign), - updatedBySub: caller.sub, - }) + const saved = { request: clean(rule.request), sign: clean(rule.sign) } + await store.setDriveAccess({ driveId, ...saved, updatedBySub: caller.sub }) logger.info({ driveId, by: caller.sub }, "[ESIGN] drive access changed") + return saved }, /** @@ -945,6 +942,11 @@ export function createEsignService(options: ServiceOptions) { }) }, + /** For the audit log: the request's title, whoever asks. */ + async requestTitle(id: string) { + return (await store.getRequest(id))?.title ?? null + }, + async resetIdentity(sub: string) { await store.setProfileIdentity(sub, null) }, diff --git a/src/people/router.ts b/src/people/router.ts index 8f09c70..cfbb094 100644 --- a/src/people/router.ts +++ b/src/people/router.ts @@ -1,5 +1,6 @@ import { TRPCError } from "@trpc/server" import { z } from "zod" +import { type AuditTargetOf, audit } from "@/audit/option" import { SCOPE } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" import * as C from "./contract" @@ -7,6 +8,20 @@ import { requireGeneral } from "./model" import type { PeopleService } from "./service" import type { Viewer } from "./types" +/** + * The person a call names (`id` or `personId`) or creates, kept only when it is a valid People id: the raw input is not + * validated yet. Handlers name the target from their validated input too, which wins over this. + */ +const personTarget: AuditTargetOf = ({ input, data }) => { + const field = (value: unknown, key: "id" | "personId") => + value && typeof value === "object" ? (value as Record)[key] : undefined + for (const candidate of [field(input, "id"), field(input, "personId"), field(data, "id")]) { + const id = C.personIdSchema.safeParse(candidate) + if (id.success) return { type: "people.person", id: id.data } + } + return { type: "people.person", id: null } +} + /** * Factory keeps policy and shape tests independent of databases and external services. * @@ -14,20 +29,24 @@ import type { Viewer } from "./types" * are open to every dashboard user here, since a team's Lead may add and remove its members. */ export function createPeopleRouter(people: PeopleService) { - const user = policy({ user: { scope: SCOPE.admin } }).use(async ({ ctx, next }) => { - if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) - const sub = ctx.actor.sub - const viewer: Viewer = { - sub, - telegramId: ctx.actor.telegramId, - can: ctx.can, - holdsRole: (role) => { - const index = ctx.access?.current() - return !!index && index.hasRole(index.bySub(sub), role) - }, - } - return next({ ctx: { viewer } }) - }) + // People keeps each record's history in `people_activity`, behind its own permissions: the audit log only says who + // changed which record, and whether it worked. + const user = policy({ user: { scope: SCOPE.admin } }) + .meta(audit.minimal({ target: personTarget })) + .use(async ({ ctx, next }) => { + if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) + const sub = ctx.actor.sub + const viewer: Viewer = { + sub, + telegramId: ctx.actor.telegramId, + can: ctx.can, + holdsRole: (role) => { + const index = ctx.access?.current() + return !!index && index.hasRole(index.bySub(sub), role) + }, + } + return next({ ctx: { viewer } }) + }) const admin = (permission: string) => user.use(({ ctx, next }) => { requireGeneral(ctx.viewer, permission) @@ -53,28 +72,44 @@ export function createPeopleRouter(people: PeopleService) { .input(C.createPersonInputSchema) .output(C.createdSchema) .mutation(({ ctx, input }) => people.createPerson(ctx.viewer, input)), - update: write - .input(C.updatePersonInputSchema) - .mutation(({ ctx, input }) => people.updatePerson(ctx.viewer, input)), - setNote: write.input(C.setNoteInputSchema).mutation(({ ctx, input }) => people.setNote(ctx.viewer, input)), + update: write.input(C.updatePersonInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.id } }) + return people.updatePerson(ctx.viewer, input) + }), + setNote: write.input(C.setNoteInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.id } }) + return people.setNote(ctx.viewer, input) + }), }), admins: createTRPCRouter({ list: read.output(C.adminSummarySchema.array()).query(({ ctx }) => people.listAdmins(ctx.viewer)), - assign: write.input(C.assignAdminInputSchema).mutation(({ ctx, input }) => people.assignAdmin(ctx.viewer, input)), - end: write.input(C.endAssignmentInputSchema).mutation(({ ctx, input }) => people.endAdmin(ctx.viewer, input)), - setCapoOfReference: write - .input(C.capoRefInputSchema) - .mutation(({ ctx, input }) => people.setCapoOfReference(ctx.viewer, input)), + assign: write.input(C.assignAdminInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.assignAdmin(ctx.viewer, input) + }), + end: write.input(C.endAssignmentInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.endAdmin(ctx.viewer, input) + }), + setCapoOfReference: write.input(C.capoRefInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.setCapoOfReference(ctx.viewer, input) + }), }), capos: createTRPCRouter({ list: read.output(C.capoSummarySchema.array()).query(({ ctx }) => people.listCapos(ctx.viewer)), - appoint: appoint - .input(C.appointCapoInputSchema) - .mutation(({ ctx, input }) => people.appointCapo(ctx.viewer, input)), - setScope: appoint - .input(C.capoScopeInputSchema) - .mutation(({ ctx, input }) => people.setCapoScope(ctx.viewer, input)), - end: appoint.input(C.endAssignmentInputSchema).mutation(({ ctx, input }) => people.endCapo(ctx.viewer, input)), + appoint: appoint.input(C.appointCapoInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.appointCapo(ctx.viewer, input) + }), + setScope: appoint.input(C.capoScopeInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.setCapoScope(ctx.viewer, input) + }), + end: appoint.input(C.endAssignmentInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.endCapo(ctx.viewer, input) + }), }), teams: createTRPCRouter({ list: user.output(C.teamSummarySchema.array()).query(({ ctx }) => people.listTeams(ctx.viewer)), @@ -82,32 +117,43 @@ export function createPeopleRouter(people: PeopleService) { .input(C.teamCandidatesInputSchema) .output(C.teamCandidateSchema.array()) .query(({ ctx, input }) => people.listTeamCandidates(ctx.viewer, input)), - addMember: user - .input(C.addTeamMemberInputSchema) - .mutation(({ ctx, input }) => people.addTeamMember(ctx.viewer, input)), - updateFields: user - .input(C.teamFieldsInputSchema) - .mutation(({ ctx, input }) => people.updateTeamFields(ctx.viewer, input)), - endMembership: user - .input(C.endTeamInputSchema) - .mutation(({ ctx, input }) => people.endTeamMembership(ctx.viewer, input)), + addMember: user.input(C.addTeamMemberInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.addTeamMember(ctx.viewer, input) + }), + updateFields: user.input(C.teamFieldsInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.updateTeamFields(ctx.viewer, input) + }), + endMembership: user.input(C.endTeamInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.endTeamMembership(ctx.viewer, input) + }), }), linking: createTRPCRouter({ invites: read.output(C.inviteSchema.array()).query(({ ctx }) => people.listInvites(ctx.viewer)), recent: read.output(C.recentLinkSchema.array()).query(({ ctx }) => people.listRecentLinks(ctx.viewer)), // People writers, or the Lead of one of the person's teams: the service decides. - sendInvite: user.input(C.personRefInputSchema).mutation(({ ctx, input }) => people.sendInvite(ctx.viewer, input)), - revokeInvite: user - .input(C.personRefInputSchema) - .mutation(({ ctx, input }) => people.revokeInvite(ctx.viewer, input)), + sendInvite: user.input(C.personRefInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.sendInvite(ctx.viewer, input) + }), + revokeInvite: user.input(C.personRefInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.revokeInvite(ctx.viewer, input) + }), searchAccounts: link .input(C.searchAccountsInputSchema) .output(C.accountMatchSchema.array()) .query(({ ctx, input }) => people.searchAccounts(ctx.viewer, input)), - link: link.input(C.linkAccountInputSchema).mutation(({ ctx, input }) => people.linkAccount(ctx.viewer, input)), - unlink: link - .input(C.unlinkAccountInputSchema) - .mutation(({ ctx, input }) => people.unlinkAccount(ctx.viewer, input)), + link: link.input(C.linkAccountInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.linkAccount(ctx.viewer, input) + }), + unlink: link.input(C.unlinkAccountInputSchema).mutation(({ ctx, input }) => { + ctx.audit.set({ target: { type: "people.person", id: input.personId } }) + return people.unlinkAccount(ctx.viewer, input) + }), }), capo: createTRPCRouter({ get: self.output(C.capoAreaSchema).query(({ ctx }) => people.getCapoArea(ctx.viewer)), @@ -120,9 +166,10 @@ export function createPeopleRouter(people: PeopleService) { .input(C.inviteTokenInputSchema) .output(C.invitePreviewSchema) .query(({ ctx, input }) => people.previewInvite(ctx.viewer, input)), - acceptInvite: user - .input(C.inviteTokenInputSchema) - .mutation(({ ctx, input }) => people.acceptInvite(ctx.viewer, input)), + acceptInvite: user.input(C.inviteTokenInputSchema).mutation(async ({ ctx, input }) => { + const personId = await people.acceptInvite(ctx.viewer, input) + ctx.audit.set({ target: { type: "people.person", id: personId } }) + }), }), }) } diff --git a/src/people/service.ts b/src/people/service.ts index ae6a2d9..cf3969f 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -877,6 +877,7 @@ export function createPeopleService(options: PeopleOptions) { const p = link(u, find(u.state, invite.personId), v.sub, v.sub, "invite", "Accepted the email invite") Object.assign(invite, { revokedAt: null, acceptedAt: now().toISOString(), acceptedBy: v.sub }) sendPending(u, ctx, p, (a) => a.assignedBy, "Linked by accepting an invite in People") + return p.id }) }, diff --git a/src/regulations/router.ts b/src/regulations/router.ts index 05c958b..3858bd0 100644 --- a/src/regulations/router.ts +++ b/src/regulations/router.ts @@ -1,5 +1,6 @@ import { TRPCError } from "@trpc/server" import { z } from "zod" +import { audit } from "@/audit/option" import { SCOPE } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" import * as C from "./contract" @@ -8,6 +9,27 @@ import type { Directory } from "./directory" import type { EmanationService } from "./emanation/service" import { fail, type RegulationsService, type Viewer } from "./service" +/** The input fields kept in audit events: references to records, states, roles and titles. */ +const AUDITED_FIELDS = [ + "draftId", + "targetDraftId", + "snapshotId", + "commentId", + "delegaId", + "documentKey", + "userId", + "role", + "to", + "from.kind", + "from.id", + "source.kind", + "source.id", + "kind", + "title", + "name", + "expiresAt", +] as const + /** * `regulations.*`: every procedure is open to dashboard users (scope `backend:admin`), and the service checks the * rest: `regulations:read|write|manage|rectify` from the IdP, per-draft assignments, and deleghe. People with only @@ -20,11 +42,15 @@ export function createRegulationsRouter( ) { const diff = () => extras.diff ?? fail("PRECONDITION_FAILED", "Le differenze non sono configurate.") const emanation = () => extras.emanation ?? fail("PRECONDITION_FAILED", "L'emanazione non è configurata.") - const user = policy({ user: { scope: SCOPE.admin } }).use(async ({ ctx, next }) => { - if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) - const viewer: Viewer = { sub: ctx.actor.sub, can: ctx.can, person: await directory.person(ctx.actor.sub) } - return next({ ctx: { viewer } }) - }) + // Comments, snapshots, deleghe and delibere keep their own authors and text: the audit log keeps only which records a + // call names, never comment bodies, quotes, merge resolutions, delibere or notes. + const user = policy({ user: { scope: SCOPE.admin } }) + .meta(audit.full({ fields: AUDITED_FIELDS })) + .use(async ({ ctx, next }) => { + if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) + const viewer: Viewer = { sub: ctx.actor.sub, can: ctx.can, person: await directory.person(ctx.actor.sub) } + return next({ ctx: { viewer } }) + }) const draftRef = C.draftRefInputSchema const ok = z.void() @@ -103,6 +129,7 @@ export function createRegulationsRouter( .mutation(({ ctx, input }) => service.removeAssignment(ctx.viewer, input)), }), collabTicket: user + .meta(audit.none("Hands out a one-minute ticket to connect to the editor; it changes nothing")) .input(draftRef) .output(C.collabTicketSchema) .mutation(({ ctx, input }) => service.collabTicket(ctx.viewer, input.draftId)), diff --git a/src/routers/audit.ts b/src/routers/audit.ts new file mode 100644 index 0000000..acd837f --- /dev/null +++ b/src/routers/audit.ts @@ -0,0 +1,104 @@ +import { and, desc, eq, gte, ilike, lt, or, type SQL } from "drizzle-orm" +import { z } from "zod" +import { telegramNames, userNames } from "@/audit/names" +import { DB, SCHEMA } from "@/db" +import { AUDIT_OUTCOME } from "@/db/schema/common/audit-events" +import { dashboard } from "@/idp/policies" +import { createTRPCRouter, policy } from "@/trpc" + +const EVENTS = SCHEMA.COMMON.auditEvents + +/** The first segment of an action: where in the ecosystem the change was made. A test keeps it in step with the routers. */ +export const AUDIT_AREAS = [ + "azure", + "esign", + "groups", + "me", + "people", + "regulations", + "soci", + "tg", + "wa", + "web", +] as const + +const escapeLike = (value: string) => value.replace(/[\\%_]/g, (char) => `\\${char}`) + +export const auditRouter = createTRPCRouter({ + /** + * Every change made through the backend, newest first: who made it, on what, the state before and after, and the + * outcome. Pages with `cursor`, the `nextCursor` of the previous page; `from` is inclusive, `to` exclusive. + */ + list: policy(dashboard("audit:read")) + .input( + z.object({ + cursor: z.number().int().positive().optional(), + limit: z.number().int().min(1).max(100).default(50), + area: z.enum(AUDIT_AREAS).optional(), + outcome: z.enum(Object.values(AUDIT_OUTCOME)).optional(), + /** Matched against the action, the target, the reason and the error. */ + search: z.string().trim().max(100).optional(), + target: z.object({ type: z.string().min(1), id: z.string().min(1) }).optional(), + /** Who made the changes: an IdP subject, or a Telegram user. */ + actor: z + .union([ + z.object({ sub: z.string().min(1) }), + z.object({ telegramId: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) }), + ]) + .optional(), + from: z.date().optional(), + to: z.date().optional(), + }) + ) + .query(async ({ input }) => { + const conditions: SQL[] = [] + if (input.cursor) conditions.push(lt(EVENTS.id, input.cursor)) + if (input.area) conditions.push(ilike(EVENTS.action, `${input.area}.%`)) + if (input.outcome) conditions.push(eq(EVENTS.outcome, input.outcome)) + if (input.target) conditions.push(eq(EVENTS.targetType, input.target.type), eq(EVENTS.targetId, input.target.id)) + if (input.actor) + conditions.push( + "sub" in input.actor ? eq(EVENTS.actorSub, input.actor.sub) : eq(EVENTS.actorTgId, input.actor.telegramId) + ) + if (input.from) conditions.push(gte(EVENTS.createdAt, input.from)) + if (input.to) conditions.push(lt(EVENTS.createdAt, input.to)) + if (input.search) { + const pattern = `%${escapeLike(input.search)}%` + const matches = or( + ilike(EVENTS.action, pattern), + ilike(EVENTS.targetLabel, pattern), + ilike(EVENTS.targetId, pattern), + ilike(EVENTS.reason, pattern), + ilike(EVENTS.error, pattern) + ) + if (matches) conditions.push(matches) + } + + const rows = await DB.select() + .from(EVENTS) + .where(and(...conditions)) + .orderBy(desc(EVENTS.id)) + .limit(input.limit + 1) + const page = rows.slice(0, input.limit) + + const subs = [...new Set(page.flatMap((row) => (row.actorSub ? [row.actorSub] : [])))] + const telegramIds = new Set(page.flatMap((row) => (row.actorTgId === null ? [] : [row.actorTgId]))) + for (const row of page) + if (row.targetType === "tg.user" && row.targetId && Number.isSafeInteger(Number(row.targetId))) + telegramIds.add(Number(row.targetId)) + const [people, telegram] = await Promise.all([userNames(subs), telegramNames([...telegramIds])]) + + return { + events: page.map((row) => ({ + ...row, + actorName: + (row.actorSub ? people.get(row.actorSub) : undefined) ?? + (row.actorTgId === null ? undefined : telegram.get(row.actorTgId)) ?? + null, + targetLabel: + row.targetLabel ?? (row.targetType === "tg.user" ? (telegram.get(Number(row.targetId)) ?? null) : null), + })), + nextCursor: rows.length > input.limit ? (page.at(-1)?.id ?? null) : null, + } + }), +}) diff --git a/src/routers/esign.ts b/src/routers/esign.ts index 3c3f47c..8f0926c 100644 --- a/src/routers/esign.ts +++ b/src/routers/esign.ts @@ -1,6 +1,8 @@ import type { Actor } from "@polinetwork/auth-kit" import { TRPCError } from "@trpc/server" import { z } from "zod" +import type { AuditRecorder } from "@/audit" +import { audit } from "@/audit/option" import { esign } from "@/esign" import { MAX_PDF_BYTES } from "@/esign/drive/types" import { EsignError, type EsignErrorCode } from "@/esign/errors" @@ -70,6 +72,11 @@ function publicPdf(pdf: PdfInfo) { const accessKey = z.string().regex(/^[A-Za-z0-9:._-]{1,100}$/) const driveRule = z.object({ roles: z.array(accessKey).max(50), permissions: z.array(accessKey).max(50) }) +/** Names the request a mutation acts on in its audit event. */ +async function auditRequest(ctx: { audit: AuditRecorder }, id: string) { + ctx.audit.set({ target: { type: "esign.request", id, label: await esign.requestTitle(id) } }) +} + function requireManage(caller: Caller) { if (!caller.canManage) throw new TRPCError({ code: "FORBIDDEN", message: "You cannot manage signature requests" }) } @@ -84,6 +91,7 @@ export const esignRouter = createTRPCRouter({ profile: createTRPCRouter({ /** The BFF passes the signed-in user's name and email from the ID token. */ sync: user + .meta(audit.none("Copies the signed-in user's name and email on each visit, not a change made by someone")) .input(z.object({ name: z.string().min(1).max(200), email: z.email().nullable() })) .mutation(({ ctx, input }) => run(() => esign.syncProfile(callerOf(ctx), input))), }), @@ -94,10 +102,14 @@ export const esignRouter = createTRPCRouter({ return run(() => esign.listProfiles()) }), /** Forgets the CIE bound to a person, e.g. after they renewed their card. */ - resetIdentity: user.input(z.object({ sub: z.string().min(1) })).mutation(({ ctx, input }) => { - requireManage(callerOf(ctx)) - return run(() => esign.resetIdentity(input.sub)) - }), + resetIdentity: user + .meta(audit.full()) + .input(z.object({ sub: z.string().min(1) })) + .mutation(({ ctx, input }) => { + requireManage(callerOf(ctx)) + ctx.audit.set({ target: { type: "esign.signer", id: input.sub } }) + return run(() => esign.resetIdentity(input.sub)) + }), }), drive: createTRPCRouter({ @@ -114,14 +126,25 @@ export const esignRouter = createTRPCRouter({ .input(z.object({ driveId: z.string().min(1), sign: driveRule })) .query(({ ctx, input }) => run(() => esign.driveAccessImpact(callerOf(ctx), input.driveId, input.sign))), setAccess: user + .meta(audit.full()) .input(z.object({ driveId: z.string().min(1), request: driveRule, sign: driveRule })) - .mutation(({ ctx, input }) => - run(() => esign.setDriveAccess(callerOf(ctx), input.driveId, { request: input.request, sign: input.sign })) - ), + .mutation(async ({ ctx, input }) => { + const caller = callerOf(ctx) + const drive = (await run(() => esign.driveAccess(caller))).drives.find((d) => d.id === input.driveId) + ctx.audit.set({ + target: { type: "esign.drive", id: input.driveId, label: drive?.label }, + before: drive && { request: drive.request, sign: drive.sign }, + }) + const saved = await run(() => + esign.setDriveAccess(caller, input.driveId, { request: input.request, sign: input.sign }) + ) + ctx.audit.set({ after: saved }) + }), }), documents: createTRPCRouter({ upload: user + .meta(audit.full()) .input( z .instanceof(FormData) @@ -134,14 +157,23 @@ export const esignRouter = createTRPCRouter({ const { document, pdf } = await run(async () => esign.stageUpload(caller, input.name, new Uint8Array(await input.arrayBuffer())) ) + ctx.audit.set({ + target: { type: "esign.document", id: document.id, label: document.fileName }, + after: document, + }) return { document, pdf: publicPdf(pdf) } }), fromDrive: user + .meta(audit.full()) .input(z.object({ driveId: z.string().min(1), itemId: z.string().min(1) })) .mutation(async ({ ctx, input }) => { const caller = callerOf(ctx) requireManage(caller) const { document, pdf } = await run(() => esign.stageDriveItem(caller, input.driveId, input.itemId)) + ctx.audit.set({ + target: { type: "esign.document", id: document.id, label: document.fileName }, + after: document, + }) return { document, pdf: publicPdf(pdf) } }), /** The document's metadata, pages and existing signatures. */ @@ -158,6 +190,12 @@ export const esignRouter = createTRPCRouter({ requests: createTRPCRouter({ create: user + .meta( + // Only the declared parts of `output`: the raw input is recorded, so extra keys a caller sends would be kept. + audit.full({ + fields: ["title", "documentId", "ordered", "output.driveId", "output.folderId", "output.fileName"], + }) + ) .input( z.object({ title: z.string().trim().min(1).max(200), @@ -186,7 +224,27 @@ export const esignRouter = createTRPCRouter({ email: z.object({ to: z.array(z.email()).max(20), message: z.string().max(2000).nullable() }).nullable(), }) ) - .mutation(({ ctx, input }) => run(() => esign.createRequest(callerOf(ctx), input))), + .mutation(async ({ ctx, input }) => { + ctx.audit.set({ target: { type: "esign.document", id: input.documentId, label: input.title } }) + const request = await run(() => esign.createRequest(callerOf(ctx), input)) + // Who signs, in which order: not their fiscal codes, certificates or the email recipients. + ctx.audit.set({ + target: { type: "esign.request", id: request.id, label: request.title }, + after: { + id: request.id, + title: request.title, + status: request.status, + ordered: request.ordered, + drives: request.drives, + signers: request.signers.map((signer) => ({ + sub: signer.sub, + role: signer.role, + position: signer.position, + })), + }, + }) + return request + }), list: user .input(z.object({ scope: z.enum(["inbox", "mine", "all"]) })) .query(({ ctx, input }) => run(() => esign.listRequests(callerOf(ctx), input.scope))), @@ -194,19 +252,33 @@ export const esignRouter = createTRPCRouter({ .input(z.object({ id: z.uuid() })) .query(({ ctx, input }) => run(() => esign.getRequest(callerOf(ctx), input.id))), cancel: user + .meta(audit.full()) .input(z.object({ id: z.uuid() })) - .mutation(({ ctx, input }) => run(() => esign.cancelRequest(callerOf(ctx), input.id))), + .mutation(async ({ ctx, input }) => { + await auditRequest(ctx, input.id) + return run(() => esign.cancelRequest(callerOf(ctx), input.id)) + }), delete: user + .meta(audit.full()) .input(z.object({ id: z.uuid() })) - .mutation(({ ctx, input }) => run(() => esign.deleteRequest(callerOf(ctx), input.id))), + .mutation(async ({ ctx, input }) => { + await auditRequest(ctx, input.id) + return run(() => esign.deleteRequest(callerOf(ctx), input.id)) + }), decline: user + .meta(audit.full({ fields: ["id"] })) .input(z.object({ id: z.uuid(), reason: z.string().max(500).nullable() })) - .mutation(({ ctx, input }) => run(() => esign.declineRequest(callerOf(ctx), input.id, input.reason))), + .mutation(async ({ ctx, input }) => { + await auditRequest(ctx, input.id) + ctx.audit.set({ reason: input.reason }) + return run(() => esign.declineRequest(callerOf(ctx), input.id, input.reason)) + }), /** * The fallback: a PDF signed with the official CIE app, uploaded by its signer. The dashboard no longer offers it; * once no deployed dashboard calls it, this and the service's `uploadSigned` can be removed. */ uploadSigned: user + .meta(audit.full()) .input( z .instanceof(FormData) @@ -218,14 +290,19 @@ export const esignRouter = createTRPCRouter({ }) ) ) - .mutation(({ ctx, input }) => - run(async () => + .mutation(async ({ ctx, input }) => { + await auditRequest(ctx, input.requestId) + return run(async () => esign.uploadSigned(callerOf(ctx), input.requestId, new Uint8Array(await input.file.arrayBuffer())) ) - ), + }), retryDelivery: user + .meta(audit.full()) .input(z.object({ id: z.uuid() })) - .mutation(({ ctx, input }) => run(() => esign.retryDelivery(callerOf(ctx), input.id))), + .mutation(async ({ ctx, input }) => { + await auditRequest(ctx, input.id) + return run(() => esign.retryDelivery(callerOf(ctx), input.id)) + }), }), jobs: createTRPCRouter({ @@ -234,6 +311,7 @@ export const esignRouter = createTRPCRouter({ * ticket, so one PIN signs them all. `places` moves the caller's boxes before signing, one per place, in order. */ create: user + .meta(audit.full()) .input( z.object({ items: z @@ -242,14 +320,27 @@ export const esignRouter = createTRPCRouter({ .max(10), }) ) - .mutation(({ ctx, input }) => run(() => esign.createJobs(callerOf(ctx), input.items))), + .mutation(({ ctx, input }) => { + const ids = input.items.map((item) => item.requestId) + // Several requests are named by their number, with the ids in the input. + ctx.audit.set({ + target: + ids.length === 1 + ? { type: "esign.request", id: ids[0] ?? null } + : { type: "esign.request", id: null, label: `${ids.length} requests` }, + }) + return run(() => esign.createJobs(callerOf(ctx), input.items)) + }), statuses: user .input(z.object({ jobIds: z.array(z.uuid()).min(1).max(10) })) .query(({ ctx, input }) => run(() => esign.jobStatuses(callerOf(ctx), input.jobIds))), - cancel: user.input(z.object({ jobIds: z.array(z.uuid()).min(1).max(10) })).mutation(({ ctx, input }) => - run(async () => { - for (const jobId of input.jobIds) await esign.cancelJob(callerOf(ctx), jobId) - }) - ), + cancel: user + .meta(audit.full()) + .input(z.object({ jobIds: z.array(z.uuid()).min(1).max(10) })) + .mutation(({ ctx, input }) => + run(async () => { + for (const jobId of input.jobIds) await esign.cancelJob(callerOf(ctx), jobId) + }) + ), }), }) diff --git a/src/routers/groups/labels.ts b/src/routers/groups/labels.ts index c7337ce..b5260ff 100644 --- a/src/routers/groups/labels.ts +++ b/src/routers/groups/labels.ts @@ -1,5 +1,6 @@ import { and, eq, sql } from "drizzle-orm" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { authorOf } from "@/idp/author" import { dashboard } from "@/idp/policies" @@ -32,6 +33,7 @@ export default createTRPCRouter({ }), create: policy(dashboard("groups:labels:write")) + .meta(audit.full()) .input( z.object({ label, @@ -52,23 +54,29 @@ export default createTRPCRouter({ }) .returning() + ctx.audit.set({ target: { type: "groups.label", id: result[0].id, label }, after: result[0] }) return result }), delete: policy(dashboard("groups:labels:write")) + .meta(audit.full()) .input( z.object({ label, }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { label } = input const labelRow = await DB.select({ id: GROUP_LABELS.id }) .from(GROUP_LABELS) .where(eq(GROUP_LABELS.label, label)) .limit(1) - if (!labelRow.length) return [] + if (!labelRow.length) { + // Nothing to delete, so nothing changed. + ctx.audit.skip() + return [] + } const labelId = labelRow[0].id const [[tgCount], [waCount]] = await Promise.all([ @@ -83,10 +91,12 @@ export default createTRPCRouter({ } const result = await DB.delete(GROUP_LABELS).where(eq(GROUP_LABELS.label, label)).returning() + ctx.audit.set({ target: { type: "groups.label", id: labelId, label }, before: result[0] }) return result }), modify: policy(dashboard("groups:labels:write")) + .meta(audit.full()) .input( z.object({ label, @@ -102,6 +112,7 @@ export default createTRPCRouter({ const { label, newLabel, description, color } = input const author = authorOf(ctx.actor) + const [before] = await DB.select().from(GROUP_LABELS).where(eq(GROUP_LABELS.label, label)).limit(1) const result = await DB.update(GROUP_LABELS) .set({ label: newLabel, @@ -114,10 +125,18 @@ export default createTRPCRouter({ .where(eq(GROUP_LABELS.label, label)) .returning() + // An unknown label changed nothing. + if (result.length === 0) ctx.audit.skip() + ctx.audit.set({ + target: { type: "groups.label", id: result[0]?.id ?? before?.id ?? null, label: newLabel ?? label }, + before, + after: result[0], + }) return result }), tagGroup: policy(dashboard("groups:labels:write")) + .meta(audit.full()) .input( z.object({ groupId: z.number(), @@ -125,8 +144,9 @@ export default createTRPCRouter({ label, }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { groupId, type, label } = input + ctx.audit.set({ target: { type: `${type}.group`, id: groupId } }) await assertGroupExists(groupId, type) const labelIdResult = await DB.select({ id: GROUP_LABELS.id }) @@ -136,25 +156,16 @@ export default createTRPCRouter({ if (!labelIdResult.length) throw new Error("Label not found") const labelId = labelIdResult[0].id - if (type === "tg") { - const result = await DB.insert(TG_RELATIONS) - .values({ - groupId, - labelId, - }) - .returning() - return result - } - - return DB.insert(WA_RELATIONS) - .values({ - groupId, - labelId, - }) - .returning() + const result = + type === "tg" + ? await DB.insert(TG_RELATIONS).values({ groupId, labelId }).returning() + : await DB.insert(WA_RELATIONS).values({ groupId, labelId }).returning() + ctx.audit.set({ after: { label } }) + return result }), untagGroup: policy(dashboard("groups:labels:write")) + .meta(audit.full()) .input( z.object({ groupId: z.number(), @@ -162,8 +173,9 @@ export default createTRPCRouter({ label, }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { groupId, type, label } = input + ctx.audit.set({ target: { type: `${type}.group`, id: groupId } }) await assertGroupExists(groupId, type) @@ -174,12 +186,17 @@ export default createTRPCRouter({ if (!labelIdResult.length) throw new Error("Label not found") const labelId = labelIdResult[0].id - return type === "tg" - ? DB.delete(TG_RELATIONS) - .where(and(eq(TG_RELATIONS.groupId, groupId), eq(TG_RELATIONS.labelId, labelId))) - .returning() - : DB.delete(WA_RELATIONS) - .where(and(eq(WA_RELATIONS.groupId, groupId), eq(WA_RELATIONS.labelId, labelId))) - .returning() + const result = + type === "tg" + ? await DB.delete(TG_RELATIONS) + .where(and(eq(TG_RELATIONS.groupId, groupId), eq(TG_RELATIONS.labelId, labelId))) + .returning() + : await DB.delete(WA_RELATIONS) + .where(and(eq(WA_RELATIONS.groupId, groupId), eq(WA_RELATIONS.labelId, labelId))) + .returning() + // The group may not have had the label: then nothing changed. + if (result.length === 0) ctx.audit.skip() + else ctx.audit.set({ before: { label } }) + return result }), }) diff --git a/src/routers/index.ts b/src/routers/index.ts index b89d038..8d6e0f4 100644 --- a/src/routers/index.ts +++ b/src/routers/index.ts @@ -1,4 +1,5 @@ import { createTRPCRouter } from "@/trpc" +import { auditRouter } from "./audit" import { azureRouter } from "./azure" import { esignRouter } from "./esign" import { groupsRouter } from "./groups" @@ -16,6 +17,7 @@ import { webRouter } from "./web" * All routers added in /api/routers should be manually added here. */ export const appRouter = createTRPCRouter({ + audit: auditRouter, azure: azureRouter, esign: esignRouter, groups: groupsRouter, diff --git a/src/routers/tg/audit-log.ts b/src/routers/tg/audit-log.ts index 7251a08..558a268 100644 --- a/src/routers/tg/audit-log.ts +++ b/src/routers/tg/audit-log.ts @@ -2,6 +2,7 @@ import { TRPCError } from "@trpc/server" import { desc, eq } from "drizzle-orm" import { alias } from "drizzle-orm/pg-core" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { ARRAY_AUDIT_TYPE, @@ -44,6 +45,7 @@ export default createTRPCRouter({ * `idempotencyKey` records nothing and returns the first record. */ record: policy({ service: { scope: SCOPE.tgAudit } }) + .meta(audit.none("Moderation is kept in tg_audit_log, under its own retention rules")) .input( z .object({ diff --git a/src/routers/tg/grants.ts b/src/routers/tg/grants.ts index 888c677..d11f149 100644 --- a/src/routers/tg/grants.ts +++ b/src/routers/tg/grants.ts @@ -1,6 +1,7 @@ import { TRPCError } from "@trpc/server" import { and, eq, gt, inArray, isNull } from "drizzle-orm" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { describeActor } from "@/idp/actor-info" import { ACT_AS_SCOPE } from "@/idp/auth" @@ -53,6 +54,7 @@ export default createTRPCRouter({ * grantor is the token's user. */ create: policy(dashboard("tg:grants:manage")) + .meta(audit.full()) .input( z.object({ userId: z.number(), @@ -76,6 +78,7 @@ export default createTRPCRouter({ ) .mutation(async ({ input, ctx }) => { const { actor } = ctx + ctx.audit.set({ target: { type: "tg.user", id: input.userId }, reason: input.reason }) if (actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) try { @@ -92,6 +95,7 @@ export default createTRPCRouter({ grantedBySub: actor.sub, grantedViaClient: actor.client, }) + ctx.audit.set({ after: { validSince: input.since, validUntil: input.until } }) if (input.sendTgLog) { const author = await describeActor(actor) @@ -119,6 +123,7 @@ export default createTRPCRouter({ telegram: { scope: ACT_AS_SCOPE, permission: "tg:grants:manage" }, ...dashboard("tg:grants:manage"), }) + .meta(audit.full()) .input( z.object({ userId: z.number(), @@ -139,6 +144,7 @@ export default createTRPCRouter({ ) .mutation(async ({ input, ctx }) => { const { actor } = ctx + ctx.audit.set({ target: { type: "tg.user", id: input.userId } }) if (actor.kind === "service") throw new TRPCError({ code: "FORBIDDEN" }) try { @@ -153,8 +159,9 @@ export default createTRPCRouter({ .where( and(eq(s.grants.telegramUserId, input.userId), gt(s.grants.validUntil, now), isNull(s.grants.interruptedAt)) ) - .returning({ id: s.grants.id }) + .returning() + ctx.audit.set({ after: interrupted }) if (interrupted.length === 0) return { success: false, diff --git a/src/routers/tg/groups.ts b/src/routers/tg/groups.ts index 3f2935c..7ee1ec9 100644 --- a/src/routers/tg/groups.ts +++ b/src/routers/tg/groups.ts @@ -1,5 +1,6 @@ -import { and, eq, exists, ilike, ne, not, notExists, or, type SQL, sql } from "drizzle-orm" +import { and, eq, exists, ilike, inArray, ne, not, notExists, or, type SQL, sql } from "drizzle-orm" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { describeActor } from "@/idp/actor-info" import { botReadOrDashboard, dashboard, SCOPE, seesHiddenGroups } from "@/idp/policies" @@ -153,6 +154,7 @@ export default createTRPCRouter({ }), create: policy({ service: { scope: SCOPE.tgGroupsSync } }) + .meta(audit.full()) .input( z.array( z.object({ @@ -164,56 +166,108 @@ export default createTRPCRouter({ ) ) .output(z.array(z.number())) - .mutation(async ({ input }) => { - for (const group of input) { - await DB.delete(GROUPS).where(and(eq(GROUPS.link, group.link), ne(GROUPS.telegramId, group.telegramId))) - } + .mutation(async ({ input, ctx }) => { + // One transaction, so the recorded state before is the one the upsert replaced. + const { replaced, before, rows } = await DB.transaction(async (tx) => { + const replaced = [] + for (const group of input) { + replaced.push( + ...(await tx + .delete(GROUPS) + .where(and(eq(GROUPS.link, group.link), ne(GROUPS.telegramId, group.telegramId))) + .returning()) + ) + } + const before = await tx + .select() + .from(GROUPS) + .where( + inArray( + GROUPS.telegramId, + input.map((group) => group.telegramId) + ) + ) - const rows = await DB.insert(GROUPS) - .values(input) - .onConflictDoUpdate({ - target: GROUPS.telegramId, - set: { - // this means: use the new value - title: sql.raw(`excluded.${GROUPS.title.name}`), - tag: sql.raw(`excluded.${GROUPS.tag.name}`), - link: sql.raw(`excluded.${GROUPS.link.name}`), - }, - }) - .returning() + const rows = await tx + .insert(GROUPS) + .values(input) + .onConflictDoUpdate({ + target: GROUPS.telegramId, + set: { + // this means: use the new value + title: sql.raw(`excluded.${GROUPS.title.name}`), + tag: sql.raw(`excluded.${GROUPS.tag.name}`), + link: sql.raw(`excluded.${GROUPS.link.name}`), + }, + }) + .returning() + return { replaced, before, rows } + }) + // The bot syncs groups often; only what it changes is recorded. + const known = new Map(before.map((group) => [group.telegramId, group])) + const changed = rows.filter((row) => { + const old = known.get(row.telegramId) + return !old || old.title !== row.title || old.tag !== row.tag || old.link !== row.link + }) + if (replaced.length === 0 && changed.length === 0) { + ctx.audit.skip() + return rows.map((r) => r.telegramId) + } + ctx.audit.set({ + target: + input.length === 1 + ? { type: "tg.group", id: input[0].telegramId, label: input[0].title } + : // Several groups are named by their number, with the ids in the input. + { type: "tg.group", id: null, label: `${input.length} groups` }, + before: [...replaced, ...changed.flatMap((row) => known.get(row.telegramId) ?? [])], + after: changed, + }) return rows.map((r) => r.telegramId) }), delete: policy({ service: { scope: SCOPE.tgGroupsSync } }) + .meta(audit.full()) .input( z.object({ telegramId: z.number(), }) ) .output(z.boolean()) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const rows = await DB.delete(GROUPS).where(eq(GROUPS.telegramId, input.telegramId)).returning() + ctx.audit.set({ target: { type: "tg.group", id: input.telegramId, label: rows[0]?.title }, before: rows[0] }) return rows.length === 1 }), setHide: policy(dashboard("tg:groups:manage")) + .meta(audit.full()) .input( z.object({ telegramId: z.number(), hide: z.boolean(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { + const [before] = await DB.select({ hide: GROUPS.hide }) + .from(GROUPS) + .where(eq(GROUPS.telegramId, input.telegramId)) + .limit(1) const rows = await DB.update(GROUPS) .set({ hide: input.hide }) .where(eq(GROUPS.telegramId, input.telegramId)) .returning() + ctx.audit.set({ + target: { type: "tg.group", id: input.telegramId, label: rows[0]?.title }, + before, + after: rows[0] && { hide: rows[0].hide }, + }) return rows.length === 1 }), /** The performer is the token's user. */ leaveChat: policy(dashboard("tg:groups:manage")) + .meta(audit.full()) .input( z.object({ chatId: z.number(), @@ -221,6 +275,8 @@ export default createTRPCRouter({ ) .mutation(async ({ input, ctx }) => { const performer = await describeActor(ctx.actor) + const [group] = await DB.select().from(GROUPS).where(eq(GROUPS.telegramId, input.chatId)).limit(1) + ctx.audit.set({ target: { type: "tg.group", id: input.chatId, label: group?.title }, before: group }) const left = await WSS.leaveChat({ chatId: input.chatId, performer, diff --git a/src/routers/tg/messages.ts b/src/routers/tg/messages.ts index 13fb7e7..7198c27 100644 --- a/src/routers/tg/messages.ts +++ b/src/routers/tg/messages.ts @@ -1,5 +1,6 @@ import { and, desc, eq } from "drizzle-orm" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { botReadOrDashboard, SCOPE } from "@/idp/policies" import { logger } from "@/logger" @@ -78,6 +79,7 @@ export default createTRPCRouter({ }), add: policy({ service: { scope: SCOPE.tgIngest } }) + .meta(audit.none("The bot's ingestion of group messages, not changes made by someone")) .input(z.object({ messages: z.array(message) })) .output(z.object({ error: z.union([z.null(), z.enum(["ENCRYPT_ERROR"])]) })) .mutation(async ({ input }) => { diff --git a/src/routers/tg/users.ts b/src/routers/tg/users.ts index a458289..8fbbb15 100644 --- a/src/routers/tg/users.ts +++ b/src/routers/tg/users.ts @@ -1,5 +1,6 @@ import { count, eq, sql } from "drizzle-orm" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { botReadOrDashboard, dashboard, SCOPE } from "@/idp/policies" import { logger } from "@/logger" @@ -138,6 +139,7 @@ export default createTRPCRouter({ }), add: policy({ service: { scope: SCOPE.tgIngest } }) + .meta(audit.none("The bot's ingestion of the users it sees, not changes made by someone")) .input(z.object({ users: z.array(TgUserSchema) })) .output( z.union([ diff --git a/src/routers/wa/groups.ts b/src/routers/wa/groups.ts index 2ad9f1c..9aa14d6 100644 --- a/src/routers/wa/groups.ts +++ b/src/routers/wa/groups.ts @@ -1,5 +1,6 @@ import { eq } from "drizzle-orm" import { z } from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { dashboard } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" @@ -45,6 +46,7 @@ export default createTRPCRouter({ }), add: policy(dashboard("wa:groups:manage")) + .meta(audit.full()) .input( z.object({ title: z.string(), @@ -52,12 +54,14 @@ export default createTRPCRouter({ hide: z.boolean().default(false), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const [created] = await DB.insert(GROUPS).values(input).returning() + ctx.audit.set({ target: { type: "wa.group", id: created.id, label: created.title }, after: created }) return created }), modify: policy(dashboard("wa:groups:manage")) + .meta(audit.full()) .input( z.object({ id: z.number(), @@ -65,33 +69,50 @@ export default createTRPCRouter({ link: z.url({ hostname: /^chat\.whatsapp\.com$/ }), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { id, ...values } = input + const [before] = await DB.select().from(GROUPS).where(eq(GROUPS.id, id)).limit(1) const [updated] = await DB.update(GROUPS).set(values).where(eq(GROUPS.id, id)).returning() + // An unknown group changed nothing. + if (!updated) ctx.audit.skip() + ctx.audit.set({ + target: { type: "wa.group", id, label: updated?.title ?? before?.title }, + before, + after: updated, + }) return updated }), delete: policy(dashboard("wa:groups:manage")) + .meta(audit.full()) .input( z.object({ id: z.number(), }) ) .output(z.boolean()) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const rows = await DB.delete(GROUPS).where(eq(GROUPS.id, input.id)).returning() + ctx.audit.set({ target: { type: "wa.group", id: input.id, label: rows[0]?.title }, before: rows[0] }) return rows.length === 1 }), setHide: policy(dashboard("wa:groups:manage")) + .meta(audit.full()) .input( z.object({ id: z.number(), hide: z.boolean(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { + const [before] = await DB.select({ hide: GROUPS.hide }).from(GROUPS).where(eq(GROUPS.id, input.id)).limit(1) const rows = await DB.update(GROUPS).set({ hide: input.hide }).where(eq(GROUPS.id, input.id)).returning() + ctx.audit.set({ + target: { type: "wa.group", id: input.id, label: rows[0]?.title }, + before, + after: rows[0] && { hide: rows[0].hide }, + }) return rows.length === 1 }), diff --git a/src/routers/web/associations.ts b/src/routers/web/associations.ts index bdfd2c1..2915743 100644 --- a/src/routers/web/associations.ts +++ b/src/routers/web/associations.ts @@ -1,5 +1,6 @@ import { asc, eq } from "drizzle-orm" import z from "zod" +import { audit } from "@/audit/option" import { uploadBlob } from "@/azure/blob" import { DB, SCHEMA } from "@/db" import { authorOf, createdByColumns, modifiedByColumns } from "@/idp/author" @@ -76,6 +77,7 @@ export default createTRPCRouter({ }), addAssociation: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z .instanceof(FormData) @@ -99,10 +101,12 @@ export default createTRPCRouter({ }) .returning() + ctx.audit.set({ target: { type: "web.association", id: res.id, label: res.name }, after: res }) return formatAssociation(res) }), editAssociation: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z .instanceof(FormData) @@ -120,22 +124,35 @@ export default createTRPCRouter({ ? await uploadBlob(Buffer.from(await logo.arrayBuffer()), getImageExtension(logo), logo.type) : undefined - const [res] = await DB.update(ASSOCIATIONS) - .set({ - name, - descriptionIt, - descriptionEn, - ...(uploadedLogo ? { logo: uploadedLogo.url } : {}), - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(ASSOCIATIONS.id, id)) - .returning() + const { before, res } = await DB.transaction(async (tx) => { + const [before] = await tx.select().from(ASSOCIATIONS).where(eq(ASSOCIATIONS.id, id)).limit(1).for("update") + if (!before) return { before, res: undefined } + const [res] = await tx + .update(ASSOCIATIONS) + .set({ + name, + descriptionIt, + descriptionEn, + ...(uploadedLogo ? { logo: uploadedLogo.url } : {}), + ...modifiedByColumns(authorOf(ctx.actor)), + }) + .where(eq(ASSOCIATIONS.id, id)) + .returning() + + return { before, res } + }) + ctx.audit.set({ + target: { type: "web.association", id, label: res?.name ?? before?.name }, + before, + after: res, + }) if (!res) return { error: "NOT_FOUND" } return formatAssociation(res) }), editAssociationLinks: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), @@ -146,36 +163,50 @@ export default createTRPCRouter({ const { id, links } = input const { email, website, facebook, instagram, tiktok, x, youtube, telegram, linkedin, spotify } = links - const [res] = await DB.update(ASSOCIATIONS) - .set({ - email, - website, - facebook, - instagram, - tiktok, - x, - youtube, - telegram, - linkedin, - spotify, - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(ASSOCIATIONS.id, id)) - .returning() + const { before, res } = await DB.transaction(async (tx) => { + const [before] = await tx.select().from(ASSOCIATIONS).where(eq(ASSOCIATIONS.id, id)).limit(1).for("update") + if (!before) return { before, res: undefined } + const [res] = await tx + .update(ASSOCIATIONS) + .set({ + email, + website, + facebook, + instagram, + tiktok, + x, + youtube, + telegram, + linkedin, + spotify, + ...modifiedByColumns(authorOf(ctx.actor)), + }) + .where(eq(ASSOCIATIONS.id, id)) + .returning() + return { before, res } + }) + + ctx.audit.set({ + target: { type: "web.association", id, label: res?.name ?? before?.name }, + before, + after: res, + }) if (!res) return { error: "NOT_FOUND" } return formatAssociation(res) }), deleteAssociation: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { id } = input const deleted = await DB.delete(ASSOCIATIONS).where(eq(ASSOCIATIONS.id, id)).returning() + ctx.audit.set({ target: { type: "web.association", id, label: deleted[0]?.name }, before: deleted[0] }) if (deleted.length === 0) return { error: "NOT_FOUND" } return { error: null } diff --git a/src/routers/web/documents.ts b/src/routers/web/documents.ts index 16f7396..2e8574a 100644 --- a/src/routers/web/documents.ts +++ b/src/routers/web/documents.ts @@ -2,6 +2,7 @@ import { TRPCError } from "@trpc/server" import { and, asc, desc, eq, inArray, max, ne, sql } from "drizzle-orm" import { PDFDocument } from "pdf-lib" import z from "zod" +import { audit } from "@/audit/option" import { deleteBlob, uploadBlob } from "@/azure/blob" import { DB, SCHEMA } from "@/db" import { authorOf, createdByColumns, modifiedByColumns } from "@/idp/author" @@ -197,6 +198,14 @@ async function nextDocumentPosition(tx: Tx, categoryId: number) { return last === null ? 0 : last + 1 } +const categoryTarget = (row: { id: number; title: string }) => ({ + type: "web.documentCategory", + id: row.id, + label: row.title, +}) +const documentTarget = (row: { id: number; title: string }) => ({ type: "web.document", id: row.id, label: row.title }) + +// Audit states are set once a transaction has committed, and only for calls that changed something. export default createTRPCRouter({ getCatalog: policy(publicData) .output( @@ -269,9 +278,10 @@ export default createTRPCRouter({ .query(async () => readCatalog()), createCategory: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(z.object({ slug: slugSchema, title: titleSchema, description: descriptionSchema })) .mutation(async ({ input, ctx }) => { - return DB.transaction(async (tx) => { + const result = await DB.transaction(async (tx) => { await lockCategoryList(tx) const [{ last }] = await tx.select({ last: max(CATEGORIES.position) }).from(CATEGORIES) const [row] = await tx @@ -282,9 +292,12 @@ export default createTRPCRouter({ if (!row) return { error: "DUPLICATE_SLUG" as const } return row }) + if (!("error" in result)) ctx.audit.set({ target: categoryTarget(result), after: result }) + return result }), updateCategory: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: idSchema, @@ -295,7 +308,9 @@ export default createTRPCRouter({ ) .mutation(async ({ input, ctx }) => { const { id, ...fields } = input - return DB.transaction(async (tx) => { + const result = await DB.transaction(async (tx) => { + const [before] = await tx.select(categoryColumns).from(CATEGORIES).where(eq(CATEGORIES.id, id)).for("update") + if (!before) return { error: "NOT_FOUND" as const } if (fields.slug !== undefined && (await slugTaken(tx, CATEGORIES, fields.slug, id))) return { error: "DUPLICATE_SLUG" as const } const [row] = await tx @@ -304,14 +319,18 @@ export default createTRPCRouter({ .where(eq(CATEGORIES.id, id)) .returning(categoryColumns) if (!row) return { error: "NOT_FOUND" as const } - return row + return { before, row } }).catch(duplicateSlug("web_document_categories")) + if (result.error) return { error: result.error } + ctx.audit.set({ target: categoryTarget(result.row), before: result.before, after: result.row }) + return result.row }), deleteCategory: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(z.object({ id: idSchema })) - .mutation(async ({ input }) => { - return DB.transaction(async (tx) => { + .mutation(async ({ input, ctx }) => { + const result = await DB.transaction(async (tx) => { if (!(await lockCategories(tx, [input.id])).has(input.id)) return { error: "NOT_FOUND" as const } const [document] = await tx .select({ id: DOCUMENTS.id }) @@ -319,15 +338,22 @@ export default createTRPCRouter({ .where(eq(DOCUMENTS.categoryId, input.id)) .limit(1) if (document) return { error: "CATEGORY_NOT_EMPTY" as const } - await tx.delete(CATEGORIES).where(eq(CATEGORIES.id, input.id)) - return { error: null } + const [deleted] = await tx.delete(CATEGORIES).where(eq(CATEGORIES.id, input.id)).returning(categoryColumns) + return { deleted } }) + if (result.error) return { error: result.error } + ctx.audit.set({ + target: { type: "web.documentCategory", id: input.id, label: result.deleted?.title }, + before: result.deleted, + }) + return { error: null } }), reorderCategories: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(z.object({ ids: orderSchema })) - .mutation(async ({ input }) => { - return DB.transaction(async (tx) => { + .mutation(async ({ input, ctx }) => { + const result = await DB.transaction(async (tx) => { await lockCategoryList(tx) const current = await tx .select({ id: CATEGORIES.id }) @@ -341,13 +367,27 @@ export default createTRPCRouter({ ) ) return { error: "INVALID_ORDER" as const } + const order = () => + tx + .select({ id: CATEGORIES.id, title: CATEGORIES.title, position: CATEGORIES.position }) + .from(CATEGORIES) + .orderBy(asc(CATEGORIES.position), asc(CATEGORIES.id)) + const before = await order() for (const [position, id] of input.ids.entries()) await tx.update(CATEGORIES).set({ position }).where(eq(CATEGORIES.id, id)) - return { error: null } + return { before, after: await order() } + }) + if (result.error) return { error: result.error } + ctx.audit.set({ + target: { type: "web.documentCategories", id: "order", label: "Document categories order" }, + before: result.before, + after: result.after, }) + return { error: null } }), createDocument: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ categoryId: idSchema, @@ -357,7 +397,7 @@ export default createTRPCRouter({ }) ) .mutation(async ({ input, ctx }) => { - return DB.transaction(async (tx) => { + const result = await DB.transaction(async (tx) => { if (!(await lockCategories(tx, [input.categoryId])).has(input.categoryId)) return { error: "CATEGORY_NOT_FOUND" as const } const [row] = await tx @@ -373,9 +413,12 @@ export default createTRPCRouter({ if (!row) return { error: "DUPLICATE_SLUG" as const } return row }) + if (!("error" in result)) ctx.audit.set({ target: documentTarget(result), after: result }) + return result }), updateDocument: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: idSchema, @@ -387,16 +430,13 @@ export default createTRPCRouter({ ) .mutation(async ({ input, ctx }) => { const { id, categoryId, description, ...fields } = input - return DB.transaction(async (tx) => { + const result = await DB.transaction(async (tx) => { await lockDocument(tx, id) - const [current] = await tx - .select({ categoryId: DOCUMENTS.categoryId }) - .from(DOCUMENTS) - .where(eq(DOCUMENTS.id, id)) - if (!current) return { error: "NOT_FOUND" as const } - const locked = await lockCategories(tx, [current.categoryId, categoryId ?? current.categoryId]) + const [before] = await tx.select(documentColumns).from(DOCUMENTS).where(eq(DOCUMENTS.id, id)) + if (!before) return { error: "NOT_FOUND" as const } + const locked = await lockCategories(tx, [before.categoryId, categoryId ?? before.categoryId]) if (categoryId !== undefined && !locked.has(categoryId)) return { error: "CATEGORY_NOT_FOUND" as const } - const moving = categoryId !== undefined && categoryId !== current.categoryId + const moving = categoryId !== undefined && categoryId !== before.categoryId if (fields.slug !== undefined && (await slugTaken(tx, DOCUMENTS, fields.slug, id))) return { error: "DUPLICATE_SLUG" as const } const [row] = await tx @@ -410,59 +450,74 @@ export default createTRPCRouter({ }) .where(eq(DOCUMENTS.id, id)) .returning(documentColumns) - return row + if (!row) return { error: "NOT_FOUND" as const } + return { before, row } }).catch(duplicateSlug("web_documents")) + if (result.error) return { error: result.error } + ctx.audit.set({ target: documentTarget(result.row), before: result.before, after: result.row }) + return result.row }), deleteDocument: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(z.object({ id: idSchema })) - .mutation(async ({ input }) => { - const files = await DB.transaction(async (tx) => { + .mutation(async ({ input, ctx }) => { + const deleted = await DB.transaction(async (tx) => { await lockDocument(tx, input.id) - const [document] = await tx - .select({ categoryId: DOCUMENTS.categoryId }) - .from(DOCUMENTS) - .where(eq(DOCUMENTS.id, input.id)) + const [document] = await tx.select(documentColumns).from(DOCUMENTS).where(eq(DOCUMENTS.id, input.id)) if (!document) return null await lockCategories(tx, [document.categoryId]) // Wait for in-flight version uploads before removing their document. await tx.select({ id: DOCUMENTS.id }).from(DOCUMENTS).where(eq(DOCUMENTS.id, input.id)).for("update") - const versions = await tx - .delete(VERSIONS) - .where(eq(VERSIONS.documentId, input.id)) - .returning({ file: VERSIONS.file }) + const versions = await tx.delete(VERSIONS).where(eq(VERSIONS.documentId, input.id)).returning(versionColumns) await tx.delete(DOCUMENTS).where(eq(DOCUMENTS.id, input.id)) - return versions.map((version) => version.file) + return { document, versions } }) - if (!files) return { error: "NOT_FOUND" as const } - await deleteBlobs(files) + if (!deleted) return { error: "NOT_FOUND" as const } + ctx.audit.set({ + target: documentTarget(deleted.document), + before: { ...deleted.document, versions: deleted.versions }, + }) + await deleteBlobs(deleted.versions.map((version) => version.file)) return { error: null } }), reorderDocuments: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(z.object({ categoryId: idSchema, ids: orderSchema })) - .mutation(async ({ input }) => { - return DB.transaction(async (tx) => { + .mutation(async ({ input, ctx }) => { + const result = await DB.transaction(async (tx) => { if (!(await lockCategories(tx, [input.categoryId])).has(input.categoryId)) return { error: "INVALID_ORDER" as const } - const current = await tx - .select({ id: DOCUMENTS.id }) - .from(DOCUMENTS) - .where(eq(DOCUMENTS.categoryId, input.categoryId)) + const order = () => + tx + .select({ id: DOCUMENTS.id, title: DOCUMENTS.title, position: DOCUMENTS.position }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.categoryId, input.categoryId)) + .orderBy(asc(DOCUMENTS.position), asc(DOCUMENTS.id)) + const before = await order() if ( !sameIds( - current.map((row) => row.id), + before.map((row) => row.id), input.ids ) ) return { error: "INVALID_ORDER" as const } for (const [position, id] of input.ids.entries()) await tx.update(DOCUMENTS).set({ position }).where(eq(DOCUMENTS.id, id)) - return { error: null } + return { before, after: await order() } }) + if (result.error) return { error: result.error } + ctx.audit.set({ + target: { type: "web.documentCategory", id: input.categoryId, label: "Documents order" }, + before: result.before, + after: result.after, + }) + return { error: null } }), addVersion: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z .instanceof(FormData) @@ -474,8 +529,11 @@ export default createTRPCRouter({ const author = createdByColumns(authorOf(ctx.actor)) const bytes = await readPdf(file) - const [document] = await DB.select({ id: DOCUMENTS.id }).from(DOCUMENTS).where(eq(DOCUMENTS.id, documentId)) + const [document] = await DB.select({ id: DOCUMENTS.id, title: DOCUMENTS.title }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.id, documentId)) if (!document) return { error: "NOT_FOUND" as const } + ctx.audit.set({ target: documentTarget(document) }) const [existing] = await DB.select({ id: VERSIONS.id }) .from(VERSIONS) .where(and(eq(VERSIONS.documentId, documentId), eq(VERSIONS.version, version))) @@ -502,14 +560,19 @@ export default createTRPCRouter({ throw error }) if ("error" in result) await deleteBlobs([uploadedFile.url]) + else ctx.audit.set({ after: result }) return result }), deleteVersion: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(z.object({ id: idSchema })) - .mutation(async ({ input }) => { - const [deleted] = await DB.delete(VERSIONS).where(eq(VERSIONS.id, input.id)).returning({ file: VERSIONS.file }) + .mutation(async ({ input, ctx }) => { + const [deleted] = await DB.delete(VERSIONS) + .where(eq(VERSIONS.id, input.id)) + .returning({ ...versionColumns, documentId: VERSIONS.documentId }) if (!deleted) return { error: "NOT_FOUND" as const } + ctx.audit.set({ target: { type: "web.document", id: deleted.documentId }, before: deleted }) await deleteBlobs([deleted.file]) return { error: null } }), diff --git a/src/routers/web/faqs.ts b/src/routers/web/faqs.ts index 5370889..b35df21 100644 --- a/src/routers/web/faqs.ts +++ b/src/routers/web/faqs.ts @@ -1,5 +1,6 @@ import { asc, eq, sql } from "drizzle-orm" import z from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { authorOf, createdByColumns, modifiedByColumns } from "@/idp/author" import { dashboard, publicData } from "@/idp/policies" @@ -55,6 +56,7 @@ export default createTRPCRouter({ }), addFaqs: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ titleIt: z.string(), @@ -78,10 +80,12 @@ export default createTRPCRouter({ }) .returning() + ctx.audit.set({ target: { type: "web.faq", id: res.id, label: res.titleIt }, after: res }) return res }), addFaqsCategory: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ titleIt: z.string(), @@ -101,10 +105,12 @@ export default createTRPCRouter({ }) .returning() + ctx.audit.set({ target: { type: "web.faqCategory", id: res.id, label: res.titleIt }, after: res }) return res }), editFaqs: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), @@ -118,23 +124,32 @@ export default createTRPCRouter({ .mutation(async ({ input, ctx }) => { const { id, titleIt, titleEn, descriptionIt, descriptionEn, categoryId } = input - const [res] = await DB.update(FAQS) - .set({ - titleIt, - titleEn, - descriptionIt, - descriptionEn, - categoryId, - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(FAQS.id, id)) - .returning() + const { before, res } = await DB.transaction(async (tx) => { + const [before] = await tx.select().from(FAQS).where(eq(FAQS.id, id)).limit(1).for("update") + if (!before) return { before, res: undefined } + const [res] = await tx + .update(FAQS) + .set({ + titleIt, + titleEn, + descriptionIt, + descriptionEn, + categoryId, + ...modifiedByColumns(authorOf(ctx.actor)), + }) + .where(eq(FAQS.id, id)) + .returning() + + return { before, res } + }) + ctx.audit.set({ target: { type: "web.faq", id, label: res?.titleIt ?? before?.titleIt }, before, after: res }) if (!res) return { error: "NOT_FOUND" } return res }), editFaqsCategory: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), @@ -146,27 +161,40 @@ export default createTRPCRouter({ .mutation(async ({ input, ctx }) => { const { id, titleIt, titleEn, icon } = input - const [res] = await DB.update(FAQ_CATEGORIES) - .set({ - titleIt, - titleEn, - icon, - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(FAQ_CATEGORIES.id, id)) - .returning() + const { before, res } = await DB.transaction(async (tx) => { + const [before] = await tx.select().from(FAQ_CATEGORIES).where(eq(FAQ_CATEGORIES.id, id)).limit(1).for("update") + if (!before) return { before, res: undefined } + const [res] = await tx + .update(FAQ_CATEGORIES) + .set({ + titleIt, + titleEn, + icon, + ...modifiedByColumns(authorOf(ctx.actor)), + }) + .where(eq(FAQ_CATEGORIES.id, id)) + .returning() + + return { before, res } + }) + ctx.audit.set({ + target: { type: "web.faqCategory", id, label: res?.titleIt ?? before?.titleIt }, + before, + after: res, + }) if (!res) return { error: "NOT_FOUND" } return res }), deleteFaqs: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { id } = input return DB.transaction(async (tx) => { // Match selectFaq's lock order so a FAQ cannot become selected between this check and deletion. @@ -178,6 +206,7 @@ export default createTRPCRouter({ .limit(1) if (featured) return { error: "FEATURED_FAQ" } const deleted = await tx.delete(FAQS).where(eq(FAQS.id, id)).returning() + ctx.audit.set({ target: { type: "web.faq", id, label: deleted[0]?.titleIt }, before: deleted[0] }) if (deleted.length === 0) return { error: "NOT_FOUND" } return { error: null } @@ -185,12 +214,13 @@ export default createTRPCRouter({ }), deleteFaqsCategory: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { id } = input return DB.transaction(async (tx) => { await tx.execute(sql`LOCK TABLE ${FEATURED} IN SHARE ROW EXCLUSIVE MODE`) @@ -202,6 +232,7 @@ export default createTRPCRouter({ .limit(1) if (featured) return { error: "FEATURED_FAQ" } const deleted = await tx.delete(FAQ_CATEGORIES).where(eq(FAQ_CATEGORIES.id, id)).returning() + ctx.audit.set({ target: { type: "web.faqCategory", id, label: deleted[0]?.titleIt }, before: deleted[0] }) if (deleted.length === 0) return { error: "NOT_FOUND" } return { error: null } diff --git a/src/routers/web/freshman.ts b/src/routers/web/freshman.ts index d611e20..a9a1a8e 100644 --- a/src/routers/web/freshman.ts +++ b/src/routers/web/freshman.ts @@ -1,5 +1,6 @@ import { TRPCError } from "@trpc/server" import { asc, eq, inArray, sql } from "drizzle-orm" +import { audit } from "@/audit/option" import { DB, SCHEMA } from "@/db" import { authorOf, modifiedByColumns } from "@/idp/author" import { dashboard, publicData } from "@/idp/policies" @@ -58,18 +59,26 @@ export default createTRPCRouter({ }), updateCard: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(updateFreshmanCardInput) .mutation(async ({ input, ctx }) => { const { id, ...fields } = input - const [updated] = await DB.update(CARDS) - .set({ ...fields, ...modifiedByColumns(authorOf(ctx.actor)) }) - .where(eq(CARDS.id, id)) - .returning({ id: CARDS.id }) - if (!updated) throw new TRPCError({ code: "NOT_FOUND", message: "The website slot is not initialized." }) + const { before, after } = await DB.transaction(async (tx) => { + const [before] = await tx.select().from(CARDS).where(eq(CARDS.id, id)).for("update") + if (!before) throw new TRPCError({ code: "NOT_FOUND", message: "The website slot is not initialized." }) + const [after] = await tx + .update(CARDS) + .set({ ...fields, ...modifiedByColumns(authorOf(ctx.actor)) }) + .where(eq(CARDS.id, id)) + .returning() + return { before, after } + }) + ctx.audit.set({ target: { type: "web.freshmanCard", id }, before, after }) return { error: null } }), moveCard: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(moveFreshmanCardInput) .mutation(async ({ input, ctx }) => { const index = freshmanSlots.findIndex((slot) => slot.id === input.id) @@ -78,7 +87,7 @@ export default createTRPCRouter({ if (!next || next.group !== slot.group) throw new TRPCError({ code: "BAD_REQUEST", message: "Cards can only move within their website section." }) const author = modifiedByColumns(authorOf(ctx.actor)) - await DB.transaction(async (tx) => { + const { before, after } = await DB.transaction(async (tx) => { const rows = await tx .select() .from(CARDS) @@ -96,17 +105,20 @@ export default createTRPCRouter({ icon: row.icon, ...author, }) - await tx.update(CARDS).set(values(target)).where(eq(CARDS.id, current.id)) - await tx.update(CARDS).set(values(current)).where(eq(CARDS.id, target.id)) + const first = await tx.update(CARDS).set(values(target)).where(eq(CARDS.id, current.id)).returning() + const second = await tx.update(CARDS).set(values(current)).where(eq(CARDS.id, target.id)).returning() + return { before: rows, after: [...first, ...second] } }) + ctx.audit.set({ target: { type: "web.freshmanCard", id: input.id }, before, after }) return { error: null } }), selectFaq: policy(dashboard("web:content:write")) + .meta(audit.full()) .input(selectFreshmanFaqInput) .mutation(async ({ input, ctx }) => { const author = modifiedByColumns(authorOf(ctx.actor)) - await DB.transaction(async (tx) => { + const { before, after } = await DB.transaction(async (tx) => { // Serialize writes to the five slots before reading; public snapshot reads remain unblocked. // Catalog deletions take the same lock before checking whether a FAQ is selected. await tx.execute(sql`LOCK TABLE ${FEATURED} IN SHARE ROW EXCLUSIVE MODE`) @@ -117,24 +129,31 @@ export default createTRPCRouter({ if (!faq) throw new TRPCError({ code: "NOT_FOUND", message: "This FAQ no longer exists." }) const current = rows.find((row) => row.position === input.position) if (!current) throw new TRPCError({ code: "NOT_FOUND" }) - if (current.faqId === input.faqId) return + if (current.faqId === input.faqId) return { before: [current], after: [current] } const existing = rows.find((row) => row.faqId === input.faqId) if (existing) { // Reinsert the pair atomically so the declared immediate unique constraint also permits swaps. // Preserve each slot's creation metadata and record this edit on both positions. await tx.delete(FEATURED).where(inArray(FEATURED.position, [current.position, existing.position])) const updatedAt = new Date() - await tx.insert(FEATURED).values([ - { ...current, faqId: existing.faqId, ...author, updatedAt }, - { ...existing, faqId: current.faqId, ...author, updatedAt }, - ]) + const after = await tx + .insert(FEATURED) + .values([ + { ...current, faqId: existing.faqId, ...author, updatedAt }, + { ...existing, faqId: current.faqId, ...author, updatedAt }, + ]) + .returning() + return { before: [current, existing], after } } else { - await tx + const after = await tx .update(FEATURED) .set({ faqId: input.faqId, ...author }) .where(eq(FEATURED.position, input.position)) + .returning() + return { before: [current], after } } }) + ctx.audit.set({ target: { type: "web.freshmanFaq", id: input.position }, before, after }) return { error: null } }), }) diff --git a/src/routers/web/guides_matricole.ts b/src/routers/web/guides_matricole.ts index 49a7c8c..95820f6 100644 --- a/src/routers/web/guides_matricole.ts +++ b/src/routers/web/guides_matricole.ts @@ -1,5 +1,6 @@ import { desc, eq } from "drizzle-orm" import z from "zod" +import { audit } from "@/audit/option" import { deleteBlob, uploadBlob } from "@/azure/blob" import { DB, SCHEMA } from "@/db" import { authorOf, createdByColumns } from "@/idp/author" @@ -42,6 +43,7 @@ export default createTRPCRouter({ }), addGuide: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z .instanceof(FormData) @@ -71,18 +73,21 @@ export default createTRPCRouter({ }) .returning() + ctx.audit.set({ target: { type: "web.guide", id: res.id, label: res.version }, after: res }) return res }), deleteGuide: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { id } = input const deleted = await DB.delete(GUIDES_MATRICOLE).where(eq(GUIDES_MATRICOLE.id, id)).returning() + ctx.audit.set({ target: { type: "web.guide", id, label: deleted[0]?.version }, before: deleted[0] }) if (deleted.length === 0) return { error: "NOT_FOUND" } diff --git a/src/routers/web/projects.ts b/src/routers/web/projects.ts index 15bbeed..4d38acb 100644 --- a/src/routers/web/projects.ts +++ b/src/routers/web/projects.ts @@ -1,5 +1,6 @@ -import { asc, eq } from "drizzle-orm" +import { asc, eq, sql } from "drizzle-orm" import z from "zod" +import { audit } from "@/audit/option" import { uploadBlob } from "@/azure/blob" import { DB, SCHEMA } from "@/db" import { projectsCategories } from "@/db/schema/web/projects" @@ -43,6 +44,7 @@ export default createTRPCRouter({ }), addProject: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z .instanceof(FormData) @@ -68,10 +70,12 @@ export default createTRPCRouter({ }) .returning() + ctx.audit.set({ target: { type: "web.project", id: res.id, label: res.title }, after: res }) return res }), editProject: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z .instanceof(FormData) @@ -88,24 +92,37 @@ export default createTRPCRouter({ ? await uploadBlob(Buffer.from(await logo.arrayBuffer()), getImageExtension(logo), logo.type) : undefined - const [res] = await DB.update(PROJECTS) - .set({ - title, - descriptionIt, - descriptionEn, - ...(uploadedLogo ? { logo: uploadedLogo.url } : {}), - link, - category, - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(PROJECTS.id, input.id)) - .returning() + const { before, res } = await DB.transaction(async (tx) => { + const [before] = await tx.select().from(PROJECTS).where(eq(PROJECTS.id, input.id)).limit(1).for("update") + if (!before) return { before, res: undefined } + const [res] = await tx + .update(PROJECTS) + .set({ + title, + descriptionIt, + descriptionEn, + ...(uploadedLogo ? { logo: uploadedLogo.url } : {}), + link, + category, + ...modifiedByColumns(authorOf(ctx.actor)), + }) + .where(eq(PROJECTS.id, input.id)) + .returning() + + return { before, res } + }) + ctx.audit.set({ + target: { type: "web.project", id: input.id, label: res?.title ?? before?.title }, + before, + after: res, + }) if (!res) return { error: "NOT_FOUND" } return res }), reorderProjects: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ projectIds: z @@ -114,25 +131,42 @@ export default createTRPCRouter({ .refine((projectIds) => new Set(projectIds).size === projectIds.length), }) ) - .mutation(async ({ input }) => { - await DB.transaction(async (tx) => { - await Promise.all( - input.projectIds.map((id, index) => tx.update(PROJECTS).set({ order: index }).where(eq(PROJECTS.id, id))) + .mutation(async ({ input, ctx }) => { + // Both orders are read in the reorder's transaction, so they are the ones it changed. + const { before, after, updatedCount } = await DB.transaction(async (tx) => { + const order = () => + tx + .select({ id: PROJECTS.id, title: PROJECTS.title, order: PROJECTS.order }) + .from(PROJECTS) + .orderBy(asc(PROJECTS.order)) + // Serialize reorders before reading, so each one's `before` is the order the previous one committed. EXCLUSIVE + // also waits for edits holding row locks (which would otherwise deadlock with this update); plain reads go on. + await tx.execute(sql`LOCK TABLE ${PROJECTS} IN EXCLUSIVE MODE`) + const before = await order() + const updated = await Promise.all( + input.projectIds.map((id, index) => + tx.update(PROJECTS).set({ order: index }).where(eq(PROJECTS.id, id)).returning({ id: PROJECTS.id }) + ) ) + return { before, after: await order(), updatedCount: updated.reduce((total, rows) => total + rows.length, 0) } }) + if (updatedCount === 0) ctx.audit.skip() + else ctx.audit.set({ target: { type: "web.projects", id: "order", label: "Projects order" }, before, after }) return { error: null } }), deleteProject: policy(dashboard("web:content:write")) + .meta(audit.full()) .input( z.object({ id: z.number(), }) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { const { id } = input const deleted = await DB.delete(PROJECTS).where(eq(PROJECTS.id, id)).returning() + ctx.audit.set({ target: { type: "web.project", id, label: deleted[0]?.title }, before: deleted[0] }) if (deleted.length === 0) return { error: "NOT_FOUND" } return { error: null } diff --git a/src/routers/web/reports.ts b/src/routers/web/reports.ts index 580d673..d74b2c4 100644 --- a/src/routers/web/reports.ts +++ b/src/routers/web/reports.ts @@ -1,5 +1,6 @@ import { and, eq, inArray, sql } from "drizzle-orm" import z from "zod" +import { audit } from "@/audit/option" import { DB, SCHEMA, VIEWS } from "@/db" import { dashboard, SCOPE } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" @@ -20,8 +21,16 @@ async function assertGroupExists(groupId: number, type: "tg" | "wa") { if (!groups.length) throw new Error("Group not found") } +/** One report by its id; several by their number, with the ids in the input. */ +function reportsTarget(ids: number[]) { + return ids.length === 1 + ? { type: "web.report", id: ids[0] ?? null } + : { type: "web.report", id: null, label: `${ids.length} reports` } +} + export const reports = createTRPCRouter({ create: policy({ service: { scope: SCOPE.publicRead } }) + .meta(audit.full()) .input( z.discriminatedUnion("reportType", [ z.object({ @@ -37,12 +46,16 @@ export const reports = createTRPCRouter({ }), ]) ) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { if (input.reportType === "broken_link") { await assertGroupExists(input.groupId, input.type) } - await DB.insert(REPORTS).values(input) + const [report] = await DB.insert(REPORTS).values(input).returning() + ctx.audit.set({ + target: { type: "web.report", id: report.id, label: report.label ?? report.reportedLink }, + after: report, + }) return { ok: true as const } }), @@ -73,14 +86,58 @@ export const reports = createTRPCRouter({ }), resolve: policy(dashboard("web:reports:manage")) + .meta(audit.full()) .input(z.object({ ids: z.array(z.number().int()).min(1) })) - .mutation(async ({ input }) => { - return await DB.update(REPORTS).set({ status: "resolved" }).where(inArray(REPORTS.id, input.ids)).returning() + .mutation(async ({ input, ctx }) => { + const { before, after } = await DB.transaction(async (tx) => { + const before = await tx + .select() + .from(REPORTS) + .where(inArray(REPORTS.id, input.ids)) + .orderBy(REPORTS.id) + .for("update") + const after = await tx + .update(REPORTS) + .set({ status: "resolved" }) + .where( + inArray( + REPORTS.id, + before.map((row) => row.id) + ) + ) + .returning() + return { before, after } + }) + + ctx.audit.set({ target: reportsTarget(input.ids), before, after }) + return after }), dismiss: policy(dashboard("web:reports:manage")) + .meta(audit.full()) .input(z.object({ ids: z.array(z.number().int()).min(1) })) - .mutation(async ({ input }) => { - return await DB.update(REPORTS).set({ status: "dismissed" }).where(inArray(REPORTS.id, input.ids)).returning() + .mutation(async ({ input, ctx }) => { + const { before, after } = await DB.transaction(async (tx) => { + const before = await tx + .select() + .from(REPORTS) + .where(inArray(REPORTS.id, input.ids)) + .orderBy(REPORTS.id) + .for("update") + const after = await tx + .update(REPORTS) + .set({ status: "dismissed" }) + .where( + inArray( + REPORTS.id, + before.map((row) => row.id) + ) + ) + .returning() + return { before, after } + }) + + ctx.audit.set({ target: reportsTarget(input.ids), before, after }) + return after }), }) diff --git a/src/server.ts b/src/server.ts index 58abbee..997c66c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -53,6 +53,7 @@ app.use( actor: c.req.header(ACTOR_HEADER), }), access: idp?.snapshot ?? null, + requestId: crypto.randomUUID(), }), }) ) diff --git a/src/soci/router.ts b/src/soci/router.ts index ba7cc1b..50eaa7e 100644 --- a/src/soci/router.ts +++ b/src/soci/router.ts @@ -1,11 +1,23 @@ import { TRPCError } from "@trpc/server" import { z } from "zod" +import { type AuditTargetOf, audit } from "@/audit/option" import { dashboard } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" import * as C from "./contract" import { MAX_RECEIPT_BYTES } from "./fees" import type { SociService } from "./service" +/** The socio a call names by member number, or the one it created; a socio's own `me.*` calls name nobody else. */ +const socioTarget: AuditTargetOf = ({ input, data }) => { + const numberOf = (value: unknown) => + C.memberNumberSchema.safeParse( + value && typeof value === "object" ? (value as { number?: unknown }).number : undefined + ) + const fromInput = numberOf(input) + const number = fromInput.success ? fromInput : numberOf(data) + return { type: "soci.member", id: number.success ? number.data : null } +} + /** * The Libro Soci. Every `members.*` and `fees.*` procedure needs `admin:access` and a `soci:*` permission; the policy * carries the `soci:*` one, so the router walk shows it. `me.*` needs `people:self` and finds the socio by the signed-in @@ -13,21 +25,27 @@ import type { SociService } from "./service" * databases and Microsoft 365. */ export function createSociRouter(soci: SociService) { + // The Libro Soci keeps each record's history in `soci_activity`, and its inputs carry personal data: the audit log + // only says who changed which socio, and whether it worked. const direttivo = (permission: string) => - policy(dashboard(permission)).use(({ ctx, next }) => { - if (ctx.actor.kind !== "user" || !ctx.can("admin:access")) - throw new TRPCError({ code: "FORBIDDEN", message: "Missing admin:access" }) - return next({ ctx: { sub: ctx.actor.sub } }) - }) + policy(dashboard(permission)) + .meta(audit.minimal({ target: socioTarget })) + .use(({ ctx, next }) => { + if (ctx.actor.kind !== "user" || !ctx.can("admin:access")) + throw new TRPCError({ code: "FORBIDDEN", message: "Missing admin:access" }) + return next({ ctx: { sub: ctx.actor.sub } }) + }) const read = direttivo("soci:read") const write = direttivo("soci:write") - const me = policy(dashboard("people:self")).use(({ ctx, next }) => { - if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN", message: "Only for signed-in soci" }) - const entraObjectId = ctx.access?.current()?.bySub(ctx.actor.sub)?.entraObjectId ?? null - if (!entraObjectId) - throw new TRPCError({ code: "FORBIDDEN", message: "Sign in with your PoliNetwork Microsoft 365 account." }) - return next({ ctx: { sub: ctx.actor.sub, entraObjectId } }) - }) + const me = policy(dashboard("people:self")) + .meta(audit.minimal({ target: () => ({ type: "soci.member", id: null }) })) + .use(({ ctx, next }) => { + if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN", message: "Only for signed-in soci" }) + const entraObjectId = ctx.access?.current()?.bySub(ctx.actor.sub)?.entraObjectId ?? null + if (!entraObjectId) + throw new TRPCError({ code: "FORBIDDEN", message: "Sign in with your PoliNetwork Microsoft 365 account." }) + return next({ ctx: { sub: ctx.actor.sub, entraObjectId } }) + }) const receipt = z .instanceof(FormData) .transform( diff --git a/src/trpc.ts b/src/trpc.ts index b03fcdd..2ee5d9d 100644 --- a/src/trpc.ts +++ b/src/trpc.ts @@ -2,6 +2,8 @@ import type { AccessSnapshotClient, Actor } from "@polinetwork/auth-kit" import { initTRPC, TRPCError } from "@trpc/server" import superjson from "superjson" import { ZodError, z } from "zod/v4" +import { auditEvent, auditRecorder, isDenied, noAudit } from "./audit" +import type { AuditOption } from "./audit/option" import { env } from "./env" import type { RequestAuth } from "./idp/auth" import { logger } from "./logger" @@ -11,6 +13,8 @@ export type Context = { auth?: RequestAuth /** Permission source for token callers; null denies every permission. */ access?: Pick | null + /** Set by the HTTP adapter, one per request: the audit events of a batched request share it. */ + requestId?: string } /** @@ -22,7 +26,11 @@ export type PolicyRule = { scope: string | readonly string[]; permission?: strin /** Actor kinds a procedure accepts. A kind that is not listed is denied. */ export type Policy = { service?: PolicyRule; telegram?: PolicyRule; user?: PolicyRule } -type Meta = { policy?: Policy } +type Meta = { + policy?: Policy + /** How a mutation is recorded in the audit log; see `audit` in `src/audit`. */ + audit?: AuditOption +} const t = initTRPC .context() @@ -66,6 +74,38 @@ const timingMiddleware = t.middleware(async ({ next, path }) => { return result }) +/** + * Records every mutation in `common_audit_events` (see `src/audit`) as its `audit` meta option says: who called it, + * on what, and whether it succeeded, failed or was denied, with the input and the states for `full`. It runs before + * the policy so that denied calls are kept too, without their input. Handlers add the target and the state before and + * after through `ctx.audit`. A failed write is logged and does not fail the call, whose change has already happened. + */ +const auditMiddleware = t.middleware(async ({ ctx, meta, path, type, getRawInput, next }) => { + const option = meta?.audit + if (type === "mutation" && !option) logger.error({ procedure: path }, "[AUDIT] mutation without an audit option") + // Calls without a valid token are not recorded, so their bodies are never read for the log. + if (type !== "mutation" || option?.capture === "none" || ctx.auth?.kind !== "token") + return next({ ctx: { audit: noAudit } }) + + const { recorder, note, skipped } = auditRecorder() + const result = await next({ ctx: { audit: recorder } }) + if (skipped()) return result + + try { + // A denied call's body may never have been read, and the event keeps none of it. + const rawInput = isDenied(result) ? undefined : await getRawInput().catch(() => undefined) + const event = auditEvent({ path, option, auth: ctx.auth, requestId: ctx.requestId, rawInput, note, result }) + if (event) { + // Imported here so that loading the router does not open the database. + const { writeAuditEvent } = await import("./audit/store") + await writeAuditEvent(event) + } + } catch (error) { + logger.error({ err: error, procedure: path }, "[AUDIT] cannot record the event") + } + return result +}) + /** What handlers see: the token's enforced actor. */ type ActorContext = { actor: Actor; can: (permission: string) => boolean } @@ -106,7 +146,7 @@ const enforcePolicy = t.middleware(async ({ ctx, meta, path, next }) => { return next({ ctx: enforced }) }) -const baseProcedure = t.procedure.use(timingMiddleware) +const baseProcedure = t.procedure.use(timingMiddleware).use(auditMiddleware) /** A procedure with its RFC v3 §8 policy. Every procedure must be built from this. */ export const policy = (rules: Policy) => baseProcedure.meta({ policy: rules }).use(enforcePolicy) diff --git a/tests/audit-json.test.ts b/tests/audit-json.test.ts new file mode 100644 index 0000000..54bdff8 --- /dev/null +++ b/tests/audit-json.test.ts @@ -0,0 +1,274 @@ +import type { Actor } from "@polinetwork/auth-kit" +import { TRPCError } from "@trpc/server" +import { describe, expect, it } from "vitest" +import { z } from "zod/v4" +import { auditEvent, auditJson } from "@/audit" + +describe("auditJson", () => { + it("hides secrets and describes files instead of copying them", () => { + const form = new FormData() + form.set("name", "PoliNetwork") + form.set("logo", new File([new Uint8Array(3)], "logo.png", { type: "image/png" })) + expect( + auditJson({ + form, + password: "hunter2", + ticket: "abc", + idempotencyKey: "k", + bytes: new Uint8Array(4), + at: new Date(0), + }) + ).toEqual({ + form: { name: "PoliNetwork", logo: { file: "logo.png", type: "image/png", size: 3 } }, + password: "(hidden)", + ticket: "(hidden)", + idempotencyKey: "(hidden)", + bytes: "(4 bytes)", + at: "1970-01-01T00:00:00.000Z", + }) + }) + + it("cuts long strings and arrays", () => { + const copy = auditJson({ text: "x".repeat(2500), list: Array.from({ length: 103 }, (_, i) => i) }) + expect(copy).toMatchObject({ text: `${"x".repeat(2000)}… (2500 characters)` }) + expect((copy as { list: unknown[] }).list).toHaveLength(101) + expect((copy as { list: unknown[] }).list.at(-1)).toBe("(3 more)") + }) + + it("cuts objects with many fields, and copies too large to keep", () => { + const fields = Object.fromEntries(Array.from({ length: 103 }, (_, i) => [`k${i}`, i])) + const copy = auditJson(fields) as Record + expect(Object.keys(copy)).toHaveLength(101) + expect(copy["(more)"]).toBe("3 more fields") + + const large = Object.fromEntries(Array.from({ length: 50 }, (_, i) => [`k${i}`, "x".repeat(2000)])) + expect(auditJson(large)).toMatch(/^\(\d+ bytes, too large to keep\)$/) + }) + + it("measures the size of a copy in UTF-8 bytes, not characters", () => { + // 20 strings of 2,000 characters: about 40 KB of ASCII, about 120 KB in three-byte characters. + const of = (char: string) => Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`k${i}`, char.repeat(2000)])) + expect(auditJson(of("x"))).toEqual(of("x")) + expect(auditJson(of("€"))).toMatch(/^\(\d+ bytes, too large to keep\)$/) + }) + + it("keeps a regulation's documentKey, which is an identifier and not a secret", () => { + expect(auditJson({ documentKey: "statuto", apiKey: "2" })).toEqual({ documentKey: "statuto", apiKey: "(hidden)" }) + }) + + it("hides whole secret names and camelCase secret suffixes only", () => { + expect( + auditJson({ code: "1", apiKey: "2", clientSecret: "3", courseCode: "054321", countryCode: "IT", monkey: 1 }) + ).toEqual({ + code: "(hidden)", + apiKey: "(hidden)", + clientSecret: "(hidden)", + courseCode: "054321", + countryCode: "IT", + monkey: 1, + }) + }) +}) + +describe("auditEvent", () => { + const admin: Actor = { kind: "user", client: "admin-dashboard", sub: "usr_admin", telegramId: null } + const auth = { kind: "token", actor: admin, scopes: new Set(["backend:admin"]) } as const + const ok = (data: unknown = undefined) => ({ ok: true as const, data }) + + const full = { capture: "full" } as const + + it("records nothing for calls without a valid token", () => { + const rejected = { kind: "rejected", status: 401, reason: "Missing bearer token" } as const + for (const caller of [undefined, rejected]) + expect(auditEvent({ path: "web.faqs.deleteFaqs", auth: caller, rawInput: {}, note: {}, result: ok() })).toBeNull() + }) + + it("keeps the request id, and no input for denied calls", () => { + const event = auditEvent({ + path: "web.faqs.deleteFaqs", + auth, + requestId: "0b0c8f0e-6a49-4a43-9d53-6a1f9b2f6f0e", + rawInput: { id: 3, padding: "x".repeat(1000) }, + note: {}, + result: { ok: false, error: new TRPCError({ code: "FORBIDDEN", message: "Missing permission" }) }, + }) + expect(event).toMatchObject({ + requestId: "0b0c8f0e-6a49-4a43-9d53-6a1f9b2f6f0e", + outcome: "denied", + input: null, + }) + }) + + it("cuts target ids, labels and reasons the caller chose", () => { + const event = auditEvent({ + path: "esign.signers.resetIdentity", + auth, + rawInput: {}, + option: full, + note: { + target: { type: "esign.signer", id: "s".repeat(5000), label: "l".repeat(5000) }, + reason: "r".repeat(5000), + }, + result: ok(), + }) + for (const value of [event?.targetId, event?.targetLabel, event?.reason]) expect(value?.length).toBeLessThan(2100) + }) + + it("lists the issues of an invalid input rather than their JSON", () => { + const invalid = z.object({ id: z.number(), title: z.string() }).safeParse({ id: "x" }) + const event = auditEvent({ + path: "web.faqs.editFaqs", + auth, + rawInput: { id: "x" }, + note: {}, + result: { ok: false, error: new TRPCError({ code: "BAD_REQUEST", cause: invalid.error }) }, + }) + expect(event?.outcome).toBe("failure") + expect(event?.error).toMatch(/^id: .+; title: .+$/) + }) + + it("names several targets by their number, without an id", () => { + const event = auditEvent({ + path: "web.reports.resolve", + auth, + rawInput: { ids: [1, 2] }, + note: { target: { type: "web.report", id: null, label: "2 reports" } }, + result: ok([]), + }) + expect(event).toMatchObject({ targetType: "web.report", targetId: null, targetLabel: "2 reports" }) + }) + + it("records nothing for a mutation declared not to be", () => { + const option = { capture: "none", why: "ingestion" } as const + expect(auditEvent({ path: "tg.messages.add", option, auth, rawInput: {}, note: {}, result: ok() })).toBeNull() + }) + + it("keeps only the actor, the action, the target and the outcome when minimal", () => { + const event = auditEvent({ + path: "people.persons.setNote", + option: { + capture: "minimal", + target: ({ input }) => ({ type: "people.person", id: (input as { id: string }).id }), + }, + auth, + rawInput: { id: "P-0001", note: "private HR note" }, + note: { before: { note: "old" }, after: { note: "new" }, reason: "why" }, + result: ok(), + }) + expect(event).toMatchObject({ + action: "people.persons.setNote", + actorSub: "usr_admin", + targetType: "people.person", + targetId: "P-0001", + outcome: "success", + reason: null, + input: null, + before: null, + after: null, + }) + }) + + it("stores as little as minimal for a mutation without an option", () => { + const event = auditEvent({ + path: "web.faqs.editFaqs", + auth, + rawInput: { id: 1 }, + note: { after: {} }, + result: ok(), + }) + expect(event).toMatchObject({ input: null, after: null }) + }) + + it("keeps only the declared fields of the input", () => { + const event = auditEvent({ + path: "azure.members.setAssocNumber", + option: { capture: "full", fields: ["userId", "assocNumber"] }, + auth, + rawInput: { userId: "u1", assocNumber: 7, notifyEmail: "ada@example.org" }, + note: {}, + result: ok({ error: null }), + }) + expect(event?.input).toEqual({ userId: "u1", assocNumber: 7 }) + }) + + it("keeps only the declared fields of a nested object, and keeps it null", () => { + const option = { capture: "full", fields: ["title", "output.driveId", "output.fileName"] } as const + const options = { path: "esign.requests.create", option, auth, note: {}, result: ok() } + const event = auditEvent({ + ...options, + rawInput: { title: "T", output: { driveId: "d", fileName: "f.pdf", extra: "x".repeat(500) }, email: {} }, + }) + expect(event?.input).toEqual({ title: "T", output: { driveId: "d", fileName: "f.pdf" } }) + expect(auditEvent({ ...options, rawInput: { title: "T", output: null } })?.input).toEqual({ + title: "T", + output: null, + }) + expect(auditEvent({ ...options, rawInput: { output: "not an object" } })?.input).toEqual({}) + }) + + it("keeps only scalar values of the declared fields, dropping objects and arrays", () => { + const event = auditEvent({ + path: "test", + auth, + option: { capture: "full", fields: ["id", "from", "tags", "from.kind", "from.id", "gone"] }, + rawInput: { id: 1, from: { kind: "draft", id: "d1", extra: "x" }, tags: ["a"], gone: null }, + note: {}, + result: ok(), + }) + expect(event?.input).toEqual({ id: 1, from: { kind: "draft", id: "d1" }, gone: null }) + }) + + it("selects fields before object and total size limits, while still redacting", () => { + const padding = Object.fromEntries(Array.from({ length: 105 }, (_, i) => [`excluded${i}`, "x".repeat(2000)])) + const event = auditEvent({ + path: "test", + auth, + option: { capture: "full", fields: ["id", "token"] }, + rawInput: { ...padding, id: 7, token: "secret" }, + note: {}, + result: ok(), + }) + expect(event?.input).toEqual({ id: 7, token: "(hidden)" }) + }) + + it.each(["scalar", 42, true, null, ["secret"]])("enforces the allowlist for unsupported input %j", (rawInput) => { + const options = { path: "test", auth, rawInput, note: {}, result: ok() } + expect(auditEvent({ ...options, option: { capture: "full", fields: ["id"] } })?.input).toEqual({}) + expect(auditEvent({ ...options, option: full })?.input).toEqual(auditJson(rawInput)) + expect( + auditEvent({ + ...options, + option: { capture: "full", fields: ["id"] }, + result: { ok: false, error: new TRPCError({ code: "FORBIDDEN" }) }, + })?.input + ).toBeNull() + }) + + it("prefers the target the handler names, and gives the option's the result", () => { + const option = { + capture: "full", + target: ({ data }: { data: unknown }) => ({ + type: "web.faq", + id: (data as { id: number } | undefined)?.id ?? null, + }), + } as const + const named = auditEvent({ + path: "web.faqs.addFaqs", + option, + auth, + rawInput: {}, + note: { target: { type: "web.faq", id: 9, label: "Exams" } }, + result: ok({ id: 1 }), + }) + expect(named).toMatchObject({ targetId: "9", targetLabel: "Exams" }) + const derived = auditEvent({ + path: "web.faqs.addFaqs", + option, + auth, + rawInput: {}, + note: {}, + result: ok({ id: 1 }), + }) + expect(derived).toMatchObject({ targetType: "web.faq", targetId: "1" }) + }) +}) diff --git a/tests/cron-retention.test.ts b/tests/cron-retention.test.ts index 35826ab..b94fdd1 100644 --- a/tests/cron-retention.test.ts +++ b/tests/cron-retention.test.ts @@ -2,25 +2,28 @@ import { beforeEach, describe, expect, it, vi } from "vitest" const state = vi.hoisted(() => { const auditLog = { id: Symbol("tg_audit_log.id") } + const auditEvents = { id: Symbol("common_audit_events.id"), createdAt: Symbol("common_audit_events.created_at") } const ended = Symbol("ended-measures") const returning = vi.fn(async () => [{ id: 1 }]) const where = vi.fn(() => ({ returning })) const deleteFrom = vi.fn(() => ({ where })) const endedMeasures = vi.fn(() => ended) - return { auditLog, deleteFrom, ended, endedMeasures, returning, where } + return { auditEvents, auditLog, deleteFrom, ended, endedMeasures, returning, where } }) vi.mock("croner", () => ({ Cron: vi.fn() })) vi.mock("@/db", () => ({ DB: { delete: state.deleteFrom }, - SCHEMA: { TG: { auditLog: state.auditLog } }, + SCHEMA: { TG: { auditLog: state.auditLog }, COMMON: { auditEvents: state.auditEvents } }, })) vi.mock("@/env", () => ({ env: { NODE_ENV: "test" } })) vi.mock("@/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } })) vi.mock("@/utils/audit-log", () => ({ endedMeasures: state.endedMeasures })) -const { cleanAuditLog } = await import("@/cron") +vi.mock("drizzle-orm", () => ({ lt: (column: unknown, value: unknown) => ({ lt: [column, value] }) })) + +const { cleanAuditEvents, cleanAuditLog } = await import("@/cron") beforeEach(() => { vi.clearAllMocks() @@ -39,3 +42,12 @@ describe("cleanAuditLog", () => { expect(state.where).toHaveBeenCalledWith(state.ended) }) }) + +describe("cleanAuditEvents", () => { + it("deletes the audit events written more than 24 months ago", async () => { + await cleanAuditEvents(new Date("2026-11-08T04:23:00Z")) + + expect(state.deleteFrom).toHaveBeenCalledWith(state.auditEvents) + expect(state.where).toHaveBeenCalledWith({ lt: [state.auditEvents.createdAt, new Date("2024-11-08T04:23:00Z")] }) + }) +}) diff --git a/tests/documents-postgres.fixture.ts b/tests/documents-postgres.fixture.ts index 1157240..a00fc01 100644 --- a/tests/documents-postgres.fixture.ts +++ b/tests/documents-postgres.fixture.ts @@ -277,6 +277,64 @@ try { assert.equal(await website.getDocument({ slug: "statuto" }), null) checked.push("deleting a version or a document deletes its files") + // The router is called on its own here, so actions are its procedure names without the `web.documents.` prefix. + const events = async (action: string) => + // `#>> '{}'` reads a jsonb object or a jsonb string holding one (as drizzle's Bun driver stores them) as text. + ( + await connection`SELECT outcome, target_type, target_id, before #>> '{}' AS before, after #>> '{}' AS after + FROM common_audit_events WHERE action = ${action} ORDER BY id` + ).map( + (event: { + outcome: string + target_type: string + target_id: string + before: string | null + after: string | null + }) => ({ + ...event, + before: event.before === null ? null : JSON.parse(event.before), + after: event.after === null ? null : JSON.parse(event.after), + }) + ) + // Not found, a duplicate slug, then the rename. + const [missingCategory, duplicateSlugEvent, renamed] = await events("updateCategory") + assert.deepEqual( + [renamed.outcome, renamed.target_type, renamed.target_id, renamed.before.title, renamed.after.title], + ["success", "web.documentCategory", String(bilanci.id), "Bilanci", "Bilanci annuali"] + ) + for (const failed of [missingCategory, duplicateSlugEvent]) + assert.deepEqual([failed.outcome, failed.before, failed.after], ["failure", null, null]) + const deletedCategories = await events("deleteCategory") + assert.deepEqual( + deletedCategories.map((event: { outcome: string; before: { title: string } | null }) => [ + event.outcome, + event.before?.title ?? null, + ]), + [ + ["failure", null], + ["success", "Vuota"], + ["failure", null], + ] + ) + const deletedVersion = (await events("deleteVersion")).find( + (event: { outcome: string }) => event.outcome === "success" + ) + assert.deepEqual( + [deletedVersion?.target_type, deletedVersion?.target_id, deletedVersion?.before.version], + ["web.document", String(statutoDoc.id), v3.version] + ) + const deletedDocument = (await events("deleteDocument")).find( + (event: { outcome: string }) => event.outcome === "success" + ) + assert.deepEqual( + [deletedDocument?.target_id, deletedDocument?.before.title, deletedDocument?.before.versions.length], + [String(statutoDoc.id), "Statuto", 2] + ) + const [{ count }] = await connection`SELECT count(*)::int AS count FROM common_audit_events + WHERE outcome <> 'success' AND after IS NOT NULL` + assert.equal(count, 0) + checked.push("audit events name the target and keep the states before and after, only for changes that happened") + for (const slug of ["Invalid", "a b", "", "a".repeat(101)]) await assert.rejects(website.getDocument({ slug }), { code: "BAD_REQUEST" }) checked.push("document lookups validate the public slug") diff --git a/tests/documents-postgres.test.ts b/tests/documents-postgres.test.ts index 1af5937..64b48e8 100644 --- a/tests/documents-postgres.test.ts +++ b/tests/documents-postgres.test.ts @@ -10,7 +10,7 @@ it.skipIf(!process.env.SEED_TEST_DB_PORT)( timeout: 60000, }) const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") - expect(result.checked).toHaveLength(14) + expect(result.checked).toHaveLength(15) }, 65000 ) diff --git a/tests/freshman.test.ts b/tests/freshman.test.ts index 0be1a83..81083a9 100644 --- a/tests/freshman.test.ts +++ b/tests/freshman.test.ts @@ -18,6 +18,9 @@ vi.hoisted(() => { }) }) +const events = vi.hoisted(() => ({ write: vi.fn() })) +vi.mock("@/audit/store", () => ({ writeAuditEvent: events.write })) + const db = vi.hoisted(() => ({ transaction: vi.fn(), set: vi.fn(), update: vi.fn() })) vi.mock("@/db", async () => ({ DB: { transaction: db.transaction, update: db.update }, @@ -48,6 +51,12 @@ beforeEach(() => { const chain = { where: () => ({ returning: async () => [{ id: "featured-1" }] }) } db.set.mockReturnValue(chain) db.update.mockReturnValue({ set: db.set }) + db.transaction.mockImplementation(async (run) => + run({ + select: () => ({ from: () => ({ where: () => ({ for: async () => [{ id: "featured-1", title: "Before" }] }) }) }), + update: db.update, + }) + ) }) describe("Freshman validation", () => { @@ -126,6 +135,70 @@ describe("Freshman authorization", () => { it("takes authorship from the token and clears a legacy modifier", async () => { await freshman.createCaller(context(editor, ["web:content:write"])).updateCard({ id: "featured-1", ...fields }) expect(db.set).toHaveBeenCalledWith({ ...fields, legacyModifiedByTgId: null, modifiedBySub: "editor" }) + expect(events.write).toHaveBeenCalledWith( + expect.objectContaining({ + targetType: "web.freshmanCard", + targetId: "featured-1", + before: { id: "featured-1", title: "Before" }, + after: { id: "featured-1" }, + }) + ) + }) + + it("records both rows of a card swap from the transaction results", async () => { + const before = [ + { id: "featured-1", ...fields }, + { id: "featured-2", ...fields, title: "Second" }, + ] + const after = [ + { ...before[0], title: "Second" }, + { ...before[1], title: "Title" }, + ] + const returning = vi.fn().mockResolvedValueOnce([after[0]]).mockResolvedValueOnce([after[1]]) + db.transaction.mockImplementation(async (run) => + run({ + select: () => ({ from: () => ({ where: () => ({ orderBy: () => ({ for: async () => before }) }) }) }), + update: () => ({ set: () => ({ where: () => ({ returning }) }) }), + }) + ) + await freshman.createCaller(context(editor, ["web:content:write"])).moveCard({ id: "featured-1", direction: 1 }) + expect(returning).toHaveBeenCalledTimes(2) + expect(events.write).toHaveBeenCalledWith( + expect.objectContaining({ + targetId: "featured-1", + before, + after, + }) + ) + }) + + it("records both FAQ slots when selecting an already featured FAQ", async () => { + const rows = Array.from({ length: 5 }, (_, position) => ({ position, faqId: position + 1 })) + const after = [ + { position: 0, faqId: 2 }, + { position: 1, faqId: 1 }, + ] + let reads = 0 + db.transaction.mockImplementation(async (run) => + run({ + execute: async () => {}, + select: () => ({ + from: () => + ++reads === 1 ? { orderBy: async () => rows } : { where: () => ({ for: async () => [{ id: 2 }] }) }, + }), + delete: () => ({ where: async () => {} }), + insert: () => ({ values: () => ({ returning: async () => after }) }), + }) + ) + await freshman.createCaller(context(editor, ["web:content:write"])).selectFaq({ position: 0, faqId: 2 }) + expect(events.write).toHaveBeenCalledWith( + expect.objectContaining({ + targetType: "web.freshmanFaq", + targetId: "0", + before: rows.slice(0, 2), + after, + }) + ) }) it("rejects a client-supplied author", async () => { diff --git a/tests/group-label-platform-isolation.test.ts b/tests/group-label-platform-isolation.test.ts index a463885..730b7c0 100644 --- a/tests/group-label-platform-isolation.test.ts +++ b/tests/group-label-platform-isolation.test.ts @@ -64,9 +64,11 @@ vi.mock("@/db", () => ({ vi.mock("@/trpc", () => { const publicProcedure = { + meta: () => publicProcedure, input: (schema: { parse: (input: unknown) => unknown }) => ({ - mutation: (handler: (args: { input: unknown }) => unknown) => ({ - execute: (input: unknown) => handler({ input: schema.parse(input) }), + mutation: (handler: (args: { input: unknown; ctx: unknown }) => unknown) => ({ + execute: (input: unknown) => + handler({ input: schema.parse(input), ctx: { audit: { set: () => {}, skip: () => {} } } }), }), }), query: (handler: () => unknown) => ({ handler }), diff --git a/tests/guides-latest.test.ts b/tests/guides-latest.test.ts index 13a4932..634e4f6 100644 --- a/tests/guides-latest.test.ts +++ b/tests/guides-latest.test.ts @@ -16,6 +16,7 @@ vi.mock("@/azure/blob", () => ({ deleteBlob: vi.fn(), uploadBlob: vi.fn() })) vi.mock("@/db", () => ({ DB: { select: state.select }, SCHEMA: { WEB: { guidesMatricole: state.guides } } })) vi.mock("@/trpc", () => { const procedure = { + meta: () => procedure, input: () => ({ mutation: (handler: unknown) => ({ handler }) }), output: () => ({ query: (handler: () => unknown) => ({ handler }) }), } diff --git a/tests/idp-router.test.ts b/tests/idp-router.test.ts index 2049263..fbbf0a1 100644 --- a/tests/idp-router.test.ts +++ b/tests/idp-router.test.ts @@ -75,6 +75,8 @@ vi.mock("@/db", async () => { } }) vi.mock("@/server", () => ({ WSS: {} })) +const audited = vi.hoisted(() => [] as Array>) +vi.mock("@/audit/store", () => ({ writeAuditEvent: async (event: Record) => audited.push(event) })) let appRouter: typeof import("@/routers").appRouter @@ -82,7 +84,9 @@ beforeAll(async () => { ;({ appRouter } = await import("@/routers")) }) -type ProcedureDef = { _def: { meta?: { policy?: unknown } } } +type ProcedureDef = { + _def: { type: string; meta?: { policy?: unknown; audit?: { capture: string; why?: string } } } +} function procedures(): Array<[string, ProcedureDef]> { return Object.entries( @@ -91,6 +95,36 @@ function procedures(): Array<[string, ProcedureDef]> { } describe("app router", () => { + it("records People changes without their details, naming a person only by a valid People id", () => { + const people = procedures().filter( + ([path, procedure]) => path.startsWith("people.") && procedure._def.type === "mutation" + ) + expect(people.length).toBeGreaterThan(10) + for (const [, procedure] of people) expect(procedure._def.meta?.audit?.capture).toBe("minimal") + const target = ( + procedures().find(([path]) => path === "people.persons.setNote")?.[1]._def.meta?.audit as unknown as { + target: (call: { input: unknown; data: unknown }) => unknown + } + ).target + expect(target({ input: { id: "P-0001", note: "" }, data: undefined })).toEqual({ + type: "people.person", + id: "P-0001", + }) + expect(target({ input: { personId: "P-0002" }, data: undefined })).toEqual({ type: "people.person", id: "P-0002" }) + expect(target({ input: { name: "Ada" }, data: { id: "P-0003" } })).toEqual({ type: "people.person", id: "P-0003" }) + expect(target({ input: { id: "ada@example.org" }, data: undefined })).toEqual({ type: "people.person", id: null }) + }) + + it("gives every mutation an audit option, and says why one is not recorded", () => { + const mutations = procedures().filter(([, procedure]) => procedure._def.type === "mutation") + expect(mutations.length).toBeGreaterThan(60) + expect(mutations.filter(([, procedure]) => !procedure._def.meta?.audit).map(([path]) => path)).toEqual([]) + const unexplained = mutations.filter( + ([, procedure]) => procedure._def.meta?.audit?.capture === "none" && !procedure._def.meta.audit.why?.trim() + ) + expect(unexplained.map(([path]) => path)).toEqual([]) + }) + it("gives every procedure a policy", () => { const missing = procedures() .filter(([, procedure]) => !procedure._def.meta?.policy) @@ -358,6 +392,7 @@ describe("tg.auditLog.record", () => { db.deleted = [] db.conflict = false db.rows = {} + audited.length = 0 }) it("stores the actor's subject and the executing client", async () => { @@ -385,6 +420,14 @@ describe("tg.auditLog.record", () => { db.conflict = true db.rows = { tg_audit_log: [{ id: 41 }] } expect(await record(access(true, ["usr_10"]), {})).toEqual({ id: 41, duplicate: true }) + expect(audited).toEqual([]) + }) + + it("keeps moderation out of the backend audit log, which has no moderation retention", async () => { + await record(access(true, ["usr_10"]), { reason: "spam" }) + await record(access(true, []), { basis: "automatic", actorTelegramId: null, idempotencyKey: "key-2" }) + expect(db.inserted).toHaveLength(2) + expect(audited).toEqual([]) }) it("deletes the records of the measures a revocation lifts", async () => { @@ -406,3 +449,131 @@ describe("tg.auditLog.record", () => { await expect(record(access(true, []), { actorTelegramId: null })).rejects.toMatchObject({ code: "BAD_REQUEST" }) }) }) + +describe("audit log", () => { + const admin: Actor = { kind: "user", client: "admin-dashboard", sub: "usr_admin", telegramId: "5" } + const caller = (permissions: string[], token = true) => + appRouter.createCaller({ + auth: token ? { kind: "token", actor: admin, scopes: new Set(["backend:admin"]) } : undefined, + access: { + has: (_actor, permission) => permissions.includes(permission), + current: () => null, + subjectBySub: () => undefined, + subjectByTelegramId: () => undefined, + status: () => ({ lastSyncAt: 1, fresh: true, generation: 1, subjects: 1 }), + }, + }) + + beforeEach(() => { + db.inserted = [] + db.rows = {} + audited.length = 0 + }) + + it("offers every area of the router as a filter", async () => { + const { AUDIT_AREAS } = await import("@/routers/audit") + const areas = new Set(procedures().map(([path]) => path.split(".")[0])) + areas.delete("audit") + expect([...AUDIT_AREAS].sort()).toEqual([...areas].sort()) + }) + + it("is readable only with audit:read", () => { + const meta = procedures().find(([name]) => name === "audit.list")?.[1]._def.meta + expect(meta?.policy).toEqual({ user: { scope: "backend:admin", permission: "audit:read" } }) + }) + + it("refuses anonymous readers", async () => { + await expect(appRouter.createCaller({}).audit.list({})).rejects.toMatchObject({ code: "UNAUTHORIZED" }) + }) + + it("records a denied mutation with the caller, without its input", async () => { + await expect(caller([]).web.faqs.deleteFaqs({ id: 3 })).rejects.toMatchObject({ code: "FORBIDDEN" }) + expect(audited).toEqual([ + expect.objectContaining({ + action: "web.faqs.deleteFaqs", + actorKind: "user", + actorSub: "usr_admin", + actorTgId: 5, + actorClient: "admin-dashboard", + outcome: "denied", + error: "Missing permission", + input: null, + targetType: null, + }), + ]) + }) + + it("records a returned error as a failure, with what the handler adds", async () => { + db.rows = { tg_grants: [{ telegramUserId: 456, validUntil: new Date(Date.now() + 3_600_000) }] } + const since = new Date() + const until = new Date(Date.now() + 7_200_000) + expect( + await caller(["tg:grants:manage"]).tg.grants.create({ userId: 456, since, until, reason: "exam week" }) + ).toEqual({ success: false, error: "ALREADY_EXISTING" }) + expect(audited).toEqual([ + expect.objectContaining({ + action: "tg.grants.create", + outcome: "failure", + error: "ALREADY_EXISTING", + targetType: "tg.user", + targetId: "456", + reason: "exam week", + // Nothing was saved, so there is no state after. + after: null, + }), + ]) + }) + + it("does not read the body of a call it will not record", async () => { + const { fetchRequestHandler } = await import("@trpc/server/adapters/fetch") + const send = async (auth: Context["auth"]) => { + let read = false + // No buffering, so `pull` runs only when someone reads the body. + const body = new ReadableStream( + { + pull(controller) { + read = true + controller.enqueue(new TextEncoder().encode(JSON.stringify({ json: { id: 3 } }))) + controller.close() + }, + }, + { highWaterMark: 0 } + ) + const res = await fetchRequestHandler({ + endpoint: "/trpc", + router: appRouter, + req: new Request("http://backend/trpc/web.faqs.deleteFaqs", { + method: "POST", + headers: { "content-type": "application/json" }, + body, + duplex: "half", + } as RequestInit), + createContext: () => ({ + auth, + access: { + has: () => false, + current: () => null, + subjectBySub: () => undefined, + subjectByTelegramId: () => undefined, + status: () => ({ lastSyncAt: 1, fresh: true, generation: 1, subjects: 1 }), + }, + }), + }) + return { status: res.status, read } + } + expect(await send(undefined)).toEqual({ status: 401, read: false }) + expect(await send({ kind: "token", actor: admin, scopes: new Set(["backend:admin"]) })).toEqual({ + status: 403, + read: false, + }) + expect(audited).toEqual([expect.objectContaining({ outcome: "denied", input: null })]) + }) + + it("does not record calls refused before the caller is known, nor queries", async () => { + await expect(caller([], false).web.faqs.deleteFaqs({ id: 3 })).rejects.toMatchObject({ + code: "UNAUTHORIZED", + }) + await caller(["admin:access"]).me.access() + expect(audited).toEqual([]) + }) +}) diff --git a/tests/people-router.test.ts b/tests/people-router.test.ts index 7439a9c..6af3415 100644 --- a/tests/people-router.test.ts +++ b/tests/people-router.test.ts @@ -1,8 +1,11 @@ import type { Actor } from "@polinetwork/auth-kit" -import { beforeAll, describe, expect, it } from "vitest" +import { beforeAll, describe, expect, it, vi } from "vitest" import type { Context } from "@/trpc" import { harness, master, permissions, profile } from "./people-fixtures" +const events = vi.hoisted(() => ({ write: vi.fn() })) +vi.mock("@/audit/store", () => ({ writeAuditEvent: events.write })) + Object.assign(process.env, { NODE_ENV: "test", BETTER_AUTH_SECRET: "test-secret-with-at-least-thirty-two-characters", @@ -49,6 +52,20 @@ describe("People tRPC contract", () => { r.createCaller(context(permissions, undefined, ["backend:public:read"])).me.get() ).rejects.toMatchObject({ code: "FORBIDDEN" }) }) + it("uses the validated mutation target when extra ids are stripped", async () => { + const h = harness() + await h.seed() + const person = await h.service.createPerson(master, profile()) + events.write.mockClear() + await makeRouter(h.service) + .createCaller(context()) + .persons.setNote({ + id: person.id, + personId: "P-9999", + note: "Updated", + } as never) + expect(events.write).toHaveBeenCalledWith(expect.objectContaining({ targetId: person.id })) + }) it("validates profiles before reaching People", async () => { const h = harness() await h.seed() @@ -67,7 +84,15 @@ describe("People tRPC contract", () => { const caller = makeRouter(h.service).createCaller(context([], actor)) await expect(caller.me.get()).rejects.toMatchObject({ code: "FORBIDDEN" }) expect(await caller.me.invite({ token })).toMatchObject({ name: "Luca Verdi" }) + events.write.mockClear() await caller.me.acceptInvite({ token }) + expect(events.write).toHaveBeenCalledWith( + expect.objectContaining({ + targetType: "people.person", + targetId: "P-0003", + input: null, + }) + ) expect(h.state().persons["P-0003"].accountSub).toBe("newcomer") }) it("mounts every People procedure with a dashboard policy", () => { diff --git a/tests/projects-reorder.test.ts b/tests/projects-reorder.test.ts new file mode 100644 index 0000000..273a5d4 --- /dev/null +++ b/tests/projects-reorder.test.ts @@ -0,0 +1,106 @@ +import { beforeEach, expect, it, vi } from "vitest" +import { auditRecorder } from "@/audit" + +const state = vi.hoisted(() => ({ + projects: { id: Symbol("id"), title: Symbol("title"), order: Symbol("order") }, + rows: [] as { id: number; title: string; order: number }[], + calls: [] as string[], +})) +vi.mock("drizzle-orm", async (importOriginal) => ({ + ...(await importOriginal()), + asc: (column: unknown) => column, + eq: (_column: unknown, id: number) => id, +})) +vi.mock("@/azure/blob", () => ({ uploadBlob: vi.fn() })) +vi.mock("@/utils/web", () => ({ getImageExtension: vi.fn() })) +vi.mock("@/db", () => { + const tx = { + execute: async () => { + state.calls.push("lock") + }, + select: (fields: Record) => ({ + from: () => ({ + orderBy: async () => + state.calls.push("select") && + [...state.rows] + .sort((a, b) => a.order - b.order) + .map((row) => Object.fromEntries(Object.keys(fields).map((key) => [key, row[key as keyof typeof row]]))), + }), + }), + update: () => ({ + set: ({ order }: { order: number }) => ({ + where: (id: number) => ({ + returning: async () => { + const row = state.rows.find((row) => row.id === id) + if (!row) return [] + row.order = order + return [{ id }] + }, + }), + }), + }), + } + return { + DB: { transaction: (run: (tx: unknown) => unknown) => run(tx) }, + SCHEMA: { WEB: { projects: state.projects } }, + } +}) +vi.mock("@/trpc", () => { + const procedure = { + meta: () => procedure, + input: () => procedure, + output: () => procedure, + mutation: (handler: unknown) => ({ handler }), + query: (handler: unknown) => ({ handler }), + } + return { createTRPCRouter: (router: T) => router, policy: () => procedure } +}) +const { default: router } = await import("@/routers/web/projects") +const reorder = router.reorderProjects as unknown as { + handler: (args: { + input: { projectIds: number[] } + ctx: { audit: ReturnType["recorder"] } + }) => Promise +} +beforeEach(() => { + state.calls = [] + state.rows = [ + { id: 1, title: "One", order: 5 }, + { id: 2, title: "Two", order: 5 }, + ] +}) +it("records order values even when tied projects retain their snapshot positions", async () => { + const audit = auditRecorder() + await expect(reorder.handler({ input: { projectIds: [1, 99] }, ctx: { audit: audit.recorder } })).resolves.toEqual({ + error: null, + }) + expect(audit.skipped()).toBe(false) + expect(audit.note).toMatchObject({ + target: { type: "web.projects", id: "order" }, + before: [ + { id: 1, title: "One", order: 5 }, + { id: 2, title: "Two", order: 5 }, + ], + after: [ + { id: 1, title: "One", order: 0 }, + { id: 2, title: "Two", order: 5 }, + ], + }) +}) +it("skips the audit when all requested projects are missing", async () => { + const audit = auditRecorder() + await reorder.handler({ input: { projectIds: [98, 99] }, ctx: { audit: audit.recorder } }) + expect(audit.skipped()).toBe(true) +}) +it("retains the audit when a matching row already has the requested order", async () => { + state.rows[0].order = 0 + const audit = auditRecorder() + await reorder.handler({ input: { projectIds: [1] }, ctx: { audit: audit.recorder } }) + expect(audit.skipped()).toBe(false) + expect(audit.note.before).toEqual(audit.note.after) +}) +it("locks the projects before reading the order it replaces", async () => { + const audit = auditRecorder() + await reorder.handler({ input: { projectIds: [2, 1] }, ctx: { audit: audit.recorder } }) + expect(state.calls).toEqual(["lock", "select", "select"]) +}) diff --git a/tests/soci-router.test.ts b/tests/soci-router.test.ts index 1607355..708b77b 100644 --- a/tests/soci-router.test.ts +++ b/tests/soci-router.test.ts @@ -1,6 +1,7 @@ import type { Actor } from "@polinetwork/auth-kit" import { PDFDocument } from "pdf-lib" import { beforeAll, describe, expect, it } from "vitest" +import type { AuditTargetOf } from "@/audit/option" import type { Context } from "@/trpc" import { admitInput, harness, registerInput } from "./soci-fixtures" @@ -36,9 +37,12 @@ function context(granted = DIRETTIVO, actor: Actor = user, scopes = ["backend:ad describe("Soci tRPC contract", () => { it("gives every procedure a dashboard policy with its soci permission", () => { const r = makeRouter(harness().service) - const procedures = (r as unknown as { _def: { procedures: Record } })._def - .procedures - expect(Object.fromEntries(Object.entries(procedures).map(([path, p]) => [path, p._def.meta]))).toEqual({ + const procedures = ( + r as unknown as { _def: { procedures: Record } } + )._def.procedures + expect( + Object.fromEntries(Object.entries(procedures).map(([path, p]) => [path, { policy: p._def.meta.policy }])) + ).toEqual({ "members.list": { policy: { user: { scope: "backend:admin", permission: "soci:read" } } }, "members.get": { policy: { user: { scope: "backend:admin", permission: "soci:read" } } }, "members.unregistered": { policy: { user: { scope: "backend:admin", permission: "soci:read" } } }, @@ -57,6 +61,22 @@ describe("Soci tRPC contract", () => { }) }) + it("records soci changes without their details, naming a socio only by a valid member number", () => { + const r = makeRouter(harness().service) + type Def = { _def: { type: string; meta: { audit: { capture: string; target: AuditTargetOf } } } } + const procedures = (r as unknown as { _def: { procedures: Record } })._def.procedures + const mutations = Object.values(procedures).filter((p) => p._def.type === "mutation") + expect(mutations).toHaveLength(9) + for (const p of mutations) expect(p._def.meta.audit.capture).toBe("minimal") + const target = procedures["members.update"]._def.meta.audit.target + expect(target({ input: { number: 12, details: {} }, data: undefined })).toEqual({ type: "soci.member", id: 12 }) + expect(target({ input: { account: {} }, data: { number: 13 } })).toEqual({ type: "soci.member", id: 13 }) + expect(target({ input: { number: "RSSMRA80A01F205X" }, data: undefined })).toEqual({ + type: "soci.member", + id: null, + }) + }) + it("needs admin:access as well as the soci permission", async () => { const r = makeRouter(harness().service) await expect(r.createCaller({}).members.list()).rejects.toMatchObject({ code: "UNAUTHORIZED" }) diff --git a/tests/tg-users-creation-history.test.ts b/tests/tg-users-creation-history.test.ts index a09db02..1b5628d 100644 --- a/tests/tg-users-creation-history.test.ts +++ b/tests/tg-users-creation-history.test.ts @@ -32,6 +32,7 @@ vi.mock("@/idp/policies", () => ({ })) vi.mock("@/trpc", () => { const procedure = { + meta: () => procedure, input: () => procedure, output: () => procedure, query: (handler: unknown) => ({ handler }),