@shipvo/capacitor 0.0.0-stage → 0.0.2

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,86 @@
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
+ The core is TypeScript and makes every decision: it verifies the signature and the hash, stages, promotes and rolls back. The native layer only stores bytes and switches the web view.
6
+
7
+ | Platform | Native layer |
8
+ |---|---|
9
+ | Android | `android/`: stores the verified bundle zip in app-private files and the state in SharedPreferences; switches the web view with `Bridge.setServerBasePath` to the unpacked bundle |
10
+ | iOS | Next slice, tracked in its own issue. It will use the same JavaScript core and the same `boot` and `bootAndServe` calls as Android. |
11
+
12
+ ## Android
13
+
14
+ `android/` is a Capacitor plugin named `Shipvo`. It backs `KeyValueStore` with SharedPreferences and `BundleFiles` with the app-private files directory, and points the web view at the staged bundle. A web bundle is a zip of your web assets with an `index.html` at its root.
15
+
16
+ 1. Register it in `MainActivity` with `registerPlugin(ShipvoPlugin.class)` before `super.onCreate`.
17
+ 2. Include the module in `settings.gradle` and add `implementation project(':shipvo-capacitor')` (see `apps/capacitor-sample/android`).
18
+ 3. When the page loads, call `bootAndServe`. It runs `boot()` (rollback included) and tells native to serve the chosen file. Native checks the sha-256 the core verified once more before it unpacks, and refuses zip entries that leave the directory.
19
+
20
+ ```ts
21
+ import { registerPlugin } from "@capacitor/core";
22
+ import { ShipvoCapacitor, NativeStore, NativeFiles, bootAndServe, bootAndSwitch } from "@shipvo/capacitor";
23
+ import type { ShipvoNativePlugin } from "@shipvo/capacitor";
24
+
25
+ const native = registerPlugin<ShipvoNativePlugin>("Shipvo");
26
+ const shipvo: ShipvoCapacitor = new ShipvoCapacitor({
27
+ appId: "tide", shellMajor: 1, shellVersion: "1.2.0", platform: "android",
28
+ publicKey: "<base64 Ed25519 key>", baseUrl: "https://cp.example.com",
29
+ store: new NativeStore(native), files: new NativeFiles(native),
30
+ onReload: async () => { await bootAndSwitch(shipvo, native); },
31
+ });
32
+ await bootAndServe(shipvo, native);
33
+ await shipvo.markHealthy();
34
+ ```
35
+
36
+ Each launch starts on the embedded bundle, then `bootAndServe` switches to the pending or current release. The page of a served bundle runs the same code; it resumes the release `boot()` already chose and does not count another trial boot.
37
+
38
+ Tests: `pnpm --filter @shipvo/capacitor test` runs the stage, apply, crash and rollback sequence through the native bridge. The plugin's JVM tests run with `./gradlew :shipvo-capacitor:testDebugUnitTest` in `apps/capacitor-sample/android` (after `pnpm --filter capacitor-sample sync`).
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ npm install @shipvo/capacitor
44
+ ```
45
+
46
+ ## Example
47
+
48
+ ```ts
49
+ import { ShipvoCapacitor, MemoryStore, MemoryFiles } from "@shipvo/capacitor";
50
+
51
+ const shipvo = new ShipvoCapacitor({
52
+ appId: "tide", shellMajor: 1, shellVersion: "1.2.0", platform: "android",
53
+ publicKey: "<base64 Ed25519 key baked into the shell>",
54
+ baseUrl: "https://cp.example.com",
55
+ store: new MemoryStore(), files: new MemoryFiles(), // Android: NativeStore and NativeFiles
56
+ });
57
+
58
+ const { release, file } = await shipvo.boot(); // which bundle to serve
59
+ const r = await shipvo.checkForUpdate({ apply: false });
60
+ if (r.status === "staged") console.log("staged release", r.release);
61
+ await shipvo.markHealthy(); // promotes a pending release that is running
62
+ console.log((await shipvo.consumeEvents()).events);
63
+ ```
64
+
65
+ ## How a web bundle is described
66
+
67
+ 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.
68
+
69
+ ## API
70
+
71
+ `ShipvoCapacitor` implements `ShipvoCapacitorPlugin`, the same methods as `Native` in `packages/runtime/src/index.ts`, all async:
72
+
73
+ | Method | What it does |
74
+ |---|---|
75
+ | `getState()` | Cohort, band, running, current, pending, previous and blocked release |
76
+ | `checkForUpdate({ apply })` | Fetch the pointer, verify, download, verify, stage. `apply: true` then calls `onReload` |
77
+ | `markHealthy()` | Promotes the pending release if it is the one running |
78
+ | `consumeEvents()` | Returns and clears queued events: `applied`, `rolled_back`, `crash_loop_revert`, `verify_failed`, `download_failed`, `pointer_rejected:<why>` |
79
+ | `rollback()` | Drops pending, blocks current, goes back to previous |
80
+ | `reload()` | Calls `onReload` |
81
+ | `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 |
82
+ | `markStable()` | Native layer only. Clears the boot counter after the app stayed up |
83
+
84
+ 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.
85
+
86
+ 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,18 @@
1
+ apply plugin: 'com.android.library'
2
+
3
+ android {
4
+ namespace = "dev.shipvo.capacitor"
5
+ compileSdk = rootProject.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
6
+ defaultConfig {
7
+ minSdkVersion rootProject.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 24
8
+ }
9
+ compileOptions {
10
+ sourceCompatibility JavaVersion.VERSION_21
11
+ targetCompatibility JavaVersion.VERSION_21
12
+ }
13
+ }
14
+
15
+ dependencies {
16
+ implementation project(':capacitor-android')
17
+ testImplementation "junit:junit:4.13.2"
18
+ }
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,116 @@
1
+ package dev.shipvo.capacitor;
2
+
3
+ import java.io.ByteArrayOutputStream;
4
+ import java.io.File;
5
+ import java.io.FileInputStream;
6
+ import java.io.FileOutputStream;
7
+ import java.io.IOException;
8
+ import java.io.InputStream;
9
+ import java.io.OutputStream;
10
+ import java.security.MessageDigest;
11
+ import java.util.ArrayList;
12
+ import java.util.Arrays;
13
+ import java.util.List;
14
+ import java.util.zip.ZipEntry;
15
+ import java.util.zip.ZipInputStream;
16
+
17
+ /**
18
+ * Bundle files in a private directory. No Android classes, so it runs in a plain JVM test.
19
+ * It never decides anything: the TypeScript core verifies the signature and hash; this class
20
+ * only stores bytes and re-checks the hash it is given before it unpacks.
21
+ */
22
+ public final class BundleStore {
23
+ private final File dir;
24
+ private final File served;
25
+
26
+ public BundleStore(File root) {
27
+ this.dir = new File(root, "bundles");
28
+ this.served = new File(root, "served");
29
+ dir.mkdirs();
30
+ }
31
+
32
+ private File file(String name) throws IOException {
33
+ if (name == null || !name.matches("[A-Za-z0-9._-]{1,128}") || name.contains("..")) {
34
+ throw new IOException("bad file name");
35
+ }
36
+ return new File(dir, name);
37
+ }
38
+
39
+ public void write(String name, byte[] bytes) throws IOException {
40
+ File f = file(name);
41
+ File tmp = new File(dir, name + ".tmp");
42
+ try (FileOutputStream o = new FileOutputStream(tmp)) { o.write(bytes); o.getFD().sync(); }
43
+ try { java.nio.file.Files.move(tmp.toPath(), f.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING); }
44
+ catch (IOException e) { tmp.delete(); throw new IOException("could not write " + name); }
45
+ }
46
+
47
+ public byte[] read(String name) throws IOException {
48
+ try (InputStream in = new FileInputStream(file(name))) {
49
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
50
+ copy(in, out);
51
+ return out.toByteArray();
52
+ }
53
+ }
54
+
55
+ private static void copy(InputStream in, OutputStream out) throws IOException {
56
+ byte[] buf = new byte[8192];
57
+ for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n);
58
+ }
59
+
60
+ public void remove(String name) throws IOException { file(name).delete(); }
61
+
62
+ public List<String> list() {
63
+ String[] names = dir.list();
64
+ List<String> out = new ArrayList<>();
65
+ if (names != null) { Arrays.sort(names); for (String n : names) if (!n.endsWith(".tmp")) out.add(n); }
66
+ return out;
67
+ }
68
+
69
+ public void clear() {
70
+ String[] names = dir.list();
71
+ if (names != null) for (String n : names) new File(dir, n).delete();
72
+ deleteTree(served);
73
+ }
74
+
75
+ public static String sha256Hex(byte[] bytes) throws IOException {
76
+ try {
77
+ byte[] d = MessageDigest.getInstance("SHA-256").digest(bytes);
78
+ StringBuilder sb = new StringBuilder();
79
+ for (byte b : d) sb.append(String.format("%02x", b));
80
+ return sb.toString();
81
+ } catch (java.security.NoSuchAlgorithmException e) { throw new IOException(e); }
82
+ }
83
+
84
+ /**
85
+ * Unpacks a stored zip into a fresh directory, but only if its sha-256 equals the hash the
86
+ * core verified against the signed pointer. Entries that escape the directory are refused.
87
+ */
88
+ public File unpack(String name, String expectedSha256) throws IOException {
89
+ byte[] bytes = read(name);
90
+ if (expectedSha256 == null || !sha256Hex(bytes).equalsIgnoreCase(expectedSha256)) {
91
+ throw new IOException("bundle hash does not match");
92
+ }
93
+ deleteTree(served);
94
+ File target = new File(served, name);
95
+ target.mkdirs();
96
+ String root = target.getCanonicalPath() + File.separator;
97
+ try (ZipInputStream z = new ZipInputStream(new java.io.ByteArrayInputStream(bytes))) {
98
+ ZipEntry e;
99
+ while ((e = z.getNextEntry()) != null) {
100
+ File out = new File(target, e.getName());
101
+ if (!out.getCanonicalPath().startsWith(root)) { deleteTree(served); throw new IOException("bad entry in bundle"); }
102
+ if (e.isDirectory()) { out.mkdirs(); continue; }
103
+ out.getParentFile().mkdirs();
104
+ try (OutputStream o = new FileOutputStream(out)) { copy(z, o); }
105
+ }
106
+ }
107
+ if (!new File(target, "index.html").isFile()) { deleteTree(served); throw new IOException("bundle has no index.html"); }
108
+ return target;
109
+ }
110
+
111
+ private static void deleteTree(File f) {
112
+ File[] kids = f.listFiles();
113
+ if (kids != null) for (File k : kids) deleteTree(k);
114
+ f.delete();
115
+ }
116
+ }
@@ -0,0 +1,107 @@
1
+ package dev.shipvo.capacitor;
2
+
3
+ import android.content.Context;
4
+ import android.content.SharedPreferences;
5
+ import android.util.Base64;
6
+ import com.getcapacitor.JSArray;
7
+ import com.getcapacitor.JSObject;
8
+ import com.getcapacitor.Plugin;
9
+ import com.getcapacitor.PluginCall;
10
+ import com.getcapacitor.PluginMethod;
11
+ import com.getcapacitor.annotation.CapacitorPlugin;
12
+ import java.io.File;
13
+
14
+ /**
15
+ * The native half of @shipvo/capacitor. It backs the core's KeyValueStore (SharedPreferences)
16
+ * and BundleFiles (app-private files), and points the web view at an unpacked bundle.
17
+ * It makes no release decisions and verifies no signatures: the TypeScript core does both.
18
+ */
19
+ @CapacitorPlugin(name = "Shipvo")
20
+ public class ShipvoPlugin extends Plugin {
21
+ private static final String PREFS = "shipvo";
22
+ // An instance field: a Plugin lives as long as its Bridge, and the web view's base path belongs to the Bridge.
23
+ // A new Bridge (Activity recreated in the same process) starts on the embedded assets, so it must boot again.
24
+ private volatile String serving;
25
+ private volatile String servingPath;
26
+ private BundleStore store;
27
+
28
+ private BundleStore store() {
29
+ if (store == null) store = new BundleStore(getContext().getFilesDir());
30
+ return store;
31
+ }
32
+
33
+ private SharedPreferences prefs() { return getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); }
34
+
35
+ @PluginMethod
36
+ public void kvGet(PluginCall call) {
37
+ String key = call.getString("key");
38
+ JSObject r = new JSObject();
39
+ if (key != null && prefs().contains(key)) r.put("value", prefs().getString(key, null));
40
+ call.resolve(r);
41
+ }
42
+
43
+ @PluginMethod
44
+ public void kvSet(PluginCall call) {
45
+ String key = call.getString("key"), value = call.getString("value");
46
+ if (key == null || value == null) { call.reject("key and value are required"); return; }
47
+ // commit(), not apply(): the boot counter must be on disk before the page runs.
48
+ if (!prefs().edit().putString(key, value).commit()) { call.reject("could not save"); return; }
49
+ call.resolve();
50
+ }
51
+
52
+ @PluginMethod
53
+ public void fileWrite(PluginCall call) {
54
+ try {
55
+ store().write(call.getString("name"), Base64.decode(call.getString("data", ""), Base64.NO_WRAP));
56
+ call.resolve();
57
+ } catch (Exception e) { call.reject(e.getMessage()); }
58
+ }
59
+
60
+ @PluginMethod
61
+ public void fileRead(PluginCall call) {
62
+ try {
63
+ JSObject r = new JSObject();
64
+ r.put("data", Base64.encodeToString(store().read(call.getString("name")), Base64.NO_WRAP));
65
+ call.resolve(r);
66
+ } catch (Exception e) { call.reject(e.getMessage()); }
67
+ }
68
+
69
+ @PluginMethod
70
+ public void fileRemove(PluginCall call) {
71
+ try { store().remove(call.getString("name")); call.resolve(); } catch (Exception e) { call.reject(e.getMessage()); }
72
+ }
73
+
74
+ @PluginMethod
75
+ public void fileList(PluginCall call) {
76
+ JSObject r = new JSObject();
77
+ r.put("names", new JSArray(store().list()));
78
+ call.resolve(r);
79
+ }
80
+
81
+ @PluginMethod
82
+ public void fileClear(PluginCall call) {
83
+ store().clear(); serving = null; servingPath = null; call.resolve();
84
+ }
85
+
86
+ /** Serve a stored bundle. `sha256` is the hash the core verified; it is checked again before unpacking. */
87
+ @PluginMethod
88
+ public void serve(PluginCall call) {
89
+ try {
90
+ String name = call.getString("name");
91
+ File dir = store().unpack(name, call.getString("sha256"));
92
+ getBridge().setServerBasePath(dir.getAbsolutePath());
93
+ serving = name;
94
+ servingPath = dir.getAbsolutePath();
95
+ call.resolve();
96
+ } catch (Exception e) { call.reject(e.getMessage()); }
97
+ }
98
+
99
+ /** Which bundle this process is already serving, so the page it loads does not boot again. */
100
+ @PluginMethod
101
+ public void status(PluginCall call) {
102
+ JSObject r = new JSObject();
103
+ // Report serving only while this Bridge still points at the unpacked directory.
104
+ if (serving != null && servingPath != null && servingPath.equals(getBridge().getServerBasePath())) r.put("serving", serving);
105
+ call.resolve(r);
106
+ }
107
+ }
@@ -0,0 +1,78 @@
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
+ /** sha-256 of a stored release's archive, as checked against the signed pointer when it was staged. The native layer re-checks it before it serves the file. */
52
+ bundleHash(release: number): Promise<string | undefined>;
53
+ /**
54
+ * The web view loaded a page of a release that `boot()` already chose in this process
55
+ * (the native layer switched bundles and the new page starts the core again). Sets the running
56
+ * release without counting another trial boot. Ignored unless it is the pending or current release.
57
+ */
58
+ resume(release: number): Promise<void>;
59
+ /** The app stayed up long enough (the native layer decides how long). Clears the boot counter. */
60
+ markStable(): Promise<void>;
61
+ getState(): Promise<RuntimeState>;
62
+ checkForUpdate(a: {
63
+ apply: boolean;
64
+ }): Promise<CheckResult>;
65
+ private doCheck;
66
+ private push;
67
+ private reject;
68
+ /** Rule 12: promote the pending release only if it is the one running. */
69
+ markHealthy(): Promise<HealthyResult>;
70
+ private doHealthy;
71
+ /** Rule 14: drop pending, block the current release, go back to the previous one. */
72
+ rollback(): Promise<void>;
73
+ private doRollback;
74
+ consumeEvents(): Promise<{
75
+ events: string[];
76
+ }>;
77
+ reload(): Promise<void>;
78
+ }
package/dist/engine.js ADDED
@@ -0,0 +1,259 @@
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
+ /** sha-256 of a stored release's archive, as checked against the signed pointer when it was staged. The native layer re-checks it before it serves the file. */
111
+ async bundleHash(release) { return (await this.load()).hashes[String(release)]; }
112
+ /**
113
+ * The web view loaded a page of a release that `boot()` already chose in this process
114
+ * (the native layer switched bundles and the new page starts the core again). Sets the running
115
+ * release without counting another trial boot. Ignored unless it is the pending or current release.
116
+ */
117
+ async resume(release) {
118
+ const s = await this.load();
119
+ if (release && (release === s.pending || release === s.current))
120
+ this.running = release;
121
+ }
122
+ /** The app stayed up long enough (the native layer decides how long). Clears the boot counter. */
123
+ async markStable() { const s = await this.load(); s.bootTimes = []; await this.save(); }
124
+ async getState() {
125
+ const s = await this.load();
126
+ return { cohort: s.cohort, band: bandForCohort(s.cohort), runningRelease: this.running, currentRelease: s.current,
127
+ pendingRelease: s.pending, previousRelease: s.previous, blockedRelease: s.blocked || undefined,
128
+ shellVersion: s.shellVersion, baseUrl: this.c.baseUrl, appId: this.c.appId, shellMajor: this.c.shellMajor };
129
+ }
130
+ checkForUpdate(a) { return this.locked(() => this.doCheck(a)); }
131
+ async doCheck({ apply }) {
132
+ const s = await this.load();
133
+ const f = this.c.fetch ?? fetch;
134
+ const band = bandForCohort(s.cohort);
135
+ const path = `/p/${encodeURIComponent(this.c.appId)}/${this.c.shellMajor}${this.c.platform === "ios" ? "/ios" : ""}/${band}`;
136
+ let env;
137
+ try {
138
+ const r = await f(this.c.baseUrl.replace(/\/$/, "") + path);
139
+ if (!r.ok)
140
+ return { status: "none" };
141
+ env = SignedEnvelope.parse(await r.json());
142
+ }
143
+ catch (e) {
144
+ return { status: "error", error: String(e?.message ?? e) };
145
+ }
146
+ // Verify the signature before reading anything in the body.
147
+ if (!(await verifyEd25519(env.body, env.signature, this.c.publicKey)))
148
+ return this.reject(s, "verify_failed", "bad pointer signature");
149
+ let p;
150
+ try {
151
+ p = ReleasePointerBody.parse(JSON.parse(env.body));
152
+ }
153
+ catch {
154
+ return this.reject(s, "pointer_rejected", "pointer is not valid");
155
+ }
156
+ // Rules 1, 2, 3: kind, platform, app, major, band.
157
+ if (p.kind !== "web")
158
+ return this.reject(s, "pointer_rejected", "not a web bundle");
159
+ if ((p.platform ?? "android") !== this.c.platform)
160
+ return this.reject(s, "pointer_rejected", "wrong platform");
161
+ if (p.app_id !== this.c.appId || p.shell_major !== this.c.shellMajor)
162
+ return this.reject(s, "pointer_rejected", "wrong app or major");
163
+ if (p.band !== band)
164
+ return this.reject(s, "pointer_rejected", "wrong band");
165
+ // Rule 4: newer than current, pending and blocked.
166
+ if (p.release <= Math.max(s.current, s.pending, s.blocked))
167
+ return { status: "none", release: p.release };
168
+ // Rule 5: minimum shell version.
169
+ if (semverLess(this.c.shellVersion, p.min_shell_version))
170
+ return { status: "none", release: p.release };
171
+ const t1 = this.now();
172
+ let bytes;
173
+ try {
174
+ const url = new URL(p.core.url, this.c.baseUrl.replace(/\/?$/, "/")).toString();
175
+ const r = await f(url);
176
+ if (!r.ok)
177
+ throw new Error(`HTTP ${r.status}`);
178
+ bytes = new Uint8Array(await r.arrayBuffer());
179
+ }
180
+ catch (e) {
181
+ this.push(s, "download_failed");
182
+ await this.save();
183
+ return { status: "error", release: p.release, error: String(e?.message ?? e) };
184
+ }
185
+ const t2 = this.now();
186
+ // Size and sha-256 against the signed pointer.
187
+ if (bytes.byteLength !== p.core.size || (await sha256Hex(bytes)) !== p.core.sha256) {
188
+ this.block(s, p.release);
189
+ return this.reject(s, "verify_failed", "bundle size or sha-256 does not match", p.release);
190
+ }
191
+ const t3 = this.now();
192
+ // Stage: write the file, then point `pending` at it. A replaced pending release is dropped.
193
+ const old = s.pending;
194
+ await this.c.files.write(bundleName(p.release), bytes);
195
+ s.hashes[String(p.release)] = p.core.sha256;
196
+ s.pending = p.release;
197
+ s.pendingBoots = 0;
198
+ if (old && old !== p.release)
199
+ await this.drop(old);
200
+ await this.save();
201
+ if (apply)
202
+ await this.reload();
203
+ return { status: "staged", release: p.release, bytes: bytes.byteLength, downloadMs: t2 - t1, verifyMs: t3 - t2, issuedAt: p.issued_at };
204
+ }
205
+ push(s, e) { if (!s.events.includes(e) || !e.startsWith("pointer_rejected"))
206
+ s.events.push(e); }
207
+ async reject(s, event, why, release) {
208
+ this.push(s, event === "pointer_rejected" ? `pointer_rejected:${why}` : event);
209
+ await this.save();
210
+ return { status: "error", release, error: why };
211
+ }
212
+ /** Rule 12: promote the pending release only if it is the one running. */
213
+ markHealthy() { return this.locked(() => this.doHealthy()); }
214
+ async doHealthy() {
215
+ const s = await this.load();
216
+ const now = this.now();
217
+ let promoted = false;
218
+ if (s.pending && s.pending === this.running) {
219
+ await this.drop(s.previous);
220
+ s.previous = s.current;
221
+ s.current = s.pending;
222
+ s.pending = 0;
223
+ s.pendingBoots = 0;
224
+ promoted = true;
225
+ s.events.push("applied");
226
+ await this.save();
227
+ }
228
+ const kind = this.firstLoad ? "cold" : "reload";
229
+ this.firstLoad = false;
230
+ return { release: this.running, coldStartMs: now - this.t0, sinceLoadMs: now - this.loadedAt, promoted, kind };
231
+ }
232
+ /** Rule 14: drop pending, block the current release, go back to the previous one. */
233
+ rollback() { return this.locked(() => this.doRollback()); }
234
+ async doRollback() {
235
+ const s = await this.load();
236
+ if (s.pending) {
237
+ await this.drop(s.pending);
238
+ s.pending = 0;
239
+ s.pendingBoots = 0;
240
+ }
241
+ if (s.current) {
242
+ this.block(s, s.current);
243
+ await this.drop(s.current);
244
+ }
245
+ s.current = s.previous;
246
+ s.previous = 0;
247
+ s.bootTimes = [];
248
+ s.events.push("rolled_back");
249
+ await this.save();
250
+ }
251
+ async consumeEvents() {
252
+ const s = await this.load();
253
+ const events = s.events;
254
+ s.events = [];
255
+ await this.save();
256
+ return { events };
257
+ }
258
+ async reload() { this.loadedAt = this.now(); await this.c.onReload?.(); }
259
+ }
@@ -0,0 +1,7 @@
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";
6
+ export { NativeStore, NativeFiles, bootAndServe, bootAndSwitch } from "./native.js";
7
+ export type { ShipvoNativePlugin } from "./native.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
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";
5
+ export { NativeStore, NativeFiles, bootAndServe, bootAndSwitch } from "./native.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,72 @@
1
+ import type { ShipvoCapacitor } from "./engine.js";
2
+ import type { BundleFiles, KeyValueStore } from "./types.js";
3
+ /** The methods the Android plugin (`android/`, plugin name `Shipvo`) exposes through the Capacitor bridge. Binary data travels as base64. */
4
+ export interface ShipvoNativePlugin {
5
+ kvGet(o: {
6
+ key: string;
7
+ }): Promise<{
8
+ value?: string;
9
+ }>;
10
+ kvSet(o: {
11
+ key: string;
12
+ value: string;
13
+ }): Promise<void>;
14
+ fileWrite(o: {
15
+ name: string;
16
+ data: string;
17
+ }): Promise<void>;
18
+ fileRead(o: {
19
+ name: string;
20
+ }): Promise<{
21
+ data: string;
22
+ }>;
23
+ fileRemove(o: {
24
+ name: string;
25
+ }): Promise<void>;
26
+ fileList(): Promise<{
27
+ names: string[];
28
+ }>;
29
+ fileClear(): Promise<void>;
30
+ /** Unpack the stored bundle and point the web view at it. Native re-checks `sha256` first. */
31
+ serve(o: {
32
+ name: string;
33
+ sha256: string;
34
+ }): Promise<void>;
35
+ /** The bundle this process already serves, if any. */
36
+ status(): Promise<{
37
+ serving?: string;
38
+ }>;
39
+ }
40
+ /** `KeyValueStore` backed by the native plugin (SharedPreferences on Android). */
41
+ export declare class NativeStore implements KeyValueStore {
42
+ private n;
43
+ constructor(n: ShipvoNativePlugin);
44
+ get(key: string): Promise<string | undefined>;
45
+ set(key: string, value: string): Promise<void>;
46
+ }
47
+ /** `BundleFiles` backed by the native plugin (the app-private files directory on Android). */
48
+ export declare class NativeFiles implements BundleFiles {
49
+ private n;
50
+ constructor(n: ShipvoNativePlugin);
51
+ write(name: string, bytes: Uint8Array): Promise<void>;
52
+ read(name: string): Promise<Uint8Array<ArrayBuffer>>;
53
+ remove(name: string): Promise<void>;
54
+ list(): Promise<string[]>;
55
+ clear(): Promise<void>;
56
+ }
57
+ /**
58
+ * Run this first when the page loads. It asks the core which release to serve (`boot()`, which also
59
+ * decides rollback) and tells the native layer to serve that file. Native never picks a bundle on its own.
60
+ * Returns `served: true` when the web view is on a staged bundle.
61
+ */
62
+ export declare function bootAndServe(shipvo: ShipvoCapacitor, native: ShipvoNativePlugin): Promise<{
63
+ release: number;
64
+ served: boolean;
65
+ error?: string;
66
+ }>;
67
+ /** Run `boot()` and serve its choice now. Use it as `onReload` so `checkForUpdate({ apply: true })` switches the web view. */
68
+ export declare function bootAndSwitch(shipvo: ShipvoCapacitor, native: ShipvoNativePlugin): Promise<{
69
+ release: number;
70
+ served: boolean;
71
+ error?: string;
72
+ }>;
package/dist/native.js ADDED
@@ -0,0 +1,55 @@
1
+ const toB64 = (u) => { let s = ""; for (let i = 0; i < u.length; i += 0x8000)
2
+ s += String.fromCharCode(...u.subarray(i, i + 0x8000)); return btoa(s); };
3
+ const fromB64 = (b) => Uint8Array.from(atob(b), (c) => c.charCodeAt(0));
4
+ /** `KeyValueStore` backed by the native plugin (SharedPreferences on Android). */
5
+ export class NativeStore {
6
+ n;
7
+ constructor(n) {
8
+ this.n = n;
9
+ }
10
+ async get(key) { return (await this.n.kvGet({ key })).value; }
11
+ async set(key, value) { await this.n.kvSet({ key, value }); }
12
+ }
13
+ /** `BundleFiles` backed by the native plugin (the app-private files directory on Android). */
14
+ export class NativeFiles {
15
+ n;
16
+ constructor(n) {
17
+ this.n = n;
18
+ }
19
+ async write(name, bytes) { await this.n.fileWrite({ name, data: toB64(bytes) }); }
20
+ async read(name) { return fromB64((await this.n.fileRead({ name })).data); }
21
+ async remove(name) { await this.n.fileRemove({ name }); }
22
+ async list() { return (await this.n.fileList()).names; }
23
+ async clear() { await this.n.fileClear(); }
24
+ }
25
+ /**
26
+ * Run this first when the page loads. It asks the core which release to serve (`boot()`, which also
27
+ * decides rollback) and tells the native layer to serve that file. Native never picks a bundle on its own.
28
+ * Returns `served: true` when the web view is on a staged bundle.
29
+ */
30
+ export async function bootAndServe(shipvo, native) {
31
+ const { serving } = await native.status();
32
+ if (serving) {
33
+ // This page was loaded by an earlier `serve` in this process: `boot()` already ran.
34
+ const release = Number(/^release-(\d+)\.bundle$/.exec(serving)?.[1] ?? 0);
35
+ await shipvo.resume(release);
36
+ return { release, served: true };
37
+ }
38
+ return bootAndSwitch(shipvo, native);
39
+ }
40
+ /** Run `boot()` and serve its choice now. Use it as `onReload` so `checkForUpdate({ apply: true })` switches the web view. */
41
+ export async function bootAndSwitch(shipvo, native) {
42
+ const { release, file } = await shipvo.boot();
43
+ if (!file)
44
+ return { release: 0, served: false };
45
+ const sha256 = await shipvo.bundleHash(release);
46
+ if (!sha256)
47
+ return { release, served: false, error: "no verified hash for the stored bundle" };
48
+ try {
49
+ await native.serve({ name: file, sha256 });
50
+ }
51
+ catch (e) {
52
+ return { release, served: false, error: String(e?.message ?? e) };
53
+ }
54
+ return { release, served: true };
55
+ }
@@ -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,49 @@
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.2",
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.6"
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
+ "android/build.gradle",
35
+ "android/src/main",
36
+ "README.md"
37
+ ],
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "provenance": true
41
+ },
42
+ "engines": {
43
+ "node": ">=20"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.json",
47
+ "test": "vitest run"
48
+ }
6
49
  }