Line data Source code
1 : import type { RequestAuthorizer } from '@comfyorg/account-core/requestAuth'
2 : import type { SessionTokenResult } from '@comfyorg/account-core/sessionTokenMint'
3 : import { SessionTokenError } from '@comfyorg/account-core/sessionTokenMint'
4 : import type {
5 : WebSession,
6 : WebSessionErrorCode
7 : } from '@comfyorg/account-core/webSession'
8 : import { classifyWebSessionFailure } from '@comfyorg/account-core/webSession'
9 :
10 : /** A workspace-token mint failure whose message is localized user-facing copy. */
11 2356 : export class WebSessionTokenError extends SessionTokenError {
12 : override readonly cause: SessionTokenError
13 :
14 : constructor(original: SessionTokenError, message: string) {
15 0 : super(original.failure)
16 0 : this.message = message
17 0 : this.name = 'WebSessionTokenError'
18 0 : this.cause = original
19 : }
20 : }
21 :
22 : /** The user, session epoch and workspace one request was started for. */
23 : export interface WebSessionRequestScope {
24 : readonly session: WebSession
25 : readonly epoch: number
26 : /** Absent means the personal workspace. */
27 : readonly workspaceId?: string
28 : }
29 :
30 : export interface WebSessionFetchPorts {
31 : /** A fresh session for the same user and epoch, or undefined to abandon. */
32 : readonly refresh: (
33 : scope: WebSessionRequestScope
34 : ) => Promise<WebSessionRequestScope | undefined>
35 : readonly workspaceDenied: (workspaceId: string) => void
36 : readonly ssoRequired: (scope: WebSessionRequestScope) => void
37 : readonly authorize: RequestAuthorizer
38 : /** Re-read the session and replay once when the server refuses it with a 401. */
39 : readonly retriesLapsedSession?: boolean
40 : }
41 :
42 0 : async function refusalCode(
43 : response: Response
44 : ): Promise<WebSessionErrorCode | undefined> {
45 0 : if (response.status !== 403) return undefined
46 0 : const body: unknown = await response
47 : .clone()
48 : .json()
49 : .catch(() => undefined)
50 0 : return classifyWebSessionFailure(response.status, body).code
51 : }
52 :
53 : /**
54 : * Sends one ingest request on the session cookie. `csrf_invalid`, and a 401
55 : * when `retriesLapsedSession` is set, are retried once on a refreshed session
56 : * for the same user and workspace; `workspace_access_denied` drops that
57 : * workspace and is returned as is, never replayed elsewhere; `sso_required`
58 : * is reported and returned.
59 : */
60 0 : export async function fetchOnWebSession(
61 : url: string,
62 : init: RequestInit,
63 : scope: WebSessionRequestScope,
64 : ports: WebSessionFetchPorts
65 : ): Promise<Response> {
66 0 : const send = async (current: WebSessionRequestScope) => {
67 0 : const { headers, credentials } = await ports.authorize(
68 : { kind: 'session', session: current.session },
69 : {
70 : target: 'ingest',
71 : method: init.method ?? 'GET',
72 : workspaceId: current.workspaceId
73 : }
74 : )
75 0 : const merged = new Headers(init.headers)
76 0 : for (const [name, value] of Object.entries(headers)) merged.set(name, value)
77 0 : return fetch(url, {
78 : ...init,
79 : headers: merged,
80 : credentials:
81 : new URL(url, location.href).origin === location.origin
82 : ? 'same-origin'
83 : : credentials
84 : })
85 : }
86 :
87 0 : const sendAndReport = async (current: WebSessionRequestScope) => {
88 0 : const response = await send(current)
89 0 : const code = await refusalCode(response)
90 0 : if (
91 : code === 'WORKSPACE_ACCESS_DENIED' &&
92 : current.workspaceId !== undefined
93 : ) {
94 0 : ports.workspaceDenied(current.workspaceId)
95 : }
96 0 : if (code === 'SSO_REQUIRED') ports.ssoRequired(current)
97 0 : return { response, code }
98 : }
99 :
100 0 : const { response, code } = await sendAndReport(scope)
101 0 : const lapsed = response.status === 401 && ports.retriesLapsedSession === true
102 0 : if (
103 : (code !== 'CSRF_STALE' && !lapsed) ||
104 : init.body instanceof ReadableStream
105 : ) {
106 0 : return response
107 : }
108 0 : const fresh = await ports.refresh(scope)
109 0 : if (!fresh) return response
110 0 : return ports.retriesLapsedSession === true
111 : ? (await sendAndReport(fresh)).response
112 : : send(fresh)
113 : }
114 :
115 : /** What a signed-in tab's requests need from the web session. */
116 : export interface WebSessionRequests {
117 : readonly refreshSession: () => Promise<void>
118 : /** Undefined unless this tab is signed in on the session. */
119 : readonly scope: () => Promise<WebSessionRequestScope | undefined>
120 : /** The signed-in session's team workspace, for URLs that carry no header. */
121 : readonly workspaceId: () => string | undefined
122 : readonly send: (
123 : url: string,
124 : init: RequestInit,
125 : scope: WebSessionRequestScope
126 : ) => Promise<Response>
127 : /** The web session's token for this scope's workspace; never rejects. */
128 : readonly workspaceToken: (
129 : scope: WebSessionRequestScope
130 : ) => Promise<SessionTokenResult>
131 : /** Mints past the cached token, for a token the server just refused; never rejects. */
132 : readonly remintWorkspaceToken: (
133 : scope: WebSessionRequestScope
134 : ) => Promise<SessionTokenResult>
135 : /** Bearer headers for a service other than ingest; mints on first use. Rejects with WebSessionTokenError. */
136 : readonly authorizeResource: (
137 : scope: WebSessionRequestScope
138 : ) => Promise<Readonly<Record<string, string>>>
139 : }
140 :
141 2356 : let provided: WebSessionRequests | undefined
142 :
143 : /** Set while the web session is on for this page load; returns its release. */
144 0 : export function provideWebSessionRequests(
145 : requests: WebSessionRequests
146 : ): () => void {
147 0 : provided = requests
148 0 : return () => {
149 0 : if (provided === requests) provided = undefined
150 : }
151 : }
152 :
153 345684 : export function webSessionRequests(): WebSessionRequests | undefined {
154 345684 : return provided
155 : }
156 :
157 : /** True when the session is on and this tab is signed in on it. */
158 0 : export async function signedInOnWebSession(): Promise<boolean> {
159 0 : return (await provided?.scope()) !== undefined
160 : }
161 :
162 : export type WebSessionSend = (
163 : url: string,
164 : init: RequestInit
165 : ) => Promise<Response>
166 :
167 : /** Sends on the signed-in session, or undefined when this tab is not on it. */
168 0 : export async function webSessionSend(): Promise<WebSessionSend | undefined> {
169 0 : const requests = webSessionRequests()
170 0 : if (!requests) return undefined
171 0 : const scope = await requests.scope()
172 0 : return scope && ((url, init) => requests.send(url, init, scope))
173 : }
174 :
175 : /** Undefined unless the session is on and this tab is signed in on it. */
176 1 : export async function webSessionResourceHeader(): Promise<
177 : Readonly<Record<string, string>> | undefined
178 : > {
179 1 : const requests = provided
180 1 : if (!requests) return undefined
181 0 : const scope = await requests.scope()
182 1 : return scope && requests.authorizeResource(scope)
183 : }
|