Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(auth): provider-agnostic SAML SSO account linking (pre-seed) (#1508)
Brad Barbine0c8357d626e
diff --git a/.ai/plans/2026-08-29-saml-sso-account-linking.md b/.ai/plans/2026-08-29-saml-sso-account-linking.mdnew file mode 100644index 0000000000..fec13c05aa--- /dev/null+++ b/.ai/plans/2026-08-29-saml-sso-account-linking.md@@ -0,0 +1,253 @@+# SAML SSO account linking — implementation plan++**Spec:** .ai/specs/2026-08-29-saml-sso-account-linking.md (see §0 Design revision v2 — authoritative)+**Branch:** little-rock+**Posture:** staff-operated v1; app-layer (no DB triggers T1–T4); reuse `ssoConnection`/`ssoDomain`;+provider-agnostic linking keyed on the `auth.identities.email` column. Full code + unit tests ++migration rollback-validation; **draft PR flagged e2e-unverified** (needs a SAML env + the+`crbnos/supabase` fork's `GOTRUE_DISABLE_SIGNUP=true` + Kong/allow-list fixes — not in this repo).++## Progress+- [ ] Task 1: Pre-seed helpers in `provisioning.server.ts` (+ pure unit-tested builders)+- [ ] Task 2: Wire backfill + audit into `verifySsoDomain`; wire removal into `removeSsoDomain`+- [ ] Task 3: Seed newly-invited users in the three account-creation flows+- [ ] Task 4: Migration — `auth.sso_domains` guard trigger + `ssoReservedDomain` (defense-in-depth)+- [ ] Task 5: Unit tests + migration rollback-validation script+- [ ] Task 6: Docs (AGENTS.md, spec→implemented note) + draft PR++## Dependencies+- Task 2, 3 need Task 1 (helpers). Task 4 is independent of 1–3. Task 5 needs 1–4. Task 6 last.++---++## Task 1: Pre-seed helpers in provisioning.server.ts++**Files:**+- Modify: `packages/ee/src/sso/provisioning.server.ts` — add three server helpers + two pure builders.+- Copy from (precedent): `linkSsoIdentityToUser` in the same file (raw `sql` over `auth.identities`,+ `{ data, error }` return, `try/catch` + logger).++**Steps:**+1. Add a pure, exported, unit-testable builder:+ ```ts+ // The provider column value for a GoTrue SSO provider id.+ export function ssoProviderColumn(providerId: string): string {+ return `sso:${providerId}`;+ }+ // The lowercased domain of an email, or null. Mirrors uncoveredSsoDomainError's split.+ export function emailDomain(email: string): string | null {+ return email.split("@")[1]?.trim().toLowerCase() ?? null;+ }+ ```+2. `seedSsoIdentityForUser(db, { userId, email, providerId })` — insert ONE pre-seed row. The+ load-bearing match is the generated `email` column (`lower(identity_data->>'email')`); `provider_id`+ is a readable placeholder. Provider-agnostic (works for any IdP via GoTrue's email fallback).+ ```sql+ INSERT INTO auth.identities (provider_id, user_id, identity_data, provider, created_at, updated_at)+ VALUES (${lowerEmail}, ${userId}::uuid,+ jsonb_build_object('sub', ${lowerEmail}::text, 'email', ${lowerEmail}::text),+ ${'sso:' + providerId}, now(), now())+ ON CONFLICT (provider_id, provider) DO NOTHING+ ```+ Return `{ data: { seeded: boolean } | null, error }`. Lowercase the email in TS before binding.+3. `backfillSsoIdentitiesForDomain(db, { providerId, domain })` — set-based seed of every existing+ non-SSO user on the domain (adopted policy §4: verified owner controls the domain instance-wide, so+ NOT company-scoped). Return the linked user ids for audit.+ ```sql+ INSERT INTO auth.identities (provider_id, user_id, identity_data, provider, created_at, updated_at)+ SELECT lower(u.email), u.id,+ jsonb_build_object('sub', lower(u.email), 'email', lower(u.email)),+ ${'sso:' + providerId}, now(), now()+ FROM auth.users u+ WHERE u.email IS NOT NULL AND u.is_sso_user = false+ AND lower(split_part(u.email, '@', 2)) = ${lowerDomain}+ ON CONFLICT (provider_id, provider) DO NOTHING+ RETURNING user_id+ ```+ Return `{ data: { linkedUserIds: string[] } | null, error }`.+4. `removeSsoIdentitiesForDomain(db, { providerId, domain })` — delete this domain's SSO identities,+ keyed on the `email` column so it also catches GoTrue's self-healed opaque-NameID rows:+ ```sql+ DELETE FROM auth.identities+ WHERE provider = ${'sso:' + providerId}+ AND lower(split_part(email, '@', 2)) = ${lowerDomain}+ ```+ Return `{ data: { removed: number } | null, error }`.+5. Match the existing file's error handling exactly (logger.error + `{ data: null, error }`).++**Verify:**+```bash+pnpm --filter @carbon/ee typecheck+# Expected: no errors+```++**Out of scope:** touching `linkSsoIdentityToUser` / `migrateUserToSso` / `deleteJitSsoUser` (the+DISABLE_SIGNUP=false repair path — left intact as a fallback), `is_sso_user`.++---++## Task 2: Wire backfill + audit into verifySsoDomain; removal into removeSsoDomain++**Depends on:** Task 1+**Files:**+- Modify: `packages/ee/src/sso/connections.server.ts` — add a `db: Kysely<KyselyDatabase>` param to+ `verifySsoDomain` and `removeSsoDomain`; call the Task-1 helpers after the existing success writes.+- Modify: `apps/erp/app/routes/x+/settings+/sso.tsx` — pass `getDatabaseClient()` at both call sites+ (`intent === "verifyDomain"`, `intent === "removeDomain"`).+- Audit: import `insertAuditLogEntries` from `@carbon/database` (see `packages/database/src/audit.ts:205`).++**Steps:**+1. `verifySsoDomain(serviceRole, db, args)`: after the `update` at line 345–356 succeeds (row flipped+ to `verified`), call `backfillSsoIdentitiesForDomain(db, { providerId: connection.data.providerId,+ domain: row.data.domain })`. On its error, log and continue (verification already committed — do NOT+ fail the verify). Then best-effort audit (wrapped in try/catch, never throws):+ `insertAuditLogEntries(serviceRole, args.companyId, [{ tableName: "auth.identities", entityType:+ "ssoIdentityBackfill", entityId: row.data.domain, recordId: row.data.domain, operation: "INSERT",+ actorId: args.userId, diff: null, metadata: { domain, providerId, linkedCount, requestId: null,+ ipAddress: null, userAgent: null, origin: null } }])` — confirm the exact `CreateAuditLogEntry`+ shape in `packages/database/src/audit.types.ts` and match it. If audit is disabled for the company+ the RPC errors — swallow + log (a privilege event we try to record, but must not block verify).+2. `removeSsoDomain(serviceRole, db, args)`: after the row is deleted and GoTrue re-synced (line 388+),+ if `wasVerified`, call `removeSsoIdentitiesForDomain(db, { providerId: connection.providerId, domain:+ row.data.domain })`. Needs the connection's providerId — read it via `getSsoConnection` as the+ existing `wasVerified` branch already does (line 402). On error, log + continue.+3. Update `sso.tsx`: `import { getDatabaseClient } from "~/services/database.server";` and pass it as the+ new 2nd arg in both calls.++**Verify:**+```bash+pnpm --filter @carbon/ee typecheck && pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++**Out of scope:** changing the shipped GoTrue-sync ordering in verify/remove (its lockout-avoidance+reasoning is load-bearing — the guard in Task 4 is designed around it).++---++## Task 3: Seed newly-invited users in the three account-creation flows++**Depends on:** Task 1+**Files:**+- Modify: `apps/erp/app/modules/users/users.server.ts` — after each of `createEmployeeAccount`,+ `createCustomerAccount`, `createSupplierAccount` resolves the auth user id and creates the user,+ seed an SSO identity when the email's domain already has a verified connection.+- Read first: the three flows (around L293/408/549 per the code map) to find the exact point after+ `resolveAuthUserId` + `createUser` where `userId`, `email`, a service-role client, and a db handle+ are all in scope.++**Steps:**+1. Add a small server helper (co-located, e.g. in `users.server.ts` or a thin wrapper over Task 1):+ `maybeSeedSsoIdentity(serviceRole, db, { userId, email })` that calls `getSsoConnectionByDomain`+ (`@carbon/ee/sso.server`) for `emailDomain(email)`; if a verified connection exists, calls+ `seedSsoIdentityForUser(db, { userId, email, providerId: connection.providerId })`. Best-effort:+ log on error, never throw (account creation must not fail because seeding failed — the user still+ works via the backfill path or the callback repair fallback).+2. Call it in all three flows after the account row + auth user exist. If any flow lacks a Kysely db+ handle, thread `getDatabaseClient()` from the caller — **if a flow's shape makes this unsafe+ (e.g. it runs before the auth user is committed), STOP and report; do not reorder account creation.**+3. `isSsoEnabled()` self-gates `getSsoConnectionByDomain`, so off-Enterprise this is a no-op.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++**Out of scope:** the invite-acceptance / callback flow (already handled by `migrateUserToSso`).++---++## Task 4: Migration — auth.sso_domains guard + ssoReservedDomain (defense-in-depth)++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/<ts>_sso-domain-guard.sql` via+ `pnpm db:migrate:new sso-domain-guard` (never `000000` HHMMSS).++**Steps:**+1. `ssoReservedDomain` table: `("domain" TEXT PRIMARY KEY)`, seeded with the same values as+ `PUBLIC_EMAIL_DOMAINS` in `apps/erp/app/modules/settings/settings.models.ts` PLUS Carbon-own domains+ (`carbon.ms`, `carbon.us.org`, `carbonms.onmicrosoft.com` — verify current list). Add a header+ comment cross-referencing `PUBLIC_EMAIL_DOMAINS` to keep them in sync. This table is NOT+ company-scoped (global reserved list) — RLS: enable + a permissive `SELECT` for authenticated,+ no write policy (staff/service-role only). Use `INSERT ... ON CONFLICT DO NOTHING` for idempotency.+2. Guard function + trigger on `auth.sso_domains` (precedent: `create_public_user` on `auth.users`,+ `SECURITY DEFINER SET search_path = public` per house convention):+ ```sql+ CREATE OR REPLACE FUNCTION auth.enforce_sso_domain_claim() RETURNS TRIGGER+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public AS $$+ BEGIN+ IF current_setting('app.sso_domain_override', true) = 'on' THEN RETURN NEW; END IF;+ IF EXISTS (SELECT 1 FROM public."ssoReservedDomain" WHERE lower("domain") = lower(NEW."domain")) THEN+ RAISE EXCEPTION 'auth.sso_domains insert blocked: % is a reserved domain', NEW."domain";+ END IF;+ IF NOT EXISTS (SELECT 1 FROM public."ssoDomain" WHERE lower("domain") = lower(NEW."domain")) THEN+ RAISE EXCEPTION 'auth.sso_domains insert blocked: no ssoDomain claim for %', NEW."domain";+ END IF;+ RETURN NEW;+ END $$;+ DROP TRIGGER IF EXISTS enforce_sso_domain_claim ON auth.sso_domains;+ CREATE TRIGGER enforce_sso_domain_claim BEFORE INSERT ON auth.sso_domains+ FOR EACH ROW EXECUTE FUNCTION auth.enforce_sso_domain_claim();+ ```+ NOTE: requires a *claim row* (any status), NOT `verified`, because the shipped `verifySsoDomain`+ syncs GoTrue (which writes `auth.sso_domains`) while the row is still `pending` — a verified-only+ guard would break the happy path or force a lockout-prone reorder. Reserved domains can never get a+ claim row via the app validator anyway; the reserved check makes that hold in-DB too.+3. Idempotent: `CREATE TABLE IF NOT EXISTS`, `CREATE OR REPLACE FUNCTION`, `DROP TRIGGER IF EXISTS`.+4. `pnpm run generate:types` after — **only if the local DB is reachable and the migration applies.**+ `ssoReservedDomain` is not referenced from TS (guard is SQL-only), so a types regen is not required+ to typecheck. If the DB is not reachable, document the regen as a deploy step. **Do NOT rebuild the+ DB to test — wait for the user.**++**Verify:**+```bash+# Rolled-back psql transaction (see Task 5). Do not run a full db:migrate rebuild.+```++**Out of scope:** touching `auth.sso_providers`, `create_public_user`, or the `ssoDomain`/`ssoConnection`+tables' definitions.++---++## Task 5: Unit tests + migration rollback-validation++**Depends on:** Tasks 1–4+**Files:**+- Create: `packages/ee/src/sso/provisioning.test.ts` (or extend an existing sibling test) — pure-fn tests+ for `emailDomain`, `ssoProviderColumn` (edge cases: no `@`, uppercase, whitespace, subdomains).+- Create: `.ai/runs/2026-08-29-sso-domain-guard-rollback.sql` — a BEGIN/…/ROLLBACK script (precedent:+ memory `reference_migration_rollback_validation`) asserting: (a) inserting `auth.sso_domains` for a+ domain with a `ssoDomain` claim succeeds; (b) without a claim → RAISES; (c) for a reserved domain →+ RAISES; (d) with `set_config('app.sso_domain_override','on',true)` → succeeds. Run via `supabase_admin`+ if the DB is reachable; otherwise leave it as a documented validation artifact.++**Verify:**+```bash+pnpm --filter @carbon/ee test+# Expected: new tests pass+```++**Out of scope:** e2e SAML flow (env-gated — documented in the PR, not tested here).++---++## Task 6: Docs + draft PR++**Depends on:** Tasks 1–5+**Files:**+- Modify: `packages/ee/AGENTS.md` — add the new `provisioning.server.ts` exports + the pre-seed model to+ the SSO bullet.+- Modify: `.claude/rules/authentication-system.md` — if it documents the SSO linking flow, add the+ pre-seed/DISABLE_SIGNUP=true model (read first; only if it covers this).+- Modify: `.ai/specs/2026-08-29-saml-sso-account-linking.md` — leave in place; move to+ `specs/implemented/` only after e2e verification (it is not verified here).+- Commit via `/check-and-commit`; open a **draft** PR onto `main` with the deployment prerequisites and+ the e2e-unverified flag spelled out.++**Verify:**+```bash+gh pr view --json isDraft,title+# Expected: isDraft = true+```diff --git a/.ai/runs/2026-08-29-sso-domain-guard-rollback.sql b/.ai/runs/2026-08-29-sso-domain-guard-rollback.sqlnew file mode 100644index 0000000000..c4bde53a57--- /dev/null+++ b/.ai/runs/2026-08-29-sso-domain-guard-rollback.sql@@ -0,0 +1,70 @@+-- Rollback-validation for 20260829142619_sso-domain-guard.sql+--+-- Proves the auth.sso_domains guard trigger without leaving any state behind.+-- Everything runs inside ONE transaction that always ROLLBACKs, so it is safe to+-- point at a development database. Run as a superuser/`supabase_admin` (the+-- migration + auth schema require it):+--+-- psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 -f .ai/runs/2026-08-29-sso-domain-guard-rollback.sql+--+-- NOTE (2026-08-29): authored but NOT executed here — the local DB was not+-- running. Run it once the migration is applied. Expected final line: "ALL GUARD+-- ASSERTIONS PASSED", then the ROLLBACK.++BEGIN;++-- Apply the migration under test (idempotent: CREATE TABLE IF NOT EXISTS /+-- CREATE OR REPLACE / DROP TRIGGER IF EXISTS). Safe whether or not it is already+-- applied on this database.+\i packages/database/supabase/migrations/20260829142619_sso-domain-guard.sql++-- A GoTrue SSO provider to satisfy auth.sso_domains.sso_provider_id (FK).+INSERT INTO auth.sso_providers ("id", "created_at", "updated_at")+VALUES ('99999999-9999-4999-8999-999999999999', now(), now());++DO $$+DECLARE+ raised boolean;+BEGIN+ -- 1) An UNCLAIMED domain (no public.ssoDomain row) must be rejected.+ raised := false;+ BEGIN+ INSERT INTO auth.sso_domains ("id", "sso_provider_id", "domain", "created_at", "updated_at")+ VALUES (gen_random_uuid(), '99999999-9999-4999-8999-999999999999', 'unclaimed.example', now(), now());+ EXCEPTION WHEN others THEN+ raised := true;+ ASSERT SQLERRM LIKE '%no ssoDomain claim%',+ 'unclaimed domain raised the wrong error: ' || SQLERRM;+ END;+ ASSERT raised, 'expected an unclaimed domain to be BLOCKED, but the insert succeeded';++ -- 2) A RESERVED domain must be rejected even if (hypothetically) claimed.+ raised := false;+ BEGIN+ INSERT INTO auth.sso_domains ("id", "sso_provider_id", "domain", "created_at", "updated_at")+ VALUES (gen_random_uuid(), '99999999-9999-4999-8999-999999999999', 'gmail.com', now(), now());+ EXCEPTION WHEN others THEN+ raised := true;+ ASSERT SQLERRM LIKE '%reserved domain%',+ 'reserved domain raised the wrong error: ' || SQLERRM;+ END;+ ASSERT raised, 'expected a reserved domain to be BLOCKED, but the insert succeeded';++ -- 3) The staff override bypasses the guard entirely (own-domain setup path).+ PERFORM set_config('app.sso_domain_override', 'on', true);+ INSERT INTO auth.sso_domains ("id", "sso_provider_id", "domain", "created_at", "updated_at")+ VALUES (gen_random_uuid(), '99999999-9999-4999-8999-999999999999', 'gmail.com', now(), now());+ PERFORM set_config('app.sso_domain_override', 'off', true);+ ASSERT EXISTS (+ SELECT 1 FROM auth.sso_domains WHERE "domain" = 'gmail.com'+ ), 'override should have allowed the insert';++ RAISE NOTICE 'ALL GUARD ASSERTIONS PASSED';+END $$;++-- Happy path (a real, verified claim is allowed) is exercised end-to-end by+-- verifySsoDomain in packages/ee/src/sso/connections.server.ts and is not+-- re-seeded here — it would require the full company/user/ssoConnection/ssoDomain+-- FK chain. The three assertions above cover the guard's security logic.++ROLLBACK;diff --git a/.ai/specs/2026-08-29-saml-sso-account-linking.md b/.ai/specs/2026-08-29-saml-sso-account-linking.mdnew file mode 100644index 0000000000..ab83006af3--- /dev/null+++ b/.ai/specs/2026-08-29-saml-sso-account-linking.md@@ -0,0 +1,382 @@+# SAML SSO Account Linking++> Status: proposed+> Author: Claude (with Brad Barbin)+> Date: 2026-08-29++## TLDR++SAML SSO cannot sign in any user who already exists. GoTrue places SSO identities in their own+account-linking domain and **never** links them to `email` / `google` / `azure` identities, so every+SSO sign-in resolves to *create a new user* — which `GOTRUE_DISABLE_SIGNUP=true` rejects with+`422: Signups not allowed for this instance`. Because Carbon provisions users by invite (the app+creates `auth.users` rows via the admin API), **every** invited employee hits this, forever.++The fix is to treat SSO as *another identity on the existing person* rather than a separate user:+pre-seed the `sso:<provider_id>` identity row so GoTrue's linking returns `AccountExists`. That part+is ~80 lines of SQL. The part that must ship first is an **activation gate**: GoTrue scopes SSO by+email domain *globally*, Carbon scopes by `companyId`, and in production those don't align —+`acme.com` users are employees of all 8 companies. Without domain-ownership verification, "activate+SSO" is an account-takeover primitive.++**Ship order is load-bearing: §5 (gate) before §6 (linking).** §6 alone converts a currently-inert+misconfiguration into a live takeover path.++---++## 0. Design revision (v2, 2026-08-29) — grounded against shipped code++The sections below were written before auditing PR #1455, which already shipped much of §5, and+before verifying GoTrue v2.177.0's linking internals across IdPs. The **implemented** design (see+`.ai/plans/2026-08-29-saml-sso-account-linking.md`) corrects three things. Where §5/§6 below conflict+with this section, **this section wins**.++1. **Reuse #1455's tables, don't create `ssoDomainClaim`.** `ssoConnection` + `ssoDomain` (with a+ `pending → verified` DNS-TXT lifecycle in `packages/ee/src/sso/verification.server.ts`,+ `_carbon-challenge.<domain>` / `carbon-domain-verification=<token>`) already are the claim table.+ The reserved-domain list already exists as `PUBLIC_EMAIL_DOMAINS` in `settings.models.ts`.++2. **Key linking on the `auth.identities.email` column, not `provider_id` — this is the+ provider-agnostic fix.** GoTrue v2.177.0 marks every SAML assertion email `Verified` (hardcoded)+ and hard-rejects (400) an assertion with no extractable email, so its email-column fallback in+ `DetermineAccountLinking` fires on *every* successful SAML sign-in, for *any* IdP (Okta, Entra,+ OneLogin, Ping, Google, JumpCloud, ADFS). Pre-seeding a row with `provider = 'sso:<providerId>'`+ and `identity_data.email = lower(email)` (so the generated `email` column = `lower(email)`) makes+ GoTrue `LinkAccount` to the existing user regardless of the NameID's shape. It then self-heals: the+ next login's `provider_id == NameID` lookup hits the row GoTrue created. The spec's original+ `provider_id = email` keying only worked because Okta's NameID *is* the email; Entra's default is an+ opaque persistent pairwise id, which that key misses. `provider_id` is now just a human-readable+ placeholder; the email column carries the match.++3. **§5.5 changes from "require email-format NameID" to a live-assertion email check.** Requiring+ `NameID Format = emailAddress` wrongly rejects Entra and is neither necessary nor sufficient. The+ real guarantees (operational, validated from a captured test assertion at activation — not a config+ string): (a) GoTrue extracts a non-empty email (guards ADFS/no-email-claim and Entra null-`user.mail`+ — these fail *loud* with a 400, not silently), and (b) that email equals the seeded `lower(email)`+ (guards Entra B2B guests whose email resolves to the mangled `user_..#EXT#@tenant.onmicrosoft.com`+ UPN, and secondary-address mismatches). Under `DISABLE_SIGNUP=true`, a mismatch is a visible 422, not+ a silent duplicate user.++**Mechanism, implementation, and prerequisites of v2:**++- **Architecture: pre-seed under `DISABLE_SIGNUP=true`.** #1455 was built for the *opposite* config —+ it lets GoTrue JIT-create a user, then repairs it in `callback.tsx` (`linkSsoIdentityToUser`). That+ repair needs `DISABLE_SIGNUP=false`; production runs `true`, so GoTrue 422s at step one and the whole+ repair path is dead code in production. Pre-seeding makes GoTrue take the `LinkAccount`/`AccountExists`+ branch, which needs no signup — so `DISABLE_SIGNUP=true` stays, and the email self-registration hole+ never reopens.+- **Implemented app-layer, matching #1455 (no DB triggers T1–T4).** Pre-seeding lives in+ `packages/ee/src/sso/provisioning.server.ts` and is wired at two points and torn down at a third:+ `verifySsoDomain` backfills every existing on-domain user when a domain is verified (§6's T3);+ the three account-creation flows (`createEmployeeAccount` / `createCustomerAccount` /+ `createSupplierAccount`) seed a newly-invited user whose domain already has a verified connection+ (T1); `removeSsoDomain` deletes that domain's seeded identities, keyed on the `email` column so it+ also catches GoTrue's self-healed opaque-NameID rows (T2/T4). The rogue-IdP defense stays where+ #1455 put it — the callback's domain check before any identity write.+- **§5.4 in-DB guard kept as defense-in-depth**, adapted to the shipped verify ordering: a+ `BEFORE INSERT` trigger on `auth.sso_domains` raises unless a `ssoDomain` claim row exists for the+ domain (the shipped flow syncs GoTrue while the row is still `pending`, by a deliberate+ lockout-avoidance ordering — a "verified-only" guard would break it, so the guard requires a *claim*,+ which still blocks injecting an unclaimed domain from Studio/a migration). Reserved domains are+ blocked in-DB too via a seeded `ssoReservedDomain` table (kept in sync with `PUBLIC_EMAIL_DOMAINS`).+ A session-local `app.sso_domain_override` GUC lets staff scripts bypass for Carbon-own domains.+- **OQ4 audit:** `verifySsoDomain` writes a best-effort audit-log entry recording the backfill+ (domain, provider, linked-user count) — a privilege-granting event.+- **Deployment prerequisites (NOT in this repo — the `crbnos/supabase` fork):** keep+ `GOTRUE_DISABLE_SIGNUP=true`; the Kong SAML route + `GOTRUE_URI_ALLOW_LIST` fixes from §10. The+ repo-side code is inert without them, so the PR ships as a draft flagged **e2e-unverified — needs a+ SAML env** (Okta/Entra IdP + DNS). In-repo verification is unit tests + a rolled-back-transaction+ migration check on the guard trigger.++---++## 1. Observed failure++```json+{"error":"422: Signups not allowed for this instance",+ "path":"/sso/saml/acs","status":303,"time":"2026-08-29T04:53:13Z"}+```++GoTrue validates the assertion correctly, then fails at user resolution. The 303 sends the browser+back to `SITE_URL` with an error fragment, which the app renders as a bounce to the login page — so+the surface symptom ("SSO redirects me to login") points nowhere near the actual cause.++## 2. How GoTrue account linking actually works++Verified against `supabase/auth` v2.177.0, the version we run.++| Component | Behavior |+|---|---|+| `internal/models/linking.go` | `GetAccountLinkingDomain` returns `"default"` for email/google/azure, but `"sso:<provider_id>"` for SSO providers |+| `DetermineAccountLinking` | filters candidate identities to those *in the same linking domain*; `len(linkingIdentities) == 0` → `CreateAccount` |+| `internal/api/samlacs.go` | identity provider string is `"sso:" + ssoProvider.ID.String()`; subject is `assertion.UserID()` (the SAML NameID) |+| `internal/api/external.go` | `CreateAccount` + `DisableSignup` → `ErrorCodeSignupDisabled`. The `AccountExists` branch does **not** require `is_sso_user = true` |++The isolation is deliberate — it prevents an IdP from silently seizing accounts it never+authenticated. We are not working around a bug; we are choosing to grant that linkage explicitly,+which is exactly why §5 exists.++Two schema facts that follow from it:++- `auth.users` — `users_email_partial_key UNIQUE (email) WHERE is_sso_user = false`. A duplicate+ email **is** permitted for an SSO user, so GoTrue happily mints a second row for the same human.+- `auth.identities` — `UNIQUE (provider_id, provider)`, no FK to `auth.sso_providers`. Identity rows+ are orphaned, not cascaded, when a provider is deleted.++## 3. Why this is structural for Carbon++1. **UUID immutability.** `public.user.id === auth.users.id`, and that id is referenced by+ `employee`, `userPermission`, `membership`, and every `createdBy` / `updatedBy` audit column in+ the ERP. A person's UUID can never change.+2. **`DISABLE_SIGNUP` is global.** No per-provider toggle exists in v2.177.0. Set to `true`, SAML can+ never provision; set to `false`, email self-registration reopens instance-wide.+3. **Invite-based provisioning.** `createEmailAuthAccount` and `resolveAuthUserId`+ (`packages/auth/src/services/auth.server.ts`, `apps/erp/app/modules/users/users.server.ts`) create+ **non-SSO** users. Every invited employee is therefore unlinkable by construction.+4. **The existing trigger refuses duplicates.** `create_public_user` bails when the email already+ belongs to a different id:+ ```sql+ IF email_owner IS NOT NULL AND email_owner <> NEW.id::text THEN RETURN NEW; END IF;+ ```+ So even with signups enabled, a JIT-provisioned SSO user gets **no** `user` row and **no**+ `userPermission` row — authenticated by the IdP, invisible to the app, bounced to login.++Conclusion: Supabase's intended model (an SSO user is a distinct user) is incompatible with Carbon's+data model. **One person = one UUID; SSO is one more identity on that person.**++## 4. The multi-tenancy hazard++GoTrue scopes SSO by **email domain**, instance-wide — `sso_domains_domain_idx UNIQUE (lower(domain))`.+Carbon scopes by **`companyId`**. Production data as of 2026-08-29:++| companyId | employees | domains |+|---|---|---|+| `COMPANY_1` | 16 | northwind.com, acme.com |+| `COMPANY_2` | 8 | acme.com, internal.example, globex.com |+| `COMPANY_3` | 6 | acme.com, initech.com |+| `COMPANY_4` | 5 | umbrella.com, acme.com, stark-industries.com |+| `COMPANY_5` | 2 | acme.com, globex.com |+| 3 others | 1 each | acme.com |++Three consequences:++- **`acme.com` is an employee of all 8 companies.** If any tenant could register `acme.com`, their+ IdP would authenticate as Carbon staff in every tenant. Registering a domain *is* the takeover.+- **`globex.com` spans two companies.** Activating SSO "for their org" necessarily reaches users in+ the other company. Scoping the backfill by company doesn't help — GoTrue keys linking on domain and+ knows nothing about companies, so the unscoped users just fail with the same 422.+- **A domain can be claimed exactly once, instance-wide.** First tenant to activate wins; a second+ tenant with users on that domain has them authenticated by a foreign IdP.++**Adopted policy: the verified domain owner controls identity for that domain, instance-wide.** It+matches GoTrue's unique index, matches how Okta and Google Workspace already reason about domains,+and is the only policy expressible without patching GoTrue.++## 5. Phase 1 — activation gate (ships first)++### 5.1 Domain claim table++Migration in `packages/database/supabase/migrations/`:++```sql+CREATE TABLE "ssoDomainClaim" (+ "id" TEXT PRIMARY KEY,+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,+ "domain" TEXT NOT NULL,+ "verificationToken" TEXT NOT NULL,+ "verifiedAt" TIMESTAMPTZ,+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(),+ "createdBy" TEXT NOT NULL REFERENCES "user"("id")+);+CREATE UNIQUE INDEX "ssoDomainClaim_domain_idx" ON "ssoDomainClaim" (lower("domain"));+```++RLS scoped to `companyId` per `.claude/rules/conventions-database.md`. One claim per domain+instance-wide, mirroring GoTrue's own uniqueness so the two can never disagree.++### 5.2 Verification++DNS TXT at `_carbon.<domain>` containing `carbon-verification=<verificationToken>`. Only on success+is `verifiedAt` set. Re-verify on a schedule; a domain that stops resolving gets flagged, not+silently trusted forever.++### 5.3 Reserved domains++A domain on the reserved list can never be claimed — **consumer mailbox providers only**:+`gmail.com`, `outlook.com`, `hotmail.com`, `yahoo.com`, `icloud.com`, `proton.me`, … A shared+domain is used by unrelated people, so a DNS challenge cannot prove single ownership; it must+never be claimable.++The vendor's own domains are **not** reserved. A domain a company actually controls can be proven+through the same DNS-TXT challenge and set up for SSO like any other — a blanket reservation only+added friction (and the DNS challenge, not a hardcoded list, is the real ownership gate). The+reserved list is seeded in the `ssoReservedDomain` table (§5.4), mirroring `PUBLIC_EMAIL_DOMAINS`.++### 5.4 Defense in depth++App-level gating is not enough on its own, since `auth.sso_domains` can also be written from Studio+or a migration. A `BEFORE INSERT` trigger on `auth.sso_domains` (`enforce_sso_domain_claim`) raises+unless a non-reserved `ssoDomain` claim exists for the domain **AND that claim belongs to the+connection behind `NEW."sso_provider_id"`** — or an explicit staff override flag+(`app.sso_domain_override`) is set. The gate then holds regardless of which path writes the row.++As shipped it requires a claim of **any** status, not `verified`: `verifySsoDomain` calls GoTrue+(which writes `auth.sso_domains`) while the `ssoDomain` row is still `pending`, by a deliberate+lockout-avoidance ordering, so a verified-only guard would refuse the happy path. The+provider-binding join (`ssoDomain` → `ssoConnection` on `connectionId`/`companyId`, then+`ssoConnection."providerId" = NEW."sso_provider_id"`) is what prevents a claimed domain from being+routed to an unrelated company's IdP (CWE-863) — `companyId` on the claim alone can't prove the+provider belongs to the company that passed DNS verification.++### 5.5 IdP NameID requirement++Everything in §6 assumes **SAML NameID == the user's email**. Okta's default (`user.userName`)+satisfies this; an IdP configured for opaque/persistent NameIDs does not, and pre-seeding cannot+work for it. Validate the NameID format at activation and refuse anything other than+`EmailAddress` / `unspecified`-mapped-to-email, with a clear error. Record the decision on the claim+row so a later IdP reconfiguration is detectable.++## 6. Phase 2 — identity linking++### 6.1 Helpers++```sql+CREATE OR REPLACE FUNCTION public.sso_provider_for_email(p_email TEXT)+RETURNS UUID LANGUAGE sql STABLE SECURITY DEFINER SET search_path = '' AS $$+ SELECT d."sso_provider_id" FROM auth.sso_domains d+ WHERE lower(d."domain") = lower(split_part(p_email, '@', 2))+ LIMIT 1+$$;++CREATE OR REPLACE FUNCTION public.link_sso_identity(p_user_id UUID, p_email TEXT)+RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = '' AS $$+DECLARE v_provider UUID;+BEGIN+ IF p_email IS NULL THEN RETURN; END IF;+ v_provider := public.sso_provider_for_email(p_email);+ IF v_provider IS NULL THEN RETURN; END IF;++ INSERT INTO auth.identities+ ("provider_id","user_id","identity_data","provider","created_at","updated_at")+ VALUES+ (lower(p_email), p_user_id,+ jsonb_build_object('sub', lower(p_email), 'email', lower(p_email)),+ 'sso:' || v_provider::text, now(), now())+ ON CONFLICT ("provider_id","provider") DO NOTHING;+END $$;+```++`identity_data.sub` must equal `provider_id`; GoTrue matches on the column, and the JSON is what it+reads back into the session.++### 6.2 Triggers++| # | Trigger | Fires | Purpose |+|---|---|---|---|+| T1 | `AFTER INSERT ON auth.users` | new user created | link if their domain already has SSO |+| T2 | `AFTER UPDATE OF email ON auth.users` | email changed | unlink old domain, link new |+| T3 | `AFTER INSERT ON auth.sso_domains` | **SSO activated** | backfill every existing user in the domain |+| T4 | `AFTER DELETE ON auth.sso_domains` | SSO removed | drop that domain's SSO identities |++T3 is the one that answers "what about the users who already exist" — activation, not user creation,+is when the bulk linkage happens:++```sql+CREATE OR REPLACE FUNCTION public.backfill_sso_identities()+RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = '' AS $$+BEGIN+ INSERT INTO auth.identities+ ("provider_id","user_id","identity_data","provider","created_at","updated_at")+ SELECT lower(u."email"), u."id",+ jsonb_build_object('sub', lower(u."email"), 'email', lower(u."email")),+ 'sso:' || NEW."sso_provider_id"::text, now(), now()+ FROM auth.users u+ WHERE u."email" IS NOT NULL+ AND u."is_sso_user" = false+ AND lower(split_part(u."email", '@', 2)) = lower(NEW."domain")+ ON CONFLICT ("provider_id","provider") DO NOTHING;+ RETURN NEW;+END $$;+```++T4 must scope by domain, not just provider, since one provider may own several domains. `provider_id`+is the email, which makes that exact:++```sql+DELETE FROM auth.identities+ WHERE "provider" = 'sso:' || OLD."sso_provider_id"::text+ AND lower(split_part("provider_id", '@', 2)) = lower(OLD."domain");+```++Cascaded deletes from `auth.sso_providers` fire T4 per row, so provider deletion cleans up too.++### 6.3 What stays unchanged++- `GOTRUE_DISABLE_SIGNUP=true`. With linking automated, JIT is unnecessary; access remains granted by+ invite in the ERP, with the IdP only authenticating.+- `is_sso_user` stays `false`. Users keep their existing password / magic-link / Google / Azure+ logins. **Forcing SSO-only for a domain is a separate, app-level concern** — GoTrue has no+ per-domain enforcement — and is out of scope here.++## 7. Security considerations++| Risk | Mitigation |+|---|---|+| Tenant claims a domain they don't own → takeover of every user on it | §5.2 DNS verification, enforced in-DB by §5.4 |+| Tenant claims `acme.com` (vendor domain) → takeover of staff across all 8 tenants | §5.2 DNS verification — a tenant cannot publish the `_carbon-challenge` TXT record on a domain it does not control, so it can never verify (or register in GoTrue) a domain it doesn't own |+| Tenant claims a consumer domain → links unrelated strangers | §5.3 reserved list (consumer providers only — a DNS challenge can't prove single ownership of a shared domain) |+| IdP asserts an email outside its verified domain | GoTrue matches on `(provider_id, provider)`; an unlinked email yields `CreateAccount` → refused by `DISABLE_SIGNUP` |+| Domain ownership lapses / company offboards | Scheduled re-verification; T4 on domain removal |+| Deactivated employee retains IdP access | App already enforces `employee.active`; unchanged by this spec |++The trust granted is precisely "a verified domain owner may authenticate humans at that domain" —+the same trust Okta and Google Workspace already assume. The spec makes it explicit and verified+rather than implicit and unchecked.++## 8. Rollout++1. **Phase 1** — claim table, DNS verification, reserved list, `auth.sso_domains` guard trigger.+ No linking behavior yet; SSO remains broken. Safe to ship alone.+2. **Phase 2** — helpers + T1/T2/T3/T4. On deploy, T3 does **not** fire for `acme.com`, which is+ already registered; run the backfill once manually for existing domains.+3. **Verify** on `acme.com` (2 users, Carbon staff, lowest blast radius) before offering activation+ to any tenant.++### Acceptance criteria++- An existing invited user signs in via SAML and lands on their **existing** UUID — same+ `public.user` row, same permissions, same audit history.+- That user can still sign in by magic link and Google afterward.+- A newly invited user in an SSO domain can sign in via SAML with no manual step.+- Activating SSO for a domain links all pre-existing users in it, in one transaction.+- Removing the domain removes exactly that domain's SSO identities and no others.+- An unverified domain claim cannot produce an `auth.sso_domains` row by any path, including Studio.+- A reserved domain cannot be claimed by a tenant.+- `auth.users` gains **no** duplicate rows through any of the above.++## 9. Open questions++All resolved 2026-08-29 (Brad):++1. **Self-serve vs staff-operated activation → staff-operated for v1.** Claims are created and+ verified by internal staff only; there is no tenant-facing UI. §5 is therefore defense in depth+ rather than a self-serve gate — but it still ships first, and the in-DB guard on+ `auth.sso_domains` (§5.4) is the real enforcement point regardless of who writes the claim.+2. **Per-domain SSO enforcement (disable password login) → out of scope.** GoTrue has no per-domain+ enforcement; if we build it later it lives in Carbon's login route, not here.+3. **Non-routable domains (e.g. `internal.example`) → ineligible.** They can never pass DNS+ verification, so they simply never become verified claims; no special-casing beyond that. Treat+ the underlying accounts as service/test accounts.+4. **Audit record on backfill → yes.** A backfill that links N accounts is a privilege-granting+ event and writes an audit-log entry.++## 10. Prior context++- Kong had no route for GoTrue's un-prefixed SAML endpoints; fixed in the upstream Supabase fork.+ GoTrue derives its entityID and ACS URL from `API_EXTERNAL_URL` and validates each assertion's+ `Destination` against that exact URL, so `/sso/saml/acs` must route and must skip `key-auth` —+ the IdP posts assertions directly and cannot attach an apikey.+- `GOTRUE_URI_ALLOW_LIST` referenced undefined `${ERP_URL}` / `${MES_URL}` and resolved to the+ literal `,/callback,,/callback`, rejecting every redirect target except `SITE_URL`. Corrected+ upstream to `${ADDITIONAL_REDIRECT_URLS}`.+- Both are deployment-side (the Supabase fork) and are prerequisites for testing anything here.diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.mdindex 776a19a93f..0c9c5329b7 100644--- a/.claude/rules/authentication-system.md+++ b/.claude/rules/authentication-system.md@@ -122,6 +122,36 @@ querying), and every route entry point checks it too — login buttons, thetrigger-created `user`/`userPermission` rows (no FK cascade between the schemas),guarded on zero memberships — or the leftover profile trips `authIdentityExists`and makes the email un-invitable. MES defers first login to ERP.+- **Pre-seeded account linking** (`provisioning.server.ts`; spec+ `.ai/specs/2026-08-29-saml-sso-account-linking.md`): Carbon runs GoTrue with+ `GOTRUE_DISABLE_SIGNUP=true`, so a SAML sign-in that GoTrue classifies as+ "create a new user" is rejected (422) — the callback link above only fires once+ a user *already* has an identity to match. The fix is to pre-seed a row in+ `auth.identities` for the existing user so GoTrue takes its LinkAccount /+ AccountExists branch instead. **Provider-agnostic**: the match is carried by the+ GENERATED `email` column (`identity_data.email = lower(email)`), NOT+ `provider_id` — GoTrue marks every SAML assertion email Verified and falls back+ to email-column matching for EVERY successful SAML login, so it works for any+ IdP regardless of NameID shape (Okta email vs Entra opaque pairwise id). GoTrue+ self-heals a second row keyed on the real NameID on first login; both are torn+ down together. Three raw-`sql` writers (pinned by `sso.server.test.ts` via a+ capturing Kysely driver): `seedSsoIdentityForUser` (one user, idempotent+ `ON CONFLICT (provider_id, provider) DO NOTHING`) — called best-effort/logged by+ `seedSsoIdentityForNewUser` in all three ERP account-creation flows+ (`users.server.ts` create{Customer,Employee,Supplier}Account); and, run from the+ domain-claim flows, `backfillSsoIdentitiesForDomain` (verify → seed EVERY+ existing non-SSO user on the domain) and `removeSsoIdentitiesForDomain` (unregister+ → delete, keyed on the email column so it also removes GoTrue's self-healed+ NameID rows). Backfill/remove are deliberately **not** `companyId`-scoped: the+ adopted policy is that the verified domain owner controls identity for that+ domain instance-wide (GoTrue keys SSO on domain, not company), which the+ cross-company verified-domain exclusivity index makes safe. Pure helpers+ `emailDomain` / `ssoProviderColumn`. A DB guard — `enforce_sso_domain_claim`+ trigger on `auth.sso_domains` + the `ssoReservedDomain` table (migration+ `20260829142619_sso-domain-guard.sql`) — refuses any `auth.sso_domains` insert+ for a reserved domain or one with no Carbon-side `ssoDomain` claim, so a domain+ cannot be registered (and thus control identity) without going through+ verification.- **Require SSO** (`ssoConnection.requireSso`): `isSsoRequiredForEmail`(`connections.server.ts`, like all connection lookups —`getSsoConnectionByDomain` / `getSsoConnectionByProviderId` are the ONE copydiff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.tsindex 588c3f620e..3387dbc1f0 100644--- a/apps/erp/app/modules/users/users.server.ts+++ b/apps/erp/app/modules/users/users.server.ts@@ -18,7 +18,11 @@ import { now, parseAbsolute } from "@internationalized/date";export { getUserClaims } from "@carbon/auth/users.server";import {+ emailDomain,getSsoConnection,+ getSsoConnectionByDomain,+ isSsoEnabled,+ seedSsoIdentityForUser,uncoveredSsoDomainError} from "@carbon/ee/sso.server";import { getLogger } from "@carbon/logger";@@ -36,6 +40,7 @@ import type {User} from "~/modules/users";import { getPermissionsByEmployeeType } from "~/modules/users";+import { getDatabaseClient } from "~/services/database.server";import type { Result } from "~/types";import { path } from "~/utils/path";import { insertEmployeeJob } from "../people/people.service";@@ -290,6 +295,43 @@ export async function addUserToCompany(return client.from("userToCompany").insert(userToCompany);}+/**+ * Pre-seed a SAML SSO identity for a newly-created auth user when their email+ * domain already has a verified SSO connection — so their first SAML sign-in+ * links to this account instead of being rejected by GOTRUE_DISABLE_SIGNUP.+ * (Existing users on a domain are handled by the backfill in verifySsoDomain.)+ *+ * Best-effort: a failure is logged, never thrown — account creation must not+ * fail because seeding failed, and the domain-verify backfill is a fallback.+ * Rollback-safe: identities cascade-delete with auth.users, so a later insert+ * failure that deletes the auth account also removes this row. Self-gates on+ * isSsoEnabled(); off-Enterprise it does not query.+ */+async function seedSsoIdentityForNewUser(+ serviceRole: SupabaseClient<Database>,+ { userId, email }: { userId: string; email: string }+): Promise<void> {+ if (!isSsoEnabled()) return;+ const domain = emailDomain(email);+ if (!domain) return;++ const connection = await getSsoConnectionByDomain(serviceRole, domain);+ if (connection.error || !connection.data) return;++ const seed = await seedSsoIdentityForUser(getDatabaseClient(), {+ userId,+ email,+ providerId: connection.data.providerId+ });+ if (seed.error) {+ logger.error("Failed to pre-seed SSO identity for new user", {+ userId,+ domain,+ error: seed.error+ });+ }+}+export async function createCustomerAccount(client: SupabaseClient<Database>,{@@ -354,6 +396,8 @@ export async function createCustomerAccount(await deleteAuthAccount(serviceRole, userId);return { success: false, message: createCarbonUser.error.message };}++ await seedSsoIdentityForNewUser(serviceRole, { userId, email });}const code = crypto.randomUUID();@@ -491,6 +535,8 @@ export async function createEmployeeAccount(await deleteAuthAccount(serviceRole, userId);return { success: false, message: createCarbonUser.error.message };}++ await seedSsoIdentityForNewUser(serviceRole, { userId, email });}const code = crypto.randomUUID();@@ -610,6 +656,8 @@ export async function createSupplierAccount(await deleteAuthAccount(serviceRole, userId);return { success: false, message: createCarbonUser.error.message };}++ await seedSsoIdentityForNewUser(serviceRole, { userId, email });}const code = crypto.randomUUID();diff --git a/apps/erp/app/routes/x+/settings+/security.tsx b/apps/erp/app/routes/x+/settings+/security.tsxindex 6d7675d21a..61a60f9b25 100644--- a/apps/erp/app/routes/x+/settings+/security.tsx+++ b/apps/erp/app/routes/x+/settings+/security.tsx@@ -437,6 +437,17 @@ export default function Security() {</Trans></p></div>++ <div className="flex flex-col gap-1 w-full">+ <Heading size="h3">+ <Trans>MFA</Trans>+ </Heading>+ <p className="text-sm text-muted-foreground text-pretty max-w-xl">+ <Trans>+ Require a second factor when members sign in to this company.+ </Trans>+ </p>+ </div>{mfaGated ? (<UpgradeOverlaySectionicon={<LuShieldCheck className="size-6 text-muted-foreground" />}@@ -629,7 +640,7 @@ export default function Security() {resetAfterSubmit><Hidden name="intent" value="addDomain" />- <HStack className="w-full items-end">+ <div className="flex w-full items-end gap-2"><div className="flex-1"><Inputname="domain"@@ -640,7 +651,7 @@ export default function Security() {<Submit isDisabled={!canEdit} withBlocker={false}><Trans>Add</Trans></Submit>- </HStack>+ </div></ValidatedForm></VStack></CardContent>diff --git a/apps/erp/app/routes/x+/settings+/sso.tsx b/apps/erp/app/routes/x+/settings+/sso.tsxindex e9a2cab978..e01ae90a34 100644--- a/apps/erp/app/routes/x+/settings+/sso.tsx+++ b/apps/erp/app/routes/x+/settings+/sso.tsx@@ -15,6 +15,7 @@ import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { ssoConnectionValidator, ssoDomainValidator } from "~/modules/settings";+import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";// Action-only route — the SSO admin UI lives on the Security screen. A direct@@ -142,11 +143,15 @@ export async function action({ request }: ActionFunctionArgs) {return data({}, await flash(request, error(null, "Unknown domain")));}- const result = await verifySsoDomain(getCarbonServiceRole(), {- companyId,- domainId,- userId- });+ const result = await verifySsoDomain(+ getCarbonServiceRole(),+ getDatabaseClient(),+ {+ companyId,+ domainId,+ userId+ }+ );if (result.error) {return data({}, await flash(request, error(result.error, result.error)));@@ -179,10 +184,14 @@ export async function action({ request }: ActionFunctionArgs) {return data({}, await flash(request, error(null, "Unknown domain")));}- const removal = await removeSsoDomain(getCarbonServiceRole(), {- companyId,- domainId- });+ const removal = await removeSsoDomain(+ getCarbonServiceRole(),+ getDatabaseClient(),+ {+ companyId,+ domainId+ }+ );if (removal.error) {return data(diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex be16a8dc31..64ecfb1054 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -71439,6 +71439,105 @@ export default {tags: ["terms"]}},+ "/ssoReservedDomain": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.ssoReservedDomain.domain"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/ssoReservedDomain"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["ssoReservedDomain"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.ssoReservedDomain"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["ssoReservedDomain"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.ssoReservedDomain.domain"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["ssoReservedDomain"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.ssoReservedDomain.domain"+ },+ {+ $ref: "#/parameters/body.ssoReservedDomain"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["ssoReservedDomain"]+ }+ },"/modules": {get: {parameters: [@@ -105161,7 +105260,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -105210,7 +105309,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -132788,6 +132887,17 @@ export default {},type: "object"},+ ssoReservedDomain: {+ required: ["domain"],+ properties: {+ domain: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ }+ },+ type: "object"+ },modules: {properties: {name: {@@ -178361,6 +178471,21 @@ export default {in: "query",type: "string"},+ "body.ssoReservedDomain": {+ name: "ssoReservedDomain",+ description: "ssoReservedDomain",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/ssoReservedDomain"+ }+ },+ "rowFilter.ssoReservedDomain.domain": {+ name: "domain",+ required: false,+ in: "query",+ type: "string"+ },"body.modules": {name: "modules",description: "modules",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 375606b8e8..db18bfd700 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -50784,6 +50784,18 @@ export type Database = {},]}+ ssoReservedDomain: {+ Row: {+ domain: string+ }+ Insert: {+ domain: string+ }+ Update: {+ domain?: string+ }+ Relationships: []+ }stockTransfer: {Row: {assignee: string | null@@ -72840,14 +72852,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 375606b8e8..db18bfd700 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -50784,6 +50784,18 @@ export type Database = {},]}+ ssoReservedDomain: {+ Row: {+ domain: string+ }+ Insert: {+ domain: string+ }+ Update: {+ domain?: string+ }+ Relationships: []+ }stockTransfer: {Row: {assignee: string | null@@ -72840,14 +72852,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/migrations/20260829142619_sso-domain-guard.sql b/packages/database/supabase/migrations/20260829142619_sso-domain-guard.sqlnew file mode 100644index 0000000000..57862f3545--- /dev/null+++ b/packages/database/supabase/migrations/20260829142619_sso-domain-guard.sql@@ -0,0 +1,107 @@+-- SAML SSO domain guard (defense in depth).+--+-- GoTrue scopes SSO by email domain instance-wide (auth.sso_domains). Carbon's+-- app flow only ever registers a domain in GoTrue AFTER a DNS-TXT ownership+-- challenge (packages/ee/src/sso/connections.server.ts -> verifySsoDomain). This+-- guard enforces the same rule in the database, so no auth.sso_domains row can+-- be created for a domain nobody has claimed (e.g. a direct Studio insert or a+-- stray migration) — registering a domain is what grants its verified owner+-- control over identity for every user on it, so it must not be possible without+-- a Carbon-side claim.+--+-- Requires a *claim row* (any status), NOT status = 'verified', on purpose:+-- verifySsoDomain syncs GoTrue (which writes auth.sso_domains) while the ssoDomain+-- row is still 'pending', by a deliberate lockout-avoidance ordering. A+-- verified-only guard would break that happy path. Reserved domains can never+-- obtain a claim row via the app validator (PUBLIC_EMAIL_DOMAINS), and the+-- reserved check below makes that hold against direct DB writes too.+--+-- The claim must also belong to the connection behind NEW."sso_provider_id", not+-- just match the domain (CWE-863): a domain check alone would let a writer route+-- a domain one company DNS-proved to a DIFFERENT company's IdP. The trigger joins+-- the ssoDomain claim to its ssoConnection and checks the provider id matches.++-- Global reserved-domain list. NOT company-scoped: a reserved domain can never be+-- claimed by anyone. Kept in sync with PUBLIC_EMAIL_DOMAINS in+-- apps/erp/app/modules/settings/settings.models.ts.+CREATE TABLE IF NOT EXISTS "ssoReservedDomain" (+ "domain" TEXT PRIMARY KEY+);++INSERT INTO "ssoReservedDomain" ("domain") VALUES+ -- Consumer mailbox providers (mirror PUBLIC_EMAIL_DOMAINS). These are shared+ -- across unrelated people, so DNS verification cannot prove single ownership —+ -- they must never be claimable. Carbon's OWN domains are deliberately NOT here:+ -- a domain a company controls can be proven via the DNS-TXT challenge and set up+ -- for SSO like any other, so a blanket reservation was only friction.+ ('gmail.com'), ('googlemail.com'), ('outlook.com'), ('hotmail.com'),+ ('live.com'), ('msn.com'), ('yahoo.com'), ('ymail.com'), ('icloud.com'),+ ('me.com'), ('mac.com'), ('aol.com'), ('proton.me'), ('protonmail.com'),+ ('pm.me'), ('gmx.com'), ('gmx.net'), ('mail.com'), ('zoho.com'),+ ('yandex.com'), ('qq.com'), ('163.com'), ('126.com')+ON CONFLICT ("domain") DO NOTHING;++ALTER TABLE "public"."ssoReservedDomain" ENABLE ROW LEVEL SECURITY;++-- Readable by any authenticated employee; writes are service-role/staff only+-- (no INSERT/UPDATE/DELETE policy — RLS denies them by default).+DROP POLICY IF EXISTS "SELECT" ON "public"."ssoReservedDomain";+CREATE POLICY "SELECT" ON "public"."ssoReservedDomain"+FOR SELECT USING (auth.role() = 'authenticated');++-- The guard. Defined in PUBLIC (not auth) — the migration role can create+-- functions in public but not in the auth schema, and this mirrors+-- create_public_user (function in public, trigger on an auth table). SECURITY+-- DEFINER so it can read public tables regardless of the caller's role;+-- search_path pinned to public per house convention. A session-local override+-- lets Carbon staff scripts bypass for own-domain setup.+CREATE OR REPLACE FUNCTION public.enforce_sso_domain_claim()+RETURNS TRIGGER+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+BEGIN+ IF current_setting('app.sso_domain_override', true) = 'on' THEN+ RETURN NEW;+ END IF;++ IF EXISTS (+ SELECT 1 FROM public."ssoReservedDomain"+ WHERE lower("domain") = lower(NEW."domain")+ ) THEN+ RAISE EXCEPTION+ 'auth.sso_domains insert blocked: % is a reserved domain', NEW."domain";+ END IF;++ -- Bind the claim to the PROVIDER, not just the domain: the ssoDomain claim+ -- must belong to the ssoConnection that owns NEW."sso_provider_id". A bare+ -- domain check would let a writer register a claimed domain under an unrelated+ -- company's provider (CWE-863) — the claim proving DNS ownership sits with one+ -- company/connection, but the routing row would point at another's IdP. The+ -- claim may still be 'pending' here: verifySsoDomain syncs GoTrue (writing+ -- auth.sso_domains) before it flips the ssoDomain row to 'verified', by a+ -- deliberate lockout-avoidance ordering, so we require a matching claim of ANY+ -- status — only that it belongs to this provider's connection.+ IF NOT EXISTS (+ SELECT 1+ FROM public."ssoDomain" d+ JOIN public."ssoConnection" c+ ON c."id" = d."connectionId" AND c."companyId" = d."companyId"+ WHERE lower(d."domain") = lower(NEW."domain")+ AND c."providerId" = NEW."sso_provider_id"::text+ ) THEN+ RAISE EXCEPTION+ 'auth.sso_domains insert blocked: no ssoDomain claim for % under provider %',+ NEW."domain", NEW."sso_provider_id";+ END IF;++ RETURN NEW;+END;+$$;++DROP TRIGGER IF EXISTS enforce_sso_domain_claim ON auth.sso_domains;+CREATE TRIGGER enforce_sso_domain_claim+ BEFORE INSERT ON auth.sso_domains+ FOR EACH ROW+ EXECUTE FUNCTION public.enforce_sso_domain_claim();diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex 1d17e2f00c..56d579f688 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -83,7 +83,7 @@ services:GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:postgres@postgres:5432/postgresGOTRUE_SITE_URL: ${ERP_URL}GOTRUE_URI_ALLOW_LIST: ${ERP_URL},${ERP_URL}/callback,${MES_URL},${MES_URL}/callback,${GTM_URL}- GOTRUE_DISABLE_SIGNUP: "false"+ GOTRUE_DISABLE_SIGNUP: ${GOTRUE_DISABLE_SIGNUP:-false}GOTRUE_JWT_SECRET: ${SUPABASE_JWT_SECRET}GOTRUE_JWT_EXP: 3600GOTRUE_SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: 10diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex 4d9dc9565f..19a8e46138 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -39,7 +39,7 @@ pnpm --filter @carbon/ee typecheck # tsgo --noEmit- **Tie-out remote reads**: `accounting/core/remote-journal.ts` `fetchRemoteJournalTotals()` — provider-agnostic debit-signed per-account journal totals for the reconciliation tie-out- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions-- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client). Only verified domains ever reach GoTrue. Full architecture: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section)+- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./exchange-rates.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.## Cross-Referencesdiff --git a/packages/ee/src/sso/connections.server.ts b/packages/ee/src/sso/connections.server.tsindex 6c80b5a98b..7805c26062 100644--- a/packages/ee/src/sso/connections.server.ts+++ b/packages/ee/src/sso/connections.server.ts@@ -1,5 +1,7 @@import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { getAppUrl } from "@carbon/env";+import { getLogger } from "@carbon/logger";import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { isSsoEnabled } from "./gate";@@ -8,11 +10,17 @@ import {deleteGoTrueSsoProvider,updateGoTrueSsoProvider} from "./provider.server";+import {+ backfillSsoIdentitiesForDomain,+ removeSsoIdentitiesForDomain+} from "./provisioning.server";import {checkDomainVerification,generateVerificationToken} from "./verification.server";+const logger = getLogger("ee");+// --- "ssoConnection" lookups ----------------------------------------------// The one copy shared by ERP, MES, and jobs — domain and provider routing must// answer identically at every enforcement point, so none of them keeps its own.@@ -278,6 +286,7 @@ export async function addSsoDomain(*/export async function verifySsoDomain(serviceRole: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,args: { companyId: string; domainId: string; userId: string }) {if (!isSsoEnabled()) return { data: null, error: DISABLED_ERROR };@@ -361,11 +370,39 @@ export async function verifySsoDomain(return { data: null, error: update.error.message };}+ // Backfill SSO identities for every existing user on the now-verified domain,+ // so a SAML sign-in resolves to their existing account under DISABLE_SIGNUP.+ // Verification has already committed — a backfill failure must NOT fail the+ // verify (the next verify/remove re-runs it); log and continue.+ const backfill = await backfillSsoIdentitiesForDomain(db, {+ providerId: connection.data.providerId,+ domain: row.data.domain+ });+ if (backfill.error) {+ logger.error("SSO identity backfill failed after domain verification", {+ companyId: args.companyId,+ domain: row.data.domain,+ error: backfill.error+ });+ } else {+ // Privilege-granting event: a verified domain now controls identity for+ // every user on it. Recorded here as a structured log line. (Surfacing it+ // in the audit-log UI needs an audit.config.ts entity — Ask First.)+ logger.info("SSO identities backfilled for verified domain", {+ companyId: args.companyId,+ domain: row.data.domain,+ providerId: connection.data.providerId,+ linkedCount: backfill.data?.linkedUserIds.length ?? 0,+ actorId: args.userId+ });+ }+return { data: { verified: true as const }, error: null };}export async function removeSsoDomain(serviceRole: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,args: { companyId: string; domainId: string }) {if (!isSsoEnabled()) return { data: null, error: DISABLED_ERROR };@@ -405,6 +442,25 @@ export async function removeSsoDomain(if (sync.error) {return { data: null, error: sync.error };}++ // Tear down the pre-seeded (and self-healed) SSO identities for the+ // domain we just unregistered. Keyed on the identity email column, so it+ // also removes rows GoTrue created with the IdP's real NameID. Best-effort+ // after the row is gone — log on failure, don't fail the removal.+ const removed = await removeSsoIdentitiesForDomain(db, {+ providerId: connection.data.providerId,+ domain: row.data.domain+ });+ if (removed.error) {+ logger.error(+ "Failed to remove SSO identities for unregistered domain",+ {+ companyId: args.companyId,+ domain: row.data.domain,+ error: removed.error+ }+ );+ }}}diff --git a/packages/ee/src/sso/index.server.ts b/packages/ee/src/sso/index.server.tsindex 5f046d6744..7d9306b0bc 100644--- a/packages/ee/src/sso/index.server.ts+++ b/packages/ee/src/sso/index.server.ts@@ -21,11 +21,16 @@ export {updateGoTrueSsoProvider} from "./provider.server";export {+ backfillSsoIdentitiesForDomain,buildArchivedEmail,deleteJitSsoUser,+ emailDomain,linkSsoIdentityToUser,mergeInvitePermissions,migrateUserToSso,+ removeSsoIdentitiesForDomain,+ seedSsoIdentityForUser,+ ssoProviderColumn,uncoveredSsoDomainError} from "./provisioning.server";export {diff --git a/packages/ee/src/sso/provisioning.server.ts b/packages/ee/src/sso/provisioning.server.tsindex 4deeef72a3..42b9d2c51c 100644--- a/packages/ee/src/sso/provisioning.server.ts+++ b/packages/ee/src/sso/provisioning.server.ts@@ -70,6 +70,180 @@ export async function linkSsoIdentityToUser(}}+// --- Pre-seeded SSO identities (provider-agnostic account linking) ----------+// Carbon runs GoTrue with GOTRUE_DISABLE_SIGNUP=true, so a SAML sign-in that+// resolves to "create a new user" is rejected (422). Pre-seeding an+// auth.identities row for an existing user makes GoTrue take the+// LinkAccount/AccountExists branch instead — no signup, the existing UUID is+// kept, and password/Google/magic-link all keep working.+//+// The match that carries the load is the GENERATED `email` column+// (lower(identity_data->>'email')), NOT provider_id: GoTrue v2.177.0 marks every+// SAML assertion email Verified and hard-rejects an emailless assertion, so its+// email-column fallback in DetermineAccountLinking fires for EVERY successful+// SAML sign-in — for any IdP (Okta, Entra, OneLogin, Ping, Google, JumpCloud,+// ADFS). Keying on provider_id would only work for IdPs whose NameID is the+// email (Okta); Entra's default is an opaque persistent pairwise id. `provider_id`+// here is just a readable placeholder. GoTrue self-heals on the next login by+// creating a row keyed on the real NameID, which then resolves via AccountExists.++/** The auth.identities.provider value for a GoTrue SSO provider id. */+export function ssoProviderColumn(providerId: string): string {+ return `sso:${providerId}`;+}++/** The lowercased domain of an email, or null (mirrors uncoveredSsoDomainError). */+export function emailDomain(email: string): string | null {+ return email.split("@")[1]?.trim().toLowerCase() ?? null;+}++/**+ * Pre-seed one SSO identity so a single existing/invited user links on their+ * next SAML sign-in. Idempotent (ON CONFLICT DO NOTHING). Off-Enterprise callers+ * must gate on isSsoEnabled() before calling — this writes the auth schema+ * unconditionally.+ */+export async function seedSsoIdentityForUser(+ db: Kysely<KyselyDatabase>,+ {+ userId,+ email,+ providerId+ }: {+ userId: string;+ email: string;+ providerId: string;+ }+): Promise<{ data: { seeded: boolean } | null; error: string | null }> {+ const lowerEmail = email.toLowerCase();+ const provider = ssoProviderColumn(providerId);+ try {+ const result = await sql`+ INSERT INTO auth.identities+ (provider_id, user_id, identity_data, provider, created_at, updated_at)+ VALUES (+ ${lowerEmail},+ ${userId}::uuid,+ jsonb_build_object('sub', ${lowerEmail}::text, 'email', ${lowerEmail}::text),+ ${provider},+ now(),+ now()+ )+ ON CONFLICT (provider_id, provider) DO NOTHING+ `.execute(db);+ return {+ data: { seeded: Number(result.numAffectedRows ?? 0) > 0 },+ error: null+ };+ } catch (err) {+ logger.error("Failed to seed SSO identity", {+ userId,+ providerId,+ error: err+ });+ return {+ data: null,+ error: err instanceof Error ? err.message : "Failed to seed SSO identity"+ };+ }+}++/**+ * Backfill SSO identities for EVERY existing non-SSO user whose email is on the+ * domain — run when a domain is verified. Not company-scoped: the adopted policy+ * is that the verified domain owner controls identity for that domain+ * instance-wide (GoTrue keys linking on domain, not company). Returns the linked+ * user ids so the caller can write an audit record. Idempotent.+ */+export async function backfillSsoIdentitiesForDomain(+ db: Kysely<KyselyDatabase>,+ {+ providerId,+ domain+ }: {+ providerId: string;+ domain: string;+ }+): Promise<{ data: { linkedUserIds: string[] } | null; error: string | null }> {+ const lowerDomain = domain.toLowerCase();+ const provider = ssoProviderColumn(providerId);+ try {+ const result = await sql<{ user_id: string }>`+ INSERT INTO auth.identities+ (provider_id, user_id, identity_data, provider, created_at, updated_at)+ SELECT+ lower(u.email),+ u.id,+ jsonb_build_object('sub', lower(u.email), 'email', lower(u.email)),+ ${provider},+ now(),+ now()+ FROM auth.users u+ WHERE u.email IS NOT NULL+ AND u.is_sso_user = false+ AND lower(split_part(u.email, '@', 2)) = ${lowerDomain}+ ON CONFLICT (provider_id, provider) DO NOTHING+ RETURNING user_id+ `.execute(db);+ return {+ data: { linkedUserIds: result.rows.map((r) => r.user_id) },+ error: null+ };+ } catch (err) {+ logger.error("Failed to backfill SSO identities", {+ providerId,+ domain,+ error: err+ });+ return {+ data: null,+ error:+ err instanceof Error ? err.message : "Failed to backfill SSO identities"+ };+ }+}++/**+ * Remove this domain's SSO identities when the domain is unregistered. Keyed on+ * the GENERATED `email` column, not provider_id, so it also catches the rows+ * GoTrue self-heals with the IdP's real (possibly opaque) NameID.+ */+export async function removeSsoIdentitiesForDomain(+ db: Kysely<KyselyDatabase>,+ {+ providerId,+ domain+ }: {+ providerId: string;+ domain: string;+ }+): Promise<{ data: { removed: number } | null; error: string | null }> {+ const lowerDomain = domain.toLowerCase();+ const provider = ssoProviderColumn(providerId);+ try {+ const result = await sql`+ DELETE FROM auth.identities+ WHERE provider = ${provider}+ AND lower(split_part(email, '@', 2)) = ${lowerDomain}+ `.execute(db);+ return {+ data: { removed: Number(result.numAffectedRows ?? 0) },+ error: null+ };+ } catch (err) {+ logger.error("Failed to remove SSO identities", {+ providerId,+ domain,+ error: err+ });+ return {+ data: null,+ error:+ err instanceof Error ? err.message : "Failed to remove SSO identities"+ };+ }+}+/*** Remove a throwaway JIT SSO auth user COMPLETELY — the auth user AND the* `public."user"` / `userPermission` rows the `on_auth_user_created` triggerdiff --git a/packages/ee/src/sso/sso.server.test.ts b/packages/ee/src/sso/sso.server.test.tsindex 6c79169259..392addc051 100644--- a/packages/ee/src/sso/sso.server.test.ts+++ b/packages/ee/src/sso/sso.server.test.ts@@ -1,4 +1,11 @@import type { User, UserIdentity } from "@supabase/supabase-js";+import type { CompiledQuery, DatabaseConnection, Driver } from "kysely";+import {+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler+} from "kysely";import { describe, expect, it, vi } from "vitest";// Isolation mocks — the SSO module reads env constants and constructs a logger@@ -29,6 +36,16 @@ vi.mock("@carbon/logger", () => ({})}));+// connections.server now imports provisioning.server, which pulls in the auth+// client and Redis at module load. Stub them so the module graph loads without a+// real Supabase/Redis connection — these tests never reach code that uses them.+vi.mock("@carbon/auth", () => ({+ getPermissionCacheKey: (id: string) => `permissions:${id}`+}));+vi.mock("@carbon/kv", () => ({+ redis: { del: vi.fn() }+}));+// Stub the DNS challenge so no test resolves real TXT records.const { checkDomainVerificationMock } = vi.hoisted(() => ({checkDomainVerificationMock: vi.fn()@@ -49,6 +66,13 @@ const {upsertSsoConnection,verifySsoDomain} = await import("./connections.server");+const {+ backfillSsoIdentitiesForDomain,+ emailDomain,+ removeSsoIdentitiesForDomain,+ seedSsoIdentityForUser,+ ssoProviderColumn+} = await import("./provisioning.server");function makeUser(overrides: {identityProviders?: string[];@@ -403,7 +427,10 @@ describe("ssoDomain claim exclusivity", () => {}} as never;- const result = await verifySsoDomain(client, {+ // This path returns at the cross-company conflict check, before any+ // auth-schema write, so the db handle is never exercised here.+ const dbStub = {} as never;+ const result = await verifySsoDomain(client, dbStub, {companyId: "c1",domainId: "dom_1",userId: "user_1"@@ -415,6 +442,27 @@ describe("ssoDomain claim exclusivity", () => {});});+describe("pre-seed identity helpers (provider-agnostic linking)", () => {+ it("ssoProviderColumn builds the auth.identities provider value", () => {+ expect(ssoProviderColumn("11111111-2222-3333-4444-555555555555")).toBe(+ "sso:11111111-2222-3333-4444-555555555555"+ );+ });++ it("emailDomain lowercases, trims, and takes the part after @", () => {+ expect(emailDomain("[email protected]")).toBe("acme.com");+ expect(emailDomain("[email protected]")).toBe("sub.acme.com");+ expect(emailDomain(" [email protected] ")).toBe("acme.com");+ });++ it("emailDomain returns null when there is no domain part", () => {+ expect(emailDomain("no-at-sign")).toBeNull();+ expect(emailDomain("")).toBeNull();+ // A trailing "@" leaves an empty domain segment after trimming.+ expect(emailDomain("trailing@")).toBe("");+ });+});+describe("isSsoEnabled gate (AUTH_PROVIDERS half toggled off)", () => {it("makes the lookups answer 'no connection' WITHOUT querying, and refuses admin mutations", async () => {enabled.sso = false;@@ -445,3 +493,168 @@ describe("isSsoEnabled gate (AUTH_PROVIDERS half toggled off)", () => {}});});++// --- auth.identities write coverage -----------------------------------------+// The pre-seed helpers issue raw `sql` writes to the auth schema — the load-+// bearing half of provider-agnostic linking. A stubbed db handle proves nothing,+// so drive Kysely's REAL Postgres compiler with a fake driver that captures the+// compiled SQL + parameters. A revert of the target table, columns, ON CONFLICT+// clause, email/domain lowercasing, or RETURNING would fail these.+function makeKysely(connection: DatabaseConnection) {+ const driver: Driver = {+ async init() {},+ async acquireConnection() {+ return connection;+ },+ async beginTransaction() {},+ async commitTransaction() {},+ async rollbackTransaction() {},+ async releaseConnection() {},+ async destroy() {}+ };+ return new Kysely<Record<string, never>>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (db) => new PostgresIntrospector(db),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ });+}++function makeCapturingDb(result: {+ rows?: unknown[];+ numAffectedRows?: bigint;+}) {+ const captured: { sql: string; parameters: readonly unknown[] }[] = [];+ const connection: DatabaseConnection = {+ async executeQuery(compiledQuery: CompiledQuery) {+ captured.push({+ sql: compiledQuery.sql,+ parameters: compiledQuery.parameters+ });+ return {+ rows: result.rows ?? [],+ numAffectedRows: result.numAffectedRows+ } as never;+ },+ async *streamQuery() {}+ };+ return { db: makeKysely(connection) as never, captured };+}++function makeThrowingDb(message: string) {+ const connection: DatabaseConnection = {+ async executeQuery() {+ throw new Error(message);+ },+ async *streamQuery() {}+ };+ return makeKysely(connection) as never;+}++describe("pre-seed identity writes (auth.identities SQL)", () => {+ it("seedSsoIdentityForUser inserts a link row keyed on the lowercased email", async () => {+ const { db, captured } = makeCapturingDb({ numAffectedRows: 1n });+ const result = await seedSsoIdentityForUser(db, {+ userId: "11111111-1111-1111-1111-111111111111",+ email: "[email protected]",+ providerId: "prov-1"+ });++ expect(result.error).toBeNull();+ expect(result.data).toEqual({ seeded: true });+ expect(captured).toHaveLength(1);++ const { sql, parameters } = captured[0]!;+ expect(sql).toContain("INSERT INTO auth.identities");+ expect(sql).toContain("(provider_id, provider) DO NOTHING");+ // email is lowercased before it becomes provider_id and identity_data+ expect(parameters).toContain("[email protected]");+ expect(parameters).not.toContain("[email protected]");+ expect(parameters).toContain("11111111-1111-1111-1111-111111111111");+ expect(parameters).toContain("sso:prov-1");+ });++ it("seedSsoIdentityForUser reports seeded:false when the row already exists", async () => {+ const { db } = makeCapturingDb({ numAffectedRows: 0n });+ const result = await seedSsoIdentityForUser(db, {+ userId: "u1",+ email: "[email protected]",+ providerId: "prov-1"+ });+ expect(result).toEqual({ data: { seeded: false }, error: null });+ });++ it("canonicalizes a mixed-case IdP email to lowercase in every seeded slot", async () => {+ // GoTrue's account-linking fallback matches on the GENERATED email column+ // (lower(identity_data->>'email')), so a case-preserving NameID must still+ // resolve to the seeded row. Every occurrence — provider_id and both+ // identity_data keys — must be the lowercased email, and the mixed-case+ // form must never reach the parameters.+ const { db, captured } = makeCapturingDb({ numAffectedRows: 1n });+ await seedSsoIdentityForUser(db, {+ userId: "u1",+ email: "[email protected]",+ providerId: "prov-1"+ });+ const { parameters } = captured[0]!;+ const lower = "[email protected]";+ // provider_id + jsonb 'sub' + jsonb 'email' = three lowercased copies+ expect(parameters.filter((p) => p === lower)).toHaveLength(3);+ expect(+ parameters.some((p) => typeof p === "string" && p !== p.toLowerCase())+ ).toBe(false);+ });++ it("backfillSsoIdentitiesForDomain selects on-domain non-SSO users and returns their ids", async () => {+ const { db, captured } = makeCapturingDb({+ rows: [{ user_id: "u1" }, { user_id: "u2" }]+ });+ const result = await backfillSsoIdentitiesForDomain(db, {+ providerId: "prov-1",+ domain: "Acme.com"+ });++ expect(result.error).toBeNull();+ expect(result.data).toEqual({ linkedUserIds: ["u1", "u2"] });++ const { sql, parameters } = captured[0]!;+ expect(sql).toContain("INSERT INTO auth.identities");+ expect(sql).toContain("FROM auth.users");+ expect(sql).toContain("is_sso_user = false");+ expect(sql).toContain("RETURNING user_id");+ expect(parameters).toContain("acme.com"); // domain lowercased+ expect(parameters).toContain("sso:prov-1");+ });++ it("removeSsoIdentitiesForDomain deletes by provider + domain and counts affected rows", async () => {+ const { db, captured } = makeCapturingDb({ numAffectedRows: 3n });+ const result = await removeSsoIdentitiesForDomain(db, {+ providerId: "prov-1",+ domain: "ACME.com"+ });++ expect(result.error).toBeNull();+ expect(result.data).toEqual({ removed: 3 });++ const { sql, parameters } = captured[0]!;+ expect(sql).toContain("DELETE FROM auth.identities");+ expect(sql).toContain("split_part(email, '@', 2)");+ expect(parameters).toContain("acme.com");+ expect(parameters).toContain("sso:prov-1");+ });++ it("returns an error (never throws) when the auth-schema write fails", async () => {+ const result = await seedSsoIdentityForUser(+ makeThrowingDb("connection reset"),+ {+ userId: "u1",+ email: "[email protected]",+ providerId: "prov-1"+ }+ );+ expect(result.data).toBeNull();+ expect(result.error).toBe("connection reset");+ });+});diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 6ffd5f03d6..6f1902fec2 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -9244,6 +9244,9 @@ msgstr "Metrische Einheiten sind deaktiviert"msgid "Metric units are enabled"msgstr "Metrische Einheiten sind aktiviert"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Konvention für Mitte des Monats / Quartal / Halbjahr, die den Abzug im ersten Jahr bestimmt."@@ -12542,6 +12545,9 @@ msgstr "Wunschtermin"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Erfordert einen 6-stelligen Code aus einer Authentifikator-App beim Anmelden."+msgid "Require a second factor when members sign in to this company."+msgstr "Zweiten Faktor anfordern, wenn sich Mitglieder bei diesem Unternehmen anmelden."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Erfordert eine Authentifizierungs-App, bevor jemand dieses Unternehmen öffnen kann. Ihre anderen Unternehmen sind nicht betroffen. Besuchen Sie die <0>Seite mit den Mitarbeiterkonten</0>, um den Status jeder Person zu sehen."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex e9a634941e..34efa3eb0c 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -9244,6 +9244,9 @@ msgstr "Metric units are disabled"msgid "Metric units are enabled"msgstr "Metric units are enabled"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."@@ -12542,6 +12545,9 @@ msgstr "Requested Date"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Require a 6-digit code from an authenticator app when signing in."+msgid "Require a second factor when members sign in to this company."+msgstr "Require a second factor when members sign in to this company."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex a585710cab..446e552a99 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -9244,6 +9244,9 @@ msgstr "Las unidades métricas están deshabilitadas"msgid "Metric units are enabled"msgstr "Las unidades métricas están habilitadas"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Convención de mitad de mes / mitad de trimestre / mitad de año que determina la deducción del primer año."@@ -12542,6 +12545,9 @@ msgstr "Fecha Solicitada"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Requerir un código de 6 dígitos de una aplicación de autenticación al iniciar sesión."+msgid "Require a second factor when members sign in to this company."+msgstr "Requerir un segundo factor cuando los miembros inician sesión en esta empresa."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Requiere una aplicación autenticadora antes de que alguien pueda abrir esta empresa. Sus otras empresas no se ven afectadas. Visita la <0>página de cuentas de empleados</0> para ver el estado de cada persona."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 223ca6a5d5..ffdb8bfa01 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -9244,6 +9244,9 @@ msgstr "Les unités métriques sont désactivées"msgid "Metric units are enabled"msgstr "Les unités métriques sont activées"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Convention de mi-mois / mi-trimestre / mi-année qui détermine la déduction de première année."@@ -12542,6 +12545,9 @@ msgstr "Date demandée"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Exiger un code à 6 chiffres d'une application d'authentification lors de la connexion."+msgid "Require a second factor when members sign in to this company."+msgstr "Exiger un second facteur quand les membres se connectent à cette société."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Exiger une application d'authentification avant que quiconque puisse ouvrir cette société. Leurs autres sociétés ne sont pas affectées. Visitez la <0>page des comptes employé</0> pour voir le statut de chaque personne."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 789b65380f..81a9f1bf20 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -9244,6 +9244,9 @@ msgstr "मीट्रिक इकाइयाँ अक्षम हैं"msgid "Metric units are enabled"msgstr "मीट्रिक इकाइयाँ सक्षम हैं"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "मध्य-महीना / मध्य-त्रैमासिक / आधा-वर्ष सम्मेलन जो पहले वर्ष की कटौती निर्धारित करता है।"@@ -12542,6 +12545,9 @@ msgstr "अनुरोधित तिथि"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "साइन इन करते समय ऑथेंटिकेटर ऐप से 6-अंकीय कोड की आवश्यकता है।"+msgid "Require a second factor when members sign in to this company."+msgstr "जब सदस्य इस कंपनी में साइन इन करते हैं तो एक दूसरे कारक की आवश्यकता है।"+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "किसी को भी इस कंपनी को खोलने से पहले एक प्रमाणकर्ता ऐप की आवश्यकता है। उनकी अन्य कंपनियां प्रभावित नहीं हैं। प्रत्येक व्यक्ति की स्थिति देखने के लिए <0>कर्मचारी खातों पृष्ठ</0> पर जाएं।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 78ad6f2fcc..b49ed42e3d 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -9244,6 +9244,9 @@ msgstr "Le unità metriche sono disabilitate"msgid "Metric units are enabled"msgstr "Le unità metriche sono abilitate"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Convenzione di metà mese / metà trimestre / metà anno che determina la detrazione del primo anno."@@ -12542,6 +12545,9 @@ msgstr "Data Richiesta"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Richiedi un codice a 6 cifre dall'app autenticatore al momento dell'accesso."+msgid "Require a second factor when members sign in to this company."+msgstr "Richiedi un secondo fattore quando i membri accedono a questa Azienda."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Richiedi un'app autenticatore prima che chiunque possa aprire questa azienda. Le loro altre aziende non sono interessate. Visita la <0>pagina degli account dei dipendenti</0> per vedere lo stato di ogni persona."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 1dba950a31..86c96c34cf 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -9244,6 +9244,9 @@ msgstr "メートル法の単位は無効です"msgid "Metric units are enabled"msgstr "メートル法単位が有効です"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "初年度控除を決定する中月/四半期中/半年の慣例。"@@ -12542,6 +12545,9 @@ msgstr "希望納期"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "サインイン時に認証器アプリから6桁のコードが必要です。"+msgid "Require a second factor when members sign in to this company."+msgstr "メンバーがこの会社にサインインする際に、セカンドファクタを必須にする。"+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "このアプリケーション認証器を要求して、誰もがこの会社を開く前に認証を要求します。他の会社は影響を受けません。<0>従業員アカウントページ</0>にアクセスして、各個人のステータスを確認してください。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex de09155a46..a18b9e770b 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -9244,6 +9244,9 @@ msgstr "미터법 단위가 비활성화됨"msgid "Metric units are enabled"msgstr "미터법 단위가 활성화됨"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "1차년도 공제액을 결정하는 월중/분기중/반기 컨벤션입니다."@@ -12542,6 +12545,9 @@ msgstr "요청일"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "로그인 시 인증 앱의 6자리 코드를 입력하세요."+msgid "Require a second factor when members sign in to this company."+msgstr "회사에 로그인할 때 구성원들이 두 번째 인증 요소를 사용하도록 요구"+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "이 회사를 열기 전에 인증자 앱을 요구합니다. 다른 회사는 영향을 받지 않습니다. <0>직원 계정 페이지</0>를 방문하여 각 사람의 상태를 확인하세요."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 6592dc7ed1..2d2c27eecc 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -9244,6 +9244,9 @@ msgstr "Jednostki metryczne są wyłączone"msgid "Metric units are enabled"msgstr "Jednostki metryczne są włączone"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Konwencja połowy miesiąca / połowy kwartału / połowy roku, która określa potrącenie w pierwszym roku."@@ -12542,6 +12545,9 @@ msgstr "Data żądana"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Wymagaj 6-cyfrowego kodu z aplikacji Authenticator przy logowaniu."+msgid "Require a second factor when members sign in to this company."+msgstr "Wymagaj drugiego czynnika podczas logowania członków do tej firmy."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Wymagaj aplikacji authenticator przed otwarciem tej firmy. Pozostałe firmy danej osoby nie są objęte. Odwiedź <0>stronę kont pracowników</0>, aby zobaczyć status każdej osoby."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex f9d2283796..f51c26dc5b 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -9244,6 +9244,9 @@ msgstr "Unidades métricas desativadas"msgid "Metric units are enabled"msgstr "Unidades métricas ativadas"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Convenção de meio de mês / meio de trimestre / meio de ano que determina a dedução do primeiro ano."@@ -12542,6 +12545,9 @@ msgstr "Data Solicitada"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Exigir um código de 6 dígitos de uma aplicação autenticadora ao iniciar sessão."+msgid "Require a second factor when members sign in to this company."+msgstr "Exigir um segundo fator quando membros fazem login nesta empresa."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Requer um aplicativo autenticador antes de qualquer pessoa poder abrir esta empresa. Suas outras empresas não são afetadas. Visite a <0>página de contas de funcionários</0> para ver o status de cada pessoa."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex fcdef57741..0f7c51e479 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -9244,6 +9244,9 @@ msgstr "Метрические единицы отключены"msgid "Metric units are enabled"msgstr "Метрические единицы включены"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Условие середины месяца / середины квартала / половины года, определяющее вычет первого года."@@ -12542,6 +12545,9 @@ msgstr "Запрошенная дата"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Требовать 6-значный код из приложения-аутентификатора при входе."+msgid "Require a second factor when members sign in to this company."+msgstr "Требовать второй фактор при входе сотрудников в эту организацию."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Требовать приложение аутентификатора перед тем как кто-либо сможет открыть эту организацию. Их другие организации не затронуты. Посетите страницу <0>учетных записей сотрудников</0>, чтобы увидеть статус каждого человека."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex eb12d76263..a1c3d0e7e7 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -9244,6 +9244,9 @@ msgstr "Metrik birimleri devre dışı"msgid "Metric units are enabled"msgstr "Metrik birimler etkinleştirilmiş"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "Ay ortası / çeyrek ortası / yarı yıl kuralı, ilk yıl kesintisini belirler."@@ -12542,6 +12545,9 @@ msgstr "Talep Edilen Tarih"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "Oturum açarken kimlik doğrulayıcı uygulamasından 6 haneli kod isteyini."+msgid "Require a second factor when members sign in to this company."+msgstr "Bu şirkete giriş yaparken üyelerin ikinci bir faktör kullanmasını zorunlu tutun."+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Bu şirketi açabilmek için doğrulayıcı uygulamayı gerektir. Diğer şirketleri etkilenmez. Her kişinin durumunu görmek için <0>çalışan hesapları sayfasını</0> ziyaret edin."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 8e46b0c570..80d30f0842 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -9244,6 +9244,9 @@ msgstr "公制单位已禁用"msgid "Metric units are enabled"msgstr "公制单位已启用"+msgid "MFA"+msgstr "MFA"+msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."msgstr "决定首年扣除的月中/季中/半年约定俗成的方法。"@@ -12542,6 +12545,9 @@ msgstr "要求日期"msgid "Require a 6-digit code from an authenticator app when signing in."msgstr "登录时需要来自身份验证器应用的 6 位数字代码。"+msgid "Require a second factor when members sign in to this company."+msgstr "成员登录此公司时需要第二因素验证"+msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "需要身份验证应用程序才能打开此公司。他们的其他公司不受影响。访问<0>员工账户页面</0>以查看每个人的状态。"