Revocation bounds
5. Database access and RLS
Today 452 migration files useauth.uid() in RLS policies, and 103 foreign
keys reference auth.users. RLS must keep working without any browser holding
a Supabase token.
Trusted data adapter
The trusted data adapter is the only code that holds an upstream token (option A) or the claims-bound database login (option C). It runs in the Web server and the session service. Satellites and mounts reach data through@tuturuuu/internal-api on Web. Before P2 removes the legacy cookie, a
satellite that builds its own server Supabase client from that cookie must
move to internal-api.
Option C requirements
- Connection. A dedicated Hyperdrive binding with caching disabled, used
only by the adapter. Every user query runs inside one explicit transaction on
one checked-out client:
BEGIN,SET LOCAL ROLE, the claim settings, the queries, thenCOMMITorROLLBACK. - Login role.
ttr_requestowns no objects, has no table privileges and noBYPASSRLS. On PostgreSQL 16 and later it is granted membership withGRANT authenticated TO ttr_request WITH INHERIT FALSE, SET TRUE, ADMIN FALSE, and the same foranon. An audit checksPUBLICgrants, transitive memberships, ownership and definerEXECUTEgrants. Because it can assumeauthenticatedwith any claims, its credential can impersonate any user; it lives only in the adapter’s secrets. - Claims. The adapter accepts a fixed role allowlist (
authenticated,anon) and builds claims from a verifiedPrincipalthrough one server-owned map, with parameterizedset_config(..., true)calls. It sets bothrequest.jwt.claimsand every legacyrequest.jwt.claim.<name>setting PostgREST sets, because some definer helpers readrequest.jwt.claim.rolebefore the JSON claims. - Inventory before enabling. List every function, policy and view that
reads
current_user,session_user,request.jwt.claim*,auth.jwt(),auth.role(), orauth.userscolumns such as email confirmation and MFA state. Inside aSECURITY DEFINERfunctioncurrent_useris the owner, so those checks need their own review. - Parity tests. The same fixtures run through PostgREST and through the adapter with identical results: rollback, a reused pooled connection, wrong tenant, wrong role, API-key and external-app scope, unconfirmed email and required MFA.
6. Migration plan
P0: HttpOnly Supabase cookie
The HttpOnly session cookie plan: browser Supabase clients retired, token-returning routes closed, and the Stage A cookieHttpOnly. Its server-only browser auth routes keep one module
per flow with the Supabase calls behind it, and each module becomes a Supabase
adapter step in P1.
- Cookie migration: the versioned-cookie gate on that page is met by P1
with
__Host-ttr_sessionin dual-run, not a second Supabase cookie. - Identity hook: browser identity reads use
useCurrentUserIdentity(packages/ui/src/hooks/use-current-user-identity.ts), a TanStack Query over the same-origin profile route. P2 changes only that route’s server side. - Rollback and data: as defined on that page.
P1: first-party session wrapping Supabase, dual-run
- Ship the portable core, the Durable Objects, the token service and the Supabase adapter.
- Grant ownership. While
TTR_SESSION_WRITER=dual, the legacy cookie’s writer is the only owner of the Supabase grant. The first-party session holds no grant and records only the linked Supabasesession_id. Readers use first-party identity; the data adapter still takes the access token from the legacy cookie. - Issuance. Each sign-in also issues
__Host-ttr_session. A signed-in browser without one gets one on its next request with a valid Supabase session, unless that Supabasesession_idis on the device’s revoked list or the device is fenced. - Shared revocation fence. Revoking a first-party session also signs out
its linked Supabase session and records that
session_id, so lazy issuance cannot restore access from the legacy cookie. - Shadow. Readers in
shadowresolve both and serve the Supabase result, logging mismatches by ID. An app moves tofirst-partyafter 72 hours without mismatches on staging, then on production, and only with trusted ingress. - Rollback: readers to
supabase. The legacy cookie stays valid throughout P1, so nobody is signed out. - Data: new Durable Objects and two additive Postgres tables
(
private.session_events,private.user_session_directory). No user data moves.
P2: every app on the shared helper
- Every app resolves identity through
@tuturuuu/session.getSatelliteAppSessionUser,getCurrentUserand serversupabase.auth.getUser()calls become wrappers overgetPrincipal(), then are removed. Abun validateguard blocks new direct provider calls outside the session service. - Credential families move as described on Tuturuuu session. Each existing endpoint stays as a compatibility shim for one mobile release cycle.
- Grant handover. With
TTR_SESSION_WRITER=first-party, a request carrying both cookies moves the Supabase grant into the device object and deletes the legacy cookie in the same response. From then on the device object is the only refresh owner. - Rollback: writer back to
dualre-emits the legacy cookie from the stored grant on the next request and returns grant ownership to it. A device created after the handover gets its legacy cookie the same way. Upstream access tokens already issued expire on the provider’s lifetime. - Data: none.
P3: Better Auth adapter, parallel then cut over
- Provisioning. Add a transactional
private.provision_userfunction that creates the profile and private-details rows theauth.userstriggers create today. Better Auth signups use it. Supabase signups keep the triggers. A unique constraint on the user ID makes a double provision fail. - Backfill. Copy identities, MFA factors and passkey credentials into Better Auth with the same UUIDs. Read each passkey’s RP ID and origin from its actual registration rather than assuming one, and prove passkey and TOTP import with fixtures. Passwords keep their bcrypt hash; the adapter verifies bcrypt and rehashes with a version-checked update after a successful verification.
- One credential authority per cohort. Each user has one authority,
Supabase or Better Auth, chosen per cohort by
userIdhash. A Better Auth rejection falls back to Supabase only forunprovisionedaccounts, under the same MFA, lockout and recovery policy. - Databases move from option A to option C before the cutover, because Better Auth has no Supabase access token.
- Rollback. Move the cohort’s authority back to Supabase. First-party sessions stay valid either way. A password changed under Better Auth is also set in Supabase through the admin API at change time, so it survives rollback. Passkeys and MFA factors created under Better Auth cannot be written back; rollback signs those users in with their remaining factors and asks them to enroll again. The set of affected users is recorded per change.
- Data: a repeatable backfill with a verifier that compares counts and hashes per user.
P4: Supabase Auth retired
- Inventory the effective staging catalog: every foreign key on
auth.userswith its referential action, and every trigger, routine, view and policy that readsauth.*. - Migrate the lifecycle. Signup, email change, MFA state and account
erasure move to
publicandprivatetables with explicit transaction and reconciliation rules. - Repoint foreign keys to
public.users(id)with the same referential actions, addedNOT VALIDand then validated. IDs do not change. auth.uid()keeps working under option C because it reads the request claims.- Retire. Disable Supabase sign-ups and sign-ins, sign out every upstream Supabase session, and remove the adapter and its secrets.
- Last reversible point: before Supabase sign-in is disabled. After that point, rollback means re-enabling Supabase Auth, and users who created or changed credentials since the P3 cutover need account recovery.
- Data: every migration needs an exact-SQL security review, a full local reset and the gated production workflow.
7. Threat model and abuse controls
IP identity
The client address is only the edge-setcf-connecting-ip on the public
request, read by the gateway as described in
Gateway Worker. Client-sent X-Forwarded-For,
X-Real-IP and True-Client-IP are ignored. A downstream Worker never trusts
its own cf-connecting-ip, because same-zone subrequests change it. Mounts
receive only the optional ipp prefix inside the assertion. An unknown address
leaves ipp unset and falls into a conservative shared rate-limit bucket. IP
is used for rate limits, audit and device display, never as authentication.
IPv6 limits aggregate by /64.
Cost bounds and stop fence
- Per request: at most one Durable Object request on a cache miss, plus one when the device’s cached epoch is older than 30 seconds. None for a request with no cookie or a failed MAC.
- Writes:
lastSeenAtat most every 5 minutes per session. Each user has at most 50 devices; adding one beyond that evicts the longest-idle device. - Background work: revoke-all fan-out runs at most 8 device requests at a time. Queue events retry at most 5 times within 24 hours, then go to a dead-letter queue. Every alarm and Queue consumer checks the stop fence first.
- Stop fence.
SessionControlstores the state durably, so it survives restarts. Auth Worker isolates read it with a 10-second cache, and the gateway never reads it, so a change takes effect within 15 seconds; a test proves that bound.issuance_stoppedblocks new sessions, refreshes, token issuance and background work. Existing sessions keep resolving.stoppedalso blocks resolution. In P1 readers fall back to the legacy cookie. From P2, when no legacy fallback exists, users see a “sign-in unavailable” page.
- Rollback is separate. The reader and writer flags roll back. The fence stops spend and issuance.
- The service-specific cost evidence goes in the Cloudflare adoption guidance before P1 enables any write.
Design gates
These requirements must be specified, reviewed and tested before the slice that introduces the behavior. None of them blocks the unwired portable core.First implementation slice
Slice 1 is the unwired portable core inpackages/session:
- the cookie codec, with MAC verification through an injected key;
- the expiry policy;
- the
Principal,VerifiedAssertionand provider interface types; verifyIdentityAssertionwith the profile on Tuturuuu session.
- a wrong issuer, environment, audience, type, algorithm, curve or key;
- an unknown
kid, an unavailable key source, or forbidden header members; - malformed, oversized, non-canonical or duplicate-member input;
exp <= iat, a lifetime over 60 seconds, a futureiator anauth_timeafteriat;- ambiguous and non-canonical cookies, and exact expiry boundaries.
Open questions for review
- Whether subdomain child sessions are worth building, or whether each subdomain app should wait for its apex mount and redirect.
- The exact cohort sizes and duration for the P3 parallel run.
- Whether
ttr+accessat 5 minutes is acceptable for mobile battery and network cost, or needs a longer lifetime with live checks on sensitive resources.