@bom0792/herdgate 0.0.0-stage → 0.9.6

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 (46) hide show
  1. package/README.md +167 -2
  2. package/app-mod/herdgate/main.js +395 -0
  3. package/app-mod/herdgate/mod.json +5 -0
  4. package/bin/herdgate.mjs +91 -0
  5. package/dist-readme.md +48 -0
  6. package/package.json +36 -3
  7. package/plugin/herdr-plugin.toml +36 -0
  8. package/plugin/server/common.mjs +79 -0
  9. package/plugin/server/e2e.d.mts +43 -0
  10. package/plugin/server/e2e.mjs +268 -0
  11. package/plugin/server/index.mjs +454 -0
  12. package/plugin/server/ssh.mjs +241 -0
  13. package/scripts/build-host-bundle.sh +12 -0
  14. package/scripts/deploy-vps.sh +74 -0
  15. package/scripts/patch-ssh2.mjs +32 -0
  16. package/src/agent/adapter.ts +23 -0
  17. package/src/agent/index.ts +183 -0
  18. package/src/cloud/gateway.ts +946 -0
  19. package/src/cloud/main.ts +88 -0
  20. package/src/cloud/pairing.ts +81 -0
  21. package/src/cloud/ssh-bridge.ts +212 -0
  22. package/src/cloud/sshd.ts +412 -0
  23. package/src/cloud/static.ts +142 -0
  24. package/src/cloud/stores.ts +180 -0
  25. package/src/cloud/util.ts +47 -0
  26. package/src/cloud/vapid.ts +105 -0
  27. package/src/dev/edge-sim.ts +99 -0
  28. package/src/dev/main.ts +33 -0
  29. package/src/host/herdr.ts +316 -0
  30. package/src/host/main.ts +105 -0
  31. package/src/host/ssh.ts +317 -0
  32. package/src/index.ts +5 -0
  33. package/src/protocol/agent.ts +84 -0
  34. package/src/protocol/device.ts +90 -0
  35. package/src/protocol/envelope.ts +58 -0
  36. package/src/protocol/index.ts +3 -0
  37. package/src/web/app.css +312 -0
  38. package/src/web/app.js +835 -0
  39. package/src/web/app.webmanifest +15 -0
  40. package/src/web/e2e.js +268 -0
  41. package/src/web/herdgate-host.zip +0 -0
  42. package/src/web/icons/icon-192.png +0 -0
  43. package/src/web/icons/icon-512.png +0 -0
  44. package/src/web/icons/icon.svg +6 -0
  45. package/src/web/index.html +99 -0
  46. package/src/web/sw.js +98 -0
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "herdgate",
3
+ "short_name": "herdgate",
4
+ "description": "Look at the machines paired to your herdgate cloud.",
5
+ "start_url": "/",
6
+ "scope": "/",
7
+ "display": "standalone",
8
+ "background_color": "#11131a",
9
+ "theme_color": "#11131a",
10
+ "icons": [
11
+ { "src": "/icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" },
12
+ { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
13
+ { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
14
+ ]
15
+ }
package/src/web/e2e.js ADDED
@@ -0,0 +1,268 @@
1
+ /**
2
+ * herdgate E2E payloads — Noise_XX over the opaque payload channel.
3
+ *
4
+ * The PWA copy of `plugin/server/e2e.mjs` (verbatim; a test asserts the two never
5
+ * drift). Everything
6
+ * runs on WebCrypto (`globalThis.crypto.subtle` — Node ≥ 20 exposes the same
7
+ * object globally), so the plugin and the browser execute identical logic.
8
+ *
9
+ * Scheme: Noise_XX with P-256 ECDH, SHA-256 and AES-256-GCM
10
+ * (Noise_XX_P256_AESGCM_SHA256). The device initiates after pairing; the host
11
+ * answers with its long-lived static key (TOFU — the device learns its
12
+ * fingerprint from the decrypted handshake and compares it on every later
13
+ * session). After handshake, payloads travel as `{op:"e2e", n:<u64>, c:<b64>}`;
14
+ * the cloud keeps routing them blind.
15
+ *
16
+ * The cloud never sees any of this: the handshake and all ciphertext travel
17
+ * inside `frame.payload`, which the gateway does not parse (DESIGN.md §3).
18
+ */
19
+
20
+ /** The Noise protocol name; its hash seeds the chaining state (spec §5.1). */
21
+ export const NOISE_NAME = "Noise_XX_P256_AESGCM_SHA256";
22
+ export const KEY_LEN = 32;
23
+ export const PUB_LEN = 65; // uncompressed P-256 point: 0x04 ‖ X ‖ Y
24
+
25
+ // ---- byte helpers (kept dependency-free; typed arrays only) ----------------
26
+
27
+ export function b64e(u8) {
28
+ let s = "";
29
+ for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000));
30
+ return btoa(s);
31
+ }
32
+ export function b64d(s) {
33
+ const bin = atob(s);
34
+ const u8 = new Uint8Array(bin.length);
35
+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
36
+ return u8;
37
+ }
38
+ export const utf8e = (s) => new TextEncoder().encode(s);
39
+ export const utf8d = (u8) => new TextDecoder().decode(u8);
40
+ export function concat(...parts) {
41
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
42
+ let o = 0;
43
+ for (const p of parts) {
44
+ out.set(p, o);
45
+ o += p.length;
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /** Short human-checkable fingerprint of a static public key (8 bytes, url-safe). */
51
+ export function fingerprint(pub) {
52
+ return b64e(pub.slice(0, 8)).replace(/[^A-Za-z0-9]/g, "").toLowerCase().slice(0, 12);
53
+ }
54
+
55
+ // ---- WebCrypto plumbing ----------------------------------------------------
56
+
57
+ const subtle = globalThis.crypto.subtle;
58
+
59
+ async function sha256(data) {
60
+ return new Uint8Array(await subtle.digest("SHA-256", data));
61
+ }
62
+ async function hmac(keyBytes, data) {
63
+ const key = await subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
64
+ return new Uint8Array(await subtle.sign("HMAC", key, data));
65
+ }
66
+ /** Noise's HKDF: two outputs (ck', k) from a chaining key and input key material. */
67
+ async function hkdf2(chainingKey, ikm) {
68
+ const temp = await hmac(chainingKey, ikm);
69
+ const o1 = await hmac(temp, new Uint8Array([0x01]));
70
+ const o2 = await hmac(temp, concat(o1, new Uint8Array([0x02])));
71
+ return [o1, o2];
72
+ }
73
+
74
+ /** ECDH over P-256; returns the 32-byte shared secret (the X coordinate). */
75
+ async function dh(privJwk, peerPubRaw) {
76
+ const priv = await subtle.importKey("jwk", privJwk, { name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
77
+ const pub = await subtle.importKey("raw", peerPubRaw, { name: "ECDH", namedCurve: "P-256" }, false, []);
78
+ return new Uint8Array(await subtle.deriveBits({ name: "ECDH", public: pub }, priv, 256));
79
+ }
80
+
81
+ export async function generateKeyPair() {
82
+ const pair = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
83
+ const jwk = await subtle.exportKey("jwk", pair.privateKey);
84
+ const pub = new Uint8Array(await subtle.exportKey("raw", pair.publicKey));
85
+ return { jwk, pub };
86
+ }
87
+
88
+ // ---- CipherState (Noise spec §5.2) ------------------------------------------
89
+
90
+ class CipherState {
91
+ k = null;
92
+ n = 0;
93
+ setKey(k) {
94
+ this.k = k;
95
+ }
96
+ nonce() {
97
+ // 96-bit: 4 zero bytes ‖ BE64(n) — n stays below 2^32 for our lifetimes.
98
+ const iv = new Uint8Array(12);
99
+ new DataView(iv.buffer).setUint32(8, this.n);
100
+ return iv;
101
+ }
102
+ async encrypt(ad, plaintext) {
103
+ if (this.n >= 0xffffffff) throw new Error("e2e: nonce exhausted");
104
+ const key = await subtle.importKey("raw", this.k, "AES-GCM", false, ["encrypt"]);
105
+ const ct = new Uint8Array(
106
+ await subtle.encrypt({ name: "AES-GCM", iv: this.nonce(), additionalData: ad, tagLength: 128 }, key, plaintext),
107
+ );
108
+ this.n += 1;
109
+ return ct;
110
+ }
111
+ async decrypt(ad, ciphertext) {
112
+ const key = await subtle.importKey("raw", this.k, "AES-GCM", false, ["decrypt"]);
113
+ const pt = new Uint8Array(
114
+ await subtle.decrypt({ name: "AES-GCM", iv: this.nonce(), additionalData: ad, tagLength: 128 }, key, ciphertext),
115
+ );
116
+ this.n += 1;
117
+ return pt;
118
+ }
119
+ }
120
+
121
+ // ---- the handshake ----------------------------------------------------------
122
+ //
123
+ // device → e_dev (msg1: 65 B raw)
124
+ // host → e_host ‖ ENC0(s_host) (msg2: ENC0 = plaintext when k unset)
125
+ // device → ENC0(s_dev) (msg3)
126
+ //
127
+ // tokens: -> e <- e, ee, s, es -> s, se
128
+ // ee = DH(e_dev, e_host) es = DH(e_dev, s_host) se = DH(e_host, s_dev)
129
+ //
130
+ // then Split() gives one CipherState per direction; every transport message is
131
+ // AES-GCM under it with the final handshake hash as associated data.
132
+
133
+ class Handshake {
134
+ h = null;
135
+ ck = null;
136
+ cs = new CipherState();
137
+ async reset() {
138
+ const nameBytes = utf8e(NOISE_NAME);
139
+ this.h = nameBytes.length === KEY_LEN ? nameBytes : await sha256(nameBytes);
140
+ this.ck = this.h;
141
+ this.cs = new CipherState();
142
+ }
143
+ async mixHash(data) {
144
+ this.h = await sha256(concat(this.h, data));
145
+ }
146
+ async mixKey(ikm) {
147
+ const [ck, k] = await hkdf2(this.ck, ikm);
148
+ this.ck = ck;
149
+ this.cs = new CipherState();
150
+ this.cs.setKey(k);
151
+ }
152
+ /** The `s` token: transport under the current key, else in the clear (ENC0). */
153
+ async writeTokenStatic(pubRaw) {
154
+ const out = this.cs.k ? await this.cs.encrypt(this.h, pubRaw) : pubRaw;
155
+ await this.mixHash(out);
156
+ return out;
157
+ }
158
+ async readTokenStatic(bytes) {
159
+ const pt = this.cs.k ? await this.cs.decrypt(this.h, bytes) : bytes;
160
+ await this.mixHash(bytes);
161
+ return pt;
162
+ }
163
+ async split() {
164
+ const [k1, k2] = await hkdf2(this.ck, new Uint8Array(0));
165
+ const c1 = new CipherState();
166
+ const c2 = new CipherState();
167
+ c1.setKey(k1);
168
+ c2.setKey(k2);
169
+ return [c1, c2];
170
+ }
171
+ }
172
+
173
+ /** The device side (initiator). `self` is {jwk, pub} from generateKeyPair(). */
174
+ export class DeviceChannel {
175
+ #hs = new Handshake();
176
+ #self = null;
177
+ #e = null;
178
+ sendCs = null;
179
+ recvCs = null;
180
+ hostFingerprint = null;
181
+ constructor(self) {
182
+ this.#self = self;
183
+ }
184
+ /** msg1 payload for `{op:"e2e.init", e}`. */
185
+ async begin() {
186
+ await this.#hs.reset();
187
+ this.#e = await generateKeyPair();
188
+ await this.#hs.mixHash(this.#e.pub);
189
+ return { e: b64e(this.#e.pub) };
190
+ }
191
+ /** Feed the host's `{op:"e2e.reply", e, c}`; returns the msg3 payload. */
192
+ async acceptReply(msg) {
193
+ const eHost = b64d(msg.e);
194
+ if (eHost.length !== PUB_LEN) throw new Error("e2e: bad host ephemeral");
195
+ await this.#hs.mixHash(eHost);
196
+ await this.#hs.mixKey(await dh(this.#e.jwk, eHost)); // ee
197
+ const sHost = await this.#hs.readTokenStatic(b64d(msg.c)); // s
198
+ if (sHost.length !== PUB_LEN) throw new Error("e2e: bad host static");
199
+ this.hostFingerprint = fingerprint(sHost);
200
+ await this.#hs.mixKey(await dh(this.#e.jwk, sHost)); // es (e_dev × s_host)
201
+ const c = await this.#hs.writeTokenStatic(this.#self.pub); // s_dev
202
+ await this.#hs.mixKey(await dh(this.#self.jwk, eHost)); // se (e_host × s_dev)
203
+ const [c1, c2] = await this.#hs.split();
204
+ this.sendCs = c1; // device → host
205
+ this.recvCs = c2; // host → device
206
+ this.#e = null;
207
+ return { c: b64e(c) };
208
+ }
209
+ ready() {
210
+ return Boolean(this.sendCs && this.recvCs);
211
+ }
212
+ async send(obj) {
213
+ const ct = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
214
+ return { op: "e2e", n: this.sendCs.n - 1, c: b64e(ct) };
215
+ }
216
+ async recv(msg) {
217
+ const pt = await this.recvCs.decrypt(this.#hs.h, b64d(msg.c));
218
+ return JSON.parse(utf8d(pt));
219
+ }
220
+ }
221
+
222
+ /** The host side (responder): one instance per device. */
223
+ export class HostChannel {
224
+ #hs = new Handshake();
225
+ #self = null;
226
+ #e = null;
227
+ sendCs = null;
228
+ recvCs = null;
229
+ deviceFingerprint = null;
230
+ constructor(self) {
231
+ this.#self = self;
232
+ }
233
+ /** Feed the device's `{op:"e2e.init", e}`; returns the msg2 payload. */
234
+ async acceptInit(msg) {
235
+ await this.#hs.reset();
236
+ const eDev = b64d(msg.e);
237
+ if (eDev.length !== PUB_LEN) throw new Error("e2e: bad device ephemeral");
238
+ await this.#hs.mixHash(eDev);
239
+ this.#e = await generateKeyPair();
240
+ await this.#hs.mixHash(this.#e.pub);
241
+ await this.#hs.mixKey(await dh(this.#e.jwk, eDev)); // ee (e_dev × e_host)
242
+ const c = await this.#hs.writeTokenStatic(this.#self.pub); // s_host
243
+ await this.#hs.mixKey(await dh(this.#self.jwk, eDev)); // es (e_dev × s_host)
244
+ return { e: b64e(this.#e.pub), c: b64e(c) };
245
+ }
246
+ /** Feed the device's `{op:"e2e.finish", c}`; the channel is ready afterwards. */
247
+ async acceptFinish(msg) {
248
+ const sDev = await this.#hs.readTokenStatic(b64d(msg.c)); // s_dev
249
+ if (sDev.length !== PUB_LEN) throw new Error("e2e: bad device static");
250
+ this.deviceFingerprint = fingerprint(sDev);
251
+ await this.#hs.mixKey(await dh(this.#e.jwk, sDev)); // se (e_host × s_dev)
252
+ const [c1, c2] = await this.#hs.split();
253
+ this.recvCs = c1; // device → host (c1 encrypts initiator→responder)
254
+ this.sendCs = c2; // host → device
255
+ this.#e = null;
256
+ }
257
+ ready() {
258
+ return Boolean(this.sendCs && this.recvCs);
259
+ }
260
+ async send(obj) {
261
+ const ct = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
262
+ return { op: "e2e", n: this.sendCs.n - 1, c: b64e(ct) };
263
+ }
264
+ async recv(msg) {
265
+ const pt = await this.recvCs.decrypt(this.#hs.h, b64d(msg.c));
266
+ return JSON.parse(utf8d(pt));
267
+ }
268
+ }
Binary file
Binary file
Binary file
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="herdgate">
2
+ <rect width="64" height="64" rx="14" fill="#11131a"/>
3
+ <!-- a gate: two posts and a lintel, with a terminal caret inside -->
4
+ <path d="M18 46V20h5v26zM41 46V20h5v26zM18 18h28v4H18z" fill="#7aa2f7"/>
5
+ <path d="M26 32l6 5-6 5" fill="none" stroke="#e7e9ee" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"/>
6
+ </svg>
@@ -0,0 +1,99 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
6
+ <meta name="theme-color" content="#11131a" />
7
+ <meta name="apple-mobile-web-app-capable" content="yes" />
8
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
9
+ <meta name="apple-mobile-web-app-title" content="herdgate" />
10
+ <title>herdgate</title>
11
+ <link rel="manifest" href="/app.webmanifest" />
12
+ <link rel="icon" href="/icons/icon.svg" type="image/svg+xml" />
13
+ <link rel="apple-touch-icon" href="/icons/icon-192.png" />
14
+ <link rel="stylesheet" href="/app.css" />
15
+ </head>
16
+ <body>
17
+ <!-- Everything the app shows is rendered by app.js into these landmarks. -->
18
+ <header id="bar">
19
+ <strong>herdgate</strong>
20
+ <span id="status" class="pill" role="status" aria-live="polite">offline</span>
21
+ <button id="menu" type="button" aria-label="Settings">⋯</button>
22
+ </header>
23
+
24
+ <main id="main">
25
+ <section id="signin" hidden>
26
+ <h1>Sign in</h1>
27
+ <p class="muted">Your herdgate account token stays on this device.</p>
28
+ <form id="signin-form" autocomplete="off">
29
+ <label for="token">Account token</label>
30
+ <input id="token" name="token" type="password" inputmode="text" autocomplete="off" required />
31
+ <button type="submit">Continue</button>
32
+ </form>
33
+ <p id="signin-error" class="error" role="alert" hidden></p>
34
+ </section>
35
+
36
+ <section id="rooms" hidden>
37
+ <h1>Machines</h1>
38
+ <ul id="room-list" class="list"></ul>
39
+ <p id="rooms-empty" class="muted" hidden>
40
+ No machine is paired yet. Pair one from Herdr — its plugin or app panel prints a code.
41
+ </p>
42
+ <p id="build" class="muted small"></p>
43
+ </section>
44
+
45
+ <section id="room" hidden>
46
+ <button id="back" type="button" class="link">← Machines</button>
47
+ <h1 id="room-name">—</h1>
48
+ <p id="room-state" class="muted">—</p>
49
+ <p id="e2e-note" class="muted small" hidden></p>
50
+ <div id="view"></div>
51
+ </section>
52
+
53
+ <section id="pair" hidden>
54
+ <button id="pair-back" type="button" class="link">← Machines</button>
55
+ <h1>Pair this device</h1>
56
+ <p class="muted">
57
+ Pairing with <code>act</code> lets this device act; the host must approve it. <code>read</code> is
58
+ enough to look.
59
+ </p>
60
+ <form id="pair-form" autocomplete="off">
61
+ <label for="pair-name">Name</label>
62
+ <input id="pair-name" name="name" required />
63
+ <label for="pair-scope">Scope</label>
64
+ <select id="pair-scope" name="scope">
65
+ <option value="read">read</option>
66
+ <option value="act">act</option>
67
+ </select>
68
+ <button type="submit">Pair</button>
69
+ </form>
70
+ <p id="pair-error" class="error" role="alert" hidden></p>
71
+ </section>
72
+ </main>
73
+
74
+ <dialog id="settings">
75
+ <h2>Settings</h2>
76
+ <form id="settings-form" method="dialog">
77
+ <label for="cloud">Cloud URL</label>
78
+ <input id="cloud" name="cloud" placeholder="https://herd.example.com" />
79
+ <p class="muted small">Leave empty to use this page's own origin.</p>
80
+ <div class="row">
81
+ <button id="signout" type="button" class="danger">Forget token</button>
82
+ <button type="submit">Close</button>
83
+ </div>
84
+ </form>
85
+ </dialog>
86
+
87
+ <template id="room-row">
88
+ <li class="row">
89
+ <button class="rowbtn">
90
+ <span class="name"></span>
91
+ <span class="meta"></span>
92
+ </button>
93
+ </li>
94
+ </template>
95
+
96
+ <script src="/e2e.js" type="module"></script>
97
+ <script src="/app.js" type="module"></script>
98
+ </body>
99
+ </html>
package/src/web/sw.js ADDED
@@ -0,0 +1,98 @@
1
+ // Service worker: cache the shell so the app opens without a network, and never cache
2
+ // anything from `/v1/` (the API must always hit the cloud).
3
+ //
4
+ // Bump VERSION when a shell file changes; old caches are dropped on activate.
5
+
6
+ const VERSION = "herdgate-v8";
7
+ const SHELL = ["/", "/app.css", "/e2e.js", "/app.js", "/app.webmanifest", "/icons/icon.svg"];
8
+
9
+ self.addEventListener("install", (event) => {
10
+ event.waitUntil(
11
+ caches
12
+ .open(VERSION)
13
+ .then((cache) => cache.addAll(SHELL))
14
+ .then(() => self.skipWaiting())
15
+ .catch(() => {
16
+ /* a missing asset must not block installation */
17
+ }),
18
+ );
19
+ });
20
+
21
+ self.addEventListener("activate", (event) => {
22
+ event.waitUntil(
23
+ caches
24
+ .keys()
25
+ .then((keys) => Promise.all(keys.filter((k) => k !== VERSION).map((k) => caches.delete(k))))
26
+ .then(() => self.clients.claim()),
27
+ );
28
+ });
29
+
30
+ // Push wake: the cloud sends a silent, payload-less ping (VAPID) when the host has
31
+ // news and this device is away. If a window is already open its socket reconnects on
32
+ // its own — otherwise raise a notification that opens the app.
33
+ self.addEventListener("push", (event) => {
34
+ event.waitUntil(
35
+ (async () => {
36
+ const all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
37
+ if (all.length > 0) {
38
+ for (const client of all) client.postMessage({ t: "wake" });
39
+ return;
40
+ }
41
+ await self.registration.showNotification("herdgate", {
42
+ body: "Có hoạt động mới trên máy của bạn — chạm để mở.",
43
+ tag: "herdgate-wake",
44
+ renotify: true,
45
+ });
46
+ })(),
47
+ );
48
+ });
49
+
50
+ self.addEventListener("notificationclick", (event) => {
51
+ event.notification.close();
52
+ event.waitUntil(
53
+ (async () => {
54
+ const all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
55
+ for (const client of all) if ("focus" in client) return client.focus();
56
+ return self.clients.openWindow("/");
57
+ })(),
58
+ );
59
+ });
60
+
61
+ self.addEventListener("fetch", (event) => {
62
+ const request = event.request;
63
+ if (request.method !== "GET") return;
64
+
65
+ const url = new URL(request.url);
66
+ if (url.origin !== self.location.origin) return; // never touch another origin
67
+ if (url.pathname.startsWith("/v1/") || url.pathname === "/healthz") return; // API: always live
68
+
69
+ // Navigations: network first (a new deploy should win), cache as the fallback.
70
+ if (request.mode === "navigate") {
71
+ event.respondWith(
72
+ fetch(request)
73
+ .then((response) => {
74
+ const copy = response.clone();
75
+ caches.open(VERSION).then((cache) => cache.put("/", copy)).catch(() => {});
76
+ return response;
77
+ })
78
+ .catch(() => caches.match("/").then((hit) => hit ?? new Response("offline", { status: 503 }))),
79
+ );
80
+ return;
81
+ }
82
+
83
+ // Assets: cache first, refresh in the background.
84
+ event.respondWith(
85
+ caches.match(request).then((hit) => {
86
+ const network = fetch(request)
87
+ .then((response) => {
88
+ if (response.ok) {
89
+ const copy = response.clone();
90
+ caches.open(VERSION).then((cache) => cache.put(request, copy)).catch(() => {});
91
+ }
92
+ return response;
93
+ })
94
+ .catch(() => hit);
95
+ return hit ?? network;
96
+ }),
97
+ );
98
+ });