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.
paths: - "packages/auth/" - "apps/erp/app/routes/_public+/" - "apps/erp/app/routes/_oauth+/" - "apps/erp/app/routes/api+/mcp+/"
Authentication System
Carbon auth is built on Supabase Auth with cookie sessions, Redis-cached claims, and
per-company role/permission gating enforced through Postgres RLS. The @carbon/auth
package is the single source of truth; ERP and MES consume it.
Package: @carbon/auth (packages/auth/src)
Export subpaths (package.json): . (index.ts), ./auth.server, ./session.server,
./company.server, ./users.server, ./passkey.server, ./verification.server,
./middleware/flash.{server,client}. User query helpers split across
services/users.ts (client-safe: getClaims, getPermissionCacheKey,
getCompaniesForUser, makePermissionsFromClaims) and services/users.server.ts
(server-only: getUserClaims, deactivate flows).
Supabase client factories (lib/supabase/client.ts, client.server.ts)
getCarbon(accessToken?)— anon-key client, optionally Bearer-authed as a user.getCarbonServiceRole()— service-role client, bypasses RLS (admin ops only).getCarbonAPIKeyClient(apiKey)— anon client that sends thecarbon-keyheader so RLS resolves the company via the key.getUserScopedClient(userId)— mints a short-lived (5m) HS256 JWT withSUPABASE_JWT_SECRETand returns a user-scoped client (RLS enforced).- All clients set
db: { timeout: 25_000 }and rely on supabase-js's built-in read retries, plusstorageReadFetchfor storage reads (seedatabase-patterns.md).
Login (apps/erp/app/routes/_public+/login.tsx)
Magic link is the primary flow. The action rate-limits by IP (Upstash via @carbon/kv,
RATE_LIMIT env default 10 per 5 minutes, shared by login, MFA and unlock), runs the bot check (verifyBotProtection), then:
Bot protection. botProtection (bot-protection.server.ts, re-exported from
auth.server.ts) picks ONE provider per process from BOT_PROTECTION: "botid" (only
ON Vercel — IS_VERCEL, from Vercel's own VERCEL=1, which SST/Docker/the BYOC chart
never set) or "turnstile" (needs both CLOUDFLARE_TURNSTILE_SITE_KEY and
_SECRET_KEY). Unset: BotID for Cloud on Vercel, else Turnstile when both keys are set,
else null (no check). It is explicit because the Turnstile keys can be present for
something else (GoTrue, another form) while login uses BotID. An explicit value that
cannot work (botid off Vercel, turnstile without keys, anything else) throws at boot.
Every login loader (erp, mes, academy, starter) returns it, and the page calls
useBotProtection("/login", botProtection) (@carbon/react), which returns
{ token, ready, challenge }: render challenge in the form, post token as the hidden
botToken, and disable submit until ready. For BotID the hook runs initBotId, which
patches window.fetch so a POST to /login or /login.data carries the invisible
challenge, and challenge is null. For Turnstile it renders the widget and ready waits
on its token. The action calls verifyBotProtection({ token: botToken, ip, actor }).
Both sides read the one value on purpose: off Vercel the BotID script (served through the
apps/*/vercel.json rewrites) 404s and the patched fetch rejects, so the client must
never init BotID where the server cannot verify it. Failure modes differ deliberately: a
checkBotId THROW fails OPEN and logs (a platform misconfiguration would otherwise lock
out every Cloud user), while an unreachable Turnstile siteverify fails CLOSED (an operator
chose Turnstile by setting its keys). The rate limit and lockout apply either way.
Turnstile is verified in-app only; Supabase Auth captcha (Attack Protection) must stay OFF,
because the magic-link call forwards no token to GoTrue.
- Unknown user (non-Enterprise) →
sendVerificationCode, redirect to/verify(email verification-code signup). Enterprise edition rejects unknown users.
Self-signup blocklist (Cloud edition only) — isSelfSignupBlockedForEmail /
SELF_SIGNUP_BLOCKED_MESSAGE in @carbon/auth/self-signup.server (the domain list is
the bundled self-signup-blocked-domains.txt, loaded via ?raw). A brand-new
self-signup on a free/disposable email domain is refused. The email path checks
before the account exists — login.tsx (unknown-user branch) and verify.tsx
(before createEmailAuthAccount). OAuth (Google/Azure) has no pre-create seam:
GoTrue and the create_public_user trigger provision the user during the handshake,
so both apps' callback.tsx refuse a blocked-domain self-signup (no company
membership AND no pending invite) in the non-SSO branch and decline to mint a
session — the inert, membership-less account is left as-is (a later legitimate invite
reuses the row via createEmployeeAccount), so there is no teardown. Existing members
and invited contractors are never affected. No-op outside Cloud edition.
Other methods on the login page: Google + Azure OAuth (signInWithOAuth, redirect to
/callback), Passkey/WebAuthn (@simplewebauthn, /api/passkey/authenticate/*,
backed by passkey.server.ts), and — Enterprise edition with sso in
AUTH_PROVIDERS — SAML SSO ("Continue with SSO" → api+/sso.check.ts →
signInWithSSO → IdP → /callback; see the SSO section below). Availability
gated by isAuthProviderEnabled(...).
Routes live under _public+/ (login, callback, logout, magic-link, verify,
invite.$code, refresh-session). MES mirrors a subset under its own _public+/.
Enterprise SAML SSO (@carbon/ee/sso.server + ssoConnection)
Self-hosted-only (direct auth.identities writes). The whole feature lives in
packages/ee/src/sso/ behind isSsoEnabled() (gate.ts): Enterprise
edition AND sso in AUTH_PROVIDERS. The connection lookups and admin
mutations SELF-GATE on it (they answer "no connection" / refuse without
querying), and every route entry point checks it too — login buttons, the
sso.check endpoints, the settings action, and the callbacks' SSO branch
(which then also skips the admin.getUserById call). @carbon/auth keeps only
AuthSession.ssoProviderId + its preservation across refresh. Design record:
.ai/specs/2026-08-21-enterprise-saml-sso.md.
- Provider management:
packages/ee/src/sso/provider.server.tswraps the GoTrue admin SSO API (create/update/delete/getGoTrueSsoProvider, service-role key).getSamlSpUrls()returns the UN-prefixed/sso/saml/{acs,metadata}URLs — GoTrue self-declares its SP entityID/ACS fromAPI_EXTERNAL_URLwithout/auth/v1and validates each assertion'sDestinationagainst that exact URL; Kong routes/sso/(kong.ymlauth-v1-sso). Admin UX: Settings → Security (x+/settings+/security.tsx, actionx+/settings+/sso.tsx) viaupsertSsoConnection/updateSsoRequireSso/deactivateSsoConnectioninconnections.server.ts. ssoConnectiontable (migration20260820215433; partial unique index also in20260825185617for pre-squash DBs) binds a provider to a company:providerIdUNIQUE,metadataUrlXORmetadataXml(CHECK),active,requireSso, and at most ONE active row per company (ssoConnection_companyId_active_key— readers use.maybeSingle()). GoTrue providers are project-global, so the CALLBACK — not GoTrue — enforces provider → company + email-domain binding.- Domain ownership verification (
ssoDomaintable, same migration; spec.ai/specs/2026-08-27-sso-domain-verification.md): one row per claimed email domain —verificationToken(32-hex, per row),status pending|verified. Exclusivity attaches to VERIFICATION, not the claim:UNIQUE("companyId","domain")plus a partial unique index on("domain") WHERE status='verified'— any number of companies may hold pending claims on one domain (a free pending row must not block the rightful owner — that would be a squatting vector); first to verify wins, race-free. A cross-company verify conflict fails fast with a deliberately GENERIC message ("Failed to verify domain") — a distinct one would be an oracle for probing which domains are verified where.addSsoDomainpre-checks the company's own duplicate (no error-code branching). A domain routes SSO / enforcesrequireSsoonly while VERIFIED; the connection lookups inconnections.server.tsattach a computeddomains: string[]of verified domains, so consumers (callbacks, invite guards) keep the old shape. The DNS challenge (verification.server.ts): TXT at_carbon-challenge.<domain>withcarbon-domain-verification=<token>, checked manually via the Verify button (pinned resolvers 1.1.1.1/8.8.8.8; no polling, no re-verification — one-shot by design). Only verified domains are pushed to the GoTrue provider (syncGoTrueDomains); a new connection registers withdomains: []. Domain admin flows:addSsoDomain/verifySsoDomain/removeSsoDomainintents onx+/settings+/sso.tsx; UI is the Email Domains card on Settings → Security. Deactivating a connection DELETES itsssoDomainrows (releases the claims; re-activation re-verifies). Public email providers are denied at validation (PUBLIC_EMAIL_DOMAINS,settings.models.ts). - Session classification:
getSsoProviderIdFromSession(accessToken, user)requires anamrentry withmethod: "sso/saml"before resolving the provider id; fails CLOSED to the non-SSO path.getSsoProviderIdFromUseronly answers "HAS an SSO identity" — a linked account's Google/magic-link login also satisfies it; never use it to classify a session.AuthSession.ssoProviderIdis stamped at the callback and preserved across refresh and company switch. - Callback SSO branch (ERP
_public+/callback.tsx): verifies connection + domain; an ACTIVE same-email account gets the SAML identity LINKED onto it (linkSsoIdentityToUser— also deletes stalesso:%identities on the target, then the duplicate auth user is deleted and a session minted via server-side magic-link redemption); otherwise the invite-first migrationmigrateUserToSsoruns (one Kysely transaction: user row, role-keyed account activation —employee/customerAccount/supplierAccount— membership, permission merge, invite accept under FOR UPDATE). No invite (and the domain-mismatch rejection) → rejected;deleteJitSsoUserremoves the WHOLE throwaway JIT user — auth user plus the trigger-createduser/userPermissionrows (no FK cascade between the schemas), guarded on zero memberships — or the leftover profile tripsauthIdentityExistsand 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 withGOTRUE_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 inauth.identitiesfor the existing user so GoTrue takes its LinkAccount / AccountExists branch instead. Provider-agnostic: the match is carried by the GENERATEDemailcolumn (identity_data.email = lower(email)), NOTprovider_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-sqlwriters (pinned bysso.server.test.tsvia a capturing Kysely driver):seedSsoIdentityForUser(one user, idempotentON CONFLICT (provider_id, provider) DO NOTHING) — called best-effort/logged byseedSsoIdentityForNewUserin all three ERP account-creation flows (users.service.tscreate{Customer,Employee,Supplier}Account); and, run from the domain-claim flows,backfillSsoIdentitiesForDomain(verify → seed EVERY existing non-SSO user on the domain) andremoveSsoIdentitiesForDomain(unregister → delete, keyed on the email column so it also removes GoTrue's self-healed NameID rows). Backfill/remove are deliberately notcompanyId-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 helpersemailDomain/ssoProviderColumn. A DB guard —enforce_sso_domain_claimtrigger onauth.sso_domains+ thessoReservedDomaintable (migration20260829142619_sso-domain-guard.sql) — refuses anyauth.sso_domainsinsert for a reserved domain or one with no Carbon-sidessoDomainclaim, 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/getSsoConnectionByProviderIdare the ONE copy shared by ERP, MES, and jobs) refuses non-SSO logins server-side at the login actions, the callbacks' non-SSO branch, and the passkey verify routes in both apps.DEV_BYPASS_EMAILis exempt. Break-glass:UPDATE "ssoConnection" SET "requireSso" = false WHERE "companyId" = '<id>';. - MFA: SSO sessions mint
mfaVerified: trueunconditionally (includingCONTROLLED_ENVIRONMENT) and therequireMfaenrollment gate exempts them — the IdP owns MFA (user decision). - Trigger:
create_public_user()SKIPS (inserts nothing) when the new auth user's email already belongs to a DIFFERENTpublic."user"row — the callback migration owns that case; inserting would FK/unique-crash GoTrue's signup transaction. - Invites:
getSsoAwareInviteLink(connections.server.ts; used by the ERP invite routes and jobsuser-admin.ts) routes covered-domain invite emails to/login?email=...instead of/invite/<code>, so the IdP is never bypassed. Employee invites outside the covered domains are refused up front (refuseEmailOutsideSsoin ERPusers.service.ts→uncoveredSsoDomainError: arulerefusal, orunavailablewhen the domains cannot be read). - Config: GoTrue SAML via
SAML_ENABLED/SAML_PRIVATE_KEYin root.env(compose substitution →GOTRUE_SAML_*;crbn reloaddoes not read root.env— see.ai/lessons.md).
CSRF and CSP (middleware/security.server.ts, lib/security.ts)
The carbon cookie is SameSite=Lax on the PARENT domain (carbon.ms), so every
*.carbon.ms host is same-site and Lax alone is not a CSRF defence. securityMiddleware
(root middleware of erp, mes, academy, starter) refuses a POST/PUT/PATCH/DELETE when
Sec-Fetch-Site is anything but same-origin/none, or — without that header — when
Origin differs from the addressed host (getRequestHost, @carbon/utils; never
request.url, the internal origin behind the proxy). No Origin at all is a server (webhooks,
Inngest, assembler callback, API-key clients, the MES→ERP proxy) and passes, so webhooks
need no exemption; CROSS_ORIGIN_ENDPOINTS is only /token, /register, /api/mcp.
Browser submissions arrive as …/path.data, stripped before matching.
React Router 7.18 has its own check (throwIfPotentialCSRFAttack: Origin host vs
request.url host, 400) — but only on DOCUMENT and .data actions, and it runs before
middleware. Resource routes (every api+ action) get no check from it; the middleware is
what refuses those (checked 2026-09-28: handleResourceRequest calls no origin check; a
cross-site POST to an api+ route now gets the middleware's 403).
GET loaders that write (kanban QR api+/kanban.$id.tsx, MES x+/start|end.$operationId,
invoice new routes, settings.sequence.next, stock-transfer pick/unpick, stripe-connect
dashboard) call rejectCrossSiteNavigation: 403 on Sec-Fetch-Site: cross-site,
while a QR scan (none) and the ERP→MES redirect (same-site) pass. Deliberately unguarded:
api+/link.ts (company switch from email links — webmail clicks are cross-site) and
stripe-connect connect (Stripe's expired-link refresh_url lands on callback, which
redirects there: a chain started on stripe.com, so cross-site).
CSP: the middleware puts a per-request nonce in nonceContext; entry.server passes it
to vercelHandleRequest(…, { nonce }), which React Router's <Links>, <Scripts> and
<ScrollRestoration> read from framework context; the inline window.env script reads
UNSAFE_FrameworkContext. The enforced policy is still the old baseline (object-src,
base-uri, frame-ancestors); the strict nonce + strict-dynamic policy
(buildContentSecurityPolicy) ships as Content-Security-Policy-Report-Only, reporting
to /api/csp-report in each app. Why each exception exists (wasm-unsafe-eval, ERP
unsafe-eval for the configurator, style-src 'unsafe-inline', img-src https:) and
why there is no form-action: .ai/plans/2026-09-28-csp-csrf.md.
Sessions (session.server.ts)
createCookieSessionStorage, cookie namecarbon,httpOnly,sameSite: "lax"("none"in Test edition, always withSecure— browsers dropNonewithout it),secure/domainfromDOMAINin non-test. Payload stored under keySESSION_KEY = "auth";SESSION_MAX_AGE = 7 days. Every write of this cookie passesSESSION_MAX_AGE, flash writes included: the toast shares the cookie, and a write without it turned the session into one that ends when the browser closes.- Cookie names are per deployment.
authCookieName(utils/cookie.ts) appendsAUTH_COOKIE_SUFFIXtocarbon,companyId,carbon-pushandcarbon-oauth-state. US and EU production both setDOMAINtocarbon.ms, so with one name each region overwrote the other's cookie and failed its signature (EU has its ownSESSION_SECRET), signing users out. EU sets the suffix (eu) on its ERP and MES; unset keeps the plain names. ChangingDOMAINinstead is not a fix: the browser still sends the parent-domain cookie, and it changes the passkeyRP_ID. requireAuthSessionreads/validates;getOrRefreshAuthSessionrefreshes withinREFRESH_ACCESS_TOKEN_THRESHOLD(10 min) of expiry viarefreshAccessToken.destroyAuthSessionclears auth + company-id cookies, redirects to login.clearAuthCookies(whichdestroyAuthSessionand the login loader's expired-session branch call) also ends this browser's push notifications: it reads the signedcarbon-pushcookie (pushEndpointCookie, set byapi+/push-subscriptionwhen browser notifications are enabled), deletes everypushSubscriptionrow of that endpoint with the service role, and clears the cookie. Every sign-out path therefore stops pushes in that browser. A cross-site navigation (Sec-Fetch-Site: cross-site, the login GET from another site's link) skips the cleanup, per the GET-write rule; such rows lapse anyway, becausenotifyskips rows no page load has refreshed within a session's lifetime. The service-role client is imported inside that cleanup, not at module load, so importingsession.serverbuilds no Supabase client (the session tests mockconfig/envwithout the Supabase keys).updateCompanySession/updateSessionConsoleswitch active company / console mode.- Console pin-in (
@carbon/auth/console-pin.server): which operator is pinned in at a console terminal lives in theconsole-pin-<companyId>cookie, SIGNED withSESSION_SECRETand bound to the company and the terminal's session user (setConsolePinIn/clearConsolePinIn).resolveConsolePinInre-validates it on every request — the operator must still be an active employee of the company andcompanySettings.consoleEnabledstill on — and is memoized per read request. PINs are bcrypt hashes inemployeePin(no API-role access;set_employee_pin/verify_employee_pinover the server's Kysely connection, via@carbon/ee/console.server). MES pin-in (x+/console.pin-in.tsx) consumes the per-operatorAccountLockoutattempt and the per-terminalRatelimittoken BEFORE verifying (refunding both on a non-guess), so a parallel burst cannot outrun the limits.companySettings.consoleEnabledis server-only: a trigger refuses API-role writes, and it only moves throughupdateConsoleSetting(requireEntitlement).
MFA / TOTP (mfa.server.ts)
Supabase TOTP MFA, gated explicitly in app code (server-side sign-in runs through the
service role, so GoTrue's automatic AAL enforcement never fires). Factors live in
Supabase's auth.mfa_factors — no app table.
- Gate at login: ERP/MES
callback.tsxandpasskey.authenticate.verify.tscheckuserHasVerifiedTotpFactor(userId)after the first factor succeeds; enrolled users get their tokens parked viasetPendingMfaSession(session key"mfa", 10-min TTL) and a redirect to/mfa— the fullcarboncookie is only minted after the challenge. - Active re-check:
requireAuthSessionbounces any session withoutAuthSession.mfaVerifiedwhose user has a verified factor to/mfa(covers sessions minted before enrollment). The factor lookup is Redis-cached (mfa:factors:${userId}, 1h TTL, invalidated on enroll/unenroll/admin reset) andoncePerRead-memoized; it fails OPEN on lookup errors. Dev-bypass sessions are minted withmfaVerified: true. /mfaroutes exist in all four apps (ERP/MES/starter_public+/mfa.tsx, academy_auth+/mfa.tsx); the shared action logic iscompleteMfaChallenge(request, code)insession.server.ts. Academy/starter have no callback gate — the re-check bounces them.- Token rotation: every
challengeAndVerifyrotates the refresh token — any caller MUST re-issue the cookie from the returned session (/mfaroutes,api+/mfa.verify,api+/mfa.unenrollall do).refreshAuthSessionpreservesmfaVerifiedlikeconsole. - auth-js gotcha:
supabase.auth.mfa.*reads the client's INTERNAL session, not theAuthorizationheader override —mfa.server.tsseeds a fresh anon client viaauth.setSessionwith the cookie's tokens. - Enrollment: Account settings → Security (the modal pane
packages/account/src/ui/SecuritySettings.tsx, data and passkey writes inapi+/account.security.ts) →api+/mfa.enroll/mfa.verify/mfa.unenroll(unenroll requires a current code as step-up). The enroll→scan→verify state machine, the 6-slot code input, and the invalid-code copy are shared with the enforcement gate via~/components/TotpEnrollment(useTotpEnrollment,OtpInput,INVALID_CODE_MESSAGE) — change them there, not per surface. The QR carriesissuer=Carbon (<company name>)so a phone can tell two Carbon tenants apart (the account line is the user's email, set by GoTrue).sanitizeIssuerstrips colons:otpauth://totp/{issuer}:{account}uses one as its delimiter and the Key-URI spec forbids it in either field. The issuer is baked into the QR at enrollment — changing it does not update existing entries. Admin recovery:x+/users+/employees.reset-mfa.$employeeId.tsx(update: "users") callsadminDeleteTotpFactors— factors are global to the auth user, so it affects every company the user belongs to. - Org enforcement:
companySettings.requireMfa(migration20260816103045) toggled from Settings → System → Security (x+/settings+/security.tsx);CONTROLLED_ENVIRONMENT=trueforces it on and cannot be overridden (NIST 800-171 3.5.3). Enforced as a BLOCKING SCREEN in the ERP/MES shell loaders (MfaEnrollmentRequired), never a redirect — a redirect would have to allowlist theapi+/mfa.*routes used to escape it, and any gap there is a lockout or a hole. Mirrors the ITAR gate. Scoped to the ACTIVE company only: a user in a company that does not require MFA is not gated, and the shell re-runs on company switch. Console sessions are exempt (a shared kiosk cannot complete a personal enrollment); SSO sessions (authSession.ssoProviderIdset) are exempt too, including underCONTROLLED_ENVIRONMENT— the IdP owns MFA (see the SSO section); MES has no enrollment UI so its gate links to ERP. - Email:
~/services/mfa-email.server.tsowns both MFA emails (MfaRequiredEmail/MfaEnabledEmailin@carbon/documents/email).sendMfaRequiredEmailsfires from the settings action on the off → on transition only (it re-readscompanySettings.requireMfafirst — the Switch re-submits on every flip), and batches active employees throughbatchTrigger("send-email", …)25 at a time. It is additionally skipped whenCONTROLLED_ENVIRONMENT— effective enforcement there isCONTROLLED_ENVIRONMENT || requireMfaand NOTHING ever writes the column, so it sitsfalsewhile MFA is already mandatory; the column alone would read as a fresh transition and announce a requirement that predates the deployment. The Switch isdisabledin that mode, but the action has no such guard, so this cannot live in the UI.sendMfaEnabledEmailfires fromapi+/mfa.verify— that route only ever verifies an ENROLLMENT (a login challenge goes throughcompleteMfaChallengeon/mfa), so reaching it means a factor was just added. Both take a service-role client, and NEITHER goes throughtrigger("notify", …): security mail must not be silenced by anotificationPreferenceopt-out or gated on theEMAIL_NOTIFICATIONSplan feature. Both swallow their own errors — enrollment and the setting flip must not fail because email did. - Admin visibility: the
users_with_verified_mfa(company_id)RPC (SECURITY DEFINER —auth.mfa_factorsis unreachable from the SECURITY_INVOKERemployeesview) backs the Two-Factor column on employee accounts. It returns ids only, is scoped to the caller's companies, and returns nothing unless the company enforces MFA. A migration that adds an RPC needs a PostgREST schema reload or the function is invisible to the app. - Config: local GoTrue MFA env in
packages/dev/docker/docker-compose.dev.yml(GOTRUE_MFA_TOTP_*);[auth.mfa]inconfig.tomlfor hosted parity. API-key and OAuth/MCP token auth are machine paths and are not challenged.
Permissions & RLS gating (auth.server.ts → requirePermissions)
requirePermissions(request, { view?, create?, update?, delete?, role?, bypassRls?, allowPortalAccounts? }) is
the gate used in every loader/action. Two paths:
carbon-keyheader present → API-key auth (see below).- Otherwise →
requireAuthSession, thengetUserClaims(userId, companyId).- A session whose role in the active company is
customerorsupplier(portal accounts) is refused with a 403 BEFORE the empty-requirement early exit, unless the route passesallowPortalAccounts: true. Portal accounts holddocuments_*,parts_view,sales_view/purchasing_view, and{}admitted any session, so before this ~50 routes that read with the service role (file previews, job travelers, order and quote pages) served them. No route is theirs: portal pages are share links on the service role. Opted in: onboarding, company switch (erp/mes/starter),api+/link.ts, academy challenge — each acts on the user's own identity. A 403, not a redirect: the MES/xmiddleware callsrequirePermissions, so a redirect there loops. - Claims are
{ role, permissions }. Cached in Redis (@carbon/kv) at keypermissions:${userId}; on miss, fetched via theget_claims(uid, company)RPC (getCarbonServiceRole) and cached.makePermissionsFromClaimsshapes the result. getUserClaimsis additionally memoized per read request viaoncePerRead(@carbon/logger/middleware.server), so the several loaders a page matches share one Redis GET. Read-gated on purpose: an action and its loader revalidation run in the same request, and memoizing there could let a gate pass on claims the action just revoked. The Supabase clientsrequirePermissionsreturns are memoized per request too (oncePerRequest), which needs no gate — a client is not database state.- Each required permission checks
permissions[name][action]contains the activecompanyId(or"0"wildcard = all companies).roleis matched directly. - On failure: if
role === nulldestroy session →/; else flash "Access Denied" → authenticated root. - Returns
{ client, companyId, companyGroupId, email, userId, sessionUserId, consoleMode }.bypassRls: true+ employee role returns a service-role client; otherwise a Bearer-authedgetCarbon(accessToken)client (RLS enforced). consoleModeisauthSession.console === companyId. In console modeuserIdis the pinned operator fromresolveConsolePinIn(falling back to the session user when nobody valid is pinned in);sessionUserIdis always the account the terminal is signed in with. Gate terminal-level actions (entering console mode) onsessionUserId, neveruserId.
- A session whose role in the active company is
Claims cache must be invalidated when permissions change — users.server.ts deactivate
flows call redis.del(getPermissionCacheKey(userId)).
API key auth
carbon-key: <key> header. requirePermissions resolves it through
getCompanyIdFromAPIKey, which now reads via getApiKeyRecord
(packages/auth/src/services/api-key.server.ts): a 30s Redis cache at
apikey:auth:<keyHash>, per-request memoized (oncePerRequest) so one HTTP call
does one lookup even though both requirePermissions and the v1 scope read need
the row. Unknown keys are cached too (the literal "null"), so a bad key
hammering the endpoint doesn't hammer Postgres. Redis being down falls through to
the DB. Busting: the api-key service functions (updateApiKey, revokeApiKey in
settings.server.ts) call invalidateApiKeyCache (settings.service.ts →
bustApiKeyCache) after an edit, and BEFORE and after a delete (the keyHash is
unreadable once the row is gone), so a scope
change or revocation takes effect immediately; the worst-case lag for any other
writer is the 30s TTL. Then:
- Reject if
expiresAtpassed (401). - Rate-limit via
checkApiKeyRateLimit(@carbon/database/ratelimit, Postgres functioncheck_api_key_rate_limit) using per-keyrateLimit+rateLimitWindow("1m"|"1h"|"1d"). 429 withX-RateLimit-*+Retry-Afterheaders on exceed. The same function also holds a company to a per-minute total across all its keys:companyPlan.apiRateLimit, or 60 when that is NULL or the company has nocompanyPlanrow (v_default_company_limit, migration20261015143857). It sums the keys' counters for the current minute, each capped at its own limit so requests refused on one key do not lock out the others. No separate table — so deleting a key drops its share, and a key on an hourly/daily window is not counted (none exist). A company refusal returns the company's limit aslimit. Pinned bysupabase/tests/api-key-rate-limit.test.sql. - Raising a limit is a support operation, not a setting. One key:
apiKey.rateLimit(tenants withsettings_updatecan also write it through the Data API, so the company total is the real ceiling). A company:companyPlan.apiRateLimit, which only the service role writes (the table has a SELECT policy and no other) and which company backups never carry. A key's limit above its company's total is capped by the total. Both are read per request through the 30s key cache. Only a company with acompanyPlanrow (every paying Cloud company) can be given an override: do not insert one just for this, sincecompany-cleanuptreats a plan row as a paying company. The Stripecustomer.subscription.deletedwebhook deletes the row, override included; the subscription sync upserts named columns only, so a plan change keeps it. lastUsedAtis written bycheck_api_key_rate_limititself, at most once a minute per key, so the Node path and the edge functions both record it. (The app used to build this update withvoid client.from(…).update(…), which never sends: a supabase-js builder only runs when awaited.)- Scope check:
scopesis JSONB{ "<permission>_<action>": [companyIds] }; required perms must be present and include the active company.{}is NOT full access here — an empty scope set fails the check. 403 on failure. - Cloud edition: Starter-plan companies are blocked from API access (Business+ only),
except
STRIPE_BYPASS_COMPANY_IDS. The plan comes from the cachedgetCompanyPlanId(seebilling-system.md), so a plan change made outside the Stripe sync can take up to 5 minutes to bite. - Returns a
getCarbonAPIKeyClient(apiKey)client (RLS resolves company via header).
Key hashing: hashApiKey = createHash("sha256") hex (same in Node ERP and Deno edge
functions). Raw key is shown once; only keyHash is stored.
OAuth 2.0 server (MCP remote connector)
ERP exposes an OAuth 2.0 AS for use as a remote Claude/MCP connector. Routes under
_oauth+/ (authorize.tsx, token.tsx, register.ts) plus discovery at
[.]well-known.oauth-authorization-server.ts and [.]well-known.oauth-protected-resource.ts.
- PKCE:
code_challengeon authorize (required for public clients), verified S256-only withcode_verifieron token. - Dynamic client registration (
POST /oauth/register) writes to theoauthClienttable. It is open by design (MCP clients self-register) but rate-limited per IP (100/hour), and the rules live in~/services/oauth.server.ts:isAllowedRedirectUriadmits https, http only on a loopback host, or a private-use scheme, never a fragment;supportedScopekeeps onlymcp:tools. Onlyclient_secret_postandnoneare accepted astoken_endpoint_auth_method(what discovery advertises;/tokennever reads a Basic header). - Authorize (
authorize.tsx) requiressettings_updateand employee role in the SELECTED company (canAuthorizeForCompany), not just the session's active one, and re-checks the redirect URI withisRegisteredRedirectUri(registered AND still allowed — clients registered before the rules existed are held to them too). The consent page shows the redirect host only once it passes that check. - Refresh tokens rotate on every use (the update matches the OLD hash, so one of
two concurrent refreshes loses) and die after 30 days idle (
isRefreshTokenIdle:expiresAt+ 30 days — no extra column). There is no revocation endpoint. - A token carries no permissions of its own: the MCP endpoint re-checks on every
request that the user is still an
employeeof the token's company and gates each operation on that user's live permissions (seemcp-tools-reference.md). - Tables:
oauthClient,oauthCode,oauthToken(all PKxid(), scoped bycompanyId/userId). Columns are plain TEXT, but access tokens, refresh tokens, and client secrets are SHA-256 hashed at the app layer before storage viahashOAuthSecret(auth.server.ts). Lookups hash the incoming value and compare. - MCP endpoint (
apps/erp/app/routes/api+/mcp+/_index.ts): aBearertoken not prefixedcrbn_is an OAuth token —findOAuthToken(hash lookup + expiry), the per-user rate limit, thenoauthContext(membership, company group, claims, user client, in parallel), both inapi+/v1+/lib/authenticate.server.tsbesideauthenticateApiKey. Acrbn_bearer is rewritten tocarbon-keyAPI-key auth.companyId/userIdalways come from the token row.
Schema (newest migrations; packages/database/supabase/migrations)
user/userPermission(id,permissionsJSONB) — seeded by thecreate_public_user()trigger (on_auth_user_createdonauth.users) — which SKIPS inserting when the email already belongs to a differentuserrow (the SSO duplicate case; the callback migration owns it).userToCompany— junction, PK(userId, companyId),roleenum'employee' | 'supplier' | 'customer'.ssoConnection— SAML SSO tenant binding (see the SSO section): PK(id, companyId),providerIdUNIQUE,metadataUrl/metadataXml(exactly one, CHECK),active,requireSso. SELECT: employee role; writes:settings_update.ssoDomain— DNS-verified email domain claims: PK(id, companyId), composite FK →ssoConnection,UNIQUE("companyId","domain")+ partial unique("domain") WHERE status='verified'(first-to-verify-wins),verificationToken,status(ssoDomainStatusenum:pending|verified),verifiedAt. Same RLS split asssoConnection.apiKey—keyHash(unique),keyPreview,name,companyId,createdBy,scopesJSONB,rateLimit(default 20; keys created before20261002153217keep 60),rateLimitWindow(default'1m'),expiresAt,lastUsedAt. The old plaintextkeycolumn was dropped.apiKeyRateLimit— UNLOGGED, PK(apiKeyId, windowStart),requestCount.- RLS/RPC functions:
get_claims,get_company_id_from_api_key,get_api_key_scopes,check_api_key_rate_limit,create_public_user.
Config (packages/env/src/index.ts, re-exported by @carbon/auth)
SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, SUPABASE_JWT_SECRET,
SESSION_SECRET, SESSION_KEY ("auth"), SESSION_MAX_AGE,
REFRESH_ACCESS_TOKEN_THRESHOLD, DOMAIN, RATE_LIMIT, CarbonEdition,
STRIPE_BYPASS_COMPANY_IDS, IS_VERCEL, Turnstile + OAuth-provider keys.
Gotchas
getUserClaimsswallows Redis errors and falls back to the DB; a stale cache is the usual cause of "Access Denied" after a permission change — invalidate the cache key.verifyAuthSession(therequireAuthSession(request, { verify: true })path) caches only its positive verdict in Redis for 60s, keyed by a SHA-256 of the access token. Negatives are never cached —getAuthAccountByAccessTokenalso returns null on a transient network error. Bounds how long a deleted/deactivated account keeps being accepted; signing out never revoked a live access token anyway.- ERP code imports
getUserClaimsfrom@carbon/auth/users.server; the ERP used to carry a drifted copy that missed the cache TTL. Don't reintroduce one. - Service-role clients bypass RLS — only use behind
bypassRls+ employee role. - API key
scopes: {}denies, not grants. Don't assume empty = full access. - Edition matters: Enterprise rejects unknown-user login; Cloud gates API keys by plan and enforces the bot check (BotID on Vercel, Turnstile elsewhere).