Line data Source code
1 : /**
2 : * The billing transport: one request carrying the workspace session, with the
3 : * reactive 401 guard the cloud app installs on its billing axios client
4 : * (`attachUnifiedRemintInterceptor` in
5 : * src/platform/auth/unified/remintRetry.ts) — re-mint once, retry once, and
6 : * surface a persistent 401 unchanged. Keep the two in step.
7 : *
8 : * Two deliberate differences from that interceptor. It gates the retry on a
9 : * replayable body; here the gate is an idempotency key, because a billing
10 : * write that the backend does not deduplicate must never be replayed by the
11 : * client even when its body is replayable. And scope comes from the minted
12 : * credential rather than a request header: the workspace a request runs
13 : * against is the workspace its JWT was minted for, and a response that
14 : * arrives after the host moved to another workspace (or signed out) is
15 : * reported as SUPERSEDED instead of being handed to a caller that would
16 : * attribute it to the wrong account.
17 : */
18 : import type { SessionRequestOptions } from '#/core/session'
19 : import type {
20 : AccountCredential,
21 : SessionErrorCode,
22 : SessionFailure
23 : } from '#/core/sessionContracts'
24 : import type {
25 : BillingErrorCode,
26 : BillingFailure,
27 : BillingHttpResponse,
28 : BillingRequest,
29 : BillingResult,
30 : BillingSession,
31 : BillingTransport
32 : } from './billingContracts'
33 : import {
34 : DEFAULT_BILLING_TIMEOUT_MS,
35 : exchangeBillingRequest,
36 : startRequestBudget
37 : } from './transportExchange'
38 :
39 : export interface SessionBillingTransportOptions {
40 : readonly session: BillingSession
41 : /**
42 : * Resolves a route to an absolute URL. The cloud app's own resolver
43 : * (`workspaceApiUrl`) differs per distribution, so the host owns it.
44 : */
45 : readonly resolveUrl: (route: string) => string
46 : /** The workspace to mint for; absent resolves the personal workspace. */
47 : readonly workspaceId?: () => string | undefined
48 : readonly fetchImpl?: typeof fetch
49 : readonly defaultTimeoutMs?: number
50 : }
51 :
52 0 : function codeForSessionFailure(code: SessionErrorCode): BillingErrorCode {
53 0 : if (code === 'ACCESS_DENIED' || code === 'SSO_REQUIRED') {
54 0 : return 'ACCESS_DENIED'
55 : }
56 0 : if (code === 'WORKSPACE_NOT_FOUND') return 'NOT_FOUND'
57 0 : if (code === 'NOT_AUTHENTICATED' || code === 'INVALID_FIREBASE_TOKEN') {
58 0 : return 'NOT_AUTHENTICATED'
59 : }
60 0 : return 'REQUEST_FAILED'
61 : }
62 :
63 0 : function billingFailureForSession(failure: SessionFailure): BillingFailure {
64 0 : return {
65 : status: 'error',
66 : code: codeForSessionFailure(failure.code),
67 : ...(failure.httpStatus === undefined
68 : ? {}
69 : : { httpStatus: failure.httpStatus })
70 : }
71 : }
72 :
73 0 : export function createSessionBillingTransport(
74 : options: SessionBillingTransportOptions
75 : ): BillingTransport {
76 0 : const {
77 : session,
78 : resolveUrl,
79 : workspaceId,
80 : fetchImpl = fetch,
81 : defaultTimeoutMs = DEFAULT_BILLING_TIMEOUT_MS
82 : } = options
83 :
84 : /**
85 : * The identity and workspace a response is allowed to be attributed to.
86 : * A snapshot still minting or not yet settled is no evidence of a change,
87 : * so only a delivered sign-out or a different uid or workspace supersedes.
88 : */
89 0 : const superseded = (uid: string, workspace: string): boolean => {
90 0 : const snapshot = session.getSnapshot()
91 0 : if (snapshot.phase === 'signed-out') return true
92 0 : if (snapshot.user !== null && snapshot.user.uid !== uid) return true
93 0 : return (
94 : snapshot.session !== undefined &&
95 : snapshot.session.workspace.id !== workspace
96 : )
97 : }
98 :
99 0 : async function ensureBillingSession(
100 : mintOptions: SessionRequestOptions
101 : ): Promise<BillingResult<AccountCredential>> {
102 0 : const minted = await session.ensureFresh(undefined, {
103 : ...mintOptions,
104 : preserveCredentialOnTransientFailure: true
105 : })
106 0 : if (minted === undefined) {
107 0 : return { status: 'error', code: 'NOT_AUTHENTICATED' }
108 : }
109 0 : if (minted.status === 'error') return billingFailureForSession(minted)
110 0 : return { status: 'ok', value: minted.session }
111 : }
112 :
113 0 : function send(
114 : request: BillingRequest,
115 : token: string,
116 : signal: AbortSignal
117 : ): Promise<BillingResult<BillingHttpResponse>> {
118 0 : return exchangeBillingRequest(request, {
119 : fetchImpl,
120 : url: resolveUrl(request.route),
121 : signal,
122 : headers: { Authorization: `Bearer ${token}` }
123 : })
124 : }
125 :
126 0 : async function retryUnauthorized(
127 : request: BillingRequest,
128 : response: BillingHttpResponse,
129 : mintOptions: SessionRequestOptions & { readonly signal: AbortSignal },
130 : expectedUid: string,
131 : expectedWorkspace: string
132 : ): Promise<BillingResult<BillingHttpResponse>> {
133 0 : if (response.httpStatus !== 401) return { status: 'ok', value: response }
134 :
135 : const replayable =
136 : request.method === 'GET' || request.idempotencyKey !== undefined
137 0 : if (!replayable) {
138 0 : return {
139 : status: 'ok',
140 : value: { ...response, authenticationRetrySkipped: true }
141 : }
142 : }
143 :
144 0 : const reminted = await session.remint(undefined, mintOptions)
145 0 : if (reminted?.status !== 'ok') return { status: 'ok', value: response }
146 0 : if (
147 : reminted.session.uid !== expectedUid ||
148 : reminted.session.workspace.id !== expectedWorkspace
149 : ) {
150 0 : return { status: 'error', code: 'SUPERSEDED' }
151 : }
152 0 : return send(request, reminted.session.token, mintOptions.signal)
153 : }
154 :
155 0 : return async function transport(
156 : request: BillingRequest
157 : ): Promise<BillingResult<BillingHttpResponse>> {
158 0 : const timeoutMs = request.timeoutMs ?? defaultTimeoutMs
159 0 : const budget = startRequestBudget(request.signal, timeoutMs)
160 0 : const target = workspaceId?.()
161 0 : const mintOptions = {
162 : signal: budget.signal,
163 : timeoutMs,
164 : ...(target === undefined ? {} : { workspaceId: target })
165 : }
166 :
167 0 : try {
168 0 : const minted = await ensureBillingSession(mintOptions)
169 0 : if (minted.status === 'error') return minted
170 :
171 0 : const { uid } = minted.value
172 0 : const workspace = minted.value.workspace.id
173 0 : const firstAttempt = await send(
174 : request,
175 : minted.value.token,
176 : budget.signal
177 : )
178 0 : if (firstAttempt.status === 'error') return firstAttempt
179 :
180 0 : const finalAttempt = await retryUnauthorized(
181 : request,
182 : firstAttempt.value,
183 : mintOptions,
184 : uid,
185 : workspace
186 : )
187 0 : if (finalAttempt.status === 'error') return finalAttempt
188 :
189 0 : if (superseded(uid, workspace)) {
190 0 : return { status: 'error', code: 'SUPERSEDED' }
191 : }
192 :
193 0 : return finalAttempt
194 : } catch {
195 0 : return { status: 'error', code: 'REQUEST_FAILED' }
196 : } finally {
197 0 : budget.close()
198 : }
199 : }
200 : }
|