@bom0792/herdgate 0.9.39 → 0.9.41

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.
@@ -38,8 +38,27 @@ import { type Account, type DeviceRecord, type RoomRecord, State } from "./store
38
38
  import { pruneBudget, readJsonBody, randomId, sameSecret, sha256Hex } from "./util.ts";
39
39
  import { serveStatic } from "./static.ts";
40
40
  import { startSshd, type SshHandle, type SshConfig } from "./sshd.ts";
41
- import { pushEndpoint, sendWake } from "./push.ts";
41
+ import { pushEndpoint, sendPush, encryptPayload, canPayload, type PushKeys } from "./push.ts";
42
42
  import { type VapidKeys } from "./vapid.ts";
43
+ import { readFileSync } from "node:fs";
44
+ import { dirname, join } from "node:path";
45
+ import { fileURLToPath } from "node:url";
46
+
47
+ /** The gate's own build id (npm package version) — served on /healthz so a PWA can
48
+ * detect that the bundle it is running is older than the gate and offer a reload. */
49
+ const BUILD_ID: string = (() => {
50
+ try {
51
+ return String(JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../package.json"), "utf8")).version ?? "");
52
+ } catch {
53
+ return "";
54
+ }
55
+ })();
56
+
57
+ /** What changed on the host, for the encrypted push payload (Vietnamese copy is PWA-side). */
58
+ export interface WakeNote {
59
+ kind: "settle" | "died" | "needs-you" | "activity";
60
+ agent?: string;
61
+ }
43
62
 
44
63
  export interface CloudConfig {
45
64
  accounts: { id: string; name: string; token: string }[];
@@ -178,13 +197,27 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
178
197
  return s;
179
198
  };
180
199
  const pendingWakes = new Set<string>();
181
- const wakeDevice = (deviceId: string): void => {
200
+ /** Push a wake to an away device. `note` (from the host) upgrades the ping to an
201
+ * encrypted payload when the subscription captured its p256dh/auth keys — the
202
+ * provider still sees only ciphertext; keyless subscriptions keep the silent ping. */
203
+ const wakeDevice = (deviceId: string, note?: WakeNote): void => {
182
204
  const push = cfg.push;
183
- const endpoint = pushEndpoint(state.deviceById(deviceId)?.push?.endpoint ?? "");
205
+ const rec = state.deviceById(deviceId);
206
+ const endpoint = pushEndpoint(rec?.push?.endpoint ?? "");
184
207
  if (!push || !endpoint || pendingWakes.has(deviceId) || pendingWakes.size >= 8) return;
185
208
  pendingWakes.add(deviceId);
186
- void sendWake(endpoint, push.keys, push.sub).catch(() => log("push: wake failed"))
187
- .finally(() => pendingWakes.delete(deviceId));
209
+ const send = async (): Promise<void> => {
210
+ const keys = rec?.push;
211
+ if (note && keys && canPayload(keys)) {
212
+ const payload = Buffer.from(JSON.stringify({
213
+ v: 1, kind: note.kind, room: rec!.roomId, ...(note.agent ? { agent: note.agent } : {}),
214
+ }), "utf8");
215
+ const body = encryptPayload(payload, keys.p256dh!, keys.auth!);
216
+ return sendPush(endpoint, push.keys, push.sub, body, note.kind === "needs-you" || note.kind === "died" ? "high" : "normal");
217
+ }
218
+ return sendPush(endpoint, push.keys, push.sub, null, "normal");
219
+ };
220
+ void send().catch(() => log("push: wake failed")).finally(() => pendingWakes.delete(deviceId));
188
221
  };
189
222
 
190
223
  const streamEmit = (roomId: string, msg: Record<string, unknown>, device?: string): void => {
@@ -420,14 +453,26 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
420
453
  }
421
454
  case "wake": {
422
455
  // The host asks for a phone to be woken: deliver a silent push only if the
423
- // device is not connected right now (a connected one is already live).
456
+ // device is not connected right now (a connected one is already live). A
457
+ // `note` upgrades the ping to an encrypted payload (settle / died / needs-you)
458
+ // when the subscription carries its RFC 8291 keys.
424
459
  if (!cfg.push) return fail(ws, "no-push", "push is not configured");
425
460
  const deviceId = typeof m.device === "string" ? m.device : null;
426
461
  if (!deviceId) return fail(ws, "bad-message", "wake.device");
427
462
  const rec = state.deviceById(deviceId);
428
463
  if (!rec || rec.roomId !== room.id) return fail(ws, "no-such-device", "not one of this room's devices");
464
+ const rawNote = m.note;
465
+ let note: WakeNote | undefined;
466
+ if (rawNote && typeof rawNote === "object") {
467
+ const kind = (rawNote as { kind?: unknown }).kind;
468
+ const agent = (rawNote as { agent?: unknown }).agent;
469
+ if (kind !== "settle" && kind !== "died" && kind !== "needs-you" && kind !== "activity") {
470
+ return fail(ws, "bad-message", "wake.note.kind");
471
+ }
472
+ note = { kind, ...(typeof agent === "string" && agent.length <= 64 ? { agent: agent.slice(0, 64) } : {}) };
473
+ }
429
474
  if ([...deviceConns].some((c) => c.device?.id === deviceId)) return;
430
- wakeDevice(deviceId);
475
+ wakeDevice(deviceId, note);
431
476
  return;
432
477
  }
433
478
  case "ping":
@@ -816,7 +861,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
816
861
  const path = url.pathname;
817
862
 
818
863
  if (req.method === "GET" && path === "/healthz") {
819
- res.writeHead(200);
864
+ res.writeHead(200, BUILD_ID ? { "x-hg-build": BUILD_ID } : undefined);
820
865
  return res.end("ok");
821
866
  }
822
867
 
@@ -897,7 +942,15 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
897
942
  if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
898
943
  const validated = pushEndpoint(endpoint);
899
944
  if (!validated) return json(res, 400, { error: "unsupported push endpoint" });
900
- state.setDevicePush(device.id, validated.href);
945
+ // Optional RFC 8291 keys: validate the shapes once here, then store verbatim.
946
+ // A subscription without them keeps working as a silent wake ping.
947
+ const p256dh = typeof body?.p256dh === "string" ? body.p256dh : "";
948
+ const auth = typeof body?.auth === "string" ? body.auth : "";
949
+ if ((p256dh || auth) && !canPayload({ p256dh, auth })) {
950
+ return json(res, 400, { error: "bad push keys" });
951
+ }
952
+ const keys: PushKeys | undefined = p256dh && auth ? { p256dh, auth } : undefined;
953
+ state.setDevicePush(device.id, validated.href, keys);
901
954
  return json(res, 200, { ok: true });
902
955
  });
903
956
  }
@@ -917,7 +970,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
917
970
  return json(res, 200, {
918
971
  devices: state.devices
919
972
  .filter((d) => d.roomId === room.id)
920
- .map((d) => ({ id: d.id, name: d.name, scope: d.scope, connected: live.has(d.id), keys: (d.sshKeys ?? []).length, created: d.created })),
973
+ .map((d) => ({ id: d.id, name: d.name, scope: d.scope, connected: live.has(d.id), keys: (d.sshKeys ?? []).length, created: d.created, push: !!d.push, payload: canPayload(d.push) })),
921
974
  });
922
975
  }
923
976
  if (path === "/v1/device/revoke") {
package/src/cloud/push.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { lookup } from "node:dns/promises";
2
2
  import { request } from "node:https";
3
3
  import { BlockList, isIPv4 } from "node:net";
4
+ import { createCipheriv, createECDH, generateKeyPairSync, hkdfSync, randomBytes } from "node:crypto";
4
5
  import { vapidHeader, type VapidKeys } from "./vapid.ts";
5
6
 
6
7
  const providers = new Set(["fcm.googleapis.com", "updates.push.services.mozilla.com", "web.push.apple.com"]);
@@ -28,6 +29,93 @@ export function publicPushAddress(address: string): boolean {
28
29
  }
29
30
 
30
31
  export async function sendWake(endpoint: URL, keys: VapidKeys, sub: string): Promise<void> {
32
+ return sendPush(endpoint, keys, sub, null, "normal");
33
+ }
34
+
35
+ /** The user-agent half of a web-push subscription (RFC 8291 §2): the P-256 public
36
+ * point the browser generated (65-byte uncompressed, base64url) and the 16-byte
37
+ * auth secret. Both arrive via /v1/device/push alongside the endpoint. */
38
+ export interface PushKeys {
39
+ p256dh: string;
40
+ auth: string;
41
+ }
42
+
43
+ export interface EncryptSeams {
44
+ /** Fixed 16-byte salt and ephemeral keypair — test seams for deterministic vectors. */
45
+ salt?: Buffer;
46
+ asKeys?: { privateKey: Buffer; publicKey: Buffer };
47
+ }
48
+
49
+ /** Web-push payload encryption (RFC 8291) in the aes128gcm content coding (RFC 8188).
50
+ *
51
+ * body = salt(16) ‖ rs(4, BE, 4096) ‖ idlen(1, 65) ‖ asPublic(65) ‖ AES-128-GCM(plaintext ‖ 0x02 ‖ pad)
52
+ *
53
+ * The ephemeral server public key rides in the keyid field — that is how the agent
54
+ * derives the same IKM without any extra header (the aesgcm "dh=" header is dead).
55
+ * IKM = HKDF(salt=auth, ecdh(asPriv, uaPublic), info="WebPush: info"‖ua‖as, 32)
56
+ * CEK = HKDF(salt=rand, IKM, info="Content-Encoding: aes128gcm", 16)
57
+ * NONCE= HKDF(salt=rand, IKM, info="Content-Encoding: nonce", 12)
58
+ * Plaintext must fit one record: ≤ 4096 − 1 (delimiter) − 16 (GCM tag) − 65… the
59
+ * record size covers plaintext+delimiter+padding+tag, so payloads stay tiny by design. */
60
+ export function encryptPayload(
61
+ plaintext: Buffer,
62
+ uaPublicB64u: string,
63
+ authB64u: string,
64
+ seams: EncryptSeams = {},
65
+ ): Buffer {
66
+ const uaPublic = Buffer.from(uaPublicB64u, "base64url");
67
+ const auth = Buffer.from(authB64u, "base64url");
68
+ if (uaPublic.length !== 65 || uaPublic[0] !== 0x04) throw new Error("p256dh must be a 65-byte uncompressed point");
69
+ if (auth.length !== 16) throw new Error("auth secret must be 16 bytes");
70
+ if (plaintext.length === 0 || plaintext.length > 3000) throw new Error("payload must be 1..3000 bytes");
71
+
72
+ const as = seams.asKeys ?? (() => {
73
+ const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
74
+ const jwk = publicKey.export({ format: "jwk" }) as { x: string; y: string };
75
+ const d = privateKey.export({ format: "jwk" }) as { d: string };
76
+ return {
77
+ privateKey: Buffer.from(d.d, "base64url"),
78
+ publicKey: Buffer.concat([Buffer.from([0x04]), Buffer.from(jwk.x, "base64url"), Buffer.from(jwk.y, "base64url")]),
79
+ };
80
+ })();
81
+ const ecdh = createECDH("prime256v1");
82
+ ecdh.setPrivateKey(as.privateKey);
83
+ const secret = ecdh.computeSecret(uaPublic);
84
+
85
+ const salt = seams.salt ?? randomBytes(16);
86
+ const info = Buffer.concat([Buffer.from("WebPush: info"), uaPublic, as.publicKey]);
87
+ const ikm = Buffer.from(hkdfSync("sha256", secret, auth, info, 32));
88
+ const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm"), 16));
89
+ const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce"), 12));
90
+
91
+ // One record: plaintext ‖ 0x02 delimiter ‖ zero padding, then GCM over the whole thing.
92
+ const rs = 4096;
93
+ const padded = Buffer.concat([plaintext, Buffer.from([0x02]), Buffer.alloc(0)]);
94
+ if (padded.length + 16 > rs) throw new Error("payload does not fit one aes128gcm record");
95
+ const cipher = createCipheriv("aes-128-gcm", cek, nonce);
96
+ const ciphertext = Buffer.concat([cipher.update(padded), cipher.final(), cipher.getAuthTag()]);
97
+
98
+ const idLen = Buffer.from([as.publicKey.length]); // 65
99
+ const rsBuf = Buffer.alloc(4);
100
+ rsBuf.writeUInt32BE(rs);
101
+ return Buffer.concat([salt, rsBuf, idLen, as.publicKey, ciphertext]);
102
+ }
103
+
104
+ /** True when a stored subscription can receive payloads (keys captured at subscribe time). */
105
+ export function canPayload(k: { p256dh?: string; auth?: string } | undefined): boolean {
106
+ return typeof k?.p256dh === "string" && typeof k?.auth === "string" &&
107
+ Buffer.from(k.p256dh, "base64url").length === 65 && Buffer.from(k.auth, "base64url").length === 16;
108
+ }
109
+
110
+ /** POST to the push service: a silent ping (no body) or an encrypted payload.
111
+ * `urgent` (needs-you / died) maps to Urgency: high so the platform budgets battery. */
112
+ export async function sendPush(
113
+ endpoint: URL,
114
+ keys: VapidKeys,
115
+ sub: string,
116
+ body: Buffer | null,
117
+ urgency: "normal" | "high" = "normal",
118
+ ): Promise<void> {
31
119
  const { hostname, pathname, search, href } = endpoint;
32
120
  // Keep the DNS lookup part of the in-flight quota even if it is slow.
33
121
  const signal = AbortSignal.timeout(5000);
@@ -39,7 +127,14 @@ export async function sendWake(endpoint: URL, keys: VapidKeys, sub: string): Pro
39
127
  hostname: address, servername: hostname, path: pathname + search,
40
128
  method: "POST", agent: false, rejectUnauthorized: true, signal,
41
129
  headers: {
42
- Host: hostname, TTL: "60", Urgency: "normal", "content-length": "0",
130
+ Host: hostname, TTL: "60", Urgency: urgency,
131
+ ...(body
132
+ ? {
133
+ "Content-Encoding": "aes128gcm",
134
+ "Content-Type": "application/octet-stream",
135
+ "Content-Length": String(body.length),
136
+ }
137
+ : { "content-length": "0" }),
43
138
  Authorization: vapidHeader(href, keys, sub),
44
139
  },
45
140
  }, (res) => {
@@ -49,6 +144,6 @@ export async function sendWake(endpoint: URL, keys: VapidKeys, sub: string): Pro
49
144
  else reject(new Error("push provider rejected wake"));
50
145
  });
51
146
  req.once("error", reject);
52
- req.end();
147
+ req.end(body ?? undefined);
53
148
  });
54
149
  }
@@ -36,8 +36,10 @@ export interface DeviceRecord {
36
36
  created: string;
37
37
  /** sha256 of the device's own secret; the plaintext exists only at pair time. */
38
38
  secretHash?: string;
39
- /** The device's web-push subscription endpoint for silent wake pings (VAPID). */
40
- push?: { endpoint: string; at: string };
39
+ /** The device's web-push subscription: endpoint for silent wake pings (VAPID) plus
40
+ * the user-agent half for encrypted payloads (RFC 8291) — p256dh (65-byte point,
41
+ * base64url) and auth (16 bytes). Old subscriptions carry the endpoint only. */
42
+ push?: { endpoint: string; at: string; p256dh?: string; auth?: string };
41
43
  /** SSH public keys this device may log in with (authorized_keys lines, parsed). */
42
44
  sshKeys?: { algo: string; b64: string; comment?: string; at: string }[];
43
45
  }
@@ -117,11 +119,13 @@ export class State {
117
119
  return this.devices.find((d) => d.id === id) ?? null;
118
120
  }
119
121
 
120
- /** Remember (or forget, with a null endpoint) where to wake a device. */
121
- setDevicePush(id: string, endpoint: string | null): boolean {
122
+ /** Remember (or forget, with a null endpoint) where to wake a device. `keys` is
123
+ * the subscription's p256dh/auth pair (validated by the caller) — present only
124
+ * on subscriptions made by the current PWA; absent keeps the legacy silent ping. */
125
+ setDevicePush(id: string, endpoint: string | null, keys?: { p256dh: string; auth: string }): boolean {
122
126
  const d = this.deviceById(id);
123
127
  if (!d) return false;
124
- d.push = endpoint ? { endpoint, at: new Date().toISOString() } : undefined;
128
+ d.push = endpoint ? { endpoint, at: new Date().toISOString(), ...keys } : undefined;
125
129
  if (!endpoint) delete d.push;
126
130
  this.#save();
127
131
  return true;
package/src/web/app.css CHANGED
@@ -710,3 +710,92 @@ button.attach {
710
710
  box-shadow: 0 6px 24px rgb(0 0 0 / 0.35);
711
711
  z-index: 40;
712
712
  }
713
+
714
+ /* Self-update banner: a newer gate than the running bundle — shown only when the
715
+ reload has to wait (once-per-build already used, or the user is typing). */
716
+ #upd {
717
+ position: fixed;
718
+ left: 50%;
719
+ bottom: calc(env(safe-area-inset-bottom, 0px) + 14px);
720
+ transform: translateX(-50%);
721
+ z-index: 45;
722
+ }
723
+ #upd button {
724
+ background: var(--accent, #4da3ff);
725
+ color: #0b1220;
726
+ border: none;
727
+ border-radius: 999px;
728
+ padding: 10px 18px;
729
+ font-size: 13px;
730
+ font-weight: 600;
731
+ box-shadow: 0 6px 24px rgb(0 0 0 / 0.4);
732
+ }
733
+
734
+ /* Files (filev): fuzzy list + one-file reader with line numbers and smartcase
735
+ search — the status glyph borrows the diff palette. */
736
+ .files-list { list-style: none; margin: 8px 0; padding: 0; }
737
+ .files-list li button {
738
+ display: flex; gap: 8px; align-items: baseline; width: 100%;
739
+ background: none; border: none; color: inherit; text-align: left;
740
+ padding: 4px 2px; font: inherit; cursor: pointer;
741
+ }
742
+ .files-list li button:active { background: var(--hover, rgb(255 255 255 / 0.08)); }
743
+ .fstat { width: 1.1em; text-align: center; font-weight: 700; opacity: 0.9; }
744
+ .fstat-M { color: #e6b450; }
745
+ .fstat-A { color: #7fd962; }
746
+ .fstat-D { color: #f07178; }
747
+ .fstat-R, .fstat-C, .fstat-U { color: #73d0ff; }
748
+ .fpath { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; overflow-wrap: anywhere; }
749
+ .files-head { display: flex; flex-wrap: wrap; gap: 8px; align-items: baseline; margin: 6px 0; }
750
+ .files-head .fpath { font-weight: 600; }
751
+ .file-search { flex: 1; min-width: 140px; }
752
+ .file-body {
753
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px;
754
+ line-height: 1.5; overflow-x: auto; white-space: pre; margin-top: 6px;
755
+ }
756
+ .file-line { display: flex; gap: 10px; }
757
+ .line-no { color: var(--muted, #8b8b8b); min-width: 3.5em; text-align: right; user-select: none; flex-shrink: 0; }
758
+ .file-hit { background: rgb(115 208 255 / 0.35); border-radius: 2px; }
759
+ .file-body .flash { background: rgb(230 180 80 / 0.3); }
760
+
761
+ /* Review (reviewr mobile): scope chips, change list, line-comment flow */
762
+ .rev-scopes { display: flex; gap: 6px; margin: 8px 0; flex-wrap: wrap; }
763
+ .rev-chip {
764
+ background: none; border: 1px solid var(--muted, #8b8b8b); border-radius: 999px;
765
+ color: inherit; padding: 3px 10px; font-size: 12px; cursor: pointer;
766
+ }
767
+ .rev-chip.active { border-color: var(--accent, #73d0ff); color: var(--accent, #73d0ff); }
768
+ .rev-list { list-style: none; margin: 8px 0; padding: 0; }
769
+ .rev-list li button {
770
+ display: flex; gap: 8px; align-items: baseline; width: 100%;
771
+ background: none; border: none; color: inherit; text-align: left;
772
+ padding: 4px 2px; font: inherit; cursor: pointer;
773
+ }
774
+ .rev-list li button:active { background: var(--hover, rgb(255 255 255 / 0.08)); }
775
+ .rev-stat { margin-left: auto; font-size: 11px; white-space: nowrap; color: var(--muted, #8b8b8b); }
776
+ .rev-stat::first-letter { color: #7fd962; }
777
+ .rev-stat.new { color: #7fd962; }
778
+ .rev-stat.comments { color: #e6b450; margin-left: 6px; }
779
+ .rev-diff .rev-hint { color: var(--muted, #8b8b8b); font-size: 11px; margin-bottom: 4px; }
780
+ .rev-row { display: flex; gap: 10px; }
781
+ .rev-row .rev-text { overflow-wrap: anywhere; }
782
+ .rev-row.dadd { background: rgb(127 217 98 / 0.12); }
783
+ .rev-row.dadd .line-no { color: #7fd962; }
784
+ .rev-row.ddel { background: rgb(240 113 120 / 0.12); }
785
+ .rev-row.ddel .line-no { color: #f07178; }
786
+ .rev-row:not(.dhunk):active { background: var(--hover, rgb(255 255 255 / 0.1)); }
787
+ .rev-row.dhunk { color: #b48eff; margin: 6px 0 2px; }
788
+ .rev-chip-comment {
789
+ display: flex; gap: 6px; align-items: baseline; margin: 2px 0 6px 3.5em;
790
+ font-size: 12px; color: #e6b450;
791
+ }
792
+ .rev-chip-comment .link { margin-left: auto; }
793
+ .rev-cbox { display: flex; gap: 6px; align-items: flex-start; margin: 4px 0 8px; flex-wrap: wrap; }
794
+ .rev-cbox textarea { flex: 1; min-width: 160px; }
795
+ .rev-send {
796
+ display: block; width: 100%; margin: 10px 0; padding: 8px;
797
+ border: 1px solid var(--accent, #73d0ff); background: none; color: var(--accent, #73d0ff);
798
+ border-radius: 6px; font: inherit; cursor: pointer;
799
+ }
800
+ .rev-send:disabled { opacity: 0.45; cursor: default; }
801
+ .rev-sent { color: #7fd962; }