@metarouter/react-native-sdk 1.7.0 → 1.9.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/README.md +302 -61
- package/android/build.gradle +2 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterClockModule.kt +24 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +3 -1
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterWebViewSupportModule.kt +27 -0
- package/ios/MetaRouterClock.m +31 -0
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +71 -2
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +313 -51
- package/lib/analytics/init.d.ts +7 -0
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +210 -37
- package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
- package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
- package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
- package/lib/analytics/proxy/proxyClient.d.ts +31 -0
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +153 -6
- package/lib/analytics/session/sessionManager.d.ts +108 -0
- package/lib/analytics/session/sessionManager.d.ts.map +1 -0
- package/lib/analytics/session/sessionManager.js +193 -0
- package/lib/analytics/types.d.ts +108 -1
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/appContext.d.ts +22 -0
- package/lib/analytics/utils/appContext.d.ts.map +1 -0
- package/lib/analytics/utils/appContext.js +23 -0
- package/lib/analytics/utils/contextInfo.d.ts +7 -3
- package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.js +12 -9
- package/lib/analytics/utils/enrichEvent.d.ts +6 -2
- package/lib/analytics/utils/enrichEvent.d.ts.map +1 -1
- package/lib/analytics/utils/enrichEvent.js +20 -3
- package/lib/analytics/utils/initOptions.d.ts +22 -0
- package/lib/analytics/utils/initOptions.d.ts.map +1 -0
- package/lib/analytics/utils/initOptions.js +107 -0
- package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
- package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
- package/lib/analytics/utils/lifecycleStorage.js +35 -0
- package/lib/analytics/utils/monotonicClock.d.ts +15 -0
- package/lib/analytics/utils/monotonicClock.d.ts.map +1 -0
- package/lib/analytics/utils/monotonicClock.js +52 -0
- package/lib/analytics/utils/sessionStorage.d.ts +27 -0
- package/lib/analytics/utils/sessionStorage.d.ts.map +1 -0
- package/lib/analytics/utils/sessionStorage.js +85 -0
- package/lib/analytics/webview/bridgeDedupStore.d.ts +37 -0
- package/lib/analytics/webview/bridgeDedupStore.d.ts.map +1 -0
- package/lib/analytics/webview/bridgeDedupStore.js +63 -0
- package/lib/analytics/webview/bridgeEnvelope.d.ts +68 -0
- package/lib/analytics/webview/bridgeEnvelope.d.ts.map +1 -0
- package/lib/analytics/webview/bridgeEnvelope.js +140 -0
- package/lib/analytics/webview/bridgeMessageProcessor.d.ts +38 -0
- package/lib/analytics/webview/bridgeMessageProcessor.d.ts.map +1 -0
- package/lib/analytics/webview/bridgeMessageProcessor.js +67 -0
- package/lib/analytics/webview/bridgeWrapperScript.d.ts +53 -0
- package/lib/analytics/webview/bridgeWrapperScript.d.ts.map +1 -0
- package/lib/analytics/webview/bridgeWrapperScript.js +161 -0
- package/lib/analytics/webview/webViewBridge.d.ts +39 -0
- package/lib/analytics/webview/webViewBridge.d.ts.map +1 -0
- package/lib/analytics/webview/webViewBridge.js +211 -0
- package/lib/analytics/webview/webViewSupport.d.ts +16 -0
- package/lib/analytics/webview/webViewSupport.d.ts.map +1 -0
- package/lib/analytics/webview/webViewSupport.js +52 -0
- package/lib/index.d.ts +4 -4
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -3
- package/package.json +11 -3
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
export const SUPPORTED_ENVELOPE_VERSION = 1;
|
|
2
|
+
/**
|
|
3
|
+
* Max envelope size accepted at the untrusted page→SDK boundary: a policy cap
|
|
4
|
+
* that bounds parse cost. 64 KiB sits well under the cluster's 250 KiB
|
|
5
|
+
* single-event ingest cap, leaving headroom for enrichment.
|
|
6
|
+
*/
|
|
7
|
+
export const MAX_ENVELOPE_BYTES = 64 * 1024;
|
|
8
|
+
// UUIDs are 36 chars; the ceiling keeps the dedup store bounded in bytes, not
|
|
9
|
+
// just entries — 1000 retained near-64 KB ids would be ~64 MB.
|
|
10
|
+
export const MAX_MESSAGE_ID_CHARS = 256;
|
|
11
|
+
/** UTF-8 byte length without allocating an encoded copy. */
|
|
12
|
+
function utf8ByteLength(s) {
|
|
13
|
+
let bytes = 0;
|
|
14
|
+
for (let i = 0; i < s.length; i++) {
|
|
15
|
+
const c = s.charCodeAt(i);
|
|
16
|
+
if (c < 0x80)
|
|
17
|
+
bytes += 1;
|
|
18
|
+
else if (c < 0x800)
|
|
19
|
+
bytes += 2;
|
|
20
|
+
else if (c >= 0xd800 &&
|
|
21
|
+
c <= 0xdbff &&
|
|
22
|
+
i + 1 < s.length &&
|
|
23
|
+
s.charCodeAt(i + 1) >= 0xdc00 &&
|
|
24
|
+
s.charCodeAt(i + 1) <= 0xdfff) {
|
|
25
|
+
// A surrogate pair is one 4-byte code point.
|
|
26
|
+
bytes += 4;
|
|
27
|
+
i++;
|
|
28
|
+
}
|
|
29
|
+
else
|
|
30
|
+
bytes += 3; // includes a lone surrogate, encoded as U+FFFD
|
|
31
|
+
}
|
|
32
|
+
return bytes;
|
|
33
|
+
}
|
|
34
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
35
|
+
const stringOrUndefined = (v) => typeof v === 'string' ? v : undefined;
|
|
36
|
+
/**
|
|
37
|
+
* Parses and validates a raw bridge message, with the same rules and messages
|
|
38
|
+
* as the iOS and Android parsers.
|
|
39
|
+
*
|
|
40
|
+
* Validation order: size (before parsing, so an oversized payload is never
|
|
41
|
+
* deserialized) → JSON → messageId → version → type → name → properties.
|
|
42
|
+
* Unknown fields are ignored so the web side can add optional fields without a
|
|
43
|
+
* version bump; optional fields of an unexpected type read as absent — only
|
|
44
|
+
* `properties`, which the merge depends on, is strict.
|
|
45
|
+
*/
|
|
46
|
+
export function parseBridgeEnvelope(raw) {
|
|
47
|
+
// A UTF-8 length is never below the UTF-16 length, so an over-length string
|
|
48
|
+
// is oversized without counting bytes.
|
|
49
|
+
if (raw.length > MAX_ENVELOPE_BYTES ||
|
|
50
|
+
utf8ByteLength(raw) > MAX_ENVELOPE_BYTES) {
|
|
51
|
+
return invalid('payload_too_large', `envelope exceeds ${MAX_ENVELOPE_BYTES} bytes`);
|
|
52
|
+
}
|
|
53
|
+
let root;
|
|
54
|
+
try {
|
|
55
|
+
root = JSON.parse(raw);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return invalid('malformed_json', 'envelope is not valid JSON');
|
|
59
|
+
}
|
|
60
|
+
if (!isObject(root)) {
|
|
61
|
+
return invalid('malformed_payload', 'envelope must be a JSON object');
|
|
62
|
+
}
|
|
63
|
+
// Extracted first so later rejections can echo it in the error reply.
|
|
64
|
+
const messageId = stringOrUndefined(root.messageId);
|
|
65
|
+
if (!messageId || messageId.trim() === '') {
|
|
66
|
+
return invalid('missing_field', 'messageId is required');
|
|
67
|
+
}
|
|
68
|
+
if (messageId.length > MAX_MESSAGE_ID_CHARS) {
|
|
69
|
+
// Not echoed: the reply would amplify the same bytes back to the page.
|
|
70
|
+
return invalid('malformed_payload', `messageId exceeds ${MAX_MESSAGE_ID_CHARS} chars`);
|
|
71
|
+
}
|
|
72
|
+
if (root.version === undefined) {
|
|
73
|
+
return invalid('missing_field', 'version is required', messageId);
|
|
74
|
+
}
|
|
75
|
+
const version = root.version;
|
|
76
|
+
if (typeof version !== 'number' || !Number.isSafeInteger(version)) {
|
|
77
|
+
return invalid('malformed_payload', 'version must be an integer', messageId);
|
|
78
|
+
}
|
|
79
|
+
if (version < 1) {
|
|
80
|
+
return invalid('malformed_payload', 'version must be >= 1', messageId);
|
|
81
|
+
}
|
|
82
|
+
if (version > SUPPORTED_ENVELOPE_VERSION) {
|
|
83
|
+
return {
|
|
84
|
+
...invalid('unsupported_version', `envelope version ${version} > supported ${SUPPORTED_ENVELOPE_VERSION}`, messageId),
|
|
85
|
+
supportedVersion: SUPPORTED_ENVELOPE_VERSION,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const type = stringOrUndefined(root.type);
|
|
89
|
+
if (type === undefined) {
|
|
90
|
+
return invalid('missing_field', 'type is required', messageId);
|
|
91
|
+
}
|
|
92
|
+
if (type !== 'track' && type !== 'page') {
|
|
93
|
+
return invalid('unknown_type', `type must be "track" or "page", got "${type}"`, messageId);
|
|
94
|
+
}
|
|
95
|
+
const name = stringOrUndefined(root.name);
|
|
96
|
+
if (!name || name.trim() === '') {
|
|
97
|
+
return invalid('missing_field', 'name is required', messageId);
|
|
98
|
+
}
|
|
99
|
+
let properties;
|
|
100
|
+
if (root.properties === undefined || root.properties === null) {
|
|
101
|
+
properties = {};
|
|
102
|
+
}
|
|
103
|
+
else if (isObject(root.properties)) {
|
|
104
|
+
properties = root.properties;
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
return invalid('malformed_payload', 'properties must be a JSON object', messageId);
|
|
108
|
+
}
|
|
109
|
+
const envelope = {
|
|
110
|
+
version,
|
|
111
|
+
messageId,
|
|
112
|
+
type,
|
|
113
|
+
name,
|
|
114
|
+
properties,
|
|
115
|
+
};
|
|
116
|
+
const sentAt = stringOrUndefined(root.sentAt);
|
|
117
|
+
if (sentAt !== undefined)
|
|
118
|
+
envelope.sentAt = sentAt;
|
|
119
|
+
if (isObject(root.page)) {
|
|
120
|
+
const page = {};
|
|
121
|
+
for (const key of ['url', 'path', 'search', 'title', 'referrer']) {
|
|
122
|
+
const value = stringOrUndefined(root.page[key]);
|
|
123
|
+
if (value !== undefined)
|
|
124
|
+
page[key] = value;
|
|
125
|
+
}
|
|
126
|
+
envelope.page = page;
|
|
127
|
+
}
|
|
128
|
+
if (isObject(root.source)) {
|
|
129
|
+
envelope.source = {
|
|
130
|
+
producer: stringOrUndefined(root.source.producer),
|
|
131
|
+
wrapperVersion: stringOrUndefined(root.source.wrapperVersion),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
return { valid: true, envelope };
|
|
135
|
+
}
|
|
136
|
+
function invalid(code, message, messageId) {
|
|
137
|
+
return messageId === undefined
|
|
138
|
+
? { valid: false, code, message }
|
|
139
|
+
: { valid: false, code, message, messageId };
|
|
140
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { BridgeDedupStore } from './bridgeDedupStore';
|
|
2
|
+
import { type BridgeEnvelope, type BridgeErrorCode } from './bridgeEnvelope';
|
|
3
|
+
/**
|
|
4
|
+
* Ack / error reply sent back to the wrapper. Wire shape (absent fields are
|
|
5
|
+
* omitted, as on iOS and Android):
|
|
6
|
+
* - ok: `{"status":"ok","messageId":"…"}`
|
|
7
|
+
* - error: `{"status":"error","messageId":"…","code":"…","message":"…","supportedVersion":1}`
|
|
8
|
+
*/
|
|
9
|
+
export interface BridgeReply {
|
|
10
|
+
status: 'ok' | 'error';
|
|
11
|
+
messageId?: string;
|
|
12
|
+
code?: BridgeErrorCode;
|
|
13
|
+
message?: string;
|
|
14
|
+
supportedVersion?: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Receives validated, deduplicated envelopes. Returns whether the event
|
|
18
|
+
* actually entered the delivery path: an `ok` ack for an event that was
|
|
19
|
+
* silently dropped (SDK not ready) would lie to the producer.
|
|
20
|
+
*/
|
|
21
|
+
export type BridgeEventSink = (envelope: BridgeEnvelope) => boolean;
|
|
22
|
+
/**
|
|
23
|
+
* The receive pipeline: raw message → parse/validate → dedup → sink, producing
|
|
24
|
+
* the reply for the wrapper. One processor serves every attached WebView of a
|
|
25
|
+
* session, like the native SDKs' one processor per client.
|
|
26
|
+
*
|
|
27
|
+
* Rejections are logged as well as replied — page consoles are rarely watched
|
|
28
|
+
* in production, so the app log is the primary debugging surface. JS is
|
|
29
|
+
* single-threaded, so the native "one confined thread" rule holds by
|
|
30
|
+
* construction.
|
|
31
|
+
*/
|
|
32
|
+
export declare class BridgeMessageProcessor {
|
|
33
|
+
private readonly sink;
|
|
34
|
+
private readonly dedupStore;
|
|
35
|
+
constructor(sink: BridgeEventSink, dedupStore?: BridgeDedupStore);
|
|
36
|
+
process(raw: string): BridgeReply;
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=bridgeMessageProcessor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bridgeMessageProcessor.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/bridgeMessageProcessor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,kBAAkB,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,QAAQ,EAAE,cAAc,KAAK,OAAO,CAAC;AAEpE;;;;;;;;;GASG;AACH,qBAAa,sBAAsB;IAE/B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,UAAU;gBADV,IAAI,EAAE,eAAe,EACrB,UAAU,GAAE,gBAAyC;IAGxE,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW;CAkDlC"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { log, warn } from '../utils/logger';
|
|
2
|
+
import { BridgeDedupStore } from './bridgeDedupStore';
|
|
3
|
+
import { parseBridgeEnvelope, } from './bridgeEnvelope';
|
|
4
|
+
/**
|
|
5
|
+
* The receive pipeline: raw message → parse/validate → dedup → sink, producing
|
|
6
|
+
* the reply for the wrapper. One processor serves every attached WebView of a
|
|
7
|
+
* session, like the native SDKs' one processor per client.
|
|
8
|
+
*
|
|
9
|
+
* Rejections are logged as well as replied — page consoles are rarely watched
|
|
10
|
+
* in production, so the app log is the primary debugging surface. JS is
|
|
11
|
+
* single-threaded, so the native "one confined thread" rule holds by
|
|
12
|
+
* construction.
|
|
13
|
+
*/
|
|
14
|
+
export class BridgeMessageProcessor {
|
|
15
|
+
constructor(sink, dedupStore = new BridgeDedupStore()) {
|
|
16
|
+
this.sink = sink;
|
|
17
|
+
this.dedupStore = dedupStore;
|
|
18
|
+
}
|
|
19
|
+
process(raw) {
|
|
20
|
+
const result = parseBridgeEnvelope(raw);
|
|
21
|
+
if (!result.valid) {
|
|
22
|
+
// Truncated: for unknown_type the message embeds page-controlled text,
|
|
23
|
+
// and a page could otherwise write 64 KB lines into the app log.
|
|
24
|
+
warn(`WebView bridge message rejected (${result.code}): ${result.message.slice(0, 200)}`);
|
|
25
|
+
// Key order matches the native serializers, so the wire form is
|
|
26
|
+
// byte-identical across platforms.
|
|
27
|
+
return {
|
|
28
|
+
status: 'error',
|
|
29
|
+
...(result.messageId !== undefined && { messageId: result.messageId }),
|
|
30
|
+
code: result.code,
|
|
31
|
+
message: result.message,
|
|
32
|
+
...(result.supportedVersion !== undefined && {
|
|
33
|
+
supportedVersion: result.supportedVersion,
|
|
34
|
+
}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const { envelope } = result;
|
|
38
|
+
if (!this.dedupStore.markIfNew(envelope.messageId)) {
|
|
39
|
+
// Acked ok, not errored: the producer's goal — exactly-once enqueue —
|
|
40
|
+
// was already met by the first delivery.
|
|
41
|
+
log(`WebView bridge duplicate dropped (messageId=${envelope.messageId})`);
|
|
42
|
+
return { status: 'ok', messageId: envelope.messageId };
|
|
43
|
+
}
|
|
44
|
+
let accepted = false;
|
|
45
|
+
try {
|
|
46
|
+
accepted = this.sink(envelope);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
warn('WebView bridge event enqueue failed:', err);
|
|
50
|
+
}
|
|
51
|
+
if (accepted) {
|
|
52
|
+
return { status: 'ok', messageId: envelope.messageId };
|
|
53
|
+
}
|
|
54
|
+
// Never entered the delivery path — un-record the id so a producer retry
|
|
55
|
+
// is not misread as a duplicate of a message that was in fact lost.
|
|
56
|
+
this.dedupStore.forget(envelope.messageId);
|
|
57
|
+
// Debug-level, as on iOS: expected while the SDK initializes or resets,
|
|
58
|
+
// and a page retrying in a loop must not flood the app log.
|
|
59
|
+
log(`WebView bridge event not accepted (messageId=${envelope.messageId})`);
|
|
60
|
+
return {
|
|
61
|
+
status: 'error',
|
|
62
|
+
messageId: envelope.messageId,
|
|
63
|
+
code: 'not_ready',
|
|
64
|
+
message: 'SDK not ready to accept events',
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export declare const DEFAULT_BRIDGE_OBJECT_NAME = "metarouterBridge";
|
|
2
|
+
/**
|
|
3
|
+
* Name of the `window` channel object the wrapper posts through and whose
|
|
4
|
+
* `onmessage` receives replies — the same name, and the same page-visible
|
|
5
|
+
* surface, as the iOS and Android SDKs.
|
|
6
|
+
*/
|
|
7
|
+
export declare const NATIVE_CHANNEL_NAME = "__metaRouterNativeChannel";
|
|
8
|
+
/**
|
|
9
|
+
* Prefix on every bridge message. `window.ReactNativeWebView.postMessage` is
|
|
10
|
+
* one channel shared with the host's own page→app messages (native has a
|
|
11
|
+
* dedicated one), so the prefix is what lets the SDK claim its messages and
|
|
12
|
+
* pass everything else through to the host untouched. The wrapper appends a
|
|
13
|
+
* per-session token after it (see attachWebViewBridge).
|
|
14
|
+
*/
|
|
15
|
+
export declare const BRIDGE_MESSAGE_PREFIX = "__metaRouterBridge:";
|
|
16
|
+
export declare const WRAPPER_VERSION = "1.0.0";
|
|
17
|
+
/**
|
|
18
|
+
* Builds the wrapper injected via `injectedJavaScriptBeforeContentLoaded`:
|
|
19
|
+
* at document start on iOS, at `onPageStarted` on Android (so a page's
|
|
20
|
+
* earliest inline scripts can run before it exists). Identical to the iOS and Android
|
|
21
|
+
* wrapper except for the channel shim:
|
|
22
|
+
*
|
|
23
|
+
* - Defines `window.metarouterBridge` with `track`/`page`, wraps each call in
|
|
24
|
+
* an envelope — minting `messageId` and stamping the page facts at call time
|
|
25
|
+
* — and posts it as a JSON string. `messageId` must be minted here: an id
|
|
26
|
+
* assigned at receipt would give two deliveries of one message two ids.
|
|
27
|
+
* - Self-checks `location.origin` against the allowlist and defines nothing on
|
|
28
|
+
* other pages. `react-native-webview` has no origin-scoped channel, so this
|
|
29
|
+
* check plus the SDK's check of the sending frame's URL carry the security
|
|
30
|
+
* model together, as on iOS.
|
|
31
|
+
* - The channel shim posts through `window.ReactNativeWebView`, resolved at
|
|
32
|
+
* call time, and exposes a settable `onmessage` that replies are delivered to.
|
|
33
|
+
* - `properties` may be an object or a JSON string; a string that fails to
|
|
34
|
+
* parse is forwarded as-is so the SDK rejects it with `malformed_payload`.
|
|
35
|
+
* - JSON.stringify is guarded: unstringifiable properties (circular, BigInt)
|
|
36
|
+
* are coerced to a string and re-posted, so the page gets a coded error
|
|
37
|
+
* reply, never a TypeError thrown into its own calling code.
|
|
38
|
+
*/
|
|
39
|
+
export declare function buildBridgeWrapperScript(allowedOrigins: readonly string[], bridgeObjectName?: string, messagePrefix?: string): string;
|
|
40
|
+
/**
|
|
41
|
+
* Reply delivery script, run in the page with the WebView ref's
|
|
42
|
+
* `injectJavaScript`. The reply JSON rides as a JS string literal, so the
|
|
43
|
+
* page-visible shape matches iOS and Android: `onmessage` receives an
|
|
44
|
+
* event-like object whose `data` is the reply string. The trailing `true;` is
|
|
45
|
+
* what react-native-webview asks injected scripts to end with.
|
|
46
|
+
*
|
|
47
|
+
* `injectJavaScript` runs in whatever page is in the main frame when the reply
|
|
48
|
+
* is sent, not in the frame that sent the message (iOS and Android reply to the
|
|
49
|
+
* source frame). The origin guard keeps a reply from reaching a page the
|
|
50
|
+
* WebView navigated to in between.
|
|
51
|
+
*/
|
|
52
|
+
export declare function buildReplyScript(replyJson: string, allowedOrigins: readonly string[]): string;
|
|
53
|
+
//# sourceMappingURL=bridgeWrapperScript.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bridgeWrapperScript.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/bridgeWrapperScript.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,0BAA0B,qBAAqB,CAAC;AAE7D;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,8BAA8B,CAAC;AAE/D;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,wBAAwB,CAAC;AAE3D,eAAO,MAAM,eAAe,UAAU,CAAC;AAEvC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,wBAAwB,CACtC,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,gBAAgB,GAAE,MAAmC,EACrD,aAAa,GAAE,MAA8B,GAC5C,MAAM,CA+FR;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,SAAS,MAAM,EAAE,GAChC,MAAM,CAKR"}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
export const DEFAULT_BRIDGE_OBJECT_NAME = 'metarouterBridge';
|
|
2
|
+
/**
|
|
3
|
+
* Name of the `window` channel object the wrapper posts through and whose
|
|
4
|
+
* `onmessage` receives replies — the same name, and the same page-visible
|
|
5
|
+
* surface, as the iOS and Android SDKs.
|
|
6
|
+
*/
|
|
7
|
+
export const NATIVE_CHANNEL_NAME = '__metaRouterNativeChannel';
|
|
8
|
+
/**
|
|
9
|
+
* Prefix on every bridge message. `window.ReactNativeWebView.postMessage` is
|
|
10
|
+
* one channel shared with the host's own page→app messages (native has a
|
|
11
|
+
* dedicated one), so the prefix is what lets the SDK claim its messages and
|
|
12
|
+
* pass everything else through to the host untouched. The wrapper appends a
|
|
13
|
+
* per-session token after it (see attachWebViewBridge).
|
|
14
|
+
*/
|
|
15
|
+
export const BRIDGE_MESSAGE_PREFIX = '__metaRouterBridge:';
|
|
16
|
+
export const WRAPPER_VERSION = '1.0.0';
|
|
17
|
+
/**
|
|
18
|
+
* Builds the wrapper injected via `injectedJavaScriptBeforeContentLoaded`:
|
|
19
|
+
* at document start on iOS, at `onPageStarted` on Android (so a page's
|
|
20
|
+
* earliest inline scripts can run before it exists). Identical to the iOS and Android
|
|
21
|
+
* wrapper except for the channel shim:
|
|
22
|
+
*
|
|
23
|
+
* - Defines `window.metarouterBridge` with `track`/`page`, wraps each call in
|
|
24
|
+
* an envelope — minting `messageId` and stamping the page facts at call time
|
|
25
|
+
* — and posts it as a JSON string. `messageId` must be minted here: an id
|
|
26
|
+
* assigned at receipt would give two deliveries of one message two ids.
|
|
27
|
+
* - Self-checks `location.origin` against the allowlist and defines nothing on
|
|
28
|
+
* other pages. `react-native-webview` has no origin-scoped channel, so this
|
|
29
|
+
* check plus the SDK's check of the sending frame's URL carry the security
|
|
30
|
+
* model together, as on iOS.
|
|
31
|
+
* - The channel shim posts through `window.ReactNativeWebView`, resolved at
|
|
32
|
+
* call time, and exposes a settable `onmessage` that replies are delivered to.
|
|
33
|
+
* - `properties` may be an object or a JSON string; a string that fails to
|
|
34
|
+
* parse is forwarded as-is so the SDK rejects it with `malformed_payload`.
|
|
35
|
+
* - JSON.stringify is guarded: unstringifiable properties (circular, BigInt)
|
|
36
|
+
* are coerced to a string and re-posted, so the page gets a coded error
|
|
37
|
+
* reply, never a TypeError thrown into its own calling code.
|
|
38
|
+
*/
|
|
39
|
+
export function buildBridgeWrapperScript(allowedOrigins, bridgeObjectName = DEFAULT_BRIDGE_OBJECT_NAME, messagePrefix = BRIDGE_MESSAGE_PREFIX) {
|
|
40
|
+
if (allowedOrigins.length === 0) {
|
|
41
|
+
throw new Error('allowedOrigins must not be empty');
|
|
42
|
+
}
|
|
43
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(bridgeObjectName)) {
|
|
44
|
+
throw new Error('bridgeObjectName must be a valid JS identifier');
|
|
45
|
+
}
|
|
46
|
+
// JSON-encoding the allowlist keeps a hostile origin string from breaking
|
|
47
|
+
// out of the script — quotes arrive escaped.
|
|
48
|
+
const originsJsArray = JSON.stringify(allowedOrigins);
|
|
49
|
+
const prefix = JSON.stringify(messagePrefix);
|
|
50
|
+
return `(function() {
|
|
51
|
+
'use strict';
|
|
52
|
+
var ALLOWED_ORIGINS = ${originsJsArray};
|
|
53
|
+
// A plain loop, not indexOf: on Android the page's own scripts can run
|
|
54
|
+
// first, and a patched Array.prototype.indexOf would pass any origin.
|
|
55
|
+
var allowed = false;
|
|
56
|
+
for (var i = 0; i < ALLOWED_ORIGINS.length; i++) {
|
|
57
|
+
if (ALLOWED_ORIGINS[i] === location.origin) { allowed = true; }
|
|
58
|
+
}
|
|
59
|
+
if (!allowed) { return; }
|
|
60
|
+
if (window.${bridgeObjectName}) { return; }
|
|
61
|
+
|
|
62
|
+
if (!window.${NATIVE_CHANNEL_NAME}) {
|
|
63
|
+
window.${NATIVE_CHANNEL_NAME} = {
|
|
64
|
+
onmessage: null,
|
|
65
|
+
postMessage: function(data) {
|
|
66
|
+
if (window.ReactNativeWebView &&
|
|
67
|
+
typeof window.ReactNativeWebView.postMessage === 'function') {
|
|
68
|
+
window.ReactNativeWebView.postMessage(${prefix} + data);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function uuidv4() {
|
|
75
|
+
if (window.crypto && window.crypto.getRandomValues) {
|
|
76
|
+
var b = new Uint8Array(16);
|
|
77
|
+
window.crypto.getRandomValues(b);
|
|
78
|
+
b[6] = (b[6] & 0x0f) | 0x40;
|
|
79
|
+
b[8] = (b[8] & 0x3f) | 0x80;
|
|
80
|
+
var h = [];
|
|
81
|
+
for (var i = 0; i < 16; i++) { h.push((b[i] + 0x100).toString(16).slice(1)); }
|
|
82
|
+
return h.slice(0, 4).join('') + '-' + h.slice(4, 6).join('') + '-' +
|
|
83
|
+
h.slice(6, 8).join('') + '-' + h.slice(8, 10).join('') + '-' +
|
|
84
|
+
h.slice(10, 16).join('');
|
|
85
|
+
}
|
|
86
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
|
87
|
+
var r = Math.random() * 16 | 0;
|
|
88
|
+
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function post(type, name, properties) {
|
|
93
|
+
if (typeof name !== 'string' || name.length === 0) { return; }
|
|
94
|
+
var props = properties;
|
|
95
|
+
if (typeof props === 'string') {
|
|
96
|
+
try { props = JSON.parse(props); } catch (e) { /* forward as-is; native rejects */ }
|
|
97
|
+
}
|
|
98
|
+
if (props === undefined || props === null) { props = {}; }
|
|
99
|
+
var envelope = {
|
|
100
|
+
version: 1,
|
|
101
|
+
messageId: uuidv4(),
|
|
102
|
+
type: type,
|
|
103
|
+
name: name,
|
|
104
|
+
properties: props,
|
|
105
|
+
sentAt: new Date().toISOString(),
|
|
106
|
+
page: {
|
|
107
|
+
url: location.href,
|
|
108
|
+
path: location.pathname,
|
|
109
|
+
search: location.search,
|
|
110
|
+
title: document.title,
|
|
111
|
+
referrer: document.referrer
|
|
112
|
+
},
|
|
113
|
+
source: { producer: 'wrapper', wrapperVersion: '${WRAPPER_VERSION}' }
|
|
114
|
+
};
|
|
115
|
+
var channel = window.${NATIVE_CHANNEL_NAME};
|
|
116
|
+
if (!channel || typeof channel.postMessage !== 'function') { return; }
|
|
117
|
+
var payload;
|
|
118
|
+
try {
|
|
119
|
+
payload = JSON.stringify(envelope);
|
|
120
|
+
} catch (e) {
|
|
121
|
+
try { envelope.properties = String(props); } catch (e2) { envelope.properties = 'unserializable'; }
|
|
122
|
+
payload = JSON.stringify(envelope);
|
|
123
|
+
}
|
|
124
|
+
channel.postMessage(payload);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
window.${bridgeObjectName} = {
|
|
128
|
+
track: function(name, properties) { post('track', name, properties); },
|
|
129
|
+
page: function(name, properties) { post('page', name, properties); }
|
|
130
|
+
};
|
|
131
|
+
})();
|
|
132
|
+
true;`;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Reply delivery script, run in the page with the WebView ref's
|
|
136
|
+
* `injectJavaScript`. The reply JSON rides as a JS string literal, so the
|
|
137
|
+
* page-visible shape matches iOS and Android: `onmessage` receives an
|
|
138
|
+
* event-like object whose `data` is the reply string. The trailing `true;` is
|
|
139
|
+
* what react-native-webview asks injected scripts to end with.
|
|
140
|
+
*
|
|
141
|
+
* `injectJavaScript` runs in whatever page is in the main frame when the reply
|
|
142
|
+
* is sent, not in the frame that sent the message (iOS and Android reply to the
|
|
143
|
+
* source frame). The origin guard keeps a reply from reaching a page the
|
|
144
|
+
* WebView navigated to in between.
|
|
145
|
+
*/
|
|
146
|
+
export function buildReplyScript(replyJson, allowedOrigins) {
|
|
147
|
+
const channel = `window.${NATIVE_CHANNEL_NAME}`;
|
|
148
|
+
// A plain loop rather than indexOf, which the page can patch (see the
|
|
149
|
+
// wrapper).
|
|
150
|
+
return `(function() { var o = ${JSON.stringify(allowedOrigins)}; for (var i = 0; i < o.length; i++) { if (o[i] === location.origin) { if (${channel} && typeof ${channel}.onmessage === 'function') { ${channel}.onmessage({ data: ${jsStringLiteral(replyJson)} }); } return; } } })(); true;`;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* JSON.stringify leaves U+2028/U+2029 unescaped; engines before ES2019 read
|
|
154
|
+
* them as line terminators, so page-controlled text echoed in a reply (a
|
|
155
|
+
* messageId, an unknown type) would turn the reply script into a SyntaxError.
|
|
156
|
+
*/
|
|
157
|
+
function jsStringLiteral(value) {
|
|
158
|
+
return JSON.stringify(value)
|
|
159
|
+
.replace(/\u2028/g, '\\u2028')
|
|
160
|
+
.replace(/\u2029/g, '\\u2029');
|
|
161
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { BridgeMessageProcessor } from './bridgeMessageProcessor';
|
|
2
|
+
import type { WebViewBridgeProps, WebViewRefLike } from '../types';
|
|
3
|
+
/**
|
|
4
|
+
* Scheme and host are case-insensitive and default ports are implied, but both
|
|
5
|
+
* origin checks compare exact canonical strings: "https://Shop.Example.com:443"
|
|
6
|
+
* would pass validation yet never match, leaving the bridge silently inert.
|
|
7
|
+
* Same normalization as iOS.
|
|
8
|
+
*/
|
|
9
|
+
export declare function normalizeOrigin(origin: string): string;
|
|
10
|
+
/** Canonical origin of a URL or origin string, or null when it has none. */
|
|
11
|
+
export declare function originOf(url: string | undefined): string | null;
|
|
12
|
+
export declare const inertProps: () => WebViewBridgeProps;
|
|
13
|
+
/**
|
|
14
|
+
* Builds the props that bridge one `react-native-webview` WebView. Same
|
|
15
|
+
* validation and warnings as the native attachWebView; differences forced by
|
|
16
|
+
* react-native-webview:
|
|
17
|
+
*
|
|
18
|
+
* - There is no WebView object to register on, so the bridge is the returned
|
|
19
|
+
* props: the wrapper for `injectedJavaScriptBeforeContentLoaded` and an
|
|
20
|
+
* `onMessage` handler that returns true for the SDK's messages and false for
|
|
21
|
+
* the host's, so the host can chain its own handler.
|
|
22
|
+
* - The message channel is not origin-scoped, so each message's reported
|
|
23
|
+
* sending-frame URL is checked against the allowlist, and must carry the
|
|
24
|
+
* session token only the main-frame wrapper holds (see BridgeState). The
|
|
25
|
+
* wrapper's own origin self-check is the page half. Failing messages are
|
|
26
|
+
* dropped with no reply — a hostile frame gets silence, not an oracle.
|
|
27
|
+
* - The wrapper reaches the main frame only, and on Android
|
|
28
|
+
* react-native-webview runs it when the page starts loading rather than at
|
|
29
|
+
* document start, so page code that runs before it finds no bridge.
|
|
30
|
+
* - Replies need the WebView ref (`injectJavaScript`), and go to the page in
|
|
31
|
+
* the main frame at reply time. Without a ref, events still flow and the
|
|
32
|
+
* page receives no acks.
|
|
33
|
+
* - Calling it again (e.g. on every render) returns equivalent props; dedup
|
|
34
|
+
* lives in the shared processor.
|
|
35
|
+
*/
|
|
36
|
+
export declare function attachWebViewBridge(webViewRef: WebViewRefLike | null | undefined, allowedOrigins: readonly string[], processor: BridgeMessageProcessor): WebViewBridgeProps;
|
|
37
|
+
/** The message prefix (with token) the processor's wrapper posts with. Tests only. */
|
|
38
|
+
export declare function bridgeMessagePrefixFor(processor: BridgeMessageProcessor): string;
|
|
39
|
+
//# sourceMappingURL=webViewBridge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webViewBridge.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/webViewBridge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAOvE,OAAO,KAAK,EACV,kBAAkB,EAElB,cAAc,EACf,MAAM,UAAU,CAAC;AAelB;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAQtD;AAED,4EAA4E;AAC5E,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAM/D;AAoED,eAAO,MAAM,UAAU,QAAO,kBAM5B,CAAC;AAsDH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,mBAAmB,CACjC,UAAU,EAAE,cAAc,GAAG,IAAI,GAAG,SAAS,EAC7C,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,SAAS,EAAE,sBAAsB,GAChC,kBAAkB,CA8EpB;AAED,sFAAsF;AACtF,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,sBAAsB,GAChC,MAAM,CAER"}
|