Line data Source code
1 : /**
2 : * Enterprise SSO sign-in through ingest: the discover call that tells whether
3 : * an email signs in through its organization, the start URL the browser
4 : * navigates to, and the codes a failed sign-in comes back with. Hosts own the
5 : * copy; nothing here is text a person reads.
6 : */
7 : import type { SsoDiscoverResponse } from '@comfyorg/ingest-types'
8 : import {
9 : zDiscoverSsoBody,
10 : zDiscoverSsoResponse,
11 : zErrorResponse
12 : } from '@comfyorg/ingest-types/zod'
13 :
14 : import { timedSignal } from './core/requestTimeout'
15 : import { safeInternalPath } from './redirect'
16 :
17 : export {
18 : isAccountOutsideOrganizationRefusal,
19 : isSsoRequiredRefusal,
20 : ssoRequiredOrganizationId
21 : } from './core/ssoRequired'
22 :
23 2356 : const SSO_DISCOVER_PATH = '/api/auth/sso/discover'
24 2356 : const SSO_START_PATH = '/api/auth/sso/start'
25 2356 : const DEFAULT_DISCOVER_TIMEOUT_MS = 5000
26 :
27 : export type SsoDiscovery =
28 : | {
29 : readonly kind: 'sso'
30 : /** False for an organization in optional mode, which only offers SSO. */
31 : readonly required: boolean
32 : readonly organizationName?: string
33 : }
34 : | { readonly kind: 'not-sso' }
35 : | { readonly kind: 'invalid-email' }
36 : | { readonly kind: 'unavailable' }
37 :
38 : export interface DiscoverSsoOptions {
39 : readonly fetchImpl: typeof fetch
40 : readonly signal?: AbortSignal
41 : /** Ingest origin; empty (the default) means same-origin. */
42 : readonly baseUrl?: string
43 : /** A sign-in waits on this call, so it is bounded. Default 5s. */
44 : readonly timeoutMs?: number
45 : }
46 :
47 0 : function fromResponse(body: SsoDiscoverResponse): SsoDiscovery {
48 0 : if (!body.sso) return { kind: 'not-sso' }
49 0 : const required = body.required ?? true
50 0 : return body.organization_name === undefined
51 : ? { kind: 'sso', required }
52 : : { kind: 'sso', required, organizationName: body.organization_name }
53 : }
54 :
55 : /** How the person reached discover: the SSO entry, or an email sign-in or sign-up. */
56 : export type SsoSignInVia = 'sso-entry' | 'email-sign-in'
57 :
58 : /**
59 : * Whether a sign-in goes to SSO. An organization in optional mode keeps its
60 : * people's other sign-ins, so only the SSO entry sends them there.
61 : */
62 0 : export function sendsToSso(
63 : discovery: SsoDiscovery,
64 : via: SsoSignInVia
65 : ): boolean {
66 0 : if (discovery.kind !== 'sso') return false
67 0 : return via === 'sso-entry' || discovery.required
68 : }
69 :
70 0 : async function readJson(response: Response): Promise<unknown> {
71 0 : try {
72 0 : return await response.json()
73 : } catch {
74 0 : return undefined
75 : }
76 : }
77 :
78 0 : function classify(status: number, body: unknown): SsoDiscovery {
79 0 : if (status === 200) {
80 0 : const parsed = zDiscoverSsoResponse.safeParse(body)
81 0 : return parsed.success ? fromResponse(parsed.data) : { kind: 'unavailable' }
82 : }
83 0 : const error = zErrorResponse.safeParse(body)
84 0 : return status === 400 && error.success && error.data.code === 'INVALID_EMAIL'
85 : ? { kind: 'invalid-email' }
86 : : { kind: 'unavailable' }
87 : }
88 :
89 : /**
90 : * Whether an email signs in through its organization's SSO. Never throws: a
91 : * network failure, timeout, unexpected status or unreadable body is
92 : * `unavailable`, so a caller can fall back to its usual sign-in.
93 : */
94 0 : export async function discoverSso(
95 : email: string,
96 : options: DiscoverSsoOptions
97 : ): Promise<SsoDiscovery> {
98 0 : const request = zDiscoverSsoBody.safeParse({ email: email.trim() })
99 0 : if (!request.success || request.data.email === '') {
100 0 : return { kind: 'invalid-email' }
101 : }
102 0 : const { signal, release } = timedSignal(
103 : options.signal,
104 : options.timeoutMs ?? DEFAULT_DISCOVER_TIMEOUT_MS
105 : )
106 0 : try {
107 0 : const response = await options.fetchImpl(
108 : `${options.baseUrl ?? ''}${SSO_DISCOVER_PATH}`,
109 : {
110 : method: 'POST',
111 : headers: { 'Content-Type': 'application/json' },
112 : body: JSON.stringify(request.data),
113 : signal
114 : }
115 : )
116 0 : return classify(response.status, await readJson(response))
117 : } catch {
118 0 : return { kind: 'unavailable' }
119 : } finally {
120 0 : release()
121 : }
122 : }
123 :
124 : /**
125 : * Ingest sends API routes back to `/`: they refuse a cross-site navigation,
126 : * so the person would land on an error. Anything off-origin goes there too.
127 : */
128 0 : function isApiRoute(url: URL): boolean {
129 0 : const pathname = url.pathname.toLowerCase()
130 0 : return pathname === '/api' || pathname.startsWith('/api/')
131 : }
132 :
133 0 : function absoluteUrl(raw: string): URL | null {
134 0 : try {
135 0 : return new URL(raw)
136 : } catch {
137 0 : return null
138 : }
139 : }
140 :
141 0 : function ssoReturnTo(
142 : raw: string,
143 : origin: string,
144 : appOrigin: string | undefined
145 : ): string {
146 0 : const url = appOrigin === undefined ? null : absoluteUrl(raw)
147 0 : if (url && url.origin === appOrigin) return isApiRoute(url) ? '/' : url.href
148 0 : const path = safeInternalPath(raw, origin, '/')
149 0 : return isApiRoute(new URL(path, origin)) ? '/' : path
150 : }
151 :
152 : /** A named organization is the target; otherwise the email's domain is. */
153 : type SsoStartTarget =
154 : | { readonly email: string; readonly organizationId?: string }
155 : | { readonly email?: string; readonly organizationId: string }
156 :
157 : /**
158 : * Where the browser goes to sign in with SSO. Ingest answers with a redirect
159 : * to the identity provider, so this is for a full-page navigation, never a
160 : * fetch.
161 : */
162 0 : export function ssoStartUrl(
163 : options: SsoStartTarget & {
164 : readonly returnTo: string
165 : readonly origin: string
166 : /**
167 : * The calling app's own origin when it is not Cloud's (billing-web,
168 : * platform): a `returnTo` on it is sent whole, and ingest returns there
169 : * only when the origin is an https one it trusts with the web session.
170 : */
171 : readonly appOrigin?: string
172 : }
173 : ): string {
174 0 : const url = new URL(SSO_START_PATH, options.origin)
175 0 : if (options.email !== undefined) {
176 0 : url.searchParams.set('email', options.email.trim())
177 : }
178 0 : if (options.organizationId !== undefined) {
179 0 : url.searchParams.set('organization', options.organizationId)
180 : }
181 0 : url.searchParams.set(
182 : 'return_to',
183 : ssoReturnTo(options.returnTo, options.origin, options.appOrigin)
184 : )
185 0 : return url.toString()
186 : }
187 :
188 : /** Every code ingest's SSO start and callback send back as `?sso_error=`. */
189 : const SSO_ERROR_CODES = [
190 : 'INTERNAL_ERROR',
191 : 'RATE_LIMITED',
192 : 'SESSION_CREATION_FAILED',
193 : 'SSO_ACCOUNT_CONFLICT',
194 : 'SSO_ACCOUNT_DELETED',
195 : 'SSO_CONFIRM_EXPIRED',
196 : 'SSO_EMAIL_DOMAIN_NOT_ALLOWED',
197 : 'SSO_EXCHANGE_FAILED',
198 : 'SSO_IDP_ERROR',
199 : 'SSO_INVALID_STATE',
200 : 'SSO_LINK_CHECK_FAILED',
201 : 'SSO_NOT_CONFIGURED',
202 : 'SSO_ORG_DISABLED',
203 : 'SSO_ORG_MISMATCH',
204 : 'SSO_ORG_NOT_ATTACHED',
205 : 'SSO_SEAT_LIMIT_REACHED',
206 : 'SSO_SIGN_IN_FAILED',
207 : 'SSO_UNAVAILABLE',
208 : 'SSO_USER_SUSPENDED'
209 : ] as const
210 :
211 : export type SsoErrorCode = (typeof SSO_ERROR_CODES)[number]
212 :
213 2356 : const KNOWN_SSO_ERRORS: ReadonlySet<string> = new Set(SSO_ERROR_CODES)
214 :
215 0 : function isSsoErrorCode(value: string): value is SsoErrorCode {
216 0 : return KNOWN_SSO_ERRORS.has(value)
217 : }
218 :
219 : /**
220 : * Reads an `?sso_error=` query value. Absent is undefined; a code this build
221 : * predates reads as a generic sign-in failure, so it still gets a message.
222 : */
223 0 : export function readSsoError(value: unknown): SsoErrorCode | undefined {
224 0 : const raw = Array.isArray(value) ? value[0] : value
225 0 : if (typeof raw !== 'string' || raw === '') return undefined
226 0 : return isSsoErrorCode(raw) ? raw : 'SSO_SIGN_IN_FAILED'
227 : }
|