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
20 changes: 7 additions & 13 deletions src/platform/auth/session/cloudWebSessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
createSessionTokenMint,
SessionTokenError
} from '@comfyorg/account-core/sessionTokenMint'
import { readWebSession } from '@comfyorg/account-core/webSession'
import { createWebSessionIdentity } from '@comfyorg/account-core/webSessionIdentity'
import {
createWebCrossTabRefreshPort,
Expand Down Expand Up @@ -168,7 +167,6 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {
let decidedForRequests: Promise<void> = Promise.resolve()
let reconnectTimer: ReturnType<typeof setTimeout> | undefined
let pendingSignIn: InteractiveSignIn | null = null
let reread: WebSession | null = null
let releaseRequests = () => {}
const state = shallowRef<WebSessionIdentityState>({ phase: 'idle' })
const signedInUser = computed(() =>
Expand Down Expand Up @@ -244,7 +242,6 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {
const session = createCloudIdentity()
identity = session
session.subscribe((next) => {
reread = null
state.value = next
})
const mint = createSessionTokenMint({
Expand Down Expand Up @@ -319,8 +316,7 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {

function currentSession(): WebSession | undefined {
const state = identity?.getState()
if (state?.phase !== 'signed_in') return undefined
return reread?.user.id === state.session.user.id ? reread : state.session
return state?.phase === 'signed_in' ? state.session : undefined
}

/** The epoch moves on every account change, so it pins the scope's user. */
Expand Down Expand Up @@ -370,15 +366,13 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {
}
}

async function rereadFor(
async function refreshFor(
scope: WebSessionRequestScope
): Promise<WebSessionRequestScope | undefined> {
const result = await readWebSession(sessionOptions(), {
expectedUserId: scope.session.user.id
})
if (result.status !== 'ok' || identity?.getEpoch() !== scope.epoch) return
reread = result.session
return { ...scope, session: result.session }
const next = await identity?.refresh(scope.session.user.id)
if (next?.phase !== 'signed_in' || next.session === scope.session) return
if (identity?.getEpoch() !== scope.epoch) return
return { ...scope, session: next.session }
}

function send(
Expand All @@ -389,7 +383,7 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {
): Promise<Response> {
return fetchOnWebSession(url, init, scope, {
authorize,
reread: rereadFor,
refresh: refreshFor,
workspaceDenied: (workspaceId) =>
useWorkspaceAuthStore().dropDeniedWorkspace(workspaceId)
})
Expand Down
4 changes: 2 additions & 2 deletions src/platform/auth/session/webSessionFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export interface WebSessionRequestScope {

export interface WebSessionFetchPorts {
/** A fresh session for the same user and epoch, or undefined to abandon. */
readonly reread: (
readonly refresh: (
scope: WebSessionRequestScope
) => Promise<WebSessionRequestScope | undefined>
readonly workspaceDenied: (workspaceId: string) => void
Expand Down Expand Up @@ -76,7 +76,7 @@ export async function fetchOnWebSession(
if (code !== 'csrf_invalid' || init.body instanceof ReadableStream) {
return response
}
const fresh = await ports.reread(scope)
const fresh = await ports.refresh(scope)
return fresh ? send(fresh) : response
}

Expand Down
61 changes: 40 additions & 21 deletions src/platform/auth/webSessionFlagOn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ function installIngest(features: Record<string, boolean> = {}) {
const ingest = {
userId: 'user-a',
csrfToken: 'csrf-1',
sessionDown: false,
refusals: [] as string[],
mintRefusal: undefined as (() => Response) | undefined,
mintGate: undefined as Promise<void> | undefined,
Expand Down Expand Up @@ -611,14 +612,17 @@ function installIngest(features: Record<string, boolean> = {}) {
)
}

const answerSession = (): Response =>
ingest.sessionDown
? jsonResponse({ code: 'unavailable', message: 'down' }, 503)
: jsonResponse({
...sessionBody(ingest.userId),
csrf_token: ingest.csrfToken
})

const respond = (request: ApiRequest, body: unknown): Response => {
const { path, headers } = request
if (path === '/api/auth/session') {
return jsonResponse({
...sessionBody(ingest.userId),
csrf_token: ingest.csrfToken
})
}
if (path === '/api/auth/session') return answerSession()
if (path === '/api/auth/token') return mint(body)
if (path === '/api/workspaces/current') {
if (ingest.currentWorkspaceDown) return ingest.currentWorkspaceDown()
Expand Down Expand Up @@ -757,31 +761,46 @@ describe('cloud API requests on the shared web session', () => {
{
name: 'the same user is re-read once and retried once with the fresh token',
sessionUser: 'user-a',
sessionDown: false,
status: 200,
tokens: ['csrf-1', 'session', 'csrf-2', 'csrf-2']
},
{
name: 'a changed user abandons the request',
name: 'a changed user abandons the request and the tab follows the new account',
sessionUser: 'user-b',
sessionDown: false,
status: 403,
tokens: ['csrf-1', 'session', 'csrf-2']
},
{
name: 'a failed re-read abandons the request',
sessionUser: 'user-a',
sessionDown: true,
status: 403,
tokens: ['csrf-1', 'session', 'csrf-1']
}
])('csrf_invalid: $name', async ({ sessionUser, status, tokens }) => {
const ingest = await bootOnSession()
ingest.refusals.push('csrf_invalid')
ingest.userId = sessionUser
ingest.csrfToken = 'csrf-2'
])(
'csrf_invalid: $name',
async ({ sessionUser, sessionDown, status, tokens }) => {
const ingest = await bootOnSession()
ingest.refusals.push('csrf_invalid')
ingest.userId = sessionUser
ingest.sessionDown = sessionDown
ingest.csrfToken = 'csrf-2'

const response = await postPrompt()
await postPrompt()
const response = await postPrompt()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const signedInAfterRefusal = useCloudWebSessionStore().signedInUser?.id
await postPrompt()

expect(response.status).toBe(status)
expect(
ingest.requests.map(({ path, headers }) =>
path === '/api/auth/session' ? 'session' : headers['x-csrf-token']
)
).toEqual(tokens)
})
expect(response.status).toBe(status)
expect(signedInAfterRefusal).toBe(sessionUser)
expect(
ingest.requests.map(({ path, headers }) =>
path === '/api/auth/session' ? 'session' : headers['x-csrf-token']
)
).toEqual(tokens)
}
)

it('workspace_access_denied drops the selection and is never replayed', async () => {
const ingest = await bootOnSession()
Expand Down
Loading