@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,452 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Encodes and decodes ReturningAI WebView bridge message envelopes and bodies.
|
|
3
|
+
*
|
|
4
|
+
* Layer: bridge
|
|
5
|
+
* Role: Parses authenticate / host-callback / event messages; validates shape, identity, and
|
|
6
|
+
* callback allowlists; builds reply payloads. Does not post to the WebView or call host handlers.
|
|
7
|
+
* Security: Rejects oversized/malformed JSON; never places embed tokens in bridge traffic;
|
|
8
|
+
* redacts secrets in protocol error paths.
|
|
9
|
+
* See also: ReturningAIBridgeIdentity.ts; Flutter packages/flutter/lib/src/bridge/bridge_codec.dart
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
encodeReturningAIJson,
|
|
14
|
+
redactReturningAISecrets,
|
|
15
|
+
validateReturningAIJsonValue,
|
|
16
|
+
type ReturningAIJsonValue,
|
|
17
|
+
} from "../errors/json";
|
|
18
|
+
import { ReturningAIWidgetError } from "../errors/ReturningAIWidgetError";
|
|
19
|
+
import {
|
|
20
|
+
ReturningAIHostCallbackRequest,
|
|
21
|
+
ReturningAIWidgetCustomEvent,
|
|
22
|
+
ReturningAIWidgetErrorEvent,
|
|
23
|
+
type ReturningAIWidgetEvent,
|
|
24
|
+
ReturningAIWidgetExternalNavigationRequested,
|
|
25
|
+
ReturningAIWidgetHeightChanged,
|
|
26
|
+
ReturningAIWidgetLoggedOut,
|
|
27
|
+
ReturningAIWidgetMounted,
|
|
28
|
+
ReturningAIWidgetReady,
|
|
29
|
+
ReturningAIWidgetSessionExpired,
|
|
30
|
+
} from "../events/ReturningAIWidgetEvent";
|
|
31
|
+
import { type ReturningAIBridgeIdentity } from "./ReturningAIBridgeIdentity";
|
|
32
|
+
|
|
33
|
+
/** Standard Base64 alphabet used for bridge response scripts. */
|
|
34
|
+
const STANDARD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
35
|
+
/** Default inbound message / outbound response size limit (256 KiB). */
|
|
36
|
+
const DEFAULT_LIMIT_BYTES = 256 * 1024;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Base class for decoded inbound bridge messages.
|
|
40
|
+
* Correlated requests carry a `requestId`; fire-and-forget events do not.
|
|
41
|
+
*/
|
|
42
|
+
export abstract class ReturningAIBridgeMessage {
|
|
43
|
+
/** Correlation id for request/response pairs, when present. */
|
|
44
|
+
readonly requestId: string | undefined;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param requestId - Optional correlation id from the envelope
|
|
48
|
+
*/
|
|
49
|
+
protected constructor(requestId?: string) {
|
|
50
|
+
this.requestId = requestId;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Widget requested a native serverless auth exchange via the bridge.
|
|
56
|
+
* The coordinator answers with `{ token, expiresIn }` — never an embed token.
|
|
57
|
+
*/
|
|
58
|
+
export class ReturningAIAuthenticateRequest extends ReturningAIBridgeMessage {
|
|
59
|
+
/**
|
|
60
|
+
* @param requestId - Correlation id reserved for the auth reply
|
|
61
|
+
*/
|
|
62
|
+
constructor(requestId: string) {
|
|
63
|
+
super(requestId);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Widget invoked an allowlisted host callback over the bridge.
|
|
69
|
+
*/
|
|
70
|
+
export class ReturningAIHostCallbackBridgeRequest extends ReturningAIBridgeMessage {
|
|
71
|
+
/** Decoded allowlisted callback request (name + JSON payload). */
|
|
72
|
+
readonly request: ReturningAIHostCallbackRequest;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @param requestId - Correlation id reserved for the callback reply
|
|
76
|
+
* @param request - Allowlisted host callback request
|
|
77
|
+
*/
|
|
78
|
+
constructor(requestId: string, request: ReturningAIHostCallbackRequest) {
|
|
79
|
+
super(requestId);
|
|
80
|
+
this.request = request;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Fire-and-forget widget event decoded from a bridge body with `name`/`detail`.
|
|
86
|
+
*/
|
|
87
|
+
export class ReturningAIEventBridgeMessage extends ReturningAIBridgeMessage {
|
|
88
|
+
/** Typed widget event mapped from the bridge event name. */
|
|
89
|
+
readonly event: ReturningAIWidgetEvent;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @param event - Typed event instance
|
|
93
|
+
*/
|
|
94
|
+
constructor(event: ReturningAIWidgetEvent) {
|
|
95
|
+
super(undefined);
|
|
96
|
+
this.event = event;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Encodes/decodes bridge envelopes for one widget session identity.
|
|
102
|
+
* Rejects oversized or malformed JSON; drops envelopes with mismatched identity;
|
|
103
|
+
* never places embed tokens in bridge traffic.
|
|
104
|
+
*/
|
|
105
|
+
export class ReturningAIBridgeCodec {
|
|
106
|
+
private readonly identity: ReturningAIBridgeIdentity;
|
|
107
|
+
private readonly callbackNames: ReadonlySet<string>;
|
|
108
|
+
private readonly messageLimitBytes: number;
|
|
109
|
+
private readonly responseLimitBytes: number;
|
|
110
|
+
private readonly activeRequestIds = new Set<string>();
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Creates a codec bound to one bridge identity and callback allowlist.
|
|
114
|
+
* @param input.identity - Session instanceId + bridgeToken
|
|
115
|
+
* @param input.callbackNames - Allowlisted host callback names
|
|
116
|
+
* @param input.messageLimitBytes - Max inbound UTF-8 byte length
|
|
117
|
+
* @param input.responseLimitBytes - Max outbound Base64 response length
|
|
118
|
+
*/
|
|
119
|
+
constructor(input: {
|
|
120
|
+
identity: ReturningAIBridgeIdentity;
|
|
121
|
+
callbackNames?: Iterable<string>;
|
|
122
|
+
messageLimitBytes?: number;
|
|
123
|
+
responseLimitBytes?: number;
|
|
124
|
+
}) {
|
|
125
|
+
this.identity = input.identity;
|
|
126
|
+
this.callbackNames = new Set(input.callbackNames ?? []);
|
|
127
|
+
this.messageLimitBytes = input.messageLimitBytes ?? DEFAULT_LIMIT_BYTES;
|
|
128
|
+
this.responseLimitBytes = input.responseLimitBytes ?? DEFAULT_LIMIT_BYTES;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Decodes a raw JSON bridge message from the WebView.
|
|
133
|
+
* @param raw - JSON string from `onMessage`
|
|
134
|
+
* @returns Typed message, or `undefined` when identity mismatches (stale session)
|
|
135
|
+
* @throws {ReturningAIWidgetError} on size/shape/protocol/allowlist failures
|
|
136
|
+
*/
|
|
137
|
+
decode(raw: string): ReturningAIBridgeMessage | undefined {
|
|
138
|
+
if (utf8ByteLength(raw) > this.messageLimitBytes) {
|
|
139
|
+
throw protocol("Bridge message exceeded the size limit.");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const envelope = decodeObject(raw);
|
|
143
|
+
requireExactKeys(
|
|
144
|
+
envelope,
|
|
145
|
+
["version", "instanceId", "bridgeToken", "body"],
|
|
146
|
+
["requestId"],
|
|
147
|
+
"Bridge envelope shape was invalid.",
|
|
148
|
+
);
|
|
149
|
+
if (!isVersionOne(envelope.version)) {
|
|
150
|
+
throw protocol("Bridge envelope did not match this widget session.");
|
|
151
|
+
}
|
|
152
|
+
if (
|
|
153
|
+
envelope.instanceId !== this.identity.instanceId ||
|
|
154
|
+
envelope.bridgeToken !== this.identity.bridgeToken
|
|
155
|
+
) {
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const body = envelope.body;
|
|
160
|
+
if (!isPlainObject(body)) {
|
|
161
|
+
throw protocol("Bridge body was malformed.");
|
|
162
|
+
}
|
|
163
|
+
const requestId = envelope.requestId;
|
|
164
|
+
|
|
165
|
+
if (body.type === "authenticate") {
|
|
166
|
+
requireExactKeys(body, ["type"], [], "Authentication bridge body was malformed.");
|
|
167
|
+
const id = this.reserveRequestId(requestId);
|
|
168
|
+
return new ReturningAIAuthenticateRequest(id);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (Object.prototype.hasOwnProperty.call(body, "callbackName")) {
|
|
172
|
+
requireExactKeys(
|
|
173
|
+
body,
|
|
174
|
+
["callbackName", "payload"],
|
|
175
|
+
[],
|
|
176
|
+
"Callback bridge body was malformed.",
|
|
177
|
+
);
|
|
178
|
+
const callbackName = body.callbackName;
|
|
179
|
+
if (typeof callbackName !== "string" || !this.callbackNames.has(callbackName)) {
|
|
180
|
+
throw new ReturningAIWidgetError({
|
|
181
|
+
code: "callbackFailed",
|
|
182
|
+
message: "The widget requested a callback that is not allowlisted.",
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
const payload = validateReturningAIJsonValue(body.payload);
|
|
186
|
+
const id = this.reserveRequestId(requestId);
|
|
187
|
+
return new ReturningAIHostCallbackBridgeRequest(
|
|
188
|
+
id,
|
|
189
|
+
new ReturningAIHostCallbackRequest(callbackName, payload),
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (Object.prototype.hasOwnProperty.call(body, "name")) {
|
|
194
|
+
requireExactKeys(body, ["name", "detail"], [], "Event bridge body was malformed.");
|
|
195
|
+
if (requestId !== undefined) {
|
|
196
|
+
throw protocol("Widget events cannot include request identifiers.");
|
|
197
|
+
}
|
|
198
|
+
return new ReturningAIEventBridgeMessage(eventFromBody(body));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
throw protocol("Bridge body type is unknown.");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Releases a reserved request id after the reply is sent (or abandoned).
|
|
206
|
+
* @param requestId - Previously reserved correlation id
|
|
207
|
+
*/
|
|
208
|
+
releaseRequestId(requestId: string): void {
|
|
209
|
+
this.activeRequestIds.delete(requestId);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Builds an injectable success reply script for a correlated request.
|
|
214
|
+
* Auth replies must use `{ token, expiresIn }` (access token only).
|
|
215
|
+
* @param requestId - Correlation id
|
|
216
|
+
* @param value - JSON-compatible success payload
|
|
217
|
+
* @returns `window.__returningAIResolveBridge(...)` script
|
|
218
|
+
* @throws {ReturningAIWidgetError} when the payload or encoded size is invalid
|
|
219
|
+
*/
|
|
220
|
+
successResponseScript(requestId: string, value: unknown): string {
|
|
221
|
+
const validated = validateReturningAIJsonValue(value);
|
|
222
|
+
return this.responseScript({
|
|
223
|
+
version: 1,
|
|
224
|
+
requestId,
|
|
225
|
+
ok: true,
|
|
226
|
+
value: validated,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Builds an injectable error reply script for a correlated request.
|
|
232
|
+
* @param requestId - Correlation id
|
|
233
|
+
* @param error - Typed error whose message must not contain credentials
|
|
234
|
+
* @returns `window.__returningAIResolveBridge(...)` script
|
|
235
|
+
*/
|
|
236
|
+
errorResponseScript(requestId: string, error: ReturningAIWidgetError): string {
|
|
237
|
+
return this.responseScript({
|
|
238
|
+
version: 1,
|
|
239
|
+
requestId,
|
|
240
|
+
ok: false,
|
|
241
|
+
error: error.message,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Validates and reserves a printable ASCII request id; rejects duplicates.
|
|
247
|
+
* Prevents replay of the same correlation id within a session generation.
|
|
248
|
+
*/
|
|
249
|
+
private reserveRequestId(requestId: unknown): string {
|
|
250
|
+
if (
|
|
251
|
+
typeof requestId !== "string" ||
|
|
252
|
+
requestId.length === 0 ||
|
|
253
|
+
requestId.length > 128 ||
|
|
254
|
+
[...requestId].some((character) => {
|
|
255
|
+
const code = character.charCodeAt(0);
|
|
256
|
+
return code < 0x20 || code > 0x7e;
|
|
257
|
+
})
|
|
258
|
+
) {
|
|
259
|
+
throw protocol("Bridge request identifier was invalid.");
|
|
260
|
+
}
|
|
261
|
+
if (this.activeRequestIds.has(requestId)) {
|
|
262
|
+
throw protocol("Bridge request identifier was duplicated.");
|
|
263
|
+
}
|
|
264
|
+
if (this.activeRequestIds.size >= 64) {
|
|
265
|
+
throw protocol("Too many pending bridge requests.");
|
|
266
|
+
}
|
|
267
|
+
this.activeRequestIds.add(requestId);
|
|
268
|
+
return requestId;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Base64-encodes a response object into the injectable resolve script. */
|
|
272
|
+
private responseScript(response: Record<string, ReturningAIJsonValue>): string {
|
|
273
|
+
const encoded = encodeBase64(new TextEncoder().encode(encodeReturningAIJson(response)));
|
|
274
|
+
if (encoded.length > this.responseLimitBytes) {
|
|
275
|
+
throw protocol("Bridge response exceeded the size limit.");
|
|
276
|
+
}
|
|
277
|
+
return `window.__returningAIResolveBridge("${encoded}");`;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Maps a bridge event body (`name`/`detail`) onto a typed event subclass. */
|
|
282
|
+
function eventFromBody(body: Record<string, unknown>): ReturningAIWidgetEvent {
|
|
283
|
+
const name = body.name;
|
|
284
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
285
|
+
throw protocol("Widget event did not include a valid name.");
|
|
286
|
+
}
|
|
287
|
+
const detail = validateReturningAIJsonValue(body.detail);
|
|
288
|
+
switch (name) {
|
|
289
|
+
case "rai-mounted":
|
|
290
|
+
return new ReturningAIWidgetMounted();
|
|
291
|
+
case "rai-ready":
|
|
292
|
+
return new ReturningAIWidgetReady();
|
|
293
|
+
case "rai-logout":
|
|
294
|
+
return new ReturningAIWidgetLoggedOut();
|
|
295
|
+
case "rai-session-expired":
|
|
296
|
+
return new ReturningAIWidgetSessionExpired();
|
|
297
|
+
case "rai-height-change": {
|
|
298
|
+
const height = heightFromDetail(detail);
|
|
299
|
+
if (height === undefined || !Number.isFinite(height) || height <= 0) {
|
|
300
|
+
throw protocol("Height-change event did not contain a valid height.");
|
|
301
|
+
}
|
|
302
|
+
return new ReturningAIWidgetHeightChanged(height);
|
|
303
|
+
}
|
|
304
|
+
case "rai-error":
|
|
305
|
+
case "javascript-error":
|
|
306
|
+
return new ReturningAIWidgetErrorEvent(
|
|
307
|
+
new ReturningAIWidgetError({
|
|
308
|
+
code: "javaScriptRuntimeFailed",
|
|
309
|
+
message: messageFromDetail(detail),
|
|
310
|
+
}),
|
|
311
|
+
);
|
|
312
|
+
case "rai-external-navigation": {
|
|
313
|
+
const uri = uriFromDetail(detail);
|
|
314
|
+
if (uri === undefined) {
|
|
315
|
+
throw new ReturningAIWidgetError({
|
|
316
|
+
code: "navigationRejected",
|
|
317
|
+
message: "External navigation event did not include a valid URL.",
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
return new ReturningAIWidgetExternalNavigationRequested(uri);
|
|
321
|
+
}
|
|
322
|
+
default:
|
|
323
|
+
return new ReturningAIWidgetCustomEvent(name, detail);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Extracts a height number from a raw or `{ height }` detail payload. */
|
|
328
|
+
function heightFromDetail(detail: ReturningAIJsonValue): number | undefined {
|
|
329
|
+
if (typeof detail === "number") {
|
|
330
|
+
return detail;
|
|
331
|
+
}
|
|
332
|
+
if (isPlainObject(detail)) {
|
|
333
|
+
const value = detail.height;
|
|
334
|
+
if (typeof value === "number") {
|
|
335
|
+
return value;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return undefined;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Extracts and redacts an error message from a detail payload. */
|
|
342
|
+
function messageFromDetail(detail: ReturningAIJsonValue): string {
|
|
343
|
+
if (typeof detail === "string" && detail.trim().length > 0) {
|
|
344
|
+
return redactReturningAISecrets(detail);
|
|
345
|
+
}
|
|
346
|
+
if (isPlainObject(detail)) {
|
|
347
|
+
const value = detail.message;
|
|
348
|
+
if (typeof value === "string" && value.trim().length > 0) {
|
|
349
|
+
return redactReturningAISecrets(value);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return "The widget reported a JavaScript error.";
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Parses a URL from a string or `{ url }` detail payload. */
|
|
356
|
+
function uriFromDetail(detail: ReturningAIJsonValue): URL | undefined {
|
|
357
|
+
const raw =
|
|
358
|
+
typeof detail === "string"
|
|
359
|
+
? detail
|
|
360
|
+
: isPlainObject(detail) && typeof detail.url === "string"
|
|
361
|
+
? detail.url
|
|
362
|
+
: undefined;
|
|
363
|
+
if (raw === undefined) {
|
|
364
|
+
return undefined;
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
return new URL(raw);
|
|
368
|
+
} catch {
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function isVersionOne(value: unknown): boolean {
|
|
374
|
+
return typeof value === "number" && value === 1;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Factory for `bridgeProtocolFailed` errors. */
|
|
378
|
+
function protocol(message: string): ReturningAIWidgetError {
|
|
379
|
+
return new ReturningAIWidgetError({
|
|
380
|
+
code: "bridgeProtocolFailed",
|
|
381
|
+
message,
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Parses a plain JSON object; rejects arrays and non-objects. */
|
|
386
|
+
function decodeObject(raw: string): Record<string, unknown> {
|
|
387
|
+
try {
|
|
388
|
+
const decoded: unknown = JSON.parse(raw);
|
|
389
|
+
if (isPlainObject(decoded)) {
|
|
390
|
+
return decoded;
|
|
391
|
+
}
|
|
392
|
+
} catch (error) {
|
|
393
|
+
if (error instanceof ReturningAIWidgetError) {
|
|
394
|
+
throw error;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
throw protocol("Bridge message was not valid JSON.");
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Ensures an object has every required key and no keys outside required+optional.
|
|
402
|
+
* Fail-closed shape check for bridge envelopes and bodies.
|
|
403
|
+
*/
|
|
404
|
+
function requireExactKeys(
|
|
405
|
+
value: Record<string, unknown>,
|
|
406
|
+
required: string[],
|
|
407
|
+
optional: string[],
|
|
408
|
+
message: string,
|
|
409
|
+
): void {
|
|
410
|
+
const allowed = new Set([...required, ...optional]);
|
|
411
|
+
const keys = Object.keys(value);
|
|
412
|
+
if (
|
|
413
|
+
!required.every((key) => Object.prototype.hasOwnProperty.call(value, key)) ||
|
|
414
|
+
keys.some((key) => !allowed.has(key))
|
|
415
|
+
) {
|
|
416
|
+
throw protocol(message);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
421
|
+
return (
|
|
422
|
+
typeof value === "object" &&
|
|
423
|
+
value !== null &&
|
|
424
|
+
!Array.isArray(value) &&
|
|
425
|
+
Object.getPrototypeOf(value) === Object.prototype
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function utf8ByteLength(value: string): number {
|
|
430
|
+
return new TextEncoder().encode(value).length;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Encodes bytes as standard Base64 (with padding) for bridge response scripts.
|
|
435
|
+
* @param bytes - UTF-8 payload bytes
|
|
436
|
+
* @returns Base64 string
|
|
437
|
+
*/
|
|
438
|
+
export function encodeBase64(bytes: Uint8Array): string {
|
|
439
|
+
const chunks: string[] = [];
|
|
440
|
+
for (let index = 0; index < bytes.length; index += 3) {
|
|
441
|
+
const remaining = bytes.length - index;
|
|
442
|
+
const b0 = bytes[index] ?? 0;
|
|
443
|
+
const b1 = remaining > 1 ? (bytes[index + 1] ?? 0) : 0;
|
|
444
|
+
const b2 = remaining > 2 ? (bytes[index + 2] ?? 0) : 0;
|
|
445
|
+
const triple = (b0 << 16) | (b1 << 8) | b2;
|
|
446
|
+
chunks.push(STANDARD_ALPHABET[(triple >> 18) & 63] ?? "");
|
|
447
|
+
chunks.push(STANDARD_ALPHABET[(triple >> 12) & 63] ?? "");
|
|
448
|
+
chunks.push(remaining > 1 ? (STANDARD_ALPHABET[(triple >> 6) & 63] ?? "") : "=");
|
|
449
|
+
chunks.push(remaining > 2 ? (STANDARD_ALPHABET[triple & 63] ?? "") : "=");
|
|
450
|
+
}
|
|
451
|
+
return chunks.join("");
|
|
452
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Generates per-instance bridge identity (instanceId + bridgeToken) for envelope auth.
|
|
3
|
+
*
|
|
4
|
+
* Layer: bridge
|
|
5
|
+
* Role: Creates cryptographically random identity values and the RN bridge channel name constant.
|
|
6
|
+
* Does not encode/decode message bodies or validate inbound envelopes.
|
|
7
|
+
* Security: Tokens are random CSPRNG values used only to bind bridge messages to this instance.
|
|
8
|
+
* See also: ReturningAIBridgeCodec.ts, crypto/fillRandomBytes.ts
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { fillRandomBytes } from "../crypto/fillRandomBytes";
|
|
12
|
+
|
|
13
|
+
/** URL-safe Base64 alphabet without padding (RFC 4648 §5). */
|
|
14
|
+
const URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Per-widget-session bridge identity embedded in the HTML shell and verified on every inbound envelope.
|
|
18
|
+
* `bridgeToken` is not an embed or access token — it only binds bridge traffic to this instance.
|
|
19
|
+
*/
|
|
20
|
+
export class ReturningAIBridgeIdentity {
|
|
21
|
+
/** Random instance id placed in shell HTML and required on every envelope. */
|
|
22
|
+
readonly instanceId: string;
|
|
23
|
+
/** Random bridge token that must match the session; never an embed/access credential. */
|
|
24
|
+
readonly bridgeToken: string;
|
|
25
|
+
|
|
26
|
+
private constructor(instanceId: string, bridgeToken: string) {
|
|
27
|
+
this.instanceId = instanceId;
|
|
28
|
+
this.bridgeToken = bridgeToken;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Creates a fresh identity from CSPRNG bytes.
|
|
33
|
+
* @returns New identity for one widget session
|
|
34
|
+
* @throws {ReturningAIWidgetError} when secure random is unavailable
|
|
35
|
+
*/
|
|
36
|
+
static generate(): ReturningAIBridgeIdentity {
|
|
37
|
+
return new ReturningAIBridgeIdentity(randomBase64Url(), randomBase64Url());
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Builds a deterministic identity for tests.
|
|
42
|
+
* @param instanceId - Fixed instance id
|
|
43
|
+
* @param bridgeToken - Fixed bridge token
|
|
44
|
+
* @returns Test identity (do not use in production hosts)
|
|
45
|
+
*/
|
|
46
|
+
static test(instanceId: string, bridgeToken: string): ReturningAIBridgeIdentity {
|
|
47
|
+
return new ReturningAIBridgeIdentity(instanceId, bridgeToken);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Global name installed by the injected bootstrap for `postMessage` into React Native.
|
|
53
|
+
* Must match the name referenced by the HTML shell bridge script.
|
|
54
|
+
*/
|
|
55
|
+
export const RETURNING_AI_REACT_NATIVE_BRIDGE_NAME = "ReturningAIReactNativeBridge";
|
|
56
|
+
|
|
57
|
+
/** 32 random bytes encoded as unpadded base64url. */
|
|
58
|
+
function randomBase64Url(): string {
|
|
59
|
+
const bytes = new Uint8Array(32);
|
|
60
|
+
fillRandomBytes(bytes);
|
|
61
|
+
return encodeBase64UrlWithoutPadding(bytes);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Encodes bytes as URL-safe Base64 without `=` padding.
|
|
66
|
+
* @param bytes - Input bytes
|
|
67
|
+
* @returns Unpadded base64url string
|
|
68
|
+
*/
|
|
69
|
+
export function encodeBase64UrlWithoutPadding(bytes: Uint8Array): string {
|
|
70
|
+
const chunks: string[] = [];
|
|
71
|
+
for (let index = 0; index < bytes.length; index += 3) {
|
|
72
|
+
const remaining = bytes.length - index;
|
|
73
|
+
const b0 = bytes[index] ?? 0;
|
|
74
|
+
const b1 = remaining > 1 ? (bytes[index + 1] ?? 0) : 0;
|
|
75
|
+
const b2 = remaining > 2 ? (bytes[index + 2] ?? 0) : 0;
|
|
76
|
+
const triple = (b0 << 16) | (b1 << 8) | b2;
|
|
77
|
+
chunks.push(URL_ALPHABET[(triple >> 18) & 63] ?? "");
|
|
78
|
+
chunks.push(URL_ALPHABET[(triple >> 12) & 63] ?? "");
|
|
79
|
+
if (remaining > 1) {
|
|
80
|
+
chunks.push(URL_ALPHABET[(triple >> 6) & 63] ?? "");
|
|
81
|
+
}
|
|
82
|
+
if (remaining > 2) {
|
|
83
|
+
chunks.push(URL_ALPHABET[triple & 63] ?? "");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return chunks.join("");
|
|
87
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Optional first-paint CSS color overrides for shell background, text, and accent.
|
|
3
|
+
*
|
|
4
|
+
* Layer: configuration
|
|
5
|
+
* Role: Stores optional color strings and a stable fingerprint for config identity.
|
|
6
|
+
* Does not inject styles into HTML (htmlRenderer consumes these via configuration).
|
|
7
|
+
* See also: ReturningAIWidgetConfiguration.ts, rendering/htmlRenderer.ts
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Optional first-paint color overrides applied as custom-element attributes (`bg`, `text`, `accent`).
|
|
12
|
+
*/
|
|
13
|
+
export class ReturningAIFirstPaintColors {
|
|
14
|
+
/** Optional CSS color for first-paint background (`bg` attribute). */
|
|
15
|
+
readonly background?: string;
|
|
16
|
+
/** Optional CSS color for first-paint text (`text` attribute). */
|
|
17
|
+
readonly text?: string;
|
|
18
|
+
/** Optional CSS color for first-paint accent (`accent` attribute). */
|
|
19
|
+
readonly accent?: string;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Creates optional first-paint color overrides.
|
|
23
|
+
* @param input.background - CSS color string for background
|
|
24
|
+
* @param input.text - CSS color string for text
|
|
25
|
+
* @param input.accent - CSS color string for accent
|
|
26
|
+
*/
|
|
27
|
+
constructor(
|
|
28
|
+
input: {
|
|
29
|
+
background?: string;
|
|
30
|
+
text?: string;
|
|
31
|
+
accent?: string;
|
|
32
|
+
} = {},
|
|
33
|
+
) {
|
|
34
|
+
this.background = input.background;
|
|
35
|
+
this.text = input.text;
|
|
36
|
+
this.accent = input.accent;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Stable fingerprint fragment included in configuration session identity.
|
|
41
|
+
* @returns Concatenated color strings separated by unit separator
|
|
42
|
+
*/
|
|
43
|
+
get fingerprint(): string {
|
|
44
|
+
return [this.background ?? "", this.text ?? "", this.accent ?? ""].join("\u001f");
|
|
45
|
+
}
|
|
46
|
+
}
|