@shipvo/capacitor 0.0.0-stage → 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @shipvo/capacitor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Signed over-the-air updates for the web bundle of a Capacitor app. It makes the same release decisions and keeps the same trust model as `@shipvo/runtime` (see `docs/adapters.md`).
4
+
5
+ This is the core, in TypeScript. It does not yet apply a bundle on a device. The native layer (next slice) backs two small interfaces, `KeyValueStore` and `BundleFiles`, and calls `boot()` when the web view loads.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @shipvo/capacitor
11
+ ```
12
+
13
+ ## Example
14
+
15
+ ```ts
16
+ import { ShipvoCapacitor, MemoryStore, MemoryFiles } from "@shipvo/capacitor";
17
+
18
+ const shipvo = new ShipvoCapacitor({
19
+ appId: "tide", shellMajor: 1, shellVersion: "1.2.0", platform: "android",
20
+ publicKey: "<base64 Ed25519 key baked into the shell>",
21
+ baseUrl: "https://cp.example.com",
22
+ store: new MemoryStore(), files: new MemoryFiles(), // the native layer provides real ones
23
+ });
24
+
25
+ const { release, file } = await shipvo.boot(); // which bundle to serve
26
+ const r = await shipvo.checkForUpdate({ apply: false });
27
+ if (r.status === "staged") console.log("staged release", r.release);
28
+ await shipvo.markHealthy(); // promotes a pending release that is running
29
+ console.log((await shipvo.consumeEvents()).events);
30
+ ```
31
+
32
+ ## How a web bundle is described
33
+
34
+ The signed release pointer has `kind: "web"` (new, optional field in `@shipvo/schema`). `core` is the one archive file: `url`, `size` and `sha256`. This package refuses a pointer without `kind: "web"`, so a React Native pointer cannot be replayed into a web shell.
35
+
36
+ ## API
37
+
38
+ `ShipvoCapacitor` implements `ShipvoCapacitorPlugin`, the same methods as `Native` in `packages/runtime/src/index.ts`, all async:
39
+
40
+ | Method | What it does |
41
+ |---|---|
42
+ | `getState()` | Cohort, band, running, current, pending, previous and blocked release |
43
+ | `checkForUpdate({ apply })` | Fetch the pointer, verify, download, verify, stage. `apply: true` then calls `onReload` |
44
+ | `markHealthy()` | Promotes the pending release if it is the one running |
45
+ | `consumeEvents()` | Returns and clears queued events: `applied`, `rolled_back`, `crash_loop_revert`, `verify_failed`, `download_failed`, `pointer_rejected:<why>` |
46
+ | `rollback()` | Drops pending, blocks current, goes back to previous |
47
+ | `reload()` | Calls `onReload` |
48
+ | `boot()` | Native layer only. Picks pending (3 trial boots), else current, else the embedded bundle (`release 0`). Applies the crash-loop window and the new-shell reset |
49
+ | `markStable()` | Native layer only. Clears the boot counter after the app stayed up |
50
+
51
+ Checks, in order: Ed25519 signature of the exact body bytes (WebCrypto), kind, platform, app and major, band, newer than current/pending/blocked, `min_shell_version`, then size and sha-256 of the bundle. A bad signature or hash is never staged. A hash mismatch also blocks that release.
52
+
53
+ Not shared yet: bsdiff patches (rule 9) and Hermes bytecode (rule 6, not relevant to plain web assets). Needs Node 20+ or a web view with WebCrypto Ed25519.
@@ -0,0 +1,70 @@
1
+ import type { BundleFiles, CheckResult, HealthyResult, KeyValueStore, RuntimeState, ShipvoCapacitorPlugin } from "./types.js";
2
+ export declare const MAX_BOOTS = 3;
3
+ export declare const WINDOW_MS = 60000;
4
+ export type ShipvoConfig = {
5
+ appId: string;
6
+ shellMajor: number;
7
+ /** Installed app version, x.y.z. */
8
+ shellVersion: string;
9
+ platform: "android" | "ios";
10
+ /** Ed25519 public key (base64), baked into the shell. Never read from the network. */
11
+ publicKey: string;
12
+ baseUrl: string;
13
+ store: KeyValueStore;
14
+ files: BundleFiles;
15
+ fetch?: typeof fetch;
16
+ now?: () => number;
17
+ random?: () => number;
18
+ /** Called by `reload`: the native layer points the web view at the chosen bundle. */
19
+ onReload?: () => void | Promise<void>;
20
+ };
21
+ export declare const bundleName: (release: number) => string;
22
+ /** Release decisions for a signed web bundle. Rules are numbered as in docs/adapters.md. */
23
+ export declare class ShipvoCapacitor implements ShipvoCapacitorPlugin {
24
+ private c;
25
+ private s?;
26
+ private running;
27
+ private loadedAt;
28
+ private firstLoad;
29
+ private readonly t0;
30
+ constructor(c: ShipvoConfig);
31
+ private now;
32
+ private loading?;
33
+ private lock;
34
+ /** Runs `fn` after every earlier locked call has finished, so check, markHealthy and rollback never overlap. */
35
+ private locked;
36
+ /** One load for all callers: concurrent first calls share the same state object. */
37
+ private load;
38
+ private doLoad;
39
+ private save;
40
+ private drop;
41
+ private block;
42
+ /**
43
+ * Called by the native layer each time the web view loads. Picks the release to serve (rules 10, 11):
44
+ * pending for up to 3 trial boots, else current, else the embedded bundle (release 0).
45
+ * Returns the release and the file name to serve, or `file: undefined` for the embedded bundle.
46
+ */
47
+ boot(): Promise<{
48
+ release: number;
49
+ file?: string;
50
+ }>;
51
+ /** The app stayed up long enough (the native layer decides how long). Clears the boot counter. */
52
+ markStable(): Promise<void>;
53
+ getState(): Promise<RuntimeState>;
54
+ checkForUpdate(a: {
55
+ apply: boolean;
56
+ }): Promise<CheckResult>;
57
+ private doCheck;
58
+ private push;
59
+ private reject;
60
+ /** Rule 12: promote the pending release only if it is the one running. */
61
+ markHealthy(): Promise<HealthyResult>;
62
+ private doHealthy;
63
+ /** Rule 14: drop pending, block the current release, go back to the previous one. */
64
+ rollback(): Promise<void>;
65
+ private doRollback;
66
+ consumeEvents(): Promise<{
67
+ events: string[];
68
+ }>;
69
+ reload(): Promise<void>;
70
+ }
package/dist/engine.js ADDED
@@ -0,0 +1,247 @@
1
+ import { ReleasePointerBody, SignedEnvelope, bandForCohort } from "@shipvo/schema";
2
+ import { semverLess, sha256Hex, verifyEd25519 } from "./verify.js";
3
+ export const MAX_BOOTS = 3;
4
+ export const WINDOW_MS = 60_000;
5
+ const KEY = "shipvo.state";
6
+ export const bundleName = (release) => `release-${release}.bundle`;
7
+ /** Release decisions for a signed web bundle. Rules are numbered as in docs/adapters.md. */
8
+ export class ShipvoCapacitor {
9
+ c;
10
+ s;
11
+ running = 0;
12
+ loadedAt;
13
+ firstLoad = true;
14
+ t0;
15
+ constructor(c) {
16
+ this.c = c;
17
+ this.t0 = this.loadedAt = this.now();
18
+ }
19
+ now() { return (this.c.now ?? Date.now)(); }
20
+ loading;
21
+ lock = Promise.resolve();
22
+ /** Runs `fn` after every earlier locked call has finished, so check, markHealthy and rollback never overlap. */
23
+ locked(fn) {
24
+ const run = this.lock.then(fn, fn);
25
+ this.lock = run.catch(() => undefined);
26
+ return run;
27
+ }
28
+ /** One load for all callers: concurrent first calls share the same state object. */
29
+ load() {
30
+ if (!this.loading) {
31
+ this.loading = this.doLoad().catch((e) => { this.loading = undefined; throw e; });
32
+ }
33
+ return this.loading;
34
+ }
35
+ async doLoad() {
36
+ let s;
37
+ let corrupt = false;
38
+ try {
39
+ const raw = await this.c.store.get(KEY);
40
+ if (raw)
41
+ s = JSON.parse(raw);
42
+ }
43
+ catch {
44
+ s = undefined;
45
+ corrupt = true;
46
+ }
47
+ if (corrupt)
48
+ await this.c.files.clear();
49
+ if (!s) {
50
+ const cohort = Math.min(999, Math.floor((this.c.random ?? Math.random)() * 1000));
51
+ s = { shellVersion: this.c.shellVersion, cohort, current: 0, pending: 0, previous: 0, blocked: 0, pendingBoots: 0, bootTimes: [], events: [], hashes: {} };
52
+ }
53
+ else if (s.shellVersion !== this.c.shellVersion) {
54
+ // Rule 13: a new shell deletes stored bundles and counters. The cohort stays.
55
+ await this.c.files.clear();
56
+ s = { ...s, shellVersion: this.c.shellVersion, current: 0, pending: 0, previous: 0, blocked: 0, pendingBoots: 0, bootTimes: [], hashes: {} };
57
+ }
58
+ this.s = s;
59
+ await this.save();
60
+ return s;
61
+ }
62
+ async save() { await this.c.store.set(KEY, JSON.stringify(this.s)); }
63
+ async drop(release) {
64
+ if (!release || !this.s)
65
+ return;
66
+ delete this.s.hashes[String(release)];
67
+ await this.c.files.remove(bundleName(release));
68
+ }
69
+ block(s, release) { s.blocked = Math.max(s.blocked, release); }
70
+ /**
71
+ * Called by the native layer each time the web view loads. Picks the release to serve (rules 10, 11):
72
+ * pending for up to 3 trial boots, else current, else the embedded bundle (release 0).
73
+ * Returns the release and the file name to serve, or `file: undefined` for the embedded bundle.
74
+ */
75
+ async boot() {
76
+ const s = await this.load();
77
+ const now = this.now();
78
+ if (s.pending) {
79
+ if (s.pendingBoots >= MAX_BOOTS) {
80
+ // Rule 10: three trial boots without markHealthy. Drop, block, report.
81
+ this.block(s, s.pending);
82
+ await this.drop(s.pending);
83
+ s.pending = 0;
84
+ s.pendingBoots = 0;
85
+ s.events.push("crash_loop_revert");
86
+ }
87
+ else {
88
+ s.pendingBoots++;
89
+ this.running = s.pending;
90
+ await this.save();
91
+ return { release: s.pending, file: bundleName(s.pending) };
92
+ }
93
+ }
94
+ if (s.current) {
95
+ // Rule 11: more than 3 unhealthy boots in 60 seconds reverts to the previous release.
96
+ s.bootTimes = [...s.bootTimes.filter((t) => now - t < WINDOW_MS), now];
97
+ if (s.bootTimes.length > MAX_BOOTS) {
98
+ this.block(s, s.current);
99
+ await this.drop(s.current);
100
+ s.current = s.previous;
101
+ s.previous = 0;
102
+ s.bootTimes = [];
103
+ s.events.push("crash_loop_revert");
104
+ }
105
+ }
106
+ this.running = s.current;
107
+ await this.save();
108
+ return { release: s.current, file: s.current ? bundleName(s.current) : undefined };
109
+ }
110
+ /** The app stayed up long enough (the native layer decides how long). Clears the boot counter. */
111
+ async markStable() { const s = await this.load(); s.bootTimes = []; await this.save(); }
112
+ async getState() {
113
+ const s = await this.load();
114
+ return { cohort: s.cohort, band: bandForCohort(s.cohort), runningRelease: this.running, currentRelease: s.current,
115
+ pendingRelease: s.pending, previousRelease: s.previous, blockedRelease: s.blocked || undefined,
116
+ shellVersion: s.shellVersion, baseUrl: this.c.baseUrl, appId: this.c.appId, shellMajor: this.c.shellMajor };
117
+ }
118
+ checkForUpdate(a) { return this.locked(() => this.doCheck(a)); }
119
+ async doCheck({ apply }) {
120
+ const s = await this.load();
121
+ const f = this.c.fetch ?? fetch;
122
+ const band = bandForCohort(s.cohort);
123
+ const path = `/p/${encodeURIComponent(this.c.appId)}/${this.c.shellMajor}${this.c.platform === "ios" ? "/ios" : ""}/${band}`;
124
+ let env;
125
+ try {
126
+ const r = await f(this.c.baseUrl.replace(/\/$/, "") + path);
127
+ if (!r.ok)
128
+ return { status: "none" };
129
+ env = SignedEnvelope.parse(await r.json());
130
+ }
131
+ catch (e) {
132
+ return { status: "error", error: String(e?.message ?? e) };
133
+ }
134
+ // Verify the signature before reading anything in the body.
135
+ if (!(await verifyEd25519(env.body, env.signature, this.c.publicKey)))
136
+ return this.reject(s, "verify_failed", "bad pointer signature");
137
+ let p;
138
+ try {
139
+ p = ReleasePointerBody.parse(JSON.parse(env.body));
140
+ }
141
+ catch {
142
+ return this.reject(s, "pointer_rejected", "pointer is not valid");
143
+ }
144
+ // Rules 1, 2, 3: kind, platform, app, major, band.
145
+ if (p.kind !== "web")
146
+ return this.reject(s, "pointer_rejected", "not a web bundle");
147
+ if ((p.platform ?? "android") !== this.c.platform)
148
+ return this.reject(s, "pointer_rejected", "wrong platform");
149
+ if (p.app_id !== this.c.appId || p.shell_major !== this.c.shellMajor)
150
+ return this.reject(s, "pointer_rejected", "wrong app or major");
151
+ if (p.band !== band)
152
+ return this.reject(s, "pointer_rejected", "wrong band");
153
+ // Rule 4: newer than current, pending and blocked.
154
+ if (p.release <= Math.max(s.current, s.pending, s.blocked))
155
+ return { status: "none", release: p.release };
156
+ // Rule 5: minimum shell version.
157
+ if (semverLess(this.c.shellVersion, p.min_shell_version))
158
+ return { status: "none", release: p.release };
159
+ const t1 = this.now();
160
+ let bytes;
161
+ try {
162
+ const url = new URL(p.core.url, this.c.baseUrl.replace(/\/?$/, "/")).toString();
163
+ const r = await f(url);
164
+ if (!r.ok)
165
+ throw new Error(`HTTP ${r.status}`);
166
+ bytes = new Uint8Array(await r.arrayBuffer());
167
+ }
168
+ catch (e) {
169
+ this.push(s, "download_failed");
170
+ await this.save();
171
+ return { status: "error", release: p.release, error: String(e?.message ?? e) };
172
+ }
173
+ const t2 = this.now();
174
+ // Size and sha-256 against the signed pointer.
175
+ if (bytes.byteLength !== p.core.size || (await sha256Hex(bytes)) !== p.core.sha256) {
176
+ this.block(s, p.release);
177
+ return this.reject(s, "verify_failed", "bundle size or sha-256 does not match", p.release);
178
+ }
179
+ const t3 = this.now();
180
+ // Stage: write the file, then point `pending` at it. A replaced pending release is dropped.
181
+ const old = s.pending;
182
+ await this.c.files.write(bundleName(p.release), bytes);
183
+ s.hashes[String(p.release)] = p.core.sha256;
184
+ s.pending = p.release;
185
+ s.pendingBoots = 0;
186
+ if (old && old !== p.release)
187
+ await this.drop(old);
188
+ await this.save();
189
+ if (apply)
190
+ await this.reload();
191
+ return { status: "staged", release: p.release, bytes: bytes.byteLength, downloadMs: t2 - t1, verifyMs: t3 - t2, issuedAt: p.issued_at };
192
+ }
193
+ push(s, e) { if (!s.events.includes(e) || !e.startsWith("pointer_rejected"))
194
+ s.events.push(e); }
195
+ async reject(s, event, why, release) {
196
+ this.push(s, event === "pointer_rejected" ? `pointer_rejected:${why}` : event);
197
+ await this.save();
198
+ return { status: "error", release, error: why };
199
+ }
200
+ /** Rule 12: promote the pending release only if it is the one running. */
201
+ markHealthy() { return this.locked(() => this.doHealthy()); }
202
+ async doHealthy() {
203
+ const s = await this.load();
204
+ const now = this.now();
205
+ let promoted = false;
206
+ if (s.pending && s.pending === this.running) {
207
+ await this.drop(s.previous);
208
+ s.previous = s.current;
209
+ s.current = s.pending;
210
+ s.pending = 0;
211
+ s.pendingBoots = 0;
212
+ promoted = true;
213
+ s.events.push("applied");
214
+ await this.save();
215
+ }
216
+ const kind = this.firstLoad ? "cold" : "reload";
217
+ this.firstLoad = false;
218
+ return { release: this.running, coldStartMs: now - this.t0, sinceLoadMs: now - this.loadedAt, promoted, kind };
219
+ }
220
+ /** Rule 14: drop pending, block the current release, go back to the previous one. */
221
+ rollback() { return this.locked(() => this.doRollback()); }
222
+ async doRollback() {
223
+ const s = await this.load();
224
+ if (s.pending) {
225
+ await this.drop(s.pending);
226
+ s.pending = 0;
227
+ s.pendingBoots = 0;
228
+ }
229
+ if (s.current) {
230
+ this.block(s, s.current);
231
+ await this.drop(s.current);
232
+ }
233
+ s.current = s.previous;
234
+ s.previous = 0;
235
+ s.bootTimes = [];
236
+ s.events.push("rolled_back");
237
+ await this.save();
238
+ }
239
+ async consumeEvents() {
240
+ const s = await this.load();
241
+ const events = s.events;
242
+ s.events = [];
243
+ await this.save();
244
+ return { events };
245
+ }
246
+ async reload() { this.loadedAt = this.now(); await this.c.onReload?.(); }
247
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./types.js";
2
+ export { ShipvoCapacitor, bundleName, MAX_BOOTS, WINDOW_MS } from "./engine.js";
3
+ export type { ShipvoConfig } from "./engine.js";
4
+ export { MemoryStore, MemoryFiles } from "./memory.js";
5
+ export { verifyEd25519, sha256Hex, semverLess } from "./verify.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./types.js";
2
+ export { ShipvoCapacitor, bundleName, MAX_BOOTS, WINDOW_MS } from "./engine.js";
3
+ export { MemoryStore, MemoryFiles } from "./memory.js";
4
+ export { verifyEd25519, sha256Hex, semverLess } from "./verify.js";
@@ -0,0 +1,12 @@
1
+ import type { BundleFiles, KeyValueStore } from "./types.js";
2
+ export declare class MemoryStore implements KeyValueStore {
3
+ readonly map: Map<string, string>;
4
+ get(k: string): Promise<string | undefined>;
5
+ set(k: string, v: string): Promise<void>;
6
+ }
7
+ export declare class MemoryFiles implements BundleFiles {
8
+ readonly files: Map<string, Uint8Array<ArrayBufferLike>>;
9
+ write(n: string, b: Uint8Array): Promise<void>;
10
+ remove(n: string): Promise<void>;
11
+ clear(): Promise<void>;
12
+ }
package/dist/memory.js ADDED
@@ -0,0 +1,11 @@
1
+ export class MemoryStore {
2
+ map = new Map();
3
+ async get(k) { return this.map.get(k); }
4
+ async set(k, v) { this.map.set(k, v); }
5
+ }
6
+ export class MemoryFiles {
7
+ files = new Map();
8
+ async write(n, b) { this.files.set(n, b); }
9
+ async remove(n) { this.files.delete(n); }
10
+ async clear() { this.files.clear(); }
11
+ }
@@ -0,0 +1,57 @@
1
+ export type Band = "b0" | "b1" | "b2";
2
+ /** Same shape as `RuntimeState` in `@shipvo/runtime`. */
3
+ export type RuntimeState = {
4
+ cohort: number;
5
+ band: Band;
6
+ runningRelease: number;
7
+ currentRelease: number;
8
+ pendingRelease: number;
9
+ previousRelease: number;
10
+ blockedRelease?: number;
11
+ shellVersion?: string;
12
+ baseUrl: string;
13
+ appId: string;
14
+ shellMajor: number;
15
+ };
16
+ export type CheckResult = {
17
+ status: "none" | "staged" | "error";
18
+ release?: number;
19
+ bytes?: number;
20
+ downloadMs?: number;
21
+ verifyMs?: number;
22
+ issuedAt?: string;
23
+ error?: string;
24
+ reason?: "hermes_bytecode_mismatch" | "native_module_missing" | "native_module_version";
25
+ };
26
+ export type HealthyResult = {
27
+ release: number;
28
+ coldStartMs: number;
29
+ sinceLoadMs: number;
30
+ promoted: boolean;
31
+ kind?: "cold" | "reload";
32
+ };
33
+ /** The plugin the Capacitor app calls. Same methods as `Native` in `packages/runtime/src/index.ts`; every call is async because Capacitor bridges are. */
34
+ export interface ShipvoCapacitorPlugin {
35
+ getState(): Promise<RuntimeState>;
36
+ checkForUpdate(options: {
37
+ apply: boolean;
38
+ }): Promise<CheckResult>;
39
+ markHealthy(): Promise<HealthyResult>;
40
+ consumeEvents(): Promise<{
41
+ events: string[];
42
+ }>;
43
+ rollback(): Promise<void>;
44
+ reload(): Promise<void>;
45
+ }
46
+ /** Small key-value store. The native layer backs it with SharedPreferences / UserDefaults. */
47
+ export interface KeyValueStore {
48
+ get(key: string): Promise<string | undefined>;
49
+ set(key: string, value: string): Promise<void>;
50
+ }
51
+ /** Bundle files. The native layer backs it with the app's private files directory. */
52
+ export interface BundleFiles {
53
+ write(name: string, bytes: Uint8Array): Promise<void>;
54
+ remove(name: string): Promise<void>;
55
+ /** Remove every file. Used when a new shell is installed. */
56
+ clear(): Promise<void>;
57
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ export declare function fromBase64(s: string): Uint8Array;
2
+ export declare function verifyEd25519(message: string, signatureB64: string, publicKeyB64: string): Promise<boolean>;
3
+ export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
4
+ /** a < b for x.y.z. Pre-release tags are ignored. */
5
+ export declare function semverLess(a: string, b: string): boolean;
package/dist/verify.js ADDED
@@ -0,0 +1,31 @@
1
+ // Trust checks with WebCrypto. Same rules as Verify.kt / Verify.swift: Ed25519 over the exact UTF-8 bytes of the
2
+ // envelope body, sha-256 and size of every downloaded file. Any error means "not valid".
3
+ export function fromBase64(s) {
4
+ const n = s.replace(/-/g, "+").replace(/_/g, "/");
5
+ const bin = atob(n + "=".repeat((4 - (n.length % 4)) % 4));
6
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
7
+ }
8
+ export async function verifyEd25519(message, signatureB64, publicKeyB64) {
9
+ try {
10
+ const key = await crypto.subtle.importKey("raw", fromBase64(publicKeyB64), { name: "Ed25519" }, false, ["verify"]);
11
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, fromBase64(signatureB64), new TextEncoder().encode(message));
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ export async function sha256Hex(bytes) {
18
+ const d = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
19
+ return Array.from(d, (b) => b.toString(16).padStart(2, "0")).join("");
20
+ }
21
+ /** a < b for x.y.z. Pre-release tags are ignored. */
22
+ export function semverLess(a, b) {
23
+ const pa = a.split("-")[0].split(".").map((x) => parseInt(x, 10) || 0);
24
+ const pb = b.split("-")[0].split(".").map((x) => parseInt(x, 10) || 0);
25
+ for (let i = 0; i < 3; i++) {
26
+ const x = pa[i] ?? 0, y = pb[i] ?? 0;
27
+ if (x !== y)
28
+ return x < y;
29
+ }
30
+ return false;
31
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@shipvo/capacitor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "description": "Signed over-the-air updates for Capacitor web bundles: the same release decisions and trust model as the Shipvo React Native runtime.",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "dependencies": {
10
+ "@shipvo/schema": "^0.0.5"
11
+ },
12
+ "devDependencies": {
13
+ "@types/node": "^22.8.0",
14
+ "typescript": "^5.6.3",
15
+ "vitest": "^2.1.4"
16
+ },
17
+ "keywords": [
18
+ "shipvo",
19
+ "capacitor",
20
+ "ota",
21
+ "over-the-air",
22
+ "ed25519",
23
+ "web",
24
+ "live-update"
25
+ ],
26
+ "homepage": "https://github.com/shipvo/shipvo#readme",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/shipvo/shipvo.git",
30
+ "directory": "packages/capacitor"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": true
39
+ },
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json",
45
+ "test": "vitest run"
46
+ }
6
47
  }