native-update 4.2.4 → 4.4.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.
@@ -0,0 +1,199 @@
1
+ # Native Update client protocol
2
+
3
+ **Version:** 1 (server marker `2026.11.20.1`, plugin 4.4.0) · **Last updated:** 2026-11-20
4
+
5
+ Every Native Update SDK speaks this protocol: the Capacitor plugin, the native Android library, the Flutter
6
+ plugin, the React Native package and, later, native iOS. It is written from the code that runs today:
7
+ `backend/app/Http/Controllers/Api/UpdateController.php`, `src/core/update-check.ts`,
8
+ `android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt` and `SecurityManager.kt`. If code and
9
+ this file disagree, the code is right and this file is fixed in the same change.
10
+
11
+ ## 1. Update check
12
+
13
+ ```
14
+ GET {serverUrl}/v1/updates/check?channel={production|staging|development}
15
+ ```
16
+
17
+ `serverUrl` is the canonical base ending in `/api` (`https://nativeupdatebe.aoneahsan.com/api`). HTTPS only.
18
+
19
+ | Header | Required | Value |
20
+ |---|---|---|
21
+ | `X-API-Key` | yes | The app's `nu_app_…` device key. Missing → 401 `MISSING_API_KEY`. |
22
+ | `X-Device-ID` | yes | A stable random id per install, generated once and stored. Missing → 400 `MISSING_DEVICE_ID`. |
23
+ | `X-Current-Version` | yes | The version of the payload running now: the active OTA payload, or the version shipped inside the binary when none is active. |
24
+ | `X-Platform` | yes | `android` · `ios` · `web` |
25
+ | `X-App-Version` | when known | The native binary's version name. Used by `minNativeVersion`. |
26
+ | `X-Client-Sdk` | yes, new SDKs | `capacitor` · `android` · `flutter` · `react-native` · `ios` |
27
+ | `X-Sdk-Version` | yes, new SDKs | The SDK's own version, `[0-9A-Za-z.+-]{1,32}` |
28
+ | `X-Accept-Payload` | new SDKs | Comma-separated payload types the client can apply; Flutter adds `dart_aot` to receive code updates |
29
+ | `X-Runtime-Key` | Flutter code updates | SHA-256 (lowercase hex) of the running `libflutter.so` |
30
+ | `X-Android-Package` | Android | applicationId, for per-key client restrictions |
31
+ | `X-Android-Cert-Sha256` / `-Sha1` | Android, when readable | Signing certificate digest, lowercase hex |
32
+ | `X-Ios-Bundle-Id` | iOS | Bundle identifier |
33
+
34
+ A key restricted to other identities answers 403 `API_KEY_RESTRICTED`. The identity headers are reported by the
35
+ client, not cryptographically attested.
36
+
37
+ ### Payload types
38
+
39
+ A build is one ZIP with one `payloadType`. The server offers a build only to an SDK that can run it:
40
+
41
+ | `X-Client-Sdk` | Accepted payload | What the SDK does with it |
42
+ |---|---|---|
43
+ | `capacitor`, `react-native`, absent | `web_bundle` | Serves it as the app's web / JS bundle |
44
+ | `android`, `flutter`, `ios` | `assets` | Exposes the unpacked files to the app (images, JSON config). Never loads code from it. |
45
+ | `flutter` with `X-Accept-Payload: …dart_aot` | also `dart_aot` | Loads the patch's `lib/<abi>/libapp.so` as the app's Dart code (below) |
46
+
47
+ A client that sends no `X-Client-Sdk` is a Capacitor plugin older than 4.3.0. When the newest build has a
48
+ payload the client cannot use, the check answers `available:false` with `code:"PAYLOAD_NOT_SUPPORTED"`.
49
+
50
+ Native Android apps never receive executable code by OTA. Flutter apps receive it only as `dart_aot`, and only when
51
+ they ask for it. The Flutter SDK asks only in a build **not** installed from Google Play that turned code updates on;
52
+ Play's policy forbids downloaded native code.
53
+
54
+ ### Dart code updates (`dart_aot`)
55
+
56
+ A `dart_aot` bundle holds `lib/<abi>/libapp.so` (compiled Dart code) per CPU architecture, plus optional asset files.
57
+ It is offered only to the exact Flutter engine it was compiled against: the build lists the SHA-256 of every
58
+ `libflutter.so` it fits (`runtime_keys`), the device sends its own as `X-Runtime-Key`, and a mismatch answers
59
+ `RUNTIME_MISMATCH`.
60
+
61
+ The device side:
62
+ 1. runs the cold-start checks **before the engine starts**: integrity, the rollback count, the new-binary retire;
63
+ 2. points the engine at the active patch (`--aot-shared-library-name`, accepted only for a `.so` inside the app's
64
+ `filesDir`);
65
+ 3. loads code only from a bundle recorded as `dart_aot`. An `assets` bundle that contains a `.so` is never run.
66
+
67
+ Build the patch APK with the same Flutter version and native plugins as the installed build;
68
+ `npx native-update bundle flutter-patch <apk>` makes the ZIP and its engine list.
69
+
70
+ ### Response (always HTTP 200 once the key is valid)
71
+
72
+ No update:
73
+
74
+ ```json
75
+ { "available": false, "message": "Already on latest version" }
76
+ ```
77
+
78
+ Other `available:false` shapes carry extra fields:
79
+ - `minNativeVersion`: the binary is too old for the newest build;
80
+ - `held: true, code: "BILLING_HOLD", version`: an update exists but delivery is paused;
81
+ - `code: "PAYLOAD_NOT_SUPPORTED"`.
82
+
83
+ Update available:
84
+
85
+ ```json
86
+ {
87
+ "available": true,
88
+ "version": "1.4.0",
89
+ "bundleId": "9b1c…uuid",
90
+ "downloadUrl": "https://…/api/v1/bundles/123/download?signature=…",
91
+ "checksum": "64 lowercase hex chars (SHA-256 of the ZIP)",
92
+ "signature": "base64 | null",
93
+ "signatureAlgorithm": "RSA-SHA256 | null",
94
+ "payloadType": "web_bundle | assets",
95
+ "size": 482113,
96
+ "mandatory": false,
97
+ "releaseNotes": "text | null",
98
+ "minNativeVersion": "1.16.0 | null",
99
+ "expiresAt": "ISO-8601, when downloadUrl stops working",
100
+ "delta": null
101
+ }
102
+ ```
103
+
104
+ The server never offers a version equal to or older than `X-Current-Version`. A client still compares the
105
+ two itself (semver: numeric major.minor.patch) and refuses a downgrade.
106
+
107
+ A network error, a timeout or a non-2xx answer is an **error**, never "no update". The SDK reports it to the
108
+ app (`NETWORK_ERROR`) and keeps running the current payload.
109
+
110
+ ## 2. Download and verification
111
+
112
+ 1. GET `downloadUrl` before `expiresAt`. Write it to a temporary file and stop past the configured size limit
113
+ (`maxBundleSize`, default 100 MB).
114
+ 2. **Checksum:** SHA-256 of the downloaded bytes, lowercase hex, must equal `checksum`. On a mismatch, delete
115
+ the file (`CHECKSUM_ERROR`).
116
+ 3. **Signature:** when `requireSignature` is on (the production default), `signature` must be present and
117
+ `signatureAlgorithm` must be `RSA-SHA256`. Verify `SHA256withRSA` (PKCS#1 v1.5) over the **exact ZIP bytes**
118
+ with the app's public key (X.509 SubjectPublicKeyInfo, PEM or bare base64). Any failure deletes the file,
119
+ stores nothing and keeps the current payload (`SIGNATURE_ERROR`). Unsigned payloads are allowed only in
120
+ debug builds, with both `requireSignature:false` and `allowUnsignedDevelopmentUpdates:true`.
121
+ 4. **Unpack** into a new directory named after `bundleId`. Every entry's canonical path must stay inside that
122
+ directory (Zip-Slip refusal), and the unpacked size is bounded (`maxUncompressedBundleSize`).
123
+
124
+ ### Delta (`NUDELTA/1`)
125
+
126
+ When the device runs a version the server still holds, `delta` carries:
127
+ `{ format:"NUDELTA/1", fromVersion, patchUrl, patchSize, patchChecksum, targetChecksum }`.
128
+
129
+ The patch is JSON: `{ format, baseChecksum, targetChecksum, targetSize, operations[] }`. Each operation is
130
+ `{op:"copy", offset, length}` (bytes from the current ZIP) or `{op:"literal", data:"base64"}`.
131
+
132
+ A client:
133
+ - checks `patchChecksum`, then `baseChecksum` against its current ZIP;
134
+ - applies at most 100,000 bounded operations and refuses any out-of-range copy or oversize output;
135
+ - runs steps 2 and 3 on the rebuilt ZIP exactly as for a full download.
136
+
137
+ Any delta failure falls back to the full `downloadUrl`. Delta support is optional for an SDK; the full
138
+ download is always valid.
139
+
140
+ ## 3. Activation, confirmation and rollback
141
+
142
+ State kept per install (Android uses SharedPreferences, iOS UserDefaults):
143
+
144
+ | Key | Meaning |
145
+ |---|---|
146
+ | active | the bundle now in use |
147
+ | previous | the rollback target |
148
+ | pending + attempts | an activated bundle not yet confirmed, and how many cold starts it has had |
149
+ | binary identity | `versionCode:versionName` of the binary that activated `active` |
150
+
151
+ - **Activate:** previous ← active, active ← new, pending ← new, attempts ← 0, and record the binary identity.
152
+ When the payload type needs a restart (web bundles), switch on the next start or background.
153
+ - **Confirm:** the app calls `notifyAppReady()` once it has started cleanly on the payload. That clears
154
+ pending.
155
+ - **Rollback:** on each cold start with pending set, attempts += 1. At **2** unconfirmed starts, go back to
156
+ previous (or to the binary's own payload) and stop offering that bundle. A checksum or signature mismatch
157
+ of the active payload on start rolls back at once.
158
+ - **New binary:** when the recorded binary identity differs from the running binary (a store update), the
159
+ stored OTA payload is retired and the binary's own payload is used. The server then decides afresh.
160
+ - **Pruning:** after a confirmed start, delete every stored bundle except active, previous, pending and the
161
+ newest staged download that is newer than active.
162
+
163
+ ## 4. Configuration
164
+
165
+ Configuration is applied once per process. Calling it again with identical values resolves. Different values
166
+ are refused until `reset()`. Optional fields are read null-safely: a missing optional field never fails
167
+ configuration (ISSUE-14).
168
+
169
+ ## 5. Release gate (layer 2)
170
+
171
+ The update check answers "is there a payload". The release gate answers "must this binary update first". It
172
+ reads the app's release record on start and resume, and on a push, never on a timer:
173
+ - an **urgent** release with a newer native version blocks the app now, showing its reason and one Update
174
+ action;
175
+ - a **normal** one says so, then blocks from the next start;
176
+ - offline, it fails open.
177
+
178
+ On Play builds the Update action uses Play in-app update (IMMEDIATE). Play-excluded apps open their APK
179
+ download instead.
180
+
181
+ ## 6. Error codes an SDK reports
182
+
183
+ Codes in use by the Capacitor plugin today, which the new SDKs reuse with the same meaning:
184
+
185
+ | Code | When |
186
+ |---|---|
187
+ | `NETWORK_ERROR` / `UPDATE_CHECK_FAILED` | the check or download could not reach the server or got a non-2xx |
188
+ | `DOWNLOAD_ERROR` | the download stopped or exceeded the size limit |
189
+ | `CHECKSUM_ERROR` | SHA-256 mismatch |
190
+ | `SIGNATURE_ERROR` | signature missing, unsupported algorithm or invalid |
191
+ | `EXTRACTION_ERROR` | unpack failed, Zip-Slip or the unpacked size limit |
192
+ | `INSECURE_URL` | a non-HTTPS server or download URL |
193
+ | `VALIDATION_ERROR` | bad input from the app |
194
+ | `PAYLOAD_NOT_SUPPORTED` | server-side: the newest build is not a payload this SDK runs |
195
+ | `RUNTIME_MISMATCH` | server-side: the newest code patch was built for a different Flutter engine |
196
+ | `BILLING_HOLD` | server-side, informational: delivery paused |
197
+
198
+ A repeated configuration with different values is refused with the message "Configuration is locked after
199
+ initialization; call reset() first". Errors never include filesystem paths, keys or signatures.
@@ -25,6 +25,10 @@ implements it in exactly one place — `src/core/update-check.ts` — used by
25
25
  - `X-Current-Version`: currently-installed bundle version
26
26
  - `X-Platform`: ios | android | web
27
27
  - `X-App-Version`: native app version (optional)
28
+ - `X-Client-Sdk`: `capacitor` (4.3.0+). A backend serving only this plugin may ignore it. A backend that also
29
+ serves the native Android, Flutter or React Native SDKs must offer each SDK only a payload it can run; see
30
+ `docs/protocol/CLIENT-PROTOCOL.md` (shipped in this package).
31
+ - `X-Sdk-Version`: the plugin version (4.3.0+, optional to read)
28
32
 
29
33
  **Optional client-identity headers** (for API-key client restrictions; a custom
30
34
  backend MAY read + enforce these, or ignore them):
@@ -19,6 +19,8 @@ class LiveUpdatePlugin: @unchecked Sendable {
19
19
  // UserDefaults keys for the A2 (boot-time re-verify) and A3
20
20
  // (crash-loop auto-rollback) defenses. Mirrors the Android constants
21
21
  // in LiveUpdatePlugin.kt so the two platforms stay in lockstep.
22
+ /// This plugin's version, sent as X-Sdk-Version. Kept equal to package.json by tests/sdk-version.test.ts.
23
+ static let sdkVersion = "4.4.0"
22
24
  private static let activeBundleKey = "native_update_active_bundle"
23
25
  private static let previousBundleKey = "native_update_previous_active_bundle"
24
26
  private static let pendingBundleKey = "native_update_pending_verify_bundle"
@@ -504,6 +506,9 @@ class LiveUpdatePlugin: @unchecked Sendable {
504
506
  request.setValue(getOrCreateDeviceId(), forHTTPHeaderField: "X-Device-ID")
505
507
  request.setValue(getCurrentVersion(), forHTTPHeaderField: "X-Current-Version")
506
508
  request.setValue("ios", forHTTPHeaderField: "X-Platform")
509
+ // SDK identity: the server offers this WebView only web bundles (docs/protocol/CLIENT-PROTOCOL.md).
510
+ request.setValue("capacitor", forHTTPHeaderField: "X-Client-Sdk")
511
+ request.setValue(LiveUpdatePlugin.sdkVersion, forHTTPHeaderField: "X-Sdk-Version")
507
512
  // App-identity header for API-key client restrictions (bundle id only;
508
513
  // team id is intentionally not sent by the plugin).
509
514
  if let bundleId = Bundle.main.bundleIdentifier {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "native-update",
3
- "version": "4.2.4",
3
+ "version": "4.4.0",
4
4
  "packageManager": "yarn@4.18.1",
5
5
  "engines": {
6
6
  "node": ">=24.16.0"
@@ -21,9 +21,7 @@
21
21
  "./dist/*": "./dist/*",
22
22
  "./cli/*": "./cli/*"
23
23
  },
24
- "bin": {
25
- "native-update": "cli/index.js"
26
- },
24
+ "bin": "cli/index.js",
27
25
  "files": [
28
26
  "android/src/main/",
29
27
  "android/build.gradle",
@@ -40,6 +38,7 @@
40
38
  "docs/CHANGELOG.md",
41
39
  "docs/MIGRATION.md",
42
40
  "docs/server-requirements.md",
41
+ "docs/protocol/CLIENT-PROTOCOL.md",
43
42
  "docs/KNOWN_LIMITATIONS.md",
44
43
  "cli/",
45
44
  "AI-INTEGRATION-GUIDE.md",
@@ -82,12 +81,15 @@
82
81
  "build:prod": "rimraf ./dist && tsc && NODE_ENV=production rollup -c rollup.config.js",
83
82
  "clean": "rimraf ./dist",
84
83
  "tsc": "tsc",
85
- "test": "vitest run tests",
84
+ "test": "vitest run tests && yarn check:android-core",
86
85
  "watch": "tsc --watch",
87
86
  "lint": "eslint . --max-warnings 0",
88
87
  "prettier": "prettier --write .",
89
88
  "prepublishOnly": "yarn build:prod",
90
- "swiftlint": "cd ios && swiftlint lint --fix --format --path Plugin --verbose"
89
+ "swiftlint": "cd ios && swiftlint lint --fix --format --path Plugin --verbose",
90
+ "sync:android-core": "node -e \"const fs=require('fs');const src='sdk/android/native-update-android/src/main/kotlin/com/aoneahsan/nativeupdate/android';for(const t of ['sdk/flutter/android/src/main/kotlin/com/aoneahsan/nativeupdate/android', 'sdk/react-native/android/src/main/java/com/aoneahsan/nativeupdate/android']){fs.rmSync(t,{recursive:true,force:true});fs.cpSync(src,t,{recursive:true});}fs.rmSync('sdk/react-native/android/build',{recursive:true,force:true});console.log('android core copied to '+['sdk/flutter/android/src/main/kotlin/com/aoneahsan/nativeupdate/android', 'sdk/react-native/android/src/main/java/com/aoneahsan/nativeupdate/android'].length+' packages')\"",
91
+ "check:android-core": "node -e \"const fs=require('fs'),path=require('path');const src='sdk/android/native-update-android/src/main/kotlin/com/aoneahsan/nativeupdate/android';const list=d=>fs.readdirSync(d,{recursive:true}).filter(f=>fs.statSync(path.join(d,f)).isFile()).sort();const want=list(src);let bad=[];for(const t of ['sdk/flutter/android/src/main/kotlin/com/aoneahsan/nativeupdate/android', 'sdk/react-native/android/src/main/java/com/aoneahsan/nativeupdate/android']){const have=fs.existsSync(t)?list(t):[];if(JSON.stringify(have)!==JSON.stringify(want))bad.push(t+': file list differs');for(const f of want){const b=path.join(t,f);if(!fs.existsSync(b)||!fs.readFileSync(b).equals(fs.readFileSync(path.join(src,f))))bad.push(b)}}if(bad.length){console.error('Android core copies drifted; run yarn sync:android-core:\\n'+bad.join('\\n'));process.exit(1)}console.log('android core copies match')\"",
92
+ "publish:capacitor-alias": "node -e \"const {execSync}=require('child_process'),fs=require('fs'),path=require('path');const dir=fs.mkdtempSync(path.resolve('../../../temp')+'/native-update-capacitor-');execSync('npm pack --ignore-scripts --pack-destination '+dir,{stdio:'inherit'});const tgz=fs.readdirSync(dir).find(f=>f.endsWith('.tgz'));execSync('tar -xzf '+tgz,{cwd:dir});const pkg=path.join(dir,'package'),pj=JSON.parse(fs.readFileSync(pkg+'/package.json','utf8'));pj.name='native-update-capacitor';pj.description='The Native Update Capacitor plugin under its framework name. Identical to native-update '+pj.version+': signed OTA updates, in-app update and in-app review.';delete pj.scripts;fs.writeFileSync(pkg+'/package.json',JSON.stringify(pj,null,2)+'\\n');fs.writeFileSync(pkg+'/README.md',fs.readFileSync('docs/capacitor-alias-note.md','utf8')+fs.readFileSync(pkg+'/README.md','utf8'));execSync('npm publish --ignore-scripts',{cwd:pkg,stdio:'inherit'});fs.rmSync(dir,{recursive:true,force:true});\""
91
93
  },
92
94
  "dependencies": {
93
95
  "archiver": "^8.0.0",