From fe9f40d84ff77f8ef3005ac0e6295cae84715eee Mon Sep 17 00:00:00 2001 From: Bianca Date: Fri, 30 Oct 2026 16:09:36 +0100 Subject: [PATCH 1/2] feat(people)!: keep People records and assignments in tables, with roles synced to Auth Each person is one record in people_persons. Group Admin, Capo Admin and team roles are rows in people_assignments, with an append-only people_activity history, people_invites and a people_mail outbox. This replaces the single JSON state. Writes stay serialized by one transaction lock. - Linked records follow PoliNetwork Auth: People reads the bound roles from GET /api/internal/people-roles (15 s cache; the last answer for up to an hour of outage) and creates linked records for people given a bound role by hand. - Changes are sent as idempotent role commands through people_role_commands. The cron sends them again until Auth answers. Assignments show `sent` until Auth confirms them, and Auth's reason when it refuses them. - Unlinked records keep their assignments `pending`. Linking sends them, acting as whoever links by hand or, for an invite, as each assignment's assigner. It also absorbs a record People created automatically for the same account. - Every role change is checked with the same rules as Auth (src/people/rules.ts): no self-grants, the right permission per kind, the Lead rule, inherited bindings and bounded delegation. Pending assignments are refused while Auth doesn't say which permissions a role grants. - The Capo Admin of reference is a relation to the Capo's record; the Capo scope is a field of the capo assignment. Closes #101 BREAKING CHANGE: the People API contract changed (records, assignments, the admins/capos/teams procedures and their inputs), and migration 0031 drops the existing People test data. Deploy together with the matching dashboard change, after PoliNetworkOrg/auth#79 and with idp:people:roles granted to the backend. --- README.md | 20 + drizzle/0031_people_records.sql | 105 + drizzle/meta/0031_snapshot.json | 3333 ++++++++++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/db/schema/people/index.ts | 170 +- src/idp/index.ts | 94 + src/index.ts | 15 +- src/people/contract.ts | 200 +- src/people/index.ts | 6 +- src/people/model.ts | 238 ++- src/people/roles.ts | 121 ++ src/people/router.ts | 36 +- src/people/rules.ts | 126 ++ src/people/service.ts | 747 +++++-- src/people/store-pg.ts | 163 +- src/people/sync.ts | 138 ++ src/people/types.ts | 109 +- tests/people-auth.ts | 121 ++ tests/people-fixtures.ts | 70 +- tests/people-postgres.fixture.ts | 152 +- tests/people-postgres.test.ts | 4 +- tests/people-router.test.ts | 9 +- tests/people-rules.test.ts | 76 + tests/people.test.ts | 520 ++++- 24 files changed, 5990 insertions(+), 590 deletions(-) create mode 100644 drizzle/0031_people_records.sql create mode 100644 drizzle/meta/0031_snapshot.json create mode 100644 src/people/roles.ts create mode 100644 src/people/rules.ts create mode 100644 src/people/sync.ts create mode 100644 tests/people-auth.ts create mode 100644 tests/people-rules.test.ts diff --git a/README.md b/README.md index cba8215..93c2284 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,26 @@ The bot's socket.io client authenticates with its service token in `auth.token` The IdP notifies `POST /internal/events` when access changes; the backend also polls the snapshot every 30 s. The last good signing keys and snapshot are stored in `common_idp_state`, so a restart during an IdP outage resumes from them. Permission checks deny once the snapshot is more than an hour old. Configuration is in `.env.example`. +## People + +The `people` router is the admin dashboard's register of Group Admins, Capo Admins and team members. Each person +is one record in `people_persons`; their roles are rows in `people_assignments`, with an append-only history in +`people_activity`. + +- **A record linked to a login account** (`account_sub`): PoliNetwork Auth is the source of truth. People reads + who holds the roles bound to People from `GET /api/internal/people-roles` (15 s cache, the last answer during an + outage of up to an hour) and creates linked records for people given a bound role by hand in Auth. Changes go to + `POST /api/internal/people-roles` through the `people_role_commands` outbox: each command has an ID Auth applies at + most once, so the cron sends it again until Auth answers. The assignment shows `sent` until Auth confirms it, and + Auth's reason when it refuses. +- **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. + +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 +serialized by one transaction lock. Grant `idp:people:roles` to the backend's OAuth client to let it change roles. + ## E-signing with the CIE The `esign` router and `/esign/agent/*` endpoints let dashboard users sign PDFs with the Italian identity card diff --git a/drizzle/0031_people_records.sql b/drizzle/0031_people_records.sql new file mode 100644 index 0000000..0e04514 --- /dev/null +++ b/drizzle/0031_people_records.sql @@ -0,0 +1,105 @@ +CREATE TABLE "people_activity" ( + "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "people_activity_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1), + "person_id" text NOT NULL, + "actor" text NOT NULL, + "text" text NOT NULL, + "at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +CREATE TABLE "people_assignments" ( + "id" uuid PRIMARY KEY NOT NULL, + "person_id" text NOT NULL, + "kind" text NOT NULL, + "team" text, + "team_role" text, + "capo_scope" text, + "capo_of_reference_id" text, + "fields" jsonb DEFAULT '{}'::jsonb NOT NULL, + "since" date NOT NULL, + "ended_on" date, + "end_reason" text, + "assigned_by" text NOT NULL, + "change" text NOT NULL, + "status" text NOT NULL, + "refusal" text, + "command_id" uuid, + CONSTRAINT "people_assignments_kind_check" CHECK ("people_assignments"."kind" in ('admin', 'capo', 'team')), + CONSTRAINT "people_assignments_team_check" CHECK (("people_assignments"."kind" = 'team') = ("people_assignments"."team" is not null and "people_assignments"."team_role" in ('member', 'lead'))), + CONSTRAINT "people_assignments_capo_ref_check" CHECK ("people_assignments"."kind" = 'admin' or "people_assignments"."capo_of_reference_id" is null), + CONSTRAINT "people_assignments_change_check" CHECK ("people_assignments"."change" in ('start', 'end')), + CONSTRAINT "people_assignments_status_check" CHECK ("people_assignments"."status" in ('pending', 'sent', 'applied', 'refused')), + CONSTRAINT "people_assignments_sent_check" CHECK (("people_assignments"."status" = 'sent') = ("people_assignments"."command_id" is not null)) +); +--> statement-breakpoint +CREATE TABLE "people_counters" ( + "key" text PRIMARY KEY NOT NULL, + "value" integer NOT NULL +); +--> statement-breakpoint +CREATE TABLE "people_invites" ( + "id" uuid PRIMARY KEY NOT NULL, + "person_id" text NOT NULL, + "token_hash" text NOT NULL, + "email" text NOT NULL, + "sent_by" text NOT NULL, + "sent_at" timestamp with time zone NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "revoked_at" timestamp with time zone, + "accepted_at" timestamp with time zone, + "accepted_by" text, + CONSTRAINT "people_invites_token_hash_unique" UNIQUE("token_hash") +); +--> statement-breakpoint +CREATE TABLE "people_mail" ( + "id" text PRIMARY KEY NOT NULL, + "person_id" text NOT NULL, + "to" text NOT NULL, + "subject" text NOT NULL, + "text" text NOT NULL, + "status" text NOT NULL, + "attempted_at" timestamp with time zone, + "error" text +); +--> statement-breakpoint +CREATE TABLE "people_persons" ( + "id" text PRIMARY KEY NOT NULL, + "first_name" text NOT NULL, + "last_name" text NOT NULL, + "contact_email" text, + "phone" text, + "telegram_username" text, + "notes" text, + "account_sub" text, + "created_by" text NOT NULL, + "created_at" timestamp with time zone NOT NULL, + "updated_by" text NOT NULL, + "updated_at" timestamp with time zone NOT NULL, + CONSTRAINT "people_persons_account_sub_unique" UNIQUE("account_sub") +); +--> statement-breakpoint +CREATE TABLE "people_role_commands" ( + "id" uuid PRIMARY KEY NOT NULL, + "person_id" text NOT NULL, + "request" jsonb NOT NULL, + "status" text NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "error" text, + "created_at" timestamp with time zone NOT NULL, + "answered_at" timestamp with time zone, + CONSTRAINT "people_role_commands_status_check" CHECK ("people_role_commands"."status" in ('queued', 'applied', 'refused')) +); +--> statement-breakpoint +DROP TABLE "people_identities" CASCADE;--> statement-breakpoint +DROP TABLE "people_records" CASCADE;--> statement-breakpoint +ALTER TABLE "people_activity" ADD CONSTRAINT "people_activity_person_id_people_persons_id_fk" FOREIGN KEY ("person_id") REFERENCES "public"."people_persons"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "people_assignments" ADD CONSTRAINT "people_assignments_person_id_people_persons_id_fk" FOREIGN KEY ("person_id") REFERENCES "public"."people_persons"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "people_assignments" ADD CONSTRAINT "people_assignments_capo_of_reference_id_people_persons_id_fk" FOREIGN KEY ("capo_of_reference_id") REFERENCES "public"."people_persons"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "people_assignments" ADD CONSTRAINT "people_assignments_command_id_people_role_commands_id_fk" FOREIGN KEY ("command_id") REFERENCES "public"."people_role_commands"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "people_invites" ADD CONSTRAINT "people_invites_person_id_people_persons_id_fk" FOREIGN KEY ("person_id") REFERENCES "public"."people_persons"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "people_mail" ADD CONSTRAINT "people_mail_person_id_people_persons_id_fk" FOREIGN KEY ("person_id") REFERENCES "public"."people_persons"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "people_role_commands" ADD CONSTRAINT "people_role_commands_person_id_people_persons_id_fk" FOREIGN KEY ("person_id") REFERENCES "public"."people_persons"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "people_activity_person_idx" ON "people_activity" USING btree ("person_id","id");--> statement-breakpoint +CREATE INDEX "people_assignments_person_idx" ON "people_assignments" USING btree ("person_id");--> statement-breakpoint +CREATE UNIQUE INDEX "people_assignments_current_idx" ON "people_assignments" USING btree ("person_id","kind",coalesce("team", '')) WHERE "people_assignments"."ended_on" is null;--> statement-breakpoint +CREATE INDEX "people_invites_person_idx" ON "people_invites" USING btree ("person_id");--> statement-breakpoint +CREATE INDEX "people_role_commands_queued_idx" ON "people_role_commands" USING btree ("created_at") WHERE "people_role_commands"."status" = 'queued'; \ No newline at end of file diff --git a/drizzle/meta/0031_snapshot.json b/drizzle/meta/0031_snapshot.json new file mode 100644 index 0000000..e0739cd --- /dev/null +++ b/drizzle/meta/0031_snapshot.json @@ -0,0 +1,3333 @@ +{ + "id": "53974741-10a4-41d5-b223-9defe715dc6a", + "prevId": "306ccd97-46c8-4260-93ca-f992b9fed731", + "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": "integer", + "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 + }, + "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 + }, + "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')" + } + }, + "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 c438380..18c63f5 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -218,6 +218,13 @@ "when": 1793284579739, "tag": "0030_people_cleanup", "breakpoints": true + }, + { + "idx": 31, + "version": "7", + "when": 1793371503277, + "tag": "0031_people_records", + "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 cf8cc24..ec102ca 100644 --- a/src/db/schema/people/index.ts +++ b/src/db/schema/people/index.ts @@ -1,26 +1,164 @@ -import { index, jsonb, text } from "drizzle-orm/pg-core" -import type { PeopleState } from "@/people/types" +import { sql } from "drizzle-orm" +import { + type AnyPgColumn, + check, + date, + index, + integer, + jsonb, + text, + timestamp, + uniqueIndex, + uuid, +} from "drizzle-orm/pg-core" +import type { TeamFields } from "@/people/contract" +import type { RoleCommand } from "@/people/roles" import { createTable } from "../create-table" -/** Small association metadata: one JSON row per person, outbox message or counter. */ -export const records = createTable.people( - "records", +const at = (name: string) => timestamp(name, { withTimezone: true, mode: "date" }) + +/** One record per person. Linked to a login account through `account_sub`, never through the contact email. */ +export const persons = createTable.people("persons", { + id: text().primaryKey(), + firstName: text("first_name").notNull(), + lastName: text("last_name").notNull(), + /** Only for sending invites. */ + contactEmail: text("contact_email"), + phone: text(), + /** Informational only. */ + telegramUsername: text("telegram_username"), + notes: text(), + accountSub: text("account_sub").unique(), + createdBy: text("created_by").notNull(), + createdAt: at("created_at").notNull(), + updatedBy: text("updated_by").notNull(), + updatedAt: at("updated_at").notNull(), +}) + +/** Role commands sent, or to be sent, to PoliNetwork Auth. Auth applies each `id` at most once. */ +export const roleCommands = createTable.people( + "role_commands", { - id: text().primaryKey(), - kind: text().$type().notNull(), - data: jsonb().$type().notNull(), + id: uuid().primaryKey(), + personId: text("person_id") + .notNull() + .references(() => persons.id), + request: jsonb().$type().notNull(), + status: text().$type<"queued" | "applied" | "refused">().notNull(), + attempts: integer().notNull().default(0), + error: text(), + createdAt: at("created_at").notNull(), + answeredAt: at("answered_at"), }, - (t) => [index("people_records_kind_idx").on(t.kind)] + (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')`), + ] ) -/** Unique identity constraints are relational, independent of the JSON projection. */ -export const identities = createTable.people("identities", { - personId: text("person_id").primaryKey(), - accountSub: text("account_sub").unique(), - telegramId: text("telegram_id").unique(), +/** Group Admin, Capo Admin, or a role in a team. At most one current assignment per concept and person. */ +export const assignments = createTable.people( + "assignments", + { + id: uuid().primaryKey(), + personId: text("person_id") + .notNull() + .references(() => persons.id), + kind: text().$type<"admin" | "capo" | "team">().notNull(), + team: text(), + teamRole: text("team_role").$type<"member" | "lead">(), + /** For `capo`, e.g. "Ingegneria Informatica". */ + capoScope: text("capo_scope"), + /** For `admin`: the record of their Capo Admin. */ + capoOfReferenceId: text("capo_of_reference_id").references((): AnyPgColumn => persons.id), + fields: jsonb().$type().notNull().default({}), + since: date({ mode: "string" }).notNull(), + endedOn: date("ended_on", { mode: "string" }), + endReason: text("end_reason"), + assignedBy: text("assigned_by").notNull(), + change: text().$type<"start" | "end">().notNull(), + status: text().$type<"pending" | "sent" | "applied" | "refused">().notNull(), + refusal: text(), + commandId: uuid("command_id").references(() => roleCommands.id), + }, + (t) => [ + index("people_assignments_person_idx").on(t.personId), + uniqueIndex("people_assignments_current_idx") + .on(t.personId, t.kind, sql`coalesce(${t.team}, '')`) + .where(sql`${t.endedOn} is null`), + check("people_assignments_kind_check", sql`${t.kind} in ('admin', 'capo', 'team')`), + check( + "people_assignments_team_check", + sql`(${t.kind} = 'team') = (${t.team} is not null and ${t.teamRole} in ('member', 'lead'))` + ), + check("people_assignments_capo_ref_check", sql`${t.kind} = 'admin' or ${t.capoOfReferenceId} is null`), + check("people_assignments_change_check", sql`${t.change} in ('start', 'end')`), + check("people_assignments_status_check", sql`${t.status} in ('pending', 'sent', 'applied', 'refused')`), + check("people_assignments_sent_check", sql`(${t.status} = 'sent') = (${t.commandId} is not null)`), + ] +) + +/** Email invites to link a record to an account. Only the token's hash is stored. */ +export const invites = createTable.people( + "invites", + { + id: uuid().primaryKey(), + personId: text("person_id") + .notNull() + .references(() => persons.id), + tokenHash: text("token_hash").notNull().unique(), + email: text().notNull(), + sentBy: text("sent_by").notNull(), + sentAt: at("sent_at").notNull(), + expiresAt: at("expires_at").notNull(), + revokedAt: at("revoked_at"), + acceptedAt: at("accepted_at"), + acceptedBy: text("accepted_by"), + }, + (t) => [index("people_invites_person_idx").on(t.personId)] +) + +/** The durable mail outbox. */ +export const mail = createTable.people("mail", { + id: text().primaryKey(), + personId: text("person_id") + .notNull() + .references(() => persons.id), + to: text().notNull(), + subject: text().notNull(), + text: text().notNull(), + status: text().$type<"pending" | "sending" | "sent" | "failed">().notNull(), + attemptedAt: at("attempted_at"), + error: text(), +}) + +/** Append-only history of changes to a record. */ +export const activity = createTable.people( + "activity", + { + /** Also orders entries written in the same instant. */ + id: integer().primaryKey().generatedAlwaysAsIdentity(), + personId: text("person_id") + .notNull() + .references(() => persons.id), + actor: text().notNull(), + text: text().notNull(), + at: at("at").notNull(), + }, + (t) => [index("people_activity_person_idx").on(t.personId, t.id)] +) + +export const counters = createTable.people("counters", { + key: text().primaryKey(), + value: integer().notNull(), }) export const schema = { - peopleRecords: records, - peopleIdentities: identities, + peoplePersons: persons, + peopleAssignments: assignments, + peopleRoleCommands: roleCommands, + peopleInvites: invites, + peopleMail: mail, + peopleActivity: activity, + peopleCounters: counters, } diff --git a/src/idp/index.ts b/src/idp/index.ts index 3f3dde5..a848dd5 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -12,12 +12,42 @@ import { import { z } from "zod" import { env } from "@/env" import { logger } from "@/logger" +import { type PeopleRoles, RoleChangeError } from "@/people/roles" import { authenticate, type RequestAuth } from "./auth" import { dbPersistence } from "./persistence" /** The projection this backend reads from the IdP (RFC v3 §5.2). */ const PROJECTION = "backend" const signerDirectory = z.array(z.object({ sub: z.string(), name: z.string(), email: z.string().nullable() })) +const boundRoles = z.array( + z.object({ + key: z.string(), + name: z.string(), + binding: z.string(), + permissions: z.array(z.string()).optional(), + bindings: z.array(z.string()).optional(), + }) +) +/** `GET /api/internal/people-roles`: the roles bound to People and who holds them. */ +const peopleDirectory = z.object({ + roles: boundRoles, + users: z.array( + z.object({ + sub: z.string(), + name: z.string(), + email: z.string().nullable(), + telegramId: z.string().nullable(), + telegramUsername: z.string().nullable(), + roles: z.array(z.string()), + assigned: z.array(z.string()), + since: z.record(z.string(), z.string().regex(/^\d{4}-\d{2}-\d{2}$/)).optional(), + }) + ), +}) +/** The person's bound roles after a role command, as `POST /api/internal/people-roles` answers. */ +const roleResult = z.object({ roles: boundRoles, held: z.array(z.string()), assigned: z.array(z.string()) }) +/** Lets the backend give and take back the roles bound to People, for the dashboard user it authenticated. */ +const PEOPLE_ROLES_SCOPE = "idp:people:roles" function report(component: string) { return (error: unknown) => { @@ -54,6 +84,7 @@ function configure() { let snapshot = null let events = null let directory: (() => Promise>) | null = null + let peopleRoles: PeopleRoles | null = null if (env.OAUTH_INTERNAL_RESOURCE_URI && env.OAUTH_BACKEND_CLIENT_ID && env.OAUTH_BACKEND_PRIVATE_JWK) { const tokens = serviceTokenSource({ clientId: env.OAUTH_BACKEND_CLIENT_ID, @@ -83,6 +114,67 @@ function configure() { if (!response.ok) throw new Error(`IdP signer directory returned ${response.status}`) return signerDirectory.parse(await response.json()) } + // A separate token, so a client not yet granted the write scope still pulls the snapshot. + const roleTokens = serviceTokenSource({ + clientId: env.OAUTH_BACKEND_CLIENT_ID, + privateKey: parsePrivateKey(env.OAUTH_BACKEND_PRIVATE_JWK), + tokenUrl: endpoints.tokenUrl, + tokenAudience: endpoints.tokenAudience, + resource: env.OAUTH_INTERNAL_RESOURCE_URI, + scopes: [PEOPLE_ROLES_SCOPE], + onError: report("people roles token source"), + }) + const peopleRolesUrl = new URL("/api/internal/people-roles", endpoints.snapshotUrl) + const sendCommand = async (body: unknown) => { + let token: string + try { + token = await roleTokens.getToken() + } catch { + throw new RoleChangeError(503, `no token to change roles; is ${PEOPLE_ROLES_SCOPE} granted to this backend?`) + } + try { + return await fetch(peopleRolesUrl, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), + }) + } catch { + throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") + } + } + peopleRoles = { + async directory() { + const token = await tokens.getToken() + const response = await fetch(peopleRolesUrl, { + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(10_000), + }) + if (response.status === 401) tokens.invalidate() + if (!response.ok) throw new Error(`IdP People roles returned ${response.status}`) + return peopleDirectory.parse(await response.json()) + }, + async change(command) { + let response = await sendCommand(command) + // A stale cached token: ask for a new one and send the same command once more. A second 401 is a refusal. + if (response.status === 401) { + roleTokens.invalidate() + response = await sendCommand(command) + if (response.status === 401) roleTokens.invalidate() + } + if (response.ok) { + // The command was applied, but without a readable answer People can't confirm it: retry it by ID. + const result = roleResult.safeParse(await response.json().catch(() => null)) + if (!result.success) throw new RoleChangeError(503, "PoliNetwork Auth sent an unreadable answer") + return result.data + } + const body = (await response.json().catch(() => null)) as { error?: unknown } | null + throw new RoleChangeError( + response.status, + typeof body?.error === "string" ? body.error : `request failed (${response.status})` + ) + }, + } events = createAccessEventHandler({ keyStore, issuer: endpoints.issuer, @@ -99,6 +191,8 @@ function configure() { keyStore, snapshot, directory, + /** The roles bound to People in Auth, and changes to them; null without a service client. */ + peopleRoles, /** Fetch API handler for `POST /internal/events`, or null without a snapshot. */ events, verify: (token: string) => verifyAccessToken(token, { issuer: endpoints.issuer, audience, keyStore }), diff --git a/src/index.ts b/src/index.ts index ccc960e..2dc356c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,17 @@ export { TRPC_PATH, WS_PATH } from "./constants" +export type { + AccountMatch as PeopleAccountMatch, + AdminSummary as PeopleAdminSummary, + Assignment as PeopleAssignment, + CapoArea as PeopleCapoArea, + CapoSummary as PeopleCapoSummary, + Invite as PeopleInvite, + MyArea as PeopleMyArea, + MyRoles as PeopleMyRoles, + PersonRecord as PeoplePersonRecord, + PersonRow as PeoplePersonRow, + TeamId as PeopleTeamId, + TeamSummary as PeopleTeamSummary, +} from "./people/contract" export type { AppRouter } from "./routers" - export type { TelegramSocket } from "./websocket/telegram" diff --git a/src/people/contract.ts b/src/people/contract.ts index df928dd..4f1d948 100644 --- a/src/people/contract.ts +++ b/src/people/contract.ts @@ -5,66 +5,28 @@ import { z } from "zod" * The admin parses responses against these shapes. Keep input/output changes coordinated with that repository. */ +/** + * The teams People knows. A team can only be assigned once PoliNetwork Auth binds a role to it + * (`team::member` / `team::lead`); see `TeamSummary.assignable`. + */ export const TEAM_IDS = ["it", "hr", "design", "intl", "events"] as const -export const CAMPUSES = ["Leonardo", "Bovisa", "Cremona", "Piacenza", "Mantova", "Lecco", "External"] as const -export const YEARS = ["1st year", "2nd year", "3rd year", "1st year MSc", "2nd year MSc", "Graduated"] as const -/** Politecnico di Milano courses offered in forms; the backend accepts any course name. */ -export const COURSES = [ - "Ingegneria Informatica", - "Computer Science and Engineering", - "Ingegneria Gestionale", - "Management Engineering", - "Ingegneria Meccanica", - "Ingegneria Aerospaziale", - "Ingegneria Energetica", - "Ingegneria Chimica", - "Ingegneria Elettronica", - "Ingegneria Biomedica", - "Ingegneria Matematica", - "Ingegneria Civile", - "Design della Comunicazione", - "Design del Prodotto Industriale", - "Design degli Interni", - "Architettura", - "Urbanistica", -] as const -export const PHOTO_CONSENTS = ["granted", "denied", "revoked"] as const export const teamIdSchema = z.enum(TEAM_IDS) -export const campusSchema = z.enum(CAMPUSES) - export type TeamId = z.infer -export type Campus = z.infer -export type PhotoConsent = (typeof PHOTO_CONSENTS)[number] const personRefSchema = z.object({ id: z.string(), name: z.string() }) +export type PersonRef = z.infer -export const profileSchema = z.object({ - firstName: z.string(), - lastName: z.string(), - /** `null` without contact rights. */ - personalEmail: z.string().nullable(), - /** `null` without contact rights. */ - phone: z.string().nullable(), - telegramUsername: z.string().nullable(), - telegramId: z.string().nullable(), - course: z.string(), - year: z.string(), - campus: campusSchema, - otherAssociations: z.array(z.string()), - studentRepresentative: z.string().nullable(), -}) - -export const adminRoleSchema = z.object({ - status: z.enum(["active", "former"]), - since: z.string(), - endedOn: z.string().nullable(), - endReason: z.string().nullable(), - availableAsCapo: z.boolean(), - capoOfReference: personRefSchema.nullable(), - /** Set when this person is a Capo Admin, e.g. "Ingegneria Informatica". */ - capoScope: z.string().nullable(), -}) +export const ASSIGNMENT_KINDS = ["admin", "capo", "team"] as const +export const TEAM_ROLES = ["member", "lead"] as const +/** + * Where an assignment stands with PoliNetwork Auth: + * - `pending`: the record is not linked to a login account, so Auth knows nothing of it yet; + * - `sent`: the change was sent to Auth, which has not confirmed it yet; + * - `applied`: Auth holds it (or, for an ending, no longer holds it); + * - `refused`: Auth refused the change; `refusal` says why. + */ +export const ASSIGNMENT_STATUSES = ["pending", "sent", "applied", "refused"] as const export const teamFieldsSchema = z.record(z.string(), z.union([z.string(), z.array(z.string())])) /** The team-specific fields a dashboard write may send: a handful of short keys and values. */ @@ -72,14 +34,33 @@ const teamFieldsInput = z .record(z.string().min(1).max(40), z.union([z.string().trim().max(200), z.array(z.string().trim().max(60)).max(20)])) .refine((fields) => Object.keys(fields).length <= 10, "Too many fields.") -export const teamMembershipSchema = z.object({ - team: teamIdSchema, - role: z.enum(["member", "lead"]), +/** Group Admin, Capo Admin, or member or Lead of a team. */ +export const assignmentSchema = z.object({ + id: z.string(), + kind: z.enum(ASSIGNMENT_KINDS), + /** Set for `team`. */ + team: teamIdSchema.nullable(), + /** Set for `team`. */ + teamRole: z.enum(TEAM_ROLES).nullable(), + /** Set for `capo`, e.g. "Ingegneria Informatica". */ + capoScope: z.string().nullable(), + /** Set for `admin`: the Capo Admin this admin answers to. */ + capoOfReference: personRefSchema.nullable(), + /** Team-specific fields, for `team`. */ + fields: teamFieldsSchema, since: z.string(), + /** `null` while current. */ endedOn: z.string().nullable(), endReason: z.string().nullable(), - fields: teamFieldsSchema, + /** The account that made the assignment, or `auth` when it was made by hand in PoliNetwork Auth. */ + assignedBy: z.string(), + /** Whether `status` is about starting or ending it. */ + change: z.enum(["start", "end"]), + status: z.enum(ASSIGNMENT_STATUSES), + /** Why PoliNetwork Auth refused the change, when `status` is `refused`. */ + refusal: z.string().nullable(), }) +export type Assignment = z.infer export const accountSchema = z.discriminatedUnion("status", [ z.object({ status: z.literal("none") }), @@ -90,28 +71,24 @@ export const accountSchema = z.discriminatedUnion("status", [ expiresOn: z.string(), sentBy: z.string(), }), - z.object({ status: z.literal("linked"), email: z.string(), via: z.string(), linkedOn: z.string(), how: z.string() }), + z.object({ status: z.literal("linked"), sub: z.string() }), ]) +export type Account = z.infer -export const consentsSchema = z.object({ - privacy: z.object({ version: z.string(), acceptedOn: z.string() }).nullable(), - photo: z.object({ status: z.enum(PHOTO_CONSENTS), on: z.string() }).nullable(), -}) - -/** One row of the People lists: everything but notes, activity and discrepancies. */ +/** One row of the People lists: everything but notes, activity and audit fields. */ export const personRowSchema = z.object({ id: z.string(), - profile: profileSchema, - admin: adminRoleSchema.nullable(), - teams: z.array(teamMembershipSchema), - consents: consentsSchema, + firstName: z.string(), + lastName: z.string(), + /** Only for sending invites, never to match accounts. `null` without contact rights. */ + contactEmail: z.string().nullable(), + /** `null` without contact rights. */ + phone: z.string().nullable(), + /** Informational only. */ + telegramUsername: z.string().nullable(), + /** `none` without `people:read`, except on one's own record. */ account: accountSchema, -}) - -export const discrepancySchema = z.object({ - kind: z.enum(["telegram-mismatch", "needs-review"]), - message: z.string(), - suggestedTelegram: z.string().nullable(), + assignments: z.array(assignmentSchema), }) export const activitySchema = z.object({ actor: z.string(), text: z.string(), at: z.string() }) @@ -119,23 +96,41 @@ export const activitySchema = z.object({ actor: z.string(), text: z.string(), at export const personRecordSchema = personRowSchema.extend({ /** `null` without `people:read`. */ notes: z.string().nullable(), - discrepancies: z.array(discrepancySchema), + /** Newest first; empty without `people:read`. */ activity: z.array(activitySchema), + createdBy: z.string(), + createdAt: z.string(), + updatedBy: z.string(), + updatedAt: z.string(), }) -export type Profile = z.infer -export type AdminRole = z.infer -export type TeamFields = z.infer -export type TeamMembership = z.infer -export type Account = z.infer -export type Consents = z.infer export type PersonRow = z.infer export type PersonRecord = z.infer -export type Discrepancy = z.infer +export type Activity = z.infer +export type TeamFields = z.infer + +export const adminSummarySchema = z.object({ + person: personRowSchema, + /** The current admin assignment. */ + admin: assignmentSchema, + /** The current Capo Admin assignment, when they are also one. */ + capo: assignmentSchema.nullable(), +}) +export type AdminSummary = z.infer + +export const capoSummarySchema = z.object({ + person: personRowSchema, + capo: assignmentSchema, + /** Current admins who have them as Capo Admin of reference. */ + admins: z.array(personRefSchema), +}) +export type CapoSummary = z.infer export const teamSummarySchema = z.object({ id: teamIdSchema, name: z.string(), + /** Whether PoliNetwork Auth binds a role to this team. Without one, nobody can be added. */ + assignable: z.object({ member: z.boolean(), lead: z.boolean() }), lead: personRefSchema.nullable(), members: z.array(personRowSchema), }) @@ -155,10 +150,7 @@ export const accountMatchSchema = z.object({ id: z.string(), name: z.string(), email: z.string(), - telegram: z.string().nullable(), - via: z.string(), linkedTo: personRefSchema.nullable(), - reason: z.enum(["same-telegram", "same-email", "similar-name"]), }) export type AccountMatch = z.infer @@ -195,7 +187,7 @@ export const myAreaSchema = z.discriminatedUnion("state", [ z.object({ id: z.string(), name: z.string(), - role: z.enum(["member", "lead"]), + role: z.enum(TEAM_ROLES), telegram: z.string().nullable(), }) ), @@ -265,6 +257,7 @@ 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) +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}$/ const telegramUsernameSchema = z @@ -276,30 +269,36 @@ const telegramUsernameSchema = z export const personInputSchema = z.object({ firstName: z.string().trim().min(1).max(80), lastName: z.string().trim().min(1).max(80), - personalEmail: z.email().max(254), + /** Empty when unknown. */ + contactEmail: z.union([z.literal(""), z.email().max(254)]), + /** Empty when unknown. */ phone: z.string().trim().max(40), + /** Empty when unknown. */ telegramUsername: telegramUsernameSchema, - course: z.string().trim().min(1).max(120), - year: z.enum(YEARS), - campus: campusSchema, }) -export const createPersonInputSchema = personInputSchema.extend({ admin: z.boolean() }) +export const createPersonInputSchema = personInputSchema export const updatePersonInputSchema = personInputSchema.extend({ id: personIdSchema }) export const setNoteInputSchema = z.object({ id: personIdSchema, note: z.string().trim().max(2000) }) -export const endAdminInputSchema = z.object({ personId: personIdSchema, reason: reasonSchema }) -export const capoScopeInputSchema = z.object({ personId: personIdSchema, scope: z.string().trim().max(120).nullable() }) +export const assignAdminInputSchema = z.object({ + personId: personIdSchema, + since: dateSchema, + capoId: personIdSchema.nullable(), +}) +export const endAssignmentInputSchema = z.object({ personId: personIdSchema, reason: reasonSchema }) export const capoRefInputSchema = z.object({ personId: personIdSchema, capoId: personIdSchema.nullable() }) +export const appointCapoInputSchema = z.object({ personId: personIdSchema, since: dateSchema, scope: capoScopeSchema }) +export const capoScopeInputSchema = z.object({ personId: personIdSchema, scope: capoScopeSchema }) export const addTeamMemberInputSchema = z.object({ teamId: teamIdSchema, personId: personIdSchema, - role: z.enum(["member", "lead"]), + role: z.enum(TEAM_ROLES), since: dateSchema, fields: teamFieldsInput, }) export const teamCandidatesInputSchema = z.object({ teamId: teamIdSchema }) -export const teamCandidateSchema = z.object({ id: z.string(), name: z.string(), course: z.string() }) +export const teamCandidateSchema = z.object({ id: z.string(), name: z.string() }) export type TeamCandidate = z.infer export const teamFieldsInputSchema = z.object({ teamId: teamIdSchema, @@ -309,25 +308,26 @@ export const teamFieldsInputSchema = z.object({ export const endTeamInputSchema = z.object({ teamId: teamIdSchema, personId: personIdSchema, - lastDay: dateSchema, reason: reasonSchema, - note: z.string().trim().max(500), }) export const personRefInputSchema = z.object({ personId: personIdSchema }) -export const searchAccountsInputSchema = z.object({ personId: personIdSchema, query: z.string().trim().max(120) }) +export const searchAccountsInputSchema = z.object({ query: z.string().trim().max(120) }) export const linkAccountInputSchema = z.object({ personId: personIdSchema, accountId: opaqueIdSchema, reason: reasonSchema, }) +export type PersonInput = z.infer export type CreatePersonInput = z.infer export type UpdatePersonInput = z.infer export type SetNoteInput = z.infer -export type EndAdminInput = z.infer -export type CapoScopeInput = z.infer +export type AssignAdminInput = z.infer +export type EndAssignmentInput = z.infer export type CapoRefInput = z.infer +export type AppointCapoInput = z.infer +export type CapoScopeInput = z.infer export type AddTeamMemberInput = z.infer export type TeamFieldsInput = z.infer export type TeamCandidatesInput = z.infer diff --git a/src/people/index.ts b/src/people/index.ts index 0568f81..446b04c 100644 --- a/src/people/index.ts +++ b/src/people/index.ts @@ -11,10 +11,8 @@ export const people = createPeopleService({ dashboardUrl: env.ESIGN_DASHBOARD_URL.replace(/\/$/, ""), async directory() { if (!idp?.directory) fail("PRECONDITION_FAILED", "The IdP account directory is not configured") - return (await idp.directory()).map((a) => ({ - ...a, - telegramId: idp?.snapshot?.current()?.bySub(a.sub)?.telegramId ?? null, - })) + return idp.directory() }, + peopleRoles: idp?.peopleRoles ?? null, sendMail: sendPeopleEmail, }) diff --git a/src/people/model.ts b/src/people/model.ts index abdbebe..de9113d 100644 --- a/src/people/model.ts +++ b/src/people/model.ts @@ -1,7 +1,8 @@ -import { createHash } from "node:crypto" +import { createHash, randomUUID } from "node:crypto" import { TRPCError } from "@trpc/server" import * as C from "./contract" -import type { PeopleState, Person, Viewer } from "./types" +import { type Concept, conceptOf } from "./roles" +import type { Activity, Assignment, Invite, PeopleState, Person, UnitOfWork, Viewer } from "./types" export function fail( code: "BAD_REQUEST" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "PRECONDITION_FAILED", @@ -9,7 +10,7 @@ export function fail( ): never { throw new TRPCError({ code, message }) } -export const nameOf = (p: Person) => `${p.profile.firstName} ${p.profile.lastName}` +export const nameOf = (p: Person) => `${p.firstName} ${p.lastName}` export const ref = (p: Person) => ({ id: p.id, name: nameOf(p) }) export const hash = (v: Uint8Array | string) => createHash("sha256").update(v).digest("hex") export const today = (now: Date) => @@ -23,7 +24,7 @@ export function find(state: PeopleState, id: string) { return state.persons[id] ?? fail("NOT_FOUND", "Person not found") } export function own(state: PeopleState, viewer: Viewer) { - return Object.values(state.persons).find((p) => p.accountSub === viewer.sub && p.account.status === "linked") ?? null + return Object.values(state.persons).find((p) => p.accountSub === viewer.sub) ?? null } export const general = (v: Viewer, permission: string) => v.can("admin:access") && v.can(permission) export function requireGeneral(v: Viewer, permission: string) { @@ -34,94 +35,106 @@ export function requireSelf(v: Viewer) { } export function requireOwn(s: PeopleState, v: Viewer) { requireSelf(v) - return own(s, v) ?? fail("FORBIDDEN", "Confirm your account link first") + return own(s, v) ?? fail("FORBIDDEN", "Your account is not linked to a People record") } -export function leads(p: Person | null, team?: C.TeamId) { - return p?.teams.filter((m) => !m.endedOn && m.role === "lead" && (!team || m.team === team)).map((m) => m.team) ?? [] + +const order = (a: Assignment) => + [a.since, C.ASSIGNMENT_KINDS.indexOf(a.kind), a.team ?? "", a.endedOn ?? "9999-12-31", a.id].join("|") +/** A person's assignments, oldest first; on the same day admin, then Capo Admin, then teams, ended ones first. */ +export function assignmentsOf(s: PeopleState, personId: string) { + return Object.values(s.assignments) + .filter((a) => a.personId === personId) + .sort((a, b) => order(a).localeCompare(order(b))) } -export function teamAccess(s: PeopleState, v: Viewer, team: C.TeamId, write: boolean) { - if (general(v, write ? "people:write" : "people:read")) return - if (!v.can("people:self") || !leads(own(s, v), team).length) fail("FORBIDDEN", "You do not lead this team") +/** The current assignment of a concept: shown as current, even while Auth hasn't confirmed it. */ +export function current(s: PeopleState, personId: string, concept: Concept) { + return assignmentsOf(s, personId).find((a) => !a.endedOn && conceptOf(a) === concept) ?? null } -export function log(p: Person, actor: string, text: string, now: Date) { - p.activity.unshift({ actor, text, at: now.toISOString() }) +/** Current and in effect: not a start still waiting for Auth. */ +export const confirmed = (a: Assignment) => !a.endedOn && !(a.change === "start" && a.status === "sent") +export function confirmedOf(s: PeopleState, personId: string, concept: Concept) { + const a = current(s, personId, concept) + return a && confirmed(a) ? a : null } -export function row(s: PeopleState, p: Person, v: Viewer, scopedContacts = false): C.PersonRow { - const self = own(s, v)?.id === p.id - const contacts = self || general(v, "people:read") || scopedContacts - return C.personRowSchema.parse({ - ...p, - profile: { - ...p.profile, - personalEmail: contacts ? p.profile.personalEmail : null, - phone: contacts ? p.profile.phone : null, - }, - account: self || general(v, "people:read") ? p.account : { status: "none" }, - }) +/** Teams the person leads, as far as People knows. Authorization reads Auth instead. */ +export function leadsOf(s: PeopleState, personId: string) { + return assignmentsOf(s, personId).flatMap((a) => + a.kind === "team" && a.teamRole === "lead" && confirmed(a) ? [a.team as C.TeamId] : [] + ) } -export function record(s: PeopleState, p: Person, v: Viewer): C.PersonRecord { - const read = general(v, "people:read") - return C.personRecordSchema.parse({ - ...row(s, p, v), - notes: read ? p.notes : null, - discrepancies: read ? p.discrepancies : [], - activity: read ? p.activity : [], - }) +/** Whether a change for the person waits for Auth: a new one could be applied before it. */ +export const waiting = (s: PeopleState, personId: string) => + Object.values(s.commands).some((c) => c.personId === personId && c.status === "queued") + +export function log(u: UnitOfWork, personId: string, actor: string, text: string, now: Date) { + u.activity.push({ personId, actor, text, at: now.toISOString() }) } -export function newPerson(s: PeopleState, input: C.CreatePersonInput, date: string): Person { - const sequence = (s.counters.person ?? 0) + 1 - if (sequence > 9999) fail("PRECONDITION_FAILED", "The admin's four-digit person ID space is exhausted") - s.counters.person = sequence +/** Once a Capo Admin's appointment has ended, the admins who had them as reference have none. */ +export function clearCapoReferences(u: UnitOfWork, capoId: string, actor: string, now: Date) { + for (const a of Object.values(u.state.assignments)) { + if (a.kind !== "admin" || a.endedOn || a.capoOfReferenceId !== capoId) continue + a.capoOfReferenceId = null + log(u, a.personId, actor, `Their Capo Admin of reference, ${capoId}, ended`, now) + } +} + +const blank = (value: string) => value.trim() || null +/** The next `P-0000` ID, or null once the four digits are used up. */ +export function nextPersonId(s: PeopleState) { + const sequence = Math.max(0, ...Object.keys(s.persons).map((id) => Number(id.slice(2)))) + 1 + return sequence > 9999 ? null : `P-${String(sequence).padStart(4, "0")}` +} +export function newPerson(s: PeopleState, input: C.PersonInput, actor: string, now: Date): Person { + const at = now.toISOString() const p: Person = { - id: `P-${String(sequence).padStart(4, "0")}`, - profile: { - ...input, - phone: input.phone || null, - telegramUsername: input.telegramUsername || null, - telegramId: null, - otherAssociations: [], - studentRepresentative: null, - }, - admin: input.admin - ? { - status: "active", - since: date, - endedOn: null, - endReason: null, - availableAsCapo: false, - capoOfReference: null, - capoScope: null, - } - : null, - teams: [], - consents: { privacy: null, photo: null }, - account: { status: "none" }, + id: nextPersonId(s) ?? fail("PRECONDITION_FAILED", "The four-digit person ID space is exhausted"), + firstName: input.firstName, + lastName: input.lastName, + contactEmail: blank(input.contactEmail), + phone: blank(input.phone), + telegramUsername: blank(input.telegramUsername), notes: null, - discrepancies: [], - activity: [], accountSub: null, - invite: null, + createdBy: actor, + createdAt: at, + updatedBy: actor, + updatedAt: at, } s.persons[p.id] = p return p } -export function queue(s: PeopleState, p: Person, id: string, to: string, subject: string, text: string) { - if (s.outbox[id]?.status === "failed") { - s.outbox[id].status = "pending" - s.outbox[id].attemptedAt = null - s.outbox[id].error = null - } - s.outbox[id] ??= { - id, - personId: p.id, - to, - subject, - text, - status: "pending", - attemptedAt: null, - error: null, +export function touch(p: Person, actor: string, now: Date) { + p.updatedBy = actor + p.updatedAt = now.toISOString() +} + +export function newAssignment( + s: PeopleState, + fields: Pick & Partial +): Assignment { + const a: Assignment = { + id: randomUUID(), + team: null, + teamRole: null, + capoScope: null, + capoOfReferenceId: null, + fields: {}, + endedOn: null, + endReason: null, + change: "start", + refusal: null, + commandId: null, + ...fields, } + s.assignments[a.id] = a + return a } + +export function queueMail(s: PeopleState, personId: string, id: string, to: string, subject: string, text: string) { + if (s.mail[id]?.status === "failed") Object.assign(s.mail[id], { status: "pending", attemptedAt: null, error: null }) + s.mail[id] ??= { id, personId, to, subject, text, status: "pending", attemptedAt: null, error: null } +} + export function validateFields(team: C.TeamId, fields: C.TeamFields) { for (const [key, value] of Object.entries(fields)) { const spec = C.TEAMS[team].fields.find((f) => f.key === key) @@ -136,3 +149,74 @@ export function validateFields(team: C.TeamId, fields: C.TeamFields) { fail("BAD_REQUEST", "Invalid team option") } } + +/** The person's open invite: not revoked, accepted or superseded. */ +export function openInvite(s: PeopleState, personId: string): Invite | null { + return ( + Object.values(s.invites) + .filter((i) => i.personId === personId && !i.revokedAt && !i.acceptedAt) + .sort((a, b) => (a.sentAt < b.sentAt ? 1 : -1))[0] ?? null + ) +} + +function account(s: PeopleState, p: Person): C.Account { + if (p.accountSub) return { status: "linked", sub: p.accountSub } + const invite = openInvite(s, p.id) + return invite + ? { + status: "invite", + email: invite.email, + sentOn: invite.sentAt.slice(0, 10), + expiresOn: invite.expiresAt.slice(0, 10), + sentBy: invite.sentBy, + } + : { status: "none" } +} + +export function assignmentView(s: PeopleState, a: Assignment): C.Assignment { + const capo = a.capoOfReferenceId ? s.persons[a.capoOfReferenceId] : null + return { + id: a.id, + kind: a.kind, + team: a.team, + teamRole: a.teamRole, + capoScope: a.capoScope, + capoOfReference: capo ? ref(capo) : null, + fields: a.fields, + since: a.since, + endedOn: a.endedOn, + endReason: a.endReason, + assignedBy: a.assignedBy, + change: a.change, + status: a.status, + refusal: a.refusal, + } +} + +export function row(s: PeopleState, p: Person, v: Viewer, scopedContacts = false): C.PersonRow { + const self = !!p.accountSub && p.accountSub === v.sub + const read = general(v, "people:read") + const contacts = self || read || scopedContacts + return C.personRowSchema.parse({ + id: p.id, + firstName: p.firstName, + lastName: p.lastName, + contactEmail: contacts ? p.contactEmail : null, + phone: contacts ? p.phone : null, + telegramUsername: p.telegramUsername, + account: self || read ? account(s, p) : { status: "none" }, + assignments: assignmentsOf(s, p.id).map((a) => assignmentView(s, a)), + }) +} +export function record(s: PeopleState, p: Person, v: Viewer, activity: Activity[]): C.PersonRecord { + const read = general(v, "people:read") + return C.personRecordSchema.parse({ + ...row(s, p, v), + notes: read ? p.notes : null, + activity: read ? activity.map(({ actor, text, at }) => ({ actor, text, at })) : [], + createdBy: p.createdBy, + createdAt: p.createdAt, + updatedBy: p.updatedBy, + updatedAt: p.updatedAt, + }) +} diff --git a/src/people/roles.ts b/src/people/roles.ts new file mode 100644 index 0000000..be00fe7 --- /dev/null +++ b/src/people/roles.ts @@ -0,0 +1,121 @@ +import * as C from "./contract" +import { type BoundRole, type PeopleBinding, parsePeopleBinding } from "./rules" + +/** + * Roles in PoliNetwork Auth bound to People: `admin`, `capo`, `team::member` or `team::lead`. + * For a linked record Auth is the source of truth for who holds them: People reads them with `directory` + * and changes them with `change`, which Auth checks again against the acting dashboard user's access. + */ +export type RoleDirectory = { + roles: BoundRole[] + users: DirectoryUser[] +} +export type DirectoryUser = { + sub: string + name: string + /** Their PoliNetwork address when they linked it, otherwise their sign-in address. */ + email: string | null + telegramId: string | null + telegramUsername: string | null + /** Bound roles held, including through a parent role. */ + roles: string[] + /** Those given directly, the only ones a change can take back. */ + assigned: string[] + /** When each held role was first given (`YYYY-MM-DD`), when Auth says. */ + since?: Record +} +export type RoleCommandChange = + | { kind: "admin"; active: boolean } + | { kind: "capo"; active: boolean } + | { kind: "team"; team: C.TeamId; role: C.Assignment["teamRole"] } +/** `POST /api/internal/people-roles`: idempotent by `id`, applied all-or-nothing. */ +export type RoleCommand = { + id: string + /** The dashboard user Auth checks the change against. */ + actor: string + sub: string + reason: string + changes: RoleCommandChange[] +} +export type RoleResult = { roles: BoundRole[]; held: string[]; assigned: string[] } +export type PeopleRoles = { + directory(): Promise + change(command: RoleCommand): Promise +} + +/** PoliNetwork Auth refused or failed a role change; `status` is its HTTP status. */ +export class RoleChangeError extends Error { + constructor( + readonly status: number, + message: string + ) { + super(message) + } + /** + * No usable answer: the command may or may not have been applied, so it is sent again with the same ID. + * Auth refusing the backend itself (a token it doesn't accept, or a client that isn't the backend's) is a + * configuration problem, not a refusal of the change, so it counts too. + */ + get unanswered() { + return ( + this.status >= 500 || + this.status === 408 || + this.status === 429 || + this.status === 401 || + (this.status === 403 && this.message === "Forbidden") + ) + } +} + +type TeamRole = NonNullable +/** One thing a person can hold: being an admin, a Capo Admin, or a role in one team. */ +export type Concept = "admin" | "capo" | `team:${C.TeamId}` +/** What a person holds per concept. */ +export type RoleView = { admin: boolean; capo: boolean; teams: Partial> } + +const isTeam = (value: string): value is C.TeamId => (C.TEAM_IDS as readonly string[]).includes(value) + +export const conceptOf = (a: { kind: C.Assignment["kind"]; team: C.TeamId | null }): Concept => + a.kind === "team" ? `team:${a.team as C.TeamId}` : a.kind + +/** The bound roles for one binding, e.g. `team:it:lead`. More than one makes the concept ambiguous. */ +export function rolesFor(roles: readonly BoundRole[], binding: string) { + return roles.filter((role) => role.binding === binding) +} + +/** The bindings of the roles in `held`, ignoring teams People doesn't know. */ +export function bindingsOf(roles: readonly BoundRole[], held: readonly string[]): PeopleBinding[] { + return roles.flatMap((role) => { + if (!held.includes(role.key)) return [] + const binding = parsePeopleBinding(role.binding) + return binding && (binding.kind !== "team" || isTeam(binding.team)) ? [binding] : [] + }) +} + +/** What these roles mean in People; a Lead role wins over a member one. */ +export function viewOf(roles: readonly BoundRole[], held: readonly string[]): RoleView { + const view: RoleView = { admin: false, capo: false, teams: {} } + for (const binding of bindingsOf(roles, held)) { + if (binding.kind === "team") { + const team = binding.team as C.TeamId + if (view.teams[team] !== "lead") view.teams[team] = binding.role + } else view[binding.kind] = true + } + return view +} + +/** Whether Auth binds a role to the concept, so People may assign it. */ +export function isBound(roles: readonly BoundRole[], concept: Concept) { + if (concept === "admin" || concept === "capo") return rolesFor(roles, concept).length > 0 + return C.TEAM_ROLES.some((role) => rolesFor(roles, `${concept}:${role}`).length > 0) +} + +/** When Auth first gave one of these roles, or `fallback` when it doesn't say. */ +export function sinceOf(keys: readonly string[], since: Record | undefined, fallback: string) { + return ( + keys + .map((key) => since?.[key]) + .filter((day): day is string => !!day) + .sort()[0] ?? fallback + ) +} diff --git a/src/people/router.ts b/src/people/router.ts index bf84206..1999b81 100644 --- a/src/people/router.ts +++ b/src/people/router.ts @@ -7,11 +7,25 @@ import { requireGeneral } from "./model" import type { PeopleService } from "./service" import type { Viewer } from "./types" -/** Factory keeps policy and shape tests independent of databases and external services. */ +/** + * Factory keeps policy and shape tests independent of databases and external services. + * + * The service checks every role change again with the same rules as PoliNetwork Auth (`rules.ts`). Team changes + * are open to every dashboard user here, since a team's Lead may add and remove its members. + */ export function createPeopleRouter(people: PeopleService) { const user = policy({ user: { scope: SCOPE.admin } }).use(async ({ ctx, next }) => { if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) - const viewer: Viewer = { sub: ctx.actor.sub, telegramId: ctx.actor.telegramId, can: ctx.can } + const sub = ctx.actor.sub + const viewer: Viewer = { + sub, + telegramId: ctx.actor.telegramId, + can: ctx.can, + holdsRole: (role) => { + const index = ctx.access?.current() + return !!index && index.hasRole(index.bySub(sub), role) + }, + } return next({ ctx: { viewer } }) }) const admin = (permission: string) => @@ -25,6 +39,7 @@ export function createPeopleRouter(people: PeopleService) { }) const read = admin("people:read") const write = admin("people:write") + const appoint = admin("people:appoint") return createTRPCRouter({ persons: createTRPCRouter({ list: read.output(C.personRowSchema.array()).query(({ ctx }) => people.listPeople(ctx.viewer)), @@ -42,14 +57,23 @@ export function createPeopleRouter(people: PeopleService) { setNote: write.input(C.setNoteInputSchema).mutation(({ ctx, input }) => people.setNote(ctx.viewer, input)), }), admins: createTRPCRouter({ - end: write.input(C.endAdminInputSchema).mutation(({ ctx, input }) => people.endAdmin(ctx.viewer, input)), - setCapoScope: admin("people:appoint") - .input(C.capoScopeInputSchema) - .mutation(({ ctx, input }) => people.setCapoScope(ctx.viewer, input)), + list: read.output(C.adminSummarySchema.array()).query(({ ctx }) => people.listAdmins(ctx.viewer)), + assign: write.input(C.assignAdminInputSchema).mutation(({ ctx, input }) => people.assignAdmin(ctx.viewer, input)), + end: write.input(C.endAssignmentInputSchema).mutation(({ ctx, input }) => people.endAdmin(ctx.viewer, input)), setCapoOfReference: write .input(C.capoRefInputSchema) .mutation(({ ctx, input }) => people.setCapoOfReference(ctx.viewer, input)), }), + capos: createTRPCRouter({ + list: read.output(C.capoSummarySchema.array()).query(({ ctx }) => people.listCapos(ctx.viewer)), + appoint: appoint + .input(C.appointCapoInputSchema) + .mutation(({ ctx, input }) => people.appointCapo(ctx.viewer, input)), + setScope: appoint + .input(C.capoScopeInputSchema) + .mutation(({ ctx, input }) => people.setCapoScope(ctx.viewer, input)), + end: appoint.input(C.endAssignmentInputSchema).mutation(({ ctx, input }) => people.endCapo(ctx.viewer, input)), + }), teams: createTRPCRouter({ list: user.output(C.teamSummarySchema.array()).query(({ ctx }) => people.listTeams(ctx.viewer)), candidates: user diff --git a/src/people/rules.ts b/src/people/rules.ts new file mode 100644 index 0000000..08016da --- /dev/null +++ b/src/people/rules.ts @@ -0,0 +1,126 @@ +/** + * Who may give or take back a People role, kept shaped like PoliNetwork Auth's own rules + * (`src/auth/people-binding.ts` in PoliNetworkOrg/auth): one rule per binding kind, with self-grants + * and bounded delegation checked around them. + * + * Auth checks every change again when it applies it. The backend applies these rules too because it is + * the only gate for assignments on records that aren't linked yet: Auth first sees those when the record + * is linked. A rule added on one side (for example "a Capo Admin may add or remove the admins under + * them") must be added on the other in the same shape. + */ + +/** What holding a role means in People. Mirrors Auth's `PeopleBinding`. */ +export type PeopleBinding = + | { kind: "admin" } + | { kind: "capo" } + | { kind: "team"; team: string; role: "member" | "lead" } + +/** Mirrors Auth's `PEOPLE_BINDING_PATTERN` and its `role_people_binding_check` constraint. */ +export const PEOPLE_BINDING_PATTERN = /^(admin|capo|team:[a-z0-9-]{1,32}:(member|lead))$/ + +export function parsePeopleBinding(value: string | null | undefined): PeopleBinding | null { + if (!value || !PEOPLE_BINDING_PATTERN.test(value)) return null + if (value === "admin" || value === "capo") return { kind: value } + const [, team, role] = value.split(":") + return { kind: "team", team, role: role as "member" | "lead" } +} + +export function bindingKey(binding: PeopleBinding) { + return binding.kind === "team" ? `team:${binding.team}:${binding.role}` : binding.kind +} + +export const ADMIN_ACCESS_PERMISSION = "admin:access" +export const PEOPLE_WRITE_PERMISSION = "people:write" +export const PEOPLE_APPOINT_PERMISSION = "people:appoint" +/** Holds every permission, so bounded delegation never limits them. */ +export const MASTER_ADMIN_ROLE = "master-admin" + +/** A role bound to People, as `GET /api/internal/people-roles` describes it. */ +export type BoundRole = { + key: string + name: string + binding: string + /** Every permission the role grants, including through parent roles, when Auth says. */ + permissions?: string[] + /** Its own binding and those of the roles it inherits, when Auth says. */ + bindings?: string[] +} + +export type PeopleRoleChange = { + actor: { sub: string; can: (permission: string) => boolean; holdsRole: (role: string) => boolean } + /** The bindings of the roles the actor holds in Auth, including through a parent role. */ + held: PeopleBinding[] + /** The account of the record being changed; null while it isn't linked. */ + targetSub: string | null + role: BoundRole + action: "assign" | "unassign" + /** + * What to do when Auth didn't say which permissions the role grants or which bindings it inherits. `defer` + * for a linked record, where Auth checks when it applies the change; `refuse` for giving a role on one + * that isn't linked, where nobody else will before the link. Ending such an assignment never reaches Auth. + */ + unknownPermissions: "defer" | "refuse" +} + +type PeopleRuleContext = PeopleRoleChange & { + binding: B + /** Whether the actor holds `admin:access` and `permission`. */ + general: (permission: string) => boolean +} +type PeopleRule = (context: PeopleRuleContext) => string | null + +const NEEDS_WRITE = "Changing this role needs people:write and admin:access." +const NEEDS_WRITE_OR_LEAD = "Changing this role needs people:write and admin:access, or leading the team." +const NEEDS_APPOINT = "Appointing or ending a Lead needs people:appoint and admin:access." +const NEEDS_APPOINT_CAPO = "Appointing or ending a Capo Admin needs people:appoint and admin:access." + +/** One rule per binding kind, as in Auth: why the actor may not, or null when they may. */ +export const PEOPLE_RULES: { + [K in PeopleBinding["kind"]]: PeopleRule> +} = { + admin: ({ general }) => (general(PEOPLE_WRITE_PERMISSION) ? null : NEEDS_WRITE), + capo: ({ general }) => (general(PEOPLE_APPOINT_PERMISSION) ? null : NEEDS_APPOINT_CAPO), + team: ({ binding, general, held }) => { + if (binding.role === "lead") return general(PEOPLE_APPOINT_PERMISSION) ? null : NEEDS_APPOINT + // A team's Lead may also add and remove that team's members. + const leads = held.some((entry) => entry.kind === "team" && entry.team === binding.team && entry.role === "lead") + return general(PEOPLE_WRITE_PERMISSION) || leads ? null : NEEDS_WRITE_OR_LEAD + }, +} + +function ruleProblem(context: PeopleRuleContext): string | null { + const rule = PEOPLE_RULES[context.binding.kind] as PeopleRule + return rule(context) +} + +/** + * Whether the actor may give or take back `role`; a reason when not. The same checks, in the same + * order, as Auth's `peopleRoleChangeProblem`: + * - nobody gives themselves a role; giving one up is always allowed; + * - the rule of the role's binding kind, and of every binding it inherits; + * - bounded delegation: unless Master Admin, the actor must already hold every permission the role grants. + */ +export function peopleRoleChangeProblem(change: PeopleRoleChange): string | null { + const { actor, targetSub, role, action } = change + const own = parsePeopleBinding(role.binding) + if (!own) return "This role is not managed from People." + if (targetSub === actor.sub) return action === "unassign" ? null : "Nobody can give themselves a role." + + const general = (key: string) => actor.can(ADMIN_ACCESS_PERMISSION) && actor.can(key) + const unknown = change.unknownPermissions === "refuse" && action === "assign" && (!role.permissions || !role.bindings) + // The role's own rule first, so a refusal names what the role itself needs. + const inherited = (role.bindings ?? []).flatMap((value) => { + const binding = parsePeopleBinding(value) + return binding && bindingKey(binding) !== bindingKey(own) ? [binding] : [] + }) + for (const binding of [own, ...inherited]) { + const refused = ruleProblem({ ...change, binding, general }) + if (refused) return refused + } + + if (actor.holdsRole(MASTER_ADMIN_ROLE)) return null + if (unknown) + return "PoliNetwork Auth didn't say which permissions this role grants, so it can't be given before the record is linked." + const missing = (role.permissions ?? []).filter((key) => !actor.can(key)) + return missing.length ? `This role grants permissions you do not hold (${missing.join(", ")}).` : null +} diff --git a/src/people/service.ts b/src/people/service.ts index 9d1b9be..cd5f935 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -1,50 +1,358 @@ -import { randomBytes } from "node:crypto" +import { randomBytes, randomUUID } from "node:crypto" import * as C from "./contract" import { + assignmentsOf, + clearCapoReferences, + confirmed, + confirmedOf, + current, fail, find, general, hash, - leads, + leadsOf, log, nameOf, + newAssignment, newPerson, + openInvite, own, - queue, + queueMail, record, ref, requireGeneral, requireOwn, requireSelf, row, - teamAccess, today, + touch, validateFields, + waiting, } from "./model" -import type { Account, PeopleState, PeopleStore, Person, UnitOfWork, Viewer } from "./types" +import { + bindingsOf, + type Concept, + conceptOf, + type PeopleRoles, + RoleChangeError, + type RoleCommand, + type RoleDirectory, + type RoleResult, + rolesFor, +} from "./roles" +import { type BoundRole, peopleRoleChangeProblem } from "./rules" +import { reconcile, syncDirectory } from "./sync" +import type { Account, Assignment, PeopleStore, Person, UnitOfWork, Viewer } from "./types" export type PeopleOptions = { store: PeopleStore /** Dashboard origin, for links in emails. */ dashboardUrl: string now?: () => Date + /** IdP login accounts, to link a record by hand. */ directory: () => Promise + /** Who holds the roles bound to People, and changes to them; null when Auth isn't configured. */ + peopleRoles: PeopleRoles | null sendMail: (mail: { id: string; to: string; subject: string; text: string }) => Promise } +/** How long People reuses Auth's answer about who holds which role. It stores no copy of it. */ +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." + +const refusalCode = (status: number) => + status === 403 ? "FORBIDDEN" : status === 404 ? "NOT_FOUND" : status === 409 ? "CONFLICT" : "PRECONDITION_FAILED" + export function createPeopleService(options: PeopleOptions) { - const { store, dashboardUrl } = options + const { store, dashboardUrl, peopleRoles } = options const now = options.now ?? (() => new Date()) const date = () => today(now()) - const tx = (fn: (u: UnitOfWork) => Promise | T) => store.transaction(async (u) => fn(u)) - function link(s: PeopleState, p: Person, account: Account, actor: string, reason: string) { - if (Object.values(s.persons).some((other) => other.id !== p.id && other.accountSub === account.sub)) - fail("CONFLICT", "This account is already linked to another person") - if (p.accountSub && p.accountSub !== account.sub) fail("CONFLICT", "Unlink the existing account first") - p.accountSub = account.sub - p.account = { status: "linked", email: account.email ?? "", via: "IdP", linkedOn: date(), how: reason } - p.invite = null - log(p, actor, `Linked account ${account.sub}: ${reason}`, now()) + const clock = () => ({ date: date(), now: now() }) + + type Read = { value: RoleDirectory; at: number; revision: number } + /** The last good answer. Kept while stale, as the fallback during an outage. */ + 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 { + if (!peopleRoles) return null + const at = now().getTime() + if (!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 { + directoryRead = { value: await peopleRoles.directory(), at, revision } + stale = false + } catch (error) { + if (!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) + } + return directoryRead + } + const bumpRevision = (u: UnitOfWork) => { + u.state.counters.roleRevision = (u.state.counters.roleRevision ?? 0) + 1 + } + + type Ctx = { + /** 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 + } + /** 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() + const deliveries: { id: string; strict: boolean }[] = [] + const result = await store.transaction(async (u) => { + if (read) { + // An older answer than the register's last confirmation would undo it: read again next time. + if (read.revision === (u.state.counters.roleRevision ?? 0)) syncDirectory(u, read.value, clock()) + else stale = true + } + return fn(u, { + directory: read?.value ?? null, + send(personId, command, strict) { + u.state.commands[command.id] = { + id: command.id, + personId, + request: command, + status: "queued", + attempts: 0, + error: null, + createdAt: now().toISOString(), + answeredAt: null, + } + deliveries.push({ id: command.id, strict }) + }, + }) + }) + for (const delivery of deliveries) { + const refused = await deliver(delivery.id) + if (refused && delivery.strict) fail(refusalCode(refused.status), `PoliNetwork Auth: ${refused.message}`) + } + return result + } + + /** + * Sends a queued role command and applies Auth's answer; returns Auth's refusal. Without an answer the command + * stays queued, and the sweep sends it again with the same ID, which Auth applies at most once. + */ + async function deliver(id: string): Promise { + const [pending, revision] = await store.transaction(async (u) => [ + structuredClone(u.state.commands[id]), + u.state.counters.roleRevision ?? 0, + ]) + if (!pending || pending.status !== "queued" || !peopleRoles) return null + let result: RoleResult + try { + result = await peopleRoles.change(pending.request) + } catch (error) { + if (!(error instanceof RoleChangeError)) console.error(error) + const failure = error instanceof RoleChangeError ? error : new RoleChangeError(503, "No answer") + await store.transaction(async (u) => { + const command = u.state.commands[id] + if (command?.status !== "queued") return + command.attempts += 1 + command.error = failure.message + if (failure.unanswered) { + if (command.attempts === 1) + log( + u, + command.personId, + "system", + `PoliNetwork Auth didn't answer (${failure.message}); the change will be sent again`, + now() + ) + return + } + command.status = "refused" + command.answeredAt = now().toISOString() + 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" }) + else Object.assign(a, { endedOn: null, endReason: null }) + Object.assign(a, { status: "refused", refusal: failure.message, commandId: null }) + } + log(u, command.personId, command.request.actor, `PoliNetwork Auth refused: ${failure.message}`, now()) + bumpRevision(u) + }) + return failure.unanswered ? null : failure + } + 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 + 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)) + clearCapoReferences(u, command.personId, command.request.actor, now()) + 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 + } + + /** The single role Auth binds to `binding`, or why People can't use it. */ + function boundRole(directory: RoleDirectory | null, binding: string, action: "assign" | "unassign"): BoundRole { + if (!directory) fail("PRECONDITION_FAILED", "PoliNetwork Auth isn't configured: People can't change roles") + const roles = rolesFor(directory.roles, binding) + if (roles.length > 1) fail("CONFLICT", `More than one role is bound to ${binding} in PoliNetwork Auth.`) + if (roles[0]) return roles[0] + // An assignment from before its concept was bound only ever existed in People. + if (action === "unassign") return { key: "", name: binding, binding, permissions: [] } + return fail("BAD_REQUEST", `No role is bound to ${binding} in PoliNetwork Auth, so it can't be assigned.`) + } + /** The gate for every role change, with the same rules as Auth: see `rules.ts`. */ + function authorize(ctx: Ctx, u: UnitOfWork, v: Viewer, p: Person, binding: string, action: "assign" | "unassign") { + const role = boundRole(ctx.directory, binding, action) + const directory = ctx.directory as RoleDirectory + const problem = peopleRoleChangeProblem({ + actor: v, + held: bindingsOf(directory.roles, directory.users.find((user) => user.sub === v.sub)?.roles ?? []), + targetSub: p.accountSub, + role, + action, + unknownPermissions: p.accountSub ? "defer" : "refuse", + }) + if (problem) fail("FORBIDDEN", problem) + if (p.accountSub && waiting(u.state, p.id)) fail("CONFLICT", WAITING) + } + + /** What the record now wants for each concept, as Auth's command expects it. */ + function desired(u: UnitOfWork, p: Person, concepts: Concept[]): RoleCommand["changes"] { + return concepts.map((concept) => { + const a = current(u.state, p.id, concept) + if (concept === "admin" || concept === "capo") return { kind: concept, active: !!a } + return { kind: "team", team: concept.slice("team:".length) as C.TeamId, role: a?.teamRole ?? null } + }) + } + /** + * After the assignments of `p` changed: a linked record sends them to Auth as one command, acting as `actor`; + * one that isn't linked keeps them pending. + */ + function push(u: UnitOfWork, ctx: Ctx, p: Person, changed: Assignment[], actor: string, reason: string) { + if (!p.accountSub) { + for (const a of changed) a.status = "pending" + return + } + const id = randomUUID() + const concepts = [...new Set(changed.map(conceptOf))] + ctx.send( + p.id, + { id, actor, sub: p.accountSub, reason: reason.slice(0, 500), changes: desired(u, p, concepts) }, + true + ) + for (const a of changed) Object.assign(a, { status: "sent", refusal: null, commandId: id }) + } + function start( + u: UnitOfWork, + v: Viewer, + p: Person, + fields: Pick & Partial + ) { + if (fields.since > date()) fail("BAD_REQUEST", "Start date is in the future") + return newAssignment(u.state, { personId: p.id, assignedBy: v.sub, status: "pending", ...fields }) + } + function end(a: Assignment, reason: string) { + Object.assign(a, { endedOn: date(), endReason: reason, change: "end" }) + return a + } + /** Delivers commands queued for linked records whose pending assignments must now reach Auth. */ + function sendPending(u: UnitOfWork, ctx: Ctx, p: Person, actorOf: (a: Assignment) => string, reason: string) { + const byActor = new Map() + for (const a of assignmentsOf(u.state, p.id)) + if (!a.endedOn && a.status === "pending") byActor.set(actorOf(a), [...(byActor.get(actorOf(a)) ?? []), a]) + // One command per actor, since Auth checks each against whoever acts. + for (const [actor, assignments] of byActor) { + const id = randomUUID() + const concepts = [...new Set(assignments.map(conceptOf))] + const command = { id, actor, sub: p.accountSub as string, reason: reason.slice(0, 500) } + ctx.send(p.id, { ...command, changes: desired(u, p, concepts) }, false) + for (const a of assignments) Object.assign(a, { status: "sent", commandId: id }) + } + } + /** A record People created for a role given in Auth, which nobody has worked on since. */ + function automatic(u: UnitOfWork, p: Person) { + return ( + p.createdBy === "auth" && + p.updatedBy === "auth" && + !p.notes && + !waiting(u.state, p.id) && + !Object.values(u.state.invites).some((i) => i.personId === p.id) && + !Object.values(u.state.mail).some((m) => m.personId === p.id) + ) + } + /** + * Folds the automatic record of an account into the record being linked to it: its assignments and history + * move over, and where both have a current assignment for a concept the one Auth holds stays, taking the + * other's People data. Records made by people are never merged. + */ + function absorb(u: UnitOfWork, p: Person, other: Person, actor: string) { + const s = u.state + for (const a of assignmentsOf(s, other.id)) { + const mine = a.endedOn ? null : current(s, p.id, conceptOf(a)) + if (mine) { + a.fields = Object.keys(a.fields).length ? a.fields : mine.fields + a.capoScope ??= mine.capoScope + a.capoOfReferenceId ??= mine.capoOfReferenceId === other.id ? null : mine.capoOfReferenceId + end(mine, "Already held in PoliNetwork Auth") + } + a.personId = p.id + } + for (const a of Object.values(s.assignments)) if (a.capoOfReferenceId === other.id) a.capoOfReferenceId = p.id + for (const c of Object.values(s.commands)) if (c.personId === other.id) c.personId = p.id + p.contactEmail ??= other.contactEmail + p.telegramUsername ??= other.telegramUsername + delete s.persons[other.id] + 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) { + 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}`) + if (other) { + other.accountSub = null + absorb(u, p, other, actor) + } + p.accountSub = sub + 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()) + return p + } + + function capoOf(u: UnitOfWork, capoId: string | null, personId: string) { + if (!capoId) return null + const capo = find(u.state, capoId) + if (capo.id === personId || !confirmedOf(u.state, capo.id, "capo")) + fail("BAD_REQUEST", "Choose a current Capo Admin") + return capo.id + } + 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. */ + 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") } return { @@ -54,13 +362,14 @@ export function createPeopleService(options: PeopleOptions) { }, async getPerson(v: Viewer, input: { id: string }) { requireGeneral(v, "people:read") - return tx((u) => record(u.state, find(u.state, input.id), v)) + const activity = await store.activity(input.id) + return tx((u) => record(u.state, find(u.state, input.id), v, activity)) }, async createPerson(v: Viewer, input: C.CreatePersonInput) { requireGeneral(v, "people:write") return tx((u) => { - const p = newPerson(u.state, input, date()) - log(p, v.sub, "Created person", now()) + const p = newPerson(u.state, input, v.sub, now()) + log(u, p.id, v.sub, "Created the record", now()) return { id: p.id } }) }, @@ -68,9 +377,15 @@ export function createPeopleService(options: PeopleOptions) { requireGeneral(v, "people:write") return tx((u) => { const p = find(u.state, input.id) - const { id: _, ...profile } = input - Object.assign(p.profile, profile) - log(p, v.sub, "Updated profile", now()) + Object.assign(p, { + firstName: input.firstName, + lastName: input.lastName, + contactEmail: input.contactEmail || null, + phone: input.phone || null, + telegramUsername: input.telegramUsername || null, + }) + touch(p, v.sub, now()) + log(u, p.id, v.sub, "Updated the record", now()) }) }, async setNote(v: Viewer, input: C.SetNoteInput) { @@ -78,57 +393,149 @@ export function createPeopleService(options: PeopleOptions) { return tx((u) => { const p = find(u.state, input.id) p.notes = input.note || null - log(p, v.sub, "Updated HR note", now()) + touch(p, v.sub, now()) + log(u, p.id, v.sub, "Updated the HR note", now()) + }) + }, + + async listAdmins(v: Viewer): Promise { + requireGeneral(v, "people:read") + return tx((u) => + Object.values(u.state.persons).flatMap((p) => { + const admin = current(u.state, p.id, "admin") + if (!admin) return [] + const capo = current(u.state, p.id, "capo") + const view = row(u.state, p, v) + const pick = (a: Assignment | null) => (a ? (view.assignments.find((x) => x.id === a.id) ?? null) : null) + return [{ person: view, admin: pick(admin) as C.Assignment, capo: pick(capo) }] + }) + ) + }, + async assignAdmin(v: Viewer, input: C.AssignAdminInput) { + return tx((u, ctx) => { + const p = find(u.state, input.personId) + authorize(ctx, u, v, p, "admin", "assign") + if (current(u.state, p.id, "admin")) fail("CONFLICT", "Already an admin") + const a = start(u, v, p, { + kind: "admin", + since: input.since, + capoOfReferenceId: capoOf(u, input.capoId, p.id), + }) + log(u, p.id, v.sub, "Made admin", now()) + push(u, ctx, p, [a], v.sub, "Made admin from People") + }) + }, + async endAdmin(v: Viewer, input: C.EndAssignmentInput) { + return tx((u, ctx) => { + const p = find(u.state, input.personId) + const a = activeOrFail(u, p.id, "admin", "Not a current admin") + authorize(ctx, u, v, p, "admin", "unassign") + if (current(u.state, p.id, "capo")) fail("CONFLICT", "End their Capo Admin appointment first") + end(a, input.reason) + log(u, p.id, v.sub, `Ended admin: ${input.reason}`, now()) + push(u, ctx, p, [a], v.sub, `Ended admin from People: ${input.reason}`) }) }, - async endAdmin(v: Viewer, input: C.EndAdminInput) { + async setCapoOfReference(v: Viewer, input: C.CapoRefInput) { requireGeneral(v, "people:write") return tx((u) => { const p = find(u.state, input.personId) - if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") - if (p.admin.capoScope) requireGeneral(v, "people:appoint") - Object.assign(p.admin, { status: "former", endedOn: date(), endReason: input.reason, capoScope: null }) - log(p, v.sub, `Ended admin role: ${input.reason}`, now()) + const a = activeOrFail(u, p.id, "admin", "Not a current admin") + a.capoOfReferenceId = capoOf(u, input.capoId, p.id) + touch(p, v.sub, now()) + log( + u, + p.id, + v.sub, + input.capoId ? `Capo Admin of reference: ${input.capoId}` : "Cleared the Capo Admin of reference", + now() + ) + }) + }, + + async listCapos(v: Viewer): Promise { + requireGeneral(v, "people:read") + return tx((u) => + Object.values(u.state.persons).flatMap((p) => { + const capo = current(u.state, p.id, "capo") + if (!capo) return [] + const view = row(u.state, p, v) + const admins = Object.values(u.state.persons).filter( + (other) => current(u.state, other.id, "admin")?.capoOfReferenceId === p.id + ) + return [ + { + person: view, + capo: view.assignments.find((x) => x.id === capo.id) as C.Assignment, + admins: admins.map(ref), + }, + ] + }) + ) + }, + async appointCapo(v: Viewer, input: C.AppointCapoInput) { + return tx((u, ctx) => { + const p = find(u.state, input.personId) + authorize(ctx, u, v, p, "capo", "assign") + if (!current(u.state, p.id, "admin")) fail("CONFLICT", "Make them an admin first") + if (current(u.state, p.id, "capo")) fail("CONFLICT", "Already a Capo Admin") + const a = start(u, v, p, { kind: "capo", since: input.since, capoScope: input.scope }) + log(u, p.id, v.sub, `Appointed Capo Admin for ${input.scope}`, now()) + push(u, ctx, p, [a], v.sub, `Appointed Capo Admin from People (${input.scope})`) }) }, async setCapoScope(v: Viewer, input: C.CapoScopeInput) { requireGeneral(v, "people:appoint") return tx((u) => { const p = find(u.state, input.personId) - if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") - p.admin.capoScope = input.scope || null - log(p, v.sub, `Set Capo Admin scope: ${input.scope ?? "none"}`, now()) + activeOrFail(u, p.id, "capo", "Not a current Capo Admin").capoScope = input.scope + touch(p, v.sub, now()) + log(u, p.id, v.sub, `Capo Admin scope: ${input.scope}`, now()) }) }, - async setCapoOfReference(v: Viewer, input: C.CapoRefInput) { - requireGeneral(v, "people:write") - return tx((u) => { + async endCapo(v: Viewer, input: C.EndAssignmentInput) { + return tx((u, ctx) => { const p = find(u.state, input.personId) - if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") - const capo = input.capoId ? find(u.state, input.capoId) : null - if (capo && (capo.id === p.id || capo.admin?.status !== "active" || !capo.admin.capoScope)) - fail("BAD_REQUEST", "Choose an active Capo Admin") - p.admin.capoOfReference = capo ? ref(capo) : null - log(p, v.sub, "Changed Capo Admin of reference", now()) + const a = activeOrFail(u, p.id, "capo", "Not a current Capo Admin") + authorize(ctx, u, v, p, "capo", "unassign") + end(a, input.reason) + // For a linked record, once Auth confirms: a refusal keeps them Capo Admin of the same admins. + if (!p.accountSub) clearCapoReferences(u, p.id, v.sub, now()) + log(u, p.id, v.sub, `Ended Capo Admin: ${input.reason}`, now()) + push(u, ctx, p, [a], v.sub, `Ended Capo Admin from People: ${input.reason}`) }) }, - async listTeams(v: Viewer) { - return tx((u) => { - const allowed = general(v, "people:read") ? [...C.TEAM_IDS] : v.can("people:self") ? leads(own(u.state, v)) : [] + + async listTeams(v: Viewer): Promise { + return tx((u, ctx) => { + const full = general(v, "people:read") + const allowed = C.TEAM_IDS.filter((team) => { + if (full) return true + try { + teamAccess(ctx, u, v, team, false) + return true + } catch { + return false + } + }) if (!allowed.length) fail("FORBIDDEN", "No readable teams") + const roles = ctx.directory?.roles ?? [] return allowed.map((id) => { - const full = general(v, "people:read") const people = Object.values(u.state.persons).filter((p) => - p.teams.some((t) => t.team === id && (full || !t.endedOn)) + assignmentsOf(u.state, p.id).some((a) => a.team === id && (full || confirmed(a))) ) - const lead = people.find((p) => leads(p, id).length) + const lead = people.find((p) => leadsOf(u.state, p.id).includes(id)) return { id, name: C.TEAMS[id].name, + assignable: { + member: rolesFor(roles, `team:${id}:member`).length === 1, + lead: rolesFor(roles, `team:${id}:lead`).length === 1, + }, lead: lead ? ref(lead) : null, members: people.map((p) => { const result = row(u.state, p, v, true) - if (!general(v, "people:read")) result.teams = result.teams.filter((t) => t.team === id) + if (!full) result.assignments = result.assignments.filter((a) => a.team === id && !a.endedOn) return result }), } @@ -136,195 +543,221 @@ export function createPeopleService(options: PeopleOptions) { }) }, async listTeamCandidates(v: Viewer, input: C.TeamCandidatesInput) { - return tx((u) => { - teamAccess(u.state, v, input.teamId, false) + return tx((u, ctx) => { + teamAccess(ctx, u, v, input.teamId, false) return Object.values(u.state.persons) - .filter((p) => !p.teams.some((m) => m.team === input.teamId && !m.endedOn)) - .map((p) => ({ ...ref(p), course: p.profile.course })) + .filter((p) => !current(u.state, p.id, `team:${input.teamId}`)) + .map(ref) }) }, async addTeamMember(v: Viewer, input: C.AddTeamMemberInput) { - return tx((u) => { - teamAccess(u.state, v, input.teamId, true) - if (input.role === "lead") requireGeneral(v, "people:appoint") - validateFields(input.teamId, input.fields) + return tx((u, ctx) => { const p = find(u.state, input.personId) - if (p.teams.some((t) => t.team === input.teamId && !t.endedOn)) fail("CONFLICT", "Already active in this team") - if (input.role === "lead" && Object.values(u.state.persons).some((p) => leads(p, input.teamId).length)) + authorize(ctx, u, v, p, `team:${input.teamId}:${input.role}`, "assign") + validateFields(input.teamId, input.fields) + if (current(u.state, p.id, `team:${input.teamId}`)) fail("CONFLICT", "Already in this team") + if ( + input.role === "lead" && + Object.values(u.state.persons).some( + (o) => current(u.state, o.id, `team:${input.teamId}`)?.teamRole === "lead" + ) + ) fail("CONFLICT", "End the existing Lead appointment first") - if (input.since > date()) fail("BAD_REQUEST", "Start date is in the future") - p.teams.push({ + const a = start(u, v, p, { + kind: "team", team: input.teamId, - role: input.role, + teamRole: input.role, since: input.since, - endedOn: null, - endReason: null, fields: input.fields, }) - log(p, v.sub, `Joined ${input.teamId} as ${input.role}`, now()) + log(u, p.id, v.sub, `Joined ${input.teamId} as ${input.role}`, now()) + push(u, ctx, p, [a], v.sub, `Joined ${input.teamId} as ${input.role} from People`) }) }, async updateTeamFields(v: Viewer, input: C.TeamFieldsInput) { - return tx((u) => { - teamAccess(u.state, v, input.teamId, true) + return tx((u, ctx) => { + teamAccess(ctx, u, v, input.teamId, true) validateFields(input.teamId, input.fields) const p = find(u.state, input.personId) - const t = p.teams.find((t) => t.team === input.teamId && !t.endedOn) - if (!t) fail("CONFLICT", "No active team membership") - t.fields = input.fields - log(p, v.sub, `Updated ${input.teamId} fields`, now()) + activeOrFail(u, p.id, `team:${input.teamId}`, "Not in this team").fields = input.fields + touch(p, v.sub, now()) + log(u, p.id, v.sub, `Updated ${input.teamId} fields`, now()) }) }, async endTeamMembership(v: Viewer, input: C.EndTeamInput) { - return tx((u) => { - teamAccess(u.state, v, input.teamId, true) + return tx((u, ctx) => { const p = find(u.state, input.personId) - const t = p.teams.find((t) => t.team === input.teamId && !t.endedOn) - if (!t) fail("CONFLICT", "No active team membership") - if (t.role === "lead") requireGeneral(v, "people:appoint") - if (input.lastDay < t.since || input.lastDay > date()) fail("BAD_REQUEST", "Invalid last day") - Object.assign(t, { endedOn: input.lastDay, endReason: input.reason }) - log(p, v.sub, `Ended ${input.teamId}: ${input.reason}${input.note ? `; ${input.note}` : ""}`, now()) + const a = activeOrFail(u, p.id, `team:${input.teamId}`, "Not in this team") + authorize(ctx, u, v, p, `team:${input.teamId}:${a.teamRole}`, "unassign") + end(a, input.reason) + log(u, p.id, v.sub, `Left ${input.teamId}: ${input.reason}`, now()) + push(u, ctx, p, [a], v.sub, `Left ${input.teamId} from People: ${input.reason}`) }) }, - async listInvites(v: Viewer) { + + async listInvites(v: Viewer): Promise { requireGeneral(v, "people:read") return tx((u) => - Object.values(u.state.persons).flatMap((p) => - p.account.status === "invite" ? [{ personId: p.id, name: nameOf(p), ...p.account }] : [] - ) + Object.values(u.state.persons).flatMap((p) => { + const invite = p.accountSub ? null : openInvite(u.state, p.id) + return invite + ? [ + { + personId: p.id, + name: nameOf(p), + email: invite.email, + sentOn: invite.sentAt.slice(0, 10), + expiresOn: invite.expiresAt.slice(0, 10), + sentBy: invite.sentBy, + }, + ] + : [] + }) ) }, async sendInvite(v: Viewer, input: { personId: string }) { requireGeneral(v, "people:write") return tx((u) => { const p = find(u.state, input.personId) - if (p.accountSub || !p.profile.personalEmail) - fail("CONFLICT", "Account already linked or personal email missing") + 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() const token = randomBytes(32).toString("base64url") - p.invite = { hash: hash(token), expiresAt: new Date(now().getTime() + 14 * 86400000).toISOString() } - p.account = { - status: "invite", - email: p.profile.personalEmail, - sentOn: date(), - expiresOn: p.invite.expiresAt.slice(0, 10), + const invite = { + id: randomUUID(), + personId: p.id, + tokenHash: hash(token), + email: p.contactEmail, sentBy: v.sub, + sentAt: now().toISOString(), + expiresAt: new Date(now().getTime() + 14 * 86_400_000).toISOString(), + revokedAt: null, + acceptedAt: null, + acceptedBy: null, } - queue( + u.state.invites[invite.id] = invite + queueMail( u.state, - p, - `invite:${p.id}:${p.invite.hash}`, - p.profile.personalEmail, + p.id, + `invite:${invite.id}`, + p.contactEmail, "PoliNetwork · collega il tuo account", `${dashboardUrl}/dashboard/account/me?peopleInvite=${token}` ) - log(p, v.sub, "Queued account invitation", now()) + 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) => { const p = find(u.state, input.personId) - if (p.account.status !== "invite") fail("CONFLICT", "No pending invitation") - p.invite = null - p.account = { status: "none" } - log(p, v.sub, "Revoked account invitation", now()) + 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) { + async searchAccounts(v: Viewer, input: C.SearchAccountsInput): Promise { requireGeneral(v, "people:write") const accounts = await options.directory() return tx((u) => { - const p = find(u.state, input.personId) const q = input.query.toLowerCase() return accounts - .filter((a) => !q || `${a.name} ${a.email ?? ""} ${a.telegramId ?? ""}`.toLowerCase().includes(q)) + .filter((a) => !q || `${a.name} ${a.email ?? ""} ${a.sub}`.toLowerCase().includes(q)) .slice(0, 100) .map((a) => { const linked = Object.values(u.state.persons).find((p) => p.accountSub === a.sub) - return { - id: a.sub, - name: a.name, - email: a.email ?? "", - telegram: a.telegramId, - via: "IdP", - linkedTo: linked ? ref(linked) : null, - reason: - a.telegramId && a.telegramId === p.profile.telegramId - ? ("same-telegram" as const) - : a.email?.toLowerCase() === p.profile.personalEmail?.toLowerCase() - ? ("same-email" as const) - : ("similar-name" as const), - } + return { id: a.sub, name: a.name, email: a.email ?? "", linkedTo: linked ? ref(linked) : null } }) }) }, + /** 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") const account = (await options.directory()).find((a) => a.sub === input.accountId) if (!account) fail("NOT_FOUND", "IdP account not found") - return tx((u) => link(u.state, find(u.state, input.personId), account, v.sub, input.reason)) + // 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) + 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) => { 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 - p.account = { status: "none" } - log(p, v.sub, "Unlinked account", now()) + touch(p, v.sub, now()) }) }, + /** + * 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. + */ 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) => { - const p = Object.values(u.state.persons).find( - (p) => p.invite?.hash === hash(input.token) && p.invite.expiresAt > now().toISOString() + 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 (!p || p.profile.personalEmail?.toLowerCase() !== account.email?.toLowerCase()) + if (!invite || invite.email.toLowerCase() !== account.email?.toLowerCase()) fail("NOT_FOUND", "Invitation expired or not addressed to this account") - link(u.state, p, account, v.sub, "Accepted email invitation") + const p = link(u, find(u.state, invite.personId), v.sub, v.sub, "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") }) }, - async getMyRoles(v: Viewer) { + async getMyRoles(v: Viewer): Promise { requireSelf(v) return tx((u) => { const p = own(u.state, v) - return { capoScope: p?.admin?.status === "active" ? p.admin.capoScope : null, leads: leads(p) } + return { + capoScope: p ? (confirmedOf(u.state, p.id, "capo")?.capoScope ?? null) : null, + leads: p ? leadsOf(u.state, p.id) : [], + } }) }, async getMyArea(v: Viewer): Promise { requireSelf(v) + const mine = await tx((u) => own(u.state, v)) + if (!mine) return { state: "none" } + const activity = await store.activity(mine.id) return tx((u) => { const p = own(u.state, v) if (!p) return { state: "none" } - const team = p.teams.find((t) => !t.endedOn)?.team + const teams = assignmentsOf(u.state, p.id).flatMap((a) => + a.kind === "team" && confirmed(a) ? [a.team as C.TeamId] : [] + ) const contacts: Extract["contacts"] = [] - const capoId = p.admin?.capoOfReference?.id - const capo = capoId ? u.state.persons[capoId] : null - if (capo) - contacts.push({ role: "capo", name: nameOf(capo), telegram: capo.profile.telegramUsername, team: null }) + const capoId = confirmedOf(u.state, p.id, "admin")?.capoOfReferenceId + const capo = capoId && confirmedOf(u.state, capoId, "capo") ? u.state.persons[capoId] : null + if (capo) contacts.push({ role: "capo", name: nameOf(capo), telegram: capo.telegramUsername, team: null }) for (const other of Object.values(u.state.persons)) { - for (const t of other.teams.filter( - (t) => !t.endedOn && t.role === "lead" && p.teams.some((mine) => !mine.endedOn && mine.team === t.team) - )) - contacts.push({ role: "lead", name: nameOf(other), telegram: other.profile.telegramUsername, team: t.team }) - if (other.teams.some((t) => t.team === "hr" && !t.endedOn)) - contacts.push({ role: "hr", name: nameOf(other), telegram: other.profile.telegramUsername, team: "hr" }) + for (const team of leadsOf(u.state, other.id).filter((team) => teams.includes(team))) + contacts.push({ role: "lead", name: nameOf(other), telegram: other.telegramUsername, team }) + if (confirmedOf(u.state, other.id, "team:hr")) + contacts.push({ role: "hr", name: nameOf(other), telegram: other.telegramUsername, team: "hr" }) } + const team = teams[0] return { state: "linked", - person: record(u.state, p, v), + person: record(u.state, p, v, activity), contacts, roster: team ? { team, members: Object.values(u.state.persons).flatMap((other) => { - const t = other.teams.find((t) => t.team === team && !t.endedOn) - return t ? [{ ...ref(other), role: t.role, telegram: other.profile.telegramUsername }] : [] + const a = confirmedOf(u.state, other.id, `team:${team}`) + return a + ? [{ ...ref(other), role: a.teamRole as "member" | "lead", telegram: other.telegramUsername }] + : [] }), } : null, @@ -335,26 +768,31 @@ export function createPeopleService(options: PeopleOptions) { requireSelf(v) return tx((u) => { const p = requireOwn(u.state, v) - const scope = p.admin?.status === "active" ? p.admin.capoScope : null - if (!scope) fail("FORBIDDEN", "No active Capo Admin scope") + const scope = confirmedOf(u.state, p.id, "capo")?.capoScope + if (!scope) fail("FORBIDDEN", "You are not a current Capo Admin") return { scope, admins: Object.values(u.state.persons) - .filter((other) => other.admin?.status === "active" && other.admin.capoOfReference?.id === p.id) - .map((other) => { - const r = row(u.state, other, v, true) - r.profile.personalEmail = null - return r - }), + .filter((other) => confirmedOf(u.state, other.id, "admin")?.capoOfReferenceId === p.id) + .map((other) => ({ ...row(u.state, other, v, true), contactEmail: null, phone: null })), } }) }, - /** Sends queued mail; the cron calls it every minute. */ + /** Sends queued mail and role commands; the cron calls it every minute. */ async deliverPending() { + const commands = await store.transaction(async (u) => + Object.values(u.state.commands) + .filter((c) => c.status === "queued") + .sort((a, b) => (a.createdAt < b.createdAt ? -1 : 1)) + .slice(0, 20) + .map((c) => c.id) + ) + for (const id of commands) await deliver(id) + // Claim and record intent before network I/O. Unknown outcomes require an explicit retry. - const claimed = await tx((u) => { - for (const mail of Object.values(u.state.outbox)) + const claimed = await store.transaction(async (u) => { + for (const mail of Object.values(u.state.mail)) if ( mail.status === "sending" && mail.attemptedAt && @@ -363,14 +801,14 @@ export function createPeopleService(options: PeopleOptions) { mail.status = "failed" mail.error = "Delivery outcome unknown after interruption; check the mailbox before retrying" } - const pending = Object.values(u.state.outbox) + const pending = Object.values(u.state.mail) .filter((m) => m.status === "pending") .slice(0, 20) for (const mail of pending) { mail.status = "sending" mail.attemptedAt = now().toISOString() } - return pending + return structuredClone(pending) }) for (const mail of claimed) { let error: string | null = null @@ -379,13 +817,12 @@ export function createPeopleService(options: PeopleOptions) { } catch (err) { error = err instanceof Error ? err.message : String(err) } - await tx((u) => { - const current = u.state.outbox[mail.id] + await store.transaction(async (u) => { + const current = u.state.mail[mail.id] if (current.status !== "sending" || current.attemptedAt !== mail.attemptedAt) return current.status = error ? "failed" : "sent" current.error = error - const p = u.state.persons[mail.personId] - log(p, "system", error ? `Email failed: ${error}` : `Sent email: ${mail.subject}`, now()) + log(u, mail.personId, "system", error ? `Email failed: ${error}` : `Sent email: ${mail.subject}`, now()) }) } }, diff --git a/src/people/store-pg.ts b/src/people/store-pg.ts index 9580d33..3ea9a59 100644 --- a/src/people/store-pg.ts +++ b/src/people/store-pg.ts @@ -1,46 +1,142 @@ -import { eq, inArray, sql } from "drizzle-orm" +import { desc, eq, sql } from "drizzle-orm" +import type { PgTable } from "drizzle-orm/pg-core" import type { DB } from "@/db" -import { identities, records } from "@/db/schema/people" -import { emptyState, type PeopleState, type PeopleStore } from "./types" +import { activity, assignments, counters, invites, mail, persons, roleCommands } from "@/db/schema/people" +import { emptyState, type PeopleState, type PeopleStore, type UnitOfWork } from "./types" type Database = typeof DB type Transaction = Parameters[0]>[0] -/** Serializes every People transaction. */ +/** Serializes People writes: the register is small, and syncing with Auth writes across records. */ const lockPeople = (tx: Transaction) => tx.execute(sql`select pg_advisory_xact_lock(198074, 1)`) +const iso = (value: Date | null) => value?.toISOString() ?? null +const time = (value: string | null) => (value ? new Date(value) : null) +/** Bun's driver returns `date` columns as a `Date` at UTC midnight, whatever the column's mode. */ +const day = (value: string | Date | null) => (value instanceof Date ? value.toISOString().slice(0, 10) : value) + +/** How each collection of the state maps to its table, in an order that satisfies the foreign keys. */ +const TABLES = [ + { + kind: "persons", + table: persons, + id: persons.id, + load: (r: typeof persons.$inferSelect) => ({ + ...r, + createdAt: r.createdAt.toISOString(), + updatedAt: r.updatedAt.toISOString(), + }), + save: (p: PeopleState["persons"][string]) => ({ + ...p, + createdAt: new Date(p.createdAt), + updatedAt: new Date(p.updatedAt), + }), + }, + { + kind: "commands", + table: roleCommands, + id: roleCommands.id, + load: (r: typeof roleCommands.$inferSelect) => ({ + ...r, + createdAt: r.createdAt.toISOString(), + answeredAt: iso(r.answeredAt), + }), + save: (c: PeopleState["commands"][string]) => ({ + ...c, + createdAt: new Date(c.createdAt), + answeredAt: time(c.answeredAt), + }), + }, + { + kind: "assignments", + table: assignments, + id: assignments.id, + load: (r: typeof assignments.$inferSelect) => ({ + ...r, + team: r.team as PeopleState["assignments"][string]["team"], + since: day(r.since) as string, + endedOn: day(r.endedOn), + }), + save: (a: PeopleState["assignments"][string]) => a, + }, + { + kind: "invites", + table: invites, + id: invites.id, + load: (r: typeof invites.$inferSelect) => ({ + ...r, + sentAt: r.sentAt.toISOString(), + expiresAt: r.expiresAt.toISOString(), + revokedAt: iso(r.revokedAt), + acceptedAt: iso(r.acceptedAt), + }), + save: (i: PeopleState["invites"][string]) => ({ + ...i, + sentAt: new Date(i.sentAt), + expiresAt: new Date(i.expiresAt), + revokedAt: time(i.revokedAt), + acceptedAt: time(i.acceptedAt), + }), + }, + { + kind: "mail", + table: mail, + id: mail.id, + load: (r: typeof mail.$inferSelect) => ({ ...r, attemptedAt: iso(r.attemptedAt) }), + save: (m: PeopleState["mail"][string]) => ({ ...m, attemptedAt: time(m.attemptedAt) }), + }, +] as const + async function loadState(tx: Transaction): Promise { const state = emptyState() - for (const row of await tx.select().from(records)) { - const separator = row.id.indexOf(":") - Object.assign(state[row.kind], { [row.id.slice(separator + 1)]: row.data }) + for (const { kind, table, load } of TABLES) { + const rows = (await tx.select().from(table as PgTable)) as Parameters[0][] + for (const r of rows) Object.assign(state[kind], { [r.id]: (load as (r: unknown) => unknown)(r) }) } + for (const r of await tx.select().from(counters)) state.counters[r.key] = r.value return state } -async function saveState(tx: Transaction, state: PeopleState, before: PeopleState) { - for (const kind of Object.keys(state) as (keyof PeopleState)[]) { - for (const [id, data] of Object.entries(state[kind])) { - if (JSON.stringify(data) === JSON.stringify(before[kind][id])) continue +const ends = (value: unknown, previous: unknown) => + !!(value as { endedOn?: string | null }).endedOn && !(previous as { endedOn?: string | null }).endedOn + +/** + * Writes what the transaction changed. Rows are never deleted, except records merged into another (`merges`), + * once everything of theirs has moved. + */ +async function saveState(tx: Transaction, uow: UnitOfWork, before: PeopleState) { + const { state, merges } = uow + const merged = new Set(merges.map((m) => m.from)) + // Free the merged records' accounts before another record takes them. + for (const { from } of merges) await tx.update(persons).set({ accountSub: null }).where(eq(persons.id, from)) + for (const { kind, table, id, save } of TABLES) { + const changed = Object.entries(state[kind]).filter( + ([key, value]) => JSON.stringify(value) !== JSON.stringify(before[kind][key]) + ) + // Rows that end first, then other updates, then new rows: an assignment frees its concept before another + // takes it, whether it is new or moves over from a merged record. + const existing = changed + .filter(([key]) => key in before[kind]) + .sort(([a, x], [b, y]) => Number(ends(y, before[kind][b])) - Number(ends(x, before[kind][a]))) + for (const [key, value] of existing) await tx - .insert(records) - .values({ id: `${kind}:${id}`, kind, data }) - .onConflictDoUpdate({ target: records.id, set: { data } }) - } - for (const id of Object.keys(before[kind])) { - if (!(id in state[kind])) await tx.delete(records).where(eq(records.id, `${kind}:${id}`)) - } + .update(table) + .set((save as (v: unknown) => Record)(value)) + .where(eq(id, key)) + const added = changed.filter(([key]) => !(key in before[kind])).map(([, v]) => (save as (v: unknown) => object)(v)) + if (added.length) await tx.insert(table).values(added as never) + const removed = Object.keys(before[kind]).filter((key) => !(key in state[kind])) + if (removed.some((key) => kind !== "persons" || !merged.has(key))) + throw new Error(`People never deletes ${kind}: ${removed.join(", ")}`) + } + for (const [key, value] of Object.entries(state.counters)) + if (before.counters[key] !== value) + await tx.insert(counters).values({ key, value }).onConflictDoUpdate({ target: counters.key, set: { value } }) + if (uow.activity.length) + await tx.insert(activity).values(uow.activity.map((entry) => ({ ...entry, at: new Date(entry.at) }))) + for (const { from, into } of merges) { + await tx.update(activity).set({ personId: into }).where(eq(activity.personId, from)) + await tx.delete(persons).where(eq(persons.id, from)) } - // Clear changed and removed unique values first so moving an identity between records is atomic. - const changed = Object.values(state.persons).filter((p) => JSON.stringify(p) !== JSON.stringify(before.persons[p.id])) - const removed = Object.keys(before.persons).filter((id) => !(id in state.persons)) - if (changed.length || removed.length) - await tx.delete(identities).where(inArray(identities.personId, [...changed.map((p) => p.id), ...removed])) - for (const p of changed) - await tx.insert(identities).values({ - personId: p.id, - accountSub: p.accountSub, - telegramId: p.profile.telegramId, - }) } export function createPeoplePgStore(db: Database): PeopleStore { @@ -50,9 +146,14 @@ export function createPeoplePgStore(db: Database): PeopleStore { await lockPeople(tx) const state = await loadState(tx) const before = structuredClone(state) - const result = await fn({ state }) - await saveState(tx, state, before) + const uow: UnitOfWork = { state, activity: [], merges: [] } + const result = await fn(uow) + await saveState(tx, uow, before) return result }), + async activity(personId) { + const rows = await db.select().from(activity).where(eq(activity.personId, personId)).orderBy(desc(activity.id)) + return rows.map((r) => ({ personId: r.personId, actor: r.actor, text: r.text, at: r.at.toISOString() })) + }, } } diff --git a/src/people/sync.ts b/src/people/sync.ts new file mode 100644 index 0000000..a685bc6 --- /dev/null +++ b/src/people/sync.ts @@ -0,0 +1,138 @@ +import * as C from "./contract" +import { clearCapoReferences, current, log, newAssignment, nextPersonId, waiting } from "./model" +import { type Concept, isBound, type RoleDirectory, rolesFor, sinceOf, viewOf } from "./roles" +import type { BoundRole } from "./rules" +import type { PeopleState, Person, UnitOfWork } from "./types" + +type Clock = { date: string; now: Date } +const CONCEPTS: Concept[] = ["admin", "capo", ...C.TEAM_IDS.map((team) => `team:${team}` as const)] +const LABEL = { admin: "admin", capo: "Capo Admin" } + +/** + * Brings a linked record in line with what PoliNetwork Auth holds: an assignment is current exactly while + * its role is held, so one whose concept no longer has a bound role ends too. A record with a change still + * waiting for Auth is left alone until Auth answers. + */ +export function reconcile( + u: UnitOfWork, + p: Person, + roles: readonly BoundRole[], + held: readonly string[], + at: Clock, + since?: Record +) { + const s = u.state + if (!p.accountSub || waiting(s, p.id)) return + const view = viewOf(roles, held) + const end = (a: ReturnType, reason: string) => { + if (!a) return + Object.assign(a, { + endedOn: at.date, + endReason: reason, + change: "end", + status: "applied", + refusal: null, + commandId: null, + }) + } + for (const concept of CONCEPTS) { + const a = current(s, p.id, concept) + if (!isBound(roles, concept)) { + if (!a) continue + end(a, "No role is bound to it in PoliNetwork Auth") + if (concept === "capo") clearCapoReferences(u, p.id, "system", at.now) + log(u, p.id, "system", `Ended ${concept}: no role is bound to it in PoliNetwork Auth`, at.now) + continue + } + if (concept === "admin" || concept === "capo") { + if (view[concept] && !a) { + newAssignment(s, { + personId: p.id, + kind: concept, + since: sinceOf( + rolesFor(roles, concept).map((r) => r.key), + since, + at.date + ), + assignedBy: "auth", + status: "applied", + }) + log(u, p.id, "system", `Became ${LABEL[concept]}: held in PoliNetwork Auth`, at.now) + } else if (!view[concept] && a) { + end(a, "Not held in PoliNetwork Auth") + if (concept === "capo") clearCapoReferences(u, p.id, "system", at.now) + log(u, p.id, "system", `Ended ${LABEL[concept]}: not held in PoliNetwork Auth`, at.now) + } else if (a?.status === "pending") a.status = "applied" + continue + } + const team = concept.slice("team:".length) as C.TeamId + const role = view.teams[team] + if (a && a.teamRole !== role) { + end(a, role ? "Changed in PoliNetwork Auth" : "Not held in PoliNetwork Auth") + if (!role) log(u, p.id, "system", `Left ${team}: not held in PoliNetwork Auth`, at.now) + } + if (role && (!a || a.teamRole !== role)) { + newAssignment(s, { + personId: p.id, + kind: "team", + team, + teamRole: role, + fields: a?.fields ?? {}, + since: sinceOf( + rolesFor(roles, `team:${team}:${role}`).map((r) => r.key), + since, + at.date + ), + assignedBy: "auth", + status: "applied", + }) + log(u, p.id, "system", `Joined ${team} as ${role}: held in PoliNetwork Auth`, at.now) + } else if (a?.status === "pending") a.status = "applied" + } +} + +function splitName(name: string) { + const parts = name.trim().split(/\s+/).filter(Boolean) + return { firstName: parts.shift() ?? "?", lastName: parts.join(" ") } +} + +/** + * Lays Auth's answer over the register: + * - someone holding a bound role without a record (e.g. assigned by hand in Auth) gets one, already linked; + * - every linked record follows the roles Auth holds for its account, none when Auth doesn't list it. + * Records that aren't linked are People's alone. + */ +export function syncDirectory(u: UnitOfWork, directory: RoleDirectory, at: Clock) { + const s: PeopleState = u.state + const bySub = new Map(Object.values(s.persons).flatMap((p) => (p.accountSub ? [[p.accountSub, p] as const] : []))) + const listed = new Set() + for (const user of directory.users) { + listed.add(user.sub) + let p = bySub.get(user.sub) + if (!p) { + const view = viewOf(directory.roles, user.roles) + if (!view.admin && !view.capo && !Object.keys(view.teams).length) continue + const id = nextPersonId(s) + if (!id) continue + const stamp = at.now.toISOString() + p = { + id, + ...splitName(user.name), + contactEmail: user.email, + phone: null, + telegramUsername: user.telegramUsername, + notes: null, + accountSub: user.sub, + createdBy: "auth", + createdAt: stamp, + updatedBy: "auth", + updatedAt: stamp, + } + s.persons[p.id] = p + bySub.set(user.sub, p) + log(u, p.id, "system", "Created from a role held in PoliNetwork Auth", at.now) + } + reconcile(u, p, directory.roles, user.roles, at, user.since) + } + for (const p of bySub.values()) if (!listed.has(p.accountSub as string)) reconcile(u, p, directory.roles, [], at) +} diff --git a/src/people/types.ts b/src/people/types.ts index 03435dc..acb90fb 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -1,11 +1,81 @@ -import type { PersonRecord } from "./contract" +import type * as C from "./contract" +import type { RoleCommand } from "./roles" -export type Viewer = { sub: string; telegramId: string | null; can: (permission: string) => boolean } -export type Person = PersonRecord & { +/** The signed-in dashboard user, as the access snapshot sees them. */ +export type Viewer = { + sub: string + telegramId: string | null + can: (permission: string) => boolean + /** Whether they hold the role in Auth, directly or through a parent role. */ + holdsRole: (role: string) => boolean +} + +export type Person = { + id: string + firstName: string + lastName: string + /** Only for sending invites. Never used to match accounts. */ + contactEmail: string | null + phone: string | null + /** Informational only. */ + telegramUsername: string | null + notes: string | null + /** The login account the record is linked to. */ accountSub: string | null - invite: { hash: string; expiresAt: string } | null + createdBy: string + createdAt: string + updatedBy: string + updatedAt: string +} + +export type Assignment = { + id: string + personId: string + kind: (typeof C.ASSIGNMENT_KINDS)[number] + team: C.TeamId | null + teamRole: (typeof C.TEAM_ROLES)[number] | null + capoScope: string | null + /** For `admin`: the person record of their Capo Admin. */ + capoOfReferenceId: string | null + fields: C.TeamFields + since: string + endedOn: string | null + endReason: string | null + /** The sub of whoever made it; `auth` when it was made by hand in PoliNetwork Auth. */ + assignedBy: string + change: "start" | "end" + status: (typeof C.ASSIGNMENT_STATUSES)[number] + refusal: string | null + /** The role command that carries `change` to Auth, while `status` is `sent`. */ + commandId: string | null +} + +/** A role command waiting in, or answered from, the outbox to PoliNetwork Auth. */ +export type StoredCommand = { + id: string + personId: string + request: RoleCommand + status: "queued" | "applied" | "refused" + attempts: number + error: string | null + createdAt: string + answeredAt: string | null +} + +export type Invite = { + id: string + personId: string + tokenHash: string + email: string + sentBy: string + sentAt: string + expiresAt: string + revokedAt: string | null + acceptedAt: string | null + acceptedBy: string | null } -export type Outbox = { + +export type Mail = { id: string personId: string to: string @@ -15,25 +85,48 @@ export type Outbox = { attemptedAt: string | null error: string | null } + +export type Activity = { personId: string; actor: string; text: string; at: string } + +/** Everything but the activity history, which is append-only and read per person. */ export type PeopleState = { persons: Record - outbox: Record + assignments: Record + commands: Record + invites: Record + mail: Record + /** `roleRevision` advances whenever Auth confirms or refuses a role change. */ counters: Record } export const emptyState = (): PeopleState => ({ persons: {}, - outbox: {}, + assignments: {}, + commands: {}, + invites: {}, + mail: {}, counters: {}, }) + export type UnitOfWork = { state: PeopleState + /** Activity entries written in this transaction; the store only ever appends them. */ + activity: Activity[] + /** + * Records folded into another in this transaction (see `absorb`): their history moves to `into`, and the + * store deletes them, the only records it ever deletes. + */ + merges: { from: string; into: string }[] } export interface PeopleStore { + /** One serialized write transaction over the register. */ transaction(fn: (uow: UnitOfWork) => Promise): Promise + /** A person's activity history, newest first. */ + activity(personId: string): Promise } + +/** A login account in the IdP directory. */ export type Account = { sub: string name: string email: string | null - telegramId: string | null } diff --git a/tests/people-auth.ts b/tests/people-auth.ts new file mode 100644 index 0000000..e3b4605 --- /dev/null +++ b/tests/people-auth.ts @@ -0,0 +1,121 @@ +import { type PeopleRoles, RoleChangeError, type RoleCommand, type RoleDirectory } from "@/people/roles" +import type { BoundRole } from "@/people/rules" + +/** Roles bound to People in the fake Auth. `design` has none, so it can't be assigned. */ +export const BOUND: BoundRole[] = [ + { key: "admin", name: "Admin", binding: "admin", permissions: ["admin:access"], bindings: ["admin"] }, + { + key: "capo-admin", + name: "Capo Admin", + binding: "capo", + permissions: ["admin:access", "people:read"], + bindings: ["capo", "admin"], + }, + { key: "it-member", name: "IT", binding: "team:it:member", permissions: [], bindings: ["team:it:member"] }, + { + key: "it-lead", + name: "IT Lead", + binding: "team:it:lead", + permissions: ["people:self"], + bindings: ["team:it:lead"], + }, + { + key: "hr-member", + name: "HR", + binding: "team:hr:member", + permissions: ["people:read"], + bindings: ["team:hr:member"], + }, +] + +/** + * PoliNetwork Auth's People endpoints, in memory: a role per binding, commands applied at most once per ID. + * `mode` simulates outages: `down` answers nothing, `lost` applies the command and loses the answer once. + */ +export function fakeAuth(roles: BoundRole[] = structuredClone(BOUND)) { + const held = new Map>() + const names = new Map() + const since = new Map>() + const applied = new Set() + const state = { + mode: "up" as "up" | "down" | "lost", + refusal: null as { status: number; message: string } | null, + calls: [] as RoleCommand[], + reads: 0, + } + const keyOf = (binding: string) => roles.find((r) => r.binding === binding)?.key + function rolesOf(sub: string) { + if (!held.has(sub)) held.set(sub, new Set()) + return held.get(sub) as Set + } + function result(sub: string) { + const keys = [...rolesOf(sub)].sort() + return { roles, held: keys, assigned: keys } + } + const auth: PeopleRoles = { + async directory(): Promise { + state.reads += 1 + if (state.mode === "down") throw new Error("Auth is down") + return { + roles, + users: [...held] + .filter(([, keys]) => keys.size) + .map(([sub, keys]) => ({ + sub, + name: names.get(sub) ?? sub, + email: `${sub}@polinetwork.org`, + telegramId: null, + telegramUsername: null, + roles: [...keys].sort(), + assigned: [...keys].sort(), + since: since.get(sub), + })), + } + }, + 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) + if (!applied.has(command.id)) { + applied.add(command.id) + const keys = rolesOf(command.sub) + for (const change of command.changes) { + if (change.kind !== "team") { + const key = keyOf(change.kind) + if (key && change.active) keys.add(key) + else if (key) keys.delete(key) + continue + } + for (const role of ["member", "lead"]) { + const key = keyOf(`team:${change.team}:${role}`) + if (key) keys.delete(key) + } + const key = change.role && keyOf(`team:${change.team}:${change.role}`) + if (key) keys.add(key) + } + } + if (state.mode === "lost") { + state.mode = "up" + throw new RoleChangeError(503, "PoliNetwork Auth sent an unreadable answer") + } + return result(command.sub) + }, + } + return { + auth, + /** The bound roles Auth answers with; tests may change them. */ + roles, + state, + applied, + /** Gives a role by hand in Auth. */ + give(sub: string, key: string, name?: string, on?: string) { + rolesOf(sub).add(key) + if (name) names.set(sub, name) + if (on) since.set(sub, { ...since.get(sub), [key]: on }) + }, + take(sub: string, key: string) { + rolesOf(sub).delete(key) + }, + held: (sub: string) => [...rolesOf(sub)].sort(), + } +} diff --git a/tests/people-fixtures.ts b/tests/people-fixtures.ts index 190934b..f7c3a91 100644 --- a/tests/people-fixtures.ts +++ b/tests/people-fixtures.ts @@ -1,82 +1,90 @@ import { vi } from "vitest" -import { newPerson } from "@/people/model" +import { log, newPerson } from "@/people/model" import { createPeopleService, type PeopleOptions } from "@/people/service" -import { type Account, emptyState, type Viewer } from "@/people/types" +import { type Account, type Activity, emptyState, type UnitOfWork, type Viewer } from "@/people/types" + +type Merge = UnitOfWork["merges"][number] + +import { fakeAuth } from "./people-auth" + +export { BOUND, fakeAuth } from "./people-auth" export const profile = (firstName = "Mario", lastName = "Rossi") => ({ firstName, lastName, - personalEmail: `${firstName.toLowerCase()}@example.org`, + contactEmail: `${firstName.toLowerCase()}@example.org`, phone: "+3902000000", telegramUsername: `${firstName.toLowerCase()}_test`, - course: "Ingegneria Informatica", - year: "2nd year" as const, - campus: "Leonardo" as const, - admin: true, }) -export const viewer = (sub: string, permissions: string[], telegramId: string | null = null): Viewer => ({ +export const viewer = (sub: string, permissions: string[], roles: string[] = []): Viewer => ({ sub, - telegramId, + telegramId: null, can: (key) => permissions.includes(key), + holdsRole: (key) => roles.includes(key), }) export const permissions = ["admin:access", "people:self", "people:read", "people:write", "people:appoint"] +/** HR with every People permission, and nothing else Auth knows of. */ export const master = viewer("president", permissions) /** A rollback-capable serialized unit of work; production concurrency is tested separately against PostgreSQL. */ export function harness(overrides: Partial = {}) { let state = emptyState() + let history: Activity[] = [] let tail: Promise = Promise.resolve() let clock = new Date("2026-10-18T10:00:00Z") const accounts: Account[] = [ - { sub: "president", name: "Mario Rossi", email: "mario@example.org", telegramId: "101" }, - { sub: "vice", name: "Anna Bianchi", email: "anna@example.org", telegramId: "102" }, - { sub: "member", name: "Luca Verdi", email: "luca@example.org", telegramId: "103" }, + { sub: "president", name: "Mario Rossi", email: "mario@example.org" }, + { sub: "vice", name: "Anna Bianchi", email: "anna@example.org" }, + { sub: "member", name: "Luca Verdi", email: "luca@example.org" }, ] const store: PeopleOptions["store"] = { transaction(fn) { const run = tail.then(async () => { - const draft = structuredClone(state) - const result = await fn({ state: draft }) - state = draft + const draft = { state: structuredClone(state), activity: [] as Activity[], merges: [] as Merge[] } + const result = await fn(draft) + state = draft.state + history = [...history, ...draft.activity].map((a) => { + const merge = draft.merges.find((m) => m.from === a.personId) + return merge ? { ...a, personId: merge.into } : a + }) return result }) tail = run.catch(() => {}) return run }, + async activity(personId) { + return history.filter((a) => a.personId === personId).reverse() + }, } + const auth = fakeAuth() const sendMail = vi.fn().mockResolvedValue(undefined) const service = createPeopleService({ store, dashboardUrl: "https://admin.example.org", now: () => clock, directory: async () => accounts, + peopleRoles: auth.auth, sendMail, ...overrides, }) - async function seed() { - await store.transaction(async ({ state: s }) => { - const people = [ - newPerson(s, profile(), "2026-10-01"), - newPerson(s, profile("Anna", "Bianchi"), "2026-10-01"), - newPerson(s, profile("Luca", "Verdi"), "2026-10-01"), - ] + /** P-0001 Mario (president), P-0002 Anna (vice), P-0003 Luca (member), all linked. */ + async function seed(linked = true) { + await store.transaction(async (u) => { + const people = [profile(), profile("Anna", "Bianchi"), profile("Luca", "Verdi")].map((p) => + newPerson(u.state, p, "seed", clock) + ) for (const [i, p] of people.entries()) { - p.accountSub = accounts[i].sub - p.profile.telegramId = accounts[i].telegramId - p.account = { - status: "linked", - email: accounts[i].email ?? "", - via: "IdP", - linkedOn: "2026-10-01", - how: "test", - } + if (linked) p.accountSub = accounts[i].sub + log(u, p.id, "seed", "Seeded", clock) } }) } return { service, store, + auth, state: () => structuredClone(state), + history: () => [...history], accounts, sendMail, seed, diff --git a/tests/people-postgres.fixture.ts b/tests/people-postgres.fixture.ts index 200d4ab..13d1373 100644 --- a/tests/people-postgres.fixture.ts +++ b/tests/people-postgres.fixture.ts @@ -1,13 +1,14 @@ import assert from "node:assert/strict" import { SQL } from "bun" +import { eq } from "drizzle-orm" import { drizzle } from "drizzle-orm/bun-sql" import { migrate } from "drizzle-orm/bun-sql/migrator" import { schema } from "@/db/schema" -import { identities } from "@/db/schema/people" -import { newPerson } from "@/people/model" +import { assignments, persons } from "@/db/schema/people" import { createPeopleService } from "@/people/service" import { createPeoplePgStore } from "@/people/store-pg" import type { Viewer } from "@/people/types" +import { fakeAuth } from "./people-auth" const connection = { hostname: "127.0.0.1", @@ -25,77 +26,108 @@ 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 viewer = (sub: string): Viewer => ({ sub, telegramId: null, can: (p) => permissionSet.has(p) }) + const viewer = (sub: string): Viewer => ({ + sub, + telegramId: null, + can: (p) => permissionSet.has(p), + holdsRole: () => false, + }) const hr = viewer("hr") const directory = [ - { sub: "mario", name: "Mario Rossi", email: "mario@example.org", telegramId: "101" }, - { sub: "anna", name: "Anna Bianchi", email: "anna@example.org", telegramId: "102" }, - { sub: "luca", name: "Luca Verdi", email: "luca@example.org", telegramId: "103" }, + { sub: "mario", name: "Mario Rossi", email: "mario@example.org" }, + { sub: "anna", name: "Anna Bianchi", email: "anna@example.org" }, ] + const auth = fakeAuth() const sent: string[] = [] - const people = createPeopleService({ - store, - dashboardUrl: "https://admin.example.org", - directory: async () => directory, - sendMail: async (m) => { - sent.push(m.id) - }, - }) - await store.transaction(async ({ state }) => { - for (const a of directory) { - const [firstName, lastName] = a.name.split(" ") - const p = newPerson( - state, - { - firstName, - lastName, - personalEmail: a.email, - phone: "", - telegramUsername: "", - course: "Informatica", - year: "2nd year", - campus: "Leonardo", - admin: true, - }, - "2026-10-01" - ) - p.profile.telegramId = a.telegramId - } + /** A new service reads Auth again instead of its cached answer. */ + const service = () => + createPeopleService({ + store, + dashboardUrl: "https://admin.example.org", + directory: async () => directory, + peopleRoles: auth.auth, + sendMail: async (m) => { + sent.push(m.id) + }, + }) + const people = service() + const input = (firstName: string) => ({ + firstName, + lastName: "Neri", + contactEmail: `${firstName.toLowerCase()}@example.org`, + phone: "", + telegramUsername: "", }) - assert.equal((await people.listPeople(hr)).length, 3) - checked.push("migrations and PostgreSQL metadata round-trip") - const created = await Promise.all( - ["Sara", "Paolo"].map((firstName) => - people.createPerson(hr, { - firstName, - lastName: "Neri", - personalEmail: `${firstName.toLowerCase()}@example.org`, - phone: "", - telegramUsername: "", - course: "Informatica", - year: "1st year", - campus: "Leonardo", - admin: false, - }) - ) - ) - assert.deepEqual(created.map((c) => c.id).sort(), ["P-0004", "P-0005"]) + const created = await Promise.all(["Sara", "Paolo", "Luca"].map((name) => people.createPerson(hr, input(name)))) + assert.deepEqual(created.map((c) => c.id).sort(), ["P-0001", "P-0002", "P-0003"]) checked.push("concurrent writes are serialized") + await people.assignAdmin(hr, { personId: "P-0001", since: "2026-10-01", capoId: null }) await people.linkAccount(hr, { personId: "P-0001", accountId: "mario", reason: "Checked in person" }) + assert.deepEqual(auth.held("mario"), ["admin"]) + await people.appointCapo(hr, { personId: "P-0001", since: "2026-10-01", scope: "Ingegneria Informatica" }) + await people.assignAdmin(hr, { personId: "P-0002", since: "2026-10-01", capoId: "P-0001" }) + const record = await people.getPerson(hr, { id: "P-0001" }) + assert.deepEqual( + record.assignments.map((a) => [a.kind, a.status, a.endedOn]), + [ + ["admin", "applied", null], + ["capo", "applied", null], + ] + ) + assert.equal( + record.activity[0].text, + "PoliNetwork Auth confirmed: Appointed Capo Admin from People (Ingegneria Informatica)" + ) + assert.equal((await people.listCapos(hr))[0].admins[0].id, "P-0002") + checked.push("assignments, role commands and the Capo relation round-trip") + + // Changing a team role in Auth ends one assignment and starts another for the same concept in one transaction. + auth.give("anna", "it-member", "Anna Bianchi") + assert.equal((await service().listPeople(hr)).length, 4) + auth.take("anna", "it-member") + auth.give("anna", "it-lead") + const anna = (await service().listPeople(hr)).find((p) => p.account.status === "linked" && p.account.sub === "anna") + assert.deepEqual( + anna?.assignments.map((a) => [a.teamRole, a.endedOn === null]), + [ + ["member", false], + ["lead", true], + ] + ) + checked.push("a record is created for a role given in Auth, and follows it") + + // Linking HR's record to that account folds the automatic one into it, in one transaction. + const automaticId = anna?.id as string + const { id: hrAnna } = await people.createPerson(hr, input("Anna")) + await people.addTeamMember(hr, { teamId: "it", personId: hrAnna, role: "lead", since: "2026-10-01", fields: {} }) + await service().linkAccount(hr, { personId: hrAnna, accountId: "anna", reason: "Same person" }) + const absorbed = await service().getPerson(hr, { id: hrAnna }) + assert.equal(absorbed.assignments.filter((a) => !a.endedOn).length, 1) + assert.ok(absorbed.activity.some((a) => a.text === "Created from a role held in PoliNetwork Auth")) + assert.equal((await db.select().from(persons).where(eq(persons.id, automaticId))).length, 0) + checked.push("an automatic record is absorbed by the record linked to its account") + await assert.rejects( - people.linkAccount(hr, { personId: "P-0002", accountId: "mario", reason: "Wrong person" }), + people.linkAccount(hr, { personId: "P-0003", accountId: "mario", reason: "Wrong person" }), /already linked/ ) - await people.unlinkAccount(hr, { personId: "P-0001" }) - await people.linkAccount(hr, { personId: "P-0002", accountId: "mario", reason: "Moved" }) - const rows = await db.select().from(identities) - assert.deepEqual( - rows.filter((i) => i.accountSub).map((i) => [i.personId, i.accountSub]), - [["P-0002", "mario"]] + await assert.rejects( + db.insert(assignments).values({ + id: crypto.randomUUID(), + personId: "P-0001", + kind: "admin", + since: "2026-10-01", + assignedBy: "x", + change: "start", + status: "applied", + }) ) - checked.push("an account moves between records without unique violations") + const [{ count }] = await client`select count(*)::int as count from people_persons where account_sub = 'mario'` + assert.equal(count, 1) + assert.equal((await db.select().from(persons)).length, 4) + checked.push("constraints hold one account and one current assignment per concept") await people.sendInvite(hr, { personId: "P-0003" }) await Promise.all([people.deliverPending(), people.deliverPending()]) diff --git a/tests/people-postgres.test.ts b/tests/people-postgres.test.ts index 46a5a3f..e6066f0 100644 --- a/tests/people-postgres.test.ts +++ b/tests/people-postgres.test.ts @@ -3,14 +3,14 @@ import { promisify } from "node:util" import { expect, it } from "vitest" it.skipIf(!process.env.SEED_TEST_DB_PORT)( - "persists People records, identities and the mail outbox in real PostgreSQL", + "persists People records, assignments, role commands and the mail outbox in real PostgreSQL", async () => { const { stdout } = await promisify(execFile)("bun", ["tests/people-postgres.fixture.ts"], { env: process.env, timeout: 60000, }) const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") - expect(result.checked).toHaveLength(4) + expect(result.checked).toHaveLength(6) }, 65000 ) diff --git a/tests/people-router.test.ts b/tests/people-router.test.ts index 8ed7597..002ecad 100644 --- a/tests/people-router.test.ts +++ b/tests/people-router.test.ts @@ -56,7 +56,7 @@ describe("People tRPC contract", () => { await expect( r.createCaller(context()).persons.create({ ...profile(), firstName: "X".repeat(81) }) ).rejects.toMatchObject({ code: "BAD_REQUEST" }) - expect(h.state().counters.person).toBe(3) + expect(Object.keys(h.state().persons)).toHaveLength(3) }) it("mounts every People procedure with a dashboard policy", () => { const r = makeRouter(harness().service) @@ -65,10 +65,15 @@ describe("People tRPC contract", () => { const defs = Object.entries(procedures) for (const [, proc] of defs) expect(proc._def.meta).toMatchObject({ policy: { user: { scope: "backend:admin" } } }) expect(Object.keys(procedures).sort()).toEqual([ + "admins.assign", "admins.end", + "admins.list", "admins.setCapoOfReference", - "admins.setCapoScope", "capo.get", + "capos.appoint", + "capos.end", + "capos.list", + "capos.setScope", "linking.invites", "linking.link", "linking.revokeInvite", diff --git a/tests/people-rules.test.ts b/tests/people-rules.test.ts new file mode 100644 index 0000000..b1780d5 --- /dev/null +++ b/tests/people-rules.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest" +import { type BoundRole, type PeopleRoleChange, peopleRoleChangeProblem } from "@/people/rules" +import { BOUND, permissions, viewer } from "./people-fixtures" + +const role = (key: string) => BOUND.find((r) => r.key === key) as BoundRole +const change = (overrides: Partial): PeopleRoleChange => ({ + actor: viewer("hr", permissions), + held: [], + targetSub: null, + role: role("admin"), + action: "assign", + unknownPermissions: "refuse", + ...overrides, +}) + +/** The cases of Auth's `people-binding.test.ts`, so both sides refuse the same changes. */ +describe("People role rules, as in PoliNetwork Auth", () => { + it("refuses giving yourself a role, and always lets you give one up", () => { + const self = viewer("hr", permissions) + expect(peopleRoleChangeProblem(change({ actor: self, targetSub: "hr" }))).toMatch(/give themselves/) + expect(peopleRoleChangeProblem(change({ actor: viewer("hr", []), targetSub: "hr", action: "unassign" }))).toBeNull() + }) + it("needs people:write and admin:access for admins", () => { + expect(peopleRoleChangeProblem(change({ actor: viewer("hr", ["people:write"]) }))).toMatch(/people:write/) + expect(peopleRoleChangeProblem(change({ actor: viewer("hr", ["admin:access", "people:write"]) }))).toBeNull() + }) + it("needs people:appoint for Capo Admins, and people:write for the admin role they inherit", () => { + const capo = role("capo-admin") + const writer = viewer("hr", ["admin:access", "people:write", "people:read"]) + expect(peopleRoleChangeProblem(change({ actor: writer, role: capo }))).toMatch(/Capo Admin needs people:appoint/) + const appointer = viewer("hr", ["admin:access", "people:appoint", "people:read"]) + expect(peopleRoleChangeProblem(change({ actor: appointer, role: capo }))).toBe( + "Changing this role needs people:write and admin:access." + ) + expect(peopleRoleChangeProblem(change({ actor: viewer("hr", permissions), role: capo }))).toBeNull() + }) + it("lets a team's Lead add and remove its members, but not appoint Leads or touch other teams", () => { + const lead = viewer("lead", ["admin:access"]) + const held = [{ kind: "team" as const, team: "it", role: "lead" as const }] + expect(peopleRoleChangeProblem(change({ actor: lead, held, role: role("it-member") }))).toBeNull() + expect( + peopleRoleChangeProblem(change({ actor: lead, held, role: role("it-member"), action: "unassign" })) + ).toBeNull() + expect(peopleRoleChangeProblem(change({ actor: lead, held, role: role("it-lead") }))).toMatch(/Lead needs/) + expect(peopleRoleChangeProblem(change({ actor: lead, held, role: role("hr-member") }))).toMatch( + /or leading the team/ + ) + }) + it("applies the rule of every inherited binding: a member role wrapping a Lead needs appointment rights", () => { + const wrapper: BoundRole = { ...role("it-member"), bindings: ["team:it:member", "team:it:lead"] } + const lead = viewer("lead", ["admin:access", "people:write"]) + expect(peopleRoleChangeProblem(change({ actor: lead, role: wrapper }))).toMatch(/Lead needs people:appoint/) + }) + it("bounds delegation: nobody hands out permissions they don't hold, except Master Admin", () => { + const writer = viewer("hr", ["admin:access", "people:write"]) + expect(peopleRoleChangeProblem(change({ actor: writer, role: role("hr-member") }))).toBeTruthy() + const lead = viewer("lead", ["admin:access"]) + const held = [{ kind: "team" as const, team: "hr", role: "lead" as const }] + expect(peopleRoleChangeProblem(change({ actor: lead, held, role: role("hr-member") }))).toBe( + "This role grants permissions you do not hold (people:read)." + ) + const master = viewer("master", ["admin:access", "people:write"], ["master-admin"]) + expect(peopleRoleChangeProblem(change({ actor: master, held, role: role("hr-member") }))).toBeNull() + }) + it("refuses a role whose permissions Auth didn't send for an unlinked record, and defers to Auth for a linked one", () => { + const opaque: BoundRole = { key: "admin", name: "Admin", binding: "admin" } + const writer = viewer("hr", ["admin:access", "people:write"]) + expect(peopleRoleChangeProblem(change({ actor: writer, role: opaque }))).toMatch(/didn't say which permissions/) + expect( + peopleRoleChangeProblem(change({ actor: writer, role: opaque, targetSub: "luca", unknownPermissions: "defer" })) + ).toBeNull() + }) + it("refuses roles that aren't bound to People", () => { + expect(peopleRoleChangeProblem(change({ role: { key: "x", name: "X", binding: "nope" } }))).toMatch(/not managed/) + }) +}) diff --git a/tests/people.test.ts b/tests/people.test.ts index ff6d1b5..b619463 100644 --- a/tests/people.test.ts +++ b/tests/people.test.ts @@ -1,142 +1,468 @@ import { describe, expect, it } from "vitest" import { myAreaSchema } from "@/people/contract" -import { harness, master, viewer } from "./people-fixtures" +import { DIRECTORY_MAX_AGE_MS, DIRECTORY_TTL_MS } from "@/people/service" +import { harness, master, permissions, profile, viewer } from "./people-fixtures" -describe("People authorization and projections", () => { - it("shows the signed-in person their own record without HR notes or activity", async () => { +const since = "2026-10-01" +const assignmentsOf = (h: ReturnType, personId: string) => + Object.values(h.state().assignments).filter((a) => a.personId === personId) + +describe("People records and Auth", () => { + it("keeps assignments of an unlinked record pending, without telling Auth", async () => { + const h = harness() + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + await h.service.assignAdmin(master, { personId: id, since, capoId: null }) + await h.service.addTeamMember(master, { teamId: "it", personId: id, role: "member", since, fields: {} }) + expect(assignmentsOf(h, id).map((a) => [a.kind, a.status, a.assignedBy])).toEqual([ + ["admin", "pending", "president"], + ["team", "pending", "president"], + ]) + expect(h.auth.state.calls).toEqual([]) + const record = await h.service.getPerson(master, { id }) + expect(record.account).toEqual({ status: "none" }) + expect(record.activity.map((a) => a.text)).toEqual(["Joined it as member", "Made admin", "Created the record"]) + }) + it("sends a linked record's change to Auth and shows it applied once Auth confirms it", async () => { const h = harness() await h.seed() - await h.service.setNote(master, { id: "P-0003", note: "HR only" }) - const mine = await h.service.getMyArea(viewer("member", ["people:self"])) - expect(myAreaSchema.parse(mine)).toMatchObject({ - state: "linked", - person: { id: "P-0003", notes: null, activity: [], profile: { personalEmail: "luca@example.org" } }, + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + expect(h.auth.state.calls).toEqual([ + { + id: expect.any(String), + actor: "president", + sub: "member", + reason: "Made admin from People", + changes: [{ kind: "admin", active: true }], + }, + ]) + expect(h.auth.held("member")).toEqual(["admin"]) + expect(assignmentsOf(h, "P-0003")).toMatchObject([ + { kind: "admin", status: "applied", change: "start", commandId: null }, + ]) + await h.service.endAdmin(master, { personId: "P-0003", reason: "Graduated" }) + expect(h.auth.held("member")).toEqual([]) + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ endedOn: "2026-10-18", change: "end", status: "applied" }]) + }) + it("shows Auth's refusal on the record and fails the dashboard call with it", async () => { + const h = harness() + await h.seed() + h.auth.state.refusal = { status: 403, message: "This role grants permissions you do not hold (people:read)." } + await expect( + h.service.addTeamMember(master, { teamId: "hr", personId: "P-0003", role: "member", since, fields: {} }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: expect.stringContaining("you do not hold (people:read)") }) + expect(assignmentsOf(h, "P-0003")).toMatchObject([ + { + team: "hr", + status: "refused", + refusal: "This role grants permissions you do not hold (people:read).", + endedOn: "2026-10-18", + }, + ]) + expect(Object.values(h.state().commands)).toMatchObject([{ status: "refused" }]) + expect((await h.service.getPerson(master, { id: "P-0003" })).activity[0].text).toMatch(/PoliNetwork Auth refused/) + }) + it("keeps the role current when Auth refuses to end it", 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.endAdmin(master, { personId: "P-0003", reason: "Done" })).rejects.toMatchObject({ + code: "CONFLICT", }) - expect(JSON.stringify(mine)).not.toContain("accountSub") - expect(await h.service.getPerson(master, { id: "P-0003" })).toMatchObject({ notes: "HR only" }) + expect(assignmentsOf(h, "P-0003")).toMatchObject([ + { endedOn: null, change: "end", status: "refused", refusal: expect.stringContaining("inherited") }, + ]) + }) + it("creates a linked record for someone given a bound role by hand in Auth, and follows Auth afterwards", async () => { + const h = harness() + h.auth.give("giulia", "it-member", "Giulia Gialli Neri", "2026-09-01") + const [p] = await h.service.listPeople(master) + expect(p).toMatchObject({ + firstName: "Giulia", + lastName: "Gialli Neri", + contactEmail: "giulia@polinetwork.org", + account: { status: "linked", sub: "giulia" }, + assignments: [{ kind: "team", team: "it", teamRole: "member", since: "2026-09-01", assignedBy: "auth" }], + }) + h.auth.take("giulia", "it-member") + h.auth.give("giulia", "it-lead") + h.advance(DIRECTORY_TTL_MS + 1) + const [after] = await h.service.listPeople(master) + expect(after.assignments.map((a) => [a.teamRole, a.endedOn, a.endReason])).toEqual([ + ["member", "2026-10-18", "Changed in PoliNetwork Auth"], + ["lead", null, null], + ]) + expect(after.assignments[1].since).toBe("2026-10-18") + h.auth.take("giulia", "it-lead") + h.advance(DIRECTORY_TTL_MS + 1) + const [gone] = await h.service.listPeople(master) + expect(gone.assignments.every((a) => a.endedOn)).toBe(true) + expect(Object.keys(h.state().persons)).toEqual(["P-0001"]) }) - it("scopes Leads to their confirmed teams and requires appointment rights to end another Lead", async () => { + it("relates admins to their Capo Admin's record", async () => { const h = harness() await h.seed() - await h.service.addTeamMember(master, { - teamId: "it", - personId: "P-0001", - role: "lead", - since: "2026-10-01", - fields: {}, - }) - const lead = viewer("president", ["people:self", "people:read"]) - expect((await h.service.listTeams(lead)).map((t) => t.id)).toEqual(["it"]) - await h.service.addTeamMember(lead, { - teamId: "it", - personId: "P-0003", - role: "member", - since: "2026-10-01", - fields: { areas: ["Backend"] }, + await h.service.assignAdmin(master, { personId: "P-0002", since, capoId: null }) + await h.service.appointCapo(master, { personId: "P-0002", since, scope: "Ingegneria Informatica" }) + expect(h.auth.held("vice")).toEqual(["admin", "capo-admin"]) + await expect(h.service.assignAdmin(master, { personId: "P-0003", since, capoId: "P-0001" })).rejects.toMatchObject({ + code: "BAD_REQUEST", + }) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: "P-0002" }) + const capos = await h.service.listCapos(master) + expect(capos).toMatchObject([ + { person: { id: "P-0002" }, capo: { capoScope: "Ingegneria Informatica" }, admins: [{ id: "P-0003" }] }, + ]) + const admins = await h.service.listAdmins(master) + expect(admins.find((a) => a.person.id === "P-0003")?.admin.capoOfReference).toEqual({ + id: "P-0002", + name: "Anna Bianchi", + }) + const area = await h.service.getCapoArea(viewer("vice", ["people:self"])) + expect(area).toMatchObject({ + scope: "Ingegneria Informatica", + admins: [{ id: "P-0003", contactEmail: null, phone: null }], }) - await expect(h.service.listTeamCandidates(lead, { teamId: "hr" })).rejects.toMatchObject({ code: "FORBIDDEN" }) + await expect(h.service.endAdmin(master, { personId: "P-0002", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + }) + await h.service.endCapo(master, { personId: "P-0002", reason: "Stepped down" }) + expect(Object.values(h.state().assignments).find((a) => a.personId === "P-0003")?.capoOfReferenceId).toBeNull() + expect(h.auth.held("vice")).toEqual(["admin"]) + }) + it("retries a command whose answer was lost with the same ID, and Auth applies it once", async () => { + const h = harness() + await h.seed() + h.auth.state.mode = "lost" + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "sent" }]) + const [command] = Object.values(h.state().commands) + expect(command).toMatchObject({ status: "queued", attempts: 1 }) + await expect(h.service.endAdmin(master, { personId: "P-0003", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + message: expect.stringContaining("waiting for PoliNetwork Auth"), + }) + await h.service.deliverPending() + expect(h.auth.state.calls.map((c) => c.id)).toEqual([command.id, command.id]) + expect(h.auth.applied.size).toBe(1) + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "applied" }]) + await h.service.deliverPending() + expect(h.auth.state.calls).toHaveLength(2) + }) + it("keeps working on Auth's last answer during a short outage, and stops after an hour", async () => { + const h = harness() + await h.seed() + h.auth.give("member", "it-member") + expect((await h.service.listTeams(master)).find((t) => t.id === "it")?.members).toHaveLength(1) + h.auth.state.mode = "down" + h.advance(DIRECTORY_TTL_MS + 1) + await h.service.assignAdmin(master, { personId: "P-0002", since, capoId: null }) + expect(assignmentsOf(h, "P-0002")).toMatchObject([{ status: "sent" }]) + h.auth.state.mode = "up" + await h.service.deliverPending() + expect(assignmentsOf(h, "P-0002")).toMatchObject([{ status: "applied" }]) + h.auth.state.mode = "down" + h.advance(DIRECTORY_MAX_AGE_MS + 1) + await expect(h.service.listPeople(master)).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + }) + it("refuses concepts Auth doesn't bind, or binds ambiguously", async () => { + const h = harness() + await h.seed() await expect( - h.service.endTeamMembership(lead, { - teamId: "it", - personId: "P-0001", - lastDay: "2026-10-18", - reason: "Leaving", - note: "", - }) - ).rejects.toMatchObject({ code: "FORBIDDEN" }) - await h.service.endTeamMembership(lead, { - teamId: "it", - personId: "P-0003", - lastDay: "2026-10-18", - reason: "Leaving", - note: "", + h.service.addTeamMember(master, { teamId: "design", personId: "P-0003", role: "member", since, fields: {} }) + ).rejects.toMatchObject({ code: "BAD_REQUEST", message: expect.stringContaining("No role is bound") }) + const teams = await h.service.listTeams(master) + expect(teams.find((t) => t.id === "design")?.assignable).toEqual({ member: false, lead: false }) + expect(teams.find((t) => t.id === "hr")?.assignable).toEqual({ member: true, lead: false }) + }) +}) + +describe("Review regressions", () => { + it("ends a Capo Admin whose binding Auth removed, and takes their area away", async () => { + const h = harness() + await h.seed() + await h.service.assignAdmin(master, { personId: "P-0002", since, capoId: null }) + await h.service.appointCapo(master, { personId: "P-0002", since, scope: "Design" }) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: "P-0002" }) + const capoRole = h.auth.roles.findIndex((r) => r.binding === "capo") + h.auth.roles.splice(capoRole, 1) + h.advance(DIRECTORY_TTL_MS + 1) + await expect(h.service.getCapoArea(viewer("vice", ["people:self"]))).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.service.listPeople(master) + expect(Object.values(h.state().assignments).find((a) => a.kind === "capo")).toMatchObject({ + endReason: "No role is bound to it in PoliNetwork Auth", }) - expect(h.state().persons["P-0003"].teams[0].endedOn).toBe("2026-10-18") + expect(Object.values(h.state().assignments).find((a) => a.personId === "P-0003")?.capoOfReferenceId).toBeNull() }) - it("does not expose former team members to a Team Lead", async () => { + it("keeps the admins' Capo Admin when Auth refuses to end the appointment", async () => { const h = harness() await h.seed() - await h.service.addTeamMember(master, { - teamId: "it", - personId: "P-0001", - role: "lead", - since: "2026-10-01", - fields: {}, + await h.service.assignAdmin(master, { personId: "P-0002", since, capoId: null }) + await h.service.appointCapo(master, { personId: "P-0002", since, scope: "Design" }) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: "P-0002" }) + h.auth.state.refusal = { status: 409, message: "The capo role is inherited. Change its granting role in Auth." } + await expect(h.service.endCapo(master, { personId: "P-0002", reason: "x" })).rejects.toMatchObject({ + code: "CONFLICT", + }) + expect((await h.service.listCapos(master))[0].admins).toEqual([{ id: "P-0003", name: "Luca Verdi" }]) + h.auth.state.refusal = null + await h.service.endCapo(master, { personId: "P-0002", reason: "Stepped down" }) + expect(await h.service.listCapos(master)).toEqual([]) + expect(Object.values(h.state().assignments).find((a) => a.personId === "P-0003")?.capoOfReferenceId).toBeNull() + }) + it("keeps Auth's last answer as the outage fallback after a confirmed change", async () => { + const h = harness() + await h.seed() + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + h.auth.state.mode = "down" + await expect(h.service.listPeople(master)).resolves.toHaveLength(3) + h.advance(DIRECTORY_MAX_AGE_MS + 1) + await expect(h.service.listPeople(master)).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + }) + it("keeps a command queued when Auth refuses the backend itself, not the change", async () => { + const h = harness() + await h.seed() + h.auth.state.refusal = { status: 403, message: "Forbidden" } + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "sent", endedOn: null }]) + h.auth.state.refusal = null + await h.service.deliverPending() + expect(assignmentsOf(h, "P-0003")).toMatchObject([{ status: "applied" }]) + }) + it("sends Auth reasons it accepts, however long the link reason", async () => { + const h = harness() + await h.seed(false) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + await h.service.linkAccount(master, { personId: "P-0003", accountId: "member", reason: "x".repeat(500) }) + expect(h.auth.state.calls[0].reason.length).toBeLessThanOrEqual(500) + }) + it("lets anyone allowed end a pending assignment even when Auth doesn't send role permissions", async () => { + const h = harness() + for (const role of h.auth.roles) { + delete role.permissions + delete role.bindings + } + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + const writer = viewer("vice", ["admin:access", "people:write", "people:read"]) + await expect(h.service.assignAdmin(writer, { personId: id, since, capoId: null })).rejects.toMatchObject({ + code: "FORBIDDEN", + message: expect.stringContaining("didn't say which permissions"), + }) + await h.service.assignAdmin(viewer("president", permissions, ["master-admin"]), { + personId: id, + since, + capoId: null, }) + await h.service.endAdmin(writer, { personId: id, reason: "Mistake" }) + expect(assignmentsOf(h, id)).toMatchObject([{ endedOn: "2026-10-18", status: "pending" }]) + }) +}) + +describe("Linking absorbs the record made for roles given in Auth", () => { + it("folds the automatic record into the one HR made, keeping what Auth holds and HR's data", async () => { + const h = harness() + h.auth.give("member", "it-member", "Luca Verdi", "2026-09-01") + expect((await h.service.listPeople(master)).map((p) => p.id)).toEqual(["P-0001"]) + const { id } = await h.service.createPerson(master, profile("Luca", "Verdi")) await h.service.addTeamMember(master, { teamId: "it", - personId: "P-0003", + personId: id, role: "member", - since: "2026-10-01", - fields: {}, + since, + fields: { github: "luca" }, }) - await h.service.endTeamMembership(master, { - teamId: "it", - personId: "P-0003", - lastDay: "2026-10-18", - reason: "Leaving", - note: "", + await h.service.assignAdmin(master, { personId: id, since, capoId: null }) + await h.service.linkAccount(viewer("vice", permissions), { + personId: id, + accountId: "member", + reason: "Same person", }) - const teams = await h.service.listTeams(viewer("president", ["people:self"])) - expect(teams[0].members.map((p) => p.id)).toEqual(["P-0001"]) + expect(Object.keys(h.state().persons)).toEqual([id]) + const record = await h.service.getPerson(master, { id }) + expect(record.contactEmail).toBe("luca@example.org") + const current = record.assignments.filter((a) => !a.endedOn) + expect(current.map((a) => [a.kind, a.status, a.assignedBy])).toEqual([ + ["team", "applied", "auth"], + ["admin", "applied", "president"], + ]) + expect(current[0]).toMatchObject({ since: "2026-09-01", fields: { github: "luca" } }) + expect(h.auth.state.calls).toMatchObject([{ actor: "vice", changes: [{ kind: "admin", active: true }] }]) + expect(record.activity.map((a) => a.text)).toContain("Created from a role held in PoliNetwork Auth") }) - it("shows a Capo Admin only the admins they are the reference for, without personal emails", async () => { + it("never merges records people made", async () => { + const h = harness() + h.auth.give("member", "it-member", "Luca Verdi") + await h.service.setNote(master, { id: "P-0001", note: "Checked" }) + const { id } = await h.service.createPerson(master, profile("Luca", "Verdi")) + await expect( + h.service.linkAccount(master, { personId: id, accountId: "member", reason: "Same person" }) + ).rejects.toMatchObject({ code: "CONFLICT", message: "This account is already linked to P-0001" }) + }) +}) + +describe("Pending assignments follow Auth's rules", () => { + it("refuses self-grants on one's own linked record", async () => { const h = harness() await h.seed() - await h.service.setCapoScope(master, { personId: "P-0001", scope: "Ingegneria Informatica" }) - await h.service.setCapoOfReference(master, { personId: "P-0003", capoId: "P-0001" }) - const capo = await h.service.getCapoArea(viewer("president", ["people:self"])) - expect(capo.scope).toBe("Ingegneria Informatica") - expect(capo.admins.map((p) => p.id)).toEqual(["P-0003"]) - expect(capo.admins[0].profile.personalEmail).toBeNull() - await expect(h.service.getCapoArea(viewer("member", ["people:self"]))).rejects.toMatchObject({ + await expect(h.service.assignAdmin(master, { personId: "P-0001", since, capoId: null })).rejects.toMatchObject({ code: "FORBIDDEN", + message: "Nobody can give themselves a role.", }) }) - it("grants no record roles to an account that is not linked", async () => { + it("needs the right permission per kind", async () => { const h = harness() - await h.seed() - await h.store.transaction(async ({ state }) => { - const p = state.persons["P-0001"] - p.accountSub = null - p.account = { status: "none" } - if (p.admin) p.admin.capoScope = "IT" - p.teams.push({ team: "it", role: "lead", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + const writer = viewer("vice", ["admin:access", "people:write", "people:read"]) + await expect( + h.service.addTeamMember(writer, { teamId: "it", personId: id, role: "lead", since, fields: {} }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: expect.stringContaining("people:appoint") }) + await h.service.assignAdmin(writer, { personId: id, since, capoId: null }) + await expect(h.service.appointCapo(writer, { personId: id, since, scope: "Design" })).rejects.toMatchObject({ + code: "FORBIDDEN", + message: expect.stringContaining("Capo Admin needs"), }) - const v = viewer("president", ["people:self"], "101") - expect(await h.service.getMyArea(v)).toEqual({ state: "none" }) - expect(await h.service.getMyRoles(v)).toEqual({ capoScope: null, leads: [] }) - await expect(h.service.getCapoArea(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) }) - it("prevents account takeover and invalidates old invitation tokens", async () => { + it("lets the Lead Auth knows of manage their team's members, within the permissions they hold", async () => { const h = harness() await h.seed() + h.auth.give("vice", "it-lead") + h.auth.give("vice", "hr-member") + const lead = viewer("vice", ["admin:access", "people:self", "people:read"]) + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + await h.service.addTeamMember(lead, { teamId: "it", personId: id, role: "member", since, fields: {} }) + expect(assignmentsOf(h, id)).toMatchObject([{ team: "it", status: "pending", assignedBy: "vice" }]) await expect( - h.service.linkAccount(master, { personId: "P-0003", accountId: "president", reason: "Test" }) - ).rejects.toMatchObject({ code: "CONFLICT" }) - await h.service.unlinkAccount(master, { personId: "P-0003" }) + h.service.addTeamMember(lead, { teamId: "hr", personId: "P-0003", role: "member", since, fields: {} }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + expect((await h.service.listTeams(viewer("vice", ["people:self"]))).map((t) => t.id)).toEqual(["it"]) + await h.service.endTeamMembership(lead, { teamId: "it", personId: id, reason: "Left" }) + expect(assignmentsOf(h, id)).toMatchObject([{ endedOn: "2026-10-18", status: "pending" }]) + }) + it("refuses a pending role whose permissions the assigner lacks, even when Auth would only see it at link time", async () => { + const h = harness() + await h.seed() + h.auth.give("vice", "it-lead") + const lead = viewer("vice", ["admin:access"]) + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + await expect( + h.service.addTeamMember(lead, { teamId: "it", personId: id, role: "member", since, fields: {} }) + ).resolves.toBeUndefined() + await expect( + h.service.addTeamMember(master, { teamId: "hr", personId: id, role: "member", since, fields: {} }) + ).resolves.toBeUndefined() + const writer = viewer("vice", ["admin:access", "people:write"]) + await expect(h.service.appointCapo(writer, { personId: id, since, scope: "x" })).rejects.toMatchObject({ + code: "FORBIDDEN", + }) + const { id: other } = await h.service.createPerson(master, profile("Paolo", "Neri")) + await expect( + h.service.addTeamMember(writer, { teamId: "hr", personId: other, role: "member", since, fields: {} }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: expect.stringContaining("(people:read)") }) + }) +}) + +describe("Linking sends pending assignments", () => { + it("acts as whoever links by hand", async () => { + const h = harness() + await h.seed(false) + await h.service.assignAdmin(master, { personId: "P-0003", since, capoId: null }) + 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" }]) + }) + it("acts as each assigner when the invitee accepts, so nobody grants themselves a role", 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().outbox).at(-1)?.text.split("peopleInvite=")[1] ?? "" + const first = Object.values(h.state().mail).at(-1)?.text.split("peopleInvite=")[1] ?? "" await h.service.sendInvite(master, { personId: "P-0003" }) - await expect(h.service.acceptInvite(viewer("member", ["people:self"]), { token: first })).rejects.toMatchObject({ - code: "NOT_FOUND", - }) - const last = Object.values(h.state().outbox).at(-1)?.text.split("peopleInvite=")[1] ?? "" + 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({ code: "NOT_FOUND", }) - await h.service.acceptInvite(viewer("member", ["people:self"]), { token: last }) + 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.auth.held("member")).toEqual(["admin", "it-member"]) + expect(await h.service.getMyRoles(invitee)).toEqual({ capoScope: null, leads: [] }) + }) + 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" }) 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 () => { + const h = harness() + await h.seed() + await expect( + h.service.linkAccount(master, { personId: "P-0003", accountId: "president", reason: "Test" }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: "Ask someone else to link your own account" }) + const { id } = await h.service.createPerson(master, profile("Sara", "Neri")) + 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" }) + 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" }) + expect(h.state().persons["P-0003"].accountSub).toBeNull() + }) +}) + +describe("People projections", () => { + it("shows the signed-in person their own record without HR notes or activity", async () => { + const h = harness() + await h.seed() + await h.service.setNote(master, { id: "P-0003", note: "HR only" }) + const mine = await h.service.getMyArea(viewer("member", ["people:self"])) + expect(myAreaSchema.parse(mine)).toMatchObject({ + state: "linked", + person: { id: "P-0003", notes: null, activity: [], contactEmail: "luca@example.org" }, + }) + expect(await h.service.getPerson(master, { id: "P-0003" })).toMatchObject({ notes: "HR only" }) + }) + it("hides contacts and account links without people:read", async () => { + const h = harness() + await h.seed() + h.auth.give("vice", "it-lead") + h.auth.give("member", "it-member") + const [team] = await h.service.listTeams(viewer("vice", ["people:self"])) + expect(team.members.find((p) => p.id === "P-0003")).toMatchObject({ account: { status: "none" } }) + }) + it("gives no area to an account without a record", async () => { + const h = harness() + const v = viewer("stranger", ["people:self"]) + expect(await h.service.getMyArea(v)).toEqual({ state: "none" }) + expect(await h.service.getMyRoles(v)).toEqual({ capoScope: null, leads: [] }) + await expect(h.service.getCapoArea(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) }) }) describe("People mail outbox", () => { async function invited() { const h = harness() - await h.seed() - await h.service.unlinkAccount(master, { personId: "P-0003" }) + await h.seed(false) await h.service.sendInvite(master, { personId: "P-0003" }) - const [mail] = Object.values(h.state().outbox) + const [mail] = Object.values(h.state().mail) return { h, mail } } it("sends a queued invitation once across concurrent workers", async () => { @@ -149,7 +475,7 @@ describe("People mail outbox", () => { subject: mail.subject, text: expect.stringContaining("https://admin.example.org/dashboard/account/me?peopleInvite="), }) - expect(h.state().outbox[mail.id]).toMatchObject({ status: "sent", error: null }) + expect(h.state().mail[mail.id]).toMatchObject({ status: "sent", error: null }) await h.service.deliverPending() expect(h.sendMail).toHaveBeenCalledTimes(1) }) @@ -157,18 +483,18 @@ describe("People mail outbox", () => { const { h, mail } = await invited() h.sendMail.mockRejectedValueOnce(new Error("Mailbox unavailable")) await h.service.deliverPending() - expect(h.state().outbox[mail.id]).toMatchObject({ status: "failed", error: "Mailbox unavailable" }) + expect(h.state().mail[mail.id]).toMatchObject({ status: "failed", error: "Mailbox unavailable" }) await h.service.deliverPending() expect(h.sendMail).toHaveBeenCalledTimes(1) }) it("does not resend mail whose outcome is unknown after a crash", async () => { const { h, mail } = await invited() await h.store.transaction(async ({ state }) => { - Object.assign(state.outbox[mail.id], { status: "sending", attemptedAt: "2026-10-18T09:00:00Z" }) + Object.assign(state.mail[mail.id], { status: "sending", attemptedAt: "2026-10-18T09:00:00Z" }) }) await h.service.deliverPending() expect(h.sendMail).not.toHaveBeenCalled() - expect(h.state().outbox[mail.id]).toMatchObject({ + expect(h.state().mail[mail.id]).toMatchObject({ status: "failed", error: expect.stringContaining("outcome unknown"), }) From c2c48de24e831ebc1050abba0eba9afaeb3d9f45 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Fri, 30 Oct 2026 18:33:40 +0100 Subject: [PATCH 2/2] fix(people): keep person IDs, directory snapshots and merged activity consistent - Allocate person IDs from a monotonic `person` counter, so the ID of a record absorbed into another is never given again. - Persist when the last applied directory read started (`directoryReadAt`) and skip older snapshots; keep the cached snapshot when an answer from an earlier read arrives late. Widen `people_counters.value` to bigint to hold the timestamp. - Move activity written in the same transaction for a merged record onto the surviving one, so it no longer violates the activity foreign key. The PostgreSQL fixture only passed because a stale snapshot ended the automatic record's IT Lead; HR's record now joins as a member instead. --- drizzle/0031_people_records.sql | 2 +- drizzle/meta/0031_snapshot.json | 2 +- src/db/schema/people/index.ts | 4 +++- src/people/model.ts | 11 ++++++--- src/people/service.ts | 16 +++++++++---- src/people/store-pg.ts | 8 ++++++- src/people/types.ts | 5 +++- tests/people-postgres.fixture.ts | 19 ++++++++++++++- tests/people-postgres.test.ts | 2 +- tests/people.test.ts | 40 ++++++++++++++++++++++++++++++-- 10 files changed, 93 insertions(+), 16 deletions(-) diff --git a/drizzle/0031_people_records.sql b/drizzle/0031_people_records.sql index 0e04514..95cd331 100644 --- a/drizzle/0031_people_records.sql +++ b/drizzle/0031_people_records.sql @@ -33,7 +33,7 @@ CREATE TABLE "people_assignments" ( --> statement-breakpoint CREATE TABLE "people_counters" ( "key" text PRIMARY KEY NOT NULL, - "value" integer NOT NULL + "value" bigint NOT NULL ); --> statement-breakpoint CREATE TABLE "people_invites" ( diff --git a/drizzle/meta/0031_snapshot.json b/drizzle/meta/0031_snapshot.json index e0739cd..44a61ad 100644 --- a/drizzle/meta/0031_snapshot.json +++ b/drizzle/meta/0031_snapshot.json @@ -1264,7 +1264,7 @@ }, "value": { "name": "value", - "type": "integer", + "type": "bigint", "primaryKey": false, "notNull": true } diff --git a/src/db/schema/people/index.ts b/src/db/schema/people/index.ts index ec102ca..13e9f1c 100644 --- a/src/db/schema/people/index.ts +++ b/src/db/schema/people/index.ts @@ -1,6 +1,7 @@ import { sql } from "drizzle-orm" import { type AnyPgColumn, + bigint, check, date, index, @@ -150,7 +151,8 @@ export const activity = createTable.people( export const counters = createTable.people("counters", { key: text().primaryKey(), - value: integer().notNull(), + /** Wide enough for a timestamp in milliseconds, like `directoryReadAt`. */ + value: bigint({ mode: "number" }).notNull(), }) export const schema = { diff --git a/src/people/model.ts b/src/people/model.ts index de9113d..b1008ac 100644 --- a/src/people/model.ts +++ b/src/people/model.ts @@ -79,10 +79,15 @@ export function clearCapoReferences(u: UnitOfWork, capoId: string, actor: string } const blank = (value: string) => value.trim() || null -/** The next `P-0000` ID, or null once the four digits are used up. */ +/** + * Allocates the next `P-0000` ID, or null once the four digits are used up. The `person` counter only moves + * forward, so the ID of a record merged into another is never given again. + */ export function nextPersonId(s: PeopleState) { - const sequence = Math.max(0, ...Object.keys(s.persons).map((id) => Number(id.slice(2)))) + 1 - return sequence > 9999 ? null : `P-${String(sequence).padStart(4, "0")}` + const sequence = Math.max(s.counters.person ?? 0, ...Object.keys(s.persons).map((id) => Number(id.slice(2)))) + 1 + if (sequence > 9999) return null + s.counters.person = sequence + return `P-${String(sequence).padStart(4, "0")}` } export function newPerson(s: PeopleState, input: C.PersonInput, actor: string, now: Date): Person { const at = now.toISOString() diff --git a/src/people/service.ts b/src/people/service.ts index cd5f935..8569a54 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -83,7 +83,10 @@ export function createPeopleService(options: PeopleOptions) { // 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 { - directoryRead = { value: await peopleRoles.directory(), at, revision } + const value = await peopleRoles.directory() + // Answers can arrive out of order: one from a read that started earlier never replaces a later one. + if (directoryRead && at < directoryRead.at) return directoryRead + directoryRead = { value, at, revision } stale = false } catch (error) { if (!directoryRead || at - directoryRead.at > DIRECTORY_MAX_AGE_MS) @@ -108,9 +111,14 @@ export function createPeopleService(options: PeopleOptions) { const deliveries: { id: string; strict: boolean }[] = [] const result = await store.transaction(async (u) => { if (read) { - // An older answer than the register's last confirmation would undo it: read again next time. - if (read.revision === (u.state.counters.roleRevision ?? 0)) syncDirectory(u, read.value, clock()) - else stale = true + // 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 { + syncDirectory(u, read.value, clock()) + u.state.counters.directoryReadAt = read.at + } } return fn(u, { directory: read?.value ?? null, diff --git a/src/people/store-pg.ts b/src/people/store-pg.ts index 3ea9a59..031a567 100644 --- a/src/people/store-pg.ts +++ b/src/people/store-pg.ts @@ -131,8 +131,14 @@ async function saveState(tx: Transaction, uow: UnitOfWork, before: PeopleState) for (const [key, value] of Object.entries(state.counters)) if (before.counters[key] !== value) await tx.insert(counters).values({ key, value }).onConflictDoUpdate({ target: counters.key, set: { value } }) + // A record merged in this transaction may never have been saved: its new entries go straight to `into`. + const mergedInto = new Map(merges.map((m) => [m.from, m.into])) + const survivor = (personId: string): string => + mergedInto.has(personId) ? survivor(mergedInto.get(personId) as string) : personId if (uow.activity.length) - await tx.insert(activity).values(uow.activity.map((entry) => ({ ...entry, at: new Date(entry.at) }))) + await tx + .insert(activity) + .values(uow.activity.map((entry) => ({ ...entry, personId: survivor(entry.personId), at: new Date(entry.at) }))) for (const { from, into } of merges) { await tx.update(activity).set({ personId: into }).where(eq(activity.personId, from)) await tx.delete(persons).where(eq(persons.id, from)) diff --git a/src/people/types.ts b/src/people/types.ts index acb90fb..f92abbd 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -95,7 +95,10 @@ export type PeopleState = { commands: Record invites: Record mail: Record - /** `roleRevision` advances whenever Auth confirms or refuses a role change. */ + /** + * `roleRevision` advances whenever Auth confirms or refuses a role change; `person` is the last person ID + * given; `directoryReadAt` is when the last directory read applied to the register started, in milliseconds. + */ counters: Record } export const emptyState = (): PeopleState => ({ diff --git a/tests/people-postgres.fixture.ts b/tests/people-postgres.fixture.ts index 13d1373..55a0e7b 100644 --- a/tests/people-postgres.fixture.ts +++ b/tests/people-postgres.fixture.ts @@ -101,7 +101,8 @@ try { // Linking HR's record to that account folds the automatic one into it, in one transaction. const automaticId = anna?.id as string const { id: hrAnna } = await people.createPerson(hr, input("Anna")) - await people.addTeamMember(hr, { teamId: "it", personId: hrAnna, role: "lead", since: "2026-10-01", fields: {} }) + // As a member: the automatic record already leads IT, and an older answer from Auth must not undo that. + await people.addTeamMember(hr, { teamId: "it", personId: hrAnna, role: "member", since: "2026-10-01", fields: {} }) await service().linkAccount(hr, { personId: hrAnna, accountId: "anna", reason: "Same person" }) const absorbed = await service().getPerson(hr, { id: hrAnna }) assert.equal(absorbed.assignments.filter((a) => !a.endedOn).length, 1) @@ -134,6 +135,22 @@ try { assert.equal(sent.length, 1) assert.equal((await people.listInvites(hr))[0].personId, "P-0003") checked.push("an invitation is delivered once from the durable outbox") + + // A service that hasn't read Auth yet makes the automatic record and absorbs it in the linking transaction. + directory.push({ sub: "luca", name: "Luca Neri", email: "luca@example.org" }) + const { id: hrLuca } = await people.createPerson(hr, input("Luca")) + auth.give("luca", "it-member", "Luca Neri") + await service().linkAccount(hr, { personId: hrLuca, accountId: "luca", reason: "Same person" }) + const luca = await service().getPerson(hr, { id: hrLuca }) + assert.deepEqual( + luca.assignments.filter((a) => !a.endedOn).map((a) => [a.team, a.teamRole]), + [["it", "member"]] + ) + assert.ok(luca.activity.some((a) => a.text === "Created from a role held in PoliNetwork Auth")) + const absorbedId = luca.activity.find((a) => a.text.startsWith("Absorbed "))?.text.split(/[ ,]/)[1] as string + const { id: next } = await people.createPerson(hr, input("Giulia")) + assert.ok(next > absorbedId, `${next} reuses or precedes the absorbed ${absorbedId}`) + checked.push("a record made and absorbed in one transaction keeps its history, and its ID isn't given again") console.log(JSON.stringify({ checked })) } finally { await client.close() diff --git a/tests/people-postgres.test.ts b/tests/people-postgres.test.ts index e6066f0..4602cb8 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(6) + expect(result.checked).toHaveLength(7) }, 65000 ) diff --git a/tests/people.test.ts b/tests/people.test.ts index b619463..44ade2e 100644 --- a/tests/people.test.ts +++ b/tests/people.test.ts @@ -1,7 +1,7 @@ -import { describe, expect, it } from "vitest" +import { describe, expect, it, vi } from "vitest" import { myAreaSchema } from "@/people/contract" import { DIRECTORY_MAX_AGE_MS, DIRECTORY_TTL_MS } from "@/people/service" -import { harness, master, permissions, profile, viewer } from "./people-fixtures" +import { fakeAuth, harness, master, permissions, profile, viewer } from "./people-fixtures" const since = "2026-10-01" const assignmentsOf = (h: ReturnType, personId: string) => @@ -256,6 +256,31 @@ describe("Review regressions", () => { await h.service.endAdmin(writer, { personId: id, reason: "Mistake" }) expect(assignmentsOf(h, id)).toMatchObject([{ endedOn: "2026-10-18", status: "pending" }]) }) + it("never lays an answer from Auth over one from a read that started later", async () => { + const auth = fakeAuth() + const gates: (() => void)[] = [] + let hold = true + const h = harness({ + peopleRoles: { + change: auth.auth.change, + async directory() { + const answer = await auth.auth.directory() + if (hold) await new Promise((resolve) => gates.push(resolve)) + return answer + }, + }, + }) + auth.give("member", "it-member", "Luca Verdi") + const slow = h.service.listPeople(master) + await vi.waitFor(() => expect(gates).toHaveLength(1)) + hold = false + auth.take("member", "it-member") + h.advance(1) + await expect(h.service.listPeople(master)).resolves.toEqual([]) + gates[0]() + await expect(slow).resolves.toEqual([]) + expect(h.state().persons).toEqual({}) + }) }) describe("Linking absorbs the record made for roles given in Auth", () => { @@ -289,6 +314,17 @@ describe("Linking absorbs the record made for roles given in Auth", () => { expect(h.auth.state.calls).toMatchObject([{ actor: "vice", changes: [{ kind: "admin", active: true }] }]) expect(record.activity.map((a) => a.text)).toContain("Created from a role held in PoliNetwork Auth") }) + it("never gives the absorbed record's ID to another record", async () => { + const h = harness() + const { id } = await h.service.createPerson(master, profile("Luca", "Verdi")) + h.auth.give("member", "it-member", "Luca Verdi") + h.advance(DIRECTORY_TTL_MS + 1) + await h.service.linkAccount(viewer("vice", permissions), { personId: id, accountId: "member", reason: "Same" }) + expect(h.history().map((a) => a.text)).toContain( + "Absorbed P-0002, created for the account's roles in PoliNetwork Auth" + ) + expect(await h.service.createPerson(master, profile("Sara", "Neri"))).toEqual({ id: "P-0003" }) + }) it("never merges records people made", async () => { const h = harness() h.auth.give("member", "it-member", "Luca Verdi")