Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ async function exchangeWithSession(
signal: context.signal
})
if (reread.status === 'error') return rereadFailure(reread)
if (!context.stillInScope()) return { status: 'error', code: 'SUPERSEDED' }
return sendAs(reread.session)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,21 @@ describe('createCredentialedBillingTransport with a web session', () => {
expect(endpoint.requests).toEqual([])
})

it('does not replay once the host left the scope during the re-read', async () => {
let reread = () => false
const { transport, fetchImpl, endpoint } = makeTransport({
responses: [refusal('csrf_invalid')],
scope: () => (reread() ? { ...SCOPE, workspaceId: 'ws-2' } : SCOPE)
})
reread = () => endpoint.requests.length > 0

const result = await transport({ method: 'POST', route: '/billing/topup' })

expect(result).toEqual({ status: 'error', code: 'SUPERSEDED' })
expect(endpoint.requests).toHaveLength(1)
expect(fetchImpl).toHaveBeenCalledOnce()
})

it('reports NOT_AUTHENTICATED without sending when there is no session', async () => {
const { transport, fetchImpl } = makeTransport({ session: undefined })

Expand Down
2 changes: 2 additions & 0 deletions packages/account-core/src/core/sessionTokenMint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,8 @@ export function createSessionTokenMint({
if (session === undefined) return failure('NO_SESSION')
const userId = session.user.id

// The cache is checked before the backoff on purpose: a caller already
// holding a fresh token is still served while new mints wait.
const cached = cache.get(workspaceId)
if (cached && isCredentialFresh(cached, now(), refreshBufferMs)) {
return { status: 'ok', credential: cached }
Expand Down
167 changes: 167 additions & 0 deletions packages/account-core/src/core/webSessionIdentity.lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,173 @@ describe('tabs of one site', () => {
expect(sibling.remoteSignOuts).toEqual([])
})

it('a sign-out during an interactive sign-in wins, in this tab and its siblings', async () => {
const endpoint = liveEndpoint({ kind: 'dead', code: 'no_session' })
const site = createFakeSiteBus()
let releasePost = () => {}
const postHeld = new Promise<void>((resolve) => {
releasePost = resolve
})
const acting = openTab({
endpoint,
site,
remembered: null,
fetchImpl: async (input, init) => {
if (init?.method === 'POST') await postHeld
return endpoint.fetch(input, init)
}
})
const sibling = openTab({ endpoint, site, remembered: null })
await settle()

const signingIn = acting.identity.signedIn(async () => 'fresh-proof')
await settle()
await acting.identity.signOut()
releasePost()
const answer = await signingIn
await settle()

expect(answer).toMatchObject({ status: 'error', code: 'SESSION_REVOKED' })
expect(summarize(acting.identity.getState())).toBe('signed_out:signed_out')
expect(summarize(sibling.identity.getState())).toBe('signed_out:signed_out')
expect(methods(endpoint).slice(-4)).toEqual([
'DELETE',
'POST',
'GET',
'DELETE'
])
})

it('a sibling tab signing out invalidates a pending sign-in in this tab', async () => {
const endpoint = liveEndpoint({ kind: 'dead', code: 'no_session' })
const site = createFakeSiteBus()
let releasePost = () => {}
const postHeld = new Promise<void>((resolve) => {
releasePost = resolve
})
const acting = openTab({
endpoint,
site,
remembered: null,
fetchImpl: async (input, init) => {
if (init?.method === 'POST') await postHeld
return endpoint.fetch(input, init)
}
})
const sibling = openTab({ endpoint, site, remembered: null })
await settle()

const signingIn = acting.identity.signedIn(async () => 'fresh-proof')
await settle()
await sibling.identity.signOut()
releasePost()
const answer = await signingIn
await settle()

expect(answer).toMatchObject({ status: 'error', code: 'SESSION_REVOKED' })
expect(summarize(acting.identity.getState())).toBe('signed_out:signed_out')
expect(summarize(sibling.identity.getState())).toBe('signed_out:signed_out')
expect(endpoint.state.kind).toBe('dead')
})

it('a stale sign-in never deletes the session a later sign-in created', async () => {
const endpoint = liveEndpoint({ kind: 'dead', code: 'no_session' })
let releaseFirstPost = () => {}
const firstPostHeld = new Promise<void>((resolve) => {
releaseFirstPost = resolve
})
let posts = 0
const tab = openTab({
endpoint,
remembered: null,
fetchImpl: async (input, init) => {
if (init?.method === 'POST' && ++posts === 1) await firstPostHeld
return endpoint.fetch(input, init)
}
})
await settle()

const stale = tab.identity.signedIn(async () => 'first-proof')
await settle()
await tab.identity.signOut()
await tab.identity.signedIn(async () => 'second-proof')
const afterSecond = methods(endpoint).length
releaseFirstPost()
await stale
await settle()

expect(summarize(tab.identity.getState())).toBe('signed_in:user-2')
expect(methods(endpoint).slice(afterSecond)).not.toContain('DELETE')
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})

it('a stale sign-in still deletes its session when the later sign-in failed', async () => {
const endpoint = liveEndpoint({ kind: 'dead', code: 'no_session' })
let releaseFirstPost = () => {}
const firstPostHeld = new Promise<void>((resolve) => {
releaseFirstPost = resolve
})
let posts = 0
const tab = openTab({
endpoint,
remembered: null,
fetchImpl: async (input, init) => {
const post = init?.method === 'POST' ? ++posts : 0
if (post === 1) await firstPostHeld
if (post === 2) return new Response('{}', { status: 503 })
return endpoint.fetch(input, init)
}
})
await settle()

const stale = tab.identity.signedIn(async () => 'first-proof')
await settle()
await tab.identity.signOut()
expect(
await tab.identity.signedIn(async () => 'second-proof')
).toMatchObject({ status: 'error' })
releaseFirstPost()

expect(await stale).toMatchObject({
status: 'error',
code: 'SESSION_REVOKED'
})
await settle()
expect(summarize(tab.identity.getState())).toBe('signed_out:signed_out')
expect(endpoint.state.kind).toBe('dead')
})

it('reports a failed cleanup instead of a clean revocation', async () => {
const endpoint = liveEndpoint({ kind: 'dead', code: 'no_session' })
let releasePost = () => {}
const postHeld = new Promise<void>((resolve) => {
releasePost = resolve
})
let deletes = 0
const tab = openTab({
endpoint,
remembered: null,
fetchImpl: async (input, init) => {
if (init?.method === 'POST') await postHeld
if (init?.method === 'DELETE' && ++deletes === 2) {
return new Response('{}', { status: 503 })
}
return endpoint.fetch(input, init)
}
})
await settle()

const signingIn = tab.identity.signedIn(async () => 'fresh-proof')
await settle()
await tab.identity.signOut()
releasePost()

expect(await signingIn).toMatchObject({
status: 'error',
code: 'SESSION_UNAVAILABLE'
})
expect(summarize(tab.identity.getState())).toBe('signed_out:signed_out')
})

it('a tab that signed out is not signed back in by a sibling heartbeat', async () => {
const endpoint = liveEndpoint()
const site = createFakeSiteBus()
Expand Down
14 changes: 14 additions & 0 deletions packages/account-core/src/core/webSessionIdentity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,20 @@ describe('network errors', () => {
expect(login.signOutLocally).not.toHaveBeenCalled()
})

it('adopts a live session even when the remembered-login lookup throws', async () => {
const login = fakeRememberedLogin('user-2')
login.currentUserId.mockRejectedValueOnce(new Error('provider offline'))
const { endpoint, scheduler, identity } = bootIdentity({
state: { kind: 'live', user: SESSION_USER },
login
})

expect(summarize(await nextRest(identity))).toBe('signed_in:user-1')
expect(scheduler.delays()).toEqual([])
expect(requestLog(endpoint)).toEqual(['GET'])
expect(login.signOutLocally).not.toHaveBeenCalled()
})

it.for([
{ name: 'a pending session read', pending: 'read' },
{ name: 'a pending identity proof', pending: 'proof' }
Expand Down
36 changes: 34 additions & 2 deletions packages/account-core/src/core/webSessionIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,11 @@ const zSharedResult = z.discriminatedUnion('status', [
})
])

/**
* Every tab of a site reads the same host-only cookie, so a sibling's answer
* is this tab's own session observed elsewhere; that is what makes adopting
* it safe. A per-tab session scope would break this assumption.
*/
const zSharedMessage = z.object({
from: z.enum(['heartbeat', 'sign_in', 'sign_out']),
result: zSharedResult
Expand Down Expand Up @@ -512,6 +517,9 @@ function createAccountIdentity(
const listeners = new Set<(state: WebSessionIdentityState) => void>()
let state: WebSessionIdentityState = { phase: 'idle' }
let epoch = 0
let signOuts = 0
let signIns = 0
let liveSignIn = 0
let cancelRetry: (() => void) | undefined
let cancelBeat: (() => void) | undefined
let releaseLeadership: (() => void) | undefined
Expand Down Expand Up @@ -545,8 +553,16 @@ function createAccountIdentity(
() => undefined
)
if (started !== epoch) return
if (remembered === undefined) return dispatch({ type: 'login_errored' })
dispatch({ ...answered, result, rememberedUserId: remembered.value })
// A failed lookup matters only without a live session to adopt: with one,
// it can skip nothing but the different-user sign-out.
if (remembered === undefined && result.status !== 'ok') {
return dispatch({ type: 'login_errored' })
}
dispatch({
...answered,
result,
rememberedUserId: remembered?.value ?? null
})
}

function beat(): void {
Expand All @@ -560,10 +576,16 @@ function createAccountIdentity(
})
}

function invalidatePendingSignIns(): void {
signOuts += 1
liveSignIn = 0
}

function adopt(message: unknown): void {
const parsed = zSharedMessage.safeParse(message)
if (!parsed.success) return
const { from, result } = parsed.data
if (from === 'sign_out') invalidatePendingSignIns()
const observed = {
type: 'session_observed',
from: `sibling_${from}`
Expand Down Expand Up @@ -702,13 +724,23 @@ function createAccountIdentity(
dispatch({ type: 'boot' })
},
signedIn: async (getProof) => {
const signOutsAtStart = signOuts
const signIn = ++signIns
const result = await createWebSession(options.session, getProof)
if (result.status !== 'ok') return result
if (signOuts !== signOutsAtStart) {
// A later sign-in owns the cookie now; deleting would end its session.
if (liveSignIn > signIn) return revoked
const cleanup = await deleteWebSession(options.session)
return cleanup.status === 'ok' ? revoked : cleanup
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
liveSignIn = signIn
dispatch({ type: 'session_created', session: result.session })
publish('sign_in', result)
return result
},
signOut: async () => {
invalidatePendingSignIns()
dispatch({ type: 'sign_out_requested' })
const result = await deleteWebSession(options.session)
if (result.status === 'ok') publish('sign_out', revoked)
Expand Down
Loading