Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(admin): add custom instance roles and per-permission admin checks

Tin4f4fd3e5a974
diff --git a/apps/api/drizzle/0070_instance_roles.sql b/apps/api/drizzle/0070_instance_roles.sql
new file mode 100644
index 000000000..766daba16
--- /dev/null
+++ b/apps/api/drizzle/0070_instance_roles.sql
@@ -0,0 +1,8 @@
+CREATE TABLE "instance_role" (
+ "id" text PRIMARY KEY NOT NULL,
+ "name" text NOT NULL,
+ "permissions" text[] DEFAULT '{}' NOT NULL,
+ "created_at" timestamp DEFAULT (now() AT TIME ZONE 'utc') NOT NULL,
+ "updated_at" timestamp DEFAULT (now() AT TIME ZONE 'utc') NOT NULL,
+ CONSTRAINT "instance_role_name_unique" UNIQUE("name")
+);
diff --git a/apps/api/drizzle/meta/0070_snapshot.json b/apps/api/drizzle/meta/0070_snapshot.json
new file mode 100644
index 000000000..cb9141ed5
--- /dev/null
+++ b/apps/api/drizzle/meta/0070_snapshot.json
@@ -0,0 +1,5684 @@
+{
+ "id": "5280db1b-84ba-447d-8990-095baa17d4f4",
+ "prevId": "625483fe-9827-48be-add5-d3a6fa358a2b",
+ "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.admin_audit_log": {
+ "name": "admin_audit_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_name": {
+ "name": "actor_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_email": {
+ "name": "actor_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_type": {
+ "name": "target_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_label": {
+ "name": "target_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() AT TIME ZONE 'utc')"
+ }
+ },
+ "indexes": {
+ "admin_audit_log_createdAt_idx": {
+ "name": "admin_audit_log_createdAt_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "admin_audit_log_actorUserId_idx": {
+ "name": "admin_audit_log_actorUserId_idx",
+ "columns": [
+ {
+ "expression": "actor_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "admin_audit_log_target_idx": {
+ "name": "admin_audit_log_target_idx",
+ "columns": [
+ {
+ "expression": "target_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "admin_audit_log_actor_user_id_user_id_fk": {
+ "name": "admin_audit_log_actor_user_id_user_id_fk",
+ "tableFrom": "admin_audit_log",
+ "tableTo": "user",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "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
+ },
+ "hidden_options": {
+ "name": "hidden_options",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "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.instance_role": {
+ "name": "instance_role",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "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": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "instance_role_name_unique": {
+ "name": "instance_role_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "name"
+ ]
+ }
+ },
+ "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
+ },
+ "recurrence": {
+ "name": "recurrence",
+ "type": "jsonb",
+ "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
+ },
+ "member_count": {
+ "name": "member_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "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
+ },
+ "membership_key": {
+ "name": "membership_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "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": {
+ "team_member_membership_key_unique": {
+ "name": "team_member_membership_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "membership_key"
+ ]
+ }
+ },
+ "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
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "archived_by": {
+ "name": "archived_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "workspace_archived_by_user_id_fk": {
+ "name": "workspace_archived_by_user_id_fk",
+ "tableFrom": "workspace",
+ "tableTo": "user",
+ "columnsFrom": [
+ "archived_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "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 file
diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.json
index b6a1557e9..594aaeaf0 100644
--- a/apps/api/drizzle/meta/_journal.json
+++ b/apps/api/drizzle/meta/_journal.json
@@ -491,6 +491,13 @@
"when": 1793128486906,
"tag": "0069_workspace_archive",
"breakpoints": true
+ },
+ {
+ "idx": 70,
+ "version": "7",
+ "when": 1793128577982,
+ "tag": "0070_instance_roles",
+ "breakpoints": true
}
]
}
diff --git a/apps/api/src/admin/controllers/create-instance-role.ts b/apps/api/src/admin/controllers/create-instance-role.ts
new file mode 100644
index 000000000..8bcefc614
--- /dev/null
+++ b/apps/api/src/admin/controllers/create-instance-role.ts
@@ -0,0 +1,43 @@
+import type { CustomRolePermission } from "@kaneo/permissions";
+import db from "../../database";
+import { instanceRoleTable } from "../../database/schema";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { assertRoleNameAvailable } from "../roles/assert-role-name-available";
+import { findInstanceRole } from "../roles/find-instance-role";
+
+type CreateInstanceRoleInput = {
+ name: string;
+ permissions: CustomRolePermission[];
+};
+
+async function createInstanceRole(
+ input: CreateInstanceRoleInput,
+ audit: AdminAuditRequest,
+) {
+ return db.transaction(async (tx) => {
+ await assertRoleNameAvailable(input.name, tx);
+ const [created] = await tx
+ .insert(instanceRoleTable)
+ .values(input)
+ .returning({ id: instanceRoleTable.id });
+ if (!created) throw new Error("Instance role was not created");
+
+ await recordAdminAction(
+ {
+ ...audit,
+ action: "role.created",
+ targetType: "role",
+ targetId: created.id,
+ targetLabel: input.name,
+ metadata: { permissions: input.permissions },
+ },
+ tx,
+ );
+ const role = await findInstanceRole(created.id, tx);
+ if (!role) throw new Error("Instance role was not created");
+ return role;
+ });
+}
+
+export default createInstanceRole;
diff --git a/apps/api/src/admin/controllers/create-user.ts b/apps/api/src/admin/controllers/create-user.ts
index 481c8eb6d..8857bd71e 100644
--- a/apps/api/src/admin/controllers/create-user.ts
+++ b/apps/api/src/admin/controllers/create-user.ts
@@ -6,6 +6,8 @@ import { isCloud } from "../../utils/is-cloud";
import { isDisposableEmail } from "../../utils/is-disposable-email";
import type { AdminAuditRequest } from "../audit/admin-audit-request";
import { recordAdminAction } from "../audit/record-admin-action";
+import { assertAssignableRole } from "../roles/assert-assignable-role";
+import { getUserAccess } from "../roles/get-instance-access";
import { emailPasswordLink } from "../users/account-email-links";
import { adminUserColumns, toAdminUser } from "../users/admin-user-columns";
import { createsPasswordAccounts } from "../users/password-sign-in";
@@ -13,7 +15,7 @@ import { createsPasswordAccounts } from "../users/password-sign-in";
type CreateUserInput = {
name: string;
email: string;
- role: "admin" | "user";
+ role: string;
};
export type PasswordSetupEmail =
@@ -45,8 +47,10 @@ async function createUser(input: CreateUserInput, audit: AdminAuditRequest) {
});
}
const withPassword = createsPasswordAccounts();
+ const actor = await getUserAccess(audit.actorUserId ?? "");
const userId = await db.transaction(async (tx) => {
+ await assertAssignableRole(input.role, actor, tx);
const [existing] = await tx
.select({ id: userTable.id })
.from(userTable)
diff --git a/apps/api/src/admin/controllers/deactivate-user.ts b/apps/api/src/admin/controllers/deactivate-user.ts
new file mode 100644
index 000000000..689bde5f1
--- /dev/null
+++ b/apps/api/src/admin/controllers/deactivate-user.ts
@@ -0,0 +1,55 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { userTable } from "../../database/schema";
+import { deleteUserSessions } from "../../sessions/delete-user-sessions";
+import { isBanActive } from "../../utils/user-ban";
+import { revokeSessionConnections } from "../../ws";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { lockAdminTargetUser } from "../users/lock-admin-target-user";
+import { readAdminUser } from "../users/read-admin-user";
+import { rejectSelfAction } from "../users/reject-self-action";
+
+const BAN_REASON = "Deactivated by an instance administrator";
+
+/** Block sign-in until reactivated and end every session the user has. */
+async function deactivateUser(
+ userId: string,
+ actorId: string,
+ audit: AdminAuditRequest,
+) {
+ rejectSelfAction(
+ actorId,
+ userId,
+ "YOU_CANNOT_BAN_YOURSELF",
+ "You cannot deactivate yourself.",
+ );
+ const { user, sessionIds } = await db.transaction(async (tx) => {
+ const target = await lockAdminTargetUser(userId, tx);
+ await tx
+ .update(userTable)
+ .set({ banned: true, banReason: BAN_REASON, banExpires: null })
+ .where(eq(userTable.id, userId));
+ const sessionIds = await deleteUserSessions(tx, userId, {
+ exceptSessionId: null,
+ });
+ if (!isBanActive(target) || target.banExpires) {
+ await recordAdminAction(
+ {
+ ...audit,
+ action: "user.deactivated",
+ targetType: "user",
+ targetId: userId,
+ targetLabel: target.email,
+ metadata: { reason: BAN_REASON, expiresAt: null },
+ },
+ tx,
+ );
+ }
+ return { user: await readAdminUser(userId, tx), sessionIds };
+ });
+ await revokeSessionConnections(userId, sessionIds);
+ return user;
+}
+
+export default deactivateUser;
diff --git a/apps/api/src/admin/controllers/delete-instance-role.ts b/apps/api/src/admin/controllers/delete-instance-role.ts
new file mode 100644
index 000000000..ca007cb18
--- /dev/null
+++ b/apps/api/src/admin/controllers/delete-instance-role.ts
@@ -0,0 +1,41 @@
+import { count, eq, sql } from "drizzle-orm";
+import db from "../../database";
+import { instanceRoleTable, userTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { lockInstanceRole } from "../roles/lock-instance-role";
+
+/** Delete a role nobody has. Assignments share-lock the role row first. */
+async function deleteInstanceRole(roleId: string, audit: AdminAuditRequest) {
+ return db.transaction(async (tx) => {
+ const role = await lockInstanceRole(roleId, tx);
+ const [assigned] = await tx
+ .select({ value: count() })
+ .from(userTable)
+ .where(sql`${role.name} = ANY(string_to_array(${userTable.role}, ','))`);
+ const userCount = assigned?.value ?? 0;
+ if (userCount > 0) {
+ throw new ApiError(409, {
+ code: "ROLE_IN_USE",
+ message: `This role is assigned to ${userCount} ${userCount === 1 ? "user" : "users"}. Give them another role first.`,
+ });
+ }
+
+ await tx.delete(instanceRoleTable).where(eq(instanceRoleTable.id, roleId));
+ await recordAdminAction(
+ {
+ ...audit,
+ action: "role.deleted",
+ targetType: "role",
+ targetId: roleId,
+ targetLabel: role.name,
+ metadata: { permissions: role.permissions },
+ },
+ tx,
+ );
+ return { id: roleId };
+ });
+}
+
+export default deleteInstanceRole;
diff --git a/apps/api/src/admin/controllers/delete-user.ts b/apps/api/src/admin/controllers/delete-user.ts
new file mode 100644
index 000000000..18c4453c7
--- /dev/null
+++ b/apps/api/src/admin/controllers/delete-user.ts
@@ -0,0 +1,63 @@
+import { isAPIError } from "better-auth/api";
+import { eq } from "drizzle-orm";
+import type { ContentfulStatusCode } from "hono/utils/http-status";
+import db from "../../database";
+import { userTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import { deleteUserSessions } from "../../sessions/delete-user-sessions";
+import deleteAccountData from "../../user/controllers/delete-account-data";
+import { revokeUserConnections } from "../../ws";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { lockAdminTargetUser } from "../users/lock-admin-target-user";
+import { rejectSelfAction } from "../users/reject-self-action";
+
+/** The same cleanup as self-service account deletion, with its conflicts. */
+async function removeAccountData(userId: string) {
+ try {
+ await deleteAccountData(userId);
+ } catch (error) {
+ if (!isAPIError(error)) throw error;
+ throw new ApiError(error.statusCode as ContentfulStatusCode, {
+ code: String(error.body?.code ?? "ACCOUNT_DELETION_BLOCKED"),
+ message: error.message,
+ });
+ }
+}
+
+/** Delete a user's account, workspaces they solely own, and their sessions. */
+async function deleteUser(
+ userId: string,
+ actorId: string,
+ audit: AdminAuditRequest,
+) {
+ rejectSelfAction(
+ actorId,
+ userId,
+ "YOU_CANNOT_REMOVE_YOURSELF",
+ "You cannot remove yourself.",
+ );
+ await lockAdminTargetUser(userId, db);
+ await removeAccountData(userId);
+
+ await db.transaction(async (tx) => {
+ const target = await lockAdminTargetUser(userId, tx);
+ await deleteUserSessions(tx, userId, { exceptSessionId: null });
+ await tx.delete(userTable).where(eq(userTable.id, userId));
+ await recordAdminAction(
+ {
+ ...audit,
+ action: "user.deleted",
+ targetType: "user",
+ targetId: userId,
+ targetLabel: target.email,
+ metadata: { name: target.name },
+ },
+ tx,
+ );
+ });
+ await revokeUserConnections(userId);
+ return { id: userId };
+}
+
+export default deleteUser;
diff --git a/apps/api/src/admin/controllers/list-instance-roles.ts b/apps/api/src/admin/controllers/list-instance-roles.ts
new file mode 100644
index 000000000..63f5b9feb
--- /dev/null
+++ b/apps/api/src/admin/controllers/list-instance-roles.ts
@@ -0,0 +1,18 @@
+import { asc } from "drizzle-orm";
+import db from "../../database";
+import { instanceRoleTable } from "../../database/schema";
+import {
+ instanceRoleColumns,
+ toInstanceRole,
+} from "../roles/find-instance-role";
+
+/** Custom instance roles by name. Built-in admin and user are not stored. */
+async function listInstanceRoles() {
+ const rows = await db
+ .select(instanceRoleColumns)
+ .from(instanceRoleTable)
+ .orderBy(asc(instanceRoleTable.name));
+ return { roles: rows.map(toInstanceRole) };
+}
+
+export default listInstanceRoles;
diff --git a/apps/api/src/admin/controllers/list-users.ts b/apps/api/src/admin/controllers/list-users.ts
index 8d8b73711..d191fd3c0 100644
--- a/apps/api/src/admin/controllers/list-users.ts
+++ b/apps/api/src/admin/controllers/list-users.ts
@@ -1,4 +1,4 @@
-import { and, count, desc, eq, ilike, or, sql } from "drizzle-orm";
+import { and, count, desc, eq, ilike, or, type SQL, sql } from "drizzle-orm";
import db from "../../database";
import { userTable } from "../../database/schema";
import { escapeLikePattern } from "../../search/like-pattern";
@@ -9,12 +9,24 @@ import { adminUserColumns, toAdminUser } from "../users/admin-user-columns";
type ListUsersInput = {
search?: string;
status?: "active" | "deactivated";
- role?: "admin" | "user";
+ role?: string;
emailVerified?: boolean;
page: number;
limit: number;
};
+// Qualified by hand: Drizzle leaves columns bare in one-table selects.
+const userRoles = sql`string_to_array("user"."role", ',')`;
+
+/** `user` means no admin or custom role: the roles that grant nothing. */
+function roleCondition(role: string, isAdmin: SQL) {
+ if (role === "admin") return isAdmin;
+ if (role !== "user") return sql`${role} = ANY(${userRoles})`;
+ return sql`NOT ${isAdmin} AND NOT EXISTS (
+ SELECT 1 FROM "instance_role" r WHERE r."name" = ANY(${userRoles})
+ )`;
+}
+
function filters({ search, status, role, emailVerified }: ListUsersInput) {
const term = search?.trim() ?? "";
const pattern = `%${escapeLikePattern(term)}%`;
@@ -29,11 +41,7 @@ function filters({ search, status, role, emailVerified }: ListUsersInput) {
: status === "deactivated"
? sql`NOT (${active})`
: active,
- role === undefined
- ? undefined
- : role === "admin"
- ? isAdmin
- : sql`NOT ${isAdmin}`,
+ role === undefined ? undefined : roleCondition(role, isAdmin),
emailVerified === undefined
? undefined
: eq(userTable.emailVerified, emailVerified),
diff --git a/apps/api/src/admin/controllers/reactivate-user.ts b/apps/api/src/admin/controllers/reactivate-user.ts
new file mode 100644
index 000000000..3536ff03f
--- /dev/null
+++ b/apps/api/src/admin/controllers/reactivate-user.ts
@@ -0,0 +1,33 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { userTable } from "../../database/schema";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { lockAdminTargetUser } from "../users/lock-admin-target-user";
+import { readAdminUser } from "../users/read-admin-user";
+
+/** Let a deactivated user sign in again. */
+async function reactivateUser(userId: string, audit: AdminAuditRequest) {
+ return db.transaction(async (tx) => {
+ const target = await lockAdminTargetUser(userId, tx);
+ if (target.banned) {
+ await tx
+ .update(userTable)
+ .set({ banned: false, banReason: null, banExpires: null })
+ .where(eq(userTable.id, userId));
+ await recordAdminAction(
+ {
+ ...audit,
+ action: "user.reactivated",
+ targetType: "user",
+ targetId: userId,
+ targetLabel: target.email,
+ },
+ tx,
+ );
+ }
+ return readAdminUser(userId, tx);
+ });
+}
+
+export default reactivateUser;
diff --git a/apps/api/src/admin/controllers/update-instance-role.ts b/apps/api/src/admin/controllers/update-instance-role.ts
new file mode 100644
index 000000000..f2bf86f04
--- /dev/null
+++ b/apps/api/src/admin/controllers/update-instance-role.ts
@@ -0,0 +1,72 @@
+import {
+ type CustomRolePermission,
+ isCustomRolePermission,
+} from "@kaneo/permissions";
+import { eq, sql } from "drizzle-orm";
+import db from "../../database";
+import { instanceRoleTable, userTable } from "../../database/schema";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { assertRoleNameAvailable } from "../roles/assert-role-name-available";
+import { findInstanceRole } from "../roles/find-instance-role";
+import { lockInstanceRole } from "../roles/lock-instance-role";
+
+type UpdateInstanceRoleInput = {
+ name: string;
+ permissions: CustomRolePermission[];
+};
+
+/** Rename a role or change its permissions. Users keep it across a rename. */
+async function updateInstanceRole(
+ roleId: string,
+ input: UpdateInstanceRoleInput,
+ audit: AdminAuditRequest,
+) {
+ return db.transaction(async (tx) => {
+ const current = await lockInstanceRole(roleId, tx);
+ const renamed = input.name !== current.name;
+ if (renamed) await assertRoleNameAvailable(input.name, tx, roleId);
+
+ await tx
+ .update(instanceRoleTable)
+ .set(input)
+ .where(eq(instanceRoleTable.id, roleId));
+ if (renamed) {
+ const roles = sql`string_to_array(${userTable.role}, ',')`;
+ await tx
+ .update(userTable)
+ .set({
+ role: sql`array_to_string(array_replace(${roles}, ${current.name}, ${input.name}), ',')`,
+ })
+ .where(sql`${current.name} = ANY(${roles})`);
+ }
+
+ const before = current.permissions.filter(isCustomRolePermission);
+ const added = input.permissions.filter((p) => !before.includes(p));
+ const removed = before.filter((p) => !input.permissions.includes(p));
+ if (renamed || added.length > 0 || removed.length > 0) {
+ await recordAdminAction(
+ {
+ ...audit,
+ action: "role.updated",
+ targetType: "role",
+ targetId: roleId,
+ targetLabel: input.name,
+ metadata: {
+ ...(renamed
+ ? { name: { from: current.name, to: input.name } }
+ : {}),
+ added,
+ removed,
+ },
+ },
+ tx,
+ );
+ }
+ const role = await findInstanceRole(roleId, tx);
+ if (!role) throw new Error("Instance role disappeared during update");
+ return role;
+ });
+}
+
+export default updateInstanceRole;
diff --git a/apps/api/src/admin/controllers/update-user.ts b/apps/api/src/admin/controllers/update-user.ts
new file mode 100644
index 000000000..e1e346d38
--- /dev/null
+++ b/apps/api/src/admin/controllers/update-user.ts
@@ -0,0 +1,155 @@
+import { and, eq, ne, sql } from "drizzle-orm";
+import db from "../../database";
+import { userTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import getManagedProfile from "../../user/controllers/get-managed-profile";
+import {
+ changesManagedProfile,
+ PROFILE_FIELD_MANAGED_BY_PROVIDER,
+} from "../../user/managed-profile";
+import { hasOtherInstanceAdmin } from "../../utils/has-other-instance-admin";
+import { hasInstanceAdminRole } from "../../utils/instance-admin-role";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordAdminAction } from "../audit/record-admin-action";
+import { assertAssignableRole } from "../roles/assert-assignable-role";
+import { getUserAccess } from "../roles/get-instance-access";
+import { lockAdminTargetUser } from "../users/lock-admin-target-user";
+import { readAdminUser } from "../users/read-admin-user";
+import { rejectSelfAction } from "../users/reject-self-action";
+
+type UpdateUserInput = {
+ userId: string;
+ actorId: string;
+ name?: string;
+ email?: string;
+ role?: string;
+};
+
+async function assertNameNotManaged(userId: string, name: string | undefined) {
+ if (name === undefined) return;
+ const managed = await getManagedProfile(userId);
+ if (
+ managed &&
+ changesManagedProfile({ name }, managed.stored, managed.fields)
+ )
+ throw new ApiError(403, { ...PROFILE_FIELD_MANAGED_BY_PROVIDER });
+}
+
+/** Change a user's name, email, or instance role. */
+async function updateUser(input: UpdateUserInput, audit: AdminAuditRequest) {
+ const { userId, actorId, role } = input;
+ if (role !== undefined) {
+ rejectSelfAction(
+ actorId,
+ userId,
+ "YOU_CANNOT_CHANGE_YOUR_OWN_ROLE",
+ "You cannot change your own role.",
+ );
+ }
+ await assertNameNotManaged(userId, input.name);
+ const actor = await getUserAccess(actorId);
+
+ return db.transaction(async (tx) => {
+ // Taken before the row lock, in the same order as the auth adapter.
+ const otherAdminRemains =
+ role === undefined ? true : await hasOtherInstanceAdmin(tx);
+ const target = await lockAdminTargetUser(userId, tx);
+ const update: Partial<typeof userTable.$inferInsert> = {};
+
+ if (input.name !== undefined && input.name !== target.name) {
+ update.name = input.name;
+ }
+ const email = input.email?.trim().toLowerCase();
+ if (email !== undefined && email !== target.email) {
+ if (email !== target.email.trim().toLowerCase()) {
+ const [taken] = await tx
+ .select({ id: userTable.id })
+ .from(userTable)
+ .where(
+ and(
+ eq(sql`lower(${userTable.email})`, email),
+ ne(userTable.id, userId),
+ ),
+ )
+ .limit(1);
+ if (taken) {
+ throw new ApiError(409, {
+ code: "USER_ALREADY_EXISTS",
+ message: "A user with this email address already exists.",
+ });
+ }
+ // A new address has to be confirmed again.
+ update.emailVerified = false;
+ }
+ update.email = email;
+ }
+ if (role !== undefined && role !== target.role) {
+ await assertAssignableRole(role, actor, tx);
+ if (
+ hasInstanceAdminRole(target.role) &&
+ !hasInstanceAdminRole(role) &&
+ !otherAdminRemains
+ ) {
+ throw new ApiError(400, {
+ code: "CANNOT_REMOVE_LAST_ADMIN",
+ message: "The instance must have at least one administrator.",
+ });
+ }
+ update.role = role;
+ }
+
+ if (Object.keys(update).length > 0) {
+ await tx.update(userTable).set(update).where(eq(userTable.id, userId));
+ await recordUserUpdate(target, update, audit, tx);
+ }
+ return readAdminUser(userId, tx);
+ });
+}
+
+async function recordUserUpdate(
+ target: Awaited<ReturnType<typeof lockAdminTargetUser>>,
+ update: Partial<typeof userTable.$inferInsert>,
+ audit: AdminAuditRequest,
+ tx: Parameters<typeof recordAdminAction>[1],
+) {
+ const about = {
+ targetType: "user",
+ targetId: target.id,
+ targetLabel: update.email ?? target.email,
+ };
+ if (update.role !== undefined) {
+ await recordAdminAction(
+ {
+ ...audit,
+ ...about,
+ action: "user.role_changed",
+ metadata: { from: target.role, to: update.role },
+ },
+ tx,
+ );
+ }
+ const fields = (["name", "email", "emailVerified"] as const).filter(
+ (field) => update[field] !== undefined,
+ );
+ if (fields.length > 0) {
+ await recordAdminAction(
+ {
+ ...audit,
+ ...about,
+ action: "user.updated",
+ metadata: {
+ fields,
+ changes: Object.fromEntries(
+ fields.map((field) => [
+ field,
+ { from: target[field], to: update[field] },
+ ]),
+ ),
+ },
+ },
+ tx,
+ );
+ }
+}
+
+export default updateUser;
diff --git a/apps/api/src/admin/index.ts b/apps/api/src/admin/index.ts
index 0b5d80c43..054aeb473 100644
--- a/apps/api/src/admin/index.ts
+++ b/apps/api/src/admin/index.ts
@@ -4,6 +4,7 @@ import {
errorResponse,
jsonResponse,
} from "../openapi";
+import { requireInstancePermission } from "./roles/require-instance-permission";
import { requireInstanceAdmin } from "../utils/require-instance-admin";
import { requireUserSession } from "../utils/require-user-session";
import { adminAuditRequest } from "./audit/admin-audit-request";
@@ -23,6 +24,10 @@ import sendAdminTestEmail from "./controllers/send-test-email";
import restoreWorkspace from "./controllers/restore-workspace";
import transferWorkspaceOwnership from "./controllers/transfer-workspace-ownership";
import updateWorkspaceMemberRole from "./controllers/update-workspace-member-role";
+import adminRoleRoutes from "./role-routes";
+import { getUserAccess } from "./roles/get-instance-access";
+import { instanceAccessSchema } from "./roles/schema";
+import adminUserAccountRoutes from "./user-account-routes";
import adminUserRoutes from "./user-routes";
import {
adminAuditLogSchema,
@@ -50,9 +55,27 @@ import {
import { adminUserSecurityRoutes } from "./user-security-routes";
const forbidden = errorResponse(
- "The caller is not an instance administrator or is authenticated with an API key",
+ "The caller lacks the instance permission or is authenticated with an API key",
);
+const getAccessRoute = createRoute({
+ method: "get",
+ operationId: "getAdminAccess",
+ path: "/access",
+ tags: ["Admin"],
+ summary: "Get your instance permissions",
+ description:
+ "List the instance permissions the signed-in user's roles grant. Empty for users without an administrator or custom role. API keys are rejected.",
+ middleware: [requireUserSession] as const,
+ responses: {
+ 200: jsonResponse(
+ "The caller's instance permissions",
+ instanceAccessSchema,
+ ),
+ 403: errorResponse("The request used an API key"),
+ },
+});
+
const listUsersRoute = createRoute({
method: "get",
operationId: "listAdminUsers",
@@ -60,8 +83,11 @@ const listUsersRoute = createRoute({
tags: ["Admin"],
summary: "List instance users",
description:
- "Page through every user account on this instance, newest first, optionally filtered by a case-insensitive name or email search, status, instance role, and email verification. Each user lists their linked sign-in methods and last session activity. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Page through every user account on this instance, newest first, optionally filtered by a case-insensitive name or email search, status, instance role, and email verification. Each user lists their linked sign-in methods and last session activity. Requires the `users:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:read"),
+ ] as const,
request: { query: listAdminUsersQuery },
responses: {
200: jsonResponse("Users matching the search", adminUserListSchema),
@@ -77,8 +103,11 @@ const listWorkspacesRoute = createRoute({
tags: ["Admin"],
summary: "List instance workspaces",
description:
- "Page through every workspace on this instance with its owners, member count, project count and archive state, optionally filtered by a case-insensitive name or slug search. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Page through every workspace on this instance with its owners, member count, project count and archive state, optionally filtered by a case-insensitive name or slug search. Requires the `workspaces:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:read"),
+ ] as const,
request: { query: listAdminWorkspacesQuery },
responses: {
200: jsonResponse(
@@ -97,8 +126,11 @@ const listWorkspaceMembersRoute = createRoute({
tags: ["Admin"],
summary: "List workspace members",
description:
- "List every member of a workspace with their role, whether or not the administrator belongs to it.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "List every member of a workspace with their role, whether or not the administrator belongs to it. Requires the `workspaces:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:read"),
+ ] as const,
request: { params: adminWorkspaceParam },
responses: {
200: jsonResponse("Workspace members", adminWorkspaceMemberListSchema),
@@ -114,8 +146,11 @@ const listWorkspaceRolesRoute = createRoute({
tags: ["Admin"],
summary: "List assignable workspace roles",
description:
- "List the roles an administrator can give members of a workspace: the built-in viewer, member and admin roles plus the workspace's custom roles. Ownership is changed with the ownership transfer instead.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "List the roles an administrator can give members of a workspace: the built-in viewer, member and admin roles plus the workspace's custom roles. Ownership is changed with the ownership transfer instead. Requires the `workspaces:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:read"),
+ ] as const,
request: { params: adminWorkspaceParam },
responses: {
200: jsonResponse("Assignable role names", adminWorkspaceRoleListSchema),
@@ -131,8 +166,11 @@ const addWorkspaceMemberRoute = createRoute({
tags: ["Admin"],
summary: "Add a user to a workspace",
description:
- "Add an existing user to a workspace with a role. They start with access to every project. Returns the updated member list.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Add an existing user to a workspace with a role. They start with access to every project. Returns the updated member list. Requires the `workspaces:manage` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:manage"),
+ ] as const,
request: {
params: adminWorkspaceParam,
body: {
@@ -159,8 +197,11 @@ const updateWorkspaceMemberRoleRoute = createRoute({
tags: ["Admin"],
summary: "Change a workspace member's role",
description:
- "Change a member's role. Use the ownership transfer to make someone the owner; the only owner's role can't be changed. Returns the updated member list.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Change a member's role. Use the ownership transfer to make someone the owner; the only owner's role can't be changed. Returns the updated member list. Requires the `workspaces:manage` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:manage"),
+ ] as const,
request: {
params: adminWorkspaceMemberParam,
body: {
@@ -189,8 +230,11 @@ const removeWorkspaceMemberRoute = createRoute({
tags: ["Admin"],
summary: "Remove a workspace member",
description:
- "Remove a member from a workspace. Their account stays. The only owner can't be removed. Returns the updated member list.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Remove a member from a workspace. Their account stays. The only owner can't be removed. Returns the updated member list. Requires the `workspaces:manage` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:manage"),
+ ] as const,
request: { params: adminWorkspaceMemberParam },
responses: {
200: jsonResponse(
@@ -210,8 +254,11 @@ const transferWorkspaceOwnershipRoute = createRoute({
tags: ["Admin"],
summary: "Transfer workspace ownership",
description:
- "Make an existing member the only owner of a workspace, for example when the previous owner has left. Previous owners become admins. Returns the updated member list.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Make an existing member the only owner of a workspace, for example when the previous owner has left. Previous owners become admins. Returns the updated member list. Requires the `workspaces:manage` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:manage"),
+ ] as const,
request: {
params: adminWorkspaceParam,
body: {
@@ -239,8 +286,11 @@ const archiveWorkspaceRoute = createRoute({
tags: ["Admin"],
summary: "Archive a workspace",
description:
- "Disable a workspace without deleting anything. Its members, API keys, MCP clients, public links, calendar feeds, notifications, and integrations stop working, and requests for it return 403 with the code WORKSPACE_ARCHIVED. Open realtime connections are closed. Restore it to undo. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Disable a workspace without deleting anything. Its members, API keys, MCP clients, public links, calendar feeds, notifications, and integrations stop working, and requests for it return 403 with the code WORKSPACE_ARCHIVED. Open realtime connections are closed. Restore it to undo. Requires the `workspaces:archive` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:archive"),
+ ] as const,
request: { params: adminWorkspaceParam },
responses: {
200: jsonResponse(
@@ -262,8 +312,11 @@ const restoreWorkspaceRoute = createRoute({
tags: ["Admin"],
summary: "Restore an archived workspace",
description:
- "Make an archived workspace usable again, with all of its data, members, and integrations as they were. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Make an archived workspace usable again, with all of its data, members, and integrations as they were. Requires the `workspaces:archive` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:archive"),
+ ] as const,
request: { params: adminWorkspaceParam },
responses: {
200: jsonResponse(
@@ -285,8 +338,11 @@ const deleteWorkspaceRoute = createRoute({
tags: ["Admin"],
summary: "Delete a workspace",
description:
- "Permanently delete a workspace and everything in it, archived or not, the same way its owner can: projects, tasks, members, invitations and uploaded files go, and open realtime connections are closed. The administrator does not need to be a member. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Permanently delete a workspace and everything in it, archived or not, the same way its owner can: projects, tasks, members, invitations and uploaded files go, and open realtime connections are closed. The administrator does not need to be a member. Requires the `workspaces:delete` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("workspaces:delete"),
+ ] as const,
request: { params: adminWorkspaceParam },
responses: {
200: jsonResponse("The deleted workspace", adminDeletedWorkspaceSchema),
@@ -305,8 +361,11 @@ const listAuditLogRoute = createRoute({
tags: ["Admin"],
summary: "List the admin audit log",
description:
- "Page through recorded administrative actions, newest first, optionally filtered by action or category, actor, or target. Entries never contain passwords, tokens, reset links, or API key values. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Page through recorded administrative actions, newest first, optionally filtered by action or category, actor, or target. Entries never contain passwords, tokens, reset links, or API key values. Requires the `audit:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("audit:read"),
+ ] as const,
request: { query: listAdminAuditLogQuery },
responses: {
200: jsonResponse("Audit log entries, newest first", adminAuditLogSchema),
@@ -322,8 +381,11 @@ const getSystemStatusRoute = createRoute({
tags: ["Admin"],
summary: "Get system status",
description:
- "Check this API instance and the services it uses: version, uptime, database, WebSockets, Redis fan-out, SMTP, object storage, sign-in providers and integration providers. Each check gives up after a few seconds, so one unreachable service can't block the response. Only statuses, counts and short error categories are returned, never hosts, credentials or secrets. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Check this API instance and the services it uses: version, uptime, database, WebSockets, Redis fan-out, SMTP, object storage, sign-in providers and integration providers. Each check gives up after a few seconds, so one unreachable service can't block the response. Only statuses, counts and short error categories are returned, never hosts, credentials or secrets. Requires the `system:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("system:read"),
+ ] as const,
responses: {
200: jsonResponse("Status of this instance", adminSystemStatusSchema),
403: forbidden,
@@ -337,8 +399,11 @@ const sendTestEmailRoute = createRoute({
tags: ["Admin"],
summary: "Send a test email",
description:
- "Send a test email to the calling administrator's own address to check the SMTP settings. There is no recipient parameter. Limited to 5 per administrator every 10 minutes on each API instance.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Send a test email to the calling administrator's own address to check the SMTP settings. There is no recipient parameter. Limited to 5 per administrator every 10 minutes on each API instance. Requires the `system:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("system:read"),
+ ] as const,
responses: {
200: jsonResponse(
"The mail server accepted the test email",
@@ -369,6 +434,10 @@ const getOverviewRoute = createRoute({
const admin = apiRouter()
.openapi(getOverviewRoute, async (c) => c.json(await getOverview(), 200))
+ .openapi(getAccessRoute, async (c) => {
+ const { permissions } = await getUserAccess(c.get("userId"));
+ return c.json({ permissions }, 200);
+ })
.openapi(listUsersRoute, async (c) =>
c.json(await listUsers(c.req.valid("query")), 200),
)
@@ -463,6 +532,8 @@ const admin = apiRouter()
c.json(await listAuditLog(c.req.valid("query")), 200),
)
.route("/users", adminUserRoutes)
+ .route("/users", adminUserAccountRoutes)
+ .route("/roles", adminRoleRoutes)
.route("/", adminUserSecurityRoutes);
export default admin;
diff --git a/apps/api/src/admin/response.ts b/apps/api/src/admin/response.ts
index 4a6e28122..22b5b4b32 100644
--- a/apps/api/src/admin/response.ts
+++ b/apps/api/src/admin/response.ts
@@ -69,6 +69,10 @@ export const adminWorkspaceArchiveStateSchema = z
})
.openapi("AdminWorkspaceArchiveState");
+export const adminDeletedUserSchema = z
+ .object({ id: z.string() })
+ .openapi("AdminDeletedUser");
+
export const adminDeletedWorkspaceSchema = z
.object({ id: z.string() })
.openapi("AdminDeletedWorkspace");
diff --git a/apps/api/src/admin/role-routes.ts b/apps/api/src/admin/role-routes.ts
new file mode 100644
index 000000000..4d3311ff1
--- /dev/null
+++ b/apps/api/src/admin/role-routes.ts
@@ -0,0 +1,140 @@
+import {
+ apiRouter,
+ createRoute,
+ errorResponse,
+ jsonResponse,
+} from "../openapi";
+import { requireUserSession } from "../utils/require-user-session";
+import { adminAuditRequest } from "./audit/admin-audit-request";
+import createInstanceRole from "./controllers/create-instance-role";
+import deleteInstanceRole from "./controllers/delete-instance-role";
+import listInstanceRoles from "./controllers/list-instance-roles";
+import updateInstanceRole from "./controllers/update-instance-role";
+import { requireInstancePermission } from "./roles/require-instance-permission";
+import {
+ deletedInstanceRoleSchema,
+ instanceRoleBody,
+ instanceRoleListSchema,
+ instanceRoleParam,
+ instanceRoleSchema,
+} from "./roles/schema";
+
+const forbidden = errorResponse(
+ "The caller lacks the instance permission or used an API key",
+);
+const roleBody = {
+ required: true,
+ content: { "application/json": { schema: instanceRoleBody } },
+};
+
+const listRolesRoute = createRoute({
+ method: "get",
+ operationId: "listInstanceRoles",
+ path: "/",
+ tags: ["Admin"],
+ summary: "List custom instance roles",
+ description:
+ "List the custom instance roles with their permissions and how many users have each. The built-in `admin` (every permission) and `user` (none) roles are not listed. Requires the `users:read` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:read"),
+ ] as const,
+ responses: {
+ 200: jsonResponse("Custom instance roles by name", instanceRoleListSchema),
+ 403: forbidden,
+ },
+});
+
+const createRoleRoute = createRoute({
+ method: "post",
+ operationId: "createInstanceRole",
+ path: "/",
+ tags: ["Admin"],
+ summary: "Create a custom instance role",
+ description:
+ "Create a role that grants a set of instance permissions. Assign it to users by name. Requires the `roles:manage` permission, which only the built-in `admin` role has; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("roles:manage"),
+ ] as const,
+ request: { body: roleBody },
+ responses: {
+ 201: jsonResponse("The new role", instanceRoleSchema),
+ 400: errorResponse("Invalid name or permission"),
+ 403: forbidden,
+ 409: errorResponse("The name is taken or reserved"),
+ },
+});
+
+const updateRoleRoute = createRoute({
+ method: "put",
+ operationId: "updateInstanceRole",
+ path: "/{roleId}",
+ tags: ["Admin"],
+ summary: "Update a custom instance role",
+ description:
+ "Rename a role or replace its permissions. Users who have it keep it under the new name, and permission changes apply to their next request. Requires the `roles:manage` permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("roles:manage"),
+ ] as const,
+ request: { params: instanceRoleParam, body: roleBody },
+ responses: {
+ 200: jsonResponse("The updated role", instanceRoleSchema),
+ 400: errorResponse("Invalid name or permission"),
+ 403: forbidden,
+ 404: errorResponse("Role not found"),
+ 409: errorResponse("The name is taken or reserved"),
+ },
+});
+
+const deleteRoleRoute = createRoute({
+ method: "delete",
+ operationId: "deleteInstanceRole",
+ path: "/{roleId}",
+ tags: ["Admin"],
+ summary: "Delete a custom instance role",
+ description:
+ "Delete a role that no user has. Requires the `roles:manage` permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("roles:manage"),
+ ] as const,
+ request: { params: instanceRoleParam },
+ responses: {
+ 200: jsonResponse("The deleted role", deletedInstanceRoleSchema),
+ 403: forbidden,
+ 404: errorResponse("Role not found"),
+ 409: errorResponse("Users still have this role (code ROLE_IN_USE)"),
+ },
+});
+
+const adminRoleRoutes = apiRouter()
+ .openapi(listRolesRoute, async (c) => c.json(await listInstanceRoles(), 200))
+ .openapi(createRoleRoute, async (c) =>
+ c.json(
+ await createInstanceRole(c.req.valid("json"), adminAuditRequest(c)),
+ 201,
+ ),
+ )
+ .openapi(updateRoleRoute, async (c) =>
+ c.json(
+ await updateInstanceRole(
+ c.req.valid("param").roleId,
+ c.req.valid("json"),
+ adminAuditRequest(c),
+ ),
+ 200,
+ ),
+ )
+ .openapi(deleteRoleRoute, async (c) =>
+ c.json(
+ await deleteInstanceRole(
+ c.req.valid("param").roleId,
+ adminAuditRequest(c),
+ ),
+ 200,
+ ),
+ );
+
+export default adminRoleRoutes;
diff --git a/apps/api/src/admin/roles/assert-assignable-role.ts b/apps/api/src/admin/roles/assert-assignable-role.ts
new file mode 100644
index 000000000..af957a362
--- /dev/null
+++ b/apps/api/src/admin/roles/assert-assignable-role.ts
@@ -0,0 +1,47 @@
+import { isCustomRolePermission } from "@kaneo/permissions";
+import { eq } from "drizzle-orm";
+import { instanceRoleTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+import { holdsAll, type InstanceAccess } from "./get-instance-access";
+
+/**
+ * Check the caller may give someone `role`. Call inside the transaction that
+ * assigns it: the role row stays share-locked so it can't be deleted or
+ * renamed before the assignment commits.
+ */
+export async function assertAssignableRole(
+ role: string,
+ actor: InstanceAccess,
+ tx: DbOrTx,
+) {
+ if (role === "user") return;
+ if (role === "admin") {
+ if (!actor.isAdmin) {
+ throw new ApiError(403, {
+ code: "ADMIN_ROLE_REQUIRED",
+ message: "Only administrators can make someone an administrator.",
+ });
+ }
+ return;
+ }
+
+ const [row] = await tx
+ .select({ permissions: instanceRoleTable.permissions })
+ .from(instanceRoleTable)
+ .where(eq(instanceRoleTable.name, role))
+ .limit(1)
+ .for("share");
+ if (!row) {
+ throw new ApiError(400, {
+ code: "UNKNOWN_ROLE",
+ message: "This role does not exist.",
+ });
+ }
+ if (!holdsAll(actor, row.permissions.filter(isCustomRolePermission))) {
+ throw new ApiError(403, {
+ code: "ROLE_EXCEEDS_YOUR_PERMISSIONS",
+ message: "You can't give a role with permissions you don't have.",
+ });
+ }
+}
diff --git a/apps/api/src/admin/roles/assert-known-instance-roles.ts b/apps/api/src/admin/roles/assert-known-instance-roles.ts
new file mode 100644
index 000000000..1119d3ffe
--- /dev/null
+++ b/apps/api/src/admin/roles/assert-known-instance-roles.ts
@@ -0,0 +1,51 @@
+import { isBuiltInInstanceRole } from "@kaneo/permissions";
+import { APIError } from "better-auth/api";
+import { inArray } from "drizzle-orm";
+import db from "../../database";
+import { instanceRoleTable } from "../../database/schema";
+
+const ROLE_PATHS = new Set([
+ "/admin/create-user",
+ "/admin/set-role",
+ "/admin/update-user",
+]);
+
+type RoleRequest = {
+ path: string;
+ body?: { role?: unknown; data?: { role?: unknown } } | null;
+};
+
+function requestedRole(ctx: RoleRequest) {
+ if (ctx.path === "/admin/update-user") return ctx.body?.data?.role;
+ return ctx.body?.role ?? ctx.body?.data?.role;
+}
+
+/**
+ * better-auth's admin endpoints accept any role string. Only built-in roles
+ * and existing custom roles may be stored, so a role created later can't
+ * silently grant permissions to users who were given its name earlier.
+ */
+export async function assertKnownInstanceRoles(ctx: RoleRequest) {
+ if (!ROLE_PATHS.has(ctx.path)) return;
+ const role = requestedRole(ctx);
+ if (role === undefined) return;
+ const values = Array.isArray(role) ? role : [role];
+ // Non-strings are left to better-auth's own validation.
+ const names = values
+ .filter((value): value is string => typeof value === "string")
+ .flatMap((value) => value.split(","))
+ .filter((name) => !isBuiltInInstanceRole(name));
+ if (names.length === 0) return;
+
+ const existing = await db
+ .select({ name: instanceRoleTable.name })
+ .from(instanceRoleTable)
+ .where(inArray(instanceRoleTable.name, names));
+ const known = new Set(existing.map((row) => row.name));
+ if (names.some((name) => !known.has(name))) {
+ throw new APIError("BAD_REQUEST", {
+ code: "UNKNOWN_ROLE",
+ message: "This role does not exist.",
+ });
+ }
+}
diff --git a/apps/api/src/admin/roles/assert-role-name-available.ts b/apps/api/src/admin/roles/assert-role-name-available.ts
new file mode 100644
index 000000000..7c13a858c
--- /dev/null
+++ b/apps/api/src/admin/roles/assert-role-name-available.ts
@@ -0,0 +1,39 @@
+import { isBuiltInInstanceRole } from "@kaneo/permissions";
+import { and, eq, ne, sql } from "drizzle-orm";
+import { instanceRoleTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+
+/**
+ * Names are unique and can't shadow a built-in role. The transaction lock
+ * makes concurrent creates and renames of the same name wait for each other.
+ */
+export async function assertRoleNameAvailable(
+ name: string,
+ tx: DbOrTx,
+ exceptRoleId?: string,
+) {
+ if (isBuiltInInstanceRole(name)) {
+ throw new ApiError(409, {
+ code: "ROLE_NAME_RESERVED",
+ message: "This name is reserved for a built-in role.",
+ });
+ }
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(2026, 1813)`);
+ const [existing] = await tx
+ .select({ id: instanceRoleTable.id })
+ .from(instanceRoleTable)
+ .where(
+ and(
+ eq(instanceRoleTable.name, name),
+ exceptRoleId ? ne(instanceRoleTable.id, exceptRoleId) : undefined,
+ ),
+ )
+ .limit(1);
+ if (existing) {
+ throw new ApiError(409, {
+ code: "ROLE_NAME_TAKEN",
+ message: "A role with this name already exists.",
+ });
+ }
+}
diff --git a/apps/api/src/admin/roles/find-instance-role.ts b/apps/api/src/admin/roles/find-instance-role.ts
new file mode 100644
index 000000000..371a04c08
--- /dev/null
+++ b/apps/api/src/admin/roles/find-instance-role.ts
@@ -0,0 +1,47 @@
+import { isCustomRolePermission } from "@kaneo/permissions";
+import { eq, sql } from "drizzle-orm";
+import { instanceRoleTable } from "../../database/schema";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+
+// Qualified by hand: Drizzle leaves columns bare in one-table selects, and a
+// bare "name" would resolve to the user's name inside the subquery.
+const userCount = sql<number>`(
+ SELECT count(*)::int FROM "user" u
+ WHERE "instance_role"."name" = ANY(string_to_array(u."role", ','))
+)`;
+
+export const instanceRoleColumns = {
+ id: instanceRoleTable.id,
+ name: instanceRoleTable.name,
+ permissions: instanceRoleTable.permissions,
+ createdAt: instanceRoleTable.createdAt,
+ updatedAt: instanceRoleTable.updatedAt,
+ userCount,
+};
+
+type InstanceRoleRow = {
+ id: string;
+ name: string;
+ permissions: string[];
+ createdAt: Date;
+ updatedAt: Date;
+ userCount: number;
+};
+
+export function toInstanceRole(row: InstanceRoleRow) {
+ return {
+ ...row,
+ permissions: row.permissions.filter(isCustomRolePermission),
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ };
+}
+
+export async function findInstanceRole(roleId: string, database: DbOrTx) {
+ const [row] = await database
+ .select(instanceRoleColumns)
+ .from(instanceRoleTable)
+ .where(eq(instanceRoleTable.id, roleId))
+ .limit(1);
+ return row ? toInstanceRole(row) : undefined;
+}
diff --git a/apps/api/src/admin/roles/get-instance-access.ts b/apps/api/src/admin/roles/get-instance-access.ts
new file mode 100644
index 000000000..4dc2b64c3
--- /dev/null
+++ b/apps/api/src/admin/roles/get-instance-access.ts
@@ -0,0 +1,66 @@
+import {
+ CUSTOM_ROLE_PERMISSIONS,
+ INSTANCE_PERMISSIONS,
+ type InstancePermission,
+ isBuiltInInstanceRole,
+ parseInstanceRoles,
+} from "@kaneo/permissions";
+import { eq, inArray } from "drizzle-orm";
+import db from "../../database";
+import { instanceRoleTable, userTable } from "../../database/schema";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+
+export type InstanceAccess = {
+ isAdmin: boolean;
+ permissions: InstancePermission[];
+};
+
+const NO_ACCESS: InstanceAccess = { isAdmin: false, permissions: [] };
+
+/** The built-in admin role grants everything; custom roles what they list. */
+export async function getRoleAccess(
+ role: string | null | undefined,
+ database: DbOrTx = db,
+): Promise<InstanceAccess> {
+ const names = parseInstanceRoles(role);
+ if (names.includes("admin")) {
+ return { isAdmin: true, permissions: [...INSTANCE_PERMISSIONS] };
+ }
+ const custom = names.filter((name) => !isBuiltInInstanceRole(name));
+ if (custom.length === 0) return NO_ACCESS;
+
+ const rows = await database
+ .select({ permissions: instanceRoleTable.permissions })
+ .from(instanceRoleTable)
+ .where(inArray(instanceRoleTable.name, custom));
+ const granted = new Set(rows.flatMap((row) => row.permissions));
+ return {
+ isAdmin: false,
+ permissions: CUSTOM_ROLE_PERMISSIONS.filter((permission) =>
+ granted.has(permission),
+ ),
+ };
+}
+
+/** A user's instance permissions, read fresh from their stored role. */
+export async function getUserAccess(userId: string, database: DbOrTx = db) {
+ const [user] = await database
+ .select({ role: userTable.role })
+ .from(userTable)
+ .where(eq(userTable.id, userId))
+ .limit(1);
+ return user ? getRoleAccess(user.role, database) : NO_ACCESS;
+}
+
+/** Whether `access` holds every permission in `permissions`. */
+export function holdsAll(
+ access: InstanceAccess,
+ permissions: readonly string[],
+) {
+ return (
+ access.isAdmin ||
+ permissions.every((permission) =>
+ (access.permissions as readonly string[]).includes(permission),
+ )
+ );
+}
diff --git a/apps/api/src/admin/roles/lock-instance-role.ts b/apps/api/src/admin/roles/lock-instance-role.ts
new file mode 100644
index 000000000..28b5c07b1
--- /dev/null
+++ b/apps/api/src/admin/roles/lock-instance-role.ts
@@ -0,0 +1,25 @@
+import { eq } from "drizzle-orm";
+import { instanceRoleTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+
+/** The role row, locked until the transaction ends, or a 404. */
+export async function lockInstanceRole(roleId: string, tx: DbOrTx) {
+ const [role] = await tx
+ .select({
+ id: instanceRoleTable.id,
+ name: instanceRoleTable.name,
+ permissions: instanceRoleTable.permissions,
+ })
+ .from(instanceRoleTable)
+ .where(eq(instanceRoleTable.id, roleId))
+ .limit(1)
+ .for("update");
+ if (!role) {
+ throw new ApiError(404, {
+ code: "ROLE_NOT_FOUND",
+ message: "Role not found",
+ });
+ }
+ return role;
+}
diff --git a/apps/api/src/admin/roles/require-instance-permission.ts b/apps/api/src/admin/roles/require-instance-permission.ts
new file mode 100644
index 000000000..5cd80e6a2
--- /dev/null
+++ b/apps/api/src/admin/roles/require-instance-permission.ts
@@ -0,0 +1,19 @@
+import type { InstancePermission } from "@kaneo/permissions";
+import type { Context, Next } from "hono";
+import { ApiError } from "../../errors/api-error";
+import { getUserAccess } from "./get-instance-access";
+
+/** Admin routes run after `requireUserSession`, so the caller is a user. */
+export function requireInstancePermission(permission: InstancePermission) {
+ return async function requirePermission(c: Context, next: Next) {
+ const access = await getUserAccess(c.get("user").id);
+ if (!access.permissions.includes(permission)) {
+ throw new ApiError(403, {
+ code: "INSTANCE_PERMISSION_REQUIRED",
+ message: "You don't have permission to do this.",
+ missingPermissions: [permission],
+ });
+ }
+ return next();
+ };
+}
diff --git a/apps/api/src/admin/roles/require-manageable-user.ts b/apps/api/src/admin/roles/require-manageable-user.ts
new file mode 100644
index 000000000..43c6dab92
--- /dev/null
+++ b/apps/api/src/admin/roles/require-manageable-user.ts
@@ -0,0 +1,26 @@
+import type { Context, Next } from "hono";
+import { ApiError } from "../../errors/api-error";
+import { getUserAccess, holdsAll } from "./get-instance-access";
+
+/**
+ * Only built-in admins may act on users who hold permissions they lack, so a
+ * custom role can't take over, lock out, or demote a more powerful account.
+ */
+export async function assertCanManageUser(actorId: string, targetId: string) {
+ const actor = await getUserAccess(actorId);
+ if (actor.isAdmin) return;
+ const target = await getUserAccess(targetId);
+ if (!holdsAll(actor, target.permissions)) {
+ throw new ApiError(403, {
+ code: "USER_HAS_MORE_PERMISSIONS",
+ message: "You can't manage a user who has permissions you don't have.",
+ });
+ }
+}
+
+/** For routes with a `{userId}` path parameter; an unknown user is left to the route. */
+export async function requireManageableUser(c: Context, next: Next) {
+ const targetId = c.req.param("userId");
+ if (targetId) await assertCanManageUser(c.get("user").id, targetId);
+ return next();
+}
diff --git a/apps/api/src/admin/roles/schema.ts b/apps/api/src/admin/roles/schema.ts
new file mode 100644
index 000000000..752639083
--- /dev/null
+++ b/apps/api/src/admin/roles/schema.ts
@@ -0,0 +1,65 @@
+import {
+ CUSTOM_ROLE_PERMISSIONS,
+ INSTANCE_PERMISSIONS,
+ INSTANCE_ROLE_NAME_PATTERN,
+} from "@kaneo/permissions";
+import { z } from "../../openapi";
+
+const permissionList = z
+ .array(z.enum(CUSTOM_ROLE_PERMISSIONS))
+ .max(CUSTOM_ROLE_PERMISSIONS.length * 2)
+ .transform((permissions) =>
+ CUSTOM_ROLE_PERMISSIONS.filter((permission) =>
+ permissions.includes(permission),
+ ),
+ )
+ .openapi({
+ description:
+ "Instance permissions the role grants. `roles:manage` belongs to the built-in admin role only.",
+ });
+
+export const instanceRoleBody = z.object({
+ name: z
+ .string()
+ .regex(
+ INSTANCE_ROLE_NAME_PATTERN,
+ "Use 2-32 lowercase letters, digits, or hyphens, starting with a letter",
+ )
+ .openapi({
+ description:
+ "Lowercase letters, digits and hyphens, starting with a letter. `admin` and `user` are reserved.",
+ example: "support",
+ }),
+ permissions: permissionList,
+});
+
+export const instanceRoleParam = z.object({ roleId: z.string().min(1) });
+
+const isoTimestamp = z.string().openapi({ format: "date-time" });
+
+export const instanceRoleSchema = z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ permissions: z.array(z.enum(CUSTOM_ROLE_PERMISSIONS)),
+ userCount: z.number().int().openapi({
+ description: "Users who currently have this role.",
+ }),
+ createdAt: isoTimestamp,
+ updatedAt: isoTimestamp,
+ })
+ .openapi("InstanceRole");
+
+export const instanceRoleListSchema = z
+ .object({ roles: z.array(instanceRoleSchema) })
+ .openapi("InstanceRoleList");
+
+export const deletedInstanceRoleSchema = z
+ .object({ id: z.string() })
+ .openapi("DeletedInstanceRole");
+
+export const instanceAccessSchema = z
+ .object({
+ permissions: z.array(z.enum(INSTANCE_PERMISSIONS)),
+ })
+ .openapi("InstanceAccess");
diff --git a/apps/api/src/admin/schema.ts b/apps/api/src/admin/schema.ts
index caab8f18d..e36f1dfc9 100644
--- a/apps/api/src/admin/schema.ts
+++ b/apps/api/src/admin/schema.ts
@@ -7,8 +7,9 @@ export const listAdminUsersQuery = z.object({
status: z.enum(["active", "deactivated"]).optional().openapi({
description: "Only active or only deactivated accounts.",
}),
- role: z.enum(["admin", "user"]).optional().openapi({
- description: "Only instance administrators, or only everyone else.",
+ role: z.string().min(1).max(64).optional().openapi({
+ description:
+ "Only users with this instance role: `admin`, a custom role name, or `user` for everyone without an administrator or custom role.",
}),
emailVerified: z
.enum(["true", "false"])
@@ -84,13 +85,29 @@ export const listAdminAuditLogQuery = z.object({
export const adminUserParam = z.object({ userId: z.string().min(1) });
+const instanceRoleName = z.string().min(1).max(64).openapi({
+ description:
+ "Instance role: `admin` administers the instance, `user` has no instance permissions, or the name of a custom role. Only administrators can assign `admin`, and nobody can assign a role with permissions they don't have.",
+});
+
export const createAdminUserBody = z.object({
name: z.string().trim().min(1).max(200),
email: z.email().max(254).openapi({
description:
"The new user's email address. They sign in with it and receive their password link there.",
}),
- role: z.enum(["admin", "user"]).default("user").openapi({
- description: "Instance role: `admin` administers the instance.",
- }),
+ role: instanceRoleName.default("user"),
});
+
+export const updateAdminUserBody = z
+ .object({
+ name: z.string().trim().min(1).max(200).optional(),
+ email: z.email().max(254).optional().openapi({
+ description:
+ "A new address must be verified again. It can't belong to another user.",
+ }),
+ role: instanceRoleName.optional(),
+ })
+ .refine((body) => Object.values(body).some((value) => value !== undefined), {
+ message: "Nothing to update",
+ });
diff --git a/apps/api/src/admin/user-account-routes.ts b/apps/api/src/admin/user-account-routes.ts
new file mode 100644
index 000000000..3cff3d2bc
--- /dev/null
+++ b/apps/api/src/admin/user-account-routes.ts
@@ -0,0 +1,163 @@
+import {
+ apiRouter,
+ createRoute,
+ errorResponse,
+ jsonResponse,
+} from "../openapi";
+import { requireUserSession } from "../utils/require-user-session";
+import { adminAuditRequest } from "./audit/admin-audit-request";
+import deactivateUser from "./controllers/deactivate-user";
+import deleteUser from "./controllers/delete-user";
+import reactivateUser from "./controllers/reactivate-user";
+import updateUser from "./controllers/update-user";
+import { adminDeletedUserSchema, adminUserSchema } from "./response";
+import { requireInstancePermission } from "./roles/require-instance-permission";
+import { requireManageableUser } from "./roles/require-manageable-user";
+import { adminUserParam, updateAdminUserBody } from "./schema";
+
+const forbidden = errorResponse(
+ "The caller lacks the instance permission, the user has permissions the caller lacks, or the request used an API key",
+);
+const notFound = errorResponse("User not found");
+
+const updateUserRoute = createRoute({
+ method: "patch",
+ operationId: "updateAdminUser",
+ path: "/{userId}",
+ tags: ["Admin"],
+ summary: "Update a user",
+ description:
+ "Change a user's name, email, or instance role. A new email must be verified again. You can't change your own role or remove the last administrator. Requires the `users:update` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:update"),
+ requireManageableUser,
+ ] as const,
+ request: {
+ params: adminUserParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: updateAdminUserBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("The updated user", adminUserSchema),
+ 400: errorResponse(
+ "Invalid fields, an unknown role, your own role, or the last administrator",
+ ),
+ 403: forbidden,
+ 404: notFound,
+ 409: errorResponse("Another user has this email address"),
+ },
+});
+
+const deactivateUserRoute = createRoute({
+ method: "post",
+ operationId: "deactivateAdminUser",
+ path: "/{userId}/deactivate",
+ tags: ["Admin"],
+ summary: "Deactivate a user",
+ description:
+ "Block a user from signing in and end all of their sessions. Their data stays. Requires the `users:disable` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:disable"),
+ requireManageableUser,
+ ] as const,
+ request: { params: adminUserParam },
+ responses: {
+ 200: jsonResponse("The deactivated user", adminUserSchema),
+ 400: errorResponse("You can't deactivate yourself"),
+ 403: forbidden,
+ 404: notFound,
+ },
+});
+
+const reactivateUserRoute = createRoute({
+ method: "post",
+ operationId: "reactivateAdminUser",
+ path: "/{userId}/reactivate",
+ tags: ["Admin"],
+ summary: "Reactivate a user",
+ description:
+ "Let a deactivated user sign in again. Requires the `users:disable` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:disable"),
+ requireManageableUser,
+ ] as const,
+ request: { params: adminUserParam },
+ responses: {
+ 200: jsonResponse("The reactivated user", adminUserSchema),
+ 403: forbidden,
+ 404: notFound,
+ },
+});
+
+const deleteUserRoute = createRoute({
+ method: "delete",
+ operationId: "deleteAdminUser",
+ path: "/{userId}",
+ tags: ["Admin"],
+ summary: "Delete a user",
+ description:
+ "Permanently delete a user's account, the same way they could themselves: workspaces where they are the only member are deleted, and they leave the others. Fails while they are the only owner of a workspace with other members. Requires the `users:delete` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:delete"),
+ requireManageableUser,
+ ] as const,
+ request: { params: adminUserParam },
+ responses: {
+ 200: jsonResponse("The deleted user", adminDeletedUserSchema),
+ 400: errorResponse("You can't delete yourself"),
+ 403: forbidden,
+ 404: notFound,
+ 409: errorResponse(
+ "The user is the only owner of a shared workspace, or one of their workspaces has an active subscription",
+ ),
+ },
+});
+
+const adminUserAccountRoutes = apiRouter()
+ .openapi(updateUserRoute, async (c) =>
+ c.json(
+ await updateUser(
+ {
+ userId: c.req.valid("param").userId,
+ actorId: c.get("userId"),
+ ...c.req.valid("json"),
+ },
+ adminAuditRequest(c),
+ ),
+ 200,
+ ),
+ )
+ .openapi(deactivateUserRoute, async (c) =>
+ c.json(
+ await deactivateUser(
+ c.req.valid("param").userId,
+ c.get("userId"),
+ adminAuditRequest(c),
+ ),
+ 200,
+ ),
+ )
+ .openapi(reactivateUserRoute, async (c) =>
+ c.json(
+ await reactivateUser(c.req.valid("param").userId, adminAuditRequest(c)),
+ 200,
+ ),
+ )
+ .openapi(deleteUserRoute, async (c) =>
+ c.json(
+ await deleteUser(
+ c.req.valid("param").userId,
+ c.get("userId"),
+ adminAuditRequest(c),
+ ),
+ 200,
+ ),
+ );
+
+export default adminUserAccountRoutes;
diff --git a/apps/api/src/admin/user-routes.ts b/apps/api/src/admin/user-routes.ts
index 0ea8077c1..ca985e80a 100644
--- a/apps/api/src/admin/user-routes.ts
+++ b/apps/api/src/admin/user-routes.ts
@@ -7,7 +7,8 @@ import {
import { MAX_AVATAR_BYTES, MAX_AVATAR_REQUEST_BYTES } from "../user/avatar";
import { uploadAvatarBody } from "../user/schema";
import { boundedRequestBody } from "../utils/bounded-request-body";
-import { requireInstanceAdmin } from "../utils/require-instance-admin";
+import { requireInstancePermission } from "./roles/require-instance-permission";
+import { requireManageableUser } from "./roles/require-manageable-user";
import { requireUserSession } from "../utils/require-user-session";
import { adminAuditRequest } from "./audit/admin-audit-request";
import createUser from "./controllers/create-user";
@@ -26,7 +27,7 @@ import {
import { adminUserParam, createAdminUserBody } from "./schema";
const forbidden = errorResponse(
- "The caller is not an instance administrator or is authenticated with an API key",
+ "The caller lacks the instance permission or is authenticated with an API key",
);
const notFound = errorResponse("User not found");
const emailErrors = {
@@ -44,8 +45,11 @@ const createUserRoute = createRoute({
tags: ["Admin"],
summary: "Create a user",
description:
- "Create an account with an instance role. No password is set or returned. When password sign-in is available, the user is emailed a single-use link, valid for 2 days, to choose their own password. When password registration or the login form is disabled, the account is created with a verified email so the user can sign in with single sign-on, and no email is sent. Registration restrictions do not apply to administrators.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Create an account with an instance role. No password is set or returned. When password sign-in is available, the user is emailed a single-use link, valid for 2 days, to choose their own password. When password registration or the login form is disabled, the account is created with a verified email so the user can sign in with single sign-on, and no email is sent. Registration restrictions do not apply to administrators. Requires the `users:create` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:create"),
+ ] as const,
request: {
body: {
required: true,
@@ -67,8 +71,12 @@ const sendPasswordResetRoute = createRoute({
tags: ["Admin"],
summary: "Email a password reset link",
description:
- "Email the user a single-use link to choose a new password, using the regular reset lifetime. The link is never returned to the administrator.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Email the user a single-use link to choose a new password, using the regular reset lifetime. The link is never returned to the administrator. Requires the `users:credentials` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:credentials"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("The email was sent", adminEmailSentSchema),
@@ -85,8 +93,12 @@ const sendVerificationRoute = createRoute({
tags: ["Admin"],
summary: "Email a verification link",
description:
- "Email the user a link, valid for 24 hours, that confirms their email address. The link is never returned to the administrator.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Email the user a link, valid for 24 hours, that confirms their email address. The link is never returned to the administrator. Requires the `users:credentials` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:credentials"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("The email was sent", adminEmailSentSchema),
@@ -103,8 +115,12 @@ const markEmailVerifiedRoute = createRoute({
tags: ["Admin"],
summary: "Mark an email as verified",
description:
- "Mark a non-guest user's email address as verified without asking them, for example so a single sign-on identity with the same address can link to the account.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Mark a non-guest user's email address as verified without asking them, for example so a single sign-on identity with the same address can link to the account. Requires the `users:credentials` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:credentials"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("The email is verified", adminEmailVerifiedSchema),
@@ -125,7 +141,8 @@ const setAvatarRoute = createRoute({
)}KB) for the user and make it their profile picture. Not available when the identity provider manages the user's picture.`,
middleware: [
requireUserSession,
- requireInstanceAdmin,
+ requireInstancePermission("users:update"),
+ requireManageableUser,
boundedRequestBody(MAX_AVATAR_REQUEST_BYTES),
] as const,
request: {
@@ -139,7 +156,7 @@ const setAvatarRoute = createRoute({
200: jsonResponse("The new picture", adminUserAvatarSchema),
400: errorResponse("Unsupported, invalid, or oversized image"),
403: errorResponse(
- "Not an instance administrator, an API key, or the picture is managed by the identity provider",
+ "Missing instance permission, an API key, or the picture is managed by the identity provider",
),
404: notFound,
413: errorResponse("Request body is too large"),
@@ -153,13 +170,17 @@ const removeAvatarRoute = createRoute({
tags: ["Admin"],
summary: "Remove a user's avatar",
description:
- "Remove the user's profile picture. A picture managed by the identity provider can't be removed, but an earlier Kaneo upload can.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Remove the user's profile picture. A picture managed by the identity provider can't be removed, but an earlier Kaneo upload can. Requires the `users:update` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:update"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("Picture removed", adminUserAvatarRemovedSchema),
403: errorResponse(
- "Not an instance administrator, an API key, or the picture is managed by the identity provider",
+ "Missing instance permission, an API key, or the picture is managed by the identity provider",
),
404: notFound,
},
diff --git a/apps/api/src/admin/user-security-routes.ts b/apps/api/src/admin/user-security-routes.ts
index 20e036b51..676ede3e4 100644
--- a/apps/api/src/admin/user-security-routes.ts
+++ b/apps/api/src/admin/user-security-routes.ts
@@ -8,7 +8,8 @@ import {
activeSessionListSchema,
revokedSessionsSchema,
} from "../sessions/response";
-import { requireInstanceAdmin } from "../utils/require-instance-admin";
+import { requireInstancePermission } from "./roles/require-instance-permission";
+import { requireManageableUser } from "./roles/require-manageable-user";
import { requireUserSession } from "../utils/require-user-session";
import { adminAuditRequest } from "./audit/admin-audit-request";
import listUserApiKeys from "./controllers/list-user-api-keys";
@@ -25,7 +26,7 @@ import {
} from "./user-security-schema";
const forbidden = errorResponse(
- "The caller is not an instance administrator or is authenticated with an API key",
+ "The caller lacks the instance permission or is authenticated with an API key",
);
const listSessionsRoute = createRoute({
@@ -35,8 +36,12 @@ const listSessionsRoute = createRoute({
tags: ["Admin"],
summary: "List a user's sessions",
description:
- "List a user's signed-in sessions with device, IP address, and activity. Tokens are never returned. `current` marks the administrator's own session. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "List a user's signed-in sessions with device, IP address, and activity. Tokens are never returned. `current` marks the administrator's own session. Requires the `users:sessions` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:sessions"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("Active sessions", activeSessionListSchema),
@@ -52,8 +57,12 @@ const revokeSessionRoute = createRoute({
tags: ["Admin"],
summary: "Sign out one of a user's sessions",
description:
- "End one session immediately, including its realtime connections, and record it in the audit log. The administrator's own current session can't be ended here; sign out instead.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "End one session immediately, including its realtime connections, and record it in the audit log. The administrator's own current session can't be ended here; sign out instead. Requires the `users:sessions` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:sessions"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserSessionParam },
responses: {
200: jsonResponse("Session signed out", revokedSessionsSchema),
@@ -70,8 +79,12 @@ const revokeSessionsRoute = createRoute({
tags: ["Admin"],
summary: "Sign out all of a user's sessions",
description:
- "End every session of a user immediately, including realtime connections, and record it in the audit log. When administrators target themselves, their current session is kept. API keys keep working; revoke them separately.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "End every session of a user immediately, including realtime connections, and record it in the audit log. When administrators target themselves, their current session is kept. API keys keep working; revoke them separately. Requires the `users:sessions` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:sessions"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("Sessions signed out", revokedSessionsSchema),
@@ -87,8 +100,12 @@ const listApiKeysRoute = createRoute({
tags: ["Admin"],
summary: "List a user's API keys",
description:
- "List a user's API keys with their name, start, status, and dates. The key and its hash are never returned. Requires an instance administrator session; API keys are rejected.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "List a user's API keys with their name, start, status, and dates. The key and its hash are never returned. Requires the `users:api_keys` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:api_keys"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserParam },
responses: {
200: jsonResponse("API keys, newest first", adminApiKeyListSchema),
@@ -104,8 +121,12 @@ const revokeApiKeyRoute = createRoute({
tags: ["Admin"],
summary: "Revoke a user's API key",
description:
- "Delete a user's API key so it stops working immediately, and record it in the audit log.",
- middleware: [requireUserSession, requireInstanceAdmin] as const,
+ "Delete a user's API key so it stops working immediately, and record it in the audit log. Requires the `users:api_keys` instance permission; API keys are rejected.",
+ middleware: [
+ requireUserSession,
+ requireInstancePermission("users:api_keys"),
+ requireManageableUser,
+ ] as const,
request: { params: adminUserApiKeyParam },
responses: {
200: jsonResponse("API key revoked", adminRevokedApiKeySchema),
diff --git a/apps/api/src/admin/users/lock-admin-target-user.ts b/apps/api/src/admin/users/lock-admin-target-user.ts
new file mode 100644
index 000000000..d5635e623
--- /dev/null
+++ b/apps/api/src/admin/users/lock-admin-target-user.ts
@@ -0,0 +1,26 @@
+import { eq } from "drizzle-orm";
+import { userTable } from "../../database/schema";
+import { ApiError } from "../../errors/api-error";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+
+/** The user an admin action changes, locked until the transaction ends. */
+export async function lockAdminTargetUser(userId: string, tx: DbOrTx) {
+ const [user] = await tx
+ .select({
+ id: userTable.id,
+ name: userTable.name,
+ email: userTable.email,
+ emailVerified: userTable.emailVerified,
+ role: userTable.role,
+ banned: userTable.banned,
+ banExpires: userTable.banExpires,
+ })
+ .from(userTable)
+ .where(eq(userTable.id, userId))
+ .limit(1)
+ .for("update");
+ if (!user) {
+ throw new ApiError(404, { code: "NOT_FOUND", message: "User not found" });
+ }
+ return user;
+}
diff --git a/apps/api/src/admin/users/read-admin-user.ts b/apps/api/src/admin/users/read-admin-user.ts
new file mode 100644
index 000000000..2d74f2d6f
--- /dev/null
+++ b/apps/api/src/admin/users/read-admin-user.ts
@@ -0,0 +1,15 @@
+import { eq } from "drizzle-orm";
+import { userTable } from "../../database/schema";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+import { adminUserColumns, toAdminUser } from "./admin-user-columns";
+
+/** A user as the admin directory lists them. */
+export async function readAdminUser(userId: string, database: DbOrTx) {
+ const [row] = await database
+ .select(adminUserColumns)
+ .from(userTable)
+ .where(eq(userTable.id, userId))
+ .limit(1);
+ if (!row) throw new Error("Admin user disappeared");
+ return toAdminUser(row);
+}
diff --git a/apps/api/src/admin/users/reject-self-action.ts b/apps/api/src/admin/users/reject-self-action.ts
new file mode 100644
index 000000000..74857bb68
--- /dev/null
+++ b/apps/api/src/admin/users/reject-self-action.ts
@@ -0,0 +1,11 @@
+import { ApiError } from "../../errors/api-error";
+
+/** Admins can't lock themselves out through the directory. */
+export function rejectSelfAction(
+ actorId: string,
+ userId: string,
+ code: string,
+ message: string,
+) {
+ if (actorId === userId) throw new ApiError(400, { code, message });
+}
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index 7fc9e8049..0bed156dd 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -82,6 +82,7 @@ import { dropArchivedInvitations } from "./workspace/archive/drop-archived-invit
import { satisfies } from "./utils/role-permissions";
import { captureAuthAdminAudit } from "./admin/audit/capture-auth-admin-audit";
import { recordAuthAdminAudit } from "./admin/audit/record-auth-admin-audit";
+import { assertKnownInstanceRoles } from "./admin/roles/assert-known-instance-roles";
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";
@@ -878,6 +879,7 @@ export const auth = betterAuth({
),
);
}
+ await assertKnownInstanceRoles(ctx);
// Before removal prep deletes account data the entry needs to name.
await captureAuthAdminAudit(ctx, (headers) =>
auth.api.getSession({ headers, query: { disableRefresh: true } }),
diff --git a/apps/api/src/database/auth-adapter.ts b/apps/api/src/database/auth-adapter.ts
index fb6da7345..c8fb9f843 100644
--- a/apps/api/src/database/auth-adapter.ts
+++ b/apps/api/src/database/auth-adapter.ts
@@ -6,11 +6,9 @@ import {
drizzleAdapter,
} from "better-auth/adapters/drizzle";
import { APIError } from "better-auth/api";
-import { asc, count, eq, inArray, sql } from "drizzle-orm";
-import {
- hasInstanceAdminRole,
- instanceAdminRoleSql,
-} from "../utils/instance-admin-role";
+import { asc, eq, inArray } from "drizzle-orm";
+import { hasOtherInstanceAdmin } from "../utils/has-other-instance-admin";
+import { hasInstanceAdminRole } from "../utils/instance-admin-role";
import db, { schema } from ".";
type OtherSessionRevocationAdapter = DBAdapter & {
@@ -151,26 +149,20 @@ export function authDatabaseAdapter(config: DrizzleAdapterConfig) {
}
return db.transaction(async (tx) => {
- // Serialize role removals across API instances, keeping the count
- // and write in the same transaction so cross-demotions cannot race.
- await tx.execute(sql`SELECT pg_advisory_xact_lock(2026, 1732)`);
const transactionAdapter = drizzleAdapter(tx, config)(options);
const user = await transactionAdapter.findOne<{ role?: string }>({
model: data.model,
where: data.where,
});
- if (hasInstanceAdminRole(user?.role)) {
- const [admins] = await tx
- .select({ value: count() })
- .from(schema.userTable)
- .where(instanceAdminRoleSql(schema.userTable.role));
- if ((admins?.value ?? 0) <= 1) {
- throw new APIError("BAD_REQUEST", {
- code: "CANNOT_REMOVE_LAST_ADMIN",
- message: "The instance must have at least one administrator.",
- });
- }
+ if (
+ hasInstanceAdminRole(user?.role) &&
+ !(await hasOtherInstanceAdmin(tx))
+ ) {
+ throw new APIError("BAD_REQUEST", {
+ code: "CANNOT_REMOVE_LAST_ADMIN",
+ message: "The instance must have at least one administrator.",
+ });
}
return transactionAdapter.update<T>(data);
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.ts
index 93225bfe7..0b5be1a12 100644
--- a/apps/api/src/database/index.ts
+++ b/apps/api/src/database/index.ts
@@ -41,6 +41,7 @@ import {
accountTable,
activityTable,
adminAuditLogTable,
+ instanceRoleTable,
apikeyTable,
assetTable,
billingEventTable,
@@ -92,6 +93,7 @@ export const schema = {
storageCleanupTable,
accountTable,
adminAuditLogTable,
+ instanceRoleTable,
assetTable,
activityTable,
apikeyTable,
diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.ts
index 6cf538ca6..99e3893b4 100644
--- a/apps/api/src/database/schema.ts
+++ b/apps/api/src/database/schema.ts
@@ -175,6 +175,26 @@ export const adminAuditLogTable = pgTable(
],
);
+// Custom instance roles. Users hold them by name in their comma-separated
+// `user.role`, next to the built-in `admin` and `user` roles.
+export const instanceRoleTable = pgTable("instance_role", {
+ id: text("id")
+ .$defaultFn(() => createId())
+ .primaryKey(),
+ name: text("name").notNull().unique(),
+ permissions: text("permissions")
+ .array()
+ .notNull()
+ .default(sql`'{}'`),
+ createdAt: timestamp("created_at", { mode: "date" })
+ .default(utcNow)
+ .notNull(),
+ updatedAt: timestamp("updated_at", { mode: "date" })
+ .default(utcNow)
+ .$onUpdate(() => new Date())
+ .notNull(),
+});
+
export const verificationTable = pgTable(
"verification",
{
diff --git a/apps/api/src/utils/has-other-instance-admin.ts b/apps/api/src/utils/has-other-instance-admin.ts
new file mode 100644
index 000000000..e15f0d10a
--- /dev/null
+++ b/apps/api/src/utils/has-other-instance-admin.ts
@@ -0,0 +1,18 @@
+import { count, sql } from "drizzle-orm";
+import { schema } from "../database";
+import type { DbOrTx } from "../project-access/db-or-tx";
+import { instanceAdminRoleSql } from "./instance-admin-role";
+
+/**
+ * Whether an admin would remain after one loses the role. Call inside the
+ * transaction that removes it: the advisory lock serializes removals across
+ * API instances, so two admins can't demote each other at the same time.
+ */
+export async function hasOtherInstanceAdmin(tx: DbOrTx) {
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(2026, 1732)`);
+ const [admins] = await tx
+ .select({ value: count() })
+ .from(schema.userTable)
+ .where(instanceAdminRoleSql(schema.userTable.role));
+ return (admins?.value ?? 0) > 1;
+}
diff --git a/tests/api-integration/admin-instance-permissions.test.ts b/tests/api-integration/admin-instance-permissions.test.ts
new file mode 100644
index 000000000..6a7bca916
--- /dev/null
+++ b/tests/api-integration/admin-instance-permissions.test.ts
@@ -0,0 +1,262 @@
+import { randomUUID } from "node:crypto";
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { readErrorBody } from "./helpers/error-body";
+import {
+ insertInstanceRole,
+ insertUser,
+ signInWithRole,
+} from "./helpers/admin/instance-roles";
+import { resetTestDatabase } from "./helpers/database";
+
+// Every instance permission a custom role can hold.
+const CUSTOM_PERMISSIONS = [
+ "users:read",
+ "users:create",
+ "users:update",
+ "users:disable",
+ "users:delete",
+ "users:credentials",
+ "users:sessions",
+ "users:api_keys",
+ "workspaces:read",
+ "workspaces:manage",
+ "workspaces:archive",
+ "workspaces:delete",
+ "audit:read",
+ "system:read",
+ "instance:settings",
+];
+
+type Ids = { userId: string; workspaceId: string; roleId: string };
+type Route = {
+ permission: string;
+ method: string;
+ path: (ids: Ids) => string;
+ body?: (ids: Ids) => unknown;
+};
+
+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString("base64");
+
+const routes: Route[] = [
+ { permission: "users:read", method: "GET", path: () => "/users" },
+ { permission: "users:read", method: "GET", path: () => "/roles" },
+ {
+ permission: "users:create",
+ method: "POST",
+ path: () => "/users",
+ body: () => ({ name: "New", email: `${randomUUID()}@example.com` }),
+ },
+ {
+ permission: "users:update",
+ method: "PATCH",
+ path: (ids) => `/users/${ids.userId}`,
+ body: () => ({ name: "Renamed" }),
+ },
+ {
+ permission: "users:update",
+ method: "PUT",
+ path: (ids) => `/users/${ids.userId}/avatar`,
+ body: () => ({ contentType: "image/png", data: PNG }),
+ },
+ {
+ permission: "users:update",
+ method: "DELETE",
+ path: (ids) => `/users/${ids.userId}/avatar`,
+ },
+ {
+ permission: "users:disable",
+ method: "POST",
+ path: (ids) => `/users/${ids.userId}/deactivate`,
+ },
+ {
+ permission: "users:disable",
+ method: "POST",
+ path: (ids) => `/users/${ids.userId}/reactivate`,
+ },
+ {
+ permission: "users:delete",
+ method: "DELETE",
+ path: (ids) => `/users/${ids.userId}`,
+ },
+ {
+ permission: "users:credentials",
+ method: "POST",
+ path: (ids) => `/users/${ids.userId}/password-reset-email`,
+ },
+ {
+ permission: "users:credentials",
+ method: "POST",
+ path: (ids) => `/users/${ids.userId}/verification-email`,
+ },
+ {
+ permission: "users:credentials",
+ method: "PUT",
+ path: (ids) => `/users/${ids.userId}/email-verified`,
+ },
+ {
+ permission: "users:sessions",
+ method: "GET",
+ path: (ids) => `/users/${ids.userId}/sessions`,
+ },
+ {
+ permission: "users:sessions",
+ method: "DELETE",
+ path: (ids) => `/users/${ids.userId}/sessions`,
+ },
+ {
+ permission: "users:sessions",
+ method: "DELETE",
+ path: (ids) => `/users/${ids.userId}/sessions/missing`,
+ },
+ {
+ permission: "users:api_keys",
+ method: "GET",
+ path: (ids) => `/users/${ids.userId}/api-keys`,
+ },
+ {
+ permission: "users:api_keys",
+ method: "DELETE",
+ path: (ids) => `/users/${ids.userId}/api-keys/missing`,
+ },
+ { permission: "workspaces:read", method: "GET", path: () => "/workspaces" },
+ {
+ permission: "workspaces:read",
+ method: "GET",
+ path: (ids) => `/workspaces/${ids.workspaceId}/members`,
+ },
+ {
+ permission: "workspaces:read",
+ method: "GET",
+ path: (ids) => `/workspaces/${ids.workspaceId}/roles`,
+ },
+ {
+ permission: "workspaces:manage",
+ method: "POST",
+ path: (ids) => `/workspaces/${ids.workspaceId}/members`,
+ body: (ids) => ({ userId: ids.userId, role: "member" }),
+ },
+ {
+ permission: "workspaces:manage",
+ method: "PUT",
+ path: (ids) => `/workspaces/${ids.workspaceId}/members/${ids.userId}/role`,
+ body: () => ({ role: "viewer" }),
+ },
+ {
+ permission: "workspaces:manage",
+ method: "DELETE",
+ path: (ids) => `/workspaces/${ids.workspaceId}/members/${ids.userId}`,
+ },
+ {
+ permission: "workspaces:manage",
+ method: "PUT",
+ path: (ids) => `/workspaces/${ids.workspaceId}/owner`,
+ body: (ids) => ({ userId: ids.userId }),
+ },
+ {
+ permission: "workspaces:archive",
+ method: "POST",
+ path: (ids) => `/workspaces/${ids.workspaceId}/archive`,
+ },
+ {
+ permission: "workspaces:archive",
+ method: "POST",
+ path: (ids) => `/workspaces/${ids.workspaceId}/restore`,
+ },
+ {
+ permission: "workspaces:delete",
+ method: "DELETE",
+ path: (ids) => `/workspaces/${ids.workspaceId}`,
+ },
+ { permission: "audit:read", method: "GET", path: () => "/audit-log" },
+ { permission: "system:read", method: "GET", path: () => "/system" },
+ {
+ permission: "system:read",
+ method: "POST",
+ path: () => "/system/test-email",
+ },
+ {
+ permission: "roles:manage",
+ method: "POST",
+ path: () => "/roles",
+ body: () => ({ name: `r${randomUUID().slice(0, 8)}`, permissions: [] }),
+ },
+ {
+ permission: "roles:manage",
+ method: "PUT",
+ path: (ids) => `/roles/${ids.roleId}`,
+ body: () => ({ name: "target-role", permissions: ["audit:read"] }),
+ },
+ {
+ permission: "roles:manage",
+ method: "DELETE",
+ path: (ids) => `/roles/${ids.roleId}`,
+ },
+];
+
+async function setUp() {
+ const { app } = createApp();
+ const target = await insertUser();
+ const workspaceId = `workspace-${randomUUID()}`;
+ await db.insert(schema.workspaceTable).values({
+ id: workspaceId,
+ name: "Permission test",
+ createdAt: new Date(),
+ slug: workspaceId,
+ });
+ const targetRole = await insertInstanceRole("target-role", []);
+ return {
+ app,
+ ids: { userId: target.id, workspaceId, roleId: targetRole.id },
+ };
+}
+
+beforeEach(resetTestDatabase);
+
+describe("instance permissions on admin routes", () => {
+ it("covers every custom role permission", () => {
+ const covered = new Set(routes.map((route) => route.permission));
+ for (const permission of CUSTOM_PERMISSIONS) {
+ if (permission === "instance:settings") continue; // No route uses it yet.
+ expect(covered, permission).toContain(permission);
+ }
+ });
+
+ it.each(
+ routes.map(
+ (route) =>
+ [
+ `${route.method} ${route.path({ userId: ":userId", workspaceId: ":workspaceId", roleId: ":roleId" })}`,
+ route,
+ ] as const,
+ ),
+ )("%s needs its permission", async (_name, route) => {
+ const { app, ids } = await setUp();
+ const others = CUSTOM_PERMISSIONS.filter((p) => p !== route.permission);
+ await insertInstanceRole("lacks", others);
+ const lacking = await signInWithRole(app, "lacks");
+
+ const denied = await lacking.api(route.path(ids), {
+ method: route.method,
+ body: route.body?.(ids),
+ });
+ expect(denied.status).toBe(403);
+ expect(await readErrorBody(denied)).toMatchObject({
+ code: "INSTANCE_PERMISSION_REQUIRED",
+ });
+
+ // roles:manage is only granted by the built-in admin role.
+ const holderRole = route.permission === "roles:manage" ? "admin" : "holds";
+ if (holderRole === "holds") {
+ await insertInstanceRole("holds", [route.permission]);
+ }
+ const holder = await signInWithRole(app, holderRole);
+ const allowed = await holder.api(route.path(ids), {
+ method: route.method,
+ body: route.body?.(ids),
+ });
+ expect(allowed.status, await allowed.clone().text()).not.toBe(403);
+ expect([500, 502]).not.toContain(allowed.status);
+ });
+});
diff --git a/tests/api-integration/admin-instance-roles.test.ts b/tests/api-integration/admin-instance-roles.test.ts
new file mode 100644
index 000000000..e35379998
--- /dev/null
+++ b/tests/api-integration/admin-instance-roles.test.ts
@@ -0,0 +1,432 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } 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 { readErrorBody } from "./helpers/error-body";
+import { readAuditLog } from "./helpers/admin/read-audit-log";
+import {
+ adminApi,
+ insertInstanceRole,
+ insertUser,
+ signInWithRole,
+} from "./helpers/admin/instance-roles";
+import { resetTestDatabase } from "./helpers/database";
+
+beforeEach(resetTestDatabase);
+
+async function roleOf(userId: string) {
+ const [user] = await db
+ .select({ role: schema.userTable.role })
+ .from(schema.userTable)
+ .where(eq(schema.userTable.id, userId));
+ return user?.role;
+}
+
+function authAdmin(path: string, body: unknown, cookie: string) {
+ return auth.handler(
+ new Request(`http://localhost:1337/api/auth${path}`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ origin: "http://localhost:5173",
+ cookie,
+ },
+ body: JSON.stringify(body),
+ }),
+ );
+}
+
+describe("custom instance roles", () => {
+ it("are created, renamed with their users, and deleted once unassigned, with audit entries", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+
+ const created = await admin.api("/roles", {
+ method: "POST",
+ body: { name: "support", permissions: ["users:read", "audit:read"] },
+ });
+ expect(created.status).toBe(201);
+ const role = (await created.json()) as { id: string; userCount: number };
+ expect(role).toMatchObject({
+ name: "support",
+ permissions: ["users:read", "audit:read"],
+ userCount: 0,
+ });
+
+ const member = await insertUser("support");
+ const renamed = await admin.api(`/roles/${role.id}`, {
+ method: "PUT",
+ body: { name: "help-desk", permissions: ["users:read"] },
+ });
+ expect(renamed.status).toBe(200);
+ expect(await renamed.json()).toMatchObject({
+ name: "help-desk",
+ permissions: ["users:read"],
+ userCount: 1,
+ });
+ expect(await roleOf(member.id)).toBe("help-desk");
+
+ const blocked = await admin.api(`/roles/${role.id}`, { method: "DELETE" });
+ expect(blocked.status).toBe(409);
+ expect(await readErrorBody(blocked)).toMatchObject({ code: "ROLE_IN_USE" });
+
+ await db
+ .update(schema.userTable)
+ .set({ role: "user" })
+ .where(eq(schema.userTable.id, member.id));
+ const deleted = await admin.api(`/roles/${role.id}`, { method: "DELETE" });
+ expect(deleted.status).toBe(200);
+
+ const entries = (await readAuditLog()).map((entry) => ({
+ action: entry.action,
+ targetType: entry.targetType,
+ targetLabel: entry.targetLabel,
+ metadata: entry.metadata,
+ }));
+ expect(entries).toEqual([
+ {
+ action: "role.created",
+ targetType: "role",
+ targetLabel: "support",
+ metadata: { permissions: ["users:read", "audit:read"] },
+ },
+ {
+ action: "role.deleted",
+ targetType: "role",
+ targetLabel: "help-desk",
+ metadata: { permissions: ["users:read"] },
+ },
+ {
+ action: "role.updated",
+ targetType: "role",
+ targetLabel: "help-desk",
+ metadata: {
+ name: { from: "support", to: "help-desk" },
+ added: [],
+ removed: ["audit:read"],
+ },
+ },
+ ]);
+ });
+
+ it("reject reserved, taken, and invalid names and role management permissions", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ await insertInstanceRole("support", []);
+
+ const cases = [
+ { body: { name: "admin", permissions: [] }, status: 409 },
+ { body: { name: "user", permissions: [] }, status: 409 },
+ { body: { name: "support", permissions: [] }, status: 409 },
+ { body: { name: "Support Team", permissions: [] }, status: 400 },
+ { body: { name: "ops", permissions: ["roles:manage"] }, status: 400 },
+ { body: { name: "ops", permissions: ["users:fly"] }, status: 400 },
+ ];
+ for (const { body, status } of cases) {
+ const response = await admin.api("/roles", { method: "POST", body });
+ expect(response.status, JSON.stringify(body)).toBe(status);
+ }
+ expect(await readAuditLog()).toEqual([]);
+ });
+
+ it("are listed with their user counts and filter the user directory", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ await insertInstanceRole("support", ["users:read"]);
+ const supporter = await insertUser("support");
+ const plain = await insertUser("user");
+
+ const list = await admin.api("/roles");
+ expect(await list.json()).toMatchObject({
+ roles: [{ name: "support", userCount: 1 }],
+ });
+
+ const ids = async (role: string) => {
+ const response = await admin.api(`/users?role=${role}`);
+ const body = (await response.json()) as { users: { id: string }[] };
+ return body.users.map((user) => user.id).sort();
+ };
+ expect(await ids("support")).toEqual([supporter.id]);
+ expect(await ids("user")).toEqual([plain.id]);
+ expect(await ids("admin")).toEqual([admin.userId]);
+ });
+
+ it("grant only their permissions through the access endpoint", async () => {
+ const { app } = createApp();
+ await insertInstanceRole("auditor", ["audit:read", "system:read"]);
+ const auditor = await signInWithRole(app, "auditor");
+ const plain = await signInWithRole(app, "user");
+ const admin = await signInWithRole(app, "admin");
+
+ const permissionsOf = async (api: typeof auditor.api) =>
+ ((await (await api("/access")).json()) as { permissions: string[] })
+ .permissions;
+ expect(await permissionsOf(auditor.api)).toEqual([
+ "audit:read",
+ "system:read",
+ ]);
+ expect(await permissionsOf(plain.api)).toEqual([]);
+ expect(await permissionsOf(admin.api)).toContain("roles:manage");
+
+ // Changes apply to the next request.
+ await db
+ .update(schema.instanceRoleTable)
+ .set({ permissions: [] })
+ .where(eq(schema.instanceRoleTable.name, "auditor"));
+ expect((await auditor.api("/audit-log")).status).toBe(403);
+ });
+
+ it("reject API keys, even from administrators", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ const target = await insertUser();
+ const { key } = await auth.api.createApiKey({
+ body: { userId: admin.userId, name: "Roles test" },
+ });
+ const role = await insertInstanceRole("support", []);
+ const requests = [
+ { path: "/access" },
+ { path: "/roles" },
+ {
+ path: "/roles",
+ method: "POST",
+ body: { name: "ops", permissions: [] },
+ },
+ { path: `/roles/${role.id}`, method: "DELETE" },
+ { path: `/users/${target.id}`, method: "PATCH", body: { name: "X" } },
+ { path: `/users/${target.id}/deactivate`, method: "POST" },
+ { path: `/users/${target.id}`, method: "DELETE" },
+ ];
+ for (const headers of [
+ { "x-api-key": key },
+ { authorization: `Bearer ${key}` },
+ ]) {
+ const api = adminApi(app, headers);
+ for (const request of requests) {
+ const response = await api(request.path, request);
+ expect(response.status, `${request.method} ${request.path}`).toBe(403);
+ }
+ }
+ expect(await readAuditLog()).toEqual([]);
+ });
+});
+
+describe("instance role escalation", () => {
+ it("lets a custom role assign only roles within its own permissions", async () => {
+ const { app } = createApp();
+ await insertInstanceRole("manager", ["users:read", "users:update"]);
+ await insertInstanceRole("reader", ["users:read"]);
+ await insertInstanceRole("auditor", ["audit:read"]);
+ const manager = await signInWithRole(app, "manager");
+ const target = await insertUser();
+
+ const assign = (role: string) =>
+ manager.api(`/users/${target.id}`, { method: "PATCH", body: { role } });
+
+ const toAdmin = await assign("admin");
+ expect(toAdmin.status).toBe(403);
+ expect(await readErrorBody(toAdmin)).toMatchObject({
+ code: "ADMIN_ROLE_REQUIRED",
+ });
+ const wider = await assign("auditor");
+ expect(wider.status).toBe(403);
+ expect(await readErrorBody(wider)).toMatchObject({
+ code: "ROLE_EXCEEDS_YOUR_PERMISSIONS",
+ });
+ const unknown = await assign("ghost");
+ expect(unknown.status).toBe(400);
+ expect(await roleOf(target.id)).toBe("user");
+
+ expect((await assign("reader")).status).toBe(200);
+ expect(await roleOf(target.id)).toBe("reader");
+ expect(
+ (await readAuditLog()).map(({ action, metadata }) => ({
+ action,
+ metadata,
+ })),
+ ).toEqual([
+ { action: "user.role_changed", metadata: { from: "user", to: "reader" } },
+ ]);
+ });
+
+ it("keeps a custom role away from users with more permissions", async () => {
+ const { app } = createApp();
+ await insertInstanceRole("support", [
+ "users:read",
+ "users:update",
+ "users:disable",
+ "users:delete",
+ "users:credentials",
+ "users:sessions",
+ ]);
+ await insertInstanceRole("auditor", ["audit:read"]);
+ const support = await signInWithRole(app, "support");
+ const admin = await insertUser("admin");
+ const auditor = await insertUser("auditor");
+
+ for (const target of [admin, auditor]) {
+ for (const request of [
+ { path: `/users/${target.id}`, method: "PATCH", body: { name: "X" } },
+ { path: `/users/${target.id}/deactivate`, method: "POST" },
+ { path: `/users/${target.id}`, method: "DELETE" },
+ { path: `/users/${target.id}/sessions`, method: "DELETE" },
+ { path: `/users/${target.id}/email-verified`, method: "PUT" },
+ ]) {
+ const response = await support.api(request.path, request);
+ expect(response.status, `${target.role} ${request.path}`).toBe(403);
+ expect(await readErrorBody(response)).toMatchObject({
+ code: "USER_HAS_MORE_PERMISSIONS",
+ });
+ }
+ }
+ expect(await readAuditLog()).toEqual([]);
+ });
+
+ it("does not let a custom role manage roles or use better-auth admin endpoints", async () => {
+ const { app } = createApp();
+ await insertInstanceRole("support", [
+ "users:read",
+ "users:update",
+ "users:disable",
+ "users:delete",
+ ]);
+ const support = await signInWithRole(app, "support");
+ const target = await insertUser();
+
+ const created = await support.api("/roles", {
+ method: "POST",
+ body: { name: "ops", permissions: [] },
+ });
+ expect(created.status).toBe(403);
+
+ for (const [path, body] of [
+ ["/admin/update-user", { userId: target.id, data: { name: "X" } }],
+ ["/admin/set-role", { userId: target.id, role: "admin" }],
+ ["/admin/ban-user", { userId: target.id }],
+ ["/admin/remove-user", { userId: target.id }],
+ [
+ "/admin/create-user",
+ { email: "[email protected]", name: "X", password: "password1234" },
+ ],
+ ] as const) {
+ const response = await authAdmin(path, body, support.cookies);
+ expect(response.status, path).toBe(403);
+ }
+ expect(await roleOf(target.id)).toBe("user");
+ });
+
+ it("lets better-auth admin endpoints assign only known roles", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ await insertInstanceRole("support", []);
+ const target = await insertUser();
+
+ for (const [path, body] of [
+ ["/admin/set-role", { userId: target.id, role: "ghost" }],
+ ["/admin/set-role", { userId: target.id, role: ["user", "ghost"] }],
+ ["/admin/update-user", { userId: target.id, data: { role: "ghost" } }],
+ ] as const) {
+ const response = await authAdmin(path, body, admin.cookies);
+ expect(response.status, JSON.stringify(body)).toBe(400);
+ expect(await response.json()).toMatchObject({ code: "UNKNOWN_ROLE" });
+ }
+ const assigned = await authAdmin(
+ "/admin/set-role",
+ { userId: target.id, role: "support" },
+ admin.cookies,
+ );
+ expect(assigned.status).toBe(200);
+ expect(await roleOf(target.id)).toBe("support");
+ });
+
+ it("keeps the last administrator and your own role", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ const other = await insertUser("admin");
+
+ const self = await admin.api(`/users/${admin.userId}`, {
+ method: "PATCH",
+ body: { role: "user" },
+ });
+ expect(self.status).toBe(400);
+ expect(await readErrorBody(self)).toMatchObject({
+ code: "YOU_CANNOT_CHANGE_YOUR_OWN_ROLE",
+ });
+
+ expect(
+ (
+ await admin.api(`/users/${other.id}`, {
+ method: "PATCH",
+ body: { role: "user" },
+ })
+ ).status,
+ ).toBe(200);
+ expect(await roleOf(admin.userId)).toBe("admin");
+ });
+});
+
+describe("admin account actions", () => {
+ it("update, deactivate, reactivate, and delete a user with one audit entry each", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ const target = await signInWithRole(app, "user");
+
+ const updated = await admin.api(`/users/${target.userId}`, {
+ method: "PATCH",
+ body: { name: "Renamed", email: "[email protected]" },
+ });
+ expect(updated.status).toBe(200);
+ expect(await updated.json()).toMatchObject({
+ name: "Renamed",
+ email: "[email protected]",
+ emailVerified: false,
+ });
+
+ const deactivated = await admin.api(`/users/${target.userId}/deactivate`, {
+ method: "POST",
+ });
+ expect(deactivated.status).toBe(200);
+ expect(await deactivated.json()).toMatchObject({ banned: true });
+ const sessions = await db
+ .select()
+ .from(schema.sessionTable)
+ .where(eq(schema.sessionTable.userId, target.userId));
+ expect(sessions).toEqual([]);
+ // Deactivating again records nothing new.
+ await admin.api(`/users/${target.userId}/deactivate`, { method: "POST" });
+
+ const reactivated = await admin.api(`/users/${target.userId}/reactivate`, {
+ method: "POST",
+ });
+ expect(await reactivated.json()).toMatchObject({ banned: false });
+
+ const self = await admin.api(`/users/${admin.userId}`, {
+ method: "DELETE",
+ });
+ expect(self.status).toBe(400);
+ const deleted = await admin.api(`/users/${target.userId}`, {
+ method: "DELETE",
+ });
+ expect(deleted.status).toBe(200);
+ expect(await roleOf(target.userId)).toBeUndefined();
+
+ expect((await readAuditLog()).map((entry) => entry.action)).toEqual([
+ "user.deactivated",
+ "user.deleted",
+ "user.reactivated",
+ "user.updated",
+ ]);
+ });
+
+ it("rejects an email another user has", async () => {
+ const { app } = createApp();
+ const admin = await signInWithRole(app, "admin");
+ const target = await insertUser();
+ const response = await admin.api(`/users/${target.id}`, {
+ method: "PATCH",
+ body: { email: admin.email.toUpperCase() },
+ });
+ expect(response.status).toBe(409);
+ });
+});
diff --git a/tests/api-integration/helpers/admin/instance-roles.ts b/tests/api-integration/helpers/admin/instance-roles.ts
new file mode 100644
index 000000000..425c4c736
--- /dev/null
+++ b/tests/api-integration/helpers/admin/instance-roles.ts
@@ -0,0 +1,50 @@
+import { randomUUID } from "node:crypto";
+import db, { schema } from "../../../../apps/api/src/database";
+import type { createApp } from "../../../../apps/api/src/index";
+import { signUpWithSession } from "../auth-session";
+
+type App = ReturnType<typeof createApp>["app"];
+
+/** Requests to `/api/admin...` with the given headers. */
+export function adminApi(app: App, headers: Record<string, string>) {
+ return (path: string, init: { method?: string; body?: unknown } = {}) =>
+ app.request(`/api/admin${path}`, {
+ method: init.method ?? "GET",
+ headers: {
+ "content-type": "application/json",
+ origin: "http://localhost:5173",
+ "user-agent": "instance-roles-test",
+ ...headers,
+ },
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
+ });
+}
+
+export async function insertInstanceRole(name: string, permissions: string[]) {
+ const [role] = await db
+ .insert(schema.instanceRoleTable)
+ .values({ name, permissions })
+ .returning();
+ return role;
+}
+
+/** A signed-in user holding `role`, with an admin API client. */
+export async function signInWithRole(app: App, role: string) {
+ const email = `${role}-${randomUUID()}@example.com`;
+ const user = await signUpWithSession(app, { email, name: role, role });
+ return {
+ ...user,
+ email,
+ api: adminApi(app, { cookie: user.cookies }),
+ };
+}
+
+/** A user without a session, to act on. */
+export async function insertUser(role = "user") {
+ const id = `user-${randomUUID()}`;
+ const [user] = await db
+ .insert(schema.userTable)
+ .values({ id, email: `${id}@example.com`, name: "Target", role })
+ .returning();
+ return user;
+}
diff --git a/tests/api-integration/helpers/auth-session.ts b/tests/api-integration/helpers/auth-session.ts
index a7acf83de..dbd6997e6 100644
--- a/tests/api-integration/helpers/auth-session.ts
+++ b/tests/api-integration/helpers/auth-session.ts
@@ -34,11 +34,7 @@ export async function signIn(
export async function signUpWithSession(
app: App,
- {
- email,
- name,
- role,
- }: { email: string; name: string; role?: "admin" | "user" },
+ { email, name, role }: { email: string; name: string; role?: string },
) {
const response = await app.request("/api/auth/sign-up/email", {
method: "POST",