@returningai/react-native-widget-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/LICENSE +4 -0
- package/README.md +111 -0
- package/package.json +60 -0
- package/src/ReturningAIWidget.tsx +601 -0
- package/src/authentication/ReturningAIAccessTokenCache.ts +90 -0
- package/src/authentication/ReturningAIAuthenticationClient.ts +379 -0
- package/src/authentication/nonce.ts +26 -0
- package/src/authentication/sessionAuthClient.ts +35 -0
- package/src/authentication/types.ts +50 -0
- package/src/bridge/ReturningAIBridgeCodec.ts +452 -0
- package/src/bridge/ReturningAIBridgeIdentity.ts +87 -0
- package/src/configuration/ReturningAIFirstPaintColors.ts +46 -0
- package/src/configuration/ReturningAIWidgetConfiguration.ts +488 -0
- package/src/configuration/ReturningAIWidgetContent.ts +59 -0
- package/src/configuration/ReturningAIWidgetDescriptor.ts +54 -0
- package/src/configuration/ReturningAIWidgetDisplayOptions.ts +59 -0
- package/src/configuration/ReturningAIWidgetDomainKey.ts +44 -0
- package/src/configuration/ReturningAIWidgetEndpoints.ts +157 -0
- package/src/configuration/ReturningAIWidgetTheme.ts +25 -0
- package/src/configuration/urls.ts +133 -0
- package/src/controller/ReturningAIWidgetController.ts +149 -0
- package/src/controller/ReturningAIWidgetSessionSnapshot.ts +49 -0
- package/src/coordinator/ReturningAIWidgetCoordinator.ts +787 -0
- package/src/crypto/fillRandomBytes.ts +28 -0
- package/src/errors/ReturningAIWidgetError.ts +150 -0
- package/src/errors/json.ts +227 -0
- package/src/events/ReturningAIWidgetEvent.ts +131 -0
- package/src/index.ts +79 -0
- package/src/navigation/ReturningAINavigationPolicy.ts +89 -0
- package/src/packageInfo.ts +23 -0
- package/src/rendering/htmlRenderer.ts +351 -0
- package/src/rendering/theme.ts +57 -0
- package/src/webview/ReturningAIReactNativeWebViewDriver.ts +136 -0
- package/src/webview/ReturningAIWebViewDriver.ts +141 -0
- package/src/webview/bridgeBootstrap.ts +26 -0
- package/src/webview/errorPolicy.ts +27 -0
- package/src/webview/originWhitelist.ts +22 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Exchanges a host-provided embed token for a short-lived widget access token over HTTPS.
|
|
3
|
+
*
|
|
4
|
+
* Layer: authentication
|
|
5
|
+
* Role: POSTs to widget auth with nonce/timeout/cancel; parses access-token responses.
|
|
6
|
+
* Does not render HTML, talk to the WebView, or mint embed tokens for the host.
|
|
7
|
+
* Security: Embed token stays in JS memory and the HTTPS request body only; WebView gets the
|
|
8
|
+
* returned access token only. Never logs or surfaces embed tokens in errors.
|
|
9
|
+
* See also: types.ts, ReturningAIAccessTokenCache.ts, Flutter authentication client layer
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { type ReturningAIWidgetConfiguration } from "../configuration/ReturningAIWidgetConfiguration";
|
|
13
|
+
import { formatUrl, originOf } from "../configuration/urls";
|
|
14
|
+
import { encodeReturningAIJson } from "../errors/json";
|
|
15
|
+
import { redactReturningAISecrets } from "../errors/json";
|
|
16
|
+
import { ReturningAIWidgetError } from "../errors/ReturningAIWidgetError";
|
|
17
|
+
import { defaultNonce } from "./nonce";
|
|
18
|
+
import type {
|
|
19
|
+
ReturningAIAccessToken,
|
|
20
|
+
ReturningAIAuthenticationOperation,
|
|
21
|
+
ReturningAIClock,
|
|
22
|
+
ReturningAIEmbedTokenProvider,
|
|
23
|
+
ReturningAINonceFactory,
|
|
24
|
+
} from "./types";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Fetch-compatible transport used by the authentication client.
|
|
28
|
+
* Redirects must stay `manual` so opaque redirects can be rejected closed.
|
|
29
|
+
*/
|
|
30
|
+
export type ReturningAIFetch = (
|
|
31
|
+
input: string,
|
|
32
|
+
init: {
|
|
33
|
+
method: string;
|
|
34
|
+
headers: Record<string, string>;
|
|
35
|
+
body: string;
|
|
36
|
+
redirect: "manual";
|
|
37
|
+
signal: AbortSignal;
|
|
38
|
+
},
|
|
39
|
+
) => Promise<Response>;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* HTTPS client that exchanges a host embed token (or user identifiers) for a short-lived
|
|
43
|
+
* access token. Embed tokens never leave JS memory except as the JSON body of this POST.
|
|
44
|
+
*/
|
|
45
|
+
export class ReturningAIAuthenticationClient {
|
|
46
|
+
private readonly fetchImpl: ReturningAIFetch;
|
|
47
|
+
private readonly clock: ReturningAIClock;
|
|
48
|
+
private readonly nonceFactory: ReturningAINonceFactory;
|
|
49
|
+
private readonly responseLimitBytes: number;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Creates an authentication client.
|
|
53
|
+
* @param input.fetch - Optional fetch implementation (defaults to global `fetch`)
|
|
54
|
+
* @param input.clock - Clock for request timestamps
|
|
55
|
+
* @param input.nonceFactory - Nonce factory for request correlation
|
|
56
|
+
* @param input.responseLimitBytes - Max auth response body size (default 1 MiB)
|
|
57
|
+
*/
|
|
58
|
+
constructor(
|
|
59
|
+
input: {
|
|
60
|
+
fetch?: ReturningAIFetch;
|
|
61
|
+
clock?: ReturningAIClock;
|
|
62
|
+
nonceFactory?: ReturningAINonceFactory;
|
|
63
|
+
responseLimitBytes?: number;
|
|
64
|
+
} = {},
|
|
65
|
+
) {
|
|
66
|
+
this.fetchImpl = input.fetch ?? defaultFetch;
|
|
67
|
+
this.clock = input.clock ?? (() => Date.now());
|
|
68
|
+
this.nonceFactory = input.nonceFactory ?? defaultNonce;
|
|
69
|
+
this.responseLimitBytes = input.responseLimitBytes ?? 1024 * 1024;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Starts a cancelable serverless auth exchange for the validated configuration.
|
|
74
|
+
* @param configuration - Host widget configuration (validated before POST)
|
|
75
|
+
* @param embedTokenProvider - Optional host mint; required unless `userIdentifiers` are set
|
|
76
|
+
* @returns Operation whose `result` resolves to an access token
|
|
77
|
+
* @throws {ReturningAIWidgetError} asynchronously via `result` on provider/network/parse failure
|
|
78
|
+
*/
|
|
79
|
+
authenticate(
|
|
80
|
+
configuration: ReturningAIWidgetConfiguration,
|
|
81
|
+
embedTokenProvider?: ReturningAIEmbedTokenProvider,
|
|
82
|
+
): ReturningAIAuthenticationOperation {
|
|
83
|
+
const validated = configuration.validated();
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
let timedOut = false;
|
|
86
|
+
let cancelled = false;
|
|
87
|
+
const timeout = setTimeout(() => {
|
|
88
|
+
timedOut = true;
|
|
89
|
+
controller.abort();
|
|
90
|
+
}, validated.authenticationTimeoutMilliseconds);
|
|
91
|
+
timeout.unref?.();
|
|
92
|
+
|
|
93
|
+
const result = this.exchange(validated, embedTokenProvider, controller.signal, () => cancelled)
|
|
94
|
+
.catch((error: unknown) => {
|
|
95
|
+
if (error instanceof ReturningAIWidgetError) {
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
if (controller.signal.aborted) {
|
|
99
|
+
throw abortError(timedOut, cancelled);
|
|
100
|
+
}
|
|
101
|
+
throw new ReturningAIWidgetError({
|
|
102
|
+
code: "authenticationFailed",
|
|
103
|
+
message: "The authentication request failed.",
|
|
104
|
+
});
|
|
105
|
+
})
|
|
106
|
+
.finally(() => {
|
|
107
|
+
clearTimeout(timeout);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
result,
|
|
112
|
+
cancel() {
|
|
113
|
+
cancelled = true;
|
|
114
|
+
controller.abort();
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Performs the embed-token → access-token HTTPS exchange.
|
|
121
|
+
* Embed token is read from the provider and placed only in the JSON request body.
|
|
122
|
+
*/
|
|
123
|
+
private async exchange(
|
|
124
|
+
configuration: ReturningAIWidgetConfiguration,
|
|
125
|
+
embedTokenProvider: ReturningAIEmbedTokenProvider | undefined,
|
|
126
|
+
signal: AbortSignal,
|
|
127
|
+
isCancelled: () => boolean,
|
|
128
|
+
): Promise<ReturningAIAccessToken> {
|
|
129
|
+
throwIfAborted(signal, isCancelled);
|
|
130
|
+
let embedToken: string | undefined;
|
|
131
|
+
if (embedTokenProvider !== undefined) {
|
|
132
|
+
try {
|
|
133
|
+
embedToken = (await raceAbort(embedTokenProvider(), signal)).trim();
|
|
134
|
+
} catch {
|
|
135
|
+
if (signal.aborted) {
|
|
136
|
+
throw abortError(false, isCancelled());
|
|
137
|
+
}
|
|
138
|
+
throw new ReturningAIWidgetError({
|
|
139
|
+
code: "tokenProviderFailed",
|
|
140
|
+
message: "The embed-token provider failed.",
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (!embedToken) {
|
|
144
|
+
throw new ReturningAIWidgetError({
|
|
145
|
+
code: "tokenProviderFailed",
|
|
146
|
+
message: "The embed-token provider returned an empty token.",
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (!embedToken && Object.keys(configuration.userIdentifiers).length === 0) {
|
|
151
|
+
throw new ReturningAIWidgetError({
|
|
152
|
+
code: "invalidConfiguration",
|
|
153
|
+
message: "Authentication requires an embed-token provider or user identifiers.",
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
throwIfAborted(signal, isCancelled);
|
|
157
|
+
|
|
158
|
+
const authUrl = `${formatUrl(configuration.endpoints.widgetAuthUrl)}/${configuration.widget.authenticationWidgetId}/auth/serverless`;
|
|
159
|
+
const body: Record<string, unknown> = {
|
|
160
|
+
nonce: this.nonceFactory(),
|
|
161
|
+
timestamp: this.clock(),
|
|
162
|
+
widgetType: configuration.widget.widgetType,
|
|
163
|
+
};
|
|
164
|
+
// Embed token belongs only in this HTTPS body — never HTML, bridge, URL, or logs.
|
|
165
|
+
if (embedToken) {
|
|
166
|
+
body.embedToken = embedToken;
|
|
167
|
+
}
|
|
168
|
+
if (Object.keys(configuration.userIdentifiers).length > 0) {
|
|
169
|
+
body.userIdentifiers = configuration.userIdentifiers;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let response: Response;
|
|
173
|
+
try {
|
|
174
|
+
response = await this.fetchImpl(authUrl, {
|
|
175
|
+
method: "POST",
|
|
176
|
+
headers: {
|
|
177
|
+
"Content-Type": "application/json",
|
|
178
|
+
Origin: originOf(configuration.clientOrigin) ?? formatUrl(configuration.clientOrigin),
|
|
179
|
+
},
|
|
180
|
+
body: encodeReturningAIJson(body),
|
|
181
|
+
redirect: "manual",
|
|
182
|
+
signal,
|
|
183
|
+
});
|
|
184
|
+
} catch {
|
|
185
|
+
if (signal.aborted) {
|
|
186
|
+
throw abortError(false, isCancelled());
|
|
187
|
+
}
|
|
188
|
+
throw new ReturningAIWidgetError({
|
|
189
|
+
code: "authenticationFailed",
|
|
190
|
+
message: "The authentication request failed.",
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (isRedirect(response)) {
|
|
195
|
+
throw new ReturningAIWidgetError({
|
|
196
|
+
code: "authenticationFailed",
|
|
197
|
+
message: "Authentication redirects are not allowed.",
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const responseBody = await readLimited(response, this.responseLimitBytes, signal);
|
|
202
|
+
const decoded = decodeJsonObject(responseBody);
|
|
203
|
+
if (response.status < 200 || response.status >= 300) {
|
|
204
|
+
throw new ReturningAIWidgetError({
|
|
205
|
+
code: "authenticationFailed",
|
|
206
|
+
// Server text may reflect an opaque credential without a label.
|
|
207
|
+
message: "Authentication failed.",
|
|
208
|
+
statusCode: response.status,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
const accessToken = safeString(decoded.accessToken);
|
|
212
|
+
const ttlNumber = asFinitePositiveNumber(decoded.accessTokenTTL);
|
|
213
|
+
if (
|
|
214
|
+
accessToken === undefined ||
|
|
215
|
+
ttlNumber === undefined ||
|
|
216
|
+
ttlNumber < 0.5 ||
|
|
217
|
+
ttlNumber >= 2147483647.5
|
|
218
|
+
) {
|
|
219
|
+
throw new ReturningAIWidgetError({
|
|
220
|
+
code: "malformedAuthenticationResponse",
|
|
221
|
+
message: "Authentication response did not contain a valid token.",
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
value: accessToken,
|
|
226
|
+
expiresIn: Math.round(ttlNumber),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Default transport: global `fetch` with the auth client's init shape. */
|
|
232
|
+
function defaultFetch(
|
|
233
|
+
input: string,
|
|
234
|
+
init: {
|
|
235
|
+
method: string;
|
|
236
|
+
headers: Record<string, string>;
|
|
237
|
+
body: string;
|
|
238
|
+
redirect: "manual";
|
|
239
|
+
signal: AbortSignal;
|
|
240
|
+
},
|
|
241
|
+
): Promise<Response> {
|
|
242
|
+
return fetch(input, init);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** True when the response is an opaque or 3xx redirect (auth must fail closed). */
|
|
246
|
+
function isRedirect(response: Response): boolean {
|
|
247
|
+
return response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Bounds collected bytes for stream-capable transports. Buffered RN fetch can
|
|
252
|
+
* only be checked after allocation; this is not a native transport memory cap.
|
|
253
|
+
*/
|
|
254
|
+
async function readLimited(
|
|
255
|
+
response: Response,
|
|
256
|
+
limitBytes: number,
|
|
257
|
+
signal: AbortSignal,
|
|
258
|
+
): Promise<string> {
|
|
259
|
+
const oversized = () =>
|
|
260
|
+
new ReturningAIWidgetError({
|
|
261
|
+
code: "malformedAuthenticationResponse",
|
|
262
|
+
message: "Authentication response exceeded the size limit.",
|
|
263
|
+
});
|
|
264
|
+
const contentLength = response.headers.get("content-length");
|
|
265
|
+
if (contentLength !== null && Number(contentLength) > limitBytes) {
|
|
266
|
+
void response.body?.cancel().catch(() => undefined);
|
|
267
|
+
throw oversized();
|
|
268
|
+
}
|
|
269
|
+
if (typeof response.body?.getReader === "function") {
|
|
270
|
+
const bytes = new Uint8Array(limitBytes);
|
|
271
|
+
const reader = response.body.getReader();
|
|
272
|
+
let length = 0;
|
|
273
|
+
let complete = false;
|
|
274
|
+
try {
|
|
275
|
+
while (true) {
|
|
276
|
+
const next = await raceAbort(reader.read(), signal);
|
|
277
|
+
if (next.done) {
|
|
278
|
+
complete = true;
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
if (next.value.byteLength > limitBytes - length) throw oversized();
|
|
282
|
+
bytes.set(next.value, length);
|
|
283
|
+
length += next.value.byteLength;
|
|
284
|
+
}
|
|
285
|
+
return new TextDecoder().decode(bytes.subarray(0, length));
|
|
286
|
+
} finally {
|
|
287
|
+
if (!complete) void reader.cancel().catch(() => undefined);
|
|
288
|
+
reader.releaseLock();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const bytes = new Uint8Array(await raceAbort(response.arrayBuffer(), signal));
|
|
292
|
+
if (bytes.byteLength > limitBytes) throw oversized();
|
|
293
|
+
return new TextDecoder().decode(bytes);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Parses a JSON object body; arrays and scalars are treated as malformed. */
|
|
297
|
+
function decodeJsonObject(body: string): Record<string, unknown> {
|
|
298
|
+
try {
|
|
299
|
+
const parsed: unknown = JSON.parse(body);
|
|
300
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
301
|
+
throw new Error("not object");
|
|
302
|
+
}
|
|
303
|
+
return parsed as Record<string, unknown>;
|
|
304
|
+
} catch {
|
|
305
|
+
throw new ReturningAIWidgetError({
|
|
306
|
+
code: "malformedAuthenticationResponse",
|
|
307
|
+
message: "Authentication response was not valid JSON.",
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function asFinitePositiveNumber(value: unknown): number | undefined {
|
|
313
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
return value;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Returns a nonempty access-token field after the existing string normalization.
|
|
321
|
+
* Server failure messages and hints are never forwarded to host-visible errors.
|
|
322
|
+
*/
|
|
323
|
+
function safeString(value: unknown): string | undefined {
|
|
324
|
+
if (typeof value === "string" && value.trim().length > 0) {
|
|
325
|
+
return redactReturningAISecrets(value);
|
|
326
|
+
}
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Maps abort causes to typed timeout vs cancelled errors. */
|
|
331
|
+
function abortError(timedOut: boolean, cancelled: boolean): ReturningAIWidgetError {
|
|
332
|
+
if (timedOut) {
|
|
333
|
+
return new ReturningAIWidgetError({
|
|
334
|
+
code: "authenticationTimeout",
|
|
335
|
+
message: "Authentication timed out.",
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
if (cancelled) {
|
|
339
|
+
return new ReturningAIWidgetError({
|
|
340
|
+
code: "cancelled",
|
|
341
|
+
message: "Authentication was cancelled.",
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return new ReturningAIWidgetError({
|
|
345
|
+
code: "authenticationTimeout",
|
|
346
|
+
message: "Authentication timed out.",
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function throwIfAborted(signal: AbortSignal, isCancelled: () => boolean): void {
|
|
351
|
+
if (signal.aborted) {
|
|
352
|
+
throw abortError(false, isCancelled());
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Races a promise against AbortSignal so provider awaits respect auth cancellation.
|
|
358
|
+
*/
|
|
359
|
+
function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
360
|
+
if (signal.aborted) {
|
|
361
|
+
return Promise.reject(new DOMException("Aborted", "AbortError"));
|
|
362
|
+
}
|
|
363
|
+
return new Promise<T>((resolve, reject) => {
|
|
364
|
+
const onAbort = () => {
|
|
365
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
366
|
+
};
|
|
367
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
368
|
+
promise.then(
|
|
369
|
+
(value) => {
|
|
370
|
+
signal.removeEventListener("abort", onAbort);
|
|
371
|
+
resolve(value);
|
|
372
|
+
},
|
|
373
|
+
(error: unknown) => {
|
|
374
|
+
signal.removeEventListener("abort", onAbort);
|
|
375
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
376
|
+
},
|
|
377
|
+
);
|
|
378
|
+
});
|
|
379
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Builds a UUID-shaped nonce for authentication request correlation.
|
|
3
|
+
*
|
|
4
|
+
* Layer: authentication
|
|
5
|
+
* Role: Fills 16 secure random bytes and formats them as a UUID string for auth POSTs.
|
|
6
|
+
* Does not send network requests or validate server responses.
|
|
7
|
+
* See also: ReturningAIAuthenticationClient.ts, crypto/fillRandomBytes.ts
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { fillRandomBytes } from "../crypto/fillRandomBytes";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Builds a UUID v4-shaped nonce from cryptographically secure random bytes.
|
|
14
|
+
* Used only as the `nonce` field on the serverless auth POST body.
|
|
15
|
+
* @returns Hyphenated hex UUID string
|
|
16
|
+
* @throws {ReturningAIWidgetError} when Web Crypto `getRandomValues` is unavailable
|
|
17
|
+
*/
|
|
18
|
+
export function defaultNonce(): string {
|
|
19
|
+
const bytes = new Uint8Array(16);
|
|
20
|
+
fillRandomBytes(bytes);
|
|
21
|
+
// Force UUID version (4) and variant (RFC 4122) bits without reducing entropy elsewhere.
|
|
22
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
23
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
24
|
+
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
25
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
26
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Session-scoped auth client reuse across fingerprint recreates.
|
|
3
|
+
*
|
|
4
|
+
* Layer: authentication
|
|
5
|
+
* Role: Keeps one ReturningAIAuthenticationClient for the lifetime of a widget
|
|
6
|
+
* mount (or until the host `fetch` identity changes). Mirrors Android/iOS
|
|
7
|
+
* session-owned HTTP stacks — RN has no connection pool, but avoids allocating
|
|
8
|
+
* a new auth client on every chip / config recreate.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
ReturningAIAuthenticationClient,
|
|
13
|
+
type ReturningAIFetch,
|
|
14
|
+
} from "./ReturningAIAuthenticationClient";
|
|
15
|
+
|
|
16
|
+
/** Mutable holder for the session-owned auth client + the `fetch` it was built with. */
|
|
17
|
+
export type ReturningAISessionAuthClientState = {
|
|
18
|
+
client: ReturningAIAuthenticationClient | null;
|
|
19
|
+
fetch: ReturningAIFetch | undefined;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Returns a stable auth client for the current widget mount.
|
|
24
|
+
* Recreates only when `fetch` identity changes or no client exists yet.
|
|
25
|
+
*/
|
|
26
|
+
export function resolveSessionAuthClient(
|
|
27
|
+
state: ReturningAISessionAuthClientState,
|
|
28
|
+
fetch: ReturningAIFetch | undefined,
|
|
29
|
+
): ReturningAIAuthenticationClient {
|
|
30
|
+
if (state.client === null || state.fetch !== fetch) {
|
|
31
|
+
state.client = new ReturningAIAuthenticationClient({ fetch });
|
|
32
|
+
state.fetch = fetch;
|
|
33
|
+
}
|
|
34
|
+
return state.client;
|
|
35
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Shared authentication type aliases used across the auth and coordinator layers.
|
|
3
|
+
*
|
|
4
|
+
* Layer: authentication
|
|
5
|
+
* Role: Defines embed-token provider, clock, nonce factory, access-token shape, and cancelable
|
|
6
|
+
* auth operation. Does not implement exchange or caching logic.
|
|
7
|
+
* Security: Embed tokens are obtained via ReturningAIEmbedTokenProvider and must stay in JS memory.
|
|
8
|
+
* See also: ReturningAIAuthenticationClient.ts, ReturningAIAccessTokenCache.ts
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Host-supplied async factory that mints a short-lived embed token for serverless auth.
|
|
13
|
+
* The returned string must stay in JS memory and HTTPS request bodies only — never HTML, bridge,
|
|
14
|
+
* URLs, logs, or public errors. The WebView receives only the exchanged access token.
|
|
15
|
+
*/
|
|
16
|
+
export type ReturningAIEmbedTokenProvider = () => Promise<string>;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Millisecond clock used for auth timestamps, timeouts, and access-token cache expiry.
|
|
20
|
+
* @returns Epoch milliseconds (typically `Date.now()`)
|
|
21
|
+
*/
|
|
22
|
+
export type ReturningAIClock = () => number;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Factory that produces a unique nonce string for each authentication POST.
|
|
26
|
+
* @returns A nonce suitable for request correlation (UUID-shaped by default)
|
|
27
|
+
*/
|
|
28
|
+
export type ReturningAINonceFactory = () => string;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Short-lived widget access token returned by the serverless auth exchange.
|
|
32
|
+
* This is the only credential shape delivered to the WebView (`token` + `expiresIn`).
|
|
33
|
+
*/
|
|
34
|
+
export type ReturningAIAccessToken = {
|
|
35
|
+
/** Opaque access token value for the widget runtime (not an embed token). */
|
|
36
|
+
readonly value: string;
|
|
37
|
+
/** Time-to-live in whole seconds from issuance. */
|
|
38
|
+
readonly expiresIn: number;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Cancelable in-flight authentication operation.
|
|
43
|
+
* Call `cancel()` to abort the HTTPS exchange and reject pending waiters.
|
|
44
|
+
*/
|
|
45
|
+
export type ReturningAIAuthenticationOperation = {
|
|
46
|
+
/** Resolves with the access token or rejects with {@link ReturningAIWidgetError}. */
|
|
47
|
+
result: Promise<ReturningAIAccessToken>;
|
|
48
|
+
/** Aborts the exchange; subsequent results surface as `cancelled`. */
|
|
49
|
+
cancel(): void;
|
|
50
|
+
};
|