diff --git a/README.md b/README.md index 93c2284..5b5ba03 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,17 @@ is one record in `people_persons`; their roles are rows in `people_assignments`, - **A record that isn't linked yet**: its assignments stay `pending` in the backend, and are sent when the record is linked, acting as whoever links it by hand or, for an invite, as whoever made each assignment. +A record is linked to a login account in exactly two ways, never by matching emails, names or Telegram: + +- **Email invite** (`people:write`, or the Lead of one of the person's teams): a single-use link to the contact + email, stored hashed, valid for 14 days; a new invite revokes the previous one. Any signed-in account can open it + (`me.invite`) and accept it (`me.acceptInvite`), with no People permission and whatever its email. +- **By hand** (`admin:access` + `people:link`): search the IdP directory and link an account; nobody links their own. + +Unlinking (`people:link`) takes the record's roles back in Auth with a role command, then detaches the account; its +assignments go back to `pending`. `linking.recent` lists the links of the last 30 days, with method, date and who +made them, so a mistake or a forwarded invite is easy to spot and undo. + The backend checks every role change with the same rules as Auth (`src/people/rules.ts`, shaped like Auth's `src/auth/people-binding.ts`): no self-grants, the right permission per kind, and bounded delegation against the role's permissions. A concept with no role bound in Auth, or with more than one, can't be assigned. Writes are diff --git a/drizzle/0032_people_linking.sql b/drizzle/0032_people_linking.sql new file mode 100644 index 0000000..06363e0 --- /dev/null +++ b/drizzle/0032_people_linking.sql @@ -0,0 +1,6 @@ +ALTER TABLE "people_persons" ADD COLUMN "linked_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "people_persons" ADD COLUMN "linked_by" text;--> statement-breakpoint +ALTER TABLE "people_persons" ADD COLUMN "link_method" text;--> statement-breakpoint +ALTER TABLE "people_role_commands" ADD COLUMN "purpose" text DEFAULT 'roles' NOT NULL;--> statement-breakpoint +ALTER TABLE "people_role_commands" ADD CONSTRAINT "people_role_commands_purpose_check" CHECK ("people_role_commands"."purpose" in ('roles', 'unlink'));--> statement-breakpoint +UPDATE "people_persons" SET "link_method" = 'auth', "linked_by" = 'auth', "linked_at" = "created_at" WHERE "account_sub" IS NOT NULL AND "created_by" = 'auth' AND "link_method" IS NULL; diff --git a/drizzle/meta/0032_snapshot.json b/drizzle/meta/0032_snapshot.json new file mode 100644 index 0000000..86525a2 --- /dev/null +++ b/drizzle/meta/0032_snapshot.json @@ -0,0 +1,3362 @@ +{ + "id": "e5e83f23-209c-4eb1-a909-bf427b65e42d", + "prevId": "53974741-10a4-41d5-b223-9defe715dc6a", + "version": "7", + "dialect": "postgresql", + "tables": { + "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.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.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_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_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_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_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_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_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_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_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_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_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 + } + }, + "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 18c63f5..1fba67f 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -225,6 +225,13 @@ "when": 1793371503277, "tag": "0031_people_records", "breakpoints": true + }, + { + "idx": 32, + "version": "7", + "when": 1793377749431, + "tag": "0032_people_linking", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/db/schema/people/index.ts b/src/db/schema/people/index.ts index 13e9f1c..aaf5381 100644 --- a/src/db/schema/people/index.ts +++ b/src/db/schema/people/index.ts @@ -30,6 +30,9 @@ export const persons = createTable.people("persons", { telegramUsername: text("telegram_username"), notes: text(), accountSub: text("account_sub").unique(), + linkedAt: at("linked_at"), + linkedBy: text("linked_by"), + linkMethod: text("link_method").$type<"invite" | "manual" | "auth">(), createdBy: text("created_by").notNull(), createdAt: at("created_at").notNull(), updatedBy: text("updated_by").notNull(), @@ -45,6 +48,7 @@ export const roleCommands = createTable.people( .notNull() .references(() => persons.id), request: jsonb().$type().notNull(), + purpose: text().$type<"roles" | "unlink">().notNull().default("roles"), status: text().$type<"queued" | "applied" | "refused">().notNull(), attempts: integer().notNull().default(0), error: text(), @@ -54,6 +58,7 @@ export const roleCommands = createTable.people( (t) => [ index("people_role_commands_queued_idx").on(t.createdAt).where(sql`${t.status} = 'queued'`), check("people_role_commands_status_check", sql`${t.status} in ('queued', 'applied', 'refused')`), + check("people_role_commands_purpose_check", sql`${t.purpose} in ('roles', 'unlink')`), ] ) diff --git a/src/people/contract.ts b/src/people/contract.ts index 4f1d948..7d11792 100644 --- a/src/people/contract.ts +++ b/src/people/contract.ts @@ -71,7 +71,15 @@ export const accountSchema = z.discriminatedUnion("status", [ expiresOn: z.string(), sentBy: z.string(), }), - z.object({ status: z.literal("linked"), sub: z.string() }), + z.object({ + status: z.literal("linked"), + sub: z.string(), + /** `auth` for a record People created for a role given by hand in PoliNetwork Auth. */ + method: z.enum(["invite", "manual", "auth"]), + linkedOn: z.string().nullable(), + /** Who linked it: the invitee for an invite, `auth` for a record created from Auth. */ + linkedBy: z.string().nullable(), + }), ]) export type Account = z.infer @@ -146,6 +154,22 @@ export const inviteSchema = z.object({ }) export type Invite = z.infer +/** A link made in the last 30 days, so a mistake (or a forwarded invite) is easy to spot and undo. */ +export const recentLinkSchema = z.object({ + person: personRefSchema, + sub: z.string(), + /** The account's directory email, when the IdP lists it. */ + email: z.string().nullable(), + method: z.enum(["invite", "manual", "auth"]), + linkedOn: z.string(), + linkedBy: z.string().nullable(), +}) +export type RecentLink = z.infer + +/** What the invite landing page shows before the signed-in account confirms. */ +export const invitePreviewSchema = z.object({ personId: z.string(), name: z.string(), expiresOn: z.string() }) +export type InvitePreview = z.infer + export const accountMatchSchema = z.object({ id: z.string(), name: z.string(), @@ -257,6 +281,8 @@ export const personIdSchema = z.string().regex(/^P-\d{4}$/) const dateSchema = z.iso.date() const opaqueIdSchema = z.string().min(1).max(128) const reasonSchema = z.string().trim().min(1).max(500) +/** Starts the reason an unlink sends Auth, which takes at most 500 characters; the record's history keeps the rest. */ +export const UNLINK_REASON = "Unlinked from People: " const capoScopeSchema = z.string().trim().min(1).max(120) /** Telegram's own rule: 5–32 letters, digits or underscores. Empty when unknown; a leading @ is dropped. */ export const TELEGRAM_USERNAME_PATTERN = /^@?[A-Za-z0-9_]{5,32}$/ @@ -312,6 +338,12 @@ export const endTeamInputSchema = z.object({ }) export const personRefInputSchema = z.object({ personId: personIdSchema }) +export const inviteTokenSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) +export const inviteTokenInputSchema = z.object({ token: inviteTokenSchema }) +export const unlinkAccountInputSchema = z.object({ + personId: personIdSchema, + reason: reasonSchema.max(500 - UNLINK_REASON.length), +}) export const searchAccountsInputSchema = z.object({ query: z.string().trim().max(120) }) export const linkAccountInputSchema = z.object({ personId: personIdSchema, @@ -334,6 +366,7 @@ export type TeamCandidatesInput = z.infer export type EndTeamInput = z.infer export type SearchAccountsInput = z.infer export type LinkAccountInput = z.infer +export type UnlinkAccountInput = z.infer export const createdSchema = z.object({ id: z.string() }) diff --git a/src/people/model.ts b/src/people/model.ts index b1008ac..bd58f63 100644 --- a/src/people/model.ts +++ b/src/people/model.ts @@ -100,6 +100,9 @@ export function newPerson(s: PeopleState, input: C.PersonInput, actor: string, n telegramUsername: blank(input.telegramUsername), notes: null, accountSub: null, + linkedAt: null, + linkedBy: null, + linkMethod: null, createdBy: actor, createdAt: at, updatedBy: actor, @@ -165,7 +168,14 @@ export function openInvite(s: PeopleState, personId: string): Invite | null { } function account(s: PeopleState, p: Person): C.Account { - if (p.accountSub) return { status: "linked", sub: p.accountSub } + if (p.accountSub) + return { + status: "linked", + sub: p.accountSub, + method: p.linkMethod ?? "manual", + linkedOn: p.linkedAt?.slice(0, 10) ?? null, + linkedBy: p.linkedBy, + } const invite = openInvite(s, p.id) return invite ? { diff --git a/src/people/router.ts b/src/people/router.ts index 1999b81..8f09c70 100644 --- a/src/people/router.ts +++ b/src/people/router.ts @@ -40,6 +40,8 @@ export function createPeopleRouter(people: PeopleService) { const read = admin("people:read") const write = admin("people:write") const appoint = admin("people:appoint") + /** Linking hands an account the record's roles, so it has its own permission. */ + const link = admin("people:link") return createTRPCRouter({ persons: createTRPCRouter({ list: read.output(C.personRowSchema.array()).query(({ ctx }) => people.listPeople(ctx.viewer)), @@ -92,18 +94,20 @@ export function createPeopleRouter(people: PeopleService) { }), linking: createTRPCRouter({ invites: read.output(C.inviteSchema.array()).query(({ ctx }) => people.listInvites(ctx.viewer)), - sendInvite: write - .input(C.personRefInputSchema) - .mutation(({ ctx, input }) => people.sendInvite(ctx.viewer, input)), - revokeInvite: write + 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)), - searchAccounts: write + searchAccounts: link .input(C.searchAccountsInputSchema) .output(C.accountMatchSchema.array()) .query(({ ctx, input }) => people.searchAccounts(ctx.viewer, input)), - link: write.input(C.linkAccountInputSchema).mutation(({ ctx, input }) => people.linkAccount(ctx.viewer, input)), - unlink: write.input(C.personRefInputSchema).mutation(({ ctx, input }) => people.unlinkAccount(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)), }), capo: createTRPCRouter({ get: self.output(C.capoAreaSchema).query(({ ctx }) => people.getCapoArea(ctx.viewer)), @@ -111,8 +115,13 @@ export function createPeopleRouter(people: PeopleService) { me: createTRPCRouter({ roles: self.output(C.myRolesSchema).query(({ ctx }) => people.getMyRoles(ctx.viewer)), get: self.output(C.myAreaSchema).query(({ ctx }) => people.getMyArea(ctx.viewer)), - acceptInvite: self - .input(z.object({ token: z.string().regex(/^[A-Za-z0-9_-]{43}$/) })) + // Any signed-in account with a valid token: someone new holds no People permission yet. + invite: user + .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)), }), }) diff --git a/src/people/service.ts b/src/people/service.ts index 8569a54..66f391b 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -33,6 +33,7 @@ import { bindingsOf, type Concept, conceptOf, + isBound, type PeopleRoles, RoleChangeError, type RoleCommand, @@ -42,7 +43,26 @@ import { } from "./roles" import { type BoundRole, peopleRoleChangeProblem } from "./rules" import { reconcile, syncDirectory } from "./sync" -import type { Account, Assignment, PeopleStore, Person, UnitOfWork, Viewer } from "./types" +import type { Account, Assignment, PeopleStore, Person, StoredCommand, UnitOfWork, Viewer } from "./types" + +const longDate = (iso: string) => + new Intl.DateTimeFormat("it-IT", { timeZone: "Europe/Rome", day: "numeric", month: "long", year: "numeric" }).format( + new Date(iso) + ) +/** The invite email. Any account will do: the link is the proof, not the address it was sent to. */ +function inviteText(p: Person, url: string, expiresAt: string) { + return [ + `Ciao ${p.firstName},`, + "", + "ti abbiamo aggiunto al registro delle persone di PoliNetwork. Per collegarlo al tuo account, apri questo link e accedi:", + "", + url, + "", + "Usa l'account con cui entrerai nella dashboard: quello PoliNetwork se fai parte dei soci, altrimenti un qualsiasi account Google. Non deve per forza essere questo indirizzo.", + "", + `Il link funziona una sola volta e scade il ${longDate(expiresAt)}. Se non sai di cosa si tratta, ignora questa email.`, + ].join("\n") +} export type PeopleOptions = { store: PeopleStore @@ -61,6 +81,8 @@ export const DIRECTORY_TTL_MS = 15_000 /** Past this without an answer, People refuses to work rather than decide who holds a role from an old one. */ export const DIRECTORY_MAX_AGE_MS = 60 * 60_000 const WAITING = "A role change for this person is waiting for PoliNetwork Auth; try again in a moment." +/** Why an assignment ended when Auth took its role back for an unlink that then found other roles held. */ +const TAKEN_BACK = "Taken back in PoliNetwork Auth to unlink the account" const refusalCode = (status: number) => status === 403 ? "FORBIDDEN" : status === 404 ? "NOT_FOUND" : status === 409 ? "CONFLICT" : "PRECONDITION_FAILED" @@ -76,10 +98,10 @@ export function createPeopleService(options: PeopleOptions) { let directoryRead: Read | null = null let stale = false /** Auth's answer, from cache for {@link DIRECTORY_TTL_MS}, or the last one during a short outage. */ - async function readDirectory(): Promise { + async function readDirectory(fresh = false): Promise { if (!peopleRoles) return null const at = now().getTime() - if (!stale && directoryRead && at - directoryRead.at < DIRECTORY_TTL_MS) return directoryRead + if (!fresh && !stale && directoryRead && at - directoryRead.at < DIRECTORY_TTL_MS) return directoryRead // A role change Auth confirms while it answers makes this answer older than the register. const revision = await store.transaction(async (u) => u.state.counters.roleRevision ?? 0) try { @@ -89,7 +111,7 @@ export function createPeopleService(options: PeopleOptions) { directoryRead = { value, at, revision } stale = false } catch (error) { - if (!directoryRead || at - directoryRead.at > DIRECTORY_MAX_AGE_MS) + if (fresh || !directoryRead || at - directoryRead.at > DIRECTORY_MAX_AGE_MS) fail("PRECONDITION_FAILED", "PoliNetwork Auth can't be reached: People can't tell who holds which role") console.error(error) } @@ -103,30 +125,36 @@ export function createPeopleService(options: PeopleOptions) { /** Auth's answer; null without Auth. */ directory: RoleDirectory | null /** Sends the command once the transaction commits; `strict` fails the call when Auth refuses it. */ - send: (personId: string, command: RoleCommand, strict: boolean) => void + send: (personId: string, command: RoleCommand, strict: boolean, purpose?: StoredCommand["purpose"]) => void } - /** A People transaction that first lays Auth's answer over the register, then delivers the role commands it queued. */ - async function tx(fn: (u: UnitOfWork, ctx: Ctx) => Promise | T): Promise { - const read = await readDirectory() + /** + * A People transaction that first lays Auth's answer over the register, then delivers the role commands it queued. + * `fresh` asks Auth again instead of using the cache, and fails rather than fall back on an older answer. + */ + async function tx(fn: (u: UnitOfWork, ctx: Ctx) => Promise | T, fresh = false): Promise { + const read = await readDirectory(fresh) const deliveries: { id: string; strict: boolean }[] = [] const result = await store.transaction(async (u) => { if (read) { // An older answer than the register's last confirmation, or than the last answer applied (by this or // another instance), would undo it: read again next time. const { roleRevision = 0, directoryReadAt = 0 } = u.state.counters - if (read.revision !== roleRevision || read.at < directoryReadAt) stale = true - else { + if (read.revision !== roleRevision || read.at < directoryReadAt) { + stale = true + if (fresh) fail("CONFLICT", "PoliNetwork Auth changed a role while People read it; try again") + } else { syncDirectory(u, read.value, clock()) u.state.counters.directoryReadAt = read.at } } return fn(u, { directory: read?.value ?? null, - send(personId, command, strict) { + send(personId, command, strict, purpose = "roles") { u.state.commands[command.id] = { id: command.id, personId, request: command, + purpose, status: "queued", attempts: 0, error: null, @@ -178,6 +206,20 @@ export function createPeopleService(options: PeopleOptions) { } command.status = "refused" command.answeredAt = now().toISOString() + if (command.purpose === "unlink") { + // The account stays linked, with the roles Auth still holds, and any earlier refusal still shown. + for (const a of Object.values(u.state.assignments).filter((a) => a.commandId === id)) + Object.assign(a, { status: a.refusal ? "refused" : "applied", commandId: null }) + log( + u, + command.personId, + command.request.actor, + `PoliNetwork Auth refused to unlink: ${failure.message}`, + now() + ) + bumpRevision(u) + return + } for (const a of Object.values(u.state.assignments).filter((a) => a.commandId === id)) { // A refused start never took effect; a refused end leaves the role held. if (a.change === "start") Object.assign(a, { endedOn: date(), endReason: "Refused by PoliNetwork Auth" }) @@ -189,11 +231,40 @@ export function createPeopleService(options: PeopleOptions) { }) return failure.unanswered ? null : failure } + let remaining: RoleChangeError | null = null await store.transaction(async (u) => { const command = u.state.commands[id] if (command?.status !== "queued") return Object.assign(command, { status: "applied", answeredAt: now().toISOString(), error: null }) command.attempts += 1 + const p = u.state.persons[command.personId] + if (command.purpose === "unlink") { + const latest = (u.state.counters.roleRevision ?? 0) === revision + bumpRevision(u) + if (!p) return + // Auth may still hold roles for the account, given since (by hand, or in Auth before a retry). + // Detaching then would leave it that access: keep the link and show what Auth holds. + if (bindingsOf(result.roles, result.held).length) { + // Auth took these back, so they end while the account stays linked; `detach` brings them back as + // pending once it is unlinked, as if this unlink had gone through. + for (const a of Object.values(u.state.assignments).filter((a) => a.commandId === id)) + Object.assign(a, { + endedOn: date(), + endReason: TAKEN_BACK, + change: "end", + status: "applied", + refusal: null, + commandId: null, + }) + // Unless another answer arrived meanwhile: this one may be older, and the next directory read settles it. + if (latest) reconcile(u, p, result.roles, result.held, clock()) + log(u, p.id, command.request.actor, "Not unlinked: PoliNetwork Auth still holds roles for the account", now()) + remaining = new RoleChangeError(409, "PoliNetwork Auth still holds roles for this account: unlink again") + return + } + detach(u, p, command.request.actor, command.request.reason.slice(C.UNLINK_REASON.length)) + return + } for (const a of Object.values(u.state.assignments).filter((a) => a.commandId === id)) Object.assign(a, { status: "applied", refusal: null, commandId: null }) if (command.request.changes.some((c) => c.kind === "capo" && !c.active)) @@ -201,12 +272,11 @@ export function createPeopleService(options: PeopleOptions) { log(u, command.personId, command.request.actor, `PoliNetwork Auth confirmed: ${command.request.reason}`, now()) // What Auth holds afterwards wins, for example a role still held through a parent role. Unless another // answer arrived meanwhile: this one may be older, and the next directory read settles it. - const p = u.state.persons[command.personId] if (p && (u.state.counters.roleRevision ?? 0) === revision) reconcile(u, p, result.roles, result.held, clock()) bumpRevision(u) }) stale = true - return null + return remaining } /** The single role Auth binds to `binding`, or why People can't use it. */ @@ -225,7 +295,7 @@ export function createPeopleService(options: PeopleOptions) { const directory = ctx.directory as RoleDirectory const problem = peopleRoleChangeProblem({ actor: v, - held: bindingsOf(directory.roles, directory.users.find((user) => user.sub === v.sub)?.roles ?? []), + held: heldBy(directory, v), targetSub: p.accountSub, role, action, @@ -324,7 +394,7 @@ export function createPeopleService(options: PeopleOptions) { u.merges.push({ from: other.id, into: p.id }) log(u, p.id, actor, `Absorbed ${other.id}, created for the account's roles in PoliNetwork Auth`, now()) } - function link(u: UnitOfWork, p: Person, sub: string, actor: string, how: string) { + function link(u: UnitOfWork, p: Person, sub: string, actor: string, method: "invite" | "manual", how: string) { if (p.accountSub) fail("CONFLICT", p.accountSub === sub ? "Already linked" : "Unlink the existing account first") const other = Object.values(u.state.persons).find((o) => o.id !== p.id && o.accountSub === sub) if (other && !automatic(u, other)) fail("CONFLICT", `This account is already linked to ${other.id}`) @@ -332,13 +402,49 @@ export function createPeopleService(options: PeopleOptions) { other.accountSub = null absorb(u, p, other, actor) } - p.accountSub = sub + Object.assign(p, { accountSub: sub, linkedAt: now().toISOString(), linkedBy: actor, linkMethod: method }) for (const invite of Object.values(u.state.invites)) if (invite.personId === p.id && !invite.revokedAt && !invite.acceptedAt) invite.revokedAt = now().toISOString() touch(p, actor, now()) - log(u, p.id, actor, `Linked account ${sub}: ${how}`, now()) + log(u, p.id, actor, `Linked account ${sub} (${method === "invite" ? "email invite" : "by hand"}): ${how}`, now()) return p } + /** Auth no longer holds the record's roles: its current assignments wait for the next link, as pending. */ + function detach(u: UnitOfWork, p: Person, actor: string, reason: string) { + // What an earlier attempt to unlink this link took back comes back too, unless it was given again since. + for (const a of assignmentsOf(u.state, p.id)) + if ( + a.endReason === TAKEN_BACK && + (a.endedOn as string) >= (p.linkedAt?.slice(0, 10) ?? "") && + !current(u.state, p.id, conceptOf(a)) + ) + Object.assign(a, { endedOn: null, endReason: null }) + for (const a of assignmentsOf(u.state, p.id)) { + if (a.endedOn) continue + Object.assign(a, { status: "pending", change: "start", refusal: null, commandId: null }) + // Auth will need a real person to act for it at the next link: whoever unlinked takes it over. + if (a.assignedBy === "auth") { + a.assignedBy = actor + log(u, p.id, actor, `Took over the ${conceptOf(a)} assignment given in PoliNetwork Auth`, now()) + } + } + log(u, p.id, actor, `Unlinked account ${p.accountSub}: ${reason}`, now()) + Object.assign(p, { accountSub: null, linkedAt: null, linkedBy: null, linkMethod: null }) + touch(p, actor, now()) + } + /** Who may invite to a record: People writers, or the Lead of one of the person's teams. */ + function inviteAccess(ctx: Ctx, u: UnitOfWork, v: Viewer, p: Person) { + if (general(v, "people:write")) return + const teams = assignmentsOf(u.state, p.id).flatMap((a) => (a.kind === "team" && !a.endedOn ? [a.team] : [])) + if (!teams.some((team) => leads(ctx, u, v, team as C.TeamId))) + fail("FORBIDDEN", "Inviting needs people:write and admin:access, or leading one of the person's teams") + } + function inviteFor(u: UnitOfWork, token: string) { + const invite = Object.values(u.state.invites).find( + (i) => i.tokenHash === hash(token) && !i.revokedAt && !i.acceptedAt && i.expiresAt > now().toISOString() + ) + return invite ?? fail("NOT_FOUND", "This invite link is no longer valid: ask for a new one") + } function capoOf(u: UnitOfWork, capoId: string | null, personId: string) { if (!capoId) return null @@ -350,17 +456,22 @@ export function createPeopleService(options: PeopleOptions) { function activeOrFail(u: UnitOfWork, personId: string, concept: Concept, message: string) { return current(u.state, personId, concept) ?? fail("CONFLICT", message) } - /** Whether a Lead (per Auth) or a People writer may work on a team's data. */ + /** The People bindings of the roles the viewer holds in Auth. */ + function heldBy(directory: RoleDirectory, v: Viewer) { + return bindingsOf(directory.roles, directory.users.find((user) => user.sub === v.sub)?.roles ?? []) + } + /** Whether the viewer leads `team`: as Auth says, or as their own record says when Auth isn't configured. */ + function leads(ctx: Ctx, u: UnitOfWork, v: Viewer, team: C.TeamId) { + if (!v.can("people:self")) return false + if (ctx.directory) + return heldBy(ctx.directory, v).some((b) => b.kind === "team" && b.team === team && b.role === "lead") + const mine = own(u.state, v) + return !!mine && leadsOf(u.state, mine.id).includes(team) + } + /** Whether a Lead or a People writer may work on a team's data. */ function teamAccess(ctx: Ctx, u: UnitOfWork, v: Viewer, team: C.TeamId, write: boolean) { if (general(v, write ? "people:write" : "people:read")) return - const held = ctx.directory - ? bindingsOf(ctx.directory.roles, ctx.directory.users.find((user) => user.sub === v.sub)?.roles ?? []) - : [] - const mine = own(u.state, v) - const leads = - held.some((b) => b.kind === "team" && b.team === team && b.role === "lead") || - (!ctx.directory && !!mine && leadsOf(u.state, mine.id).includes(team)) - if (!v.can("people:self") || !leads) fail("FORBIDDEN", "You do not lead this team") + if (!leads(ctx, u, v, team)) fail("FORBIDDEN", "You do not lead this team") } return { @@ -624,9 +735,9 @@ export function createPeopleService(options: PeopleOptions) { ) }, async sendInvite(v: Viewer, input: { personId: string }) { - requireGeneral(v, "people:write") - return tx((u) => { + return tx((u, ctx) => { const p = find(u.state, input.personId) + inviteAccess(ctx, u, v, p) if (p.accountSub || !p.contactEmail) fail("CONFLICT", "Account already linked or contact email missing") const previous = openInvite(u.state, p.id) if (previous) previous.revokedAt = now().toISOString() @@ -650,22 +761,22 @@ export function createPeopleService(options: PeopleOptions) { `invite:${invite.id}`, p.contactEmail, "PoliNetwork · collega il tuo account", - `${dashboardUrl}/dashboard/account/me?peopleInvite=${token}` + inviteText(p, `${dashboardUrl}/dashboard/account/me?peopleInvite=${token}`, invite.expiresAt) ) log(u, p.id, v.sub, "Queued an account invite", now()) }) }, async revokeInvite(v: Viewer, input: { personId: string }) { - requireGeneral(v, "people:write") - return tx((u) => { + return tx((u, ctx) => { const p = find(u.state, input.personId) + inviteAccess(ctx, u, v, p) const invite = openInvite(u.state, p.id) ?? fail("CONFLICT", "No open invite") invite.revokedAt = now().toISOString() log(u, p.id, v.sub, "Revoked the account invite", now()) }) }, async searchAccounts(v: Viewer, input: C.SearchAccountsInput): Promise { - requireGeneral(v, "people:write") + requireGeneral(v, "people:link") const accounts = await options.directory() return tx((u) => { const q = input.query.toLowerCase() @@ -680,43 +791,90 @@ export function createPeopleService(options: PeopleOptions) { }, /** Links by hand, then sends the record's pending assignments to Auth acting as whoever linked it. */ async linkAccount(v: Viewer, input: C.LinkAccountInput) { - requireGeneral(v, "people:write") + requireGeneral(v, "people:link") const account = (await options.directory()).find((a) => a.sub === input.accountId) if (!account) fail("NOT_FOUND", "IdP account not found") // Its pending assignments would be sent as self-grants, which Auth refuses. if (account.sub === v.sub) fail("FORBIDDEN", "Ask someone else to link your own account") return tx((u, ctx) => { - const p = link(u, find(u.state, input.personId), account.sub, v.sub, input.reason) + const p = link(u, find(u.state, input.personId), account.sub, v.sub, "manual", input.reason) sendPending(u, ctx, p, () => v.sub, `Linked from People: ${input.reason}`) }) }, - async unlinkAccount(v: Viewer, input: { personId: string }) { - requireGeneral(v, "people:write") - return tx((u) => { + /** + * Takes the record's roles back from the account in Auth, then detaches it; its assignments go back to + * `pending` for the next link. Without roles Auth holds, it detaches at once: it asks Auth afresh to tell, + * since a role given by hand in Auth since the last answer would otherwise stay with the detached account. + */ + async unlinkAccount(v: Viewer, input: C.UnlinkAccountInput) { + requireGeneral(v, "people:link") + return tx((u, ctx) => { const p = find(u.state, input.personId) if (!p.accountSub) fail("CONFLICT", "Account not linked") - if (assignmentsOf(u.state, p.id).some((a) => !a.endedOn) || waiting(u.state, p.id)) - fail("CONFLICT", "End this record's roles before unlinking it: PoliNetwork Auth holds them for the account") - log(u, p.id, v.sub, `Unlinked account ${p.accountSub}`, now()) - p.accountSub = null - touch(p, v.sub, now()) + if (waiting(u.state, p.id)) fail("CONFLICT", WAITING) + const held = assignmentsOf(u.state, p.id).filter( + (a) => !a.endedOn && !!ctx.directory && isBound(ctx.directory.roles, conceptOf(a)) + ) + for (const a of held) { + const binding = a.kind === "team" ? `team:${a.team}:${a.teamRole}` : a.kind + authorize(ctx, u, v, p, binding, "unassign") + } + if (!held.length) return detach(u, p, v.sub, input.reason) + const id = randomUUID() + const changes = desired(u, p, [...new Set(held.map(conceptOf))]).map((c) => + c.kind === "team" ? { ...c, role: null } : { ...c, active: false } + ) + const reason = `${C.UNLINK_REASON}${input.reason}` + ctx.send(p.id, { id, actor: v.sub, sub: p.accountSub, reason, changes }, true, "unlink") + // An earlier refusal to end one stays: it shows again if Auth refuses the unlink. + for (const a of held) Object.assign(a, { status: "sent", commandId: id }) + log(u, p.id, v.sub, "Asked PoliNetwork Auth to take the record's roles back before unlinking", now()) + }, true) + }, + async listRecentLinks(v: Viewer): Promise { + requireGeneral(v, "people:read") + const since = new Date(now().getTime() - 30 * 86_400_000).toISOString() + const links = await tx((u) => + Object.values(u.state.persons) + .filter((p) => p.accountSub && p.linkedAt && p.linkedAt >= since) + .sort((a, b) => ((a.linkedAt as string) < (b.linkedAt as string) ? 1 : -1)) + .map((p) => ({ + person: ref(p), + sub: p.accountSub as string, + method: p.linkMethod ?? "manual", + linkedOn: (p.linkedAt as string).slice(0, 10), + linkedBy: p.linkedBy, + })) + ) + if (!links.length) return [] + // The emails are only a hint for spotting a forwarded invite: without the directory, the list still shows. + const accounts = await options.directory().catch((error) => { + console.error(error) + return [] as Account[] }) + return links.map((link) => ({ ...link, email: accounts.find((a) => a.sub === link.sub)?.email ?? null })) }, /** - * Links the signed-in account to the invited record. Each pending assignment is sent acting as whoever made - * it: Auth refuses self-grants, so the invitee can't be the actor. + * The record an invite is for, so the landing page can ask "Link this account to ?". It only reads the + * register, so it neither waits for Auth nor lays Auth's answer over it. + */ + async previewInvite(_v: Viewer, input: { token: string }): Promise { + return store.transaction(async (u) => { + const invite = inviteFor(u, input.token) + const p = find(u.state, invite.personId) + return { personId: p.id, name: nameOf(p), expiresOn: invite.expiresAt.slice(0, 10) } + }) + }, + /** + * Links the signed-in account to the invited record. Any signed-in account may accept: the single-use token is + * the proof, not the account's email, since people often sign in with another account than the one we know. + * Recently linked lists it, in case an invite was forwarded. Each pending assignment is sent acting as whoever + * made it: Auth refuses self-grants, so the invitee can't be the actor. */ async acceptInvite(v: Viewer, input: { token: string }) { - requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) - if (!account?.email) fail("FORBIDDEN", "Verified account email required") return tx((u, ctx) => { - const invite = Object.values(u.state.invites).find( - (i) => i.tokenHash === hash(input.token) && !i.revokedAt && !i.acceptedAt && i.expiresAt > now().toISOString() - ) - if (!invite || invite.email.toLowerCase() !== account.email?.toLowerCase()) - fail("NOT_FOUND", "Invitation expired or not addressed to this account") - const p = link(u, find(u.state, invite.personId), v.sub, v.sub, "Accepted the email invite") + const invite = inviteFor(u, input.token) + 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") }) diff --git a/src/people/store-pg.ts b/src/people/store-pg.ts index 031a567..4fbabc7 100644 --- a/src/people/store-pg.ts +++ b/src/people/store-pg.ts @@ -22,11 +22,13 @@ const TABLES = [ id: persons.id, load: (r: typeof persons.$inferSelect) => ({ ...r, + linkedAt: iso(r.linkedAt), createdAt: r.createdAt.toISOString(), updatedAt: r.updatedAt.toISOString(), }), save: (p: PeopleState["persons"][string]) => ({ ...p, + linkedAt: time(p.linkedAt), createdAt: new Date(p.createdAt), updatedAt: new Date(p.updatedAt), }), diff --git a/src/people/sync.ts b/src/people/sync.ts index a685bc6..9a81f47 100644 --- a/src/people/sync.ts +++ b/src/people/sync.ts @@ -123,6 +123,9 @@ export function syncDirectory(u: UnitOfWork, directory: RoleDirectory, at: Clock telegramUsername: user.telegramUsername, notes: null, accountSub: user.sub, + linkedAt: stamp, + linkedBy: "auth", + linkMethod: "auth", createdBy: "auth", createdAt: stamp, updatedBy: "auth", diff --git a/src/people/types.ts b/src/people/types.ts index f92abbd..f5a03e2 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -22,6 +22,10 @@ export type Person = { notes: string | null /** The login account the record is linked to. */ accountSub: string | null + /** When and how it was linked, and by whom (`auth` for a record created from a role held in Auth). */ + linkedAt: string | null + linkedBy: string | null + linkMethod: "invite" | "manual" | "auth" | null createdBy: string createdAt: string updatedBy: string @@ -55,6 +59,8 @@ export type StoredCommand = { id: string personId: string request: RoleCommand + /** `unlink` revokes the record's roles, then detaches the account once Auth confirms. */ + purpose: "roles" | "unlink" status: "queued" | "applied" | "refused" attempts: number error: string | null diff --git a/tests/people-auth.ts b/tests/people-auth.ts index e3b4605..01650a4 100644 --- a/tests/people-auth.ts +++ b/tests/people-auth.ts @@ -40,6 +40,10 @@ export function fakeAuth(roles: BoundRole[] = structuredClone(BOUND)) { const state = { mode: "up" as "up" | "down" | "lost", refusal: null as { status: number; message: string } | null, + /** Runs before a command is applied, e.g. to change Auth between People's read and its command. */ + before: null as ((command: RoleCommand) => void) | null, + /** Refuses only the commands it returns a refusal for, e.g. one actor's. */ + refuse: null as ((command: RoleCommand) => { status: number; message: string } | null) | null, calls: [] as RoleCommand[], reads: 0, } @@ -75,7 +79,9 @@ export function fakeAuth(roles: BoundRole[] = structuredClone(BOUND)) { async change(command) { state.calls.push(structuredClone(command)) if (state.mode === "down") throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") - if (state.refusal) throw new RoleChangeError(state.refusal.status, state.refusal.message) + state.before?.(command) + const refusal = state.refusal ?? state.refuse?.(command) + if (refusal) throw new RoleChangeError(refusal.status, refusal.message) if (!applied.has(command.id)) { applied.add(command.id) const keys = rolesOf(command.sub) diff --git a/tests/people-fixtures.ts b/tests/people-fixtures.ts index f7c3a91..944f897 100644 --- a/tests/people-fixtures.ts +++ b/tests/people-fixtures.ts @@ -22,7 +22,14 @@ export const viewer = (sub: string, permissions: string[], roles: string[] = []) can: (key) => permissions.includes(key), holdsRole: (key) => roles.includes(key), }) -export const permissions = ["admin:access", "people:self", "people:read", "people:write", "people:appoint"] +export const permissions = [ + "admin:access", + "people:self", + "people:read", + "people:write", + "people:appoint", + "people:link", +] /** HR with every People permission, and nothing else Auth knows of. */ export const master = viewer("president", permissions) diff --git a/tests/people-postgres.fixture.ts b/tests/people-postgres.fixture.ts index 55a0e7b..3501145 100644 --- a/tests/people-postgres.fixture.ts +++ b/tests/people-postgres.fixture.ts @@ -25,7 +25,14 @@ const checked: string[] = [] try { await migrate(db, { migrationsFolder: "./drizzle" }) const store = createPeoplePgStore(db) - const permissionSet = new Set(["admin:access", "people:self", "people:read", "people:write", "people:appoint"]) + const permissionSet = new Set([ + "admin:access", + "people:self", + "people:read", + "people:write", + "people:appoint", + "people:link", + ]) const viewer = (sub: string): Viewer => ({ sub, telegramId: null, @@ -130,6 +137,19 @@ try { assert.equal((await db.select().from(persons)).length, 4) checked.push("constraints hold one account and one current assignment per concept") + // Unlinking takes the roles back in Auth, then detaches the account with its link details. + await service().unlinkAccount(hr, { personId: "P-0001", reason: "Wrong person" }) + assert.deepEqual(auth.held("mario"), []) + const [unlinked] = await db.select().from(persons).where(eq(persons.id, "P-0001")) + assert.equal(unlinked.accountSub, null) + assert.equal(unlinked.linkedAt, null) + const recent = await service().listRecentLinks(hr) + assert.deepEqual( + recent.map((r) => [r.person.id, r.method]), + [[hrAnna, "manual"]] + ) + checked.push("unlinking revokes in Auth and detaches, with link details") + await people.sendInvite(hr, { personId: "P-0003" }) await Promise.all([people.deliverPending(), people.deliverPending()]) assert.equal(sent.length, 1) diff --git a/tests/people-postgres.test.ts b/tests/people-postgres.test.ts index 4602cb8..7f095ed 100644 --- a/tests/people-postgres.test.ts +++ b/tests/people-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(7) + expect(result.checked).toHaveLength(8) }, 65000 ) diff --git a/tests/people-router.test.ts b/tests/people-router.test.ts index 002ecad..bc8cd4d 100644 --- a/tests/people-router.test.ts +++ b/tests/people-router.test.ts @@ -1,7 +1,7 @@ import type { Actor } from "@polinetwork/auth-kit" import { beforeAll, describe, expect, it } from "vitest" import type { Context } from "@/trpc" -import { harness, permissions, profile } from "./people-fixtures" +import { harness, master, permissions, profile } from "./people-fixtures" Object.assign(process.env, { NODE_ENV: "test", @@ -58,6 +58,18 @@ describe("People tRPC contract", () => { ).rejects.toMatchObject({ code: "BAD_REQUEST" }) expect(Object.keys(h.state().persons)).toHaveLength(3) }) + it("lets a signed-in account without People permissions open and accept an invite", async () => { + const h = harness() + await h.seed(false) + await h.service.sendInvite(master, { personId: "P-0003" }) + const token = Object.values(h.state().mail)[0].text.match(/peopleInvite=([A-Za-z0-9_-]{43})/)?.[1] ?? "" + const actor: Actor = { kind: "user", sub: "newcomer", client: "admin-dashboard", telegramId: null } + 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" }) + await caller.me.acceptInvite({ token }) + expect(h.state().persons["P-0003"].accountSub).toBe("newcomer") + }) it("mounts every People procedure with a dashboard policy", () => { const r = makeRouter(harness().service) const procedures = (r as unknown as { _def: { procedures: Record } })._def @@ -76,12 +88,14 @@ describe("People tRPC contract", () => { "capos.setScope", "linking.invites", "linking.link", + "linking.recent", "linking.revokeInvite", "linking.searchAccounts", "linking.sendInvite", "linking.unlink", "me.acceptInvite", "me.get", + "me.invite", "me.roles", "persons.create", "persons.get", diff --git a/tests/people.test.ts b/tests/people.test.ts index 44ade2e..7e5ac73 100644 --- a/tests/people.test.ts +++ b/tests/people.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from "vitest" -import { myAreaSchema } from "@/people/contract" +import { myAreaSchema, UNLINK_REASON, unlinkAccountInputSchema } from "@/people/contract" +import { newAssignment } from "@/people/model" import { DIRECTORY_MAX_AGE_MS, DIRECTORY_TTL_MS } from "@/people/service" import { fakeAuth, harness, master, permissions, profile, viewer } from "./people-fixtures" @@ -397,56 +398,193 @@ describe("Pending assignments follow Auth's rules", () => { }) }) -describe("Linking sends pending assignments", () => { - it("acts as whoever links by hand", async () => { +const tokenOf = (h: ReturnType) => + Object.values(h.state().mail) + .at(-1) + ?.text.match(/peopleInvite=([A-Za-z0-9_-]{43})/)?.[1] ?? "" + +describe("Linking by invite", () => { + it("links whichever account accepts, acting as each assigner, without People permissions or a matching email", async () => { const h = harness() await h.seed(false) + const vice = viewer("vice", permissions) await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) - await h.service.linkAccount(viewer("vice", permissions), { + await h.service.addTeamMember(vice, { teamId: "it", personId: "P-0003", role: "member", since, fields: {} }) + await h.service.sendInvite(master, { personId: "P-0003" }) + // Signed in with an account whose email isn't the invited one, holding no People permission. + const invitee = viewer("luca-google", []) + expect(await h.service.previewInvite(invitee, { token: tokenOf(h) })).toEqual({ personId: "P-0003", - accountId: "member", - reason: "Checked in person", + name: "Luca Verdi", + expiresOn: "2026-11-01", }) - expect(h.auth.state.calls).toMatchObject([ - { actor: "vice", sub: "member", changes: [{ kind: "admin", active: true }] }, + await h.service.acceptInvite(invitee, { token: tokenOf(h) }) + expect(h.auth.state.calls.map((c) => [c.actor, c.sub, c.changes]).sort()).toEqual([ + ["president", "luca-google", [{ kind: "admin", active: true }]], + ["vice", "luca-google", [{ kind: "team", team: "it", role: "member" }]], ]) - expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "applied" }]) + expect(h.auth.held("luca-google")).toEqual(["admin", "it-member"]) + expect((await h.service.getPerson(master, { id: "P-0003" })).account).toEqual({ + status: "linked", + sub: "luca-google", + method: "invite", + linkedOn: "2026-10-18", + linkedBy: "luca-google", + }) }) - it("acts as each assigner when the invitee accepts, so nobody grants themselves a role", async () => { + it("uses each token once, until it expires, and only the latest one", async () => { const h = harness() await h.seed(false) - const vice = viewer("vice", permissions) - await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) - await h.service.addTeamMember(vice, { teamId: "it", personId: "P-0003", role: "member", since, fields: {} }) await h.service.sendInvite(master, { personId: "P-0003" }) - const first = Object.values(h.state().mail).at(-1)?.text.split("peopleInvite=")[1] ?? "" + const first = tokenOf(h) await h.service.sendInvite(master, { personId: "P-0003" }) - const last = Object.values(h.state().mail).at(-1)?.text.split("peopleInvite=")[1] ?? "" - const invitee = viewer("member", ["people:self"]) - await expect(h.service.acceptInvite(invitee, { token: first })).rejects.toMatchObject({ code: "NOT_FOUND" }) - await expect(h.service.acceptInvite(viewer("vice", ["people:self"]), { token: last })).rejects.toMatchObject({ + const second = tokenOf(h) + const someone = viewer("someone", []) + await expect(h.service.acceptInvite(someone, { token: first })).rejects.toMatchObject({ code: "NOT_FOUND" }) + await h.service.revokeInvite(master, { personId: "P-0003" }) + await expect(h.service.previewInvite(someone, { token: second })).rejects.toMatchObject({ code: "NOT_FOUND" }) + await h.service.sendInvite(master, { personId: "P-0002" }) + const late = tokenOf(h) + h.advance(14 * 86_400_000 + 1) + await expect(h.service.acceptInvite(someone, { token: late })).rejects.toMatchObject({ code: "NOT_FOUND" }) + await h.service.sendInvite(master, { personId: "P-0002" }) + const fresh = tokenOf(h) + await h.service.acceptInvite(someone, { token: fresh }) + await expect(h.service.acceptInvite(viewer("other", []), { token: fresh })).rejects.toMatchObject({ code: "NOT_FOUND", }) - await h.service.acceptInvite(invitee, { token: last }) - expect(h.auth.state.calls.map((c) => [c.actor, c.changes]).sort()).toEqual([ - ["president", [{ kind: "admin", active: true }]], - ["vice", [{ kind: "team", team: "it", role: "member" }]], + expect(h.state().persons["P-0002"].accountSub).toBe("someone") + }) + it("refuses an account already linked to another record", async () => { + const h = harness() + await h.seed() + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + await h.service.sendInvite(master, { personId: id }) + await expect(h.service.acceptInvite(viewer("member", []), { token: tokenOf(h) })).rejects.toMatchObject({ + code: "CONFLICT", + message: "This account is already linked to P-0003", + }) + expect(h.state().persons[id].accountSub).toBeNull() + }) + it("lets a Lead invite their team's members, and nobody else's", async () => { + const h = harness() + await h.seed(false) + h.auth.give("vice", "it-lead") + await h.service.addTeamMember(master, { teamId: "it", personId: "P-0003", role: "member", since, fields: {} }) + const lead = viewer("vice", ["admin:access", "people:self"]) + await h.service.sendInvite(lead, { personId: "P-0003" }) + await expect(h.service.sendInvite(lead, { personId: "P-0001" })).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.service.revokeInvite(lead, { personId: "P-0003" }) + }) + it("keeps on the record what Auth refuses, and applies the rest", async () => { + const h = harness() + await h.seed(false) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + await h.service.addTeamMember(viewer("vice", permissions), { + teamId: "it", + personId: "P-0003", + role: "member", + since, + fields: {}, + }) + h.auth.state.refuse = (c) => + c.actor === "vice" ? { status: 403, message: "Changing this role needs people:write and admin:access." } : null + await h.service.sendInvite(master, { personId: "P-0003" }) + await h.service.acceptInvite(viewer("member", []), { token: tokenOf(h) }) + expect(assignmentsOf(h, "P-0003").map((a) => [a.kind, a.status, a.endedOn])).toEqual([ + ["admin", "applied", null], + ["team", "refused", "2026-10-18"], ]) - expect(h.auth.held("member")).toEqual(["admin", "it-member"]) - expect(await h.service.getMyRoles(invitee)).toEqual({ capoScope: null, leads: [] }) + expect(h.auth.held("member")).toEqual(["admin"]) + }) + it("previews an invite without asking Auth, even when it has been down for long", async () => { + const h = harness() + await h.seed(false) + await h.service.sendInvite(master, { personId: "P-0003" }) + h.auth.state.mode = "down" + h.advance(DIRECTORY_MAX_AGE_MS + 1) + const reads = h.auth.state.reads + await expect(h.service.previewInvite(viewer("someone", []), { token: tokenOf(h) })).resolves.toMatchObject({ + personId: "P-0003", + }) + expect(h.auth.state.reads).toBe(reads) + }) + it("lets a Lead invite their team's members without Auth, as they manage the team", async () => { + const h = harness({ peopleRoles: null }) + await h.seed() + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + await h.store.transaction(async (u) => { + const team = { kind: "team", team: "it", since, assignedBy: "seed", status: "applied" } as const + newAssignment(u.state, { ...team, personId: "P-0002", teamRole: "lead" }) + newAssignment(u.state, { ...team, personId: id, teamRole: "member" }) + }) + await h.service.sendInvite(viewer("vice", ["admin:access", "people:self"]), { personId: id }) + await expect(h.service.sendInvite(viewer("vice", ["admin:access"]), { personId: id })).rejects.toMatchObject({ + code: "FORBIDDEN", + }) + }) + it("says in the email that any account will do", async () => { + const h = harness() + await h.seed(false) + await h.service.sendInvite(master, { personId: "P-0003" }) + const [mail] = Object.values(h.state().mail) + expect(mail.text).toContain("Ciao Luca,") + expect(mail.text).toContain("Non deve per forza essere questo indirizzo") + expect(mail.text).toContain("scade il 1 novembre 2026") + }) +}) + +describe("Linking by hand", () => { + it("needs people:link, and acts as whoever links", async () => { + const h = harness() + await h.seed(false) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + const writer = viewer("vice", ["admin:access", "people:write", "people:read"]) + await expect( + h.service.linkAccount(writer, { personId: "P-0003", accountId: "member", reason: "x" }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: expect.stringContaining("people:link") }) + await expect(h.service.searchAccounts(writer, { query: "" })).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.service.linkAccount(viewer("vice", permissions), { + personId: "P-0003", + accountId: "member", + reason: "Checked in person", + }) + expect(h.auth.state.calls).toMatchObject([ + { actor: "vice", sub: "member", changes: [{ kind: "admin", active: true }] }, + ]) + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "applied" }]) + expect(await h.service.listRecentLinks(master)).toEqual([ + { + person: { id: "P-0003", name: "Luca Verdi" }, + sub: "member", + email: "luca@example.org", + method: "manual", + linkedOn: "2026-10-18", + linkedBy: "vice", + }, + ]) + h.advance(31 * 86_400_000) + expect(await h.service.listRecentLinks(master)).toEqual([]) + }) + it("lists recent links without asking the IdP directory when there are none", async () => { + const directory = vi.fn(async () => []) + const h = harness({ directory }) + await h.seed() + expect(await h.service.listRecentLinks(master)).toEqual([]) + expect(directory).not.toHaveBeenCalled() }) it("keeps an assignment Auth refuses at link time on the record as refused", async () => { const h = harness() await h.seed(false) await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) h.auth.state.refusal = { status: 403, message: "Changing this role needs people:write and admin:access." } - await h.service.linkAccount(master, { personId: "P-0003", accountId: "member", reason: "In person" }) + await h.service.linkAccount(viewer("vice", permissions), { personId: "P-0003", accountId: "member", reason: "x" }) expect(h.state().persons["P-0003"].accountSub).toBe("member") expect(assignmentsOf(h, "P-0003")).toMatchObject([ { status: "refused", refusal: expect.stringContaining("people:write") }, ]) }) - it("refuses an account already linked elsewhere, and unlinking while Auth holds roles", async () => { + it("refuses your own account and one linked elsewhere", async () => { const h = harness() await h.seed() await expect( @@ -456,11 +594,151 @@ describe("Linking sends pending assignments", () => { await expect( h.service.linkAccount(master, { personId: id, accountId: "vice", reason: "Test" }) ).rejects.toMatchObject({ code: "CONFLICT", message: "This account is already linked to P-0002" }) + }) +}) + +describe("Unlinking", () => { + it("takes the roles back in Auth, then detaches the account and puts the assignments back to pending", async () => { + const h = harness() + await h.seed() + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + await h.service.addTeamMember(master, { teamId: "it", personId: "P-0003", role: "member", since, fields: {} }) + await expect( + h.service.unlinkAccount(viewer("vice", ["admin:access", "people:write"]), { personId: "P-0003", reason: "x" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.service.unlinkAccount(viewer("vice", permissions), { personId: "P-0003", reason: "Wrong person" }) + expect(h.auth.held("member")).toEqual([]) + expect(h.auth.state.calls.at(-1)).toMatchObject({ + actor: "vice", + changes: [ + { kind: "admin", active: false }, + { kind: "team", team: "it", role: null }, + ], + }) + expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: null, linkMethod: null }) + expect(assignmentsOf(h, "P-0003").map((a) => [a.kind, a.status, a.endedOn])).toEqual([ + ["admin", "pending", null], + ["team", "pending", null], + ]) + // Linking again sends them as for any pending assignment. + await h.service.linkAccount(viewer("vice", permissions), { + personId: "P-0003", + accountId: "member", + reason: "Right one", + }) + expect(h.auth.held("member")).toEqual(["admin", "it-member"]) + }) + it("retries a lost answer with the same ID before detaching", async () => { + const h = harness() + await h.seed() + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + h.auth.state.mode = "lost" + await h.service.unlinkAccount(master, { personId: "P-0003", reason: "Wrong person" }) + expect(h.state().persons["P-0003"].accountSub).toBe("member") + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "sent" }]) + await h.service.deliverPending() + const ids = h.auth.state.calls.slice(-2).map((c) => c.id) + expect(ids[0]).toBe(ids[1]) + expect(h.state().persons["P-0003"].accountSub).toBeNull() + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "pending", endedOn: null }]) + }) + it("keeps the account linked when Auth refuses", async () => { + const h = harness() + await h.seed() + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + h.auth.state.refusal = { status: 409, message: "The admin role is inherited. Change its granting role in Auth." } + await expect(h.service.unlinkAccount(master, { personId: "P-0003", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + }) + expect(h.state().persons["P-0003"].accountSub).toBe("member") + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "applied", endedOn: null }]) + }) + it("keeps the account linked when Auth still holds a role given meanwhile", async () => { + const h = harness() + await h.seed() + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + // Given by hand in Auth after People read it, just before the unlink reaches Auth. + h.auth.state.before = (c) => { + if (c.reason.startsWith("Unlinked")) h.auth.give("member", "it-member") + } + await expect(h.service.unlinkAccount(master, { personId: "P-0003", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + message: expect.stringContaining("still holds roles"), + }) + expect(h.state().persons["P-0003"].accountSub).toBe("member") + expect(assignmentsOf(h, "P-0003").map((a) => [a.kind, a.status, a.endedOn])).toEqual([ + ["admin", "applied", "2026-10-18"], + ["team", "applied", null], + ]) + // Unlinking again ends as if the first unlink had gone through: what it took back is pending too. + h.auth.state.before = null + await h.service.unlinkAccount(master, { personId: "P-0003", reason: "Wrong person" }) + expect(h.state().persons["P-0003"].accountSub).toBeNull() + expect(assignmentsOf(h, "P-0003").map((a) => [a.kind, a.status, a.endedOn])).toEqual([ + ["admin", "pending", null], + ["team", "pending", null], + ]) + expect(h.history().map((a) => a.text)).toContain("Unlinked account member: Wrong person") + }) + it("keeps an earlier refusal on the record when Auth refuses the unlink", async () => { + const h = harness() + await h.seed() await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) - await expect(h.service.unlinkAccount(master, { personId: "P-0003" })).rejects.toMatchObject({ code: "CONFLICT" }) - await h.service.endAdmin(master, { personId: "P-0003", reason: "Done" }) - await h.service.unlinkAccount(master, { personId: "P-0003" }) + h.auth.state.refusal = { status: 409, message: "The admin role is inherited." } + await expect(h.service.endAdmin(master, { personId: "P-0003", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + }) + h.auth.state.refusal = { status: 409, message: "Not now." } + await expect(h.service.unlinkAccount(master, { personId: "P-0003", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + }) + expect(assignmentsOf(h, "P-0003")).toMatchObject([ + { status: "refused", refusal: "The admin role is inherited.", endedOn: null }, + ]) + }) + it("gives assignments made in Auth a real actor, so the next link can send them", async () => { + const h = harness() + h.auth.give("giulia", "it-member", "Giulia Neri") + await h.service.listPeople(master) + await h.service.unlinkAccount(master, { personId: "P-0001", reason: "Old account" }) + expect(assignmentsOf(h, "P-0001")).toMatchObject([{ status: "pending", assignedBy: "president" }]) + await h.service.updatePerson(master, { id: "P-0001", ...profile("Giulia", "Neri") }) + await h.service.sendInvite(master, { personId: "P-0001" }) + await h.service.acceptInvite(viewer("giulia-new", []), { token: tokenOf(h) }) + expect(h.auth.state.calls.at(-1)).toMatchObject({ actor: "president", sub: "giulia-new" }) + expect(assignmentsOf(h, "P-0001")).toMatchObject([{ status: "applied" }]) + }) + it("asks Auth afresh, so a role given by hand since the last answer is taken back too", async () => { + const h = harness() + await h.seed() + await h.service.listPeople(master) + h.auth.give("member", "it-member") + await h.service.unlinkAccount(master, { personId: "P-0003", reason: "Wrong person" }) + expect(h.auth.held("member")).toEqual([]) expect(h.state().persons["P-0003"].accountSub).toBeNull() + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ kind: "team", status: "pending", endedOn: null }]) + }) + it("refuses to unlink without a fresh answer from Auth", async () => { + const h = harness() + await h.seed() + await h.service.listPeople(master) + h.auth.state.mode = "down" + await expect(h.service.unlinkAccount(master, { personId: "P-0003", reason: "x" })).rejects.toMatchObject({ + code: "PRECONDITION_FAILED", + }) + expect(h.state().persons["P-0003"].accountSub).toBe("member") + }) + it("takes reasons that still fit Auth's 500 characters once prefixed", () => { + const max = 500 - UNLINK_REASON.length + expect(unlinkAccountInputSchema.safeParse({ personId: "P-0001", reason: "x".repeat(max) }).success).toBe(true) + expect(unlinkAccountInputSchema.safeParse({ personId: "P-0001", reason: "x".repeat(max + 1) }).success).toBe(false) + }) + it("detaches at once when Auth holds nothing for the record", async () => { + const h = harness() + await h.seed() + await h.service.unlinkAccount(master, { personId: "P-0003", reason: "Wrong person" }) + expect(h.state().persons["P-0003"].accountSub).toBeNull() + expect(h.auth.state.calls).toEqual([]) }) })