@returningai/react-native-widget-sdk 0.1.1 → 0.1.2
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 +23 -0
- package/package.json +1 -1
- package/src/ReturningAIWidget.tsx +163 -12
- package/src/authentication/ReturningAIAuthenticationClient.ts +84 -24
- package/src/configuration/ReturningAIWidgetConfiguration.ts +1 -1
- package/src/configuration/urls.ts +69 -1
- package/src/navigation/ReturningAINavigationPolicy.ts +2 -9
- package/src/packageInfo.ts +1 -1
- package/src/rendering/htmlRenderer.ts +33 -3
- package/src/webview/ReturningAIReactNativeWebViewDriver.ts +118 -0
- package/src/webview/ReturningAIWebViewDriver.ts +86 -11
- package/src/webview/bridgeBootstrap.ts +44 -2
- package/src/webview/originWhitelist.ts +6 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,11 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.2
|
|
4
|
+
|
|
5
|
+
- RN CLI / iOS 26 / Fabric: widgets now reach `rai-ready` like Expo. Live
|
|
6
|
+
verified on LoyaltyCliApp Earning Overview (auth 200, `rai-mounted`).
|
|
7
|
+
- iOS `loadHTMLString` with HTTPS `baseUrl` is treated as a GET of `/`. The
|
|
8
|
+
first origin load is allowed so the document is not `about:blank` (null
|
|
9
|
+
origin / CORS). Later origin-root refetches are cancelled. `onOpenWindow`
|
|
10
|
+
waits until ready so nil `targetFrame` does not cancel the shell.
|
|
11
|
+
- If origin is still opaque, promote with `location.replace` then
|
|
12
|
+
`document.write` the stored HTML unless `__RETURNINGAI_MOBILE_SDK__` is set.
|
|
13
|
+
Re-append `script[src]` until the custom element is defined.
|
|
14
|
+
- Hermes/`formatUrl` parsed `unpkg.com/@returningai/...` as userinfo@host
|
|
15
|
+
(`https://returningai/@returningai/...`). Path `@` is percent-encoded in
|
|
16
|
+
HTML (`unpkg.com/%40returningai/...`).
|
|
17
|
+
- Auth bodies: never `body.getReader()` (empty/throws after HTTP 200 → widget
|
|
18
|
+
502). Try `text()`, then `json()`, then `arrayBuffer()`.
|
|
19
|
+
- Shell HTML installs `ReturningAIReactNativeBridge`; empty/`about:` URLs are
|
|
20
|
+
the HTML shell; `originWhitelist` includes `*`. `debug: true` logs nav/load
|
|
21
|
+
including `hasSdk` / `ce` / runtime src.
|
|
22
|
+
- Loyalty CLI sample: `file:` local SDK, Metro `@babel/runtime` from the app,
|
|
23
|
+
fetch wrapper materializes `response.text()` into an in-memory `Response`.
|
|
24
|
+
|
|
3
25
|
## 0.1.1
|
|
4
26
|
|
|
5
27
|
- Allows native iOS HTML-string WebView origins (`about:srcdoc`, `applewebdata://`)
|
|
6
28
|
in `originWhitelist`, navigation policy, and `onMessage` gating. Expo Go still
|
|
7
29
|
reports `about:blank`; RN CLI / WKWebView on iOS 26 reports `about:srcdoc`,
|
|
8
30
|
which previously blocked the shell and timed out ready.
|
|
31
|
+
- Slims the published README to client install, usage, and controller APIs.
|
|
9
32
|
|
|
10
33
|
## 0.1.0
|
|
11
34
|
|
package/package.json
CHANGED
|
@@ -67,14 +67,20 @@ import {
|
|
|
67
67
|
returningAIShellBackgroundColor,
|
|
68
68
|
type ReturningAIResolvedTheme,
|
|
69
69
|
} from "./rendering/theme";
|
|
70
|
-
import {
|
|
70
|
+
import {
|
|
71
|
+
RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP,
|
|
72
|
+
RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX,
|
|
73
|
+
RETURNING_AI_REACT_NATIVE_WEBVIEW_DEBUG_PROBE,
|
|
74
|
+
} from "./webview/bridgeBootstrap";
|
|
71
75
|
import {
|
|
72
76
|
ReturningAIReactNativeWebViewDriver,
|
|
73
77
|
type ReturningAIHtmlSource,
|
|
74
78
|
} from "./webview/ReturningAIReactNativeWebViewDriver";
|
|
75
79
|
import { returningAIOriginWhitelist } from "./webview/originWhitelist";
|
|
76
80
|
import {
|
|
81
|
+
isReturningAIHtmlShellDocumentUrl,
|
|
77
82
|
returningAIWebMessageOrigin,
|
|
83
|
+
shouldCancelReturningAIContentOriginRootRefetch,
|
|
78
84
|
shouldDeliverReturningAIWebMessage,
|
|
79
85
|
} from "./webview/ReturningAIWebViewDriver";
|
|
80
86
|
import {
|
|
@@ -146,6 +152,9 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
146
152
|
const [isLoading, setIsLoading] = useState(true);
|
|
147
153
|
const [height, setHeight] = useState(props.configuration.display.initialHeight);
|
|
148
154
|
const [source, setSource] = useState<ReturningAIHtmlSource | null>(null);
|
|
155
|
+
// react-native-webview cancels iOS navigations with a nil targetFrame when
|
|
156
|
+
// onOpenWindow is set. Attach only after shell scripts have run (`rai-ready`).
|
|
157
|
+
const [allowOpenWindow, setAllowOpenWindow] = useState(false);
|
|
149
158
|
|
|
150
159
|
const coordinatorRef = useRef<ReturningAIWidgetCoordinator | null>(null);
|
|
151
160
|
const driverRef = useRef<ReturningAIReactNativeWebViewDriver | null>(null);
|
|
@@ -158,6 +167,8 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
158
167
|
});
|
|
159
168
|
const mountedRef = useRef(true);
|
|
160
169
|
const startSessionRef = useRef<(reuseDriver: boolean) => void>(() => undefined);
|
|
170
|
+
const htmlShellLiveRef = useRef(false);
|
|
171
|
+
const widgetPostedBridgeRef = useRef(false);
|
|
161
172
|
|
|
162
173
|
const platformBrightness: ReturningAIResolvedTheme = colorScheme === "dark" ? "dark" : "light";
|
|
163
174
|
|
|
@@ -211,6 +222,8 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
211
222
|
}
|
|
212
223
|
if (event instanceof ReturningAIWidgetReady || event instanceof ReturningAIWidgetMounted) {
|
|
213
224
|
setIsLoading(false);
|
|
225
|
+
htmlShellLiveRef.current = true;
|
|
226
|
+
setAllowOpenWindow(true);
|
|
214
227
|
} else if (event instanceof ReturningAIWidgetErrorEvent) {
|
|
215
228
|
setIsLoading(false);
|
|
216
229
|
} else if (
|
|
@@ -257,12 +270,18 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
257
270
|
setHeight(configuration.display.initialHeight);
|
|
258
271
|
setError(null);
|
|
259
272
|
setIsLoading(true);
|
|
273
|
+
setAllowOpenWindow(false);
|
|
274
|
+
htmlShellLiveRef.current = false;
|
|
275
|
+
widgetPostedBridgeRef.current = false;
|
|
260
276
|
|
|
261
277
|
const driver =
|
|
262
278
|
existingDriver ??
|
|
263
279
|
new ReturningAIReactNativeWebViewDriver({
|
|
264
280
|
onSourceChange: (next) => {
|
|
265
281
|
if (mountedRef.current) {
|
|
282
|
+
htmlShellLiveRef.current = false;
|
|
283
|
+
widgetPostedBridgeRef.current = false;
|
|
284
|
+
setAllowOpenWindow(false);
|
|
266
285
|
setSource({ html: next.html, baseUrl: next.baseUrl });
|
|
267
286
|
}
|
|
268
287
|
},
|
|
@@ -377,37 +396,98 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
377
396
|
|
|
378
397
|
/** Origin-gates then forwards bridge payloads to the coordinator. */
|
|
379
398
|
const onMessage = useCallback((event: WebViewMessageEvent) => {
|
|
399
|
+
const data = event.nativeEvent.data;
|
|
400
|
+
const configuration = propsRef.current.configuration;
|
|
401
|
+
if (
|
|
402
|
+
typeof data === "string" &&
|
|
403
|
+
data.startsWith(RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX)
|
|
404
|
+
) {
|
|
405
|
+
const payload = data.slice(RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX.length);
|
|
406
|
+
logReturningAIWebView(configuration, "debug", event.nativeEvent.url, payload);
|
|
407
|
+
if (debugProbeReportsShellScriptsRan(payload)) {
|
|
408
|
+
htmlShellLiveRef.current = true;
|
|
409
|
+
}
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
380
412
|
const coordinator = coordinatorRef.current;
|
|
381
413
|
if (coordinator === undefined || coordinator === null) {
|
|
382
414
|
return;
|
|
383
415
|
}
|
|
384
|
-
const expected = returningAIWebMessageOrigin(
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
416
|
+
const expected = returningAIWebMessageOrigin(configuration);
|
|
417
|
+
const delivered = shouldDeliverReturningAIWebMessage({
|
|
418
|
+
sourceUrl: event.nativeEvent.url,
|
|
419
|
+
expectedOrigin: expected,
|
|
420
|
+
});
|
|
421
|
+
logReturningAIWebView(
|
|
422
|
+
configuration,
|
|
423
|
+
delivered ? "message" : "message-drop",
|
|
424
|
+
event.nativeEvent.url,
|
|
425
|
+
debugWebViewPayloadName(data),
|
|
426
|
+
);
|
|
427
|
+
if (!delivered) {
|
|
391
428
|
return;
|
|
392
429
|
}
|
|
393
|
-
|
|
430
|
+
widgetPostedBridgeRef.current = true;
|
|
431
|
+
void coordinator.handleBridgeMessage(data);
|
|
394
432
|
}, []);
|
|
395
433
|
|
|
396
434
|
/** Applies navigation policy; only `allow` proceeds in the WebView. */
|
|
397
435
|
const onShouldStartLoadWithRequest = useCallback((request: ShouldStartLoadRequest): boolean => {
|
|
436
|
+
const configuration = propsRef.current.configuration;
|
|
437
|
+
if (isReturningAIHtmlShellDocumentUrl(request.url)) {
|
|
438
|
+
logReturningAIWebView(
|
|
439
|
+
configuration,
|
|
440
|
+
"nav-allow-shell",
|
|
441
|
+
request.url,
|
|
442
|
+
`top=${String(request.isTopFrame)}`,
|
|
443
|
+
`frame=${String(request.hasTargetFrame)}`,
|
|
444
|
+
request.navigationType,
|
|
445
|
+
);
|
|
446
|
+
return true;
|
|
447
|
+
}
|
|
448
|
+
if (
|
|
449
|
+
htmlShellLiveRef.current &&
|
|
450
|
+
shouldCancelReturningAIContentOriginRootRefetch({
|
|
451
|
+
url: request.url,
|
|
452
|
+
isTopFrame: request.isTopFrame,
|
|
453
|
+
hasTargetFrame: request.hasTargetFrame,
|
|
454
|
+
configuration,
|
|
455
|
+
})
|
|
456
|
+
) {
|
|
457
|
+
logReturningAIWebView(
|
|
458
|
+
configuration,
|
|
459
|
+
"nav-block-base-refetch",
|
|
460
|
+
request.url,
|
|
461
|
+
`top=${String(request.isTopFrame)}`,
|
|
462
|
+
`frame=${String(request.hasTargetFrame)}`,
|
|
463
|
+
request.navigationType,
|
|
464
|
+
);
|
|
465
|
+
return false;
|
|
466
|
+
}
|
|
398
467
|
const coordinator = coordinatorRef.current;
|
|
399
468
|
if (coordinator === null) {
|
|
469
|
+
logReturningAIWebView(configuration, "nav-block-no-session", request.url);
|
|
400
470
|
return false;
|
|
401
471
|
}
|
|
402
472
|
let uri: URL;
|
|
403
473
|
try {
|
|
404
474
|
uri = new URL(request.url);
|
|
405
475
|
} catch {
|
|
406
|
-
|
|
476
|
+
logReturningAIWebView(configuration, "nav-allow-unparseable", request.url);
|
|
477
|
+
return true;
|
|
407
478
|
}
|
|
408
479
|
const isMainFrame = request.isTopFrame !== false;
|
|
409
480
|
const action = coordinator.handleNavigation(uri, isMainFrame);
|
|
410
|
-
|
|
481
|
+
const allow = action === ReturningAINavigationAction.allow;
|
|
482
|
+
logReturningAIWebView(
|
|
483
|
+
configuration,
|
|
484
|
+
allow ? "nav-allow" : `nav-${action}`,
|
|
485
|
+
request.url,
|
|
486
|
+
`top=${String(request.isTopFrame)}`,
|
|
487
|
+
`frame=${String(request.hasTargetFrame)}`,
|
|
488
|
+
request.navigationType,
|
|
489
|
+
);
|
|
490
|
+
return allow;
|
|
411
491
|
}, []);
|
|
412
492
|
|
|
413
493
|
const onError = useCallback((event: WebViewErrorEvent) => {
|
|
@@ -456,6 +536,37 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
456
536
|
}
|
|
457
537
|
}, []);
|
|
458
538
|
|
|
539
|
+
const onLoadStart = useCallback((event?: { nativeEvent?: { url?: string } }) => {
|
|
540
|
+
logReturningAIWebView(
|
|
541
|
+
propsRef.current.configuration,
|
|
542
|
+
"loadStart",
|
|
543
|
+
event?.nativeEvent?.url ?? "",
|
|
544
|
+
);
|
|
545
|
+
}, []);
|
|
546
|
+
|
|
547
|
+
const onLoadEnd = useCallback((event?: { nativeEvent?: { url?: string } }) => {
|
|
548
|
+
const url = event?.nativeEvent?.url ?? "";
|
|
549
|
+
logReturningAIWebView(propsRef.current.configuration, "loadEnd", url);
|
|
550
|
+
// Do not attach onOpenWindow here. Enabling it before scripts run cancels
|
|
551
|
+
// document.write / the origin-establishing GET of `/`.
|
|
552
|
+
const driver = driverRef.current;
|
|
553
|
+
// about:blank is a null origin: writing there never lets ES modules load.
|
|
554
|
+
// Promote to the HTTPS content origin first, then write the stored shell.
|
|
555
|
+
if (isReturningAIHtmlShellDocumentUrl(url)) {
|
|
556
|
+
void driver?.promoteHtmlShellOriginIfNeeded();
|
|
557
|
+
} else {
|
|
558
|
+
if (!widgetPostedBridgeRef.current) {
|
|
559
|
+
void driver?.applyHtmlIfDocumentEmpty();
|
|
560
|
+
void driver?.ensureExternalScripts();
|
|
561
|
+
}
|
|
562
|
+
htmlShellLiveRef.current = true;
|
|
563
|
+
}
|
|
564
|
+
void driver?.runJavaScript(RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP);
|
|
565
|
+
if (propsRef.current.configuration.debug) {
|
|
566
|
+
void driver?.runJavaScript(RETURNING_AI_REACT_NATIVE_WEBVIEW_DEBUG_PROBE);
|
|
567
|
+
}
|
|
568
|
+
}, []);
|
|
569
|
+
|
|
459
570
|
const autoHeight = props.configuration.display.autoHeight;
|
|
460
571
|
const showLoading = props.loadingBuilder !== undefined && isLoading && error === null;
|
|
461
572
|
const webViewStyle = autoHeight ? { height, width: "100%" as const } : styles.flex;
|
|
@@ -492,8 +603,13 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
492
603
|
onShouldStartLoadWithRequest,
|
|
493
604
|
onError,
|
|
494
605
|
onHttpError,
|
|
495
|
-
|
|
606
|
+
onLoadStart,
|
|
607
|
+
onLoadEnd,
|
|
608
|
+
onOpenWindow: allowOpenWindow ? onOpenWindow : undefined,
|
|
496
609
|
injectedJavaScriptBeforeContentLoaded: RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP,
|
|
610
|
+
injectedJavaScript: RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP,
|
|
611
|
+
injectedJavaScriptBeforeContentLoadedForMainFrameOnly: false,
|
|
612
|
+
injectedJavaScriptForMainFrameOnly: false,
|
|
497
613
|
javaScriptEnabled: true,
|
|
498
614
|
originWhitelist: returningAIOriginWhitelist(props.configuration.debug),
|
|
499
615
|
mixedContentMode: "never",
|
|
@@ -507,6 +623,7 @@ export function ReturningAIWidget(props: ReturningAIWidgetProps): ReactElement {
|
|
|
507
623
|
overScrollMode: "never",
|
|
508
624
|
startInLoadingState: false,
|
|
509
625
|
domStorageEnabled: true,
|
|
626
|
+
webviewDebuggingEnabled: props.configuration.debug,
|
|
510
627
|
testID: "returningai-webview",
|
|
511
628
|
});
|
|
512
629
|
|
|
@@ -588,6 +705,40 @@ const styles = StyleSheet.create({
|
|
|
588
705
|
},
|
|
589
706
|
});
|
|
590
707
|
|
|
708
|
+
/** True when a debug probe payload reports the inline shell scripts already ran. */
|
|
709
|
+
function debugProbeReportsShellScriptsRan(payload: string): boolean {
|
|
710
|
+
try {
|
|
711
|
+
const parsed = JSON.parse(payload) as { hasSdk?: unknown };
|
|
712
|
+
return parsed.hasSdk === true;
|
|
713
|
+
} catch {
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** Debug-only WebView lifecycle logs for RN CLI / Safari Web Inspector. */
|
|
719
|
+
function logReturningAIWebView(
|
|
720
|
+
configuration: ReturningAIWidgetConfiguration,
|
|
721
|
+
...parts: Array<string | number | boolean | undefined>
|
|
722
|
+
): void {
|
|
723
|
+
if (!configuration.debug) {
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
console.warn("[returningai-webview]", ...parts);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** Best-effort event name from a bridge JSON string for debug logs. */
|
|
730
|
+
function debugWebViewPayloadName(data: string): string {
|
|
731
|
+
try {
|
|
732
|
+
const parsed = JSON.parse(data) as { body?: { name?: unknown } };
|
|
733
|
+
if (typeof parsed.body?.name === "string") {
|
|
734
|
+
return parsed.body.name;
|
|
735
|
+
}
|
|
736
|
+
} catch {
|
|
737
|
+
// Ignore malformed debug payloads.
|
|
738
|
+
}
|
|
739
|
+
return data.slice(0, 120);
|
|
740
|
+
}
|
|
741
|
+
|
|
591
742
|
/** Converts ARGB integers to `#rrggbb` or `rgba(...)` for RN style props. */
|
|
592
743
|
function argbToCss(color: number): string {
|
|
593
744
|
const alpha = ((color >>> 24) & 0xff) / 255;
|
|
@@ -239,7 +239,8 @@ function defaultFetch(
|
|
|
239
239
|
signal: AbortSignal;
|
|
240
240
|
},
|
|
241
241
|
): Promise<Response> {
|
|
242
|
-
|
|
242
|
+
const { redirect: _redirect, ...rest } = init;
|
|
243
|
+
return fetch(input, rest);
|
|
243
244
|
}
|
|
244
245
|
|
|
245
246
|
/** True when the response is an opaque or 3xx redirect (auth must fail closed). */
|
|
@@ -248,8 +249,9 @@ function isRedirect(response: Response): boolean {
|
|
|
248
249
|
}
|
|
249
250
|
|
|
250
251
|
/**
|
|
251
|
-
*
|
|
252
|
-
*
|
|
252
|
+
* Reads an auth response body with a size cap.
|
|
253
|
+
* RN CLI `arrayBuffer()` / `getReader()` throw after HTTP 200; try `text()`,
|
|
254
|
+
* then `json()`, then `arrayBuffer()`, cloning between attempts.
|
|
253
255
|
*/
|
|
254
256
|
async function readLimited(
|
|
255
257
|
response: Response,
|
|
@@ -261,36 +263,94 @@ async function readLimited(
|
|
|
261
263
|
code: "malformedAuthenticationResponse",
|
|
262
264
|
message: "Authentication response exceeded the size limit.",
|
|
263
265
|
});
|
|
266
|
+
const unreadable = () =>
|
|
267
|
+
new ReturningAIWidgetError({
|
|
268
|
+
code: "malformedAuthenticationResponse",
|
|
269
|
+
message: "Authentication response body could not be read.",
|
|
270
|
+
});
|
|
264
271
|
const contentLength = response.headers.get("content-length");
|
|
265
272
|
if (contentLength !== null && Number(contentLength) > limitBytes) {
|
|
266
273
|
void response.body?.cancel().catch(() => undefined);
|
|
267
274
|
throw oversized();
|
|
268
275
|
}
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
276
|
+
|
|
277
|
+
const cancelBody = () => {
|
|
278
|
+
void response.body?.cancel().catch(() => undefined);
|
|
279
|
+
};
|
|
280
|
+
if (signal.aborted) {
|
|
281
|
+
cancelBody();
|
|
282
|
+
throw new DOMException("Aborted", "AbortError");
|
|
283
|
+
}
|
|
284
|
+
signal.addEventListener("abort", cancelBody, { once: true });
|
|
285
|
+
|
|
286
|
+
const attempts: Array<(res: Response) => Promise<string>> = [
|
|
287
|
+
async (res) => {
|
|
288
|
+
if (typeof res.text !== "function") {
|
|
289
|
+
throw new Error("text unavailable");
|
|
290
|
+
}
|
|
291
|
+
const text = await raceAbort(res.text(), signal);
|
|
292
|
+
if (text.length > limitBytes) {
|
|
293
|
+
throw oversized();
|
|
294
|
+
}
|
|
295
|
+
return text;
|
|
296
|
+
},
|
|
297
|
+
async (res) => {
|
|
298
|
+
if (typeof res.json !== "function") {
|
|
299
|
+
throw new Error("json unavailable");
|
|
300
|
+
}
|
|
301
|
+
const parsed: unknown = await raceAbort(res.json(), signal);
|
|
302
|
+
const text = JSON.stringify(parsed);
|
|
303
|
+
if (text.length > limitBytes) {
|
|
304
|
+
throw oversized();
|
|
305
|
+
}
|
|
306
|
+
return text;
|
|
307
|
+
},
|
|
308
|
+
async (res) => {
|
|
309
|
+
if (typeof res.arrayBuffer !== "function") {
|
|
310
|
+
throw new Error("arrayBuffer unavailable");
|
|
311
|
+
}
|
|
312
|
+
const bytes = new Uint8Array(await raceAbort(res.arrayBuffer(), signal));
|
|
313
|
+
if (bytes.byteLength > limitBytes) {
|
|
314
|
+
throw oversized();
|
|
315
|
+
}
|
|
316
|
+
return new TextDecoder().decode(bytes);
|
|
317
|
+
},
|
|
318
|
+
];
|
|
319
|
+
|
|
320
|
+
try {
|
|
321
|
+
let current: Response | undefined = response;
|
|
322
|
+
for (const attempt of attempts) {
|
|
323
|
+
if (current === undefined) {
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
const backup = cloneAuthResponse(current);
|
|
327
|
+
try {
|
|
328
|
+
return await attempt(current);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
if (error instanceof ReturningAIWidgetError) {
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
if (signal.aborted) {
|
|
334
|
+
throw error;
|
|
280
335
|
}
|
|
281
|
-
|
|
282
|
-
bytes.set(next.value, length);
|
|
283
|
-
length += next.value.byteLength;
|
|
336
|
+
current = backup;
|
|
284
337
|
}
|
|
285
|
-
return new TextDecoder().decode(bytes.subarray(0, length));
|
|
286
|
-
} finally {
|
|
287
|
-
if (!complete) void reader.cancel().catch(() => undefined);
|
|
288
|
-
reader.releaseLock();
|
|
289
338
|
}
|
|
339
|
+
throw unreadable();
|
|
340
|
+
} finally {
|
|
341
|
+
signal.removeEventListener("abort", cancelBody);
|
|
290
342
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function cloneAuthResponse(response: Response): Response | undefined {
|
|
346
|
+
try {
|
|
347
|
+
if (typeof response.clone === "function") {
|
|
348
|
+
return response.clone();
|
|
349
|
+
}
|
|
350
|
+
} catch {
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
return undefined;
|
|
294
354
|
}
|
|
295
355
|
|
|
296
356
|
/** Parses a JSON object body; arrays and scalars are treated as malformed. */
|
|
@@ -164,7 +164,7 @@ export class ReturningAIWidgetConfiguration {
|
|
|
164
164
|
readonly debug: boolean;
|
|
165
165
|
|
|
166
166
|
/** Parsed {@link DEFAULT_RUNTIME_URL}. */
|
|
167
|
-
static readonly defaultRuntimeUrl =
|
|
167
|
+
static readonly defaultRuntimeUrl = parseUrl(DEFAULT_RUNTIME_URL);
|
|
168
168
|
/** Default callback allowlist as a mutable `Set` copy source. */
|
|
169
169
|
static readonly defaultCallbackNames = new Set(DEFAULT_CALLBACK_NAMES);
|
|
170
170
|
|
|
@@ -10,23 +10,91 @@
|
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Parses a string into a `URL`, or returns the existing `URL` instance.
|
|
13
|
+
* Percent-encodes `@` in the path first so RN/Hermes does not treat
|
|
14
|
+
* `unpkg.com/@scope` as `userinfo@host` (`https://returningai/@returningai/...`).
|
|
13
15
|
* @param value - Absolute URL string or `URL`
|
|
14
16
|
* @returns Parsed `URL`
|
|
15
17
|
*/
|
|
16
18
|
export function parseUrl(value: string | URL): URL {
|
|
17
|
-
|
|
19
|
+
const raw = value instanceof URL ? restoreHermesScopedPackageHref(value) : value;
|
|
20
|
+
return new URL(encodeAtInUrlPath(raw));
|
|
18
21
|
}
|
|
19
22
|
|
|
20
23
|
/**
|
|
21
24
|
* Formats a URL similarly to Java `URI.toString()` for HTTPS origins (no forced trailing slash).
|
|
25
|
+
* Recovers unpkg scoped-package URLs that Hermes parsed as `userinfo@host`.
|
|
22
26
|
* @param url - URL to format
|
|
23
27
|
* @returns Canonical string without a lone `/` pathname
|
|
24
28
|
*/
|
|
25
29
|
export function formatUrl(url: URL): string {
|
|
30
|
+
const recovered = recoverHermesUnpkgScopedUrl(url);
|
|
31
|
+
if (recovered !== undefined) {
|
|
32
|
+
return recovered;
|
|
33
|
+
}
|
|
26
34
|
const pathname = url.pathname === "/" ? "" : url.pathname;
|
|
27
35
|
return `${url.protocol}//${url.host}${pathname}${url.search}${url.hash}`;
|
|
28
36
|
}
|
|
29
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Like {@link formatUrl} but percent-encodes path `@` so HTML / `<base href>` /
|
|
40
|
+
* WKWebView do not parse `unpkg.com/@scope` as `userinfo@host`.
|
|
41
|
+
*/
|
|
42
|
+
export function formatHtmlUrl(url: URL): string {
|
|
43
|
+
return encodeAtInUrlPath(formatUrl(url));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `https://unpkg.com/@scope/pkg` — encode path `@` so it is not parsed as userinfo.
|
|
48
|
+
*/
|
|
49
|
+
function encodeAtInUrlPath(value: string): string {
|
|
50
|
+
const schemeEnd = value.indexOf("://");
|
|
51
|
+
if (schemeEnd === -1) {
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
const pathStart = value.indexOf("/", schemeEnd + 3);
|
|
55
|
+
if (pathStart === -1) {
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
const authority = value.slice(0, pathStart);
|
|
59
|
+
if (authority.includes("@")) {
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
return `${authority}${value.slice(pathStart).replace(/@/g, "%40")}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Rebuilds a string for `new URL` when Hermes already split `unpkg.com/@scope`.
|
|
67
|
+
*/
|
|
68
|
+
function restoreHermesScopedPackageHref(url: URL): string {
|
|
69
|
+
const recovered = recoverHermesUnpkgScopedUrl(url);
|
|
70
|
+
return recovered ?? url.href;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Hermes/RN `URL` parses `https://unpkg.com/@returningai/widget-sdk/...` as
|
|
75
|
+
* username `unpkg.com`, hostname `returningai`. `formatUrl` then dropped the
|
|
76
|
+
* username and the WebView requested `https://returningai/@returningai/...`.
|
|
77
|
+
*/
|
|
78
|
+
function recoverHermesUnpkgScopedUrl(url: URL): string | undefined {
|
|
79
|
+
const user = url.username;
|
|
80
|
+
const hostIsScopedName = url.hostname.length > 0 && !url.hostname.includes(".");
|
|
81
|
+
if (user.includes(".") && hostIsScopedName) {
|
|
82
|
+
const path =
|
|
83
|
+
url.pathname.startsWith("/@") || url.pathname.startsWith("/%40")
|
|
84
|
+
? url.pathname
|
|
85
|
+
: `/@${url.hostname}${url.pathname === "/" ? "" : url.pathname}`;
|
|
86
|
+
return `${url.protocol}//${user}${path}${url.search}${url.hash}`;
|
|
87
|
+
}
|
|
88
|
+
if (url.hostname === "returningai") {
|
|
89
|
+
const path =
|
|
90
|
+
url.pathname.startsWith("/@") || url.pathname.startsWith("/%40")
|
|
91
|
+
? url.pathname
|
|
92
|
+
: `/@returningai${url.pathname === "/" ? "" : url.pathname}`;
|
|
93
|
+
return `https://unpkg.com${path}${url.search}${url.hash}`;
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
30
98
|
/**
|
|
31
99
|
* Whether a hostname is a localhost loopback name.
|
|
32
100
|
* @param host - Hostname (case-insensitive)
|
|
@@ -90,15 +90,8 @@ export class ReturningAINavigationPolicy {
|
|
|
90
90
|
|
|
91
91
|
/**
|
|
92
92
|
* iOS `loadHTMLString:baseURL:` may navigate to `about:blank`, `about:srcdoc`,
|
|
93
|
-
* or `applewebdata://` instead of the content-origin HTTPS URL.
|
|
93
|
+
* other `about:` URLs, or `applewebdata://` instead of the content-origin HTTPS URL.
|
|
94
94
|
*/
|
|
95
95
|
function isHtmlShellNavigation(uri: URL, scheme: string): boolean {
|
|
96
|
-
|
|
97
|
-
return true;
|
|
98
|
-
}
|
|
99
|
-
if (scheme !== "about") {
|
|
100
|
-
return false;
|
|
101
|
-
}
|
|
102
|
-
const href = uri.href.toLowerCase();
|
|
103
|
-
return href === "about:blank" || href === "about:srcdoc";
|
|
96
|
+
return scheme === "applewebdata" || scheme === "about";
|
|
104
97
|
}
|
package/src/packageInfo.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
export const RETURNING_AI_REACT_NATIVE_PACKAGE = {
|
|
15
15
|
/** Semver of `@returningai/react-native-widget-sdk`. */
|
|
16
|
-
version: "0.1.
|
|
16
|
+
version: "0.1.2",
|
|
17
17
|
/** Documented Expo SDK major this package targets. */
|
|
18
18
|
expoSdk: 57,
|
|
19
19
|
/** Documented React Native minor this package targets. */
|
|
@@ -19,6 +19,7 @@ import { encodeReturningAIJson, encodeReturningAIJsonForScript } from "../errors
|
|
|
19
19
|
import {
|
|
20
20
|
argbToRadixString,
|
|
21
21
|
escapeAttribute,
|
|
22
|
+
formatHtmlUrl,
|
|
22
23
|
formatUrl,
|
|
23
24
|
originOf,
|
|
24
25
|
siblingResource,
|
|
@@ -58,7 +59,7 @@ export function renderReturningAIHtml(input: {
|
|
|
58
59
|
const darkBackground = shellBackgroundCss(validated, "dark");
|
|
59
60
|
const pageBackground = theme === "dark" ? darkBackground : lightBackground;
|
|
60
61
|
const htmlLang = escapeAttribute(validated.locale ?? "en");
|
|
61
|
-
const runtimeSrc = escapeAttribute(
|
|
62
|
+
const runtimeSrc = escapeAttribute(formatHtmlUrl(validated.runtimeUrl));
|
|
62
63
|
const nativeAuthJson = encodeReturningAIJsonForScript(NATIVE_AUTH_URL);
|
|
63
64
|
const elementTagJson = encodeReturningAIJsonForScript(validated.widget.elementTag);
|
|
64
65
|
const lightJson = encodeReturningAIJson(lightBackground);
|
|
@@ -70,6 +71,7 @@ export function renderReturningAIHtml(input: {
|
|
|
70
71
|
<head>
|
|
71
72
|
<meta charset="utf-8">
|
|
72
73
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
|
|
74
|
+
${renderDocumentBaseHref(validated)}
|
|
73
75
|
${renderResourceHints(validated)}
|
|
74
76
|
<style>
|
|
75
77
|
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: ${pageBackground}; }
|
|
@@ -94,8 +96,24 @@ export function renderReturningAIHtml(input: {
|
|
|
94
96
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
95
97
|
}
|
|
96
98
|
|
|
99
|
+
function ensureBridge() {
|
|
100
|
+
if (window.${bridgeName} && typeof window.${bridgeName}.postMessage === "function") return;
|
|
101
|
+
window.${bridgeName} = {
|
|
102
|
+
postMessage: function(data) {
|
|
103
|
+
var payload = typeof data === "string" ? data : String(data);
|
|
104
|
+
var webView = window.ReactNativeWebView;
|
|
105
|
+
if (webView && typeof webView.postMessage === "function") {
|
|
106
|
+
webView.postMessage(payload);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
var handlers = window.webkit && window.webkit.messageHandlers;
|
|
110
|
+
if (handlers && handlers.ReactNativeWebView) handlers.ReactNativeWebView.postMessage(payload);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
97
115
|
function post(body, requestId) {
|
|
98
|
-
|
|
116
|
+
ensureBridge();
|
|
99
117
|
window.${bridgeName}.postMessage(JSON.stringify({ version, instanceId, bridgeToken, requestId, body }));
|
|
100
118
|
}
|
|
101
119
|
|
|
@@ -289,6 +307,18 @@ function renderElement(
|
|
|
289
307
|
return `<${configuration.widget.elementTag}\n ${attributeText}>\n </${configuration.widget.elementTag}>`;
|
|
290
308
|
}
|
|
291
309
|
|
|
310
|
+
/**
|
|
311
|
+
* Document `<base href>` so relative URLs resolve to the widget origin.
|
|
312
|
+
*/
|
|
313
|
+
function renderDocumentBaseHref(configuration: ReturningAIWidgetConfiguration): string {
|
|
314
|
+
const origin = originOf(configuration.content.url);
|
|
315
|
+
if (!origin) {
|
|
316
|
+
return "";
|
|
317
|
+
}
|
|
318
|
+
const href = origin.endsWith("/") ? origin : `${origin}/`;
|
|
319
|
+
return `<base href="${escapeAttribute(href)}">`;
|
|
320
|
+
}
|
|
321
|
+
|
|
292
322
|
/** Preconnect/preload hints for runtime and bundle siblings (`app.js` / `style.css`). */
|
|
293
323
|
function renderResourceHints(configuration: ReturningAIWidgetConfiguration): string {
|
|
294
324
|
const origins = new Set<string>();
|
|
@@ -301,7 +331,7 @@ function renderResourceHints(configuration: ReturningAIWidgetConfiguration): str
|
|
|
301
331
|
hints.push(`<link rel="preconnect" href="${escapeAttribute(origin)}">`);
|
|
302
332
|
}
|
|
303
333
|
hints.push(
|
|
304
|
-
`<link rel="preload" as="script" href="${escapeAttribute(
|
|
334
|
+
`<link rel="preload" as="script" href="${escapeAttribute(formatHtmlUrl(configuration.runtimeUrl))}">`,
|
|
305
335
|
);
|
|
306
336
|
if (configuration.content.kind === "bundle") {
|
|
307
337
|
const bundle = configuration.content.url;
|
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
* See also: ReturningAIWebViewDriver.ts, ReturningAIWidget.tsx, webview/bridgeBootstrap.ts
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import { Platform } from "react-native";
|
|
11
|
+
|
|
12
|
+
import { RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX } from "./bridgeBootstrap";
|
|
10
13
|
import type { ReturningAIWebViewDriver } from "./ReturningAIWebViewDriver";
|
|
11
14
|
|
|
12
15
|
/**
|
|
@@ -111,6 +114,43 @@ export class ReturningAIReactNativeWebViewDriver implements ReturningAIWebViewDr
|
|
|
111
114
|
await Promise.resolve();
|
|
112
115
|
}
|
|
113
116
|
|
|
117
|
+
/**
|
|
118
|
+
* iOS: if `location.origin` is not HTTPS (opaque `about:blank` on RN CLI),
|
|
119
|
+
* navigate to the content origin. Expo already has an HTTPS origin and no-ops.
|
|
120
|
+
*/
|
|
121
|
+
async promoteHtmlShellOriginIfNeeded(): Promise<void> {
|
|
122
|
+
if (Platform.OS !== "ios" || this.loadedBaseUrl === undefined) {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (!this.loadedBaseUrl.startsWith("https:")) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
await this.runJavaScript(returningAIReplaceAboutBlankWithContentOrigin(this.loadedBaseUrl));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* iOS: writes the stored HTML unless the shell scripts already ran.
|
|
133
|
+
* `loadHTMLString` can parse markup (widget root in the DOM) without executing
|
|
134
|
+
* scripts. After the HTTPS origin load, this re-applies the shell so modules run.
|
|
135
|
+
*/
|
|
136
|
+
async applyHtmlIfDocumentEmpty(): Promise<void> {
|
|
137
|
+
if (Platform.OS !== "ios" || this.loadedHtml === undefined) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
await this.runJavaScript(returningAIApplyHtmlIfMissingScript(this.loadedHtml));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* iOS: `loadHTMLString` / `document.write` often leave `script[src]` in the DOM
|
|
145
|
+
* without executing them. Re-append until the widget custom element is defined.
|
|
146
|
+
*/
|
|
147
|
+
async ensureExternalScripts(): Promise<void> {
|
|
148
|
+
if (Platform.OS !== "ios") {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
await this.runJavaScript(RETURNING_AI_ENSURE_EXTERNAL_SCRIPTS);
|
|
152
|
+
}
|
|
153
|
+
|
|
114
154
|
/**
|
|
115
155
|
* Marks the driver disposed and drops the handle + pending scripts.
|
|
116
156
|
*/
|
|
@@ -134,3 +174,81 @@ export function returningAIInjectableScript(source: string): string {
|
|
|
134
174
|
}
|
|
135
175
|
return `${trimmed}\ntrue;`;
|
|
136
176
|
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* iOS `loadHTMLString` often parses markup without running scripts (`hasRoot` with
|
|
180
|
+
* no `__RETURNINGAI_MOBILE_SDK__`). `document.write` reapplies the shell so
|
|
181
|
+
* scripts execute. Skip when the SDK flag is already set so we do not loop.
|
|
182
|
+
* @param html - Generated shell HTML (must not contain embed tokens)
|
|
183
|
+
*/
|
|
184
|
+
export function returningAIApplyHtmlIfMissingScript(html: string): string {
|
|
185
|
+
return `(function() {
|
|
186
|
+
"use strict";
|
|
187
|
+
try {
|
|
188
|
+
if (window.__RETURNINGAI_MOBILE_SDK__) return;
|
|
189
|
+
document.open("text/html", "replace");
|
|
190
|
+
document.write(${JSON.stringify(html)});
|
|
191
|
+
document.close();
|
|
192
|
+
} catch (_) {}
|
|
193
|
+
})();
|
|
194
|
+
true;`;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Expo `loadHTMLString` assigns an HTTPS `location.origin` even when href is
|
|
199
|
+
* `about:blank` — skip. RN CLI leaves a null origin; replace with the HTTPS base
|
|
200
|
+
* so widget modules can load, then `document.write` applies the stored shell.
|
|
201
|
+
* @param baseUrl - HTTPS content-origin document base
|
|
202
|
+
*/
|
|
203
|
+
export function returningAIReplaceAboutBlankWithContentOrigin(baseUrl: string): string {
|
|
204
|
+
return `(function() {
|
|
205
|
+
"use strict";
|
|
206
|
+
try {
|
|
207
|
+
var origin = "";
|
|
208
|
+
try { origin = String(location.origin || ""); } catch (_) {}
|
|
209
|
+
if (origin.indexOf("https:") === 0 || origin.indexOf("http:") === 0) return;
|
|
210
|
+
location.replace(${JSON.stringify(baseUrl)});
|
|
211
|
+
} catch (_) {}
|
|
212
|
+
})();
|
|
213
|
+
true;`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Re-inserts `script[src]` nodes when the widget custom element was never defined.
|
|
218
|
+
* WKWebView on RN CLI often parses those tags without fetching/executing them.
|
|
219
|
+
*/
|
|
220
|
+
export const RETURNING_AI_ENSURE_EXTERNAL_SCRIPTS = `(function() {
|
|
221
|
+
"use strict";
|
|
222
|
+
try {
|
|
223
|
+
var root = document.getElementById("returning-ai-widget-root");
|
|
224
|
+
if (root && window.customElements && window.customElements.get(root.localName)) return;
|
|
225
|
+
var nodes = Array.prototype.slice.call(document.querySelectorAll("script[src]"));
|
|
226
|
+
for (var i = 0; i < nodes.length; i++) {
|
|
227
|
+
var old = nodes[i];
|
|
228
|
+
var src = old.getAttribute("src");
|
|
229
|
+
if (!src || !old.parentNode) continue;
|
|
230
|
+
src = src.replace("://returningai/", "://unpkg.com/");
|
|
231
|
+
src = src.split("unpkg.com/@").join("unpkg.com/%40");
|
|
232
|
+
var s = document.createElement("script");
|
|
233
|
+
s.src = src;
|
|
234
|
+
(function(scriptSrc, node) {
|
|
235
|
+
node.onload = function() {
|
|
236
|
+
try {
|
|
237
|
+
if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
|
238
|
+
window.ReactNativeWebView.postMessage("${RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX}" + JSON.stringify({ runtimeLoaded: true, src: scriptSrc }));
|
|
239
|
+
}
|
|
240
|
+
} catch (_) {}
|
|
241
|
+
};
|
|
242
|
+
node.onerror = function() {
|
|
243
|
+
try {
|
|
244
|
+
if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
|
245
|
+
window.ReactNativeWebView.postMessage("${RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX}" + JSON.stringify({ runtimeError: true, src: scriptSrc }));
|
|
246
|
+
}
|
|
247
|
+
} catch (_) {}
|
|
248
|
+
};
|
|
249
|
+
})(src, s);
|
|
250
|
+
old.parentNode.replaceChild(s, old);
|
|
251
|
+
}
|
|
252
|
+
} catch (_) {}
|
|
253
|
+
})();
|
|
254
|
+
true;`;
|
|
@@ -89,9 +89,84 @@ export function normalizeReturningAIOrigin(origin: string): string {
|
|
|
89
89
|
return origin.trim().replace(/\/+$/, "").toLowerCase();
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
92
|
+
/**
|
|
93
|
+
* True when the WebView is reporting the local HTML shell rather than a fetched URL.
|
|
94
|
+
* RN CLI / iOS 26 may omit the URL (`""`) for `loadHTMLString:baseURL:` before the
|
|
95
|
+
* document origin is assigned. Envelope identity still gates bridge payloads.
|
|
96
|
+
* All `about:` URLs are treated as the shell — iOS 26 has used values other than
|
|
97
|
+
* `about:blank` / `about:srcdoc`.
|
|
98
|
+
* @param sourceUrl - `nativeEvent.url` or `ShouldStartLoadRequest.url`
|
|
99
|
+
*/
|
|
100
|
+
export function isReturningAIHtmlShellDocumentUrl(sourceUrl: string | undefined): boolean {
|
|
101
|
+
if (sourceUrl === undefined || sourceUrl.trim().length === 0) {
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
const url = sourceUrl.trim().toLowerCase();
|
|
105
|
+
return url.startsWith("about:") || url.startsWith("applewebdata:");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* True when `sourceUrl` is exactly the HTML `baseUrl` origin root (`https://host/`).
|
|
110
|
+
* @param sourceUrl - Navigation or message URL
|
|
111
|
+
* @param configuration - Widget configuration used to compute the document base
|
|
112
|
+
*/
|
|
113
|
+
export function isReturningAIContentOriginRootUrl(
|
|
114
|
+
sourceUrl: string,
|
|
115
|
+
configuration: ReturningAIWidgetConfiguration,
|
|
116
|
+
): boolean {
|
|
117
|
+
const baseUrl = returningAIDocumentBaseUrl(configuration);
|
|
118
|
+
if (baseUrl === undefined) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const uri = new URL(sourceUrl);
|
|
123
|
+
const expected = new URL(baseUrl);
|
|
124
|
+
if (uri.protocol !== expected.protocol) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
if (uri.hostname.toLowerCase() !== expected.hostname.toLowerCase()) {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
if (uri.port !== expected.port) {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
const path = uri.pathname.length === 0 ? "/" : uri.pathname;
|
|
134
|
+
return path === "/" && uri.search === "" && uri.hash === "";
|
|
135
|
+
} catch {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Cancels the follow-up GET of `https://host/` that WKWebView issues after
|
|
142
|
+
* `loadHTMLString:baseURL:` **once the HTML shell is live**. The first framed
|
|
143
|
+
* GET of `/` is allowed so RN CLI / iOS 26 can assign the HTTPS document origin;
|
|
144
|
+
* later ones replace the written shell. Subresources (`/widget.js`) still load.
|
|
145
|
+
* @param input.url - `ShouldStartLoadRequest.url`
|
|
146
|
+
* @param input.isTopFrame - Main-frame vs subframe (`undefined` treated as main)
|
|
147
|
+
* @param input.hasTargetFrame - Native `targetFrame != nil`. The HTML string
|
|
148
|
+
* load reports `false`; a later GET of `/` reports `true`.
|
|
149
|
+
* @param input.configuration - Widget configuration
|
|
150
|
+
*/
|
|
151
|
+
export function shouldCancelReturningAIContentOriginRootRefetch(input: {
|
|
152
|
+
url: string;
|
|
153
|
+
isTopFrame?: boolean;
|
|
154
|
+
hasTargetFrame?: boolean;
|
|
155
|
+
configuration: ReturningAIWidgetConfiguration;
|
|
156
|
+
}): boolean {
|
|
157
|
+
// loadHTMLString itself is reported as this URL with a nil targetFrame.
|
|
158
|
+
// Cancelling that navigation blanks the WebView. Only a later framed GET of
|
|
159
|
+
// `/` should be blocked.
|
|
160
|
+
if (input.hasTargetFrame !== true) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
if (input.isTopFrame === false) {
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
if (isReturningAIHtmlShellDocumentUrl(input.url)) {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
return isReturningAIContentOriginRootUrl(input.url, input.configuration);
|
|
95
170
|
}
|
|
96
171
|
|
|
97
172
|
/**
|
|
@@ -117,8 +192,8 @@ export function shouldAcceptReturningAIWebMessage(
|
|
|
117
192
|
/**
|
|
118
193
|
* RN-specific gate for delivering `onMessage` payloads to the coordinator.
|
|
119
194
|
* When no expected origin is configured, delivery is allowed (fail-open only then).
|
|
120
|
-
* iOS may report `about:blank`, `about:srcdoc`,
|
|
121
|
-
* with a content-origin baseUrl; envelope identity still gates.
|
|
195
|
+
* iOS may report `about:blank`, `about:srcdoc`, `applewebdata://`, or an empty
|
|
196
|
+
* URL for HTML with a content-origin baseUrl; envelope identity still gates.
|
|
122
197
|
* @param input.sourceUrl - `nativeEvent.url` from react-native-webview
|
|
123
198
|
* @param input.expectedOrigin - Expected origin from configuration
|
|
124
199
|
* @returns True when the message should be decoded
|
|
@@ -130,15 +205,15 @@ export function shouldDeliverReturningAIWebMessage(input: {
|
|
|
130
205
|
if (input.expectedOrigin === undefined) {
|
|
131
206
|
return true;
|
|
132
207
|
}
|
|
208
|
+
// Native iOS WKWebView reports about:blank, about:srcdoc, applewebdata, or
|
|
209
|
+
// an empty URL for HTML loaded with a content-origin baseUrl.
|
|
210
|
+
if (isReturningAIHtmlShellDocumentUrl(input.sourceUrl)) {
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
133
213
|
const sourceUrl = input.sourceUrl;
|
|
134
|
-
if (sourceUrl === undefined
|
|
214
|
+
if (sourceUrl === undefined) {
|
|
135
215
|
return false;
|
|
136
216
|
}
|
|
137
|
-
// Native iOS WKWebView reports about:blank, about:srcdoc, or applewebdata
|
|
138
|
-
// for HTML loaded with a content-origin baseUrl. Envelope identity still gates.
|
|
139
|
-
if (isHtmlShellDocumentUrl(sourceUrl)) {
|
|
140
|
-
return true;
|
|
141
|
-
}
|
|
142
217
|
try {
|
|
143
218
|
return shouldAcceptReturningAIWebMessage(true, new URL(sourceUrl).origin, input.expectedOrigin);
|
|
144
219
|
} catch {
|
|
@@ -17,10 +17,52 @@ export const RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP = `(function() {
|
|
|
17
17
|
if (window.ReturningAIReactNativeBridge) return;
|
|
18
18
|
window.ReturningAIReactNativeBridge = {
|
|
19
19
|
postMessage: function(data) {
|
|
20
|
+
var payload = typeof data === "string" ? data : String(data);
|
|
20
21
|
var webView = window.ReactNativeWebView;
|
|
21
|
-
if (
|
|
22
|
-
|
|
22
|
+
if (webView && typeof webView.postMessage === "function") {
|
|
23
|
+
webView.postMessage(payload);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
var handlers = window.webkit && window.webkit.messageHandlers;
|
|
27
|
+
if (handlers && handlers.ReactNativeWebView) {
|
|
28
|
+
handlers.ReactNativeWebView.postMessage(payload);
|
|
29
|
+
}
|
|
23
30
|
}
|
|
24
31
|
};
|
|
25
32
|
})();
|
|
26
33
|
true;`;
|
|
34
|
+
|
|
35
|
+
/** Prefix for host-only WebView diagnostics; not a bridge envelope. */
|
|
36
|
+
export const RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX = "__rai_debug__";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Injected after `onLoadEnd` when `configuration.debug` is true.
|
|
40
|
+
* Posts document URL and whether `ReactNativeWebView` / WK handlers exist.
|
|
41
|
+
*/
|
|
42
|
+
export const RETURNING_AI_REACT_NATIVE_WEBVIEW_DEBUG_PROBE = `(function() {
|
|
43
|
+
"use strict";
|
|
44
|
+
try {
|
|
45
|
+
var info = JSON.stringify({
|
|
46
|
+
href: String((typeof location !== "undefined" && location.href) || ""),
|
|
47
|
+
hasRN: !!(window.ReactNativeWebView && window.ReactNativeWebView.postMessage),
|
|
48
|
+
hasWK: !!(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.ReactNativeWebView),
|
|
49
|
+
hasRoot: !!document.getElementById("returning-ai-widget-root"),
|
|
50
|
+
hasSdk: !!window.__RETURNINGAI_MOBILE_SDK__,
|
|
51
|
+
origin: String((typeof location !== "undefined" && location.origin) || ""),
|
|
52
|
+
ce: (function() {
|
|
53
|
+
var root = document.getElementById("returning-ai-widget-root");
|
|
54
|
+
return !!(root && window.customElements && window.customElements.get(root.localName));
|
|
55
|
+
})(),
|
|
56
|
+
runtime: (function() {
|
|
57
|
+
var node = document.querySelector("script[src]");
|
|
58
|
+
return node ? String(node.getAttribute("src") || "") : "";
|
|
59
|
+
})(),
|
|
60
|
+
tags: document.getElementsByTagName("*").length,
|
|
61
|
+
scripts: document.scripts ? document.scripts.length : 0
|
|
62
|
+
});
|
|
63
|
+
if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === "function") {
|
|
64
|
+
window.ReactNativeWebView.postMessage("${RETURNING_AI_REACT_NATIVE_DEBUG_MESSAGE_PREFIX}" + info);
|
|
65
|
+
}
|
|
66
|
+
} catch (_) {}
|
|
67
|
+
})();
|
|
68
|
+
true;`;
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* Layer: webview
|
|
5
5
|
* Role: Returns allowed origin patterns for the WebView; debug adds localhost/127.0.0.1 HTTP entries.
|
|
6
6
|
* Does not decide navigation allow/delegate/reject (navigation policy does).
|
|
7
|
-
* Security:
|
|
7
|
+
* Security: Coarse WebView pre-filter is HTTPS + HTML-shell origins + `*`.
|
|
8
|
+
* Navigation policy is the real allow/delegate/reject gate.
|
|
8
9
|
* See also: navigation/ReturningAINavigationPolicy.ts, ReturningAIWidget.tsx
|
|
9
10
|
*/
|
|
10
11
|
|
|
@@ -15,12 +16,14 @@ const htmlShellOrigins = ["about:blank", "about:srcdoc", "applewebdata://*"] as
|
|
|
15
16
|
* Builds the `originWhitelist` patterns for `react-native-webview`.
|
|
16
17
|
* Production allows HTTPS plus HTML-string shell origins; debug also allows localhost HTTP.
|
|
17
18
|
* Native iOS WKWebView (not Expo Go) may report `about:srcdoc` for `loadHTMLString`.
|
|
19
|
+
* `*` is last so RN CLI / iOS 26 empty document URLs are not cancelled before JS policy runs.
|
|
20
|
+
* Navigation policy remains the real allow/delegate/reject gate.
|
|
18
21
|
* @param debug - Configuration debug flag
|
|
19
22
|
* @returns Origin pattern list for the WebView prop
|
|
20
23
|
*/
|
|
21
24
|
export function returningAIOriginWhitelist(debug: boolean): string[] {
|
|
22
25
|
if (debug) {
|
|
23
|
-
return ["https://*", "http://localhost*", "http://127.0.0.1*", ...htmlShellOrigins];
|
|
26
|
+
return ["https://*", "http://localhost*", "http://127.0.0.1*", ...htmlShellOrigins, "*"];
|
|
24
27
|
}
|
|
25
|
-
return ["https://*", ...htmlShellOrigins];
|
|
28
|
+
return ["https://*", ...htmlShellOrigins, "*"];
|
|
26
29
|
}
|