@scalebun/react-native 1.0.1 → 1.0.3
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/android/src/main/java/com/scalebun/rn/ota/BundleDownloader.kt +170 -0
- package/android/src/main/java/com/scalebun/rn/ota/ScaleBunOtaModule.kt +160 -12
- package/android/src/main/java/com/scalebun/rn/ota/SlotManager.kt +32 -6
- package/android/src/oldarch/java/com/scalebun/rn/ota/ScaleBunOtaSpec.kt +7 -1
- package/ios/Ota/BundleDownloader.swift +182 -0
- package/ios/Ota/OtaSlotManager.swift +35 -9
- package/ios/Ota/ScaleBunOtaBridge.mm +9 -0
- package/ios/Ota/ScaleBunOtaEventsModule.swift +61 -0
- package/ios/Ota/ScaleBunOtaModule.swift +58 -5
- package/lib/commonjs/bootstrap/SDKBootstrapper.js +22 -0
- package/lib/commonjs/bootstrap/SDKBootstrapper.js.map +1 -1
- package/lib/commonjs/features/crash/CrashFeature.js +18 -0
- package/lib/commonjs/features/crash/CrashFeature.js.map +1 -1
- package/lib/commonjs/features/crash/rejectionHandler.js +123 -0
- package/lib/commonjs/features/crash/rejectionHandler.js.map +1 -0
- package/lib/commonjs/features/engage/EngagePromptProvider.js +4 -2
- package/lib/commonjs/features/engage/EngagePromptProvider.js.map +1 -1
- package/lib/commonjs/features/engage/engageThrottle.js +41 -10
- package/lib/commonjs/features/engage/engageThrottle.js.map +1 -1
- package/lib/commonjs/features/engage/engageTypes.js.map +1 -1
- package/lib/commonjs/features/navigation/AutoScreenDetector.js +53 -10
- package/lib/commonjs/features/navigation/AutoScreenDetector.js.map +1 -1
- package/lib/commonjs/features/ota/OtaOrchestrator.js +515 -20
- package/lib/commonjs/features/ota/OtaOrchestrator.js.map +1 -1
- package/lib/commonjs/features/ota/environment.js +172 -0
- package/lib/commonjs/features/ota/environment.js.map +1 -0
- package/lib/commonjs/features/ota/retry.js +96 -0
- package/lib/commonjs/features/ota/retry.js.map +1 -0
- package/lib/commonjs/features/ota/signature.js +115 -0
- package/lib/commonjs/features/ota/signature.js.map +1 -0
- package/lib/commonjs/features/session/BackendSessionAdapter.js +231 -26
- package/lib/commonjs/features/session/BackendSessionAdapter.js.map +1 -1
- package/lib/commonjs/index.js +7 -0
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/public/ScaleBunErrorBoundary.js +79 -0
- package/lib/commonjs/public/ScaleBunErrorBoundary.js.map +1 -0
- package/lib/commonjs/specs/NativeScaleBunOta.js.map +1 -1
- package/lib/module/bootstrap/SDKBootstrapper.js +22 -0
- package/lib/module/bootstrap/SDKBootstrapper.js.map +1 -1
- package/lib/module/features/crash/CrashFeature.js +18 -0
- package/lib/module/features/crash/CrashFeature.js.map +1 -1
- package/lib/module/features/crash/rejectionHandler.js +116 -0
- package/lib/module/features/crash/rejectionHandler.js.map +1 -0
- package/lib/module/features/engage/EngagePromptProvider.js +4 -2
- package/lib/module/features/engage/EngagePromptProvider.js.map +1 -1
- package/lib/module/features/engage/engageThrottle.js +41 -10
- package/lib/module/features/engage/engageThrottle.js.map +1 -1
- package/lib/module/features/engage/engageTypes.js.map +1 -1
- package/lib/module/features/navigation/AutoScreenDetector.js +53 -10
- package/lib/module/features/navigation/AutoScreenDetector.js.map +1 -1
- package/lib/module/features/ota/OtaOrchestrator.js +516 -21
- package/lib/module/features/ota/OtaOrchestrator.js.map +1 -1
- package/lib/module/features/ota/environment.js +165 -0
- package/lib/module/features/ota/environment.js.map +1 -0
- package/lib/module/features/ota/retry.js +87 -0
- package/lib/module/features/ota/retry.js.map +1 -0
- package/lib/module/features/ota/signature.js +109 -0
- package/lib/module/features/ota/signature.js.map +1 -0
- package/lib/module/features/session/BackendSessionAdapter.js +230 -26
- package/lib/module/features/session/BackendSessionAdapter.js.map +1 -1
- package/lib/module/index.js +6 -0
- package/lib/module/index.js.map +1 -1
- package/lib/module/public/ScaleBunErrorBoundary.js +70 -0
- package/lib/module/public/ScaleBunErrorBoundary.js.map +1 -0
- package/lib/module/specs/NativeScaleBunOta.js.map +1 -1
- package/lib/typescript/bootstrap/SDKBootstrapper.d.ts.map +1 -1
- package/lib/typescript/features/crash/CrashFeature.d.ts.map +1 -1
- package/lib/typescript/features/crash/rejectionHandler.d.ts +46 -0
- package/lib/typescript/features/crash/rejectionHandler.d.ts.map +1 -0
- package/lib/typescript/features/engage/EngagePromptProvider.d.ts.map +1 -1
- package/lib/typescript/features/engage/engageThrottle.d.ts +24 -4
- package/lib/typescript/features/engage/engageThrottle.d.ts.map +1 -1
- package/lib/typescript/features/engage/engageTypes.d.ts +6 -0
- package/lib/typescript/features/engage/engageTypes.d.ts.map +1 -1
- package/lib/typescript/features/navigation/AutoScreenDetector.d.ts +9 -0
- package/lib/typescript/features/navigation/AutoScreenDetector.d.ts.map +1 -1
- package/lib/typescript/features/ota/OtaOrchestrator.d.ts +67 -1
- package/lib/typescript/features/ota/OtaOrchestrator.d.ts.map +1 -1
- package/lib/typescript/features/ota/OtaTypes.d.ts +42 -0
- package/lib/typescript/features/ota/OtaTypes.d.ts.map +1 -1
- package/lib/typescript/features/ota/environment.d.ts +99 -0
- package/lib/typescript/features/ota/environment.d.ts.map +1 -0
- package/lib/typescript/features/ota/retry.d.ts +53 -0
- package/lib/typescript/features/ota/retry.d.ts.map +1 -0
- package/lib/typescript/features/ota/signature.d.ts +66 -0
- package/lib/typescript/features/ota/signature.d.ts.map +1 -0
- package/lib/typescript/features/session/BackendSessionAdapter.d.ts +93 -2
- package/lib/typescript/features/session/BackendSessionAdapter.d.ts.map +1 -1
- package/lib/typescript/index.d.ts +6 -0
- package/lib/typescript/index.d.ts.map +1 -1
- package/lib/typescript/public/ScaleBunErrorBoundary.d.ts +44 -0
- package/lib/typescript/public/ScaleBunErrorBoundary.d.ts.map +1 -0
- package/lib/typescript/specs/NativeScaleBunOta.d.ts +11 -0
- package/lib/typescript/specs/NativeScaleBunOta.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/bootstrap/SDKBootstrapper.ts +24 -0
- package/src/features/crash/CrashFeature.ts +19 -0
- package/src/features/crash/rejectionHandler.ts +134 -0
- package/src/features/engage/EngagePromptProvider.tsx +4 -2
- package/src/features/engage/engageThrottle.ts +44 -6
- package/src/features/engage/engageTypes.ts +6 -0
- package/src/features/navigation/AutoScreenDetector.ts +59 -4
- package/src/features/ota/OtaOrchestrator.ts +594 -23
- package/src/features/ota/OtaTypes.ts +56 -0
- package/src/features/ota/environment.ts +199 -0
- package/src/features/ota/retry.ts +123 -0
- package/src/features/ota/signature.ts +123 -0
- package/src/features/session/BackendSessionAdapter.ts +233 -25
- package/src/index.ts +6 -0
- package/src/public/ScaleBunErrorBoundary.tsx +79 -0
- package/src/specs/NativeScaleBunOta.ts +12 -0
|
@@ -14,6 +14,43 @@ export interface OtaCheckRequest {
|
|
|
14
14
|
installationId: string;
|
|
15
15
|
currentBundleId?: string;
|
|
16
16
|
currentBundleHash?: string;
|
|
17
|
+
|
|
18
|
+
// ── C1: channel + targeting context ────────────────────────────────────────
|
|
19
|
+
// The backend DTO has accepted all of these since Sprint 9. The SDK declared
|
|
20
|
+
// none of them and `checkForUpdate` sent none, so every device in the field
|
|
21
|
+
// resolved to the `default` channel with an empty targeting context: beta
|
|
22
|
+
// channels were unreachable and the entire targeting-rule engine — country,
|
|
23
|
+
// segment, lifecycle, attributes — could never match. Sending them is what
|
|
24
|
+
// turns that already-built subsystem on.
|
|
25
|
+
/** Channel to pull from. Omitted means `default`. */
|
|
26
|
+
channelName?: string;
|
|
27
|
+
/** ISO 3166-1 alpha-2. The server fills this from the edge when absent. */
|
|
28
|
+
country?: string;
|
|
29
|
+
/** Free-form device attributes evaluated by ATTRIBUTE rules. */
|
|
30
|
+
attributes?: Record<string, string | number>;
|
|
31
|
+
/** CDP segment ids this installation belongs to. */
|
|
32
|
+
segmentIds?: string[];
|
|
33
|
+
/** Lifecycle stage (e.g. 'onboarding', 'activated', 'churned'). */
|
|
34
|
+
lifecycleStage?: string;
|
|
35
|
+
|
|
36
|
+
// ── Runtime compatibility context ──────────────────────────────────────────
|
|
37
|
+
// `appVersion` is a marketing string; these are the actual runtime contract.
|
|
38
|
+
// Serving a bundle built for a different runtime is the most common way an
|
|
39
|
+
// OTA product bricks an app, and without these fields the backend cannot
|
|
40
|
+
// even detect the mismatch, let alone refuse to serve it.
|
|
41
|
+
/** React Native version of the host binary, e.g. `"0.81.5"`. */
|
|
42
|
+
rnVersion?: string;
|
|
43
|
+
/** True when the JS engine is Hermes. */
|
|
44
|
+
hermes?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Hermes bytecode (HBC) format version of the running engine. Independent of
|
|
47
|
+
* the RN release number. A mismatch either fails to load outright ("Wrong
|
|
48
|
+
* bytecode version. Expected 96 but got 98") or — worse — loads and crashes
|
|
49
|
+
* later on a path the older runtime does not expose.
|
|
50
|
+
*/
|
|
51
|
+
hermesBytecodeVersion?: number;
|
|
52
|
+
/** True when running the New Architecture's bridgeless runtime. */
|
|
53
|
+
bridgeless?: boolean;
|
|
17
54
|
}
|
|
18
55
|
|
|
19
56
|
// ── backend → SDK ────────────────────────────────────────────────────────────
|
|
@@ -30,8 +67,27 @@ export interface OtaBundlePayload {
|
|
|
30
67
|
sha256: string;
|
|
31
68
|
signature?: string; // ed25519 detached signature (hex)
|
|
32
69
|
isMandatory: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* How to activate the bundle after install:
|
|
72
|
+
* ON_NEXT_RESTART — nothing to do now; next cold start loads it (default)
|
|
73
|
+
* ON_NEXT_RESUME — restart the JS runtime when the app next returns to
|
|
74
|
+
* the foreground after a background stay
|
|
75
|
+
* IMMEDIATE — restart the JS runtime right after install
|
|
76
|
+
* Absent means ON_NEXT_RESTART, which is what every pre-installMode release
|
|
77
|
+
* actually did.
|
|
78
|
+
*/
|
|
79
|
+
installMode?: 'ON_NEXT_RESTART' | 'ON_NEXT_RESUME' | 'IMMEDIATE';
|
|
33
80
|
releaseNote?: string;
|
|
34
81
|
patch?: OtaPatchPayload;
|
|
82
|
+
/**
|
|
83
|
+
* Identity marker compiled into this bundle at publish time.
|
|
84
|
+
*
|
|
85
|
+
* Recorded at install; compared after restart against the marker the RUNNING
|
|
86
|
+
* bundle carries. Its PRESENCE is the important part — knowing a bundle
|
|
87
|
+
* definitely has a marker is what turns "no marker after restart" from
|
|
88
|
+
* ambiguous into proof that the install never took effect.
|
|
89
|
+
*/
|
|
90
|
+
identityToken?: string;
|
|
35
91
|
}
|
|
36
92
|
|
|
37
93
|
export interface OtaPatchPayload {
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { Platform } from 'react-native';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* OTA runtime environment detection.
|
|
5
|
+
*
|
|
6
|
+
* ── Why this file exists ────────────────────────────────────────────────────
|
|
7
|
+
*
|
|
8
|
+
* Our Android OTA resolves the active bundle through
|
|
9
|
+
* `MainApplication.getJSBundleFile()`. That is a *bridge-mode* API.
|
|
10
|
+
*
|
|
11
|
+
* Under the New Architecture (bridgeless), the app is built by
|
|
12
|
+
* `DefaultReactHost` instead — and until React Native 0.76.1,
|
|
13
|
+
* `DefaultReactNativeHost.toReactHost()` never forwarded `jsBundleFile`:
|
|
14
|
+
*
|
|
15
|
+
* // RN 0.74.1 — DefaultReactNativeHost.kt
|
|
16
|
+
* public fun toReactHost(context: Context): ReactHost =
|
|
17
|
+
* DefaultReactHost.getDefaultReactHost(
|
|
18
|
+
* context, packages, jsMainModuleName,
|
|
19
|
+
* bundleAssetName ?: "index", // <- jsBundleFile is NEVER passed
|
|
20
|
+
* isHermesEnabled ?: true)
|
|
21
|
+
*
|
|
22
|
+
* // RN 0.74.1 — DefaultReactHost.kt
|
|
23
|
+
* val jsBundleLoader =
|
|
24
|
+
* JSBundleLoader.createAssetLoader(context, "assets://$jsBundleAssetPath", true)
|
|
25
|
+
*
|
|
26
|
+
* The loader is hardcoded to the APK asset. `getJSBundleFile()` is never
|
|
27
|
+
* consulted, so an update stages, applies, reports INSTALLED, restarts — and
|
|
28
|
+
* the app loads the bundle baked into the APK. Every signal says success and
|
|
29
|
+
* nothing happened. This is the same failure that killed CodePush on modern RN.
|
|
30
|
+
*
|
|
31
|
+
* Fixed upstream in 0.76.1 (`jsBundleFile` is threaded through). Verified
|
|
32
|
+
* present in 0.81.5.
|
|
33
|
+
*
|
|
34
|
+
* We refuse to run rather than pretend to work. A loud failure at startup is
|
|
35
|
+
* recoverable; a silent no-op that reports success is not — it corrupts the
|
|
36
|
+
* adoption metrics, the guard thresholds, and every rollout decision made
|
|
37
|
+
* from them.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** First React Native version where bridgeless honours `getJSBundleFile()`. */
|
|
41
|
+
export const MIN_BRIDGELESS_RN = { major: 0, minor: 76, patch: 1 } as const;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* React Native 0.82 REMOVED `ReactNativeHost`. The New Architecture became
|
|
45
|
+
* mandatory and `newArchEnabled=false` was withdrawn, so the legacy
|
|
46
|
+
* `override fun getJSBundleFile()` integration does not merely stop working —
|
|
47
|
+
* it does not compile. From 0.82 the only correct integration is passing
|
|
48
|
+
* `jsBundleFilePath` straight to `getDefaultReactHost(...)`.
|
|
49
|
+
*
|
|
50
|
+
* We cannot see which integration a host app used, so this is not a block. It
|
|
51
|
+
* drives a startup hint, and the post-restart identity check is what actually
|
|
52
|
+
* catches a host that got it wrong.
|
|
53
|
+
*/
|
|
54
|
+
export const REACT_HOST_ONLY_RN = { major: 0, minor: 82, patch: 0 } as const;
|
|
55
|
+
|
|
56
|
+
export interface RnVersion {
|
|
57
|
+
major: number;
|
|
58
|
+
minor: number;
|
|
59
|
+
patch: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface OtaEnvironment {
|
|
63
|
+
/** Parsed React Native version, or null when it could not be determined. */
|
|
64
|
+
rnVersion: RnVersion | null;
|
|
65
|
+
/** `"0.76.1"`, or null. Sent to the backend for compatibility gating. */
|
|
66
|
+
rnVersionString: string | null;
|
|
67
|
+
/** True when running on the New Architecture's bridgeless runtime. */
|
|
68
|
+
bridgeless: boolean;
|
|
69
|
+
/** True when the JS engine is Hermes. */
|
|
70
|
+
hermes: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Hermes bytecode (HBC) format version of the *running* engine. This is the
|
|
73
|
+
* file-format compatibility number, NOT a React Native release number — the
|
|
74
|
+
* two move independently. A bundle compiled by a different hermesc can be
|
|
75
|
+
* rejected outright ("Wrong bytecode version. Expected 96 but got 98") or,
|
|
76
|
+
* worse, load fine and crash later on a path the older runtime lacks.
|
|
77
|
+
*/
|
|
78
|
+
hermesBytecodeVersion: number | null;
|
|
79
|
+
/** False when OTA cannot work on this runtime and must not be enabled. */
|
|
80
|
+
supported: boolean;
|
|
81
|
+
/** Human-readable explanation when `supported` is false. */
|
|
82
|
+
blockReason: string | null;
|
|
83
|
+
/**
|
|
84
|
+
* True on RN >= 0.82, where `ReactNativeHost` no longer exists and the only
|
|
85
|
+
* valid integration is `getDefaultReactHost(..., jsBundleFilePath = …)`.
|
|
86
|
+
* Used to make the startup diagnostic name the right fix.
|
|
87
|
+
*/
|
|
88
|
+
requiresReactHostIntegration: boolean;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function compare(a: RnVersion, b: { major: number; minor: number; patch: number }): number {
|
|
92
|
+
if (a.major !== b.major) return a.major - b.major;
|
|
93
|
+
if (a.minor !== b.minor) return a.minor - b.minor;
|
|
94
|
+
return a.patch - b.patch;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function readRnVersion(): RnVersion | null {
|
|
98
|
+
// `Platform.constants.reactNativeVersion` is public API and present on both
|
|
99
|
+
// platforms since 0.62. Preferred over the deep `Libraries/Core/...` import,
|
|
100
|
+
// which is private and has moved between releases.
|
|
101
|
+
try {
|
|
102
|
+
const v = (Platform as unknown as { constants?: { reactNativeVersion?: RnVersion } })
|
|
103
|
+
.constants?.reactNativeVersion;
|
|
104
|
+
if (v && typeof v.major === 'number' && typeof v.minor === 'number') {
|
|
105
|
+
return { major: v.major, minor: v.minor, patch: v.patch ?? 0 };
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
// fall through
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function readBridgeless(): boolean {
|
|
114
|
+
// Set by the runtime itself when the bridgeless host is in use. Absent on
|
|
115
|
+
// the old architecture, so `=== true` is the correct test.
|
|
116
|
+
try {
|
|
117
|
+
return (globalThis as unknown as { RN$Bridgeless?: boolean }).RN$Bridgeless === true;
|
|
118
|
+
} catch {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface HermesInternalShape {
|
|
124
|
+
getRuntimeProperties?: () => Record<string, unknown>;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function readHermes(): { hermes: boolean; bytecodeVersion: number | null } {
|
|
128
|
+
try {
|
|
129
|
+
const h = (globalThis as unknown as { HermesInternal?: HermesInternalShape }).HermesInternal;
|
|
130
|
+
if (!h) return { hermes: false, bytecodeVersion: null };
|
|
131
|
+
|
|
132
|
+
let bytecodeVersion: number | null = null;
|
|
133
|
+
const props = h.getRuntimeProperties?.();
|
|
134
|
+
if (props) {
|
|
135
|
+
// Hermes reports this as "Bytecode Version"; the value has been both a
|
|
136
|
+
// number and a numeric string across releases, so coerce and validate.
|
|
137
|
+
const raw = props['Bytecode Version'];
|
|
138
|
+
const n = typeof raw === 'string' ? Number(raw) : raw;
|
|
139
|
+
if (typeof n === 'number' && Number.isFinite(n)) bytecodeVersion = n;
|
|
140
|
+
}
|
|
141
|
+
return { hermes: true, bytecodeVersion };
|
|
142
|
+
} catch {
|
|
143
|
+
return { hermes: false, bytecodeVersion: null };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
let cached: OtaEnvironment | null = null;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Detect the runtime environment and decide whether OTA can function at all.
|
|
151
|
+
* Result is cached — none of these values change during a process lifetime.
|
|
152
|
+
*/
|
|
153
|
+
export function detectOtaEnvironment(): OtaEnvironment {
|
|
154
|
+
if (cached) return cached;
|
|
155
|
+
|
|
156
|
+
const rnVersion = readRnVersion();
|
|
157
|
+
const bridgeless = readBridgeless();
|
|
158
|
+
const { hermes, bytecodeVersion } = readHermes();
|
|
159
|
+
|
|
160
|
+
let supported = true;
|
|
161
|
+
let blockReason: string | null = null;
|
|
162
|
+
|
|
163
|
+
if (bridgeless && rnVersion) {
|
|
164
|
+
if (compare(rnVersion, MIN_BRIDGELESS_RN) < 0) {
|
|
165
|
+
supported = false;
|
|
166
|
+
blockReason =
|
|
167
|
+
`React Native ${rnVersion.major}.${rnVersion.minor}.${rnVersion.patch} is running ` +
|
|
168
|
+
`bridgeless (New Architecture), but jsBundleFile was not threaded through ` +
|
|
169
|
+
`DefaultReactHost until RN 0.76.1. getJSBundleFile() is ignored on this runtime, ` +
|
|
170
|
+
`so an OTA bundle would install successfully and never actually load. ` +
|
|
171
|
+
`Upgrade to React Native >= 0.76.1, or disable the New Architecture.`;
|
|
172
|
+
}
|
|
173
|
+
} else if (bridgeless && !rnVersion) {
|
|
174
|
+
// Can't prove it's broken, and blocking every app whose version we failed
|
|
175
|
+
// to read would be worse than the bug. Warn instead of blocking.
|
|
176
|
+
blockReason = null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
cached = {
|
|
180
|
+
rnVersion,
|
|
181
|
+
rnVersionString: rnVersion
|
|
182
|
+
? `${rnVersion.major}.${rnVersion.minor}.${rnVersion.patch}`
|
|
183
|
+
: null,
|
|
184
|
+
bridgeless,
|
|
185
|
+
hermes,
|
|
186
|
+
hermesBytecodeVersion: bytecodeVersion,
|
|
187
|
+
supported,
|
|
188
|
+
blockReason,
|
|
189
|
+
requiresReactHostIntegration: rnVersion
|
|
190
|
+
? compare(rnVersion, REACT_HOST_ONLY_RN) >= 0
|
|
191
|
+
: false,
|
|
192
|
+
};
|
|
193
|
+
return cached;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Test seam — the detection result is process-lifetime cached. */
|
|
197
|
+
export function _resetOtaEnvironmentCache(): void {
|
|
198
|
+
cached = null;
|
|
199
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { logger } from '../../core/logger/internalLogger';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Retry with exponential backoff and full jitter.
|
|
5
|
+
*
|
|
6
|
+
* ── Why ─────────────────────────────────────────────────────────────────────
|
|
7
|
+
*
|
|
8
|
+
* The OTA path had no retry at all. A download that failed on a flaky mobile
|
|
9
|
+
* connection returned an error and the device then waited for the next cold
|
|
10
|
+
* start to try again — which on a phone is often hours, and on a device that
|
|
11
|
+
* is never fully restarted, effectively never. On mobile networks a single
|
|
12
|
+
* transient failure is the common case, not the exception.
|
|
13
|
+
*
|
|
14
|
+
* Full jitter (`random(0, backoff)` rather than `backoff`) matters more here
|
|
15
|
+
* than in most clients: every device on a release checks in against the same
|
|
16
|
+
* schedule, so a fixed backoff would retry the whole fleet in lockstep and
|
|
17
|
+
* turn one origin blip into a synchronised thundering herd.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export interface RetryOptions {
|
|
21
|
+
/** Total attempts including the first. Default 3. */
|
|
22
|
+
attempts?: number;
|
|
23
|
+
/** Base delay in ms for the first backoff. Default 1000. */
|
|
24
|
+
baseDelayMs?: number;
|
|
25
|
+
/** Upper bound on any single delay. Default 30_000. */
|
|
26
|
+
maxDelayMs?: number;
|
|
27
|
+
/** Label used in log lines. */
|
|
28
|
+
label?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Decides whether a given failure is worth retrying. Default: retry
|
|
31
|
+
* everything. Callers should pass a predicate that returns false for
|
|
32
|
+
* failures that will never succeed on a retry (4xx, hash mismatch), so a
|
|
33
|
+
* device does not burn battery re-requesting something already rejected.
|
|
34
|
+
*/
|
|
35
|
+
isRetryable?: (err: unknown) => boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const DEFAULT_ATTEMPTS = 3;
|
|
39
|
+
const DEFAULT_BASE_DELAY_MS = 1_000;
|
|
40
|
+
const DEFAULT_MAX_DELAY_MS = 30_000;
|
|
41
|
+
|
|
42
|
+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
43
|
+
|
|
44
|
+
/** Exposed for tests; `Math.random` is the only nondeterminism in the schedule. */
|
|
45
|
+
export function backoffDelay(
|
|
46
|
+
attemptIndex: number,
|
|
47
|
+
baseDelayMs: number,
|
|
48
|
+
maxDelayMs: number,
|
|
49
|
+
random: () => number = Math.random,
|
|
50
|
+
): number {
|
|
51
|
+
const exponential = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attemptIndex));
|
|
52
|
+
return Math.floor(random() * exponential);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Run `fn`, retrying on failure with exponential backoff.
|
|
57
|
+
* Rethrows the last error once attempts are exhausted.
|
|
58
|
+
*/
|
|
59
|
+
export async function retryWithBackoff<T>(
|
|
60
|
+
fn: (attempt: number) => Promise<T>,
|
|
61
|
+
options: RetryOptions = {},
|
|
62
|
+
): Promise<T> {
|
|
63
|
+
const attempts = options.attempts ?? DEFAULT_ATTEMPTS;
|
|
64
|
+
const baseDelayMs = options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
|
|
65
|
+
const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
|
66
|
+
const label = options.label ?? 'operation';
|
|
67
|
+
const isRetryable = options.isRetryable ?? (() => true);
|
|
68
|
+
|
|
69
|
+
let lastError: unknown;
|
|
70
|
+
|
|
71
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
72
|
+
try {
|
|
73
|
+
return await fn(attempt);
|
|
74
|
+
} catch (err) {
|
|
75
|
+
lastError = err;
|
|
76
|
+
|
|
77
|
+
if (!isRetryable(err)) {
|
|
78
|
+
logger.debug(`[OTA] ${label} failed with a non-retryable error — not retrying`);
|
|
79
|
+
throw err;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const isLast = attempt === attempts - 1;
|
|
83
|
+
if (isLast) break;
|
|
84
|
+
|
|
85
|
+
const delay = backoffDelay(attempt, baseDelayMs, maxDelayMs);
|
|
86
|
+
logger.debug(
|
|
87
|
+
`[OTA] ${label} failed (attempt ${attempt + 1}/${attempts}) — retrying in ${delay}ms`,
|
|
88
|
+
);
|
|
89
|
+
await sleep(delay);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
throw lastError;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* True for failures that a later attempt could plausibly survive.
|
|
98
|
+
*
|
|
99
|
+
* Network errors and 5xx/429 are retryable. A 4xx other than 429 is the server
|
|
100
|
+
* telling us the request itself is wrong — retrying it just wastes battery.
|
|
101
|
+
*/
|
|
102
|
+
export function isRetryableNetworkError(err: unknown): boolean {
|
|
103
|
+
const status = (err as { status?: number } | undefined)?.status;
|
|
104
|
+
if (typeof status === 'number') {
|
|
105
|
+
if (status === 429) return true;
|
|
106
|
+
if (status >= 500) return true;
|
|
107
|
+
if (status >= 400) return false;
|
|
108
|
+
}
|
|
109
|
+
// fetch() rejects with a TypeError on DNS failure, connection refused, and
|
|
110
|
+
// airplane mode — all of which are exactly what we want to retry.
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Error carrying an HTTP status so `isRetryableNetworkError` can classify it. */
|
|
115
|
+
export class HttpStatusError extends Error {
|
|
116
|
+
constructor(
|
|
117
|
+
message: string,
|
|
118
|
+
public readonly status: number,
|
|
119
|
+
) {
|
|
120
|
+
super(message);
|
|
121
|
+
this.name = 'HttpStatusError';
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { logger } from '../../core/logger/internalLogger';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Bundle signature verification (OTA-03).
|
|
5
|
+
*
|
|
6
|
+
* WHAT WAS WRONG. `ota-signing-key.service.ts` documents the intended model
|
|
7
|
+
* exactly: the CLI generates an ed25519 keypair locally, uploads only the public
|
|
8
|
+
* half, and "the device verifies every bundle's signature before install and
|
|
9
|
+
* rejects forgeries." Two of those three steps did not exist. The CLI had no
|
|
10
|
+
* signing code, and this SDK received `bundle.signature` in the check response
|
|
11
|
+
* and never read it. The only client-side check was SHA-256 against a hash
|
|
12
|
+
* delivered in the same response as the URL — which defends against a corrupted
|
|
13
|
+
* download and nothing else. On a platform whose entire purpose is remote code
|
|
14
|
+
* delivery, that is the control that matters most.
|
|
15
|
+
*
|
|
16
|
+
* WHY IT IS SHAPED LIKE THIS. The SDK ships zero third-party runtime
|
|
17
|
+
* dependencies, and React Native has no built-in ed25519. So verification is
|
|
18
|
+
* delegated to a host-provided verifier when one is installed, and the SDK's job
|
|
19
|
+
* is to decide — unambiguously — what happens when there is not one.
|
|
20
|
+
*
|
|
21
|
+
* THE POLICY, which is the important part:
|
|
22
|
+
*
|
|
23
|
+
* - A bundle carrying a signature, with a configured public key and a
|
|
24
|
+
* verifier: verified. Failure REJECTS the install. This is the goal state.
|
|
25
|
+
* - A bundle carrying a signature, with a public key configured, but no
|
|
26
|
+
* verifier available: REJECT. The app asked for signature enforcement by
|
|
27
|
+
* configuring a key; silently installing unverified code because a helper is
|
|
28
|
+
* missing would turn a security feature into a placebo.
|
|
29
|
+
* - No public key configured: skip, and say so once. Signing is opt-in per app,
|
|
30
|
+
* and an app that has not adopted it must keep working.
|
|
31
|
+
*
|
|
32
|
+
* The failure mode is the whole design: an app that opts in cannot be
|
|
33
|
+
* accidentally downgraded to unverified installs.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** Verifies a detached ed25519 signature. Supplied by the host app. */
|
|
37
|
+
export type SignatureVerifier = (input: {
|
|
38
|
+
/** Hex-encoded SHA-256 of the bundle — what the signature is over. */
|
|
39
|
+
messageHex: string;
|
|
40
|
+
/** Hex or base64 detached signature from the check response. */
|
|
41
|
+
signature: string;
|
|
42
|
+
/** The app's configured ed25519 public key. */
|
|
43
|
+
publicKey: string;
|
|
44
|
+
}) => boolean | Promise<boolean>;
|
|
45
|
+
|
|
46
|
+
export interface SignatureConfig {
|
|
47
|
+
/** ed25519 public key shipped in the app binary. Absent = signing not adopted. */
|
|
48
|
+
publicKey?: string;
|
|
49
|
+
/** Host-provided ed25519 verification function. */
|
|
50
|
+
verifier?: SignatureVerifier;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type SignatureOutcome =
|
|
54
|
+
| { ok: true; reason: 'verified' | 'not_configured' }
|
|
55
|
+
| { ok: false; reason: 'no_verifier' | 'invalid_signature' | 'missing_signature' | 'verifier_threw' };
|
|
56
|
+
|
|
57
|
+
let warnedNotConfigured = false;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Decide whether a bundle may be staged.
|
|
61
|
+
*
|
|
62
|
+
* Returns a structured outcome rather than a boolean so the caller can emit a
|
|
63
|
+
* precise telemetry reason — "we shipped unverified code because no key was
|
|
64
|
+
* configured" and "we refused because the signature was forged" are very
|
|
65
|
+
* different operational events and must not collapse into one.
|
|
66
|
+
*/
|
|
67
|
+
export async function verifyBundleSignature(
|
|
68
|
+
bundleSha256: string,
|
|
69
|
+
signature: string | undefined,
|
|
70
|
+
config: SignatureConfig | undefined,
|
|
71
|
+
): Promise<SignatureOutcome> {
|
|
72
|
+
const publicKey = config?.publicKey;
|
|
73
|
+
|
|
74
|
+
// Signing not adopted by this app — nothing to enforce.
|
|
75
|
+
if (!publicKey) {
|
|
76
|
+
if (!warnedNotConfigured) {
|
|
77
|
+
warnedNotConfigured = true;
|
|
78
|
+
logger.warn(
|
|
79
|
+
'[OTA] No signing public key configured — bundles are accepted on SHA-256 ' +
|
|
80
|
+
'integrity alone. Configure `ota.publicSigningKey` to enforce authenticity.',
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return { ok: true, reason: 'not_configured' };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The app opted in, so a bundle without a signature is a refusal, not a pass.
|
|
87
|
+
if (!signature) {
|
|
88
|
+
logger.error(
|
|
89
|
+
'[OTA] Bundle has no signature but a signing key is configured — refusing to stage.',
|
|
90
|
+
);
|
|
91
|
+
return { ok: false, reason: 'missing_signature' };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (typeof config?.verifier !== 'function') {
|
|
95
|
+
logger.error(
|
|
96
|
+
'[OTA] A signing key is configured but no signature verifier is available — ' +
|
|
97
|
+
'refusing to stage. Provide `ota.verifySignature` so signatures can be checked.',
|
|
98
|
+
);
|
|
99
|
+
return { ok: false, reason: 'no_verifier' };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const valid = await config.verifier({
|
|
104
|
+
messageHex: bundleSha256,
|
|
105
|
+
signature,
|
|
106
|
+
publicKey,
|
|
107
|
+
});
|
|
108
|
+
if (!valid) {
|
|
109
|
+
logger.error('[OTA] Bundle signature is INVALID — refusing to stage.');
|
|
110
|
+
return { ok: false, reason: 'invalid_signature' };
|
|
111
|
+
}
|
|
112
|
+
return { ok: true, reason: 'verified' };
|
|
113
|
+
} catch (err: any) {
|
|
114
|
+
// A throwing verifier is treated as a failed verification, never as a pass.
|
|
115
|
+
logger.error(`[OTA] Signature verifier threw: ${err?.message ?? err}`);
|
|
116
|
+
return { ok: false, reason: 'verifier_threw' };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Test seam — resets the once-per-process "not configured" warning. */
|
|
121
|
+
export function _resetSignatureWarnings(): void {
|
|
122
|
+
warnedNotConfigured = false;
|
|
123
|
+
}
|