Line data Source code
1 : /**
2 : * Shared telemetry vocabulary. The event names match the cloud app's
3 : * TelemetryEvents verbatim so an auth outcome is one queryable event across
4 : * every host. The package never calls a telemetry API itself; call sites
5 : * stay host-specific.
6 : */
7 : import { z } from 'zod'
8 :
9 : import type {
10 : WebSessionBootstrapEvent,
11 : WebSessionIdentityOptions
12 : } from './core/webSessionIdentity'
13 : import type { SsoErrorCode } from './sso'
14 :
15 2356 : export const SESSION_TELEMETRY_EVENT = {
16 : refreshSucceeded: 'auth.unified.refresh.succeeded',
17 : refreshFailed: 'auth.unified.refresh.failed',
18 : bootstrap: 'session_bootstrap',
19 : signedOutRemotely: 'session_signed_out_remotely'
20 : } as const
21 :
22 : export type WebSessionTelemetryEvent =
23 : | {
24 : readonly name: typeof SESSION_TELEMETRY_EVENT.bootstrap
25 : readonly properties: WebSessionBootstrapEvent
26 : }
27 : | {
28 : readonly name: typeof SESSION_TELEMETRY_EVENT.signedOutRemotely
29 : readonly properties: { readonly origin: string }
30 : }
31 :
32 : /** The web-session identity's telemetry hooks, routed to one host sink. */
33 0 : export function webSessionTelemetryHooks(
34 : track: (event: WebSessionTelemetryEvent) => void
35 : ): Pick<WebSessionIdentityOptions, 'onBootstrap' | 'onSignedOutRemotely'> {
36 0 : return {
37 : onBootstrap: ({ outcome, origin }) =>
38 : track({
39 : name: SESSION_TELEMETRY_EVENT.bootstrap,
40 : properties: { outcome, origin }
41 : }),
42 : onSignedOutRemotely: ({ origin }) =>
43 : track({
44 : name: SESSION_TELEMETRY_EVENT.signedOutRemotely,
45 : properties: { origin }
46 : })
47 : }
48 : }
49 :
50 : /**
51 : * The cloud app's `billing.operation.*` events, emitted by the billing
52 : * operation lifecycle for every observed `billing_op_id` regardless of
53 : * which presentation settled it.
54 : */
55 2356 : export const BILLING_OPERATION_TELEMETRY_EVENT = {
56 : started: 'billing.operation.started',
57 : succeeded: 'billing.operation.succeeded',
58 : failed: 'billing.operation.failed',
59 : timeout: 'billing.operation.timeout'
60 : } as const
61 :
62 : /**
63 : * Payment friction the lifecycle observes inside one operation: a bank
64 : * challenge and its verdict, each retryable decline, and a hosted step the
65 : * customer was sent to and came back from.
66 : */
67 2356 : export const BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT = {
68 : challengeRequired: 'billing.checkout.challenge_required',
69 : challengeCompleted: 'billing.checkout.challenge_completed',
70 : challengeFailed: 'billing.checkout.challenge_failed',
71 : redirectStarted: 'billing.checkout.redirect_started',
72 : returned: 'billing.checkout.returned'
73 : } as const
74 :
75 2356 : export const AUTH_TELEMETRY_EVENT = {
76 : signUpOpened: 'app:user_sign_up_opened',
77 : authCompleted: 'app:user_auth_completed',
78 : authFailed: 'app:user_auth_failed'
79 : } as const
80 :
81 : export type AuthMethod = 'email' | 'google' | 'github'
82 :
83 : /** What the cloud app reports on every successful credential. */
84 : export interface AuthCompletedMetadata {
85 : method: AuthMethod
86 : is_new_user: boolean
87 : user_id: string
88 : email?: string
89 : }
90 :
91 : export type AuthFlowAction =
92 : | 'email_sign_in'
93 : | 'email_sign_up'
94 : | 'google_sign_in'
95 : | 'google_sign_up'
96 : | 'github_sign_in'
97 : | 'github_sign_up'
98 : | 'password_reset'
99 :
100 : export interface AuthErrorMetadata {
101 : error_code: string
102 : auth_action: AuthFlowAction
103 : }
104 :
105 2356 : export const SSO_TELEMETRY_EVENT = {
106 : requiredShown: 'app:sso_required_shown',
107 : continueClicked: 'app:sso_continue_clicked',
108 : signInFailed: 'app:sso_sign_in_failed',
109 : signInCompleted: 'app:sso_sign_in_completed',
110 : workspaceLanded: 'app:sso_workspace_landed'
111 : } as const
112 :
113 2356 : const SSO_SURFACES = [
114 : 'cloud_login',
115 : 'cloud_signup',
116 : 'cloud_customer_create',
117 : 'cloud_app',
118 : 'billing_web',
119 : 'platform',
120 : 'desktop',
121 : 'local_web'
122 : ] as const
123 :
124 : /** Where an SSO attempt started; `cloud_app` is the in-app dialog. */
125 : export type SsoSurface = (typeof SSO_SURFACES)[number]
126 :
127 : /** The refusal that showed the SSO-required screen. */
128 : export type SsoRequiredTrigger =
129 : | 'firebase_sign_in'
130 : | 'api_key'
131 : | 'customer_create'
132 : | 'session_refused'
133 : | 'session_expired'
134 :
135 : /**
136 : * `notice` waits for the person to continue; `redirect` sends them straight
137 : * to SSO, so no `sso_continue_clicked` follows.
138 : */
139 : export type SsoRequiredPresentation = 'notice' | 'redirect'
140 :
141 : export type SsoSignInFailureReason =
142 : | 'cancelled'
143 : | 'state_mismatch'
144 : | 'org_not_attached'
145 : | 'server_error'
146 : | 'network'
147 : | 'seat_limit_reached'
148 :
149 : interface SsoFlowProperties {
150 : readonly surface: SsoSurface
151 : readonly flow_id: string
152 : }
153 :
154 : /** IDs and enums only: never an email, a name or an organization name. */
155 : export type SsoTelemetryEvent =
156 : | {
157 : readonly name: typeof SSO_TELEMETRY_EVENT.requiredShown
158 : readonly properties: SsoFlowProperties & {
159 : readonly trigger: SsoRequiredTrigger
160 : readonly presentation: SsoRequiredPresentation
161 : }
162 : }
163 : | {
164 : readonly name: typeof SSO_TELEMETRY_EVENT.continueClicked
165 : readonly properties: SsoFlowProperties
166 : }
167 : | {
168 : readonly name: typeof SSO_TELEMETRY_EVENT.signInFailed
169 : readonly properties: SsoFlowProperties & {
170 : readonly reason: SsoSignInFailureReason
171 : readonly http_status?: number
172 : }
173 : }
174 : | {
175 : readonly name: typeof SSO_TELEMETRY_EVENT.signInCompleted
176 : readonly properties: SsoFlowProperties
177 : }
178 : | {
179 : readonly name: typeof SSO_TELEMETRY_EVENT.workspaceLanded
180 : readonly properties: SsoFlowProperties & {
181 : readonly landed_in_default_workspace: boolean
182 : }
183 : }
184 :
185 2356 : const SSO_FAILURE_REASON: Partial<
186 : Readonly<Record<SsoErrorCode, SsoSignInFailureReason>>
187 : > = {
188 : SSO_INVALID_STATE: 'state_mismatch',
189 : SSO_CONFIRM_EXPIRED: 'state_mismatch',
190 : SSO_ORG_NOT_ATTACHED: 'org_not_attached',
191 : SSO_ORG_MISMATCH: 'org_not_attached',
192 : SSO_SEAT_LIMIT_REACHED: 'seat_limit_reached'
193 : }
194 :
195 : /** Reduces an `?sso_error=` code to the reason telemetry reports. */
196 0 : export function ssoFailureReason(code: SsoErrorCode): SsoSignInFailureReason {
197 0 : return SSO_FAILURE_REASON[code] ?? 'server_error'
198 : }
199 :
200 : /** One SSO attempt; `flowId` joins its steps across the IdP redirect. */
201 : export interface SsoFlow {
202 : readonly flowId: string
203 : readonly surface: SsoSurface
204 : /** Set once the person chose to continue to SSO. */
205 : readonly continued?: boolean
206 : }
207 :
208 2356 : const SSO_FLOW_STORAGE_KEY = 'Comfy.Sso.TelemetryFlow'
209 :
210 2356 : const zSsoFlow = z.object({
211 : flowId: z.string().min(1),
212 : surface: z.enum(SSO_SURFACES),
213 : continued: z.boolean().optional()
214 : })
215 :
216 0 : function randomBytes(): Uint8Array {
217 0 : const bytes = new Uint8Array(16)
218 0 : try {
219 0 : return crypto.getRandomValues(bytes)
220 : } catch {
221 0 : return bytes.map(() => Math.floor(Math.random() * 256))
222 : }
223 : }
224 :
225 : /** `getRandomValues`, unlike `randomUUID`, also works outside a secure context. */
226 0 : function newFlowId(): string {
227 0 : return Array.from(randomBytes(), (byte) =>
228 : byte.toString(16).padStart(2, '0')
229 : ).join('')
230 : }
231 :
232 0 : export function createSsoFlow(surface: SsoSurface): SsoFlow {
233 0 : return { flowId: newFlowId(), surface }
234 : }
235 :
236 : /**
237 : * Keeps the current attempt in session storage across the redirect, and in
238 : * memory for this page when storage fails, so telemetry never fails a sign-in.
239 : */
240 2356 : export function createSsoFlowStore(storage: () => Storage) {
241 2356 : let inMemory: SsoFlow | undefined
242 :
243 1 : function readStored(): SsoFlow | undefined {
244 1 : try {
245 1 : const raw = storage().getItem(SSO_FLOW_STORAGE_KEY)
246 1 : if (raw === null) return undefined
247 0 : const parsed = zSsoFlow.safeParse(JSON.parse(raw))
248 1 : return parsed.success ? parsed.data : undefined
249 : } catch {
250 0 : return undefined
251 : }
252 : }
253 :
254 0 : function save(flow: SsoFlow): SsoFlow {
255 0 : inMemory = flow
256 0 : try {
257 0 : storage().setItem(SSO_FLOW_STORAGE_KEY, JSON.stringify(flow))
258 : } catch {
259 0 : return flow
260 : }
261 0 : return flow
262 : }
263 :
264 0 : function start(surface: SsoSurface, continued = false): SsoFlow {
265 0 : return save({ ...createSsoFlow(surface), ...(continued && { continued }) })
266 : }
267 :
268 1 : function current(): SsoFlow | undefined {
269 1 : return inMemory ?? readStored()
270 : }
271 :
272 : /** Marks the current attempt, or a new one from `surface`, as continued. */
273 0 : function markContinued(surface: SsoSurface): SsoFlow {
274 0 : return save({ ...(current() ?? createSsoFlow(surface)), continued: true })
275 : }
276 :
277 1 : function finish(): SsoFlow | undefined {
278 1 : const flow = current()
279 1 : inMemory = undefined
280 1 : try {
281 1 : storage().removeItem(SSO_FLOW_STORAGE_KEY)
282 : } catch {
283 0 : return flow
284 : }
285 1 : return flow
286 : }
287 :
288 : /** Drops an attempt the person never continued. */
289 0 : function abandon(): void {
290 0 : if (current()?.continued) return
291 0 : finish()
292 : }
293 :
294 2356 : return { start, current, markContinued, finish, abandon }
295 : }
296 :
297 2356 : export const ssoFlowStore = createSsoFlowStore(() => globalThis.sessionStorage)
|