Skip to content

⭐️⭐️⭐️ 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.

feat: limit new accounts to allowed email domains (#567)

Croffba76b9204148
diff --git a/.env.example b/.env.example
index aca1d4d8..4ad499d7 100644
--- a/.env.example
+++ b/.env.example
@@ -53,6 +53,10 @@ API_PORT=3000
# Upgrade without a dump — for an operator who backs up by other means.
# SKIP_PRE_MIGRATION_BACKUP=1
+# ── Migrations of an extending build ──
+# A folder of a build's own migrations, which the migrate step applies after the core's.
+# BUILD_MIGRATIONS_DIR=
+
# ── S3 object store: RustFS (issue attachments; metadata stays in the DB) ──
# Leave S3_* unset to disable uploads. The keys double as RustFS root credentials;
# the secret must be >= 8 chars. Upload limits are DB settings (god mode), not env.
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index e2dbdacd..eb105a1c 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -167,6 +167,10 @@ Enforced declaratively through macros, never imperative calls in handlers.
last-owner check. An expired invite gives way: inviting the address again, or
renewing it (`.../invites/:inviteId/renew`), replaces it with a new invite under a new
link. A link is never reissued, and an expired one is neither accepted nor mailed.
+ An address takes an invite only where the installed policy admits it
+ (`invites/email-policy.ts`, 400 `EMAIL_DOMAIN_NOT_ALLOWED`): by default, one with an
+ account always and one without only if it could register. A build that lets a
+ workspace keep domains of its own calls `setInviteEmailPolicy` with a check against them.
`members/` removes (last owner protected).
- The member list of a project is governed by its role matrix **or** by the team that
owns it: `memberAdmin: ["members_manage", "<action>"]` passes an owner or manager of
@@ -359,6 +363,16 @@ links it. The group mappings and the settings are routes of `modules/workspaces/
workspaces. It sees the accounts it linked and the people in the workspace's teams
(`inWorkspace` in `service.ts`), a name or address it sends is accepted and the account
keeps its own, and a group maps to projects of its workspace only.
+- **On, with the instance's beside it** (`setInstanceScimBeside()` from `@repo/auth`), for
+ a build where one organisation runs the instance: the instance workspace's provider acts
+ as when SCIM is the instance's, every other workspace's as when it is each workspace's.
+ `instanceScimWorkspace()` names the workspace whose provider acts on the whole instance,
+ or null, and `actsOnInstance` in `service.ts` is what the routes ask. The instance's
+ groups grant nothing in a workspace that set up SCIM of its own
+ (`workspacesWithOwnScim`): `reconcile.ts` leaves them out there, the mapping picker
+ leaves its projects out, and turning that workspace's SCIM on or off reconciles its
+ mapped projects (`reconcileWorkspaceGrants` in `workspaces/scim.ts`). That provider's
+ settings stay the instance owner's (`workspaceScim` guard).
A create first asks the installed policy whether the workspace may provision the address
(`email-policy.ts`). A self-hosted instance allows any address, since only its owner sets
diff --git a/apps/api/src/__tests__/integration/auth-extensions.test.ts b/apps/api/src/__tests__/integration/auth-extensions.test.ts
new file mode 100644
index 00000000..dfabefe4
--- /dev/null
+++ b/apps/api/src/__tests__/integration/auth-extensions.test.ts
@@ -0,0 +1,29 @@
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { auth, setAuthSettings, setRegistrationAdmission } from '@repo/auth';
+import { extendAuth } from '@repo/auth/extensions';
+import { openMagicLink, signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+// What a build adds to better-auth: plugins before the instance is first used, and its
+// say on an account the registration gate would refuse.
+
+describe('auth extensions', () => {
+ beforeEach(resetDb);
+ afterEach(() => setRegistrationAdmission());
+
+ it('refuses a plugin once the instance has been used', () => {
+ expect(auth.api).toBeDefined();
+ expect(() => extendAuth({ plugins: [] })).toThrow();
+ });
+
+ it('lets an admitted account past a closed instance', async () => {
+ await signUpTestUser({ name: 'Owner' });
+ await setAuthSettings({ registration: 'closed' });
+ setRegistrationAdmission(async (email) => email.endsWith('@company.com'));
+
+ const admitted = await openMagicLink('[email protected]', 'magic-admitted');
+ expect(admitted.searchParams.get('error')).toBeNull();
+ const refused = await openMagicLink('[email protected]', 'magic-refused');
+ expect(refused.searchParams.get('error')).toBe('REGISTRATION_CLOSED');
+ });
+});
diff --git a/apps/api/src/__tests__/integration/email-domains.test.ts b/apps/api/src/__tests__/integration/email-domains.test.ts
new file mode 100644
index 00000000..09ae4d28
--- /dev/null
+++ b/apps/api/src/__tests__/integration/email-domains.test.ts
@@ -0,0 +1,105 @@
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { auth, setAuthSettings, setRegistrationEmailPolicy } from '@repo/auth';
+import { setInviteEmailPolicy } from '#modules/invites/email-policy';
+import { authedApi } from '#tests/helpers/app';
+import { openMagicLink, signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+// The allowed email domains of the instance: a new account's address must be at one of
+// them, on every way in, and an address that could not register takes no invite.
+
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ await setAuthSettings({ allowedEmailDomains: ['company.com'] });
+ return { asOwner };
+}
+
+const signUp = (email: string) =>
+ auth.api.signUpEmail({
+ body: { email, password: 'test-password-123', name: 'Newcomer' },
+ asResponse: true,
+ });
+
+async function refusalCode(promise: Promise<unknown>): Promise<string | null> {
+ try {
+ await promise;
+ return null;
+ } catch (err) {
+ return (err as { body?: { code?: string } }).body?.code ?? 'unknown';
+ }
+}
+
+describe('allowed email domains', () => {
+ beforeEach(resetDb);
+ afterEach(() => {
+ setRegistrationEmailPolicy();
+ setInviteEmailPolicy();
+ });
+
+ it('admits an address at a listed domain, in any case', async () => {
+ await setup();
+ expect((await signUp('[email protected]')).status).toBe(200);
+ });
+
+ it('refuses the email form for an address at another domain', async () => {
+ await setup();
+ expect(await refusalCode(signUp('[email protected]'))).toBe(
+ 'EMAIL_DOMAIN_NOT_ALLOWED',
+ );
+ expect(await refusalCode(signUp('[email protected]'))).toBe('EMAIL_DOMAIN_NOT_ALLOWED');
+ });
+
+ it('refuses a magic link for an address at another domain', async () => {
+ await setup();
+ const location = await openMagicLink('[email protected]', 'magic-outside');
+ expect(location.searchParams.get('error')).toBe('EMAIL_DOMAIN_NOT_ALLOWED');
+ });
+
+ it('refuses to invite an address with no account at another domain', async () => {
+ const { asOwner } = await setup();
+ const res = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ expect(res.status).toBe(400);
+ expect((res.error?.value as { code?: string }).code).toBe('EMAIL_DOMAIN_NOT_ALLOWED');
+ });
+
+ it('invites an account that already exists at another domain', async () => {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ await signUpTestUser({ email: '[email protected]' });
+ await setAuthSettings({ allowedEmailDomains: ['company.com'] });
+ const res = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ expect(res.status).toBe(201);
+ });
+
+ it('saves only lowercase domains in god mode', async () => {
+ const { asOwner } = await setup();
+ const settings = asOwner.god['auth-settings'];
+ expect((await settings.put({ allowedEmailDomains: ['Company.com'] })).status).toBe(400);
+ expect((await settings.put({ allowedEmailDomains: ['not a domain'] })).status).toBe(400);
+ const saved = await settings.put({ allowedEmailDomains: ['company.com', 'company.io'] });
+ expect(saved.data?.allowedEmailDomains).toEqual(['company.com', 'company.io']);
+ });
+
+ it('registers an address the installed policy admits', async () => {
+ await setup();
+ setRegistrationEmailPolicy(async (email) => email.endsWith('@partner.com'));
+ expect((await signUp('[email protected]')).status).toBe(200);
+ });
+
+ it('refuses an invite the installed policy refuses, to an account as well', async () => {
+ const { asOwner } = await setup();
+ await signUpTestUser({ email: '[email protected]' });
+ setInviteEmailPolicy(async () => false);
+ const res = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.ts
index 7180234e..816ca052 100644
--- a/apps/api/src/modules/god/index.ts
+++ b/apps/api/src/modules/god/index.ts
@@ -141,7 +141,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
detail: {
summary: 'Get authentication settings',
description:
- 'Get the instance registration mode, invite lifetime and email-dependent auth options.',
+ 'Get the instance registration mode, allowed email domains, invite lifetime and email-dependent auth options.',
},
},
)
@@ -170,7 +170,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
detail: {
summary: 'Update authentication settings',
description:
- 'Update the instance registration mode, invite lifetime and email-dependent auth options.',
+ 'Update the instance registration mode, allowed email domains, invite lifetime and email-dependent auth options.',
},
},
)
diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.ts
index fead6ab3..0ee1aa33 100644
--- a/apps/api/src/modules/god/model.ts
+++ b/apps/api/src/modules/god/model.ts
@@ -6,6 +6,14 @@ import { USER_KINDS } from './service';
const encryption = t.UnionEnum(['none', 'ssl', 'tls']);
+const EMAIL_DOMAIN_PATTERN = '^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9-]{2,63}$';
+
+// Lowercase domains, compared with the part of an address after the "@".
+export const EmailDomains = t.Array(t.String({ pattern: EMAIL_DOMAIN_PATTERN }), {
+ maxItems: 100,
+ uniqueItems: true,
+});
+
export const userParams = t.Object({ userId: t.String() });
export const projectParams = t.Object({ projectId: t.Numeric() });
@@ -39,6 +47,7 @@ export const AuthSettingsResponse = t.Object({
trustProviderEmails: t.Boolean(),
personalWorkspaces: t.Boolean(),
inviteTtlDays: t.Integer(),
+ allowedEmailDomains: t.Array(t.String()),
// The settings that depend on outbound email cannot be turned on without a mail
// provider, and the UI explains why.
hasEmailProvider: t.Boolean(),
@@ -58,6 +67,7 @@ export const AuthSettingsBody = t.Object({
personalWorkspaces: t.Optional(t.Boolean()),
// The cap keeps createdAt plus the lifetime inside the range a Date can hold.
inviteTtlDays: t.Optional(t.Integer({ minimum: 0, maximum: 3650 })),
+ allowedEmailDomains: t.Optional(EmailDomains),
});
export const EmailSettingsResponse = t.Object({
diff --git a/apps/api/src/modules/invites/email-policy.ts b/apps/api/src/modules/invites/email-policy.ts
new file mode 100644
index 00000000..c22de473
--- /dev/null
+++ b/apps/api/src/modules/invites/email-policy.ts
@@ -0,0 +1,27 @@
+import { registrationEmailAllowed } from '@repo/auth';
+
+export type InviteEmailPolicy = (
+ teamId: number,
+ email: string,
+ hasAccount: boolean,
+) => Promise<boolean>;
+
+const couldJoin: InviteEmailPolicy = async (_teamId, email, hasAccount) =>
+ hasAccount || registrationEmailAllowed(email);
+
+// Whether a team takes an invite for an address: one with an account always, one without
+// only if it could register. A build that lets a workspace keep domains of its own checks
+// the address against the domains of the team's workspace.
+let policy = couldJoin;
+
+export function setInviteEmailPolicy(next = couldJoin): void {
+ policy = next;
+}
+
+export function isInviteEmailAllowed(
+ teamId: number,
+ email: string,
+ hasAccount: boolean,
+): Promise<boolean> {
+ return policy(teamId, email, hasAccount);
+}
diff --git a/apps/api/src/modules/invites/index.ts b/apps/api/src/modules/invites/index.ts
index 542fbfed..ef8e5681 100644
--- a/apps/api/src/modules/invites/index.ts
+++ b/apps/api/src/modules/invites/index.ts
@@ -324,7 +324,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
{
teamManager: true,
params: teamInviteParams,
- response: { 201: InviteCreateResponse, ...errors(401, 403, 404, 409) },
+ response: { 201: InviteCreateResponse, ...errors(400, 401, 403, 404, 409) },
detail: {
summary: 'Renew an expired invite of the team',
description:
diff --git a/apps/api/src/modules/invites/service.ts b/apps/api/src/modules/invites/service.ts
index c0d71c22..28649fcb 100644
--- a/apps/api/src/modules/invites/service.ts
+++ b/apps/api/src/modules/invites/service.ts
@@ -6,6 +6,7 @@ import { getProjectAccess, getTeamAccess } from '#shared/access';
import { teamRef } from '#modules/teams/ref';
import { getMembership, type MemberRole } from '#modules/members/service';
import { assertSeatFree, getTeamMembership, runsTeam, type TeamRole } from '#modules/teams/service';
+import { isInviteEmailAllowed } from './email-policy';
// Data access for invites. An invite is a token-addressed grant of membership in a
// team, and — when it names a project — in that project too. Creating one requires
@@ -171,8 +172,15 @@ async function findAccount(email: string): Promise<{ id: string } | undefined> {
// An address already inside the team takes no invite. Accepting one rewrites the
// membership the account already holds, which is how a project's last owner would be
// demoted to member; a team member reaches a project through its member list instead.
-async function assertNotAlreadyMember(input: NewInvite, email: string): Promise<void> {
+async function assertInvitable(input: NewInvite, email: string): Promise<void> {
const account = await findAccount(email);
+ if (!(await isInviteEmailAllowed(input.teamId, email, account != null))) {
+ throw new HttpError(
+ 400,
+ 'Addresses at this domain cannot be invited here',
+ 'EMAIL_DOMAIN_NOT_ALLOWED',
+ );
+ }
if (!account) return;
if (input.projectId != null && (await getMembership(input.projectId, account.id))) {
@@ -225,7 +233,7 @@ export async function mayGrantInviteRanks(
export async function createInvite(input: NewInvite): Promise<InviteRow> {
const email = normalizeEmail(input.email);
- await assertNotAlreadyMember(input, email);
+ await assertInvitable(input, email);
// Project owners bypass roles, so an owner invite never carries a role_id.
const roleId = input.projectRole === 'member' ? input.roleId : null;
// An expired invite still holds the one pending slot per address; it gives way to the
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.ts
index 89d84724..79b09f64 100644
--- a/apps/api/src/modules/scim/__tests__/integration/scim-reconcile.test.ts
+++ b/apps/api/src/modules/scim/__tests__/integration/scim-reconcile.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, afterEach, beforeEach } from 'bun:test';
-import { eq } from 'drizzle-orm';
-import { setWorkspaceScim } from '@repo/auth';
+import { eq, inArray } from 'drizzle-orm';
+import { setInstanceScimBeside, setWorkspaceScim } from '@repo/auth';
import { createWorkspace, db, team } from '@repo/db';
import { resetDb } from '#tests/helpers/db';
import { addUser, joinProject, type Actor } from '#modules/god/__tests__/helpers';
@@ -487,6 +487,109 @@ describe('SCIM group reconciliation', () => {
});
});
+ // Beside the workspaces' own, the instance's provider still grants projects of every
+ // workspace, except one that set up SCIM of its own: its provider decides there.
+ describe("beside the workspaces' own", () => {
+ beforeEach(() => {
+ setWorkspaceScim();
+ setInstanceScimBeside();
+ });
+ afterEach(() => {
+ setWorkspaceScim(false);
+ setInstanceScimBeside(false);
+ });
+
+ it("takes the instance's groups out of a workspace with its own, and lets them back", async () => {
+ const setup = await setupScim();
+ const outsider = await addUser({ email: '[email protected]' });
+ const project = await createProject(outsider, 'Sales', 'SAL');
+ const workspaceId = await createWorkspace(db, 'Other', outsider.id);
+ await db.update(team).set({ workspaceId }).where(eq(team.id, project.teamId));
+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
+ await setup.settings.groups({ groupId }).mappings.put({
+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],
+ });
+ const memberIds = async () => (await membersOf(outsider, 'SAL')).map((m) => m.userId);
+ const options = async () =>
+ (
+ await setup.god.api.workspaces({ workspaceId: setup.workspaceId }).projects.options.get()
+ ).data!.map((o) => o.key);
+ expect(await memberIds()).toContain(ada.data!.id);
+
+ const own = outsider.api.workspaces({ workspaceId }).scim;
+ await own.token.post();
+ expect((await own.patch({ enabled: true })).status).toBe(200);
+ expect(await memberIds()).not.toContain(ada.data!.id);
+ expect(await options()).not.toContain('SAL');
+
+ await own.patch({ enabled: false });
+ expect(await memberIds()).toContain(ada.data!.id);
+ expect(await options()).toContain('SAL');
+ });
+
+ it('keeps a mapping into a workspace with its own when the group is saved again', async () => {
+ const setup = await setupScim();
+ const outsider = await addUser({ email: '[email protected]' });
+ const sales = await createProject(outsider, 'Sales', 'SAL');
+ const support = await createProject(outsider, 'Support', 'SUP');
+ const marketing = await createProject(setup.god, 'Marketing', 'MKT');
+ const workspaceId = await createWorkspace(db, 'Other', outsider.id);
+ await db
+ .update(team)
+ .set({ workspaceId })
+ .where(inArray(team.id, [sales.teamId, support.teamId]));
+ const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
+ const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
+ const map = (...projectIds: number[]) =>
+ setup.settings.groups({ groupId }).mappings.put({
+ mappings: projectIds.map((projectId) => ({
+ projectId,
+ role: 'member' as const,
+ roleId: null,
+ })),
+ });
+ const memberIds = async () => (await membersOf(outsider, 'SAL')).map((m) => m.userId);
+ await map(sales.id);
+ const own = outsider.api.workspaces({ workspaceId }).scim;
+ await own.token.post();
+ await own.patch({ enabled: true });
+
+ expect((await map(sales.id, marketing.id)).status).toBe(200);
+ expect(await memberIds()).not.toContain(ada.data!.id);
+ expect((await map(sales.id, marketing.id, support.id)).status).toBe(400);
+
+ await own.patch({ enabled: false });
+ expect(await memberIds()).toContain(ada.data!.id);
+ });
+
+ it('grants nothing to a person deactivated while SCIM was per workspace', async () => {
+ setInstanceScimBeside(false);
+ 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.settings.groups({ groupId }).mappings.put({
+ mappings: [{ projectId: project.id, role: 'member', roleId: null }],
+ });
+ const setActive = (value: boolean) =>
+ setup.scim.scim.v2
+ .Users({ id: ada.data!.id })
+ .patch(patchOps([{ op: 'replace', path: 'active', value }]));
+ const memberIds = async () => (await membersOf(setup.god, 'MKT')).map((m) => m.userId);
+ await setActive(false);
+
+ setInstanceScimBeside();
+ await setup.scim.scim.v2
+ .Groups({ id: groupId })
+ .patch(patchOps([{ op: 'replace', path: 'displayName', value: 'Engineers' }]));
+ expect(await memberIds()).not.toContain(ada.data!.id);
+
+ await setActive(true);
+ expect(await memberIds()).toContain(ada.data!.id);
+ });
+ });
+
// 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.
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.ts
index 753be08d..c4274f37 100644
--- a/apps/api/src/modules/scim/__tests__/integration/scim-users.test.ts
+++ b/apps/api/src/modules/scim/__tests__/integration/scim-users.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, beforeEach } from 'bun:test';
-import { setWorkspaceScim } from '@repo/auth';
+import { setInstanceScimBeside, setWorkspaceScim } from '@repo/auth';
import { createWorkspace, db, notificationDelivery, team, teamMember } from '@repo/db';
import { eq } from 'drizzle-orm';
import { app, authedApi } from '#tests/helpers/app';
@@ -829,4 +829,48 @@ describe('SCIM users', () => {
expect((await god.api.god.users({ userId: member.id }).get()).status).toBe(200);
});
});
+
+ // Beside the workspaces' own, the instance's provider still acts on the whole instance,
+ // and every other workspace's on its own workspace.
+ describe("beside the workspaces' own", () => {
+ beforeEach(() => {
+ setWorkspaceScim();
+ setInstanceScimBeside();
+ });
+ afterEach(() => {
+ setWorkspaceScim(false);
+ setInstanceScimBeside(false);
+ });
+
+ it("lets the instance's provider deactivate an account in any workspace", async () => {
+ const { god, scim } = await setupScim();
+ const member = await signUpTestUser({ email: '[email protected]' });
+ const [memberTeam] = (await authedApi(member.cookie).teams.get()).data!;
+ await setupOtherWorkspace(god, [memberTeam!.id]);
+ const session = authedApi(member.cookie);
+
+ const res = await scim.scim.v2
+ .Users({ id: member.userId })
+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));
+
+ expect(res.status).toBe(200);
+ expect((await session.projects.get()).status).toBe(401);
+ });
+
+ it("leaves an account signing in when another workspace's provider deactivates it", async () => {
+ const { god } = await setupScim();
+ const member = await signUpTestUser({ email: '[email protected]' });
+ const [memberTeam] = (await authedApi(member.cookie).teams.get()).data!;
+ const other = await setupOtherWorkspace(god, [memberTeam!.id]);
+
+ const res = await other.scim.scim.v2
+ .Users({ id: member.userId })
+ .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));
+
+ expect(res.status).toBe(200);
+ expect((await authedApi(member.cookie).me.get()).data).toMatchObject({
+ authenticated: true,
+ });
+ });
+ });
});
diff --git a/apps/api/src/modules/scim/index.ts b/apps/api/src/modules/scim/index.ts
index e0d30733..b99facde 100644
--- a/apps/api/src/modules/scim/index.ts
+++ b/apps/api/src/modules/scim/index.ts
@@ -1,5 +1,5 @@
import { Elysia, t } from 'elysia';
-import { verifyScimToken, workspaceScim } from '@repo/auth';
+import { verifyScimToken } from '@repo/auth';
import { HttpError } from '#shared/lib';
import { noContent } from '#shared/http';
import {
@@ -38,6 +38,7 @@ import {
import {
GROUP_FILTER_ATTRIBUTES,
USER_FILTER_ATTRIBUTES,
+ actsOnInstance,
createScimGroup,
createScimUser,
deleteScimGroup,
@@ -226,15 +227,15 @@ const scimHandlers = new Elysia({
'/Users/:id',
async ({ workspaceId, params, body }) => {
const doc = asDoc(body);
- const account = workspaceScim()
- ? {}
- : {
+ const account = (await actsOnInstance(workspaceId))
+ ? {
email: readAccountEmail(doc),
name: joinName(
doc.name as never,
(doc.displayName as string) || (await requireUser(workspaceId, params.id)).name,
),
- };
+ }
+ : {};
const updated = await updateScimUser(workspaceId, params.id, {
...account,
active: doc.active === undefined ? true : asBoolean(doc.active),
@@ -260,6 +261,7 @@ const scimHandlers = new Elysia({
const ops = parsePatch(body);
// The address comes from `emails` when the request carries it, as on a create.
const sendsEmails = ops.some((op) => op.path!.toLowerCase().startsWith('emails'));
+ const instanceWide = await actsOnInstance(workspaceId);
for (const op of ops) {
const path = op.path!.toLowerCase();
if (op.op === 'remove') {
@@ -275,7 +277,7 @@ const scimHandlers = new Elysia({
else if (path === 'externalid') patch.externalId = asString(op.value, 'externalId');
else if (!ACCOUNT_ATTRIBUTE.test(path)) {
throw new ScimError(400, `Attribute '${op.path}' is not writable`, 'invalidPath');
- } else if (!workspaceScim() && !(path === 'username' && sendsEmails)) {
+ } else if (instanceWide && !(path === 'username' && sendsEmails)) {
const name = patch.name ?? (await requireUser(workspaceId, params.id)).name;
Object.assign(patch, accountOp(path, op.value, name));
}
diff --git a/apps/api/src/modules/scim/reconcile.ts b/apps/api/src/modules/scim/reconcile.ts
index 7ffd5036..cd98141f 100644
--- a/apps/api/src/modules/scim/reconcile.ts
+++ b/apps/api/src/modules/scim/reconcile.ts
@@ -8,9 +8,10 @@ import {
scimUser,
teamMember,
teamWorkspaceId,
+ user,
} from '@repo/db';
-import { and, eq, isNull, or } from 'drizzle-orm';
-import { workspaceScim } from '@repo/auth';
+import { and, eq, isNull, ne, or } from 'drizzle-orm';
+import { instanceScimWorkspace, workspacesWithOwnScim } from '@repo/auth';
import { removeMember, setMembership, type MemberRole } from '#modules/members/service';
import { listSeatHolderIds } from '#modules/teams/service';
import { getLimits } from '#shared/limits';
@@ -20,7 +21,8 @@ import { getLimits } from '#shared/limits';
// 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.
+// Called after a group's members or its mappings change, a person becomes active, or a
+// workspace turns SCIM of its own on or off.
interface Desired {
role: MemberRole;
@@ -33,13 +35,31 @@ export async function reconcileProjects(projectIds: number[]): Promise<void> {
}
}
+// The group members whose mappings grant a project of this workspace, as a condition on
+// `scimGroup`, `scimUser` and `user`. A person a workspace's provider deactivated is
+// granted nothing by its groups. An account the instance's provider deactivated keeps
+// what it had: it cannot sign in, and is back where it was once reactivated. A person it
+// deactivated in `scim_user` alone, as it did while it ran per workspace, can still sign
+// in, so its groups grant them nothing. The instance's groups grant nothing in a
+// workspace that set up SCIM of its own.
+async function grantingMembers(workspaceId: number) {
+ const active = or(isNull(scimUser.active), eq(scimUser.active, true));
+ const instanceId = await instanceScimWorkspace();
+ if (instanceId === null) return active;
+ if ((await workspacesWithOwnScim()).includes(workspaceId)) {
+ return and(ne(scimGroup.workspaceId, instanceId), active);
+ }
+ return or(active, and(eq(scimGroup.workspaceId, instanceId), eq(user.active, false)));
+}
+
// 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.
-// Set up per workspace, a person the workspace's provider deactivated is granted
-// nothing by its groups. While SCIM is the instance's, a deactivated account keeps
-// what it had: it cannot sign in, and is back where it was once reactivated.
-async function desiredMembers(projectId: number): Promise<Map<string, Desired>> {
+async function desiredMembers(
+ projectId: number,
+ workspaceId: number,
+): Promise<Map<string, Desired>> {
+ const granting = await grantingMembers(workspaceId);
const rows = await db
.select({
userId: scimGroupMember.userId,
@@ -49,6 +69,7 @@ async function desiredMembers(projectId: number): Promise<Map<string, Desired>>
.from(scimGroupMapping)
.innerJoin(scimGroupMember, eq(scimGroupMember.groupId, scimGroupMapping.groupId))
.innerJoin(scimGroup, eq(scimGroup.id, scimGroupMapping.groupId))
+ .innerJoin(user, eq(user.id, scimGroupMember.userId))
.leftJoin(
scimUser,
and(
@@ -56,12 +77,7 @@ async function desiredMembers(projectId: number): Promise<Map<string, Desired>>
eq(scimUser.userId, scimGroupMember.userId),
),
)
- .where(
- and(
- eq(scimGroupMapping.projectId, projectId),
- workspaceScim() ? or(isNull(scimUser.active), eq(scimUser.active, true)) : undefined,
- ),
- )
+ .where(and(eq(scimGroupMapping.projectId, projectId), granting))
.orderBy(scimGroupMapping.id);
const desired = new Map<string, Desired>();
@@ -76,12 +92,13 @@ async function desiredMembers(projectId: number): Promise<Map<string, Desired>>
}
async function reconcileProject(projectId: number): Promise<void> {
- const desired = await desiredMembers(projectId);
const [owner] = await db
.select({ teamId: project.teamId })
.from(project)
.where(eq(project.id, projectId));
if (!owner) return;
+ const workspaceId = await teamWorkspaceId(owner.teamId, db);
+ const desired = await desiredMembers(projectId, workspaceId);
const existing = await db
.select({
userId: projectMember.userId,
@@ -95,7 +112,6 @@ async function reconcileProject(projectId: number): Promise<void> {
const byUser = new Map(existing.map((row) => [row.userId, row]));
// A seat ceiling stops the provider from adding people the workspace has no room for.
// Those already in it keep their membership and still join the project.
- const workspaceId = await teamWorkspaceId(owner.teamId, db);
const { maxSeats } = await getLimits(workspaceId);
const seats = maxSeats > 0 ? new Set(await listSeatHolderIds(workspaceId)) : new Set<string>();
// Tracked as rows change so the last-owner guard below stays correct without
diff --git a/apps/api/src/modules/scim/service.ts b/apps/api/src/modules/scim/service.ts
index 7dbad134..e6c01fc1 100644
--- a/apps/api/src/modules/scim/service.ts
+++ b/apps/api/src/modules/scim/service.ts
@@ -13,7 +13,7 @@ import {
workspaceManager,
} from '@repo/db';
import { and, eq, exists, inArray, isNotNull, notExists, or, sql } from 'drizzle-orm';
-import { generateUsername, workspaceScim } from '@repo/auth';
+import { generateUsername, instanceScimWorkspace } from '@repo/auth';
import { iso } from '#shared/lib';
import { deleteAccount } from '#shared/account-deletion';
import { countOwners } from '#modules/members/service';
@@ -26,14 +26,14 @@ import { mappedProjectIds, reconcileProjects } from './reconcile';
// bearer token opened, and what its provider says about a person — its own id for
// them and whether they are active — is kept per workspace in `scim_user`.
//
-// How far the provider reaches depends on `workspaceScim()` in @repo/auth. Off, as on
-// a self-hosted instance, SCIM is the instance owner's and acts on the whole instance,
-// through the instance workspace: the provider sees every account, keeps names and
-// addresses in step, a deactivated account cannot sign in, and a delete removes the
-// account. On, as in a hosted build, a workspace's provider decides who has the
-// workspace, not who has an account: it sees the accounts it linked and the people in
-// the workspace's teams, deactivating or deleting someone takes them out of those
-// teams, and their name, address and sign-in stay as they are.
+// How far a provider reaches depends on its workspace (`instanceScimWorkspace()` in
+// @repo/auth). The instance workspace's, on a self-hosted instance and wherever it stays
+// beside the workspaces', is the instance owner's and acts on the whole instance: it
+// sees every account, keeps names and addresses in step, a deactivated account cannot
+// sign in, and a delete removes the account. Any other workspace's, as in a hosted
+// build, decides who has the workspace, not who has an account: it sees the accounts it
+// linked and the people in the workspace's teams, deactivating or deleting someone takes
+// them out of those teams, and their name, address and sign-in stay as they are.
//
// A create for an address that has no account inserts the `user` row directly rather
// than going through better-auth's sign-up — the same way an agent's bot user is
@@ -65,10 +65,14 @@ function linkOf(workspaceId: number) {
return and(eq(scimUser.userId, user.id), eq(scimUser.workspaceId, workspaceId));
}
+export async function actsOnInstance(workspaceId: number): Promise<boolean> {
+ return workspaceId === (await instanceScimWorkspace());
+}
+
// The accounts a workspace's provider sees: the ones it wrote, and the people in the
-// workspace's teams. While SCIM is the instance's, every account.
-function inWorkspace(workspaceId: number) {
- if (!workspaceScim()) return notAnAgent;
+// workspace's teams. The instance's provider, every account.
+async function inWorkspace(workspaceId: number) {
+ if (await actsOnInstance(workspaceId)) return notAnAgent;
return and(
notAnAgent,
or(
@@ -128,19 +132,18 @@ const userColumns = {
// ── Users ─────────────────────────────────────────────────────────────────────
-function userWhere(workspaceId: number, filter: ScimFilter | null) {
- if (!filter) return inWorkspace(workspaceId);
- if (filter.attribute === 'externalid') {
- return and(inWorkspace(workspaceId), eq(scimUser.externalId, filter.value));
- }
- return and(inWorkspace(workspaceId), emailEq(filter.value));
+async function userWhere(workspaceId: number, filter: ScimFilter | null) {
+ const seen = await inWorkspace(workspaceId);
+ if (!filter) return seen;
+ if (filter.attribute === 'externalid') return and(seen, eq(scimUser.externalId, filter.value));
+ return and(seen, emailEq(filter.value));
}
export async function listScimUsers(
workspaceId: number,
options: { filter: ScimFilter | null; startIndex: number; count: number },
): Promise<{ records: ScimUserRecord[]; total: number }> {
- const where = userWhere(workspaceId, options.filter);
+ const where = await userWhere(workspaceId, options.filter);
const [rows, totals] = await Promise.all([
db
.select(userColumns)
@@ -164,7 +167,7 @@ export async function getScimUser(workspaceId: number, id: string): Promise<Scim
.select(userColumns)
.from(user)
.leftJoin(scimUser, linkOf(workspaceId))
- .where(and(eq(user.id, id), inWorkspace(workspaceId)));
+ .where(and(eq(user.id, id), await inWorkspace(workspaceId)));
return rows[0] ? toUserRecord(rows[0]) : null;
}
@@ -176,11 +179,11 @@ function assertNotGod(role: string | null, action: string): void {
}
// The workspace owner runs its SCIM provisioning and receives what a deprovisioned
-// person owned alone, so the workspace's own provider cannot take it from them. While
-// SCIM is the instance's, that owner is the instance owner, whom assertNotGod covers,
-// and nothing is handed over.
+// person owned alone, so the workspace's own provider cannot take it from them. The
+// instance's provider answers to the instance owner, whom assertNotGod covers, and
+// nothing is handed over.
async function assertNotWorkspaceOwner(workspaceId: number, userId: string): Promise<void> {
- if (!workspaceScim()) return;
+ if (await actsOnInstance(workspaceId)) return;
const [owner] = await db
.select({ userId: workspaceManager.userId })
.from(workspaceManager)
@@ -230,9 +233,9 @@ export async function createScimUser(
// An address with an account is that person: the provider links it rather than
// creating a second one, and leaves its name and username as the person set them.
- // While SCIM is the instance's, `active` is the account's own: it decides whether
- // the account signs in at all.
- const instanceWide = !workspaceScim();
+ // For the instance's provider, `active` is the account's own: it decides whether the
+ // account signs in at all.
+ const instanceWide = await actsOnInstance(workspaceId);
const userId = await db.transaction(async (tx) => {
let id = existing?.id;
if (id && instanceWide) {
@@ -265,14 +268,14 @@ export async function createScimUser(
return id;
});
if (input.active) await reconcileProjects(await groupProjectIds(workspaceId, userId));
- else if (workspaceScim()) await dropWorkspaceMemberships(workspaceId, userId);
+ else if (!instanceWide) await dropWorkspaceMemberships(workspaceId, userId);
return (await getScimUser(workspaceId, userId))!;
}
// Writes what the provider says about a person: its id for them and whether they are
-// active. While SCIM is the instance's, it writes their name and address too; set up
-// per workspace, those are the person's own, and a PUT or PATCH that carries them
-// leaves them as they are.
+// active. The instance's provider writes their name and address too; for a workspace's,
+// those are the person's own, and a PUT or PATCH that carries them leaves them as they
+// are.
export async function updateScimUser(
workspaceId: number,
id: string,
@@ -282,13 +285,14 @@ export async function updateScimUser(
.select({ role: user.role, active: scimUser.active })
.from(user)
.leftJoin(scimUser, linkOf(workspaceId))
- .where(and(eq(user.id, id), inWorkspace(workspaceId)));
+ .where(and(eq(user.id, id), await inWorkspace(workspaceId)));
if (!target) return null;
assertNotGod(target.role, 'updated');
const wasActive = target.active !== false;
const active = patch.active ?? wasActive;
if (wasActive && !active) await assertNotWorkspaceOwner(workspaceId, id);
- if (!workspaceScim()) await updateAccount(id, { ...patch, active });
+ const instanceWide = await actsOnInstance(workspaceId);
+ if (instanceWide) await updateAccount(id, { ...patch, active });
await db
.insert(scimUser)
@@ -297,7 +301,7 @@ export async function updateScimUser(
target: [scimUser.workspaceId, scimUser.userId],
set: { active, ...(patch.externalId !== undefined ? { externalId: patch.externalId } : {}) },
});
- if (wasActive && !active && workspaceScim()) await dropWorkspaceMemberships(workspaceId, id);
+ if (wasActive && !active && !instanceWide) await dropWorkspaceMemberships(workspaceId, id);
// Back in the workspace: the groups they are still in grant their projects again.
if (!wasActive && active) await reconcileProjects(await groupProjectIds(workspaceId, id));
return getScimUser(workspaceId, id);
@@ -390,21 +394,21 @@ export async function syncEmbeddedGroups(
await reconcileProjects(projectIds);
}
-// Set up per workspace, unlinks a person from the provider and takes them out of the
-// workspace: its teams, its projects and its groups. The account stays. While SCIM is
-// the instance's, removes the account, the way god mode does; deprovisioning normally
-// arrives as `active: false` instead.
+// For a workspace's provider, unlinks a person from it and takes them out of the
+// workspace: its teams, its projects and its groups. The account stays. The instance's
+// provider removes the account, the way god mode does; deprovisioning normally arrives
+// as `active: false` instead.
export async function deleteScimUser(workspaceId: number, id: string): Promise<void> {
const [target] = await db
.select({ role: user.role })
.from(user)
.leftJoin(scimUser, linkOf(workspaceId))
- .where(and(eq(user.id, id), inWorkspace(workspaceId)));
+ .where(and(eq(user.id, id), await inWorkspace(workspaceId)));
// An agent's bot user and an account outside the workspace are not part of its
// SCIM user surface at all, so they answer the same way an unknown id does.
if (!target) throw new ScimError(404, `User '${id}' not found`);
assertNotGod(target.role, 'deleted');
- if (!workspaceScim()) {
+ if (await actsOnInstance(workspaceId)) {
if (await ownsProjectAlone(id)) {
throw new ScimError(
409,
@@ -490,7 +494,7 @@ async function assertKnownMembers(workspaceId: number, ids: string[]): Promise<v
.select({ id: user.id })
.from(user)
.leftJoin(scimUser, linkOf(workspaceId))
- .where(and(inArray(user.id, ids), inWorkspace(workspaceId)));
+ .where(and(inArray(user.id, ids), await inWorkspace(workspaceId)));
const knownIds = new Set(known.map((row) => row.id));
const missing = ids.filter((id) => !knownIds.has(id));
if (missing.length > 0) {
diff --git a/apps/api/src/modules/workspaces/index.ts b/apps/api/src/modules/workspaces/index.ts
index 112d947e..590513f7 100644
--- a/apps/api/src/modules/workspaces/index.ts
+++ b/apps/api/src/modules/workspaces/index.ts
@@ -38,6 +38,7 @@ import {
import {
listWorkspaceProjectOptions,
listWorkspaceScimGroups,
+ reconcileWorkspaceGrants,
setWorkspaceScimGroupMappings,
} from './scim';
@@ -195,7 +196,10 @@ export const workspaceRoutes = new Elysia({ name: 'workspaces', detail: { tags:
if (body.enabled && !current.hasToken) {
throw new HttpError(400, 'Generate a SCIM token first');
}
- return { ...(await setScimSettings(standing.workspaceId, body)), baseUrl: SCIM_BASE_URL };
+ const settings = await setScimSettings(standing.workspaceId, body);
+ if (settings.enabled !== current.enabled)
+ await reconcileWorkspaceGrants(standing.workspaceId);
+ return { ...settings, baseUrl: SCIM_BASE_URL };
},
{
workspaceScim: true,
diff --git a/apps/api/src/modules/workspaces/scim.ts b/apps/api/src/modules/workspaces/scim.ts
index 588bbcb6..fac1ae4e 100644
--- a/apps/api/src/modules/workspaces/scim.ts
+++ b/apps/api/src/modules/workspaces/scim.ts
@@ -7,8 +7,8 @@ import {
team,
teamRole,
} from '@repo/db';
-import { and, asc, eq, inArray, sql } from 'drizzle-orm';
-import { workspaceScim } from '@repo/auth';
+import { and, asc, eq, inArray, notInArray, or, sql } from 'drizzle-orm';
+import { instanceScimWorkspace, workspacesWithOwnScim } from '@repo/auth';
import { HttpError } from '#shared/lib';
import { mappedProjectIds, reconcileProjects } from '#modules/scim/reconcile';
@@ -98,12 +98,16 @@ export async function setWorkspaceScimGroupMappings(
if (new Set(projectIds).size !== projectIds.length) {
throw new HttpError(400, 'A group can be mapped to a project only once');
}
+ const before = await mappedProjectIds(groupId);
if (projectIds.length > 0) {
+ // A mapping the group already has is kept even where it may no longer grant: the
+ // reconciliation passes over it there, and it grants again once that changes.
+ const where = await grantable(workspaceId);
const known = await db
.select({ id: project.id, teamId: project.teamId })
.from(project)
.innerJoin(team, eq(team.id, project.teamId))
- .where(and(inArray(project.id, projectIds), grantable(workspaceId)));
+ .where(and(inArray(project.id, projectIds), where && or(where, inArray(project.id, before))));
if (known.length !== projectIds.length) throw new HttpError(400, 'Unknown project');
// A role belongs to one team, so a mapping that names another team's role would
// silently grant the wrong permissions.
@@ -124,7 +128,6 @@ export async function setWorkspaceScimGroupMappings(
}
}
- const before = await mappedProjectIds(groupId);
await db.transaction(async (tx) => {
await tx.delete(scimGroupMapping).where(eq(scimGroupMapping.groupId, groupId));
if (mappings.length > 0) {
@@ -148,18 +151,19 @@ export async function setWorkspaceScimGroupMappings(
// Every project a group may grant, with the roles of the team that owns it. What the
// group mapping form fills its project and role selects from.
export async function listWorkspaceProjectOptions(workspaceId: number) {
+ const where = await grantable(workspaceId);
const [projects, roles] = await Promise.all([
db
.select({ id: project.id, key: project.key, name: project.name, teamId: project.teamId })
.from(project)
.innerJoin(team, eq(team.id, project.teamId))
- .where(grantable(workspaceId))
+ .where(where)
.orderBy(asc(project.key)),
db
.select({ id: teamRole.id, name: teamRole.name, teamId: teamRole.teamId })
.from(teamRole)
.innerJoin(team, eq(team.id, teamRole.teamId))
- .where(grantable(workspaceId))
+ .where(where)
.orderBy(asc(teamRole.id)),
]);
return projects.map(({ teamId, ...entry }) => ({
@@ -168,7 +172,22 @@ export async function listWorkspaceProjectOptions(workspaceId: number) {
}));
}
-// The teams whose projects a workspace's groups may grant, as a condition on `team`.
-function grantable(workspaceId: number) {
- return workspaceScim() ? eq(team.workspaceId, workspaceId) : undefined;
+// The teams whose projects a workspace's groups may grant, as a condition on `team`: its
+// own, or for the instance's provider every team outside a workspace with SCIM of its own.
+async function grantable(workspaceId: number) {
+ if (workspaceId !== (await instanceScimWorkspace())) return eq(team.workspaceId, workspaceId);
+ const own = await workspacesWithOwnScim();
+ return own.length > 0 ? notInArray(team.workspaceId, own) : undefined;
+}
+
+// A workspace turning its own SCIM on or off takes the instance's groups out of its
+// projects or lets them back in, so every project of it a group grants is reconciled.
+export async function reconcileWorkspaceGrants(workspaceId: number): Promise<void> {
+ const rows = await db
+ .selectDistinct({ projectId: scimGroupMapping.projectId })
+ .from(scimGroupMapping)
+ .innerJoin(project, eq(project.id, scimGroupMapping.projectId))
+ .innerJoin(team, eq(team.id, project.teamId))
+ .where(eq(team.workspaceId, workspaceId));
+ await reconcileProjects(rows.map((row) => row.projectId));
}
diff --git a/apps/api/src/shared/guards.ts b/apps/api/src/shared/guards.ts
index 74759567..5e748415 100644
--- a/apps/api/src/shared/guards.ts
+++ b/apps/api/src/shared/guards.ts
@@ -1,5 +1,5 @@
import { Elysia, type DocumentDecoration } from 'elysia';
-import { workspaceScim as isScimPerWorkspace } from '@repo/auth';
+import { instanceScimWorkspace, workspaceScim as isScimPerWorkspace } from '@repo/auth';
import { authContext } from './auth-context';
import {
requireProjectAccess,
@@ -346,7 +346,7 @@ export const guards = new Elysia({ name: 'guards' }).use(authContext).macro({
// SCIM creates accounts and attaches existing ones to the workspace, which reaches past
// the workspace to the whole instance, so only the instance owner sets it up, in a
// workspace they own, unless SCIM is set up per workspace (setWorkspaceScim in
- // @repo/auth).
+ // @repo/auth). The provider that acts on the whole instance stays the instance owner's.
workspaceScim(_enabled: boolean) {
return {
async resolve({ params, user }) {
@@ -354,11 +354,12 @@ export const guards = new Elysia({ name: 'guards' }).use(authContext).macro({
Number((params as WorkspaceIdParams).workspaceId),
user,
);
- const perWorkspace = isScimPerWorkspace();
- if (standing.role !== 'owner' || (!perWorkspace && user?.role !== 'god')) {
+ const byWorkspaceOwner =
+ isScimPerWorkspace() && standing.workspaceId !== (await instanceScimWorkspace());
+ if (standing.role !== 'owner' || (!byWorkspaceOwner && user?.role !== 'god')) {
throw new HttpError(
403,
- `Only the ${perWorkspace ? 'workspace' : 'instance'} owner sets up SCIM provisioning`,
+ `Only the ${byWorkspaceOwner ? 'workspace' : 'instance'} owner sets up SCIM provisioning`,
);
}
return { standing };
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 8255684f..b066ee01 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -18,9 +18,10 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`
nowhere else. `useWorkspaceSections(workspace, core)` returns a workspace's settings menu,
shown by `WorkspaceSectionNav`: here the core's sections as they are, while the hosted
build adds its own at any position or drops some. One it adds carries in `Component` the
- page `/workspaces/:id/:sectionId` opens. Every section names its group: an `overview`
- one sits at the top of the menu, a `settings` one in the folding Settings group below,
- each in the order given.
+ page `/workspaces/:id/:sectionId` opens; that page answers 404 only once the workspace and
+ every query in flight have loaded, so a section that waits on a query of its own opens
+ from a direct link. Every section names its group: an `overview` one sits at the top of
+ the menu, a `settings` one in the folding Settings group below, each in the order given.
`/workspaces/:id` names no section and opens the first entry of the menu, so the order
also decides the page a workspace opens on.
`NoTeamStart` is the start page of an account with no team and no workspace it owns,
@@ -33,8 +34,11 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`
some. One it adds carries in `Component` the page `/god/<slug>` opens. SCIM is set up in
god mode, for the instance workspace; the hosted build that moves it to every
workspace drops the god section and adds `WorkspaceScimSection` through
- `useWorkspaceSections`. `GodSectionExtras` renders at the end of every god section page, by
- its slug, for settings the hosted build adds to an existing section; `WorkspaceSectionExtras`
+ `useWorkspaceSections`. `SignInExtras` sits among the sign-in methods, after the
+ instance's own provider; here it adds nothing, while the hosted build offers a sign-in
+ through providers of its own. A sign-in that comes back with a code the core does not
+ know shows the text the build's messages give it under `auth.errors.codes.<code>`.
+ `GodSectionExtras` renders at the end of every god section page, by its slug, for settings the hosted build adds to an existing section; `WorkspaceSectionExtras`
does the same on a workspace's own settings pages (`general`, `managers`), with the
workspace, and its controls save themselves. `ScheduleDialog` is the dialog that creates
and edits an agent schedule: here the core's, while the hosted build opens its own with
@@ -42,7 +46,7 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`
schedule. The schedule list names such a type by the message
`settings.schedules.types.<id>`. `AgentAnalyticsExtras` renders below the panels of an
agent dashboard, a team's or a workspace's, with the scope and the window it shows;
- here a preview of the panels the hosted build and Pro add, which folds to its title and
+ here a preview of the panels a build adds, which folds to its title and
description. `cloudMessages` is the
hosted build's English, merged into the catalogue the keys are typed against (a god
section's name and blurb go under `sections.god.<slug>` like the core ones), and
diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.json
index 211d37da..95aad832 100644
--- a/apps/web/messages/ar/auth.json
+++ b/apps/web/messages/ar/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "هذا الحساب معطّل. اطلب من المسؤول إعادة تفعيله.",
"registrationClosed": "هذه النسخة لا تقبل حسابات جديدة. اطلب الوصول من المسؤول.",
"inviteOnly": "هذه النسخة تقبل المدعوّين فقط. اطلب دعوة من المسؤول.",
+ "emailDomainNotAllowed": "هذه النسخة لا تقبل إلا عناوين من نطاقات معيّنة. استخدم عنوانًا آخر أو تواصل مع المسؤول.",
"oauthClientUnknown": "التطبيق الذي يطلب الوصول غير مسجّل هنا. أزل هذا الخادم من التطبيق ثم أضفه من جديد ليُسجَّل مرة أخرى.",
"oauthRedirectUnknown": "طلب التطبيق العودة إلى عنوان لم يسجّله، لذلك أُوقف التفويض. أزل هذا الخادم من التطبيق ثم أضفه من جديد.",
"oauthClientRefused": "لا يُسمح لهذا التطبيق بالاتصال بحسابك."
diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.json
index 2375db7d..48f4bcda 100644
--- a/apps/web/messages/ar/god.json
+++ b/apps/web/messages/ar/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "مدة صلاحية الدعوات (بالأيام)",
"inviteTtlDaysHint": "بعد انقضاء هذه المدة يتوقف رابط الدعوة عن العمل، ومع التسجيل بالدعوة فقط لا يعود يسمح بالتسجيل. مع القيمة 0 لا تنتهي صلاحية الدعوات.",
"inviteTtlDaysInvalid": "أدخل عددًا صحيحًا من الأيام من 0 إلى {max}.",
+ "allowedEmailDomains": "نطاقات البريد المسموح بها",
+ "allowedEmailDomainsHint": "يمكن إنشاء حساب بعناوين من هذه النطاقات فقط. افصل بينها بفواصل، أو اترك الحقل فارغًا للسماح بأي عنوان. تحتفظ الحسابات الحالية بإمكانية الدخول.",
+ "allowedEmailDomainsInvalid": "يجب أن يكون كل نطاق بصيغة example.com، وبحد أقصى 100 نطاق.",
"modes": {
"open": {
"label": "مفتوح",
diff --git a/apps/web/messages/ar/members.json b/apps/web/messages/ar/members.json
index 7b7b6a7a..6e2804df 100644
--- a/apps/web/messages/ar/members.json
+++ b/apps/web/messages/ar/members.json
@@ -12,6 +12,7 @@
"byEmail": "دعوة بالبريد",
"inviteEmail": "دعوة {email}",
"alreadyInvited": "{email} مدعو بالفعل",
+ "domainNotAllowed": "نطاق {email} غير مسموح به في هذه النسخة",
"alreadyMember": "{email} موجود بالفعل في هذا المشروع",
"alreadyInTeam": "{email} موجود بالفعل في الفريق — اخترهم من القائمة أعلاه",
"refused": "تعذّرت إضافة {email}",
diff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.json
index 450d5fbd..7c963266 100644
--- a/apps/web/messages/ar/teams.json
+++ b/apps/web/messages/ar/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} موجود بالفعل في هذا الفريق",
"alreadyPending": "{email} لديه دعوة معلقة بالفعل",
+ "domainNotAllowed": "نطاق {email} غير مسموح به في هذه النسخة",
"refused": "تعذّرت دعوة {email}",
"roleLabel": "الدور في الفريق",
"roleHint": {
diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.json
index fd6f5bf7..ddc37bb7 100644
--- a/apps/web/messages/en/auth.json
+++ b/apps/web/messages/en/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "This account is deactivated. Ask your administrator to restore it.",
"registrationClosed": "This instance is not open for new accounts. Ask your administrator for access.",
"inviteOnly": "This instance only admits people who have been invited. Ask your administrator for an invite.",
+ "emailDomainNotAllowed": "This instance only admits addresses at certain domains. Use another address or ask your administrator.",
"oauthClientUnknown": "The app asking for access is not registered here. Remove this server from the app and add it again, so that it registers anew.",
"oauthRedirectUnknown": "The app asked to come back to an address it has not registered, so the authorization was stopped. Remove this server from the app and add it again.",
"oauthClientRefused": "This app is not allowed to connect to your account."
diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.json
index a98174f7..f91c02af 100644
--- a/apps/web/messages/en/god.json
+++ b/apps/web/messages/en/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Invite expiry (days)",
"inviteTtlDaysHint": "After this many days an invite link stops working and, with invite-only registration, no longer lets its address sign up. 0 keeps invites valid until they are answered.",
"inviteTtlDaysInvalid": "Enter a whole number of days from 0 to {max}.",
+ "allowedEmailDomains": "Allowed email domains",
+ "allowedEmailDomainsHint": "Only addresses at these domains can create an account. Separate them with commas, or leave empty to allow any. Existing accounts keep their access.",
+ "allowedEmailDomainsInvalid": "Each domain should look like example.com, with up to 100 domains.",
"modes": {
"open": {
"label": "Open",
diff --git a/apps/web/messages/en/members.json b/apps/web/messages/en/members.json
index 2b1e4385..3b17d430 100644
--- a/apps/web/messages/en/members.json
+++ b/apps/web/messages/en/members.json
@@ -12,6 +12,7 @@
"byEmail": "Invite by email",
"inviteEmail": "Invite {email}",
"alreadyInvited": "{email} is already invited",
+ "domainNotAllowed": "{email} is at a domain this instance doesn't allow",
"alreadyMember": "{email} is already in this project",
"alreadyInTeam": "{email} is already in the team — pick them from the list above",
"refused": "{email} could not be added",
diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.json
index 5a1bc9fc..d7af164f 100644
--- a/apps/web/messages/en/teams.json
+++ b/apps/web/messages/en/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} is already in this team",
"alreadyPending": "{email} already has a pending invite",
+ "domainNotAllowed": "{email} is at a domain this instance doesn't allow",
"refused": "{email} could not be invited",
"roleLabel": "Team role",
"roleHint": {
diff --git a/apps/web/messages/es-ES/auth.json b/apps/web/messages/es-ES/auth.json
index dae7ab39..437492fa 100644
--- a/apps/web/messages/es-ES/auth.json
+++ b/apps/web/messages/es-ES/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "Esta cuenta está desactivada. Pide a tu administrador que la restaure.",
"registrationClosed": "Esta instancia no admite cuentas nuevas. Pide acceso a tu administrador.",
"inviteOnly": "Esta instancia solo admite a quienes han sido invitados. Pide una invitación a tu administrador.",
+ "emailDomainNotAllowed": "Esta instancia solo admite direcciones de ciertos dominios. Usa otra dirección o pide ayuda a tu administrador.",
"oauthClientUnknown": "La aplicación que pide acceso no está registrada aquí. Quita este servidor en la aplicación y vuelve a añadirlo para que se registre de nuevo.",
"oauthRedirectUnknown": "La aplicación pidió volver a una dirección que no tiene registrada, así que se ha detenido la autorización. Quita este servidor en la aplicación y vuelve a añadirlo.",
"oauthClientRefused": "Esta aplicación no puede conectarse a tu cuenta."
diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.json
index 4c3020d5..8f493351 100644
--- a/apps/web/messages/es-ES/god.json
+++ b/apps/web/messages/es-ES/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Caducidad de las invitaciones (días)",
"inviteTtlDaysHint": "Pasado este plazo, el enlace de una invitación deja de funcionar y, con el registro por invitación, ya no permite darse de alta. Con 0, las invitaciones no caducan.",
"inviteTtlDaysInvalid": "Escribe un número entero de días entre 0 y {max}.",
+ "allowedEmailDomains": "Dominios de correo permitidos",
+ "allowedEmailDomainsHint": "Solo las direcciones de estos dominios pueden crear una cuenta. Sepáralos con comas o deja el campo vacío para permitir cualquiera. Las cuentas existentes conservan el acceso.",
+ "allowedEmailDomainsInvalid": "Cada dominio debe tener la forma example.com, con un máximo de 100.",
"modes": {
"open": {
"label": "Abierto",
diff --git a/apps/web/messages/es-ES/members.json b/apps/web/messages/es-ES/members.json
index b649ccb7..8ae02ba1 100644
--- a/apps/web/messages/es-ES/members.json
+++ b/apps/web/messages/es-ES/members.json
@@ -12,6 +12,7 @@
"byEmail": "Invitar por correo",
"inviteEmail": "Invitar a {email}",
"alreadyInvited": "{email} ya está invitado",
+ "domainNotAllowed": "El dominio de {email} no está permitido en esta instancia",
"alreadyMember": "{email} ya está en este proyecto",
"alreadyInTeam": "{email} ya está en el equipo — selecciónalo de la lista de arriba",
"refused": "No se ha podido añadir a {email}",
diff --git a/apps/web/messages/es-ES/teams.json b/apps/web/messages/es-ES/teams.json
index ad6aba20..8e5c47a3 100644
--- a/apps/web/messages/es-ES/teams.json
+++ b/apps/web/messages/es-ES/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} ya está en este equipo",
"alreadyPending": "{email} ya tiene una invitación pendiente",
+ "domainNotAllowed": "El dominio de {email} no está permitido en esta instancia",
"refused": "No se ha podido invitar a {email}",
"roleLabel": "Rol del equipo",
"roleHint": {
diff --git a/apps/web/messages/fr/auth.json b/apps/web/messages/fr/auth.json
index eb1e0aea..f3448de5 100644
--- a/apps/web/messages/fr/auth.json
+++ b/apps/web/messages/fr/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "Ce compte est désactivé. Demandez à votre administrateur de le rétablir.",
"registrationClosed": "Cette instance n'accepte pas de nouveaux comptes. Demandez l'accès à votre administrateur.",
"inviteOnly": "Cette instance n'admet que les personnes invitées. Demandez une invitation à votre administrateur.",
+ "emailDomainNotAllowed": "Cette instance n'accepte que les adresses de certains domaines. Utilisez une autre adresse ou contactez votre administrateur.",
"oauthClientUnknown": "L’application qui demande l’accès n’est pas enregistrée ici. Retirez ce serveur de l’application puis ajoutez-le de nouveau pour qu’elle s’enregistre à nouveau.",
"oauthRedirectUnknown": "L’application a demandé à revenir à une adresse qu’elle n’a pas enregistrée ; l’autorisation a donc été arrêtée. Retirez ce serveur de l’application puis ajoutez-le de nouveau.",
"oauthClientRefused": "Cette application n’est pas autorisée à se connecter à votre compte."
diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.json
index af552d9e..5fc20b6e 100644
--- a/apps/web/messages/fr/god.json
+++ b/apps/web/messages/fr/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Expiration des invitations (jours)",
"inviteTtlDaysHint": "Passé ce délai, le lien d'invitation ne fonctionne plus et, avec l'inscription sur invitation, ne permet plus de créer un compte. Avec 0, les invitations n'expirent pas.",
"inviteTtlDaysInvalid": "Saisissez un nombre entier de jours entre 0 et {max}.",
+ "allowedEmailDomains": "Domaines e-mail autorisés",
+ "allowedEmailDomainsHint": "Seules les adresses de ces domaines peuvent créer un compte. Séparez-les par des virgules ou laissez vide pour tout autoriser. Les comptes existants gardent leur accès.",
+ "allowedEmailDomainsInvalid": "Chaque domaine doit avoir la forme example.com, 100 au maximum.",
"modes": {
"open": {
"label": "Ouverte",
diff --git a/apps/web/messages/fr/members.json b/apps/web/messages/fr/members.json
index 187fa711..530298e9 100644
--- a/apps/web/messages/fr/members.json
+++ b/apps/web/messages/fr/members.json
@@ -12,6 +12,7 @@
"byEmail": "Inviter par e-mail",
"inviteEmail": "Inviter {email}",
"alreadyInvited": "{email} est déjà invité",
+ "domainNotAllowed": "Le domaine de {email} n'est pas autorisé sur cette instance",
"alreadyMember": "{email} fait déjà partie de ce projet",
"alreadyInTeam": "{email} fait déjà partie de l'équipe — sélectionnez cette personne dans la liste ci-dessus",
"refused": "{email} n'a pas pu être ajouté",
diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.json
index 5439374d..8e58d32b 100644
--- a/apps/web/messages/fr/teams.json
+++ b/apps/web/messages/fr/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} fait déjà partie de cette équipe",
"alreadyPending": "{email} a déjà une invitation en attente",
+ "domainNotAllowed": "Le domaine de {email} n'est pas autorisé sur cette instance",
"refused": "{email} n'a pas pu être invité",
"roleLabel": "Rôle dans l'équipe",
"roleHint": {
diff --git a/apps/web/messages/id/auth.json b/apps/web/messages/id/auth.json
index 3abbf4fd..b827b899 100644
--- a/apps/web/messages/id/auth.json
+++ b/apps/web/messages/id/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "Akun ini telah dinonaktifkan. Minta administrator Anda untuk memulihkannya.",
"registrationClosed": "Instance ini tidak menerima akun baru. Minta akses kepada administrator Anda.",
"inviteOnly": "Instance ini hanya menerima orang yang diundang. Minta undangan kepada administrator Anda.",
+ "emailDomainNotAllowed": "Instance ini hanya menerima alamat dari domain tertentu. Gunakan alamat lain atau hubungi administrator Anda.",
"oauthClientUnknown": "Aplikasi yang meminta akses tidak terdaftar di sini. Hapus server ini dari aplikasi lalu tambahkan lagi agar aplikasi mendaftar ulang.",
"oauthRedirectUnknown": "Aplikasi meminta kembali ke alamat yang tidak didaftarkannya, sehingga otorisasi dihentikan. Hapus server ini dari aplikasi lalu tambahkan lagi.",
"oauthClientRefused": "Aplikasi ini tidak diizinkan terhubung ke akun Anda."
diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.json
index c4bd2704..c767a42c 100644
--- a/apps/web/messages/id/god.json
+++ b/apps/web/messages/id/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Masa berlaku undangan (hari)",
"inviteTtlDaysHint": "Setelah jangka waktu ini, tautan undangan tidak berfungsi lagi dan, dengan pendaftaran khusus undangan, tidak bisa lagi dipakai untuk mendaftar. Dengan 0, undangan tidak kedaluwarsa.",
"inviteTtlDaysInvalid": "Masukkan jumlah hari berupa bilangan bulat dari 0 sampai {max}.",
+ "allowedEmailDomains": "Domain email yang diizinkan",
+ "allowedEmailDomainsHint": "Hanya alamat di domain ini yang bisa membuat akun. Pisahkan dengan koma, atau kosongkan untuk mengizinkan semua alamat. Akun yang sudah ada tetap bisa masuk.",
+ "allowedEmailDomainsInvalid": "Setiap domain harus berbentuk seperti example.com, maksimal 100 domain.",
"modes": {
"open": {
"label": "Terbuka",
diff --git a/apps/web/messages/id/members.json b/apps/web/messages/id/members.json
index a26ba96c..f875374d 100644
--- a/apps/web/messages/id/members.json
+++ b/apps/web/messages/id/members.json
@@ -12,6 +12,7 @@
"byEmail": "Undang lewat email",
"inviteEmail": "Undang {email}",
"alreadyInvited": "{email} sudah diundang",
+ "domainNotAllowed": "Domain {email} tidak diizinkan di instance ini",
"alreadyMember": "{email} sudah ada di proyek ini",
"alreadyInTeam": "{email} sudah ada di tim — pilih mereka dari daftar di atas",
"refused": "{email} tidak dapat ditambahkan",
diff --git a/apps/web/messages/id/teams.json b/apps/web/messages/id/teams.json
index 8b884664..7bc62669 100644
--- a/apps/web/messages/id/teams.json
+++ b/apps/web/messages/id/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} sudah berada di tim ini",
"alreadyPending": "{email} sudah memiliki undangan tertunda",
+ "domainNotAllowed": "Domain {email} tidak diizinkan di instance ini",
"refused": "{email} tidak dapat diundang",
"roleLabel": "Peran tim",
"roleHint": {
diff --git a/apps/web/messages/ko/auth.json b/apps/web/messages/ko/auth.json
index dc8c2927..b4e1538a 100644
--- a/apps/web/messages/ko/auth.json
+++ b/apps/web/messages/ko/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "비활성화된 계정입니다. 관리자에게 계정 복구를 요청하세요.",
"registrationClosed": "이 서버는 새 계정을 받지 않습니다. 관리자에게 접근 권한을 요청하세요.",
"inviteOnly": "이 서버는 초대받은 사람만 가입할 수 있습니다. 관리자에게 초대를 요청하세요.",
+ "emailDomainNotAllowed": "이 서버는 특정 도메인의 주소만 받습니다. 다른 주소를 사용하거나 관리자에게 문의하세요.",
"oauthClientUnknown": "접근을 요청한 앱이 여기에 등록되어 있지 않습니다. 앱에서 이 서버를 제거한 뒤 다시 추가해 새로 등록되게 하세요.",
"oauthRedirectUnknown": "앱이 등록하지 않은 주소로 돌아가려고 해서 인증이 중단되었습니다. 앱에서 이 서버를 제거한 뒤 다시 추가하세요.",
"oauthClientRefused": "이 앱은 계정에 연결할 수 없습니다."
diff --git a/apps/web/messages/ko/god.json b/apps/web/messages/ko/god.json
index 7e3bb498..5e53e606 100644
--- a/apps/web/messages/ko/god.json
+++ b/apps/web/messages/ko/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "초대 유효 기간(일)",
"inviteTtlDaysHint": "초대 링크는 이 일수가 지나면 더 이상 작동하지 않으며, 초대 전용 회원가입에서는 해당 주소로 가입할 수 없게 됩니다. 0으로 설정하면 초대에 응답할 때까지 유효합니다.",
"inviteTtlDaysInvalid": "0에서 {max} 사이의 정수 일수를 입력하세요.",
+ "allowedEmailDomains": "허용된 이메일 도메인",
+ "allowedEmailDomainsHint": "이 도메인의 주소로만 계정을 만들 수 있습니다. 쉼표로 구분하고, 비워 두면 모든 주소를 허용합니다. 기존 계정은 계속 로그인할 수 있습니다.",
+ "allowedEmailDomainsInvalid": "각 도메인은 example.com 형식이어야 하며 최대 100개까지 입력할 수 있습니다.",
"modes": {
"open": {
"label": "공개",
diff --git a/apps/web/messages/ko/members.json b/apps/web/messages/ko/members.json
index c5b61d32..4a70bf5e 100644
--- a/apps/web/messages/ko/members.json
+++ b/apps/web/messages/ko/members.json
@@ -12,6 +12,7 @@
"byEmail": "이메일로 초대",
"inviteEmail": "{email} 초대",
"alreadyInvited": "{email} 주소로 이미 초대했습니다",
+ "domainNotAllowed": "{email}의 도메인은 이 서버에서 허용되지 않습니다",
"alreadyMember": "{email} 계정은 이미 이 프로젝트의 멤버입니다",
"alreadyInTeam": "{email} 계정은 이미 팀에 있습니다. 위 목록에서 선택하세요.",
"refused": "{email} 계정을 추가할 수 없습니다",
diff --git a/apps/web/messages/ko/teams.json b/apps/web/messages/ko/teams.json
index 02244d04..cb725992 100644
--- a/apps/web/messages/ko/teams.json
+++ b/apps/web/messages/ko/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email}은(는) 이미 이 팀의 멤버입니다",
"alreadyPending": "{email}에 이미 대기 중인 초대가 있습니다",
+ "domainNotAllowed": "{email}의 도메인은 이 서버에서 허용되지 않습니다",
"refused": "{email}을(를) 초대할 수 없습니다",
"roleLabel": "팀 역할",
"roleHint": {
diff --git a/apps/web/messages/pt-BR/auth.json b/apps/web/messages/pt-BR/auth.json
index 89cc5a15..bd41025c 100644
--- a/apps/web/messages/pt-BR/auth.json
+++ b/apps/web/messages/pt-BR/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "Esta conta está desativada. Peça ao seu administrador para restaurá-la.",
"registrationClosed": "Esta instância não aceita contas novas. Peça acesso ao seu administrador.",
"inviteOnly": "Esta instância só admite pessoas convidadas. Peça um convite ao seu administrador.",
+ "emailDomainNotAllowed": "Esta instância só aceita endereços de determinados domínios. Use outro endereço ou fale com o seu administrador.",
"oauthClientUnknown": "O aplicativo que pede acesso não está registrado aqui. Remova este servidor do aplicativo e adicione-o de novo para que ele se registre novamente.",
"oauthRedirectUnknown": "O aplicativo pediu para voltar a um endereço que não registrou, então a autorização foi interrompida. Remova este servidor do aplicativo e adicione-o de novo.",
"oauthClientRefused": "Este aplicativo não tem permissão para se conectar à sua conta."
diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.json
index cf927068..0286fb46 100644
--- a/apps/web/messages/pt-BR/god.json
+++ b/apps/web/messages/pt-BR/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Validade dos convites (dias)",
"inviteTtlDaysHint": "Depois desse prazo, o link do convite deixa de funcionar e, com o cadastro somente por convite, não permite mais criar a conta. Com 0, os convites não expiram.",
"inviteTtlDaysInvalid": "Informe um número inteiro de dias entre 0 e {max}.",
+ "allowedEmailDomains": "Domínios de e-mail permitidos",
+ "allowedEmailDomainsHint": "Só endereços desses domínios podem criar uma conta. Separe-os por vírgulas ou deixe vazio para permitir qualquer um. As contas existentes mantêm o acesso.",
+ "allowedEmailDomainsInvalid": "Cada domínio deve ter o formato example.com, até 100 domínios.",
"modes": {
"open": {
"label": "Aberto",
diff --git a/apps/web/messages/pt-BR/members.json b/apps/web/messages/pt-BR/members.json
index 0ae6db50..0a3b8bcf 100644
--- a/apps/web/messages/pt-BR/members.json
+++ b/apps/web/messages/pt-BR/members.json
@@ -12,6 +12,7 @@
"byEmail": "Convidar por e-mail",
"inviteEmail": "Convidar {email}",
"alreadyInvited": "{email} já foi convidado",
+ "domainNotAllowed": "O domínio de {email} não é permitido nesta instância",
"alreadyMember": "{email} já está neste projeto",
"alreadyInTeam": "{email} já está no time — escolha-o na lista acima",
"refused": "{email} não pôde ser adicionado",
diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.json
index 331cbc07..d2318bd4 100644
--- a/apps/web/messages/pt-BR/teams.json
+++ b/apps/web/messages/pt-BR/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} já está neste time",
"alreadyPending": "{email} já tem um convite pendente",
+ "domainNotAllowed": "O domínio de {email} não é permitido nesta instância",
"refused": "{email} não pôde ser convidado",
"roleLabel": "Função no time",
"roleHint": {
diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.json
index 76f153cd..d2c495bb 100644
--- a/apps/web/messages/ru/auth.json
+++ b/apps/web/messages/ru/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "Учётная запись отключена. Обратитесь к администратору.",
"registrationClosed": "Этот инстанс не принимает новые учётные записи. Запросите доступ у администратора.",
"inviteOnly": "В этот инстанс допускаются только приглашённые. Попросите приглашение у администратора.",
+ "emailDomainNotAllowed": "Этот инстанс принимает только адреса на определённых доменах. Используйте другой адрес или обратитесь к администратору.",
"oauthClientUnknown": "Приложение, запрашивающее доступ, здесь не зарегистрировано. Удалите этот сервер в приложении и добавьте его снова, чтобы оно зарегистрировалось заново.",
"oauthRedirectUnknown": "Приложение запросило возврат на адрес, который оно не регистрировало, поэтому авторизация остановлена. Удалите этот сервер в приложении и добавьте его снова.",
"oauthClientRefused": "Этому приложению запрещено подключаться к вашему аккаунту."
diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.json
index 054e31ee..23e3f9e4 100644
--- a/apps/web/messages/ru/god.json
+++ b/apps/web/messages/ru/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Срок действия приглашений (дни)",
"inviteTtlDaysHint": "По истечении этого срока ссылка приглашения перестаёт работать и при регистрации только по приглашению больше не позволяет зарегистрироваться. При 0 приглашения не истекают.",
"inviteTtlDaysInvalid": "Введите целое число дней от 0 до {max}.",
+ "allowedEmailDomains": "Разрешённые домены почты",
+ "allowedEmailDomainsHint": "Создать учётную запись можно только с адресом на этих доменах. Перечислите их через запятую или оставьте поле пустым, чтобы разрешить любой адрес. Существующие учётные записи сохраняют доступ.",
+ "allowedEmailDomainsInvalid": "Каждый домен должен выглядеть как example.com, не больше 100 доменов.",
"modes": {
"open": {
"label": "Открытая",
diff --git a/apps/web/messages/ru/members.json b/apps/web/messages/ru/members.json
index 6ee79302..397b5d64 100644
--- a/apps/web/messages/ru/members.json
+++ b/apps/web/messages/ru/members.json
@@ -12,6 +12,7 @@
"byEmail": "Пригласить по почте",
"inviteEmail": "Пригласить {email}",
"alreadyInvited": "{email} уже приглашён",
+ "domainNotAllowed": "Домен адреса {email} не разрешён на этом инстансе",
"alreadyMember": "{email} уже в этом проекте",
"alreadyInTeam": "{email} уже в команде — выберите его в списке выше",
"refused": "Не удалось добавить {email}",
diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.json
index 3bab9f3e..d8d3828b 100644
--- a/apps/web/messages/ru/teams.json
+++ b/apps/web/messages/ru/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} уже в этой команде",
"alreadyPending": "{email} уже приглашён",
+ "domainNotAllowed": "Домен адреса {email} не разрешён на этом инстансе",
"refused": "Не удалось пригласить {email}",
"roleLabel": "Роль в команде",
"roleHint": {
diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.json
index 10e56bf3..0a71cf13 100644
--- a/apps/web/messages/uk/auth.json
+++ b/apps/web/messages/uk/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "Обліковий запис вимкнено. Зверніться до адміністратора.",
"registrationClosed": "Цей інстанс не приймає нових облікових записів. Попросіть доступ в адміністратора.",
"inviteOnly": "До цього інстансу допускаються лише запрошені. Попросіть запрошення в адміністратора.",
+ "emailDomainNotAllowed": "Цей інстанс приймає лише адреси на певних доменах. Використайте іншу адресу або зверніться до адміністратора.",
"oauthClientUnknown": "Застосунок, що запитує доступ, тут не зареєстрований. Видаліть цей сервер у застосунку й додайте його знову, щоб він зареєструвався повторно.",
"oauthRedirectUnknown": "Застосунок попросив повернутися на адресу, яку не реєстрував, тому авторизацію зупинено. Видаліть цей сервер у застосунку й додайте його знову.",
"oauthClientRefused": "Цьому застосунку не дозволено під’єднуватися до вашого облікового запису."
diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.json
index 594dfa79..51aa208f 100644
--- a/apps/web/messages/uk/god.json
+++ b/apps/web/messages/uk/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "Термін дії запрошень (дні)",
"inviteTtlDaysHint": "Після цього терміну посилання запрошення перестає працювати і, з реєстрацією лише за запрошенням, більше не дозволяє зареєструватися. При 0 запрошення не спливають.",
"inviteTtlDaysInvalid": "Введіть ціле число днів від 0 до {max}.",
+ "allowedEmailDomains": "Дозволені домени пошти",
+ "allowedEmailDomainsHint": "Створити обліковий запис можна лише з адресою на цих доменах. Перелічіть їх через кому або залиште поле порожнім, щоб дозволити будь-яку адресу. Наявні облікові записи зберігають доступ.",
+ "allowedEmailDomainsInvalid": "Кожен домен має виглядати як example.com, не більше 100 доменів.",
"modes": {
"open": {
"label": "Відкрита",
diff --git a/apps/web/messages/uk/members.json b/apps/web/messages/uk/members.json
index 488471ef..1a95b5c1 100644
--- a/apps/web/messages/uk/members.json
+++ b/apps/web/messages/uk/members.json
@@ -12,6 +12,7 @@
"byEmail": "Запросити поштою",
"inviteEmail": "Запросити {email}",
"alreadyInvited": "{email} вже запрошений",
+ "domainNotAllowed": "Домен адреси {email} не дозволений на цьому інстансі",
"alreadyMember": "{email} вже в цьому проєкті",
"alreadyInTeam": "{email} вже в команді — виберіть його у списку вище",
"refused": "Не вдалося додати {email}",
diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.json
index cc117b95..9c1a73dd 100644
--- a/apps/web/messages/uk/teams.json
+++ b/apps/web/messages/uk/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} вже в цій команді",
"alreadyPending": "{email} вже запрошений",
+ "domainNotAllowed": "Домен адреси {email} не дозволений на цьому інстансі",
"refused": "Не вдалося запросити {email}",
"roleLabel": "Роль у команді",
"roleHint": {
diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.json
index c164c89c..9abd6754 100644
--- a/apps/web/messages/zh-CN/auth.json
+++ b/apps/web/messages/zh-CN/auth.json
@@ -96,6 +96,7 @@
"accountDeactivated": "该账号已停用,请联系管理员恢复。",
"registrationClosed": "此实例不接受新账户,请联系管理员申请访问权限。",
"inviteOnly": "此实例仅限受邀用户加入,请联系管理员获取邀请。",
+ "emailDomainNotAllowed": "此实例只接受特定域名的地址。请换一个地址,或联系管理员。",
"oauthClientUnknown": "请求访问的应用未在此处注册。请在该应用中移除此服务器并重新添加,让它重新注册。",
"oauthRedirectUnknown": "该应用要求返回到一个未注册的地址,因此授权已停止。请在该应用中移除此服务器并重新添加。",
"oauthClientRefused": "此应用不允许连接到你的账户。"
diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.json
index 8d7b81c4..bf863849 100644
--- a/apps/web/messages/zh-CN/god.json
+++ b/apps/web/messages/zh-CN/god.json
@@ -193,6 +193,9 @@
"inviteTtlDays": "邀请有效期(天)",
"inviteTtlDaysHint": "超过此期限后,邀请链接将失效;在仅限邀请注册时,也无法再用它注册。设为 0 则邀请永不过期。",
"inviteTtlDaysInvalid": "请输入 0 到 {max} 之间的整数天数。",
+ "allowedEmailDomains": "允许的邮箱域名",
+ "allowedEmailDomainsHint": "只有这些域名下的地址可以创建账户。用逗号分隔;留空则允许任何地址。已有账户不受影响。",
+ "allowedEmailDomainsInvalid": "每个域名应类似 example.com,最多 100 个。",
"modes": {
"open": {
"label": "开放注册",
diff --git a/apps/web/messages/zh-CN/members.json b/apps/web/messages/zh-CN/members.json
index 022e2ef6..b8070a73 100644
--- a/apps/web/messages/zh-CN/members.json
+++ b/apps/web/messages/zh-CN/members.json
@@ -12,6 +12,7 @@
"byEmail": "通过邮箱邀请",
"inviteEmail": "邀请 {email}",
"alreadyInvited": "{email} 已被邀请",
+ "domainNotAllowed": "此实例不允许 {email} 所在的域名",
"alreadyMember": "{email} 已在此项目中",
"alreadyInTeam": "{email} 已在团队中 — 请从上方列表中选择",
"refused": "无法添加 {email}",
diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.json
index 08ef0e60..fee91b88 100644
--- a/apps/web/messages/zh-CN/teams.json
+++ b/apps/web/messages/zh-CN/teams.json
@@ -95,6 +95,7 @@
"emailPlaceholder": "[email protected]",
"alreadyMember": "{email} 已在此团队中",
"alreadyPending": "{email} 已有待处理的邀请",
+ "domainNotAllowed": "此实例不允许 {email} 所在的域名",
"refused": "无法邀请 {email}",
"roleLabel": "团队角色",
"roleHint": {
diff --git a/apps/web/src/ce/AgentAnalyticsExtras.tsx b/apps/web/src/ce/AgentAnalyticsExtras.tsx
index 9a0a7c73..957a17da 100644
--- a/apps/web/src/ce/AgentAnalyticsExtras.tsx
+++ b/apps/web/src/ce/AgentAnalyticsExtras.tsx
@@ -3,9 +3,8 @@
import type { AgentAnalyticsScope } from '@/lib/api/endpoints/agentAnalytics';
import AgentAnalyticsPreview from '@/features/agent-analytics/components/AgentAnalyticsPreview';
-// Below the panels of an agent dashboard, over the scope and the window it shows. A
-// self-hosted instance shows what the hosted build and Pro add there; they render the
-// panels themselves.
+// Below the panels of an agent dashboard, over the scope and the window it shows. Here a
+// preview of the panels a build adds there; the build renders the panels themselves.
export default function AgentAnalyticsExtras(_props: { scope: AgentAnalyticsScope; days: number }) {
return <AgentAnalyticsPreview />;
}
diff --git a/apps/web/src/ce/SignInExtras.tsx b/apps/web/src/ce/SignInExtras.tsx
new file mode 100644
index 00000000..845bae02
--- /dev/null
+++ b/apps/web/src/ce/SignInExtras.tsx
@@ -0,0 +1,7 @@
+'use client';
+
+// Among the sign-in methods, after the instance's own provider. A self-hosted instance
+// adds nothing; the hosted build offers a sign-in through providers of its own.
+export default function SignInExtras(_props: { pending: boolean }) {
+ return null;
+}
diff --git a/apps/web/src/ce/index.ts b/apps/web/src/ce/index.ts
index 009edcf6..5890930e 100644
--- a/apps/web/src/ce/index.ts
+++ b/apps/web/src/ce/index.ts
@@ -8,6 +8,7 @@ export { cloudMessages, loadCloudMessages } from './messages';
export { default as NoTeamStart } from './NoTeamStart';
export { default as ScheduleDialog } from './ScheduleDialog';
export { default as ShellNotice } from './ShellNotice';
+export { default as SignInExtras } from './SignInExtras';
export { default as useWorkspaceSections } from './useWorkspaceSections';
export { default as WorkspaceRailActions } from './WorkspaceRailActions';
export { default as WorkspaceSectionExtras } from './WorkspaceSectionExtras';
diff --git a/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsx b/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsx
index 525053a1..fbe83e31 100644
--- a/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsx
+++ b/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsx
@@ -14,8 +14,7 @@ const PANELS = ['byPerson', 'byTrigger', 'bySchedule', 'tools', 'latency'] as co
// still, so they do not read as a panel that is loading.
const BARS = ['85%', '60%', '40%'];
-// What the panels of the hosted build and Pro add to the dashboard, named and shown as
-// empty shapes.
+// The panels a build adds to the dashboard, named and shown as empty shapes.
export default function AgentAnalyticsPreview() {
const t = useTranslations('agentAnalytics.preview');
const tCommon = useTranslations('common');
diff --git a/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx b/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx
index b80dafa1..30d386fd 100644
--- a/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx
+++ b/apps/web/src/features/auth/components/login/AuthLoginAlternatives.tsx
@@ -2,6 +2,7 @@
import { KeyRound, Lock, Mail, ShieldCheck } from 'lucide-react';
import { useTranslations } from 'next-intl';
+import { SignInExtras } from '@/cloud';
import { Button } from '@/components/ui/button';
import { Field } from '@/components/ui/field';
import GoogleIcon from '@/components/common/GoogleIcon';
@@ -50,6 +51,7 @@ export default function AuthLoginAlternatives({
{authConfig.oidcLabel || t('withSso')}
</Button>
)}
+ <SignInExtras pending={pending} />
{authConfig?.google && (
<Button type="button" variant="outline" onClick={onGoogle} disabled={pending}>
<GoogleIcon className="size-4" />
diff --git a/apps/web/src/features/auth/hooks/useRedirectError.test.tsx b/apps/web/src/features/auth/hooks/useRedirectError.test.tsx
index edbd2583..ebb921f3 100644
--- a/apps/web/src/features/auth/hooks/useRedirectError.test.tsx
+++ b/apps/web/src/features/auth/hooks/useRedirectError.test.tsx
@@ -22,10 +22,10 @@ function Message({ error, description }: { error: string; description: string |
return <p>{useRedirectError()(error, description)}</p>;
}
-function render(error: string, description: string | null = null): string {
+function render(error: string, description: string | null = null, messages = { auth }): string {
act(() =>
root.render(
- <NextIntlClientProvider locale="en" messages={{ auth }} timeZone="UTC">
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
<Message error={error} description={description} />
</NextIntlClientProvider>,
),
@@ -78,6 +78,12 @@ describe('useRedirectError', () => {
assert.equal(render('INVITE_ONLY'), auth.errors.inviteOnly);
});
+ it("names a build's own code by the text the build gives it", () => {
+ const text = 'Sign out at your identity provider, then try again.';
+ const messages = { auth: { ...auth, errors: { ...auth.errors, codes: { BUILD_CODE: text } } } };
+ assert.equal(render('BUILD_CODE', 'English description', messages), text);
+ });
+
it('falls back to the description, then to the generic text, for an unknown error', () => {
assert.equal(render('something_else', 'Provider said no'), 'Provider said no');
assert.equal(render('something_else'), auth.errors.generic);
diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.ts
index 7fd567da..0a29825a 100644
--- a/apps/web/src/features/auth/hooks/useRedirectError.ts
+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts
@@ -48,6 +48,9 @@ export function useRedirectError() {
if (!error) return null;
const key = MESSAGE_KEYS[error as keyof typeof MESSAGE_KEYS];
if (key) return t(key);
+ // A build that sends codes of its own names their texts under auth.errors.codes.
+ const own = `codes.${error}` as Parameters<typeof t.has>[0];
+ if (t.has(own)) return t(own);
return description ?? t('generic');
};
}
diff --git a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx
index f0b14c37..d6f11e24 100644
--- a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx
+++ b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx
@@ -47,7 +47,12 @@ export default function GodAuthenticationForm({
<Button
size="sm"
onClick={() => void save()}
- disabled={!policy.dirty || !policy.inviteTtlDaysValid || policy.saving}
+ disabled={
+ !policy.dirty ||
+ !policy.inviteTtlDaysValid ||
+ !policy.allowedEmailDomainsValid ||
+ policy.saving
+ }
>
{policy.saving ? tCommon('saving') : tCommon('save')}
</Button>
@@ -61,6 +66,22 @@ export default function GodAuthenticationForm({
disabled={policy.saving}
onChange={policy.setRegistration}
/>
+ <SettingsRow
+ title={t('allowedEmailDomains')}
+ description={t('allowedEmailDomainsHint')}
+ note={policy.allowedEmailDomainsValid ? undefined : t('allowedEmailDomainsInvalid')}
+ control={
+ <Input
+ className="w-40 shrink-0 sm:w-72"
+ placeholder="example.com"
+ aria-label={t('allowedEmailDomains')}
+ aria-invalid={!policy.allowedEmailDomainsValid}
+ value={policy.allowedEmailDomains}
+ disabled={policy.saving}
+ onChange={(e) => policy.setAllowedEmailDomains(e.target.value)}
+ />
+ }
+ />
<SettingsRow
title={t('inviteTtlDays')}
description={t('inviteTtlDaysHint')}
diff --git a/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx b/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx
index 7e2ddf66..11b6bf6e 100644
--- a/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx
+++ b/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx
@@ -6,8 +6,9 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { JSDOM } from 'jsdom';
import type { InstanceAuthSettings, InstanceAuthSettingsPatch } from '@/lib/api/endpoints/god';
-// The invite lifetime is typed into the form as text: only a whole number of days, 0 or
-// more, can be saved, and it is saved with the rest of the page.
+// The invite lifetime and the allowed email domains are typed into the form as text:
+// only a whole number of days, 0 or more, and domains the api accepts can be saved, and
+// they are saved with the rest of the page.
const replacedGlobals = [
'window',
'document',
@@ -34,6 +35,7 @@ const settings = {
trustProviderEmails: false,
personalWorkspaces: true,
inviteTtlDays: 7,
+ allowedEmailDomains: ['company.com'],
hasEmailProvider: true,
hasSsoProvider: true,
} satisfies InstanceAuthSettings;
@@ -129,3 +131,46 @@ describe('useGodPolicyForm invite lifetime', () => {
assert.equal(saved[0].inviteTtlDays, 3);
});
});
+
+describe('useGodPolicyForm allowed email domains', () => {
+ it('starts clean on the stored list', async () => {
+ await render();
+
+ assert.equal(form.allowedEmailDomains, 'company.com');
+ assert.equal(form.dirty, false);
+ });
+
+ it('stays clean when the same domains are typed differently', async () => {
+ await render();
+
+ await act(async () => form.setAllowedEmailDomains(' @Company.com, company.com '));
+ assert.equal(form.dirty, false);
+ });
+
+ it('refuses a value that is not a domain', async () => {
+ await render();
+
+ for (const value of ['company', 'company .com', 'company.com/x', '-company.com']) {
+ await act(async () => form.setAllowedEmailDomains(value));
+ assert.equal(form.allowedEmailDomainsValid, false, value);
+ }
+ });
+
+ it('saves the domains as a lowercase list, and an empty field as none', async () => {
+ await render();
+
+ await act(async () =>
+ form.setAllowedEmailDomains('company.com, @Company.IO\nsub.company.com'),
+ );
+ await act(async () => form.save());
+ await act(async () => form.setAllowedEmailDomains(''));
+ await act(async () => form.save());
+
+ assert.deepEqual(saved[0].allowedEmailDomains, [
+ 'company.com',
+ 'company.io',
+ 'sub.company.com',
+ ]);
+ assert.deepEqual(saved[1].allowedEmailDomains, []);
+ });
+});
diff --git a/apps/web/src/features/god/hooks/useGodPolicyForm.ts b/apps/web/src/features/god/hooks/useGodPolicyForm.ts
index d3eae913..a151a72c 100644
--- a/apps/web/src/features/god/hooks/useGodPolicyForm.ts
+++ b/apps/web/src/features/god/hooks/useGodPolicyForm.ts
@@ -2,6 +2,7 @@
import { useState } from 'react';
import type { InstanceAuthSettings, RegistrationMode } from '@/lib/api/endpoints/god';
+import { emailDomainsValid, parseEmailDomains } from '@/utils/emailDomains';
import { useUpdateInstanceAuthSettings } from '../services/god.service';
// The api's own limit on the invite lifetime.
@@ -22,6 +23,9 @@ export interface GodPolicyForm {
inviteTtlDays: string;
setInviteTtlDays: (v: string) => void;
inviteTtlDaysValid: boolean;
+ allowedEmailDomains: string;
+ setAllowedEmailDomains: (v: string) => void;
+ allowedEmailDomainsValid: boolean;
dirty: boolean;
saving: boolean;
save: () => Promise<void>;
@@ -42,6 +46,11 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm
const [inviteTtlDays, setInviteTtlDays] = useState(String(settings.inviteTtlDays));
const inviteTtlDaysValid =
/^\d+$/.test(inviteTtlDays.trim()) && Number(inviteTtlDays) <= MAX_INVITE_TTL_DAYS;
+ const [allowedEmailDomains, setAllowedEmailDomains] = useState(
+ settings.allowedEmailDomains.join(', '),
+ );
+ const domains = parseEmailDomains(allowedEmailDomains);
+ const allowedEmailDomainsValid = emailDomainsValid(domains);
const dirty =
registration !== settings.registration ||
@@ -49,11 +58,12 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm
magicLink !== settings.magicLink ||
emailPassword !== settings.emailPassword ||
trustProviderEmails !== settings.trustProviderEmails ||
- inviteTtlDays.trim() !== String(settings.inviteTtlDays);
+ inviteTtlDays.trim() !== String(settings.inviteTtlDays) ||
+ domains.join() !== settings.allowedEmailDomains.join();
async function save() {
// An empty field would be read as 0, which turns expiry off.
- if (!inviteTtlDaysValid) return;
+ if (!inviteTtlDaysValid || !allowedEmailDomainsValid) return;
await update.mutateAsync({
registration,
requireEmailVerification,
@@ -61,6 +71,7 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm
emailPassword,
trustProviderEmails,
inviteTtlDays: Number(inviteTtlDays.trim()),
+ allowedEmailDomains: domains,
});
}
@@ -78,6 +89,9 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm
inviteTtlDays,
setInviteTtlDays,
inviteTtlDaysValid,
+ allowedEmailDomains,
+ setAllowedEmailDomains,
+ allowedEmailDomainsValid,
dirty,
saving: update.isPending,
save,
diff --git a/apps/web/src/features/members/components/members/MemberAddDialog.tsx b/apps/web/src/features/members/components/members/MemberAddDialog.tsx
index cb527f9c..80840161 100644
--- a/apps/web/src/features/members/components/members/MemberAddDialog.tsx
+++ b/apps/web/src/features/members/components/members/MemberAddDialog.tsx
@@ -25,12 +25,14 @@ import { OWNER_VALUE, chosenRole, ownerOffered } from '../../utils/addMemberRole
// The message for each refusal the API can answer with; any other error falls back
// to 'refused'.
-type RefusalKey = 'alreadyMember' | 'alreadyInTeam' | 'alreadyInvited' | 'refused';
+type RefusalKey =
+ 'alreadyMember' | 'alreadyInTeam' | 'alreadyInvited' | 'domainNotAllowed' | 'refused';
const REFUSAL_KEY: Record<string, RefusalKey> = {
ALREADY_PROJECT_MEMBER: 'alreadyMember',
ALREADY_TEAM_MEMBER: 'alreadyInTeam',
INVITE_ALREADY_PENDING: 'alreadyInvited',
+ EMAIL_DOMAIN_NOT_ALLOWED: 'domainNotAllowed',
};
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
diff --git a/apps/web/src/features/settings/components/schedules/SettingsScheduleTypeField.tsx b/apps/web/src/features/settings/components/schedules/SettingsScheduleTypeField.tsx
index 294253d0..1ce740f1 100644
--- a/apps/web/src/features/settings/components/schedules/SettingsScheduleTypeField.tsx
+++ b/apps/web/src/features/settings/components/schedules/SettingsScheduleTypeField.tsx
@@ -12,8 +12,8 @@ import { PRO_URL } from '@/utils/app';
import { SettingsScheduleField } from './SettingsScheduleField';
import { useTranslations } from 'next-intl';
-// The last item opens the page about Cloud and Pro, which start schedules on more
-// events. An item rather than a link, so the keyboard reaches it too.
+// The last item opens the page about the editions that start schedules on more events.
+// An item rather than a link, so the keyboard reaches it too.
const MORE = 'more';
export function SettingsScheduleTypeField({
diff --git a/apps/web/src/features/teams/components/members/TeamInviteDialog.tsx b/apps/web/src/features/teams/components/members/TeamInviteDialog.tsx
index 72bc4bfc..b3859c98 100644
--- a/apps/web/src/features/teams/components/members/TeamInviteDialog.tsx
+++ b/apps/web/src/features/teams/components/members/TeamInviteDialog.tsx
@@ -20,11 +20,12 @@ import { useCreateTeamInvite } from '@/services/teams.service';
// The message for each refusal the API can answer with; any other error falls back
// to 'refused'.
-type RefusalKey = 'alreadyMember' | 'alreadyPending' | 'refused';
+type RefusalKey = 'alreadyMember' | 'alreadyPending' | 'domainNotAllowed' | 'refused';
const REFUSAL_KEY: Record<string, RefusalKey> = {
ALREADY_TEAM_MEMBER: 'alreadyMember',
INVITE_ALREADY_PENDING: 'alreadyPending',
+ EMAIL_DOMAIN_NOT_ALLOWED: 'domainNotAllowed',
};
// Invites someone to the team itself: they join its member list and reach its
diff --git a/apps/web/src/features/teams/components/workspace/WorkspaceExtraSectionPage.tsx b/apps/web/src/features/teams/components/workspace/WorkspaceExtraSectionPage.tsx
index 80d74b66..be6a1345 100644
--- a/apps/web/src/features/teams/components/workspace/WorkspaceExtraSectionPage.tsx
+++ b/apps/web/src/features/teams/components/workspace/WorkspaceExtraSectionPage.tsx
@@ -1,9 +1,13 @@
'use client';
+import { useIsFetching } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import type { WorkspaceSummary } from '@/lib/api/endpoints/workspaces';
+import { useWorkspaceQuery } from '@/services/workspaces.service';
import { useWorkspaceSettingsSections } from '../../hooks/useWorkspaceSettingsSections';
+// A build's sections can depend on the workspace and on queries of their own, so a link
+// straight to one waits for those to load before it calls the section unknown.
export default function WorkspaceExtraSectionPage({
workspace,
sectionId,
@@ -12,7 +16,12 @@ export default function WorkspaceExtraSectionPage({
sectionId: string;
}) {
const sections = useWorkspaceSettingsSections(workspace);
+ const pending = useWorkspaceQuery(workspace.id).isPending;
+ const loading = useIsFetching() > 0;
const Component = sections.find((entry) => entry.id === sectionId)?.Component;
- if (!Component) notFound();
+ if (!Component) {
+ if (pending || loading) return null;
+ notFound();
+ }
return <Component workspaceId={workspace.id} />;
}
diff --git a/apps/web/src/lib/api/endpoints/agentSchedules.ts b/apps/web/src/lib/api/endpoints/agentSchedules.ts
index 7f56b8eb..a9645123 100644
--- a/apps/web/src/lib/api/endpoints/agentSchedules.ts
+++ b/apps/web/src/lib/api/endpoints/agentSchedules.ts
@@ -32,8 +32,8 @@ export interface AgentSchedule {
// False when the agent's runner is scoped to another member, who alone may run or
// stop it.
canTrigger: boolean;
- // False for a schedule set up with Cloud or Pro, whose type or options this instance
- // lacks: kept as it is, it starts no run and can only be deleted.
+ // False for a schedule set up by a build whose type or options this instance lacks:
+ // kept as it is, it starts no run and can only be deleted.
supported: boolean;
createdAt: string;
updatedAt: string;
diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.ts
index b2b6b87b..6255d39d 100644
--- a/apps/web/src/lib/api/endpoints/god.ts
+++ b/apps/web/src/lib/api/endpoints/god.ts
@@ -25,6 +25,8 @@ export interface InstanceAuthSettings {
personalWorkspaces: boolean;
// Days an invite link stays valid; 0 means invites never expire.
inviteTtlDays: number;
+ // The domains a new account's address must be at; empty admits any address.
+ allowedEmailDomains: string[];
hasEmailProvider: boolean;
// Whether Google or the OIDC provider can run. Password sign-in may only be turned
// off while one of them can.
@@ -39,6 +41,7 @@ export interface InstanceAuthSettingsPatch {
trustProviderEmails?: boolean;
personalWorkspaces?: boolean;
inviteTtlDays?: number;
+ allowedEmailDomains?: string[];
}
// The instance mail provider used for authentication email (password reset, address
diff --git a/apps/web/src/utils/app.ts b/apps/web/src/utils/app.ts
index d8208b5a..6230a095 100644
--- a/apps/web/src/utils/app.ts
+++ b/apps/web/src/utils/app.ts
@@ -7,7 +7,7 @@ export const APP_NAME = "It's a Plan";
// The product site. The product mark on the public share pages links to it.
export const APP_SITE_URL = 'https://itsaplan.dev/';
-// The page about Cloud and self-hosted Pro, linked wherever the app names what they add.
+// The page about the other editions, linked wherever the app names what they add.
export const PRO_URL = 'https://itsaplan.dev/pro';
// The legal document URLs, linked from the logged-out screens: Google requires the
diff --git a/apps/web/src/utils/emailDomains.ts b/apps/web/src/utils/emailDomains.ts
new file mode 100644
index 00000000..2ffeda7c
--- /dev/null
+++ b/apps/web/src/utils/emailDomains.ts
@@ -0,0 +1,18 @@
+// The api's own rule for an allowed email domain, and its limit on how many there are.
+const EMAIL_DOMAIN = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/;
+const MAX_EMAIL_DOMAINS = 100;
+
+export function parseEmailDomains(text: string): string[] {
+ const domains = text
+ .toLowerCase()
+ .split(/[\s,;]+/)
+ .map((domain) => domain.replace(/^@/, ''))
+ .filter(Boolean);
+ return [...new Set(domains)];
+}
+
+export function emailDomainsValid(domains: string[]): boolean {
+ return (
+ domains.length <= MAX_EMAIL_DOMAINS && domains.every((domain) => EMAIL_DOMAIN.test(domain))
+ );
+}
diff --git a/apps/web/src/utils/registrationRefusals.test.ts b/apps/web/src/utils/registrationRefusals.test.ts
index fb4c87ca..54f92d18 100644
--- a/apps/web/src/utils/registrationRefusals.test.ts
+++ b/apps/web/src/utils/registrationRefusals.test.ts
@@ -6,6 +6,7 @@ describe('registrationRefusalKey', () => {
it('names each refusal of the registration gate', () => {
assert.equal(registrationRefusalKey('REGISTRATION_CLOSED'), 'registrationClosed');
assert.equal(registrationRefusalKey('INVITE_ONLY'), 'inviteOnly');
+ assert.equal(registrationRefusalKey('EMAIL_DOMAIN_NOT_ALLOWED'), 'emailDomainNotAllowed');
});
it('leaves any other code to the caller', () => {
diff --git a/apps/web/src/utils/registrationRefusals.ts b/apps/web/src/utils/registrationRefusals.ts
index ca1cfd8c..a4f619dd 100644
--- a/apps/web/src/utils/registrationRefusals.ts
+++ b/apps/web/src/utils/registrationRefusals.ts
@@ -4,6 +4,7 @@
export const REGISTRATION_REFUSAL_KEYS = {
REGISTRATION_CLOSED: 'registrationClosed',
INVITE_ONLY: 'inviteOnly',
+ EMAIL_DOMAIN_NOT_ALLOWED: 'emailDomainNotAllowed',
} as const;
export function registrationRefusalKey(
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index c272c6e8..ded116b2 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -33,7 +33,8 @@ workspace settings can change them without a restart. Read them
through this module — never inline a query on `app_setting` / `app_secret` elsewhere.
- `app_setting` key `auth` → `{ registration, requireEmailVerification, magicLink,
- emailPassword }`.
+ emailPassword, trustProviderEmails, personalWorkspaces, inviteTtlDays,
+ allowedEmailDomains }`.
- `app_secret` keys `auth.email`, `auth.google` and `auth.oidc` → the mail provider, Google
and the OIDC provider, set in god mode; `workspace.<id>.scim` → a workspace's SCIM token,
set by the workspace owner. All encrypted with `@repo/crypto`, each with a `redacted`
@@ -51,9 +52,9 @@ Invites are created and revoked inside a team, so there is no instance-level inv
table and god mode has no invite section — do not add one; god mode only sets how long
they last.
-`hooks.before` gates `/sign-up/email` (closed → 403, invite → no pending, unexpired
-invite for that address → 403) and holds back `/sign-in/email` for an unconfirmed address while
-verification is required. The requirement never outlives the mail provider: the api
+`hooks.before` gates `/sign-up/email` (closed → 403, an address outside
+`allowedEmailDomains` → 403, invite → no pending, unexpired invite for that address → 403)
+and holds back `/sign-in/email` for an unconfirmed address while verification is required. The requirement never outlives the mail provider: the api
refuses to turn it on without one, and `setEmailSettings` clears it when the provider
is removed, so the setting alone is what the gate, the sign-up endpoint and the
public `/auth-config` read — none of them checks the provider again.
@@ -155,13 +156,16 @@ What a provider says about a person is kept per workspace in `scim_user`, writte
instance workspace's token opens it, and it also writes `active`, one more
`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. An
-account with `active` false (`isAccountDeactivated`) is refused at sign-in by the
+(`accountsManagedByScim`: SCIM per workspace alone, or the instance workspace's SCIM set
+up with a token); while one does, `apps/api` answers god's switch with 409. An account
+with `active` false (`isAccountDeactivated`) is refused at sign-in by the
`session.create.before` hook with `ACCOUNT_DEACTIVATED`, which covers every sign-in method
at once; `apps/api` refuses the sessions and keys it already holds. On, a workspace's
provider decides who is in the workspace, not who has an account, `active` is not read,
-and nothing here refuses a session.
+and nothing here refuses a session. `setInstanceScimBeside()` keeps the instance
+workspace's provider, beside every other workspace's, as it is while off: acting on the
+whole instance and writing `active`. `instanceScimWorkspace()` names the workspace whose
+provider acts on the whole instance, or null when none does.
`getScimSettings` / `rotateScimToken` / `verifyScimToken` hold the bearer token of each
workspace that the SCIM endpoints in `apps/api` authenticate with. A token reads
@@ -203,14 +207,22 @@ receive its real owner.
The registration gate (`assertRegistrationAllowed`) runs in
`databaseHooks.user.create.before`, which every account creation passes, and that is what
applies closed/invite-only to a Google, OIDC or magic-link sign-up. It refuses with
-`REGISTRATION_CLOSED` on a closed instance, `INVITE_ONLY` when the address has no pending
-invite, and `INVITE_EXPIRED` when its only invites have expired. That last one reveals that
-the address was invited, so it is given only where the address is proven (provider, magic
-link); the email form, open to anyone, gets `INVITE_ONLY`. Its `APIError`s carry a `code`
-because the provider callback and the magic link turn that into the `?error=` they redirect
-with; without one the callback fails the request instead (`invite-forms.test.ts` pins
-`INVITE_EXPIRED` and `INVITE_ONLY`). Agent bot users are written with a direct insert and never
-reach the hook.
+`REGISTRATION_CLOSED` on a closed instance, `EMAIL_DOMAIN_NOT_ALLOWED` when the address is
+not at one of `allowedEmailDomains` (an empty list admits any), `INVITE_ONLY` when the
+address has no pending invite, and `INVITE_EXPIRED` when its only invites have expired.
+That last one reveals that the address was invited, so it is given only where the address
+is proven (provider, magic link); the email form, open to anyone, gets `INVITE_ONLY`. Its
+`APIError`s carry a `code` because the provider callback and the magic link turn that into
+the `?error=` they redirect with; without one the callback fails the request instead
+(`invite-forms.test.ts` pins `INVITE_EXPIRED` and `INVITE_ONLY`). Agent bot users are
+written with a direct insert and never reach the hook.
+
+A domain in `allowedEmailDomains` matches the part of the address after the "@" exactly, so
+a subdomain is listed on its own. The list applies to new accounts only; the api also
+refuses to invite an address that has no account and is outside it, since it could not
+register. The gate asks `registrationEmailAllowed`, which checks the list unless a build
+installs its own policy with `setRegistrationEmailPolicy`, as one that lets a workspace
+keep domains of its own does to admit an address that workspace invited.
## API keys
@@ -275,6 +287,23 @@ from the planner's own OpenAPI docs at `/docs` (the `@elysiajs/swagger` spec, wh
not see the catch-all auth handler). Docs-only: it adds no table, so `auth:generate` is
not required for it.
+## What a build adds
+
+`@repo/auth/extensions` is the one module of this package that does not create the
+instance. A build calls `extendAuth({ plugins, schema, disabledPaths })` from it before
+the first request: the plugins join the core's, their drizzle tables join the adapter's
+schema by model name, and the paths are refused to requests while the server still calls
+them through `auth.api`. `./index.ts` creates the instance on its first use, not on
+import, so the call takes effect wherever a bundler puts the build's module; it reads the
+extensions then, and a later call throws. A plugin that needs origins trusted adds them
+itself, through its `init`. The plugins are typed as none, so `Auth` stays the core's
+type.
+
+`setRegistrationAdmission(fn)` is a build's say on an account the gate is about to create,
+by the request creating it (the better-auth endpoint context): true lets it past the
+registration mode and the allowed domains, as a sign-in through a provider the build
+manages that may create accounts; a throw turns it away. Without one the gate decides.
+
## Rules
- This package is **server-only** — never import a client SDK (`better-auth/react`) here;
diff --git a/packages/auth/package.json b/packages/auth/package.json
index e3334ee5..f26cb7b9 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -4,7 +4,8 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./extensions": "./src/extensions.ts"
},
"scripts": {
"auth:generate": "dotenv -e ../../.env -- bunx [email protected] generate --config ./src/index.ts --output ../db/src/schema/auth.ts --yes",
diff --git a/packages/auth/src/extensions.ts b/packages/auth/src/extensions.ts
new file mode 100644
index 00000000..fd6a6cfd
--- /dev/null
+++ b/packages/auth/src/extensions.ts
@@ -0,0 +1,31 @@
+import type { BetterAuthPlugin } from 'better-auth';
+
+// What a build adds to the instance's better-auth: plugins, the drizzle tables they keep
+// (by model name, for the adapter), and paths no request may reach, which the server still
+// calls through `auth.api`. Read once, when ./index.ts creates the instance on its first
+// use, so a build calls extendAuth before the first request. A later call throws rather
+// than going unread.
+export interface AuthExtensions {
+ plugins: BetterAuthPlugin[];
+ schema: Record<string, unknown>;
+ disabledPaths: string[];
+}
+
+const extensions: AuthExtensions = {
+ plugins: [],
+ schema: {},
+ disabledPaths: [],
+};
+let read = false;
+
+export function extendAuth(next: Partial<AuthExtensions>): void {
+ if (read) throw new Error('extendAuth must run before the auth instance is first used');
+ extensions.plugins.push(...(next.plugins ?? []));
+ Object.assign(extensions.schema, next.schema);
+ extensions.disabledPaths.push(...(next.disabledPaths ?? []));
+}
+
+export function readAuthExtensions(): AuthExtensions {
+ read = true;
+ return extensions;
+}
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 3233610d..6bf0a1ca 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -16,6 +16,8 @@ import { createLocalJWKSet, jwtVerify } from 'jose';
import * as schema from '@repo/db/schema';
import {
getAuthSettings,
+ admittedPastGate,
+ registrationEmailAllowed,
hasPendingInvite,
hasExpiredInvite,
getGoogleConfig,
@@ -25,6 +27,7 @@ import {
isAccountDeactivated,
} from './instance';
import { sendAuthEmail } from './mail';
+import { readAuthExtensions } from './extensions';
// Frontend origins allowed to call the auth handler. Mandatory config: cookies, the
// WebAuthn relying party and the cookie domain are all derived from it, so a deploy
@@ -324,11 +327,14 @@ const instanceOidc = (): BetterAuthPlugin => ({
// leaves the setting here for the getter to read.
let trustProviderEmails = false;
-// The trusted providers for one request. The settings are read on the OAuth callback
-// only — the resolver runs on every request to the auth API, and a session check has
-// no linking decision to make.
+// The trusted providers for one request. The settings are read where a provider's
+// sign-in comes back — an OAuth callback, or a SAML response posted to `/acs/` — only:
+// the resolver runs on every request to the auth API, and a session check has no linking
+// decision to make.
+const PROVIDER_RETURN = /\/(callback|acs)\//;
+
async function resolveTrustedProviders(request?: Request): Promise<string[]> {
- if (!request || !new URL(request.url).pathname.includes('/callback/')) return [];
+ if (!request || !PROVIDER_RETURN.test(new URL(request.url).pathname)) return [];
trustProviderEmails = (await getAuthSettings()).trustProviderEmails;
return trustProviderEmails ? ['google', OIDC_PROVIDER_ID] : [];
}
@@ -359,6 +365,7 @@ const REGISTRATION_REFUSALS = {
REGISTRATION_CLOSED: 'Registration is closed on this instance',
INVITE_ONLY: 'This instance is invite-only. Ask a project owner to invite this address.',
INVITE_EXPIRED: 'The invite for this address has expired. Ask for a new one.',
+ EMAIL_DOMAIN_NOT_ALLOWED: 'This instance does not admit addresses at this domain',
} as const;
function refuseRegistration(code: keyof typeof REGISTRATION_REFUSALS): never {
@@ -379,6 +386,7 @@ async function assertRegistrationAllowed(
): Promise<void> {
const settings = await getAuthSettings();
if (settings.registration === 'closed') refuseRegistration('REGISTRATION_CLOSED');
+ if (!(await registrationEmailAllowed(email))) refuseRegistration('EMAIL_DOMAIN_NOT_ALLOWED');
if (settings.registration === 'invite' && !(await hasPendingInvite(email))) {
const expired = addressProven && (await hasExpiredInvite(email));
refuseRegistration(expired ? 'INVITE_EXPIRED' : 'INVITE_ONLY');
@@ -503,442 +511,465 @@ const DAY_SEC = 24 * 60 * 60;
export const API_KEY_DEFAULT_EXPIRES_IN_SEC = 90 * DAY_SEC;
export const API_KEY_MAX_EXPIRES_IN_DAYS = 365;
-export const auth = betterAuth({
- baseURL,
- secret: process.env.BETTER_AUTH_SECRET,
- onAPIError: { errorURL: oauthErrorURL },
-
- database: drizzleAdapter(db, {
- provider: 'pg',
- schema: {
- user: schema.user,
- session: schema.session,
- account: schema.account,
- verification: schema.verification,
- passkey: schema.passkey,
- apikey: schema.apikey,
- jwks: schema.jwks,
- oauthClient: schema.oauthClient,
- oauthResource: schema.oauthResource,
- oauthClientResource: schema.oauthClientResource,
- oauthRefreshToken: schema.oauthRefreshToken,
- oauthAccessToken: schema.oauthAccessToken,
- oauthConsent: schema.oauthConsent,
- oauthClientAssertion: schema.oauthClientAssertion,
- },
- }),
-
- emailAndPassword: {
- enabled: true,
- // While this is true, sign-up answers without a session and a duplicate address
- // gets the same answer as a new one; sign-in of an unconfirmed account is
- // refused in the hook below before better-auth's own check runs.
- get requireEmailVerification() {
- return verificationRequired;
- },
- autoSignIn: true,
- // A reset is how a stolen password is dealt with, so every session opened with
- // the old one ends with it. The signed-in change-password form sends
- // revokeOtherSessions for the same reason.
- revokeSessionsOnPasswordReset: true,
- sendResetPassword: async ({ user, url }) => {
- await sendAuthEmail({
- to: user.email,
- subject: 'Reset your password',
- text: 'Use the link below to set a new password. Ignore this email if you did not ask for it.',
- url: withPublicOrigin(url),
- });
- },
- },
+// Created on first use rather than on import, so a build's extendAuth (./extensions) takes
+// effect wherever a bundler puts its module, as long as it runs before the first request.
+function createAuth() {
+ const extensions = readAuthExtensions();
+ return betterAuth({
+ baseURL,
+ secret: process.env.BETTER_AUTH_SECRET,
+ onAPIError: { errorURL: oauthErrorURL },
+
+ database: drizzleAdapter(db, {
+ provider: 'pg',
+ schema: {
+ user: schema.user,
+ session: schema.session,
+ account: schema.account,
+ verification: schema.verification,
+ passkey: schema.passkey,
+ apikey: schema.apikey,
+ jwks: schema.jwks,
+ oauthClient: schema.oauthClient,
+ oauthResource: schema.oauthResource,
+ oauthClientResource: schema.oauthClientResource,
+ oauthRefreshToken: schema.oauthRefreshToken,
+ oauthAccessToken: schema.oauthAccessToken,
+ oauthConsent: schema.oauthConsent,
+ oauthClientAssertion: schema.oauthClientAssertion,
+ ...extensions.schema,
+ },
+ }),
- emailVerification: {
- // The mail goes out on every sign-up; sendVerificationEmail below drops it when
- // the instance does not require verification.
- sendOnSignUp: true,
- autoSignInAfterVerification: true,
- sendVerificationEmail: async ({ user, url }) => {
- const settings = await getAuthSettings();
- if (!settings.requireEmailVerification) return;
- await sendAuthEmail({
- to: user.email,
- subject: 'Confirm your email address',
- text: 'Use the link below to confirm this address and finish signing up.',
- url: withPublicOrigin(url),
- });
+ emailAndPassword: {
+ enabled: true,
+ // While this is true, sign-up answers without a session and a duplicate address
+ // gets the same answer as a new one; sign-in of an unconfirmed account is
+ // refused in the hook below before better-auth's own check runs.
+ get requireEmailVerification() {
+ return verificationRequired;
+ },
+ autoSignIn: true,
+ // A reset is how a stolen password is dealt with, so every session opened with
+ // the old one ends with it. The signed-in change-password form sends
+ // revokeOtherSessions for the same reason.
+ revokeSessionsOnPasswordReset: true,
+ sendResetPassword: async ({ user, url }) => {
+ await sendAuthEmail({
+ to: user.email,
+ subject: 'Reset your password',
+ text: 'Use the link below to set a new password. Ignore this email if you did not ask for it.',
+ url: withPublicOrigin(url),
+ });
+ },
},
- },
- // Google sign-in. The provider is always mounted; whether it may run is decided per
- // request in the hook below, the same way the magic link is handled. The factory
- // runs once, at startup, and returns the shared options object described above.
- socialProviders: {
- google: async () => {
- await refreshGoogleOptions();
- return googleOptions;
+ emailVerification: {
+ // The mail goes out on every sign-up; sendVerificationEmail below drops it when
+ // the instance does not require verification.
+ sendOnSignUp: true,
+ autoSignInAfterVerification: true,
+ sendVerificationEmail: async ({ user, url }) => {
+ const settings = await getAuthSettings();
+ if (!settings.requireEmailVerification) return;
+ await sendAuthEmail({
+ to: user.email,
+ subject: 'Confirm your email address',
+ text: 'Use the link below to confirm this address and finish signing up.',
+ url: withPublicOrigin(url),
+ });
+ },
},
- },
- // A provider address that already has an account signs into it and gains a linked
- // account row, rather than being refused as a duplicate. By default that happens
- // only when the provider reported the address as verified and the local account
- // confirmed its own — Google always reports a verified address, an OIDC provider
- // need not, and an instance with no mail provider has no confirmed accounts at
- // all. The instance setting drops both conditions; after a successful link
- // better-auth marks the local user confirmed too.
- account: {
- accountLinking: {
- trustedProviders: resolveTrustedProviders,
- get requireLocalEmailVerified() {
- return !trustProviderEmails;
+ // Google sign-in. The provider is always mounted; whether it may run is decided per
+ // request in the hook below, the same way the magic link is handled. The factory
+ // runs once, at startup, and returns the shared options object described above.
+ socialProviders: {
+ google: async () => {
+ await refreshGoogleOptions();
+ return googleOptions;
},
},
- // The id_token is stored unencrypted, so this covers only the access and refresh
- // tokens.
- encryptOAuthTokens: true,
- },
- // Extra column on the user table. Not client-settable (input: false) — the role
- // is decided by the create hook below.
- user: {
- additionalFields: {
- role: {
- type: 'string',
- required: false,
- defaultValue: 'user',
- input: false,
- },
- // Deprovisioning flag, written only over SCIM while it acts on the whole instance.
- // Nullable: read it through isAccountDeactivated, which takes only `false`.
- active: {
- type: 'boolean',
- required: false,
- defaultValue: true,
- input: false,
+ // A provider address that already has an account signs into it and gains a linked
+ // account row, rather than being refused as a duplicate. By default that happens
+ // only when the provider reported the address as verified and the local account
+ // confirmed its own — Google always reports a verified address, an OIDC provider
+ // need not, and an instance with no mail provider has no confirmed accounts at
+ // all. The instance setting drops both conditions; after a successful link
+ // better-auth marks the local user confirmed too.
+ account: {
+ accountLinking: {
+ trustedProviders: resolveTrustedProviders,
+ get requireLocalEmailVerified() {
+ return !trustProviderEmails;
+ },
},
+ // The id_token is stored unencrypted, so this covers only the access and refresh
+ // tokens.
+ encryptOAuthTokens: true,
},
- },
- // The registration gate and the verification check. Both read instance settings
- // 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;
- if (passwordSettings) verificationRequired = passwordSettings.requireEmailVerification;
- // 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',
- });
- }
+ // Extra column on the user table. Not client-settable (input: false) — the role
+ // is decided by the create hook below.
+ user: {
+ additionalFields: {
+ role: {
+ type: 'string',
+ required: false,
+ defaultValue: 'user',
+ input: false,
+ },
+ // Deprovisioning flag, written only over SCIM while it acts on the whole instance.
+ // Nullable: read it through isAccountDeactivated, which takes only `false`.
+ active: {
+ type: 'boolean',
+ required: false,
+ defaultValue: true,
+ input: false,
+ },
+ },
+ },
- if (ctx.path === '/sign-up/email') {
- await assertRegistrationAllowed((ctx.body as { email?: string } | undefined)?.email ?? '', {
- addressProven: false,
- });
- return;
- }
-
- const provider =
- ctx.path === '/sign-in/social' || ctx.path === '/link-social'
- ? (ctx.body as { provider?: string } | undefined)?.provider
- : ctx.path.startsWith('/callback/')
- ? ctx.path.slice('/callback/'.length)
- : undefined;
- // No screen links an OIDC identity to the signed-in account, and better-auth
- // already attaches a sign-in to a matching confirmed address on its own.
- if (ctx.path === '/link-social' && provider === OIDC_PROVIDER_ID) {
- throw new APIError('FORBIDDEN', { message: 'Single sign-on cannot be linked' });
- }
-
- // Both halves of an OAuth round trip: starting it and coming back from it. This
- // is where the stored settings are loaded into the provider, so a request never
- // runs on a value the owner has since changed. The OIDC refusal carries a code
- // because the callback turns it into the ?error= it redirects with; without one
- // the callback fails the request instead.
- if (provider === OIDC_PROVIDER_ID) {
- if (!(await refreshOidcProvider())) {
+ // The registration gate and the verification check. Both read instance settings
+ // 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;
+ if (passwordSettings) verificationRequired = passwordSettings.requireEmailVerification;
+ // 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: 'OIDC_DISABLED',
- message: 'Single sign-on is disabled on this instance',
+ code: 'PASSWORD_AUTH_DISABLED',
+ message: 'Password sign-in is disabled on this instance',
});
}
- return;
- }
- if (provider === 'google') {
- if (!(await refreshGoogleOptions())) {
- throw new APIError('FORBIDDEN', {
- message: 'Google sign-in is disabled on this instance',
- });
+
+ if (ctx.path === '/sign-up/email') {
+ await assertRegistrationAllowed(
+ (ctx.body as { email?: string } | undefined)?.email ?? '',
+ {
+ addressProven: false,
+ },
+ );
+ return;
}
- return;
- }
-
- // Both password endpoints: the sign-in screen sends the one field it has to
- // /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 = passwordSettings ?? (await getAuthSettings());
- if (!settings.requireEmailVerification) return;
- const body = ctx.body as { email?: string; username?: string } | undefined;
- const identifier =
- ctx.path === '/sign-in/email'
- ? eq(schema.user.email, (body?.email ?? '').trim().toLowerCase())
- : eq(schema.user.username, (body?.username ?? '').trim().toLowerCase());
- if (await isUnverified(identifier)) {
- throw new APIError('FORBIDDEN', {
- message: 'Confirm your email address before signing in',
- });
+
+ const provider =
+ ctx.path === '/sign-in/social' || ctx.path === '/link-social'
+ ? (ctx.body as { provider?: string } | undefined)?.provider
+ : ctx.path.startsWith('/callback/')
+ ? ctx.path.slice('/callback/'.length)
+ : undefined;
+ // No screen links an OIDC identity to the signed-in account, and better-auth
+ // already attaches a sign-in to a matching confirmed address on its own.
+ if (ctx.path === '/link-social' && provider === OIDC_PROVIDER_ID) {
+ throw new APIError('FORBIDDEN', { message: 'Single sign-on cannot be linked' });
}
- return;
- }
-
- // The profile form changes the username here. The plugin only checks it against
- // the other accounts, so the agents are checked on this side.
- if (ctx.path === '/update-user') {
- const handle = (ctx.body as { username?: string } | undefined)?.username;
- if (handle && (await isAgentHandle(handle))) {
- throw new APIError('BAD_REQUEST', {
- message: 'Username is already taken. Please try another.',
- });
+
+ // Both halves of an OAuth round trip: starting it and coming back from it. This
+ // is where the stored settings are loaded into the provider, so a request never
+ // runs on a value the owner has since changed. The OIDC refusal carries a code
+ // because the callback turns it into the ?error= it redirects with; without one
+ // the callback fails the request instead.
+ if (provider === OIDC_PROVIDER_ID) {
+ if (!(await refreshOidcProvider())) {
+ throw new APIError('FORBIDDEN', {
+ code: 'OIDC_DISABLED',
+ message: 'Single sign-on is disabled on this instance',
+ });
+ }
+ return;
+ }
+ if (provider === 'google') {
+ if (!(await refreshGoogleOptions())) {
+ throw new APIError('FORBIDDEN', {
+ message: 'Google sign-in is disabled on this instance',
+ });
+ }
+ return;
}
- return;
- }
-
- // A key resolves to its owner's session, so a request carrying a leaked key
- // reaches the key endpoints. It may not issue another one: a new key starts a
- // fresh lifetime, which is the expiry of the leaked key renewed under a
- // different row. Issuing a key is left to a signed-in session. The server-side
- // call that issues an agent's key carries no request and is unaffected.
- if (ctx.path === '/api-key/create' && ctx.request?.headers.get('x-api-key')) {
- throw new APIError('FORBIDDEN', {
- message: 'An API key cannot create another API key. Sign in to create one.',
- });
- }
- // The lifetime is fixed at creation for the same reason; a longer one is a new
- // key, created from a session.
- if (ctx.path === '/api-key/update') {
- const body = ctx.body as { expiresIn?: number | null } | undefined;
- if (body && body.expiresIn !== undefined) {
- throw new APIError('FORBIDDEN', {
- message: 'The expiry of an API key cannot be changed. Create a new key instead.',
- });
+ // Both password endpoints: the sign-in screen sends the one field it has to
+ // /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 = passwordSettings ?? (await getAuthSettings());
+ if (!settings.requireEmailVerification) return;
+ const body = ctx.body as { email?: string; username?: string } | undefined;
+ const identifier =
+ ctx.path === '/sign-in/email'
+ ? eq(schema.user.email, (body?.email ?? '').trim().toLowerCase())
+ : eq(schema.user.username, (body?.username ?? '').trim().toLowerCase());
+ if (await isUnverified(identifier)) {
+ throw new APIError('FORBIDDEN', {
+ message: 'Confirm your email address before signing in',
+ });
+ }
+ return;
}
- }
- }),
- },
- databaseHooks: {
- user: {
- create: {
- // Every account creation passes here, whichever method made it, so this is
- // where the registration gate applies to Google. Agent bot users are written
- // with a direct insert and never reach this hook.
- //
- // Assign the role before the row is inserted: first user ever → "god",
- // everyone else → "user".
- before: async (user) => {
- // The email form is refused up front unless its invite is valid, so a refusal
- // here comes from a provider or a magic link, which prove the address.
- await assertRegistrationAllowed(user.email, { addressProven: true });
- const isFirstUser = (await db.$count(schema.user)) === 0;
- // A sign-up that carried its own username has passed the plugin's own
- // check against the other accounts by now, but not the one against the
- // agents; only an account without one gets a derived name.
- const carried = typeof user.username === 'string' ? user.username : null;
- if (carried && (await isAgentHandle(carried))) {
+ // The profile form changes the username here. The plugin only checks it against
+ // the other accounts, so the agents are checked on this side.
+ if (ctx.path === '/update-user') {
+ const handle = (ctx.body as { username?: string } | undefined)?.username;
+ if (handle && (await isAgentHandle(handle))) {
throw new APIError('BAD_REQUEST', {
- code: 'USERNAME_IS_ALREADY_TAKEN',
message: 'Username is already taken. Please try another.',
});
}
- const derived = carried ?? (await generateUsername(user.email));
- return {
- data: {
- ...user,
- role: isFirstUser ? 'god' : 'user',
- username: derived,
- displayUsername: user.displayUsername ?? derived,
- },
- };
- },
- after: async (user) => {
- if (user.role === 'god') {
- await db
- .insert(schema.workspaceManager)
- .values({
- workspaceId: await instanceWorkspaceId(db),
- userId: user.id,
- role: 'owner',
- })
- .onConflictDoNothing();
- } else {
- await ensurePersonalWorkspace(user.id);
+ return;
+ }
+
+ // A key resolves to its owner's session, so a request carrying a leaked key
+ // reaches the key endpoints. It may not issue another one: a new key starts a
+ // fresh lifetime, which is the expiry of the leaked key renewed under a
+ // different row. Issuing a key is left to a signed-in session. The server-side
+ // call that issues an agent's key carries no request and is unaffected.
+ if (ctx.path === '/api-key/create' && ctx.request?.headers.get('x-api-key')) {
+ throw new APIError('FORBIDDEN', {
+ message: 'An API key cannot create another API key. Sign in to create one.',
+ });
+ }
+
+ // The lifetime is fixed at creation for the same reason; a longer one is a new
+ // key, created from a session.
+ if (ctx.path === '/api-key/update') {
+ const body = ctx.body as { expiresIn?: number | null } | undefined;
+ if (body && body.expiresIn !== undefined) {
+ throw new APIError('FORBIDDEN', {
+ message: 'The expiry of an API key cannot be changed. Create a new key instead.',
+ });
}
+ }
+ }),
+ },
+
+ databaseHooks: {
+ user: {
+ create: {
+ // Every account creation passes here, whichever method made it, so this is
+ // where the registration gate applies to Google. Agent bot users are written
+ // with a direct insert and never reach this hook.
+ //
+ // Assign the role before the row is inserted: first user ever → "god",
+ // everyone else → "user".
+ before: async (user, ctx) => {
+ // The email form is refused up front unless its invite is valid, so a refusal
+ // here comes from a provider or a magic link, which prove the address.
+ if (!(await admittedPastGate(user.email, ctx))) {
+ await assertRegistrationAllowed(user.email, { addressProven: true });
+ }
+ const isFirstUser = (await db.$count(schema.user)) === 0;
+ // A sign-up that carried its own username has passed the plugin's own
+ // check against the other accounts by now, but not the one against the
+ // agents; only an account without one gets a derived name.
+ const carried = typeof user.username === 'string' ? user.username : null;
+ if (carried && (await isAgentHandle(carried))) {
+ throw new APIError('BAD_REQUEST', {
+ code: 'USERNAME_IS_ALREADY_TAKEN',
+ message: 'Username is already taken. Please try another.',
+ });
+ }
+ const derived = carried ?? (await generateUsername(user.email));
+ return {
+ data: {
+ ...user,
+ role: isFirstUser ? 'god' : 'user',
+ username: derived,
+ displayUsername: user.displayUsername ?? derived,
+ },
+ };
+ },
+ after: async (user) => {
+ if (user.role === 'god') {
+ await db
+ .insert(schema.workspaceManager)
+ .values({
+ workspaceId: await instanceWorkspaceId(db),
+ userId: user.id,
+ role: 'owner',
+ })
+ .onConflictDoNothing();
+ } else {
+ await ensurePersonalWorkspace(user.id);
+ }
+ },
+ },
+ },
+ session: {
+ create: {
+ // Every sign-in method ends here, so one check covers password, magic link,
+ // 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 })
+ .from(schema.user)
+ .where(eq(schema.user.id, session.userId));
+ if (account && isAccountDeactivated(account)) {
+ throw new APIError('FORBIDDEN', {
+ code: 'ACCOUNT_DEACTIVATED',
+ message: 'This account is deactivated',
+ });
+ }
+ },
},
},
},
- session: {
- create: {
- // Every sign-in method ends here, so one check covers password, magic link,
- // 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 })
- .from(schema.user)
- .where(eq(schema.user.id, session.userId));
- if (account && isAccountDeactivated(account)) {
+
+ plugins: [
+ // WebAuthn passkeys, a second sign-in method alongside email + password. A
+ // passkey is added to an already signed-in account (passkey.addPasskey) and
+ // then used to sign in (signIn.passkey). Adds the `passkey` table.
+ passkey({
+ rpID: passkeyRpID,
+ rpName: process.env.PASSKEY_RP_NAME ?? "It's a Plan",
+ // Expected origin(s) of the WebAuthn ceremony — the frontend origins.
+ origin: trustedOrigins,
+ }),
+ // Personal API keys: a signed-in user creates a named key, sees its value once
+ // at creation, and can list (value hidden) or delete it. Adds the `apikey` table.
+ // enableSessionForAPIKeys makes a request carrying an `x-api-key` header resolve
+ // to the key owner's session, so getSession (and every planner guard built on it)
+ // accepts API keys without any change in apps/api. Rate limit: 100 requests per
+ // second per key (timeWindow is in milliseconds). The ceiling is set for the
+ // heaviest legitimate caller rather than a typical one: an internal AI agent runs
+ // on its own key and dispatches every tool call through a route, and a model that
+ // emits a batch of tool calls in one step turns them into a burst of requests.
+ apiKey({
+ enableSessionForAPIKeys: true,
+ // Brand prefix so a leaked key is identifiable by secret scanners and in logs.
+ // The trailing underscore separates it from the random part (itp_<64 chars>).
+ defaultPrefix: 'itp_',
+ // A key is a full-account credential, so one that was forgotten stops working
+ // on its own. The caller may pick a shorter or longer life up to the maximum;
+ // an agent's key is the exception, cleared where it is issued in apps/api.
+ keyExpiration: {
+ defaultExpiresIn: API_KEY_DEFAULT_EXPIRES_IN_SEC,
+ maxExpiresIn: API_KEY_MAX_EXPIRES_IN_DAYS,
+ },
+ rateLimit: {
+ enabled: true,
+ timeWindow: 1000,
+ maxRequests: 100,
+ },
+ }),
+ // Sign-in by emailed link, offered alongside the password. Whether it is
+ // available is an instance setting, so the plugin is always mounted and the
+ // sender refuses when it is off. It reuses the `verification` table — no new
+ // table, so `auth:generate` output is unchanged.
+ magicLink({
+ // Stored plain, an OAuth state also passes as a token (GHSA-965c-763c-88jm).
+ storeToken: 'hashed',
+ sendMagicLink: async ({ email, url }) => {
+ const settings = await getAuthSettings();
+ if (!settings.magicLink) {
throw new APIError('FORBIDDEN', {
- code: 'ACCOUNT_DEACTIVATED',
- message: 'This account is deactivated',
+ message: 'Magic links are disabled on this instance',
});
}
+ await sendAuthEmail({
+ to: email,
+ subject: 'Your sign-in link',
+ text: 'Use the link below to sign in. It works once and expires shortly.',
+ url: withPublicOrigin(url),
+ });
},
+ }),
+ // The instance's OIDC provider, configured in god mode; see oidcProvider above.
+ instanceOidc(),
+ // 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
+ // name rather than an address. Nobody is asked for one — the create hook above
+ // derives it from the address, and the profile page changes it afterwards.
+ username({
+ minUsernameLength: USERNAME_MIN_LENGTH,
+ maxUsernameLength: USERNAME_MAX_LENGTH,
+ }),
+ // OAuth 2.1 for Streamable HTTP MCP clients, on top of the existing session. Any
+ // client registers itself (RFC 7591), as ChatGPT and Claude do. The access tokens
+ // are JWTs signed by jwt(); no screen reads a session JWT, so it does not put one
+ // on every session response.
+ ...(mcpOAuth
+ ? [
+ jwt({ disableSettingJwtHeader: true, jwt: { issuer: MCP_ISSUER } }),
+ mcp({
+ resource: MCP_RESOURCE,
+ loginPage: `${trustedOrigins[0]}/login`,
+ consentPage: `${trustedOrigins[0]}/oauth/consent`,
+ // Every token acts for a person; client_credentials would mint one for none.
+ grantTypes: ['authorization_code', 'refresh_token'],
+ allowDynamicClientRegistration: true,
+ allowUnauthenticatedClientRegistration: true,
+ }),
+ ]
+ : []),
+ // OpenAPI reference for the better-auth handler. Serves a Scalar UI at
+ // /api/auth/reference and the raw schema at /api/auth/open-api/generate-schema.
+ // The schema is built from every active plugin, so the passkey and apiKey
+ // endpoints are documented automatically. This is docs-only: it adds no table,
+ // so `auth:generate` is not needed. The planner's own OpenAPI docs stay at /docs.
+ openAPI(),
+ // A build's own (./extensions). Typed as none, so the instance's type stays the core's.
+ ...(extensions.plugins as []),
+ ],
+
+ // The frontend runs on a different origin (Next :3001) — allow its requests.
+ trustedOrigins,
+
+ // /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. jwt()'s /token hands out a JWT of the session, which nothing reads.
+ disabledPaths: ['/is-username-available', '/token', ...extensions.disabledPaths],
+
+ advanced: {
+ // Share the session cookie across subdomains when COOKIE_DOMAIN is the parent
+ // domain (e.g. ".itsaplan.dev" for app.itsaplan.dev + api.itsaplan.dev). Without
+ // it the cookie is host-only for the api origin, so the SSR web app on another
+ // subdomain cannot read the session. Leave COOKIE_DOMAIN unset on localhost
+ // (single host), where "lax" host-only cookies already work across ports.
+ ...(cookieDomain
+ ? {
+ crossSubDomainCookies: {
+ enabled: true,
+ domain: cookieDomain,
+ },
+ }
+ : {}),
+ // For a single site (localhost / one domain) "lax" is enough. Subdomains of one
+ // registrable domain are same-site, so "lax" cookies are still sent between them.
+ ...(hostPrefixedCookies
+ ? {
+ useSecureCookies: false,
+ cookiePrefix: '__Secure-better-auth',
+ cookies: Object.fromEntries(
+ SESSION_COOKIES.map((name) => [
+ name,
+ { name: `__Host-better-auth.${name}`, attributes: { path: '/', secure: true } },
+ ]),
+ ),
+ }
+ : {}),
+ defaultCookieAttributes: {
+ sameSite: 'lax',
+ secure: hostPrefixedCookies || process.env.NODE_ENV === 'production',
},
},
- },
+ });
+}
- plugins: [
- // WebAuthn passkeys, a second sign-in method alongside email + password. A
- // passkey is added to an already signed-in account (passkey.addPasskey) and
- // then used to sign in (signIn.passkey). Adds the `passkey` table.
- passkey({
- rpID: passkeyRpID,
- rpName: process.env.PASSKEY_RP_NAME ?? "It's a Plan",
- // Expected origin(s) of the WebAuthn ceremony — the frontend origins.
- origin: trustedOrigins,
- }),
- // Personal API keys: a signed-in user creates a named key, sees its value once
- // at creation, and can list (value hidden) or delete it. Adds the `apikey` table.
- // enableSessionForAPIKeys makes a request carrying an `x-api-key` header resolve
- // to the key owner's session, so getSession (and every planner guard built on it)
- // accepts API keys without any change in apps/api. Rate limit: 100 requests per
- // second per key (timeWindow is in milliseconds). The ceiling is set for the
- // heaviest legitimate caller rather than a typical one: an internal AI agent runs
- // on its own key and dispatches every tool call through a route, and a model that
- // emits a batch of tool calls in one step turns them into a burst of requests.
- apiKey({
- enableSessionForAPIKeys: true,
- // Brand prefix so a leaked key is identifiable by secret scanners and in logs.
- // The trailing underscore separates it from the random part (itp_<64 chars>).
- defaultPrefix: 'itp_',
- // A key is a full-account credential, so one that was forgotten stops working
- // on its own. The caller may pick a shorter or longer life up to the maximum;
- // an agent's key is the exception, cleared where it is issued in apps/api.
- keyExpiration: {
- defaultExpiresIn: API_KEY_DEFAULT_EXPIRES_IN_SEC,
- maxExpiresIn: API_KEY_MAX_EXPIRES_IN_DAYS,
- },
- rateLimit: {
- enabled: true,
- timeWindow: 1000,
- maxRequests: 100,
- },
- }),
- // Sign-in by emailed link, offered alongside the password. Whether it is
- // available is an instance setting, so the plugin is always mounted and the
- // sender refuses when it is off. It reuses the `verification` table — no new
- // table, so `auth:generate` output is unchanged.
- magicLink({
- // Stored plain, an OAuth state also passes as a token (GHSA-965c-763c-88jm).
- storeToken: 'hashed',
- sendMagicLink: async ({ email, url }) => {
- const settings = await getAuthSettings();
- if (!settings.magicLink) {
- throw new APIError('FORBIDDEN', { message: 'Magic links are disabled on this instance' });
- }
- await sendAuthEmail({
- to: email,
- subject: 'Your sign-in link',
- text: 'Use the link below to sign in. It works once and expires shortly.',
- url: withPublicOrigin(url),
- });
- },
- }),
- // The instance's OIDC provider, configured in god mode; see oidcProvider above.
- instanceOidc(),
- // 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
- // name rather than an address. Nobody is asked for one — the create hook above
- // derives it from the address, and the profile page changes it afterwards.
- username({
- minUsernameLength: USERNAME_MIN_LENGTH,
- maxUsernameLength: USERNAME_MAX_LENGTH,
- }),
- // OAuth 2.1 for Streamable HTTP MCP clients, on top of the existing session. Any
- // client registers itself (RFC 7591), as ChatGPT and Claude do. The access tokens
- // are JWTs signed by jwt(); no screen reads a session JWT, so it does not put one
- // on every session response.
- ...(mcpOAuth
- ? [
- jwt({ disableSettingJwtHeader: true, jwt: { issuer: MCP_ISSUER } }),
- mcp({
- resource: MCP_RESOURCE,
- loginPage: `${trustedOrigins[0]}/login`,
- consentPage: `${trustedOrigins[0]}/oauth/consent`,
- // Every token acts for a person; client_credentials would mint one for none.
- grantTypes: ['authorization_code', 'refresh_token'],
- allowDynamicClientRegistration: true,
- allowUnauthenticatedClientRegistration: true,
- }),
- ]
- : []),
- // OpenAPI reference for the better-auth handler. Serves a Scalar UI at
- // /api/auth/reference and the raw schema at /api/auth/open-api/generate-schema.
- // The schema is built from every active plugin, so the passkey and apiKey
- // endpoints are documented automatically. This is docs-only: it adds no table,
- // so `auth:generate` is not needed. The planner's own OpenAPI docs stay at /docs.
- openAPI(),
- ],
-
- // The frontend runs on a different origin (Next :3001) — allow its requests.
- trustedOrigins,
-
- // /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. jwt()'s /token hands out a JWT of the session, which nothing reads.
- disabledPaths: ['/is-username-available', '/token'],
-
- advanced: {
- // Share the session cookie across subdomains when COOKIE_DOMAIN is the parent
- // domain (e.g. ".itsaplan.dev" for app.itsaplan.dev + api.itsaplan.dev). Without
- // it the cookie is host-only for the api origin, so the SSR web app on another
- // subdomain cannot read the session. Leave COOKIE_DOMAIN unset on localhost
- // (single host), where "lax" host-only cookies already work across ports.
- ...(cookieDomain
- ? {
- crossSubDomainCookies: {
- enabled: true,
- domain: cookieDomain,
- },
- }
- : {}),
- // For a single site (localhost / one domain) "lax" is enough. Subdomains of one
- // registrable domain are same-site, so "lax" cookies are still sent between them.
- ...(hostPrefixedCookies
- ? {
- useSecureCookies: false,
- cookiePrefix: '__Secure-better-auth',
- cookies: Object.fromEntries(
- SESSION_COOKIES.map((name) => [
- name,
- { name: `__Host-better-auth.${name}`, attributes: { path: '/', secure: true } },
- ]),
- ),
- }
- : {}),
- defaultCookieAttributes: {
- sameSite: 'lax',
- secure: hostPrefixedCookies || process.env.NODE_ENV === 'production',
- },
- },
+let instance: ReturnType<typeof createAuth> | undefined;
+const instanceOf = () => (instance ??= createAuth());
+
+export const auth = new Proxy({} as ReturnType<typeof createAuth>, {
+ get: (_target, key) => Reflect.get(instanceOf(), key),
+ has: (_target, key) => Reflect.has(instanceOf(), key),
});
export type Auth = typeof auth;
@@ -970,6 +1001,10 @@ export {
REGISTRATION_MODES,
getAuthSettings,
setAuthSettings,
+ emailDomainAllowed,
+ registrationEmailAllowed,
+ setRegistrationEmailPolicy,
+ setRegistrationAdmission,
inviteValidSince,
getEmailSettings,
setEmailSettings,
@@ -989,6 +1024,9 @@ export {
verifyScimToken,
setWorkspaceScim,
workspaceScim,
+ setInstanceScimBeside,
+ instanceScimWorkspace,
+ workspacesWithOwnScim,
isAccountDeactivated,
accountsManagedByScim,
} from './instance';
diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.ts
index cebf0c80..9152d1d7 100644
--- a/packages/auth/src/instance.ts
+++ b/packages/auth/src/instance.ts
@@ -1,6 +1,7 @@
import { randomBytes, timingSafeEqual } from 'node:crypto';
import {
db,
+ appSecret,
instanceWorkspaceId,
teamInvite,
getSetting,
@@ -12,8 +13,9 @@ import {
INSTANCE_EMAIL_SECRET_KEY,
type InstanceEmailConfig,
} from '@repo/db';
-import { and, eq, gte, lt } from 'drizzle-orm';
+import { and, eq, gte, like, lt, sql } from 'drizzle-orm';
import { hasEmailProvider, type SmtpConfig } from '@repo/mailer';
+import type { GenericEndpointContext } from 'better-auth';
// Authentication settings: who may register, whether email has to be confirmed,
// which sign-in methods are offered, the mail provider used for authentication email,
@@ -66,6 +68,9 @@ export interface AuthSettings {
// pending invite older than this neither gates registration nor can be accepted.
// 0 disables the limit (invites never expire).
inviteTtlDays: number;
+ // The domains a new account's address must be at, lowercase. Empty admits any address.
+ // Accounts that already exist keep signing in.
+ allowedEmailDomains: string[];
}
function defaultAuthSettings(): AuthSettings {
@@ -77,9 +82,58 @@ function defaultAuthSettings(): AuthSettings {
trustProviderEmails: false,
personalWorkspaces: true,
inviteTtlDays: 7,
+ allowedEmailDomains: [],
};
}
+// A subdomain is not admitted by its parent: listing company.com leaves eu.company.com out.
+export function emailDomainAllowed(email: string, domains: string[]): boolean {
+ if (domains.length === 0) return true;
+ const address = email.trim().toLowerCase();
+ return domains.includes(address.slice(address.lastIndexOf('@') + 1));
+}
+
+type RegistrationEmailPolicy = (email: string) => Promise<boolean>;
+
+const atInstanceDomains: RegistrationEmailPolicy = async (email) =>
+ emailDomainAllowed(email, (await getAuthSettings()).allowedEmailDomains);
+
+// Whether an address may create an account: by default, when it is at one of the
+// instance's allowed domains. A build that lets a workspace keep domains of its own can
+// also admit an address that workspace invited.
+let registrationEmailPolicy = atInstanceDomains;
+
+export function setRegistrationEmailPolicy(next = atInstanceDomains): void {
+ registrationEmailPolicy = next;
+}
+
+export function registrationEmailAllowed(email: string): Promise<boolean> {
+ return registrationEmailPolicy(email);
+}
+
+type RegistrationAdmission = (
+ email: string,
+ ctx: GenericEndpointContext | null,
+) => Promise<boolean>;
+
+const noAdmission: RegistrationAdmission = async () => false;
+
+// Whether an account goes past the registration gate whatever the instance's settings, by
+// the request creating it: a build that manages providers of its own can let one of them
+// create accounts on a closed instance, as SCIM does. It throws to turn the account away.
+let registrationAdmission = noAdmission;
+
+export function setRegistrationAdmission(next = noAdmission): void {
+ registrationAdmission = next;
+}
+
+export function admittedPastGate(
+ email: string,
+ ctx: GenericEndpointContext | null,
+): Promise<boolean> {
+ return registrationAdmission(email, ctx);
+}
+
export async function getAuthSettings(): Promise<AuthSettings> {
const stored = await getSetting<Partial<AuthSettings>>(AUTH_SETTING_KEY);
// Merge over the default so a value written before a field was added stays valid.
@@ -417,22 +471,60 @@ export function workspaceScim(): boolean {
return scimPerWorkspace;
}
+// Set up per workspace, whether the instance workspace's provider still acts on the
+// whole instance, as it does while SCIM is the instance's. A build where one
+// organisation runs the instance keeps its own provider over every account, and a
+// workspace that sets up its own decides who is in that workspace instead.
+let instanceScimBeside = false;
+
+export function setInstanceScimBeside(on = true): void {
+ instanceScimBeside = on;
+}
+
+const instanceScimWide = () => !scimPerWorkspace || instanceScimBeside;
+
+// The workspace whose provider acts on the whole instance, or null when none does.
+export async function instanceScimWorkspace(): Promise<number | null> {
+ return instanceScimWide() ? instanceWorkspaceId(db) : null;
+}
+
// True for an account the instance's identity provider deactivated (`user.active`),
-// while SCIM acts on the whole instance. Such an account cannot sign in, and the api
-// refuses the sessions and keys it already holds.
+// while that provider acts on the whole instance. Such an account cannot sign in, and
+// the api refuses the sessions and keys it already holds.
export function isAccountDeactivated(account: { active?: boolean | null }): boolean {
- return !scimPerWorkspace && account.active === false;
+ return instanceScimWide() && 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.
+// per workspace alone, 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;
+ if (!instanceScimWide()) return true;
const config = await getScimConfig(await instanceWorkspaceId(db));
return config.enabled && config.token.length > 0;
}
+// The workspaces besides the instance's that set up SCIM of their own, read from the
+// redacted mirror. Their own provider decides who is in them, so the instance's groups
+// grant nothing there.
+export async function workspacesWithOwnScim(): Promise<number[]> {
+ if (!scimPerWorkspace) return [];
+ const rows = await db
+ .select({ key: appSecret.key })
+ .from(appSecret)
+ .where(
+ and(
+ like(appSecret.key, 'workspace.%.scim'),
+ sql`${appSecret.redacted}->>'enabled' = 'true'`,
+ sql`${appSecret.redacted}->>'hasToken' = 'true'`,
+ ),
+ );
+ const instanceId = await instanceWorkspaceId(db);
+ return rows
+ .map((row) => Number(row.key.split('.')[1]))
+ .filter((id) => Number.isInteger(id) && id !== instanceId);
+}
+
// 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.
diff --git a/packages/db/AGENTS.md b/packages/db/AGENTS.md
index da3486e9..08313d1a 100644
--- a/packages/db/AGENTS.md
+++ b/packages/db/AGENTS.md
@@ -24,7 +24,7 @@ See root `AGENTS.md` for monorepo-wide rules.
(`@repo/auth`, api, worker), a team's notification providers (api, worker), and the
instance's upload limits and project-storage-quota accounting (api, worker — an
imported attachment is checked against the same limits an interactive upload is).
-- `src/migrate.ts` — programmatic migrator (no drizzle-kit in prod), run by the `migrate` compose service, the api pods' init container, and the api image's CMD.
+- `src/migrate.ts` — programmatic migrator (no drizzle-kit in prod), run by the `migrate` compose service, the api pods' init container, and the api image's CMD. With `BUILD_MIGRATIONS_DIR` set, it applies that folder too, after the core's, under the same lock and backup: a build's own tables, recorded in `drizzle.__build_migrations`.
- `src/wait-for-migrations.ts` — exits once the database holds this release's migrations; the Helm init container of the worker and bot pods.
- `drizzle/` — generated SQL migrations (committed).
diff --git a/packages/db/package.json b/packages/db/package.json
index 6850a805..05c157a7 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -12,6 +12,7 @@
"db:migrate": "drizzle-kit migrate",
"db:studio": "drizzle-kit studio",
"lint": "eslint .",
+ "test": "bun test --env-file=../../.env.test",
"typecheck": "tsc --noEmit"
},
"dependencies": {
diff --git a/packages/db/src/__tests__/backup.test.ts b/packages/db/src/__tests__/backup.test.ts
new file mode 100644
index 00000000..c8c2a720
--- /dev/null
+++ b/packages/db/src/__tests__/backup.test.ts
@@ -0,0 +1,21 @@
+import { afterAll, expect, it } from 'bun:test';
+import postgres from 'postgres';
+import { pendingMigrations } from '../backup';
+
+// Runs against the migrated test database, whose core table holds rows.
+const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
+afterAll(() => sql.end());
+
+it('counts every migration of a build whose table does not exist yet as pending', async () => {
+ const journal = {
+ entries: [
+ { when: 2, tag: '0001_b' },
+ { when: 1, tag: '0000_a' },
+ ],
+ };
+ expect(await pendingMigrations(sql, journal)).toEqual([]);
+ expect(await pendingMigrations(sql, journal, '__missing_migrations')).toEqual([
+ '0000_a',
+ '0001_b',
+ ]);
+});
diff --git a/packages/db/src/backup.ts b/packages/db/src/backup.ts
index d4684b63..5f4bc452 100644
--- a/packages/db/src/backup.ts
+++ b/packages/db/src/backup.ts
@@ -34,18 +34,33 @@ interface JournalEntry {
tag: string;
}
+const CORE_TABLE = '__drizzle_migrations';
+
+// The newest row of a drizzle bookkeeping table, or null when the table is missing or
+// empty.
+async function lastApplied(sql: Sql, table: string): Promise<string | null> {
+ const [found] = await sql<{ exists: boolean }[]>`
+ select to_regclass(${`drizzle.${table}`}) is not null as exists
+ `;
+ if (!found?.exists) return null;
+ const [applied] = await sql<{ last: string | null }[]>`
+ select max(created_at)::text as last from drizzle.${sql(table)}
+ `;
+ return applied?.last ?? null;
+}
+
// The migrations drizzle is about to apply: the journal entries newer than the last
// row of its own table, which is exactly what its migrator compares.
export async function pendingMigrations(
sql: Sql,
journal: { entries: JournalEntry[] },
+ table = CORE_TABLE,
): Promise<string[]> {
- const [applied] = await sql<{ last: string | null }[]>`
- select max(created_at)::text as last from drizzle.__drizzle_migrations
- `.catch(() => [{ last: null }]);
- // No drizzle table, or an empty one: the database is new and holds nothing to dump.
- if (!applied?.last) return [];
- const last = Number(applied.last);
+ const core = await lastApplied(sql, CORE_TABLE);
+ // No core table, or an empty one: the database is new and holds nothing to dump.
+ if (core === null) return [];
+ // A build's table that is missing or empty has every migration of the build ahead of it.
+ const last = Number((table === CORE_TABLE ? core : await lastApplied(sql, table)) ?? 0);
return journal.entries
.filter((e) => e.when > last)
.sort((a, b) => a.when - b.when)
diff --git a/packages/db/src/migrate.ts b/packages/db/src/migrate.ts
index 4af74e9a..2d0a9062 100644
--- a/packages/db/src/migrate.ts
+++ b/packages/db/src/migrate.ts
@@ -25,6 +25,13 @@ const db = drizzle(migrationClient);
const migrationsFolder = fileURLToPath(new URL('../drizzle', import.meta.url));
+// A build's own tables, kept apart from the core's: its migrations folder, applied after
+// the core's under the same lock and backup, with a bookkeeping table of its own.
+const buildFolder = process.env.BUILD_MIGRATIONS_DIR;
+const BUILD_TABLE = '__build_migrations';
+const readJournal = (folder: string) =>
+ JSON.parse(readFileSync(`${folder}/meta/_journal.json`, 'utf8'));
+
// Compose orders the api behind a healthy postgres, but a platform without that
// guarantee (Railway, plain `docker run`) starts both at once and the first
// connections are refused. Wait for the server separately so a failing migration
@@ -61,8 +68,12 @@ if (!locked) {
// SKIP_PRE_MIGRATION_BACKUP=1 is for an operator who backs up by other means, and is
// what `db:migrate:test` sets — BACKUP_DIR is a path only the api container has, and
// a test database that is truncated between tests has nothing to go back to.
-const journal = JSON.parse(readFileSync(`${migrationsFolder}/meta/_journal.json`, 'utf8'));
-const pending = await pendingMigrations(migrationClient, journal);
+const pending = [
+ ...(await pendingMigrations(migrationClient, readJournal(migrationsFolder))),
+ ...(buildFolder
+ ? await pendingMigrations(migrationClient, readJournal(buildFolder), BUILD_TABLE)
+ : []),
+];
const skipBackup = process.env.SKIP_PRE_MIGRATION_BACKUP === '1';
let backup = null;
@@ -82,6 +93,7 @@ if (pending.length > 0 && !skipBackup) {
console.log('⏳ Running migrations...');
await migrate(db, { migrationsFolder });
+if (buildFolder) await migrate(db, { migrationsFolder: buildFolder, migrationsTable: BUILD_TABLE });
if (pending.length > 0) await recordMigrationRun(migrationClient, pending);
if (backup) await recordBackup(migrationClient, backup);
const removed = await pruneBackups();