⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: add generic OIDC sign-in, SCIM 2.0 provisioning, and a password-auth switch (#250)
Nasreddine Bac Alic21728d400fc
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.mdindex 7e9a8b1b..2e11f13d 100644--- a/apps/api/AGENTS.md+++ b/apps/api/AGENTS.md@@ -95,9 +95,57 @@ Enforced declaratively through macros, never imperative calls in handlers.`assertPermission` on the fetched row.- Guards/macros wrap the `shared/access.ts` primitives. Handlers that still need`user` (project create, invite accept/reject, self-removal) call `requireUser(user)`.-- **Members join only through invites/**, not a direct add. One pending invite per- (project, email) — partial unique index → 409. `members/` removes only (last owner- protected).+- **Members join through invites or a provisioned group**, never a direct add from+ `members/`. One pending invite per (project, email) — partial unique index → 409.+ `members/` removes only (last owner protected). `project_member.source` says which path+ a row came from: `modules/scim/reconcile.ts` only ever writes, re-roles or removes its own+ `'scim'` rows, and `members/` refuses to edit or remove one (409) because the next sync+ would undo the change.++## SCIM++`modules/scim/` serves SCIM 2.0 (RFC 7643 / 7644) at `/scim/v2` for an identity provider+to provision users and groups with. Three things make it unlike every other module:++- **Mounted on the root app in `app.ts`, not under `planner`.** The planner's `authContext`+ answers 401 before the bearer check could run. Authentication is one `onBeforeHandle`+ against the instance SCIM token from `@repo/auth`.+- **Its own error document.** `onError` sits on a parent instance that `.use()`s the routes+ and answers only for paths under `/scim/v2`, handing everything else back to the planner's+ handler. Two reasons for that shape: an `onError` beside the routes widens the inferred+ response type of every one of them with the body it returns (which then reaches the Eden+ client as a success shape), and Elysia propagates the handler to the root app either way.+- **Bodies are `t.Any()`.** SCIM defines its own schemas and clients send attributes this app+ ignores, so `resource.ts` validates instead and raises `ScimError`, which carries the+ `scimType` a provisioning client branches on. Responses are declared per route from+ `model.ts` — `scimErrors(...)` is the SCIM-shaped counterpart of `shared/responses.ts`.++Filtering is `<attribute> eq "<value>"` only, over the attributes each resource lists in+`service.ts`; that is what Okta, Entra and Authentik send, and `ServiceProviderConfig`+advertises exactly that. A create inserts the `user` row directly, the way `createAgent`+does, which deliberately skips the registration gate — with SCIM on, the identity provider+decides who exists, and that is what makes `registration: 'closed'` plus SSO work.++`createScimUser`/`updateScimUser` refuse a `god`-role account outright (409): the role is+what grants god mode, and nothing about the instance owner's account is provider-owned. A+create for an address already linked (`user.scimExternalId` set) is refused the same way —+it is a retry, not a new person, and must not overwrite the link a first create wrote.++A group member removal arrives in two shapes: `path: 'members'` with the id(s) to drop in+`value`, or RFC 7644 §3.5.2.2's path filter, `path: 'members[value eq "<id>"]'`, which Okta+sends and which carries no `value` at all. `resource.ts`'s `memberFilterIds` reads the+second shape; a `PATCH /Groups/:id` remove that only checked `value` would silently drop+nothing for a provider that sends the filter form.++The `scim_group` / `scim_group_member` tables have two writers, not one. A SCIM sync is+the obvious one, but a group can also be embedded right on a resource instead of pushed on+its own: `resource.ts`'s `groupDisplayNames` reads a SCIM User's `groups` attribute, and+`oidc-sync.ts` reads an OIDC sign-in's `groups` claim off the ID token stored on the linked+`account` row, decoded with no signature check since it already crossed a trusted, TLS+channel and is read only for a claim, not for authentication. Both funnel into+`syncEmbeddedGroups`, the same additive-only join a group pushed through `POST /Groups`+gets — a name missing from a later sync is never removed by this path, only by an explicit+`PATCH /Groups/:id` or an unmapping in god mode.## Securitydiff --git a/apps/api/src/__tests__/helpers/app.ts b/apps/api/src/__tests__/helpers/app.tsindex faa350eb..365c7693 100644--- a/apps/api/src/__tests__/helpers/app.ts+++ b/apps/api/src/__tests__/helpers/app.ts@@ -21,4 +21,10 @@ export function apiKeyApi(apiKey: string) {return treaty(app, { headers: { 'x-api-key': apiKey } });}+// Treaty client that authenticates with the instance SCIM token — how an identity+// provider calls /scim/v2.+export function scimApi(token: string) {+ return treaty(app, { headers: { authorization: `Bearer ${token}` } });+}+export type Api = typeof api;diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex a57e64bb..2302f634 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -4,6 +4,8 @@ import {getAuthSettings,hasConfiguredEmailProvider,hasConfiguredGoogle,+ hasConfiguredOidc,+ getOidcLabel,} from '@repo/auth';import { cors } from '@elysiajs/cors';import { swagger } from '@elysiajs/swagger';@@ -15,6 +17,8 @@ import { internalAgentRunRoutes } from './modules/agents/core/internal-routes';import { internalNotificationRoutes } from './modules/notifications/internal-routes';import { internalTelegramRoutes } from './modules/telegram/internal-routes';import { gitWebhookRoutes } from './modules/git/webhook';+import { scimRoutes } from './modules/scim';+import { syncOidcGroupsAfterCallback } from './modules/scim/oidc-sync';// The assembled Elysia app, without `.listen()`. `index.ts` imports this and// binds the port; tests import it and pass it to Eden Treaty to drive routes in@@ -118,7 +122,12 @@ export const app = new Elysia(){name: 'God',description:- 'Instance administration: registration policy, email provider, Google sign-in',+ 'Instance administration: registration policy, email provider, sign-in providers, ' ++ 'SCIM provisioning',+ },+ {+ name: 'SCIM',+ description: 'SCIM 2.0 provisioning, authenticated with the instance SCIM bearer token',},{name: 'System',@@ -144,14 +153,26 @@ export const app = new Elysia()},}),)- // better-auth: forward every /api/auth/* request to its handler.- .all('/api/auth/*', ({ request }) => auth.handler(request))+ // better-auth: forward every /api/auth/* request to its handler. The OIDC+ // callback gets one extra step afterwards: folding the provider's `groups` claim+ // into the SCIM group tables, so a group mapped to a project in god mode grants+ // access on an OIDC-only instance too, not just one that also runs a SCIM sync.+ .all('/api/auth/*', async ({ request }) => {+ const response = await auth.handler(request);+ if (new URL(request.url).pathname.startsWith('/api/auth/oauth2/callback/')) {+ await syncOidcGroupsAfterCallback(response);+ }+ return response;+ })// Example protected handler: read the session from better-auth..get('/me',async ({ request }) => {const session = await auth.api.getSession({ headers: request.headers });- if (!session) return { authenticated: false };+ // A deactivated account is not signed in as far as the app is concerned:+ // every planner route answers 401 for it, and this is what the screens ask+ // first. Deactivation arrives over SCIM, after the session was opened.+ if (!session || session.user.active === false) return { authenticated: false };return { authenticated: true, user: session.user };},{@@ -160,7 +181,8 @@ export const app = new Elysia()summary: 'Get the current session user',description:'Resolve the request credentials to a session and return the user it belongs to. ' +- 'Without a session it answers `{ authenticated: false }` instead of failing.',+ 'Without a session, or for a deactivated account, it answers ' ++ '`{ authenticated: false }` instead of failing.',},},)@@ -179,7 +201,14 @@ export const app = new Elysia()magicLink: settings.magicLink && emailEnabled,requireEmailVerification: settings.requireEmailVerification && emailEnabled,emailEnabled,+ // Whether the email/password form is offered at all. The api refuses to turn+ // it off while no provider below is usable, so this is never false alone.+ emailPassword: settings.emailPassword,google: await hasConfiguredGoogle(),+ oidc: await hasConfiguredOidc(),+ // Names the operator's own identity provider, so the button shows it as+ // given. Empty falls back to a translated default.+ oidcLabel: await getOidcLabel(),};},{@@ -205,6 +234,11 @@ export const app = new Elysia().use(internalTelegramRoutes)// Inbound repository webhook receiver (authenticated by its per-project secret)..use(gitWebhookRoutes)+ // SCIM 2.0 provisioning (authenticated by the instance SCIM bearer token). Mounted+ // here rather than under the planner: the planner's session guard would answer 401+ // before the bearer check runs, and its error handler emits a body SCIM does not+ // understand.+ .use(scimRoutes)// Planner API: projects, issues, and their dependent entities..use(planner);diff --git a/apps/api/src/mcp/__tests__/integration/mcp-auth.test.ts b/apps/api/src/mcp/__tests__/integration/mcp-auth.test.tsnew file mode 100644index 00000000..bff0c33d--- /dev/null+++ b/apps/api/src/mcp/__tests__/integration/mcp-auth.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, beforeEach } from 'bun:test';+import { auth } from '@repo/auth';+import { app } from '#tests/helpers/app';+import { resetDb } from '#tests/helpers/db';+import { signUpTestUser } from '#tests/helpers/auth';+import { patchOps, setupScim } from '#modules/scim/__tests__/helpers';++// The MCP endpoint resolves the API key itself instead of going through+// authContext, so the rules that gate a planner route have to hold here too.++async function initialize(apiKey: string) {+ return app.handle(+ new Request('http://localhost/mcp', {+ method: 'POST',+ headers: {+ authorization: `Bearer ${apiKey}`,+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'test', version: '1' },+ },+ }),+ }),+ );+}++describe('MCP authentication', () => {+ beforeEach(resetDb);++ it('refuses a request with no key', async () => {+ const res = await app.handle(+ new Request('http://localhost/mcp', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }),+ }),+ );++ expect(res.status).toBe(401);+ });++ it('refuses a key whose account was deactivated over SCIM', async () => {+ const { scim } = await setupScim();+ const member = await signUpTestUser({ email: '[email protected]' });+ const created = await auth.api.createApiKey({+ body: { userId: member.userId, name: 'mcp' },+ });++ expect((await initialize(created.key)).status).not.toBe(401);++ await scim.scim.v2+ .Users({ id: member.userId })+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));++ expect((await initialize(created.key)).status).toBe(401);+ });+});diff --git a/apps/api/src/mcp/mount.ts b/apps/api/src/mcp/mount.tsindex e99230fa..0f42b971 100644--- a/apps/api/src/mcp/mount.ts+++ b/apps/api/src/mcp/mount.ts@@ -42,7 +42,10 @@ export function mountMcp(app: any): void {const headers = new Headers(request.headers);headers.set('x-api-key', apiKey);const session = await auth.api.getSession({ headers });- if (session) {+ // A deactivated account is refused here too, the way shared/auth-context.ts+ // refuses it for every planner route. Deactivation arrives over SCIM, after+ // the key was issued.+ if (session && session.user.active !== false) {const server = buildMcpServer(mcpApp, apiKey);const transport = new WebStandardStreamableHTTPServerTransport({sessionIdGenerator: undefined,diff --git a/apps/api/src/modules/god/__tests__/integration/god-oidc.test.ts b/apps/api/src/modules/god/__tests__/integration/god-oidc.test.tsnew file mode 100644index 00000000..167b5886--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-oidc.test.ts@@ -0,0 +1,169 @@+import { describe, expect, it, beforeEach } from 'bun:test';+import { app } from '#tests/helpers/app';+import { resetDb } from '#tests/helpers/db';+import { addUser, setup } from '../helpers';++// The password endpoints live behind the better-auth catch-all, which Eden Treaty+// does not model, so they are driven through the app handler directly.+function signInWithPassword(email: string, password: string) {+ return app.handle(+ new Request('http://localhost/api/auth/sign-in/email', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ email, password }),+ }),+ );+}++const credentials = {+ discoveryUrl: 'https://idp.example.com/.well-known/openid-configuration',+ clientId: 'itsaplan',+ clientSecret: 'sh-secret',+};++describe('god OIDC and password settings', () => {+ beforeEach(resetDb);++ describe('access', () => {+ it('refuses a plain user', async () => {+ await setup();+ const user = await addUser({ email: '[email protected]' });++ expect((await user.api.god['oidc-settings'].get()).status).toBe(403);+ expect((await user.api.god['oidc-settings'].put({ enabled: false })).status).toBe(403);+ });+ });++ describe('GET /god/oidc-settings', () => {+ it('reports an unconfigured provider with the redirect URI to register', async () => {+ const { god } = await setup();++ const res = await god.api.god['oidc-settings'].get();++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({+ enabled: false,+ label: '',+ discoveryUrl: '',+ clientId: '',+ hasClientSecret: false,+ scopes: ['openid', 'profile', 'email'],+ pkce: true,+ redirectUri: 'http://localhost:3000/api/auth/oauth2/callback/oidc',+ });+ });+ });++ describe('PUT /god/oidc-settings', () => {+ it('stores the credentials and never returns the secret', async () => {+ const { god } = await setup();++ const saved = await god.api.god['oidc-settings'].put({+ ...credentials,+ label: 'Acme SSO',+ enabled: true,+ });++ expect(saved.status).toBe(200);+ expect(saved.data).toMatchObject({+ enabled: true,+ label: 'Acme SSO',+ discoveryUrl: credentials.discoveryUrl,+ clientId: credentials.clientId,+ hasClientSecret: true,+ });+ expect(JSON.stringify(saved.data)).not.toContain(credentials.clientSecret);+ });++ it('keeps the stored secret when the field is sent empty', async () => {+ const { god } = await setup();+ await god.api.god['oidc-settings'].put({ ...credentials, enabled: true });++ const saved = await god.api.god['oidc-settings'].put({ clientSecret: '' });++ expect(saved.data).toMatchObject({ hasClientSecret: true, enabled: true });+ });++ it('refuses to enable a provider with no credentials', async () => {+ const { god } = await setup();++ const res = await god.api.god['oidc-settings'].put({ enabled: true });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({+ error: 'Add the discovery URL, client ID and secret first',+ });+ });++ it('refuses to enable a provider that is missing only the secret', async () => {+ const { god } = await setup();++ const res = await god.api.god['oidc-settings'].put({+ discoveryUrl: credentials.discoveryUrl,+ clientId: credentials.clientId,+ enabled: true,+ });++ expect(res.status).toBe(400);+ });+ });++ describe('turning off password sign-in', () => {+ it('refuses while no single sign-on provider is configured', async () => {+ const { god } = await setup();++ const before = await god.api.god['auth-settings'].get();+ expect(before.data).toMatchObject({ emailPassword: true, hasSsoProvider: false });++ const res = await god.api.god['auth-settings'].put({ emailPassword: false });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({+ error: 'Configure a single sign-on provider first',+ });+ });++ it('allows it once OIDC is usable, and reports it publicly', async () => {+ const { god } = await setup();+ await god.api.god['oidc-settings'].put({ ...credentials, label: 'Acme SSO', enabled: true });++ const res = await god.api.god['auth-settings'].put({ emailPassword: false });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ emailPassword: false, hasSsoProvider: true });++ const config = await god.api['auth-config'].get();+ expect(config.data).toMatchObject({+ emailPassword: false,+ oidc: true,+ oidcLabel: 'Acme SSO',+ });+ });++ it('accepts a password sign-in while it is on and refuses it once it is off', async () => {+ const { god } = await setup();+ const user = await addUser({ email: '[email protected]' });+ await god.api.god['oidc-settings'].put({ ...credentials, enabled: true });+ expect((await signInWithPassword(user.email, 'test-password-123')).status).toBe(200);+ await god.api.god['auth-settings'].put({ emailPassword: false });++ const res = await signInWithPassword(user.email, 'test-password-123');++ expect(res.status).toBe(403);+ });++ it('stops offering OIDC once the provider is disabled again', async () => {+ const { god } = await setup();+ await god.api.god['oidc-settings'].put({ ...credentials, enabled: true });+ await god.api.god['auth-settings'].put({ emailPassword: false });++ // Password sign-in has to come back first, or the instance would be left+ // with no way in at all.+ await god.api.god['auth-settings'].put({ emailPassword: true });+ await god.api.god['oidc-settings'].put({ enabled: false });++ const config = await god.api['auth-config'].get();+ expect(config.data).toMatchObject({ oidc: false, oidcLabel: '', emailPassword: true });+ });+ });+});diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.tsindex ff467127..7acf701d 100644--- a/apps/api/src/modules/god/index.ts+++ b/apps/api/src/modules/god/index.ts@@ -1,6 +1,7 @@import { Elysia, t } from 'elysia';import {GOOGLE_REDIRECT_URI,+ OIDC_REDIRECT_URI,getAuthSettings,setAuthSettings,getEmailSettings,@@ -8,6 +9,13 @@ import {hasConfiguredEmailProvider,getGoogleSettings,setGoogleSettings,+ hasConfiguredGoogle,+ getOidcSettings,+ setOidcSettings,+ hasConfiguredOidc,+ getScimSettings,+ setScimSettings,+ rotateScimToken,} from '@repo/auth';import { authContext } from '#shared/auth-context';import { requireGod } from '#shared/access';@@ -21,6 +29,8 @@ import {getInstanceUser,listInstanceProjects,listInstanceUsers,+ listScimGroups,+ setScimGroupMappings,verifyInstanceUserEmail,} from './service';import {@@ -34,6 +44,13 @@ import {InstanceProjectListResponse,InstanceUserDetailResponse,InstanceUserListResponse,+ OidcSettingsBody,+ OidcSettingsResponse,+ ScimGroupMappingsBody,+ ScimGroupResponse,+ ScimSettingsBody,+ ScimSettingsResponse,+ ScimTokenResponse,StorageSettingsBody,TelegramSettingsBody,TelegramSettingsResponse,@@ -41,9 +58,11 @@ import {listProjectsQuery,listUsersQuery,projectParams,+ scimGroupParams,userParams,} from './model';import { getInstanceBotSettings, setInstanceBotSettings } from '#modules/telegram/service';+import { SCIM_BASE_URL } from '#modules/scim/resource';import {getStorageSettings,setStorageSettings,@@ -62,14 +81,20 @@ import {// God mode: instance-wide administration, open only to the "god" user (the first// registered account). It covers how people may register, the mail provider that-// sends authentication email, and the Google OAuth credentials. Invites are per-// project (project_invite), managed in the project's Members section — there is-// nothing instance-level to add here.+// sends authentication email, the OAuth credentials, and SCIM provisioning. Invites+// are per project (project_invite), managed in the project's Members section — there+// is nothing instance-level to add here.//// The settings themselves are owned by @repo/auth, which reads them at sign-up and// when sending mail; these routes only expose them over HTTP. Secrets are never// returned — each is replaced by a boolean telling whether a value is stored.+// Whether any single sign-on provider can run right now. Password sign-in may only+// be turned off while one can.+async function hasSsoProvider(): Promise<boolean> {+ return (await hasConfiguredOidc()) || (await hasConfiguredGoogle());+}+export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } }).use(authContext)// Every route in this plugin is instance administration, so the role check runs@@ -83,6 +108,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })async () => ({...(await getAuthSettings()),hasEmailProvider: await hasConfiguredEmailProvider(),+ hasSsoProvider: await hasSsoProvider(),}),{response: { 200: AuthSettingsResponse, ...errors(401, 403) },@@ -102,8 +128,14 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })if (!ready && (body.requireEmailVerification || body.magicLink)) {throw new HttpError(400, 'Configure an email provider first');}+ const sso = await hasSsoProvider();+ // Without another way in, turning the password form off would lock everyone+ // out, the instance owner included.+ if (body.emailPassword === false && !sso) {+ throw new HttpError(400, 'Configure a single sign-on provider first');+ }const next = await setAuthSettings(body);- return { ...next, hasEmailProvider: ready };+ return { ...next, hasEmailProvider: ready, hasSsoProvider: sso };},{body: AuthSettingsBody,@@ -168,6 +200,116 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })},)+ .get(+ '/god/oidc-settings',+ async () => ({ ...(await getOidcSettings()), redirectUri: OIDC_REDIRECT_URI }),+ {+ response: { 200: OidcSettingsResponse, ...errors(401, 403) },+ detail: {+ summary: 'Get OIDC sign-in settings',+ description: 'Get the generic OIDC/OAuth2 provider settings (the client secret redacted).',+ },+ },+ )++ .put(+ '/god/oidc-settings',+ async ({ body }) => {+ const current = await getOidcSettings();+ const discoveryUrl = body.discoveryUrl ?? current.discoveryUrl;+ const clientId = body.clientId ?? current.clientId;+ const hasClientSecret = (body.clientSecret?.length ?? 0) > 0 || current.hasClientSecret;+ // Turning it on without credentials would only offer a button that fails at+ // the provider, the same rule the Google settings apply.+ if (+ body.enabled &&+ (discoveryUrl.length === 0 || clientId.length === 0 || !hasClientSecret)+ ) {+ throw new HttpError(400, 'Add the discovery URL, client ID and secret first');+ }+ const next = await setOidcSettings(body);+ return { ...next, redirectUri: OIDC_REDIRECT_URI };+ },+ {+ body: OidcSettingsBody,+ response: { 200: OidcSettingsResponse, ...errors(400, 401, 403) },+ detail: {+ summary: 'Update OIDC sign-in settings',+ description:+ 'Update the generic OIDC/OAuth2 credentials and whether the provider is offered.',+ },+ },+ )++ .get(+ '/god/scim-settings',+ async () => ({ ...(await getScimSettings()), baseUrl: SCIM_BASE_URL }),+ {+ response: { 200: ScimSettingsResponse, ...errors(401, 403) },+ detail: {+ summary: 'Get SCIM provisioning settings',+ description: 'Get whether SCIM provisioning is on and whether a token has been generated.',+ },+ },+ )++ .put(+ '/god/scim-settings',+ async ({ body }) => {+ const current = await getScimSettings();+ // Enabling it without a token would leave the endpoint answering 401 to+ // everything, which reads as a broken integration rather than a missing step.+ if (body.enabled && !current.hasToken) {+ throw new HttpError(400, 'Generate a SCIM token first');+ }+ return { ...(await setScimSettings(body)), baseUrl: SCIM_BASE_URL };+ },+ {+ body: ScimSettingsBody,+ response: { 200: ScimSettingsResponse, ...errors(400, 401, 403) },+ detail: {+ summary: 'Update SCIM provisioning settings',+ description: 'Turn SCIM provisioning on or off.',+ },+ },+ )++ .post('/god/scim-settings/token', async () => ({ token: await rotateScimToken() }), {+ response: { 200: ScimTokenResponse, ...errors(401, 403) },+ detail: {+ summary: 'Generate a SCIM token',+ description:+ 'Generate the bearer token an identity provider sends to /scim/v2, replacing any ' ++ 'previous one. The value is returned once and cannot be read back.',+ },+ })++ .get('/god/scim-groups', () => listScimGroups(), {+ response: { 200: t.Array(ScimGroupResponse), ...errors(401, 403) },+ detail: {+ summary: 'List provisioned groups',+ description:+ 'List the groups an identity provider has pushed, with their member counts and the ' ++ 'projects they grant membership in.',+ },+ })++ .put(+ '/god/scim-groups/:groupId/mappings',+ ({ params, body }) => setScimGroupMappings(params.groupId, body.mappings),+ {+ params: scimGroupParams,+ body: ScimGroupMappingsBody,+ response: { 200: ScimGroupResponse, ...commonErrors },+ detail: {+ summary: "Set a group's project mappings",+ description:+ 'Replace the list of projects a provisioned group grants membership in, then ' ++ 'reconcile the membership of every project the change touched.',+ },+ },+ )+.get('/god/storage-settings', () => getStorageSettings(), {response: { 200: StorageSettingsSchema, ...errors(401, 403) },detail: {diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.tsindex 7666236a..e597d3b9 100644--- a/apps/api/src/modules/god/model.ts+++ b/apps/api/src/modules/god/model.ts@@ -34,15 +34,20 @@ export const AuthSettingsResponse = t.Object({registration: t.UnionEnum([...REGISTRATION_MODES]),requireEmailVerification: t.Boolean(),magicLink: t.Boolean(),+ emailPassword: t.Boolean(),// The settings that depend on outbound email cannot be turned on without a mail// provider, and the UI explains why.hasEmailProvider: t.Boolean(),+ // Password sign-in cannot be turned off without another way in, and the UI+ // explains why.+ hasSsoProvider: t.Boolean(),});export const AuthSettingsBody = t.Object({registration: t.Optional(t.UnionEnum([...REGISTRATION_MODES])),requireEmailVerification: t.Optional(t.Boolean()),magicLink: t.Optional(t.Boolean()),+ emailPassword: t.Optional(t.Boolean()),});export const EmailSettingsResponse = t.Object({@@ -94,6 +99,72 @@ export const GoogleSettingsBody = t.Object({clientSecret: t.Optional(t.String()),});+export const OidcSettingsResponse = t.Object({+ enabled: t.Boolean(),+ label: t.String(),+ discoveryUrl: t.String(),+ clientId: t.String(),+ hasClientSecret: t.Boolean(),+ scopes: t.Array(t.String()),+ pkce: t.Boolean(),+ // The value to register with the identity provider. Derived from the API origin,+ // so the UI shows it rather than asking the owner to assemble it.+ redirectUri: t.String(),+});++export const OidcSettingsBody = t.Object({+ enabled: t.Optional(t.Boolean()),+ label: t.Optional(t.String({ maxLength: 60 })),+ discoveryUrl: t.Optional(t.String({ maxLength: 2048 })),+ clientId: t.Optional(t.String({ maxLength: 512 })),+ clientSecret: t.Optional(t.String({ maxLength: 512 })),+ scopes: t.Optional(t.Array(t.String({ minLength: 1, maxLength: 64 }), { maxItems: 32 })),+ pkce: t.Optional(t.Boolean()),+});++export const ScimSettingsResponse = t.Object({+ enabled: t.Boolean(),+ hasToken: t.Boolean(),+ tokenPrefix: t.String(),+ // Where to point the identity provider. Derived from the API origin, like the+ // OIDC redirect URI.+ baseUrl: t.String(),+});++export const ScimSettingsBody = t.Object({+ enabled: t.Optional(t.Boolean()),+});++// The generated token, returned once. It is not stored anywhere it can be read+// back, so a lost token is replaced rather than recovered.+export const ScimTokenResponse = t.Object({+ token: t.String(),+});++const scimGroupMapping = t.Object({+ projectId: t.Integer(),+ role: t.UnionEnum(['owner', 'member']),+ // Which project_role a member joins on. Null for an owner (owners bypass the+ // permission matrix) or to fall back to the project's default role.+ roleId: t.Nullable(t.Integer()),+});++export const ScimGroupResponse = t.Object({+ id: t.String(),+ displayName: t.String(),+ externalId: t.Nullable(t.String()),+ memberCount: t.Integer(),+ mappings: t.Array(+ t.Intersect([scimGroupMapping, t.Object({ projectKey: t.String(), projectName: t.String() })]),+ ),+});++export const ScimGroupMappingsBody = t.Object({+ mappings: t.Array(scimGroupMapping, { maxItems: 100 }),+});++export const scimGroupParams = t.Object({ groupId: t.String() });+export const StorageSettingsBody = t.Object({maxAttachmentMb: t.Optional(t.Integer({ minimum: 1, maximum: 10240 })),maxAvatarMb: t.Optional(t.Integer({ minimum: 1, maximum: 1024 })),@@ -189,6 +260,7 @@ export const InstanceProjectDetailResponse = t.Composite([joinedAt: t.String(),}),),+ roles: t.Array(t.Object({ id: t.Integer(), name: t.String(), isDefault: t.Boolean() })),}),]);diff --git a/apps/api/src/modules/god/service.ts b/apps/api/src/modules/god/service.tsindex 9c89aa82..9aa3c29d 100644--- a/apps/api/src/modules/god/service.ts+++ b/apps/api/src/modules/god/service.ts@@ -15,6 +15,9 @@ import {projectMember,projectRole,projectView,+ scimGroup,+ scimGroupMapping,+ scimGroupMember,} from '@repo/db';import {and,@@ -31,7 +34,8 @@ import {type SQL,} from 'drizzle-orm';import type { AnyPgColumn, PgTable } from 'drizzle-orm/pg-core';-import { iso } from '#shared/lib';+import { HttpError, iso } from '#shared/lib';+import { mappedProjectIds, reconcileProjects } from '#modules/scim/reconcile';import {defaultMemberPermissions,fullPermissions,@@ -332,6 +336,9 @@ export interface InstanceProjectMember {export interface InstanceProjectDetail extends InstanceProjectRow {members: InstanceProjectMember[];+ // The custom roles a member of this project can be put on. Read by the SCIM group+ // mapping form, which names one when a group grants membership.+ roles: { id: number; name: string; isDefault: boolean }[];}export interface InstanceProjectPage {@@ -486,7 +493,7 @@ export async function getInstanceProject(projectId: number): Promise<InstanceProconst row = rows[0];if (!row) return null;- const [facts, memberships, agentRows] = await Promise.all([+ const [facts, memberships, agentRows, roles] = await Promise.all([loadProjectFacts([row.id]),db.select({@@ -506,6 +513,11 @@ export async function getInstanceProject(projectId: number): Promise<InstancePro.where(eq(projectMember.projectId, projectId)).orderBy(user.name),db.select({ userId: aiAgent.userId }).from(aiAgent).where(eq(aiAgent.projectId, projectId)),+ db+ .select({ id: projectRole.id, name: projectRole.name, isDefault: projectRole.isDefault })+ .from(projectRole)+ .where(eq(projectRole.projectId, projectId))+ .orderBy(projectRole.name),]);const agentUserIds = new Set(agentRows.map((r) => r.userId));@@ -525,7 +537,7 @@ export async function getInstanceProject(projectId: number): Promise<InstancePro};});- return { ...toProjectRow(row, facts(row.id)), members };+ return { ...toProjectRow(row, facts(row.id)), members, roles };}// Marks the account's email address as confirmed and returns the updated user.@@ -539,3 +551,125 @@ export async function verifyInstanceUserEmail(userId: string): Promise<InstanceUif (updated.length === 0) return null;return getInstanceUser(userId);}++// ── Provisioned groups ───────────────────────────────────────────────────────++// A group an identity provider pushed over SCIM, with what it grants. The group+// and its members belong to the provider and are read-only here; the mappings are+// the instance owner's, and are what turns group membership into project access.+export interface InstanceScimGroupMapping {+ projectId: number;+ projectKey: string;+ projectName: string;+ role: 'owner' | 'member';+ roleId: number | null;+}++export interface InstanceScimGroup {+ id: string;+ displayName: string;+ externalId: string | null;+ memberCount: number;+ mappings: InstanceScimGroupMapping[];+}++export async function listScimGroups(): Promise<InstanceScimGroup[]> {+ const [groups, counts, mappings] = await Promise.all([+ db.select().from(scimGroup).orderBy(scimGroup.displayName),+ db+ .select({ groupId: scimGroupMember.groupId, count: sql<number>`count(*)::int` })+ .from(scimGroupMember)+ .groupBy(scimGroupMember.groupId),+ db+ .select({+ groupId: scimGroupMapping.groupId,+ projectId: scimGroupMapping.projectId,+ projectKey: project.key,+ projectName: project.name,+ role: scimGroupMapping.role,+ roleId: scimGroupMapping.roleId,+ })+ .from(scimGroupMapping)+ .innerJoin(project, eq(project.id, scimGroupMapping.projectId))+ .orderBy(project.name),+ ]);++ const countByGroup = new Map(counts.map((row) => [row.groupId, row.count]));+ return groups.map((group) => ({+ id: group.id,+ displayName: group.displayName,+ externalId: group.externalId,+ memberCount: countByGroup.get(group.id) ?? 0,+ mappings: mappings+ .filter((m) => m.groupId === group.id)+ .map((m) => ({+ projectId: m.projectId,+ projectKey: m.projectKey,+ projectName: m.projectName,+ role: m.role === 'owner' ? ('owner' as const) : ('member' as const),+ roleId: m.roleId,+ })),+ }));+}++// Replaces what a group grants, then reconciles every project the change touched —+// the ones it granted before as well as the ones it grants now, so a project it was+// unmapped from loses the memberships that came from it.+export async function setScimGroupMappings(+ groupId: string,+ mappings: { projectId: number; role: 'owner' | 'member'; roleId: number | null }[],+): Promise<InstanceScimGroup> {+ const found = await db+ .select({ id: scimGroup.id })+ .from(scimGroup)+ .where(eq(scimGroup.id, groupId));+ if (!found[0]) throw new HttpError(404, 'Group not found');++ const projectIds = mappings.map((m) => m.projectId);+ if (new Set(projectIds).size !== projectIds.length) {+ throw new HttpError(400, 'A group can be mapped to a project only once');+ }+ if (projectIds.length > 0) {+ const known = await db+ .select({ id: project.id })+ .from(project)+ .where(inArray(project.id, projectIds));+ if (known.length !== new Set(projectIds).size) throw new HttpError(400, 'Unknown project');+ // A role belongs to one project, so a mapping that names another project's role+ // would silently grant the wrong permissions.+ const roleIds = mappings.map((m) => m.roleId).filter((id): id is number => id !== null);+ if (roleIds.length > 0) {+ const roles = await db+ .select({ id: projectRole.id, projectId: projectRole.projectId })+ .from(projectRole)+ .where(inArray(projectRole.id, roleIds));+ for (const mapping of mappings) {+ if (mapping.roleId === null) continue;+ const role = roles.find((r) => r.id === mapping.roleId);+ if (!role || role.projectId !== mapping.projectId) {+ throw new HttpError(400, 'The role does not belong to that project');+ }+ }+ }+ }++ const before = await mappedProjectIds(groupId);+ await db.transaction(async (tx) => {+ await tx.delete(scimGroupMapping).where(eq(scimGroupMapping.groupId, groupId));+ if (mappings.length > 0) {+ await tx.insert(scimGroupMapping).values(+ mappings.map((m) => ({+ groupId,+ projectId: m.projectId,+ role: m.role,+ // Owners bypass the permission matrix, so they carry no custom role.+ roleId: m.role === 'owner' ? null : m.roleId,+ })),+ );+ }+ });+ await reconcileProjects([...before, ...projectIds]);++ const groups = await listScimGroups();+ return groups.find((g) => g.id === groupId)!;+}diff --git a/apps/api/src/modules/members/index.ts b/apps/api/src/modules/members/index.tsindex f124a737..a5dd437d 100644--- a/apps/api/src/modules/members/index.ts+++ b/apps/api/src/modules/members/index.ts@@ -5,7 +5,7 @@ import { authContext } from '#shared/auth-context';import { guards } from '#shared/guards';import { assertPermission, requireUser } from '#shared/access';import { HttpError } from '#shared/lib';-import { accessErrors, commonErrors } from '#shared/responses';+import { accessErrors, commonErrors, errors } from '#shared/responses';import { getRole } from '#modules/roles/service';import {MemberListResponse,@@ -16,12 +16,22 @@ import {import {listMembers,getMembership,+ getMembershipSource,removeMember,setMembership,setMemberDescription,countOwners,} from './service';+// A membership the SCIM group reconciliation owns is rewritten on every sync, so+// editing it here would be undone without trace. The identity provider is where it+// changes.+async function assertNotProvisioned(projectId: number, userId: string): Promise<void> {+ if ((await getMembershipSource(projectId, userId)) === 'scim') {+ throw new HttpError(409, 'This membership is managed by SCIM');+ }+}+export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Members'] } }).use(authContext).use(guards)@@ -47,6 +57,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb}const target = await getMembership(project.id, params.userId);if (!target) throw new HttpError(404, 'Member not found');+ await assertNotProvisioned(project.id, params.userId);if (body.role === 'owner') {await setMembership(project.id, params.userId, 'owner', null);@@ -69,12 +80,13 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Membparams: memberParams,body: setMemberRoleBody,projectOwner: true,- response: { 204: t.Void(), ...commonErrors },+ response: { 204: t.Void(), ...commonErrors, ...errors(409) },detail: {summary: "Update a member's role",description:"Set a member's role. 'owner' promotes to owner; 'member' assigns a custom role by " +- 'roleId, or null for the default. The last owner cannot be demoted.',+ 'roleId, or null for the default. The last owner cannot be demoted, and a membership ' ++ 'granted by a provisioned group is managed by the identity provider.',...mcpTool('set_member_role'),},},@@ -121,6 +133,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb}const target = await getMembership(project.id, params.userId);if (!target) throw new HttpError(404, 'Member not found');+ await assertNotProvisioned(project.id, params.userId);if (target === 'owner' && (await countOwners(project.id)) === 1) {throw new HttpError(400, 'A project must have at least one owner');}@@ -130,10 +143,12 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb{params: memberParams,projectMember: true,- response: { 204: t.Void(), ...commonErrors },+ response: { 204: t.Void(), ...commonErrors, ...errors(409) },detail: {summary: 'Remove a member',- description: 'Remove a member from the project, or leave it yourself.',+ description:+ 'Remove a member from the project, or leave it yourself. A membership granted by a ' ++ 'provisioned group is managed by the identity provider.',...mcpTool('remove_member'),},},diff --git a/apps/api/src/modules/members/model.ts b/apps/api/src/modules/members/model.tsindex 21a25775..0df04f55 100644--- a/apps/api/src/modules/members/model.ts+++ b/apps/api/src/modules/members/model.ts@@ -17,6 +17,9 @@ const MemberResponse = t.Object({roleName: t.Nullable(t.String()),description: t.String(),isAgent: t.Boolean(),+ // 'scim' when an identity provider's group granted this membership. Such a row is+ // rewritten on every sync, so the role and remove actions are refused.+ source: t.UnionEnum(['invite', 'scim']),createdAt: t.String(),});diff --git a/apps/api/src/modules/members/service.ts b/apps/api/src/modules/members/service.tsindex 2c0e816e..0a6d4a62 100644--- a/apps/api/src/modules/members/service.ts+++ b/apps/api/src/modules/members/service.ts@@ -23,6 +23,10 @@ import {export type MemberRole = 'owner' | 'member';+// How a membership came about. 'scim' rows are owned by the group reconciliation,+// which rewrites them on every sync, so they are not editable by hand.+export type MemberSource = 'invite' | 'scim';+export interface MemberRow {userId: string;name: string;@@ -45,6 +49,7 @@ export interface MemberRow {// join by agent creation, not an invite, so their role and access are managed on// the AI Agents screen, not here.isAgent: boolean;+ source: MemberSource;createdAt: string;}@@ -57,6 +62,19 @@ export interface MemberContext {permissions: Permissions;}+// Where a membership came from, or null when the user is not a member. Read by the+// routes that edit a membership, which refuse to touch a row SCIM owns.+export async function getMembershipSource(+ projectId: number,+ userId: string,+): Promise<MemberSource | null> {+ const rows = await db+ .select({ source: projectMember.source })+ .from(projectMember)+ .where(and(eq(projectMember.projectId, projectId), eq(projectMember.userId, userId)));+ return rows[0] ? (rows[0].source as MemberSource) : null;+}+// The current user's role in a project, or null when they are not a member.export async function getMembership(projectId: number, userId: string): Promise<MemberRole | null> {const rows = await db@@ -205,6 +223,7 @@ export async function listMembers(projectId: number): Promise<MemberRow[]> {roleId: projectMember.roleId,roleName: projectRole.name,description: projectMember.description,+ source: projectMember.source,agentId: aiAgent.id,createdAt: projectMember.createdAt,})@@ -227,6 +246,7 @@ export async function listMembers(projectId: number): Promise<MemberRow[]> {roleName: r.roleName,description: r.description,isAgent: r.agentId !== null,+ source: r.source as MemberSource,createdAt: iso(r.createdAt),}));}diff --git a/apps/api/src/modules/scim/__tests__/helpers.ts b/apps/api/src/modules/scim/__tests__/helpers.tsnew file mode 100644index 00000000..4eb3b030--- /dev/null+++ b/apps/api/src/modules/scim/__tests__/helpers.ts@@ -0,0 +1,42 @@+import { scimApi } from '#tests/helpers/app';+import { addUser, type Actor } from '#modules/god/__tests__/helpers';++// Turns SCIM provisioning on and hands back a client that authenticates with the+// generated token, the way an identity provider does.++export interface ScimSetup {+ god: Actor;+ token: string;+ scim: ReturnType<typeof scimApi>;+}++export async function setupScim(): Promise<ScimSetup> {+ const god = await addUser({ name: 'Root', email: '[email protected]' });+ const created = await god.api.god['scim-settings'].token.post();+ const token = created.data!.token;+ await god.api.god['scim-settings'].put({ enabled: true });+ return { god, token, scim: scimApi(token) };+}++// `emails` follows `userName` by default, so overriding just `userName` in a test+// still produces a distinct, matching address — the api reads the account's email+// from `emails` first. Pass `emails` explicitly to test the two attributes+// disagreeing.+export function scimUserBody(overrides: Record<string, unknown> = {}) {+ const userName = (overrides.userName as string | undefined) ?? '[email protected]';+ return {+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName,+ name: { givenName: 'Ada', familyName: 'Lovelace' },+ emails: [{ value: userName, primary: true, type: 'work' }],+ active: true,+ ...overrides,+ };+}++export function patchOps(operations: Record<string, unknown>[]) {+ return {+ schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],+ Operations: operations,+ };+}diff --git a/apps/api/src/modules/scim/__tests__/integration/scim-discovery.test.ts b/apps/api/src/modules/scim/__tests__/integration/scim-discovery.test.tsnew file mode 100644index 00000000..16c2fc01--- /dev/null+++ b/apps/api/src/modules/scim/__tests__/integration/scim-discovery.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, beforeEach } from 'bun:test';+import { api, scimApi } from '#tests/helpers/app';+import { resetDb } from '#tests/helpers/db';+import { addUser } from '#modules/god/__tests__/helpers';+import { setupScim } from '../helpers';++describe('SCIM discovery and authentication', () => {+ beforeEach(resetDb);++ describe('authentication', () => {+ it('refuses a request with no token', async () => {+ await setupScim();++ const res = await api.scim.v2.ServiceProviderConfig.get();++ expect(res.status).toBe(401);+ expect(res.error!.value).toMatchObject({+ schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],+ status: '401',+ });+ });++ it('refuses a wrong token', async () => {+ await setupScim();++ const res = await scimApi('scim_wrong').scim.v2.ServiceProviderConfig.get();++ expect(res.status).toBe(401);+ expect(res.error!.value).toMatchObject({+ schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],+ status: '401',+ });+ });++ it('refuses the right token while provisioning is off', async () => {+ const { god, token } = await setupScim();+ await god.api.god['scim-settings'].put({ enabled: false });++ const res = await scimApi(token).scim.v2.ServiceProviderConfig.get();++ expect(res.status).toBe(401);+ });++ it('refuses a token that has been replaced', async () => {+ const { god, token } = await setupScim();+ await god.api.god['scim-settings'].token.post();++ const res = await scimApi(token).scim.v2.ServiceProviderConfig.get();++ expect(res.status).toBe(401);+ });+ });++ describe('god settings', () => {+ it('refuses a plain user', async () => {+ await addUser({ email: '[email protected]' });+ const user = await addUser({ email: '[email protected]' });++ expect((await user.api.god['scim-settings'].get()).status).toBe(403);+ expect((await user.api.god['scim-settings'].token.post()).status).toBe(403);+ });++ it('refuses to enable provisioning before a token exists', async () => {+ const god = await addUser({ email: '[email protected]' });++ const res = await god.api.god['scim-settings'].put({ enabled: true });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ error: 'Generate a SCIM token first' });+ });++ it('reports the token prefix and the base URL, never the token', async () => {+ const { god, token } = await setupScim();++ const res = await god.api.god['scim-settings'].get();++ expect(res.data).toMatchObject({+ enabled: true,+ hasToken: true,+ baseUrl: 'http://localhost:3000/scim/v2',+ });+ expect(res.data!.tokenPrefix.length).toBeLessThan(token.length);+ expect(token.startsWith(res.data!.tokenPrefix)).toBe(true);+ });+ });++ describe('discovery documents', () => {+ it('describes what the server supports', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.ServiceProviderConfig.get();++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({+ patch: { supported: true },+ filter: { supported: true },+ bulk: { supported: false },+ sort: { supported: false },+ changePassword: { supported: false },+ });+ });++ it('lists the two resource types and serves each one', async () => {+ const { scim } = await setupScim();++ const list = await scim.scim.v2.ResourceTypes.get();+ expect(list.data).toMatchObject({+ schemas: ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],+ totalResults: 2,+ });++ const one = await scim.scim.v2.ResourceTypes({ id: 'User' }).get();+ expect(one.data).toMatchObject({ id: 'User', endpoint: '/Users' });++ expect((await scim.scim.v2.ResourceTypes({ id: 'Nope' }).get()).status).toBe(404);+ });++ it('lists the two schemas and serves each one', async () => {+ const { scim } = await setupScim();++ const list = await scim.scim.v2.Schemas.get();+ expect(list.data).toMatchObject({ totalResults: 2 });++ const one = await scim.scim.v2+ .Schemas({ id: 'urn:ietf:params:scim:schemas:core:2.0:User' })+ .get();+ expect(one.data).toMatchObject({ name: 'User' });++ expect((await scim.scim.v2.Schemas({ id: 'urn:nope' }).get()).status).toBe(404);+ });+ });+});diff --git a/apps/api/src/modules/scim/__tests__/integration/scim-groups.test.ts b/apps/api/src/modules/scim/__tests__/integration/scim-groups.test.tsnew file mode 100644index 00000000..022776c9--- /dev/null+++ b/apps/api/src/modules/scim/__tests__/integration/scim-groups.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it, beforeEach } from 'bun:test';+import { resetDb } from '#tests/helpers/db';+import { patchOps, scimUserBody, setupScim } from '../helpers';++const groupBody = (overrides: Record<string, unknown> = {}) => ({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:Group'],+ displayName: 'Engineering',+ ...overrides,+});++describe('SCIM groups', () => {+ beforeEach(resetDb);++ describe('POST /scim/v2/Groups', () => {+ it('provisions a group with its members', async () => {+ const { scim } = await setupScim();+ const ada = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2.Groups.post(+ groupBody({ externalId: 'idp-eng', members: [{ value: ada.data!.id }] }),+ );++ expect(res.status).toBe(201);+ expect(res.data).toMatchObject({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:Group'],+ displayName: 'Engineering',+ externalId: 'idp-eng',+ members: [{ value: ada.data!.id, display: 'Ada Lovelace' }],+ meta: { resourceType: 'Group' },+ });+ });++ it('refuses a name another group already has', async () => {+ const { scim } = await setupScim();+ await scim.scim.v2.Groups.post(groupBody());++ const res = await scim.scim.v2.Groups.post(groupBody());++ expect(res.status).toBe(409);+ expect(res.error!.value).toMatchObject({ scimType: 'uniqueness' });+ });++ it('refuses a member id that has no account', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Groups.post(groupBody({ members: [{ value: 'nobody' }] }));++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidValue' });+ });++ it('refuses a body with no displayName', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Groups.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:Group'],+ });++ expect(res.status).toBe(400);+ });+ });++ describe('GET /scim/v2/Groups', () => {+ it('lists the groups and finds one by displayName', async () => {+ const { scim } = await setupScim();+ await scim.scim.v2.Groups.post(groupBody());+ await scim.scim.v2.Groups.post(groupBody({ displayName: 'Design' }));++ const all = await scim.scim.v2.Groups.get({ query: {} });+ expect(all.data).toMatchObject({ totalResults: 2 });++ const one = await scim.scim.v2.Groups.get({+ query: { filter: 'displayName eq "Design"' },+ });+ expect(one.data).toMatchObject({ totalResults: 1 });+ expect(one.data!.Resources[0]).toMatchObject({ displayName: 'Design' });+ });++ it('refuses a filter it does not implement', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Groups.get({ query: { filter: 'members eq "x"' } });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidFilter' });+ });+ });++ describe('GET /scim/v2/Groups/:id', () => {+ it('serves one group and 404s an unknown id', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Groups.post(groupBody());++ expect((await scim.scim.v2.Groups({ id: created.data!.id }).get()).status).toBe(200);+ expect(+ (await scim.scim.v2.Groups({ id: '00000000-0000-4000-8000-000000000000' }).get()).status,+ ).toBe(404);+ });+ });++ describe('PUT /scim/v2/Groups/:id', () => {+ it('replaces the name and the whole member list', async () => {+ const { scim } = await setupScim();+ const ada = await scim.scim.v2.Users.post(scimUserBody());+ const grace = await scim.scim.v2.Users.post(scimUserBody({ userName: '[email protected]' }));+ const created = await scim.scim.v2.Groups.post(+ groupBody({ members: [{ value: ada.data!.id }] }),+ );++ const res = await scim.scim.v2+ .Groups({ id: created.data!.id })+ .put(groupBody({ displayName: 'Platform', members: [{ value: grace.data!.id }] }));++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ displayName: 'Platform' });+ expect(res.data!.members.map((m) => m.value)).toEqual([grace.data!.id]);+ });+ });++ describe('PATCH /scim/v2/Groups/:id', () => {+ it('adds and removes members', async () => {+ const { scim } = await setupScim();+ const ada = await scim.scim.v2.Users.post(scimUserBody());+ const grace = await scim.scim.v2.Users.post(scimUserBody({ userName: '[email protected]' }));+ const created = await scim.scim.v2.Groups.post(groupBody());++ const added = await scim.scim.v2.Groups({ id: created.data!.id }).patch(+ patchOps([+ { op: 'add', path: 'members', value: [{ value: ada.data!.id }] },+ { op: 'add', path: 'members', value: [{ value: grace.data!.id }] },+ ]),+ );+ expect(added.data!.members.map((m) => m.value).sort()).toEqual(+ [ada.data!.id, grace.data!.id].sort(),+ );++ const removed = await scim.scim.v2+ .Groups({ id: created.data!.id })+ .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: ada.data!.id }] }]));+ expect(removed.data!.members.map((m) => m.value)).toEqual([grace.data!.id]);+ });++ it('removes a member addressed by the RFC 7644 path filter, as Okta sends it', async () => {+ const { scim } = await setupScim();+ const ada = await scim.scim.v2.Users.post(scimUserBody());+ const grace = await scim.scim.v2.Users.post(scimUserBody({ userName: '[email protected]' }));+ const created = await scim.scim.v2.Groups.post(+ groupBody({ members: [{ value: ada.data!.id }, { value: grace.data!.id }] }),+ );++ const res = await scim.scim.v2+ .Groups({ id: created.data!.id })+ .patch(patchOps([{ op: 'remove', path: `members[value eq "${ada.data!.id}"]` }]));++ expect(res.data!.members.map((m) => m.value)).toEqual([grace.data!.id]);+ });++ it('renames the group', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Groups.post(groupBody());++ const res = await scim.scim.v2+ .Groups({ id: created.data!.id })+ .patch(patchOps([{ op: 'replace', path: 'displayName', value: 'Platform' }]));++ expect(res.data).toMatchObject({ displayName: 'Platform' });+ });++ it('refuses an attribute it cannot write', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Groups.post(groupBody());++ const res = await scim.scim.v2+ .Groups({ id: created.data!.id })+ .patch(patchOps([{ op: 'replace', path: 'description', value: 'nope' }]));++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidPath' });+ });+ });++ describe('DELETE /scim/v2/Groups/:id', () => {+ it('removes the group', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Groups.post(groupBody());++ expect((await scim.scim.v2.Groups({ id: created.data!.id }).delete()).status).toBe(204);+ expect((await scim.scim.v2.Groups({ id: created.data!.id }).get()).status).toBe(404);+ });++ it('404s an unknown id', async () => {+ const { scim } = await setupScim();++ expect(+ (await scim.scim.v2.Groups({ id: '00000000-0000-4000-8000-000000000000' }).delete()).status,+ ).toBe(404);+ });+ });+});diff --git a/apps/api/src/modules/scim/__tests__/integration/scim-reconcile.test.ts b/apps/api/src/modules/scim/__tests__/integration/scim-reconcile.test.tsnew file mode 100644index 00000000..b2c9e79d--- /dev/null+++ b/apps/api/src/modules/scim/__tests__/integration/scim-reconcile.test.ts@@ -0,0 +1,383 @@+import { describe, expect, it, beforeEach } from 'bun:test';+import { resetDb } from '#tests/helpers/db';+import { addUser, joinProject, type Actor } from '#modules/god/__tests__/helpers';+import { patchOps, scimUserBody, setupScim, type ScimSetup } from '../helpers';++// What a provisioned group grants: the mappings the instance owner declares in god+// mode turn group membership into project membership. Only the rows the sync owns+// are ever touched, so a membership somebody set up through an invite survives.++async function createProject(owner: Actor, name: string, key: string) {+ const created = await owner.api.projects.post({ name, key });+ return created.data!;+}++async function membersOf(owner: Actor, projectKey: string) {+ const res = await owner.api.projects({ projectKey }).members.get();+ return res.data!;+}++async function provisionGroup(setup: ScimSetup, displayName: string, memberIds: string[]) {+ const created = await setup.scim.scim.v2.Groups.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:Group'],+ displayName,+ members: memberIds.map((value) => ({ value })),+ });+ return created.data!.id;+}++describe('SCIM group reconciliation', () => {+ beforeEach(resetDb);++ it('grants membership at the mapped role when a group is mapped', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);++ const res = await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],+ });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({+ displayName: 'Engineering',+ memberCount: 1,+ mappings: [{ projectId: project.id, projectKey: 'MKT', role: 'member' }],+ });++ const members = await membersOf(setup.god, 'MKT');+ expect(members).toContainEqual(+ expect.objectContaining({ userId: ada.data!.id, role: 'member', source: 'scim' }),+ );+ });++ it('assigns the project role named in the mapping', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const role = await setup.god.api.projects({ projectKey: 'MKT' }).roles.post({+ name: 'Reviewer',+ permissions: {},+ });+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);++ await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'member', roleId: role.data!.id }],+ });++ const members = await membersOf(setup.god, 'MKT');+ expect(members).toContainEqual(+ expect.objectContaining({ userId: ada.data!.id, roleId: role.data!.id }),+ );+ });++ it('revokes membership when the member leaves the group', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);+ await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],+ });++ await setup.scim.scim.v2+ .Groups({ id: groupId })+ .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: ada.data!.id }] }]));++ const members = await membersOf(setup.god, 'MKT');+ expect(members.map((m) => m.userId)).not.toContain(ada.data!.id);+ });++ it('revokes membership when the group is unmapped, and when it is deleted', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);+ const mapTo = (mappings: { projectId: number; role: 'owner' | 'member'; roleId: null }[]) =>+ setup.god.api.god['scim-groups']({ groupId }).mappings.put({ mappings });++ await mapTo([{ projectId: project.id, role: 'member', roleId: null }]);+ await mapTo([]);+ expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).not.toContain(ada.data!.id);++ await mapTo([{ projectId: project.id, role: 'member', roleId: null }]);+ expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).toContain(ada.data!.id);++ await setup.scim.scim.v2.Groups({ id: groupId }).delete();+ expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).not.toContain(ada.data!.id);+ });++ it('leaves a membership that came from an invite alone', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const invited = await addUser({ email: '[email protected]' });+ await joinProject(setup.god, invited, 'MKT', 'member');+ const groupId = await provisionGroup(setup, 'Engineering', [invited.id]);++ // Mapped as owner, but the invited membership outranks it and is not re-roled.+ await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'owner', roleId: null }],+ });+ let members = await membersOf(setup.god, 'MKT');+ expect(members).toContainEqual(+ expect.objectContaining({ userId: invited.id, role: 'member', source: 'invite' }),+ );++ // And removing them from the group does not take the invited membership away.+ await setup.scim.scim.v2+ .Groups({ id: groupId })+ .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: invited.id }] }]));+ members = await membersOf(setup.god, 'MKT');+ expect(members.map((m) => m.userId)).toContain(invited.id);+ });++ it('resolves a user in two mappings to the stronger role', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const members = await provisionGroup(setup, 'Members', [ada.data!.id]);+ const leads = await provisionGroup(setup, 'Leads', [ada.data!.id]);++ await setup.god.api.god['scim-groups']({ groupId: members }).mappings.put({+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],+ });+ await setup.god.api.god['scim-groups']({ groupId: leads }).mappings.put({+ mappings: [{ projectId: project.id, role: 'owner', roleId: null }],+ });++ expect(await membersOf(setup.god, 'MKT')).toContainEqual(+ expect.objectContaining({ userId: ada.data!.id, role: 'owner' }),+ );+ });++ it('keeps the last owner even when the group no longer grants it', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const groupId = await provisionGroup(setup, 'Leads', [ada.data!.id]);+ await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'owner', roleId: null }],+ });+ // The creator leaves, which the second owner makes possible. The project is+ // now owned by the provisioned membership alone.+ await setup.god.api.projects({ projectKey: 'MKT' }).members({ userId: setup.god.id }).delete();++ await setup.scim.scim.v2+ .Groups({ id: groupId })+ .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: ada.data!.id }] }]));++ // Read through god mode: the creator is no longer a member, so the project's+ // own members route is closed to them.+ const detail = await setup.god.api.god.users({ userId: ada.data!.id }).get();+ expect(detail.data!.projects).toContainEqual(+ expect.objectContaining({ projectKey: 'MKT', role: 'owner' }),+ );+ });++ it('refuses to edit or remove a membership the sync owns', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);+ await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],+ });++ const promoted = await setup.god.api+ .projects({ projectKey: 'MKT' })+ .members({ userId: ada.data!.id })+ .patch({ role: 'owner' });+ expect(promoted.status).toBe(409);+ expect(promoted.error!.value).toMatchObject({ error: 'This membership is managed by SCIM' });++ const removed = await setup.god.api+ .projects({ projectKey: 'MKT' })+ .members({ userId: ada.data!.id })+ .delete();+ expect(removed.status).toBe(409);+ });++ describe('mapping validation', () => {+ it('404s an unknown group', async () => {+ const setup = await setupScim();++ const res = await setup.god.api.god['scim-groups']({+ groupId: '00000000-0000-4000-8000-000000000000',+ }).mappings.put({ mappings: [] });++ expect(res.status).toBe(404);+ });++ it('refuses an unknown project', async () => {+ const setup = await setupScim();+ const groupId = await provisionGroup(setup, 'Engineering', []);++ const res = await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: 987654, role: 'member', roleId: null }],+ });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ error: 'Unknown project' });+ });++ it('refuses a role that belongs to another project', async () => {+ const setup = await setupScim();+ const marketing = await createProject(setup.god, 'Marketing', 'MKT');+ await createProject(setup.god, 'Design', 'DSN');+ const role = await setup.god.api.projects({ projectKey: 'DSN' }).roles.post({+ name: 'Reviewer',+ permissions: {},+ });+ const groupId = await provisionGroup(setup, 'Engineering', []);++ const res = await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: marketing.id, role: 'member', roleId: role.data!.id }],+ });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({+ error: 'The role does not belong to that project',+ });+ });++ it('refuses the same project twice', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const groupId = await provisionGroup(setup, 'Engineering', []);++ const res = await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [+ { projectId: project.id, role: 'member', roleId: null },+ { projectId: project.id, role: 'owner', roleId: null },+ ],+ });++ expect(res.status).toBe(400);+ });++ it('refuses a plain user', async () => {+ const setup = await setupScim();+ const user = await addUser({ email: '[email protected]' });+ const groupId = await provisionGroup(setup, 'Engineering', []);++ expect((await user.api.god['scim-groups'].get()).status).toBe(403);+ expect(+ (await user.api.god['scim-groups']({ groupId }).mappings.put({ mappings: [] })).status,+ ).toBe(403);+ });+ });++ // A directory that never calls POST /Groups still grants access this way: it+ // embeds the groups a user belongs to right on the user payload, which is what+ // "push groups" means in some identity providers instead of a separate sync.+ describe('groups embedded on a user', () => {+ it('creates the group from a userless sync and adds the account to it', async () => {+ const setup = await setupScim();++ const created = await setup.scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: [{ display: 'Engineering' }],+ });++ const groups = await setup.god.api.god['scim-groups'].get();+ expect(groups.data).toContainEqual(+ expect.objectContaining({ displayName: 'Engineering', memberCount: 1 }),+ );+ expect(groups.data!.find((g) => g.displayName === 'Engineering')!.mappings).toEqual([]);+ expect(created.status).toBe(201);+ });++ it('falls back to value when the provider sends no display name', async () => {+ const setup = await setupScim();++ await setup.scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: [{ value: 'Engineering' }],+ });++ const groups = await setup.god.api.god['scim-groups'].get();+ expect(groups.data).toContainEqual(+ expect.objectContaining({ displayName: 'Engineering', memberCount: 1 }),+ );+ });++ // The same parser reads an OIDC `groups` claim, which is conventionally a bare+ // array of names rather than SCIM's `{ value, display }` refs.+ it('accepts a plain array of group names', async () => {+ const setup = await setupScim();++ await setup.scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: ['Engineering', 'Design'],+ });++ const groups = await setup.god.api.god['scim-groups'].get();+ expect(groups.data!.map((g) => g.displayName).sort()).toEqual(['Design', 'Engineering']);+ });++ it('grants project access right away when the group is already mapped', async () => {+ const setup = await setupScim();+ const project = await createProject(setup.god, 'Marketing', 'MKT');+ const groupId = await provisionGroup(setup, 'Engineering', []);+ await setup.god.api.god['scim-groups']({ groupId }).mappings.put({+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],+ });++ const created = await setup.scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: [{ display: 'Engineering' }],+ });++ const members = await membersOf(setup.god, 'MKT');+ expect(members).toContainEqual(+ expect.objectContaining({ userId: created.data!.id, role: 'member', source: 'scim' }),+ );+ });++ it('does not duplicate a group already pushed through POST /Groups', async () => {+ const setup = await setupScim();+ const groupId = await provisionGroup(setup, 'Engineering', []);++ await setup.scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: [{ display: 'Engineering' }],+ });++ const groups = await setup.god.api.god['scim-groups'].get();+ expect(groups.data!.filter((g) => g.displayName === 'Engineering')).toHaveLength(1);+ expect(groups.data!.find((g) => g.id === groupId)!.memberCount).toBe(1);+ });++ it('adds an updated group without removing the ones already there', async () => {+ const setup = await setupScim();++ const created = await setup.scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: [{ display: 'Engineering' }],+ });+ await setup.scim.scim.v2.Users({ id: created.data!.id }).put({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ emails: [{ value: '[email protected]', primary: true }],+ groups: [{ display: 'Design' }],+ });++ const groups = await setup.god.api.god['scim-groups'].get();+ expect(groups.data!.find((g) => g.displayName === 'Engineering')!.memberCount).toBe(1);+ expect(groups.data!.find((g) => g.displayName === 'Design')!.memberCount).toBe(1);+ });+ });+});diff --git a/apps/api/src/modules/scim/__tests__/integration/scim-users.test.ts b/apps/api/src/modules/scim/__tests__/integration/scim-users.test.tsnew file mode 100644index 00000000..693bd155--- /dev/null+++ b/apps/api/src/modules/scim/__tests__/integration/scim-users.test.ts@@ -0,0 +1,480 @@+import { describe, expect, it, beforeEach } from 'bun:test';+import { app, authedApi } from '#tests/helpers/app';+import { resetDb } from '#tests/helpers/db';+import { signUpTestUser } from '#tests/helpers/auth';+import { addUser, createAgentUser } from '#modules/god/__tests__/helpers';+import { patchOps, scimUserBody, setupScim } from '../helpers';++describe('SCIM users', () => {+ beforeEach(resetDb);++ describe('POST /scim/v2/Users', () => {+ it('provisions an account and returns it as a SCIM user', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.post(scimUserBody({ externalId: 'idp-1' }));++ expect(res.status).toBe(201);+ expect(res.data).toMatchObject({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ externalId: 'idp-1',+ displayName: 'Ada Lovelace',+ name: { givenName: 'Ada', familyName: 'Lovelace', formatted: 'Ada Lovelace' },+ emails: [{ value: '[email protected]', primary: true }],+ active: true,+ meta: { resourceType: 'User' },+ });+ expect(res.data!.id).toBeTruthy();+ });++ it('accepts a user whose address only comes in the primary email', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ emails: [+ { value: '[email protected]', primary: false },+ { value: '[email protected]', primary: true },+ ],+ displayName: 'Grace Hopper',+ });++ expect(res.status).toBe(201);+ expect(res.data).toMatchObject({ userName: '[email protected]' });+ });++ it('prefers the emails attribute over userName when both are present', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ // A directory that mixes a non-email login id into userName while still+ // reporting the real address in emails.+ userName: 'ada.lovelace',+ emails: [{ value: '[email protected]', primary: true }],+ displayName: 'Ada Lovelace',+ });++ expect(res.status).toBe(201);+ expect(res.data).toMatchObject({ userName: '[email protected]' });+ });++ it('accepts userName as a fallback address when it looks like one', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: '[email protected]',+ displayName: 'Ada Lovelace',+ });++ expect(res.status).toBe(201);+ expect(res.data).toMatchObject({ userName: '[email protected]' });+ });++ it('refuses a userName that is not an email when emails is absent', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ userName: 'ada.lovelace',+ displayName: 'Ada Lovelace',+ });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidValue' });+ });++ it('refuses a body with no identifier', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.post({+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],+ displayName: 'Nobody',+ });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidValue' });+ });++ it('refuses to provision an address already linked to the provider', async () => {+ // A retry (Okta repeats a create after a timeout) must not silently+ // overwrite the id that links the account back to the provider.+ const { scim } = await setupScim();+ const first = await scim.scim.v2.Users.post(scimUserBody({ externalId: 'idp-1' }));++ const second = await scim.scim.v2.Users.post(+ scimUserBody({ externalId: 'idp-1-reprovisioned' }),+ );++ expect(second.status).toBe(409);+ expect(second.error!.value).toMatchObject({ scimType: 'uniqueness' });+ const unchanged = await scim.scim.v2.Users({ id: first.data!.id }).get();+ expect(unchanged.data!.externalId).toBe('idp-1');+ });++ it('claims an account that predates the sync, matching the address by case', async () => {+ const { scim } = await setupScim();+ const existing = await signUpTestUser({ email: '[email protected]' });++ const res = await scim.scim.v2.Users.post(+ scimUserBody({ userName: '[email protected]' }),+ );++ expect(res.status).toBe(201);+ expect(res.data!.id).toBe(existing.userId);+ const list = await scim.scim.v2.Users.get({ query: {} });+ expect(list.data!.Resources.filter((u) => u.id === existing.userId)).toHaveLength(1);+ });++ it("refuses to claim the instance owner's account", async () => {+ const { god, scim } = await setupScim();++ const res = await scim.scim.v2.Users.post(scimUserBody({ userName: god.email }));++ expect(res.status).toBe(409);+ expect(res.error!.value).toMatchObject({+ detail: 'An instance owner cannot be provisioned through SCIM',+ });+ });++ // RFC 7644 §3.1 lets a SCIM client send this content type instead of+ // application/json, and real identity providers (Okta, Entra, Authentik) do.+ // Eden Treaty always sends application/json, so this goes through app.handle+ // directly with the header set by hand.+ it('accepts a body sent as application/scim+json', async () => {+ const { token } = await setupScim();++ const res = await app.handle(+ new Request('http://localhost/scim/v2/Users', {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/scim+json',+ },+ body: JSON.stringify(scimUserBody()),+ }),+ );++ expect(res.status).toBe(201);+ const body = (await res.json()) as { userName: string };+ expect(body.userName).toBe('[email protected]');+ });++ it('provisions on a closed instance, where signing up is refused', async () => {+ const { god, scim } = await setupScim();+ await god.api.god['auth-settings'].put({ registration: 'closed' });++ const res = await scim.scim.v2.Users.post(scimUserBody());++ expect(res.status).toBe(201);+ });+ });++ describe('GET /scim/v2/Users', () => {+ it('pages the accounts and reports the total', async () => {+ const { scim } = await setupScim();+ await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2.Users.get({ query: { startIndex: 1, count: 10 } });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({+ schemas: ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],+ // The instance owner registered in setupScim counts too.+ totalResults: 2,+ startIndex: 1,+ itemsPerPage: 2,+ });+ });++ it('finds one account by userName', async () => {+ const { scim } = await setupScim();+ await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2.Users.get({+ query: { filter: 'userName eq "[email protected]"' },+ });++ expect(res.data).toMatchObject({ totalResults: 1 });+ expect(res.data!.Resources[0]).toMatchObject({ userName: '[email protected]' });+ });++ it('finds one account by externalId', async () => {+ const { scim } = await setupScim();+ await scim.scim.v2.Users.post(scimUserBody({ externalId: 'idp-7' }));++ const res = await scim.scim.v2.Users.get({ query: { filter: 'externalId eq "idp-7"' } });++ expect(res.data).toMatchObject({ totalResults: 1 });+ });++ it('answers an empty list for an address that has no account', async () => {+ const { scim } = await setupScim();++ const res = await scim.scim.v2.Users.get({ query: { filter: 'userName eq "[email protected]"' } });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ totalResults: 0, Resources: [] });+ });++ it('refuses a filter it does not implement', async () => {+ const { scim } = await setupScim();++ const unsupportedOperator = await scim.scim.v2.Users.get({+ query: { filter: 'userName co "ada"' },+ });+ expect(unsupportedOperator.status).toBe(400);+ expect(unsupportedOperator.error!.value).toMatchObject({ scimType: 'invalidFilter' });++ const unsupportedAttribute = await scim.scim.v2.Users.get({+ query: { filter: 'nickName eq "ada"' },+ });+ expect(unsupportedAttribute.status).toBe(400);+ expect(unsupportedAttribute.error!.value).toMatchObject({ scimType: 'invalidFilter' });+ });+ });++ describe("AI agents' accounts", () => {+ // An agent's bot user belongs to the project that created it, not to the identity+ // provider. Letting a sync reach it would let it rename the agent or deactivate+ // it, which stops the agent without a trace.+ it('leaves them out of the list, and 404s every route that names one', async () => {+ const { god, scim } = await setupScim();+ const project = await god.api.projects.post({ name: 'Agents', key: 'AGT' });+ const agentUserId = await createAgentUser(god, project.data!.key);++ const list = await scim.scim.v2.Users.get({ query: {} });+ expect(list.data!.Resources.map((u) => u.id)).not.toContain(agentUserId);++ expect((await scim.scim.v2.Users({ id: agentUserId }).get()).status).toBe(404);+ expect((await scim.scim.v2.Users({ id: agentUserId }).put(scimUserBody())).status).toBe(404);+ expect(+ (+ await scim.scim.v2+ .Users({ id: agentUserId })+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]))+ ).status,+ ).toBe(404);+ });+ });++ describe('GET /scim/v2/Users/:id', () => {+ it('serves one account and 404s an unknown id', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2.Users({ id: created.data!.id }).get();+ expect(res.data).toMatchObject({ userName: '[email protected]' });++ expect((await scim.scim.v2.Users({ id: 'nope' }).get()).status).toBe(404);+ });+ });++ describe('PUT /scim/v2/Users/:id', () => {+ it('replaces the account', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody({ externalId: 'idp-1' }));++ const res = await scim.scim.v2.Users({ id: created.data!.id }).put(+ scimUserBody({+ userName: '[email protected]',+ name: { givenName: 'Ada', familyName: 'Byron' },+ externalId: 'idp-1',+ }),+ );++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({+ userName: '[email protected]',+ displayName: 'Ada Byron',+ });+ });++ it('refuses an address another account already has', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());+ await scim.scim.v2.Users.post(scimUserBody({ userName: '[email protected]' }));++ const res = await scim.scim.v2+ .Users({ id: created.data!.id })+ .put(scimUserBody({ userName: '[email protected]' }));++ expect(res.status).toBe(409);+ });++ it('refuses the instance owner', async () => {+ const { god, scim } = await setupScim();++ const res = await scim.scim.v2.Users({ id: god.id }).put(scimUserBody());++ expect(res.status).toBe(409);+ expect(res.error!.value).toMatchObject({+ detail: 'An instance owner cannot be updated through SCIM',+ });+ });+ });++ describe('PATCH /scim/v2/Users/:id', () => {+ it('deactivates an account and cuts off its open session', async () => {+ const { scim } = await setupScim();+ const member = await signUpTestUser({ email: '[email protected]' });+ const session = authedApi(member.cookie);+ expect((await session.projects.get()).status).toBe(200);++ const res = await scim.scim.v2+ .Users({ id: member.userId })+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ active: false });+ expect((await session.projects.get()).status).toBe(401);+ expect((await session.me.get()).data).toMatchObject({ authenticated: false });+ });++ it('lets a reactivated account back in', async () => {+ const { scim } = await setupScim();+ const member = await signUpTestUser({ email: '[email protected]' });+ const session = authedApi(member.cookie);+ await scim.scim.v2+ .Users({ id: member.userId })+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));++ await scim.scim.v2+ .Users({ id: member.userId })+ .patch(patchOps([{ op: 'replace', path: 'active', value: true }]));++ expect((await session.projects.get()).status).toBe(200);+ expect((await session.me.get()).data).toMatchObject({ authenticated: true });+ });++ it('refuses a deactivated account a new sign-in', async () => {+ const { scim } = await setupScim();+ const member = await signUpTestUser({ email: '[email protected]' });+ await scim.scim.v2+ .Users({ id: member.userId })+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));++ const res = await app.handle(+ new Request('http://localhost/api/auth/sign-in/email', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ email: member.email, password: 'test-password-123' }),+ }),+ );++ expect(res.status).toBe(403);+ });++ it('accepts the path-less replace some providers send', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2+ .Users({ id: created.data!.id })+ .patch(patchOps([{ op: 'replace', value: { active: false, displayName: 'Ada L.' } }]));++ expect(res.data).toMatchObject({ active: false, displayName: 'Ada L.' });+ });++ it('updates one part of the name and keeps the other', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2+ .Users({ id: created.data!.id })+ .patch(patchOps([{ op: 'replace', path: 'name.familyName', value: 'Byron' }]));++ expect(res.data).toMatchObject({ name: { givenName: 'Ada', familyName: 'Byron' } });+ });++ it('refuses an attribute it cannot write', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2+ .Users({ id: created.data!.id })+ .patch(patchOps([{ op: 'replace', path: 'title', value: 'Countess' }]));++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidPath' });+ });++ it('refuses a body that is not a PatchOp', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2+ .Users({ id: created.data!.id })+ .patch({ Operations: [{ op: 'replace', path: 'active', value: false }] });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ scimType: 'invalidSyntax' });+ });++ it('refuses to deactivate the instance owner', async () => {+ const { god, scim } = await setupScim();++ const res = await scim.scim.v2+ .Users({ id: god.id })+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));++ expect(res.status).toBe(409);+ expect(res.error!.value).toMatchObject({+ detail: 'An instance owner cannot be updated through SCIM',+ });+ });+ });++ describe('DELETE /scim/v2/Users/:id', () => {+ it('removes the account', async () => {+ const { scim } = await setupScim();+ const created = await scim.scim.v2.Users.post(scimUserBody());++ const res = await scim.scim.v2.Users({ id: created.data!.id }).delete();++ expect(res.status).toBe(204);+ expect((await scim.scim.v2.Users({ id: created.data!.id }).get()).status).toBe(404);+ });++ it('refuses the instance owner', async () => {+ const { god, scim } = await setupScim();++ const res = await scim.scim.v2.Users({ id: god.id }).delete();++ expect(res.status).toBe(409);+ expect(res.error!.value).toMatchObject({ detail: 'An instance owner cannot be deleted' });+ });++ it("does not see an AI agent's account", async () => {+ const { god, scim } = await setupScim();+ const project = await god.api.projects.post({ name: 'Agents', key: 'AGT' });+ const agentUserId = await createAgentUser(god, project.data!.key);++ const res = await scim.scim.v2.Users({ id: agentUserId }).delete();++ expect(res.status).toBe(404);+ });++ it('refuses the only owner of a project', async () => {+ const { god, scim } = await setupScim();+ const owner = await addUser({ email: '[email protected]' });+ await owner.api.projects.post({ name: 'Solo', key: 'SOL' });+ expect(god.id).not.toBe(owner.id);++ const res = await scim.scim.v2.Users({ id: owner.id }).delete();++ expect(res.status).toBe(409);+ expect(res.error!.value).toMatchObject({+ detail: expect.stringContaining('only owner of a project'),+ });+ });++ it('404s an unknown id', async () => {+ const { scim } = await setupScim();++ expect((await scim.scim.v2.Users({ id: 'nope' }).delete()).status).toBe(404);+ });+ });+});diff --git a/apps/api/src/modules/scim/__tests__/unit/oidc-sync.test.ts b/apps/api/src/modules/scim/__tests__/unit/oidc-sync.test.tsnew file mode 100644index 00000000..e21077b8--- /dev/null+++ b/apps/api/src/modules/scim/__tests__/unit/oidc-sync.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'bun:test';+import { decodeJwtPayload } from '../../oidc-sync';++function jwt(payload: Record<string, unknown>): string {+ const header = Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url');+ const body = Buffer.from(JSON.stringify(payload)).toString('base64url');+ // No signature: decoding never checks one, so an empty third segment is enough.+ return `${header}.${body}.`;+}++describe('decodeJwtPayload', () => {+ it('reads the claims out of the payload segment', () => {+ const token = jwt({ sub: 'user-1', groups: ['Engineering', 'Design'] });++ expect(decodeJwtPayload(token)).toEqual({ sub: 'user-1', groups: ['Engineering', 'Design'] });+ });++ it('decodes a payload whose base64url length needs padding', () => {+ // Payload lengths that are not a multiple of 4 once base64url-encoded are the+ // case the padding logic exists for.+ const token = jwt({ a: '1' });++ expect(decodeJwtPayload(token)).toEqual({ a: '1' });+ });++ it('returns null for a string with no payload segment', () => {+ expect(decodeJwtPayload('not-a-jwt')).toBeNull();+ });++ it('returns null for a payload segment that is not valid JSON', () => {+ const token = `${Buffer.from('{}').toString('base64url')}.not-base64-json.`;++ expect(decodeJwtPayload(token)).toBeNull();+ });+});diff --git a/apps/api/src/modules/scim/discovery.ts b/apps/api/src/modules/scim/discovery.tsnew file mode 100644index 00000000..4a4b8566--- /dev/null+++ b/apps/api/src/modules/scim/discovery.ts@@ -0,0 +1,130 @@+import { SCIM_BASE_URL } from './resource';++// The discovery documents of RFC 7643 §6. A provisioning client reads these before+// its first sync to learn what the server supports, so they describe what is+// actually implemented — filtering is `eq` only, and nothing is sorted or bulked.++const MAX_FILTER_RESULTS = 200;++export const SERVICE_PROVIDER_CONFIG = {+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig'],+ documentationUri: 'https://datatracker.ietf.org/doc/html/rfc7644',+ patch: { supported: true },+ bulk: { supported: false, maxOperations: 0, maxPayloadSize: 0 },+ filter: { supported: true, maxResults: MAX_FILTER_RESULTS },+ changePassword: { supported: false },+ sort: { supported: false },+ etag: { supported: false },+ authenticationSchemes: [+ {+ type: 'oauthbearertoken',+ name: 'OAuth Bearer Token',+ description: 'Authentication with the instance SCIM token, generated in god mode.',+ specUri: 'https://datatracker.ietf.org/doc/html/rfc6750',+ primary: true,+ },+ ],+ meta: {+ resourceType: 'ServiceProviderConfig',+ location: `${SCIM_BASE_URL}/ServiceProviderConfig`,+ },+};++export const RESOURCE_TYPES = [+ {+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:ResourceType'],+ id: 'User',+ name: 'User',+ endpoint: '/Users',+ description: 'An account on this instance.',+ schema: 'urn:ietf:params:scim:schemas:core:2.0:User',+ schemaExtensions: [],+ meta: { resourceType: 'ResourceType', location: `${SCIM_BASE_URL}/ResourceTypes/User` },+ },+ {+ schemas: ['urn:ietf:params:scim:schemas:core:2.0:ResourceType'],+ id: 'Group',+ name: 'Group',+ endpoint: '/Groups',+ description: 'A group of accounts. What it grants is configured in god mode.',+ schema: 'urn:ietf:params:scim:schemas:core:2.0:Group',+ schemaExtensions: [],+ meta: { resourceType: 'ResourceType', location: `${SCIM_BASE_URL}/ResourceTypes/Group` },+ },+];++function attribute(options: {+ name: string;+ type?: string;+ multiValued?: boolean;+ required?: boolean;+ uniqueness?: string;+ mutability?: string;+ subAttributes?: unknown[];+}) {+ return {+ name: options.name,+ type: options.type ?? 'string',+ multiValued: options.multiValued ?? false,+ required: options.required ?? false,+ caseExact: false,+ mutability: options.mutability ?? 'readWrite',+ returned: 'default',+ uniqueness: options.uniqueness ?? 'none',+ ...(options.subAttributes ? { subAttributes: options.subAttributes } : {}),+ };+}++export const SCHEMAS = [+ {+ id: 'urn:ietf:params:scim:schemas:core:2.0:User',+ name: 'User',+ description: 'An account on this instance.',+ attributes: [+ attribute({ name: 'userName', required: true, uniqueness: 'server' }),+ attribute({+ name: 'name',+ type: 'complex',+ subAttributes: [+ attribute({ name: 'formatted' }),+ attribute({ name: 'givenName' }),+ attribute({ name: 'familyName' }),+ ],+ }),+ attribute({ name: 'displayName' }),+ attribute({+ name: 'emails',+ type: 'complex',+ multiValued: true,+ subAttributes: [+ attribute({ name: 'value' }),+ attribute({ name: 'type' }),+ attribute({ name: 'primary', type: 'boolean' }),+ ],+ }),+ attribute({ name: 'active', type: 'boolean' }),+ ],+ meta: {+ resourceType: 'Schema',+ location: `${SCIM_BASE_URL}/Schemas/urn:ietf:params:scim:schemas:core:2.0:User`,+ },+ },+ {+ id: 'urn:ietf:params:scim:schemas:core:2.0:Group',+ name: 'Group',+ description: 'A group of accounts. What it grants is configured in god mode.',+ attributes: [+ attribute({ name: 'displayName', required: true, uniqueness: 'server' }),+ attribute({+ name: 'members',+ type: 'complex',+ multiValued: true,+ subAttributes: [attribute({ name: 'value' }), attribute({ name: 'display' })],+ }),+ ],+ meta: {+ resourceType: 'Schema',+ location: `${SCIM_BASE_URL}/Schemas/urn:ietf:params:scim:schemas:core:2.0:Group`,+ },+ },+];diff --git a/apps/api/src/modules/scim/index.ts b/apps/api/src/modules/scim/index.tsnew file mode 100644index 00000000..8d6fa2eb--- /dev/null+++ b/apps/api/src/modules/scim/index.ts@@ -0,0 +1,440 @@+import { Elysia, t } from 'elysia';+import { isScimEnabled, verifyScimToken } from '@repo/auth';+import { HttpError } from '#shared/lib';+import { noContent } from '#shared/http';+import {+ SCIM_CONTENT_TYPE,+ SCIM_PREFIX,+ ScimError,+ asBoolean,+ asString,+ groupDisplayNames,+ joinName,+ memberFilterIds,+ memberIds,+ parseFilter,+ parsePatch,+ readEmail,+ readAccountEmail,+ scimErrorBody,+ splitName,+ toListResponse,+ toScimGroup,+ toScimUser,+} from './resource';+import { RESOURCE_TYPES, SCHEMAS, SERVICE_PROVIDER_CONFIG } from './discovery';+import {+ ScimDocumentListResponse,+ ScimDocumentResponse,+ ScimGroupListResponse,+ ScimGroupResponse,+ ScimUserListResponse,+ ScimUserResponse,+ listQuery,+ resourceParams,+ scimErrors,+} from './model';+import {+ GROUP_FILTER_ATTRIBUTES,+ USER_FILTER_ATTRIBUTES,+ addScimGroupMembers,+ createScimGroup,+ createScimUser,+ deleteScimGroup,+ deleteScimUser,+ getScimGroup,+ getScimUser,+ listScimGroups,+ listScimUsers,+ removeScimGroupMembers,+ syncEmbeddedGroups,+ updateScimGroup,+ updateScimUser,+} from './service';++// SCIM 2.0 provisioning (RFC 7643 / 7644). An identity provider pushes users and+// groups here with the instance's SCIM bearer token.++function extractToken(authorization: string | undefined): string | null {+ return authorization?.match(/^Bearer\s+(.+)$/i)?.[1] ?? null;+}++// The bodies are read as `t.Any()`: SCIM defines its own schemas and clients send+// attributes this app ignores, so rejecting an unknown field would fail a+// provisioning run over something harmless. The shapes are checked in resource.ts,+// which raises SCIM errors rather than the planner's validation error.+const anyBody = { body: t.Any() };++// A create or replace body, cast and checked. Guards the four spots that read+// `doc.<attribute>` straight off the request body: without this, a request that+// reached the handler with no body (a client-parse mismatch, or a body Elysia+// left unparsed) would throw inside the handler instead of answering a SCIM 400.+function asDoc(body: unknown): Record<string, unknown> {+ if (!body || typeof body !== 'object') {+ throw new ScimError(400, 'A JSON object body is required', 'invalidSyntax');+ }+ return body as Record<string, unknown>;+}++function requestedPage(query: { startIndex?: number; count?: number }) {+ return {+ startIndex: Math.max(1, query.startIndex ?? 1),+ count: Math.min(Math.max(query.count ?? 100, 0), 200),+ };+}++const scimHandlers = new Elysia({ name: 'scim-handlers', prefix: SCIM_PREFIX })+ // RFC 7644 §3.1 allows a SCIM client to send `application/scim+json`, and real+ // identity providers (Okta, Entra, Authentik) do. Elysia's default body parser+ // matches `Content-Type` exactly against `application/json`, so a request sent+ // with the SCIM type would otherwise leave `body` undefined instead of parsed.+ // Falling through (returning undefined) for anything else keeps plain+ // `application/json` on Elysia's own parser.+ .onParse(({ request, contentType }) => {+ if (contentType?.includes('json')) return request.json();+ })+ .onBeforeHandle(async ({ headers, set }) => {+ set.headers['content-type'] = SCIM_CONTENT_TYPE;+ const token = extractToken(headers.authorization);+ // One answer for "off", "no token" and "wrong token": whether provisioning is+ // configured is not something an unauthenticated caller should learn.+ if (!token || !(await isScimEnabled()) || !(await verifyScimToken(token))) {+ throw new ScimError(401, 'Invalid or missing SCIM bearer token');+ }+ })++ // ── Discovery ───────────────────────────────────────────────────────────────++ .get('/ServiceProviderConfig', () => SERVICE_PROVIDER_CONFIG, {+ response: { 200: ScimDocumentResponse, ...scimErrors(401) },+ detail: { summary: 'Get the SCIM service provider configuration' },+ })++ .get('/ResourceTypes', () => toListResponse(RESOURCE_TYPES, RESOURCE_TYPES.length, 1), {+ response: { 200: ScimDocumentListResponse, ...scimErrors(401) },+ detail: { summary: 'List the SCIM resource types' },+ })++ .get(+ '/ResourceTypes/:id',+ ({ params }) => {+ const found = RESOURCE_TYPES.find((r) => r.id === params.id);+ if (!found) throw new ScimError(404, `Resource type '${params.id}' not found`);+ return found;+ },+ {+ params: resourceParams,+ response: { 200: ScimDocumentResponse, ...scimErrors(401, 404) },+ detail: { summary: 'Get one SCIM resource type' },+ },+ )++ .get('/Schemas', () => toListResponse(SCHEMAS, SCHEMAS.length, 1), {+ response: { 200: ScimDocumentListResponse, ...scimErrors(401) },+ detail: { summary: 'List the SCIM schemas' },+ })++ .get(+ '/Schemas/:id',+ ({ params }) => {+ const found = SCHEMAS.find((s) => s.id === params.id);+ if (!found) throw new ScimError(404, `Schema '${params.id}' not found`);+ return found;+ },+ {+ params: resourceParams,+ response: { 200: ScimDocumentResponse, ...scimErrors(401, 404) },+ detail: { summary: 'Get one SCIM schema' },+ },+ )++ // ── Users ───────────────────────────────────────────────────────────────────++ .get(+ '/Users',+ async ({ query }) => {+ const page = requestedPage(query);+ const { records, total } = await listScimUsers({+ filter: parseFilter(query.filter, USER_FILTER_ATTRIBUTES),+ ...page,+ });+ return toListResponse(records.map(toScimUser), total, page.startIndex);+ },+ {+ query: listQuery,+ response: { 200: ScimUserListResponse, ...scimErrors(400, 401) },+ detail: { summary: 'List provisioned users' },+ },+ )++ .post(+ '/Users',+ async ({ body, set }) => {+ const doc = asDoc(body);+ const email = readAccountEmail(doc);+ const record = await createScimUser({+ email,+ name: joinName(doc.name as never, (doc.displayName as string) || email),+ active: doc.active === undefined ? true : asBoolean(doc.active),+ externalId: typeof doc.externalId === 'string' ? doc.externalId : null,+ });+ await syncEmbeddedGroups(record.id, groupDisplayNames(doc.groups));+ set.status = 201;+ return toScimUser(record);+ },+ {+ ...anyBody,+ response: { 201: ScimUserResponse, ...scimErrors(400, 401, 409) },+ detail: { summary: 'Provision a user' },+ },+ )++ .get('/Users/:id', async ({ params }) => toScimUser(await requireUser(params.id)), {+ params: resourceParams,+ response: { 200: ScimUserResponse, ...scimErrors(401, 404) },+ detail: { summary: 'Get one provisioned user' },+ })++ .put(+ '/Users/:id',+ async ({ params, body }) => {+ const current = await requireUser(params.id);+ const doc = asDoc(body);+ const email = readAccountEmail(doc);+ const updated = await updateScimUser(params.id, {+ email,+ name: joinName(doc.name as never, (doc.displayName as string) || current.name),+ active: doc.active === undefined ? true : asBoolean(doc.active),+ externalId: typeof doc.externalId === 'string' ? doc.externalId : null,+ });+ await syncEmbeddedGroups(params.id, groupDisplayNames(doc.groups));+ return toScimUser(requireUpdated(updated, 'User', params.id));+ },+ {+ params: resourceParams,+ ...anyBody,+ response: { 200: ScimUserResponse, ...scimErrors(400, 401, 404, 409) },+ detail: { summary: 'Replace a provisioned user' },+ },+ )++ .patch(+ '/Users/:id',+ async ({ params, body }) => {+ const current = await requireUser(params.id);+ const patch: { email?: string; name?: string; active?: boolean; externalId?: string | null } =+ {};+ for (const op of parsePatch(body)) {+ const path = op.path!.toLowerCase();+ if (op.op === 'remove') {+ // The only removable attribute is the deprovisioning flag; everything+ // else is required for the account to be usable.+ if (path !== 'active') {+ throw new ScimError(400, `Attribute '${op.path}' cannot be removed`, 'invalidPath');+ }+ patch.active = false;+ continue;+ }+ if (path === 'active') patch.active = asBoolean(op.value);+ else if (path === 'username') patch.email = asString(op.value, 'userName');+ else if (path === 'externalid') patch.externalId = asString(op.value, 'externalId');+ else if (path === 'displayname' || path === 'name.formatted') {+ patch.name = asString(op.value, 'name');+ } else if (path === 'name') {+ patch.name = joinName(op.value as never, current.name);+ } else if (path === 'name.givenname' || path === 'name.familyname') {+ const parts = splitName(patch.name ?? current.name);+ const key = path === 'name.givenname' ? 'givenName' : 'familyName';+ patch.name = joinName({ ...parts, [key]: asString(op.value, 'name') }, current.name);+ } else if (path.startsWith('emails')) {+ patch.email = readEmail(op.value);+ } else {+ throw new ScimError(400, `Attribute '${op.path}' is not writable`, 'invalidPath');+ }+ }+ const updated = await updateScimUser(params.id, patch);+ return toScimUser(requireUpdated(updated, 'User', params.id));+ },+ {+ params: resourceParams,+ ...anyBody,+ response: { 200: ScimUserResponse, ...scimErrors(400, 401, 404, 409) },+ detail: { summary: 'Update a provisioned user' },+ },+ )++ .delete(+ '/Users/:id',+ async ({ params }) => {+ await deleteScimUser(params.id);+ return noContent();+ },+ {+ params: resourceParams,+ response: { 204: t.Void(), ...scimErrors(401, 404, 409) },+ detail: { summary: 'Delete a provisioned user' },+ },+ )++ // ── Groups ──────────────────────────────────────────────────────────────────++ .get(+ '/Groups',+ async ({ query }) => {+ const page = requestedPage(query);+ const { records, total } = await listScimGroups({+ filter: parseFilter(query.filter, GROUP_FILTER_ATTRIBUTES),+ ...page,+ });+ return toListResponse(records.map(toScimGroup), total, page.startIndex);+ },+ {+ query: listQuery,+ response: { 200: ScimGroupListResponse, ...scimErrors(400, 401) },+ detail: { summary: 'List provisioned groups' },+ },+ )++ .post(+ '/Groups',+ async ({ body, set }) => {+ const doc = asDoc(body);+ const record = await createScimGroup({+ displayName: asString(doc.displayName, 'displayName'),+ externalId: typeof doc.externalId === 'string' ? doc.externalId : null,+ members: doc.members === undefined ? [] : memberIds(doc.members),+ });+ set.status = 201;+ return toScimGroup(record);+ },+ {+ ...anyBody,+ response: { 201: ScimGroupResponse, ...scimErrors(400, 401, 409) },+ detail: { summary: 'Provision a group' },+ },+ )++ .get('/Groups/:id', async ({ params }) => toScimGroup(await requireGroup(params.id)), {+ params: resourceParams,+ response: { 200: ScimGroupResponse, ...scimErrors(401, 404) },+ detail: { summary: 'Get one provisioned group' },+ })++ .put(+ '/Groups/:id',+ async ({ params, body }) => {+ await requireGroup(params.id);+ const doc = asDoc(body);+ const updated = await updateScimGroup(params.id, {+ displayName: asString(doc.displayName, 'displayName'),+ externalId: typeof doc.externalId === 'string' ? doc.externalId : null,+ members: doc.members === undefined ? [] : memberIds(doc.members),+ });+ return toScimGroup(requireUpdated(updated, 'Group', params.id));+ },+ {+ params: resourceParams,+ ...anyBody,+ response: { 200: ScimGroupResponse, ...scimErrors(400, 401, 404, 409) },+ detail: { summary: 'Replace a provisioned group' },+ },+ )++ .patch(+ '/Groups/:id',+ async ({ params, body }) => {+ await requireGroup(params.id);+ // Members are applied as they arrive so an add and a remove in the same+ // request compose; the rest is collected and written once.+ const patch: { displayName?: string; externalId?: string | null; members?: string[] } = {};+ for (const op of parsePatch(body)) {+ const path = op.path!.toLowerCase();+ if (path.startsWith('members')) {+ // A remove sent as a path filter (RFC 7644 §3.5.2.2, e.g. Okta) carries+ // the id in the path itself, not in `value`.+ const ids =+ memberFilterIds(op.path!) ?? (op.value === undefined ? [] : memberIds(op.value));+ if (op.op === 'remove') await removeScimGroupMembers(params.id, ids);+ else if (op.op === 'add') await addScimGroupMembers(params.id, ids);+ else patch.members = ids;+ continue;+ }+ if (op.op === 'remove') {+ throw new ScimError(400, `Attribute '${op.path}' cannot be removed`, 'invalidPath');+ }+ if (path === 'displayname') patch.displayName = asString(op.value, 'displayName');+ else if (path === 'externalid') patch.externalId = asString(op.value, 'externalId');+ else throw new ScimError(400, `Attribute '${op.path}' is not writable`, 'invalidPath');+ }+ const updated = await updateScimGroup(params.id, patch);+ return toScimGroup(requireUpdated(updated, 'Group', params.id));+ },+ {+ params: resourceParams,+ ...anyBody,+ response: { 200: ScimGroupResponse, ...scimErrors(400, 401, 404, 409) },+ detail: { summary: 'Update a provisioned group' },+ },+ )++ .delete(+ '/Groups/:id',+ async ({ params }) => {+ if (!(await deleteScimGroup(params.id))) {+ throw new ScimError(404, `Group '${params.id}' not found`);+ }+ return noContent();+ },+ {+ params: resourceParams,+ response: { 204: t.Void(), ...scimErrors(401, 404) },+ detail: { summary: 'Delete a provisioned group' },+ },+ );++// SCIM failures carry their own document, so this replaces the planner's `{ error }`+// handler for these routes. Two things decide its shape:+//+// - It wraps the routes from the outside rather than sitting on the same instance.+// An onError beside the routes widens the inferred response type of every one of+// them with the body it returns, which reaches the Eden client as a success shape.+// - Elysia propagates it to the root app, and from there over every route, so it+// answers only for its own paths and hands everything else back for the planner's+// handler to answer.+export const scimRoutes = new Elysia({ name: 'scim' })+ .onError({ as: 'global' }, ({ error, path, set }) => {+ if (!path.startsWith(SCIM_PREFIX)) return;+ set.headers['content-type'] = SCIM_CONTENT_TYPE;+ if (error instanceof ScimError) {+ set.status = error.status;+ return scimErrorBody(error.status, error.message, error.scimType);+ }+ if (error instanceof HttpError) {+ set.status = error.status;+ return scimErrorBody(error.status, error.message);+ }+ console.error('[scim]', error);+ set.status = 500;+ return scimErrorBody(500, 'Internal error');+ })+ .use(scimHandlers);++// The update returns null when the row is gone, which the read at the start of the+// handler cannot rule out. Answering 404 keeps a provisioning client on a path it+// understands instead of a 500.+function requireUpdated<T>(record: T | null, resource: string, id: string): T {+ if (!record) throw new ScimError(404, `${resource} '${id}' not found`);+ return record;+}++async function requireUser(id: string) {+ const record = await getScimUser(id);+ if (!record) throw new ScimError(404, `User '${id}' not found`);+ return record;+}++async function requireGroup(id: string) {+ const record = await getScimGroup(id);+ if (!record) throw new ScimError(404, `Group '${id}' not found`);+ return record;+}diff --git a/apps/api/src/modules/scim/model.ts b/apps/api/src/modules/scim/model.tsnew file mode 100644index 00000000..a0a7ed8f--- /dev/null+++ b/apps/api/src/modules/scim/model.ts@@ -0,0 +1,94 @@+import { t } from 'elysia';++// Request and response schemas for the SCIM endpoints.+//+// The request *bodies* are read as `t.Any()` in index.ts and validated in+// resource.ts instead: SCIM defines its own schemas, clients send attributes this+// app ignores, and a rejection has to come back as a SCIM error document rather than+// the planner's validation error. The responses are declared here, so the OpenAPI+// spec and the Eden client both describe what the endpoints actually return.++// SCIM ids are opaque strings: a user id is better-auth's, a group id a uuid.+export const resourceParams = t.Object({ id: t.String() });++export const listQuery = t.Object({+ // `<attribute> eq "<value>"`. What is filterable is listed per resource in+ // service.ts and advertised in ServiceProviderConfig.+ filter: t.Optional(t.String()),+ // SCIM paging is 1-based, unlike the offset/limit used elsewhere in this API.+ startIndex: t.Optional(t.Numeric({ minimum: 1 })),+ count: t.Optional(t.Numeric({ minimum: 0, maximum: 200 })),+});++const meta = t.Object({+ resourceType: t.String(),+ created: t.String(),+ lastModified: t.String(),+ location: t.String(),+});++export const ScimUserResponse = t.Object({+ schemas: t.Array(t.String()),+ id: t.String(),+ externalId: t.Optional(t.String()),+ userName: t.String(),+ name: t.Object({+ formatted: t.String(),+ givenName: t.String(),+ familyName: t.String(),+ }),+ displayName: t.String(),+ emails: t.Array(t.Object({ value: t.String(), primary: t.Boolean(), type: t.String() })),+ active: t.Boolean(),+ meta,+});++export const ScimGroupResponse = t.Object({+ schemas: t.Array(t.String()),+ id: t.String(),+ externalId: t.Optional(t.String()),+ displayName: t.String(),+ members: t.Array(t.Object({ value: t.String(), display: t.String(), $ref: t.String() })),+ meta,+});++function listOf<T extends ReturnType<typeof t.Object>>(resource: T) {+ return t.Object({+ schemas: t.Array(t.String()),+ totalResults: t.Integer(),+ startIndex: t.Integer(),+ itemsPerPage: t.Integer(),+ Resources: t.Array(resource),+ });+}++export const ScimUserListResponse = listOf(ScimUserResponse);+export const ScimGroupListResponse = listOf(ScimGroupResponse);++// The discovery documents are static constants describing the SCIM standard itself,+// so they are declared as they are rather than mirrored attribute by attribute.+export const ScimDocumentResponse = t.Any();+export const ScimDocumentListResponse = t.Object({+ schemas: t.Array(t.String()),+ totalResults: t.Integer(),+ startIndex: t.Integer(),+ itemsPerPage: t.Integer(),+ Resources: t.Array(t.Any()),+});++// RFC 7644 §3.12. `status` is a string here, unlike everywhere else in this API.+const ScimErrorResponse = t.Object({+ schemas: t.Array(t.String()),+ status: t.String(),+ scimType: t.Optional(t.String()),+ detail: t.String(),+});++// The SCIM error document, for each status a route can fail with. Same shape as+// shared/responses.ts `errors`, including the cast that keeps the status codes as+// literal keys — without it Eden Treaty cannot tell a failure body from a success+// one. The planner's own error map is the wrong body here.+export const scimErrors = <const C extends readonly number[]>(...codes: C) =>+ Object.fromEntries(codes.map((code) => [code, ScimErrorResponse])) as {+ [K in C[number]]: typeof ScimErrorResponse;+ };diff --git a/apps/api/src/modules/scim/oidc-sync.ts b/apps/api/src/modules/scim/oidc-sync.tsnew file mode 100644index 00000000..a71a5057--- /dev/null+++ b/apps/api/src/modules/scim/oidc-sync.ts@@ -0,0 +1,63 @@+import { and, desc, eq } from 'drizzle-orm';+import { db, account } from '@repo/db';+import { auth, OIDC_PROVIDER_ID } from '@repo/auth';+import { groupDisplayNames } from './resource';+import { syncEmbeddedGroups } from './service';++// Folds an OIDC sign-in's `groups` claim into the same scim_group /+// scim_group_member tables a SCIM sync writes to, so a group mapped to a project in+// god mode grants access on an instance that uses OIDC, SCIM, or both. Runs after+// every successful callback, not just the first one, so membership follows the+// provider going forward.+//+// The claim lives in the ID token, not necessarily the userinfo response some+// providers keep small — better-auth stores the raw token on the linked `account`+// row (`idToken`), so it is read from there rather than re-fetching anything.+// Reading its payload needs no signature check: this token already went through+// better-auth's own exchange with the provider's token endpoint over TLS, and nothing+// here relies on it for authentication — only on an optional claim used to seed+// project access.+export function decodeJwtPayload(token: string): Record<string, unknown> | null {+ const segment = token.split('.')[1];+ if (!segment) return null;+ try {+ const base64 = segment.replace(/-/g, '+').replace(/_/g, '/');+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=');+ return JSON.parse(Buffer.from(padded, 'base64').toString('utf8')) as Record<string, unknown>;+ } catch {+ return null;+ }+}++// Called with the response of `/api/auth/oauth2/callback/:providerId`, whose+// Set-Cookie header resolves the session a successful sign-in just opened. Best+// effort throughout: a decode failure, a missing claim, or a DB error is logged and+// swallowed rather than surfaced, since none of it should turn a successful sign-in+// into a failed one.+export async function syncOidcGroupsAfterCallback(response: Response): Promise<void> {+ try {+ const cookie = response.headers+ .getSetCookie()+ .map((c) => c.split(';')[0])+ .join('; ');+ if (!cookie) return;++ const session = await auth.api.getSession({ headers: new Headers({ cookie }) });+ if (!session) return;++ const rows = await db+ .select({ idToken: account.idToken })+ .from(account)+ .where(and(eq(account.userId, session.user.id), eq(account.providerId, OIDC_PROVIDER_ID)))+ .orderBy(desc(account.updatedAt))+ .limit(1);+ const idToken = rows[0]?.idToken;+ if (!idToken) return;++ const claims = decodeJwtPayload(idToken);+ const names = groupDisplayNames(claims?.groups);+ await syncEmbeddedGroups(session.user.id, names);+ } catch (error) {+ console.error('[scim] OIDC group sync failed:', error);+ }+}diff --git a/apps/api/src/modules/scim/reconcile.ts b/apps/api/src/modules/scim/reconcile.tsnew file mode 100644index 00000000..709c46e5--- /dev/null+++ b/apps/api/src/modules/scim/reconcile.ts@@ -0,0 +1,107 @@+import { db, projectMember, scimGroupMapping, scimGroupMember } from '@repo/db';+import { eq } from 'drizzle-orm';+import { removeMember, setMembership, type MemberRole } from '#modules/members/service';++// Turns provisioned group membership into project membership. This is the only+// place a project_member row is written from SCIM, and it only ever touches rows+// it owns (`source: 'scim'`) — a membership somebody set up through an invite is+// left exactly as it is, in either direction.+//+// Called after a group's members or its mappings change.++interface Desired {+ role: MemberRole;+ roleId: number | null;+}++export async function reconcileProjects(projectIds: number[]): Promise<void> {+ for (const projectId of new Set(projectIds)) {+ await reconcileProject(projectId);+ }+}++// Who the mappings say should be a member of this project. A user reachable+// through two mappings resolves to the strongest: 'owner' beats 'member', and among+// equals the lowest mapping id wins, so the result does not depend on row order.+async function desiredMembers(projectId: number): Promise<Map<string, Desired>> {+ const rows = await db+ .select({+ userId: scimGroupMember.userId,+ role: scimGroupMapping.role,+ roleId: scimGroupMapping.roleId,+ })+ .from(scimGroupMapping)+ .innerJoin(scimGroupMember, eq(scimGroupMember.groupId, scimGroupMapping.groupId))+ .where(eq(scimGroupMapping.projectId, projectId))+ .orderBy(scimGroupMapping.id);++ const desired = new Map<string, Desired>();+ for (const row of rows) {+ const role = row.role as MemberRole;+ const current = desired.get(row.userId);+ if (current && (current.role === 'owner' || role !== 'owner')) continue;+ // Owners bypass the permission matrix, so they carry no custom role.+ desired.set(row.userId, { role, roleId: role === 'owner' ? null : row.roleId });+ }+ return desired;+}++async function reconcileProject(projectId: number): Promise<void> {+ const desired = await desiredMembers(projectId);+ const existing = await db+ .select({+ userId: projectMember.userId,+ role: projectMember.role,+ roleId: projectMember.roleId,+ source: projectMember.source,+ })+ .from(projectMember)+ .where(eq(projectMember.projectId, projectId));++ const byUser = new Map(existing.map((row) => [row.userId, row]));+ // Tracked as rows change so the last-owner guard below stays correct without+ // re-counting after every write.+ let owners = existing.filter((row) => row.role === 'owner').length;++ for (const [userId, want] of desired) {+ const have = byUser.get(userId);+ if (!have) {+ await db.insert(projectMember).values({+ projectId,+ userId,+ role: want.role,+ roleId: want.roleId,+ source: 'scim',+ });+ if (want.role === 'owner') owners += 1;+ continue;+ }+ // A membership a person set up outranks the identity provider: the group adds+ // nothing on top of it and never takes it away.+ if (have.source !== 'scim') continue;+ if (have.role === want.role && have.roleId === want.roleId) continue;+ if (have.role === 'owner' && want.role !== 'owner' && owners <= 1) continue;+ await setMembership(projectId, userId, want.role, want.roleId);+ if (have.role === 'owner' && want.role !== 'owner') owners -= 1;+ if (have.role !== 'owner' && want.role === 'owner') owners += 1;+ }++ for (const row of existing) {+ if (row.source !== 'scim' || desired.has(row.userId)) continue;+ // A project without an owner has nobody who can manage its members, so the+ // last one stays even when the group no longer grants it.+ if (row.role === 'owner' && owners <= 1) continue;+ await removeMember(projectId, row.userId);+ if (row.role === 'owner') owners -= 1;+ }+}++// The projects a group currently grants membership in. Read before and after a+// change so reconciliation covers the projects it was removed from as well.+export async function mappedProjectIds(groupId: string): Promise<number[]> {+ const rows = await db+ .select({ projectId: scimGroupMapping.projectId })+ .from(scimGroupMapping)+ .where(eq(scimGroupMapping.groupId, groupId));+ return rows.map((row) => row.projectId);+}diff --git a/apps/api/src/modules/scim/resource.ts b/apps/api/src/modules/scim/resource.tsnew file mode 100644index 00000000..66ece97a--- /dev/null+++ b/apps/api/src/modules/scim/resource.ts@@ -0,0 +1,303 @@+import { HttpError } from '#shared/lib';++// SCIM 2.0 representation: the JSON shapes of RFC 7643, the filter and PATCH+// grammar of RFC 7644, and the mapping between them and this app's DTOs.+//+// The account's email comes from the `emails` attribute, not `userName`: RFC 7643+// does not require `userName` to be an email address, and some directories set it+// to a login id that is not one, while `emails` is what SCIM actually calls an+// email. `userName` is read only as a fallback, for a provider that omits `emails`+// altogether. `user.username` (the app's own handle, used in @mentions) is a+// different thing entirely and is derived at creation — SCIM never sets it.++const API_URL = process.env.API_URL ?? '';++export const SCIM_PREFIX = '/scim/v2';++export const SCIM_BASE_URL = `${API_URL}${SCIM_PREFIX}`;++export const SCIM_CONTENT_TYPE = 'application/scim+json';++const USER_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User';+const GROUP_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:Group';+const LIST_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:ListResponse';+const ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error';+const PATCH_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:PatchOp';++// A SCIM failure. `scimType` is the machine-readable reason from RFC 7644 §3.12;+// provisioning clients branch on it, so it is carried alongside the status.+export class ScimError extends HttpError {+ readonly scimType?: string;++ constructor(status: number, detail: string, scimType?: string) {+ super(status, detail);+ this.scimType = scimType;+ }+}++export function scimErrorBody(status: number, detail: string, scimType?: string) {+ return {+ schemas: [ERROR_SCHEMA],+ // The status is a string in SCIM, unlike everywhere else in this API.+ status: String(status),+ ...(scimType ? { scimType } : {}),+ detail,+ };+}++// ── Users ─────────────────────────────────────────────────────────────────────++export interface ScimUserRecord {+ id: string;+ email: string;+ name: string;+ active: boolean;+ externalId: string | null;+ createdAt: string;+ updatedAt: string;+}++// SCIM splits a name into parts, the app stores one string. The first word is the+// given name and the rest the family name, which is the reverse of how a create+// request is folded back together.+export function splitName(name: string): { givenName: string; familyName: string } {+ const trimmed = name.trim();+ const gap = trimmed.indexOf(' ');+ if (gap === -1) return { givenName: trimmed, familyName: '' };+ return { givenName: trimmed.slice(0, gap), familyName: trimmed.slice(gap + 1) };+}++export function joinName(+ parts: { givenName?: string; familyName?: string; formatted?: string } | undefined,+ fallback: string,+): string {+ if (parts?.formatted?.trim()) return parts.formatted.trim();+ const joined = [parts?.givenName, parts?.familyName]+ .map((p) => p?.trim())+ .filter(Boolean)+ .join(' ');+ return joined || fallback;+}++// The address a create or replace request assigns as the account's email. `emails`+// is preferred; `userName` is read only when a provider sends no `emails` at all,+// and is then checked for an "@" so a bare login id is refused rather than written+// into `user.email`, where it would break sign-in and password reset links that+// assume the value is a real address.+export function readAccountEmail(doc: Record<string, unknown>): string {+ if (doc.emails !== undefined) return readEmail(doc.emails);+ if (typeof doc.userName === 'string' && doc.userName.trim()) {+ const userName = doc.userName.trim();+ if (!userName.includes('@')) {+ throw new ScimError(400, 'userName is not an email address', 'invalidValue');+ }+ return userName;+ }+ throw new ScimError(400, 'userName or emails is required', 'invalidValue');+}++// One address out of a multi-valued `emails` attribute: the one marked primary, or+// the first. Entries may be objects or bare strings.+export function readEmail(value: unknown): string {+ const list = Array.isArray(value) ? value : [value];+ const entries = list.map((entry) =>+ typeof entry === 'string'+ ? { value: entry, primary: false }+ : (entry as Record<string, unknown>),+ );+ const chosen = entries.find((e) => e?.primary === true) ?? entries[0];+ return asString(chosen?.value, 'email address');+}++export function toScimUser(record: ScimUserRecord) {+ return {+ schemas: [USER_SCHEMA],+ id: record.id,+ ...(record.externalId ? { externalId: record.externalId } : {}),+ userName: record.email,+ name: { ...splitName(record.name), formatted: record.name },+ displayName: record.name,+ emails: [{ value: record.email, primary: true, type: 'work' }],+ active: record.active,+ meta: {+ resourceType: 'User',+ created: record.createdAt,+ lastModified: record.updatedAt,+ location: `${SCIM_BASE_URL}/Users/${record.id}`,+ },+ };+}++// ── Groups ────────────────────────────────────────────────────────────────────++export interface ScimGroupRecord {+ id: string;+ displayName: string;+ externalId: string | null;+ members: { userId: string; name: string }[];+ createdAt: string;+ updatedAt: string;+}++export function toScimGroup(record: ScimGroupRecord) {+ return {+ schemas: [GROUP_SCHEMA],+ id: record.id,+ ...(record.externalId ? { externalId: record.externalId } : {}),+ displayName: record.displayName,+ members: record.members.map((m) => ({+ value: m.userId,+ display: m.name,+ $ref: `${SCIM_BASE_URL}/Users/${m.userId}`,+ })),+ meta: {+ resourceType: 'Group',+ created: record.createdAt,+ lastModified: record.updatedAt,+ location: `${SCIM_BASE_URL}/Groups/${record.id}`,+ },+ };+}++// ── List response ─────────────────────────────────────────────────────────────++export function toListResponse<T>(resources: T[], total: number, startIndex: number) {+ return {+ schemas: [LIST_SCHEMA],+ totalResults: total,+ startIndex,+ itemsPerPage: resources.length,+ Resources: resources,+ };+}++// ── Filters ───────────────────────────────────────────────────────────────────++// Only `<attribute> eq "<value>"` is understood. That is what Okta, Entra and+// Authentik send to find an existing resource before creating one, and it is what+// ServiceProviderConfig advertises. Anything richer is refused rather than+// silently ignored, which would return the wrong resource.+const EQ_FILTER = /^\s*([\w.]+)\s+eq\s+"((?:[^"\\]|\\.)*)"\s*$/i;++export interface ScimFilter {+ attribute: string;+ value: string;+}++export function parseFilter(filter: string | undefined, allowed: string[]): ScimFilter | null {+ if (!filter) return null;+ const match = EQ_FILTER.exec(filter);+ if (!match) {+ throw new ScimError(+ 400,+ `Only '<attribute> eq "<value>"' filters are supported`,+ 'invalidFilter',+ );+ }+ const attribute = match[1]!.toLowerCase();+ if (!allowed.some((a) => a.toLowerCase() === attribute)) {+ throw new ScimError(+ 400,+ `Filtering on '${match[1]}' is not supported. Supported: ${allowed.join(', ')}`,+ 'invalidFilter',+ );+ }+ return { attribute, value: match[2]!.replace(/\\(.)/g, '$1') };+}++// ── PATCH ─────────────────────────────────────────────────────────────────────++export interface ScimPatchOperation {+ op: 'add' | 'replace' | 'remove';+ path?: string;+ value?: unknown;+}++// Normalises a PatchOp body into operations with a lower-cased op. Entra sends a+// path-less `replace` whose value is an object of attributes, which is expanded+// here into one operation per attribute so callers handle a single shape.+export function parsePatch(body: unknown): ScimPatchOperation[] {+ const doc = body as { schemas?: unknown; Operations?: unknown } | null;+ const schemas = Array.isArray(doc?.schemas) ? doc.schemas : [];+ if (!schemas.includes(PATCH_SCHEMA)) {+ throw new ScimError(400, `Body must carry the ${PATCH_SCHEMA} schema`, 'invalidSyntax');+ }+ if (!Array.isArray(doc?.Operations)) {+ throw new ScimError(400, 'Body must carry an Operations array', 'invalidSyntax');+ }++ const out: ScimPatchOperation[] = [];+ for (const raw of doc.Operations) {+ const entry = raw as { op?: unknown; path?: unknown; value?: unknown };+ const op = String(entry.op ?? '').toLowerCase();+ if (op !== 'add' && op !== 'replace' && op !== 'remove') {+ throw new ScimError(400, `Unsupported operation '${entry.op}'`, 'invalidSyntax');+ }+ const path = typeof entry.path === 'string' ? entry.path : undefined;+ if (!path && op !== 'remove' && entry.value && typeof entry.value === 'object') {+ for (const [key, value] of Object.entries(entry.value as Record<string, unknown>)) {+ out.push({ op, path: key, value });+ }+ continue;+ }+ if (!path) throw new ScimError(400, `Operation '${op}' needs a path`, 'noTarget');+ out.push({ op, path, value: entry.value });+ }+ return out;+}++// SCIM sends booleans as booleans, but some clients send them as strings.+export function asBoolean(value: unknown): boolean {+ if (typeof value === 'boolean') return value;+ if (typeof value === 'string') return value.toLowerCase() === 'true';+ throw new ScimError(400, `Expected a boolean, got ${JSON.stringify(value)}`, 'invalidValue');+}++export function asString(value: unknown, what: string): string {+ if (typeof value === 'string' && value.trim().length > 0) return value.trim();+ throw new ScimError(400, `Expected a non-empty ${what}`, 'invalidValue');+}++// A member list as PATCH sends it: `[{ value: "<user id>" }]`, or a bare id.+export function memberIds(value: unknown): string[] {+ const list = Array.isArray(value) ? value : [value];+ return list.map((entry) => {+ if (typeof entry === 'string') return entry;+ const id = (entry as { value?: unknown } | null)?.value;+ return asString(id, 'member id');+ });+}++const MEMBER_PATH_FILTER = /^members\[(.+)]$/i;+const VALUE_EQ = /value\s+eq\s+"((?:[^"\\]|\\.)*)"/gi;++// RFC 7644 §3.5.2.2's canonical way to remove one group member puts the id in a+// filter on the path itself — `path: 'members[value eq "<id>"]'`, no `value` — which+// is what Okta sends. Returns null for the other shape, `path: 'members'` with the+// id(s) in `value` the ordinary way, so a caller can fall back to `memberIds`.+export function memberFilterIds(path: string): string[] | null {+ const match = MEMBER_PATH_FILTER.exec(path.trim());+ if (!match) return null;+ return [...match[1]!.matchAll(VALUE_EQ)].map((m) => m[1]!.replace(/\\(.)/g, '$1'));+}++// Group names out of a loosely-typed "which groups does this account belong to"+// value. Two shapes reach this: the `groups` attribute a SCIM User body can carry+// (RFC 7643 §4.1.2) — `{ value, display }` refs, where `display` is meant to be the+// human-readable name and `value` the provider's own opaque id, but a provider that+// skips Group resources entirely often has no `display` to send and puts the name+// in `value` instead — and an OIDC `groups` claim, which is conventionally a plain+// array of name strings. Both are accepted so the same sync feeds from either.+export function groupDisplayNames(value: unknown): string[] {+ if (value === undefined) return [];+ const list = Array.isArray(value) ? value : [value];+ const names = list+ .map((entry) => {+ if (typeof entry === 'string') return entry;+ const ref = entry as { display?: unknown; value?: unknown } | null;+ return ref?.display ?? ref?.value;+ })+ .filter((name): name is string => typeof name === 'string' && name.trim().length > 0)+ .map((name) => name.trim());+ return [...new Set(names)];+}diff --git a/apps/api/src/modules/scim/service.ts b/apps/api/src/modules/scim/service.tsnew file mode 100644index 00000000..66231a77--- /dev/null+++ b/apps/api/src/modules/scim/service.ts@@ -0,0 +1,472 @@+import { db, aiAgent, projectMember, scimGroup, scimGroupMember, user } from '@repo/db';+import { and, eq, inArray, notExists, sql } from 'drizzle-orm';+import { generateUsername } from '@repo/auth';+import { iso } from '#shared/lib';+import { deleteInstanceUser } from '#modules/god/service';+import { countOwners } from '#modules/members/service';+import { ScimError, type ScimFilter, type ScimGroupRecord, type ScimUserRecord } from './resource';+import { mappedProjectIds, reconcileProjects } from './reconcile';++// Data access for the SCIM endpoints. The identity provider is the authority on+// who exists, so a create here inserts the `user` row directly rather than going+// through better-auth's sign-up — the same way an agent's bot user is written. That+// deliberately skips the instance registration gate, which is what makes a closed+// instance plus SSO a working combination.+//+// An AI agent's bot user is an account too, but it belongs to the project that+// created it, not to the identity provider: `notAnAgent` keeps every one of them out+// of /Users, so a sync cannot rename an agent or deactivate it (which would make the+// api refuse the agent's own API key and stop it without a trace).++// What each resource can be filtered on. Advertised by ServiceProviderConfig and+// enforced by parseFilter, so the three never drift apart.+export const USER_FILTER_ATTRIBUTES = ['userName', 'externalId', 'emails.value'];+export const GROUP_FILTER_ATTRIBUTES = ['displayName', 'externalId'];++// True for every account that is not an AI agent's bot user. The same test the god+// user directory uses for its `human` filter.+const notAnAgent = notExists(+ db+ .select({ n: sql`1` })+ .from(aiAgent)+ .where(eq(aiAgent.userId, user.id)),+);++// The address is the identity a SCIM sync and an OIDC/password sign-up share, but+// the two paths do not agree on case: better-auth stores whatever case a sign-up or+// an OIDC profile carried, while a SCIM `userName` typically arrives lowercased from+// a directory. Matching case-sensitively would miss an account that predates the+// sync and provision a duplicate instead of claiming it.+function emailEq(email: string) {+ return eq(sql`lower(${user.email})`, email.trim().toLowerCase());+}++interface UserRow {+ id: string;+ email: string;+ name: string;+ active: boolean | null;+ scimExternalId: string | null;+ createdAt: Date;+ updatedAt: Date;+}++function toUserRecord(row: UserRow): ScimUserRecord {+ return {+ id: row.id,+ email: row.email,+ name: row.name,+ // Nullable for accounts that predate the column, which are active.+ active: row.active !== false,+ externalId: row.scimExternalId,+ createdAt: iso(row.createdAt),+ updatedAt: iso(row.updatedAt),+ };+}++const userColumns = {+ id: user.id,+ email: user.email,+ name: user.name,+ active: user.active,+ scimExternalId: user.scimExternalId,+ createdAt: user.createdAt,+ updatedAt: user.updatedAt,+};++// ── Users ─────────────────────────────────────────────────────────────────────++function userWhere(filter: ScimFilter | null) {+ if (!filter) return notAnAgent;+ if (filter.attribute === 'externalid') {+ return and(notAnAgent, eq(user.scimExternalId, filter.value));+ }+ return and(notAnAgent, emailEq(filter.value));+}++export async function listScimUsers(options: {+ filter: ScimFilter | null;+ startIndex: number;+ count: number;+}): Promise<{ records: ScimUserRecord[]; total: number }> {+ const where = userWhere(options.filter);+ const [rows, totals] = await Promise.all([+ db+ .select(userColumns)+ .from(user)+ .where(where)+ .orderBy(user.createdAt)+ .limit(options.count)+ .offset(options.startIndex - 1),+ db+ .select({ count: sql<number>`count(*)::int` })+ .from(user)+ .where(where),+ ]);+ return { records: rows.map(toUserRecord), total: totals[0]?.count ?? 0 };+}++export async function getScimUser(id: string): Promise<ScimUserRecord | null> {+ const rows = await db+ .select(userColumns)+ .from(user)+ .where(and(eq(user.id, id), notAnAgent));+ return rows[0] ? toUserRecord(rows[0]) : null;+}++export async function createScimUser(input: {+ email: string;+ name: string;+ active: boolean;+ externalId: string | null;+}): Promise<ScimUserRecord> {+ const email = input.email.trim().toLowerCase();+ const existing = await db+ .select({ id: user.id, role: user.role, scimExternalId: user.scimExternalId })+ .from(user)+ .where(and(emailEq(email), notAnAgent));+ if (existing[0]) {+ // The role is what grants god mode, so linking this account into a sync would+ // let the identity provider rename, reassign or deactivate the instance owner+ // with no route back except SQL.+ if (existing[0].role === 'god') {+ throw new ScimError(409, 'An instance owner cannot be provisioned through SCIM');+ }+ // A second create for an address already linked to the provider is a retry,+ // not a new person — Okta repeats a create after a timeout — and must not+ // silently overwrite what the first one wrote, including the id the second+ // request left out, with whatever the retry happens to carry.+ if (existing[0].scimExternalId) {+ throw new ScimError(+ 409,+ `A user with userName '${input.email}' already exists`,+ 'uniqueness',+ );+ }+ // Otherwise this address belongs to an account that predates the sync —+ // created by a sign-up or an OIDC sign-in — so provisioning claims it instead+ // of creating a second one for the same person. Its name and username are left+ // as they are: both may already be the ones the person set for themselves, and+ // the identity provider is only the authority on whether the account should+ // exist and be active.+ const linked = await db+ .update(user)+ .set({ active: input.active, scimExternalId: input.externalId, updatedAt: new Date() })+ .where(eq(user.id, existing[0].id))+ .returning(userColumns);+ return toUserRecord(linked[0]!);+ }+ const rows = await db+ .insert(user)+ .values({+ id: crypto.randomUUID(),+ email,+ name: input.name,+ emailVerified: true,+ role: 'user',+ active: input.active,+ scimExternalId: input.externalId,+ // The @mention handle, derived from the address the same way a sign-up+ // derives it. The identity provider does not supply one.+ username: await generateUsername(email),+ })+ .returning(userColumns);+ return toUserRecord(rows[0]!);+}++export async function updateScimUser(+ id: string,+ patch: { email?: string; name?: string; active?: boolean; externalId?: string | null },+): Promise<ScimUserRecord | null> {+ const target = await db+ .select({ role: user.role })+ .from(user)+ .where(and(eq(user.id, id), notAnAgent));+ // Same reason as the create guard above: nothing about this account is+ // provider-owned, so PUT and PATCH — this function backs both — refuse it too.+ if (target[0]?.role === 'god') {+ throw new ScimError(409, 'An instance owner cannot be updated through SCIM');+ }+ const email = patch.email?.trim().toLowerCase();+ if (email) {+ const clash = await db+ .select({ id: user.id })+ .from(user)+ .where(and(emailEq(email), notAnAgent));+ if (clash[0] && clash[0].id !== id) {+ throw new ScimError(+ 409,+ `A user with userName '${patch.email}' already exists`,+ 'uniqueness',+ );+ }+ }+ const rows = await db+ .update(user)+ .set({+ ...(email ? { email } : {}),+ ...(patch.name !== undefined ? { name: patch.name } : {}),+ ...(patch.active !== undefined ? { active: patch.active } : {}),+ ...(patch.externalId !== undefined ? { scimExternalId: patch.externalId } : {}),+ updatedAt: new Date(),+ })+ .where(and(eq(user.id, id), notAnAgent))+ .returning(userColumns);+ return rows[0] ? toUserRecord(rows[0]) : null;+}++// Some identity providers embed group membership on the user instead of, or as well+// as, pushing separate Group resources — this is what makes a sync grant project+// access without the operator ever configuring a Group push. A named group that+// does not exist yet is created, the way a group pushed through POST /Groups would+// be; the user is added to each one, and every project already mapped to one of+// them is reconciled so membership takes effect immediately.+//+// Additive only: a name missing from a later sync is not removed here. Which+// provider is authoritative for a group is a per-instance choice — a provider that+// also pushes Group resources removes a member through PATCH /Groups, and one that+// only ever embeds `groups` on the user never lists a name it wants revoked, so+// there is nothing to compare against without one of the two mechanisms winning+// over the other by accident.+export async function syncEmbeddedGroups(userId: string, displayNames: string[]): Promise<void> {+ if (displayNames.length === 0) return;+ const groupIds: string[] = [];+ for (const displayName of displayNames) {+ const created = await db+ .insert(scimGroup)+ .values({ displayName })+ .onConflictDoNothing({ target: scimGroup.displayName })+ .returning({ id: scimGroup.id });+ if (created[0]) {+ groupIds.push(created[0].id);+ continue;+ }+ const existing = await db+ .select({ id: scimGroup.id })+ .from(scimGroup)+ .where(eq(scimGroup.displayName, displayName));+ groupIds.push(existing[0]!.id);+ }+ await db+ .insert(scimGroupMember)+ .values(groupIds.map((groupId) => ({ groupId, userId })))+ .onConflictDoNothing();+ const projectIds = (await Promise.all(groupIds.map(mappedProjectIds))).flat();+ await reconcileProjects(projectIds);+}++// Removing the account for real, the way god mode does. Deprovisioning normally+// arrives as `active: false` instead; DELETE stays a real delete so it does not+// disagree with what the owner sees in god mode.+export async function deleteScimUser(id: string): Promise<void> {+ const rows = await db+ .select({ role: user.role, agentId: aiAgent.id })+ .from(user)+ .leftJoin(aiAgent, eq(aiAgent.userId, user.id))+ .where(eq(user.id, id));+ const row = rows[0];+ // An agent's bot user is not part of the SCIM user surface at all, so it answers+ // the same way an unknown id does.+ if (!row || row.agentId) throw new ScimError(404, `User '${id}' not found`);+ if (row.role === 'god') throw new ScimError(409, 'An instance owner cannot be deleted');++ if ((await soleOwnedProjects(id)).length > 0) {+ throw new ScimError(+ 409,+ 'This user is the only owner of a project. Deactivate them instead, or hand the ' ++ 'project over to another owner first.',+ );+ }+ await deleteInstanceUser(id);+}++// The projects this user owns alone. Deleting them would leave those projects with+// nobody who can manage their members.+async function soleOwnedProjects(userId: string): Promise<number[]> {+ const owned = await db+ .select({ projectId: projectMember.projectId })+ .from(projectMember)+ .where(and(eq(projectMember.userId, userId), eq(projectMember.role, 'owner')));+ const sole: number[] = [];+ for (const row of owned) {+ if ((await countOwners(row.projectId)) <= 1) sole.push(row.projectId);+ }+ return sole;+}++// ── Groups ────────────────────────────────────────────────────────────────────++function groupFilterWhere(filter: ScimFilter | null) {+ if (!filter) return undefined;+ if (filter.attribute === 'externalid') return eq(scimGroup.externalId, filter.value);+ return eq(scimGroup.displayName, filter.value);+}++async function loadMembers(+ groupIds: string[],+): Promise<Map<string, { userId: string; name: string }[]>> {+ const out = new Map<string, { userId: string; name: string }[]>();+ if (groupIds.length === 0) return out;+ const rows = await db+ .select({ groupId: scimGroupMember.groupId, userId: user.id, name: user.name })+ .from(scimGroupMember)+ .innerJoin(user, eq(user.id, scimGroupMember.userId))+ .where(inArray(scimGroupMember.groupId, groupIds))+ .orderBy(user.name);+ for (const row of rows) {+ const list = out.get(row.groupId) ?? [];+ list.push({ userId: row.userId, name: row.name });+ out.set(row.groupId, list);+ }+ return out;+}++async function toGroupRecords(+ rows: {+ id: string;+ displayName: string;+ externalId: string | null;+ createdAt: Date;+ updatedAt: Date;+ }[],+): Promise<ScimGroupRecord[]> {+ const members = await loadMembers(rows.map((r) => r.id));+ return rows.map((row) => ({+ id: row.id,+ displayName: row.displayName,+ externalId: row.externalId,+ members: members.get(row.id) ?? [],+ createdAt: iso(row.createdAt),+ updatedAt: iso(row.updatedAt),+ }));+}++export async function listScimGroups(options: {+ filter: ScimFilter | null;+ startIndex: number;+ count: number;+}): Promise<{ records: ScimGroupRecord[]; total: number }> {+ const where = groupFilterWhere(options.filter);+ const [rows, totals] = await Promise.all([+ db+ .select()+ .from(scimGroup)+ .where(where)+ .orderBy(scimGroup.createdAt)+ .limit(options.count)+ .offset(options.startIndex - 1),+ db+ .select({ count: sql<number>`count(*)::int` })+ .from(scimGroup)+ .where(where),+ ]);+ return { records: await toGroupRecords(rows), total: totals[0]?.count ?? 0 };+}++export async function getScimGroup(id: string): Promise<ScimGroupRecord | null> {+ const rows = await db.select().from(scimGroup).where(eq(scimGroup.id, id));+ if (!rows[0]) return null;+ return (await toGroupRecords(rows))[0]!;+}++// Replaces a group's member list and reconciles every project the group grants+// membership in. Passing `undefined` leaves the members alone.+async function writeMembers(groupId: string, userIds: string[] | undefined): Promise<void> {+ if (!userIds) return;+ const unique = [...new Set(userIds)];+ if (unique.length > 0) {+ const known = await db.select({ id: user.id }).from(user).where(inArray(user.id, unique));+ const missing = unique.filter((id) => !known.some((k) => k.id === id));+ if (missing.length > 0) {+ throw new ScimError(400, `Unknown member id(s): ${missing.join(', ')}`, 'invalidValue');+ }+ }+ await db.transaction(async (tx) => {+ await tx.delete(scimGroupMember).where(eq(scimGroupMember.groupId, groupId));+ if (unique.length > 0) {+ await tx.insert(scimGroupMember).values(unique.map((userId) => ({ groupId, userId })));+ }+ });+}++export async function createScimGroup(input: {+ displayName: string;+ externalId: string | null;+ members: string[];+}): Promise<ScimGroupRecord> {+ const existing = await db+ .select({ id: scimGroup.id })+ .from(scimGroup)+ .where(eq(scimGroup.displayName, input.displayName));+ if (existing.length > 0) {+ throw new ScimError(409, `A group named '${input.displayName}' already exists`, 'uniqueness');+ }+ const rows = await db+ .insert(scimGroup)+ .values({ displayName: input.displayName, externalId: input.externalId })+ .returning();+ const created = rows[0]!;+ await writeMembers(created.id, input.members);+ await reconcileProjects(await mappedProjectIds(created.id));+ return (await getScimGroup(created.id))!;+}++export async function updateScimGroup(+ id: string,+ patch: { displayName?: string; externalId?: string | null; members?: string[] },+): Promise<ScimGroupRecord | null> {+ const found = await db.select({ id: scimGroup.id }).from(scimGroup).where(eq(scimGroup.id, id));+ if (!found[0]) return null;+ if (patch.displayName) {+ const clash = await db+ .select({ id: scimGroup.id })+ .from(scimGroup)+ .where(eq(scimGroup.displayName, patch.displayName));+ if (clash[0] && clash[0].id !== id) {+ throw new ScimError(409, `A group named '${patch.displayName}' already exists`, 'uniqueness');+ }+ }+ await db+ .update(scimGroup)+ .set({+ ...(patch.displayName ? { displayName: patch.displayName } : {}),+ ...(patch.externalId !== undefined ? { externalId: patch.externalId } : {}),+ updatedAt: new Date(),+ })+ .where(eq(scimGroup.id, id));+ await writeMembers(id, patch.members);+ await reconcileProjects(await mappedProjectIds(id));+ return getScimGroup(id);+}++export async function addScimGroupMembers(groupId: string, userIds: string[]): Promise<void> {+ const current = await db+ .select({ userId: scimGroupMember.userId })+ .from(scimGroupMember)+ .where(eq(scimGroupMember.groupId, groupId));+ await writeMembers(groupId, [...current.map((r) => r.userId), ...userIds]);+}++export async function removeScimGroupMembers(groupId: string, userIds: string[]): Promise<void> {+ await db+ .delete(scimGroupMember)+ .where(+ and(+ eq(scimGroupMember.groupId, groupId),+ inArray(scimGroupMember.userId, [...new Set(userIds)]),+ ),+ );+}++export async function deleteScimGroup(id: string): Promise<boolean> {+ // Read the mappings before the cascade removes them, so the projects the group+ // granted membership in are reconciled after it is gone.+ const projects = await mappedProjectIds(id);+ const deleted = await db+ .delete(scimGroup)+ .where(eq(scimGroup.id, id))+ .returning({ id: scimGroup.id });+ if (deleted.length === 0) return false;+ await reconcileProjects(projects);+ return true;+}diff --git a/apps/api/src/shared/auth-context.ts b/apps/api/src/shared/auth-context.tsindex 88a15ad0..a2e2559d 100644--- a/apps/api/src/shared/auth-context.ts+++ b/apps/api/src/shared/auth-context.ts@@ -25,11 +25,18 @@ export type SessionUser = SessionResult['user'];// session-gated. A feature also uses it directly when its handlers or local// macros reference `user`, which is what makes the `user` type flow there. The// plugin is named, so its resolve runs once per request (dedup).+//+// A deactivated account is refused here rather than at sign-in: deactivation+// arrives over SCIM while sessions and API keys are already open, and this is the+// one place every planner route and the MCP surface pass through.export const authContext = new Elysia({ name: 'auth-context' }).resolve({ as: 'scoped' },async ({ request, path }): Promise<{ user: SessionUser | null }> => {const session = await auth.api.getSession({ headers: request.headers });- if (session) return { user: session.user };+ if (session) {+ if (session.user.active === false) throw new HttpError(401, 'This account is deactivated');+ return { user: session.user };+ }// The public raw-attachment route has no session and needs none.if (request.method === 'GET' && PUBLIC_GET.test(path)) return { user: null };throw new HttpError(401, 'Authentication required');diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.jsonindex b7f3ee84..24405132 100644--- a/apps/web/messages/ar/auth.json+++ b/apps/web/messages/ar/auth.json@@ -37,7 +37,9 @@"withPasskey": "تسجيل الدخول عبر passkey","unconfirmedResent": "بعتنا بريد التأكيد. بصّ في صندوق الوارد وفي مجلد البريد غير المرغوب.","unconfirmedPrompt": "بصّ في مجلد البريد غير المرغوب، أو <resend>ابعت بريد تأكيد جديد</resend>.",- "unconfirmedNeedsEmail": "ادخل ببريدك الإلكتروني عشان تبعت بريد تأكيد جديد."+ "unconfirmedNeedsEmail": "ادخل ببريدك الإلكتروني عشان تبعت بريد تأكيد جديد.",+ "withSso": "المتابعة بالدخول الموحّد",+ "subtitleSso": "سجّل الدخول بحساب مؤسستك"},"register": {"title": "أنشئ حسابك",@@ -53,7 +55,9 @@"confirmDescription": "بعتنا رابط على {email}. افتحه عشان تكمّل إنشاء حسابك.","backToSignIn": "العودة إلى تسجيل الدخول","closedTitle": "التسجيل مغلق",- "closedDescription": "النسخة دي مش بتقبل حسابات جديدة."+ "closedDescription": "النسخة دي مش بتقبل حسابات جديدة.",+ "withSso": "المتابعة بالدخول الموحّد",+ "subtitleSso": "يُنشئ حسابك مزوّد الهوية الخاص بمؤسستك"},"forgotPassword": {"title": "إعادة تعيين كلمة المرور",@@ -85,6 +89,9 @@"emailNotFound": "Google مرجّعش عنوان بريد للحساب ده.","tokenExpired": "رابط التأكيد ده انتهت صلاحيته. سجّل دخولك من تحت عشان يوصلك رابط جديد.","invalidToken": "رابط التأكيد ده مش صالح. سجّل دخولك من تحت عشان يوصلك رابط جديد.",- "userNotFound": "رابط التأكيد ده بتاع حساب مبقاش موجود."+ "userNotFound": "رابط التأكيد ده بتاع حساب مبقاش موجود.",+ "ssoDisabled": "الدخول الموحّد غير متاح على هذا الخادم.",+ "passwordDisabled": "يتم تسجيل الدخول على هذا الخادم عبر مزوّد الهوية فقط.",+ "accountDeactivated": "هذا الحساب معطّل. اطلب من المسؤول إعادة تفعيله."}}diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex c9ed1eb2..e5539f9f 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -145,12 +145,15 @@}},"signIn": "خيارات تسجيل الدخول",- "signInHint": "الخيارات دي محتاجة بريد صادر، فهتفضل معطّلة لحد ما تظبط مزوّد بريد.",+ "signInHint": "كيف يسجّل الناس الدخول. تبقى الخيارات التي ترسل بريداً معطّلة حتى يُضبط مزوّد بريد.","needsProvider": "ظبّط مزوّد البريد الإلكتروني من التكاملات الأول.","requireVerification": "اشتراط تأكيد البريد الإلكتروني","requireVerificationHint": "الحساب الجديد لازم يأكّد عنوان بريده الأول عشان يقدر يسجّل دخول.","magicLink": "روابط تسجيل الدخول",- "magicLinkHint": "تدّي الناس خيار إنها تسجّل دخول برابط بيوصل على البريد، جنب كلمة المرور."+ "magicLinkHint": "تدّي الناس خيار إنها تسجّل دخول برابط بيوصل على البريد، جنب كلمة المرور.",+ "emailPassword": "البريد وكلمة المرور",+ "emailPasswordHint": "إظهار نموذج تسجيل الدخول والتسجيل. عطّله ليتم الدخول عبر مزوّد تسجيل الدخول فقط.",+ "needsSso": "اضبط مزوّد تسجيل دخول من قسم التكاملات أولاً."},"hotkeys": {"saved": "تم حفظ اختصارات لوحة المفاتيح"@@ -212,6 +215,61 @@"clientSecret": "سر العميل","redirectUri": "URL إعادة التوجيه","redirectUriHint": "سجّل ده في عميل OAuth في وحدة تحكم Google Cloud. لو مش متطابق بالحرف، Google هترفض تسجيل الدخول.",- "copyRedirectUri": "نسخ URL إعادة التوجيه"+ "copyRedirectUri": "نسخ URL إعادة التوجيه",+ "oidc": "OpenID Connect",+ "oidcConfigured": "العنوان الذي لا حساب له يحصل على حساب، والعنوان الذي له حساب مؤكَّد يدخل إليه.",+ "oidcMissing": "أضف عنوان الاكتشاف ومعرّف العميل والسر أولاً.",+ "discoveryUrl": "عنوان الاكتشاف",+ "discoveryUrlHint": "عنوان .well-known/openid-configuration الخاص بمزوّدك. تُقرأ منه نقاط التخويل والرمز ومعلومات المستخدم.",+ "oidcLabel": "نص الزر",+ "oidcLabelPlaceholder": "تسجيل الدخول عبر Acme SSO",+ "oidcLabelHint": "يسمّي مزوّدك على زر تسجيل الدخول. اتركه فارغاً لنص عام.",+ "scopes": "النطاقات",+ "scopesHint": "مفصولة بمسافات. openid مطلوب، وprofile وemail يملآن الاسم والعنوان.",+ "oidcRedirectUriHint": "سجّل هذا العنوان كعنوان إعادة توجيه في العميل لدى مزوّد الهوية. يرفض المزوّد تسجيل الدخول إن لم يطابقه تماماً."+ },+ "scim": {+ "saved": "تم حفظ إعدادات SCIM",+ "provisioning": "تزويد الحسابات",+ "provisioningConfigured": "يقوم مزوّد الهوية بإنشاء الحسابات وتحديثها وتعطيلها على هذا الخادم.",+ "provisioningMissing": "أنشئ رمزاً أولاً.",+ "token": "الرمز",+ "noToken": "لم يُنشأ رمز بعد",+ "tokenHint": "الرمز الذي يرسله مزوّد الهوية. يُعرض مرة واحدة، وإنشاء رمز جديد يوقف القديم.",+ "generateToken": "إنشاء رمز",+ "replaceToken": "استبدال الرمز",+ "baseUrl": "عنوان SCIM",+ "baseUrlHint": "وجّه مزوّد الهوية إلى هذا العنوان.",+ "copyBaseUrl": "نسخ عنوان SCIM",+ "groups": "المجموعات",+ "groupsHint": "المجموعات التي أرسلها مزوّد الهوية. القائمة تخصّه، وما تمنحه كل مجموعة يُحدَّد هنا.",+ "groupsEmpty": "لم تُرسل أي مجموعات بعد.",+ "memberCount": "{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}}",+ "grantsNothing": "لا تمنح شيئاً بعد",+ "editMappings": "تعديل الوصول",+ "roleOwner": "مالك",+ "roleMember": "عضو",+ "tokenDialog": {+ "title": "إنشاء رمز SCIM",+ "description": "يُعرض الرمز مرة واحدة ولا يمكن قراءته لاحقاً. أي رمز مستخدَم حالياً سيتوقف عن العمل.",+ "submit": "إنشاء",+ "submitPending": "جارٍ الإنشاء…",+ "createdTitle": "رمز SCIM الخاص بك",+ "createdDescription": "انسخه إلى مزوّد الهوية الآن. لا يمكن عرضه مرة أخرى.",+ "copy": "نسخ الرمز"+ },+ "mappings": {+ "title": "ما تمنحه {group}",+ "description": "ينضم أعضاء هذه المجموعة إلى المشاريع المذكورة هنا. إزالة مشروع تسحب العضويات التي منحتها هذه المجموعة له.",+ "empty": "لا تمنح هذه المجموعة شيئاً بعد.",+ "addProject": "إضافة مشروع…",+ "role": "الدور",+ "roleOwner": "مالك",+ "roleMember": "عضو",+ "projectRole": "الدور في المشروع",+ "defaultRole": "الدور الافتراضي",+ "remove": "إزالة المشروع",+ "saved": "تم حفظ وصول المجموعة"+ }}}diff --git a/apps/web/messages/ar/members.json b/apps/web/messages/ar/members.jsonindex ea00ce43..c358b7f6 100644--- a/apps/web/messages/ar/members.json+++ b/apps/web/messages/ar/members.json@@ -104,5 +104,6 @@},"promoted": "تمت ترقية العضو إلى مالك","roleUpdated": "تم تحديث دور العضو",- "descriptionUpdated": "تم تحديث وصف العضو"+ "descriptionUpdated": "تم تحديث وصف العضو",+ "provisioned": "مُدار عبر SCIM"}diff --git a/apps/web/messages/ar/sections.json b/apps/web/messages/ar/sections.jsonindex a16f8be3..d5b186ce 100644--- a/apps/web/messages/ar/sections.json+++ b/apps/web/messages/ar/sections.json@@ -46,6 +46,10 @@"auth-provider": {"label": "مزوّد المصادقة","description": "الحسابات الخارجية اللي الناس تقدر تدخل بيها."+ },+ "scim": {+ "label": "SCIM",+ "description": "اسمح لمزوّد الهوية بإنشاء الحسابات وتحديثها وتعطيلها على هذا الخادم، ومنح الوصول إلى المشاريع عبر مجموعاته."}},"settings": {diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.jsonindex 161a54eb..ab0e115b 100644--- a/apps/web/messages/en/auth.json+++ b/apps/web/messages/en/auth.json@@ -37,7 +37,9 @@"withPasskey": "Sign in with passkey","unconfirmedResent": "Confirmation email sent. Check your inbox, and your spam folder.","unconfirmedPrompt": "Check your spam folder, or <resend>send a new confirmation email</resend>.",- "unconfirmedNeedsEmail": "Sign in with your email address to send a new confirmation email."+ "unconfirmedNeedsEmail": "Sign in with your email address to send a new confirmation email.",+ "withSso": "Continue with single sign-on",+ "subtitleSso": "Sign in with your organization account"},"register": {"title": "Create your account",@@ -53,7 +55,9 @@"confirmDescription": "We sent a link to {email}. Open it to finish creating your account.","backToSignIn": "Back to sign in","closedTitle": "Registration is closed",- "closedDescription": "This instance is not accepting new accounts."+ "closedDescription": "This instance is not accepting new accounts.",+ "withSso": "Continue with single sign-on",+ "subtitleSso": "Your account is created by your identity provider"},"forgotPassword": {"title": "Reset your password",@@ -85,6 +89,9 @@"emailNotFound": "Google did not return an email address for this account.","tokenExpired": "This confirmation link has expired. Sign in below to get a new one.","invalidToken": "This confirmation link is not valid. Sign in below to get a new one.",- "userNotFound": "This confirmation link belongs to an account that no longer exists."+ "userNotFound": "This confirmation link belongs to an account that no longer exists.",+ "ssoDisabled": "Single sign-on is not available on this instance.",+ "passwordDisabled": "This instance signs people in through its identity provider only.",+ "accountDeactivated": "This account is deactivated. Ask your administrator to restore it."}}diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex 453329c0..aa4dcebc 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -145,12 +145,15 @@}},"signIn": "Sign-in options",- "signInHint": "Options that need outbound mail. They stay off until a provider is configured.",+ "signInHint": "How people sign in. The options that send mail stay off until a provider is configured.","needsProvider": "Set up the Email provider under Integrations first.","requireVerification": "Require email confirmation","requireVerificationHint": "A new account must confirm its address before it can sign in.","magicLink": "Sign-in links",- "magicLinkHint": "Offer signing in with a link sent by email, alongside the password."+ "magicLinkHint": "Offer signing in with a link sent by email, alongside the password.",+ "emailPassword": "Email and password",+ "emailPasswordHint": "Offer the sign-in and sign-up form. Turn it off to let people in through a sign-in provider only.",+ "needsSso": "Set up a sign-in provider under Integrations first."},"hotkeys": {"saved": "Keyboard shortcuts saved"@@ -212,6 +215,61 @@"clientSecret": "Client secret","redirectUri": "Redirect URI","redirectUriHint": "Register this on the OAuth client in the Google Cloud console. Google refuses the sign-in if it does not match exactly.",- "copyRedirectUri": "Copy redirect URI"+ "copyRedirectUri": "Copy redirect URI",+ "oidc": "OpenID Connect",+ "oidcConfigured": "An address without an account gets one; an address that already has a confirmed account signs into it.",+ "oidcMissing": "Add the discovery URL, client ID and secret first.",+ "discoveryUrl": "Discovery URL",+ "discoveryUrlHint": "Your provider's .well-known/openid-configuration. The authorization, token and userinfo endpoints are read from it.",+ "oidcLabel": "Button label",+ "oidcLabelPlaceholder": "Sign in with Acme SSO",+ "oidcLabelHint": "Names your provider on the sign-in button. Leave it empty for a generic label.",+ "scopes": "Scopes",+ "scopesHint": "Separated by spaces. openid is required; profile and email fill in the name and address.",+ "oidcRedirectUriHint": "Register this as a redirect URI on the client at your identity provider. The provider refuses the sign-in if it does not match exactly."+ },+ "scim": {+ "saved": "SCIM settings saved",+ "provisioning": "Provisioning",+ "provisioningConfigured": "Your identity provider creates, updates and deactivates accounts on this instance.",+ "provisioningMissing": "Generate a token first.",+ "token": "Token",+ "noToken": "No token generated yet",+ "tokenHint": "The bearer token your identity provider sends. It is shown once; generating a new one stops the old one working.",+ "generateToken": "Generate token",+ "replaceToken": "Replace token",+ "baseUrl": "SCIM endpoint",+ "baseUrlHint": "Point your identity provider at this address.",+ "copyBaseUrl": "Copy SCIM endpoint",+ "groups": "Groups",+ "groupsHint": "The groups your identity provider has pushed. The list is theirs; what each group grants is set here.",+ "groupsEmpty": "No groups have been pushed yet.",+ "memberCount": "{count, plural, =0 {No members} one {# member} other {# members}}",+ "grantsNothing": "grants nothing yet",+ "editMappings": "Edit access",+ "roleOwner": "Owner",+ "roleMember": "Member",+ "tokenDialog": {+ "title": "Generate a SCIM token",+ "description": "The token is shown once and cannot be read back. Any token already in use stops working.",+ "submit": "Generate",+ "submitPending": "Generating…",+ "createdTitle": "Your SCIM token",+ "createdDescription": "Copy it into your identity provider now. It cannot be shown again.",+ "copy": "Copy token"+ },+ "mappings": {+ "title": "What {group} grants",+ "description": "Members of this group join the projects listed here. Removing a project takes away the memberships this group gave it.",+ "empty": "This group grants nothing yet.",+ "addProject": "Add a project…",+ "role": "Role",+ "roleOwner": "Owner",+ "roleMember": "Member",+ "projectRole": "Project role",+ "defaultRole": "Default role",+ "remove": "Remove project",+ "saved": "Group access saved"+ }}}diff --git a/apps/web/messages/en/members.json b/apps/web/messages/en/members.jsonindex 52ea99f3..233b1564 100644--- a/apps/web/messages/en/members.json+++ b/apps/web/messages/en/members.json@@ -104,5 +104,6 @@},"promoted": "Member promoted to owner","roleUpdated": "Member role updated",- "descriptionUpdated": "Member description updated"+ "descriptionUpdated": "Member description updated",+ "provisioned": "Managed by SCIM"}diff --git a/apps/web/messages/en/sections.json b/apps/web/messages/en/sections.jsonindex 25f8befd..b5a15aac 100644--- a/apps/web/messages/en/sections.json+++ b/apps/web/messages/en/sections.json@@ -46,6 +46,10 @@"auth-provider": {"label": "Auth provider","description": "The external accounts people may sign in with."+ },+ "scim": {+ "label": "SCIM",+ "description": "Let an identity provider create, update and deactivate accounts on this instance, and grant project access through its groups."}},"settings": {diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.jsonindex f9f233db..c985fd18 100644--- a/apps/web/messages/ru/auth.json+++ b/apps/web/messages/ru/auth.json@@ -37,7 +37,9 @@"withPasskey": "Войти по passkey","unconfirmedResent": "Письмо с подтверждением отправлено. Проверьте входящие и папку со спамом.","unconfirmedPrompt": "Проверьте папку со спамом или <resend>отправьте новое письмо с подтверждением</resend>.",- "unconfirmedNeedsEmail": "Войдите по адресу почты, чтобы отправить новое письмо с подтверждением."+ "unconfirmedNeedsEmail": "Войдите по адресу почты, чтобы отправить новое письмо с подтверждением.",+ "withSso": "Войти через единый вход",+ "subtitleSso": "Войдите с учётной записью вашей организации"},"register": {"title": "Создайте аккаунт",@@ -53,7 +55,9 @@"confirmDescription": "Мы отправили ссылку на {email}. Откройте её, чтобы завершить создание аккаунта.","backToSignIn": "Назад ко входу","closedTitle": "Регистрация закрыта",- "closedDescription": "Этот инстанс не принимает новые аккаунты."+ "closedDescription": "Этот инстанс не принимает новые аккаунты.",+ "withSso": "Войти через единый вход",+ "subtitleSso": "Учётную запись создаёт ваш поставщик удостоверений"},"forgotPassword": {"title": "Сброс пароля",@@ -85,6 +89,9 @@"emailNotFound": "Google не вернул адрес почты для этого аккаунта.","tokenExpired": "Срок действия ссылки для подтверждения истёк. Войдите ниже, чтобы получить новую.","invalidToken": "Ссылка для подтверждения недействительна. Войдите ниже, чтобы получить новую.",- "userNotFound": "Ссылка для подтверждения принадлежит аккаунту, которого больше не существует."+ "userNotFound": "Ссылка для подтверждения принадлежит аккаунту, которого больше не существует.",+ "ssoDisabled": "Единый вход недоступен на этом сервере.",+ "passwordDisabled": "На этом сервере вход выполняется только через поставщика удостоверений.",+ "accountDeactivated": "Учётная запись отключена. Обратитесь к администратору."}}diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex 61813966..a18a6b84 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -145,12 +145,15 @@}},"signIn": "Способы входа",- "signInHint": "Опции, которым нужна исходящая почта. Они выключены, пока не настроен провайдер.",+ "signInHint": "Как выполняется вход. Варианты, отправляющие почту, недоступны, пока не настроен поставщик.","needsProvider": "Сначала настройте почтового провайдера в разделе «Интеграции».","requireVerification": "Требовать подтверждение почты","requireVerificationHint": "Новый аккаунт должен подтвердить адрес, прежде чем сможет войти.","magicLink": "Ссылки для входа",- "magicLinkHint": "Предлагать вход по ссылке из письма, наряду с паролем."+ "magicLinkHint": "Предлагать вход по ссылке из письма, наряду с паролем.",+ "emailPassword": "Почта и пароль",+ "emailPasswordHint": "Показывать форму входа и регистрации. Отключите, чтобы вход выполнялся только через поставщика.",+ "needsSso": "Сначала настройте поставщика входа в разделе «Интеграции»."},"hotkeys": {"saved": "Клавиатурные сокращения сохранены"@@ -212,6 +215,61 @@"clientSecret": "Client secret","redirectUri": "Redirect URI","redirectUriHint": "Зарегистрируйте его для OAuth-клиента в Google Cloud console. Google отклонит вход, если он не совпадает точно.",- "copyRedirectUri": "Скопировать redirect URI"+ "copyRedirectUri": "Скопировать redirect URI",+ "oidc": "OpenID Connect",+ "oidcConfigured": "Адрес без учётной записи получает её; адрес с подтверждённой учётной записью входит в неё.",+ "oidcMissing": "Сначала укажите адрес discovery, идентификатор клиента и секрет.",+ "discoveryUrl": "Адрес discovery",+ "discoveryUrlHint": "Адрес .well-known/openid-configuration вашего поставщика. Из него читаются конечные точки авторизации, токена и userinfo.",+ "oidcLabel": "Надпись на кнопке",+ "oidcLabelPlaceholder": "Войти через Acme SSO",+ "oidcLabelHint": "Называет вашего поставщика на кнопке входа. Оставьте пустым для общей надписи.",+ "scopes": "Scopes",+ "scopesHint": "Через пробел. openid обязателен; profile и email заполняют имя и адрес.",+ "oidcRedirectUriHint": "Укажите этот адрес как redirect URI у клиента вашего поставщика удостоверений. При несовпадении поставщик отклонит вход."+ },+ "scim": {+ "saved": "Настройки SCIM сохранены",+ "provisioning": "Подготовка учётных записей",+ "provisioningConfigured": "Ваш поставщик удостоверений создаёт, обновляет и отключает учётные записи на этом сервере.",+ "provisioningMissing": "Сначала создайте токен.",+ "token": "Токен",+ "noToken": "Токен ещё не создан",+ "tokenHint": "Токен, который отправляет ваш поставщик удостоверений. Он показывается один раз; новый токен отменяет прежний.",+ "generateToken": "Создать токен",+ "replaceToken": "Заменить токен",+ "baseUrl": "Адрес SCIM",+ "baseUrlHint": "Укажите этот адрес в вашем поставщике удостоверений.",+ "copyBaseUrl": "Копировать адрес SCIM",+ "groups": "Группы",+ "groupsHint": "Группы, переданные вашим поставщиком удостоверений. Список принадлежит ему; что даёт каждая группа, задаётся здесь.",+ "groupsEmpty": "Группы ещё не переданы.",+ "memberCount": "{count, plural, =0 {Нет участников} one {# участник} few {# участника} many {# участников} other {# участника}}",+ "grantsNothing": "пока ничего не даёт",+ "editMappings": "Изменить доступ",+ "roleOwner": "Владелец",+ "roleMember": "Участник",+ "tokenDialog": {+ "title": "Создать токен SCIM",+ "description": "Токен показывается один раз и не может быть прочитан позже. Действующий токен перестанет работать.",+ "submit": "Создать",+ "submitPending": "Создание…",+ "createdTitle": "Ваш токен SCIM",+ "createdDescription": "Скопируйте его в поставщика удостоверений сейчас. Показать его снова нельзя.",+ "copy": "Копировать токен"+ },+ "mappings": {+ "title": "Что даёт группа {group}",+ "description": "Участники этой группы входят в перечисленные проекты. Удаление проекта снимает участия, которые дала эта группа.",+ "empty": "Эта группа пока ничего не даёт.",+ "addProject": "Добавить проект…",+ "role": "Роль",+ "roleOwner": "Владелец",+ "roleMember": "Участник",+ "projectRole": "Роль в проекте",+ "defaultRole": "Роль по умолчанию",+ "remove": "Убрать проект",+ "saved": "Доступ группы сохранён"+ }}}diff --git a/apps/web/messages/ru/members.json b/apps/web/messages/ru/members.jsonindex 810ac694..48ca5334 100644--- a/apps/web/messages/ru/members.json+++ b/apps/web/messages/ru/members.json@@ -104,5 +104,6 @@},"promoted": "Участник назначен владельцем","roleUpdated": "Роль участника обновлена",- "descriptionUpdated": "Описание участника обновлено"+ "descriptionUpdated": "Описание участника обновлено",+ "provisioned": "Управляется SCIM"}diff --git a/apps/web/messages/ru/sections.json b/apps/web/messages/ru/sections.jsonindex 7cb2a7e5..7c844e30 100644--- a/apps/web/messages/ru/sections.json+++ b/apps/web/messages/ru/sections.json@@ -46,6 +46,10 @@"auth-provider": {"label": "Провайдер входа","description": "Внешние аккаунты, через которые можно входить."+ },+ "scim": {+ "label": "SCIM",+ "description": "Позвольте поставщику удостоверений создавать, обновлять и отключать учётные записи на этом сервере и давать доступ к проектам через свои группы."}},"settings": {diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.jsonindex 21e60920..ff35f047 100644--- a/apps/web/messages/uk/auth.json+++ b/apps/web/messages/uk/auth.json@@ -37,7 +37,9 @@"withPasskey": "Увійти за passkey","unconfirmedResent": "Лист із підтвердженням надіслано. Перевірте вхідні та теку зі спамом.","unconfirmedPrompt": "Перевірте теку зі спамом або <resend>надішліть новий лист із підтвердженням</resend>.",- "unconfirmedNeedsEmail": "Увійдіть за адресою пошти, щоб надіслати новий лист із підтвердженням."+ "unconfirmedNeedsEmail": "Увійдіть за адресою пошти, щоб надіслати новий лист із підтвердженням.",+ "withSso": "Увійти через єдиний вхід",+ "subtitleSso": "Увійдіть обліковим записом вашої організації"},"register": {"title": "Створіть акаунт",@@ -53,7 +55,9 @@"confirmDescription": "Ми надіслали посилання на {email}. Відкрийте його, щоб завершити створення акаунта.","backToSignIn": "Назад до входу","closedTitle": "Реєстрацію закрито",- "closedDescription": "Цей інстанс не приймає нових акаунтів."+ "closedDescription": "Цей інстанс не приймає нових акаунтів.",+ "withSso": "Увійти через єдиний вхід",+ "subtitleSso": "Обліковий запис створює ваш постачальник ідентифікації"},"forgotPassword": {"title": "Скидання пароля",@@ -85,6 +89,9 @@"emailNotFound": "Google не повернув адресу пошти для цього акаунта.","tokenExpired": "Термін дії посилання для підтвердження минув. Увійдіть нижче, щоб отримати нове.","invalidToken": "Посилання для підтвердження недійсне. Увійдіть нижче, щоб отримати нове.",- "userNotFound": "Посилання для підтвердження належить акаунту, якого більше не існує."+ "userNotFound": "Посилання для підтвердження належить акаунту, якого більше не існує.",+ "ssoDisabled": "Єдиний вхід недоступний на цьому сервері.",+ "passwordDisabled": "На цьому сервері вхід виконується лише через постачальника ідентифікації.",+ "accountDeactivated": "Обліковий запис вимкнено. Зверніться до адміністратора."}}diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex c04c5004..98c94d4f 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -145,12 +145,15 @@}},"signIn": "Способи входу",- "signInHint": "Опції, яким потрібна вихідна пошта. Вони вимкнені, доки не налаштовано провайдера.",+ "signInHint": "Як виконується вхід. Варіанти, що надсилають пошту, недоступні, доки не налаштовано постачальника.","needsProvider": "Спершу налаштуйте поштового провайдера в розділі «Інтеграції».","requireVerification": "Вимагати підтвердження пошти","requireVerificationHint": "Новий акаунт має підтвердити адресу, перш ніж зможе увійти.","magicLink": "Посилання для входу",- "magicLinkHint": "Пропонувати вхід за посиланням із листа, поряд із паролем."+ "magicLinkHint": "Пропонувати вхід за посиланням із листа, поряд із паролем.",+ "emailPassword": "Пошта і пароль",+ "emailPasswordHint": "Показувати форму входу та реєстрації. Вимкніть, щоб вхід виконувався лише через постачальника.",+ "needsSso": "Спочатку налаштуйте постачальника входу в розділі «Інтеграції»."},"hotkeys": {"saved": "Клавіатурні скорочення збережено"@@ -212,6 +215,61 @@"clientSecret": "Client secret","redirectUri": "Redirect URI","redirectUriHint": "Зареєструйте його для OAuth-клієнта в Google Cloud console. Google відхилить вхід, якщо він не збігається точно.",- "copyRedirectUri": "Скопіювати redirect URI"+ "copyRedirectUri": "Скопіювати redirect URI",+ "oidc": "OpenID Connect",+ "oidcConfigured": "Адреса без облікового запису отримує його; адреса з підтвердженим обліковим записом входить у нього.",+ "oidcMissing": "Спочатку вкажіть адресу discovery, ідентифікатор клієнта та секрет.",+ "discoveryUrl": "Адреса discovery",+ "discoveryUrlHint": "Адреса .well-known/openid-configuration вашого постачальника. З неї читаються кінцеві точки авторизації, токена та userinfo.",+ "oidcLabel": "Напис на кнопці",+ "oidcLabelPlaceholder": "Увійти через Acme SSO",+ "oidcLabelHint": "Називає вашого постачальника на кнопці входу. Залиште порожнім для загального напису.",+ "scopes": "Scopes",+ "scopesHint": "Через пробіл. openid обовʼязковий; profile та email заповнюють імʼя й адресу.",+ "oidcRedirectUriHint": "Вкажіть цю адресу як redirect URI у клієнта вашого постачальника ідентифікації. За розбіжності постачальник відхилить вхід."+ },+ "scim": {+ "saved": "Налаштування SCIM збережено",+ "provisioning": "Підготовка облікових записів",+ "provisioningConfigured": "Ваш постачальник ідентифікації створює, оновлює та вимикає облікові записи на цьому сервері.",+ "provisioningMissing": "Спочатку створіть токен.",+ "token": "Токен",+ "noToken": "Токен ще не створено",+ "tokenHint": "Токен, який надсилає ваш постачальник ідентифікації. Він показується один раз; новий токен скасовує попередній.",+ "generateToken": "Створити токен",+ "replaceToken": "Замінити токен",+ "baseUrl": "Адреса SCIM",+ "baseUrlHint": "Вкажіть цю адресу у вашому постачальнику ідентифікації.",+ "copyBaseUrl": "Копіювати адресу SCIM",+ "groups": "Групи",+ "groupsHint": "Групи, передані вашим постачальником ідентифікації. Список належить йому; що дає кожна група, задається тут.",+ "groupsEmpty": "Групи ще не передано.",+ "memberCount": "{count, plural, =0 {Немає учасників} one {# учасник} few {# учасники} many {# учасників} other {# учасника}}",+ "grantsNothing": "поки нічого не дає",+ "editMappings": "Змінити доступ",+ "roleOwner": "Власник",+ "roleMember": "Учасник",+ "tokenDialog": {+ "title": "Створити токен SCIM",+ "description": "Токен показується один раз і не може бути прочитаний пізніше. Чинний токен перестане працювати.",+ "submit": "Створити",+ "submitPending": "Створення…",+ "createdTitle": "Ваш токен SCIM",+ "createdDescription": "Скопіюйте його в постачальника ідентифікації зараз. Показати його знову не можна.",+ "copy": "Копіювати токен"+ },+ "mappings": {+ "title": "Що дає група {group}",+ "description": "Учасники цієї групи входять до перелічених проєктів. Вилучення проєкту знімає участі, які дала ця група.",+ "empty": "Ця група поки нічого не дає.",+ "addProject": "Додати проєкт…",+ "role": "Роль",+ "roleOwner": "Власник",+ "roleMember": "Учасник",+ "projectRole": "Роль у проєкті",+ "defaultRole": "Роль за замовчуванням",+ "remove": "Прибрати проєкт",+ "saved": "Доступ групи збережено"+ }}}diff --git a/apps/web/messages/uk/members.json b/apps/web/messages/uk/members.jsonindex cdf4e56e..e367b88b 100644--- a/apps/web/messages/uk/members.json+++ b/apps/web/messages/uk/members.json@@ -104,5 +104,6 @@},"promoted": "Учасника призначено власником","roleUpdated": "Роль учасника оновлено",- "descriptionUpdated": "Опис учасника оновлено"+ "descriptionUpdated": "Опис учасника оновлено",+ "provisioned": "Керується SCIM"}diff --git a/apps/web/messages/uk/sections.json b/apps/web/messages/uk/sections.jsonindex 651e4812..602a8d4c 100644--- a/apps/web/messages/uk/sections.json+++ b/apps/web/messages/uk/sections.json@@ -46,6 +46,10 @@"auth-provider": {"label": "Провайдер входу","description": "Зовнішні акаунти, через які можна входити."+ },+ "scim": {+ "label": "SCIM",+ "description": "Дозвольте постачальнику ідентифікації створювати, оновлювати та вимикати облікові записи на цьому сервері й надавати доступ до проєктів через свої групи."}},"settings": {diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.jsonindex 48d1d88e..d6b77eb7 100644--- a/apps/web/messages/zh-CN/auth.json+++ b/apps/web/messages/zh-CN/auth.json@@ -37,7 +37,9 @@"withPasskey": "使用通行密钥登录","unconfirmedResent": "验证邮件已发送,请检查收件箱和垃圾邮件。","unconfirmedPrompt": "请检查垃圾邮件,或<resend>重新发送验证邮件</resend>。",- "unconfirmedNeedsEmail": "请用邮箱地址登录,以便重新发送验证邮件。"+ "unconfirmedNeedsEmail": "请用邮箱地址登录,以便重新发送验证邮件。",+ "withSso": "使用单点登录继续",+ "subtitleSso": "使用你所在组织的账号登录"},"register": {"title": "创建账户",@@ -53,7 +55,9 @@"confirmDescription": "验证链接已发送至 {email},打开链接以完成账户创建。","backToSignIn": "返回登录","closedTitle": "注册已关闭",- "closedDescription": "此实例不接受新账户注册。"+ "closedDescription": "此实例不接受新账户注册。",+ "withSso": "使用单点登录继续",+ "subtitleSso": "你的账号由组织的身份提供方创建"},"forgotPassword": {"title": "重置密码",@@ -85,6 +89,9 @@"emailNotFound": "Google 未返回此账户的邮箱地址。","tokenExpired": "此验证链接已过期。请在下方登录以获取新链接。","invalidToken": "此验证链接无效。请在下方登录以获取新链接。",- "userNotFound": "此验证链接对应的账户已不存在。"+ "userNotFound": "此验证链接对应的账户已不存在。",+ "ssoDisabled": "此实例未启用单点登录。",+ "passwordDisabled": "此实例仅通过身份提供方登录。",+ "accountDeactivated": "该账号已停用,请联系管理员恢复。"}}diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex bc2d46f8..49496adb 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -145,12 +145,15 @@}},"signIn": "登录选项",- "signInHint": "这些选项需要发送邮件,配置邮件服务商后才可启用。",+ "signInHint": "登录方式。需要发送邮件的选项在配置邮件服务前不可用。","needsProvider": "请先在“邮件服务商”中完成配置。","requireVerification": "要求验证邮箱","requireVerificationHint": "新账户必须验证邮箱后才能登录。","magicLink": "邮箱登录链接",- "magicLinkHint": "通过邮件发送免密码登录链接。"+ "magicLinkHint": "通过邮件发送免密码登录链接。",+ "emailPassword": "邮箱和密码",+ "emailPasswordHint": "提供登录和注册表单。关闭后只能通过登录提供方进入。",+ "needsSso": "请先在「集成」中配置登录提供方。"},"hotkeys": {"saved": "键盘快捷键已保存"@@ -212,6 +215,61 @@"clientSecret": "客户端密钥","redirectUri": "重定向 URI","redirectUriHint": "请在 Google Cloud 控制台的 OAuth 客户端中添加此地址。地址不完全匹配时,Google 会拒绝登录。",- "copyRedirectUri": "复制重定向 URI"+ "copyRedirectUri": "复制重定向 URI",+ "oidc": "OpenID Connect",+ "oidcConfigured": "没有账号的邮箱会自动创建账号;已有已确认账号的邮箱将登录该账号。",+ "oidcMissing": "请先填写发现地址、客户端 ID 和密钥。",+ "discoveryUrl": "发现地址",+ "discoveryUrlHint": "身份提供方的 .well-known/openid-configuration 地址,授权、令牌和用户信息端点都从中读取。",+ "oidcLabel": "按钮文字",+ "oidcLabelPlaceholder": "使用 Acme SSO 登录",+ "oidcLabelHint": "在登录按钮上标明你的提供方。留空则使用通用文字。",+ "scopes": "权限范围",+ "scopesHint": "以空格分隔。openid 为必需;profile 和 email 用于填充姓名和邮箱。",+ "oidcRedirectUriHint": "将此地址注册为身份提供方客户端的重定向 URI。不完全一致时提供方会拒绝登录。"+ },+ "scim": {+ "saved": "SCIM 设置已保存",+ "provisioning": "账号预配",+ "provisioningConfigured": "身份提供方会在此实例上创建、更新和停用账号。",+ "provisioningMissing": "请先生成令牌。",+ "token": "令牌",+ "noToken": "尚未生成令牌",+ "tokenHint": "身份提供方发送的持有者令牌。仅显示一次;生成新令牌会使旧令牌失效。",+ "generateToken": "生成令牌",+ "replaceToken": "更换令牌",+ "baseUrl": "SCIM 地址",+ "baseUrlHint": "在身份提供方中填入此地址。",+ "copyBaseUrl": "复制 SCIM 地址",+ "groups": "群组",+ "groupsHint": "身份提供方推送的群组。列表由其维护;每个群组授予什么在这里设置。",+ "groupsEmpty": "尚未推送任何群组。",+ "memberCount": "{count, plural, =0 {没有成员} other {# 位成员}}",+ "grantsNothing": "尚未授予任何权限",+ "editMappings": "编辑权限",+ "roleOwner": "所有者",+ "roleMember": "成员",+ "tokenDialog": {+ "title": "生成 SCIM 令牌",+ "description": "令牌仅显示一次,之后无法查看。正在使用的令牌将立即失效。",+ "submit": "生成",+ "submitPending": "正在生成…",+ "createdTitle": "你的 SCIM 令牌",+ "createdDescription": "现在把它复制到身份提供方。之后无法再次显示。",+ "copy": "复制令牌"+ },+ "mappings": {+ "title": "{group} 授予的权限",+ "description": "该群组的成员会加入这里列出的项目。移除项目会收回此群组授予的成员资格。",+ "empty": "该群组尚未授予任何权限。",+ "addProject": "添加项目…",+ "role": "角色",+ "roleOwner": "所有者",+ "roleMember": "成员",+ "projectRole": "项目角色",+ "defaultRole": "默认角色",+ "remove": "移除项目",+ "saved": "群组权限已保存"+ }}}diff --git a/apps/web/messages/zh-CN/members.json b/apps/web/messages/zh-CN/members.jsonindex 177a8f70..1d351ca9 100644--- a/apps/web/messages/zh-CN/members.json+++ b/apps/web/messages/zh-CN/members.json@@ -104,5 +104,6 @@},"promoted": "成员已晋升为所有者","roleUpdated": "成员角色已更新",- "descriptionUpdated": "成员描述已更新"+ "descriptionUpdated": "成员描述已更新",+ "provisioned": "由 SCIM 管理"}diff --git a/apps/web/messages/zh-CN/sections.json b/apps/web/messages/zh-CN/sections.jsonindex e1e8c954..e9b11363 100644--- a/apps/web/messages/zh-CN/sections.json+++ b/apps/web/messages/zh-CN/sections.json@@ -46,6 +46,10 @@"auth-provider": {"label": "身份验证提供商","description": "设置用户可以用于登录的外部账户。"+ },+ "scim": {+ "label": "SCIM",+ "description": "让身份提供方在此实例上创建、更新和停用账号,并通过其群组授予项目访问权限。"}},"settings": {diff --git a/apps/web/src/app/god/scim/page.tsx b/apps/web/src/app/god/scim/page.tsxnew file mode 100644index 00000000..a474845d--- /dev/null+++ b/apps/web/src/app/god/scim/page.tsx@@ -0,0 +1,5 @@+import GodScimPage from '@/features/god/GodScimPage';++export default function Page() {+ return <GodScimPage />;+}diff --git a/apps/web/src/components/common/page/CopyableValue.tsx b/apps/web/src/components/common/page/CopyableValue.tsxnew file mode 100644index 00000000..0f870dbb--- /dev/null+++ b/apps/web/src/components/common/page/CopyableValue.tsx@@ -0,0 +1,52 @@+'use client';++import { useState } from 'react';+import { Check, Copy } from 'lucide-react';+import { Button } from '@/components/ui/button';++// A value the reader copies out rather than fills in: a redirect URI to register+// with an identity provider, an endpoint to paste into one. Read-only on purpose, so+// it does not read as a form field.+export default function CopyableValue({+ title,+ value,+ hint,+ copyLabel,+}: {+ title: string;+ value: string;+ hint?: string;+ copyLabel: string;+}) {+ const [copied, setCopied] = useState(false);++ async function copy() {+ try {+ await navigator.clipboard.writeText(value);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ // Clipboard can be blocked (no permission / insecure origin); ignore.+ }+ }++ return (+ <div className="flex items-start justify-between gap-4 border-t border-border/60 pt-4">+ <div className="min-w-0 space-y-1">+ <div className="text-sm font-medium">{title}</div>+ <p className="truncate font-mono text-xs">{value}</p>+ {hint && <p className="text-xs text-muted-foreground">{hint}</p>}+ </div>+ <Button+ type="button"+ variant="outline"+ size="icon"+ className="shrink-0"+ title={copyLabel}+ onClick={() => void copy()}+ >+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}+ </Button>+ </div>+ );+}diff --git a/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx b/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsxindex e6e59476..b80dafa1 100644--- a/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx+++ b/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx@@ -1,6 +1,6 @@'use client';-import { KeyRound, Lock, Mail } from 'lucide-react';+import { KeyRound, Lock, Mail, ShieldCheck } from 'lucide-react';import { useTranslations } from 'next-intl';import { Button } from '@/components/ui/button';import { Field } from '@/components/ui/field';@@ -8,34 +8,48 @@ import GoogleIcon from '@/components/common/GoogleIcon';import { useAuthConfig } from '@/services/authConfig.service';// The sign-in methods that are not the email + password form: the magic link toggle,-// Google, and passkeys. Which of the first two show depends on the instance config.+// the instance's own OIDC provider, Google, and passkeys. Which of the first three+// show depends on the instance config.export default function AuthLoginAlternatives({signingInWithLink,pending,onToggleMethod,+ onOidc,onGoogle,onPasskey,}: {signingInWithLink: boolean;pending: boolean;onToggleMethod: () => void;+ onOidc: () => void;onGoogle: () => void;onPasskey: () => void;}) {const t = useTranslations('auth.login');const authConfig = useAuthConfig();+ // With the password form off there is no method to toggle away from, so the magic+ // link button would offer a screen the API refuses.+ const passwordEnabled = authConfig?.emailPassword !== false;// One Field for all of them so they sit together as a group — a Field each would// space them like separate form questions. Tighter than the default field gap:// they are one stack of choices, not separate answers.return (<Field className="gap-2">- {authConfig?.magicLink && (+ {authConfig?.magicLink && passwordEnabled && (<Button type="button" variant="outline" disabled={pending} onClick={onToggleMethod}>{signingInWithLink ? <Lock /> : <Mail />}{signingInWithLink ? t('withPassword') : t('withLink')}</Button>)}+ {authConfig?.oidc && (+ <Button type="button" variant="outline" onClick={onOidc} disabled={pending}>+ <ShieldCheck />+ {/* The operator named their own identity provider, so the label is shown+ as given rather than translated. */}+ {authConfig.oidcLabel || t('withSso')}+ </Button>+ )}{authConfig?.google && (<Button type="button" variant="outline" onClick={onGoogle} disabled={pending}><GoogleIcon className="size-4" />diff --git a/apps/web/src/features/auth/components/login/AuthLoginForm.tsx b/apps/web/src/features/auth/components/login/AuthLoginForm.tsxindex c7d9fb20..fa9755e4 100644--- a/apps/web/src/features/auth/components/login/AuthLoginForm.tsx+++ b/apps/web/src/features/auth/components/login/AuthLoginForm.tsx@@ -10,12 +10,11 @@ import {FieldDescription,FieldError,FieldGroup,- FieldLabel,FieldSeparator,} from '@/components/ui/field';-import { Input } from '@/components/ui/input';import AuthFormHeader from '../AuthFormHeader';import AuthLoginAlternatives from './AuthLoginAlternatives';+import AuthLoginPasswordFields from './AuthLoginPasswordFields';import AuthMessagePanel from '../AuthMessagePanel';import AuthUnconfirmedNotice from './AuthUnconfirmedNotice';import {@@ -25,6 +24,7 @@ import {sendMagicLink,signInWithPassword,signInWithGoogle,+ signInWithOidc,signInWithPasskey,} from '../../services/auth.service';import { useAuthAction } from '../../hooks/useAuthAction';@@ -53,6 +53,9 @@ export default function AuthLoginForm() {const [unconfirmed, setUnconfirmed] = useState(false);const { error, pending, setError, run } = useAuthAction();const authConfig = useAuthConfig();+ // An instance that runs entirely off its identity provider offers no form at all,+ // only the buttons below it.+ const passwordEnabled = authConfig?.emailPassword !== false;const params = useSearchParams();const justReset = params.get('reset') === '1';// `apiFailure` in lib/api.ts sends the browser here with ?expired=1 after the API@@ -124,6 +127,7 @@ export default function AuthLoginForm() {if (sessionExpired) return t('login.subtitleExpired');if (justVerified) return t('login.subtitleVerified');if (justReset) return t('login.subtitleReset');+ if (!passwordEnabled) return t('login.subtitleSso');if (signingInWithLink) return t('login.subtitleLink');return t('login.subtitlePassword');}@@ -138,46 +142,15 @@ export default function AuthLoginForm() {<FieldGroup><AuthFormHeader title={t('login.title')} description={subtitle()} />- <Field>- <FieldLabel htmlFor="identifier">- {signingInWithLink ? t('fields.email') : t('fields.identifier')}- </FieldLabel>- <Input- id="identifier"- type={signingInWithLink ? 'email' : 'text'}- placeholder={t('fields.emailPlaceholder')}- autoComplete="username"- required- value={identifier}- onChange={(e) => setIdentifier(e.target.value)}- disabled={pending}+ {passwordEnabled && (+ <AuthLoginPasswordFields+ signingInWithLink={signingInWithLink}+ identifier={identifier}+ password={password}+ pending={pending}+ onIdentifierChange={setIdentifier}+ onPasswordChange={setPassword}/>- </Field>-- {!signingInWithLink && (- <Field>- <div className="flex items-center justify-between">- <FieldLabel htmlFor="password">{t('fields.password')}</FieldLabel>- {authConfig?.emailEnabled && (- <Link- href="/forgot-password"- className="text-sm text-muted-foreground underline-offset-4 hover:underline"- >- {t('login.forgotPassword')}- </Link>- )}- </div>- <Input- id="password"- type="password"- autoComplete="current-password"- required- minLength={8}- value={password}- onChange={(e) => setPassword(e.target.value)}- disabled={pending}- />- </Field>)}{(error || redirectError) && <FieldError>{error ?? redirectError}</FieldError>}@@ -199,25 +172,31 @@ export default function AuthLoginForm() {/>)}- <Field>- <Button type="submit" disabled={pending}>- {submitLabel()}- </Button>- </Field>+ {passwordEnabled && (+ <>+ <Field>+ <Button type="submit" disabled={pending}>+ {submitLabel()}+ </Button>+ </Field>- <FieldSeparator>{t('login.or')}</FieldSeparator>+ <FieldSeparator>{t('login.or')}</FieldSeparator>+ </>+ )}<AuthLoginAlternativessigningInWithLink={signingInWithLink}pending={pending}onToggleMethod={() => switchTo(signingInWithLink ? 'password' : 'link')}+ onOidc={() => run(signInWithOidc, { redirect: false })}onGoogle={() => run(signInWithGoogle, { redirect: false })}onPasskey={() => run(signInWithPasskey, { fallback: t('errors.passkey') })}/>- {/* Only when anyone can register. An invite-only instance hands out links- directly, and a closed one has nowhere to send the visitor. */}- {authConfig?.registration === 'open' && (+ {/* Only when anyone can register with a password. An invite-only instance+ hands out links directly, a closed one has nowhere to send the visitor,+ and with single sign-on the identity provider makes the account. */}+ {authConfig?.registration === 'open' && passwordEnabled && (<FieldDescription className="text-center">{t('login.noAccount')}{' '}<Link href="/register" className="underline underline-offset-4">diff --git a/apps/web/src/features/auth/components/login/AuthLoginPasswordFields.tsx b/apps/web/src/features/auth/components/login/AuthLoginPasswordFields.tsxnew file mode 100644index 00000000..9a758fd7--- /dev/null+++ b/apps/web/src/features/auth/components/login/AuthLoginPasswordFields.tsx@@ -0,0 +1,75 @@+'use client';++import Link from 'next/link';+import { useTranslations } from 'next-intl';+import { Field, FieldLabel } from '@/components/ui/field';+import { Input } from '@/components/ui/input';+import { useAuthConfig } from '@/services/authConfig.service';++// The identifier and password pair. With a password the identifier is an address or+// a username; a sign-in link can only go to an address, so the password field drops+// away and the label changes with it.+export default function AuthLoginPasswordFields({+ signingInWithLink,+ identifier,+ password,+ pending,+ onIdentifierChange,+ onPasswordChange,+}: {+ signingInWithLink: boolean;+ identifier: string;+ password: string;+ pending: boolean;+ onIdentifierChange: (value: string) => void;+ onPasswordChange: (value: string) => void;+}) {+ const t = useTranslations('auth');+ const authConfig = useAuthConfig();++ return (+ <>+ <Field>+ <FieldLabel htmlFor="identifier">+ {signingInWithLink ? t('fields.email') : t('fields.identifier')}+ </FieldLabel>+ <Input+ id="identifier"+ type={signingInWithLink ? 'email' : 'text'}+ placeholder={t('fields.emailPlaceholder')}+ autoComplete="username"+ required+ value={identifier}+ onChange={(e) => onIdentifierChange(e.target.value)}+ disabled={pending}+ />+ </Field>++ {!signingInWithLink && (+ <Field>+ <div className="flex items-center justify-between">+ <FieldLabel htmlFor="password">{t('fields.password')}</FieldLabel>+ {authConfig?.emailEnabled && (+ <Link+ href="/forgot-password"+ className="text-sm text-muted-foreground underline-offset-4 hover:underline"+ >+ {t('login.forgotPassword')}+ </Link>+ )}+ </div>+ <Input+ id="password"+ type="password"+ autoComplete="current-password"+ required+ minLength={8}+ value={password}+ onChange={(e) => onPasswordChange(e.target.value)}+ disabled={pending}+ />+ </Field>+ )}+ </>+ );+}diff --git a/apps/web/src/features/auth/components/register/AuthRegisterForm.tsx b/apps/web/src/features/auth/components/register/AuthRegisterForm.tsxindex 1dce48cd..2ec28306 100644--- a/apps/web/src/features/auth/components/register/AuthRegisterForm.tsx+++ b/apps/web/src/features/auth/components/register/AuthRegisterForm.tsx@@ -9,14 +9,18 @@ import {FieldDescription,FieldError,FieldGroup,- FieldLabel,FieldSeparator,} from '@/components/ui/field';-import { Input } from '@/components/ui/input';-import GoogleIcon from '@/components/common/GoogleIcon';import AuthFormHeader from '../AuthFormHeader';import AuthMessagePanel from '../AuthMessagePanel';-import { signInWithGoogle, signOutUnverified, signUpWithEmail } from '../../services/auth.service';+import AuthRegisterPasswordFields from './AuthRegisterPasswordFields';+import AuthRegisterProviders from './AuthRegisterProviders';+import {+ signInWithGoogle,+ signInWithOidc,+ signOutUnverified,+ signUpWithEmail,+} from '../../services/auth.service';import { useAuthAction } from '../../hooks/useAuthAction';import { useAuthConfig } from '@/services/authConfig.service';@@ -30,6 +34,10 @@ export default function AuthRegisterForm() {const authConfig = useAuthConfig();const inviteOnly = authConfig?.registration === 'invite';const needsConfirmation = authConfig?.requireEmailVerification === true;+ // With the password form off, the identity provider is what creates the account,+ // so this screen keeps only the buttons that start that round trip.+ const passwordEnabled = authConfig?.emailPassword !== false;+ const hasProvider = authConfig?.oidc === true || authConfig?.google === true;function onSubmit(event: FormEvent) {event.preventDefault();@@ -87,84 +95,50 @@ export default function AuthRegisterForm() {);}+ function subtitle() {+ if (!passwordEnabled) return t('register.subtitleSso');+ if (inviteOnly) return t('register.subtitleInviteOnly');+ return t('register.subtitle');+ }+return (<form onSubmit={onSubmit} className="p-6 md:p-8"><FieldGroup>- <AuthFormHeader- title={t('register.title')}- description={inviteOnly ? t('register.subtitleInviteOnly') : t('register.subtitle')}- />-- <Field>- <FieldLabel htmlFor="email">{t('fields.email')}</FieldLabel>- <Input- id="email"- type="email"- placeholder={t('fields.emailPlaceholder')}- autoComplete="email"- required- value={email}- onChange={(e) => setEmail(e.target.value)}- disabled={pending}- />- </Field>-- <Field>- <FieldLabel htmlFor="password">{t('fields.password')}</FieldLabel>- <Input- id="password"- type="password"- autoComplete="new-password"- required- minLength={8}- value={password}- onChange={(e) => setPassword(e.target.value)}- disabled={pending}- />- <FieldDescription>{t('fields.passwordHint')}</FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor="confirm-password">{t('fields.confirmPassword')}</FieldLabel>- <Input- id="confirm-password"- type="password"- autoComplete="new-password"- required- minLength={8}- value={confirm}- onChange={(e) => setConfirm(e.target.value)}- disabled={pending}- />- </Field>+ <AuthFormHeader title={t('register.title')} description={subtitle()} />- {error && <FieldError>{error}</FieldError>}+ {passwordEnabled && (+ <>+ <AuthRegisterPasswordFields+ email={email}+ password={password}+ confirm={confirm}+ pending={pending}+ onEmailChange={setEmail}+ onPasswordChange={setPassword}+ onConfirmChange={setConfirm}+ />- <Field>- <Button type="submit" disabled={pending}>- {pending ? t('register.submitPending') : t('register.submit')}- </Button>- </Field>+ {error && <FieldError>{error}</FieldError>}- {/* Google covers sign-up too: an address without an account gets one, subject- to the same registration mode as the form above. */}- {authConfig?.google && (- <>- <FieldSeparator>{t('register.or')}</FieldSeparator><Field>- <Button- type="button"- variant="outline"- onClick={() => run(signInWithGoogle, { redirect: false })}- disabled={pending}- >- <GoogleIcon className="size-4" />- {t('register.withGoogle')}+ <Button type="submit" disabled={pending}>+ {pending ? t('register.submitPending') : t('register.submit')}</Button></Field></>)}+ {hasProvider && (+ <>+ {passwordEnabled && <FieldSeparator>{t('register.or')}</FieldSeparator>}+ <AuthRegisterProviders+ pending={pending}+ onOidc={() => run(signInWithOidc, { redirect: false })}+ onGoogle={() => run(signInWithGoogle, { redirect: false })}+ />+ </>+ )}+<FieldDescription className="text-center">{t('register.haveAccount')}{' '}<Link href="/login" className="underline underline-offset-4">diff --git a/apps/web/src/features/auth/components/register/AuthRegisterPasswordFields.tsx b/apps/web/src/features/auth/components/register/AuthRegisterPasswordFields.tsxnew file mode 100644index 00000000..8da88536--- /dev/null+++ b/apps/web/src/features/auth/components/register/AuthRegisterPasswordFields.tsx@@ -0,0 +1,74 @@+'use client';++import { useTranslations } from 'next-intl';+import { Field, FieldDescription, FieldLabel } from '@/components/ui/field';+import { Input } from '@/components/ui/input';++// The address and the two password fields. They are the whole email/password sign-up,+// so an instance that runs off its identity provider leaves them out entirely.+export default function AuthRegisterPasswordFields({+ email,+ password,+ confirm,+ pending,+ onEmailChange,+ onPasswordChange,+ onConfirmChange,+}: {+ email: string;+ password: string;+ confirm: string;+ pending: boolean;+ onEmailChange: (value: string) => void;+ onPasswordChange: (value: string) => void;+ onConfirmChange: (value: string) => void;+}) {+ const t = useTranslations('auth');++ return (+ <>+ <Field>+ <FieldLabel htmlFor="email">{t('fields.email')}</FieldLabel>+ <Input+ id="email"+ type="email"+ placeholder={t('fields.emailPlaceholder')}+ autoComplete="email"+ required+ value={email}+ onChange={(e) => onEmailChange(e.target.value)}+ disabled={pending}+ />+ </Field>++ <Field>+ <FieldLabel htmlFor="password">{t('fields.password')}</FieldLabel>+ <Input+ id="password"+ type="password"+ autoComplete="new-password"+ required+ minLength={8}+ value={password}+ onChange={(e) => onPasswordChange(e.target.value)}+ disabled={pending}+ />+ <FieldDescription>{t('fields.passwordHint')}</FieldDescription>+ </Field>++ <Field>+ <FieldLabel htmlFor="confirm-password">{t('fields.confirmPassword')}</FieldLabel>+ <Input+ id="confirm-password"+ type="password"+ autoComplete="new-password"+ required+ minLength={8}+ value={confirm}+ onChange={(e) => onConfirmChange(e.target.value)}+ disabled={pending}+ />+ </Field>+ </>+ );+}diff --git a/apps/web/src/features/auth/components/register/AuthRegisterProviders.tsx b/apps/web/src/features/auth/components/register/AuthRegisterProviders.tsxnew file mode 100644index 00000000..ec9c2cb8--- /dev/null+++ b/apps/web/src/features/auth/components/register/AuthRegisterProviders.tsx@@ -0,0 +1,42 @@+'use client';++import { ShieldCheck } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import { Field } from '@/components/ui/field';+import GoogleIcon from '@/components/common/GoogleIcon';+import { useAuthConfig } from '@/services/authConfig.service';++// Signing in through a provider covers sign-up too: an address without an account+// gets one, subject to the same registration mode as the form above.+export default function AuthRegisterProviders({+ pending,+ onOidc,+ onGoogle,+}: {+ pending: boolean;+ onOidc: () => void;+ onGoogle: () => void;+}) {+ const t = useTranslations('auth.register');+ const authConfig = useAuthConfig();++ return (+ <Field className="gap-2">+ {authConfig?.oidc && (+ <Button type="button" variant="outline" onClick={onOidc} disabled={pending}>+ <ShieldCheck />+ {/* The operator named their own identity provider, so the label is shown+ as given rather than translated. */}+ {authConfig.oidcLabel || t('withSso')}+ </Button>+ )}+ {authConfig?.google && (+ <Button type="button" variant="outline" onClick={onGoogle} disabled={pending}>+ <GoogleIcon className="size-4" />+ {t('withGoogle')}+ </Button>+ )}+ </Field>+ );+}diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.tsindex 00f3851b..d755511e 100644--- a/apps/web/src/features/auth/hooks/useRedirectError.ts+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts@@ -16,6 +16,9 @@ const MESSAGE_KEYS = {unable_to_link_account: 'linkRefused',account_not_linked: 'linkRefused',signup_disabled: 'signupDisabled',+ OIDC_DISABLED: 'ssoDisabled',+ PASSWORD_AUTH_DISABLED: 'passwordDisabled',+ ACCOUNT_DEACTIVATED: 'accountDeactivated',email_not_found: 'emailNotFound',// The confirmation link failed. better-auth redirects with these uppercase codes.TOKEN_EXPIRED: 'tokenExpired',diff --git a/apps/web/src/features/auth/services/auth.service.ts b/apps/web/src/features/auth/services/auth.service.tsindex 08849ec5..34654526 100644--- a/apps/web/src/features/auth/services/auth.service.ts+++ b/apps/web/src/features/auth/services/auth.service.ts@@ -126,6 +126,18 @@ export async function signInWithGoogle(): Promise<void> {if (result.error) throw new Error(result.error.message ?? '');}+// Starts the round trip through the instance's own OIDC provider. Same shape as the+// Google call above: it navigates away, and both callback URLs must be on the web+// origin. The provider id is fixed — the instance has exactly one.+export async function signInWithOidc(): Promise<void> {+ const result = await signIn.oauth2({+ providerId: 'oidc',+ callbackURL: appUrl('/'),+ errorCallbackURL: appUrl('/login'),+ });+ if (result.error) throw new Error(result.error.message ?? '');+}+export async function signInWithPasskey(): Promise<void> {const result = await signIn.passkey();if (result?.error) throw new Error(result.error.message ?? '');diff --git a/apps/web/src/features/god/GodAuthProviderPage.tsx b/apps/web/src/features/god/GodAuthProviderPage.tsxindex 7d8bc8ca..69e0575c 100644--- a/apps/web/src/features/god/GodAuthProviderPage.tsx+++ b/apps/web/src/features/god/GodAuthProviderPage.tsx@@ -1,51 +1,35 @@'use client';-import { toast } from 'sonner';-import { useTranslations } from 'next-intl';-import type { InstanceGoogleSettings } from '@/lib/api';-import { Button } from '@/components/ui/button';-import GodGoogleSettings from './components/auth-provider/GodGoogleSettings';+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import GodAuthProviderForm from './components/auth-provider/GodAuthProviderForm';import GodSectionPage from './components/GodSectionPage';-import GodSettingsGate from './components/GodSettingsGate';-import { useGodGoogleForm } from './hooks/useGodGoogleForm';-import { useInstanceGoogleSettingsQuery } from './services/god.service';+import {+ useInstanceGoogleSettingsQuery,+ useInstanceOidcSettingsQuery,+} from './services/god.service';+// The sign-in providers: Google and the instance's own OIDC server. Two settings+// rows rather than one, so this page loads both before the form can compare against+// them. GodSettingsGate takes a single query, which is why the gate is spelled out.export default function GodAuthProviderPage() {- const query = useInstanceGoogleSettingsQuery();+ const google = useInstanceGoogleSettingsQuery();+ const oidc = useInstanceOidcSettingsQuery();- return (- <GodSettingsGate slug="auth-provider" data={query.data}>- {(settings) => <AuthProviderForm settings={settings} />}- </GodSettingsGate>- );-}--// Google is the only provider so far. A second one becomes another section on this-// page with its own form hook.-function AuthProviderForm({ settings }: { settings: InstanceGoogleSettings }) {- const t = useTranslations('god.authProvider');- const tCommon = useTranslations('common');- const form = useGodGoogleForm(settings);-- async function save() {- try {- await form.save();- toast.success(t('saved'));- } catch {- // The failure already surfaced through the global mutation error toast.- }+ if (!google.data || !oidc.data) {+ return (+ <GodSectionPage slug="auth-provider">+ <ListSkeleton rows={5} rowClassName="h-12" />+ </GodSectionPage>+ );}+ // Keyed on the loaded state: a save replaces the cache entries, so the form+ // remounts with fresh initial values instead of a stale "dirty" comparison.return (- <GodSectionPage- slug="auth-provider"- actions={- <Button size="sm" onClick={() => void save()} disabled={!form.dirty || form.saving}>- {form.saving ? tCommon('saving') : tCommon('save')}- </Button>- }- >- <GodGoogleSettings form={form} />- </GodSectionPage>+ <GodAuthProviderForm+ key={`${JSON.stringify(google.data)}|${JSON.stringify(oidc.data)}`}+ googleSettings={google.data}+ oidcSettings={oidc.data}+ />);}diff --git a/apps/web/src/features/god/GodAuthenticationPage.tsx b/apps/web/src/features/god/GodAuthenticationPage.tsxindex 297d6c93..508631d8 100644--- a/apps/web/src/features/god/GodAuthenticationPage.tsx+++ b/apps/web/src/features/god/GodAuthenticationPage.tsx@@ -1,17 +1,7 @@'use client';-import { toast } from 'sonner';-import { useTranslations } from 'next-intl';-import type { InstanceAuthSettings } from '@/lib/api';-import SettingsCard from '@/components/common/page/SettingsCard';-import SettingsSection from '@/components/common/page/SettingsSection';-import SettingsRow from '@/components/common/page/SettingsRow';-import { Button } from '@/components/ui/button';-import { Switch } from '@/components/ui/switch';-import GodSectionPage from './components/GodSectionPage';+import GodAuthenticationForm from './components/authentication/GodAuthenticationForm';import GodSettingsGate from './components/GodSettingsGate';-import RegistrationModePicker from './components/authentication/RegistrationModePicker';-import { useGodPolicyForm } from './hooks/useGodPolicyForm';import { useInstanceAuthSettingsQuery } from './services/god.service';export default function GodAuthenticationPage() {@@ -19,80 +9,7 @@ export default function GodAuthenticationPage() {return (<GodSettingsGate slug="authentication" data={auth.data}>- {(settings) => <AuthenticationForm authSettings={settings} />}+ {(settings) => <GodAuthenticationForm authSettings={settings} />}</GodSettingsGate>);}--// The registration policy and the sign-in options. The provider credentials live-// under Integrations (Email provider, Auth provider).-function AuthenticationForm({ authSettings }: { authSettings: InstanceAuthSettings }) {- const t = useTranslations('god.authentication');- const tCommon = useTranslations('common');- const policy = useGodPolicyForm(authSettings);-- // The options that send mail need a configured provider; the API rejects them- // without one.- const needsProvider = !authSettings.hasEmailProvider;-- async function save() {- try {- await policy.save();- toast.success(t('saved'));- } catch {- // The failure already surfaced through the global mutation error toast.- }- }-- return (- <GodSectionPage- slug="authentication"- actions={- <Button size="sm" onClick={() => void save()} disabled={!policy.dirty || policy.saving}>- {policy.saving ? tCommon('saving') : tCommon('save')}- </Button>- }- >- <div className="space-y-10">- <SettingsSection title={t('registration')} description={t('registrationHint')}>- <SettingsCard className="divide-y divide-border/60">- <RegistrationModePicker- value={policy.registration}- disabled={policy.saving}- onChange={policy.setRegistration}- />- </SettingsCard>- </SettingsSection>-- <SettingsSection title={t('signIn')} description={t('signInHint')}>- <SettingsCard className="divide-y divide-border/60">- <SettingsRow- title={t('requireVerification')}- description={t('requireVerificationHint')}- note={needsProvider ? t('needsProvider') : undefined}- control={- <Switch- checked={policy.requireEmailVerification}- disabled={policy.saving || needsProvider}- onCheckedChange={policy.setRequireEmailVerification}- />- }- />- <SettingsRow- title={t('magicLink')}- description={t('magicLinkHint')}- note={needsProvider ? t('needsProvider') : undefined}- control={- <Switch- checked={policy.magicLink}- disabled={policy.saving || needsProvider}- onCheckedChange={policy.setMagicLink}- />- }- />- </SettingsCard>- </SettingsSection>- </div>- </GodSectionPage>- );-}diff --git a/apps/web/src/features/god/GodScimPage.tsx b/apps/web/src/features/god/GodScimPage.tsxnew file mode 100644index 00000000..ccb3e744--- /dev/null+++ b/apps/web/src/features/god/GodScimPage.tsx@@ -0,0 +1,23 @@+'use client';++import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import GodScimSettings from './components/scim/GodScimSettings';+import GodSectionPage from './components/GodSectionPage';+import { useInstanceScimSettingsQuery } from './services/god.service';++// SCIM provisioning: the token an identity provider authenticates with, and what the+// groups it pushes grant. Nothing here is a form the owner fills in and saves — the+// switch and the token act on their own — so there is no page-level Save.+export default function GodScimPage() {+ const settings = useInstanceScimSettingsQuery();++ return (+ <GodSectionPage slug="scim">+ {settings.data ? (+ <GodScimSettings settings={settings.data} />+ ) : (+ <ListSkeleton rows={5} rowClassName="h-12" />+ )}+ </GodSectionPage>+ );+}diff --git a/apps/web/src/features/god/components/auth-provider/GodAuthProviderForm.tsx b/apps/web/src/features/god/components/auth-provider/GodAuthProviderForm.tsxnew file mode 100644index 00000000..2449e1d5--- /dev/null+++ b/apps/web/src/features/god/components/auth-provider/GodAuthProviderForm.tsx@@ -0,0 +1,57 @@+'use client';++import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import type { InstanceGoogleSettings, InstanceOidcSettings } from '@/lib/api';+import { Button } from '@/components/ui/button';+import GodSectionPage from '../GodSectionPage';+import GodGoogleSettings from './GodGoogleSettings';+import GodOidcSettings from './GodOidcSettings';+import { useGodGoogleForm } from '../../hooks/useGodGoogleForm';+import { useGodOidcForm } from '../../hooks/useGodOidcForm';++// One section per provider, committed through the page's single Save. A third+// provider is another section with its own form hook.+export default function GodAuthProviderForm({+ googleSettings,+ oidcSettings,+}: {+ googleSettings: InstanceGoogleSettings;+ oidcSettings: InstanceOidcSettings;+}) {+ const t = useTranslations('god.authProvider');+ const tCommon = useTranslations('common');+ const google = useGodGoogleForm(googleSettings);+ const oidc = useGodOidcForm(oidcSettings);++ const dirty = google.dirty || oidc.dirty;+ const saving = google.saving || oidc.saving;++ // Only the sections that changed are written, so saving one provider does not+ // resubmit the other's credentials.+ async function save() {+ try {+ if (google.dirty) await google.save();+ if (oidc.dirty) await oidc.save();+ toast.success(t('saved'));+ } catch {+ // The failure already surfaced through the global mutation error toast.+ }+ }++ return (+ <GodSectionPage+ slug="auth-provider"+ actions={+ <Button size="sm" onClick={() => void save()} disabled={!dirty || saving}>+ {saving ? tCommon('saving') : tCommon('save')}+ </Button>+ }+ >+ <div className="space-y-10">+ <GodOidcSettings form={oidc} />+ <GodGoogleSettings form={google} />+ </div>+ </GodSectionPage>+ );+}diff --git a/apps/web/src/features/god/components/auth-provider/GodGoogleSettings.tsx b/apps/web/src/features/god/components/auth-provider/GodGoogleSettings.tsxindex 2090d18c..545abeaf 100644--- a/apps/web/src/features/god/components/auth-provider/GodGoogleSettings.tsx+++ b/apps/web/src/features/god/components/auth-provider/GodGoogleSettings.tsx@@ -1,11 +1,9 @@-import { useState } from 'react';-import { Check, Copy } from 'lucide-react';import { useTranslations } from 'next-intl';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';-import { Button } from '@/components/ui/button';import SettingsSection from '@/components/common/page/SettingsSection';import SettingsCard from '@/components/common/page/SettingsCard';+import CopyableValue from '@/components/common/page/CopyableValue';import EnabledSwitch from '@/components/common/inputs/EnabledSwitch';import SecretInput from '@/components/common/inputs/SecretInput';import type { GodGoogleForm } from '../../hooks/useGodGoogleForm';@@ -15,17 +13,6 @@ import type { GodGoogleForm } from '../../hooks/useGodGoogleForm';// registered on the OAuth client for the round trip to work at all.export default function GodGoogleSettings({ form }: { form: GodGoogleForm }) {const t = useTranslations('god.authProvider');- const [copied, setCopied] = useState(false);-- async function copyRedirectUri() {- try {- await navigator.clipboard.writeText(form.settings.redirectUri);- setCopied(true);- setTimeout(() => setCopied(false), 1500);- } catch {- // Clipboard can be blocked (no permission / insecure origin); ignore.- }- }return (<SettingsSection@@ -64,25 +51,12 @@ export default function GodGoogleSettings({ form }: { form: GodGoogleForm }) {</div></div>- {/* Read-only, so it reads as something to copy out rather than a field to fill- in. It is not part of the form and never saved. */}- <div className="flex items-start justify-between gap-4 border-t border-border/60 pt-4">- <div className="min-w-0 space-y-1">- <div className="text-sm font-medium">{t('redirectUri')}</div>- <p className="truncate font-mono text-xs">{form.settings.redirectUri}</p>- <p className="text-xs text-muted-foreground">{t('redirectUriHint')}</p>- </div>- <Button- type="button"- variant="outline"- size="icon"- className="shrink-0"- title={t('copyRedirectUri')}- onClick={() => void copyRedirectUri()}- >- {copied ? <Check className="size-4" /> : <Copy className="size-4" />}- </Button>- </div>+ <CopyableValue+ title={t('redirectUri')}+ value={form.settings.redirectUri}+ hint={t('redirectUriHint')}+ copyLabel={t('copyRedirectUri')}+ /></SettingsCard></SettingsSection>);diff --git a/apps/web/src/features/god/components/auth-provider/GodOidcSettings.tsx b/apps/web/src/features/god/components/auth-provider/GodOidcSettings.tsxnew file mode 100644index 00000000..3ead78d6--- /dev/null+++ b/apps/web/src/features/god/components/auth-provider/GodOidcSettings.tsx@@ -0,0 +1,95 @@+import { useTranslations } from 'next-intl';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import SettingsSection from '@/components/common/page/SettingsSection';+import SettingsCard from '@/components/common/page/SettingsCard';+import CopyableValue from '@/components/common/page/CopyableValue';+import EnabledSwitch from '@/components/common/inputs/EnabledSwitch';+import SecretInput from '@/components/common/inputs/SecretInput';+import type { GodOidcForm } from '../../hooks/useGodOidcForm';++// The instance's own OIDC provider: any server that publishes a well-known document+// (Keycloak, Authentik, KanIDM, GitLab, Forgejo). The authorization, token and+// userinfo endpoints are read from that document, so none of them is entered here.+export default function GodOidcSettings({ form }: { form: GodOidcForm }) {+ const t = useTranslations('god.authProvider');++ return (+ <SettingsSection+ title={t('oidc')}+ description={t(form.hasCredentials ? 'oidcConfigured' : 'oidcMissing')}+ action={+ <EnabledSwitch+ checked={form.enabled}+ onChange={form.setEnabled}+ disabled={form.saving || !form.hasCredentials}+ />+ }+ >+ <SettingsCard className="space-y-6 p-4">+ <div className="space-y-1.5">+ <Label htmlFor="oidc-discovery-url">{t('discoveryUrl')}</Label>+ <Input+ id="oidc-discovery-url"+ value={form.discoveryUrl}+ onChange={(e) => form.setDiscoveryUrl(e.target.value)}+ placeholder="https://idp.example.com/.well-known/openid-configuration"+ autoComplete="off"+ />+ <p className="text-xs text-muted-foreground">{t('discoveryUrlHint')}</p>+ </div>++ <div className="grid gap-4 sm:grid-cols-2">+ <div className="space-y-1.5">+ <Label htmlFor="oidc-client-id">{t('clientId')}</Label>+ <Input+ id="oidc-client-id"+ value={form.clientId}+ onChange={(e) => form.setClientId(e.target.value)}+ autoComplete="off"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="oidc-client-secret">{t('clientSecret')}</Label>+ <SecretInput+ id="oidc-client-secret"+ value={form.clientSecret}+ onChange={form.setClientSecret}+ hasStored={form.settings.hasClientSecret}+ editable+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="oidc-label">{t('oidcLabel')}</Label>+ <Input+ id="oidc-label"+ value={form.label}+ onChange={(e) => form.setLabel(e.target.value)}+ placeholder={t('oidcLabelPlaceholder')}+ maxLength={60}+ />+ <p className="text-xs text-muted-foreground">{t('oidcLabelHint')}</p>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="oidc-scopes">{t('scopes')}</Label>+ <Input+ id="oidc-scopes"+ value={form.scopes}+ onChange={(e) => form.setScopes(e.target.value)}+ placeholder="openid profile email"+ autoComplete="off"+ />+ <p className="text-xs text-muted-foreground">{t('scopesHint')}</p>+ </div>+ </div>++ <CopyableValue+ title={t('redirectUri')}+ value={form.settings.redirectUri}+ hint={t('oidcRedirectUriHint')}+ copyLabel={t('copyRedirectUri')}+ />+ </SettingsCard>+ </SettingsSection>+ );+}diff --git a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsxnew file mode 100644index 00000000..1fc5a20d--- /dev/null+++ b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx@@ -0,0 +1,105 @@+'use client';++import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import type { InstanceAuthSettings } from '@/lib/api';+import SettingsCard from '@/components/common/page/SettingsCard';+import SettingsSection from '@/components/common/page/SettingsSection';+import SettingsRow from '@/components/common/page/SettingsRow';+import { Button } from '@/components/ui/button';+import { Switch } from '@/components/ui/switch';+import GodSectionPage from '../GodSectionPage';+import RegistrationModePicker from './RegistrationModePicker';+import { useGodPolicyForm } from '../../hooks/useGodPolicyForm';++// The registration policy and the sign-in options. The provider credentials live+// under Integrations (Email provider, Auth provider).+export default function GodAuthenticationForm({+ authSettings,+}: {+ authSettings: InstanceAuthSettings;+}) {+ const t = useTranslations('god.authentication');+ const tCommon = useTranslations('common');+ const policy = useGodPolicyForm(authSettings);++ // The options that send mail need a configured provider; the API rejects them+ // without one.+ const needsProvider = !authSettings.hasEmailProvider;+ // Turning the password form off needs another way in, or nobody could sign in at+ // all. The API rejects it, and the switch says why before anyone tries.+ const needsSso = !authSettings.hasSsoProvider;++ async function save() {+ try {+ await policy.save();+ toast.success(t('saved'));+ } catch {+ // The failure already surfaced through the global mutation error toast.+ }+ }++ return (+ <GodSectionPage+ slug="authentication"+ actions={+ <Button size="sm" onClick={() => void save()} disabled={!policy.dirty || policy.saving}>+ {policy.saving ? tCommon('saving') : tCommon('save')}+ </Button>+ }+ >+ <div className="space-y-10">+ <SettingsSection title={t('registration')} description={t('registrationHint')}>+ <SettingsCard className="divide-y divide-border/60">+ <RegistrationModePicker+ value={policy.registration}+ disabled={policy.saving}+ onChange={policy.setRegistration}+ />+ </SettingsCard>+ </SettingsSection>++ <SettingsSection title={t('signIn')} description={t('signInHint')}>+ <SettingsCard className="divide-y divide-border/60">+ <SettingsRow+ title={t('emailPassword')}+ description={t('emailPasswordHint')}+ note={needsSso ? t('needsSso') : undefined}+ control={+ <Switch+ checked={policy.emailPassword}+ disabled={policy.saving || (needsSso && policy.emailPassword)}+ onCheckedChange={policy.setEmailPassword}+ />+ }+ />+ <SettingsRow+ title={t('requireVerification')}+ description={t('requireVerificationHint')}+ note={needsProvider ? t('needsProvider') : undefined}+ control={+ <Switch+ checked={policy.requireEmailVerification}+ disabled={policy.saving || needsProvider}+ onCheckedChange={policy.setRequireEmailVerification}+ />+ }+ />+ <SettingsRow+ title={t('magicLink')}+ description={t('magicLinkHint')}+ note={needsProvider ? t('needsProvider') : undefined}+ control={+ <Switch+ checked={policy.magicLink}+ disabled={policy.saving || needsProvider}+ onCheckedChange={policy.setMagicLink}+ />+ }+ />+ </SettingsCard>+ </SettingsSection>+ </div>+ </GodSectionPage>+ );+}diff --git a/apps/web/src/features/god/components/scim/GodScimGroupItem.tsx b/apps/web/src/features/god/components/scim/GodScimGroupItem.tsxnew file mode 100644index 00000000..6b481e1f--- /dev/null+++ b/apps/web/src/features/god/components/scim/GodScimGroupItem.tsx@@ -0,0 +1,50 @@+'use client';++import { UsersRound } from 'lucide-react';+import { useTranslations } from 'next-intl';+import type { InstanceScimGroup } from '@/lib/api';+import { Button } from '@/components/ui/button';+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from '@/components/ui/item';++export default function GodScimGroupItem({+ group,+ onEdit,+}: {+ group: InstanceScimGroup;+ onEdit: () => void;+}) {+ const t = useTranslations('god.scim');++ const grants = group.mappings+ .map((m) => `${m.projectKey} (${t(m.role === 'owner' ? 'roleOwner' : 'roleMember')})`)+ .join(', ');++ return (+ <Item+ size="sm"+ className="rounded-none border-0 border-b border-border px-1 last:border-b-0 hover:bg-accent/50"+ >+ <ItemMedia>+ <UsersRound className="size-4" />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{group.displayName}</ItemTitle>+ <ItemDescription>+ {t('memberCount', { count: group.memberCount })} · {grants || t('grantsNothing')}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Button variant="outline" size="sm" onClick={onEdit}>+ {t('editMappings')}+ </Button>+ </ItemActions>+ </Item>+ );+}diff --git a/apps/web/src/features/god/components/scim/GodScimGroupList.tsx b/apps/web/src/features/god/components/scim/GodScimGroupList.tsxnew file mode 100644index 00000000..b40defd2--- /dev/null+++ b/apps/web/src/features/god/components/scim/GodScimGroupList.tsx@@ -0,0 +1,40 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import type { InstanceScimGroup } from '@/lib/api';+import SettingsSection from '@/components/common/page/SettingsSection';+import { ItemGroup } from '@/components/ui/item';+import { Skeleton } from '@/components/ui/skeleton';+import GodScimGroupItem from './GodScimGroupItem';+import GodScimGroupMappingDialog from './GodScimGroupMappingDialog';+import { useInstanceScimGroupsQuery } from '../../services/god.service';++// The groups the identity provider has pushed. The list itself is read-only — it is+// the provider's — and what each group grants is set here.+export default function GodScimGroupList() {+ const t = useTranslations('god.scim');+ const groups = useInstanceScimGroupsQuery();+ const [editing, setEditing] = useState<InstanceScimGroup | null>(null);++ return (+ <SettingsSection title={t('groups')} description={t('groupsHint')}>+ {groups.isPending ? (+ <div className="space-y-2 py-3">+ <Skeleton className="h-10 w-full" />+ <Skeleton className="h-10 w-full" />+ </div>+ ) : groups.data && groups.data.length > 0 ? (+ <ItemGroup>+ {groups.data.map((group) => (+ <GodScimGroupItem key={group.id} group={group} onEdit={() => setEditing(group)} />+ ))}+ </ItemGroup>+ ) : (+ <p className="py-6 text-sm text-muted-foreground">{t('groupsEmpty')}</p>+ )}++ {editing && <GodScimGroupMappingDialog group={editing} onClose={() => setEditing(null)} />}+ </SettingsSection>+ );+}diff --git a/apps/web/src/features/god/components/scim/GodScimGroupMappingDialog.tsx b/apps/web/src/features/god/components/scim/GodScimGroupMappingDialog.tsxnew file mode 100644index 00000000..0c45be3a--- /dev/null+++ b/apps/web/src/features/god/components/scim/GodScimGroupMappingDialog.tsx@@ -0,0 +1,95 @@+'use client';++import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import type { InstanceScimGroup } from '@/lib/api';+import Modal from '@/components/common/overlay/Modal';+import { Button } from '@/components/ui/button';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import GodScimMappingRow from './GodScimMappingRow';+import { useGodScimMappingForm } from '../../hooks/useGodScimMappingForm';+import { useInstanceProjectsQuery } from '../../services/god.service';++// What one provisioned group grants. Saving reconciles the membership of every+// project the change touched, so a project taken off this list loses the members the+// group put there.+export default function GodScimGroupMappingDialog({+ group,+ onClose,+}: {+ group: InstanceScimGroup;+ onClose: () => void;+}) {+ const t = useTranslations('god.scim.mappings');+ const tCommon = useTranslations('common');+ const form = useGodScimMappingForm(group);+ // One page wide enough to hold every project of a self-hosted instance; the picker+ // is a dropdown, not a searchable list.+ const projects = useInstanceProjectsQuery({ search: '', limit: 200, offset: 0 });++ const available = (projects.data?.items ?? []).filter(+ (project) => !form.takenProjectIds.includes(project.id),+ );++ async function save() {+ try {+ await form.save();+ toast.success(t('saved'));+ onClose();+ } catch {+ // The failure already surfaced through the global mutation error toast.+ }+ }++ return (+ <Modal title={t('title', { group: group.displayName })} onClose={onClose}>+ <div className="space-y-4">+ <p className="text-sm text-muted-foreground">{t('description')}</p>++ {form.mappings.length === 0 ? (+ <p className="py-2 text-sm text-muted-foreground">{t('empty')}</p>+ ) : (+ <div className="space-y-3">+ {form.mappings.map((mapping, index) => (+ <GodScimMappingRow+ key={mapping.projectId}+ mapping={mapping}+ projects={projects.data?.items ?? []}+ onChange={(patch) => form.update(index, patch)}+ onRemove={() => form.remove(index)}+ />+ ))}+ </div>+ )}++ <Select value="" onValueChange={(value) => form.add(Number(value))}>+ <SelectTrigger className="w-full" disabled={available.length === 0}>+ <SelectValue placeholder={t('addProject')} />+ </SelectTrigger>+ <SelectContent>+ {available.map((project) => (+ <SelectItem key={project.id} value={String(project.id)}>+ {project.name} ({project.key})+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" onClick={onClose} disabled={form.saving}>+ {tCommon('cancel')}+ </Button>+ <Button type="button" onClick={() => void save()} disabled={!form.dirty || form.saving}>+ {form.saving ? tCommon('saving') : tCommon('save')}+ </Button>+ </div>+ </div>+ </Modal>+ );+}diff --git a/apps/web/src/features/god/components/scim/GodScimMappingRow.tsx b/apps/web/src/features/god/components/scim/GodScimMappingRow.tsxnew file mode 100644index 00000000..5e4f02be--- /dev/null+++ b/apps/web/src/features/god/components/scim/GodScimMappingRow.tsx@@ -0,0 +1,89 @@+'use client';++import { X } from 'lucide-react';+import { useTranslations } from 'next-intl';+import type { InstanceProject } from '@/lib/api';+import { Button } from '@/components/ui/button';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import type { ScimMappingDraft } from '../../hooks/useGodScimMappingForm';+import { useInstanceProjectQuery } from '../../services/god.service';++// One project a group grants membership in, and the role it grants there. The custom+// roles belong to that project, so they are read from its detail; owners bypass the+// permission matrix and carry none.+const DEFAULT_ROLE = 'default';++export default function GodScimMappingRow({+ mapping,+ projects,+ onChange,+ onRemove,+}: {+ mapping: ScimMappingDraft;+ projects: InstanceProject[];+ onChange: (patch: Partial<ScimMappingDraft>) => void;+ onRemove: () => void;+}) {+ const t = useTranslations('god.scim.mappings');+ const detail = useInstanceProjectQuery(mapping.projectId);+ const project = projects.find((p) => p.id === mapping.projectId);++ return (+ <div className="flex items-center gap-2">+ <div className="min-w-0 flex-1 truncate text-sm">+ {project ? `${project.name} (${project.key})` : mapping.projectId}+ </div>++ <Select+ value={mapping.role}+ onValueChange={(value) => onChange({ role: value as ScimMappingDraft['role'] })}+ >+ <SelectTrigger className="h-9 w-[130px]" aria-label={t('role')}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="member">{t('roleMember')}</SelectItem>+ <SelectItem value="owner">{t('roleOwner')}</SelectItem>+ </SelectContent>+ </Select>++ {mapping.role === 'member' && (+ <Select+ value={mapping.roleId === null ? DEFAULT_ROLE : String(mapping.roleId)}+ onValueChange={(value) =>+ onChange({ roleId: value === DEFAULT_ROLE ? null : Number(value) })+ }+ >+ <SelectTrigger className="h-9 w-[150px]" aria-label={t('projectRole')}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={DEFAULT_ROLE}>{t('defaultRole')}</SelectItem>+ {(detail.data?.roles ?? []).map((role) => (+ <SelectItem key={role.id} value={String(role.id)}>+ {role.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}++ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="shrink-0"+ title={t('remove')}+ onClick={onRemove}+ >+ <X className="size-4" />+ </Button>+ </div>+ );+}diff --git a/apps/web/src/features/god/components/scim/GodScimSettings.tsx b/apps/web/src/features/god/components/scim/GodScimSettings.tsxnew file mode 100644index 00000000..8258c2c3--- /dev/null+++ b/apps/web/src/features/god/components/scim/GodScimSettings.tsx@@ -0,0 +1,79 @@+'use client';++import { useState } from 'react';+import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import type { InstanceScimSettings } from '@/lib/api';+import SettingsSection from '@/components/common/page/SettingsSection';+import SettingsCard from '@/components/common/page/SettingsCard';+import CopyableValue from '@/components/common/page/CopyableValue';+import EnabledSwitch from '@/components/common/inputs/EnabledSwitch';+import { Button } from '@/components/ui/button';+import GodScimTokenDialog from './GodScimTokenDialog';+import GodScimGroupList from './GodScimGroupList';+import { useUpdateInstanceScimSettings } from '../../services/god.service';++// The endpoint and the token go into the identity provider; the groups it then+// pushes appear below, where the owner says what each one grants.+export default function GodScimSettings({ settings }: { settings: InstanceScimSettings }) {+ const t = useTranslations('god.scim');+ const update = useUpdateInstanceScimSettings();+ const [generating, setGenerating] = useState(false);++ async function toggle(enabled: boolean) {+ try {+ await update.mutateAsync({ enabled });+ toast.success(t('saved'));+ } catch {+ // The failure already surfaced through the global mutation error toast.+ }+ }++ return (+ <div className="space-y-10">+ <SettingsSection+ title={t('provisioning')}+ description={t(settings.hasToken ? 'provisioningConfigured' : 'provisioningMissing')}+ action={+ <EnabledSwitch+ checked={settings.enabled}+ onChange={(v) => void toggle(v)}+ disabled={update.isPending || !settings.hasToken}+ />+ }+ >+ <SettingsCard className="space-y-6 p-4">+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0 space-y-1">+ <div className="text-sm font-medium">{t('token')}</div>+ <p className="font-mono text-xs">+ {settings.hasToken ? `${settings.tokenPrefix}…` : t('noToken')}+ </p>+ <p className="text-xs text-muted-foreground">{t('tokenHint')}</p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="shrink-0"+ onClick={() => setGenerating(true)}+ >+ {settings.hasToken ? t('replaceToken') : t('generateToken')}+ </Button>+ </div>++ <CopyableValue+ title={t('baseUrl')}+ value={settings.baseUrl}+ hint={t('baseUrlHint')}+ copyLabel={t('copyBaseUrl')}+ />+ </SettingsCard>+ </SettingsSection>++ <GodScimGroupList />++ {generating && <GodScimTokenDialog onClose={() => setGenerating(false)} />}+ </div>+ );+}diff --git a/apps/web/src/features/god/components/scim/GodScimTokenDialog.tsx b/apps/web/src/features/god/components/scim/GodScimTokenDialog.tsxnew file mode 100644index 00000000..c30cb23b--- /dev/null+++ b/apps/web/src/features/god/components/scim/GodScimTokenDialog.tsx@@ -0,0 +1,81 @@+'use client';++import { useState } from 'react';+import { Check, Copy } from 'lucide-react';+import { useTranslations } from 'next-intl';+import Modal from '@/components/common/overlay/Modal';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { useCreateInstanceScimToken } from '../../services/god.service';++// The generated token is kept in this dialog only, never lifted into page state: it+// is shown once, right after it is generated, and cannot be retrieved later.+// Generating one replaces the previous token, which stops working immediately.+export default function GodScimTokenDialog({ onClose }: { onClose: () => void }) {+ const t = useTranslations('god.scim.tokenDialog');+ const tCommon = useTranslations('common');+ const create = useCreateInstanceScimToken();+ const [token, setToken] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);++ async function copy() {+ if (!token) return;+ try {+ await navigator.clipboard.writeText(token);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ // Clipboard can be blocked (no permission / insecure origin); ignore.+ }+ }++ if (token !== null) {+ return (+ <Modal title={t('createdTitle')} onClose={onClose}>+ <div className="space-y-4">+ <p className="text-sm text-muted-foreground">{t('createdDescription')}</p>+ <div className="flex items-center gap-2">+ <Input+ readOnly+ value={token}+ className="font-mono text-xs"+ onFocus={(e) => e.currentTarget.select()}+ />+ <Button+ variant="outline"+ size="icon"+ className="shrink-0"+ title={t('copy')}+ onClick={() => void copy()}+ >+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}+ </Button>+ </div>+ <div className="flex justify-end">+ <Button onClick={onClose}>{tCommon('done')}</Button>+ </div>+ </div>+ </Modal>+ );+ }++ return (+ <Modal title={t('title')} onClose={onClose}>+ <div className="space-y-4">+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" onClick={onClose} disabled={create.isPending}>+ {tCommon('cancel')}+ </Button>+ <Button+ type="button"+ disabled={create.isPending}+ onClick={() => create.mutate(undefined, { onSuccess: (data) => setToken(data.token) })}+ >+ {create.isPending ? t('submitPending') : t('submit')}+ </Button>+ </div>+ </div>+ </Modal>+ );+}diff --git a/apps/web/src/features/god/hooks/useGodOidcForm.ts b/apps/web/src/features/god/hooks/useGodOidcForm.tsnew file mode 100644index 00000000..2fe3e1df--- /dev/null+++ b/apps/web/src/features/god/hooks/useGodOidcForm.ts@@ -0,0 +1,91 @@+'use client';++import { useState } from 'react';+import type { InstanceOidcSettings } from '@/lib/api';+import { useUpdateInstanceOidcSettings } from '../services/god.service';++export interface GodOidcForm {+ enabled: boolean;+ setEnabled: (v: boolean) => void;+ label: string;+ setLabel: (v: string) => void;+ discoveryUrl: string;+ setDiscoveryUrl: (v: string) => void;+ clientId: string;+ setClientId: (v: string) => void;+ clientSecret: string;+ setClientSecret: (v: string) => void;+ // Space-separated in the field, an array over the wire.+ scopes: string;+ setScopes: (v: string) => void;+ // Discovery URL, client id and secret are all present, counting a stored secret+ // the user has not retyped. The switch stays off without them: the API refuses it,+ // and the sign-in button would otherwise only fail at the provider.+ hasCredentials: boolean;+ settings: InstanceOidcSettings;+ dirty: boolean;+ saving: boolean;+ save: () => Promise<void>;+}++function parseScopes(value: string): string[] {+ return value.split(/[\s,]+/).filter(Boolean);+}++// Form state for the generic OIDC provider. Same contract as the Google credentials:+// the secret starts blank and an empty field on save keeps the stored one.+export function useGodOidcForm(settings: InstanceOidcSettings): GodOidcForm {+ const update = useUpdateInstanceOidcSettings();++ const [enabled, setEnabled] = useState(settings.enabled);+ const [label, setLabel] = useState(settings.label);+ const [discoveryUrl, setDiscoveryUrl] = useState(settings.discoveryUrl);+ const [clientId, setClientId] = useState(settings.clientId);+ const [clientSecret, setClientSecret] = useState('');+ const [scopes, setScopes] = useState(settings.scopes.join(' '));++ const hasCredentials =+ discoveryUrl.trim().length > 0 &&+ clientId.trim().length > 0 &&+ (settings.hasClientSecret || clientSecret.length > 0);++ const dirty =+ enabled !== settings.enabled ||+ label !== settings.label ||+ discoveryUrl !== settings.discoveryUrl ||+ clientId !== settings.clientId ||+ clientSecret.length > 0 ||+ parseScopes(scopes).join(' ') !== settings.scopes.join(' ');++ async function save() {+ await update.mutateAsync({+ enabled: enabled && hasCredentials,+ label: label.trim(),+ discoveryUrl: discoveryUrl.trim(),+ clientId: clientId.trim(),+ scopes: parseScopes(scopes),+ ...(clientSecret.length > 0 ? { clientSecret } : {}),+ });+ setClientSecret('');+ }++ return {+ enabled,+ setEnabled,+ label,+ setLabel,+ discoveryUrl,+ setDiscoveryUrl,+ clientId,+ setClientId,+ clientSecret,+ setClientSecret,+ scopes,+ setScopes,+ hasCredentials,+ settings,+ dirty,+ saving: update.isPending,+ save,+ };+}diff --git a/apps/web/src/features/god/hooks/useGodPolicyForm.ts b/apps/web/src/features/god/hooks/useGodPolicyForm.tsindex ae315171..75921eb9 100644--- a/apps/web/src/features/god/hooks/useGodPolicyForm.ts+++ b/apps/web/src/features/god/hooks/useGodPolicyForm.ts@@ -11,14 +11,17 @@ export interface GodPolicyForm {setRequireEmailVerification: (v: boolean) => void;magicLink: boolean;setMagicLink: (v: boolean) => void;+ emailPassword: boolean;+ setEmailPassword: (v: boolean) => void;dirty: boolean;saving: boolean;save: () => Promise<void>;}-// Form state for the instance sign-in policy: who may register and the two options-// that need outbound mail. Held here rather than saved on change so the whole page,-// policy and provider credentials alike, commits through one Save.+// Form state for the instance sign-in policy: who may register, whether the+// email/password form is offered at all, and the two options that need outbound+// mail. Held here rather than saved on change so the whole page commits through one+// Save.export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm {const update = useUpdateInstanceAuthSettings();@@ -27,14 +30,16 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyFormsettings.requireEmailVerification,);const [magicLink, setMagicLink] = useState(settings.magicLink);+ const [emailPassword, setEmailPassword] = useState(settings.emailPassword);const dirty =registration !== settings.registration ||requireEmailVerification !== settings.requireEmailVerification ||- magicLink !== settings.magicLink;+ magicLink !== settings.magicLink ||+ emailPassword !== settings.emailPassword;async function save() {- await update.mutateAsync({ registration, requireEmailVerification, magicLink });+ await update.mutateAsync({ registration, requireEmailVerification, magicLink, emailPassword });}return {@@ -44,6 +49,8 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyFormsetRequireEmailVerification,magicLink,setMagicLink,+ emailPassword,+ setEmailPassword,dirty,saving: update.isPending,save,diff --git a/apps/web/src/features/god/hooks/useGodScimMappingForm.ts b/apps/web/src/features/god/hooks/useGodScimMappingForm.tsnew file mode 100644index 00000000..2d14311e--- /dev/null+++ b/apps/web/src/features/god/hooks/useGodScimMappingForm.ts@@ -0,0 +1,63 @@+'use client';++import { useState } from 'react';+import type { InstanceScimGroup } from '@/lib/api';+import { useSetInstanceScimGroupMappings } from '../services/god.service';++// One row of the form: a project the group grants membership in, and the role it+// grants there. `roleId` is null for an owner (owners bypass the permission matrix)+// or to fall back to the project's default role.+export interface ScimMappingDraft {+ projectId: number;+ role: 'owner' | 'member';+ roleId: number | null;+}++export interface GodScimMappingForm {+ mappings: ScimMappingDraft[];+ add: (projectId: number) => void;+ update: (index: number, patch: Partial<ScimMappingDraft>) => void;+ remove: (index: number) => void;+ // Projects already in the list, so the picker does not offer them twice — the API+ // allows at most one mapping per (group, project).+ takenProjectIds: number[];+ dirty: boolean;+ saving: boolean;+ save: () => Promise<void>;+}++function serialize(mappings: ScimMappingDraft[]): string {+ return JSON.stringify([...mappings].sort((a, b) => a.projectId - b.projectId));+}++export function useGodScimMappingForm(group: InstanceScimGroup): GodScimMappingForm {+ const update = useSetInstanceScimGroupMappings();+ const initial: ScimMappingDraft[] = group.mappings.map((m) => ({+ projectId: m.projectId,+ role: m.role,+ roleId: m.roleId,+ }));+ const [mappings, setMappings] = useState<ScimMappingDraft[]>(initial);++ return {+ mappings,+ add: (projectId) =>+ setMappings((current) => [...current, { projectId, role: 'member', roleId: null }]),+ update: (index, patch) =>+ setMappings((current) =>+ current.map((mapping, i) => {+ if (i !== index) return mapping;+ const next = { ...mapping, ...patch };+ // An owner carries no custom role, so switching to owner drops it.+ return next.role === 'owner' ? { ...next, roleId: null } : next;+ }),+ ),+ remove: (index) => setMappings((current) => current.filter((_, i) => i !== index)),+ takenProjectIds: mappings.map((m) => m.projectId),+ dirty: serialize(mappings) !== serialize(initial),+ saving: update.isPending,+ save: async () => {+ await update.mutateAsync({ groupId: group.id, mappings });+ },+ };+}diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.tsindex d59d21d9..9ec8811a 100644--- a/apps/web/src/features/god/services/god.service.ts+++ b/apps/web/src/features/god/services/god.service.ts@@ -6,6 +6,7 @@ import {type InstanceAuthSettingsPatch,type InstanceEmailSettingsPatch,type InstanceGoogleSettingsPatch,+ type InstanceOidcSettingsPatch,type InstanceTelegramSettingsPatch,type InstanceUserKind,type ProjectDefaults,@@ -17,6 +18,13 @@ import { qk } from '@/services/queryKeys';// cache entry directly — these are single-row settings, so there is nothing else to// invalidate. The invite list is a list, so its writes refetch it.+// Configuring a sign-in provider decides whether password sign-in may be turned off,+// and changes what the sign-in screen offers.+function invalidateSignInMethods(qc: ReturnType<typeof useQueryClient>): void {+ void qc.invalidateQueries({ queryKey: qk.instanceAuthSettings });+ void qc.invalidateQueries({ queryKey: qk.authConfig });+}+export function useInstanceAuthSettingsQuery() {return useQuery({queryKey: qk.instanceAuthSettings,@@ -62,7 +70,74 @@ export function useUpdateInstanceGoogleSettings() {const qc = useQueryClient();return useMutation({mutationFn: (patch: InstanceGoogleSettingsPatch) => api.updateInstanceGoogleSettings(patch),- onSuccess: (data) => qc.setQueryData(qk.instanceGoogleSettings, data),+ onSuccess: (data) => {+ qc.setQueryData(qk.instanceGoogleSettings, data);+ invalidateSignInMethods(qc);+ },+ });+}++// The instance's generic OIDC provider, the second way in besides Google.+export function useInstanceOidcSettingsQuery() {+ return useQuery({+ queryKey: qk.instanceOidcSettings,+ queryFn: () => api.getInstanceOidcSettings(),+ });+}++export function useUpdateInstanceOidcSettings() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (patch: InstanceOidcSettingsPatch) => api.updateInstanceOidcSettings(patch),+ onSuccess: (data) => {+ qc.setQueryData(qk.instanceOidcSettings, data);+ invalidateSignInMethods(qc);+ },+ });+}++// SCIM provisioning: the token an identity provider authenticates with, and what the+// groups it pushes grant.+export function useInstanceScimSettingsQuery() {+ return useQuery({+ queryKey: qk.instanceScimSettings,+ queryFn: () => api.getInstanceScimSettings(),+ });+}++export function useUpdateInstanceScimSettings() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (patch: { enabled: boolean }) => api.updateInstanceScimSettings(patch),+ onSuccess: (data) => qc.setQueryData(qk.instanceScimSettings, data),+ });+}++export function useCreateInstanceScimToken() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: () => api.createInstanceScimToken(),+ // The response is the token itself, not the settings, so the redacted view has+ // to be refetched for its new prefix.+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.instanceScimSettings }),+ });+}++export function useInstanceScimGroupsQuery() {+ return useQuery({+ queryKey: qk.instanceScimGroups,+ queryFn: () => api.listInstanceScimGroups(),+ });+}++export function useSetInstanceScimGroupMappings() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (input: {+ groupId: string;+ mappings: { projectId: number; role: 'owner' | 'member'; roleId: number | null }[];+ }) => api.setInstanceScimGroupMappings(input.groupId, input.mappings),+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.instanceScimGroups }),});}diff --git a/apps/web/src/features/members/components/members/MemberRow.tsx b/apps/web/src/features/members/components/members/MemberRow.tsxindex 6bf9f20f..aac201bd 100644--- a/apps/web/src/features/members/components/members/MemberRow.tsx+++ b/apps/web/src/features/members/components/members/MemberRow.tsx@@ -1,6 +1,6 @@'use client';-import { Bot, LogOut, UserMinus } from 'lucide-react';+import { Bot, LogOut, UserMinus, UsersRound } from 'lucide-react';import { useTranslations } from 'next-intl';import type { MemberRow as Member, Role } from '@/lib/api';import { formatDateTime } from '@/utils/dates';@@ -17,7 +17,9 @@ import MemberDescriptionDialog from './MemberDescriptionDialog';// One member's row in the members list: identity, role control, and the actions// (edit description, leave or revoke access). An owner can revoke anyone's-// access; a member can only leave. The last owner cannot be removed.+// access; a member can only leave. The last owner cannot be removed, and neither+// is a membership a provisioned group granted — that one changes in the identity+// provider, and the API refuses it here.export default function MemberRow({projectKey,member,@@ -36,9 +38,11 @@ export default function MemberRow({const { data: session } = useSession();const self = member.userId === session?.user.id;+ // Removing or re-roling a provisioned membership would be undone at the next sync.+ const provisioned = member.source === 'scim';// Agents join and leave with their AI Agent config, not from this list,// so they cannot be revoked or reassigned here.- const canRemove = !member.isAgent && (self || can('members_manage', 'delete'));+ const canRemove = !member.isAgent && !provisioned && (self || can('members_manage', 'delete'));const canEditDescription = !member.isAgent && (isOwner || self);const removeLabel = self ? t('leaveProject') : t('revokeAccess');const displayName = member.name || member.email;@@ -59,6 +63,12 @@ export default function MemberRow({{self && (<span className="text-xs font-normal text-muted-foreground">{t('you')}</span>)}+ {provisioned && (+ <Badge variant="outline" className="gap-1 px-1.5 py-0 text-[10px] font-normal">+ <UsersRound className="size-3" />+ {t('provisioned')}+ </Badge>+ )}</span><span className="flex items-center gap-1.5 truncate text-xs text-muted-foreground">{member.isAgent ? (@@ -88,7 +98,7 @@ export default function MemberRow({projectKey={projectKey}member={member}roles={roles}- canManage={isOwner && !self && !member.isAgent}+ canManage={isOwner && !self && !member.isAgent && !provisioned}isLastOwner={isLastOwner}/></TableCell>diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex c7174c98..716dfb18 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1110,13 +1110,18 @@ export interface InstanceAuthSettings {registration: RegistrationMode;requireEmailVerification: boolean;magicLink: boolean;+ emailPassword: boolean;hasEmailProvider: boolean;+ // Whether Google or the OIDC provider can run. Password sign-in may only be turned+ // off while one of them can.+ hasSsoProvider: boolean;}export interface InstanceAuthSettingsPatch {registration?: RegistrationMode;requireEmailVerification?: boolean;magicLink?: boolean;+ emailPassword?: boolean;}// The instance mail provider used for authentication email (password reset, address@@ -1169,6 +1174,57 @@ export interface InstanceGoogleSettingsPatch {clientSecret?: string;}+// The instance's generic OIDC/OAuth2 provider. The client secret is never returned,+// only a `hasClientSecret` flag. redirectUri is derived from the API origin and has+// to be registered with the identity provider.+export interface InstanceOidcSettings {+ enabled: boolean;+ label: string;+ discoveryUrl: string;+ clientId: string;+ hasClientSecret: boolean;+ scopes: string[];+ pkce: boolean;+ redirectUri: string;+}++export interface InstanceOidcSettingsPatch {+ enabled?: boolean;+ label?: string;+ discoveryUrl?: string;+ clientId?: string;+ clientSecret?: string;+ scopes?: string[];+ pkce?: boolean;+}++// SCIM provisioning. The token is never returned, only its prefix; a new one is+// generated with createInstanceScimToken and shown once.+export interface InstanceScimSettings {+ enabled: boolean;+ hasToken: boolean;+ tokenPrefix: string;+ baseUrl: string;+}++// What a provisioned group grants: membership in a project, at a role. The group and+// its members come from the identity provider; the mappings are set here.+export interface InstanceScimGroupMapping {+ projectId: number;+ projectKey: string;+ projectName: string;+ role: 'owner' | 'member';+ roleId: number | null;+}++export interface InstanceScimGroup {+ id: string;+ displayName: string;+ externalId: string | null;+ memberCount: number;+ mappings: InstanceScimGroupMapping[];+}+// The instance Telegram bot: the one bot users link their accounts through, and the// default sender for Telegram notifications. `botUsername` is resolved from Telegram// when the token is saved.@@ -1268,6 +1324,9 @@ export interface InstanceProjectMember {export interface InstanceProjectDetail extends InstanceProject {members: InstanceProjectMember[];+ // The custom roles a member of this project can be put on, for the SCIM group+ // mapping form.+ roles: { id: number; name: string; isDefault: boolean }[];}export interface InstanceProjectPage {@@ -1283,7 +1342,14 @@ export interface PublicAuthConfig {magicLink: boolean;requireEmailVerification: boolean;emailEnabled: boolean;+ // Whether the email/password form is offered at all. False only on an instance+ // that has a working single sign-on provider.+ emailPassword: boolean;google: boolean;+ oidc: boolean;+ // The sign-in button text the operator gave their identity provider. Empty when+ // OIDC is not offered, or when they left it blank.+ oidcLabel: string;}// The session member's own notification preferences for a project: which issue@@ -2392,6 +2458,9 @@ export interface MemberRow {// True when this member is an AI agent's bot user. Its role and access are managed// on the AI Agents screen, so this list does not let you reassign or revoke it.isAgent: boolean;+ // 'scim' when a provisioned group granted this membership. The sync rewrites such+ // a row on every run, so the role and remove actions are refused for it.+ source: 'invite' | 'scim';createdAt: string;}@@ -3528,6 +3597,33 @@ export const api = {method: 'PUT',body: JSON.stringify(patch),}),+ getInstanceOidcSettings: () => request<InstanceOidcSettings>('/god/oidc-settings'),+ updateInstanceOidcSettings: (patch: InstanceOidcSettingsPatch) =>+ request<InstanceOidcSettings>('/god/oidc-settings', {+ method: 'PUT',+ body: JSON.stringify(patch),+ }),++ getInstanceScimSettings: () => request<InstanceScimSettings>('/god/scim-settings'),+ updateInstanceScimSettings: (patch: { enabled: boolean }) =>+ request<InstanceScimSettings>('/god/scim-settings', {+ method: 'PUT',+ body: JSON.stringify(patch),+ }),+ // Returns the new token in the clear. It is shown once and cannot be read back.+ createInstanceScimToken: () =>+ request<{ token: string }>('/god/scim-settings/token', { method: 'POST' }),++ listInstanceScimGroups: () => request<InstanceScimGroup[]>('/god/scim-groups'),+ setInstanceScimGroupMappings: (+ groupId: string,+ mappings: { projectId: number; role: 'owner' | 'member'; roleId: number | null }[],+ ) =>+ request<InstanceScimGroup>(`/god/scim-groups/${groupId}/mappings`, {+ method: 'PUT',+ body: JSON.stringify({ mappings }),+ }),+// The instance user directory: one page of accounts, and one account with the// projects it can reach. Search, the kind filter and paging all run on the server.listInstanceUsers: (params: {diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.tsindex 89cfb833..fda122dc 100644--- a/apps/web/src/lib/auth-client.ts+++ b/apps/web/src/lib/auth-client.ts@@ -1,6 +1,6 @@import { createAuthClient } from 'better-auth/react';import { inferAdditionalFields } from 'better-auth/client/plugins';-import { magicLinkClient, usernameClient } from 'better-auth/client/plugins';+import { genericOAuthClient, magicLinkClient, usernameClient } from 'better-auth/client/plugins';import { passkeyClient } from '@better-auth/passkey/client';import { apiKeyClient } from '@better-auth/api-key/client';import { API_URL, markSigningOut } from '@/lib/api';@@ -25,6 +25,9 @@ export const authClient = createAuthClient({// instance setting the sign-in screen reads from /auth-config; the server// refuses to send when it is off.magicLinkClient(),+ // The instance's own OIDC provider: signIn.oauth2(). One provider, configured in+ // god mode; whether it is offered comes from /auth-config.+ genericOAuthClient(),// Usernames: signIn.username(). The sign-in screen sends its one field here when// what was typed is not an address, and the plugin types `username` on the// session user so the profile page can show it.diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex c5105e67..85ee4c7d 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -157,10 +157,13 @@ export const qk = {// start page). Read app-wide, not just on the preferences page.accountPreferences: ['accountPreferences'] as const,// Instance administration (god mode): the sign-in policy, the mail provider, the- // Google credentials and the Telegram bot. Not scoped to a project.+ // sign-in providers, SCIM provisioning and the Telegram bot. Not scoped to a project.instanceAuthSettings: ['instanceAuthSettings'] as const,instanceEmailSettings: ['instanceEmailSettings'] as const,instanceGoogleSettings: ['instanceGoogleSettings'] as const,+ instanceOidcSettings: ['instanceOidcSettings'] as const,+ instanceScimSettings: ['instanceScimSettings'] as const,+ instanceScimGroups: ['instanceScimGroups'] as const,instanceTelegramSettings: ['instanceTelegramSettings'] as const,instanceProjectDefaults: ['instanceProjectDefaults'] as const,instanceStorageSettings: ['instanceStorageSettings'] as const,diff --git a/apps/web/src/utils/godSections.ts b/apps/web/src/utils/godSections.tsindex 0215c8f1..3f6bf6e0 100644--- a/apps/web/src/utils/godSections.ts+++ b/apps/web/src/utils/godSections.ts@@ -7,6 +7,7 @@ import {Send,SlidersHorizontal,Users,+ UsersRound,type LucideIcon,} from 'lucide-react';@@ -77,6 +78,12 @@ export const GOD_SECTIONS: GodSection[] = [icon: KeyRound,integration: true,},+ {+ slug: 'scim',+ group: 'instance',+ icon: UsersRound,+ integration: true,+ },];// The content column a god page occupies. Shared with the skeletons that stand indiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 0b8bb42f..c43ef725 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -22,6 +22,57 @@ becomes the instance admin.`.env.example` documents every variable, including the optional ones: legal document URLs,passkey and cookie settings, telemetry opt-out, and worker tuning.+## Single sign-on++Any provider that publishes an OpenID Connect discovery document works: Keycloak,+Authentik, KanIDM, GitLab, Forgejo, Okta, Entra. The credentials are stored in the+database, not in env, so nothing here needs a restart.++1. In god mode, open **Integrations → Auth provider** and copy the redirect URI it shows+ (`<API_URL>/api/auth/oauth2/callback/oidc`).+2. Create a confidential client at your provider with that redirect URI.+3. Paste the discovery URL (`.../.well-known/openid-configuration`), the client ID and the+ client secret back into the page, name the sign-in button, and turn the provider on.++A first sign-in creates the account, subject to the registration mode under+**Authentication**: `open` creates it, `invite only` needs a pending project invite, and+`closed` refuses it — use SCIM below to provision people on a closed instance.++Once a provider works, **Authentication → Email and password** can be turned off. That+hides and refuses the sign-in and sign-up forms, password reset and sign-in links; the+provider becomes the only way in. Passkeys keep working, since one can only be added to an+account that already exists. The switch stays disabled until a provider is configured, so+an instance cannot be left with no way in.++## Provisioning with SCIM++An identity provider can create, update and deactivate accounts over SCIM 2.0, and grant+project access through its groups.++1. In god mode, open **Integrations → SCIM**, generate a token and copy it — it is shown+ once — then turn provisioning on.+2. Point your provider's SCIM application at the endpoint the page shows+ (`<API_URL>/scim/v2`), authenticating with `Authorization: Bearer <token>`.+3. Push users, and groups if you use them.++Deactivating someone at the provider (`active: false`) ends their sessions and refuses+their API keys; reactivating restores them with their projects intact. The instance owner's+own account is outside SCIM's reach — a provisioning run can neither change nor deactivate+it, and a repeated create for an address it already provisioned answers "already exists"+rather than overwriting the link back to the provider.++A pushed group grants nothing until you say what it is for: on the same page, open a group+and add the projects its members should join, and the role they join on. Removing a project+from that list takes away the memberships the group gave it. A membership someone got+through an invite is never touched by a sync, and one the sync created cannot be edited from+the project's members page — it changes at the identity provider.++A group also appears here without any explicit push, in two cases: a SCIM user whose+payload embeds a `groups` attribute instead of being assigned through a separate group+push, and anyone who signs in through OIDC while their identity provider puts a `groups`+claim on the token — set that up as a claim mapping on the OIDC client if the provider+supports one. Either way, map the group the same way once it shows up.+## Updating```bashdiff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex ad3c0ff5..4e861f20 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -6,7 +6,8 @@ The **server-side** better-auth instance. Consumed by `apps/api`. See root `AGEN(`provider: "pg"`) over `@repo/db`. Email+password enabled (no email confirmation:`requireEmailVerification: false`, `autoSignIn: true`), plus the WebAuthn passkeyplugin (`@better-auth/passkey`).-- Exports `auth`, `USER_ROLES` / `UserRole`, plus `Auth` / `Session` types.+- Exports `auth`, `USER_ROLES` / `UserRole`, `generateUsername` (the SCIM module derives a+ handle with the same rule), plus `Auth` / `Session` types.## User role@@ -16,13 +17,16 @@ hook sets it: the first user to register gets `"god"`, everyone after gets `"use## Instance settings (`src/instance.ts`)-Registration mode, the email-dependent auth options, and the mail provider are stored-in the database, not in env, so god mode can change them without a restart. Read them+Registration mode, which sign-in methods are offered, the mail provider, the OAuth+credentials and the SCIM token are stored in the database, not in env, so god mode can+change them without a restart. Read themthrough this module — never inline a query on `app_setting` / `app_secret` elsewhere.-- `app_setting` key `auth` → `{ registration, requireEmailVerification, magicLink }`.-- `app_secret` key `auth.email` → the mail provider, encrypted with `@repo/crypto`,- with a `redacted` mirror for the settings UI. Secrets never leave the server.+- `app_setting` key `auth` → `{ registration, requireEmailVerification, magicLink,+ emailPassword }`.+- `app_secret` keys `auth.email`, `auth.google`, `auth.oidc` and `auth.scim` → the mail+ provider, the two OAuth providers and the SCIM token, encrypted with `@repo/crypto`,+ each with a `redacted` mirror for the settings UI. Secrets never leave the server."Invite only" means the address has a pending `project_invite` (`hasPendingInvite`).Invites are created and revoked inside a project, so there is no instance-level invite@@ -76,6 +80,52 @@ what was typed contains an "@". `/sign-in/username` checks only the static`emailAndPassword.requireEmailVerification`, which is `false` here, so the instanceverification gate in `hooks.before` covers that path as well as `/sign-in/email`.+## Generic OIDC++`genericOAuth({ config: [oidcOptions] })` adds one OIDC/OAuth2 provider, discovered from+the well-known document the operator points it at (`app_secret` key `auth.oidc`). It adds+`/sign-in/oauth2` and `/oauth2/callback/:providerId`, and reuses the `account` table, so it+adds none of its own.++`providerId` is the constant `OIDC_PROVIDER_ID` (`"oidc"`): it is what the `account` rows+store, and better-auth materialises the provider list once at startup, so the config array+can neither grow nor be re-keyed afterwards. That is also why there is exactly one+provider. `oidcOptions` is refreshed per request by `refreshOidcOptions()` in+`hooks.before` — the same by-reference rule as `googleOptions`: assign its fields, never+replace the object.++`/oauth2/link` is in `disabledPaths`. No screen offers linking an OIDC identity to the+signed-in account, and better-auth already attaches a sign-in to a matching confirmed+address on its own.++## Turning password authentication off++`AuthSettings.emailPassword` (default `true`). When it is off, the first branch of+`hooks.before` refuses every path in `PASSWORD_PATHS` — the two sign-in endpoints, sign-up,+password reset, and both halves of the magic link, so a link issued before the switch was+flipped cannot still be redeemed. Passkeys stay available: a passkey is only ever added to+an account that already exists.++Like every other instance setting this is read per request, so it cannot be+`emailAndPassword.enabled: false` (evaluated at startup) and cannot live in `disabledPaths`+(a static array). The api refuses to turn it off while neither Google nor OIDC is usable,+which is what stops an instance being left with no way in.++## Deactivation and SCIM++Two more `additionalFields` on the user table, both written only over SCIM and both+nullable, so every check is `active !== false` rather than `!active`:++- `active` — the deprovisioning flag. `databaseHooks.session.create.before` refuses to open+ a session for an inactive account, which covers every sign-in method at once; `apps/api`+ refuses the sessions and API keys that were already open.+- `scimExternalId` — the identity provider's own id, used to correlate an account it did+ not choose the id for.++`getScimSettings` / `rotateScimToken` / `verifyScimToken` hold the bearer token the SCIM+endpoints in `apps/api` authenticate with. The token is returned in the clear exactly once,+when it is generated; only its prefix is kept in the redacted mirror.+## Passkey`passkey({ rpID, rpName, origin })` adds WebAuthn. `rpID` is the frontend hostname thediff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex b02c8166..1574a693 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -6,13 +6,16 @@ import { createAuthMiddleware, APIError } from 'better-auth/api';import { drizzleAdapter } from 'better-auth/adapters/drizzle';import { passkey } from '@better-auth/passkey';import { apiKey } from '@better-auth/api-key';-import { openAPI, magicLink, username } from 'better-auth/plugins';+import { openAPI, magicLink, username, genericOAuth } from 'better-auth/plugins';+import type { GenericOAuthConfig } from 'better-auth/plugins/generic-oauth';import * as schema from '@repo/db/schema';import {getAuthSettings,hasPendingInvite,getGoogleConfig,isGoogleUsable,+ getOidcConfig,+ isOidcUsable,hasConfiguredEmailProvider,} from './instance';import { sendAuthEmail } from './mail';@@ -96,6 +99,60 @@ async function refreshGoogleOptions(): Promise<boolean> {}}+// The generic OIDC provider. One per instance, so its id is a constant: it is what+// the `account` rows store, and better-auth materialises the provider list once at+// startup — the config array can neither grow nor be re-keyed afterwards. As with+// Google, the plugin keeps this object by reference and reads its fields on every+// call, so refreshing it per request is what lets the owner change the credentials+// without a restart. Assign the fields, never replace the object.+export const OIDC_PROVIDER_ID = 'oidc';++const oidcOptions: GenericOAuthConfig = {+ providerId: OIDC_PROVIDER_ID,+ clientId: '',+ clientSecret: '',+ discoveryUrl: '',+ scopes: [],+ pkce: true,+};++// The exact value that has to be registered as a redirect URI with the identity+// provider. god mode shows it so the owner can copy it instead of assembling it.+export const OIDC_REDIRECT_URI = `${baseURL}/api/auth/oauth2/callback/${OIDC_PROVIDER_ID}`;++// Loads the stored credentials into that object and reports whether OIDC sign-in can+// run. A read failure disables the provider rather than failing the request with a+// stale secret.+async function refreshOidcOptions(): Promise<boolean> {+ try {+ const config = await getOidcConfig();+ oidcOptions.clientId = config.clientId;+ oidcOptions.clientSecret = config.clientSecret;+ oidcOptions.discoveryUrl = config.discoveryUrl;+ oidcOptions.scopes = config.scopes;+ oidcOptions.pkce = config.pkce;+ return isOidcUsable(config);+ } catch (error) {+ console.error('[auth] could not read the OIDC credentials:', error);+ return false;+ }+}++// The endpoints of the email/password form, including the two the magic link uses.+// Turning password authentication off refuses all of them, so a link issued before+// the switch was flipped cannot still be redeemed. Passkey sign-in is not here: a+// passkey is only ever added to an account that already exists, so it cannot be used+// to get around single sign-on.+const PASSWORD_PATHS = new Set([+ '/sign-up/email',+ '/sign-in/email',+ '/sign-in/username',+ '/forget-password',+ '/reset-password',+ '/sign-in/magic-link',+ '/magic-link/verify',+]);+// The registration gate: who may create an account. Both sign-up paths run it — the// email form checks it up front (below), and the user create hook catches every other// path, which is what stops a Google sign-up on a closed or invite-only instance.@@ -161,7 +218,7 @@ async function isAgentHandle(handle: string): Promise<boolean> {// local part, with everything the plugin's validator rejects removed — and the owner// changes it later in the profile. A name already in use gets a random suffix, and// the check repeats until the name is free.-async function generateUsername(email: string): Promise<string> {+export async function generateUsername(email: string): Promise<string> {const stem =.split('@')[0]@@ -255,6 +312,21 @@ export const auth = betterAuth({defaultValue: 'user',input: false,},+ // Deprovisioning flag, written only over SCIM. Nullable, so every check is+ // `active !== false` — an account that predates the column has no value.+ active: {+ type: 'boolean',+ required: false,+ defaultValue: true,+ input: false,+ },+ // The identity provider's own id for this account, used by SCIM to correlate+ // a user it did not create the id for.+ scimExternalId: {+ type: 'string',+ required: false,+ input: false,+ },},},@@ -262,11 +334,36 @@ export const auth = betterAuth({// per request, so god mode can change them without a restart.hooks: {before: createAuthMiddleware(async (ctx) => {+ // Read here so the two sign-in endpoints, which also go through the+ // verification gate below, make one query instead of two.+ const passwordSettings = PASSWORD_PATHS.has(ctx.path) ? await getAuthSettings() : null;+ // The api will not let the switch be turned off while no OAuth provider is+ // configured, so this cannot leave an instance with no way in.+ if (passwordSettings && !passwordSettings.emailPassword) {+ throw new APIError('FORBIDDEN', {+ code: 'PASSWORD_AUTH_DISABLED',+ message: 'Password sign-in is disabled on this instance',+ });+ }+if (ctx.path === '/sign-up/email') {await assertRegistrationAllowed((ctx.body as { email?: string } | undefined)?.email ?? '');return;}+ // Both halves of the OIDC round trip. The refusal carries a code because the+ // callback turns it into the ?error= it redirects with; without one the+ // callback fails the request instead.+ if (ctx.path === '/sign-in/oauth2' || ctx.path.startsWith('/oauth2/callback/')) {+ if (!(await refreshOidcOptions())) {+ throw new APIError('FORBIDDEN', {+ code: 'OIDC_DISABLED',+ message: 'Single sign-on is disabled on this instance',+ });+ }+ return;+ }+// Both halves of the Google round trip: starting it and coming back from it.// This is where the stored credentials are loaded into the provider's options,// so a request never runs on a value the owner has since changed.@@ -283,7 +380,7 @@ export const auth = betterAuth({// /sign-in/email or /sign-in/username depending on what was typed, and the// instance gate has to apply either way.if (ctx.path === '/sign-in/email' || ctx.path === '/sign-in/username') {- const settings = await getAuthSettings();+ const settings = passwordSettings ?? (await getAuthSettings());if (!settings.requireEmailVerification) return;// Holding an account back is only fair while a confirmation link can still// be sent: with the mail provider gone, an unconfirmed account has no way@@ -350,6 +447,25 @@ export const auth = betterAuth({},},},+ session: {+ create: {+ // Every sign-in method ends here, so one check covers password, magic link,+ // passkey, Google and OIDC. Deactivation arrives over SCIM; apps/api refuses+ // the sessions that are already open.+ before: async (session) => {+ const rows = await db+ .select({ active: schema.user.active })+ .from(schema.user)+ .where(eq(schema.user.id, session.userId));+ if (rows[0]?.active === false) {+ throw new APIError('FORBIDDEN', {+ code: 'ACCOUNT_DEACTIVATED',+ message: 'This account is deactivated',+ });+ }+ },+ },+ },},plugins: [@@ -400,6 +516,12 @@ export const auth = betterAuth({});},}),+ // A single generic OIDC/OAuth2 provider, configured by the instance owner and+ // discovered from its well-known document. Adds /sign-in/oauth2 and+ // /oauth2/callback/:providerId; it reuses the `account` table, so it adds none.+ // The config array is materialised at startup — see oidcOptions above for why+ // there is exactly one entry and why its fields are mutated rather than replaced.+ genericOAuth({ config: [oidcOptions] }),// Usernames: a second identifier next to the address, unique across the// instance. Adds `username` / `display_username` to the user table and the// /sign-in/username endpoint the sign-in screen uses when the visitor typed a@@ -420,11 +542,13 @@ export const auth = betterAuth({// The frontend runs on a different origin (Next :3001) — allow its requests.trustedOrigins,- // The username plugin's /is-username-available answers for anyone, and a username- // is derived from the address, so the endpoint would tell a stranger which- // addresses are registered. Nothing in the app calls it — the profile form learns- // a name is taken from updateUser's error.- disabledPaths: ['/is-username-available'],+ // /is-username-available answers for anyone, and a username is derived from the+ // address, so it would tell a stranger which addresses are registered. Nothing in+ // the app calls it — the profile form learns a name is taken from updateUser's+ // error. /oauth2/link attaches an OIDC identity to the signed-in account, which no+ // screen offers: better-auth already links a sign-in to a matching confirmed+ // address on its own.+ disabledPaths: ['/is-username-available', '/oauth2/link'],advanced: {// Share the session cookie across subdomains when COOKIE_DOMAIN is the parent@@ -468,6 +592,16 @@ export {setGoogleSettings,getGoogleConfig,hasConfiguredGoogle,+ getOidcSettings,+ setOidcSettings,+ getOidcConfig,+ getOidcLabel,+ hasConfiguredOidc,+ getScimSettings,+ setScimSettings,+ rotateScimToken,+ isScimEnabled,+ verifyScimToken,} from './instance';export type {RegistrationMode,@@ -478,4 +612,8 @@ export type {InstanceGoogleDto,InstanceGooglePatch,InstanceGoogleConfig,+ InstanceOidcDto,+ InstanceOidcPatch,+ InstanceOidcConfig,+ InstanceScimDto,} from './instance';diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.tsindex bf5c9de6..a51d1768 100644--- a/packages/auth/src/instance.ts+++ b/packages/auth/src/instance.ts@@ -1,3 +1,4 @@+import { randomBytes, timingSafeEqual } from 'node:crypto';import { db, appSecret, projectInvite, getSetting, setSetting } from '@repo/db';import { and, eq, sql } from 'drizzle-orm';import { encryptSecret, decryptSecret } from '@repo/crypto';@@ -9,18 +10,22 @@ import {} from '@repo/mailer';// Instance-wide authentication settings: who may register, whether email has to be-// confirmed, the mail provider used for authentication email, and the Google OAuth-// credentials. Read by the better-auth instance in ./index.ts (the registration gate,-// the mail senders, the Google provider) and written by god mode in the api, so it-// lives here rather than in the api.+// confirmed, which sign-in methods are offered, the mail provider used for+// authentication email, and the credentials of the OAuth providers. Read by the+// better-auth instance in ./index.ts (the registration gate, the mail senders, the+// Google and OIDC providers) and written by god mode in the api, so it lives here+// rather than in the api.//// Non-secret settings are one jsonb blob in app_setting under the 'auth' key; the-// credentials are encrypted in app_secret under 'auth.email' and 'auth.google', each-// with a `redacted` mirror the settings UI can read without decrypting.+// credentials are encrypted in app_secret under 'auth.email', 'auth.google',+// 'auth.oidc' and 'auth.scim', each with a `redacted` mirror the settings UI can read+// without decrypting.const AUTH_SETTING_KEY = 'auth';const EMAIL_SECRET_KEY = 'auth.email';const GOOGLE_SECRET_KEY = 'auth.google';+const OIDC_SECRET_KEY = 'auth.oidc';+const SCIM_SECRET_KEY = 'auth.scim';// Who may create an account.// open — anyone can sign up@@ -36,10 +41,19 @@ export interface AuthSettings {requireEmailVerification: boolean;// Offer sign-in by emailed link alongside the password.magicLink: boolean;+ // Offer the email/password form at all. Turning it off leaves single sign-on (and+ // passkeys, which are added to an account that already exists) as the way in, so+ // the api refuses to turn it off while no OAuth provider is configured.+ emailPassword: boolean;}function defaultAuthSettings(): AuthSettings {- return { registration: 'open', requireEmailVerification: false, magicLink: false };+ return {+ registration: 'open',+ requireEmailVerification: false,+ magicLink: false,+ emailPassword: true,+ };}export async function getAuthSettings(): Promise<AuthSettings> {@@ -56,9 +70,9 @@ export async function setAuthSettings(patch: Partial<AuthSettings>): Promise<Aut// ── Encrypted config storage ──────────────────────────────────────────────────-// The mail provider and the Google credentials are stored the same way: one JSON-// blob per key in app_secret, encrypted as a whole, with a `redacted` mirror the-// settings UI reads without decrypting.+// Every credential is stored the same way: one JSON blob per key in app_secret,+// encrypted as a whole, with a `redacted` mirror the settings UI reads without+// decrypting.async function readSecret<T>(key: string): Promise<T | null> {const rows = await db@@ -298,6 +312,197 @@ export async function setGoogleSettings(patch: InstanceGooglePatch): Promise<Insreturn redacted;}+// ── Generic OIDC / OAuth2 ─────────────────────────────────────────────────────++// One OIDC provider per instance, discovered from its well-known document. The+// stored, decrypted credentials; read by the provider in ./index.ts on every+// request, never returned over HTTP.+export interface InstanceOidcConfig {+ enabled: boolean;+ // Text of the sign-in button. Free-form because it names the operator's own+ // identity provider, so the sign-in screen renders it as given rather than+ // translating it. Empty falls back to a translated default.+ label: string;+ // The provider's .well-known/openid-configuration. The authorization, token and+ // userinfo endpoints are read from it, so none of them is configured by hand.+ discoveryUrl: string;+ clientId: string;+ clientSecret: string;+ scopes: string[];+ pkce: boolean;+}++// The config as returned to the client: the secret replaced by a boolean telling+// whether a value is stored.+export interface InstanceOidcDto {+ enabled: boolean;+ label: string;+ discoveryUrl: string;+ clientId: string;+ hasClientSecret: boolean;+ scopes: string[];+ pkce: boolean;+}++// A partial write. The secret keeps its stored value when omitted or sent empty (a+// masked field the user did not edit).+export interface InstanceOidcPatch {+ enabled?: boolean;+ label?: string;+ discoveryUrl?: string;+ clientId?: string;+ clientSecret?: string;+ scopes?: string[];+ pkce?: boolean;+}++function defaultOidcConfig(): InstanceOidcConfig {+ return {+ enabled: false,+ label: '',+ discoveryUrl: '',+ clientId: '',+ clientSecret: '',+ scopes: ['openid', 'profile', 'email'],+ pkce: true,+ };+}++function toOidcDto(config: InstanceOidcConfig): InstanceOidcDto {+ return {+ enabled: config.enabled,+ label: config.label,+ discoveryUrl: config.discoveryUrl,+ clientId: config.clientId,+ hasClientSecret: config.clientSecret.length > 0,+ scopes: config.scopes,+ pkce: config.pkce,+ };+}++export async function getOidcConfig(): Promise<InstanceOidcConfig> {+ const stored = await readSecret<InstanceOidcConfig>(OIDC_SECRET_KEY);+ // Merge over the default so a config written before a field was added stays valid.+ return { ...defaultOidcConfig(), ...(stored ?? {}) };+}++export async function getOidcSettings(): Promise<InstanceOidcDto> {+ return toOidcDto(await getOidcConfig());+}++// Whether OIDC sign-in can run right now. The provider is always mounted, so this is+// what both the god settings and the public sign-in screen ask before offering it.+export function isOidcUsable(config: InstanceOidcConfig): boolean {+ return (+ config.enabled &&+ config.discoveryUrl.length > 0 &&+ config.clientId.length > 0 &&+ config.clientSecret.length > 0+ );+}++export async function hasConfiguredOidc(): Promise<boolean> {+ return isOidcUsable(await getOidcConfig());+}++// The button text the sign-in screen shows, or an empty string when OIDC is not+// usable. Read by the public /auth-config.+export async function getOidcLabel(): Promise<string> {+ const config = await getOidcConfig();+ return isOidcUsable(config) ? config.label : '';+}++export async function setOidcSettings(patch: InstanceOidcPatch): Promise<InstanceOidcDto> {+ const current = await getOidcConfig();+ const next: InstanceOidcConfig = {+ enabled: patch.enabled ?? current.enabled,+ label: patch.label ?? current.label,+ discoveryUrl: patch.discoveryUrl ?? current.discoveryUrl,+ clientId: patch.clientId ?? current.clientId,+ clientSecret: mergeSecret(current.clientSecret, patch.clientSecret),+ scopes: patch.scopes ?? current.scopes,+ pkce: patch.pkce ?? current.pkce,+ };+ const redacted = toOidcDto(next);+ await writeSecret(OIDC_SECRET_KEY, next, redacted);+ return redacted;+}++// ── SCIM provisioning token ───────────────────────────────────────────────────++// The bearer token an identity provider sends to /scim/v2. One token per instance,+// generated here and shown to the owner once: only its prefix is kept in the+// redacted mirror, so a lost token is replaced rather than recovered.+export interface InstanceScimConfig {+ enabled: boolean;+ token: string;+}++export interface InstanceScimDto {+ enabled: boolean;+ hasToken: boolean;+ // First characters of the stored token, so the owner can tell which one an IdP+ // is configured with.+ tokenPrefix: string;+}++const SCIM_TOKEN_PREFIX = 'scim_';++function defaultScimConfig(): InstanceScimConfig {+ return { enabled: false, token: '' };+}++function toScimDto(config: InstanceScimConfig): InstanceScimDto {+ return {+ enabled: config.enabled,+ hasToken: config.token.length > 0,+ tokenPrefix: config.token.slice(0, SCIM_TOKEN_PREFIX.length + 6),+ };+}++async function getScimConfig(): Promise<InstanceScimConfig> {+ const stored = await readSecret<InstanceScimConfig>(SCIM_SECRET_KEY);+ return { ...defaultScimConfig(), ...(stored ?? {}) };+}++export async function getScimSettings(): Promise<InstanceScimDto> {+ return toScimDto(await getScimConfig());+}++export async function setScimSettings(patch: { enabled?: boolean }): Promise<InstanceScimDto> {+ const current = await getScimConfig();+ const next: InstanceScimConfig = { ...current, enabled: patch.enabled ?? current.enabled };+ const redacted = toScimDto(next);+ await writeSecret(SCIM_SECRET_KEY, next, redacted);+ return redacted;+}++// Mints a token, replacing any previous one, and returns it in the clear. This is+// the only time the value leaves the server.+export async function rotateScimToken(): Promise<string> {+ const current = await getScimConfig();+ const token = `${SCIM_TOKEN_PREFIX}${randomBytes(24).toString('hex')}`;+ const next: InstanceScimConfig = { ...current, token };+ await writeSecret(SCIM_SECRET_KEY, next, toScimDto(next));+ return token;+}++export async function isScimEnabled(): Promise<boolean> {+ const config = await getScimConfig();+ return config.enabled && config.token.length > 0;+}++// Constant-time comparison, so a wrong token cannot be recovered by timing the+// answer. Lengths are compared first because timingSafeEqual rejects buffers of+// different sizes.+export async function verifyScimToken(candidate: string): Promise<boolean> {+ const config = await getScimConfig();+ if (!config.enabled || config.token.length === 0) return false;+ const expected = Buffer.from(config.token);+ const given = Buffer.from(candidate);+ return expected.length === given.length && timingSafeEqual(expected, given);+}+// ── Invites ───────────────────────────────────────────────────────────────────// True when this address has a pending project invite. That is what "invite only"diff --git a/packages/db/drizzle/0111_bitter_pride.sql b/packages/db/drizzle/0111_bitter_pride.sqlnew file mode 100644index 00000000..b7f8f1de--- /dev/null+++ b/packages/db/drizzle/0111_bitter_pride.sql@@ -0,0 +1,37 @@+CREATE TABLE "scim_group" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "display_name" text NOT NULL,+ "external_id" text,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,+ CONSTRAINT "scim_group_display_name_unique" UNIQUE("display_name")+);+--> statement-breakpoint+CREATE TABLE "scim_group_mapping" (+ "id" serial PRIMARY KEY NOT NULL,+ "group_id" uuid NOT NULL,+ "project_id" integer NOT NULL,+ "role" text DEFAULT 'member' NOT NULL,+ "role_id" integer,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ CONSTRAINT "scim_group_mapping_group_id_project_id_unique" UNIQUE("group_id","project_id"),+ CONSTRAINT "scim_group_mapping_role_check" CHECK ("scim_group_mapping"."role" IN ('owner', 'member'))+);+--> statement-breakpoint+CREATE TABLE "scim_group_member" (+ "group_id" uuid NOT NULL,+ "user_id" text NOT NULL,+ CONSTRAINT "scim_group_member_group_id_user_id_pk" PRIMARY KEY("group_id","user_id")+);+--> statement-breakpoint+ALTER TABLE "user" ADD COLUMN "active" boolean DEFAULT true;--> statement-breakpoint+ALTER TABLE "user" ADD COLUMN "scim_external_id" text;--> statement-breakpoint+ALTER TABLE "project_member" ADD COLUMN "source" text DEFAULT 'invite' NOT NULL;--> statement-breakpoint+ALTER TABLE "scim_group_mapping" ADD CONSTRAINT "scim_group_mapping_group_id_scim_group_id_fk" FOREIGN KEY ("group_id") REFERENCES "public"."scim_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "scim_group_mapping" ADD CONSTRAINT "scim_group_mapping_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "scim_group_mapping" ADD CONSTRAINT "scim_group_mapping_role_id_project_role_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."project_role"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "scim_group_member" ADD CONSTRAINT "scim_group_member_group_id_scim_group_id_fk" FOREIGN KEY ("group_id") REFERENCES "public"."scim_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "scim_group_member" ADD CONSTRAINT "scim_group_member_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+CREATE INDEX "scim_group_mapping_project_idx" ON "scim_group_mapping" USING btree ("project_id");--> statement-breakpoint+CREATE INDEX "scim_group_member_user_idx" ON "scim_group_member" USING btree ("user_id");--> statement-breakpoint+ALTER TABLE "project_member" ADD CONSTRAINT "project_member_source_check" CHECK ("project_member"."source" IN ('invite', 'scim'));\ No newline at end of filediff --git a/packages/db/drizzle/meta/0111_snapshot.json b/packages/db/drizzle/meta/0111_snapshot.jsonnew file mode 100644index 00000000..c035455e--- /dev/null+++ b/packages/db/drizzle/meta/0111_snapshot.json@@ -0,0 +1,7837 @@+{+ "id": "bdd412b9-2d3f-41f7-b1c5-54f9e26580a4",+ "prevId": "0d5231b8-d7b4-439f-b825-f20cff65306a",+ "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()"+ },+ "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.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+ },+ "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": 1000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 100+ },+ "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_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_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": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.passkey": {+ "name": "passkey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "public_key": {+ "name": "public_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_id": {+ "name": "credential_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "counter": {+ "name": "counter",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "device_type": {+ "name": "device_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "backed_up": {+ "name": "backed_up",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "transports": {+ "name": "transports",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "aaguid": {+ "name": "aaguid",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "passkey_userId_idx": {+ "name": "passkey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "passkey_credentialID_idx": {+ "name": "passkey_credentialID_idx",+ "columns": [+ {+ "expression": "credential_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "passkey_user_id_user_id_fk": {+ "name": "passkey_user_id_user_id_fk",+ "tableFrom": "passkey",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "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()"+ },+ "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+ }+ },+ "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": {}+ }+ },+ "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.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,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "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()"+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "display_username": {+ "name": "display_username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'user'"+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "scim_external_id": {+ "name": "scim_external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ },+ "user_username_unique": {+ "name": "user_username_unique",+ "nullsNotDistinct": false,+ "columns": [+ "username"+ ]+ }+ },+ "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()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "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.agent_chat_event": {+ "name": "agent_chat_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigserial",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_event_message_idx": {+ "name": "agent_chat_event_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_event_message_id_agent_chat_message_id_fk": {+ "name": "agent_chat_event_message_id_agent_chat_message_id_fk",+ "tableFrom": "agent_chat_event",+ "tableTo": "agent_chat_message",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_favorite": {+ "name": "agent_chat_favorite",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_chat_favorite_user_id_user_id_fk": {+ "name": "agent_chat_favorite_user_id_user_id_fk",+ "tableFrom": "agent_chat_favorite",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_favorite_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_favorite_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_favorite",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_chat_favorite_user_id_thread_id_pk": {+ "name": "agent_chat_favorite_user_id_thread_id_pk",+ "columns": [+ "user_id",+ "thread_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_message": {+ "name": "agent_chat_message",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_message_thread_idx": {+ "name": "agent_chat_message_thread_idx",+ "columns": [+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_chat_message_due_idx": {+ "name": "agent_chat_message_due_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_message_thread_id_agent_chat_thread_id_fk": {+ "name": "agent_chat_message_thread_id_agent_chat_thread_id_fk",+ "tableFrom": "agent_chat_message",+ "tableTo": "agent_chat_thread",+ "columnsFrom": [+ "thread_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_message_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_message_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_message",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_chat_message_role_check": {+ "name": "agent_chat_message_role_check",+ "value": "\"agent_chat_message\".\"role\" IN ('user', 'assistant')"+ },+ "agent_chat_message_status_check": {+ "name": "agent_chat_message_status_check",+ "value": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming', 'success', 'failed', 'canceled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_chat_thread": {+ "name": "agent_chat_thread",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cli_session_id": {+ "name": "cli_session_id",+ "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": {+ "agent_chat_thread_agent_user_idx": {+ "name": "agent_chat_thread_agent_user_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_thread_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_thread_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_thread",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_thread_user_id_user_id_fk": {+ "name": "agent_chat_thread_user_id_user_id_fk",+ "tableFrom": "agent_chat_thread",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_usage": {+ "name": "agent_chat_usage",+ "schema": "",+ "columns": {+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_usage_agent_idx": {+ "name": "agent_chat_usage_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_usage_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_usage_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_usage",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_field_trigger": {+ "name": "agent_field_trigger",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "delay_sec": {+ "name": "delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 120+ }+ },+ "indexes": {+ "agent_field_trigger_field_idx": {+ "name": "agent_field_trigger_field_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_field_trigger_agent_id_ai_agent_id_fk": {+ "name": "agent_field_trigger_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_field_trigger",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_field_trigger_field_id_custom_field_id_fk": {+ "name": "agent_field_trigger_field_id_custom_field_id_fk",+ "tableFrom": "agent_field_trigger",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_field_trigger_agent_id_field_id_pk": {+ "name": "agent_field_trigger_agent_id_field_id_pk",+ "columns": [+ "agent_id",+ "field_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_field_trigger_delay_check": {+ "name": "agent_field_trigger_delay_check",+ "value": "\"agent_field_trigger\".\"delay_sec\" >= 0 AND \"agent_field_trigger\".\"delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_run": {+ "name": "agent_run",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "schedule_id": {+ "name": "schedule_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'delegation'"+ },+ "scheduled_for": {+ "name": "scheduled_for",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "source_activity_id": {+ "name": "source_activity_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "output": {+ "name": "output",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_run_schedule_fire_uq": {+ "name": "agent_run_schedule_fire_uq",+ "columns": [+ {+ "expression": "schedule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scheduled_for",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_due_idx": {+ "name": "agent_run_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_schedule_idx": {+ "name": "agent_run_schedule_idx",+ "columns": [+ {+ "expression": "schedule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_run_agent_id_ai_agent_id_fk": {+ "name": "agent_run_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_issue_id_issue_id_fk": {+ "name": "agent_run_issue_id_issue_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_schedule_id_agent_schedule_id_fk": {+ "name": "agent_run_schedule_id_agent_schedule_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "agent_schedule",+ "columnsFrom": [+ "schedule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_source_activity_id_issue_activity_id_fk": {+ "name": "agent_run_source_activity_id_issue_activity_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "source_activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_run_status_check": {+ "name": "agent_run_status_check",+ "value": "\"agent_run\".\"status\" IN ('pending', 'success', 'failed', 'canceled')"+ },+ "agent_run_trigger_check": {+ "name": "agent_run_trigger_check",+ "value": "\"agent_run\".\"trigger\" IN ('mention', 'delegation', 'field', 'schedule', 'manual')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_schedule": {+ "name": "agent_schedule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "cron": {+ "name": "cron",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "next_run_at": {+ "name": "next_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "last_run_at": {+ "name": "last_run_at",+ "type": "timestamp with time zone",+ "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": {+ "agent_schedule_due_idx": {+ "name": "agent_schedule_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_run_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_schedule_agent_idx": {+ "name": "agent_schedule_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_schedule_agent_id_ai_agent_id_fk": {+ "name": "agent_schedule_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_schedule",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_schedule_agent_id_name_unique": {+ "name": "agent_schedule_agent_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "agent_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "agent_schedule_status_check": {+ "name": "agent_schedule_status_check",+ "value": "\"agent_schedule\".\"status\" IN ('active', 'paused')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_skill": {+ "name": "agent_skill",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_url": {+ "name": "source_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_prefix": {+ "name": "s3_prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "files": {+ "name": "files",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_skill_project_idx": {+ "name": "agent_skill_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_skill_project_id_project_id_fk": {+ "name": "agent_skill_project_id_project_id_fk",+ "tableFrom": "agent_skill",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_skill_project_id_name_unique": {+ "name": "agent_skill_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "agent_skill_source_check": {+ "name": "agent_skill_source_check",+ "value": "\"agent_skill\".\"source\" IN ('upload', 'inline', 'github')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_skill_link": {+ "name": "agent_skill_link",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "skill_id": {+ "name": "skill_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_skill_link_skill_idx": {+ "name": "agent_skill_link_skill_idx",+ "columns": [+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_skill_link_agent_id_ai_agent_id_fk": {+ "name": "agent_skill_link_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_skill_link",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_skill_link_skill_id_agent_skill_id_fk": {+ "name": "agent_skill_link_skill_id_agent_skill_id_fk",+ "tableFrom": "agent_skill_link",+ "tableTo": "agent_skill",+ "columnsFrom": [+ "skill_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_skill_link_agent_id_skill_id_pk": {+ "name": "agent_skill_link_agent_id_skill_id_pk",+ "columns": [+ "agent_id",+ "skill_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_tool": {+ "name": "agent_tool",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "tool_key": {+ "name": "tool_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_id": {+ "name": "credential_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_tool_project_idx": {+ "name": "agent_tool_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_tool_credential_idx": {+ "name": "agent_tool_credential_idx",+ "columns": [+ {+ "expression": "credential_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_tool_project_id_project_id_fk": {+ "name": "agent_tool_project_id_project_id_fk",+ "tableFrom": "agent_tool",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_tool_credential_id_integration_credential_id_fk": {+ "name": "agent_tool_credential_id_integration_credential_id_fk",+ "tableFrom": "agent_tool",+ "tableTo": "integration_credential",+ "columnsFrom": [+ "credential_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_tool_project_id_tool_key_credential_id_unique": {+ "name": "agent_tool_project_id_tool_key_credential_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "tool_key",+ "credential_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_tool_link": {+ "name": "agent_tool_link",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "agent_tool_id": {+ "name": "agent_tool_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_tool_link_tool_idx": {+ "name": "agent_tool_link_tool_idx",+ "columns": [+ {+ "expression": "agent_tool_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_tool_link_agent_id_ai_agent_id_fk": {+ "name": "agent_tool_link_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_tool_link",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_tool_link_agent_tool_id_agent_tool_id_fk": {+ "name": "agent_tool_link_agent_tool_id_agent_tool_id_fk",+ "tableFrom": "agent_tool_link",+ "tableTo": "agent_tool",+ "columnsFrom": [+ "agent_tool_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_tool_link_agent_id_agent_tool_id_pk": {+ "name": "agent_tool_link_agent_id_agent_tool_id_pk",+ "columns": [+ "agent_id",+ "agent_tool_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_agent": {+ "name": "ai_agent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "model_credential_id": {+ "name": "model_credential_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tools": {+ "name": "tools",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "temperature": {+ "name": "temperature",+ "type": "double precision",+ "primaryKey": false,+ "notNull": false+ },+ "max_steps": {+ "name": "max_steps",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_on_mention": {+ "name": "trigger_on_mention",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "trigger_on_assign": {+ "name": "trigger_on_assign",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "delegation_delay_sec": {+ "name": "delegation_delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 120+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_ciphertext": {+ "name": "api_key_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_iv": {+ "name": "api_key_iv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_auth_tag": {+ "name": "api_key_auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "memory_enabled": {+ "name": "memory_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "memory_last_messages": {+ "name": "memory_last_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runner_scope": {+ "name": "runner_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'project'"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_agent_project_username_uq": {+ "name": "ai_agent_project_username_uq",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(\"username\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_agent_project_idx": {+ "name": "ai_agent_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_agent_project_id_project_id_fk": {+ "name": "ai_agent_project_id_project_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_agent_user_id_user_id_fk": {+ "name": "ai_agent_user_id_user_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_agent_model_credential_id_integration_credential_id_fk": {+ "name": "ai_agent_model_credential_id_integration_credential_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "integration_credential",+ "columnsFrom": [+ "model_credential_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "ai_agent_role_id_project_role_id_fk": {+ "name": "ai_agent_role_id_project_role_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "project_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "ai_agent_owner_user_id_user_id_fk": {+ "name": "ai_agent_owner_user_id_user_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "ai_agent_user_id_unique": {+ "name": "ai_agent_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "ai_agent_kind_check": {+ "name": "ai_agent_kind_check",+ "value": "\"ai_agent\".\"kind\" IN ('external', 'internal')"+ },+ "ai_agent_runner_scope_check": {+ "name": "ai_agent_runner_scope_check",+ "value": "\"ai_agent\".\"runner_scope\" IN ('owner', 'project')"+ },+ "ai_agent_delegation_delay_check": {+ "name": "ai_agent_delegation_delay_check",+ "value": "\"ai_agent\".\"delegation_delay_sec\" >= 0 AND \"ai_agent\".\"delegation_delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.app_secret": {+ "name": "app_secret",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.app_setting": {+ "name": "app_setting",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_attachment": {+ "name": "chat_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "uploaded_by_user_id": {+ "name": "uploaded_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_attachment_project_idx": {+ "name": "chat_attachment_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_attachment_project_id_project_id_fk": {+ "name": "chat_attachment_project_id_project_id_fk",+ "tableFrom": "chat_attachment",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_attachment_uploaded_by_user_id_user_id_fk": {+ "name": "chat_attachment_uploaded_by_user_id_user_id_fk",+ "tableFrom": "chat_attachment",+ "tableTo": "user",+ "columnsFrom": [+ "uploaded_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_attachment_public_id_unique": {+ "name": "chat_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field": {+ "name": "custom_field",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_type_id": {+ "name": "issue_type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_type": {+ "name": "field_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "member_scope": {+ "name": "member_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "show_in_body": {+ "name": "show_in_body",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "custom_field_project_id_project_id_fk": {+ "name": "custom_field_project_id_project_id_fk",+ "tableFrom": "custom_field",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "custom_field_issue_type_id_issue_type_id_fk": {+ "name": "custom_field_issue_type_id_issue_type_id_fk",+ "tableFrom": "custom_field",+ "tableTo": "issue_type",+ "columnsFrom": [+ "issue_type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "custom_field_field_type_check": {+ "name": "custom_field_field_type_check",+ "value": "\"custom_field\".\"field_type\" IN ('text', 'markdown', 'url', 'number', 'boolean', 'date', 'datetime', 'datetime_range', 'select', 'multi_select', 'member')"+ },+ "custom_field_member_scope_check": {+ "name": "custom_field_member_scope_check",+ "value": "(\"custom_field\".\"field_type\" = 'member') = (\"custom_field\".\"member_scope\" IS NOT NULL) AND (\"custom_field\".\"member_scope\" IS NULL OR \"custom_field\".\"member_scope\" IN ('all', 'humans', 'agents'))"+ }+ },+ "isRLSEnabled": false+ },+ "public.custom_field_option": {+ "name": "custom_field_option",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {+ "custom_field_option_field_id_custom_field_id_fk": {+ "name": "custom_field_option_field_id_custom_field_id_fk",+ "tableFrom": "custom_field_option",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_option_field_id_value_unique": {+ "name": "custom_field_option_field_id_value_unique",+ "nullsNotDistinct": false,+ "columns": [+ "field_id",+ "value"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cycle": {+ "name": "cycle",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "goal": {+ "name": "goal",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "end_date": {+ "name": "end_date",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "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": {+ "cycle_project_idx": {+ "name": "cycle_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "start_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "cycle_project_id_project_id_fk": {+ "name": "cycle_project_id_project_id_fk",+ "tableFrom": "cycle",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "cycle_dates_check": {+ "name": "cycle_dates_check",+ "value": "\"cycle\".\"end_date\" >= \"cycle\".\"start_date\""+ }+ },+ "isRLSEnabled": false+ },+ "public.initiative": {+ "name": "initiative",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'planned'"+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "target_date": {+ "name": "target_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "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": {+ "initiative_project_idx": {+ "name": "initiative_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "initiative_project_id_project_id_fk": {+ "name": "initiative_project_id_project_id_fk",+ "tableFrom": "initiative",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "initiative_owner_user_id_user_id_fk": {+ "name": "initiative_owner_user_id_user_id_fk",+ "tableFrom": "initiative",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "initiative_status_check": {+ "name": "initiative_status_check",+ "value": "\"initiative\".\"status\" IN ('proposed', 'planned', 'active', 'completed', 'canceled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.initiative_label": {+ "name": "initiative_label",+ "schema": "",+ "columns": {+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "initiative_label_initiative_id_initiative_id_fk": {+ "name": "initiative_label_initiative_id_initiative_id_fk",+ "tableFrom": "initiative_label",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "initiative_label_label_id_label_id_fk": {+ "name": "initiative_label_label_id_label_id_fk",+ "tableFrom": "initiative_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "initiative_label_initiative_id_label_id_pk": {+ "name": "initiative_label_initiative_id_label_id_pk",+ "columns": [+ "initiative_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration_credential": {+ "name": "integration_credential",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "integration_key": {+ "name": "integration_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_credential_project_idx": {+ "name": "integration_credential_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_credential_project_id_project_id_fk": {+ "name": "integration_credential_project_id_project_id_fk",+ "tableFrom": "integration_credential",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue": {+ "name": "issue",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "sequence_number": {+ "name": "sequence_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "type_id": {+ "name": "type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cycle_id": {+ "name": "cycle_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "delegate_user_id": {+ "name": "delegate_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "estimate_points": {+ "name": "estimate_points",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false+ },+ "estimate_minutes": {+ "name": "estimate_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "share_token": {+ "name": "share_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "share_extended": {+ "name": "share_extended",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": 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": {+ "issue_project_active_idx": {+ "name": "issue_project_active_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"archived_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_project_title_idx": {+ "name": "issue_project_title_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(btrim(\"title\"))",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_parent_idx": {+ "name": "issue_parent_idx",+ "columns": [+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"parent_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_idx": {+ "name": "issue_cycle_idx",+ "columns": [+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"cycle_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_project_id_project_id_fk": {+ "name": "issue_project_id_project_id_fk",+ "tableFrom": "issue",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_type_id_issue_type_id_fk": {+ "name": "issue_type_id_issue_type_id_fk",+ "tableFrom": "issue",+ "tableTo": "issue_type",+ "columnsFrom": [+ "type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_initiative_id_initiative_id_fk": {+ "name": "issue_initiative_id_initiative_id_fk",+ "tableFrom": "issue",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_cycle_id_cycle_id_fk": {+ "name": "issue_cycle_id_cycle_id_fk",+ "tableFrom": "issue",+ "tableTo": "cycle",+ "columnsFrom": [+ "cycle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_column_id_project_column_id_fk": {+ "name": "issue_column_id_project_column_id_fk",+ "tableFrom": "issue",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "issue_parent_id_issue_id_fk": {+ "name": "issue_parent_id_issue_id_fk",+ "tableFrom": "issue",+ "tableTo": "issue",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_assignee_user_id_user_id_fk": {+ "name": "issue_assignee_user_id_user_id_fk",+ "tableFrom": "issue",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_delegate_user_id_user_id_fk": {+ "name": "issue_delegate_user_id_user_id_fk",+ "tableFrom": "issue",+ "tableTo": "user",+ "columnsFrom": [+ "delegate_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_share_token_unique": {+ "name": "issue_share_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "share_token"+ ]+ },+ "issue_project_id_sequence_number_unique": {+ "name": "issue_project_id_sequence_number_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "sequence_number"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "issue_estimate_points_check": {+ "name": "issue_estimate_points_check",+ "value": "\"issue\".\"estimate_points\" >= 0"+ },+ "issue_estimate_minutes_check": {+ "name": "issue_estimate_minutes_check",+ "value": "\"issue\".\"estimate_minutes\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_activity": {+ "name": "issue_activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reply_to_id": {+ "name": "reply_to_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_name": {+ "name": "actor_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_activity_issue_idx": {+ "name": "issue_activity_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_activity_reply_idx": {+ "name": "issue_activity_reply_idx",+ "columns": [+ {+ "expression": "reply_to_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_activity_initiative_idx": {+ "name": "issue_activity_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_activity_issue_id_issue_id_fk": {+ "name": "issue_activity_issue_id_issue_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_initiative_id_initiative_id_fk": {+ "name": "issue_activity_initiative_id_initiative_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_reply_to_id_issue_activity_id_fk": {+ "name": "issue_activity_reply_to_id_issue_activity_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "reply_to_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_actor_user_id_user_id_fk": {+ "name": "issue_activity_actor_user_id_user_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "user",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_activity_kind_check": {+ "name": "issue_activity_kind_check",+ "value": "\"issue_activity\".\"kind\" IN ('comment', 'activity')"+ },+ "issue_activity_owner_check": {+ "name": "issue_activity_owner_check",+ "value": "(\"issue_activity\".\"issue_id\" IS NOT NULL) <> (\"issue_activity\".\"initiative_id\" IS NOT NULL)"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_attachment": {+ "name": "issue_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_attachment_issue_idx": {+ "name": "issue_attachment_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_attachment_issue_id_issue_id_fk": {+ "name": "issue_attachment_issue_id_issue_id_fk",+ "tableFrom": "issue_attachment",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_attachment_public_id_unique": {+ "name": "issue_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_checklist": {+ "name": "issue_checklist",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_checklist_issue_idx": {+ "name": "issue_checklist_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_checklist_issue_id_issue_id_fk": {+ "name": "issue_checklist_issue_id_issue_id_fk",+ "tableFrom": "issue_checklist",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_checklist_item": {+ "name": "issue_checklist_item",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "checklist_id": {+ "name": "checklist_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "done": {+ "name": "done",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_checklist_item_checklist_idx": {+ "name": "issue_checklist_item_checklist_idx",+ "columns": [+ {+ "expression": "checklist_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_checklist_item_checklist_id_issue_checklist_id_fk": {+ "name": "issue_checklist_item_checklist_id_issue_checklist_id_fk",+ "tableFrom": "issue_checklist_item",+ "tableTo": "issue_checklist",+ "columnsFrom": [+ "checklist_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_cycle": {+ "name": "issue_cycle",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "cycle_id": {+ "name": "cycle_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "entered_at": {+ "name": "entered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "left_at": {+ "name": "left_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "issue_cycle_issue_idx": {+ "name": "issue_cycle_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_cycle_idx": {+ "name": "issue_cycle_cycle_idx",+ "columns": [+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_open_idx": {+ "name": "issue_cycle_open_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_cycle\".\"left_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_cycle_issue_id_issue_id_fk": {+ "name": "issue_cycle_issue_id_issue_id_fk",+ "tableFrom": "issue_cycle",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_cycle_cycle_id_cycle_id_fk": {+ "name": "issue_cycle_cycle_id_cycle_id_fk",+ "tableFrom": "issue_cycle",+ "tableTo": "cycle",+ "columnsFrom": [+ "cycle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_field_option": {+ "name": "issue_field_option",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "option_id": {+ "name": "option_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_field_option_issue_id_issue_id_fk": {+ "name": "issue_field_option_issue_id_issue_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_option_field_id_custom_field_id_fk": {+ "name": "issue_field_option_field_id_custom_field_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_option_option_id_custom_field_option_id_fk": {+ "name": "issue_field_option_option_id_custom_field_option_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "custom_field_option",+ "columnsFrom": [+ "option_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_field_option_issue_id_field_id_option_id_pk": {+ "name": "issue_field_option_issue_id_field_id_option_id_pk",+ "columns": [+ "issue_id",+ "field_id",+ "option_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_field_value": {+ "name": "issue_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "value_text": {+ "name": "value_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "value_number": {+ "name": "value_number",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false+ },+ "value_bool": {+ "name": "value_bool",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "value_date": {+ "name": "value_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "value_datetime": {+ "name": "value_datetime",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "value_datetime_end": {+ "name": "value_datetime_end",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "value_user_id": {+ "name": "value_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_field_value_issue_id_issue_id_fk": {+ "name": "issue_field_value_issue_id_issue_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_value_field_id_custom_field_id_fk": {+ "name": "issue_field_value_field_id_custom_field_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_value_value_user_id_user_id_fk": {+ "name": "issue_field_value_value_user_id_user_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "user",+ "columnsFrom": [+ "value_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_field_value_issue_id_field_id_unique": {+ "name": "issue_field_value_issue_id_field_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "issue_id",+ "field_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_import": {+ "name": "issue_import",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'mapped'"+ },+ "mapping": {+ "name": "mapping",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "error_text": {+ "name": "error_text",+ "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": {+ "issue_import_project_idx": {+ "name": "issue_import_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_import_project_id_project_id_fk": {+ "name": "issue_import_project_id_project_id_fk",+ "tableFrom": "issue_import",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_import_attachment_id_chat_attachment_id_fk": {+ "name": "issue_import_attachment_id_chat_attachment_id_fk",+ "tableFrom": "issue_import",+ "tableTo": "chat_attachment",+ "columnsFrom": [+ "attachment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_import_public_id_unique": {+ "name": "issue_import_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_label": {+ "name": "issue_label",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_label_issue_id_issue_id_fk": {+ "name": "issue_label_issue_id_issue_id_fk",+ "tableFrom": "issue_label",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_label_label_id_label_id_fk": {+ "name": "issue_label_label_id_label_id_fk",+ "tableFrom": "issue_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_label_issue_id_label_id_pk": {+ "name": "issue_label_issue_id_label_id_pk",+ "columns": [+ "issue_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_link": {+ "name": "issue_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "target_issue_id": {+ "name": "target_issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_link_pair_kind_idx": {+ "name": "issue_link_pair_kind_idx",+ "columns": [+ {+ "expression": "least(\"source_issue_id\", \"target_issue_id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "greatest(\"source_issue_id\", \"target_issue_id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_link_source_idx": {+ "name": "issue_link_source_idx",+ "columns": [+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_link_target_idx": {+ "name": "issue_link_target_idx",+ "columns": [+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_link_source_issue_id_issue_id_fk": {+ "name": "issue_link_source_issue_id_issue_id_fk",+ "tableFrom": "issue_link",+ "tableTo": "issue",+ "columnsFrom": [+ "source_issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_link_target_issue_id_issue_id_fk": {+ "name": "issue_link_target_issue_id_issue_id_fk",+ "tableFrom": "issue_link",+ "tableTo": "issue",+ "columnsFrom": [+ "target_issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_link_kind_check": {+ "name": "issue_link_kind_check",+ "value": "\"issue_link\".\"kind\" IN ('blocks', 'relates', 'duplicates')"+ },+ "issue_link_self_check": {+ "name": "issue_link_self_check",+ "value": "\"issue_link\".\"source_issue_id\" <> \"issue_link\".\"target_issue_id\""+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_status": {+ "name": "issue_status",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_name": {+ "name": "column_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state_type": {+ "name": "state_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "entered_at": {+ "name": "entered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "left_at": {+ "name": "left_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "issue_status_issue_idx": {+ "name": "issue_status_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_status_column_idx": {+ "name": "issue_status_column_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue_status\".\"column_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_status_open_idx": {+ "name": "issue_status_open_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_status\".\"left_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_status_issue_id_issue_id_fk": {+ "name": "issue_status_issue_id_issue_id_fk",+ "tableFrom": "issue_status",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_status_column_id_project_column_id_fk": {+ "name": "issue_status_column_id_project_column_id_fk",+ "tableFrom": "issue_status",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_type": {+ "name": "issue_type",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_type_project_id_project_id_fk": {+ "name": "issue_type_project_id_project_id_fk",+ "tableFrom": "issue_type",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_type_project_id_name_unique": {+ "name": "issue_type_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_watcher": {+ "name": "issue_watcher",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subscribed": {+ "name": "subscribed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_watcher_issue_id_issue_id_fk": {+ "name": "issue_watcher_issue_id_issue_id_fk",+ "tableFrom": "issue_watcher",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_watcher_user_id_user_id_fk": {+ "name": "issue_watcher_user_id_user_id_fk",+ "tableFrom": "issue_watcher",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_watcher_issue_id_user_id_pk": {+ "name": "issue_watcher_issue_id_user_id_pk",+ "columns": [+ "issue_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_worklog": {+ "name": "issue_worklog",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "minutes": {+ "name": "minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "spent_on": {+ "name": "spent_on",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_worklog_issue_idx": {+ "name": "issue_worklog_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "spent_on",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_worklog_issue_id_issue_id_fk": {+ "name": "issue_worklog_issue_id_issue_id_fk",+ "tableFrom": "issue_worklog",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_worklog_user_id_user_id_fk": {+ "name": "issue_worklog_user_id_user_id_fk",+ "tableFrom": "issue_worklog",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_worklog_minutes_check": {+ "name": "issue_worklog_minutes_check",+ "value": "\"issue_worklog\".\"minutes\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "group_id": {+ "name": "group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_project_id_project_id_fk": {+ "name": "label_project_id_project_id_fk",+ "tableFrom": "label",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "label_group_id_label_group_id_fk": {+ "name": "label_group_id_label_group_id_fk",+ "tableFrom": "label",+ "tableTo": "label_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_project_id_name_unique": {+ "name": "label_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label_group": {+ "name": "label_group",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_group_project_id_project_id_fk": {+ "name": "label_group_project_id_project_id_fk",+ "tableFrom": "label_group",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_group_project_id_name_unique": {+ "name": "label_group_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.note_board": {+ "name": "note_board",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "canvas": {+ "name": "canvas",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "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": {+ "note_board_project_idx": {+ "name": "note_board_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "note_board_project_id_project_id_fk": {+ "name": "note_board_project_id_project_id_fk",+ "tableFrom": "note_board",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_owner_user_id_user_id_fk": {+ "name": "note_board_owner_user_id_user_id_fk",+ "tableFrom": "note_board",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_created_by_user_id_user_id_fk": {+ "name": "note_board_created_by_user_id_user_id_fk",+ "tableFrom": "note_board",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.note_board_member": {+ "name": "note_board_member",+ "schema": "",+ "columns": {+ "board_id": {+ "name": "board_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "note_board_member_user_idx": {+ "name": "note_board_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "note_board_member_board_id_note_board_id_fk": {+ "name": "note_board_member_board_id_note_board_id_fk",+ "tableFrom": "note_board_member",+ "tableTo": "note_board",+ "columnsFrom": [+ "board_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_member_user_id_user_id_fk": {+ "name": "note_board_member_user_id_user_id_fk",+ "tableFrom": "note_board_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "note_board_member_board_id_user_id_pk": {+ "name": "note_board_member_board_id_user_id_pk",+ "columns": [+ "board_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "source_activity_id": {+ "name": "source_activity_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "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+ },+ "read_at": {+ "name": "read_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_user_idx": {+ "name": "notification_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "notification_user_unread_idx": {+ "name": "notification_user_unread_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"notification\".\"read_at\" IS NULL",+ "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": "no action"+ },+ "notification_project_id_project_id_fk": {+ "name": "notification_project_id_project_id_fk",+ "tableFrom": "notification",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_issue_id_issue_id_fk": {+ "name": "notification_issue_id_issue_id_fk",+ "tableFrom": "notification",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_source_activity_id_issue_activity_id_fk": {+ "name": "notification_source_activity_id_issue_activity_id_fk",+ "tableFrom": "notification",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "source_activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "notification_actor_user_id_user_id_fk": {+ "name": "notification_actor_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "notification_type_check": {+ "name": "notification_type_check",+ "value": "\"notification\".\"type\" IN ('assigned', 'mentioned', 'commented', 'state_changed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.notification_delivery": {+ "name": "notification_delivery",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "recipient": {+ "name": "recipient",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_delivery_due_idx": {+ "name": "notification_delivery_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"notification_delivery\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_delivery_project_id_project_id_fk": {+ "name": "notification_delivery_project_id_project_id_fk",+ "tableFrom": "notification_delivery",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "notification_delivery_channel_check": {+ "name": "notification_delivery_channel_check",+ "value": "\"notification_delivery\".\"channel\" IN ('email', 'telegram')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "next_sequence": {+ "name": "next_sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "mcp_enabled": {+ "name": "mcp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "initiatives_enabled": {+ "name": "initiatives_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "dashboards_enabled": {+ "name": "dashboards_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "notes_enabled": {+ "name": "notes_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "cycles_enabled": {+ "name": "cycles_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "subtasks_enabled": {+ "name": "subtasks_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "checklists_enabled": {+ "name": "checklists_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "issue_stats_enabled": {+ "name": "issue_stats_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "points_estimate_enabled": {+ "name": "points_estimate_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "time_estimate_enabled": {+ "name": "time_estimate_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "time_logging_enabled": {+ "name": "time_logging_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_key_unique": {+ "name": "project_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_action": {+ "name": "project_action",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "condition": {+ "name": "condition",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "effect": {+ "name": "effect",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_action_project_idx": {+ "name": "project_action_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_action_project_id_project_id_fk": {+ "name": "project_action_project_id_project_id_fk",+ "tableFrom": "project_action",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_column": {+ "name": "project_column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state_type": {+ "name": "state_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unstarted'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "wip_limit": {+ "name": "wip_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "wip_mode": {+ "name": "wip_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'soft'"+ },+ "auto_assign_user_id": {+ "name": "auto_assign_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_column_project_id_project_id_fk": {+ "name": "project_column_project_id_project_id_fk",+ "tableFrom": "project_column",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_column_auto_assign_user_id_user_id_fk": {+ "name": "project_column_auto_assign_user_id_user_id_fk",+ "tableFrom": "project_column",+ "tableTo": "user",+ "columnsFrom": [+ "auto_assign_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_column_project_id_position_unique": {+ "name": "project_column_project_id_position_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "position"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "project_column_state_type_check": {+ "name": "project_column_state_type_check",+ "value": "\"project_column\".\"state_type\" IN ('backlog', 'unstarted', 'started', 'completed', 'canceled')"+ },+ "project_column_wip_mode_check": {+ "name": "project_column_wip_mode_check",+ "value": "\"project_column\".\"wip_mode\" IN ('soft', 'hard')"+ },+ "project_column_wip_limit_check": {+ "name": "project_column_wip_limit_check",+ "value": "\"project_column\".\"wip_limit\" IS NULL OR \"project_column\".\"wip_limit\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_dashboard": {+ "name": "project_dashboard",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "layout": {+ "name": "layout",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_dashboard_project_idx": {+ "name": "project_dashboard_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_dashboard_project_id_project_id_fk": {+ "name": "project_dashboard_project_id_project_id_fk",+ "tableFrom": "project_dashboard",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_invite": {+ "name": "project_invite",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "invited_by_user_id": {+ "name": "invited_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accepted_by_user_id": {+ "name": "accepted_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "responded_at": {+ "name": "responded_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "project_invite_pending_uq": {+ "name": "project_invite_pending_uq",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"project_invite\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_invite_project_idx": {+ "name": "project_invite_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_invite_project_id_project_id_fk": {+ "name": "project_invite_project_id_project_id_fk",+ "tableFrom": "project_invite",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_invite_role_id_project_role_id_fk": {+ "name": "project_invite_role_id_project_role_id_fk",+ "tableFrom": "project_invite",+ "tableTo": "project_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_invite_invited_by_user_id_user_id_fk": {+ "name": "project_invite_invited_by_user_id_user_id_fk",+ "tableFrom": "project_invite",+ "tableTo": "user",+ "columnsFrom": [+ "invited_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_invite_accepted_by_user_id_user_id_fk": {+ "name": "project_invite_accepted_by_user_id_user_id_fk",+ "tableFrom": "project_invite",+ "tableTo": "user",+ "columnsFrom": [+ "accepted_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_invite_token_unique": {+ "name": "project_invite_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "project_invite_role_check": {+ "name": "project_invite_role_check",+ "value": "\"project_invite\".\"role\" IN ('owner', 'member')"+ },+ "project_invite_status_check": {+ "name": "project_invite_status_check",+ "value": "\"project_invite\".\"status\" IN ('pending', 'accepted', 'rejected')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_member": {+ "name": "project_member",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "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'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'invite'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_member_user_idx": {+ "name": "project_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_member_project_id_project_id_fk": {+ "name": "project_member_project_id_project_id_fk",+ "tableFrom": "project_member",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_member_user_id_user_id_fk": {+ "name": "project_member_user_id_user_id_fk",+ "tableFrom": "project_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_member_role_id_project_role_id_fk": {+ "name": "project_member_role_id_project_role_id_fk",+ "tableFrom": "project_member",+ "tableTo": "project_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_member_project_id_user_id_pk": {+ "name": "project_member_project_id_user_id_pk",+ "columns": [+ "project_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "project_member_role_check": {+ "name": "project_member_role_check",+ "value": "\"project_member\".\"role\" IN ('owner', 'member')"+ },+ "project_member_source_check": {+ "name": "project_member_source_check",+ "value": "\"project_member\".\"source\" IN ('invite', 'scim')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_notification_setting": {+ "name": "project_notification_setting",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_notification_setting_project_id_project_id_fk": {+ "name": "project_notification_setting_project_id_project_id_fk",+ "tableFrom": "project_notification_setting",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_role": {+ "name": "project_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "permissions": {+ "name": "permissions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_role_default_uq": {+ "name": "project_role_default_uq",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"project_role\".\"is_default\"",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_role_project_idx": {+ "name": "project_role_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_role_project_id_project_id_fk": {+ "name": "project_role_project_id_project_id_fk",+ "tableFrom": "project_role",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_role_project_id_name_unique": {+ "name": "project_role_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_setting": {+ "name": "project_setting",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_setting_project_id_project_id_fk": {+ "name": "project_setting_project_id_project_id_fk",+ "tableFrom": "project_setting",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_setting_project_id_key_pk": {+ "name": "project_setting_project_id_key_pk",+ "columns": [+ "project_id",+ "key"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_view": {+ "name": "project_view",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "filters": {+ "name": "filters",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "display": {+ "name": "display",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "share_token": {+ "name": "share_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "share_extended": {+ "name": "share_extended",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_view_project_idx": {+ "name": "project_view_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_view_project_id_project_id_fk": {+ "name": "project_view_project_id_project_id_fk",+ "tableFrom": "project_view",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_view_share_token_unique": {+ "name": "project_view_share_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "share_token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_view_favorite": {+ "name": "project_view_favorite",+ "schema": "",+ "columns": {+ "view_id": {+ "name": "view_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_view_favorite_view_id_project_view_id_fk": {+ "name": "project_view_favorite_view_id_project_view_id_fk",+ "tableFrom": "project_view_favorite",+ "tableTo": "project_view",+ "columnsFrom": [+ "view_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_view_favorite_user_id_user_id_fk": {+ "name": "project_view_favorite_user_id_user_id_fk",+ "tableFrom": "project_view_favorite",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_view_favorite_view_id_user_id_pk": {+ "name": "project_view_favorite_view_id_user_id_pk",+ "columns": [+ "view_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.revision": {+ "name": "revision",+ "schema": "",+ "columns": {+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "rev": {+ "name": "rev",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "revision_project_idx": {+ "name": "revision_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "email_events": {+ "name": "email_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "telegram_events": {+ "name": "telegram_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "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": {},+ "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": "no action"+ },+ "user_notification_preference_project_id_project_id_fk": {+ "name": "user_notification_preference_project_id_project_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_pref_user_project_unique": {+ "name": "user_notification_pref_user_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_preference": {+ "name": "user_preference",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'UTC'"+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "theme": {+ "name": "theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "issue_open_mode": {+ "name": "issue_open_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'panel'"+ },+ "start_page": {+ "name": "start_page",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'work-items'"+ },+ "show_chat_by_default": {+ "name": "show_chat_by_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "issue_stats_open": {+ "name": "issue_stats_open",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "issue_stats_view": {+ "name": "issue_stats_view",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'compact'"+ },+ "issue_activity_view": {+ "name": "issue_activity_view",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'flat'"+ },+ "auto_watch": {+ "name": "auto_watch",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "hotkeys": {+ "name": "hotkeys",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "last_project_id": {+ "name": "last_project_id",+ "type": "integer",+ "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": {},+ "foreignKeys": {+ "user_preference_user_id_user_id_fk": {+ "name": "user_preference_user_id_user_id_fk",+ "tableFrom": "user_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_preference_last_project_id_project_id_fk": {+ "name": "user_preference_last_project_id_project_id_fk",+ "tableFrom": "user_preference",+ "tableTo": "project",+ "columnsFrom": [+ "last_project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "user_preference_theme_check": {+ "name": "user_preference_theme_check",+ "value": "\"user_preference\".\"theme\" IN ('light', 'dark', 'system')"+ },+ "user_preference_issue_open_mode_check": {+ "name": "user_preference_issue_open_mode_check",+ "value": "\"user_preference\".\"issue_open_mode\" IN ('panel', 'page')"+ },+ "user_preference_start_page_check": {+ "name": "user_preference_start_page_check",+ "value": "\"user_preference\".\"start_page\" IN ('inbox', 'dashboard', 'work-items', 'initiatives')"+ },+ "user_preference_issue_stats_view_check": {+ "name": "user_preference_issue_stats_view_check",+ "value": "\"user_preference\".\"issue_stats_view\" IN ('compact', 'timeline')"+ },+ "user_preference_issue_activity_view_check": {+ "name": "user_preference_issue_activity_view_check",+ "value": "\"user_preference\".\"issue_activity_view\" IN ('flat', 'grouped')"+ }+ },+ "isRLSEnabled": false+ },+ "public.user_telegram_account": {+ "name": "user_telegram_account",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_code": {+ "name": "link_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_code_expires_at": {+ "name": "link_code_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "linked_at": {+ "name": "linked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_telegram_account_chat_id_unique": {+ "name": "user_telegram_account_chat_id_unique",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_telegram_account\".\"chat_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_telegram_account_link_code_unique": {+ "name": "user_telegram_account_link_code_unique",+ "columns": [+ {+ "expression": "link_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_telegram_account\".\"link_code\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_telegram_account_user_id_user_id_fk": {+ "name": "user_telegram_account_user_id_user_id_fk",+ "tableFrom": "user_telegram_account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook": {+ "name": "webhook",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "events": {+ "name": "events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "webhook_project_idx": {+ "name": "webhook_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_project_id_project_id_fk": {+ "name": "webhook_project_id_project_id_fk",+ "tableFrom": "webhook",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook_delivery": {+ "name": "webhook_delivery",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "event_id": {+ "name": "event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_status": {+ "name": "response_status",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "response_body": {+ "name": "response_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "webhook_delivery_due_idx": {+ "name": "webhook_delivery_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"webhook_delivery\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "webhook_delivery_webhook_idx": {+ "name": "webhook_delivery_webhook_idx",+ "columns": [+ {+ "expression": "webhook_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_delivery_webhook_id_webhook_id_fk": {+ "name": "webhook_delivery_webhook_id_webhook_id_fk",+ "tableFrom": "webhook_delivery",+ "tableTo": "webhook",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.scim_group": {+ "name": "scim_group",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "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": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_group_display_name_unique": {+ "name": "scim_group_display_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "display_name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.scim_group_mapping": {+ "name": "scim_group_mapping",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "group_id": {+ "name": "group_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "scim_group_mapping_project_idx": {+ "name": "scim_group_mapping_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_mapping_group_id_scim_group_id_fk": {+ "name": "scim_group_mapping_group_id_scim_group_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "scim_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_mapping_project_id_project_id_fk": {+ "name": "scim_group_mapping_project_id_project_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_mapping_role_id_project_role_id_fk": {+ "name": "scim_group_mapping_role_id_project_role_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "project_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_group_mapping_group_id_project_id_unique": {+ "name": "scim_group_mapping_group_id_project_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "group_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "scim_group_mapping_role_check": {+ "name": "scim_group_mapping_role_check",+ "value": "\"scim_group_mapping\".\"role\" IN ('owner', 'member')"+ }+ },+ "isRLSEnabled": false+ },+ "public.scim_group_member": {+ "name": "scim_group_member",+ "schema": "",+ "columns": {+ "group_id": {+ "name": "group_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "scim_group_member_user_idx": {+ "name": "scim_group_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_member_group_id_scim_group_id_fk": {+ "name": "scim_group_member_group_id_scim_group_id_fk",+ "tableFrom": "scim_group_member",+ "tableTo": "scim_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_member_user_id_user_id_fk": {+ "name": "scim_group_member_user_id_user_id_fk",+ "tableFrom": "scim_group_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "scim_group_member_group_id_user_id_pk": {+ "name": "scim_group_member_group_id_user_id_pk",+ "columns": [+ "group_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex f1e152ff..ac8db439 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -778,6 +778,13 @@"when": 1787915227537,"tag": "0110_spooky_the_santerians","breakpoints": true+ },+ {+ "idx": 111,+ "version": "7",+ "when": 1787927286587,+ "tag": "0111_bitter_pride",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.tsindex cca538df..fa56f1ea 100644--- a/packages/db/src/schema/app.ts+++ b/packages/db/src/schema/app.ts@@ -221,11 +221,17 @@ export const projectMember = pgTable(// members page and given to agents so they can pick who to tag on an unassigned// issue. Empty string when unset.description: text('description').notNull().default(''),+ // How this membership came about. 'invite' is a person accepting an invite;+ // 'scim' is a row the SCIM group reconciliation created and therefore owns —+ // it only ever updates or removes its own rows, so a sync never undoes a+ // membership someone set up by hand.+ source: text('source').notNull().default('invite'),createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),},(t) => [primaryKey({ columns: [t.projectId, t.userId] }),check('project_member_role_check', sql`${t.role} IN ('owner', 'member')`),+ check('project_member_source_check', sql`${t.source} IN ('invite', 'scim')`),index('project_member_user_idx').on(t.userId),],);diff --git a/packages/db/src/schema/auth.ts b/packages/db/src/schema/auth.tsindex ef10d385..9f660eb2 100644--- a/packages/db/src/schema/auth.ts+++ b/packages/db/src/schema/auth.ts@@ -22,6 +22,8 @@ export const user = pgTable("user", {username: text("username").unique(),displayUsername: text("display_username"),role: text("role").default("user"),+ active: boolean("active").default(true),+ scimExternalId: text("scim_external_id"),});export const session = pgTable(diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex 20e09197..943a684d 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -1,2 +1,3 @@export * from './auth';export * from './app';+export * from './scim';diff --git a/packages/db/src/schema/scim.ts b/packages/db/src/schema/scim.tsnew file mode 100644index 00000000..ace6ffa9--- /dev/null+++ b/packages/db/src/schema/scim.ts@@ -0,0 +1,71 @@+// SCIM 2.0 provisioning tables. An identity provider pushes users and groups to+// /scim/v2 in the API; users land on the `user` table, groups land here.+import {+ check,+ index,+ integer,+ pgTable,+ primaryKey,+ serial,+ text,+ timestamp,+ unique,+ uuid,+} from 'drizzle-orm/pg-core';+import { sql } from 'drizzle-orm';+import { user } from './auth';+import { project, projectRole } from './app';++// A group as the identity provider sees it. Written only over SCIM: the group list+// and its members are the provider's, and god mode shows them read-only.+export const scimGroup = pgTable('scim_group', {+ id: uuid('id').primaryKey().defaultRandom(),+ displayName: text('display_name').notNull().unique(),+ // The provider's own id for the group, sent as `externalId` and used to find a+ // group again after it is renamed.+ externalId: text('external_id'),+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),+});++export const scimGroupMember = pgTable(+ 'scim_group_member',+ {+ groupId: uuid('group_id')+ .notNull()+ .references(() => scimGroup.id, { onDelete: 'cascade' }),+ userId: text('user_id')+ .notNull()+ .references(() => user.id, { onDelete: 'cascade' }),+ },+ (t) => [+ primaryKey({ columns: [t.groupId, t.userId] }),+ index('scim_group_member_user_idx').on(t.userId),+ ],+);++// What a group grants. A SCIM group carries only a name and a member list, so the+// instance owner declares in god mode that group X makes its members part of project+// Y at role Z. One group may map to several projects; at most one mapping per pair.+// `role_id` names the project_role a "member" joins on, and is NULL for an owner (an+// owner bypasses the permission matrix) or when the project's default role applies.+export const scimGroupMapping = pgTable(+ 'scim_group_mapping',+ {+ id: serial('id').primaryKey(),+ groupId: uuid('group_id')+ .notNull()+ .references(() => scimGroup.id, { onDelete: 'cascade' }),+ projectId: integer('project_id')+ .notNull()+ .references(() => project.id, { onDelete: 'cascade' }),+ role: text('role').notNull().default('member'),+ roleId: integer('role_id').references(() => projectRole.id, { onDelete: 'set null' }),+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),+ },+ (t) => [+ unique().on(t.groupId, t.projectId),+ check('scim_group_mapping_role_check', sql`${t.role} IN ('owner', 'member')`),+ index('scim_group_mapping_project_idx').on(t.projectId),+ ],+);