@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,601 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Host-facing React Native component that mounts the ReturningAI widget WebView.
|
|
3
|
+
*
|
|
4
|
+
* Layer: public API
|
|
5
|
+
* Role: Wires props (configuration, embedTokenProvider, controller, hostCallbacks) to the
|
|
6
|
+
* coordinator and react-native-webview; owns loading/error UI and theme shell.
|
|
7
|
+
* Does not exchange embed tokens itself or parse bridge envelopes.
|
|
8
|
+
* Security: Embed tokens stay in JS via the provider/coordinator; WebView receives access tokens only.
|
|
9
|
+
* See also: coordinator/ReturningAIWidgetCoordinator.ts, controller/ReturningAIWidgetController.ts
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
createElement,
|
|
14
|
+
useCallback,
|
|
15
|
+
useEffect,
|
|
16
|
+
useRef,
|
|
17
|
+
useState,
|
|
18
|
+
type ReactElement,
|
|
19
|
+
type ReactNode,
|
|
20
|
+
} from "react";
|
|
21
|
+
import {
|
|
22
|
+
Platform,
|
|
23
|
+
Pressable,
|
|
24
|
+
StyleSheet,
|
|
25
|
+
Text,
|
|
26
|
+
useColorScheme,
|
|
27
|
+
View,
|
|
28
|
+
type StyleProp,
|
|
29
|
+
type ViewStyle,
|
|
30
|
+
} from "react-native";
|
|
31
|
+
import { WebView } from "react-native-webview";
|
|
32
|
+
import type { WebView as WebViewHandle } from "react-native-webview";
|
|
33
|
+
import type {
|
|
34
|
+
ShouldStartLoadRequest,
|
|
35
|
+
WebViewErrorEvent,
|
|
36
|
+
WebViewHttpErrorEvent,
|
|
37
|
+
WebViewMessageEvent,
|
|
38
|
+
WebViewOpenWindowEvent,
|
|
39
|
+
} from "react-native-webview/lib/WebViewTypes";
|
|
40
|
+
|
|
41
|
+
import type { ReturningAIFetch } from "./authentication/ReturningAIAuthenticationClient";
|
|
42
|
+
import {
|
|
43
|
+
resolveSessionAuthClient,
|
|
44
|
+
type ReturningAISessionAuthClientState,
|
|
45
|
+
} from "./authentication/sessionAuthClient";
|
|
46
|
+
import type { ReturningAIEmbedTokenProvider } from "./authentication/types";
|
|
47
|
+
import { type ReturningAIWidgetConfiguration } from "./configuration/ReturningAIWidgetConfiguration";
|
|
48
|
+
import {
|
|
49
|
+
type ReturningAIWidgetController,
|
|
50
|
+
type ReturningAIWidgetControllerTarget,
|
|
51
|
+
} from "./controller/ReturningAIWidgetController";
|
|
52
|
+
import { ReturningAIWidgetSessionSnapshotDetached } from "./controller/ReturningAIWidgetSessionSnapshot";
|
|
53
|
+
import { ReturningAIWidgetCoordinator } from "./coordinator/ReturningAIWidgetCoordinator";
|
|
54
|
+
import { ReturningAIWidgetError, toReturningAIWidgetError } from "./errors/ReturningAIWidgetError";
|
|
55
|
+
import { redactReturningAISecrets } from "./errors/json";
|
|
56
|
+
import {
|
|
57
|
+
ReturningAIWidgetErrorEvent,
|
|
58
|
+
type ReturningAIWidgetEvent,
|
|
59
|
+
ReturningAIWidgetHeightChanged,
|
|
60
|
+
ReturningAIWidgetMounted,
|
|
61
|
+
ReturningAIWidgetReady,
|
|
62
|
+
type ReturningAIHostCallbackHandler,
|
|
63
|
+
} from "./events/ReturningAIWidgetEvent";
|
|
64
|
+
import { ReturningAINavigationAction } from "./navigation/ReturningAINavigationPolicy";
|
|
65
|
+
import {
|
|
66
|
+
resolveReturningAIWidgetTheme,
|
|
67
|
+
returningAIShellBackgroundColor,
|
|
68
|
+
type ReturningAIResolvedTheme,
|
|
69
|
+
} from "./rendering/theme";
|
|
70
|
+
import { RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP } from "./webview/bridgeBootstrap";
|
|
71
|
+
import {
|
|
72
|
+
ReturningAIReactNativeWebViewDriver,
|
|
73
|
+
type ReturningAIHtmlSource,
|
|
74
|
+
} from "./webview/ReturningAIReactNativeWebViewDriver";
|
|
75
|
+
import { returningAIOriginWhitelist } from "./webview/originWhitelist";
|
|
76
|
+
import {
|
|
77
|
+
returningAIWebMessageOrigin,
|
|
78
|
+
shouldDeliverReturningAIWebMessage,
|
|
79
|
+
} from "./webview/ReturningAIWebViewDriver";
|
|
80
|
+
import {
|
|
81
|
+
isReturningAIHttpErrorTerminal,
|
|
82
|
+
isReturningAIResourceErrorTerminal,
|
|
83
|
+
} from "./webview/errorPolicy";
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Host-supplied loading UI factory shown while the widget is not yet ready.
|
|
87
|
+
* @returns React node for the loading overlay/placeholder
|
|
88
|
+
*/
|
|
89
|
+
export type ReturningAIWidgetLoadingBuilder = () => ReactNode;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Host-supplied error UI factory with a retry action.
|
|
93
|
+
* @param error - Typed widget error (messages are credential-redacted)
|
|
94
|
+
* @param retry - Restarts the session
|
|
95
|
+
* @returns React node for the error overlay/placeholder
|
|
96
|
+
*/
|
|
97
|
+
export type ReturningAIWidgetErrorBuilder = (
|
|
98
|
+
error: ReturningAIWidgetError,
|
|
99
|
+
retry: () => void,
|
|
100
|
+
) => ReactNode;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Props for {@link ReturningAIWidget}.
|
|
104
|
+
* Embed tokens are obtained only via `embedTokenProvider` and never placed in HTML/bridge/URLs.
|
|
105
|
+
*/
|
|
106
|
+
export type ReturningAIWidgetProps = {
|
|
107
|
+
/** Validated host configuration for the widget session. */
|
|
108
|
+
configuration: ReturningAIWidgetConfiguration;
|
|
109
|
+
/**
|
|
110
|
+
* Optional async mint for the embed token used in the HTTPS auth body only.
|
|
111
|
+
* The WebView receives the exchanged access token, never this value.
|
|
112
|
+
*/
|
|
113
|
+
embedTokenProvider?: ReturningAIEmbedTokenProvider;
|
|
114
|
+
/** Optional imperative controller for reload/retry/theme/logout/session query/invalidate. */
|
|
115
|
+
controller?: ReturningAIWidgetController;
|
|
116
|
+
/** Optional custom fetch used by the authentication client. */
|
|
117
|
+
fetch?: ReturningAIFetch;
|
|
118
|
+
/** Allowlisted host callback name → handler map. */
|
|
119
|
+
hostCallbacks?: Record<string, ReturningAIHostCallbackHandler>;
|
|
120
|
+
/** Lifecycle and runtime event sink. */
|
|
121
|
+
onEvent?: (event: ReturningAIWidgetEvent) => void;
|
|
122
|
+
/** Non-terminal and configuration error sink. */
|
|
123
|
+
onError?: (error: ReturningAIWidgetError) => void;
|
|
124
|
+
/** Called when navigation policy delegates an external URL to the host. */
|
|
125
|
+
onExternalNavigation?: (uri: URL) => void;
|
|
126
|
+
/** Optional loading UI builder. */
|
|
127
|
+
loadingBuilder?: ReturningAIWidgetLoadingBuilder;
|
|
128
|
+
/** Optional error UI builder (defaults to message + Retry). */
|
|
129
|
+
errorBuilder?: ReturningAIWidgetErrorBuilder;
|
|
130
|
+
/** Optional style applied to the root shell `View`. */
|
|
131
|
+
style?: StyleProp<ViewStyle>;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Host-facing React Native component that mounts the ReturningAI widget WebView.
|
|
136
|
+
* Wires configuration, auth provider, controller, and hostCallbacks to the coordinator.
|
|
137
|
+
* @param props - {@link ReturningAIWidgetProps}
|
|
138
|
+
* @returns React element tree (shell + WebView + optional overlays)
|
|
139
|
+
*/
|
|
140
|
+
export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
141
|
+
const colorScheme = useColorScheme();
|
|
142
|
+
const propsRef = useRef(props);
|
|
143
|
+
propsRef.current = props;
|
|
144
|
+
|
|
145
|
+
const [error, setError] = useState<ReturningAIWidgetError | null>(null);
|
|
146
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
147
|
+
const [height, setHeight] = useState(props.configuration.display.initialHeight);
|
|
148
|
+
const [source, setSource] = useState<ReturningAIHtmlSource | null>(null);
|
|
149
|
+
|
|
150
|
+
const coordinatorRef = useRef<ReturningAIWidgetCoordinator | null>(null);
|
|
151
|
+
const driverRef = useRef<ReturningAIReactNativeWebViewDriver | null>(null);
|
|
152
|
+
const fingerprintRef = useRef<string | undefined>(undefined);
|
|
153
|
+
const callbackNamesRef = useRef<Set<string>>(new Set());
|
|
154
|
+
const fetchRef = useRef(props.fetch);
|
|
155
|
+
const authClientStateRef = useRef<ReturningAISessionAuthClientState>({
|
|
156
|
+
client: null,
|
|
157
|
+
fetch: undefined,
|
|
158
|
+
});
|
|
159
|
+
const mountedRef = useRef(true);
|
|
160
|
+
const startSessionRef = useRef<(reuseDriver: boolean) => void>(() => undefined);
|
|
161
|
+
|
|
162
|
+
const platformBrightness: ReturningAIResolvedTheme = colorScheme === "dark" ? "dark" : "light";
|
|
163
|
+
|
|
164
|
+
/** Clears terminal error UI and restarts the session reusing the driver when possible. */
|
|
165
|
+
const retryFromError = useCallback(() => {
|
|
166
|
+
setError(null);
|
|
167
|
+
setIsLoading(true);
|
|
168
|
+
startSessionRef.current(true);
|
|
169
|
+
}, []);
|
|
170
|
+
|
|
171
|
+
const targetRef = useRef<ReturningAIWidgetControllerTarget>({
|
|
172
|
+
reload: async () => {
|
|
173
|
+
await coordinatorRef.current?.reload();
|
|
174
|
+
},
|
|
175
|
+
retry: () => {
|
|
176
|
+
setError(null);
|
|
177
|
+
setIsLoading(true);
|
|
178
|
+
startSessionRef.current(true);
|
|
179
|
+
return Promise.resolve();
|
|
180
|
+
},
|
|
181
|
+
updateTheme: async (theme) => {
|
|
182
|
+
const resolved = resolveReturningAIWidgetTheme(theme, platformBrightness);
|
|
183
|
+
await coordinatorRef.current?.updateTheme(resolved);
|
|
184
|
+
},
|
|
185
|
+
logout: async () => {
|
|
186
|
+
await coordinatorRef.current?.logout();
|
|
187
|
+
},
|
|
188
|
+
get isAuthenticated() {
|
|
189
|
+
return coordinatorRef.current?.isAuthenticated ?? false;
|
|
190
|
+
},
|
|
191
|
+
get sessionSnapshot() {
|
|
192
|
+
return coordinatorRef.current?.sessionSnapshot ?? ReturningAIWidgetSessionSnapshotDetached;
|
|
193
|
+
},
|
|
194
|
+
invalidate: () => {
|
|
195
|
+
coordinatorRef.current?.invalidate();
|
|
196
|
+
return Promise.resolve();
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
targetRef.current.updateTheme = async (theme) => {
|
|
200
|
+
const resolved = resolveReturningAIWidgetTheme(
|
|
201
|
+
theme,
|
|
202
|
+
colorScheme === "dark" ? "dark" : "light",
|
|
203
|
+
);
|
|
204
|
+
await coordinatorRef.current?.updateTheme(resolved);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** Applies ready/error/height side effects then forwards to `onEvent`. */
|
|
208
|
+
const handleEvent = useCallback((event: ReturningAIWidgetEvent) => {
|
|
209
|
+
if (!mountedRef.current) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (event instanceof ReturningAIWidgetReady || event instanceof ReturningAIWidgetMounted) {
|
|
213
|
+
setIsLoading(false);
|
|
214
|
+
} else if (event instanceof ReturningAIWidgetErrorEvent) {
|
|
215
|
+
setIsLoading(false);
|
|
216
|
+
} else if (
|
|
217
|
+
event instanceof ReturningAIWidgetHeightChanged &&
|
|
218
|
+
propsRef.current.configuration.display.autoHeight
|
|
219
|
+
) {
|
|
220
|
+
const display = propsRef.current.configuration.display;
|
|
221
|
+
const clamped = Math.min(display.maxHeight, Math.max(display.minHeight, event.height));
|
|
222
|
+
setHeight(clamped);
|
|
223
|
+
}
|
|
224
|
+
propsRef.current.onEvent?.(event);
|
|
225
|
+
}, []);
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Creates a new coordinator session. When `reuseDriver` is false the WebView source is cleared.
|
|
229
|
+
* Invalidates any previous coordinator first.
|
|
230
|
+
*/
|
|
231
|
+
const startSession = useCallback(
|
|
232
|
+
(reuseDriver: boolean) => {
|
|
233
|
+
if (!mountedRef.current) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const current = propsRef.current;
|
|
237
|
+
const existingDriver = reuseDriver ? driverRef.current : null;
|
|
238
|
+
coordinatorRef.current?.invalidate(existingDriver === null);
|
|
239
|
+
coordinatorRef.current = null;
|
|
240
|
+
try {
|
|
241
|
+
if (Platform.OS !== "ios" && Platform.OS !== "android") {
|
|
242
|
+
throw new ReturningAIWidgetError({
|
|
243
|
+
code: "unsupportedPlatform",
|
|
244
|
+
message: "ReturningAIWidget supports Android and iOS only.",
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
const configuration = current.configuration.validated();
|
|
248
|
+
const resolvedTheme = resolveReturningAIWidgetTheme(
|
|
249
|
+
configuration.theme,
|
|
250
|
+
colorScheme === "dark" ? "dark" : "light",
|
|
251
|
+
);
|
|
252
|
+
const sessionConfiguration = configuration.copyWith({
|
|
253
|
+
theme: resolvedTheme,
|
|
254
|
+
});
|
|
255
|
+
fingerprintRef.current = configuration.sessionFingerprint;
|
|
256
|
+
callbackNamesRef.current = new Set(Object.keys(current.hostCallbacks ?? {}));
|
|
257
|
+
setHeight(configuration.display.initialHeight);
|
|
258
|
+
setError(null);
|
|
259
|
+
setIsLoading(true);
|
|
260
|
+
|
|
261
|
+
const driver =
|
|
262
|
+
existingDriver ??
|
|
263
|
+
new ReturningAIReactNativeWebViewDriver({
|
|
264
|
+
onSourceChange: (next) => {
|
|
265
|
+
if (mountedRef.current) {
|
|
266
|
+
setSource({ html: next.html, baseUrl: next.baseUrl });
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
const coordinator = new ReturningAIWidgetCoordinator({
|
|
271
|
+
configuration: sessionConfiguration,
|
|
272
|
+
embedTokenProvider: current.embedTokenProvider,
|
|
273
|
+
hostCallbacks: current.hostCallbacks,
|
|
274
|
+
authenticationClient: resolveSessionAuthClient(authClientStateRef.current, current.fetch),
|
|
275
|
+
onEvent: handleEvent,
|
|
276
|
+
onError: (widgetError) => propsRef.current.onError?.(widgetError),
|
|
277
|
+
onTerminalError: (widgetError) => {
|
|
278
|
+
if (!mountedRef.current) {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
setError(widgetError);
|
|
282
|
+
setIsLoading(false);
|
|
283
|
+
},
|
|
284
|
+
onExternalNavigation: (uri) => propsRef.current.onExternalNavigation?.(uri),
|
|
285
|
+
});
|
|
286
|
+
coordinatorRef.current = coordinator;
|
|
287
|
+
driverRef.current = driver;
|
|
288
|
+
void coordinator.start(driver);
|
|
289
|
+
} catch (caught) {
|
|
290
|
+
const widgetError = toReturningAIWidgetError(
|
|
291
|
+
caught,
|
|
292
|
+
"Unable to create ReturningAI widget.",
|
|
293
|
+
);
|
|
294
|
+
if (existingDriver === null) {
|
|
295
|
+
driverRef.current = null;
|
|
296
|
+
setSource(null);
|
|
297
|
+
}
|
|
298
|
+
setError(widgetError);
|
|
299
|
+
setIsLoading(false);
|
|
300
|
+
current.onError?.(widgetError);
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
[colorScheme, handleEvent],
|
|
304
|
+
);
|
|
305
|
+
startSessionRef.current = startSession;
|
|
306
|
+
|
|
307
|
+
useEffect(() => {
|
|
308
|
+
mountedRef.current = true;
|
|
309
|
+
return () => {
|
|
310
|
+
mountedRef.current = false;
|
|
311
|
+
coordinatorRef.current?.invalidate(true);
|
|
312
|
+
coordinatorRef.current = null;
|
|
313
|
+
driverRef.current = null;
|
|
314
|
+
authClientStateRef.current = { client: null, fetch: undefined };
|
|
315
|
+
};
|
|
316
|
+
}, []);
|
|
317
|
+
|
|
318
|
+
useEffect(() => {
|
|
319
|
+
const controller = props.controller;
|
|
320
|
+
const target = targetRef.current;
|
|
321
|
+
controller?.attach(target);
|
|
322
|
+
return () => {
|
|
323
|
+
controller?.detach(target);
|
|
324
|
+
};
|
|
325
|
+
}, [props.controller]);
|
|
326
|
+
|
|
327
|
+
useEffect(() => {
|
|
328
|
+
const nextCallbacks = new Set(Object.keys(props.hostCallbacks ?? {}));
|
|
329
|
+
const fetchChanged = fetchRef.current !== props.fetch;
|
|
330
|
+
fetchRef.current = props.fetch;
|
|
331
|
+
const coordinator = coordinatorRef.current;
|
|
332
|
+
if (coordinator === null && driverRef.current === null) {
|
|
333
|
+
startSession(false);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
let nextFingerprint: string | undefined;
|
|
337
|
+
try {
|
|
338
|
+
nextFingerprint = props.configuration.validated().sessionFingerprint;
|
|
339
|
+
} catch {
|
|
340
|
+
startSession(true);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const requiresNewSession =
|
|
344
|
+
fingerprintRef.current !== nextFingerprint ||
|
|
345
|
+
!sameSet(callbackNamesRef.current, nextCallbacks) ||
|
|
346
|
+
fetchChanged;
|
|
347
|
+
if (requiresNewSession) {
|
|
348
|
+
startSession(true);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
coordinator?.updateConfiguration(props.configuration);
|
|
352
|
+
coordinator?.updateHandlers({
|
|
353
|
+
embedTokenProvider: props.embedTokenProvider,
|
|
354
|
+
hostCallbacks: props.hostCallbacks,
|
|
355
|
+
});
|
|
356
|
+
}, [
|
|
357
|
+
props.configuration,
|
|
358
|
+
props.hostCallbacks,
|
|
359
|
+
props.embedTokenProvider,
|
|
360
|
+
props.fetch,
|
|
361
|
+
colorScheme,
|
|
362
|
+
startSession,
|
|
363
|
+
]);
|
|
364
|
+
|
|
365
|
+
useEffect(() => {
|
|
366
|
+
void coordinatorRef.current?.updateTheme(
|
|
367
|
+
resolveReturningAIWidgetTheme(
|
|
368
|
+
props.configuration.theme,
|
|
369
|
+
colorScheme === "dark" ? "dark" : "light",
|
|
370
|
+
),
|
|
371
|
+
);
|
|
372
|
+
}, [props.configuration.theme, colorScheme]);
|
|
373
|
+
|
|
374
|
+
const attachWebView = useCallback((instance: WebViewHandle | null) => {
|
|
375
|
+
driverRef.current?.attach(instance);
|
|
376
|
+
}, []);
|
|
377
|
+
|
|
378
|
+
/** Origin-gates then forwards bridge payloads to the coordinator. */
|
|
379
|
+
const onMessage = useCallback((event: WebViewMessageEvent) => {
|
|
380
|
+
const coordinator = coordinatorRef.current;
|
|
381
|
+
if (coordinator === undefined || coordinator === null) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const expected = returningAIWebMessageOrigin(propsRef.current.configuration);
|
|
385
|
+
if (
|
|
386
|
+
!shouldDeliverReturningAIWebMessage({
|
|
387
|
+
sourceUrl: event.nativeEvent.url,
|
|
388
|
+
expectedOrigin: expected,
|
|
389
|
+
})
|
|
390
|
+
) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
void coordinator.handleBridgeMessage(event.nativeEvent.data);
|
|
394
|
+
}, []);
|
|
395
|
+
|
|
396
|
+
/** Applies navigation policy; only `allow` proceeds in the WebView. */
|
|
397
|
+
const onShouldStartLoadWithRequest = useCallback((request: ShouldStartLoadRequest): boolean => {
|
|
398
|
+
const coordinator = coordinatorRef.current;
|
|
399
|
+
if (coordinator === null) {
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
let uri: URL;
|
|
403
|
+
try {
|
|
404
|
+
uri = new URL(request.url);
|
|
405
|
+
} catch {
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
const isMainFrame = request.isTopFrame !== false;
|
|
409
|
+
const action = coordinator.handleNavigation(uri, isMainFrame);
|
|
410
|
+
return action === ReturningAINavigationAction.allow;
|
|
411
|
+
}, []);
|
|
412
|
+
|
|
413
|
+
const onError = useCallback((event: WebViewErrorEvent) => {
|
|
414
|
+
const coordinator = coordinatorRef.current;
|
|
415
|
+
if (coordinator === null) {
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
const isMainFrame =
|
|
419
|
+
(event.nativeEvent as { isForMainFrame?: boolean }).isForMainFrame !== false;
|
|
420
|
+
coordinator.handleWebViewError(
|
|
421
|
+
new ReturningAIWidgetError({
|
|
422
|
+
code: "webViewLoadFailed",
|
|
423
|
+
message: redactReturningAISecrets(
|
|
424
|
+
event.nativeEvent.description || "The widget WebView failed to load.",
|
|
425
|
+
),
|
|
426
|
+
}),
|
|
427
|
+
isReturningAIResourceErrorTerminal(isMainFrame),
|
|
428
|
+
);
|
|
429
|
+
}, []);
|
|
430
|
+
|
|
431
|
+
const onHttpError = useCallback((event: WebViewHttpErrorEvent) => {
|
|
432
|
+
const coordinator = coordinatorRef.current;
|
|
433
|
+
if (coordinator === null) {
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
coordinator.handleWebViewError(
|
|
437
|
+
new ReturningAIWidgetError({
|
|
438
|
+
code: "webViewLoadFailed",
|
|
439
|
+
message: "The widget WebView returned an HTTP error.",
|
|
440
|
+
statusCode: event.nativeEvent.statusCode,
|
|
441
|
+
}),
|
|
442
|
+
isReturningAIHttpErrorTerminal(),
|
|
443
|
+
);
|
|
444
|
+
}, []);
|
|
445
|
+
|
|
446
|
+
/** Treats `window.open` targets as main-frame navigations for policy/delegation. */
|
|
447
|
+
const onOpenWindow = useCallback((event: WebViewOpenWindowEvent) => {
|
|
448
|
+
const coordinator = coordinatorRef.current;
|
|
449
|
+
if (coordinator === null) {
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
try {
|
|
453
|
+
coordinator.handleNavigation(new URL(event.nativeEvent.targetUrl), true);
|
|
454
|
+
} catch {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
}, []);
|
|
458
|
+
|
|
459
|
+
const autoHeight = props.configuration.display.autoHeight;
|
|
460
|
+
const showLoading = props.loadingBuilder !== undefined && isLoading && error === null;
|
|
461
|
+
const webViewStyle = autoHeight ? { height, width: "100%" as const } : styles.flex;
|
|
462
|
+
const resolvedTheme = resolveReturningAIWidgetTheme(
|
|
463
|
+
props.configuration.theme,
|
|
464
|
+
platformBrightness,
|
|
465
|
+
);
|
|
466
|
+
const rootStyle = [
|
|
467
|
+
autoHeight ? { height } : styles.root,
|
|
468
|
+
{
|
|
469
|
+
backgroundColor: argbToCss(
|
|
470
|
+
returningAIShellBackgroundColor(resolvedTheme, props.configuration.display.backgroundColor),
|
|
471
|
+
),
|
|
472
|
+
},
|
|
473
|
+
props.style,
|
|
474
|
+
];
|
|
475
|
+
|
|
476
|
+
if (source === null) {
|
|
477
|
+
if (error !== null) {
|
|
478
|
+
return createElement(
|
|
479
|
+
View,
|
|
480
|
+
{ style: rootStyle },
|
|
481
|
+
renderError(error, retryFromError, props.errorBuilder),
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
return createElement(View, { style: rootStyle }, props.loadingBuilder?.() ?? null);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const webView = createElement(WebView, {
|
|
488
|
+
ref: attachWebView,
|
|
489
|
+
source,
|
|
490
|
+
style: webViewStyle,
|
|
491
|
+
onMessage,
|
|
492
|
+
onShouldStartLoadWithRequest,
|
|
493
|
+
onError,
|
|
494
|
+
onHttpError,
|
|
495
|
+
onOpenWindow,
|
|
496
|
+
injectedJavaScriptBeforeContentLoaded: RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP,
|
|
497
|
+
javaScriptEnabled: true,
|
|
498
|
+
originWhitelist: returningAIOriginWhitelist(props.configuration.debug),
|
|
499
|
+
mixedContentMode: "never",
|
|
500
|
+
allowFileAccess: false,
|
|
501
|
+
allowFileAccessFromFileURLs: false,
|
|
502
|
+
allowUniversalAccessFromFileURLs: false,
|
|
503
|
+
setSupportMultipleWindows: true,
|
|
504
|
+
mediaPlaybackRequiresUserAction: false,
|
|
505
|
+
allowsInlineMediaPlayback: true,
|
|
506
|
+
bounces: false,
|
|
507
|
+
overScrollMode: "never",
|
|
508
|
+
startInLoadingState: false,
|
|
509
|
+
domStorageEnabled: true,
|
|
510
|
+
testID: "returningai-webview",
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
if (!showLoading && error === null) {
|
|
514
|
+
return createElement(View, { style: rootStyle }, webView);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
return createElement(
|
|
518
|
+
View,
|
|
519
|
+
{ style: rootStyle },
|
|
520
|
+
webView,
|
|
521
|
+
showLoading ? createElement(View, { style: styles.overlay }, props.loadingBuilder?.()) : null,
|
|
522
|
+
error !== null
|
|
523
|
+
? createElement(
|
|
524
|
+
View,
|
|
525
|
+
{ style: styles.overlay },
|
|
526
|
+
renderError(error, retryFromError, props.errorBuilder),
|
|
527
|
+
)
|
|
528
|
+
: null,
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** Renders host `errorBuilder` or the default message + Retry control. */
|
|
533
|
+
function renderError(
|
|
534
|
+
error: ReturningAIWidgetError,
|
|
535
|
+
retry: () => void,
|
|
536
|
+
errorBuilder?: ReturningAIWidgetErrorBuilder,
|
|
537
|
+
): ReactNode {
|
|
538
|
+
if (errorBuilder !== undefined) {
|
|
539
|
+
return errorBuilder(error, retry);
|
|
540
|
+
}
|
|
541
|
+
return createElement(
|
|
542
|
+
View,
|
|
543
|
+
{ style: styles.error },
|
|
544
|
+
createElement(Text, { style: styles.errorMessage }, error.message),
|
|
545
|
+
createElement(
|
|
546
|
+
Pressable,
|
|
547
|
+
{
|
|
548
|
+
onPress: retry,
|
|
549
|
+
testID: "returningai-retry",
|
|
550
|
+
accessibilityRole: "button",
|
|
551
|
+
},
|
|
552
|
+
createElement(Text, null, "Retry"),
|
|
553
|
+
),
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function sameSet(left: Set<string>, right: Set<string>): boolean {
|
|
558
|
+
if (left.size !== right.size) {
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
for (const value of left) {
|
|
562
|
+
if (!right.has(value)) {
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return true;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const styles = StyleSheet.create({
|
|
570
|
+
root: {
|
|
571
|
+
flex: 1,
|
|
572
|
+
},
|
|
573
|
+
flex: {
|
|
574
|
+
flex: 1,
|
|
575
|
+
},
|
|
576
|
+
overlay: {
|
|
577
|
+
...StyleSheet.absoluteFill,
|
|
578
|
+
},
|
|
579
|
+
error: {
|
|
580
|
+
flex: 1,
|
|
581
|
+
alignItems: "center",
|
|
582
|
+
justifyContent: "center",
|
|
583
|
+
padding: 16,
|
|
584
|
+
},
|
|
585
|
+
errorMessage: {
|
|
586
|
+
textAlign: "center",
|
|
587
|
+
marginBottom: 12,
|
|
588
|
+
},
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
/** Converts ARGB integers to `#rrggbb` or `rgba(...)` for RN style props. */
|
|
592
|
+
function argbToCss(color: number): string {
|
|
593
|
+
const alpha = ((color >>> 24) & 0xff) / 255;
|
|
594
|
+
const red = (color >>> 16) & 0xff;
|
|
595
|
+
const green = (color >>> 8) & 0xff;
|
|
596
|
+
const blue = color & 0xff;
|
|
597
|
+
if (alpha >= 1) {
|
|
598
|
+
return `#${red.toString(16).padStart(2, "0")}${green.toString(16).padStart(2, "0")}${blue.toString(16).padStart(2, "0")}`;
|
|
599
|
+
}
|
|
600
|
+
return `rgba(${red}, ${green}, ${blue}, ${alpha.toFixed(3)})`;
|
|
601
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview In-memory cache of short-lived access tokens keyed by session fingerprint.
|
|
3
|
+
*
|
|
4
|
+
* Layer: authentication
|
|
5
|
+
* Role: Stores access tokens with expiry skew; returns unused entries or clears on invalidate.
|
|
6
|
+
* Does not perform network auth or hold embed tokens.
|
|
7
|
+
* Security: Caches access tokens in JS memory only; never persist or put tokens in HTML/bridge.
|
|
8
|
+
* See also: ReturningAIAuthenticationClient.ts, types.ts
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { ReturningAIAccessToken, ReturningAIClock } from "./types";
|
|
12
|
+
|
|
13
|
+
/** Default remaining-lifetime skew so tokens near expiry are treated as stale. */
|
|
14
|
+
const DEFAULT_SKEW_MS = 30_000;
|
|
15
|
+
|
|
16
|
+
/** Internal cache row: token plus absolute expiry wall time. */
|
|
17
|
+
type CachedToken = {
|
|
18
|
+
token: ReturningAIAccessToken;
|
|
19
|
+
expiresAtMillis: number;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Session-scoped in-memory cache for short-lived access tokens.
|
|
24
|
+
* Keys are coordinator session identifiers; values are never written to storage, HTML, or bridge.
|
|
25
|
+
*/
|
|
26
|
+
export class ReturningAIAccessTokenCache {
|
|
27
|
+
private readonly clock: ReturningAIClock;
|
|
28
|
+
private readonly skewMs: number;
|
|
29
|
+
private readonly entries = new Map<string, CachedToken>();
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Creates an access-token cache.
|
|
33
|
+
* @param input.clock - Clock for expiry checks (defaults to `Date.now`)
|
|
34
|
+
* @param input.skewMs - Remaining-lifetime margin before treating a token as expired
|
|
35
|
+
*/
|
|
36
|
+
constructor(input: { clock?: ReturningAIClock; skewMs?: number } = {}) {
|
|
37
|
+
this.clock = input.clock ?? (() => Date.now());
|
|
38
|
+
this.skewMs = input.skewMs ?? DEFAULT_SKEW_MS;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Returns a cached access token when it still has more than `skewMs` of life remaining.
|
|
43
|
+
* @param sessionKey - Coordinator session key (typically bridge instance id)
|
|
44
|
+
* @returns The cached token, or `undefined` when missing or near expiry
|
|
45
|
+
*/
|
|
46
|
+
get(sessionKey: string): ReturningAIAccessToken | undefined {
|
|
47
|
+
const entry = this.entries.get(sessionKey);
|
|
48
|
+
if (!entry) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
const remainingMillis = entry.expiresAtMillis - this.clock();
|
|
52
|
+
return remainingMillis > this.skewMs ? entry.token : undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Stores an access token using `expiresIn` relative to the current clock.
|
|
57
|
+
* @param sessionKey - Coordinator session key
|
|
58
|
+
* @param token - Short-lived access token from the auth exchange
|
|
59
|
+
*/
|
|
60
|
+
put(sessionKey: string, token: ReturningAIAccessToken): void {
|
|
61
|
+
this.entries.set(sessionKey, {
|
|
62
|
+
token,
|
|
63
|
+
expiresAtMillis: this.clock() + token.expiresIn * 1000,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Removes one session's cached access token (for example after `rai-session-expired`).
|
|
69
|
+
* @param sessionKey - Coordinator session key to clear
|
|
70
|
+
*/
|
|
71
|
+
clear(sessionKey: string): void {
|
|
72
|
+
this.entries.delete(sessionKey);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Absolute expiry wall time for a cached entry when present (even if near skew).
|
|
77
|
+
* Never returns the token value.
|
|
78
|
+
* @param sessionKey - Coordinator session key
|
|
79
|
+
*/
|
|
80
|
+
expiresAtMillis(sessionKey: string): number | undefined {
|
|
81
|
+
return this.entries.get(sessionKey)?.expiresAtMillis;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Drops every cached access token. Used on full invalidate paths.
|
|
86
|
+
*/
|
|
87
|
+
clearAll(): void {
|
|
88
|
+
this.entries.clear();
|
|
89
|
+
}
|
|
90
|
+
}
|