⭐️⭐️⭐️ 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(god): deactivate an account without deleting it (#536)
Pasqual Troncone8a500525f380
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.mdindex 4cf228a2..a1fdf7e7 100644--- a/apps/api/AGENTS.md+++ b/apps/api/AGENTS.md@@ -341,6 +341,13 @@ links it. The group mappings and the settings are routes of `modules/workspaces/A deactivated account (`user.active` false, written alongside `scim_user.active`) keepsits teams and projects but cannot sign in, and `isAccountDeactivated` makes`authContext`, `/me` and the MCP key check refuse what it already holds.+ God mode writes `user.active` too (`POST /god/users/:userId/deactivate` and+ `/reactivate` in `modules/god/`) while no provider manages accounts+ (`accountsManagedByScim` from `@repo/auth`), and answers 409 while one does. Deactivating+ there also deletes the account's sessions, its MCP OAuth tokens and the pending invites+ it created; its API keys are kept and answer 401 until it is reactivated. The instance+ owner and an agent's account are refused (403). The user list and detail carry+ `activeLock` (`owner`, `agent` or `scim`), the reason the switch is locked, or null.- **On, as in a hosted build, SCIM is each workspace's.** A workspace's provider decides whois in the workspace, not who has an account, so the same person can be linked by severalworkspaces. It sees the accounts it linked and the people in the workspace's teamsdiff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 180e93e3..0c9f4c5a 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -262,7 +262,8 @@ export const app = new Elysia()const session = await getSessionFromHeaders(request.headers);// 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.+ // first. Deactivation arrives over SCIM or from god mode, after the session+ // was opened.if (!session || isAccountDeactivated(session.user)) {return { authenticated: false };}diff --git a/apps/api/src/mcp/mount.ts b/apps/api/src/mcp/mount.tsindex 776e62b4..661a78d7 100644--- a/apps/api/src/mcp/mount.ts+++ b/apps/api/src/mcp/mount.ts@@ -47,8 +47,8 @@ export function mountMcp(app: any): void {try {const session = await auth.api.getSession({ headers });// 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.+ // refuses it for every planner route. Deactivation arrives over SCIM or from+ // god mode, after the key was issued.if (session && !isAccountDeactivated(session.user))return serve({ kind: 'api-key', apiKey }, session.user.id);} catch {diff --git a/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.ts b/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.tsnew file mode 100644index 00000000..11ad9fe0--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.ts@@ -0,0 +1,241 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { auth } from '@repo/auth';+import { apiKeyApi, app, authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { setupScim } from '#modules/scim/__tests__/helpers';+import { createAgentUser, setup } from '../helpers';++const PASSWORD = 'test-password-123';++async function signIn(email: string) {+ return auth.api.signInEmail({+ body: { email, password: PASSWORD },+ asResponse: true,+ });+}++const REDIRECT_URI = 'https://client.example.com/callback';+// The RFC 7636 example pair: the challenge is the S256 of the verifier.+const CODE_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';+const CODE_CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';++// The MCP OAuth token a person gets by approving a client: register, authorize with+// their session, consent, and exchange the code.+async function mcpAccessToken(cookie: string): Promise<string> {+ const registered = await app.handle(+ new Request('http://localhost/api/auth/mcp/register', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ redirect_uris: [REDIRECT_URI],+ token_endpoint_auth_method: 'none',+ client_name: 'Test client',+ }),+ }),+ );+ const clientId = ((await registered.json()) as { client_id: string }).client_id;+ const authorize = await app.handle(+ new Request(+ `http://localhost/api/auth/mcp/authorize?${new URLSearchParams({+ response_type: 'code',+ client_id: clientId,+ redirect_uri: REDIRECT_URI,+ code_challenge: CODE_CHALLENGE,+ code_challenge_method: 'S256',+ scope: 'openid',+ state: 'st',+ })}`,+ { headers: { cookie } },+ ),+ );+ const consentCode = new URL(+ authorize.headers.get('location') ?? '',+ 'http://localhost',+ ).searchParams.get('consent_code');+ const consent = await app.handle(+ new Request('http://localhost/api/auth/oauth2/consent', {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie },+ body: JSON.stringify({ accept: true, consent_code: consentCode }),+ }),+ );+ const { redirectURI } = (await consent.json()) as { redirectURI: string };+ const token = await app.handle(+ new Request('http://localhost/api/auth/mcp/token', {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ code: new URL(redirectURI).searchParams.get('code') ?? '',+ redirect_uri: REDIRECT_URI,+ client_id: clientId,+ code_verifier: CODE_VERIFIER,+ }),+ }),+ );+ return ((await token.json()) as { access_token: string }).access_token;+}++async function mcpInitialize(bearer: string) {+ return app.handle(+ new Request('http://localhost/mcp', {+ method: 'POST',+ headers: {+ authorization: `Bearer ${bearer}`,+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'test', version: '1' },+ },+ }),+ }),+ );+}++// god can deactivate an account without deleting it: its sessions are revoked, it+// cannot sign in or use its API keys, and god sees the status. Reactivating lets it back+// in with the same keys. Not for the instance owner, an agent's account, or while a SCIM+// provider manages accounts.+describe('god deactivate / reactivate', () => {+ beforeEach(resetDb);++ it('revokes the session, blocks sign-in, and reports the status', async () => {+ const { god } = await setup();+ const victim = await signUpTestUser({ team: false });+ const asVictim = authedApi(victim.cookie);++ // The account works before.+ expect((await asVictim.projects.get()).status).toBe(200);++ const deactivated = await god.api.god.users({ userId: victim.userId }).deactivate.post();+ expect(deactivated.status).toBe(200);+ expect(deactivated.data?.active).toBe(false);++ // The existing session is gone, and a fresh sign-in is refused.+ expect((await asVictim.projects.get()).status).toBe(401);+ expect((await signIn(victim.email)).status).toBe(403);++ // god sees it as inactive in the directory.+ const listed = await god.api.god.users({ userId: victim.userId }).get();+ expect(listed.data?.active).toBe(false);+ });++ it('lets the account sign in again after reactivation', async () => {+ const { god } = await setup();+ const victim = await signUpTestUser({ team: false });++ await god.api.god.users({ userId: victim.userId }).deactivate.post();+ const reactivated = await god.api.god.users({ userId: victim.userId }).reactivate.post();+ expect(reactivated.data?.active).toBe(true);++ expect((await signIn(victim.email)).status).toBe(200);+ });++ it('revokes the MCP OAuth tokens the account approved', async () => {+ const { god } = await setup();+ const victim = await signUpTestUser({ team: false });+ const accessToken = await mcpAccessToken(victim.cookie);+ expect((await mcpInitialize(accessToken)).status).toBe(200);++ await god.api.god.users({ userId: victim.userId }).deactivate.post();+ expect((await mcpInitialize(accessToken)).status).toBe(401);++ // Deleted, not merely refused: reactivating does not bring the token back.+ await god.api.god.users({ userId: victim.userId }).reactivate.post();+ expect((await mcpInitialize(accessToken)).status).toBe(401);+ });++ it('reports the status and the lock of each account in the list', async () => {+ const { god } = await setup();+ const victim = await signUpTestUser({ team: false });+ await god.api.god.users({ userId: victim.userId }).deactivate.post();++ const listed = await god.api.god.users.get({ query: { kind: 'all', page: 1, pageSize: 50 } });++ expect(listed.status).toBe(200);+ expect(listed.data!.items).toContainEqual(+ expect.objectContaining({ id: god.id, active: true, activeLock: 'owner' }),+ );+ expect(listed.data!.items).toContainEqual(+ expect.objectContaining({ id: victim.userId, active: false, activeLock: null }),+ );+ });++ it('answers 404 for an account that does not exist', async () => {+ const { god } = await setup();+ const missing = god.api.god.users({ userId: 'no-such-user' });++ expect((await missing.deactivate.post()).status).toBe(404);+ expect((await missing.reactivate.post()).status).toBe(404);+ });++ it('refuses to deactivate the instance owner', async () => {+ const { god } = await setup();+ expect((await god.api.god.users({ userId: god.id }).deactivate.post()).status).toBe(403);+ expect((await god.api.god.users({ userId: god.id }).reactivate.post()).status).toBe(403);+ expect((await god.api.god.users({ userId: god.id }).get()).data?.activeLock).toBe('owner');+ });++ it('keeps the API keys, refused while deactivated and working again once reactivated', async () => {+ const { god } = await setup();+ const victim = await signUpTestUser({ team: false });+ const created = await auth.api.createApiKey({ body: { userId: victim.userId, name: 'ci' } });++ await god.api.god.users({ userId: victim.userId }).deactivate.post();+ expect((await apiKeyApi(created.key).projects.get()).status).toBe(401);++ await god.api.god.users({ userId: victim.userId }).reactivate.post();+ expect((await apiKeyApi(created.key).projects.get()).status).toBe(200);+ });++ it("refuses to switch an agent's account", async () => {+ const { god } = await setup();+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ const botId = await createAgentUser(god, 'MKT');++ expect((await god.api.god.users({ userId: botId }).deactivate.post()).status).toBe(403);+ expect((await god.api.god.users({ userId: botId }).reactivate.post()).status).toBe(403);+ expect((await god.api.god.users({ userId: botId }).get()).data?.activeLock).toBe('agent');+ });++ it('leaves accounts to the SCIM provider while it manages them', async () => {+ const { god } = await setupScim();+ const person = await signUpTestUser({ team: false });+ const account = god.api.god.users({ userId: person.userId });++ expect((await account.get()).data?.activeLock).toBe('scim');+ expect((await account.deactivate.post()).status).toBe(409);+ expect((await account.reactivate.post()).status).toBe(409);+ expect((await account.get()).data?.active).toBe(true);+ });++ it('drops the pending invites the deactivated account created', async () => {+ const { god } = await setup();+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ const inviter = await signUpTestUser({ team: false });+ const invite = await god.api.projects({ projectKey: 'MKT' }).invites.post({+ email: inviter.email,+ role: 'owner',+ });+ await authedApi(inviter.cookie).invites({ token: invite.data!.token }).accept.post();+ await authedApi(inviter.cookie)+ .projects({ projectKey: 'MKT' })+ .invites.post({ email: '[email protected]', role: 'member' });+ const before = await god.api.projects({ projectKey: 'MKT' }).invites.get();+ expect(before.data!.filter((i) => i.email === '[email protected]')).toHaveLength(1);++ await god.api.god.users({ userId: inviter.userId }).deactivate.post();++ const pending = await god.api.projects({ projectKey: 'MKT' }).invites.get();+ expect(pending.status).toBe(200);+ expect(pending.data!.filter((i) => i.email === '[email protected]')).toHaveLength(0);+ });+});diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.tsindex 4b6a802f..6caa38bb 100644--- a/apps/api/src/modules/god/index.ts+++ b/apps/api/src/modules/god/index.ts@@ -33,7 +33,9 @@ import {listInstanceTeamProjects,listInstanceTeamMembers,listInstanceUsers,+ setInstanceUserActive,verifyInstanceUserEmail,+ type ActiveLock,} from './service';import {AuthSettingsBody,@@ -109,6 +111,16 @@ async function assertUsableSignInMethod(}}+// Deactivating the instance owner is how an instance locks itself out, and an agent's+// account follows its agent; with SCIM the identity provider decides.+function assertActiveSwitchable(lock: ActiveLock | null): void {+ if (lock === 'owner') throw new HttpError(403, 'An instance owner cannot be deactivated');+ if (lock === 'agent') throw new HttpError(403, "An agent's account follows its agent");+ if (lock === 'scim') {+ throw new HttpError(409, 'Accounts are activated and deactivated by the SCIM provider');+ }+}+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@@ -486,6 +498,51 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })},)+ .post(+ '/god/users/:userId/deactivate',+ async ({ params }) => {+ const target = await getInstanceUser(params.userId);+ if (!target) throw new HttpError(404, 'User not found');+ assertActiveSwitchable(target.activeLock);+ const updated = await setInstanceUserActive(params.userId, false);+ if (!updated) throw new HttpError(404, 'User not found');+ return updated;+ },+ {+ params: userParams,+ response: { 200: InstanceUserDetailResponse, ...errors(401, 403, 404, 409) },+ detail: {+ summary: 'Deactivate a user',+ description:+ 'Cut off an account without deleting it: end its sessions, revoke its MCP OAuth ' ++ 'tokens and pending invites, and refuse its sign-ins and API keys until it is ' ++ 'reactivated. Refused with 409 while a SCIM provider manages accounts.',+ },+ },+ )++ .post(+ '/god/users/:userId/reactivate',+ async ({ params }) => {+ const target = await getInstanceUser(params.userId);+ if (!target) throw new HttpError(404, 'User not found');+ assertActiveSwitchable(target.activeLock);+ const updated = await setInstanceUserActive(params.userId, true);+ if (!updated) throw new HttpError(404, 'User not found');+ return updated;+ },+ {+ params: userParams,+ response: { 200: InstanceUserDetailResponse, ...errors(401, 403, 404, 409) },+ detail: {+ summary: 'Reactivate a user',+ description:+ 'Lift a deactivation so the account can sign in again and its API keys work. ' ++ 'Refused with 409 while a SCIM provider manages accounts.',+ },+ },+ )+.delete('/god/users/:userId',async ({ params, query }) => {diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.tsindex d84a98ac..3e1253e4 100644--- a/apps/api/src/modules/god/model.ts+++ b/apps/api/src/modules/god/model.ts@@ -161,6 +161,8 @@ const InstanceUserResponse = t.Object({isAgent: t.Boolean(),providers: t.Array(t.String()),projectCount: t.Number(),+ active: t.Boolean(),+ activeLock: t.Nullable(t.UnionEnum(['owner', 'agent', 'scim'])),lastSeenAt: t.Nullable(t.String()),createdAt: t.String(),});diff --git a/apps/api/src/modules/god/service.ts b/apps/api/src/modules/god/service.tsindex 750d76f0..eeb3aa28 100644--- a/apps/api/src/modules/god/service.ts+++ b/apps/api/src/modules/god/service.ts@@ -2,6 +2,8 @@ import {db,user,session,+ oauthAccessToken,+ teamInvite,account,agentSkill,agentTool,@@ -33,6 +35,7 @@ import {type SQL,} from 'drizzle-orm';import type { AnyPgColumn, PgTable } from 'drizzle-orm/pg-core';+import { accountsManagedByScim } from '@repo/auth';import { iso } from '#shared/lib';import { deleteAccount } from '#shared/account-deletion';import {@@ -49,6 +52,10 @@ import type { TeamStanding } from '#modules/teams/service';// account) and across projects the caller is not a member of, which no// project-scoped store may do — every function here is behind the god guard.+// The instance owner keeps god mode; an agent's account follows its agent; with SCIM the+// identity provider decides.+export type ActiveLock = 'owner' | 'agent' | 'scim';+export interface InstanceUserRow {id: string;name: string;@@ -63,6 +70,11 @@ export interface InstanceUserRow {// The sign-in methods linked to the account ("credential", "google", …).providers: string[];projectCount: number;+ // False when the account is deactivated (user.active), by god or the instance's SCIM+ // provider: it cannot open a session until it is reactivated.+ active: boolean;+ // Why god cannot switch `active` here, or null when it can.+ activeLock: ActiveLock | null;// The start of the most recent session, or null when the user never signed in.lastSeenAt: string | null;createdAt: string;@@ -161,18 +173,28 @@ async function loadUserFacts(userIds: string[]): Promise<UserFacts> {};}-function toRow(r: UserRow, facts: UserFacts): InstanceUserRow {+function activeLockOf(role: string, isAgent: boolean, scim: boolean): ActiveLock | null {+ if (role === 'god') return 'owner';+ if (isAgent) return 'agent';+ return scim ? 'scim' : null;+}++function toRow(r: UserRow, facts: UserFacts, scim: boolean): InstanceUserRow {const lastSeen = facts.lastSeen.get(r.id) ?? null;+ const role = r.role ?? 'user';+ const isAgent = facts.agents.has(r.id);return {id: r.id,name: r.name,email: r.email,image: r.image,emailVerified: r.emailVerified,- role: r.role ?? 'user',- isAgent: facts.agents.has(r.id),+ role,+ isAgent,providers: facts.providers.get(r.id) ?? [],projectCount: facts.projectCounts.get(r.id) ?? 0,+ active: r.active !== false,+ activeLock: activeLockOf(role, isAgent, scim),lastSeenAt: lastSeen ? iso(lastSeen) : null,createdAt: iso(r.createdAt),};@@ -227,7 +249,8 @@ export async function listInstanceUsers(options: {]);const facts = await loadUserFacts(rows.map((r) => r.id));- return { items: rows.map((r) => toRow(r, facts)), total: totals[0]?.count ?? 0 };+ const scim = await accountsManagedByScim();+ return { items: rows.map((r) => toRow(r, facts, scim)), total: totals[0]?.count ?? 0 };}// One account with the projects it can reach. Returns null for an unknown id.@@ -281,7 +304,7 @@ export async function getInstanceUser(userId: string): Promise<InstanceUserDetai};});- return { ...toRow(row, facts), projects };+ return { ...toRow(row, facts, await accountsManagedByScim()), projects };}// How many owners each of the given projects has, keyed by project id.@@ -303,6 +326,28 @@ export async function deleteInstanceUser(userId: string): Promise<void> {await deleteAccount(userId);}+// Deactivates or reactivates an account without deleting it, through the same user.active+// a SCIM provider writes: the auth session hook and the request guard refuse it, API keys+// included, which therefore stay and work again once it is reactivated. Its sessions, MCP+// OAuth tokens and pending invites are dropped. Returns the updated user, or null if gone.+export async function setInstanceUserActive(+ userId: string,+ active: boolean,+): Promise<InstanceUserDetail | null> {+ if (!(await getInstanceUser(userId))) return null;+ // Marked first, so a sign-in that lands while the revocation runs is refused a session.+ await db.update(user).set({ active }).where(eq(user.id, userId));+ if (!active) {+ await db.delete(session).where(eq(session.userId, userId));+ await db.delete(oauthAccessToken).where(eq(oauthAccessToken.userId, userId));+ // Their pending invites would otherwise keep the registration gate open.+ await db+ .delete(teamInvite)+ .where(and(eq(teamInvite.invitedByUserId, userId), eq(teamInvite.status, 'pending')));+ }+ return getInstanceUser(userId);+}+// ── Project directory ────────────────────────────────────────────────────────// What a project holds, counted across its dependent tables. Read for the list anddiff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex ed3e482e..aa4d79ee 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -19,7 +19,8 @@"signIn": "تسجيل الدخول","projects": "المشاريع","lastSeen": "آخر ظهور",- "email": "البريد الإلكتروني"+ "email": "البريد الإلكتروني",+ "active": "نشط"},"registered": "انضم في {date}","roleGod": "المشرف الأعلى",@@ -30,7 +31,20 @@"verified": "موثَّق","notVerified": "غير موثَّق","open": "فتح الحساب",- "showAccess": "عرض الوصول إلى المشاريع"+ "showAccess": "عرض الوصول إلى المشاريع",+ "activeAria": "الحساب نشط: {email}",+ "activeState": {+ "on": "نشط",+ "off": "غير نشط"+ },+ "activeLock": {+ "owner": "مالك النسخة نشط دايمًا.",+ "agent": "حساب الوكيل بيمشي مع وكيله.",+ "scim": "مزوّد الهوية بتاعك (SCIM) هو اللي بيحدد الحسابات النشطة."+ },+ "deactivateTitle": "تعطيل {email}؟",+ "deactivateBody": "هيتقفل الدخول بتاعه فورًا ومش هيقدر يدخل أو يستخدم مفاتيح الـAPI لحد ما ترجّع تفعّل الحساب. هتتشال اتصالات MCP والدعوات اللي بعتها. مفيش حاجة تانية هتتمسح.",+ "deactivateConfirm": "تعطيل"},"userPanel": {"instanceOwner": "مالك النسخة",diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex 0c44247b..f52f8471 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -19,7 +19,8 @@"signIn": "Sign-in","projects": "Projects","lastSeen": "Last seen",- "email": "Email"+ "email": "Email",+ "active": "Active"},"registered": "joined {date}","roleGod": "God",@@ -30,7 +31,20 @@"verified": "Verified","notVerified": "Not verified","open": "Open account",- "showAccess": "Show project access"+ "showAccess": "Show project access",+ "activeAria": "Account active: {email}",+ "activeState": {+ "on": "Active",+ "off": "Inactive"+ },+ "activeLock": {+ "owner": "The instance owner is always active.",+ "agent": "An agent's account follows its agent.",+ "scim": "Your identity provider (SCIM) decides which accounts are active."+ },+ "deactivateTitle": "Deactivate {email}?",+ "deactivateBody": "They are signed out at once and cannot sign in or use their API keys until you turn the account back on. Their MCP connections and the invites they sent are removed. Nothing else is deleted.",+ "deactivateConfirm": "Deactivate"},"userPanel": {"instanceOwner": "Instance owner",diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.jsonindex 3a5d08bd..d0fe157f 100644--- a/apps/web/messages/es-ES/god.json+++ b/apps/web/messages/es-ES/god.json@@ -19,7 +19,8 @@"signIn": "Inicio de sesión","projects": "Proyectos","lastSeen": "Última actividad",- "email": "Correo"+ "email": "Correo",+ "active": "Activa"},"registered": "se unió el {date}","roleGod": "Dios",@@ -30,7 +31,20 @@"verified": "Verificado","notVerified": "No verificado","open": "Abrir la cuenta",- "showAccess": "Mostrar el acceso a proyectos"+ "showAccess": "Mostrar el acceso a proyectos",+ "activeAria": "Cuenta activa: {email}",+ "activeState": {+ "on": "Activa",+ "off": "Inactiva"+ },+ "activeLock": {+ "owner": "El propietario de la instancia siempre está activo.",+ "agent": "La cuenta de un agente sigue a su agente.",+ "scim": "Tu proveedor de identidad (SCIM) decide qué cuentas están activas."+ },+ "deactivateTitle": "¿Desactivar {email}?",+ "deactivateBody": "Se cierra su sesión al momento y no podrá entrar ni usar sus claves de API hasta que vuelvas a activar la cuenta. Se quitan sus conexiones MCP y las invitaciones que envió. No se borra nada más.",+ "deactivateConfirm": "Desactivar"},"userPanel": {"instanceOwner": "Propietario de la instancia",diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.jsonindex 69e0eb90..e12e550e 100644--- a/apps/web/messages/fr/god.json+++ b/apps/web/messages/fr/god.json@@ -19,7 +19,8 @@"signIn": "Connexion","projects": "Projets","lastSeen": "Dernière activité",- "email": "E-mail"+ "email": "E-mail",+ "active": "Actif"},"registered": "arrivé {date}","roleGod": "God",@@ -30,7 +31,20 @@"verified": "Vérifié","notVerified": "Non vérifié","open": "Ouvrir le compte",- "showAccess": "Afficher l'accès aux projets"+ "showAccess": "Afficher l'accès aux projets",+ "activeAria": "Compte actif : {email}",+ "activeState": {+ "on": "Actif",+ "off": "Inactif"+ },+ "activeLock": {+ "owner": "Le propriétaire de l'instance est toujours actif.",+ "agent": "Le compte d'un agent suit son agent.",+ "scim": "Votre fournisseur d'identité (SCIM) décide quels comptes sont actifs."+ },+ "deactivateTitle": "Désactiver {email} ?",+ "deactivateBody": "La personne est déconnectée immédiatement et ne peut plus se connecter ni utiliser ses clés d'API tant que vous ne réactivez pas le compte. Ses connexions MCP et les invitations qu'elle a envoyées sont supprimées. Rien d'autre n'est supprimé.",+ "deactivateConfirm": "Désactiver"},"userPanel": {"instanceOwner": "Propriétaire de l'instance",diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.jsonindex cdeb7901..ee384829 100644--- a/apps/web/messages/id/god.json+++ b/apps/web/messages/id/god.json@@ -19,7 +19,8 @@"signIn": "Masuk","projects": "Proyek","lastSeen": "Terakhir dilihat",- "email": "Email"+ "email": "Email",+ "active": "Aktif"},"registered": "bergabung {date}","roleGod": "God",@@ -30,7 +31,20 @@"verified": "Terverifikasi","notVerified": "Belum terverifikasi","open": "Buka akun",- "showAccess": "Tampilkan akses proyek"+ "showAccess": "Tampilkan akses proyek",+ "activeAria": "Akun aktif: {email}",+ "activeState": {+ "on": "Aktif",+ "off": "Nonaktif"+ },+ "activeLock": {+ "owner": "Pemilik instans selalu aktif.",+ "agent": "Akun agen mengikuti agennya.",+ "scim": "Penyedia identitas Anda (SCIM) menentukan akun mana yang aktif."+ },+ "deactivateTitle": "Nonaktifkan {email}?",+ "deactivateBody": "Orang ini langsung dikeluarkan dan tidak bisa masuk atau memakai kunci API-nya sampai Anda mengaktifkan akunnya lagi. Koneksi MCP dan undangan yang dikirimnya dihapus. Tidak ada yang lain yang dihapus.",+ "deactivateConfirm": "Nonaktifkan"},"userPanel": {"instanceOwner": "Pemilik instance",diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.jsonindex aa0b7061..613fdd65 100644--- a/apps/web/messages/pt-BR/god.json+++ b/apps/web/messages/pt-BR/god.json@@ -19,7 +19,8 @@"signIn": "Login","projects": "Projetos","lastSeen": "Visto por último",- "email": "E-mail"+ "email": "E-mail",+ "active": "Ativa"},"registered": "entrou em {date}","roleGod": "God",@@ -30,7 +31,20 @@"verified": "Verificado","notVerified": "Não verificado","open": "Abrir conta",- "showAccess": "Mostrar acesso a projetos"+ "showAccess": "Mostrar acesso a projetos",+ "activeAria": "Conta ativa: {email}",+ "activeState": {+ "on": "Ativa",+ "off": "Inativa"+ },+ "activeLock": {+ "owner": "O proprietário da instância está sempre ativo.",+ "agent": "A conta de um agente acompanha o agente.",+ "scim": "Seu provedor de identidade (SCIM) decide quais contas estão ativas."+ },+ "deactivateTitle": "Desativar {email}?",+ "deactivateBody": "A pessoa é desconectada na hora e não pode entrar nem usar suas chaves de API até você reativar a conta. As conexões MCP e os convites que ela enviou são removidos. Nada mais é excluído.",+ "deactivateConfirm": "Desativar"},"userPanel": {"instanceOwner": "Dono da instância",diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex e9b7a4b8..b72b09ed 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -19,7 +19,8 @@"signIn": "Вход","projects": "Проекты","lastSeen": "Последний визит",- "email": "Почта"+ "email": "Почта",+ "active": "Активна"},"registered": "зарегистрирован {date}","roleGod": "Администратор",@@ -30,7 +31,20 @@"verified": "Подтверждено","notVerified": "Не подтверждено","open": "Открыть аккаунт",- "showAccess": "Показать доступ к проектам"+ "showAccess": "Показать доступ к проектам",+ "activeAria": "Учётная запись активна: {email}",+ "activeState": {+ "on": "Активна",+ "off": "Неактивна"+ },+ "activeLock": {+ "owner": "Владелец экземпляра всегда активен.",+ "agent": "Учётная запись агента следует за агентом.",+ "scim": "Ваш провайдер удостоверений (SCIM) решает, какие учётные записи активны."+ },+ "deactivateTitle": "Деактивировать {email}?",+ "deactivateBody": "Сеанс сразу завершается, и войти или использовать API-ключи нельзя, пока вы снова не включите учётную запись. Подключения MCP и отправленные ею приглашения удаляются. Больше ничего не удаляется.",+ "deactivateConfirm": "Деактивировать"},"userPanel": {"instanceOwner": "Владелец инстанса",diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex e955170b..7f2a9972 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -19,7 +19,8 @@"signIn": "Вхід","projects": "Проєкти","lastSeen": "Останній візит",- "email": "Пошта"+ "email": "Пошта",+ "active": "Активний"},"registered": "зареєстровано {date}","roleGod": "Адміністратор",@@ -30,7 +31,20 @@"verified": "Підтверджено","notVerified": "Не підтверджено","open": "Відкрити акаунт",- "showAccess": "Показати доступ до проєктів"+ "showAccess": "Показати доступ до проєктів",+ "activeAria": "Обліковий запис активний: {email}",+ "activeState": {+ "on": "Активний",+ "off": "Неактивний"+ },+ "activeLock": {+ "owner": "Власник екземпляра завжди активний.",+ "agent": "Обліковий запис агента слідує за агентом.",+ "scim": "Ваш провайдер ідентичності (SCIM) вирішує, які облікові записи активні."+ },+ "deactivateTitle": "Деактивувати {email}?",+ "deactivateBody": "Сеанс одразу завершується, і увійти чи використати API-ключі не можна, доки ви знову не ввімкнете обліковий запис. Підключення MCP і надіслані ним запрошення видаляються. Більше нічого не видаляється.",+ "deactivateConfirm": "Деактивувати"},"userPanel": {"instanceOwner": "Власник інстансу",diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex 11c1c06f..fd6a8934 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -19,7 +19,8 @@"signIn": "登录方式","projects": "项目","lastSeen": "最近登录",- "email": "邮箱"+ "email": "邮箱",+ "active": "启用"},"registered": "注册于 {date}","roleGod": "实例管理员",@@ -30,7 +31,20 @@"verified": "已验证","notVerified": "未验证","open": "打开账户",- "showAccess": "查看项目权限"+ "showAccess": "查看项目权限",+ "activeAria": "账号启用:{email}",+ "activeState": {+ "on": "启用",+ "off": "停用"+ },+ "activeLock": {+ "owner": "实例所有者始终处于启用状态。",+ "agent": "代理的账号随其代理而定。",+ "scim": "由你的身份提供方(SCIM)决定哪些账号处于启用状态。"+ },+ "deactivateTitle": "停用 {email}?",+ "deactivateBody": "该用户会立即退出登录,在你重新启用账号之前无法登录,也无法使用其 API 密钥。其 MCP 连接和发出的邀请将被移除。其他内容不会被删除。",+ "deactivateConfirm": "停用"},"userPanel": {"instanceOwner": "实例管理员",diff --git a/apps/web/src/components/common/fields/OnOffStatus.tsx b/apps/web/src/components/common/fields/OnOffStatus.tsxnew file mode 100644index 00000000..d5e830cb--- /dev/null+++ b/apps/web/src/components/common/fields/OnOffStatus.tsx@@ -0,0 +1,22 @@+import { forwardRef, type ComponentProps } from 'react';+import { Check, Minus } from 'lucide-react';+import { cn } from '@/lib/utils';++// The read-only state of a switch the reader may not change: one icon and one wording+// for on and off everywhere, in place of a disabled control (apps/web/AGENTS.md).+// forwardRef + spread so it works as a Radix Tooltip `asChild` trigger.+const OnOffStatus = forwardRef<HTMLSpanElement, ComponentProps<'span'> & { on: boolean }>(+ ({ on, className, children, ...props }, ref) => (+ <span+ ref={ref}+ className={cn('flex items-center gap-1.5 text-sm text-muted-foreground', className)}+ {...props}+ >+ {on ? <Check className="size-4 text-green-500" /> : <Minus className="size-4" />}+ {children}+ </span>+ ),+);+OnOffStatus.displayName = 'OnOffStatus';++export default OnOffStatus;diff --git a/apps/web/src/features/god/components/users/GodUserActiveSwitch.test.tsx b/apps/web/src/features/god/components/users/GodUserActiveSwitch.test.tsxnew file mode 100644index 00000000..50bbc773--- /dev/null+++ b/apps/web/src/features/god/components/users/GodUserActiveSwitch.test.tsx@@ -0,0 +1,157 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { NextIntlClientProvider } from 'next-intl';+import { JSDOM } from 'jsdom';+import type { InstanceUser } from '@/lib/api/endpoints/god';+import god from '../../../../../messages/en/god.json';+import common from '../../../../../messages/en/common.json';++// Turning an account off signs the person out at once, so it asks first; turning it on+// does not. An account god cannot switch shows its state, locked.++let dom: JSDOM;+let root: Root;+let queryClient: QueryClient;+let originals: Map<string, PropertyDescriptor | undefined>;+let originalFetch: typeof fetch;+let calls: { method: string; path: string }[];++const wait = (ms = 20) => act(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));++const person = (overrides: Partial<InstanceUser> = {}) =>+ ({+ id: 'u1',+ email: '[email protected]',+ active: true,+ activeLock: null,+ ...overrides,+ }) as InstanceUser;++async function render(user: InstanceUser) {+ const { default: GodUserActiveSwitch } = await import('./GodUserActiveSwitch');+ const { TooltipProvider } = await import('@/components/ui/tooltip');+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={{ god, common }} timeZone="UTC">+ <QueryClientProvider client={queryClient}>+ <TooltipProvider>+ <GodUserActiveSwitch user={user} />+ </TooltipProvider>+ </QueryClientProvider>+ </NextIntlClientProvider>,+ ),+ );+ await wait();+}++const theSwitch = () => document.querySelector<HTMLButtonElement>('button[role="switch"]');+const dialog = () => document.querySelector('[role="alertdialog"], [role="dialog"]');++function button(label: string) {+ const result = [...document.querySelectorAll('button')].find(+ (element) => element.textContent?.trim() === label,+ );+ assert.ok(result, `Missing button: ${label}`);+ return result;+}++async function click(element: HTMLElement) {+ await act(async () => {+ element.click();+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ });+}++beforeEach(async () => {+ dom = new JSDOM('<div id="root"></div>', {+ url: 'https://planner.test/god/users',+ pretendToBeVisual: true,+ });+ dom.window.__ITSAPLAN_ENV__ = { apiUrl: 'http://api.test', privacyUrl: '', termsUrl: '' };+ const globals = {+ window: dom.window,+ document: dom.window.document,+ navigator: dom.window.navigator,+ HTMLElement: dom.window.HTMLElement,+ HTMLInputElement: dom.window.HTMLInputElement,+ HTMLFormElement: dom.window.HTMLFormElement,+ Element: dom.window.Element,+ Node: dom.window.Node,+ NodeFilter: dom.window.NodeFilter,+ CustomEvent: dom.window.CustomEvent,+ MutationObserver: dom.window.MutationObserver,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window),+ cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window),+ IS_REACT_ACT_ENVIRONMENT: true,+ };+ originals = new Map(+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),+ );+ for (const [key, value] of Object.entries(globals))+ Object.defineProperty(globalThis, key, { configurable: true, value });+ originalFetch = globalThis.fetch;+ calls = [];+ globalThis.fetch = (async (input, init) => {+ const url = new URL(String(input));+ calls.push({ method: init?.method ?? 'GET', path: url.pathname });+ return Response.json({ ...person(), active: url.pathname.endsWith('/reactivate') });+ }) as typeof fetch;+ const { createRoot } = await import('react-dom/client');+ root = createRoot(document.getElementById('root')!);+ queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+});++afterEach(async () => {+ await act(() => root.unmount());+ await wait(5);+ queryClient.clear();+ globalThis.fetch = originalFetch;+ dom.window.close();+ for (const [key, descriptor] of originals) {+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);+ else Reflect.deleteProperty(globalThis, key);+ }+});++const switchCalls = () => calls.filter((call) => /\/(de|re)activate$/.test(call.path));++describe('GodUserActiveSwitch', () => {+ it('asks before turning an account off, and only then deactivates it', async () => {+ await render(person());++ await click(theSwitch()!);+ assert.deepEqual(switchCalls(), []);+ assert.ok(dialog());+ assert.ok(document.body.textContent?.includes(god.users.deactivateBody));++ await click(button(god.users.deactivateConfirm));+ assert.deepEqual(switchCalls(), [{ method: 'POST', path: '/god/users/u1/deactivate' }]);+ });++ it('turns an account back on without asking', async () => {+ await render(person({ active: false }));+ // The switch role announces on or off; the label names the account only.+ assert.equal(theSwitch()!.getAttribute('aria-label'), 'Account active: [email protected]');+ assert.equal(theSwitch()!.getAttribute('aria-checked'), 'false');++ await click(theSwitch()!);++ assert.equal(dialog(), null);+ assert.deepEqual(switchCalls(), [{ method: 'POST', path: '/god/users/u1/reactivate' }]);+ });++ it('shows the state of an account god cannot switch, not a disabled switch', async () => {+ await render(person({ activeLock: 'scim' }));+ assert.equal(theSwitch(), null);+ assert.ok(document.body.textContent?.includes(god.users.activeState.on));++ await render(person({ active: false, activeLock: 'owner' }));+ assert.equal(theSwitch(), null);+ assert.ok(document.body.textContent?.includes(god.users.activeState.off));+ assert.deepEqual(switchCalls(), []);+ });+});diff --git a/apps/web/src/features/god/components/users/GodUserActiveSwitch.tsx b/apps/web/src/features/god/components/users/GodUserActiveSwitch.tsxnew file mode 100644index 00000000..04a75512--- /dev/null+++ b/apps/web/src/features/god/components/users/GodUserActiveSwitch.tsx@@ -0,0 +1,59 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import type { InstanceUser } from '@/lib/api/endpoints/god';+import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';+import OnOffStatus from '@/components/common/fields/OnOffStatus';+import { Switch } from '@/components/ui/switch';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { useSetInstanceUserActive } from '../../services/god.service';++// Whether the account may sign in. Turning it off asks first, since it signs the person+// out at once; turning it back on does not. An account god cannot switch shows its state.+export default function GodUserActiveSwitch({ user }: { user: InstanceUser }) {+ const t = useTranslations('god.users');+ const setActive = useSetInstanceUserActive();+ const [confirming, setConfirming] = useState(false);+ const label = t('activeAria', { email: user.email });++ if (user.activeLock) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <OnOffStatus on={user.active}>+ {t(user.active ? 'activeState.on' : 'activeState.off')}+ </OnOffStatus>+ </TooltipTrigger>+ <TooltipContent>{t(`activeLock.${user.activeLock}`)}</TooltipContent>+ </Tooltip>+ );+ }++ return (+ <>+ <Switch+ checked={user.active}+ disabled={setActive.isPending}+ aria-label={label}+ onCheckedChange={(on) => {+ if (on) setActive.mutate({ userId: user.id, active: true });+ else setConfirming(true);+ }}+ />+ {confirming && (+ <ConfirmDialog+ title={t('deactivateTitle', { email: user.email })}+ confirmLabel={t('deactivateConfirm')}+ onConfirm={async () => {+ await setActive.mutateAsync({ userId: user.id, active: false });+ setConfirming(false);+ }}+ onClose={() => setConfirming(false)}+ >+ <p className="text-sm text-muted-foreground">{t('deactivateBody')}</p>+ </ConfirmDialog>+ )}+ </>+ );+}diff --git a/apps/web/src/features/god/components/users/GodUsersTable.tsx b/apps/web/src/features/god/components/users/GodUsersTable.tsxindex 8240ba22..0cd0882c 100644--- a/apps/web/src/features/god/components/users/GodUsersTable.tsx+++ b/apps/web/src/features/god/components/users/GodUsersTable.tsx@@ -16,6 +16,7 @@ import {TableRow,} from '@/components/ui/table';import { useProviderList } from '../../hooks/useProviderList';+import GodUserActiveSwitch from './GodUserActiveSwitch';// The account list. A row (or the pencil in its Actions cell) opens the account in// the side panel, where the email can be confirmed and the account deleted.@@ -33,13 +34,14 @@ export default function GodUsersTable({return (<Table className="min-w-[900px] table-fixed"><colgroup>- <col className="w-[30%]" />+ <col className="w-[27%]" /><col className="w-[12%]" />- <col className="w-[15%]" />- <col className="w-[9%]" />- <col className="w-[13%]" />- <col className="w-[13%]" />+ <col className="w-[14%]" /><col className="w-[8%]" />+ <col className="w-[12%]" />+ <col className="w-[12%]" />+ <col className="w-[8%]" />+ <col className="w-[7%]" /></colgroup><TableHeader><TableRow className="hover:bg-transparent">@@ -61,6 +63,9 @@ export default function GodUsersTable({<TableHead className="text-xs font-medium text-muted-foreground">{t('columns.email')}</TableHead>+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.active')}+ </TableHead><TableHead className="text-right text-xs font-medium text-muted-foreground">{tCommon('actions')}</TableHead>@@ -134,6 +139,10 @@ export default function GodUsersTable({)}</TableCell>+ <TableCell className="px-3 py-3 align-top" onClick={(e) => e.stopPropagation()}>+ <GodUserActiveSwitch user={u} />+ </TableCell>+<TableCell className="px-3 py-3 text-right align-top"><Buttonvariant="ghost"diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.tsindex 8eaa5b01..a5b43490 100644--- a/apps/web/src/features/god/services/god.service.ts+++ b/apps/web/src/features/god/services/god.service.ts@@ -37,6 +37,7 @@ import {getInstanceStorageSettings,updateInstanceStorageSettings,listInstanceUsers,+ setInstanceUserActive,getInstanceUser,deleteInstanceUser,listInstanceProjects,@@ -271,6 +272,18 @@ export function useInstanceProjectQuery(projectId: number) {});}+export function useSetInstanceUserActive() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: ({ userId, active }: { userId: string; active: boolean }) =>+ setInstanceUserActive(userId, active),+ onSuccess: (data) => {+ qc.setQueryData(qk.instanceUser(data.id), data);+ void qc.invalidateQueries({ queryKey: qk.anyInstanceUsers });+ },+ });+}+export function useVerifyInstanceUserEmail() {const qc = useQueryClient();return useMutation({diff --git a/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsx b/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsxindex 355faa6b..49cd1a18 100644--- a/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsx+++ b/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsx@@ -1,21 +1,16 @@'use client';import { useTranslations } from 'next-intl';-import { Check, Minus } from 'lucide-react';import { useTeam, useTeamProjectOptionsQuery, useUpdateTeamMcp } from '@/services/teams.service';import SectionPageView from '@/components/common/page/SectionPageView';import ListSkeleton from '@/components/common/skeleton/ListSkeleton';import { Switch } from '@/components/ui/switch';+import OnOffStatus from '@/components/common/fields/OnOffStatus';import McpConnectionGuide from '@/features/mcp/components/McpConnectionGuide';function McpStatus({ on }: { on: boolean }) {const t = useTranslations('teams.mcp');- return (- <span className="flex items-center gap-1.5 text-sm text-muted-foreground">- {on ? <Check className="size-4 text-green-500" /> : <Minus className="size-4" />}- {t(on ? 'statusOn' : 'statusOff')}- </span>- );+ return <OnOffStatus on={on}>{t(on ? 'statusOn' : 'statusOff')}</OnOffStatus>;}// The team's MCP settings: the switch that opens the team to MCP clients at all, anddiff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.tsindex 340570d0..77bfe872 100644--- a/apps/web/src/lib/api/endpoints/god.ts+++ b/apps/web/src/lib/api/endpoints/god.ts@@ -142,6 +142,9 @@ export interface InstanceUser {isAgent: boolean;providers: string[];projectCount: number;+ active: boolean;+ // Why god cannot switch `active`, or null when it can.+ activeLock: 'owner' | 'agent' | 'scim' | null;lastSeenAt: string | null;createdAt: string;}@@ -316,6 +319,11 @@ export const listInstanceUsers = (export const getInstanceUser = (userId: string) =>request<InstanceUserDetail>(`/god/users/${userId}`);+export const setInstanceUserActive = (userId: string, active: boolean) =>+ request<InstanceUserDetail>(`/god/users/${userId}/${active ? 'reactivate' : 'deactivate'}`, {+ method: 'POST',+ });+export const verifyInstanceUserEmail = (userId: string) =>request<InstanceUserDetail>(`/god/users/${userId}/verify-email`, { method: 'POST' });diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex d56bdff7..5ede658d 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -144,7 +144,10 @@ What a provider says about a person is kept per workspace in `scim_user`, writte`apps/api`. How far it reaches is `workspaceScim()`, which a hosted build turns on with`setWorkspaceScim()`. Off, as on a self-hosted instance, SCIM is the instance's: only theinstance workspace's token opens it, and it also writes `active`, one more-`additionalField` on the user table (nullable, so every check is `active !== false`). An+`additionalField` on the user table (nullable, so every check is `active !== false`).+God mode writes `active` too, from the users table, while no provider manages accounts+(`accountsManagedByScim`: SCIM per workspace, or the instance workspace's SCIM set up with+a token); while one does, `apps/api` answers god's switch with 409. Anaccount with `active` false (`isAccountDeactivated`) is refused at sign-in by the`session.create.before` hook with `ACCOUNT_DEACTIVATED`, which covers every sign-in methodat once; `apps/api` refuses the sessions and keys it already holds. On, a workspace'sdiff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex c609a342..a373fa22 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -684,8 +684,8 @@ 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.+ // passkey, Google and OIDC. Deactivation arrives over SCIM or from god mode;+ // apps/api refuses the sessions that are already open.before: async (session) => {const [account] = await db.select({ active: schema.user.active })@@ -886,6 +886,7 @@ export {setWorkspaceScim,workspaceScim,isAccountDeactivated,+ accountsManagedByScim,} from './instance';export type {RegistrationMode,diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.tsindex 35de6a22..b4a2b092 100644--- a/packages/auth/src/instance.ts+++ b/packages/auth/src/instance.ts@@ -411,6 +411,15 @@ export function isAccountDeactivated(account: { active?: boolean | null }): boolreturn !scimPerWorkspace && account.active === false;}+// Whether an identity provider decides which accounts are active, so god does not: SCIM+// per workspace, where a deactivation has no effect, or the instance workspace's SCIM set+// up with a token, the same condition under which verifyScimToken opens /scim/v2.+export async function accountsManagedByScim(): Promise<boolean> {+ if (scimPerWorkspace) return true;+ const config = await getScimConfig(await instanceWorkspaceId(db));+ return config.enabled && config.token.length > 0;+}+// A token reads scim_<workspaceId>_<secret>, so the workspace it opens is found// without trying the token of every workspace. A token issued before workspaces// existed reads scim_<secret> and belongs to the instance workspace.