packages/session over injected storage ports; the auth Worker in slice 4 hosts it. It is one of
the Tuturuuu session slices.
Entry point @tuturuuu/session/device. A pure reducer over injected ports,
so the Durable Object host in slice 4 stays thin.
State and ports
Entropy and compared as hashes with
constantTimeEqual. SessionRecord is the parent page’s session record,
whose epochSeen sign_in sets. StepUpGrant is
{ id, sid, gen, act, ph, expiresAtMs, consumedBy?: string }, with ph from
slice 2b’s paramsHash; there is no second canonicalization. An EpochRead
whose userId differs from the session it is checked against is rejected as
invalid_operation.
Effect registry
A registry, owned by each app’s integration and validated at build time, maps everyRouteId to a declaration:
auth.ai_token.mint and
auth.handoff.mint, as { class: 'credential', accountScoped: true } with no
step-up. An issuer mints only after resolving one of those route ids, so a
stale tab without the expected account cannot receive a credential for
whichever account is active.
The class is independent of HTTP method, GET and upgrades. An unknown route
is treated as { class: 'security', accountScoped: true } and never takes a
step-up. A route is account-sensitive when accountScoped is true. For a
step-up route, tenantParams names the workspace and target fields the
parameters hash must cover; the host builds the parameters from the request
with those fields present, so a missing tenant field fails before hashing.
GrantAct is a closed union covering the parent page’s step-up actions.
Each act names the parameters its hash must cover, and the registry rejects a
step-up route whose tenantParams omit any of them:
Every act also hashes its own name through
paramsHash, so a grant confirmed
for one act never matches another, even with equal parameters. Adding a value
is a reviewed change to this union.
Resolve
resolve(state, { secretHash, route, expectedSessionId, epoch, nowMs }) is a
pure read. It never records an operation and never bumps version; the host
calls touch for lastSeenAt at most once every 5 minutes per session.
- The current secret resolves for every route. The grace secret resolves
only for
readroutes, withstale: true; any other route getsrotated. - A session with
revokedAtset, or past its idle or absolute expiry, resolves assigned_outbefore any epoch check. A child session also resolves assigned_outwhen its parent row is revoked or expired. - A
readroute may useepochCachefor the session’s user when it is at most 30 seconds old. Every other route, and areadroute whose cache is older, needs afreshEpochRead, andstaleorunavailablethen fails closed withepoch_unavailable. A fresh read refreshes the cache throughrefreshEpochCache, outside the device version, so a cache refresh never supersedes a rendered fence. - A session whose
epochSeenis below the epoch used resolves assigned_out, and the host commits its revocation.
Mutations
Every mutation carries anoperationId, an idempotency key from the caller,
and every fenced mutation carries the fence its page was rendered under:
fence: null is accepted only for a sign_in from a request with no device
cookie and a revoke of the caller’s own session (logout); any other null
fence is invalid_operation. redeem_child is a server-to-server call from
the handoff redemption, authenticated by the host and bound to the code’s
stored parent triple instead of a fence; a moved parent generation or epoch
fails it. Logout, revoke_user_below_epoch and
revoke_user_on_device take no fresh epoch, so they still run while
UserSessions is unavailable. The three system mutations come from
UserSessions or the host and are authenticated by it.
Epoch cache merge. Every writer of the cache uses one rule inside one
storage transaction: an entry is replaced only when the new epoch is higher,
or equal with a newer readAtMs. Versioned commits never assign the cache
from a snapshot; they return epochRaises, which write merges under that
rule in the same transaction as the compare-and-set. refreshEpochCache
accepts only status: 'fresh' with readAtMs at most 5 seconds before
nowMs. revoke_user_below_epoch raises that user’s entry to belowEpoch
with readAtMs set to the bump’s own time, bumpedAtMs from UserSessions,
never the delivery time, so a reached device stops resolving the revoked
sessions at once, a delayed lower fan-out cannot roll the cache back, and a
late intermediate fan-out cannot look freshly read and suppress the re-read
that would learn a newer epoch. Logout and
revoke_user_on_device never raise it. A crash mid-merge leaves the older
entry, which ages out within the 30-second bound. Because the cache is
outside DeviceState, a fan-out none of whose writes returned committed
succeeds only when the final read shows its revocation and a cache read shows
the user’s entry at or above belowEpoch; otherwise it is unavailable and
UserSessions retries it.
Device revoke by slot. Each session stores the reservationId of the
index slot it was admitted under. revoke_user_on_device names the evicted
slot’s reservationId and revokes only that user’s sessions admitted under
it, so a redelivery never revokes a session from a later sign-in, whatever
the two clocks say.
Commit rule
The request hash is SHA-256 over the UTF-8 bytes ofcanonicalJson of the
mutation without operationId and nowMs, with byte arrays as canonical
base64url strings.
- Read. If
operations[operationId]exists, an equal request hash returns the stored result and re-emits its stored effects without a second transition; a different hash returnsidempotency_mismatch. IfexpiredOperations[operationId]exists, returnexpired_idempotencywithout reducing. - Fence. For a fenced mutation, any difference in
sessionId,genorversionreturnssuperseded. The reducer never recomputes a fenced write against newer state. - Reduce. Compute the next state, its result and its effects (cookie to
emit, audit events, upstream revocations, index confirmations, epoch
fan-out, tab invalidation), record the mutation with its effects, move
expired records into
expiredOperationsand dropexpiredOperationsentries older than 7 days, all in this one write, with compare-and-set on the version read. - Unconfirmed write. On
conflictorunknown, read again and go to step 1, so a write that committed but lost its acknowledgement returns its stored result and effects. A fenced mutation then returnssupersededat step 2 if the state moved. An unfenced mutation reduces again against the new state. After three attempts, read once more and apply step 1; only when that read shows no record is the resultunavailable, with nothing emitted. - Effects run only from a committed record, at step 1 or after step 3.
Every effect is idempotent on
operationId, so re-emission is safe.
operationId, never return
idempotency_mismatch, and never move or evict a record. In the same
transaction that sets revokedAt, the reducer also sets revokedAt on every
child session of each revoked session, so resolve never serves a child of a
revoked parent, and gives each revoked session one RevocationOutbox row,
outside both caps. The row holds the device gen at revocation, the upstream
grant (moved off the session row) and a state per effect. A child’s upstream
grant belongs to its parent, so a child’s row has none and its upstream
effect starts acked.
Session-bound credentials. AI temporary tokens and handoff codes are bound
to the sid that minted them, and the device keeps no list of their ids.
- An issuer mints only after resolving the request’s current device secret through its declared mint route. That resolution refuses the grace secret and any revoked or expired session, so the previous cookie cannot mint during the 30-second rotation window.
-
Issuer contract. A
SessionCredentialIssuerport, implemented by each credential store, provides:- a
sidon every credential and an index bysid; mint(sid, resolvedAtMs, credential), one atomic conditional write under a per-sidlock that commits only under the full predicate below, never a read followed by a separate write.resolvedAtMsis the device clock’snowMsof the authorizing resolution, copied unchanged by the device host; the issuer never substitutes its own clock. Inside the lock the write commits only when no tombstone exists for thatsid,resolvedAtMs >= watermark(a missing watermark does not restrict), andresolvedAtMsis no more than 30 seconds behind and no more than 5 seconds ahead of the issuer’s clock. Each stored credential keeps itsresolvedAtMs;revokeForSession(sid), which under the same lock inserts the tombstone and revokes every credential for thatsid; an existing tombstone is success;- validation that rejects a credential whose
sidhas a tombstone.
- a
-
Issuer registry.
IssuerIdis a closed union from a build-time registry of the same shape as the route registry:ai_tokenandhandoff_code. Every outbox row initializes every registered issuer topending; a key that is missing counts as pending and blocks prune, so one issuer’s success never retires another’s revocation. - Resolve-to-commit bound. The 30-second bound is part of the locked predicate above, never a check made before the lock, so the tombstone lifetime of at least 300 seconds always covers a late commit.
-
Credential changes. A password change, MFA reset, or MFA or passkey
removal keeps the acting session, so it also calls each issuer’s
revokeForSessionBefore(sid, changedAt)for that session, withchangedAtfrom the device clock. Under the same per-sidlock it raises thesid’s watermark tochangedAt(never lowering it) and revokes every stored credential whoseresolvedAtMsis beforechangedAt. A mint authorized before the change therefore fails at commit, whenever it lands, and a mint authorized after it succeeds. The watermark lives at least the 30-second resolve-to-commit bound plus the issuer’s longest credential lifetime. This revoke is acredentialseffect on its own outbox row, keyed<sid>:change:<changedAt>so it never collides with a later revocation of the same session. That row carries norevokedAtand no tombstone, has a null upstream grant, and starts itsupstreamandcookieeffectsacked, so the drain never signs the acting session out upstream. The drain retries only itscredentialseffects, and acknowledges one only after that issuer’s watermark raise and revoke scan have committed. The row prunes once nocredentialseffect is pending, countingabandonedas not pending. -
Current stores. The existing AI temporary token store and
private.cross_app_tokenscarry nosid, mint with a read followed by a separate write, and revoke handoff codes only for the calling user. They do not meet the issuer contract, and this design has no fallback for them: the first-party session never mints or revokes through a store that does not meet it. The slice that wires each store first moves it onto the contract (asidcolumn and index, the locked conditional mint, a tombstone, and a service revoke that needs no user context). Until then the existing session path keeps today’s behavior unchanged. -
Child sessions. A
redeem_childmutation creates a child session only in the same compare-and-set that sees its parent live, andresolveof a child returnssigned_outwhenever its parent row is revoked or expired, so a redemption racing the parent’s revocation can never serve a child.- The handoff code freezes the parent’s
sid,genand epoch from the authorizing resolution, never from the time of the commit. The redemption reads that stored triple in the same transaction that consumes the code and passes it;redeem_childrejects unless it equals the live parent’ssidandgenand the fresh epoch. A code minted before a rotation or a credential change therefore fails, and the host can never substitute the current generation. ChildSessionInputis{ host, callback, kind: 'child' }. The reducer sets the child’s idle and absolute deadlines to the minimum of the parent’s and the child policy’s, caps the child cookie’sMax-Agethere, andtouchnever moves a child deadline past its parent’s.- A child is live when it is neither revoked nor expired. A parent holds at
most 8 live children and at most 32 retained child rows; a
redeem_childpast either ceiling returnsrate_limited. Expired child rows are pruned on the drain alarm without waiting for a revoke, and revoked ones prune under the session rule below.
- The handoff code freezes the parent’s
-
The cookie effect needs a browser response, so the alarm never emits or
counts it. It stays pending and rides the next response to this device,
and for a logout that is the logout response itself. At that emit it is
checked against the row’s
gen: if the device’sgenhas moved on, it becomessupersededand the current cookie is left alone; otherwise it emitsMax-Age=0only when the device has no live session, and the current session’s cookie when it does. A cookie that is never delivered restores nothing, becauseresolvealready returnssigned_outfromrevokedAt. -
The outbox is the committed record for these three. After an
unknownwrite, the host re-reads. If the session showsrevokedAt, it emits every pending effect and returns success. If it does not, the host retries, and when the last read still shows norevokedAtthe result isunavailablewith nothing emitted, so a lost write is never reported as a completed logout. - A replay of an already revoked session reduces to no change and emits only pending effects; once none is pending it emits nothing.
-
Credential revocation is scoped to the revoked
sid, so a replay never touches credentials a newer session minted. -
Drain. A device alarm retries each pending
upstreamandcredentialseffect on its own attempt count, after 1 minute, 15 minutes, 1 hour, 6 hours and 24 hours, the parent design’s dead-letter bound. After the fifth failure it raises an alert and marks only that effectabandoned, which is terminal: no replay emits it again. The first-party revocation is never undone. The same alarm deletesrevokedReservationsentries older than 30 days. -
A session row and its outbox are pruned together, once neither
upstreamnorcredentialsis pending and at least 7 days afterrevokedAt, so every row is pruned within 7 days plus the drain bound. A cookie still pending at prune time is dropped; it restores nothing. Rows are bounded by sessions, whichsign_in(under its caps) andredeem_child(32 retained rows per parent) create.
expiredOperations keeps their ids 7 days, so a
late replay fails instead of reducing again. Each attempt first moves records
older than 24 hours and drops ids older than 7 days, then applies the caps:
at most 256 records and 4,096 expired ids.
- Security records (
sign_in,redeem_child,record_factors,grant_step_up,consume_step_up) are never moved before 24 hours and their ids are never dropped before 7 days. - Fenced-only records (
switch,rotate) may move early intoexpiredOperationswhen records are full, and their ids may be dropped early when ids are full. A replay of a dropped one fails its fence, because the device’s version has moved past it, and returnssuperseded. - When neither cap can make room under those rules, the mutation returns
rate_limited. Logout and the two system revokes are never rate limited, because they need no record.
operationStatus(state, operationId) is a pure read returning succeeded,
rejected (a stored result that changed no session, such as
credentials_changed), expired or absent, used by the index lease below.
Generations and epochs
sign_in,switch,record_factorsandgrant_step_upeach bumpgen, replace the secret, cleargraceand emitSet-Cookiefor the new generation in the same commit.rotatedoes the same but keeps the previous secret ingracefor 30 seconds.sign_insets the new session’sepochSeentoepoch.epochand storesreservation.reservationIdon it.- Every mutation that takes an
EpochReadrequires itfreshfor the user of the session it acts on, fails closed withepoch_unavailableotherwise, and refuses, revoking in the same commit, any session it acts on or activates whoseepochSeen < epoch.epoch. A fresh read also returns an epoch raise, merged in that commit. grant_step_up,consume_step_upandrecord_factorstake the act’s raw parameters and never a hash. The reducer validates them against the act table, sorts the fields the table marks sorted, rejects duplicates and missing fields, and computesparamsHash(act, params)itself, so a host cannot spend a grant on other parameters by echoing its hash.record_factorsderives the session’s nextfactorsfrom the act: enrollment adds the named factor or passkey with its role (account.mfa.enrolladds asecond_factor,account.passkey.enrollasign_inpasskey); removal requires every listed id to be in the session’s factors and removes exactly those; password change leavesfactorsunchanged.- A
FreshFactorsvalue is accepted only when itsuserIdequals the session’s user and itsreadAtMsis at most 5 seconds beforenowMs; otherwise the mutation isinvalid_operation, the same rule as anEpochRead.unavailablefails the mutation closed. account.mfa.resetrequires aFreshFactorsread;nullorunavailablefails it. Reset covers second factors only: the listedfactorIdsmust equal that read’ssecond_factorids exactly, so a second factor enrolled on any device after confirmation fails the reset, and one already removed elsewhere does not block it. The commit keeps exactly the session’s ownsign_infactors, whateversign_inpasskeys the read lists, so a reset never adds or drops one; onlyaccount.passkey.removeremoves them.sign_inrequires aFreshFactorsread. It rejects the sign-in whenoutcome.amrnamestotporpasskeyand the read has no factor of that method. When the read has anysecond_factor, the sign-in must carry eithertotpinoutcome.amrwhile atotpsecond factor is enrolled, orpasskeyinoutcome.amrwithoutcome.passkeyUserVerified === true(passkey user verification, which the parent design accepts in place of a password plus a second factor), whatever the outcome’saallabel. A passkey without that result never satisfies an enrolled second factor, even when that factor is itself a passkey.passkeyUserVerifiedis a field the provider adapter’sAuthOutcomegains in the slice that wires sign-in. A user whose only factors aresign_inpasskeys needs nothing beyond the passkey inamr. It stores the read as the session’sfactors, and whether the sign-in met that second-factor rule assecondFactorSatisfied. The flag is true only when the sign-in actually presentedtotpor a user-verifiedpasskey, never because no second factor was required.record_factorsnever sets the flag true. It sets it false only when the previous set had nosecond_factorand this act adds one; every other act leaves it unchanged.record_factorswith acredentialChangerequirescredentialChange.newEpoch === epoch.epoch > session.epochSeen, sets this session’sepochSeento it, and exempts this session from the below-epoch check in the same commit. The credential changes are the acts marked “Yes” in the act table: MFA and passkey removal, MFA reset and password change.record_factorsacceptscredentialChangeonly for those acts and refuses it for enrollment.- Account deletion, an admin “compromised” action and
sessions.revoke_allare revoke-all:UserSessionsbumps the epoch and fans out to every device including this one, with noepochSeenexemption.
Gate design
Tests
- Property tests over random interleavings of every mutation and
resolve, with a store fake that injectsconflict,unknownafter a committed write on any attempt including the last, and lost effect acknowledgements, assert:- at most one current generation per device, and a grace secret only after
rotate; - no fenced mutation commits against a state whose fence differs;
- a committed mutation whose acknowledgement was lost returns its stored
result and emits its effects, and is never reported
unavailable; resolvenever changesversionor the record maps;- no session with
epochSeen >= belowEpochis revoked by an epoch fan-out, and no session withepochSeenbelow a fresh epoch is activated, granted or consumed; - a grant is consumed at most once, only under its
sidandgen, and only for a route whose registryactmatches; - eviction never removes another user’s sessions, a failed sign-in never leaves its victim evicted unless another sign-in was admitted under the same slot, a provisional slot always has an unsettled claim, and a committed sign-in, including one that raced another sign-in of its user on the device, is always confirmed in the index with its victim evicted and never restored;
- replaying an
operationIdnever applies a second transition, before or after its record expires, and the record maps never exceed their caps.
- at most one current generation per device, and a grace secret only after
- Each mutation has negative cases for a wrong fence, a null fence where it
is not allowed, a missing expected account, a wrong account, the grace
secret on a write route, an unknown route, an expired or mismatched grant,
a grant used on a route with another
act, arecord_factorswithout a grant, a stale or unavailable epoch, anEpochReadfor another user, a reusedoperationIdwith a different body, and anevictingreservation.resolvehas cases for a cached epoch within and past 30 seconds during aUserSessionsoutage, a revoked or expired session with a young cache, and a reached device right afterrevoke_user_below_epoch. - Bounds tests fill the record maps and assert that logout and both system
revokes still commit without adding a record, that thousands of repeated
logouts leave the maps unchanged, that a committed
sign_instayssucceededthrough its lease, that security records survive underswitchandrotatechurn, that the epoch cache never lowers under a late lower fan-out or a concurrent versioned commit, that a redelivered device revoke spares a later sign-in (the evicted slot’s id revokes, an earlier or later id does not), that a lost acknowledgement on logout re-emits from the outbox and returns success, that a replayed logout after full acknowledgement emits nothing, that a host-echoedphwith other parameters fails, that reset fails after a new factor is enrolled, that a lease confirms only asucceededsign-in, and that acredentials_changedsign-in after a swap restores the evicted device. - Outbox tests: a provider outage on
revokeUpstreamis retried by the drain until success orabandoned; a logout replayed after a later sign-in leaves the new cookie alone; a system revoke’s cookie effect waits for the next response and never spends an attempt; one effect’s failures never abandon another; anabandonedeffect is never re-emitted; a child of a revoked parent never resolves; a session with no upstream grant and no minted credentials prunes after 7 days; a mint and arevokeForSessionracing under the per-sidlock never leave a live credential; a credential presented after itssidtombstone fails validation; one issuer’s ack leaves the other pending; a child redeemed while its parent is revoked never resolves; a code minted before the parent rotated fails; a ninth child is refused; a child cookie never outlives its parent; a late intermediate fan-out keeps its bump time; the grace secret cannot mint; an issuer that has not written itssidtombstone never acks thecredentialseffect; a credential minted for a newer session survives. - Factor tests: a lagging read is never used,
unavailablefails sign-in and reset, a password-only sign-in for a user with an enrolledtotpor MFA passkey is rejected whatever itsaallabel, a passkey sign-in without user verification is rejected for a user with an MFA passkey, enrolling a first second factor and then switching back to that saved session needs a fresh sign-in, a mint authorized before a credential change and committed after its revoke leaves nothing live while one authorized after it succeeds, eight expired children do not block a ninth handoff, a passkey sign-in for a passkey-only user is accepted, an offline device’s revoked row still prunes, a read for another user or older than 5 seconds is rejected, and a factor removed elsewhere does not block a reset. A late slot revoke after pruning returnsalready_revoked. - The reducer runs under the boundary test: no clock, random source or network access except through its ports.