@scalebun/react-native 1.10.5 → 1.10.7

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.
Files changed (64) hide show
  1. package/android/src/main/java/com/scalebun/rn/ota/ScaleBunOtaModule.kt +75 -0
  2. package/android/src/oldarch/java/com/scalebun/rn/ota/ScaleBunOtaSpec.kt +12 -0
  3. package/dist/scalebun.full.js +485 -51
  4. package/dist/scalebun.slim.js +485 -51
  5. package/ios/Core/DeviceIdentity.swift +50 -0
  6. package/ios/Ota/ScaleBunOtaBridge.mm +6 -0
  7. package/ios/Ota/ScaleBunOtaModule.swift +67 -0
  8. package/ios/Profiler/ScaleBunProfilerModule.swift +2 -8
  9. package/ios/ReplaySdk.swift +3 -1
  10. package/lib/commonjs/analytics/EventTracker.js +22 -0
  11. package/lib/commonjs/core/config/schema.js +34 -1
  12. package/lib/commonjs/core/constants/version.js +1 -1
  13. package/lib/commonjs/core/context/device.js +5 -0
  14. package/lib/commonjs/features/journey/ScaleBunDebugRoot.js +24 -0
  15. package/lib/commonjs/features/journey/uiState.js +87 -0
  16. package/lib/commonjs/features/ota/crypto/builtinVerifier.js +248 -0
  17. package/lib/commonjs/features/ota/crypto/loadEd25519.js +40 -0
  18. package/lib/commonjs/features/ota/crypto/loadSha512.js +40 -0
  19. package/lib/commonjs/features/ota/crypto/nativeVerifier.js +121 -0
  20. package/lib/commonjs/features/ota/signature.js +87 -27
  21. package/lib/commonjs/metro/serializerCompose.js +32 -0
  22. package/lib/commonjs/public/ScaleBunFacade.js +108 -11
  23. package/lib/module/analytics/EventTracker.js +22 -0
  24. package/lib/module/core/config/schema.js +34 -1
  25. package/lib/module/core/constants/version.js +1 -1
  26. package/lib/module/core/context/device.js +5 -0
  27. package/lib/module/features/journey/ScaleBunDebugRoot.js +24 -0
  28. package/lib/module/features/journey/uiState.js +79 -0
  29. package/lib/module/features/ota/crypto/builtinVerifier.js +240 -0
  30. package/lib/module/features/ota/crypto/loadEd25519.js +34 -0
  31. package/lib/module/features/ota/crypto/loadSha512.js +34 -0
  32. package/lib/module/features/ota/crypto/nativeVerifier.js +113 -0
  33. package/lib/module/features/ota/signature.js +87 -27
  34. package/lib/module/metro/serializerCompose.js +32 -0
  35. package/lib/module/public/ScaleBunFacade.js +109 -12
  36. package/lib/typescript/analytics/EventTracker.d.ts +15 -0
  37. package/lib/typescript/core/config/schema.d.ts +2 -0
  38. package/lib/typescript/core/constants/version.d.ts +1 -1
  39. package/lib/typescript/core/context/device.d.ts +1 -0
  40. package/lib/typescript/features/journey/uiState.d.ts +53 -0
  41. package/lib/typescript/features/ota/OtaTypes.d.ts +50 -0
  42. package/lib/typescript/features/ota/crypto/builtinVerifier.d.ts +53 -0
  43. package/lib/typescript/features/ota/crypto/loadEd25519.d.ts +30 -0
  44. package/lib/typescript/features/ota/crypto/loadSha512.d.ts +15 -0
  45. package/lib/typescript/features/ota/crypto/nativeVerifier.d.ts +35 -0
  46. package/lib/typescript/features/ota/signature.d.ts +22 -7
  47. package/lib/typescript/public/ScaleBunFacade.d.ts +43 -6
  48. package/lib/typescript/specs/NativeScaleBunOta.d.ts +23 -0
  49. package/package.json +18 -3
  50. package/src/analytics/EventTracker.ts +19 -0
  51. package/src/core/config/schema.ts +30 -3
  52. package/src/core/constants/version.ts +1 -1
  53. package/src/core/context/device.ts +6 -0
  54. package/src/features/journey/ScaleBunDebugRoot.tsx +22 -0
  55. package/src/features/journey/uiState.ts +84 -0
  56. package/src/features/ota/OtaTypes.ts +51 -0
  57. package/src/features/ota/crypto/builtinVerifier.ts +257 -0
  58. package/src/features/ota/crypto/loadEd25519.ts +41 -0
  59. package/src/features/ota/crypto/loadSha512.ts +35 -0
  60. package/src/features/ota/crypto/nativeVerifier.ts +117 -0
  61. package/src/features/ota/signature.ts +108 -25
  62. package/src/metro/serializerCompose.ts +38 -2
  63. package/src/public/ScaleBunFacade.ts +128 -14
  64. package/src/specs/NativeScaleBunOta.ts +24 -0
@@ -289,6 +289,14 @@ const SHAPE = {
289
289
  kind: 'str',
290
290
  opt: true
291
291
  },
292
+ // Rotation support: several pinned keys, any of which may verify a
293
+ // bundle. Ship a build pinning [old, new], re-sign server-side with
294
+ // new, drop old next release — no emergency store submission when a
295
+ // key must be replaced. Merged with publicSigningKey by the facade.
296
+ publicSigningKeys: {
297
+ kind: 'strArr',
298
+ opt: true
299
+ },
292
300
  mandatoryBlocksUi: bool(false)
293
301
  }
294
302
  }
@@ -328,7 +336,7 @@ function parseField(field, input, path, issues) {
328
336
  present: true
329
337
  };
330
338
  // Required with no default (matches the base schemas' type errors on undefined).
331
- return fail(field.kind === 'bool' ? 'Expected boolean, received undefined' : field.kind === 'num' ? 'Expected number, received undefined' : field.kind === 'str' ? 'Expected string, received undefined' : field.kind === 'enum' ? "Invalid enum value. Expected " + field.values.map(v => `'${v}'`).join(' | ') : 'Expected object, received undefined');
339
+ return fail(field.kind === 'bool' ? 'Expected boolean, received undefined' : field.kind === 'num' ? 'Expected number, received undefined' : field.kind === 'str' ? 'Expected string, received undefined' : field.kind === 'strArr' ? 'Expected array, received undefined' : field.kind === 'enum' ? "Invalid enum value. Expected " + field.values.map(v => `'${v}'`).join(' | ') : 'Expected object, received undefined');
332
340
  }
333
341
  switch (field.kind) {
334
342
  case 'any':
@@ -354,6 +362,31 @@ function parseField(field, input, path, issues) {
354
362
  value: input,
355
363
  present: true
356
364
  };
365
+ case 'strArr':
366
+ {
367
+ // Mirrors the vendored ArraySchema exactly: element failures are
368
+ // reported at their index and fail the whole field (no partial
369
+ // arrays reach the output).
370
+ if (!Array.isArray(input)) return fail(`Expected array, received ${typeofName(input)}`);
371
+ let allOk = true;
372
+ for (let i = 0; i < input.length; i++) {
373
+ if (typeof input[i] !== 'string') {
374
+ issues.push({
375
+ path: [...path, i],
376
+ message: `Expected string, received ${typeofName(input[i])}`
377
+ });
378
+ allOk = false;
379
+ }
380
+ }
381
+ return allOk ? {
382
+ ok: true,
383
+ value: [...input],
384
+ present: true
385
+ } : {
386
+ ok: false,
387
+ present: true
388
+ };
389
+ }
357
390
  case 'num':
358
391
  if (typeof input !== 'number' || Number.isNaN(input)) {
359
392
  return fail(`Expected number, received ${typeofName(input)}`);
@@ -3,5 +3,5 @@
3
3
  * can attribute telemetry to the SDK build that produced it.
4
4
  * Keep in sync with package.json "version".
5
5
  */
6
- export const SDK_VERSION = '1.10.5';
6
+ export const SDK_VERSION = '1.10.7';
7
7
  //# sourceMappingURL=version.js.map
@@ -92,6 +92,10 @@ export function staticDeviceContext() {
92
92
  if (osVersion) out.os_version = String(osVersion);
93
93
  if (c.Model) out.device_model = String(c.Model);
94
94
  if (c.Manufacturer) out.manufacturer = String(c.Manufacturer);else if (c.Brand) out.manufacturer = String(c.Brand);
95
+ // iOS exposes no manufacturer because it does not need to: every device running iOS is Apple's.
96
+ // A tautology, not a guess — and it means the field is populated on event #1 rather than waiting
97
+ // for a bridge that may never answer.
98
+ else if (out.platform_os === 'ios') out.manufacturer = 'Apple';
95
99
  return out;
96
100
  }
97
101
 
@@ -101,6 +105,7 @@ export function nativeDeviceContext(info) {
101
105
  if (!info) return out;
102
106
  if (info.osVersion) out.os_version = info.osVersion;
103
107
  if (info.deviceModel) out.device_model = info.deviceModel;
108
+ if (info.manufacturer) out.manufacturer = info.manufacturer;
104
109
  return out;
105
110
  }
106
111
 
@@ -496,9 +496,33 @@ export function ScaleBunDebugRoot({
496
496
  } = require('../navigation/AutoScreenDetector');
497
497
  screen = AutoScreenDetector.getInstance().getCurrentScreen() || undefined;
498
498
  } catch {/* no-throw */}
499
+ /**
500
+ * UI STATE, read HERE and not later.
501
+ *
502
+ * A tap belongs to the surface that was on screen when the finger landed: tapping the
503
+ * filter button while the sheet is DOWN belongs to `closed`, because that is what the
504
+ * user was looking at when they reached for it. Reading it after the handler has run
505
+ * moves every "open the thing" tap into the state it created — the one state it
506
+ * certainly does not belong to.
507
+ *
508
+ * Declared-only on this platform (see uiState.ts): absent means not captured, which
509
+ * the dashboard keeps distinct from "nothing was open".
510
+ */
511
+ let ui;
512
+ try {
513
+ const {
514
+ uiStateSignature
515
+ } = require('./uiState');
516
+ ui = uiStateSignature();
517
+ } catch {/* no-throw: a tap must never be lost to state capture */}
499
518
  emitAutomaticEvent('element_interacted', {
500
519
  gesture_type: gestureType,
501
520
  screen_name: screen,
521
+ /* THIS MAP ENUMERATES. A field added to the payload and forgotten here reaches the
522
+ backend as undefined with no error anywhere — the recurring defect class in this
523
+ codebase. `ui` is the key the grid aggregate reads for state, byte-identical to
524
+ the web SDK's, so one dashboard control queries both platforms. */
525
+ ui,
502
526
  // testID/nativeID is an author-controlled stable identifier.
503
527
  // Accessibility labels and rendered text are deliberately omitted.
504
528
  target_id: targetInfo?.testId,
@@ -0,0 +1,79 @@
1
+ /**
2
+ * UI STATE AT INTERACTION TIME — React Native.
3
+ *
4
+ * A screen is not just `Cart`. It is `Cart` with the filter sheet down, or up; with the address form
5
+ * expanded, or collapsed. Those are different interaction surfaces and a tap on one must never be
6
+ * counted on another — heat from the open sheet painted over the closed layout is a picture of
7
+ * something that never existed.
8
+ *
9
+ * HOW THIS DIFFERS FROM THE WEB, and the difference is not an omission:
10
+ *
11
+ * The web SDK ALSO detects state automatically, by reading `aria-expanded` and open `<dialog>`
12
+ * elements out of the live DOM. Those are platform-defined, so reading them is a measurement.
13
+ *
14
+ * React Native has no equivalent. There is no queryable tree of accessibility state that says a
15
+ * bottom sheet is up; a sheet is a component with a boolean in someone's store, and the only place
16
+ * that boolean exists is the host's own code. Guessing at it — from a modal's presence in the tree, or
17
+ * from a component name — would produce a state key that is right on some apps and silently wrong on
18
+ * others, and a wrong state key partitions taps into buckets corresponding to nothing.
19
+ *
20
+ * So on RN, state is DECLARED and never inferred. `ScaleBun.setUiState('filter-sheet', 'open')` is the
21
+ * whole mechanism, and its absence means "not captured" rather than "nothing was open". That
22
+ * distinction is carried all the way to the dashboard: a tap with no declared state is NULL, not '',
23
+ * and cannot be selected as a state or counted as one. Reporting it as "nothing was open" would be
24
+ * asserting a measurement nobody took.
25
+ *
26
+ * PAIRED WITH: whatzbug-web-sdk/packages/web/src/features/journey/uiState.ts — same wire format
27
+ * (`name:value` pairs, sorted, `;`-joined, <= 96 chars), same separator stripping, same explicit-wins
28
+ * precedence, so one dashboard control queries both platforms.
29
+ */
30
+
31
+ /** Host-declared state dimensions. The only source on this platform. */
32
+ const declared = new Map();
33
+
34
+ /**
35
+ * `;` and `:` are the wire separators and cannot appear inside a name or value; the length is bounded.
36
+ *
37
+ * Names and values are IDENTIFIERS, not content. They become aggregation keys in the dashboard, so a
38
+ * value carrying a person's name or a cart total would put user data into a query key — and into every
39
+ * chart legend built from it.
40
+ */
41
+ const clean = s => typeof s === 'string' ? s.replace(/[;:|]/g, '').trim().slice(0, 32) : '';
42
+
43
+ /**
44
+ * Declare the state of one UI dimension.
45
+ *
46
+ * Call it when the state CHANGES, not on every render: the value is read at interaction time, so it
47
+ * only has to be correct by the time the next tap lands.
48
+ */
49
+ export function setUiState(name, value) {
50
+ const n = clean(name);
51
+ const v = clean(value);
52
+ if (n && v) declared.set(n, v);
53
+ }
54
+
55
+ /**
56
+ * Stop reporting a dimension — or, with no name, all of them.
57
+ *
58
+ * Later taps carry no value for it, which is not the same as carrying a value. Clearing all is what a
59
+ * screen unmount wants: declarations from the previous screen would otherwise follow the user onto a
60
+ * surface where they mean nothing, and every tap there would be filed under a state that was not on
61
+ * screen.
62
+ */
63
+ export function clearUiState(name) {
64
+ if (name === undefined) declared.clear();else declared.delete(clean(name));
65
+ }
66
+
67
+ /**
68
+ * The signature for the interaction happening RIGHT NOW, or undefined when nothing is declared.
69
+ *
70
+ * undefined rather than '' deliberately — see the header. '' is the web's "we looked and nothing was
71
+ * open"; on RN there is nothing to look at, so the honest answer is silence.
72
+ */
73
+ export function uiStateSignature() {
74
+ if (!declared.size) return undefined;
75
+ /* SORTED, or the same surface produces different signatures depending on the order the host happened
76
+ to declare things in, and every count fragments into several that mean nothing. */
77
+ return [...declared.keys()].sort().map(k => `${k}:${declared.get(k)}`).join(';').slice(0, 96);
78
+ }
79
+ //# sourceMappingURL=uiState.js.map
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Built-in ed25519 verifier, assembled from OPTIONAL peer dependencies.
3
+ *
4
+ * WHAT THIS REPLACES. Pinning `ota.publicSigningKey` used to require the host
5
+ * app to write its own `verifySignature` — roughly a hundred lines of hex and
6
+ * base64 decoding wrapped around a crypto library. That put the single most
7
+ * security-critical operation in the product, the one deciding whether remote
8
+ * code is authentic before it executes, in code the SDK could neither test nor
9
+ * audit. Three failure modes all landed on the app author:
10
+ *
11
+ * - A verifier that always returns `true` silently disables the feature, and
12
+ * nothing can detect it.
13
+ * - @noble's hash-provider property moved between major versions, so a
14
+ * routine dependency bump made every update fail closed with no signal
15
+ * pointing at the cause.
16
+ * - Hand-written base64 decoders tend to omit base64url, so a signature
17
+ * containing `-` or `_` is rejected as a forgery.
18
+ *
19
+ * All three are now the SDK's problem, which is where they belong. A host that
20
+ * installs `@noble/ed25519` and `@noble/hashes` gets verification by pinning a
21
+ * key and writing no code at all.
22
+ *
23
+ * WHY OPTIONAL AND NOT A HARD DEPENDENCY. Most apps never adopt bundle
24
+ * signing, and they should not carry curve arithmetic they will not run. The
25
+ * `verifySignature` hook remains supported and still WINS over this, for teams
26
+ * with their own crypto policy or a native implementation to delegate to.
27
+ *
28
+ * WHAT THIS DOES NOT FIX. Verification still happens in JS, inside the very
29
+ * bundle it protects. An attacker who lands one malicious bundle by other means
30
+ * can neuter the check for every update after it. Closing that needs native
31
+ * verification — CryptoKit on iOS (13.4+, already the deployment target) and
32
+ * `Signature.getInstance("Ed25519")` on Android API 33+, with a fallback below.
33
+ */
34
+
35
+ import { loadEd25519 } from './loadEd25519';
36
+ import { loadSha512 } from './loadSha512';
37
+ import { logger } from '../../../core/logger/internalLogger';
38
+ const ED25519_SIGNATURE_BYTES = 64;
39
+ const ED25519_PUBLIC_KEY_BYTES = 32;
40
+
41
+ /** Hex → bytes. Returns null rather than throwing; callers treat null as "reject". */
42
+ function hexToBytes(hex) {
43
+ const clean = hex.trim().toLowerCase().replace(/^0x/, '');
44
+ if (clean.length === 0 || clean.length % 2 !== 0 || /[^0-9a-f]/.test(clean)) return null;
45
+ const out = new Uint8Array(clean.length / 2);
46
+ for (let i = 0; i < out.length; i++) {
47
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
48
+ }
49
+ return out;
50
+ }
51
+ const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
52
+
53
+ /**
54
+ * Base64 → bytes, accepting base64url as well.
55
+ *
56
+ * The `-`/`_` handling is the point. A verifier that omits it rejects a
57
+ * perfectly valid signature as a forgery the moment the signing side emits
58
+ * base64url, and the resulting symptom — updates silently stop installing —
59
+ * looks nothing like a decoding bug.
60
+ */
61
+ function base64ToBytes(b64) {
62
+ const s = b64.trim().replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '');
63
+ if (s.length === 0) return null;
64
+ const out = [];
65
+ let buffer = 0;
66
+ let bits = 0;
67
+ for (const ch of s) {
68
+ const idx = B64_ALPHABET.indexOf(ch);
69
+ if (idx === -1) return null;
70
+ buffer = buffer << 6 | idx;
71
+ bits += 6;
72
+ if (bits >= 8) {
73
+ bits -= 8;
74
+ out.push(buffer >> bits & 0xff);
75
+ }
76
+ }
77
+ return Uint8Array.from(out);
78
+ }
79
+
80
+ /**
81
+ * Decode a detached signature that may arrive hex- or base64-encoded.
82
+ *
83
+ * Tries the unambiguous case first: 128 hex characters is exactly 64 bytes and
84
+ * cannot be anything else. Otherwise base64, then hex as a last resort. Only a
85
+ * result of exactly 64 bytes is accepted, so a string that decodes under the
86
+ * wrong scheme is rejected rather than fed to the curve code as garbage.
87
+ */
88
+ export function decodeSignature(sig) {
89
+ const trimmed = sig.trim();
90
+ if (/^(0x)?[0-9a-fA-F]{128}$/.test(trimmed)) {
91
+ const hex = hexToBytes(trimmed);
92
+ if (hex && hex.length === ED25519_SIGNATURE_BYTES) return hex;
93
+ }
94
+ const b64 = base64ToBytes(trimmed);
95
+ if (b64 && b64.length === ED25519_SIGNATURE_BYTES) return b64;
96
+ const hex = hexToBytes(trimmed);
97
+ if (hex && hex.length === ED25519_SIGNATURE_BYTES) return hex;
98
+ return null;
99
+ }
100
+
101
+ /**
102
+ * Give @noble its SHA-512 provider.
103
+ *
104
+ * The property it reads moved between major versions — v2 wants
105
+ * `etc.sha512Sync`, v3 wants `hashes.sha512` — so both are populated when
106
+ * present. Getting this wrong does not fail loudly: verification simply throws
107
+ * from inside the curve code and the outer catch converts it to "rejected",
108
+ * which is indistinguishable from an actual forgery. That ambiguity is exactly
109
+ * what made this a bad thing to ask app authors to maintain.
110
+ */
111
+ function wireSha512(ed, sha512) {
112
+ // VARIADIC ON PURPOSE. @noble calls its hash provider with several byte
113
+ // arrays to be hashed as one concatenated message. A wrapper taking a
114
+ // single argument hashes only the first, silently produces the wrong
115
+ // digest, and every genuine signature is then reported as INVALID — no
116
+ // error, no exception, just an authenticity check that always says no.
117
+ // Verified against a real CLI-produced signature; the single-argument form
118
+ // failed every positive case while passing every negative one, which is
119
+ // the most misleading shape a bug of this kind can take.
120
+ const concat = parts => {
121
+ if (parts.length === 1) return parts[0];
122
+ let total = 0;
123
+ for (const p of parts) total += p.length;
124
+ const out = new Uint8Array(total);
125
+ let off = 0;
126
+ for (const p of parts) {
127
+ out.set(p, off);
128
+ off += p.length;
129
+ }
130
+ return out;
131
+ };
132
+ const sync = (...msgs) => sha512(concat(msgs));
133
+ const asyncFn = async (...msgs) => sha512(concat(msgs));
134
+
135
+ // EACH BRANCH GETS ITS OWN try. Wrapping both in one is a trap, and it cost
136
+ // an afternoon: under v3 the `hashes` assignment succeeds and the `etc`
137
+ // object is FROZEN, so the v2-shaped assignment throws "object is not
138
+ // extensible" — discarding a verifier that was, by then, already correctly
139
+ // wired. Only "neither shape took" means unavailable.
140
+ let wired = false;
141
+ try {
142
+ if (ed.hashes && typeof ed.hashes === 'object') {
143
+ if (typeof ed.hashes.sha512 !== 'function') ed.hashes.sha512 = sync;
144
+ if (typeof ed.hashes.sha512Async !== 'function') ed.hashes.sha512Async = asyncFn;
145
+ wired = typeof ed.hashes.sha512 === 'function';
146
+ }
147
+ } catch {
148
+ /* frozen or absent — try the other shape */
149
+ }
150
+ try {
151
+ if (ed.etc && typeof ed.etc === 'object') {
152
+ if (typeof ed.etc.sha512Sync !== 'function') ed.etc.sha512Sync = sync;
153
+ if (typeof ed.etc.sha512Async !== 'function') ed.etc.sha512Async = asyncFn;
154
+ wired = wired || typeof ed.etc.sha512Sync === 'function';
155
+ }
156
+ } catch {
157
+ /* frozen or absent — `wired` already records whether the other shape took */
158
+ }
159
+ return wired;
160
+ }
161
+ let resolved;
162
+
163
+ /**
164
+ * The built-in verifier, or null when the optional deps are not installed.
165
+ * Resolution is cached, including the negative result — a missing dependency
166
+ * does not become present at runtime, and retrying the require on every update
167
+ * check would be pure overhead.
168
+ */
169
+ export function getBuiltinVerifier() {
170
+ if (resolved !== undefined) return resolved;
171
+ const ed = loadEd25519();
172
+ const sha512 = loadSha512();
173
+ if (!ed || !sha512) {
174
+ resolved = null;
175
+ return null;
176
+ }
177
+ if (!wireSha512(ed, sha512)) {
178
+ // A shape neither branch matched — a @noble major this SDK predates.
179
+ // Report "no verifier", which is actionable, rather than letting every
180
+ // update fail deep inside the curve code with an opaque error.
181
+ logger.error('[OTA] @noble/ed25519 is installed but its SHA-512 provider could not be ' + 'wired (unrecognised version shape). Supply `ota.verifySignature` ' + 'yourself, or pin a @noble/ed25519 version this SDK supports.');
182
+ resolved = null;
183
+ return null;
184
+ }
185
+ resolved = async ({
186
+ messageHex,
187
+ signature,
188
+ publicKey
189
+ }) => {
190
+ const message = hexToBytes(messageHex);
191
+ const pub = hexToBytes(publicKey);
192
+ const sig = decodeSignature(signature);
193
+ if (!message) {
194
+ logger.error('[OTA] Bundle SHA-256 is not valid hex — refusing to stage.');
195
+ return false;
196
+ }
197
+ if (!pub || pub.length !== ED25519_PUBLIC_KEY_BYTES) {
198
+ // Worth naming precisely: a mistyped or wrongly-encoded key would
199
+ // otherwise present as "every update is a forgery".
200
+ logger.error(`[OTA] ota.publicSigningKey must be ${ED25519_PUBLIC_KEY_BYTES} bytes of hex ` + `(${ED25519_PUBLIC_KEY_BYTES * 2} characters) — got ` + `${pub ? `${pub.length} bytes` : 'a value that is not hex'}.`);
201
+ return false;
202
+ }
203
+ if (!sig) {
204
+ logger.error('[OTA] Bundle signature is not a 64-byte hex/base64 value.');
205
+ return false;
206
+ }
207
+
208
+ // @noble THROWS rather than returning false for bytes that are not a
209
+ // well-formed point — which is most forgeries, since a tampered
210
+ // signature usually decodes to garbage rather than to a valid-but-wrong
211
+ // point. Swallowing that here is deliberate: from the SDK's side a
212
+ // malformed signature IS a rejection, and letting it escape would
213
+ // surface as `verifier_threw`, the outcome reserved for a HOST verifier
214
+ // misbehaving. Conflating "this bundle is forged" with "your verifier
215
+ // is broken" would point every investigation in the wrong direction.
216
+ try {
217
+ // SYNC FIRST, and this is not a style preference. @noble's
218
+ // `verifyAsync` reaches for `crypto.subtle` — "crypto.subtle must be
219
+ // defined, consider polyfill" — which React Native does not provide
220
+ // and neither does a plain Node test environment. The sync `verify`
221
+ // uses the SHA-512 provider wired above and needs no WebCrypto, so
222
+ // it is the path that actually works on a phone. Verification is a
223
+ // few hundred microseconds over a 32-byte digest, once per update
224
+ // check, so there is nothing to gain from the async form anyway.
225
+ if (typeof ed.verify === 'function') return ed.verify(sig, message, pub);
226
+ if (typeof ed.verifyAsync === 'function') return await ed.verifyAsync(sig, message, pub);
227
+ return false;
228
+ } catch {
229
+ return false;
230
+ }
231
+ };
232
+ __DEV__ && logger.debug('[OTA] Using built-in ed25519 verifier (@noble/ed25519 detected).');
233
+ return resolved;
234
+ }
235
+
236
+ /** Test seam — clears the cached resolution. */
237
+ export function _resetBuiltinVerifier() {
238
+ resolved = undefined;
239
+ }
240
+ //# sourceMappingURL=builtinVerifier.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Isolated lazy loader for the OPTIONAL `@noble/ed25519` dep.
3
+ *
4
+ * WHY ITS OWN FILE: Metro's dependency collector emits a dependency map one
5
+ * entry short for a module containing TWO OR MORE different-string inline
6
+ * `require()` calls, so the require indices desync and `_dependencyMap[N]`
7
+ * reads `undefined` ("Requiring unknown module 'undefined'"). Exactly ONE
8
+ * inline require per module avoids the miscount. `loadSha512` is a sibling file
9
+ * for the same reason — see `push/adapters/loadNotifee.ts`, which hit this first.
10
+ *
11
+ * The string must still be STATICALLY resolvable at bundle time; hosts that do
12
+ * not install it stub it via `withScaleBun`.
13
+ */
14
+
15
+ /** The subset of the @noble/ed25519 surface this SDK uses. */
16
+
17
+ export function loadEd25519() {
18
+ try {
19
+ const mod = require('@noble/ed25519');
20
+ const ed = mod?.default ?? mod;
21
+ // Validate the API actually used, not mere truthiness: when the package
22
+ // is absent `withScaleBun` resolves it to an EMPTY STUB MODULE, which is
23
+ // a perfectly truthy object. A stub must read as "unavailable", because
24
+ // treating it as available would make every signed update fail with a
25
+ // crypto error instead of the actionable "no verifier" message.
26
+ if (typeof ed?.verifyAsync === 'function' || typeof ed?.verify === 'function') {
27
+ return ed;
28
+ }
29
+ return null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ //# sourceMappingURL=loadEd25519.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Isolated lazy loader for the OPTIONAL `@noble/hashes` SHA-512.
3
+ *
4
+ * Separate file from `loadEd25519` because Metro miscounts a module holding two
5
+ * different-string inline `require()` calls — see the comment there.
6
+ *
7
+ * ed25519 is defined in terms of SHA-512, and React Native has no native
8
+ * SHA-512, so @noble/ed25519 cannot verify anything until a hash provider is
9
+ * wired into it. Which property it expects differs by major version, so the
10
+ * wiring lives in `builtinVerifier`, not here; this module only obtains the
11
+ * function.
12
+ */
13
+
14
+ export function loadSha512() {
15
+ try {
16
+ // The `.js` SUFFIX IS REQUIRED, not stylistic. @noble/hashes v2 declares
17
+ // its exports map with extensions — `"./sha2.js"`, not `"./sha2"` — so
18
+ // the extensionless form misses the map entirely. Node still resolves it
19
+ // by falling back to file-based lookup, which is why it passes here,
20
+ // but Metro prints
21
+ // "Attempted to import … not listed in the exports … Falling back to
22
+ // file-based resolution"
23
+ // on every bundle, and that fallback is exactly what a stricter resolver
24
+ // (or a future Metro) drops. Caught while bundling a real Expo app.
25
+ const mod = require('@noble/hashes/sha2.js');
26
+ const sha512 = mod?.sha512 ?? mod?.default?.sha512;
27
+ // A stubbed module yields undefined here, which correctly reads as
28
+ // "unavailable" rather than throwing deep inside the curve code later.
29
+ return typeof sha512 === 'function' ? sha512 : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ //# sourceMappingURL=loadSha512.js.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Native ed25519 verifier — platform crypto wrapped as a SignatureVerifier.
3
+ *
4
+ * WHY IT EXISTS. The built-in @noble verifier runs in JS, inside the very
5
+ * bundle it protects: an attacker who lands one malicious bundle can neuter a
6
+ * JS check for every update after it. Platform crypto (CryptoKit on iOS,
7
+ * Android's conscrypt on API 33+) sits outside the bundle's reach — and using
8
+ * it also drops the runtime dependency on the optional @noble peers wherever
9
+ * the OS provides ed25519.
10
+ *
11
+ * WHAT IT DOES NOT FIX, stated plainly: the ORCHESTRATION still lives in JS.
12
+ * A hostile bundle can skip calling any verifier and drive the native staging
13
+ * methods directly. Moving the crypto native shrinks the attack surface (no
14
+ * more tampering with a bundled crypto lib to flip a verdict) but the full
15
+ * close needs native-ENFORCED staging with a natively-pinned key — an
16
+ * architectural change tracked separately, not smuggled into this one.
17
+ *
18
+ * VERDICT CONTRACT (mirrors the spec): the native side resolves
19
+ * 'valid' | 'invalid' | 'unavailable'. 'invalid' is a definitive NO.
20
+ * 'unavailable' (Android < 33, malformed input, machinery failure) means this
21
+ * source cannot answer — the composed verifier below then delegates to the
22
+ * @noble builtin, and when that is absent too it THROWS, which the policy
23
+ * layer converts to a rejection. Every path that cannot verify refuses.
24
+ */
25
+
26
+ import NativeScaleBunOta from '../../../specs/NativeScaleBunOta';
27
+ import { logger } from '../../../core/logger/internalLogger';
28
+ import { decodeSignature, getBuiltinVerifier } from './builtinVerifier';
29
+ const ED25519_PUBLIC_KEY_HEX_CHARS = 64;
30
+
31
+ /** bytes → lowercase hex (the native side takes clean hex only). */
32
+ function bytesToHex(bytes) {
33
+ let out = '';
34
+ for (const b of bytes) out += b.toString(16).padStart(2, '0');
35
+ return out;
36
+ }
37
+
38
+ /** Strict lowercase-hex normalization; null when the value is not hex. */
39
+ function normalizeHex(value, expectedChars) {
40
+ const clean = value.trim().toLowerCase().replace(/^0x/, '');
41
+ if (clean.length !== expectedChars || /[^0-9a-f]/.test(clean)) return null;
42
+ return clean;
43
+ }
44
+ let resolved;
45
+
46
+ /**
47
+ * The native-first verifier, or null when the native module (or its
48
+ * verifyEd25519 method — an app running new JS against an old binary) is
49
+ * absent. Cached like the builtin: module availability does not change at
50
+ * runtime, and this is consulted on every update check.
51
+ */
52
+ export function getNativeVerifier() {
53
+ if (resolved !== undefined) return resolved;
54
+ const native = NativeScaleBunOta;
55
+ if (!native || typeof native.verifyEd25519 !== 'function') {
56
+ // Old binary, Jest, web/SSR — not an error, just not this source.
57
+ resolved = null;
58
+ return null;
59
+ }
60
+ resolved = async ({
61
+ messageHex,
62
+ signature,
63
+ publicKey
64
+ }) => {
65
+ // All decoding and validation happens HERE, in one place, so both
66
+ // platforms' native code only ever sees clean fixed-length hex. The
67
+ // signature may arrive hex or base64 (the wire allows both) — reuse
68
+ // the builtin's decoder rather than growing a second, subtly
69
+ // different one.
70
+ const message = normalizeHex(messageHex, 64);
71
+ const key = normalizeHex(publicKey, ED25519_PUBLIC_KEY_HEX_CHARS);
72
+ const sigBytes = decodeSignature(signature);
73
+ if (!message || !key || !sigBytes) {
74
+ // Same messages-by-symptom philosophy as the builtin: a mistyped
75
+ // key must not present as "every update is a forgery".
76
+ logger.error('[OTA] Signature inputs malformed (bundle hash, signature, or public key) — refusing to stage.');
77
+ return false;
78
+ }
79
+ let verdict;
80
+ try {
81
+ verdict = await native.verifyEd25519(message, bytesToHex(sigBytes), key);
82
+ } catch (err) {
83
+ // A rejected promise is machinery failure, not a forgery verdict.
84
+ logger.warn(`[OTA] Native ed25519 verify failed to run: ${err?.message ?? err}`);
85
+ verdict = 'unavailable';
86
+ }
87
+ if (verdict === 'valid') return true;
88
+ if (verdict === 'invalid') return false;
89
+
90
+ // 'unavailable' (Android < 33) — fall back to the JS verifier so those
91
+ // devices keep verifying rather than losing enforcement.
92
+ const builtin = getBuiltinVerifier();
93
+ if (builtin) {
94
+ return builtin({
95
+ messageHex,
96
+ signature,
97
+ publicKey
98
+ });
99
+ }
100
+ // No source can verify. Throwing (rather than returning false) keeps
101
+ // the policy layer's outcome labels honest: this surfaces as machinery
102
+ // failure with an actionable message, not as "the bundle is forged".
103
+ throw new Error('ed25519 unavailable: this OS has no native implementation (Android < 13) and the ' + 'optional peers @noble/ed25519 + @noble/hashes are not installed.');
104
+ };
105
+ __DEV__ && logger.debug('[OTA] Using native ed25519 verifier (platform crypto).');
106
+ return resolved;
107
+ }
108
+
109
+ /** Test seam — clears the cached resolution. */
110
+ export function _resetNativeVerifier() {
111
+ resolved = undefined;
112
+ }
113
+ //# sourceMappingURL=nativeVerifier.js.map