Line data Source code
1 : /**
2 : * Authorization code + PKCE (RFC 7636, S256 only) against the Cloud OAuth
3 : * server, for a browser page that signs in as a public client. Builds the
4 : * authorize URL, reads the redirect back, and runs the code and refresh grants
5 : * on `/oauth/token`. Holds no state: the caller keeps the verifier and state
6 : * across the redirect and owns where the tokens live.
7 : */
8 : import type { OAuthTokenResponse } from '@comfyorg/ingest-types'
9 : import {
10 : zOAuthTokenError,
11 : zOAuthTokenResponse
12 : } from '@comfyorg/ingest-types/zod'
13 :
14 : import { timedSignal } from './core/requestTimeout'
15 :
16 2352 : export const LOCAL_WEB_CLIENT_ID = 'comfy-local-web'
17 :
18 2352 : const AUTHORIZE_PATH = '/oauth/authorize'
19 2352 : const TOKEN_PATH = '/oauth/token'
20 2352 : const REVOKE_PATH = '/oauth/revoke'
21 : /** The `comfy-cloud` resource is seeded issuer-relative at `/api`. */
22 2352 : const CLOUD_RESOURCE_PATH = '/api'
23 2352 : const DEFAULT_TOKEN_TIMEOUT_MS = 15_000
24 : /** 32 bytes encode to the 43-character minimum verifier length. */
25 2352 : const RANDOM_BYTES = 32
26 2352 : const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
27 :
28 0 : function base64Url(bytes: Uint8Array): string {
29 0 : const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')
30 0 : return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
31 : }
32 :
33 0 : function randomToken(): string {
34 0 : return base64Url(crypto.getRandomValues(new Uint8Array(RANDOM_BYTES)))
35 : }
36 :
37 0 : export async function codeChallengeS256(verifier: string): Promise<string> {
38 0 : const digest = await crypto.subtle.digest(
39 : 'SHA-256',
40 : new TextEncoder().encode(verifier)
41 : )
42 0 : return base64Url(new Uint8Array(digest))
43 : }
44 :
45 : export interface PkceRequest {
46 : readonly verifier: string
47 : readonly challenge: string
48 : readonly state: string
49 : }
50 :
51 : /** A fresh verifier, its S256 challenge, and an unguessable `state`. */
52 0 : export async function createPkceRequest(): Promise<PkceRequest> {
53 0 : const verifier = randomToken()
54 0 : return {
55 : verifier,
56 : challenge: await codeChallengeS256(verifier),
57 : state: randomToken()
58 : }
59 : }
60 :
61 : /** The redirect URI registered for a page served at `origin`. */
62 0 : export function localRedirectUri(origin: string): string {
63 0 : return new URL('/', origin).href
64 : }
65 :
66 : export interface AuthorizeUrlOptions {
67 : /** Cloud origin, e.g. `https://cloud.comfy.org`. */
68 : readonly issuer: string
69 : readonly clientId: string
70 : readonly redirectUri: string
71 : readonly challenge: string
72 : readonly state: string
73 : }
74 :
75 : /** Where the browser navigates to sign in; never fetched. */
76 0 : export function authorizeUrl(options: AuthorizeUrlOptions): string {
77 0 : const url = new URL(AUTHORIZE_PATH, options.issuer)
78 0 : url.search = new URLSearchParams({
79 : response_type: 'code',
80 : client_id: options.clientId,
81 : redirect_uri: options.redirectUri,
82 : code_challenge: options.challenge,
83 : code_challenge_method: 'S256',
84 : state: options.state,
85 : resource: new URL(CLOUD_RESOURCE_PATH, options.issuer).href
86 : }).toString()
87 0 : return url.href
88 : }
89 :
90 : export type AuthorizationResponse =
91 : | { readonly kind: 'none' }
92 : | { readonly kind: 'code'; readonly code: string }
93 : | { readonly kind: 'denied'; readonly error: string }
94 : | { readonly kind: 'state-mismatch' }
95 :
96 : /**
97 : * Reads the authorize redirect (RFC 6749 ยง4.1.2) off the page URL. A response
98 : * whose `state` is not the one this browser sent is never used.
99 : */
100 0 : export function readAuthorizationResponse(
101 : params: URLSearchParams,
102 : expectedState: string | undefined
103 : ): AuthorizationResponse {
104 0 : const code = params.get('code')
105 0 : const error = params.get('error')
106 0 : if (code === null && error === null) return { kind: 'none' }
107 0 : const state = params.get('state')
108 0 : if (expectedState === undefined || state !== expectedState) {
109 0 : return { kind: 'state-mismatch' }
110 : }
111 0 : if (error !== null) return { kind: 'denied', error }
112 0 : return code
113 : ? { kind: 'code', code }
114 : : { kind: 'denied', error: 'invalid_request' }
115 : }
116 :
117 : export interface OAuthTokens {
118 : readonly accessToken: string
119 : readonly refreshToken: string
120 : /** Epoch milliseconds. */
121 : readonly expiresAt: number
122 : readonly scope: string
123 : }
124 :
125 : /**
126 : * `invalid_grant`: the code or refresh token is dead; sign in again.
127 : * `rejected`: any other OAuth error the server returned.
128 : * `unavailable`: network failure, timeout, or a response that is not OAuth.
129 : */
130 : export type TokenFailureReason = 'invalid_grant' | 'rejected' | 'unavailable'
131 :
132 : export type TokenResult =
133 : | { readonly ok: true; readonly tokens: OAuthTokens }
134 : | {
135 : readonly ok: false
136 : readonly reason: TokenFailureReason
137 : readonly error?: string
138 : }
139 :
140 : export interface TokenRequestOptions {
141 : readonly issuer: string
142 : readonly clientId: string
143 : readonly fetchImpl: typeof fetch
144 : readonly now: () => number
145 : readonly signal?: AbortSignal
146 : /** Default 15s. */
147 : readonly timeoutMs?: number
148 : }
149 :
150 0 : function toTokens(body: OAuthTokenResponse, now: number): OAuthTokens {
151 0 : return {
152 : accessToken: body.access_token,
153 : refreshToken: body.refresh_token,
154 : expiresAt: now + body.expires_in * 1000,
155 : scope: body.scope
156 : }
157 : }
158 :
159 0 : async function readJson(response: Response): Promise<unknown> {
160 0 : try {
161 0 : return await response.json()
162 : } catch {
163 0 : return undefined
164 : }
165 : }
166 :
167 0 : function classify(status: number, body: unknown, now: number): TokenResult {
168 0 : if (status === 200) {
169 0 : const parsed = zOAuthTokenResponse.safeParse(body)
170 0 : return parsed.success
171 : ? { ok: true, tokens: toTokens(parsed.data, now) }
172 : : { ok: false, reason: 'unavailable' }
173 : }
174 0 : const error = zOAuthTokenError.safeParse(body)
175 0 : if (status < 400 || status >= 500 || !error.success) {
176 0 : return { ok: false, reason: 'unavailable' }
177 : }
178 0 : return {
179 : ok: false,
180 : reason: error.data.error === 'invalid_grant' ? 'invalid_grant' : 'rejected',
181 : error: error.data.error
182 : }
183 : }
184 :
185 0 : function oauthEndpoint(path: string, issuer: string): URL | undefined {
186 0 : const url = new URL(path, issuer)
187 0 : if (url.protocol === 'https:') return url
188 0 : if (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname)) return url
189 : return undefined
190 : }
191 :
192 0 : async function postTokenGrant(
193 : form: Record<string, string>,
194 : options: TokenRequestOptions
195 : ): Promise<TokenResult> {
196 0 : const { signal, release } = timedSignal(
197 : options.signal,
198 : options.timeoutMs ?? DEFAULT_TOKEN_TIMEOUT_MS
199 : )
200 0 : try {
201 0 : const endpoint = oauthEndpoint(TOKEN_PATH, options.issuer)
202 0 : if (!endpoint) return { ok: false, reason: 'unavailable' }
203 0 : const response = await options.fetchImpl(endpoint.href, {
204 : method: 'POST',
205 : headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
206 : body: new URLSearchParams({ ...form, client_id: options.clientId }),
207 : signal
208 : })
209 0 : return classify(response.status, await readJson(response), options.now())
210 : } catch {
211 0 : return { ok: false, reason: 'unavailable' }
212 : } finally {
213 0 : release()
214 : }
215 : }
216 :
217 : /** Trades the authorize redirect's code for tokens. Never throws. */
218 0 : export function exchangeAuthorizationCode(
219 : grant: {
220 : readonly code: string
221 : readonly verifier: string
222 : readonly redirectUri: string
223 : },
224 : options: TokenRequestOptions
225 : ): Promise<TokenResult> {
226 0 : return postTokenGrant(
227 : {
228 : grant_type: 'authorization_code',
229 : code: grant.code,
230 : code_verifier: grant.verifier,
231 : redirect_uri: grant.redirectUri
232 : },
233 : options
234 : )
235 : }
236 :
237 : /**
238 : * Trades a refresh token for a new pair. The server rotates on every success
239 : * and revokes the family when an old one is replayed, so the caller must keep
240 : * only the returned refresh token. Never throws.
241 : */
242 0 : export function refreshAccessToken(
243 : refreshToken: string,
244 : options: TokenRequestOptions
245 : ): Promise<TokenResult> {
246 0 : return postTokenGrant(
247 : { grant_type: 'refresh_token', refresh_token: refreshToken },
248 : options
249 : )
250 : }
251 :
252 : /**
253 : * Asks the server to end the sign-in a refresh token belongs to (RFC 7009).
254 : * Sent with keepalive so it survives the page closing. Never throws.
255 : */
256 0 : export async function revokeRefreshToken(
257 : refreshToken: string,
258 : options: TokenRequestOptions
259 : ): Promise<boolean> {
260 0 : const { signal, release } = timedSignal(
261 : options.signal,
262 : options.timeoutMs ?? DEFAULT_TOKEN_TIMEOUT_MS
263 : )
264 0 : try {
265 0 : const endpoint = oauthEndpoint(REVOKE_PATH, options.issuer)
266 0 : if (!endpoint) return false
267 : const response = await options.fetchImpl(endpoint.href, {
268 : method: 'POST',
269 : headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
270 : body: new URLSearchParams({
271 : token: refreshToken,
272 : token_type_hint: 'refresh_token',
273 : client_id: options.clientId
274 : }),
275 : signal,
276 : keepalive: true,
277 : redirect: 'error'
278 : })
279 0 : return response.ok
280 : } catch {
281 0 : return false
282 : } finally {
283 0 : release()
284 : }
285 : }
|