Line data Source code
1 : /**
2 : * The session's authoritative state and its only commit boundary. Effects
3 : * come back in the order the client must run them: persist before arming
4 : * the scheduler, publish last, so a host reacting to a snapshot never reads
5 : * state a later step would still change.
6 : */
7 : import type {
8 : AccountCredential,
9 : AccountUser,
10 : SessionFailure
11 : } from './sessionContracts'
12 : import { isPermanentSessionError } from './sessionContracts'
13 :
14 : export interface SessionState<TUser extends AccountUser = AccountUser> {
15 : readonly user: TUser | null
16 : readonly identitySettled: boolean
17 : readonly credential: AccountCredential | undefined
18 : readonly credentialTarget: string | undefined
19 : readonly failure: SessionFailure | undefined
20 : /**
21 : * The result the winning mint published, so a caller joining that same mint
22 : * returns it instead of running the commit/publication path a second time.
23 : */
24 : readonly committedMint:
25 : | { readonly mintId: number; readonly session: AccountCredential }
26 : | undefined
27 : /**
28 : * Bumped on every identity event so a mint can tell "the listener has not
29 : * settled yet" (the legitimate popup path) from "an identity event
30 : * happened while I was in flight" (must invalidate).
31 : */
32 : readonly identityEpoch: number
33 : readonly invalidationEpoch: number
34 : /**
35 : * Monotonic id taken by every started mint; a commit is allowed only for
36 : * the newest one. Target-agnostic on purpose — a slower mint for the old
37 : * workspace resolving after a switch must never revert it. Ports the
38 : * cloud store's unifiedRefreshRequestId guard.
39 : */
40 : readonly mintSequence: number
41 : }
42 :
43 2355 : export function initialSessionState<
44 : TUser extends AccountUser = AccountUser
45 : >(): SessionState<TUser> {
46 2355 : return {
47 : user: null,
48 : identitySettled: false,
49 : credential: undefined,
50 : credentialTarget: undefined,
51 : failure: undefined,
52 : committedMint: undefined,
53 : identityEpoch: 0,
54 : invalidationEpoch: 0,
55 : mintSequence: 0
56 : }
57 : }
58 :
59 : export type SessionEvent<TUser extends AccountUser = AccountUser> =
60 : | { readonly type: 'identity-changed'; readonly user: TUser | null }
61 : | { readonly type: 'identity-detached' }
62 : | { readonly type: 'invalidated' }
63 : | { readonly type: 'mint-started' }
64 : | {
65 : readonly type: 'mint-committed'
66 : readonly origin: 'caller'
67 : readonly session: AccountCredential
68 : readonly target: string | undefined
69 : readonly mintId: number
70 : }
71 : | {
72 : readonly type: 'mint-committed'
73 : readonly origin: 'scheduler'
74 : readonly session: AccountCredential
75 : readonly mintId: number
76 : }
77 : | {
78 : readonly type: 'mint-rejected'
79 : readonly origin: 'caller'
80 : readonly failure: SessionFailure
81 : readonly preserveCredentialOnTransientFailure: boolean
82 : }
83 : | {
84 : readonly type: 'mint-rejected'
85 : readonly origin: 'scheduler'
86 : readonly failure: SessionFailure
87 : }
88 : | { readonly type: 'credential-adopted'; readonly session: AccountCredential }
89 : | {
90 : readonly type: 'credential-expired'
91 : readonly expiring: AccountCredential
92 : }
93 :
94 : export type SessionEffect =
95 : | {
96 : readonly type: 'persist'
97 : readonly session: AccountCredential
98 : readonly target: string | undefined
99 : }
100 : | { readonly type: 'armScheduler'; readonly session: AccountCredential }
101 : | { readonly type: 'clearStorage' }
102 : | { readonly type: 'stopScheduler' }
103 : | { readonly type: 'abandonInFlight' }
104 : | { readonly type: 'publish' }
105 :
106 : export interface SessionTransition<TUser extends AccountUser = AccountUser> {
107 : readonly state: SessionState<TUser>
108 : readonly effects: readonly SessionEffect[]
109 : }
110 :
111 2356 : const clearStorage: SessionEffect = { type: 'clearStorage' }
112 2356 : const stopScheduler: SessionEffect = { type: 'stopScheduler' }
113 2356 : const abandonInFlight: SessionEffect = { type: 'abandonInFlight' }
114 2356 : const publish: SessionEffect = { type: 'publish' }
115 :
116 : type EventOf<
117 : TUser extends AccountUser,
118 : TType extends SessionEvent<TUser>['type']
119 : > = Extract<SessionEvent<TUser>, { type: TType }>
120 :
121 4706 : function dropSession<TUser extends AccountUser>(
122 : state: SessionState<TUser>
123 : ): SessionState<TUser> {
124 4706 : return {
125 : ...state,
126 : credential: undefined,
127 : credentialTarget: undefined,
128 : failure: undefined
129 : }
130 : }
131 :
132 2356 : function applyIdentityChanged<TUser extends AccountUser>(
133 : state: SessionState<TUser>,
134 : event: EventOf<TUser, 'identity-changed'>
135 : ): SessionTransition<TUser> {
136 2356 : return {
137 : state: {
138 : ...dropSession(state),
139 : user: event.user,
140 : identitySettled: true,
141 : identityEpoch: state.identityEpoch + 1
142 : },
143 : // A sign-out or a different user makes the running mint unjoinable: it
144 : // was started with the previous identity's token, and a caller arriving
145 : // after the event must mint for itself. A same-uid re-auth must not
146 : // adopt it either.
147 : effects:
148 : event.user === null
149 : ? [stopScheduler, abandonInFlight, clearStorage, publish]
150 : : [stopScheduler, abandonInFlight, publish]
151 : }
152 : }
153 :
154 0 : function applyIdentityDetached<TUser extends AccountUser>(
155 : state: SessionState<TUser>
156 : ): SessionTransition<TUser> {
157 0 : return {
158 : state: {
159 : ...dropSession(state),
160 : user: null,
161 : identitySettled: false,
162 : identityEpoch: state.identityEpoch + 1
163 : },
164 : effects: [stopScheduler, publish]
165 : }
166 : }
167 :
168 2350 : function applyInvalidated<TUser extends AccountUser>(
169 : state: SessionState<TUser>
170 : ): SessionTransition<TUser> {
171 : // A mint still running belongs to the scope being discarded; a caller
172 : // arriving after this must start its own rather than join it.
173 2350 : return {
174 : state: {
175 : ...dropSession(state),
176 : invalidationEpoch: state.invalidationEpoch + 1
177 : },
178 : effects: [stopScheduler, abandonInFlight, clearStorage, publish]
179 : }
180 : }
181 :
182 0 : function applyMintStarted<TUser extends AccountUser>(
183 : state: SessionState<TUser>
184 : ): SessionTransition<TUser> {
185 0 : return {
186 : state: { ...state, mintSequence: state.mintSequence + 1 },
187 : effects: []
188 : }
189 : }
190 :
191 0 : function applyMintCommitted<TUser extends AccountUser>(
192 : state: SessionState<TUser>,
193 : event: EventOf<TUser, 'mint-committed'>
194 : ): SessionTransition<TUser> {
195 0 : const target =
196 : event.origin === 'caller' ? event.target : state.credentialTarget
197 0 : const persist: SessionEffect = {
198 : type: 'persist',
199 : session: event.session,
200 : target
201 : }
202 0 : return {
203 : state: {
204 : ...state,
205 : credential: event.session,
206 : credentialTarget: target,
207 : committedMint: { mintId: event.mintId, session: event.session },
208 : failure: undefined
209 : },
210 : effects:
211 : event.origin === 'caller'
212 : ? [persist, { type: 'armScheduler', session: event.session }, publish]
213 : : [persist, publish]
214 : }
215 : }
216 :
217 0 : function applySchedulerRejection<TUser extends AccountUser>(
218 : state: SessionState<TUser>,
219 : failure: SessionFailure
220 : ): SessionTransition<TUser> {
221 0 : return {
222 : state: { ...dropSession(state), failure },
223 : effects: [clearStorage, publish]
224 : }
225 : }
226 :
227 0 : function applyCallerRejection<TUser extends AccountUser>(
228 : state: SessionState<TUser>,
229 : event: EventOf<TUser, 'mint-rejected'> & { readonly origin: 'caller' }
230 : ): SessionTransition<TUser> {
231 0 : const permanent = isPermanentSessionError(event.failure.code)
232 0 : if (
233 : !permanent &&
234 : event.preserveCredentialOnTransientFailure &&
235 : state.credential !== undefined
236 : ) {
237 0 : return { state, effects: [] }
238 : }
239 0 : if (!permanent) {
240 0 : return {
241 : state: { ...state, credential: undefined, failure: event.failure },
242 : effects: [publish]
243 : }
244 : }
245 : // A caller-initiated permanent failure must retire the armed scheduler
246 : // and target too, or its old timer could resurrect the dead session.
247 0 : return {
248 : state: { ...dropSession(state), failure: event.failure },
249 : effects: [stopScheduler, clearStorage, publish]
250 : }
251 : }
252 :
253 0 : function applyMintRejected<TUser extends AccountUser>(
254 : state: SessionState<TUser>,
255 : event: EventOf<TUser, 'mint-rejected'>
256 : ): SessionTransition<TUser> {
257 0 : return event.origin === 'scheduler'
258 : ? applySchedulerRejection(state, event.failure)
259 : : applyCallerRejection(state, event)
260 : }
261 :
262 0 : function applyCredentialAdopted<TUser extends AccountUser>(
263 : state: SessionState<TUser>,
264 : event: EventOf<TUser, 'credential-adopted'>
265 : ): SessionTransition<TUser> {
266 : // Adoption is a commit: it supersedes any in-flight mint of this
267 : // tab's own, exactly like a newer mint would.
268 0 : return {
269 : state: {
270 : ...state,
271 : mintSequence: state.mintSequence + 1,
272 : credential: event.session,
273 : failure: undefined
274 : },
275 : effects: [
276 : {
277 : type: 'persist',
278 : session: event.session,
279 : target: state.credentialTarget
280 : },
281 : publish
282 : ]
283 : }
284 : }
285 :
286 0 : function applyCredentialExpired<TUser extends AccountUser>(
287 : state: SessionState<TUser>,
288 : event: EventOf<TUser, 'credential-expired'>
289 : ): SessionTransition<TUser> {
290 0 : if (state.credential !== event.expiring) return { state, effects: [] }
291 0 : return {
292 : state: {
293 : ...dropSession(state),
294 : failure: { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }
295 : },
296 : effects: [clearStorage, publish]
297 : }
298 : }
299 :
300 4706 : export function transition<TUser extends AccountUser>(
301 : state: SessionState<TUser>,
302 : event: SessionEvent<TUser>
303 : ): SessionTransition<TUser> {
304 4706 : switch (event.type) {
305 : case 'identity-changed':
306 2356 : return applyIdentityChanged(state, event)
307 : case 'identity-detached':
308 0 : return applyIdentityDetached(state)
309 : case 'invalidated':
310 2350 : return applyInvalidated(state)
311 : case 'mint-started':
312 0 : return applyMintStarted(state)
313 : case 'mint-committed':
314 0 : return applyMintCommitted(state, event)
315 : case 'mint-rejected':
316 0 : return applyMintRejected(state, event)
317 : case 'credential-adopted':
318 0 : return applyCredentialAdopted(state, event)
319 : case 'credential-expired':
320 0 : return applyCredentialExpired(state, event)
321 : }
322 : }
323 :
324 : export interface MintAttempt {
325 : readonly mintId: number
326 : /** Awaited another owner's in-flight mint instead of starting its own. */
327 : readonly joined: boolean
328 : readonly explicitUser: boolean
329 : readonly userUid: string
330 : readonly requestedTarget: string | undefined
331 : readonly startEpoch: number
332 : readonly startInvalidation: number
333 : readonly startedSignedOut: boolean
334 : }
335 :
336 : export type MintVerdict =
337 : | { readonly verdict: 'commit' }
338 : | { readonly verdict: 'reuse'; readonly session: AccountCredential }
339 : | { readonly verdict: 'superseded' }
340 :
341 2356 : const SUPERSEDED: MintVerdict = { verdict: 'superseded' }
342 :
343 0 : function supersededByInvalidation<TUser extends AccountUser>(
344 : state: SessionState<TUser>,
345 : attempt: MintAttempt
346 : ): boolean {
347 0 : return state.invalidationEpoch !== attempt.startInvalidation
348 : }
349 :
350 : // The newest mint won, but when it committed a credential for this
351 : // caller's exact target, that credential answers the request — a lost
352 : // race is not a failure. A different target (or none) stays undefined.
353 0 : function lostRace<TUser extends AccountUser>(
354 : state: SessionState<TUser>,
355 : attempt: MintAttempt
356 : ): MintVerdict | undefined {
357 0 : if (attempt.mintId === state.mintSequence) return undefined
358 : const answered =
359 : state.credential !== undefined &&
360 : state.credential.uid === attempt.userUid &&
361 : state.user?.uid === attempt.userUid &&
362 : attempt.requestedTarget === state.credentialTarget
363 0 : return answered ? { verdict: 'reuse', session: state.credential } : SUPERSEDED
364 : }
365 :
366 0 : function crossedIdentityEvent<TUser extends AccountUser>(
367 : state: SessionState<TUser>,
368 : attempt: MintAttempt
369 : ): boolean {
370 0 : return state.identityEpoch !== attempt.startEpoch
371 : }
372 :
373 : // The one mint allowed to cross an identity event: an explicit-user
374 : // mint started while signed out, for the user the port then
375 : // delivered (the popup path) as the single event since. Everything else
376 : // was minted for an identity that is gone, even when the uid matches again.
377 0 : function popupSettled<TUser extends AccountUser>(
378 : state: SessionState<TUser>,
379 : attempt: MintAttempt
380 : ): boolean {
381 0 : return (
382 : attempt.explicitUser &&
383 : attempt.startedSignedOut &&
384 : state.identityEpoch === attempt.startEpoch + 1 &&
385 : state.user?.uid === attempt.userUid
386 : )
387 : }
388 :
389 : // The explicit-user bypass is the popup path, valid only before the
390 : // identity port has ever fired; a settled null identity blocks it.
391 0 : function userMismatchBlocksCommit<TUser extends AccountUser>(
392 : state: SessionState<TUser>,
393 : attempt: MintAttempt
394 : ): boolean {
395 0 : return (
396 : state.user?.uid !== attempt.userUid &&
397 : (!attempt.explicitUser || state.user !== null || state.identitySettled)
398 : )
399 : }
400 :
401 0 : function joinerReuse<TUser extends AccountUser>(
402 : state: SessionState<TUser>,
403 : attempt: MintAttempt
404 : ): MintVerdict | undefined {
405 0 : return attempt.joined &&
406 : state.committedMint !== undefined &&
407 : state.committedMint.mintId === attempt.mintId &&
408 : state.credential === state.committedMint.session
409 : ? { verdict: 'reuse', session: state.committedMint.session }
410 : : undefined
411 : }
412 :
413 0 : export function arbitrateMint<TUser extends AccountUser>(
414 : state: SessionState<TUser>,
415 : attempt: MintAttempt
416 : ): MintVerdict {
417 0 : if (supersededByInvalidation(state, attempt)) return SUPERSEDED
418 0 : const raced = lostRace(state, attempt)
419 0 : if (raced) return raced
420 : const stale = crossedIdentityEvent(state, attempt)
421 : ? !popupSettled(state, attempt)
422 : : userMismatchBlocksCommit(state, attempt)
423 0 : if (stale) return SUPERSEDED
424 0 : return joinerReuse(state, attempt) ?? { verdict: 'commit' }
425 : }
426 :
427 0 : export function scheduledMintHolds<TUser extends AccountUser>(
428 : state: SessionState<TUser>,
429 : guards: { readonly epoch: number; readonly invalidation: number },
430 : userUid: string,
431 : mintId: number
432 : ): boolean {
433 0 : return (
434 : mintId === state.mintSequence &&
435 : state.user?.uid === userUid &&
436 : state.identityEpoch === guards.epoch &&
437 : state.invalidationEpoch === guards.invalidation
438 : )
439 : }
|