native-update-capacitor 0.0.0-stage → 4.3.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.
Files changed (139) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/init.js +146 -0
  30. package/cli/commands/keys-generate.js +58 -0
  31. package/cli/commands/monitor.js +89 -0
  32. package/cli/commands/remote-shared.js +262 -0
  33. package/cli/commands/remote.js +622 -0
  34. package/cli/commands/server-start.js +96 -0
  35. package/cli/index.js +605 -0
  36. package/cli/package.json +21 -0
  37. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  38. package/dist/esm/app-review/app-review-manager.js +194 -0
  39. package/dist/esm/app-review/index.d.ts +5 -0
  40. package/dist/esm/app-review/index.js +5 -0
  41. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  42. package/dist/esm/app-review/platform-review-handler.js +137 -0
  43. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  44. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  45. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  46. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  47. package/dist/esm/app-review/types.d.ts +41 -0
  48. package/dist/esm/app-review/types.js +1 -0
  49. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  50. package/dist/esm/app-update/app-update-checker.js +227 -0
  51. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  52. package/dist/esm/app-update/app-update-installer.js +134 -0
  53. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  54. package/dist/esm/app-update/app-update-manager.js +198 -0
  55. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  56. package/dist/esm/app-update/app-update-notifier.js +99 -0
  57. package/dist/esm/app-update/index.d.ts +6 -0
  58. package/dist/esm/app-update/index.js +6 -0
  59. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  60. package/dist/esm/app-update/platform-app-update.js +138 -0
  61. package/dist/esm/app-update/types.d.ts +58 -0
  62. package/dist/esm/app-update/types.js +11 -0
  63. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  64. package/dist/esm/background-update/background-scheduler.js +332 -0
  65. package/dist/esm/background-update/index.d.ts +3 -0
  66. package/dist/esm/background-update/index.js +2 -0
  67. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  68. package/dist/esm/background-update/notification-manager.js +88 -0
  69. package/dist/esm/config/support.d.ts +9 -0
  70. package/dist/esm/config/support.js +9 -0
  71. package/dist/esm/core/analytics.d.ts +83 -0
  72. package/dist/esm/core/analytics.js +151 -0
  73. package/dist/esm/core/cache-manager.d.ts +72 -0
  74. package/dist/esm/core/cache-manager.js +274 -0
  75. package/dist/esm/core/config.d.ts +69 -0
  76. package/dist/esm/core/config.js +107 -0
  77. package/dist/esm/core/errors.d.ts +56 -0
  78. package/dist/esm/core/errors.js +85 -0
  79. package/dist/esm/core/event-emitter.d.ts +30 -0
  80. package/dist/esm/core/event-emitter.js +80 -0
  81. package/dist/esm/core/logger.d.ts +21 -0
  82. package/dist/esm/core/logger.js +108 -0
  83. package/dist/esm/core/performance.d.ts +53 -0
  84. package/dist/esm/core/performance.js +153 -0
  85. package/dist/esm/core/plugin-manager.d.ts +88 -0
  86. package/dist/esm/core/plugin-manager.js +224 -0
  87. package/dist/esm/core/security.d.ts +123 -0
  88. package/dist/esm/core/security.js +361 -0
  89. package/dist/esm/core/update-check.d.ts +121 -0
  90. package/dist/esm/core/update-check.js +127 -0
  91. package/dist/esm/definitions.d.ts +872 -0
  92. package/dist/esm/definitions.js +104 -0
  93. package/dist/esm/index.d.ts +14 -0
  94. package/dist/esm/index.js +18 -0
  95. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  96. package/dist/esm/live-update/bundle-manager.js +344 -0
  97. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  98. package/dist/esm/live-update/certificate-pinning.js +77 -0
  99. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  100. package/dist/esm/live-update/delta-processor.js +257 -0
  101. package/dist/esm/live-update/download-manager.d.ts +106 -0
  102. package/dist/esm/live-update/download-manager.js +412 -0
  103. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  104. package/dist/esm/live-update/rollout-checker.js +304 -0
  105. package/dist/esm/live-update/update-manager.d.ts +63 -0
  106. package/dist/esm/live-update/update-manager.js +321 -0
  107. package/dist/esm/live-update/version-manager.d.ts +93 -0
  108. package/dist/esm/live-update/version-manager.js +390 -0
  109. package/dist/esm/plugin.d.ts +3 -0
  110. package/dist/esm/plugin.js +848 -0
  111. package/dist/esm/security/crypto.d.ts +88 -0
  112. package/dist/esm/security/crypto.js +228 -0
  113. package/dist/esm/security/validator.d.ts +60 -0
  114. package/dist/esm/security/validator.js +142 -0
  115. package/dist/esm/types/app-identity.d.ts +36 -0
  116. package/dist/esm/types/app-identity.js +1 -0
  117. package/dist/esm/types/rollout.d.ts +91 -0
  118. package/dist/esm/types/rollout.js +25 -0
  119. package/dist/esm/web.d.ts +130 -0
  120. package/dist/esm/web.js +981 -0
  121. package/dist/plugin.cjs +1 -0
  122. package/dist/plugin.esm.js +1 -0
  123. package/dist/plugin.js +2 -0
  124. package/docs/CHANGELOG.md +993 -0
  125. package/docs/KNOWN_LIMITATIONS.md +235 -0
  126. package/docs/MIGRATION.md +391 -0
  127. package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
  128. package/docs/server-requirements.md +211 -0
  129. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  130. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  131. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  133. package/ios/Plugin/Info.plist +43 -0
  134. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  135. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  136. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  137. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  138. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  139. package/package.json +135 -4
@@ -0,0 +1,178 @@
1
+ # Native Update client protocol
2
+
3
+ **Version:** 1 (server marker `2026.11.19.1`, plugin 4.3.0) · **Last updated:** 2026-11-19
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-Android-Package` | Android | applicationId, for per-key client restrictions |
29
+ | `X-Android-Cert-Sha256` / `-Sha1` | Android, when readable | Signing certificate digest, lowercase hex |
30
+ | `X-Ios-Bundle-Id` | iOS | Bundle identifier |
31
+
32
+ A key restricted to other identities answers 403 `API_KEY_RESTRICTED`. The identity headers are reported by the
33
+ client, not cryptographically attested.
34
+
35
+ ### Payload types
36
+
37
+ A build is one ZIP with one `payloadType`. The server offers a build only to an SDK that can run it:
38
+
39
+ | `X-Client-Sdk` | Accepted payload | What the SDK does with it |
40
+ |---|---|---|
41
+ | `capacitor`, `react-native`, absent | `web_bundle` | Serves it as the app's web / JS bundle |
42
+ | `android`, `flutter`, `ios` | `assets` | Exposes the unpacked files to the app (images, JSON config). Never loads code from it. |
43
+
44
+ A client that sends no `X-Client-Sdk` is a Capacitor plugin older than 4.3.0. When the newest build has a
45
+ payload the client cannot use, the check answers `available:false` with `code:"PAYLOAD_NOT_SUPPORTED"`.
46
+
47
+ Native Android and Flutter apps never receive executable code by OTA. That is the store-policy line, and the
48
+ server enforces it.
49
+
50
+ ### Response (always HTTP 200 once the key is valid)
51
+
52
+ No update:
53
+
54
+ ```json
55
+ { "available": false, "message": "Already on latest version" }
56
+ ```
57
+
58
+ Other `available:false` shapes carry extra fields:
59
+ - `minNativeVersion`: the binary is too old for the newest build;
60
+ - `held: true, code: "BILLING_HOLD", version`: an update exists but delivery is paused;
61
+ - `code: "PAYLOAD_NOT_SUPPORTED"`.
62
+
63
+ Update available:
64
+
65
+ ```json
66
+ {
67
+ "available": true,
68
+ "version": "1.4.0",
69
+ "bundleId": "9b1c…uuid",
70
+ "downloadUrl": "https://…/api/v1/bundles/123/download?signature=…",
71
+ "checksum": "64 lowercase hex chars (SHA-256 of the ZIP)",
72
+ "signature": "base64 | null",
73
+ "signatureAlgorithm": "RSA-SHA256 | null",
74
+ "payloadType": "web_bundle | assets",
75
+ "size": 482113,
76
+ "mandatory": false,
77
+ "releaseNotes": "text | null",
78
+ "minNativeVersion": "1.16.0 | null",
79
+ "expiresAt": "ISO-8601, when downloadUrl stops working",
80
+ "delta": null
81
+ }
82
+ ```
83
+
84
+ The server never offers a version equal to or older than `X-Current-Version`. A client still compares the
85
+ two itself (semver: numeric major.minor.patch) and refuses a downgrade.
86
+
87
+ A network error, a timeout or a non-2xx answer is an **error**, never "no update". The SDK reports it to the
88
+ app (`NETWORK_ERROR`) and keeps running the current payload.
89
+
90
+ ## 2. Download and verification
91
+
92
+ 1. GET `downloadUrl` before `expiresAt`. Write it to a temporary file and stop past the configured size limit
93
+ (`maxBundleSize`, default 100 MB).
94
+ 2. **Checksum:** SHA-256 of the downloaded bytes, lowercase hex, must equal `checksum`. On a mismatch, delete
95
+ the file (`CHECKSUM_ERROR`).
96
+ 3. **Signature:** when `requireSignature` is on (the production default), `signature` must be present and
97
+ `signatureAlgorithm` must be `RSA-SHA256`. Verify `SHA256withRSA` (PKCS#1 v1.5) over the **exact ZIP bytes**
98
+ with the app's public key (X.509 SubjectPublicKeyInfo, PEM or bare base64). Any failure deletes the file,
99
+ stores nothing and keeps the current payload (`SIGNATURE_ERROR`). Unsigned payloads are allowed only in
100
+ debug builds, with both `requireSignature:false` and `allowUnsignedDevelopmentUpdates:true`.
101
+ 4. **Unpack** into a new directory named after `bundleId`. Every entry's canonical path must stay inside that
102
+ directory (Zip-Slip refusal), and the unpacked size is bounded (`maxUncompressedBundleSize`).
103
+
104
+ ### Delta (`NUDELTA/1`)
105
+
106
+ When the device runs a version the server still holds, `delta` carries:
107
+ `{ format:"NUDELTA/1", fromVersion, patchUrl, patchSize, patchChecksum, targetChecksum }`.
108
+
109
+ The patch is JSON: `{ format, baseChecksum, targetChecksum, targetSize, operations[] }`. Each operation is
110
+ `{op:"copy", offset, length}` (bytes from the current ZIP) or `{op:"literal", data:"base64"}`.
111
+
112
+ A client:
113
+ - checks `patchChecksum`, then `baseChecksum` against its current ZIP;
114
+ - applies at most 100,000 bounded operations and refuses any out-of-range copy or oversize output;
115
+ - runs steps 2 and 3 on the rebuilt ZIP exactly as for a full download.
116
+
117
+ Any delta failure falls back to the full `downloadUrl`. Delta support is optional for an SDK; the full
118
+ download is always valid.
119
+
120
+ ## 3. Activation, confirmation and rollback
121
+
122
+ State kept per install (Android uses SharedPreferences, iOS UserDefaults):
123
+
124
+ | Key | Meaning |
125
+ |---|---|
126
+ | active | the bundle now in use |
127
+ | previous | the rollback target |
128
+ | pending + attempts | an activated bundle not yet confirmed, and how many cold starts it has had |
129
+ | binary identity | `versionCode:versionName` of the binary that activated `active` |
130
+
131
+ - **Activate:** previous ← active, active ← new, pending ← new, attempts ← 0, and record the binary identity.
132
+ When the payload type needs a restart (web bundles), switch on the next start or background.
133
+ - **Confirm:** the app calls `notifyAppReady()` once it has started cleanly on the payload. That clears
134
+ pending.
135
+ - **Rollback:** on each cold start with pending set, attempts += 1. At **2** unconfirmed starts, go back to
136
+ previous (or to the binary's own payload) and stop offering that bundle. A checksum or signature mismatch
137
+ of the active payload on start rolls back at once.
138
+ - **New binary:** when the recorded binary identity differs from the running binary (a store update), the
139
+ stored OTA payload is retired and the binary's own payload is used. The server then decides afresh.
140
+ - **Pruning:** after a confirmed start, delete every stored bundle except active, previous, pending and the
141
+ newest staged download that is newer than active.
142
+
143
+ ## 4. Configuration
144
+
145
+ Configuration is applied once per process. Calling it again with identical values resolves. Different values
146
+ are refused until `reset()`. Optional fields are read null-safely: a missing optional field never fails
147
+ configuration (ISSUE-14).
148
+
149
+ ## 5. Release gate (layer 2)
150
+
151
+ The update check answers "is there a payload". The release gate answers "must this binary update first". It
152
+ reads the app's release record on start and resume, and on a push, never on a timer:
153
+ - an **urgent** release with a newer native version blocks the app now, showing its reason and one Update
154
+ action;
155
+ - a **normal** one says so, then blocks from the next start;
156
+ - offline, it fails open.
157
+
158
+ On Play builds the Update action uses Play in-app update (IMMEDIATE). Play-excluded apps open their APK
159
+ download instead.
160
+
161
+ ## 6. Error codes an SDK reports
162
+
163
+ Codes in use by the Capacitor plugin today, which the new SDKs reuse with the same meaning:
164
+
165
+ | Code | When |
166
+ |---|---|
167
+ | `NETWORK_ERROR` / `UPDATE_CHECK_FAILED` | the check or download could not reach the server or got a non-2xx |
168
+ | `DOWNLOAD_ERROR` | the download stopped or exceeded the size limit |
169
+ | `CHECKSUM_ERROR` | SHA-256 mismatch |
170
+ | `SIGNATURE_ERROR` | signature missing, unsupported algorithm or invalid |
171
+ | `EXTRACTION_ERROR` | unpack failed, Zip-Slip or the unpacked size limit |
172
+ | `INSECURE_URL` | a non-HTTPS server or download URL |
173
+ | `VALIDATION_ERROR` | bad input from the app |
174
+ | `PAYLOAD_NOT_SUPPORTED` | server-side: the newest build is not a payload this SDK runs |
175
+ | `BILLING_HOLD` | server-side, informational: delivery paused |
176
+
177
+ A repeated configuration with different values is refused with the message "Configuration is locked after
178
+ initialization; call reset() first". Errors never include filesystem paths, keys or signatures.
@@ -0,0 +1,211 @@
1
+ # Backend Server Requirements
2
+
3
+ This document outlines the server infrastructure you need to build to use this plugin.
4
+
5
+ The hosted service already implements this contract, and the repository includes its Laravel 13 +
6
+ Nova 5 reference backend. Use this document only when implementing or auditing another backend.
7
+
8
+ ## Required API Endpoints
9
+
10
+ ### 1. Version Check Endpoint
11
+ ```
12
+ GET /api/v1/updates/check?channel={channel}
13
+ ```
14
+
15
+ This is the single endpoint every OTA update check hits. The plugin
16
+ implements it in exactly one place — `src/core/update-check.ts` — used by
17
+ `checkForUpdate()`, `VersionManager`, and the background scheduler alike.
18
+
19
+ **Query Parameters:**
20
+ - `channel`: production | staging | development (defaults to `production`)
21
+
22
+ **Headers (sent by the plugin — a custom backend MUST read these):**
23
+ - `X-API-Key`: app API key (**required** — return 401 if missing/invalid)
24
+ - `X-Device-ID`: stable per-device hash (**required** — return 400 if missing)
25
+ - `X-Current-Version`: currently-installed bundle version
26
+ - `X-Platform`: ios | android | web
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)
32
+
33
+ **Optional client-identity headers** (for API-key client restrictions; a custom
34
+ backend MAY read + enforce these, or ignore them):
35
+ - `X-Android-Package`: Android applicationId
36
+ - `X-Android-Cert-Sha256` / `X-Android-Cert-Sha1`: signing-cert fingerprints (hex)
37
+ - `X-Ios-Bundle-Id`: iOS bundle identifier
38
+ - `X-Ios-Team-Id`: iOS team id (the plugin does not currently send this)
39
+
40
+ A backend that gates keys on these should return **403** with a JSON body like
41
+ `{ "error": { "code": "API_KEY_RESTRICTED", "reason": "origin_not_allowed",
42
+ "message": "…" } }` when a client is not on the key's allowlist. The reference
43
+ Laravel backend enforces per-key allowlists of web origins (via the browser
44
+ `Origin` header), Android apps (package + cert), and iOS apps (bundle id).
45
+ Origins are matched **exactly**, scheme and port included — `https://localhost`,
46
+ `http://localhost:3843` and `https://localhost:3843` are three distinct entries —
47
+ and only `localhost`/`*.localhost`/loopback/private IPs may be allowlisted over
48
+ plain `http`; every public host is https-only. Note the native identity headers
49
+ are **client-attested**, not cryptographic attestation — treat them as
50
+ anti-casual-reuse, not a hard security boundary.
51
+
52
+ **Response (200) — no update:**
53
+ ```json
54
+ { "available": false, "message": "No updates available" }
55
+ ```
56
+
57
+ **Response (200) — update available:**
58
+ ```json
59
+ {
60
+ "available": true,
61
+ "version": "1.2.3",
62
+ "bundleId": "0f1e…uuid",
63
+ "downloadUrl": "https://cdn.example.com/bundles/1.2.3.zip",
64
+ "checksum": "sha256-hash",
65
+ "signature": "base64-encoded-signature",
66
+ "signatureAlgorithm": "RSA-SHA256",
67
+ "size": 1234567,
68
+ "mandatory": false,
69
+ "releaseNotes": "Bug fixes and improvements",
70
+ "minNativeVersion": "2.0.0",
71
+ "expiresAt": "2026-07-10T12:00:00+00:00"
72
+ }
73
+ ```
74
+
75
+ Sign the exact ZIP bytes with RSASSA-PKCS1-v1_5 + SHA-256. The checksum is 64 hexadecimal SHA-256
76
+ characters. Production clients reject missing signatures, unknown algorithms, checksum mismatches,
77
+ non-HTTPS URLs, oversized downloads, and paths outside their bundle sandbox.
78
+
79
+ **Optional delta object:** when a patch is materially smaller than the full target ZIP, include:
80
+
81
+ ```json
82
+ {
83
+ "delta": {
84
+ "format": "NUDELTA/1",
85
+ "fromVersion": "1.2.2",
86
+ "patchUrl": "https://cdn.example.com/deltas/1.2.2-to-1.2.3.json",
87
+ "patchSize": 45678,
88
+ "patchChecksum": "64-hex-sha256-of-the-patch",
89
+ "targetChecksum": "64-hex-sha256-of-the-target-zip"
90
+ }
91
+ }
92
+ ```
93
+
94
+ `NUDELTA/1` is a JSON document containing `format`, `fromVersion`, `toVersion`, `baseChecksum`,
95
+ `targetChecksum`, `targetSize`, and bounded `operations`. Each operation is either
96
+ `{"op":"copy","offset":0,"length":8192}` into the source ZIP or
97
+ `{"op":"literal","data":"<base64>"}`. A client validates every boundary and falls back to
98
+ `downloadUrl` on any mismatch. The canonical backend builds patches only from the last three active
99
+ builds in the same app/channel and advertises one only when it is smaller than 85% of the full ZIP.
100
+ Serve `patchUrl` over HTTPS from a host allowed by the client. The canonical backend proxies patches
101
+ through a short-lived, checksum-bound signed URL on the same API host as `downloadUrl`; its generator
102
+ uses a 25 MiB input cap and simply leaves `delta` absent for larger bundles.
103
+
104
+ > **Field names are the contract.** Use `available` (not `updateAvailable`)
105
+ > and `downloadUrl` (not `bundleUrl`); a custom backend that renames these
106
+ > will read back as "no update available". These names match the reference
107
+ > Laravel backend's `UpdateController@check`.
108
+
109
+ ### 1a. (Optional) Native app-version endpoint — custom extension point
110
+ ```
111
+ GET {serverUrl}/app-version?platform={ios|android|web}&current={ver}
112
+ ```
113
+ Only needed if you want SERVER-driven **native app-store** update prompts
114
+ (a newer Play Store / App Store *binary*, not an OTA bundle). This is a
115
+ plugin extension point, separate from the OTA `/v1/updates/check` flow, and
116
+ is a no-op unless you configure it. Return `{ "version": "2.1.0", "priority": 3 }`
117
+ (or `latestVersion`). See `docs/api/background-update-api.md`.
118
+
119
+ ### 2. Bundle Download URL
120
+
121
+ **Requirements:**
122
+ - Return an HTTPS URL in `downloadUrl`; it may be signed and need not use a fixed path
123
+ - Serve ZIP bytes with `application/zip` (or `application/octet-stream`) and an accurate content length
124
+ - Support byte ranges when possible so resumable clients can use `Range`
125
+ - Include security headers
126
+ - CDN integration recommended
127
+
128
+ ## Security Requirements
129
+
130
+ ### Bundle Signing
131
+ - Generate RSA key pairs (2048 bits minimum)
132
+ - Sign the exact bundle bytes with RSA-SHA256 (PKCS#1 v1.5)
133
+ - Include public key in app
134
+ - Verify signatures before applying updates
135
+
136
+ ### HTTPS Requirements
137
+ - All endpoints must use HTTPS
138
+ - Consider certificate pinning
139
+ - Implement rate limiting
140
+ - Add authentication tokens
141
+
142
+ ## Storage Infrastructure
143
+
144
+ ### Bundle Storage
145
+ - Store bundle files securely
146
+ - Implement versioning system
147
+ - Clean up old versions
148
+ - Monitor storage usage
149
+
150
+ ### CDN Configuration
151
+ - Geographic distribution
152
+ - Caching strategies
153
+ - Bandwidth optimization
154
+ - Fallback mechanisms
155
+
156
+ ## Example Server Structure
157
+
158
+ ```
159
+ update-server/
160
+ ├── src/
161
+ │ ├── api/
162
+ │ │ ├── updates.js
163
+ │ │ ├── bundles.js
164
+ │ │ └── analytics.js
165
+ │ ├── services/
166
+ │ │ ├── signing.js
167
+ │ │ ├── storage.js
168
+ │ │ └── version.js
169
+ │ ├── middleware/
170
+ │ │ ├── auth.js
171
+ │ │ ├── security.js
172
+ │ │ └── logging.js
173
+ │ └── config/
174
+ │ └── index.js
175
+ ├── bundles/
176
+ │ └── [stored bundle files]
177
+ ├── keys/
178
+ │ ├── private.pem
179
+ │ └── public.pem
180
+ └── package.json
181
+ ```
182
+
183
+ ## Minimum Implementation Checklist
184
+
185
+ - [ ] Version check API endpoint
186
+ - [ ] Bundle download endpoint
187
+ - [ ] Bundle signing implementation
188
+ - [ ] HTTPS configuration
189
+ - [ ] Basic authentication
190
+ - [ ] Error handling
191
+ - [ ] Logging system
192
+ - [ ] Health check endpoint
193
+
194
+ ## Recommended Features
195
+
196
+ - [ ] Analytics tracking
197
+ - [ ] A/B testing support
198
+ - [ ] Rollback capabilities
199
+ - [ ] Multi-tenant support
200
+ - [ ] Admin dashboard
201
+ - [ ] Monitoring/alerting
202
+ - [ ] Automated testing
203
+
204
+ ## Getting Help
205
+
206
+ Since no server is provided, you'll need to:
207
+ 1. Build your own implementation
208
+ 2. Use a third-party service
209
+ 3. Hire developers familiar with update servers
210
+
211
+ Consider looking at open-source examples or commercial solutions for inspiration.
@@ -0,0 +1,158 @@
1
+ import Foundation
2
+ import Capacitor
3
+ import StoreKit
4
+
5
+ class AppReviewPlugin {
6
+ private weak var plugin: CAPPlugin?
7
+ private var config: [String: Any]?
8
+ private let userDefaults = UserDefaults.standard
9
+
10
+ private struct Keys {
11
+ static let installDate = "native_update_review_install_date"
12
+ static let lastReviewRequest = "native_update_review_last_request"
13
+ static let launchCount = "native_update_review_launch_count"
14
+ static let reviewShownCount = "native_update_review_shown_count"
15
+ }
16
+
17
+ init(plugin: CAPPlugin) {
18
+ self.plugin = plugin
19
+
20
+ // Initialize install date if not set
21
+ if userDefaults.object(forKey: Keys.installDate) == nil {
22
+ userDefaults.set(Date(), forKey: Keys.installDate)
23
+ }
24
+
25
+ // Increment launch count
26
+ incrementLaunchCount()
27
+ }
28
+
29
+ func configure(_ config: [String: Any]) throws {
30
+ self.config = config
31
+ }
32
+
33
+ func requestReview(_ call: CAPPluginCall) {
34
+ // First check if we can request a review
35
+ let (allowed, reason) = checkCanRequestReview()
36
+
37
+ if !allowed {
38
+ call.resolve([
39
+ "shown": false, "displayed": false,
40
+ "error": reason ?? "Review conditions not met"
41
+ ])
42
+ return
43
+ }
44
+
45
+ // Request review using StoreKit
46
+ DispatchQueue.main.async { [weak self] in
47
+ if #available(iOS 14.0, *) {
48
+ if let windowScene = UIApplication.shared.connectedScenes
49
+ .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
50
+ SKStoreReviewController.requestReview(in: windowScene)
51
+ self?.updateReviewRequestTime()
52
+
53
+ call.resolve([
54
+ "shown": true, "displayed": true
55
+ ])
56
+ } else {
57
+ call.resolve([
58
+ "shown": false, "displayed": false,
59
+ "error": "No active window scene found"
60
+ ])
61
+ }
62
+ } else {
63
+ // Fallback for iOS 13 and earlier
64
+ SKStoreReviewController.requestReview()
65
+ self?.updateReviewRequestTime()
66
+
67
+ call.resolve([
68
+ "shown": true, "displayed": true
69
+ ])
70
+ }
71
+ }
72
+ }
73
+
74
+ func canRequestReview(_ call: CAPPluginCall) {
75
+ let (allowed, reason) = checkCanRequestReview()
76
+
77
+ var result: [String: Any] = ["allowed": allowed, "canRequest": allowed]
78
+ if !allowed, let reason = reason {
79
+ result["reason"] = reason
80
+ }
81
+
82
+ call.resolve(result)
83
+ }
84
+
85
+ // MARK: - Private Methods
86
+
87
+ private func checkCanRequestReview() -> (Bool, String?) {
88
+ // Check if debug mode is enabled
89
+ let debugMode = config?["debugMode"] as? Bool ?? false
90
+ if debugMode {
91
+ return (true, nil)
92
+ }
93
+
94
+ let now = Date()
95
+ let installDate = userDefaults.object(forKey: Keys.installDate) as? Date ?? now
96
+ let lastReviewRequest = userDefaults.object(forKey: Keys.lastReviewRequest) as? Date
97
+ let launchCount = userDefaults.integer(forKey: Keys.launchCount)
98
+ let shownCount = userDefaults.integer(forKey: Keys.reviewShownCount)
99
+
100
+ // Check minimum days since install
101
+ let minDaysSinceInstall = config?["minimumDaysSinceInstall"] as? Int ?? 7
102
+ let daysSinceInstall = Calendar.current.dateComponents([.day], from: installDate, to: now).day ?? 0
103
+ if daysSinceInstall < minDaysSinceInstall {
104
+ return (false, "Not enough days since install")
105
+ }
106
+
107
+ // Check minimum days since last prompt
108
+ if let lastRequest = lastReviewRequest {
109
+ let minDaysSinceLastPrompt = config?["minimumDaysSinceLastPrompt"] as? Int ?? 90
110
+ let daysSinceLastPrompt = Calendar.current.dateComponents([.day], from: lastRequest, to: now).day ?? 0
111
+ if daysSinceLastPrompt < minDaysSinceLastPrompt {
112
+ return (false, "Too soon since last review request")
113
+ }
114
+ }
115
+
116
+ // Check minimum launch count
117
+ let minLaunchCount = config?["minimumLaunchCount"] as? Int ?? 3
118
+ if launchCount < minLaunchCount {
119
+ return (false, "Not enough app launches")
120
+ }
121
+
122
+ // iOS limits to 3 review requests per year
123
+ if shownCount >= 3 {
124
+ // Check if it's been a year since the first request
125
+ if let firstRequestDate = userDefaults.object(forKey: "native_update_review_first_request") as? Date {
126
+ let daysSinceFirst = Calendar.current.dateComponents([.day], from: firstRequestDate, to: now).day ?? 0
127
+ if daysSinceFirst < 365 {
128
+ return (false, "Review quota exceeded")
129
+ } else {
130
+ // Reset count after a year
131
+ userDefaults.set(0, forKey: Keys.reviewShownCount)
132
+ userDefaults.removeObject(forKey: "native_update_review_first_request")
133
+ }
134
+ }
135
+ }
136
+
137
+ return (true, nil)
138
+ }
139
+
140
+ private func incrementLaunchCount() {
141
+ let currentCount = userDefaults.integer(forKey: Keys.launchCount)
142
+ userDefaults.set(currentCount + 1, forKey: Keys.launchCount)
143
+ }
144
+
145
+ private func updateReviewRequestTime() {
146
+ let now = Date()
147
+ userDefaults.set(now, forKey: Keys.lastReviewRequest)
148
+
149
+ // Track first request for yearly quota
150
+ if userDefaults.object(forKey: "native_update_review_first_request") == nil {
151
+ userDefaults.set(now, forKey: "native_update_review_first_request")
152
+ }
153
+
154
+ // Increment shown count
155
+ let shownCount = userDefaults.integer(forKey: Keys.reviewShownCount)
156
+ userDefaults.set(shownCount + 1, forKey: Keys.reviewShownCount)
157
+ }
158
+ }