⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(auth): manage profile fields and back-channel logout for custom OIDC
tiran1332158a5a29b38
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9c72bb11c..b5cb200ed 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -219,7 +219,7 @@ The root `package.json` includes scripts to keep locale files in sync:1. Create a new file in [`i18n/`](./i18n) using a locale code filename such as `fr-FR.json`.2. Copy [`i18n/en-US.json`](./i18n/en-US.json) and translate the values.-3. Register the locale in [`i18n/resources.ts`](./i18n/resources.ts) by updating `supportedLocales` and `resources`.+3. Register the locale in [`i18n/resources.ts`](./i18n/resources.ts) by updating `supportedLocales` and `resources`, and add it at the same position to `SUPPORTED_LOCALES` in [`apps/api/src/utils/supported-locales.ts`](./apps/api/src/utils/supported-locales.ts) (a unit test checks that both lists match).4. If the locale should be selectable in the UI, add it to the language picker in [`apps/web/src/routes/_layout/_authenticated/dashboard/settings/account/preferences.tsx`](./apps/web/src/routes/_layout/_authenticated/dashboard/settings/account/preferences.tsx).5. Run `pnpm i18n:check`, `pnpm i18n:report`, and `pnpm i18n:schema` before opening your PR.diff --git a/apps/api/drizzle/0064_session_oidc_sid.sql b/apps/api/drizzle/0064_session_oidc_sid.sqlnew file mode 100644index 000000000..a066a14dd--- /dev/null+++ b/apps/api/drizzle/0064_session_oidc_sid.sql@@ -0,0 +1,2 @@+ALTER TABLE "session" ADD COLUMN "oidc_sid" text;--> statement-breakpoint+CREATE INDEX "session_oidcSid_idx" ON "session" USING btree ("oidc_sid");\ No newline at end of filediff --git a/apps/api/drizzle/meta/0064_snapshot.json b/apps/api/drizzle/meta/0064_snapshot.jsonnew file mode 100644index 000000000..123b989ec--- /dev/null+++ b/apps/api/drizzle/meta/0064_snapshot.json@@ -0,0 +1,5412 @@+{+ "id": "4f7ec868-e674-4d8e-b26f-313f84cb44ba",+ "prevId": "f569b31a-0316-4069-acb6-0443dcf0a86f",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_createdAt_idx": {+ "name": "activity_createdAt_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "external_source",+ "external_url"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": [+ "reference_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_draft_expiry_idx": {+ "name": "asset_draft_expiry_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"asset\".\"task_id\" is null and \"asset\".\"surface\" in ('draft', 'draft-pending')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "tableTo": "activity",+ "columnsFrom": [+ "activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "object_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "reminder_type"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.calendar_feed": {+ "name": "calendar_feed",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label_ids": {+ "name": "label_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "time_zone": {+ "name": "time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'UTC'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "calendar_feed_project_id_idx": {+ "name": "calendar_feed_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "calendar_feed_project_id_project_id_fk": {+ "name": "calendar_feed_project_id_project_id_fk",+ "tableFrom": "calendar_feed",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "calendar_feed_token_unique": {+ "name": "calendar_feed_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "custom_field_definition",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "field_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.data_migration": {+ "name": "data_migration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_deferred_issue_idx": {+ "name": "external_link_deferred_issue_idx",+ "columns": [+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"external_link\".\"resource_type\" = 'issue' AND \"external_link\".\"metadata\" LIKE '%\"deferredIssueEdit\":%'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "tableTo": "integration",+ "columnsFrom": [+ "integration_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_import": {+ "name": "github_import",+ "schema": "",+ "columns": {+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_import_integration_id_integration_id_fk": {+ "name": "github_import_integration_id_integration_id_fk",+ "tableFrom": "github_import",+ "tableTo": "integration",+ "columnsFrom": [+ "integration_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_run": {+ "name": "import_run",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "include_comments": {+ "name": "include_comments",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "projects": {+ "name": "projects",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "import_run_workspace_created_idx": {+ "name": "import_run_workspace_created_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_run_workspace_id_workspace_id_fk": {+ "name": "import_run_workspace_id_workspace_id_fk",+ "tableFrom": "import_run",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "import_run_user_id_user_id_fk": {+ "name": "import_run_user_id_user_id_fk",+ "tableFrom": "import_run",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "type"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_access": {+ "name": "project_access",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "project_ids": {+ "name": "project_ids",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::text[]"+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "deletion_started_at": {+ "name": "deletion_started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_cascade_idx": {+ "name": "label_workspace_cascade_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"label\".\"task_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "background_object_key": {+ "name": "background_object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "background_mime_type": {+ "name": "background_mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "background_version": {+ "name": "background_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "project_background_object_key_idx": {+ "name": "project_background_object_key_idx",+ "columns": [+ {+ "expression": "background_object_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"project\".\"background_object_key\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "oidc_sid": {+ "name": "oidc_sid",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "session_oidcSid_idx": {+ "name": "session_oidcSid_idx",+ "columns": [+ {+ "expression": "oidc_sid",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.storage_cleanup": {+ "name": "storage_cleanup",+ "schema": "",+ "columns": {+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": [+ "source_task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": [+ "target_task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "reminder_type"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_project_scheduled_id_idx": {+ "name": "task_project_scheduled_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"task\".\"start_date\" is not null or \"task\".\"due_date\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "tableTo": "column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "number"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "user_notification_workspace_rule",+ "columnsFrom": [+ "workspace_id",+ "workspace_rule_id"+ ],+ "columnsTo": [+ "workspace_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "project",+ "columnsFrom": [+ "workspace_id",+ "project_id"+ ],+ "columnsTo": [+ "workspace_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_rule_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "workspace_id"+ ]+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id"+ ]+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "creem_subscription_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member_access": {+ "name": "workspace_member_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_access": {+ "name": "project_access",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_member_access_userId_idx": {+ "name": "workspace_member_access_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_access_workspace_id_workspace_id_fk": {+ "name": "workspace_member_access_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member_access",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_access_user_id_user_id_fk": {+ "name": "workspace_member_access_user_id_user_id_fk",+ "tableFrom": "workspace_member_access",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_member_access_workspace_user_unique": {+ "name": "workspace_member_access_workspace_user_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member_project": {+ "name": "workspace_member_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_member_project_projectId_idx": {+ "name": "workspace_member_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_project_user_id_user_id_fk": {+ "name": "workspace_member_project_user_id_user_id_fk",+ "tableFrom": "workspace_member_project",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "workspace_member_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "workspace_member_project",+ "tableTo": "project",+ "columnsFrom": [+ "workspace_id",+ "project_id"+ ],+ "columnsTo": [+ "workspace_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_member_project_workspace_user_project_unique": {+ "name": "workspace_member_project_workspace_user_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "user_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.jsonindex b20531503..770ce366a 100644--- a/apps/api/drizzle/meta/_journal.json+++ b/apps/api/drizzle/meta/_journal.json@@ -449,6 +449,13 @@"when": 1791727180448,"tag": "0063_import_runs","breakpoints": true+ },+ {+ "idx": 64,+ "version": "7",+ "when": 1792314678541,+ "tag": "0064_session_oidc_sid",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 0061ec5c9..2ad209107 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -37,6 +37,14 @@ import type { AccessControl } from "better-auth/plugins/access";import type { UserWithAnonymous } from "better-auth/plugins/anonymous";import { config } from "dotenv-mono";import { eq } from "drizzle-orm";+import {+ assertBackchannelLogoutEnv,+ resolveBackchannelLogoutConfig,+} from "./backchannel-logout/config";+import {+ rememberSignInSessionId,+ takeSignInSessionId,+} from "./backchannel-logout/sign-in-session-id";import {findBillableWorkspaces,formatBillableWorkspacesMessage,@@ -53,9 +61,11 @@ import { handleMemberAdded } from "./workspace-members/handle-member-added";import { handleMemberRemoved } from "./workspace-members/handle-member-removed";import { handleOwnerPromoted } from "./workspace-members/handle-owner-promoted";import { hideInaccessibleInvitationProjects } from "./project-access/hide-inaccessible-invitation-projects";+import assertManagedProfileUnchanged from "./user/controllers/assert-managed-profile-unchanged";import clearEmailVerificationOnAdminChange from "./user/controllers/clear-email-verification-on-admin-change";import deleteAccountData from "./user/controllers/delete-account-data";import prepareAdminUserRemoval from "./user/controllers/prepare-admin-user-removal";+import refreshManagedProfile from "./user/controllers/refresh-managed-profile";import { resolveAuthSecret } from "./utils/auth-secret";import {canSendSignInEmail,@@ -63,7 +73,15 @@ import {userExistsByEmail,} from "./utils/check-registration-allowed";import { checkWorkspaceName } from "./utils/check-workspace-name";+import {+ assertCustomOAuthEnv,+ parseManagedProfileFields,+} from "./utils/custom-oauth-env";import { mapCustomOAuthProfileToUser } from "./utils/custom-oauth-profile";+import {+ rememberCustomOAuthProfile,+ takeCustomOAuthProfile,+} from "./utils/custom-oauth-sign-in";import { resolveFileSecret } from "./utils/file-secret";import { generateDemoName } from "./utils/generate-demo-name";import { getEmailRequestContext } from "./utils/email-request-context";@@ -138,6 +156,14 @@ const authSecret = (() => {}})();+try {+ assertCustomOAuthEnv();+ assertBackchannelLogoutEnv();+} catch (error) {+ console.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+}+async function getUserLocale(email: string) {const [user] = await db.select({ locale: schema.userTable.locale })@@ -677,7 +703,13 @@ export const auth = betterAuth({responseType: process.env.CUSTOM_OAUTH_RESPONSE_TYPE || "code",discoveryUrl: process.env.CUSTOM_OAUTH_DISCOVERY_URL || "",pkce: process.env.CUSTOM_AUTH_PKCE !== "false",- mapProfileToUser: mapCustomOAuthProfileToUser,+ mapProfileToUser: (profile) => {+ rememberCustomOAuthProfile(profile);+ return mapCustomOAuthProfileToUser(+ profile,+ parseManagedProfileFields(),+ );+ },},],}),@@ -703,6 +735,14 @@ export const auth = betterAuth({openAPI(),],session: {+ additionalFields: {+ oidcSid: {+ type: "string",+ required: false,+ input: false,+ returned: false,+ },+ },cookieCache: {// Consult the session store on every request so password recovery// immediately rejects revoked cookies, including caches issued before upgrade.@@ -750,6 +790,7 @@ export const auth = betterAuth({message: "You cannot change your own role.",});}+ await assertManagedProfileUnchanged(user, ctx);return clearEmailVerificationOnAdminChange(user, ctx);},},@@ -781,6 +822,26 @@ export const auth = betterAuth({},},},+ account: {+ create: {+ before: async (account, ctx) => {+ rememberSignInSessionId(account.idToken, ctx);+ },+ },+ update: {+ before: async (account, ctx) => {+ rememberSignInSessionId(account.idToken, ctx);+ },+ },+ },+ session: {+ create: {+ before: async (_session, ctx) => {+ const oidcSid = takeSignInSessionId(ctx);+ if (oidcSid) return { data: { oidcSid } };+ },+ },+ },},hooks: {before: createAuthMiddleware(async (ctx) => {@@ -872,6 +933,15 @@ export const auth = betterAuth({}}+ if (+ ctx.path === "/callback/:id" &&+ ctx.params?.id === "custom" &&+ (parseManagedProfileFields().length > 0 ||+ resolveBackchannelLogoutConfig().enabled)+ ) {+ throw new APIError("NOT_FOUND");+ }+const isSignUpPath =ctx.path === "/sign-up/email" ||ctx.path.startsWith("/callback/") ||@@ -991,6 +1061,27 @@ export const auth = betterAuth({}}}++ if (+ ctx.path === "/oauth2/callback/:providerId" &&+ ctx.context.newSession+ ) {+ const profile = takeCustomOAuthProfile();+ if (profile) {+ await refreshManagedProfile(+ ctx.context.newSession.user.id,+ profile,+ ).catch((error) => {+ // Database errors repeat the query parameters, which hold the claims.+ const cause = (error as { cause?: unknown } | null)?.cause ?? error;+ const code = (cause as { code?: unknown } | null)?.code;+ console.error("Managed profile refresh failed:", {+ error: error instanceof Error ? error.name : typeof error,+ code: typeof code === "string" ? code : undefined,+ });+ });+ }+ }}),},advanced: {diff --git a/apps/api/src/backchannel-logout/config.ts b/apps/api/src/backchannel-logout/config.tsnew file mode 100644index 000000000..ffabce146--- /dev/null+++ b/apps/api/src/backchannel-logout/config.ts@@ -0,0 +1,42 @@+import { isHttpUrl } from "../utils/is-http-url";++export type BackchannelLogoutConfig =+ | { enabled: false }+ | { enabled: true; discoveryUrl: string; clientId: string };++export function resolveBackchannelLogoutConfig(+ env: NodeJS.ProcessEnv = process.env,+): BackchannelLogoutConfig {+ if (env.CUSTOM_OAUTH_BACKCHANNEL_LOGOUT !== "true") {+ return { enabled: false };+ }++ const discoveryUrl = env.CUSTOM_OAUTH_DISCOVERY_URL?.trim() ?? "";+ if (!isHttpUrl(discoveryUrl)) {+ throw new Error(+ "CUSTOM_OAUTH_BACKCHANNEL_LOGOUT=true requires CUSTOM_OAUTH_DISCOVERY_URL to be an absolute http or https URL.",+ );+ }++ const clientId = env.CUSTOM_OAUTH_CLIENT_ID?.trim();+ if (!clientId) {+ throw new Error(+ "CUSTOM_OAUTH_BACKCHANNEL_LOGOUT=true requires CUSTOM_OAUTH_CLIENT_ID.",+ );+ }++ return { enabled: true, discoveryUrl, clientId };+}++export function assertBackchannelLogoutEnv(+ env: NodeJS.ProcessEnv = process.env,+) {+ const requestsOpenId = env.CUSTOM_OAUTH_SCOPES?.split(",").some((entry) =>+ entry.trim().split(" ").includes("openid"),+ );+ if (resolveBackchannelLogoutConfig(env).enabled && !requestsOpenId) {+ console.warn(+ "CUSTOM_OAUTH_BACKCHANNEL_LOGOUT is enabled, but CUSTOM_OAUTH_SCOPES lacks openid. Logout tokens with a session ID will not match any Kaneo session.",+ );+ }+}diff --git a/apps/api/src/backchannel-logout/controllers/end-provider-sessions.ts b/apps/api/src/backchannel-logout/controllers/end-provider-sessions.tsnew file mode 100644index 000000000..5b65dc9d3--- /dev/null+++ b/apps/api/src/backchannel-logout/controllers/end-provider-sessions.ts@@ -0,0 +1,101 @@+import { createHash } from "node:crypto";+import { and, eq, gt, inArray } from "drizzle-orm";+import db, { schema } from "../../database";+import { revokeUserConnections } from "../../ws";+import { LogoutTokenRejected } from "../errors";+import {+ CLOCK_SKEW_SECONDS,+ type LogoutTokenClaims,+ MAX_LOGOUT_TOKEN_AGE_SECONDS,+} from "../verify-logout-token";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++async function claimLogoutToken(+ tx: Transaction,+ { iss, jti, iat }: LogoutTokenClaims,+) {+ const identifier = `backchannel-logout:${iss}:${jti}`;+ const [claimed] = await tx+ .insert(schema.verificationTable)+ .values({+ id: createHash("sha256").update(identifier).digest("base64url"),+ identifier,+ value: "used",+ expiresAt: new Date(+ (iat + MAX_LOGOUT_TOKEN_AGE_SECONDS + CLOCK_SKEW_SECONDS) * 1000,+ ),+ })+ .onConflictDoNothing({ target: schema.verificationTable.id })+ .returning({ id: schema.verificationTable.id });+ return Boolean(claimed);+}++async function findCustomAccountUsers(tx: Transaction, accountId: string) {+ const accounts = await tx+ .select({ userId: schema.accountTable.userId })+ .from(schema.accountTable)+ .where(+ and(+ eq(schema.accountTable.providerId, "custom"),+ eq(schema.accountTable.accountId, accountId),+ ),+ );+ return [...new Set(accounts.map((account) => account.userId))];+}++async function hasActiveSession(userId: string) {+ const [session] = await db+ .select({ id: schema.sessionTable.id })+ .from(schema.sessionTable)+ .where(+ and(+ eq(schema.sessionTable.userId, userId),+ gt(schema.sessionTable.expiresAt, new Date()),+ ),+ )+ .limit(1);+ return Boolean(session);+}++async function closeSignedOutConnections(userIds: string[]) {+ for (const userId of userIds) {+ // Revoked sockets sign out every tab, so wait until no session is left.+ if (!(await hasActiveSession(userId))) await revokeUserConnections(userId);+ }+}++export async function endProviderSessions(claims: LogoutTokenClaims) {+ const { sid, sub } = claims;+ if (sid === undefined && sub === undefined) {+ throw new Error("A logout needs a session ID or a subject");+ }++ const signedOutUserIds = await db.transaction(async (tx) => {+ if (!(await claimLogoutToken(tx, claims))) {+ throw new LogoutTokenRejected("the logout token was used before");+ }+ const userIds =+ sub === undefined ? undefined : await findCustomAccountUsers(tx, sub);+ if (userIds?.length === 0) return [];+ const ended = await tx+ .delete(schema.sessionTable)+ .where(+ and(+ sid === undefined ? undefined : eq(schema.sessionTable.oidcSid, sid),+ userIds === undefined+ ? undefined+ : inArray(schema.sessionTable.userId, userIds),+ ),+ )+ .returning({ userId: schema.sessionTable.userId });+ return [...new Set(ended.map((session) => session.userId))];+ });++ await closeSignedOutConnections(signedOutUserIds).catch((error) => {+ console.error(+ "Closing realtime connections after a back-channel logout failed:",+ error,+ );+ });+}diff --git a/apps/api/src/backchannel-logout/decode-jwt-segment.ts b/apps/api/src/backchannel-logout/decode-jwt-segment.tsnew file mode 100644index 000000000..6c891cd51--- /dev/null+++ b/apps/api/src/backchannel-logout/decode-jwt-segment.ts@@ -0,0 +1,14 @@+import { isJsonObject } from "./is-json-object";++export function decodeJwtSegment(token: string, index: 0 | 1) {+ const segment = token.split(".")[index];+ if (!segment) return null;+ try {+ const value: unknown = JSON.parse(+ Buffer.from(segment, "base64url").toString("utf8"),+ );+ return isJsonObject(value) ? value : null;+ } catch {+ return null;+ }+}diff --git a/apps/api/src/backchannel-logout/errors.ts b/apps/api/src/backchannel-logout/errors.tsnew file mode 100644index 000000000..1971c2d8a--- /dev/null+++ b/apps/api/src/backchannel-logout/errors.ts@@ -0,0 +1,3 @@+export class LogoutTokenRejected extends Error {}++export class LogoutProviderUnavailable extends Error {}diff --git a/apps/api/src/backchannel-logout/fetch-provider-json.ts b/apps/api/src/backchannel-logout/fetch-provider-json.tsnew file mode 100644index 000000000..72635532d--- /dev/null+++ b/apps/api/src/backchannel-logout/fetch-provider-json.ts@@ -0,0 +1,50 @@+import { LogoutProviderUnavailable } from "./errors";++const PROVIDER_TIMEOUT_MS = 5_000;+export const MAX_PROVIDER_DOCUMENT_BYTES = 64 * 1024;++export async function fetchProviderJson(url: string): Promise<unknown> {+ let response: Response;+ try {+ response = await fetch(url, {+ headers: { Accept: "application/json" },+ redirect: "error",+ signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS),+ });+ } catch {+ throw new LogoutProviderUnavailable(`${url} could not be fetched`);+ }++ const reader = response.ok ? response.body?.getReader() : undefined;+ if (!reader) {+ void response.body?.cancel().catch(() => {});+ throw new LogoutProviderUnavailable(+ `${url} answered HTTP ${response.status}`,+ );+ }++ const bytes = new Uint8Array(MAX_PROVIDER_DOCUMENT_BYTES);+ let size = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (size + value.byteLength > MAX_PROVIDER_DOCUMENT_BYTES) {+ throw new LogoutProviderUnavailable(+ `${url} answered with too much data`,+ );+ }+ bytes.set(value, size);+ size += value.byteLength;+ }+ return JSON.parse(new TextDecoder().decode(bytes.subarray(0, size)));+ } catch (error) {+ if (error instanceof LogoutProviderUnavailable) throw error;+ throw new LogoutProviderUnavailable(+ `${url} did not answer with a JSON document`,+ );+ } finally {+ void reader.cancel().catch(() => {});+ reader.releaseLock();+ }+}diff --git a/apps/api/src/backchannel-logout/index.ts b/apps/api/src/backchannel-logout/index.tsnew file mode 100644index 000000000..86a1b72d0--- /dev/null+++ b/apps/api/src/backchannel-logout/index.ts@@ -0,0 +1,62 @@+import type { Context, MiddlewareHandler } from "hono";+import { notFoundResponse } from "../errors/not-found-response";+import { resolveBackchannelLogoutConfig } from "./config";+import { endProviderSessions } from "./controllers/end-provider-sessions";+import { LogoutProviderUnavailable, LogoutTokenRejected } from "./errors";+import { providerJwks } from "./provider-jwks";+import { getProviderMetadata } from "./provider-metadata";+import { verifyLogoutToken } from "./verify-logout-token";++export const MAX_LOGOUT_REQUEST_BYTES = 16 * 1024;++const COMPACT_JWS = /^[\w-]+\.[\w-]+\.[\w-]+$/;++export const noStore: MiddlewareHandler = async (c, next) => {+ await next();+ c.res.headers.set("Cache-Control", "no-store");+};++async function readLogoutToken(c: Context) {+ const type = c.req+ .header("content-type")+ ?.split(";")[0]+ ?.trim()+ .toLowerCase();+ if (type !== "application/x-www-form-urlencoded") return null;+ const tokens = new URLSearchParams(await c.req.text()).getAll("logout_token");+ const [token] = tokens;+ return tokens.length === 1 && token && COMPACT_JWS.test(token) ? token : null;+}++async function loadLogoutTokenProvider(discoveryUrl: string) {+ const { issuer, algorithms, jwksUri } =+ await getProviderMetadata(discoveryUrl);+ return { issuer, algorithms, ...providerJwks(jwksUri) };+}++export async function handleBackchannelLogoutRoute(c: Context) {+ const config = resolveBackchannelLogoutConfig();+ if (!config.enabled) return notFoundResponse();++ const token = await readLogoutToken(c);+ if (!token) return c.json({ error: "invalid_request" }, 400);++ try {+ const claims = await verifyLogoutToken(token, config.clientId, () =>+ loadLogoutTokenProvider(config.discoveryUrl),+ );+ await endProviderSessions(claims);+ } catch (error) {+ if (error instanceof LogoutProviderUnavailable) {+ console.warn(`Back-channel logout is unavailable: ${error.message}`);+ return c.json({ error: "temporarily_unavailable" }, 503);+ }+ if (error instanceof LogoutTokenRejected) {+ console.warn(`Rejected a back-channel logout token: ${error.message}`);+ return c.json({ error: "invalid_request" }, 400);+ }+ throw error;+ }++ return c.body(null, 200);+}diff --git a/apps/api/src/backchannel-logout/is-json-object.ts b/apps/api/src/backchannel-logout/is-json-object.tsnew file mode 100644index 000000000..42f0aac35--- /dev/null+++ b/apps/api/src/backchannel-logout/is-json-object.ts@@ -0,0 +1,3 @@+export function isJsonObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/apps/api/src/backchannel-logout/provider-jwks.ts b/apps/api/src/backchannel-logout/provider-jwks.tsnew file mode 100644index 000000000..32aef8278--- /dev/null+++ b/apps/api/src/backchannel-logout/provider-jwks.ts@@ -0,0 +1,67 @@+import { LogoutProviderUnavailable } from "./errors";+import { fetchProviderJson } from "./fetch-provider-json";+import { isJsonObject } from "./is-json-object";+import type { JsonWebKeySet } from "./verify-logout-token";++const JWKS_REFETCH_COOLDOWN_MS = 30 * 1000;++type ProviderJwks = {+ jwksCacheKey: object;+ jwksFetch: () => Promise<JsonWebKeySet>;+};++const providerKeySources = new Map<string, ProviderJwks>();++function parseJwks(document: unknown): JsonWebKeySet {+ const keys = isJsonObject(document) ? document.keys : undefined;+ if (!Array.isArray(keys) || !keys.every(isJsonObject)) {+ throw new LogoutProviderUnavailable("the provider's key set is malformed");+ }+ return { keys: keys as JsonWebKeySet["keys"] };+}++export function providerJwks(jwksUri: string): ProviderJwks {+ const known = providerKeySources.get(jwksUri);+ if (known) return known;++ let jwks: JsonWebKeySet | undefined;+ let attemptedAt = 0;+ let pending: Promise<JsonWebKeySet> | undefined;++ const load = async () => {+ try {+ jwks = parseJwks(await fetchProviderJson(jwksUri));+ return jwks;+ } catch (error) {+ if (!jwks) throw error;+ const reason = error instanceof Error ? error.message : String(error);+ console.warn(+ `Back-channel logout kept the previous signing keys: ${reason}`,+ );+ return jwks;+ }+ };++ const source: ProviderJwks = {+ jwksCacheKey: {},+ jwksFetch: () => {+ if (pending) return pending;+ if (Date.now() - attemptedAt < JWKS_REFETCH_COOLDOWN_MS) {+ return jwks+ ? Promise.resolve(jwks)+ : Promise.reject(+ new LogoutProviderUnavailable(+ "the provider's key set failed to load moments ago",+ ),+ );+ }+ attemptedAt = Date.now();+ pending = load().finally(() => {+ pending = undefined;+ });+ return pending;+ },+ };+ providerKeySources.set(jwksUri, source);+ return source;+}diff --git a/apps/api/src/backchannel-logout/provider-metadata.ts b/apps/api/src/backchannel-logout/provider-metadata.tsnew file mode 100644index 000000000..150e8b773--- /dev/null+++ b/apps/api/src/backchannel-logout/provider-metadata.ts@@ -0,0 +1,98 @@+import { isHttpUrl } from "../utils/is-http-url";+import { LogoutProviderUnavailable } from "./errors";+import { fetchProviderJson } from "./fetch-provider-json";+import { isJsonObject } from "./is-json-object";+import { ASYMMETRIC_ALGORITHMS } from "./verify-logout-token";++const METADATA_TTL_MS = 60 * 60 * 1000;+const RETRY_AFTER_FAILURE_MS = 30 * 1000;++export type ProviderMetadata = {+ issuer: string;+ jwksUri: string;+ algorithms: string[];+};++type CachedMetadata = {+ metadata?: ProviderMetadata;+ fetchedAt: number;+ failedAt?: number;+ pending?: Promise<ProviderMetadata>;+};++const cachedMetadata = new Map<string, CachedMetadata>();++export function parseProviderMetadata(document: unknown): ProviderMetadata {+ const fields: Record<string, unknown> = isJsonObject(document)+ ? document+ : {};+ const {+ issuer,+ jwks_uri: jwksUri,+ id_token_signing_alg_values_supported: offered,+ } = fields;+ if (typeof issuer !== "string" || !issuer) {+ throw new LogoutProviderUnavailable("the discovery document has no issuer");+ }+ if (typeof jwksUri !== "string" || !isHttpUrl(jwksUri)) {+ throw new LogoutProviderUnavailable(+ "the discovery document has no absolute jwks_uri",+ );+ }+ const algorithms = Array.isArray(offered)+ ? ASYMMETRIC_ALGORITHMS.filter((algorithm) => offered.includes(algorithm))+ : ASYMMETRIC_ALGORITHMS;+ if (algorithms.length === 0) {+ throw new LogoutProviderUnavailable(+ "the provider offers no asymmetric ID token signing algorithm",+ );+ }+ return { issuer, jwksUri, algorithms };+}++export function getProviderMetadata(+ discoveryUrl: string,+): Promise<ProviderMetadata> {+ const cached = cachedMetadata.get(discoveryUrl);+ if (cached?.pending) return cached.pending;+ const now = Date.now();+ if (cached?.metadata && now - cached.fetchedAt < METADATA_TTL_MS) {+ return Promise.resolve(cached.metadata);+ }+ if (+ cached?.failedAt !== undefined &&+ now - cached.failedAt < RETRY_AFTER_FAILURE_MS+ ) {+ return cached.metadata+ ? Promise.resolve(cached.metadata)+ : Promise.reject(+ new LogoutProviderUnavailable(+ "the discovery document failed to load moments ago",+ ),+ );+ }++ const pending = fetchProviderJson(discoveryUrl)+ .then(parseProviderMetadata)+ .then(+ (metadata) => {+ cachedMetadata.set(discoveryUrl, { metadata, fetchedAt: Date.now() });+ return metadata;+ },+ (error: unknown) => {+ cachedMetadata.set(discoveryUrl, {+ metadata: cached?.metadata,+ fetchedAt: cached?.fetchedAt ?? 0,+ failedAt: Date.now(),+ });+ if (cached?.metadata) return cached.metadata;+ throw error;+ },+ );+ cachedMetadata.set(discoveryUrl, {+ ...cached,+ fetchedAt: cached?.fetchedAt ?? 0,+ pending,+ });+ return pending;+}diff --git a/apps/api/src/backchannel-logout/sign-in-session-id.ts b/apps/api/src/backchannel-logout/sign-in-session-id.tsnew file mode 100644index 000000000..5a8929a81--- /dev/null+++ b/apps/api/src/backchannel-logout/sign-in-session-id.ts@@ -0,0 +1,29 @@+import type { GenericEndpointContext } from "better-auth";+import { decodeJwtSegment } from "./decode-jwt-segment";++const signInSessionIds = new WeakMap<object, string>();++function isCustomProviderCallback(+ ctx: GenericEndpointContext | null,+): ctx is GenericEndpointContext {+ return (+ ctx?.path === "/oauth2/callback/:providerId" &&+ ctx.params?.providerId === "custom"+ );+}++export function rememberSignInSessionId(+ idToken: unknown,+ ctx: GenericEndpointContext | null,+) {+ if (!isCustomProviderCallback(ctx) || typeof idToken !== "string") return;+ const sid = decodeJwtSegment(idToken, 1)?.sid;+ if (typeof sid === "string" && sid) signInSessionIds.set(ctx.context, sid);+}++export function takeSignInSessionId(ctx: GenericEndpointContext | null) {+ if (!isCustomProviderCallback(ctx)) return undefined;+ const sid = signInSessionIds.get(ctx.context);+ signInSessionIds.delete(ctx.context);+ return sid;+}diff --git a/apps/api/src/backchannel-logout/verify-logout-token.ts b/apps/api/src/backchannel-logout/verify-logout-token.tsnew file mode 100644index 000000000..64ff24e3d--- /dev/null+++ b/apps/api/src/backchannel-logout/verify-logout-token.ts@@ -0,0 +1,130 @@+import { verifyJwsAccessToken } from "better-auth/oauth2";+import { decodeJwtSegment } from "./decode-jwt-segment";+import { LogoutProviderUnavailable, LogoutTokenRejected } from "./errors";+import { isJsonObject } from "./is-json-object";++type VerifyJwsOptions = Parameters<typeof verifyJwsAccessToken>[1];++export type JsonWebKeySet = NonNullable<+ Awaited<ReturnType<Exclude<VerifyJwsOptions["jwksFetch"], string>>>+>;++export const ASYMMETRIC_ALGORITHMS = [+ "RS256",+ "RS384",+ "RS512",+ "PS256",+ "PS384",+ "PS512",+ "ES256",+ "ES384",+ "ES512",+ "EdDSA",+];++export const BACKCHANNEL_LOGOUT_EVENT =+ "http://schemas.openid.net/event/backchannel-logout";+export const MAX_LOGOUT_TOKEN_AGE_SECONDS = 10 * 60;+export const CLOCK_SKEW_SECONDS = 60;++export type LogoutTokenProvider = {+ issuer: string;+ algorithms: string[];+ jwksFetch: () => Promise<JsonWebKeySet>;+ jwksCacheKey: object;+};++export type LogoutTokenClaims = {+ iss: string;+ jti: string;+ iat: number;+ sid?: string;+ sub?: string;+};++function isLogoutTokenType(type: unknown) {+ if (typeof type !== "string") return false;+ const normalized = type.toLowerCase().replace(/^application\//, "");+ return normalized === "logout+jwt" || normalized === "jwt";+}++function readIdentifier(value: unknown, claim: "sid" | "sub") {+ if (value === undefined) return undefined;+ if (typeof value === "string" && value) return value;+ throw new LogoutTokenRejected(`${claim} must be a non-empty string`);+}++export async function verifyLogoutToken(+ token: string,+ clientId: string,+ loadProvider: () => Promise<LogoutTokenProvider>,+): Promise<LogoutTokenClaims> {+ const header = decodeJwtSegment(token, 0);+ if (!header) throw new LogoutTokenRejected("the header is not a JSON object");+ const { alg, typ, crit } = header;+ if (typeof alg !== "string" || !ASYMMETRIC_ALGORITHMS.includes(alg)) {+ throw new LogoutTokenRejected("the signing algorithm is not supported");+ }+ if (typ !== undefined && !isLogoutTokenType(typ)) {+ throw new LogoutTokenRejected("the token type is not logout+jwt or JWT");+ }+ if (crit !== undefined) {+ throw new LogoutTokenRejected(+ "critical header parameters are not supported",+ );+ }++ const provider = await loadProvider();+ if (!provider.algorithms.includes(alg)) {+ throw new LogoutTokenRejected(+ "the provider does not sign ID tokens with this algorithm",+ );+ }++ let payload: Awaited<ReturnType<typeof verifyJwsAccessToken>>;+ try {+ payload = await verifyJwsAccessToken(token, {+ jwksFetch: provider.jwksFetch,+ jwksCacheKey: provider.jwksCacheKey,+ verifyOptions: {+ issuer: provider.issuer,+ audience: clientId,+ algorithms: provider.algorithms,+ requiredClaims: ["iat", "jti", "events"],+ clockTolerance: CLOCK_SKEW_SECONDS,+ },+ });+ } catch (error) {+ if (error instanceof LogoutProviderUnavailable) throw error;+ throw new LogoutTokenRejected(+ error instanceof Error ? error.message : "the token is invalid",+ );+ }++ const now = Math.floor(Date.now() / 1000);+ const { iat, jti, events } = payload;+ if (+ typeof iat !== "number" ||+ iat > now + CLOCK_SKEW_SECONDS ||+ iat < now - MAX_LOGOUT_TOKEN_AGE_SECONDS+ ) {+ throw new LogoutTokenRejected("iat is outside the accepted window");+ }+ if (typeof jti !== "string" || !jti) {+ throw new LogoutTokenRejected("jti must be a non-empty string");+ }+ if (+ !isJsonObject(events) ||+ !isJsonObject(events[BACKCHANNEL_LOGOUT_EVENT])+ ) {+ throw new LogoutTokenRejected("the back-channel logout event is missing");+ }+ if (Object.hasOwn(payload, "nonce")) {+ throw new LogoutTokenRejected("a logout token must not contain a nonce");+ }+ const sid = readIdentifier(payload.sid, "sid");+ const sub = readIdentifier(payload.sub, "sub");+ if (!sid && !sub) throw new LogoutTokenRejected("sid or sub is required");++ return { iss: provider.issuer, jti, iat, sid, sub };+}diff --git a/apps/api/src/config/response.ts b/apps/api/src/config/response.tsindex 80cf070ed..538bf7887 100644--- a/apps/api/src/config/response.ts+++ b/apps/api/src/config/response.ts@@ -1,4 +1,5 @@import { z } from "../openapi";+import { MANAGED_PROFILE_FIELDS } from "../utils/custom-oauth-env";export const configSchema = z.object({@@ -25,6 +26,16 @@ export const configSchema = z}),customOAuthAutoLogin: z.boolean(),customOAuthLogoutUrl: z.string().nullable(),+ customOAuthManagedProfileFields: z+ .array(z.enum(MANAGED_PROFILE_FIELDS))+ .openapi({+ description:+ "Profile fields the custom OAuth/OIDC provider manages for people with a linked provider account.",+ }),+ customOAuthAccountUrl: z.string().nullable().openapi({+ description:+ "Account page of the custom OAuth/OIDC provider, where people change managed profile fields. Null when not configured.",+ }),billingEnabled: z.boolean(),}).openapi("Config");diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.tsindex d905f0951..9502d1af0 100644--- a/apps/api/src/database/schema.ts+++ b/apps/api/src/database/schema.ts@@ -72,8 +72,12 @@ export const sessionTable = pgTable(activeOrganizationId: text("active_organization_id"),activeTeamId: text("active_team_id"),impersonatedBy: text("impersonated_by"),+ oidcSid: text("oidc_sid"),},- (table) => [index("session_userId_idx").on(table.userId)],+ (table) => [+ index("session_userId_idx").on(table.userId),+ index("session_oidcSid_idx").on(table.oidcSid),+ ],);export const accountTable = pgTable(diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 3e9af3bca..f3b5aada6 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -20,6 +20,11 @@ import activity from "./activity";import admin from "./admin";import { auth } from "./auth";import { organizationRoutes } from "./auth-openapi";+import {+ handleBackchannelLogoutRoute,+ MAX_LOGOUT_REQUEST_BYTES,+ noStore,+} from "./backchannel-logout";import billing from "./billing";import calendarFeed, { publicCalendarFeed } from "./calendar-feed";import column from "./column";@@ -91,8 +96,10 @@ import {authorizeAssetAccess,isPublicAsset,} from "./utils/authorize-asset-access";+import { boundedRequestBody } from "./utils/bounded-request-body";import { getInvitationDetails } from "./utils/check-registration-allowed";import { clientIpMiddleware } from "./utils/client-ip";+import { runCustomOAuthCallback } from "./utils/custom-oauth-sign-in";import { migrateApiKeyReferenceId } from "./utils/migrate-apikey-reference-id";import { migrateNotificationPreferencesSchema } from "./utils/migrate-notification-preferences-schema";import { migrateSessionColumn } from "./utils/migrate-session-column";@@ -444,6 +451,13 @@ export function createApp() {handleGitlabWebhookRoute,);+ api.post(+ "/auth/oauth2/backchannel-logout/custom",+ noStore,+ boundedRequestBody(MAX_LOGOUT_REQUEST_BYTES),+ handleBackchannelLogoutRoute,+ );+const invitationPublicApi = api.get("/invitation/public/:id", async (c) => {const { id } = c.req.param();const result = await getInvitationDetails(id);@@ -466,6 +480,11 @@ export function createApp() {);});+ // Lets the sign-in refresh in auth.ts read the claims the provider sent.+ api.use("/auth/oauth2/callback/custom", (_c, next) =>+ runCustomOAuthCallback(next),+ );+api.openapi(createRoute({method: "get",diff --git a/apps/api/src/user/avatar.ts b/apps/api/src/user/avatar.tsindex d2b4b420c..59bdf8526 100644--- a/apps/api/src/user/avatar.ts+++ b/apps/api/src/user/avatar.ts@@ -101,3 +101,10 @@ export function decodeAvatarUpload(input: {export function buildAvatarUrl(avatarId: string) {return `/api/user/avatar/${avatarId}`;}++export function isUploadedAvatarUrl(image: string | null | undefined) {+ const prefix = buildAvatarUrl("");+ if (!image?.startsWith(prefix)) return false;+ const avatarId = image.slice(prefix.length);+ return avatarId.length > 0 && !/[/?#]/.test(avatarId);+}diff --git a/apps/api/src/user/controllers/assert-managed-profile-unchanged.ts b/apps/api/src/user/controllers/assert-managed-profile-unchanged.tsnew file mode 100644index 000000000..5e6585bec--- /dev/null+++ b/apps/api/src/user/controllers/assert-managed-profile-unchanged.ts@@ -0,0 +1,38 @@+import { APIError } from "better-auth/api";+import { parseManagedProfileFields } from "../../utils/custom-oauth-env";+import {+ changesManagedProfile,+ PROFILE_FIELD_MANAGED_BY_PROVIDER,+} from "../managed-profile";+import getManagedProfile from "./get-managed-profile";++type UpdateHookContext = {+ path?: string;+ body?: { userId?: unknown };+ context?: { session?: { user: { id: string } } | null };+};++function getEditedUserId(ctx: UpdateHookContext | null | undefined) {+ if (ctx?.path === "/update-user") return ctx.context?.session?.user.id;+ if (ctx?.path === "/admin/update-user") return ctx.body?.userId;+ return undefined;+}++export async function assertManagedProfileUnchanged(+ data: Record<string, unknown>,+ ctx: UpdateHookContext | null | undefined,+) {+ const userId = getEditedUserId(ctx);+ if (+ typeof userId !== "string" ||+ !parseManagedProfileFields().some((field) => data[field] !== undefined)+ ) {+ return;+ }+ const managed = await getManagedProfile(userId);+ if (managed && changesManagedProfile(data, managed.stored, managed.fields)) {+ throw new APIError("FORBIDDEN", { ...PROFILE_FIELD_MANAGED_BY_PROVIDER });+ }+}++export default assertManagedProfileUnchanged;diff --git a/apps/api/src/user/controllers/get-current-user.ts b/apps/api/src/user/controllers/get-current-user.tsindex e288c6a20..d38a5cea3 100644--- a/apps/api/src/user/controllers/get-current-user.ts+++ b/apps/api/src/user/controllers/get-current-user.ts@@ -2,6 +2,7 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { userTable } from "../../database/schema";+import getManagedProfile from "./get-managed-profile";export async function getCurrentUser(userId: string) {const [user] = await db@@ -20,7 +21,8 @@ export async function getCurrentUser(userId: string) {throw new HTTPException(404, { message: "User not found" });}- return user;+ const managed = await getManagedProfile(userId);+ return { ...user, managedProfileFields: managed?.fields ?? [] };}export default getCurrentUser;diff --git a/apps/api/src/user/controllers/get-managed-profile.ts b/apps/api/src/user/controllers/get-managed-profile.tsnew file mode 100644index 000000000..4d3f025db--- /dev/null+++ b/apps/api/src/user/controllers/get-managed-profile.ts@@ -0,0 +1,30 @@+import { and, eq } from "drizzle-orm";+import db from "../../database";+import { accountTable, userTable } from "../../database/schema";+import { parseManagedProfileFields } from "../../utils/custom-oauth-env";++export async function getManagedProfile(userId: string) {+ const fields = parseManagedProfileFields();+ if (fields.length === 0) return null;++ const [stored] = await db+ .select({+ name: userTable.name,+ image: userTable.image,+ locale: userTable.locale,+ })+ .from(userTable)+ .innerJoin(+ accountTable,+ and(+ eq(accountTable.userId, userTable.id),+ eq(accountTable.providerId, "custom"),+ ),+ )+ .where(eq(userTable.id, userId))+ .limit(1);++ return stored ? { fields, stored } : null;+}++export default getManagedProfile;diff --git a/apps/api/src/user/controllers/refresh-managed-profile.ts b/apps/api/src/user/controllers/refresh-managed-profile.tsnew file mode 100644index 000000000..a0dd1de34--- /dev/null+++ b/apps/api/src/user/controllers/refresh-managed-profile.ts@@ -0,0 +1,37 @@+import { eq } from "drizzle-orm";+import db from "../../database";+import { userTable } from "../../database/schema";+import { parseManagedProfileFields } from "../../utils/custom-oauth-env";+import { planManagedProfileRefresh } from "../managed-profile";+import deleteAvatar from "./delete-avatar";++export async function refreshManagedProfile(+ userId: string,+ profile: Record<string, unknown>,+) {+ const fields = parseManagedProfileFields();+ if (fields.length === 0) return;++ const [stored] = await db+ .select({+ name: userTable.name,+ image: userTable.image,+ locale: userTable.locale,+ })+ .from(userTable)+ .where(eq(userTable.id, userId))+ .limit(1);+ if (!stored) return;++ const { update, removeUploadedAvatar } = planManagedProfileRefresh(+ profile,+ stored,+ fields,+ );+ if (Object.keys(update).length > 0) {+ await db.update(userTable).set(update).where(eq(userTable.id, userId));+ }+ if (removeUploadedAvatar) await deleteAvatar(userId);+}++export default refreshManagedProfile;diff --git a/apps/api/src/user/index.ts b/apps/api/src/user/index.tsindex ff2c201e9..184fd838a 100644--- a/apps/api/src/user/index.ts+++ b/apps/api/src/user/index.ts@@ -10,6 +10,10 @@ import { MAX_AVATAR_BYTES, MAX_AVATAR_REQUEST_BYTES } from "./avatar";import deleteAvatar from "./controllers/delete-avatar";import getCurrentUser from "./controllers/get-current-user";import saveAvatar from "./controllers/save-avatar";+import {+ requireRemovableAvatar,+ requireUnmanagedAvatar,+} from "./managed-avatar-guards";import {avatarDeletedSchema,avatarSchema,@@ -40,7 +44,10 @@ const uploadAvatarRoute = createRoute({description: `Store a base64 encoded avatar (PNG, JPEG, or WebP, up to ${Math.floor(MAX_AVATAR_BYTES / 1024,)}KB) for the current user and return its public URL. Replaces any existing avatar.`,- middleware: [boundedRequestBody(MAX_AVATAR_REQUEST_BYTES)] as const,+ middleware: [+ requireUnmanagedAvatar,+ boundedRequestBody(MAX_AVATAR_REQUEST_BYTES),+ ] as const,request: {body: {required: true,@@ -49,6 +56,9 @@ const uploadAvatarRoute = createRoute({},responses: {200: jsonResponse("Avatar stored", avatarSchema),+ 403: errorResponse(+ "The custom OAuth/OIDC provider manages the profile picture",+ ),408: errorResponse("Request body timed out"),413: errorResponse("Request body exceeds the upload limit"),400: errorResponse(@@ -65,8 +75,12 @@ const deleteAvatarRoute = createRoute({summary: "Delete avatar",description:"Remove the uploaded avatar of the current user. Succeeds even when there was nothing to remove.",+ middleware: [requireRemovableAvatar] as const,responses: {200: jsonResponse("Avatar removed", avatarDeletedSchema),+ 403: errorResponse(+ "The custom OAuth/OIDC provider manages the profile picture",+ ),},});diff --git a/apps/api/src/user/managed-avatar-guards.ts b/apps/api/src/user/managed-avatar-guards.tsnew file mode 100644index 000000000..c8f87a316--- /dev/null+++ b/apps/api/src/user/managed-avatar-guards.ts@@ -0,0 +1,26 @@+import type { Context, Next } from "hono";+import { ApiError } from "../errors/api-error";+import getManagedProfile from "./controllers/get-managed-profile";+import {+ canRemoveAvatar,+ PROFILE_FIELD_MANAGED_BY_PROVIDER,+} from "./managed-profile";++export async function requireUnmanagedAvatar(c: Context, next: Next) {+ const managed = await getManagedProfile(c.get("userId"));+ if (managed?.fields.includes("image")) {+ throw new ApiError(403, { ...PROFILE_FIELD_MANAGED_BY_PROVIDER });+ }+ return next();+}++export async function requireRemovableAvatar(c: Context, next: Next) {+ const managed = await getManagedProfile(c.get("userId"));+ if (+ managed?.fields.includes("image") &&+ !canRemoveAvatar(managed.stored.image)+ ) {+ throw new ApiError(403, { ...PROFILE_FIELD_MANAGED_BY_PROVIDER });+ }+ return next();+}diff --git a/apps/api/src/user/managed-profile.ts b/apps/api/src/user/managed-profile.tsnew file mode 100644index 000000000..08ba41eea--- /dev/null+++ b/apps/api/src/user/managed-profile.ts@@ -0,0 +1,71 @@+import type { ManagedProfileField } from "../utils/custom-oauth-env";+import {+ mapCustomOAuthProfileToUser,+ readCustomOAuthPicture,+} from "../utils/custom-oauth-profile";+import { resolveSupportedLocale } from "../utils/supported-locales";+import { isUploadedAvatarUrl } from "./avatar";++export type StoredProfile = {+ name: string;+ image: string | null;+ locale: string | null;+};++export const PROFILE_FIELD_MANAGED_BY_PROVIDER = {+ code: "PROFILE_FIELD_MANAGED_BY_PROVIDER",+ message:+ "Profile fields managed by the identity provider cannot be changed in Kaneo.",+} as const;++// An upload made in Kaneo can still be withdrawn, but never replaced.+export function canRemoveAvatar(image: string | null) {+ return image === null || isUploadedAvatarUrl(image);+}++export function changesManagedProfile(+ data: Record<string, unknown>,+ stored: StoredProfile,+ fields: readonly ManagedProfileField[],+) {+ return fields.some((field) => {+ const next = data[field];+ if (next === undefined || next === stored[field]) return false;+ return !(+ field === "image" &&+ next === null &&+ canRemoveAvatar(stored.image)+ );+ });+}++export function planManagedProfileRefresh(+ profile: Record<string, unknown>,+ stored: StoredProfile,+ fields: readonly ManagedProfileField[],+) {+ const update: Partial<StoredProfile> = {};+ let removeUploadedAvatar = false;++ if (fields.includes("name")) {+ const { name } = mapCustomOAuthProfileToUser(profile);+ if (name && name !== stored.name) update.name = name;+ }++ if (fields.includes("image")) {+ const picture = readCustomOAuthPicture(profile);+ if (picture) {+ if (picture !== stored.image) update.image = picture;+ removeUploadedAvatar = true;+ } else if (stored.image !== null && !isUploadedAvatarUrl(stored.image)) {+ update.image = null;+ }+ }++ if (fields.includes("locale")) {+ const locale = resolveSupportedLocale(profile.locale);+ if (locale && locale !== stored.locale) update.locale = locale;+ }++ return { update, removeUploadedAvatar };+}diff --git a/apps/api/src/user/response.ts b/apps/api/src/user/response.tsindex 07f33af40..c64152cf8 100644--- a/apps/api/src/user/response.ts+++ b/apps/api/src/user/response.ts@@ -1,4 +1,5 @@import { z } from "../openapi";+import { MANAGED_PROFILE_FIELDS } from "../utils/custom-oauth-env";export const avatarSchema = z.object({@@ -26,5 +27,9 @@ export const currentUserSchema = zemail: z.string(),image: z.string().nullable(),role: z.string().nullable(),+ managedProfileFields: z.array(z.enum(MANAGED_PROFILE_FIELDS)).openapi({+ description:+ "Profile fields the custom OAuth/OIDC provider manages for this user. Kaneo updates them at sign-in and refuses changes to them.",+ }),}).openapi("CurrentUser");diff --git a/apps/api/src/utils/custom-oauth-env.ts b/apps/api/src/utils/custom-oauth-env.tsnew file mode 100644index 000000000..7bd0556b5--- /dev/null+++ b/apps/api/src/utils/custom-oauth-env.ts@@ -0,0 +1,44 @@+import { isHttpUrl } from "./is-http-url";++export const MANAGED_PROFILE_FIELDS = ["name", "image", "locale"] as const;++export type ManagedProfileField = (typeof MANAGED_PROFILE_FIELDS)[number];++function isManagedProfileField(value: string): value is ManagedProfileField {+ return (MANAGED_PROFILE_FIELDS as readonly string[]).includes(value);+}++export function parseManagedProfileFields(+ raw = process.env.CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS,+): ManagedProfileField[] {+ const fields = new Set<ManagedProfileField>();+ for (const entry of (raw ?? "").split(",")) {+ const field = entry.trim().toLowerCase();+ if (!field) continue;+ if (!isManagedProfileField(field)) {+ throw new Error(+ `CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS accepts name, image and locale, not "${entry.trim()}".`,+ );+ }+ fields.add(field);+ }+ return MANAGED_PROFILE_FIELDS.filter((field) => fields.has(field));+}++export function parseCustomOAuthAccountUrl(+ raw = process.env.CUSTOM_OAUTH_ACCOUNT_URL,+): string | null {+ const value = raw?.trim();+ if (!value) return null;+ if (!isHttpUrl(value)) {+ throw new Error(+ "CUSTOM_OAUTH_ACCOUNT_URL must be an absolute http or https URL.",+ );+ }+ return new URL(value).href;+}++export function assertCustomOAuthEnv() {+ parseManagedProfileFields();+ parseCustomOAuthAccountUrl();+}diff --git a/apps/api/src/utils/custom-oauth-profile.ts b/apps/api/src/utils/custom-oauth-profile.tsindex c8952836b..5c73d082b 100644--- a/apps/api/src/utils/custom-oauth-profile.ts+++ b/apps/api/src/utils/custom-oauth-profile.ts@@ -1,8 +1,26 @@+import type { ManagedProfileField } from "./custom-oauth-env";+import { isHttpUrl } from "./is-http-url";+import { resolveSupportedLocale } from "./supported-locales";++const MAX_PICTURE_URL_LENGTH = 2048;+function stringOrEmpty(value: unknown) {return typeof value === "string" ? value.trim() : "";}-export function mapCustomOAuthProfileToUser(profile: Record<string, unknown>) {+export function readCustomOAuthPicture(profile: Record<string, unknown>) {+ const picture = stringOrEmpty(profile.picture);+ if (picture.length > MAX_PICTURE_URL_LENGTH || !isHttpUrl(picture)) {+ return null;+ }+ const { href } = new URL(picture);+ return href.length <= MAX_PICTURE_URL_LENGTH ? href : null;+}++export function mapCustomOAuthProfileToUser(+ profile: Record<string, unknown>,+ managedFields: readonly ManagedProfileField[] = [],+) {const email = stringOrEmpty(profile.email);const nameFromParts = [stringOrEmpty(profile.given_name),@@ -18,5 +36,13 @@ export function mapCustomOAuthProfileToUser(profile: Record<string, unknown>) {email ? email.split("@")[0] : "",].find(Boolean);- return fallbackName ? { name: fallbackName } : {};+ return {+ ...(fallbackName ? { name: fallbackName } : {}),+ ...(managedFields.includes("image")+ ? { image: readCustomOAuthPicture(profile) }+ : {}),+ ...(managedFields.includes("locale")+ ? { locale: resolveSupportedLocale(profile.locale) }+ : {}),+ };}diff --git a/apps/api/src/utils/custom-oauth-sign-in.ts b/apps/api/src/utils/custom-oauth-sign-in.tsnew file mode 100644index 000000000..5ba347327--- /dev/null+++ b/apps/api/src/utils/custom-oauth-sign-in.ts@@ -0,0 +1,21 @@+import { AsyncLocalStorage } from "node:async_hooks";++type CustomOAuthSignIn = { profile?: Record<string, unknown> };++const customOAuthSignIn = new AsyncLocalStorage<CustomOAuthSignIn>();++export function runCustomOAuthCallback<T>(callback: () => T): T {+ return customOAuthSignIn.run({}, callback);+}++export function rememberCustomOAuthProfile(profile: Record<string, unknown>) {+ const store = customOAuthSignIn.getStore();+ if (store) store.profile = profile;+}++export function takeCustomOAuthProfile() {+ const store = customOAuthSignIn.getStore();+ const profile = store?.profile;+ if (store) store.profile = undefined;+ return profile;+}diff --git a/apps/api/src/utils/get-settings.ts b/apps/api/src/utils/get-settings.tsindex df4abd873..42fcfac4b 100644--- a/apps/api/src/utils/get-settings.ts+++ b/apps/api/src/utils/get-settings.ts@@ -2,6 +2,10 @@ import { isSmtpConfigured } from "@kaneo/email";import { config } from "dotenv-mono";import { isBillingEnabled } from "../billing/config";import { isStorageConfigured } from "../storage/s3";+import {+ parseCustomOAuthAccountUrl,+ parseManagedProfileFields,+} from "./custom-oauth-env";import { resolveFileSecret } from "./file-secret";import { isGithubSsoConfigured } from "./github-sso-env";import { isCloud } from "./is-cloud";@@ -39,6 +43,8 @@ function getSettings() {customOAuthName: process.env.CUSTOM_OAUTH_NAME?.trim() || null,customOAuthAutoLogin: process.env.CUSTOM_OAUTH_AUTO_LOGIN === "true",customOAuthLogoutUrl: process.env.CUSTOM_OAUTH_LOGOUT_URL || null,+ customOAuthManagedProfileFields: parseManagedProfileFields(),+ customOAuthAccountUrl: parseCustomOAuthAccountUrl(),billingEnabled: isBillingEnabled(),};}diff --git a/apps/api/src/utils/is-http-url.ts b/apps/api/src/utils/is-http-url.tsnew file mode 100644index 000000000..21981ee47--- /dev/null+++ b/apps/api/src/utils/is-http-url.ts@@ -0,0 +1,8 @@+export function isHttpUrl(value: string) {+ try {+ const { protocol } = new URL(value);+ return protocol === "http:" || protocol === "https:";+ } catch {+ return false;+ }+}diff --git a/apps/api/src/utils/supported-locales.ts b/apps/api/src/utils/supported-locales.tsnew file mode 100644index 000000000..263af2c39--- /dev/null+++ b/apps/api/src/utils/supported-locales.ts@@ -0,0 +1,56 @@+// Mirrors i18n/resources.ts, which lies outside this package's rootDir.+export const SUPPORTED_LOCALES = [+ "az-AZ",+ "mk-MK",+ "nl-NL",+ "de-DE",+ "el-GR",+ "en-US",+ "es-ES",+ "fr-FR",+ "hi-IN",+ "id-ID",+ "it-IT",+ "ja-JP",+ "ko-KR",+ "pl-PL",+ "pt-BR",+ "ru-RU",+ "tr-TR",+ "uk-UA",+ "vi-VN",+ "zh-CN",+ "zh-TW",+] as const;++export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number];++function getLanguageCode(locale: string) {+ return locale.toLowerCase().split("-")[0];+}++function getScript(locale: string) {+ try {+ return new Intl.Locale(locale).maximize().script;+ } catch {+ return undefined;+ }+}++export function resolveSupportedLocale(value: unknown): SupportedLocale | null {+ if (typeof value !== "string") return null;+ const candidate = value.trim().replaceAll("_", "-").toLowerCase();+ if (!candidate) return null;+ return (+ SUPPORTED_LOCALES.find((locale) => locale.toLowerCase() === candidate) ??+ SUPPORTED_LOCALES.find(+ (locale) =>+ getLanguageCode(locale) === getLanguageCode(candidate) &&+ getScript(locale) === getScript(candidate),+ ) ??+ SUPPORTED_LOCALES.find(+ (locale) => getLanguageCode(locale) === getLanguageCode(candidate),+ ) ??+ null+ );+}diff --git a/apps/docs/api-reference/errors.mdx b/apps/docs/api-reference/errors.mdxindex 30a5915b4..c150426f7 100644--- a/apps/docs/api-reference/errors.mdx+++ b/apps/docs/api-reference/errors.mdx@@ -55,6 +55,7 @@ An unknown path under `/api` returns `404` with `{"message": "Not found", "code"| `API_KEY_SCOPE` | 403 | The API key was created with permissions that do not cover the action. `missingPermissions` lists what is missing. || `SESSION_REQUIRED` | 403 | The endpoint needs a signed-in user session and does not accept API keys. This covers account-level actions such as billing, instance administration, and some GitHub setup routes. || `INTEGRATION_AUTH_FAILED` | 401 | A connected service such as GitLab rejected the token in the request, or could not be reached to check it. Your Kaneo session or API key is still valid. |+| `PROFILE_FIELD_MANAGED_BY_PROVIDER` | 403 | The custom OAuth/OIDC provider manages this profile field for the user, so Kaneo does not change it. Returned by `POST /api/auth/update-user`, `POST /api/auth/admin/update-user`, and `PUT` or `DELETE /api/user/avatar`. See [Managed profile fields](/core/social-providers/custom-oauth#managed-profile-fields). |`missingPermissions` only names permissions for the route you called in the workspace it targets.@@ -96,6 +97,7 @@ These endpoints follow external standards and keep their own error bodies:- **Device authorization.** `/api/auth/device/code` and `/api/auth/device/token` return RFC 8628 errors such as `{"error": "authorization_pending"}` and `{"error": "slow_down"}`. See [Authentication](/api-reference/authentication#poll-for-a-token).- **MCP OAuth.** `/api/mcp/register`, `/api/mcp/authorize`, `/api/mcp/authorize/request/{requestId}`, and `/api/mcp/token` return RFC 6749 and RFC 7591 errors shaped as `{"error": "invalid_request", "error_description": "..."}`. The `/api/mcp` endpoint itself answers with `{"error": ...}` bodies, such as `invalid_token`, and MCP protocol messages.- **Inbound webhooks.** The GitHub, Gitea, and GitLab webhook receivers are called by those services, not by API clients, and keep their existing responses.+- **Back-channel logout.** Your identity provider calls `POST /api/auth/oauth2/backchannel-logout/custom`, which answers as OpenID Connect back-channel logout describes: `200` with an empty body, `400` with `{"error": "invalid_request"}` for a missing, invalid, or reused logout token, and `503` with `{"error": "temporarily_unavailable"}` when Kaneo cannot load the provider's discovery document or signing keys. See [Back-channel logout](/core/social-providers/custom-oauth#back-channel-logout).## Older instancesdiff --git a/apps/docs/core/functional/manage-your-account.mdx b/apps/docs/core/functional/manage-your-account.mdxindex e93ae6016..eb07224dd 100644--- a/apps/docs/core/functional/manage-your-account.mdx+++ b/apps/docs/core/functional/manage-your-account.mdx@@ -14,6 +14,8 @@ Your profile picture and your account itself are both managed from **SettingsSelect **Remove** to go back to your initials. Pictures are stored in your Kaneo database, so self-hosted instances need no object storage for this and a normal database backup includes them.+If your organization manages profile pictures through single sign-on, the row says **Managed by your organization.** and has no **Upload** button. Change the picture with your sign-in provider, through the **Edit in** link when it is shown. **Remove** still works for a picture you uploaded in Kaneo earlier.+## Change your passwordOpen **Settings → Account → Security** and select **Change password**. Enter the current password, choose a new one, and confirm it. The new password must be between 8 and 128 characters.diff --git a/apps/docs/core/functional/personalize-your-workspace.mdx b/apps/docs/core/functional/personalize-your-workspace.mdxindex d605b8482..f38c5a2c7 100644--- a/apps/docs/core/functional/personalize-your-workspace.mdx+++ b/apps/docs/core/functional/personalize-your-workspace.mdx@@ -7,7 +7,7 @@ Open **Settings → Account → Preferences**. These are your preferences, so ch## Appearance and layout-Choose your theme, default task view, compact mode, and whether the sidebar starts open or closed. You can also change the language and calendar preferences available on this page.+Choose your theme, default task view, compact mode, and whether the sidebar starts open or closed. You can also change the language and calendar preferences available on this page. If your organization manages your language through single sign-on, the language picker is read-only.<Frame caption="List view is useful when you prefer to scan work in rows."><img className="block dark:hidden" src="/images/product/list-light.png" alt="List view is useful when you prefer to scan work in rows." />diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdxindex 0365f87a3..1094931f7 100644--- a/apps/docs/core/installation/environment-variables.mdx+++ b/apps/docs/core/installation/environment-variables.mdx@@ -188,6 +188,9 @@ Name | Description || `CUSTOM_AUTH_PKCE` | (Optional) Enable/disable PKCE. Default: `true`.| `CUSTOM_OAUTH_NAME` | (Optional) Provider name on the sign-in button, for example `Authentik`. Default: `SSO`.| `CUSTOM_OAUTH_LOGOUT_URL` | (Optional) Logout endpoint URL for your identity provider.+| `CUSTOM_OAUTH_BACKCHANNEL_LOGOUT` | (Optional) Set to `true` to sign out Kaneo sessions when your identity provider sends an OpenID Connect back-channel logout to `/api/auth/oauth2/backchannel-logout/custom`. Requires `CUSTOM_OAUTH_DISCOVERY_URL` and `CUSTOM_OAUTH_CLIENT_ID`. Without them, the API stops at startup. Default: `false`.+| `CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS` | (Optional) Comma-separated profile fields your identity provider manages: `name`, `image`, `locale`. Kaneo updates them from the provider's claims whenever someone signs in with it, and people with a linked provider account cannot change them in Kaneo. Any other value stops the API at startup. Default: unset, so profiles stay editable.+| `CUSTOM_OAUTH_ACCOUNT_URL` | (Optional) Absolute `http` or `https` URL of your identity provider's account page. Kaneo links to it next to managed profile fields. An invalid URL stops the API at startup.### Redisdiff --git a/apps/docs/core/social-providers/custom-oauth.mdx b/apps/docs/core/social-providers/custom-oauth.mdxindex c09931f57..d45412587 100644--- a/apps/docs/core/social-providers/custom-oauth.mdx+++ b/apps/docs/core/social-providers/custom-oauth.mdx@@ -35,7 +35,10 @@ If you use a discovery URL, the provider can supply the authorization, token, an| `CUSTOM_AUTH_PKCE` | Enable/disable PKCE (Proof Key for Code Exchange) | `true` || `CUSTOM_OAUTH_NAME` | Provider name on the sign-in button, for example `Authentik` | `SSO` || `CUSTOM_OAUTH_LOGOUT_URL` | Provider logout endpoint, if needed | Unset |+| `CUSTOM_OAUTH_BACKCHANNEL_LOGOUT` | Sign out Kaneo sessions when the provider sends a back-channel logout. Requires `CUSTOM_OAUTH_DISCOVERY_URL`. See [back-channel logout](#back-channel-logout) | `false` || `CUSTOM_OAUTH_AUTO_LOGIN` | Auto-redirect to the custom OAuth provider, bypassing the login page | `false` |+| `CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS` | Comma-separated profile fields the provider manages: `name`, `image`, `locale`. See [managed profile fields](#managed-profile-fields) | Unset |+| `CUSTOM_OAUTH_ACCOUNT_URL` | Provider account page, linked next to managed profile fields | Unset |## Setup Steps@@ -180,6 +183,47 @@ CUSTOM_OAUTH_DISCOVERY_URL=https://your-idp.com/.well-known/openid-configurationThis will automatically discover the authorization, token, and userinfo endpoints. However, you still need to provide the client ID and secret.+## Back-channel logout++With OpenID Connect back-channel logout, your identity provider tells Kaneo when a session ends there, for example when someone signs out in another app or an administrator ends their session. Kaneo then signs out the matching Kaneo sessions, even when no Kaneo tab is open.++Kaneo reads the issuer and the signing keys from the discovery document, and it needs the `openid` scope to remember which provider session each sign-in belongs to:++```bash+CUSTOM_OAUTH_DISCOVERY_URL=https://keycloak.example.com/realms/your-realm/.well-known/openid-configuration+CUSTOM_OAUTH_SCOPES=openid,profile,email+CUSTOM_OAUTH_BACKCHANNEL_LOGOUT=true+```++Recreate the Kaneo container, then register this back-channel logout URL with your provider:++```+https://kaneo.example.com/api/auth/oauth2/backchannel-logout/custom+```++For a separately hosted API at `https://api.kaneo.example.com`, use `https://api.kaneo.example.com/api/auth/oauth2/backchannel-logout/custom`. If `KANEO_API_URL` already ends in `/api`, do not add another `/api` segment. The provider calls this URL directly, so it must be able to reach Kaneo.++What a logout signs out:++- A logout token with a session ID (`sid`) ends the Kaneo sessions that started from that provider session. Kaneo stores the `sid` of the ID token at every sign-in through the provider, also while `CUSTOM_OAUTH_BACKCHANNEL_LOGOUT` is off, so turning it on later also covers sessions that already exist.+- A logout token without a session ID ends all Kaneo sessions of that person.+- Only sign-ins through the provider store a session ID. Sessions of the Kaneo mobile app, the Kaneo CLI and MCP clients have none, even when someone approves them while signed in through the provider. Sessions that started before you upgraded to a Kaneo version with back-channel logout, or without the `openid` scope, have none either. Only a logout token without a session ID ends them.+- API keys are not sessions. They keep working until you revoke them.++Open Kaneo tabs return to the sign-in page right away once the person has no Kaneo session left. Otherwise, a signed-out tab notices on its next request. With several API instances, this needs [Redis](/core/installation/environment-variables#redis).++Kaneo answers `200` when it accepts a logout token, also when no session matched, and `400` for an invalid or reused token. It answers `503` when it cannot load the discovery document or the signing keys, and `404` while `CUSTOM_OAUTH_BACKCHANNEL_LOGOUT` is not `true`. Once Kaneo has loaded the signing keys, it keeps using them while they cannot be refreshed, so a token signed with a key the provider added since then answers `400` until the keys load again.++In Keycloak, open your client and go to **Settings** > **Logout settings**:++1. Turn off **Front channel logout**.+2. Set **Backchannel logout URL** to the URL above.+3. Keep **Backchannel logout session required** on, so that logout tokens carry the session ID.++With **Backchannel logout session required** on, Keycloak sends a session ID in every logout token, so mobile app, CLI and MCP sessions stay signed in after a Keycloak logout. When someone leaves, also [deactivate their account](/core/operations/administration#manage-users) in Kaneo. That ends all of their sessions and stops their API keys from working.++If Kaneo reads the discovery document through an internal address, configure Keycloak's hostname so the issuer in the document matches the `iss` claim of Keycloak's tokens. Otherwise, Kaneo rejects every logout token.+## Account linkingWhen a user signs in with this provider using an email that already belongs to a Kaneo account, Kaneo can link the OIDC identity to that account. The provider must return a verified email claim; being configured does not make an unverified email trusted. Configure your identity provider to return `email_verified: true` only after establishing ownership of the email address. An unverified claim cannot satisfy email-based invitation matching either.@@ -188,6 +232,34 @@ For safety, Kaneo only links to an existing local account if that account's emaiOn existing installations, local accounts created before this requirement may still have an unverified email. Those users will receive `error=account_not_linked` until they verify the local account. Before enforcing SSO-only access, keep the login form available so affected users can sign in with an email OTP or magic link, which verifies the email. If users are already locked out, temporarily set `DISABLE_LOGIN_FORM=false` and `CUSTOM_OAUTH_AUTO_LOGIN=false`, recreate the Kaneo container, and have them complete an email sign-in before enabling SSO-only access again.+## Managed profile fields++When your identity provider is the source of truth for names, profile pictures, or languages, let it manage them in Kaneo:++```bash+CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS=name,image,locale+# Optional: link people to the page where they change these fields+CUSTOM_OAUTH_ACCOUNT_URL=https://keycloak.example.com/realms/your-realm/account+```++At every sign-in through this provider, Kaneo copies the listed fields from the provider's claims. It reads the claims from the ID token when the token contains `sub` and `email`, and from the user info endpoint otherwise.++| Field | Claim | What Kaneo stores |+|-------|-------|-------------------|+| `name` | `name` | The same name Kaneo uses when it creates the account: `name`, then `given_name` and `family_name`, then `preferred_username`, then the part of the email before the `@`. |+| `image` | `picture` | An absolute `http` or `https` URL of up to 2,048 characters. Without one, Kaneo removes the profile picture, but keeps a picture uploaded in Kaneo until the provider sends one. A picture from the provider replaces the upload and deletes it. |+| `locale` | `locale` | The matching Kaneo language: first by tag, then by language and script, then by language, so `de` becomes `de-DE` and `zh-Hant` or `zh-HK` becomes `zh-TW`. A missing or unsupported value keeps the current language. |++Fields you do not list stay as they are. Accounts that Kaneo creates through the provider start with the same values. Signing in never changes the email address, but it marks the email of an account already linked to the provider as verified when the provider reports the same address as verified.++People with a linked provider account see managed fields as read-only on their profile and preferences pages, with a link to `CUSTOM_OAUTH_ACCOUNT_URL` when you set it. They can still remove a picture they uploaded in Kaneo earlier, but they cannot upload a new one. People without a linked provider account keep full editing.++The API enforces this too, also for API keys and administrators. `POST /api/auth/update-user` and `POST /api/auth/admin/update-user` answer `403` with the code `PROFILE_FIELD_MANAGED_BY_PROVIDER` when they would change a managed field, except removing a picture uploaded in Kaneo. A request that sends the current value again succeeds. While the provider manages the picture, `PUT /api/user/avatar` answers the same way, and so does `DELETE /api/user/avatar` if a picture other than an upload made in Kaneo is stored.++In Keycloak, the default `profile` client scope maps the `picture` and `locale` user attributes to these claims. Keycloak only sets `locale` when internationalization is enabled for the realm.++If you remove the provider settings later, remove `CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS` as well, so people can edit their profiles in Kaneo again.+## Security Notes- Always use HTTPS in productiondiff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex e196867dc..ff5167255 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -606,6 +606,25 @@"null"]},+ "customOAuthManagedProfileFields": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "name",+ "image",+ "locale"+ ]+ },+ "description": "Profile fields the custom OAuth/OIDC provider manages for people with a linked provider account."+ },+ "customOAuthAccountUrl": {+ "type": [+ "string",+ "null"+ ],+ "description": "Account page of the custom OAuth/OIDC provider, where people change managed profile fields. Null when not configured."+ },"billingEnabled": {"type": "boolean"}@@ -628,6 +647,8 @@"customOAuthName","customOAuthAutoLogin","customOAuthLogoutUrl",+ "customOAuthManagedProfileFields",+ "customOAuthAccountUrl","billingEnabled"]},@@ -5175,6 +5196,18 @@"string","null"]+ },+ "managedProfileFields": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "name",+ "image",+ "locale"+ ]+ },+ "description": "Profile fields the custom OAuth/OIDC provider manages for this user. Kaneo updates them at sign-in and refuses changes to them."}},"required": [@@ -5182,7 +5215,8 @@"name","email","image",- "role"+ "role",+ "managedProfileFields"]},"UserAvatar": {@@ -23569,6 +23603,16 @@}}},+ "403": {+ "description": "The custom OAuth/OIDC provider manages the profile picture",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },"408": {"description": "Request body timed out","content": {@@ -23622,6 +23666,16 @@}}},+ "403": {+ "description": "The custom OAuth/OIDC provider manages the profile picture",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },"429": {"$ref": "#/components/responses/ApiKeyRateLimited"}diff --git a/apps/web/src/components/auth/auth-methods.test.ts b/apps/web/src/components/auth/auth-methods.test.tsindex d8c0636d6..4a448f569 100644--- a/apps/web/src/components/auth/auth-methods.test.ts+++ b/apps/web/src/components/auth/auth-methods.test.ts@@ -28,6 +28,8 @@ function config(overrides: Partial<GetConfigResponse> = {}) {customOAuthName: null,customOAuthAutoLogin: false,customOAuthLogoutUrl: null,+ customOAuthManagedProfileFields: [],+ customOAuthAccountUrl: null,billingEnabled: false,...overrides,} satisfies GetConfigResponse;diff --git a/apps/web/src/components/settings/managed-profile-note.test.tsx b/apps/web/src/components/settings/managed-profile-note.test.tsxnew file mode 100644index 000000000..9a7baa0fa--- /dev/null+++ b/apps/web/src/components/settings/managed-profile-note.test.tsx@@ -0,0 +1,75 @@+import { cleanup, render, screen } from "@testing-library/react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { ManagedProfileNote } from "./managed-profile-note";++const m = vi.hoisted(() => ({+ config: undefined as+ | {+ customOAuthName: string | null;+ customOAuthAccountUrl: string | null;+ }+ | undefined,+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, options?: { provider?: string }) =>+ options?.provider ? `${key}|${options.provider}` : key,+ }),+}));+vi.mock("@/hooks/queries/config/use-get-config", () => ({+ default: () => ({ data: m.config }),+}));++const ACCOUNT_URL = "https://keycloak.example.com/realms/acme/account";++describe("ManagedProfileNote", () => {+ afterEach(cleanup);++ beforeEach(() => {+ m.config = { customOAuthName: "Keycloak", customOAuthAccountUrl: null };+ });++ it("says the organization manages the field and offers no link without an account page", () => {+ render(<ManagedProfileNote />);++ expect(screen.getByText("settings:managedProfile.note")).toBeTruthy();+ expect(screen.queryByRole("link")).toBeNull();+ });++ it("links to the provider's account page in a new tab", () => {+ m.config = {+ customOAuthName: "Keycloak",+ customOAuthAccountUrl: ACCOUNT_URL,+ };+ render(<ManagedProfileNote />);++ const link = screen.getByRole("link", {+ name: "settings:managedProfile.edit|Keycloak",+ });+ expect(link).toHaveAttribute("href", ACCOUNT_URL);+ expect(link).toHaveAttribute("target", "_blank");+ expect(link).toHaveAttribute("rel", "noopener noreferrer");+ });++ it("names the provider by its generic label when it has no name", () => {+ m.config = {+ customOAuthName: null,+ customOAuthAccountUrl: ACCOUNT_URL,+ };+ render(<ManagedProfileNote />);++ expect(+ screen.getByRole("link", {+ name: "settings:managedProfile.edit|auth:providers.sso",+ }),+ ).toBeTruthy();+ });+});diff --git a/apps/web/src/components/settings/managed-profile-note.tsx b/apps/web/src/components/settings/managed-profile-note.tsxnew file mode 100644index 000000000..b4ca6b7c1--- /dev/null+++ b/apps/web/src/components/settings/managed-profile-note.tsx@@ -0,0 +1,31 @@+import { useTranslation } from "react-i18next";+import { useProviderName } from "@/components/auth/use-provider-name";+import useGetConfig from "@/hooks/queries/config/use-get-config";++export function ManagedProfileNote() {+ const { t } = useTranslation();+ const { data: config } = useGetConfig();+ const getProviderName = useProviderName(config?.customOAuthName);+ const accountUrl = config?.customOAuthAccountUrl;++ return (+ <span>+ {t("settings:managedProfile.note")}+ {accountUrl ? (+ <>+ {" "}+ <a+ href={accountUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-foreground underline underline-offset-2"+ >+ {t("settings:managedProfile.edit", {+ provider: getProviderName("custom"),+ })}+ </a>+ </>+ ) : null}+ </span>+ );+}diff --git a/apps/web/src/components/settings/preferences/language-row.test.tsx b/apps/web/src/components/settings/preferences/language-row.test.tsxnew file mode 100644index 000000000..9517c1240--- /dev/null+++ b/apps/web/src/components/settings/preferences/language-row.test.tsx@@ -0,0 +1,85 @@+import { cleanup, render, screen } from "@testing-library/react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { LanguageRow } from "./language-row";++const m = vi.hoisted(() => ({+ managedFields: [] as string[],+ config: undefined as+ | {+ customOAuthName: string | null;+ customOAuthAccountUrl: string | null;+ }+ | undefined,+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, options?: { provider?: string }) =>+ options?.provider ? `${key}|${options.provider}` : key,+ }),+}));+vi.mock("@/hooks/use-locale", () => ({+ useLocale: () => ({ locale: "de-DE", setLocale: vi.fn() }),+}));+vi.mock("@/hooks/queries/user/use-managed-profile-fields", () => ({+ default: () => m.managedFields,+}));+vi.mock("@/hooks/queries/config/use-get-config", () => ({+ default: () => ({ data: m.config }),+}));++const ACCOUNT_URL = "https://keycloak.example.com/realms/acme/account";++function languagePicker() {+ return screen.getByRole("combobox", {+ name: "settings:preferencesPage.language",+ });+}++describe("LanguageRow", () => {+ afterEach(cleanup);++ beforeEach(() => {+ m.managedFields = [];+ m.config = { customOAuthName: "Keycloak", customOAuthAccountUrl: null };+ });++ it("lets people pick a language when it is not managed", () => {+ m.managedFields = ["name", "image"];+ render(<LanguageRow />);++ expect(languagePicker()).not.toHaveAttribute("data-disabled");+ expect(screen.queryByText("settings:managedProfile.note")).toBeNull();+ });++ it("disables the picker with a hint when the provider manages the language", () => {+ m.managedFields = ["locale"];+ render(<LanguageRow />);++ expect(languagePicker()).toHaveAttribute("data-disabled");+ expect(screen.getByText("settings:managedProfile.note")).toBeTruthy();+ expect(screen.queryByRole("link")).toBeNull();+ });++ it("links to the provider's account page when one is configured", () => {+ m.managedFields = ["locale"];+ m.config = {+ customOAuthName: "Keycloak",+ customOAuthAccountUrl: ACCOUNT_URL,+ };+ render(<LanguageRow />);++ expect(+ screen.getByRole("link", {+ name: "settings:managedProfile.edit|Keycloak",+ }),+ ).toHaveAttribute("href", ACCOUNT_URL);+ });+});diff --git a/apps/web/src/components/settings/preferences/language-row.tsx b/apps/web/src/components/settings/preferences/language-row.tsxindex c57ced894..1acbb1f20 100644--- a/apps/web/src/components/settings/preferences/language-row.tsx+++ b/apps/web/src/components/settings/preferences/language-row.tsx@@ -4,6 +4,7 @@ import {supportedLocales,} from "@i18n/resources";import { useTranslation } from "react-i18next";+import { ManagedProfileNote } from "@/components/settings/managed-profile-note";import { SettingsRow } from "@/components/settings/settings-row";import {Select,@@ -12,18 +13,25 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";+import useManagedProfileFields from "@/hooks/queries/user/use-managed-profile-fields";import { useLocale } from "@/hooks/use-locale";import { getLocaleLabel } from "@/lib/i18n/get-locale-label";export function LanguageRow() {const { t } = useTranslation();const { locale, setLocale } = useLocale();+ const isManaged = useManagedProfileFields().includes("locale");const selectedLocale: AppLocale = locale ?? defaultLocale;return (- <SettingsRow stack title={t("settings:preferencesPage.language")}>+ <SettingsRow+ stack+ title={t("settings:preferencesPage.language")}+ description={isManaged ? <ManagedProfileNote /> : undefined}+ ><Selectvalue={selectedLocale}+ disabled={isManaged}onValueChange={(value) => {if (value) {void setLocale(value as AppLocale);diff --git a/apps/web/src/components/settings/profile/avatar-row.test.tsx b/apps/web/src/components/settings/profile/avatar-row.test.tsxindex 12e726605..a9e4b3db5 100644--- a/apps/web/src/components/settings/profile/avatar-row.test.tsx+++ b/apps/web/src/components/settings/profile/avatar-row.test.tsx@@ -76,4 +76,51 @@ describe("AvatarRow", () => {await waitFor(() => expect(m.remove).toHaveBeenCalled());await waitFor(() => expect(m.refetch).toHaveBeenCalled());});++ it("shows the managed note instead of the upload controls", () => {+ render(+ <AvatarRow+ name="Jo"+ image="https://id.example.com/jo.png"+ refetchUser={m.refetch}+ managedNote="Managed elsewhere"+ />,+ );++ expect(screen.getByText("Managed elsewhere")).toBeTruthy();+ expect(+ screen.queryByText("settings:informationPage.avatar.hint"),+ ).toBeNull();+ for (const action of ["upload", "remove"]) {+ expect(+ screen.queryByRole("button", {+ name: `settings:informationPage.avatar.${action}`,+ }),+ ).toBeNull();+ }+ });++ it("still removes a managed user's earlier upload", async () => {+ render(+ <AvatarRow+ name="Jo"+ image="/api/user/avatar/avatar-1"+ refetchUser={m.refetch}+ managedNote="Managed elsewhere"+ />,+ );++ fireEvent.click(+ screen.getByRole("button", {+ name: "settings:informationPage.avatar.remove",+ }),+ );++ await waitFor(() => expect(m.remove).toHaveBeenCalled());+ expect(+ screen.queryByRole("button", {+ name: "settings:informationPage.avatar.upload",+ }),+ ).toBeNull();+ });});diff --git a/apps/web/src/components/settings/profile/avatar-row.tsx b/apps/web/src/components/settings/profile/avatar-row.tsxindex 8213d12bd..31ed3d418 100644--- a/apps/web/src/components/settings/profile/avatar-row.tsx+++ b/apps/web/src/components/settings/profile/avatar-row.tsx@@ -1,5 +1,5 @@import { Loader2, ImageMinusIcon, ImageUpIcon } from "lucide-react";-import { type ChangeEvent, useRef } from "react";+import { type ChangeEvent, type ReactNode, useRef } from "react";import { useTranslation } from "react-i18next";import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";import { Button } from "@/components/ui/button";@@ -13,9 +13,15 @@ type AvatarRowProps = {name: string | undefined;image: string | null | undefined;refetchUser: () => Promise<unknown>;+ managedNote?: ReactNode;};-export function AvatarRow({ name, image, refetchUser }: AvatarRowProps) {+export function AvatarRow({+ name,+ image,+ refetchUser,+ managedNote,+}: AvatarRowProps) {const { t } = useTranslation();const inputRef = useRef<HTMLInputElement>(null);const { mutateAsync: updateAvatar, isPending: isUploading } =@@ -23,6 +29,10 @@ export function AvatarRow({ name, image, refetchUser }: AvatarRowProps) {const { mutateAsync: removeAvatar, isPending: isRemoving } =useRemoveUserAvatar();const isBusy = isUploading || isRemoving;+ // With a managed picture, only an earlier Kaneo upload can be removed.+ const canRemove = managedNote+ ? Boolean(image?.startsWith("/api/user/avatar/"))+ : Boolean(image);const handleSelected = async (event: ChangeEvent<HTMLInputElement>) => {const file = event.target.files?.[0];@@ -74,19 +84,12 @@ export function AvatarRow({ name, image, refetchUser }: AvatarRowProps) {{t("settings:informationPage.profilePicture")}</p><p className="text-xs text-muted-foreground">- {t("settings:informationPage.avatar.hint")}+ {managedNote ?? t("settings:informationPage.avatar.hint")}</p></div></div><div className="flex shrink-0 items-center gap-2">- <input- ref={inputRef}- type="file"- accept={ACCEPTED_AVATAR_TYPES}- className="hidden"- onChange={handleSelected}- />- {image ? (+ {canRemove ? (<Buttontype="button"variant="ghost"@@ -98,17 +101,28 @@ export function AvatarRow({ name, image, refetchUser }: AvatarRowProps) {{t("settings:informationPage.avatar.remove")}</Button>) : null}- <Button- type="button"- variant="outline"- size="sm"- className="w-24"- disabled={isBusy}- onClick={() => inputRef.current?.click()}- >- {isUploading ? <Loader2 className="animate-spin" /> : null}- {t("settings:informationPage.avatar.upload")}- </Button>+ {managedNote ? null : (+ <>+ <input+ ref={inputRef}+ type="file"+ accept={ACCEPTED_AVATAR_TYPES}+ className="hidden"+ onChange={handleSelected}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="w-24"+ disabled={isBusy}+ onClick={() => inputRef.current?.click()}+ >+ {isUploading ? <Loader2 className="animate-spin" /> : null}+ {t("settings:informationPage.avatar.upload")}+ </Button>+ </>+ )}</div></div>);diff --git a/apps/web/src/components/settings/profile/profile-details-section.tsx b/apps/web/src/components/settings/profile/profile-details-section.tsxindex 826a3f4e2..0006ca7dd 100644--- a/apps/web/src/components/settings/profile/profile-details-section.tsx+++ b/apps/web/src/components/settings/profile/profile-details-section.tsx@@ -1,5 +1,6 @@import type { UseFormReturn } from "react-hook-form";import { useTranslation } from "react-i18next";+import { ManagedProfileNote } from "@/components/settings/managed-profile-note";import { AvatarRow } from "@/components/settings/profile/avatar-row";import { SettingsCard } from "@/components/settings/settings-card";import { SettingsFormRow } from "@/components/settings/settings-form-row";@@ -7,19 +8,23 @@ import { SettingsRow } from "@/components/settings/settings-row";import { SettingsSection } from "@/components/settings/settings-section";import { Form, FormField } from "@/components/ui/form";import { Input } from "@/components/ui/input";+import type { ManagedProfileField } from "@/hooks/queries/user/use-managed-profile-fields";type ProfileDetailsSectionProps = {form: UseFormReturn<{ name: string }>;user: { name?: string; email?: string; image?: string | null } | undefined;refetchUser: () => Promise<unknown>;+ managedFields: readonly ManagedProfileField[];};export function ProfileDetailsSection({form,user,refetchUser,+ managedFields,}: ProfileDetailsSectionProps) {const { t } = useTranslation();+ const isNameManaged = managedFields.includes("name");return (<SettingsSection title={t("settings:informationPage.sectionTitle")}>@@ -28,6 +33,9 @@ export function ProfileDetailsSection({name={user?.name}image={user?.image}refetchUser={refetchUser}+ managedNote={+ managedFields.includes("image") ? <ManagedProfileNote /> : undefined+ }/><Form {...form}><form onSubmit={(event) => event.preventDefault()}>@@ -35,7 +43,12 @@ export function ProfileDetailsSection({control={form.control}name="name"render={({ field }) => (- <SettingsFormRow label={t("settings:informationPage.fullName")}>+ <SettingsFormRow+ label={t("settings:informationPage.fullName")}+ description={+ isNameManaged ? <ManagedProfileNote /> : undefined+ }+ ><Inputsize="sm"className="sm:w-64"@@ -44,6 +57,7 @@ export function ProfileDetailsSection({"settings:informationPage.fullNamePlaceholder",)}{...field}+ disabled={isNameManaged}/></SettingsFormRow>)}diff --git a/apps/web/src/components/settings/profile/profile-page.test.tsx b/apps/web/src/components/settings/profile/profile-page.test.tsxnew file mode 100644index 000000000..751b76823--- /dev/null+++ b/apps/web/src/components/settings/profile/profile-page.test.tsx@@ -0,0 +1,140 @@+import { cleanup, render, screen } from "@testing-library/react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { ProfilePage } from "./profile-page";++const m = vi.hoisted(() => ({+ managedFields: [] as string[],+ config: undefined as+ | {+ customOAuthName: string | null;+ customOAuthAccountUrl: string | null;+ }+ | undefined,+ user: {+ id: "user-1",+ name: "Jane Doe",+ email: "[email protected]",+ image: null as string | null,+ },+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, options?: { provider?: string }) =>+ options?.provider ? `${key}|${options.provider}` : key,+ }),+}));+vi.mock("@/components/providers/auth-provider/hooks/use-auth", () => ({+ default: () => ({ user: m.user, refetchUser: vi.fn() }),+}));+vi.mock("@/hooks/queries/user/use-managed-profile-fields", () => ({+ default: () => m.managedFields,+}));+vi.mock("@/hooks/queries/config/use-get-config", () => ({+ default: () => ({ data: m.config }),+}));+vi.mock("@/hooks/mutations/use-update-user-profile", () => ({+ default: () => ({ mutateAsync: vi.fn() }),+}));+vi.mock("@/hooks/mutations/use-update-user-avatar", () => ({+ default: () => ({ mutateAsync: vi.fn(), isPending: false }),+}));+vi.mock("@/hooks/mutations/use-remove-user-avatar", () => ({+ default: () => ({ mutateAsync: vi.fn(), isPending: false }),+}));+vi.mock("@/components/settings/profile/delete-account-section", () => ({+ DeleteAccountSection: () => null,+}));+vi.mock("@/lib/toast", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));++const ACCOUNT_URL = "https://keycloak.example.com/realms/acme/account";++function nameInput() {+ return screen.getByRole("textbox", {+ name: "settings:informationPage.fullName",+ });+}++function avatarButton(action: "upload" | "remove") {+ return screen.queryByRole("button", {+ name: `settings:informationPage.avatar.${action}`,+ });+}++describe("ProfilePage", () => {+ afterEach(cleanup);++ beforeEach(() => {+ m.managedFields = [];+ m.config = { customOAuthName: "Keycloak", customOAuthAccountUrl: null };+ m.user = {+ id: "user-1",+ name: "Jane Doe",+ email: "[email protected]",+ image: "https://id.example.com/jane.png",+ };+ });++ it("keeps the name and picture editable when nothing is managed", () => {+ render(<ProfilePage />);++ expect(nameInput()).toBeEnabled();+ expect(avatarButton("upload")).toBeTruthy();+ expect(avatarButton("remove")).toBeTruthy();+ expect(+ screen.getByText("settings:informationPage.avatar.hint"),+ ).toBeTruthy();+ expect(screen.queryByText("settings:managedProfile.note")).toBeNull();+ });++ it("shows the managed name and picture read-only with a hint", () => {+ m.managedFields = ["name", "image"];+ render(<ProfilePage />);++ expect(nameInput()).toBeDisabled();+ expect(nameInput()).toHaveValue("Jane Doe");+ expect(avatarButton("upload")).toBeNull();+ expect(avatarButton("remove")).toBeNull();+ expect(+ screen.queryByText("settings:informationPage.avatar.hint"),+ ).toBeNull();+ expect(screen.getAllByText("settings:managedProfile.note")).toHaveLength(2);+ expect(screen.queryByRole("link")).toBeNull();+ });++ it("links each managed field to the provider's account page", () => {+ m.managedFields = ["name", "image"];+ m.config = {+ customOAuthName: "Keycloak",+ customOAuthAccountUrl: ACCOUNT_URL,+ };+ render(<ProfilePage />);++ const links = screen.getAllByRole("link", {+ name: "settings:managedProfile.edit|Keycloak",+ });+ expect(links).toHaveLength(2);+ for (const link of links) {+ expect(link).toHaveAttribute("href", ACCOUNT_URL);+ }+ });++ it("still lets people remove a picture they uploaded in Kaneo", () => {+ m.managedFields = ["image"];+ m.user.image = "/api/user/avatar/avatar-1";+ render(<ProfilePage />);++ expect(avatarButton("remove")).toBeTruthy();+ expect(avatarButton("upload")).toBeNull();+ expect(nameInput()).toBeEnabled();+ });+});diff --git a/apps/web/src/components/settings/profile/profile-page.tsx b/apps/web/src/components/settings/profile/profile-page.tsxindex 4c76b5ca3..eb0933507 100644--- a/apps/web/src/components/settings/profile/profile-page.tsx+++ b/apps/web/src/components/settings/profile/profile-page.tsx@@ -6,11 +6,13 @@ import { DeleteAccountSection } from "@/components/settings/profile/delete-accouimport { ProfileDetailsSection } from "@/components/settings/profile/profile-details-section";import { useProfileNameAutosave } from "@/components/settings/profile/use-profile-name-autosave";import { SettingsPage } from "@/components/settings/settings-page";+import useManagedProfileFields from "@/hooks/queries/user/use-managed-profile-fields";export function ProfilePage() {const { t } = useTranslation();const { user, refetchUser } = useAuth();const form = useProfileNameAutosave({ name: user?.name, refetchUser });+ const managedFields = useManagedProfileFields();return (<>@@ -24,6 +26,7 @@ export function ProfilePage() {form={form}user={user ?? undefined}refetchUser={refetchUser}+ managedFields={managedFields}/><DeleteAccountSection email={user?.email} /></SettingsPage>diff --git a/apps/web/src/fetchers/user/get-current-user.ts b/apps/web/src/fetchers/user/get-current-user.tsnew file mode 100644index 000000000..787e5e576--- /dev/null+++ b/apps/web/src/fetchers/user/get-current-user.ts@@ -0,0 +1,15 @@+import { client } from "@kaneo/libs";++import { HttpError } from "@/lib/http-error";++async function getCurrentUser() {+ const response = await client.user.me.$get();++ if (!response.ok) {+ throw await HttpError.fromResponse(response);+ }++ return response.json();+}++export default getCurrentUser;diff --git a/apps/web/src/hooks/queries/user/use-managed-profile-fields.test.tsx b/apps/web/src/hooks/queries/user/use-managed-profile-fields.test.tsxnew file mode 100644index 000000000..43cacd59b--- /dev/null+++ b/apps/web/src/hooks/queries/user/use-managed-profile-fields.test.tsx@@ -0,0 +1,94 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, renderHook, waitFor } from "@testing-library/react";+import type { PropsWithChildren } from "react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import useManagedProfileFields from "./use-managed-profile-fields";++const m = vi.hoisted(() => ({+ getCurrentUser: vi.fn(),+ configured: [] as string[],+}));++vi.mock("@/components/providers/auth-provider/hooks/use-auth", () => ({+ default: () => ({ user: { id: "user-1" } }),+}));+vi.mock("@/hooks/queries/config/use-get-config", () => ({+ default: () => ({+ data: { customOAuthManagedProfileFields: m.configured },+ }),+}));+vi.mock("@/fetchers/user/get-current-user", () => ({+ default: m.getCurrentUser,+}));++function renderManagedFields() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: PropsWithChildren) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ return renderHook(() => useManagedProfileFields(), { wrapper });+}++describe("useManagedProfileFields", () => {+ afterEach(cleanup);++ beforeEach(() => {+ m.getCurrentUser.mockReset();+ m.configured = [];+ });++ it("manages nothing and asks nothing when the instance lists no fields", () => {+ const { result } = renderManagedFields();++ expect(result.current).toEqual([]);+ expect(m.getCurrentUser).not.toHaveBeenCalled();+ });++ it("locks the configured fields until the server answers", async () => {+ m.configured = ["name", "locale"];+ m.getCurrentUser.mockReturnValue(new Promise(() => {}));++ const { result } = renderManagedFields();++ expect(result.current).toEqual(["name", "locale"]);+ await waitFor(() => expect(m.getCurrentUser).toHaveBeenCalled());+ });++ it("follows the server for people with a provider account", async () => {+ m.configured = ["name", "locale"];+ m.getCurrentUser.mockResolvedValue({ managedProfileFields: ["name"] });++ const { result } = renderManagedFields();++ await waitFor(() => expect(result.current).toEqual(["name"]));+ });++ it("unlocks the fields for people without a provider account", async () => {+ m.configured = ["name", "locale"];+ m.getCurrentUser.mockResolvedValue({ managedProfileFields: [] });++ const { result } = renderManagedFields();++ await waitFor(() => expect(result.current).toEqual([]));+ });++ it("unlocks the fields when the server cannot answer", async () => {+ m.configured = ["name", "locale"];+ m.getCurrentUser.mockRejectedValue(new Error("Internal Server Error"));++ const { result } = renderManagedFields();++ expect(result.current).toEqual(["name", "locale"]);+ await waitFor(() => expect(result.current).toEqual([]));+ expect(m.getCurrentUser).toHaveBeenCalled();+ });+});diff --git a/apps/web/src/hooks/queries/user/use-managed-profile-fields.ts b/apps/web/src/hooks/queries/user/use-managed-profile-fields.tsnew file mode 100644index 000000000..2e902cca9--- /dev/null+++ b/apps/web/src/hooks/queries/user/use-managed-profile-fields.ts@@ -0,0 +1,26 @@+import { useQuery } from "@tanstack/react-query";+import useAuth from "@/components/providers/auth-provider/hooks/use-auth";+import type { GetConfigResponse } from "@/fetchers/config/get-config";+import getCurrentUser from "@/fetchers/user/get-current-user";+import useGetConfig from "@/hooks/queries/config/use-get-config";++export type ManagedProfileField =+ GetConfigResponse["customOAuthManagedProfileFields"][number];++function useManagedProfileFields(): readonly ManagedProfileField[] {+ const { user } = useAuth();+ const { data: config } = useGetConfig();+ const configured = config?.customOAuthManagedProfileFields ?? [];+ const enabled = Boolean(user?.id) && configured.length > 0;+ const { data, isPending } = useQuery({+ queryKey: ["current-user", user?.id],+ queryFn: getCurrentUser,+ enabled,+ });++ if (!enabled) return [];+ // Lock the configured fields until the server has answered for this user.+ return isPending ? configured : (data?.managedProfileFields ?? []);+}++export default useManagedProfileFields;diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex 491a232ba..c181a5808 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -763,6 +763,10 @@"projectBackgroundsDescription": "Layihənin öz lövhəsi üçün təyin etdiyi arxa fon şəklini göstər.","advancedTitle": "Qabaqcıl"},+ "managedProfile": {+ "note": "Təşkilatınız tərəfindən idarə olunur.",+ "edit": "{{provider}} vasitəsilə redaktə et"+ },"developerPage": {"pageTitle": "API açarları","title": "API açarları",diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 9d7a8ff0c..82d9e755c 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -840,6 +840,10 @@"projectBackgroundsDescription": "Das Hintergrundbild eines Projekts hinter seinem Board anzeigen.","advancedTitle": "Erweitert"},+ "managedProfile": {+ "note": "Von deiner Organisation verwaltet.",+ "edit": "In {{provider}} bearbeiten"+ },"developerPage": {"pageTitle": "API-Schlüssel","title": "API-Schlüssel",diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex b62bd24ab..c8fb96ebe 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -763,6 +763,10 @@"projectBackgroundsDescription": "Εμφάνιση της εικόνας που ορίζει ένα έργο πίσω από τον πίνακά του.","advancedTitle": "Σύνθετα"},+ "managedProfile": {+ "note": "Διαχειρίζεται από τον οργανισμό σας.",+ "edit": "Επεξεργασία στο {{provider}}"+ },"developerPage": {"pageTitle": "Κλειδιά API","title": "Κλειδιά API",diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 22e73a4f0..0b16fc5b9 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -986,6 +986,10 @@"projectBackgroundsDescription": "Show the image a project sets behind its board.","advancedTitle": "Advanced"},+ "managedProfile": {+ "note": "Managed by your organization.",+ "edit": "Edit in {{provider}}"+ },"developerPage": {"pageTitle": "API keys","title": "API keys",diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex a925fca3d..68fb62c84 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -646,6 +646,10 @@"projectBackgroundsDescription": "Muestra la imagen que un proyecto pone detrás de su tablero.","advancedTitle": "Avanzado"},+ "managedProfile": {+ "note": "Gestionado por tu organización.",+ "edit": "Editar en {{provider}}"+ },"developerPage": {"pageTitle": "Claves de API","title": "Claves de API",diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex d97e9e5ec..0ffa0c08e 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -771,6 +771,10 @@"projectBackgroundsDescription": "Afficher l'image définie par un projet derrière son tableau.","advancedTitle": "Avancé"},+ "managedProfile": {+ "note": "Géré par votre organisation.",+ "edit": "Modifier dans {{provider}}"+ },"developerPage": {"pageTitle": "Clés API","title": "Clés API",diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex 40e42bfdd..b9759064d 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -763,6 +763,10 @@"projectBackgroundsDescription": "प्रोजेक्ट द्वारा अपने बोर्ड के पीछे सेट की गई छवि दिखाएँ।","advancedTitle": "उन्नत"},+ "managedProfile": {+ "note": "आपके संगठन द्वारा प्रबंधित।",+ "edit": "{{provider}} में संपादित करें"+ },"developerPage": {"pageTitle": "API कुंजियाँ","title": "API कुंजियाँ",diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 6229f80dd..346601b44 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -755,6 +755,10 @@"projectBackgroundsDescription": "Tampilkan gambar yang diatur proyek di belakang papannya.","advancedTitle": "Lanjutan"},+ "managedProfile": {+ "note": "Dikelola oleh organisasi Anda.",+ "edit": "Edit di {{provider}}"+ },"developerPage": {"pageTitle": "API key","title": "API key",diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex 1a4b5d1cf..bcc2d9f2d 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -771,6 +771,10 @@"projectBackgroundsDescription": "Mostra l'immagine che un progetto imposta dietro la sua board.","advancedTitle": "Avanzate"},+ "managedProfile": {+ "note": "Gestito dalla tua organizzazione.",+ "edit": "Modifica in {{provider}}"+ },"developerPage": {"pageTitle": "Chiavi API","title": "Chiavi API",diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex 33858c154..d15e3f4ad 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -755,6 +755,10 @@"projectBackgroundsDescription": "プロジェクトがボードの背景に設定した画像を表示します。","advancedTitle": "詳細設定"},+ "managedProfile": {+ "note": "組織によって管理されています。",+ "edit": "{{provider}} で編集"+ },"developerPage": {"pageTitle": "APIキー","title": "APIキー",diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex 0c2b55ccf..a871077db 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -755,6 +755,10 @@"projectBackgroundsDescription": "프로젝트에서 보드 배경으로 설정한 이미지를 표시합니다.","advancedTitle": "고급"},+ "managedProfile": {+ "note": "조직에서 관리합니다.",+ "edit": "{{provider}}에서 편집"+ },"developerPage": {"pageTitle": "API 키","title": "API 키",diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 87d0ee040..db488ce2e 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -763,6 +763,10 @@"projectBackgroundsDescription": "Прикажи ја сликата што проектот ја поставува зад својата табла.","advancedTitle": "Напредно"},+ "managedProfile": {+ "note": "Се управува од твојата организација.",+ "edit": "Уреди во {{provider}}"+ },"developerPage": {"pageTitle": "API клучеви","title": "API клучеви",diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 4fbef8285..e506d347e 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -641,6 +641,10 @@"projectBackgroundsDescription": "Toon de afbeelding die een project achter het bord instelt.","advancedTitle": "Geavanceerd"},+ "managedProfile": {+ "note": "Beheerd door je organisatie.",+ "edit": "Bewerken in {{provider}}"+ },"developerPage": {"pageTitle": "API-sleutels","title": "API-sleutels",diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex 53c882e24..5ccd26cdf 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -1692,6 +1692,10 @@"projectBackgroundsDescription": "Pokazuj obraz ustawiony przez projekt za jego tablicą.","advancedTitle": "Zaawansowane"},+ "managedProfile": {+ "note": "Zarządzane przez Twoją organizację.",+ "edit": "Edytuj w {{provider}}"+ },"projectGeneral": {"dangerZone": "Strefa niebezpieczna","deleteModalConfirm": "Usuń projekt",diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex 3c3e6d32f..5b936604f 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -771,6 +771,10 @@"projectBackgroundsDescription": "Mostrar a imagem que um projeto define atrás do quadro.","advancedTitle": "Avançado"},+ "managedProfile": {+ "note": "Gerenciado pela sua organização.",+ "edit": "Editar em {{provider}}"+ },"developerPage": {"pageTitle": "Chaves de API","title": "Chaves de API",diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex 85757527d..1907d2fbb 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -779,6 +779,10 @@"projectBackgroundsDescription": "Показывать изображение, которое проект задаёт за своей доской.","advancedTitle": "Дополнительно"},+ "managedProfile": {+ "note": "Управляется вашей организацией.",+ "edit": "Изменить в {{provider}}"+ },"developerPage": {"pageTitle": "API-ключи","title": "API-ключи",diff --git a/i18n/schema.json b/i18n/schema.jsonindex 39b444ac6..3cb03656e 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -3956,6 +3956,19 @@"projectBackgroundsDescription"]},+ "managedProfile": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "note": {+ "type": "string"+ },+ "edit": {+ "type": "string"+ }+ },+ "required": ["note", "edit"]+ },"developerPage": {"type": "object","additionalProperties": false,@@ -10027,6 +10040,7 @@"informationPage","notificationsPage","preferencesPage",+ "managedProfile","developerPage","apiKey","workspaceGeneral",diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex 35ddd7200..17e0f3035 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -763,6 +763,10 @@"projectBackgroundsDescription": "Projenin panosunun arkasına ayarladığı görseli göster.","advancedTitle": "Gelişmiş"},+ "managedProfile": {+ "note": "Kuruluşunuz tarafından yönetiliyor.",+ "edit": "{{provider}} üzerinde düzenle"+ },"developerPage": {"pageTitle": "API anahtarları","title": "API anahtarları",diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 9a7972a0f..973b4c851 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -779,6 +779,10 @@"projectBackgroundsDescription": "Показувати зображення, яке проєкт задає за своєю дошкою.","advancedTitle": "Додатково"},+ "managedProfile": {+ "note": "Керується вашою організацією.",+ "edit": "Редагувати в {{provider}}"+ },"developerPage": {"pageTitle": "API-ключі","title": "API-ключі",diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex e76b19ea8..dc5cb8236 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -755,6 +755,10 @@"projectBackgroundsDescription": "Hiển thị hình ảnh mà dự án đặt làm nền bảng.","advancedTitle": "Nâng cao"},+ "managedProfile": {+ "note": "Được quản lý bởi tổ chức của bạn.",+ "edit": "Chỉnh sửa trong {{provider}}"+ },"developerPage": {"pageTitle": "Khóa API","title": "Khóa API",diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex fc2aaeac4..a0720e337 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -755,6 +755,10 @@"projectBackgroundsDescription": "显示项目为看板设置的背景图片。","advancedTitle": "高级"},+ "managedProfile": {+ "note": "由你的组织管理。",+ "edit": "在 {{provider}} 中编辑"+ },"developerPage": {"pageTitle": "API 密钥","title": "API 密钥",diff --git a/i18n/zh-TW.json b/i18n/zh-TW.jsonindex de6adc37d..52a29df1c 100644--- a/i18n/zh-TW.json+++ b/i18n/zh-TW.json@@ -754,6 +754,10 @@"projectBackgroundsDescription": "顯示專案為看板設定的背景圖片。","advancedTitle": "進階"},+ "managedProfile": {+ "note": "由你的組織管理。",+ "edit": "在 {{provider}} 中編輯"+ },"developerPage": {"pageTitle": "API 金鑰","title": "API 金鑰",diff --git a/tests/api-integration/backchannel-logout-sign-in.test.ts b/tests/api-integration/backchannel-logout-sign-in.test.tsnew file mode 100644index 000000000..aa778fb12--- /dev/null+++ b/tests/api-integration/backchannel-logout-sign-in.test.ts@@ -0,0 +1,170 @@+import { randomUUID } from "node:crypto";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import {+ CUSTOM_OAUTH_CALLBACK_URL,+ signInWithCustomOAuth,+} from "./helpers/custom-oauth";+import { resetTestDatabase } from "./helpers/database";+import {+ enableBackchannelLogout,+ postLogoutToken,+ signLogoutToken,+} from "./helpers/logout-token";++vi.hoisted(() => {+ process.env.CUSTOM_OAUTH_CLIENT_ID = "kaneo-test";+ process.env.CUSTOM_OAUTH_CLIENT_SECRET = "kaneo-test-secret";+ process.env.CUSTOM_OAUTH_AUTHORIZATION_URL =+ "https://idp.example.com/authorize";+ process.env.CUSTOM_OAUTH_TOKEN_URL = "https://idp.example.com/token";+ process.env.CUSTOM_OAUTH_SCOPES = "openid,profile,email";+});++type App = ReturnType<typeof createApp>["app"];++function claims(sid?: string) {+ return {+ sub: "kc-user-1",+ email: "[email protected]",+ email_verified: true,+ name: "Jane Provider",+ sid,+ };+}++async function signIn(app: App, sid?: string) {+ const response = await signInWithCustomOAuth(app, claims(sid));+ expect(response.status).toBe(302);+ return response;+}++async function storedSessionIds() {+ const sessions = await db+ .select({ oidcSid: schema.sessionTable.oidcSid })+ .from(schema.sessionTable);+ return sessions.map((session) => session.oidcSid);+}++describe("API integration: back-channel logout after a sign-in", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ });++ it("stores the provider session ID of every sign-in on its session", async () => {+ const { app } = createApp();+ await signIn(app, "kc-session-1");+ await signIn(app, "kc-session-2");+ await signIn(app);++ expect((await storedSessionIds()).sort()).toEqual([+ "kc-session-1",+ "kc-session-2",+ null,+ ]);+ const accounts = await db+ .select({+ providerId: schema.accountTable.providerId,+ accountId: schema.accountTable.accountId,+ })+ .from(schema.accountTable);+ expect(accounts).toEqual([+ { providerId: "custom", accountId: "kc-user-1" },+ ]);+ });++ it("stores the provider session ID when the first sign-in links a local account", async () => {+ const [user] = await db+ .insert(schema.userTable)+ .values({+ id: `user-${randomUUID()}`,+ email: "[email protected]",+ emailVerified: true,+ name: "Jane Local",+ })+ .returning({ id: schema.userTable.id });+ if (!user) throw new Error("Failed to seed user");+ const { app } = createApp();++ const response = await signIn(app, "kc-session-1");++ expect(response.headers.get("location")).toBe(CUSTOM_OAUTH_CALLBACK_URL);+ const sessions = await db+ .select({+ userId: schema.sessionTable.userId,+ oidcSid: schema.sessionTable.oidcSid,+ })+ .from(schema.sessionTable);+ expect(sessions).toEqual([{ userId: user.id, oidcSid: "kc-session-1" }]);+ const accounts = await db+ .select({+ providerId: schema.accountTable.providerId,+ accountId: schema.accountTable.accountId,+ userId: schema.accountTable.userId,+ })+ .from(schema.accountTable);+ expect(accounts).toEqual([+ { providerId: "custom", accountId: "kc-user-1", userId: user.id },+ ]);+ });++ it("keeps the provider session ID out of session responses", async () => {+ const { app } = createApp();+ const response = await signIn(app, "kc-session-1");+ const cookie = response.headers+ .getSetCookie()+ .map((value) => value.split(";")[0])+ .join("; ");++ const session = await app.request("/api/auth/get-session", {+ headers: { cookie },+ });++ expect(session.status).toBe(200);+ const body = (await session.json()) as { session?: object } | null;+ expect(body?.session).toBeDefined();+ expect(body?.session).not.toHaveProperty("oidcSid");+ });++ it("ends only the session that started from the logged-out provider session", async () => {+ const { app } = createApp();+ await signIn(app, "kc-session-1");+ await signIn(app, "kc-session-2");+ const { issuer } = enableBackchannelLogout();++ const response = await postLogoutToken(+ app,+ signLogoutToken(issuer, { sub: "kc-user-1", sid: "kc-session-1" }),+ );++ expect(response.status).toBe(200);+ expect(await storedSessionIds()).toEqual(["kc-session-2"]);+ });++ it("refuses provider sign-ins through the social callback", async () => {+ const { app } = createApp();+ enableBackchannelLogout();++ const response = await signInWithCustomOAuth(+ app,+ claims("kc-session-1"),+ "/api/auth/callback/custom",+ );++ expect(response.status).toBe(404);+ expect(await storedSessionIds()).toEqual([]);+ });+});diff --git a/tests/api-integration/backchannel-logout.test.ts b/tests/api-integration/backchannel-logout.test.tsnew file mode 100644index 000000000..b00c70dfa--- /dev/null+++ b/tests/api-integration/backchannel-logout.test.ts@@ -0,0 +1,310 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import type { WSContext } from "hono/ws";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { addUserConnection, removeUserConnection } from "../../apps/api/src/ws";+import { resetTestDatabase } from "./helpers/database";+import {+ enableBackchannelLogout,+ postLogoutToken,+ signLogoutToken,+} from "./helpers/logout-token";++async function seedUser(accountId?: string, providerId = "custom") {+ const [user] = await db+ .insert(schema.userTable)+ .values({+ id: `user-${randomUUID()}`,+ email: `${randomUUID()}@example.com`,+ emailVerified: true,+ name: "Provider User",+ })+ .returning();+ if (!user) throw new Error("Failed to seed user");+ if (accountId) {+ await db.insert(schema.accountTable).values({+ accountId,+ providerId,+ userId: user.id,+ });+ }+ return user;+}++async function seedSession(userId: string, oidcSid: string | null = null) {+ const id = randomUUID();+ await db.insert(schema.sessionTable).values({+ id,+ userId,+ token: randomUUID(),+ expiresAt: new Date(Date.now() + 60_000),+ oidcSid,+ });+ return id;+}++async function remainingSessionIds() {+ const sessions = await db+ .select({ id: schema.sessionTable.id })+ .from(schema.sessionTable);+ return sessions.map((session) => session.id).sort();+}++function fakeSocket() {+ return { send: vi.fn(), close: vi.fn() };+}++describe("API integration: back-channel logout", () => {+ let issuer: string;++ beforeEach(async () => {+ await resetTestDatabase();+ ({ issuer } = enableBackchannelLogout());+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ });++ it("ends only the subject's sessions with the provider session ID", async () => {+ const user = await seedUser("kc-user-1");+ const other = await seedUser("kc-user-2");+ await seedSession(user.id, "kc-session-1");+ const otherProviderSession = await seedSession(user.id, "kc-session-2");+ const withoutSid = await seedSession(user.id);+ const otherUser = await seedSession(other.id, "kc-session-1");++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "kc-user-1", sid: "kc-session-1" }),+ );++ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(await response.text()).toBe("");+ expect(await remainingSessionIds()).toEqual(+ [otherProviderSession, withoutSid, otherUser].sort(),+ );+ });++ it("ends the sessions with the provider session ID when no subject is sent", async () => {+ const user = await seedUser("kc-user-1");+ const other = await seedUser("kc-user-2");+ await seedSession(user.id, "kc-session-1");+ await seedSession(other.id, "kc-session-1");+ const kept = await seedSession(user.id, "kc-session-2");++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sid: "kc-session-1" }),+ );++ expect(response.status).toBe(200);+ expect(await remainingSessionIds()).toEqual([kept]);+ });++ it("ends every session of the subject, closes its realtime connections and keeps its API keys", async () => {+ const user = await seedUser("kc-user-1");+ const other = await seedUser("kc-user-2");+ await seedSession(user.id, "kc-session-1");+ await seedSession(user.id);+ const kept = await seedSession(other.id, "kc-session-3");+ const { key } = await auth.api.createApiKey({+ body: { userId: user.id, name: "Logout test" },+ });+ const { app } = createApp();+ const socket = fakeSocket();+ const otherSocket = fakeSocket();+ const connection = addUserConnection(+ user.id,+ socket as unknown as WSContext,+ );+ const otherConnection = addUserConnection(+ other.id,+ otherSocket as unknown as WSContext,+ );+ try {+ const response = await postLogoutToken(+ app,+ signLogoutToken(issuer, { sub: "kc-user-1" }),+ );++ expect(response.status).toBe(200);+ expect(await remainingSessionIds()).toEqual([kept]);+ expect(socket.send).toHaveBeenCalledWith(+ JSON.stringify({ type: "USER_ACCESS_REVOKED" }),+ );+ expect(socket.close).toHaveBeenCalledWith(1008, "User access revoked");+ expect(otherSocket.close).not.toHaveBeenCalled();+ expect(+ (await app.request("/api/user/me", { headers: { "x-api-key": key } }))+ .status,+ ).toBe(200);+ } finally {+ removeUserConnection(user.id, connection);+ removeUserConnection(other.id, otherConnection);+ }+ });++ it("leaves users of other providers with the same account ID signed in", async () => {+ const user = await seedUser("12345");+ const githubUser = await seedUser("12345", "github");+ await seedSession(user.id);+ const kept = await seedSession(githubUser.id);++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "12345" }),+ );++ expect(response.status).toBe(200);+ expect(await remainingSessionIds()).toEqual([kept]);+ });++ it("keeps the realtime connections while the user has another session", async () => {+ const user = await seedUser("kc-user-1");+ await seedSession(user.id, "kc-session-1");+ const kept = await seedSession(user.id, "kc-session-2");+ const socket = fakeSocket();+ const connection = addUserConnection(+ user.id,+ socket as unknown as WSContext,+ );+ try {+ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "kc-user-1", sid: "kc-session-1" }),+ );++ expect(response.status).toBe(200);+ expect(await remainingSessionIds()).toEqual([kept]);+ expect(socket.close).not.toHaveBeenCalled();+ } finally {+ removeUserConnection(user.id, connection);+ }+ });++ it("refuses a logout token the second time", async () => {+ const user = await seedUser("kc-user-1");+ await seedSession(user.id, "kc-session-1");+ const jti = randomUUID();+ const iat = Math.floor(Date.now() / 1000);+ const token = signLogoutToken(issuer, { sub: "kc-user-1", jti, iat });+ const { app } = createApp();+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});++ expect((await postLogoutToken(app, token)).status).toBe(200);+ const replay = await postLogoutToken(app, token);++ expect(replay.status).toBe(400);+ expect(warn).toHaveBeenCalledWith(+ "Rejected a back-channel logout token: the logout token was used before",+ );+ expect(replay.headers.get("cache-control")).toBe("no-store");+ expect(await replay.json()).toEqual({ error: "invalid_request" });+ const [used, ...others] = await db+ .select()+ .from(schema.verificationTable)+ .where(+ eq(+ schema.verificationTable.identifier,+ `backchannel-logout:${issuer}:${jti}`,+ ),+ );+ expect(others).toHaveLength(0);+ expect(used?.expiresAt.getTime()).toBe((iat + 660) * 1000);+ });++ it("accepts only one of two identical logout tokens sent at once", async () => {+ const user = await seedUser("kc-user-1");+ await seedSession(user.id, "kc-session-1");+ const token = signLogoutToken(issuer, {+ sub: "kc-user-1",+ sid: "kc-session-1",+ });+ const { app } = createApp();+ vi.spyOn(console, "warn").mockImplementation(() => {});++ const responses = await Promise.all([+ postLogoutToken(app, token),+ postLogoutToken(app, token),+ ]);++ expect(responses.map((response) => response.status).sort()).toEqual([+ 200, 400,+ ]);+ expect(await remainingSessionIds()).toEqual([]);+ });++ it("answers 200 for a subject without a Kaneo account", async () => {+ const user = await seedUser("kc-user-1");+ const kept = await seedSession(user.id, "kc-session-1");++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "kc-user-9", sid: "kc-session-1" }),+ );++ expect(response.status).toBe(200);+ expect(await remainingSessionIds()).toEqual([kept]);+ });++ it("answers 404 while back-channel logout is off", async () => {+ vi.stubEnv("CUSTOM_OAUTH_BACKCHANNEL_LOGOUT", "");++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "kc-user-1" }),+ );++ expect(response.status).toBe(404);+ expect(response.headers.get("cache-control")).toBe("no-store");+ });++ it("rejects a token for another client without recording it", async () => {+ const user = await seedUser("kc-user-1");+ const kept = await seedSession(user.id, "kc-session-1");+ vi.spyOn(console, "warn").mockImplementation(() => {});++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "kc-user-1", aud: "other-client" }),+ );++ expect(response.status).toBe(400);+ expect(await response.json()).toEqual({ error: "invalid_request" });+ expect(await remainingSessionIds()).toEqual([kept]);+ expect(await db.select().from(schema.verificationTable)).toHaveLength(0);+ });++ it("answers 503 while the discovery document cannot be loaded", async () => {+ const user = await seedUser("kc-user-1");+ const kept = await seedSession(user.id, "kc-session-1");+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response("down", { status: 500 })),+ );+ vi.spyOn(console, "warn").mockImplementation(() => {});++ const response = await postLogoutToken(+ createApp().app,+ signLogoutToken(issuer, { sub: "kc-user-1" }),+ );++ expect(response.status).toBe(503);+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(await response.json()).toEqual({ error: "temporarily_unavailable" });+ expect(await remainingSessionIds()).toEqual([kept]);+ });+});diff --git a/tests/api-integration/config.test.ts b/tests/api-integration/config.test.tsindex 3a880ba74..2d64f6882 100644--- a/tests/api-integration/config.test.ts+++ b/tests/api-integration/config.test.ts@@ -66,4 +66,25 @@ describe("API integration: config", () => {"Authentik",);});++ it("reports no managed profile fields and no account page by default", async () => {+ const response = await createApp().app.request("/api/config");+ expect(await response.json()).toMatchObject({+ customOAuthManagedProfileFields: [],+ customOAuthAccountUrl: null,+ });+ });++ it("reports the managed profile fields and the provider account page", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", " Locale,name ");+ vi.stubEnv(+ "CUSTOM_OAUTH_ACCOUNT_URL",+ "https://keycloak.example.com/realms/acme/account",+ );+ const response = await createApp().app.request("/api/config");+ expect(await response.json()).toMatchObject({+ customOAuthManagedProfileFields: ["name", "locale"],+ customOAuthAccountUrl: "https://keycloak.example.com/realms/acme/account",+ });+ });});diff --git a/tests/api-integration/current-user.test.ts b/tests/api-integration/current-user.test.tsindex 5c510cb44..c365cbc3c 100644--- a/tests/api-integration/current-user.test.ts+++ b/tests/api-integration/current-user.test.ts@@ -36,6 +36,7 @@ describe("GET /api/user/me", () => {email: user.email,image: user.image,role: user.role,+ managedProfileFields: [],});},);diff --git a/tests/api-integration/custom-oauth-profile-refresh.test.ts b/tests/api-integration/custom-oauth-profile-refresh.test.tsnew file mode 100644index 000000000..bd4fb3772--- /dev/null+++ b/tests/api-integration/custom-oauth-profile-refresh.test.ts@@ -0,0 +1,333 @@+import { randomUUID } from "node:crypto";+import { DrizzleQueryError, eq } from "drizzle-orm";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import db, { getDatabase, schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { buildAvatarUrl } from "../../apps/api/src/user/avatar";+import { resetTestDatabase } from "./helpers/database";+import {+ CUSTOM_OAUTH_CALLBACK_URL,+ signInWithCustomOAuth,+} from "./helpers/custom-oauth";++vi.hoisted(() => {+ process.env.CUSTOM_OAUTH_CLIENT_ID = "kaneo-test";+ process.env.CUSTOM_OAUTH_CLIENT_SECRET = "kaneo-test-secret";+ process.env.CUSTOM_OAUTH_AUTHORIZATION_URL =+ "https://idp.example.com/authorize";+ process.env.CUSTOM_OAUTH_TOKEN_URL = "https://idp.example.com/token";+});++const SUBJECT = "provider-subject-1";+const PICTURE = "https://idp.example.com/avatars/jane.png";++function claims(overrides: Record<string, unknown> = {}) {+ return {+ sub: SUBJECT,+ email: "[email protected]",+ email_verified: true,+ name: "Jane Provider",+ ...overrides,+ };+}++async function seedUser(+ overrides: Partial<typeof schema.userTable.$inferInsert> = {},+) {+ const [user] = await db+ .insert(schema.userTable)+ .values({+ id: `user-${randomUUID()}`,+ email: "[email protected]",+ emailVerified: true,+ name: "Jane Local",+ ...overrides,+ })+ .returning();+ if (!user) throw new Error("Failed to seed user");+ return user;+}++async function seedLinkedUser(+ overrides: Partial<typeof schema.userTable.$inferInsert> = {},+) {+ const user = await seedUser(overrides);+ await db.insert(schema.accountTable).values({+ accountId: SUBJECT,+ providerId: "custom",+ userId: user.id,+ });+ return user;+}++async function storeUpload(userId: string) {+ const [avatar] = await db+ .insert(schema.userAvatarTable)+ .values({+ userId,+ mimeType: "image/png",+ size: 8,+ data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ })+ .returning({ id: schema.userAvatarTable.id });+ if (!avatar) throw new Error("Failed to seed avatar");+ const image = buildAvatarUrl(avatar.id);+ await db+ .update(schema.userTable)+ .set({ image })+ .where(eq(schema.userTable.id, userId));+ return image;+}++async function loadUser(email: string) {+ const [user] = await db+ .select({+ id: schema.userTable.id,+ name: schema.userTable.name,+ email: schema.userTable.email,+ emailVerified: schema.userTable.emailVerified,+ image: schema.userTable.image,+ locale: schema.userTable.locale,+ })+ .from(schema.userTable)+ .where(eq(schema.userTable.email, email));+ return user;+}++async function signIn(overrides: Record<string, unknown> = {}) {+ const { app } = createApp();+ const response = await signInWithCustomOAuth(app, claims(overrides));+ expect(response.status).toBe(302);+ expect(response.headers.get("location")).toBe(CUSTOM_OAUTH_CALLBACK_URL);+ return { app, response };+}++describe("API integration: custom OAuth profile refresh", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ });++ describe("sign-up", () => {+ it("stores the managed picture and the supported locale", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,image,locale");++ await signIn({ picture: PICTURE, locale: "de" });++ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Provider",+ image: PICTURE,+ locale: "de-DE",+ });+ });++ it("stores no picture or locale it cannot use", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image,locale");++ await signIn({ picture: "javascript:alert(1)", locale: "sv" });++ expect(await loadUser("[email protected]")).toMatchObject({+ image: null,+ locale: null,+ });+ });++ it("keeps storing the raw claims while no field is managed", async () => {+ await signIn({ picture: PICTURE, locale: "de" });++ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Provider",+ image: PICTURE,+ locale: "de",+ });+ });+ });++ describe("returning users", () => {+ it("refreshes only the managed fields", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ await seedLinkedUser({ image: null, locale: "en-US" });++ await signIn({ picture: PICTURE, locale: "de" });++ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Provider",+ image: null,+ locale: "en-US",+ });+ });++ it("leaves the profile alone while no field is managed", async () => {+ await seedLinkedUser({ locale: "en-US" });++ await signIn({ picture: PICTURE, locale: "de" });++ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Local",+ image: null,+ locale: "en-US",+ });+ });++ it("never changes the email of a user linked with another address", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,image,locale");+ await seedLinkedUser({+ email: "[email protected]",+ emailVerified: false,+ });++ await signIn({ email: "[email protected]", picture: PICTURE });++ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Provider",+ email: "[email protected]",+ emailVerified: false,+ image: PICTURE,+ });+ expect(await loadUser("[email protected]")).toBeUndefined();+ });++ it("still marks the email verified when the provider verified it", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ await seedLinkedUser({ emailVerified: false });++ await signIn();++ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Provider",+ emailVerified: true,+ });+ });++ it("refreshes a verified local user it links on the first sign-in", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,locale");+ const user = await seedUser({ locale: "en-US" });++ await signIn({ locale: "de" });++ expect(await loadUser("[email protected]")).toMatchObject({+ id: user.id,+ name: "Jane Provider",+ locale: "de-DE",+ });+ const accounts = await db+ .select({ providerId: schema.accountTable.providerId })+ .from(schema.accountTable)+ .where(eq(schema.accountTable.userId, user.id));+ expect(accounts).toEqual([{ providerId: "custom" }]);+ });+ });++ describe("profile picture", () => {+ it("replaces an upload with the provider's picture and deletes the upload", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const user = await seedLinkedUser();+ const upload = await storeUpload(user.id);++ const { app } = await signIn({ picture: PICTURE });++ expect(await loadUser("[email protected]")).toMatchObject({+ image: PICTURE,+ });+ expect(await db.select().from(schema.userAvatarTable)).toHaveLength(0);+ expect((await app.request(upload)).status).toBe(404);+ });++ it("keeps an upload while the provider sends no picture", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const user = await seedLinkedUser();+ const upload = await storeUpload(user.id);++ await signIn();++ expect(await loadUser("[email protected]")).toMatchObject({+ image: upload,+ });+ expect(await db.select().from(schema.userAvatarTable)).toHaveLength(1);+ });++ it("clears a picture the provider no longer sends", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ await seedLinkedUser({ image: PICTURE });++ await signIn();++ expect(await loadUser("[email protected]")).toMatchObject({+ image: null,+ });+ });+ });++ it.each([undefined, "sv"])(+ "keeps the stored locale when the claim is %p",+ async (locale) => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "locale");+ await seedLinkedUser({ locale: "fr-FR" });++ await signIn({ locale });++ expect(await loadUser("[email protected]")).toMatchObject({+ locale: "fr-FR",+ });+ },+ );++ it("completes the sign-in when the refresh fails", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ await seedLinkedUser();+ const update = getDatabase().update.bind(getDatabase());+ vi.spyOn(getDatabase(), "update").mockImplementation((table) => {+ if (table === schema.userTable) {+ throw new DrizzleQueryError(+ 'update "user" set "name" = $1',+ ["Jane Provider"],+ Object.assign(new Error("Connection terminated"), {+ code: "ECONNRESET",+ }),+ );+ }+ return update(table);+ });+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});++ const { response } = await signIn();++ expect(response.headers.getSetCookie().join("; ")).toContain(+ "session_token=",+ );+ expect(errors).toHaveBeenCalledWith("Managed profile refresh failed:", {+ error: "Error",+ code: "ECONNRESET",+ });+ expect(JSON.stringify(errors.mock.calls)).not.toContain("Jane Provider");+ expect(await loadUser("[email protected]")).toMatchObject({+ name: "Jane Local",+ });+ });++ it("refuses provider sign-ins through the social callback", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();++ const response = await signInWithCustomOAuth(+ app,+ claims(),+ "/api/auth/callback/custom",+ );++ expect(response.status).toBe(404);+ expect(await loadUser("[email protected]")).toBeUndefined();+ expect(await db.select().from(schema.sessionTable)).toHaveLength(0);+ });+});diff --git a/tests/api-integration/helpers/custom-oauth.ts b/tests/api-integration/helpers/custom-oauth.tsnew file mode 100644index 000000000..496dfb442--- /dev/null+++ b/tests/api-integration/helpers/custom-oauth.ts@@ -0,0 +1,72 @@+import { expect, vi } from "vite-plus/test";+import type { createApp } from "../../../apps/api/src/index";++type App = ReturnType<typeof createApp>["app"];++export const CUSTOM_OAUTH_CALLBACK_URL = "http://localhost:5173/dashboard";++function encodeSegment(value: unknown) {+ return Buffer.from(JSON.stringify(value)).toString("base64url");+}++// Better Auth decodes the id_token from the token response without checking its signature.+function unsignedIdToken(claims: Record<string, unknown>) {+ return `${encodeSegment({ alg: "none", typ: "JWT" })}.${encodeSegment(claims)}.signature`;+}++function readCookies(response: Response) {+ return response.headers+ .getSetCookie()+ .map((cookie) => cookie.split(";")[0] ?? "")+ .filter((pair) => {+ const [name, ...value] = pair.split("=");+ return Boolean(name) && value.join("=") !== "";+ })+ .join("; ");+}++function requestUrl(input: RequestInfo | URL) {+ if (input instanceof Request) return input.url;+ return input instanceof URL ? input.href : input;+}++export async function signInWithCustomOAuth(+ app: App,+ claims: Record<string, unknown>,+ callbackPath = "/api/auth/oauth2/callback/custom",+) {+ const start = await app.request("/api/auth/sign-in/oauth2", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ Origin: "http://localhost:5173",+ },+ body: JSON.stringify({+ providerId: "custom",+ callbackURL: CUSTOM_OAUTH_CALLBACK_URL,+ }),+ });+ expect(start.status).toBe(200);+ const { url } = (await start.json()) as { url: string };+ const state = new URL(url).searchParams.get("state");+ expect(state).toBeTruthy();++ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const target = requestUrl(input);+ if (target !== process.env.CUSTOM_OAUTH_TOKEN_URL) {+ throw new Error(`Unexpected request to ${target}`);+ }+ return Response.json({+ access_token: "access-token",+ token_type: "Bearer",+ expires_in: 300,+ id_token: unsignedIdToken(claims),+ });+ });+ vi.stubGlobal("fetch", fetchMock);++ return app.request(+ `${callbackPath}?code=test-code&state=${encodeURIComponent(state ?? "")}`,+ { headers: { cookie: readCookies(start) } },+ );+}diff --git a/tests/api-integration/helpers/logout-token.ts b/tests/api-integration/helpers/logout-token.tsnew file mode 100644index 000000000..4afce6449--- /dev/null+++ b/tests/api-integration/helpers/logout-token.ts@@ -0,0 +1,77 @@+import { generateKeyPairSync, randomUUID, sign } from "node:crypto";+import { vi } from "vite-plus/test";+import { BACKCHANNEL_LOGOUT_EVENT } from "../../../apps/api/src/backchannel-logout/verify-logout-token";+import type { createApp } from "../../../apps/api/src/index";++type App = ReturnType<typeof createApp>["app"];++export const LOGOUT_CLIENT_ID = "kaneo-test";++const { privateKey, publicKey } = generateKeyPairSync("rsa", {+ modulusLength: 2048,+});+const signingKey = {+ ...publicKey.export({ format: "jwk" }),+ kid: "test-key",+ use: "sig",+};++function encodeSegment(value: unknown) {+ return Buffer.from(JSON.stringify(value)).toString("base64url");+}++function requestUrl(input: RequestInfo | URL) {+ if (input instanceof Request) return input.url;+ return input instanceof URL ? input.href : input;+}++export function enableBackchannelLogout() {+ const issuer = `https://idp.example.com/realms/${randomUUID()}`;+ const discoveryUrl = `${issuer}/.well-known/openid-configuration`;+ const jwksUri = `${issuer}/protocol/openid-connect/certs`;+ vi.stubEnv("CUSTOM_OAUTH_BACKCHANNEL_LOGOUT", "true");+ vi.stubEnv("CUSTOM_OAUTH_DISCOVERY_URL", discoveryUrl);+ vi.stubEnv("CUSTOM_OAUTH_CLIENT_ID", LOGOUT_CLIENT_ID);++ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const target = requestUrl(input);+ if (target === discoveryUrl) {+ return Response.json({+ issuer,+ jwks_uri: jwksUri,+ id_token_signing_alg_values_supported: ["RS256", "HS256"],+ });+ }+ if (target === jwksUri) return Response.json({ keys: [signingKey] });+ return new Response("Not found", { status: 404 });+ });+ vi.stubGlobal("fetch", fetchMock);+ return { issuer, discoveryUrl, fetchMock };+}++export function signLogoutToken(+ issuer: string,+ claims: Record<string, unknown> = {},+) {+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: "RS256", typ: "logout+jwt", kid: "test-key" };+ const payload = {+ iss: issuer,+ aud: LOGOUT_CLIENT_ID,+ iat: now,+ exp: now + 120,+ jti: randomUUID(),+ events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },+ ...claims,+ };+ const input = `${encodeSegment(header)}.${encodeSegment(payload)}`;+ return `${input}.${sign("sha256", Buffer.from(input), privateKey).toString("base64url")}`;+}++export function postLogoutToken(app: App, logoutToken: string) {+ return app.request("/api/auth/oauth2/backchannel-logout/custom", {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ logout_token: logoutToken }).toString(),+ });+}diff --git a/tests/api-integration/managed-profile-edits.test.ts b/tests/api-integration/managed-profile-edits.test.tsnew file mode 100644index 000000000..09e9f2299--- /dev/null+++ b/tests/api-integration/managed-profile-edits.test.ts@@ -0,0 +1,489 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { buildAvatarUrl } from "../../apps/api/src/user/avatar";+import { signUpWithSession } from "./helpers/auth-session";+import { resetTestDatabase } from "./helpers/database";+import { readErrorBody } from "./helpers/error-body";+import { createWorkspaceMember } from "./helpers/fixtures";++type App = ReturnType<typeof createApp>["app"];++const PICTURE = "https://id.example.com/jane.png";+const PNG = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00,+]).toString("base64");++async function linkCustomAccount(userId: string) {+ await db.insert(schema.accountTable).values({+ accountId: `sub-${randomUUID()}`,+ providerId: "custom",+ userId,+ });+}++async function signUpProviderUser(app: App) {+ const session = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Jane Doe",+ });+ await linkCustomAccount(session.userId);+ return session;+}++async function setImage(userId: string, image: string | null) {+ await db+ .update(schema.userTable)+ .set({ image })+ .where(eq(schema.userTable.id, userId));+}++async function storeUpload(userId: string) {+ const [avatar] = await db+ .insert(schema.userAvatarTable)+ .values({+ userId,+ mimeType: "image/png",+ size: 9,+ data: Buffer.from(PNG, "base64"),+ })+ .returning({ id: schema.userAvatarTable.id });+ if (!avatar) throw new Error("Failed to seed avatar");+ const image = buildAvatarUrl(avatar.id);+ await setImage(userId, image);+ return image;+}++async function loadProfile(userId: string) {+ const [user] = await db+ .select({+ name: schema.userTable.name,+ email: schema.userTable.email,+ emailVerified: schema.userTable.emailVerified,+ image: schema.userTable.image,+ locale: schema.userTable.locale,+ })+ .from(schema.userTable)+ .where(eq(schema.userTable.id, userId));+ return user;+}++function listAvatars() {+ return db+ .select({ id: schema.userAvatarTable.id })+ .from(schema.userAvatarTable);+}++function updateUser(+ app: App,+ headers: Record<string, string>,+ data: Record<string, unknown>,+) {+ return app.request("/api/auth/update-user", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify(data),+ });+}++function adminUpdateUser(+ app: App,+ cookies: string,+ userId: string,+ data: Record<string, unknown>,+) {+ return app.request("/api/auth/admin/update-user", {+ method: "POST",+ headers: { "content-type": "application/json", cookie: cookies },+ body: JSON.stringify({ userId, data }),+ });+}++function uploadAvatar(app: App, cookies: string) {+ return app.request("/api/user/avatar", {+ method: "PUT",+ headers: { "content-type": "application/json", cookie: cookies },+ body: JSON.stringify({ contentType: "image/png", data: PNG }),+ });+}++function removeAvatar(app: App, cookies: string) {+ return app.request("/api/user/avatar", {+ method: "DELETE",+ headers: { cookie: cookies },+ });+}++async function expectManagedRefusal(response: Response) {+ expect(response.status).toBe(403);+ expect(await readErrorBody(response)).toMatchObject({+ code: "PROFILE_FIELD_MANAGED_BY_PROVIDER",+ });+}++describe("API integration: profile fields managed by the custom provider", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ describe("POST /api/auth/update-user", () => {+ it.each([+ ["name", { name: "Janet Doe" }],+ ["locale", { locale: "fr-FR" }],+ ["image", { image: PICTURE }],+ ])("refuses a new %s and keeps the stored profile", async (field, data) => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", field);+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ const before = await loadProfile(userId);++ await expectManagedRefusal(+ await updateUser(app, { cookie: cookies }, data),+ );+ expect(await loadProfile(userId)).toEqual(before);+ });++ it("accepts the current managed values sent again", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,image,locale");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ await setImage(userId, PICTURE);++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Jane Doe", image: PICTURE, locale: null },+ );++ expect(response.status).toBe(200);+ });++ it("accepts changes to fields the provider does not manage", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Jane Doe", locale: "de-DE", image: PICTURE },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({+ name: "Jane Doe",+ locale: "de-DE",+ image: PICTURE,+ });+ });++ it("keeps profiles editable while no field is managed", async () => {+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Janet Doe" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({ name: "Janet Doe" });+ });++ it("keeps profiles editable for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,image,locale");+ const { app } = createApp();+ const { userId, cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Renamed Person", image: PICTURE, locale: "de-DE" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({+ name: "Renamed Person",+ image: PICTURE,+ locale: "de-DE",+ });+ });++ it.each(["x-api-key", "Authorization"])(+ "refuses a managed change sent with an API key in %s",+ async (header) => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();+ const { userId } = await signUpProviderUser(app);+ const { key } = await auth.api.createApiKey({+ body: { userId, name: "Managed profile test" },+ });++ await expectManagedRefusal(+ await updateUser(+ app,+ { [header]: header === "Authorization" ? `Bearer ${key}` : key },+ { name: "Janet Doe" },+ ),+ );+ expect(await loadProfile(userId)).toMatchObject({ name: "Jane Doe" });+ },+ );++ it("refuses a managed change sent with a session bearer token", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();+ const signUp = await app.request("/api/auth/sign-up/email", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ email: "[email protected]",+ password: "correct horse battery staple",+ name: "Jane Doe",+ }),+ });+ expect(signUp.status).toBe(200);+ const { token, user } = (await signUp.json()) as {+ token: string;+ user: { id: string };+ };+ await linkCustomAccount(user.id);++ await expectManagedRefusal(+ await updateUser(+ app,+ { Authorization: `Bearer ${token}` },+ { name: "Janet Doe" },+ ),+ );+ expect(await loadProfile(user.id)).toMatchObject({ name: "Jane Doe" });+ });+ });++ describe("POST /api/auth/admin/update-user", () => {+ async function setUp(managedFields = "name") {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", managedFields);+ const { app } = createApp();+ const admin = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Instance Admin",+ role: "admin",+ });+ const target = await createWorkspaceMember({ role: "member" });+ return { app, admin, target };+ }++ it.each([+ ["name", { name: "Renamed Member" }],+ ["image", { image: PICTURE }],+ ["locale", { locale: "fr-FR" }],+ ])("refuses a new %s for a provider user", async (field, data) => {+ const { app, admin, target } = await setUp(field);+ await linkCustomAccount(target.user.id);+ const before = await loadProfile(target.user.id);++ await expectManagedRefusal(+ await adminUpdateUser(app, admin.cookies, target.user.id, data),+ );+ expect(await loadProfile(target.user.id)).toEqual(before);+ });++ it("changes the email of a provider user when the managed name stays", async () => {+ const { app, admin, target } = await setUp();+ await linkCustomAccount(target.user.id);++ const response = await adminUpdateUser(+ app,+ admin.cookies,+ target.user.id,+ { name: target.user.name, email: "[email protected]" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(target.user.id)).toMatchObject({+ name: target.user.name,+ email: "[email protected]",+ emailVerified: false,+ });+ });++ it("renames people without a provider account", async () => {+ const { app, admin, target } = await setUp();++ const response = await adminUpdateUser(+ app,+ admin.cookies,+ target.user.id,+ { name: "Renamed Member" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(target.user.id)).toMatchObject({+ name: "Renamed Member",+ });+ });+ });++ describe("profile picture", () => {+ it("refuses an upload while the provider manages the picture", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { cookies } = await signUpProviderUser(app);++ await expectManagedRefusal(await uploadAvatar(app, cookies));+ expect(await listAvatars()).toHaveLength(0);+ });++ it("refuses removing the picture the provider sent", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ await setImage(userId, PICTURE);++ await expectManagedRefusal(+ await updateUser(app, { cookie: cookies }, { image: null }),+ );+ await expectManagedRefusal(await removeAvatar(app, cookies));+ expect(await loadProfile(userId)).toMatchObject({ image: PICTURE });+ });++ it("still removes a picture uploaded to Kaneo before", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ const upload = await storeUpload(userId);++ expect(+ (await updateUser(app, { cookie: cookies }, { image: null })).status,+ ).toBe(200);+ expect((await removeAvatar(app, cookies)).status).toBe(200);++ expect(await loadProfile(userId)).toMatchObject({ image: null });+ expect(await listAvatars()).toHaveLength(0);+ expect((await app.request(upload)).status).toBe(404);+ });++ it("also removes an upload when the file is deleted before the picture is cleared", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ await storeUpload(userId);++ expect((await removeAvatar(app, cookies)).status).toBe(200);+ expect(+ (await updateUser(app, { cookie: cookies }, { image: null })).status,+ ).toBe(200);++ expect(await loadProfile(userId)).toMatchObject({ image: null });+ expect(await listAvatars()).toHaveLength(0);+ });++ it("refuses replacing an upload with another one", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ const upload = await storeUpload(userId);++ await expectManagedRefusal(await uploadAvatar(app, cookies));+ await expectManagedRefusal(+ await updateUser(+ app,+ { cookie: cookies },+ { image: buildAvatarUrl("another-avatar") },+ ),+ );+ expect(await loadProfile(userId)).toMatchObject({ image: upload });+ });++ it("keeps uploads open for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });++ const response = await uploadAvatar(app, cookies);++ expect(response.status).toBe(200);+ expect(await listAvatars()).toHaveLength(1);+ });++ it("keeps removal open for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });+ await storeUpload(userId);+ await setImage(userId, PICTURE);++ expect((await removeAvatar(app, cookies)).status).toBe(200);+ expect(await listAvatars()).toHaveLength(0);+ expect(+ (await updateUser(app, { cookie: cookies }, { image: null })).status,+ ).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({ image: null });+ });++ it("keeps uploads open while the picture is not managed", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,locale");+ const { app } = createApp();+ const { cookies } = await signUpProviderUser(app);++ expect((await uploadAvatar(app, cookies)).status).toBe(200);+ expect((await removeAvatar(app, cookies)).status).toBe(200);+ });+ });++ describe("GET /api/user/me", () => {+ async function readManagedFields(app: App, cookies: string) {+ const response = await app.request("/api/user/me", {+ headers: { cookie: cookies },+ });+ expect(response.status).toBe(200);+ const body = (await response.json()) as {+ managedProfileFields: string[];+ };+ return body.managedProfileFields;+ }++ it("lists the managed fields for a provider user", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image,name");+ const { app } = createApp();+ const { cookies } = await signUpProviderUser(app);++ expect(await readManagedFields(app, cookies)).toEqual(["name", "image"]);+ });++ it("lists nothing for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image,name");+ const { app } = createApp();+ const { cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });++ expect(await readManagedFields(app, cookies)).toEqual([]);+ });+ });+});diff --git a/tests/api-integration/setup.ts b/tests/api-integration/setup.tsindex d61803df1..0242525dc 100644--- a/tests/api-integration/setup.ts+++ b/tests/api-integration/setup.ts@@ -96,8 +96,11 @@ process.env.CUSTOM_OAUTH_USER_INFO_URL = "";process.env.CUSTOM_OAUTH_SCOPES = "";process.env.CUSTOM_OAUTH_RESPONSE_TYPE = "";process.env.CUSTOM_OAUTH_DISCOVERY_URL = "";+process.env.CUSTOM_OAUTH_BACKCHANNEL_LOGOUT = "";process.env.CUSTOM_OAUTH_AUTO_LOGIN = "";process.env.CUSTOM_OAUTH_NAME = "";+process.env.CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS = "";+process.env.CUSTOM_OAUTH_ACCOUNT_URL = "";process.env.DEVICE_AUTH_CLIENT_IDS = "kaneo-cli";afterEach(() => {diff --git a/tests/api/backchannel-logout/config.test.ts b/tests/api/backchannel-logout/config.test.tsnew file mode 100644index 000000000..a5a26c431--- /dev/null+++ b/tests/api/backchannel-logout/config.test.ts@@ -0,0 +1,102 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import {+ assertBackchannelLogoutEnv,+ resolveBackchannelLogoutConfig,+} from "../../../apps/api/src/backchannel-logout/config";++const DISCOVERY_URL =+ "https://idp.example.com/realms/kaneo/.well-known/openid-configuration";+const ENABLED = {+ CUSTOM_OAUTH_BACKCHANNEL_LOGOUT: "true",+ CUSTOM_OAUTH_DISCOVERY_URL: DISCOVERY_URL,+ CUSTOM_OAUTH_CLIENT_ID: "kaneo",+};++afterEach(() => {+ vi.restoreAllMocks();+});++describe("back-channel logout configuration", () => {+ it.each([undefined, "", "false", "TRUE", "1"])(+ "stays off for %p without checking the provider settings",+ (value) => {+ expect(+ resolveBackchannelLogoutConfig({+ CUSTOM_OAUTH_BACKCHANNEL_LOGOUT: value,+ }),+ ).toEqual({ enabled: false });+ },+ );++ it.each([+ undefined,+ "",+ "/realms/kaneo/.well-known/openid-configuration",+ "ftp://idp.example.com/.well-known/openid-configuration",+ ])("refuses to start without a usable discovery URL (%p)", (url) => {+ expect(() =>+ resolveBackchannelLogoutConfig({+ ...ENABLED,+ CUSTOM_OAUTH_DISCOVERY_URL: url,+ }),+ ).toThrow(/CUSTOM_OAUTH_DISCOVERY_URL/);+ });++ it.each([undefined, "", " "])(+ "refuses to start without a client ID (%p)",+ (clientId) => {+ expect(() =>+ resolveBackchannelLogoutConfig({+ ...ENABLED,+ CUSTOM_OAUTH_CLIENT_ID: clientId,+ }),+ ).toThrow(/CUSTOM_OAUTH_CLIENT_ID/);+ },+ );++ it("returns the trimmed discovery URL and client ID", () => {+ expect(+ resolveBackchannelLogoutConfig({+ ...ENABLED,+ CUSTOM_OAUTH_DISCOVERY_URL: ` ${DISCOVERY_URL} `,+ CUSTOM_OAUTH_CLIENT_ID: " kaneo ",+ }),+ ).toEqual({+ enabled: true,+ discoveryUrl: DISCOVERY_URL,+ clientId: "kaneo",+ });+ });++ it("warns at startup when sign-ins do not request the openid scope", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});++ assertBackchannelLogoutEnv(ENABLED);+ assertBackchannelLogoutEnv({+ ...ENABLED,+ CUSTOM_OAUTH_SCOPES: "profile,email",+ });+ expect(warn).toHaveBeenCalledTimes(2);++ warn.mockClear();+ assertBackchannelLogoutEnv({+ ...ENABLED,+ CUSTOM_OAUTH_SCOPES: "profile, openid ,email",+ });+ assertBackchannelLogoutEnv({+ ...ENABLED,+ CUSTOM_OAUTH_SCOPES: "openid profile email",+ });+ assertBackchannelLogoutEnv({ CUSTOM_OAUTH_SCOPES: "profile,email" });+ expect(warn).not.toHaveBeenCalled();+ });++ it("stops the startup check on invalid settings", () => {+ expect(() =>+ assertBackchannelLogoutEnv({+ ...ENABLED,+ CUSTOM_OAUTH_DISCOVERY_URL: "",+ }),+ ).toThrow(/CUSTOM_OAUTH_DISCOVERY_URL/);+ });+});diff --git a/tests/api/backchannel-logout/end-provider-sessions.test.ts b/tests/api/backchannel-logout/end-provider-sessions.test.tsnew file mode 100644index 000000000..1e00ea418--- /dev/null+++ b/tests/api/backchannel-logout/end-provider-sessions.test.ts@@ -0,0 +1,136 @@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";++const mocks = vi.hoisted(() => {+ const rows = {+ claimed: [] as Array<{ id: string }>,+ accounts: [] as Array<{ userId: string }>,+ ended: [] as Array<{ userId: string }>,+ activeSessions: [] as Array<{ id: string }>,+ };+ const deleteWhere = vi.fn(() => ({ returning: async () => rows.ended }));+ const tx = {+ insert: vi.fn(() => ({+ values: () => ({+ onConflictDoNothing: () => ({ returning: async () => rows.claimed }),+ }),+ })),+ select: vi.fn(() => ({+ from: () => ({ where: async () => rows.accounts }),+ })),+ delete: vi.fn(() => ({ where: deleteWhere })),+ };+ const db = {+ transaction: vi.fn(async (callback: (transaction: typeof tx) => unknown) =>+ callback(tx),+ ),+ select: vi.fn(() => ({+ from: () => ({+ where: () => ({ limit: async () => rows.activeSessions }),+ }),+ })),+ };+ return { rows, tx, db, deleteWhere, revokeUserConnections: vi.fn() };+});++vi.mock("../../../apps/api/src/database", async () => ({+ default: mocks.db,+ schema: await import("../../../apps/api/src/database/schema"),+}));++vi.mock("../../../apps/api/src/ws", () => ({+ revokeUserConnections: mocks.revokeUserConnections,+}));++import { endProviderSessions } from "../../../apps/api/src/backchannel-logout/controllers/end-provider-sessions";+import { LogoutTokenRejected } from "../../../apps/api/src/backchannel-logout/errors";++const TOKEN = {+ iss: "https://idp.example.com/realms/kaneo",+ jti: "logout-1",+ iat: 1_792_315_200,+};++beforeEach(() => {+ mocks.rows.claimed = [{ id: "claim" }];+ mocks.rows.accounts = [{ userId: "user-1" }];+ mocks.rows.ended = [{ userId: "user-1" }];+ mocks.rows.activeSessions = [];+});++afterEach(() => {+ vi.clearAllMocks();+ vi.restoreAllMocks();+});++describe("endProviderSessions", () => {+ it("refuses a logout without a session ID or subject before any query", async () => {+ await expect(endProviderSessions(TOKEN)).rejects.toThrow(+ "A logout needs a session ID or a subject",+ );+ expect(mocks.db.transaction).not.toHaveBeenCalled();+ });++ it("rejects a token that was used before and ends nothing", async () => {+ mocks.rows.claimed = [];++ await expect(+ endProviderSessions({ ...TOKEN, sub: "kc-user-1" }),+ ).rejects.toBeInstanceOf(LogoutTokenRejected);+ expect(mocks.tx.delete).not.toHaveBeenCalled();+ });++ it("ends nothing for a subject without a Kaneo account", async () => {+ mocks.rows.accounts = [];++ await endProviderSessions({+ ...TOKEN,+ sid: "kc-session-1",+ sub: "kc-user-9",+ });++ expect(mocks.tx.insert).toHaveBeenCalledOnce();+ expect(mocks.tx.delete).not.toHaveBeenCalled();+ expect(mocks.revokeUserConnections).not.toHaveBeenCalled();+ });++ it("ends sessions by session ID without looking up an account", async () => {+ await endProviderSessions({ ...TOKEN, sid: "kc-session-1" });++ expect(mocks.tx.select).not.toHaveBeenCalled();+ expect(mocks.deleteWhere).toHaveBeenCalledWith(expect.anything());+ });++ it("closes the realtime connections of users without a session left", async () => {+ mocks.rows.ended = [{ userId: "user-1" }, { userId: "user-1" }];++ await endProviderSessions({ ...TOKEN, sub: "kc-user-1" });++ expect(mocks.revokeUserConnections).toHaveBeenCalledOnce();+ expect(mocks.revokeUserConnections).toHaveBeenCalledWith("user-1");+ });++ it("keeps the connections of users who still have a session", async () => {+ mocks.rows.activeSessions = [{ id: "session-2" }];++ await endProviderSessions({ ...TOKEN, sid: "kc-session-1" });++ expect(mocks.revokeUserConnections).not.toHaveBeenCalled();+ });++ it("logs, but does not fail, when closing connections fails", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ mocks.revokeUserConnections.mockRejectedValueOnce(new Error("socket"));++ await expect(+ endProviderSessions({ ...TOKEN, sub: "kc-user-1" }),+ ).resolves.toBeUndefined();+ expect(error).toHaveBeenCalledOnce();+ });+});diff --git a/tests/api/backchannel-logout/provider-jwks.test.ts b/tests/api/backchannel-logout/provider-jwks.test.tsnew file mode 100644index 000000000..2d2a5dd3c--- /dev/null+++ b/tests/api/backchannel-logout/provider-jwks.test.ts@@ -0,0 +1,165 @@+import { generateKeyPairSync, randomUUID, sign } from "node:crypto";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import {+ LogoutProviderUnavailable,+ LogoutTokenRejected,+} from "../../../apps/api/src/backchannel-logout/errors";+import { providerJwks } from "../../../apps/api/src/backchannel-logout/provider-jwks";+import {+ BACKCHANNEL_LOGOUT_EVENT,+ verifyLogoutToken,+} from "../../../apps/api/src/backchannel-logout/verify-logout-token";++const ISSUER = "https://idp.example.com/realms/kaneo";+const { privateKey, publicKey } = generateKeyPairSync("rsa", {+ modulusLength: 2048,+});+const KEYS = {+ keys: [{ ...publicKey.export({ format: "jwk" }), kid: "rsa", use: "sig" }],+};++function jwksUrl() {+ return `https://idp.example.com/${randomUUID()}/certs`;+}++function serveKeys() {+ const fetchMock = vi.fn(async () => Response.json(KEYS));+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function encode(value: unknown) {+ return Buffer.from(JSON.stringify(value)).toString("base64url");+}++function tokenWithKeyId(kid: string) {+ const now = Math.floor(Date.now() / 1000);+ const input = `${encode({ alg: "RS256", typ: "logout+jwt", kid })}.${encode({+ iss: ISSUER,+ aud: "kaneo-test",+ iat: now,+ jti: randomUUID(),+ sub: "kc-user-1",+ events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },+ })}`;+ return `${input}.${sign("sha256", Buffer.from(input), privateKey).toString("base64url")}`;+}++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("providerJwks", () => {+ it("keeps one cache key per key set URL", () => {+ const url = jwksUrl();+ expect(providerJwks(url).jwksCacheKey).toBe(providerJwks(url).jwksCacheKey);+ expect(providerJwks(jwksUrl()).jwksCacheKey).not.toBe(+ providerJwks(url).jwksCacheKey,+ );+ });++ it("fetches the key set at most once every 30 seconds", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ const fetchMock = serveKeys();+ const { jwksFetch } = providerJwks(jwksUrl());++ await expect(jwksFetch()).resolves.toEqual(KEYS);+ vi.setSystemTime(Date.now() + 29_000);+ await expect(jwksFetch()).resolves.toEqual(KEYS);+ expect(fetchMock).toHaveBeenCalledOnce();++ vi.setSystemTime(Date.now() + 1_000);+ await expect(jwksFetch()).resolves.toEqual(KEYS);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("shares one fetch between concurrent calls", async () => {+ const fetchMock = serveKeys();+ const { jwksFetch } = providerJwks(jwksUrl());++ await Promise.all([jwksFetch(), jwksFetch(), jwksFetch()]);++ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it("keeps the previous key set when a later fetch fails", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ const fetchMock = vi+ .fn()+ .mockImplementationOnce(async () => Response.json(KEYS))+ .mockRejectedValue(new TypeError("fetch failed"));+ vi.stubGlobal("fetch", fetchMock);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const url = jwksUrl();+ const { jwksFetch } = providerJwks(url);++ await jwksFetch();+ vi.setSystemTime(Date.now() + 30_000);++ await expect(jwksFetch()).resolves.toEqual(KEYS);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(warn).toHaveBeenCalledWith(+ `Back-channel logout kept the previous signing keys: ${url} could not be fetched`,+ );+ });++ it("reports a missing key set as unavailable and waits before retrying", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(new TypeError("fetch failed"))+ .mockImplementation(async () => Response.json(KEYS));+ vi.stubGlobal("fetch", fetchMock);+ const { jwksFetch } = providerJwks(jwksUrl());++ await expect(jwksFetch()).rejects.toBeInstanceOf(LogoutProviderUnavailable);+ await expect(jwksFetch()).rejects.toBeInstanceOf(LogoutProviderUnavailable);+ expect(fetchMock).toHaveBeenCalledOnce();++ vi.setSystemTime(Date.now() + 30_000);+ await expect(jwksFetch()).resolves.toEqual(KEYS);+ });++ it.each([{}, { keys: "rsa" }, { keys: [1] }, [KEYS]])(+ "treats the malformed key set %j as unavailable",+ async (document) => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json(document)),+ );+ await expect(providerJwks(jwksUrl()).jwksFetch()).rejects.toBeInstanceOf(+ LogoutProviderUnavailable,+ );+ },+ );++ it("fetches once for many tokens with unknown key IDs", async () => {+ const fetchMock = serveKeys();+ const provider = {+ issuer: ISSUER,+ algorithms: ["RS256"],+ ...providerJwks(jwksUrl()),+ };++ for (let attempt = 0; attempt < 5; attempt++) {+ await expect(+ verifyLogoutToken(+ tokenWithKeyId(randomUUID()),+ "kaneo-test",+ async () => provider,+ ),+ ).rejects.toBeInstanceOf(LogoutTokenRejected);+ }+ await expect(+ verifyLogoutToken(+ tokenWithKeyId("rsa"),+ "kaneo-test",+ async () => provider,+ ),+ ).resolves.toEqual(expect.objectContaining({ sub: "kc-user-1" }));++ expect(fetchMock).toHaveBeenCalledOnce();+ });+});diff --git a/tests/api/backchannel-logout/provider-metadata.test.ts b/tests/api/backchannel-logout/provider-metadata.test.tsnew file mode 100644index 000000000..03018cbb2--- /dev/null+++ b/tests/api/backchannel-logout/provider-metadata.test.ts@@ -0,0 +1,164 @@+import { randomUUID } from "node:crypto";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { LogoutProviderUnavailable } from "../../../apps/api/src/backchannel-logout/errors";+import { MAX_PROVIDER_DOCUMENT_BYTES } from "../../../apps/api/src/backchannel-logout/fetch-provider-json";+import {+ getProviderMetadata,+ parseProviderMetadata,+} from "../../../apps/api/src/backchannel-logout/provider-metadata";+import { ASYMMETRIC_ALGORITHMS } from "../../../apps/api/src/backchannel-logout/verify-logout-token";++const ISSUER = "https://idp.example.com/realms/kaneo";+const JWKS_URI = `${ISSUER}/protocol/openid-connect/certs`;+const DOCUMENT = {+ issuer: ISSUER,+ jwks_uri: JWKS_URI,+ id_token_signing_alg_values_supported: ["RS256", "HS256", "ES256", "Ed448"],+};++function discoveryUrl() {+ return `https://idp.example.com/${randomUUID()}/.well-known/openid-configuration`;+}++function serveDocument() {+ const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) =>+ Response.json(DOCUMENT),+ );+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("parseProviderMetadata", () => {+ it("keeps the asymmetric ID token algorithms the provider offers", () => {+ expect(parseProviderMetadata(DOCUMENT)).toEqual({+ issuer: ISSUER,+ jwksUri: JWKS_URI,+ algorithms: ["RS256", "ES256"],+ });+ });++ it("allows every asymmetric algorithm when the provider lists none", () => {+ expect(+ parseProviderMetadata({ issuer: ISSUER, jwks_uri: JWKS_URI }).algorithms,+ ).toEqual(ASYMMETRIC_ALGORITHMS);+ });++ it.each([+ ["no issuer", { jwks_uri: JWKS_URI }],+ ["an empty issuer", { issuer: "", jwks_uri: JWKS_URI }],+ ["no jwks_uri", { issuer: ISSUER }],+ ["a relative jwks_uri", { issuer: ISSUER, jwks_uri: "/certs" }],+ [+ "only symmetric algorithms",+ {+ issuer: ISSUER,+ jwks_uri: JWKS_URI,+ id_token_signing_alg_values_supported: ["HS256"],+ },+ ],+ ["a list instead of an object", [ISSUER]],+ ])("treats a document with %s as unavailable", (_name, document) => {+ expect(() => parseProviderMetadata(document)).toThrow(+ LogoutProviderUnavailable,+ );+ });+});++describe("getProviderMetadata", () => {+ it("asks for JSON, refuses redirects and sets a timeout", async () => {+ const fetchMock = serveDocument();+ const url = discoveryUrl();++ await getProviderMetadata(url);++ expect(fetchMock).toHaveBeenCalledWith(+ url,+ expect.objectContaining({+ headers: { Accept: "application/json" },+ redirect: "error",+ signal: expect.any(AbortSignal),+ }),+ );+ });++ it("caches the document and shares one fetch between concurrent calls", async () => {+ const fetchMock = serveDocument();+ const url = discoveryUrl();++ const [first, second] = await Promise.all([+ getProviderMetadata(url),+ getProviderMetadata(url),+ ]);++ expect(second).toEqual(first);+ await expect(getProviderMetadata(url)).resolves.toEqual(first);+ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it.each([+ ["an error status", () => new Response("down", { status: 500 })],+ ["invalid JSON", () => new Response("not json")],+ [+ "a body over the size limit",+ () => new Response("x".repeat(MAX_PROVIDER_DOCUMENT_BYTES + 1)),+ ],+ ])("treats %s as unavailable", async (_name, respond) => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => respond()),+ );+ await expect(getProviderMetadata(discoveryUrl())).rejects.toBeInstanceOf(+ LogoutProviderUnavailable,+ );+ });++ it("waits 30 seconds before it retries a failed fetch", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(new TypeError("fetch failed"))+ .mockImplementation(async () => Response.json(DOCUMENT));+ vi.stubGlobal("fetch", fetchMock);+ const url = discoveryUrl();++ await expect(getProviderMetadata(url)).rejects.toBeInstanceOf(+ LogoutProviderUnavailable,+ );+ vi.setSystemTime(Date.now() + 29_000);+ await expect(getProviderMetadata(url)).rejects.toBeInstanceOf(+ LogoutProviderUnavailable,+ );+ expect(fetchMock).toHaveBeenCalledOnce();++ vi.setSystemTime(Date.now() + 1_000);+ await expect(getProviderMetadata(url)).resolves.toEqual(+ expect.objectContaining({ issuer: ISSUER }),+ );+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("refreshes after an hour and keeps the cached document if that fails", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ const fetchMock = vi+ .fn()+ .mockImplementationOnce(async () => Response.json(DOCUMENT))+ .mockRejectedValue(new TypeError("fetch failed"));+ vi.stubGlobal("fetch", fetchMock);+ const url = discoveryUrl();+ const cached = await getProviderMetadata(url);++ vi.setSystemTime(Date.now() + 59 * 60 * 1000);+ await expect(getProviderMetadata(url)).resolves.toEqual(cached);+ expect(fetchMock).toHaveBeenCalledOnce();++ vi.setSystemTime(Date.now() + 60 * 1000);+ await expect(getProviderMetadata(url)).resolves.toEqual(cached);+ await expect(getProviderMetadata(url)).resolves.toEqual(cached);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});diff --git a/tests/api/backchannel-logout/route.test.ts b/tests/api/backchannel-logout/route.test.tsnew file mode 100644index 000000000..45cfd8f07--- /dev/null+++ b/tests/api/backchannel-logout/route.test.ts@@ -0,0 +1,238 @@+import { Hono } from "hono";+import { HTTPException } from "hono/http-exception";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";++const mocks = vi.hoisted(() => ({+ verifyLogoutToken: vi.fn(),+ endProviderSessions: vi.fn(),+ getProviderMetadata: vi.fn(),+}));++vi.mock(+ "../../../apps/api/src/backchannel-logout/verify-logout-token",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ verifyLogoutToken: mocks.verifyLogoutToken,+ }),+);++vi.mock(+ "../../../apps/api/src/backchannel-logout/controllers/end-provider-sessions",+ () => ({ endProviderSessions: mocks.endProviderSessions }),+);++vi.mock("../../../apps/api/src/backchannel-logout/provider-metadata", () => ({+ getProviderMetadata: mocks.getProviderMetadata,+}));++import {+ handleBackchannelLogoutRoute,+ MAX_LOGOUT_REQUEST_BYTES,+ noStore,+} from "../../../apps/api/src/backchannel-logout";+import {+ LogoutProviderUnavailable,+ LogoutTokenRejected,+} from "../../../apps/api/src/backchannel-logout/errors";+import { httpExceptionResponse } from "../../../apps/api/src/errors/http-exception-response";+import { boundedRequestBody } from "../../../apps/api/src/utils/bounded-request-body";++const DISCOVERY_URL =+ "https://idp.example.com/realms/kaneo/.well-known/openid-configuration";+const TOKEN = "eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiJsb2dvdXQtMSJ9.c2lnbmF0dXJl";+const CLAIMS = {+ iss: "https://idp.example.com/realms/kaneo",+ jti: "logout-1",+ iat: 1_792_315_200,+ sid: "kc-session-1",+ sub: "kc-user-1",+};++const app = new Hono();+app.onError((error) =>+ httpExceptionResponse(+ error instanceof HTTPException+ ? error+ : new HTTPException(500, { message: "Internal Server Error" }),+ ),+);+app.post(+ "/logout",+ noStore,+ boundedRequestBody(MAX_LOGOUT_REQUEST_BYTES),+ handleBackchannelLogoutRoute,+);++function postForm(+ body: string | URLSearchParams,+ contentType = "application/x-www-form-urlencoded",+) {+ return app.request("/logout", {+ method: "POST",+ headers: { "content-type": contentType },+ body,+ });+}++function postToken(token = TOKEN) {+ return postForm(new URLSearchParams({ logout_token: token }));+}++async function expectAnswer(+ response: Response,+ status: number,+ body?: unknown,+) {+ expect(response.status).toBe(status);+ expect(response.headers.get("cache-control")).toBe("no-store");+ if (body !== undefined) expect(await response.json()).toEqual(body);+}++beforeEach(() => {+ vi.stubEnv("CUSTOM_OAUTH_BACKCHANNEL_LOGOUT", "true");+ vi.stubEnv("CUSTOM_OAUTH_DISCOVERY_URL", DISCOVERY_URL);+ vi.stubEnv("CUSTOM_OAUTH_CLIENT_ID", "kaneo-test");+ mocks.verifyLogoutToken.mockResolvedValue(CLAIMS);+ mocks.endProviderSessions.mockResolvedValue(undefined);+});++afterEach(() => {+ vi.unstubAllEnvs();+ vi.resetAllMocks();+ vi.restoreAllMocks();+});++describe("back-channel logout route", () => {+ it("ends the provider sessions of a valid logout token", async () => {+ const response = await postToken();++ await expectAnswer(response, 200);+ expect(await response.text()).toBe("");+ expect(mocks.verifyLogoutToken).toHaveBeenCalledWith(+ TOKEN,+ "kaneo-test",+ expect.any(Function),+ );+ expect(mocks.endProviderSessions).toHaveBeenCalledWith(CLAIMS);+ });++ it("loads the issuer, algorithms and keys from the discovery document", async () => {+ mocks.getProviderMetadata.mockResolvedValue({+ issuer: CLAIMS.iss,+ jwksUri: `${CLAIMS.iss}/protocol/openid-connect/certs`,+ algorithms: ["RS256"],+ });+ await postToken();++ const loadProvider = mocks.verifyLogoutToken.mock.calls[0]?.[2] as+ | (() => Promise<unknown>)+ | undefined;+ await expect(loadProvider?.()).resolves.toEqual({+ issuer: CLAIMS.iss,+ algorithms: ["RS256"],+ jwksCacheKey: expect.any(Object),+ jwksFetch: expect.any(Function),+ });+ expect(mocks.getProviderMetadata).toHaveBeenCalledWith(DISCOVERY_URL);+ });++ it("accepts a form content type with a charset", async () => {+ await expectAnswer(+ await postForm(+ new URLSearchParams({ logout_token: TOKEN }).toString(),+ "application/x-www-form-urlencoded; charset=UTF-8",+ ),+ 200,+ );+ });++ it.each(["", "false"])(+ "answers 404 while back-channel logout is %p",+ async (value) => {+ vi.stubEnv("CUSTOM_OAUTH_BACKCHANNEL_LOGOUT", value);++ await expectAnswer(await postToken(), 404);+ expect(mocks.verifyLogoutToken).not.toHaveBeenCalled();+ },+ );++ it.each([+ [+ "a JSON body",+ JSON.stringify({ logout_token: TOKEN }),+ "application/json",+ ],+ ["no logout_token", "state=1", undefined],+ ["an empty logout_token", "logout_token=", undefined],+ [+ "two logout tokens",+ `logout_token=${TOKEN}&logout_token=${TOKEN}`,+ undefined,+ ],+ ["a logout_token that is no JWS", "logout_token=a.b", undefined],+ ])("rejects %s", async (_name, body, contentType) => {+ await expectAnswer(await postForm(body, contentType), 400, {+ error: "invalid_request",+ });+ expect(mocks.verifyLogoutToken).not.toHaveBeenCalled();+ });++ it("refuses a body over 16 KiB", async () => {+ await expectAnswer(+ await postForm(`logout_token=${"a".repeat(MAX_LOGOUT_REQUEST_BYTES)}`),+ 413,+ );+ expect(mocks.verifyLogoutToken).not.toHaveBeenCalled();+ });++ it("answers 503 while the provider's keys cannot be loaded", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ mocks.verifyLogoutToken.mockRejectedValue(+ new LogoutProviderUnavailable(+ "https://idp.example.com could not be reached",+ ),+ );++ await expectAnswer(await postToken(), 503, {+ error: "temporarily_unavailable",+ });+ expect(mocks.endProviderSessions).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalledOnce();+ });++ it("rejects a token the verifier refuses without logging it", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ mocks.verifyLogoutToken.mockRejectedValue(+ new LogoutTokenRejected("signature verification failed"),+ );++ await expectAnswer(await postToken(), 400, { error: "invalid_request" });+ expect(mocks.endProviderSessions).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalledWith(+ "Rejected a back-channel logout token: signature verification failed",+ );+ expect(JSON.stringify(warn.mock.calls)).not.toContain(TOKEN);+ });++ it("rejects a token that was used before", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ mocks.endProviderSessions.mockRejectedValue(+ new LogoutTokenRejected("the logout token was used before"),+ );++ await expectAnswer(await postToken(), 400, { error: "invalid_request" });+ });++ it("answers 500 when ending the sessions fails", async () => {+ mocks.endProviderSessions.mockRejectedValue(new Error("database down"));++ await expectAnswer(await postToken(), 500);+ });+});diff --git a/tests/api/backchannel-logout/sign-in-session-id.test.ts b/tests/api/backchannel-logout/sign-in-session-id.test.tsnew file mode 100644index 000000000..6cfbb5b45--- /dev/null+++ b/tests/api/backchannel-logout/sign-in-session-id.test.ts@@ -0,0 +1,80 @@+import type { GenericEndpointContext } from "better-auth";+import { describe, expect, it } from "vite-plus/test";+import {+ rememberSignInSessionId,+ takeSignInSessionId,+} from "../../../apps/api/src/backchannel-logout/sign-in-session-id";++const CALLBACK_PATH = "/oauth2/callback/:providerId";++function endpointContext(+ context: object = {},+ path = CALLBACK_PATH,+ providerId = "custom",+) {+ return {+ path,+ params: { providerId },+ context,+ } as unknown as GenericEndpointContext;+}++function idToken(claims: Record<string, unknown>) {+ const encode = (value: unknown) =>+ Buffer.from(JSON.stringify(value)).toString("base64url");+ return `${encode({ alg: "RS256", typ: "JWT" })}.${encode(claims)}.signature`;+}++describe("sign-in session ID", () => {+ it("hands the ID token's sid of a custom provider callback over once", () => {+ const ctx = endpointContext();+ rememberSignInSessionId(idToken({ sid: "kc-session-1" }), ctx);++ expect(takeSignInSessionId(ctx)).toBe("kc-session-1");+ expect(takeSignInSessionId(ctx)).toBeUndefined();+ });++ it("keeps the sids of concurrent callbacks apart", () => {+ const first = endpointContext();+ const second = endpointContext();+ rememberSignInSessionId(idToken({ sid: "kc-session-1" }), first);+ rememberSignInSessionId(idToken({ sid: "kc-session-2" }), second);++ expect(takeSignInSessionId(second)).toBe("kc-session-2");+ expect(takeSignInSessionId(first)).toBe("kc-session-1");+ });++ it.each([+ ["another provider", CALLBACK_PATH, "github"],+ ["a social provider callback", "/callback/:id", "custom"],+ ["an email sign-in", "/sign-in/email", "custom"],+ ])("ignores %s", (_name, path, providerId) => {+ const context = {};+ const other = endpointContext(context, path, providerId);+ const callback = endpointContext(context);++ rememberSignInSessionId(idToken({ sid: "kc-session-1" }), other);+ expect(takeSignInSessionId(callback)).toBeUndefined();++ rememberSignInSessionId(idToken({ sid: "kc-session-2" }), callback);+ expect(takeSignInSessionId(other)).toBeUndefined();+ expect(takeSignInSessionId(callback)).toBe("kc-session-2");+ });++ it("ignores hooks that run outside an endpoint", () => {+ rememberSignInSessionId(idToken({ sid: "kc-session-1" }), null);+ expect(takeSignInSessionId(null)).toBeUndefined();+ });++ it.each([+ ["no ID token", undefined],+ ["a malformed ID token", "not-a-jwt"],+ ["an ID token without sid", idToken({ sub: "kc-user-1" })],+ ["an empty sid", idToken({ sid: "" })],+ ["a numeric sid", idToken({ sid: 7 })],+ ])("stores nothing for %s", (_name, token) => {+ const ctx = endpointContext();+ rememberSignInSessionId(token, ctx);+ expect(takeSignInSessionId(ctx)).toBeUndefined();+ });+});diff --git a/tests/api/backchannel-logout/verify-logout-token.test.ts b/tests/api/backchannel-logout/verify-logout-token.test.tsnew file mode 100644index 000000000..48aaea283--- /dev/null+++ b/tests/api/backchannel-logout/verify-logout-token.test.ts@@ -0,0 +1,292 @@+import {+ constants,+ generateKeyPairSync,+ type KeyObject,+ randomUUID,+ sign,+} from "node:crypto";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import {+ LogoutProviderUnavailable,+ LogoutTokenRejected,+} from "../../../apps/api/src/backchannel-logout/errors";+import {+ ASYMMETRIC_ALGORITHMS,+ BACKCHANNEL_LOGOUT_EVENT,+ type LogoutTokenProvider,+ verifyLogoutToken,+} from "../../../apps/api/src/backchannel-logout/verify-logout-token";++const ISSUER = "https://idp.example.com/realms/kaneo";+const CLIENT_ID = "kaneo-test";+const NOW = Math.floor(Date.parse("2026-10-18T12:00:00Z") / 1000);++const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 });+const otherRsa = generateKeyPairSync("rsa", { modulusLength: 2048 });+const ec = generateKeyPairSync("ec", { namedCurve: "P-256" });+const ed = generateKeyPairSync("ed25519");++const JWKS = {+ keys: [+ { ...rsa.publicKey.export({ format: "jwk" }), kid: "rsa", use: "sig" },+ { ...ec.publicKey.export({ format: "jwk" }), kid: "ec", use: "sig" },+ { ...ed.publicKey.export({ format: "jwk" }), kid: "ed", use: "sig" },+ ],+};++const signers: Record<+ string,+ { kid: string; sign: (data: Buffer, key?: KeyObject) => Buffer }+> = {+ RS256: {+ kid: "rsa",+ sign: (data, key = rsa.privateKey) => sign("sha256", data, key),+ },+ PS256: {+ kid: "rsa",+ sign: (data) =>+ sign("sha256", data, {+ key: rsa.privateKey,+ padding: constants.RSA_PKCS1_PSS_PADDING,+ saltLength: 32,+ }),+ },+ ES256: {+ kid: "ec",+ sign: (data) =>+ sign("sha256", data, { key: ec.privateKey, dsaEncoding: "ieee-p1363" }),+ },+ EdDSA: { kid: "ed", sign: (data) => sign(null, data, ed.privateKey) },+};++function encode(value: unknown) {+ return Buffer.from(JSON.stringify(value)).toString("base64url");+}++function logoutClaims(overrides: Record<string, unknown> = {}) {+ return {+ iss: ISSUER,+ aud: CLIENT_ID,+ iat: NOW,+ exp: NOW + 120,+ jti: "logout-1",+ sub: "kc-user-1",+ sid: "kc-session-1",+ events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },+ ...overrides,+ };+}++function signToken(+ claims: unknown = logoutClaims(),+ header: Record<string, unknown> = {},+ key?: KeyObject,+) {+ const alg = typeof header.alg === "string" ? header.alg : "RS256";+ const signer = signers[alg] ?? signers.RS256;+ if (!signer) throw new Error("Missing RS256 signer");+ const input = `${encode({ alg, typ: "logout+jwt", kid: signer.kid, ...header })}.${encode(claims)}`;+ return `${input}.${signer.sign(Buffer.from(input), key).toString("base64url")}`;+}++function providerWith(overrides: Partial<LogoutTokenProvider> = {}) {+ const provider: LogoutTokenProvider = {+ issuer: ISSUER,+ algorithms: ASYMMETRIC_ALGORITHMS,+ jwksFetch: async () => JWKS,+ jwksCacheKey: {},+ ...overrides,+ };+ return vi.fn(async () => provider);+}++function verify(token: string, loadProvider = providerWith()) {+ return verifyLogoutToken(token, CLIENT_ID, loadProvider);+}++async function expectRejected(token: string, loadProvider = providerWith()) {+ await expect(verify(token, loadProvider)).rejects.toBeInstanceOf(+ LogoutTokenRejected,+ );+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(NOW * 1000);+});++afterEach(() => {+ vi.useRealTimers();+});++describe("verifyLogoutToken", () => {+ it("returns the claims of a valid logout token", async () => {+ await expect(verify(signToken())).resolves.toEqual({+ iss: ISSUER,+ jti: "logout-1",+ iat: NOW,+ sid: "kc-session-1",+ sub: "kc-user-1",+ });+ });++ it.each(["PS256", "ES256", "EdDSA"])("accepts %s signatures", async (alg) => {+ await expect(verify(signToken(logoutClaims(), { alg }))).resolves.toEqual(+ expect.objectContaining({ jti: "logout-1" }),+ );+ });++ it.each(["logout+jwt", "JWT", "application/logout+jwt", undefined])(+ "accepts the token type %p",+ async (typ) => {+ await expect(verify(signToken(logoutClaims(), { typ }))).resolves.toEqual(+ expect.objectContaining({ jti: "logout-1" }),+ );+ },+ );++ it("accepts an audience list that contains the client ID", async () => {+ await expect(+ verify(signToken(logoutClaims({ aud: ["other-client", CLIENT_ID] }))),+ ).resolves.toEqual(expect.objectContaining({ jti: "logout-1" }));+ });++ it("accepts a token with only a session ID or only a subject", async () => {+ await expect(+ verify(signToken(logoutClaims({ sub: undefined }))),+ ).resolves.toEqual(+ expect.objectContaining({ sid: "kc-session-1", sub: undefined }),+ );+ await expect(+ verify(signToken(logoutClaims({ sid: undefined }))),+ ).resolves.toEqual(+ expect.objectContaining({ sid: undefined, sub: "kc-user-1" }),+ );+ });++ it.each([+ [+ "a header that is not JSON",+ `${Buffer.from("not-json").toString("base64url")}.e30.c2ln`,+ ],+ ["a header that is a JSON array", `${encode(["RS256"])}.e30.c2ln`],+ ["alg none", `${encode({ alg: "none" })}.${encode(logoutClaims())}.c2ln`],+ [+ "HS256",+ `${encode({ alg: "HS256", kid: "rsa" })}.${encode(logoutClaims())}.c2ln`,+ ],+ [+ "ES256K",+ `${encode({ alg: "ES256K", kid: "ec" })}.${encode(logoutClaims())}.c2ln`,+ ],+ ["a critical header", signToken(logoutClaims(), { crit: ["exp"], exp: 1 })],+ ["typ at+jwt", signToken(logoutClaims(), { typ: "at+jwt" })],+ ["typ secevent+jwt", signToken(logoutClaims(), { typ: "secevent+jwt" })],+ ["a numeric typ", signToken(logoutClaims(), { typ: 1 })],+ ])("rejects %s before loading the provider", async (_name, token) => {+ const loadProvider = providerWith();+ await expectRejected(token, loadProvider);+ expect(loadProvider).not.toHaveBeenCalled();+ });++ it("rejects an algorithm the provider does not sign ID tokens with", async () => {+ await expectRejected(signToken(), providerWith({ algorithms: ["ES256"] }));+ });++ it("rejects a payload that is not a JSON object", async () => {+ await expectRejected(signToken([logoutClaims()]));+ });++ it("rejects a token signed by another key", async () => {+ await expectRejected(signToken(logoutClaims(), {}, otherRsa.privateKey));+ await expectRejected(signToken(logoutClaims(), { kid: "unknown" }));+ });++ it.each([+ ["another issuer", { iss: "https://idp.example.com/realms/other" }],+ ["no issuer", { iss: undefined }],+ ["another audience", { aud: "other-client" }],+ ["no audience", { aud: undefined }],+ ["no iat", { iat: undefined }],+ ["a string iat", { iat: String(NOW) }],+ ["an iat over a minute ahead", { iat: NOW + 61 }],+ ["an iat over ten minutes old", { iat: NOW - 601 }],+ ["an exp over a minute ago", { exp: NOW - 61 }],+ ["no jti", { jti: undefined }],+ ["an empty jti", { jti: "" }],+ ["a numeric jti", { jti: 42 }],+ ["no events", { events: undefined }],+ ["events as a list", { events: [BACKCHANNEL_LOGOUT_EVENT] }],+ ["events without the logout event", { events: { other: {} } }],+ [+ "a logout event set to true",+ { events: { [BACKCHANNEL_LOGOUT_EVENT]: true } },+ ],+ [+ "a logout event set to a list",+ { events: { [BACKCHANNEL_LOGOUT_EVENT]: [] } },+ ],+ [+ "a logout event set to null",+ { events: { [BACKCHANNEL_LOGOUT_EVENT]: null } },+ ],+ [+ "a logout event set to text",+ { events: { [BACKCHANNEL_LOGOUT_EVENT]: "x" } },+ ],+ ["neither sid nor sub", { sid: undefined, sub: undefined }],+ ["an empty sub", { sub: "" }],+ ["a numeric sid", { sid: 7 }],+ ["a nonce", { nonce: "n-1" }],+ ])("rejects a token with %s", async (_name, overrides) => {+ await expectRejected(signToken(logoutClaims(overrides)));+ });++ it.each([+ ["an iat a minute ahead", { iat: NOW + 60 }],+ ["an iat ten minutes old", { iat: NOW - 600, exp: NOW + 60 }],+ ["an exp less than a minute ago", { exp: NOW - 59 }],+ ["no exp", { exp: undefined }],+ ])("accepts a token with %s", async (_name, overrides) => {+ await expect(verify(signToken(logoutClaims(overrides)))).resolves.toEqual(+ expect.objectContaining({ jti: "logout-1" }),+ );+ });++ it("reports an unreachable provider as unavailable", async () => {+ await expect(+ verify(+ signToken(),+ vi.fn(async () => {+ throw new LogoutProviderUnavailable("down");+ }),+ ),+ ).rejects.toBeInstanceOf(LogoutProviderUnavailable);+ await expect(+ verify(+ signToken(),+ providerWith({+ jwksFetch: async () => {+ throw new LogoutProviderUnavailable("down");+ },+ }),+ ),+ ).rejects.toBeInstanceOf(LogoutProviderUnavailable);+ });++ it("never puts the token or its claims into the rejection message", async () => {+ const jti = randomUUID();+ const token = signToken(logoutClaims({ jti, aud: "other-client" }));+ const error = await verify(token).catch((rejection: unknown) => rejection);+ expect(error).toBeInstanceOf(LogoutTokenRejected);+ expect(String(error)).not.toContain(jti);+ expect(String(error)).not.toContain(token);+ });+});diff --git a/tests/api/user/assert-managed-profile-unchanged.test.ts b/tests/api/user/assert-managed-profile-unchanged.test.tsnew file mode 100644index 000000000..e118b90c8--- /dev/null+++ b/tests/api/user/assert-managed-profile-unchanged.test.ts@@ -0,0 +1,91 @@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";++const { getManagedProfile } = vi.hoisted(() => ({+ getManagedProfile: vi.fn(),+}));++vi.mock("../../../apps/api/src/user/controllers/get-managed-profile", () => ({+ default: getManagedProfile,+ getManagedProfile,+}));++const { assertManagedProfileUnchanged } =+ await import("../../../apps/api/src/user/controllers/assert-managed-profile-unchanged");++const refusal = {+ status: "FORBIDDEN",+ body: { code: "PROFILE_FIELD_MANAGED_BY_PROVIDER" },+};++function hookContext(+ path: string | undefined,+ sessionUserId: string,+ body: { userId?: string } = {},+) {+ return { path, body, context: { session: { user: { id: sessionUserId } } } };+}++describe("assertManagedProfileUnchanged", () => {+ beforeEach(() => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ getManagedProfile.mockReset();+ getManagedProfile.mockResolvedValue({+ fields: ["name"],+ stored: { name: "Jane Doe", image: null, locale: "en-US" },+ });+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("checks the signed-in user's own profile on /update-user", async () => {+ await expect(+ assertManagedProfileUnchanged(+ { name: "Janet" },+ hookContext("/update-user", "self"),+ ),+ ).rejects.toMatchObject(refusal);+ expect(getManagedProfile).toHaveBeenCalledWith("self");+ });++ it("checks the target user, not the admin, on /admin/update-user", async () => {+ await expect(+ assertManagedProfileUnchanged(+ { name: "Janet" },+ hookContext("/admin/update-user", "admin", { userId: "target" }),+ ),+ ).rejects.toMatchObject(refusal);+ expect(getManagedProfile).toHaveBeenCalledWith("target");+ expect(getManagedProfile).not.toHaveBeenCalledWith("admin");+ });++ it.each(["/oauth2/callback/:providerId", "/verify-email", undefined])(+ "leaves user updates on %p alone",+ async (path) => {+ await expect(+ assertManagedProfileUnchanged(+ { name: "Janet" },+ hookContext(path, "self"),+ ),+ ).resolves.toBeUndefined();+ expect(getManagedProfile).not.toHaveBeenCalled();+ },+ );++ it("accepts the stored value sent again", async () => {+ await expect(+ assertManagedProfileUnchanged(+ { name: "Jane Doe" },+ hookContext("/update-user", "self"),+ ),+ ).resolves.toBeUndefined();+ });+});diff --git a/tests/api/user/avatar.test.ts b/tests/api/user/avatar.test.tsindex 79c006498..5fb8f5bb7 100644--- a/tests/api/user/avatar.test.ts+++ b/tests/api/user/avatar.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test";import {buildAvatarUrl,decodeAvatarUpload,+ isUploadedAvatarUrl,MAX_AVATAR_BYTES,MAX_AVATAR_INPUT_CHARS,normalizeAvatarMimeType,@@ -158,3 +159,21 @@ describe("buildAvatarUrl", () => {expect(buildAvatarUrl("abc123")).toBe("/api/user/avatar/abc123");});});++describe("isUploadedAvatarUrl", () => {+ it("recognizes an avatar uploaded to Kaneo", () => {+ expect(isUploadedAvatarUrl(buildAvatarUrl("abc123"))).toBe(true);+ });++ it.each([+ null,+ undefined,+ "",+ "/api/user/avatar/",+ "/api/user/avatar/abc/def",+ "/api/user/avatar/abc?size=64",+ "https://cdn.example.com/api/user/avatar/abc123",+ ])("does not treat %p as an upload", (image) => {+ expect(isUploadedAvatarUrl(image)).toBe(false);+ });+});diff --git a/tests/api/user/managed-avatar-guards.test.ts b/tests/api/user/managed-avatar-guards.test.tsnew file mode 100644index 000000000..4d05abb3d--- /dev/null+++ b/tests/api/user/managed-avatar-guards.test.ts@@ -0,0 +1,81 @@+import type { Context } from "hono";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++const { getManagedProfile } = vi.hoisted(() => ({+ getManagedProfile: vi.fn(),+}));++vi.mock("../../../apps/api/src/user/controllers/get-managed-profile", () => ({+ default: getManagedProfile,+ getManagedProfile,+}));++const { requireRemovableAvatar, requireUnmanagedAvatar } =+ await import("../../../apps/api/src/user/managed-avatar-guards");++const context = { get: () => "user-1" } as unknown as Context;++const refusal = { status: 403, code: "PROFILE_FIELD_MANAGED_BY_PROVIDER" };++function managedProfile(fields: string[], image: string | null) {+ return { fields, stored: { name: "Jane Doe", image, locale: null } };+}++describe("managed avatar guards", () => {+ beforeEach(() => {+ getManagedProfile.mockReset();+ });++ it("refuses an upload while the provider manages the picture", async () => {+ getManagedProfile.mockResolvedValue(managedProfile(["image"], null));+ const next = vi.fn(async () => {});++ await expect(requireUnmanagedAvatar(context, next)).rejects.toMatchObject(+ refusal,+ );+ expect(next).not.toHaveBeenCalled();+ expect(getManagedProfile).toHaveBeenCalledWith("user-1");+ });++ it.each([+ ["people without a provider account", null],+ ["a picture the provider does not manage", managedProfile(["name"], null)],+ ])("allows an upload for %s", async (_name, managed) => {+ getManagedProfile.mockResolvedValue(managed);+ const next = vi.fn(async () => {});++ await requireUnmanagedAvatar(context, next);+ expect(next).toHaveBeenCalledOnce();+ });++ it.each(["/api/user/avatar/abc", null])(+ "allows removing while the stored picture is %p",+ async (image) => {+ getManagedProfile.mockResolvedValue(managedProfile(["image"], image));+ const next = vi.fn(async () => {});++ await requireRemovableAvatar(context, next);+ expect(next).toHaveBeenCalledOnce();+ },+ );++ it("refuses removing the provider's picture", async () => {+ getManagedProfile.mockResolvedValue(+ managedProfile(["image"], "https://id.example.com/jane.png"),+ );+ const next = vi.fn(async () => {});++ await expect(requireRemovableAvatar(context, next)).rejects.toMatchObject(+ refusal,+ );+ expect(next).not.toHaveBeenCalled();+ });++ it("allows people without a provider account to remove any picture", async () => {+ getManagedProfile.mockResolvedValue(null);+ const next = vi.fn(async () => {});++ await requireRemovableAvatar(context, next);+ expect(next).toHaveBeenCalledOnce();+ });+});diff --git a/tests/api/user/managed-profile.test.ts b/tests/api/user/managed-profile.test.tsnew file mode 100644index 000000000..2ed78ddea--- /dev/null+++ b/tests/api/user/managed-profile.test.ts@@ -0,0 +1,164 @@+import { describe, expect, it } from "vite-plus/test";+import { buildAvatarUrl } from "../../../apps/api/src/user/avatar";+import {+ canRemoveAvatar,+ changesManagedProfile,+ planManagedProfileRefresh,+ type StoredProfile,+} from "../../../apps/api/src/user/managed-profile";++const upload = buildAvatarUrl("avatar-1");+const picture = "https://id.example.com/jane.png";++function stored(overrides: Partial<StoredProfile> = {}): StoredProfile {+ return { name: "Jane Doe", image: null, locale: "en-US", ...overrides };+}++describe("canRemoveAvatar", () => {+ it("allows removing an upload or nothing", () => {+ expect(canRemoveAvatar(upload)).toBe(true);+ expect(canRemoveAvatar(null)).toBe(true);+ });++ it("refuses removing the provider's picture", () => {+ expect(canRemoveAvatar(picture)).toBe(false);+ });+});++describe("changesManagedProfile", () => {+ const all = ["name", "image", "locale"] as const;++ it("ignores fields the request leaves out", () => {+ expect(changesManagedProfile({ name: undefined }, stored(), ["name"])).toBe(+ false,+ );+ });++ it("accepts the current values sent again", () => {+ expect(+ changesManagedProfile(+ { name: "Jane Doe", image: picture, locale: "en-US" },+ stored({ image: picture }),+ all,+ ),+ ).toBe(false);+ });++ it.each([+ [{ name: "Janet" }],+ [{ locale: "de-DE" }],+ [{ image: "https://id.example.com/other.png" }],+ [{ image: buildAvatarUrl("avatar-2") }],+ ])("refuses a changed managed value %o", (data) => {+ expect(changesManagedProfile(data, stored({ image: upload }), all)).toBe(+ true,+ );+ });++ it("accepts changes to fields the provider does not manage", () => {+ expect(+ changesManagedProfile(+ { name: "Janet", locale: "de-DE", image: picture },+ stored({ image: picture }),+ ["image"],+ ),+ ).toBe(false);+ });++ it("allows removing a picture uploaded to Kaneo", () => {+ expect(+ changesManagedProfile({ image: null }, stored({ image: upload }), [+ "image",+ ]),+ ).toBe(false);+ });++ it("refuses removing the provider's picture", () => {+ expect(+ changesManagedProfile({ image: null }, stored({ image: picture }), [+ "image",+ ]),+ ).toBe(true);+ });+});++describe("planManagedProfileRefresh", () => {+ it("updates only the listed fields", () => {+ expect(+ planManagedProfileRefresh(+ { name: "Janet Doe", picture, locale: "de" },+ stored(),+ ["name"],+ ),+ ).toEqual({ update: { name: "Janet Doe" }, removeUploadedAvatar: false });+ });++ it("derives the name like account creation does", () => {+ expect(+ planManagedProfileRefresh(+ { given_name: "Janet", family_name: "Doe" },+ stored(),+ ["name"],+ ).update,+ ).toEqual({ name: "Janet Doe" });+ });++ it("leaves an unchanged profile alone", () => {+ expect(+ planManagedProfileRefresh(+ { name: "Jane Doe", picture, locale: "en" },+ stored({ image: picture }),+ ["name", "image", "locale"],+ ),+ ).toEqual({ update: {}, removeUploadedAvatar: true });+ });++ it("replaces an upload with the provider's picture and removes the upload", () => {+ expect(+ planManagedProfileRefresh({ picture }, stored({ image: upload }), [+ "image",+ ]),+ ).toEqual({ update: { image: picture }, removeUploadedAvatar: true });+ });++ it.each([undefined, "not a url"])(+ "keeps an upload while the picture is %p",+ (value) => {+ expect(+ planManagedProfileRefresh(+ { picture: value },+ stored({ image: upload }),+ ["image"],+ ),+ ).toEqual({ update: {}, removeUploadedAvatar: false });+ },+ );++ it("clears a picture the provider no longer sends", () => {+ expect(+ planManagedProfileRefresh({}, stored({ image: picture }), ["image"]),+ ).toEqual({ update: { image: null }, removeUploadedAvatar: false });+ });++ it("does nothing without a picture on either side", () => {+ expect(planManagedProfileRefresh({}, stored(), ["image"])).toEqual({+ update: {},+ removeUploadedAvatar: false,+ });+ });++ it("stores the supported locale for the claim", () => {+ expect(+ planManagedProfileRefresh({ locale: "de" }, stored(), ["locale"]).update,+ ).toEqual({ locale: "de-DE" });+ });++ it.each([undefined, "sv"])(+ "keeps the locale when the claim is %p",+ (locale) => {+ expect(+ planManagedProfileRefresh({ locale }, stored(), ["locale"]).update,+ ).toEqual({});+ },+ );+});diff --git a/tests/api/utils/custom-oauth-env.test.ts b/tests/api/utils/custom-oauth-env.test.tsnew file mode 100644index 000000000..a8db0d671--- /dev/null+++ b/tests/api/utils/custom-oauth-env.test.ts@@ -0,0 +1,92 @@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import {+ assertCustomOAuthEnv,+ parseCustomOAuthAccountUrl,+ parseManagedProfileFields,+} from "../../../apps/api/src/utils/custom-oauth-env";++afterEach(() => {+ vi.unstubAllEnvs();+});++describe("parseManagedProfileFields", () => {+ it.each(["", " , ,"])("manages nothing for %p", (value) => {+ expect(parseManagedProfileFields(value)).toEqual([]);+ });++ it("reads CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS by default", () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ expect(parseManagedProfileFields()).toEqual(["image"]);+ });++ it("trims, ignores case and empty entries, and keeps a stable order", () => {+ expect(parseManagedProfileFields(" Locale ,IMAGE,, name ")).toEqual([+ "name",+ "image",+ "locale",+ ]);+ });++ it("lists a repeated field once", () => {+ expect(parseManagedProfileFields("name,NAME")).toEqual(["name"]);+ });++ it("refuses an unknown field", () => {+ expect(() => parseManagedProfileFields("name, avatar")).toThrow(+ 'CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS accepts name, image and locale, not "avatar".',+ );+ });+});++describe("parseCustomOAuthAccountUrl", () => {+ it.each(["", " "])("is unset for %p", (value) => {+ expect(parseCustomOAuthAccountUrl(value)).toBeNull();+ });++ it.each([+ [+ " https://keycloak.example.com/realms/acme/account ",+ "https://keycloak.example.com/realms/acme/account",+ ],+ ["http://id.example.com", "http://id.example.com/"],+ ])("accepts %p", (value, expected) => {+ expect(parseCustomOAuthAccountUrl(value)).toBe(expected);+ });++ it.each([+ "ftp://id.example.com/account",+ "javascript:alert(1)",+ "/realms/acme/account",+ "not a url",+ ])("refuses %p", (value) => {+ expect(() => parseCustomOAuthAccountUrl(value)).toThrow(+ "CUSTOM_OAUTH_ACCOUNT_URL must be an absolute http or https URL.",+ );+ });+});++describe("assertCustomOAuthEnv", () => {+ beforeEach(() => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "");+ vi.stubEnv("CUSTOM_OAUTH_ACCOUNT_URL", "");+ });++ it("accepts unset settings", () => {+ expect(() => assertCustomOAuthEnv()).not.toThrow();+ });++ it.each([+ ["CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "email"],+ ["CUSTOM_OAUTH_ACCOUNT_URL", "id.example.com/account"],+ ])("refuses an invalid %s", (key, value) => {+ vi.stubEnv(key, value);+ expect(() => assertCustomOAuthEnv()).toThrow(key);+ });+});diff --git a/tests/api/utils/custom-oauth-profile.test.ts b/tests/api/utils/custom-oauth-profile.test.tsindex eea48a088..f627185e2 100644--- a/tests/api/utils/custom-oauth-profile.test.ts+++ b/tests/api/utils/custom-oauth-profile.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from "vite-plus/test";-import { mapCustomOAuthProfileToUser } from "../../../apps/api/src/utils/custom-oauth-profile";+import {+ mapCustomOAuthProfileToUser,+ readCustomOAuthPicture,+} from "../../../apps/api/src/utils/custom-oauth-profile";describe("mapCustomOAuthProfileToUser", () => {it("uses the provider name when present", () => {@@ -45,4 +48,98 @@ describe("mapCustomOAuthProfileToUser", () => {it("returns an empty mapping when no usable display value exists", () => {expect(mapCustomOAuthProfileToUser({ email: "" })).toEqual({});});++ it("leaves the picture and locale to Better Auth when they are not managed", () => {+ expect(+ mapCustomOAuthProfileToUser(+ {+ name: "Jane Doe",+ picture: "https://id.example.com/jane.png",+ locale: "de",+ },+ ["name"],+ ),+ ).toEqual({ name: "Jane Doe" });+ });++ it("maps a managed picture and locale", () => {+ expect(+ mapCustomOAuthProfileToUser(+ {+ name: "Jane Doe",+ picture: "https://id.example.com/jane.png",+ locale: "de",+ },+ ["image", "locale"],+ ),+ ).toEqual({+ name: "Jane Doe",+ image: "https://id.example.com/jane.png",+ locale: "de-DE",+ });+ });++ it("maps an unusable managed picture and locale to null", () => {+ expect(+ mapCustomOAuthProfileToUser(+ { name: "Jane Doe", picture: "javascript:alert(1)", locale: "sv" },+ ["image", "locale"],+ ),+ ).toEqual({ name: "Jane Doe", image: null, locale: null });+ });+});++describe("readCustomOAuthPicture", () => {+ const pictureOfLength = (length: number) => {+ const base = "https://id.example.com/";+ return `${base}${"a".repeat(length - base.length)}`;+ };++ it.each([+ "https://id.example.com/jane.png",+ "http://id.example.com/jane.png",+ ])("keeps %s", (picture) => {+ expect(readCustomOAuthPicture({ picture })).toBe(picture);+ });++ it("trims the claim", () => {+ expect(+ readCustomOAuthPicture({ picture: " https://id.example.com/jane.png " }),+ ).toBe("https://id.example.com/jane.png");+ });++ it.each([+ ["https:/api/auth/sign-out", "https://api/auth/sign-out"],+ ["https:id.example.com/jane.png", "https://id.example.com/jane.png"],+ ["http:/path", "http://path/"],+ ["https:\\api/x", "https://api/x"],+ ])("stores %p as the absolute URL %p", (picture, expected) => {+ expect(readCustomOAuthPicture({ picture })).toBe(expected);+ });++ it("accepts up to 2048 characters", () => {+ const picture = pictureOfLength(2048);+ expect(readCustomOAuthPicture({ picture })).toBe(picture);+ expect(readCustomOAuthPicture({ picture: pictureOfLength(2049) })).toBe(+ null,+ );+ });++ it("measures the length of the URL it stores", () => {+ const picture = `https://id.example.com/${"a b".repeat(600)}`;+ expect(picture.length).toBeLessThanOrEqual(2048);+ expect(readCustomOAuthPicture({ picture })).toBeNull();+ });++ it.each([+ undefined,+ "",+ 42,+ "javascript:alert(1)",+ "data:image/png;base64,AAAA",+ "/avatars/jane.png",+ "id.example.com/jane.png",+ ])("treats %p as absent", (picture) => {+ expect(readCustomOAuthPicture({ picture })).toBeNull();+ });});diff --git a/tests/api/utils/custom-oauth-sign-in.test.ts b/tests/api/utils/custom-oauth-sign-in.test.tsnew file mode 100644index 000000000..53e2e5b87--- /dev/null+++ b/tests/api/utils/custom-oauth-sign-in.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vite-plus/test";+import {+ rememberCustomOAuthProfile,+ runCustomOAuthCallback,+ takeCustomOAuthProfile,+} from "../../../apps/api/src/utils/custom-oauth-sign-in";++describe("custom OAuth sign-in profile", () => {+ it("keeps nothing outside a callback", () => {+ rememberCustomOAuthProfile({ sub: "sub-1" });+ expect(takeCustomOAuthProfile()).toBeUndefined();+ });++ it("hands the profile over once within a callback", async () => {+ const taken = await runCustomOAuthCallback(async () => {+ await Promise.resolve();+ rememberCustomOAuthProfile({ sub: "sub-1" });+ await Promise.resolve();+ return [takeCustomOAuthProfile(), takeCustomOAuthProfile()];+ });+ expect(taken).toEqual([{ sub: "sub-1" }, undefined]);+ });++ it("keeps concurrent callbacks apart", async () => {+ const signIn = (sub: string) =>+ runCustomOAuthCallback(async () => {+ rememberCustomOAuthProfile({ sub });+ await new Promise((resolve) => setTimeout(resolve, 5));+ return takeCustomOAuthProfile();+ });+ await expect(Promise.all([signIn("a"), signIn("b")])).resolves.toEqual([+ { sub: "a" },+ { sub: "b" },+ ]);+ });+});diff --git a/tests/api/utils/supported-locales.test.ts b/tests/api/utils/supported-locales.test.tsnew file mode 100644index 000000000..8b609ba9a--- /dev/null+++ b/tests/api/utils/supported-locales.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vite-plus/test";+import {+ resolveSupportedLocale,+ SUPPORTED_LOCALES,+} from "../../../apps/api/src/utils/supported-locales";+import { supportedLocales } from "../../../i18n/resources";++describe("SUPPORTED_LOCALES", () => {+ it("matches the locales the web app ships, in the same order", () => {+ expect(SUPPORTED_LOCALES).toEqual(supportedLocales);+ });+});++describe("resolveSupportedLocale", () => {+ it.each([+ ["de-DE", "de-DE"],+ ["DE-de", "de-DE"],+ ["de", "de-DE"],+ ["en", "en-US"],+ ["en-GB", "en-US"],+ ["pt_BR", "pt-BR"],+ [" fr-CA ", "fr-FR"],+ ["zh-TW", "zh-TW"],+ ["zh", "zh-CN"],+ ["zh-Hant", "zh-TW"],+ ["zh_Hant", "zh-TW"],+ ["zh-Hant-TW", "zh-TW"],+ ["zh-HK", "zh-TW"],+ ["zh-MO", "zh-TW"],+ ["zh-Hans", "zh-CN"],+ ["zh-Hans-HK", "zh-CN"],+ ["zh-SG", "zh-CN"],+ ])("resolves %p to %p", (value, expected) => {+ expect(resolveSupportedLocale(value)).toBe(expected);+ });++ it.each(["sv", "sv-SE", "", " ", 42, null, undefined, ["de"]])(+ "has no supported locale for %p",+ (value) => {+ expect(resolveSupportedLocale(value)).toBeNull();+ },+ );+});