Skip to main content
Tuturuuu is the proposed SAML 2.0 identity provider: an invited Claude organization member signs into Claude through WorkOS using a Tuturuuu account. This is distinct from inbound enterprise sign-in to Tuturuuu and from internal cross-app sessions. No Supabase bearer token is shared with Claude.

Pilot decisions

The pilot is SP-initiated and defaults to denied access. A future enabled client selects exactly one active nonpersonal workspace. Each user needs current MEMBER status, an explicit client assignment, a confirmed email in an approved domain, fresh verified MFA no older than ten minutes, and identity-sharing approval on every login. Guests, invitations and email-domain matches alone confer no access. No workspace or test population has been selected by the protocol fixture. Share only a stable random pairwise NameID/id, confirmed email, firstName and lastName. Persist subjects per client/Auth account; do not derive them from email or recycle them. An email change requires fresh verification and operator review of Claude linking behavior before restoring SSO. Names are presentation, never authorization. Claude owns roles, seats and invite-only provisioning. The pilot excludes OIDC, SCIM, groups, IdP-initiated login and single logout. Tuturuuu logout does not imply termination of an existing Claude session. These decisions apply to future outbound SSO Web/consent/management surfaces; ordinary Tuturuuu sign-in and cross-app session policy retain their own rules.

Phase 1 protocol boundary

packages/sso provides strict Zod configuration/request/identity/assurance contracts, bounded Redirect and POST AuthnRequest decoding, pinned request signatures when required, signed response/assertion construction and public IdP metadata without SLO. Clock, signer and ID generation are injected. Portable entrypoints have no framework imports; the implementation targets Node crypto and zlib for the future Next.js Node runtime on Vercel. The selected libraries are xml-crypto 6.4.0 and @xmldom/xmldom 0.9.12. RSA-SHA256 signatures, SHA256 digests and exclusive canonicalization are supplied by the library. Request admission rejects unknown SPs, exact-URL mismatches, stale requests, unsupported NameID/authentication contexts, passive interactions, duplicate IDs/parameters, DTDs and oversized compressed/expanded XML. Unsigned requests require an explicitly unsigned profile and do not authenticate the SP. Assertions expire after two minutes and bind Audience, Recipient, Destination and InResponseTo. The only supported NameID format is persistent; the connection’s actual requirements must be confirmed before enabling it. For both request bindings, NameIDPolicy or AllowCreate omission means false, including signed requests. Only explicit true/1 permits the future caller to allocate a subject; otherwise it must find an existing mapping or deny. These defaults apply to the portable protocol and future outbound SSO adapters, with no unsigned-request exception. See packages/sso/src/__tests__/security-review.test.ts for omission and invalid-boolean regression coverage. REFEDS MFA context requires a future adapter to prove primary authentication and current TOTP MFA; the package cannot establish assurance from a supplied timestamp alone. Phase 1 adds no routes, UI, migrations, live clients or hosted configuration. Metadata generation is a library function, not a published metadata endpoint. Do not expose the protocol functions as an issuance API without the later gates.

Phase 2 persistence boundary

Six additive migrations (20261022100000 through 20261022100005) introduce manage_sso_clients and eight RLS-enabled private tables: sso_clients, sso_saml_clients, sso_assignments, sso_subjects, sso_disclosure_grants, sso_transactions, sso_signing_keys and sso_audit_events. All children carry ws_id and composite tenant foreign keys. Creation always starts disabled; client changes require an expected policy revision. The initial profile supports only persistent NameID and one to eight exact HTTPS ACS destinations, without credentials, fragments or custom ports. Configuration stores approved email domains; authoritative email/domain enforcement belongs to phase 3. Browser roles and service_role have no direct table privileges. Management is through service-only sso_manage_client and sso_set_assignment RPCs. Both require a current MEMBER in an active nonpersonal workspace with effective manage_sso_clients permission (including the existing creator/admin semantics). The server must resolve the authenticated actor before calling them; an actor ID is a trusted server input, never a browser authorization claim. Service-only sso_create_transaction reserves a request hash uniquely per client, stores InResponseTo and an exact configured ACS, and caps expiry at five minutes. Opaque handles, browser/session bindings and RelayState are hashes; raw RelayState and assertions are absent. sso_record_consent records one immutable per-login approval or denial for the fixed identity attribute list, binding actor, policy, browser and session. Denial burns the transaction. sso_consume_transaction takes row locks, rejects expired/used transactions, rechecks enabled client, policy, current MEMBER and active assignment, and requires the matching approval and bindings. The validated request’s allow_create is persisted with default false; allocation requires explicit true, while false can reuse an existing mapping. Consumption, random 256-bit pairwise subject allocation and audit append commit together. Concurrent consumers yield one winner and a replay error. authenticated users can call sso_read_own_disclosures(ws_id) to read up to 100 of their own receipts. Its actor comes exclusively from auth.uid(). Other users and anonymous callers cannot read those receipts. Disclosure receipts and audit rows reject updates and deletes; audit appends expose only bounded event codes and correlation IDs. sso_append_audit is service-only and requires a consumed, approved transaction for issuance events. A signed event records the issuer’s observation; it does not prove Claude accepted the response. Signing-key rows contain only a public certificate, kid, status, revision and validity/rotation timestamps. A partial unique index permits at most one active key per client. Certificate syntax constraints reject private-key PEM; the future signer must validate the actual X.509 certificate and key match. No private key, secret reference, key import/rotation RPC or signer route is added by this phase. Subjects reference auth.users, so actual Auth deletion clears their user link while reserving the random value. Auth deletion also clears client/assignment creator attribution and deletes assignments and actor-bound transactions, even though the public user row remains. Membership deletion cascades assignments; MEMBER-to-GUEST demotion deletes them too. Rejoining or later promotion requires an explicit new assignment. This rule applies to every phase 2 SSO client. Workspace hard deletion cascades clients, protocol profiles, assignments, subjects, transactions and public signing-key metadata, including disabled clients. Immutable disclosure receipts and audit events retain denormalized workspace/client/actor/ transaction UUIDs without parent foreign keys. These historical receipts cannot authorize a login without a live transaction and current membership/assignment. Cleanup never disables or bypasses their append-only triggers. All eight tables force RLS; approved definer RPCs retain their PostgreSQL BYPASSRLS owner, while a non-BYPASSRLS table owner is subject to the policies. Receipt/audit actors are UUID-only correlation values without deletion-blocking user foreign keys; retention and pseudonymization require the phase 5 operating policy. There is no automatic retention job in this phase.

Database verification

From the repository root, run:
The runner stages the complete migration history into an owned disposable Supabase project, applies it with supabase start and supabase db reset, runs sso-persistence.sql with strict pgTAP parsing, and drives a real two-connection consume race. It generates packages/types/src/supabase.ts from that same applied public,private,storage schema, then stops only the owned database without backup. Synthetic race rows are committed only inside the disposable database and vanish with its teardown; immutable audit rows are never bypassed for fixture cleanup. Each race uses fresh UUIDs so repeat runs preserve retained user/workspace history. The pgTAP packet covers membership removal/rejoin, demotion/promotion, real Auth deletion (including retained public users), creator and workspace deletion, byte-identical retained history, and a non-BYPASSRLS table owner. The separate race requires one winner, one replay rejection, one subject and one consume audit. It also races membership deletion and assignment deactivation against consume in both orders. The holder observes its own PID blocking the competitor before it commits: revocation first must deny consume without a subject or consume audit; consume first must commit before revocation can commit. Both orders deny a later consume. Assignment deactivation uses direct SQL so the management RPC’s client lock cannot mask missing authorization-row locks. Keep lock-removal negative controls confined to a disposable database; never alter production migrations to make the harness pass. When the committed base type snapshot already lags its applied schema, generate both the clean base and candidate using the same CLI and formatter. Apply their generated delta to the committed base with a three-way merge, failing on conflicts; exclude unrelated baseline drift rather than manually editing generated objects. The SSO-only committed type delta intentionally excludes existing employee-profile objects absent from the base snapshot. The workflow artifact still contains the complete applied schema. Check packages/users-core as well as the types package after generation because new FK relationships affect nested select inference. The runner prints a schema snapshot digest and recovery directory for a failed cleanup. Use the existing isolated lifecycle cleanup procedure for that directory. The SSO persistence database contract CI workflow repeats this on the exact PR head. No application stack or build is needed for this check. These primitives do not establish Auth account status, confirmed email, MFA, request XML validation, key selection or an issuance permit. Phase 3 must provide those checks, recheck current key/policy state after signing, and burn the original transaction on an unknown signing outcome. Never interpret a consumed database row as permission to retry or emit an assertion without those service gates.

Verification and remaining work

packages/sso/src/__tests__ drives generated signatures through Node-SAML’s SP consumer with disposable in-memory keys. Negative coverage includes wrapping, tampered claims, unsigned assertions, wrong audience/ACS, expiration, replayed InResponseTo, unknown SPs and deflate bombs. Node-SAML uses the same underlying signature library; independent SAML parsing is not independent crypto validation. Parser and XML-signature library failures expose fixed protocol error messages without request-derived diagnostics. Wrapping regressions retain an intact signed assertion beside a distinct unsigned attacker assertion, verify both original assertion and renewed outer signatures, and assert semantic rejection. The harness adds exact Destination/Recipient checks because Node-SAML 5.1.0 does not enforce them for login responses. See packages/sso/README.md for dependency advisories, limits, reproduction commands and the samlify evaluation. Phase 2 supplies the private database primitives described above. Phase 3 adds authoritative Auth/MFA/eligibility reads, disclosure enforcement, key/policy revision fences, durable audit, disabled Web routes and a minimal bilingual per-login consent page. Phase 4 supplies workspace management UI. Phase 5 supplies rotation, compromise/disable procedures, an explicitly selected test workspace and connection, exact-commit CI/runtime acceptance and real Claude SSO tests. Runtime profile verification and actual Claude login remain unrun. Run focused tests through ttr resources run -- bun run --cwd packages/sso test and the package’s type-check script. Require applicable exact-commit CI before integration; no local release builds or production configuration changes are part of this phase.

Disabled issuance adapters (phase 3)

All endpoints return 404 unless the server-only SSO_SAML_ENABLED is exactly true. No enabled client or production configuration is included in source. The adapter additionally requires explicit server configuration, the applied schema, an enabled nonpersonal-workspace client, active current public signing-key metadata, and matching private signing material. Missing dependencies fail closed. The initial adapter supports one pinned client, one exact ACS, persistent NameID and TOTP MFA. Other MFA methods and multiple ACS profiles remain unqualified. Admission validates the request against the registered SP and reserves its unique request ID through sso_create_transaction. An encrypted Secure, HttpOnly, host-only cookie preserves the exact validated request and RelayState. Navigation URLs contain only the opaque handle. Parallel transactions have separate cookies; oversized state is rejected rather than truncated. The transaction lasts 290 seconds, leaving transit margin below the database’s five-minute maximum. A verified account/session present at admission is hashed into an immutable starter binding. Signed-out and cross-site POST admission remain supported: the first authenticated continuation atomically claims the unbound transaction before any consent form or decision. Consent reloads and decision POSTs must match that user/session pair. Switching accounts or signing in again with a new session burns and audits the pending transaction; restart SSO from the SP. Refreshing tokens within the same provider session preserves the binding. This rule applies to all outbound SAML clients, including optional-MFA accounts, with no account-switch exception. Route/page regressions are in apps/web/src/app/api/v1/sso/routes.test.ts; SQL binding and invalidation coverage is in supabase/tests/sso-persistence.sql. Before approval and after signing, the adapter revalidates the provider cookie’s account, fresh Auth email and server-owned recovery policy. It reuses checkRequiredAccountMfa, verified claims, bindCurrentMfaFactor and the existing primary-authentication policy. Optional-MFA accounts still need a current factor-bound TOTP proof at most ten minutes old. Refresh iat is not MFA evidence. ForceAuthn additionally requires primary authentication and MFA after the SP request. The consent page links to the existing login/MFA flow with a local return path. For an already authenticated account needing fresh MFA it reuses the existing required-MFA enrollment surface and Supabase challenge/verify service; an explicit sign-in-again action supplies ForceAuthn/recovery primary login. Current MEMBER status and explicit assignment are checked in both portable policy and transactional RPCs. Names must be explicit given_name and family_name profile fields; the adapter does not split display names. Only fresh confirmed Auth email is shared. Names confer no access. Phase-2 random 64-character hex subjects are accepted as pairwise persistent NameID and id; earlier UUID protocol fixtures remain supported. Every admitted decision records immutable per-login consent or a browser-bound rejection. Consent and consumption retain phase-2 atomic auditing. Rejected decisions can burn only an actor-unbound pending transaction; a losing concurrent decision cannot cancel another decision’s committed consent. After consume, failures append issuance.failed through the audit RPC. The new sso_finalize_issuance locks and rechecks the client, MEMBER, assignment, active key revision, expiry and five-second issuance window, then invokes the same append-only audit RPC for issuance.signed. Finalization cannot be replayed. No response is emitted on audit/finalization failure, disable or elapsed budget. After the finalization RPC, the service checks the verified final principal’s MFA age again before releasing the signed response. The inclusive ten-minute cutoff also covers RPC transit time; stale assurance burns issuance and requires SP restart after reauthentication. packages/sso/src/__tests__/service.test.ts covers finalization crossing that cutoff within the five-second budget and a valid boundary control. Unknown outcomes are never retried; restart at the SP. Invalid requests without a validated transaction have no client/actor audit attribution. The adapter signs assertion and response, then returns an auto-submitting form to the exact stored ACS, with a localized submit fallback. Its CSP permits only that form destination and a nonce-bound script. It uses no external assets and sets no-store, no-referrer and framing denial. Consent pages also deny caching and framing. The finalized permit has a bounded emission window; it cannot revoke an assertion or Claude session already delivered. The existing Redis limiter is used with fail-closed behavior: 20 starts/minute per IP/client, 10 decisions/minute per account/client, and 100 starts or decisions/minute per client. Metadata is limited to 20 reads per IP/client/minute. Deployment must sanitize the forwarded IP header. The per-client ceiling applies independently of IP attribution.

Server configuration

These variables are server-only. Never use NEXT_PUBLIC_ prefixes, print secret values, store private keys in the database, or reuse internal session signing keys. Existing server Supabase configuration supplies Auth and service-only RPC access. sso_issuance_snapshot, sso_finalize_issuance and sso_reject_transaction grant no direct table privileges or browser execution rights. Their key projection contains public certificates only.

Runbook for a later pilot

  1. Keep server flag and client disabled. Require exact-commit Web build, lint, type-check, protocol/route and database-contract CI. Apply migrations through authorized staging/production workflows and verify their separate results; never manually push schema changes.
  2. Obtain separate authorization for one nonpersonal workspace, named MEMBERs, company domains and Claude parent connection. Confirm the actual WorkOS entity ID, ACS, request-signature mode, NameID policy and attribute mapping. Keep Claude enforcement/JIT off and preserve an Owner recovery path.
  3. Through the trusted operator boundary, provision a dedicated RSA secret, install only its public certificate/current revision in key metadata, and configure the independent transaction secret and limiter. Key management UI remains a later phase; this PR provides no provisioning bypass or enabled client. Verify names, email, assignment and current MFA for each invited user.
  4. Enable only the authorized pilot configuration after these gates. Fetch metadata from the canonical host and verify issuer, endpoint and certificate fingerprint. Upload it in Claude’s actual setup portal. Run Test SSO and normal sign-in, then denial, stale/removed MFA, unassigned/guest/removed-member, expired/replayed request and disable cases. Retain private redacted correlation evidence; do not publish raw assertions.
  5. To stop issuance, set SSO_SAML_ENABLED off and disable the client through the revision-checked management boundary. Confirm new starts/decisions deny. Retain consent and audit history. Handle existing Claude sessions through Claude’s own controls; Tuturuuu logout is not SLO.
  6. For rotation or compromise recovery, disable issuance, replace the secret and active public-key metadata with a new revision, update SP trust, and rerun real acceptance before enabling. Overlapping metadata certificates/seamless rotation require later qualification; this adapter publishes one active key.

Regression evidence and remaining gates

packages/sso/src/__tests__/policy.test.ts and service.test.ts exercise actual portable policy/orchestration, including a response consumed by the phase-1 Node-SAML SP. apps/web/src/app/api/v1/sso/routes.test.ts calls real route exports, parser, policy, encrypted cookies and signer, with mocked Supabase Auth/RPC and limiter transport. rate-limit-sso.test.ts covers unavailable limiter storage. The applied-schema pgTAP fixture covers the service-only snapshot, finalization and rejection contracts and retains the real consume/revocation races. These fixtures do not establish hosted Auth/cookies/PostgREST or Claude behavior. Browser accessibility/layout, actual login/MFA return, hosted custody, rotation and real WorkOS acceptance remain pilot gates.

Workspace administration (phase 4)

Open Single sign-on in the workspace navigation, or follow its link from workspace settings (/{locale}/{wsId}/sso). This is outbound SSO application management, separate from incoming enterprise sign-in. Only current MEMBERs of an active nonpersonal workspace with manage_sso_clients can open it. The same permission and MEMBER checks apply to every management API and service RPC.
  1. Select Add SSO application. Give it the Claude organization name, the exact SP entity ID and canonical HTTPS ACS from that WorkOS connection, and comma-separated lowercase approved email domains. The current pilot supports one exact ACS and persistent pairwise NameID. Choose the actual request-signing policy explicitly; required signatures need the SP’s RSA public certificate. Unsigned requests are a deliberate configuration choice. No remote metadata or certificate URL is fetched.
  2. Complete current factor-bound TOTP verification when prompted. All trust, enable/disable and assignment writes require a verified proof no older than ten minutes, including optional-MFA accounts. Verification does not replay a failed mutation: submit again after checking its current state.
  3. Save the application. Creation is always disabled. Saving edited trust also disables the application in the UI; review and enable it as a separate action. Legacy applications retain the deployment-pinned request-signature policy until saved with an explicit policy. They can always be disabled without resubmitting trust settings. Revisions prevent stale edits from overwriting concurrent administrator changes. On a conflict or unknown result, refresh before making another change; mutations are never retried automatically. While editing, Refresh explicitly discards unsaved edits, reloads the latest revision and trust fields, and confirms that values were reloaded. Ordinary background refreshes preserve editor values. Both ordinary editor refresh and conflict-refresh-save regressions in sso-management.test.tsx verify the next intentional save uses the refreshed revision and trust values.
  4. Select the application and assign named test MEMBERs. Guests and invitations do not appear. The assignment RPC rechecks current membership atomically; stale roster entries cannot assign a demoted member. Revocation prevents future issuance but does not end existing Claude sessions, invite a user to Claude, purchase seats or change Claude roles.
  5. Copy the IdP entity ID, SSO URL and active public certificate into the Claude custom SAML provider setup, or use its metadata URL if the portal supports import. Setup URLs come only from SSO_SAML_ORIGIN, never the request Host. A missing canonical origin is shown explicitly. The deployment-selected client, global flag and provisioned active key remain separate requirements; metadata itself remains unavailable while the global/client gate is off.
  6. After separately authorized pilot verification, select Enable and confirm in the application dialog. The UI shows the current server-side SSO_SAML_ENABLED state and has no control that can change it. A client enabled while the flag is off remains inert. The phase-3 deployment still selects one client through SSO_SAML_CLIENT_ID; other configured clients cannot issue.
The public-key panel shows kid, status, public certificate, validity and creation, activation, retirement and revocation timestamps. It offers no private-key import, creation or rotation control. Dedicated private-key provisioning and SP trust rotation remain trusted operator operations. The latest 50 audit events expose only event id/type, policy revision and time, excluding raw assertions, email, actor/session/transaction identifiers and private material. A prepared signed response is not a successful Claude-login receipt.

Management transport and regression boundaries

@tuturuuu/internal-api/sso owns the typed browser transport; the Web UI uses TanStack Query with workspace/client query keys and no automatic write retries. All new handlers live in apps/web/src/app/api/v1/workspaces/[wsId]/sso/: The additive migration keeps private table access revoked. New read projections and trust/activation writes are service-only definers with an empty search path, canonical workspace/client predicates and the phase-2 manager assertion. The trust writer composes the existing client RPC in one transaction so policy revision, SP settings and audit either all commit or all roll back. New clients persist their signature policy; issuance uses it, while unchanged legacy profiles retain the deployment setting as a compatibility boundary. Server configuration still needs the phase-3 deployment variables above. management.test.ts calls the real HTTP exports against mocked Auth/RPC transport for unauthenticated, non-manager, guest and foreign-workspace denial, confirmation, MFA age, exact ACS validation and sanitized disclosure. Guest mutation authority is independently covered in the applied-schema sso-persistence.sql fixture. sso-management.test.tsx drives creation, disabled trust edits, confirmation, assignment/revocation and public copy controls using the shared dialog components. packages/internal-api/src/sso.test.ts verifies the actual transport contract. These checks do not establish hosted Auth/PostgREST, browser layout, production configuration or real Claude/WorkOS acceptance; those remain pilot gates.