my-durable 0.0.115 → 0.0.117

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 (24) hide show
  1. package/apps/dpi-backend/src/backup.ts +41 -0
  2. package/apps/dpi-backend/src/diagnostics.ts +12 -1
  3. package/apps/dpi-backend/src/git.ts +92 -35
  4. package/apps/dpi-backend/src/store.ts +46 -6
  5. package/apps/dpi-backend/src/vitals.ts +6 -0
  6. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-5H8W3a_-.js +83 -0
  7. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-lji31QeB.css → index-DD66rPUN.css} +1 -1
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  9. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/composables.ts +29 -2
  10. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +14 -0
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/markdown.ts +7 -2
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GitPanel.vue +11 -8
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TunnelStatusBar.vue +5 -1
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +12 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +153 -17
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +38 -11
  17. package/apps/dpi-sdk/src/client.ts +53 -2
  18. package/apps/dpi-sdk/src/node/ops.ts +6 -2
  19. package/apps/dpi-sdk/src/node/private-file.ts +34 -1
  20. package/apps/dpi-sdk/src/node/registry.ts +5 -1
  21. package/apps/dpi-sdk/src/protocol/limits.ts +21 -0
  22. package/docs/verification.md +18 -0
  23. package/package.json +1 -1
  24. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-jjYABCI4.js +0 -83
@@ -34,6 +34,7 @@ import {
34
34
  } from "lucide-vue-next";
35
35
  import { deviceId, network, sessionSummary, notify, select } from "../client/store";
36
36
  import { deviceClient } from "../client/hub";
37
+ import { externalHref } from "../client/link-policy"; // r10 h4-1: device-authored URLs never bind raw
37
38
  import { ensureGit, gitAllowedFor, gitEntry, wireGitAutoRefresh } from "../client/git-store";
38
39
  import { addWorktree as gitAddWorktree, createSessionOn } from "../client/worktree";
39
40
  import type { GitStatus } from "@sdk/client";
@@ -136,7 +137,7 @@ const prBusy = ref(false);
136
137
  * actions built from the origin URL — no CLI, no login, no assumption. */
137
138
  const forge = computed<"github" | "gitlab" | "bitbucket" | "other" | undefined>(() => status.value?.forge);
138
139
  const isGitHub = computed(() => forge.value === "github");
139
- const webUrl = computed(() => status.value?.webUrl ?? "");
140
+ const webUrl = computed(() => externalHref(status.value?.webUrl ?? "", globalThis.location?.origin ?? "") ?? "");
140
141
  const changeLabel = computed(() =>
141
142
  forge.value === "gitlab" ? "merge request" : forge.value === "bitbucket" ? "pull request" : forge.value === "github" ? "pull request" : "change request",
142
143
  );
@@ -153,9 +154,11 @@ const newChangeHref = computed(() => {
153
154
  if (forge.value === "github") return `${webUrl.value}/compare/${b || "main"}...${e}?expand=1`;
154
155
  return "";
155
156
  });
156
- const changesHref = computed(() =>
157
- forge.value === "gitlab" ? `${webUrl.value}/-/merge_requests` : forge.value === "bitbucket" ? `${webUrl.value}/pull-requests` : `${webUrl.value}/pulls`,
158
- );
157
+ const changesHref = computed(() => {
158
+ if (!webUrl.value) return "";
159
+ return forge.value === "gitlab" ? `${webUrl.value}/-/merge_requests` : forge.value === "bitbucket" ? `${webUrl.value}/pull-requests` : `${webUrl.value}/pulls`;
160
+ });
161
+ const prSafeUrl = (u: string) => externalHref(u, globalThis.location?.origin ?? "");
159
162
  const loadPRs = async () => {
160
163
  if (!devId.value || !cwd.value) return;
161
164
  const allowed = gitAllowedFor(devId.value, cwd.value);
@@ -346,7 +349,7 @@ const dirty = computed(() => (status.value?.staged ?? 0) + (status.value?.unstag
346
349
  const noIdentity = computed(() => status.value?.repo === true && status.value?.identityComplete === false);
347
350
  /** The device parses the origin once (ssh/https/self-hosted/nested GitLab
348
351
  * namespaces) and reports the browser URL; a second FE parser drifted from it. */
349
- const remoteWeb = computed(() => status.value?.webUrl ?? "");
352
+ const remoteWeb = computed(() => externalHref(status.value?.webUrl ?? "", globalThis.location?.origin ?? "") ?? "");
350
353
  const toggle = (p: string) => {
351
354
  const next = new Set(checked.value);
352
355
  if (next.has(p)) next.delete(p);
@@ -1237,8 +1240,8 @@ const laneX = (lane: number) => lane * 12 + 7;
1237
1240
  <h4><GitMerge :size="16" /> {{ isGitHub ? "Pull requests" : changeLabel + "s" }}</h4>
1238
1241
  <span class="grow" />
1239
1242
  <a v-if="!isGitHub && newChangeHref" class="small btn-like" :href="newChangeHref" target="_blank" rel="noopener">new {{ changeLabel }}</a>
1240
- <a v-if="!isGitHub" class="small btn-like" :href="changesHref" target="_blank" rel="noopener">open {{ changeLabel }}s</a>
1241
- <a v-if="!isGitHub" class="small btn-like" :href="webUrl" target="_blank" rel="noopener">repo</a>
1243
+ <a v-if="!isGitHub && changesHref" class="small btn-like" :href="changesHref" target="_blank" rel="noopener">open {{ changeLabel }}s</a>
1244
+ <a v-if="!isGitHub && webUrl" class="small btn-like" :href="webUrl" target="_blank" rel="noopener">repo</a>
1242
1245
  </div>
1243
1246
  <template v-if="!isGitHub">
1244
1247
  <p class="hint">
@@ -1263,7 +1266,7 @@ const laneX = (lane: number) => lane * 12 + 7;
1263
1266
  <button class="icon-button" title="run checks" :disabled="prBusy" @click="prChecksOf(pr.n)"><RefreshCw :size="13" /></button>
1264
1267
  <button class="icon-button" title="comment" :disabled="prBusy" @click="prCommentAsk(pr.n)"><Copy :size="13" /></button>
1265
1268
  <button v-if="pr.state === 'OPEN'" class="small" :disabled="prBusy || !!busy" @click="prMergeAsk(pr.n)">squash &amp; merge</button>
1266
- <a class="icon-button" :href="pr.url" target="_blank" rel="noopener" title="open on the forge"><ArrowUpFromLine :size="13" style="transform: rotate(45deg)" /></a>
1269
+ <a v-if="prSafeUrl(pr.url)" class="icon-button" :href="prSafeUrl(pr.url)!" target="_blank" rel="noopener" title="open on the forge"><ArrowUpFromLine :size="13" style="transform: rotate(45deg)" /></a>
1267
1270
  </div>
1268
1271
  <pre v-for="[n, text] in prChecks" :key="n" class="pr-checks">#{{ n }} checks:{{ "\n" }}{{ text }}</pre>
1269
1272
  </div>
@@ -12,8 +12,12 @@
12
12
  import { computed } from "vue";
13
13
  import { Cable, Wifi, WifiOff } from "lucide-vue-next";
14
14
  import type { NetworkDevice } from "@sdk/api";
15
+ import { externalHref } from "../client/link-policy"; // r10 h4-1: device.url is device-authored
15
16
  import { ago } from "../client/store";
16
17
 
18
+ /** Template helper: device-authored URL → http(s)-only, non-hub href (r10 h4-1). */
19
+ const safeUrl = (u: string) => externalHref(u, globalThis.location?.origin ?? "") || undefined;
20
+
17
21
  const props = defineProps<{ device: NetworkDevice }>();
18
22
 
19
23
  const online = computed(() => props.device.status === "online");
@@ -51,7 +55,7 @@ const tunnelLive = computed(() => props.device.tunnel?.state === "connected");
51
55
  >
52
56
  {{ device.tunnel.readerCount }} reader{{ device.tunnel.readerCount === 1 ? "" : "s" }}
53
57
  </span>
54
- <a v-if="device.url" class="axis url" :href="device.url" target="_blank" rel="noreferrer">{{
58
+ <a v-if="device.url" class="axis url" :href="safeUrl(device.url)" target="_blank" rel="noreferrer">{{
55
59
  device.url
56
60
  }}</a>
57
61
  <span
@@ -96,7 +96,15 @@ registry.clearTunnelState(); // live tunnel state is RAM-only; never resurrect f
96
96
  // promise inside the registry — await it (non-fatal, logged) so network.sqlite
97
97
  // is locked down before the listener starts serving.
98
98
  try {
99
- await registry.restrictOwner;
99
+ // r10 h1-3: the DACL pass runs execFile (whoami+icacls) whose callback can
100
+ // outlive its timeout if a grandchild inherits the stdout pipe — boot never
101
+ // depends on the outcome, so race it with a deadline and log lateness.
102
+ const late = Symbol("late");
103
+ const raced = await Promise.race([
104
+ registry.restrictOwner.then(() => true, () => false),
105
+ new Promise<typeof late>((resolve) => setTimeout(() => resolve(late), 10_000)),
106
+ ]);
107
+ if (raced === late) console.warn("[hub] registry owner restriction still running after 10s — continuing boot");
100
108
  } catch (error) {
101
109
  console.warn("[hub] registry owner restriction failed:", error);
102
110
  }
@@ -505,7 +513,9 @@ app.post(
505
513
  },
506
514
  );
507
515
 
508
- app.get("/api/network", (_req, res) => res.json({ configFile, devices: monitor.network() }));
516
+ app.get("/api/network", (_req, res) =>
517
+ res.json({ configFile, devices: monitor.network(), relay: mux.relayStats() }), // r10 h1-4: relay drop counters surfaced to the operator
518
+ );
509
519
  // Devices are configured in dpi-network.yaml and `just net register`; the hub only reads them.
510
520
  app.post(
511
521
  "/api/devices/:id/check",
@@ -8,6 +8,7 @@ import { randomUUID } from "node:crypto";
8
8
  import type { Request, Response } from "express";
9
9
  import { DpiError } from "../../../../dpi-sdk/src/errors.js";
10
10
  import { transportFor } from "./transport.js";
11
+ import { reassembledFrameBytes } from "./tunnel-transport.js";
11
12
  import type { MuxFrame } from "../../../../dpi-sdk/src/api.js";
12
13
  import type { NetworkRegistry } from "../../../../dpi-sdk/src/node/registry.js";
13
14
  import type { DeviceMonitor, TunnelTransportSource } from "./monitor.js";
@@ -52,6 +53,32 @@ const RELAY_TREE_CAP_BYTES = 4 * 1024 * 1024;
52
53
  * canonical ones) and measure the tree payload exactly as it does, so every
53
54
  * tree the monitor admits also passes here and nothing it rejects does. */
54
55
  const TREE_RELAY_MAX_SESSIONS = 2000;
56
+ /** Run-11 h1-1 (Unit A; cold-review r11 f1): the relay wrapper's EXACT byte
57
+ * overhead over the frame's own serialization —
58
+ * `{"sub":` (7) + JSON-escaped key + `,"frame":` (9) + `}` (1) = 17 + key
59
+ * bytes. Used by the raw-bytes pre-check in follow() so it faults only
60
+ * frames the authoritative stringify check would also reject. A CONSTANT
61
+ * allowance ≥ the real overhead inverted that direction and faulted LEGAL
62
+ * near-cap chunked frames (the ~480 B band under the cap). Exact math keeps
63
+ * the pre-check admission-identical to the authoritative check for every
64
+ * canonical (device-JSON.stringify'd) frame; only non-canonical raw bytes
65
+ * (hand-crafted whitespace) can diverge — and then the belt-and-braces
66
+ * byteLength(text) check after the single stringify still gates admission. */
67
+ function relayWrapperOverhead(key: string): number {
68
+ return 17 + Buffer.byteLength(JSON.stringify(key));
69
+ }
70
+ /** Run-11 h4-5 (Unit A): per-subscription token bucket for `tree` frames —
71
+ * capacity 4, refill 2/s, reset to full at every (re)connect (see
72
+ * follow()). Trees are whole-document snapshots that supersede each other,
73
+ * so a device pushing a back-to-back burst costs one multi-MiB
74
+ * stringify+copy per frame per tab for a view the next tree replaces
75
+ * anyway. Coalesced frames are counted (relayStats().coalescedTreeFrames →
76
+ * GET /api/network, next to droppedTreeFrames) and the next tree (a healthy
77
+ * device re-pushes on state change within ~500 ms) delivers the fresh view.
78
+ * Only `tree` is gated — snapshot/agents are handshake payloads and every
79
+ * other frame type stays unlimited (scope = h4-5 trees). */
80
+ const TREE_BUCKET_CAPACITY = 4;
81
+ const TREE_BUCKET_REFILL_PER_SEC = 2;
55
82
 
56
83
  const sseBudget = new ByteBudget("hub-sse", HUB_BUFFER_BUDGET_BYTES);
57
84
 
@@ -122,12 +149,28 @@ export class StreamMux {
122
149
  /** Run-9 U5/U8: device-authored tree frames dropped at the relay seam for
123
150
  * exceeding the monitor-mirror bounds — surfaced via relayStats(). */
124
151
  private droppedTreeFrames = 0;
152
+ /** Run-11 h4-5 (Unit A): tree frames coalesced away by the per-follow
153
+ * token bucket (see follow() — the bucket itself is LOCAL to each loop,
154
+ * cold-review r11 f2, so there is no Map state here to leak or share). */
155
+ private coalescedTreeFrames = 0;
125
156
 
126
157
  constructor(
127
158
  private readonly registry: NetworkRegistry,
128
159
  private readonly monitor: DeviceMonitor,
129
160
  private readonly options: { budget?: ByteBudget } = {},
130
- ) {}
161
+ ) {
162
+ // r10 h1-5: ONE network snapshot + ONE serialization per monitor change,
163
+ // shared by every open tab — the old per-tab listener rebuilt and
164
+ // re-stringified the whole network view (≤32×256KiB trees) once per tab
165
+ // per change. The invalidator fires once; the first tab's send lazily
166
+ // rebuilds the cached text.
167
+ this.monitor.onChange(() => {
168
+ this.networkText = undefined;
169
+ });
170
+ }
171
+
172
+ /** Cached `data:` payload for the network fan-out (r10 h1-5). */
173
+ private networkText?: string;
131
174
 
132
175
  private readerCount(deviceId: string): number {
133
176
  const mux = this.readersByDevice.get(deviceId) ?? 0;
@@ -147,8 +190,14 @@ export class StreamMux {
147
190
  }
148
191
 
149
192
  /** Read-only relay admission counters for tests and diagnostics. */
150
- relayStats(): { droppedTreeFrames: number } {
151
- return { droppedTreeFrames: this.droppedTreeFrames };
193
+ relayStats(): { droppedTreeFrames: number; coalescedTreeFrames: number } {
194
+ return {
195
+ droppedTreeFrames: this.droppedTreeFrames,
196
+ // run-11 h4-5 (Unit A): token-bucket coalescing, surfaced on
197
+ // GET /api/network next to droppedTreeFrames (main.ts spreads this
198
+ // object verbatim into the relay payload — no shape change needed).
199
+ coalescedTreeFrames: this.coalescedTreeFrames,
200
+ };
152
201
  }
153
202
 
154
203
  /** Wire the tunnel dispatcher source (main.ts, after construction). */
@@ -203,8 +252,13 @@ export class StreamMux {
203
252
  this.streams.set(streamId, stream);
204
253
  stream.send({ sub: "hello", frame: { type: "stream", streamId } });
205
254
  if (closed) return;
206
- const pushNetwork = () =>
207
- stream.send({ sub: "network", frame: { type: "network", devices: this.monitor.network() } });
255
+ const pushNetwork = () => {
256
+ const text = (this.networkText ??= JSON.stringify({
257
+ sub: "network",
258
+ frame: { type: "network", devices: this.monitor.network() },
259
+ }));
260
+ stream.send({ sub: "network", frame: { type: "network", devices: [] } }, text);
261
+ };
208
262
  pushNetwork();
209
263
  if (closed) return;
210
264
  off = this.monitor.onChange(pushNetwork);
@@ -284,9 +338,39 @@ export class StreamMux {
284
338
  signal: AbortSignal,
285
339
  ) {
286
340
  const backoff = new Backoff(RECONNECT_BACKOFF_S);
341
+ // run-11 h4-5 (Unit A; cold-review r11 f2 rework): the tree token bucket
342
+ // is LOCAL to this follow() loop — one budget per (tab × sub) reader. A
343
+ // Map keyed by sub.key shared across follow() loops let a second tab on
344
+ // the same key drain this loop's budget, and the entry's deletion on the
345
+ // OTHER tab's exit lazily re-armed a FULL bucket here — bypassable
346
+ // shaping. Local state has neither seam. Reset to full at every
347
+ // (re)connect: the device's initial tree (a tab's first full view after a
348
+ // flap) always relays.
349
+ let treeTokens = TREE_BUCKET_CAPACITY;
350
+ let treeTokensAt = Date.now();
351
+ /** Consume one tree token (refill TREE_BUCKET_REFILL_PER_SEC, clamped at
352
+ * capacity; fractional idle credit kept on refuse). False = exhausted —
353
+ * the caller coalesces (snapshots supersede each other; the next tree
354
+ * delivers a strictly fresher view). */
355
+ const admitTree = (): boolean => {
356
+ const now = Date.now();
357
+ const tokens = Math.min(
358
+ TREE_BUCKET_CAPACITY,
359
+ treeTokens + ((now - treeTokensAt) / 1000) * TREE_BUCKET_REFILL_PER_SEC,
360
+ );
361
+ treeTokensAt = now;
362
+ if (tokens < 1) {
363
+ treeTokens = tokens;
364
+ return false;
365
+ }
366
+ treeTokens = tokens - 1;
367
+ return true;
368
+ };
287
369
  while (!signal.aborted) {
288
370
  await this.monitor.whenOnline(sub.deviceId, signal);
289
371
  if (signal.aborted) return;
372
+ treeTokens = TREE_BUCKET_CAPACITY;
373
+ treeTokensAt = Date.now();
290
374
  const device = this.registry.get(sub.deviceId);
291
375
  const transport = device ? transportFor(device, this.tunnel) : undefined;
292
376
  if (!transport?.available) return;
@@ -297,12 +381,6 @@ export class StreamMux {
297
381
  )) {
298
382
  if (!checkDeviceFrame(frame))
299
383
  throw new DpiError("invalid", "Invalid device stream frame");
300
- // run-8 U5: admission bound at the relay seam — checkDeviceFrame is
301
- // shape-only, so agent-event frames rode the ~16MiB transport
302
- // ceiling into per-tab stringify (B4 capped TREE frames at the
303
- // monitor seam only). Serialize ONCE here, admit on its byte size,
304
- // and hand the same string to every tab.
305
- const text = JSON.stringify({ sub: sub.key, frame });
306
384
  // snapshot/agents/network carry whole-document payloads by design
307
385
  // (a session snapshot includes entries + inbox) and legitimately
308
386
  // exceed the per-event cap — capping them turned a large session's
@@ -311,7 +389,7 @@ export class StreamMux {
311
389
  frame.type === "tree" || frame.type === "snapshot" || frame.type === "agents"
312
390
  ? RELAY_TREE_CAP_BYTES
313
391
  : RELAY_FRAME_CAP_BYTES;
314
- if (Buffer.byteLength(text) > cap) {
392
+ const relayCapFault = () =>
315
393
  stream.send({
316
394
  sub: sub.key,
317
395
  frame: {
@@ -322,15 +400,16 @@ export class StreamMux {
322
400
  },
323
401
  },
324
402
  });
325
- continue;
326
- }
327
403
  // Run-9 U5/U8: the monitor seam (state owner) degrades oversized
328
404
  // trees — but the RELAY is a pipe, and the tunnel chunk path exists
329
405
  // precisely to deliver legitimately large trees (tunnel-pacing
330
406
  // contract: a 1.5MB chunked tree arrives intact). The pipe's byte
331
- // cap is RELAY_TREE_CAP_BYTES above; here we mirror only the
332
- // session-COUNT policy. Byte parity with the monitor was tried and
333
- // reverted: it dropped the chunked-tree contract.
407
+ // cap is RELAY_TREE_CAP_BYTES; here we mirror only the session-COUNT
408
+ // policy. Byte parity with the monitor was tried and reverted: it
409
+ // dropped the chunked-tree contract. A count violation faults —
410
+ // never silently drops (r9 relay contract), never consumes a token,
411
+ // and the subscription survives (skip, not cut). Checked FIRST so
412
+ // both paths below share it (cold-review r11 f3 ordering).
334
413
  if (frame.type === "tree") {
335
414
  const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
336
415
  if (sessions.length > TREE_RELAY_MAX_SESSIONS) {
@@ -348,6 +427,63 @@ export class StreamMux {
348
427
  continue;
349
428
  }
350
429
  }
430
+ // run-11 h1-1 (Unit A; cold-review r11 f1/f3 rework): chunked
431
+ // (tunnel) frames already know their exact serialized size
432
+ // (reassembledFrameBytes, recorded at the reassembly push seam in
433
+ // tunnel-transport). For them EVERY admission decision precedes the
434
+ // one serialization: an oversized multi-MiB frame faults on
435
+ // raw + EXACT wrapper overhead (relayWrapperOverhead — a constant
436
+ // allowance ≥ the real overhead faulted LEGAL near-cap frames), and
437
+ // a burst tree the token bucket coalesces away costs ZERO
438
+ // stringify. For canonical device JSON (the device's own
439
+ // JSON.stringify — the normal case) the pre-check faults exactly
440
+ // what the authoritative check would; hand-crafted non-canonical
441
+ // raw bytes can only diverge into an early fault (self-harm) or a
442
+ // late catch — the belt-and-braces byteLength(text) check below
443
+ // still gates every admission, so nothing over-cap ever relays.
444
+ const rawBytes = reassembledFrameBytes.get(frame);
445
+ if (rawBytes !== undefined) {
446
+ if (rawBytes + relayWrapperOverhead(sub.key) > cap) {
447
+ relayCapFault();
448
+ continue;
449
+ }
450
+ if (frame.type === "tree" && !admitTree()) {
451
+ // run-11 h4-5 (Unit A): bucket exhausted — coalesce (drop) this
452
+ // legal snapshot silently and count it: unlike the faults above
453
+ // (protocol violations worth surfacing), this is rate shaping of
454
+ // frames that supersede each other; the next tree (a healthy
455
+ // device re-pushes on state change within ~500 ms) delivers a
456
+ // strictly fresher view. Runs AFTER every admission check, so
457
+ // violations still fault and never consume a token.
458
+ this.coalescedTreeFrames++;
459
+ continue;
460
+ }
461
+ // run-8 U5 + h1-1: serialize ONCE — the only stringify on this
462
+ // path — admit on its byte size, hand the same string to the
463
+ // writer. Belt-and-braces after the pre-check: non-canonical raw
464
+ // bytes can re-stringify LONGER than raw (exponent-form numbers,
465
+ // e.g. 1e-9 → 0.000000001), so this check is still load-bearing.
466
+ const text = JSON.stringify({ sub: sub.key, frame });
467
+ if (Buffer.byteLength(text) > cap) {
468
+ relayCapFault();
469
+ continue;
470
+ }
471
+ stream.send({ sub: sub.key, frame }, text);
472
+ if (frame.type === "hello") backoff.reset();
473
+ continue;
474
+ }
475
+ // run-8 U5: inline/LAN frames have no raw-bytes side-channel — this
476
+ // stays the authoritative path: serialize ONCE here, admit on its
477
+ // byte size, and hand the same string to every tab.
478
+ const text = JSON.stringify({ sub: sub.key, frame });
479
+ if (Buffer.byteLength(text) > cap) {
480
+ relayCapFault();
481
+ continue;
482
+ }
483
+ if (frame.type === "tree" && !admitTree()) {
484
+ this.coalescedTreeFrames++;
485
+ continue;
486
+ }
351
487
  stream.send({ sub: sub.key, frame }, text);
352
488
  if (frame.type === "hello") backoff.reset();
353
489
  }
@@ -42,7 +42,10 @@ import type { DeviceTransport, TransportRequest, TransportResponse } from "./tra
42
42
  * (defense in depth — the device already sanitizes before putting it on the wire). */
43
43
  const safeHeaderValue = (value: unknown): string | undefined => {
44
44
  if (typeof value !== "string") return undefined;
45
- const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
45
+ const clean = value
46
+ .replace(/[^\x20-\x7E]/g, "")
47
+ .slice(0, 200)
48
+ .trim();
46
49
  return clean.length > 0 ? clean : undefined;
47
50
  };
48
51
  import type { TunnelConnection, TunnelServer } from "./tunnel.js";
@@ -72,9 +75,23 @@ interface Subscription {
72
75
  onAbort: () => void;
73
76
  }
74
77
 
78
+ /** run-11 h1-1 (Unit A): exact serialized size of REASSEMBLED chunked
79
+ * tunnel-data frames, recorded once at the reassembled push seam in
80
+ * `route()`. Downstream consumers (mux relay admission, `relayBytes` budget
81
+ * charging) read the real byte size instead of re-serializing multi-MiB
82
+ * frames to learn it — one serialization per frame on the whole hot path.
83
+ * WeakMap on purpose: the size lives and dies with the frame object, so
84
+ * there is no manual lifetime to manage. Inline/LAN frames get no entry:
85
+ * their size is only knowable by serializing, which the fallback paths do. */
86
+ export const reassembledFrameBytes = new WeakMap<Frame, number>();
87
+
75
88
  /** run-8 U8: the byte size a relayed frame holds in a viewer queue. One extra
76
89
  * serialization per device frame, bounded by the mux relay caps. */
77
90
  function relayBytes(frame: Frame): number {
91
+ // run-11 h1-1 (Unit A): reassembled (chunked) frames already know their
92
+ // exact size — charge it without a second multi-MiB serialization.
93
+ const raw = reassembledFrameBytes.get(frame);
94
+ if (raw !== undefined) return raw;
78
95
  try {
79
96
  return Buffer.byteLength(JSON.stringify(frame));
80
97
  } catch {
@@ -409,15 +426,22 @@ export class TunnelDispatcher {
409
426
  } as unknown as Frame);
410
427
  return;
411
428
  }
412
- if (out.done)
413
- sub.push(
414
- checkDeviceFrame(out.value)
415
- ? out.value
416
- : {
417
- type: "fault",
418
- error: { code: "invalid", message: "Invalid device stream frame" },
419
- },
420
- );
429
+ if (out.done) {
430
+ if (checkDeviceFrame(out.value)) {
431
+ // run-11 h1-1 (Unit A): record the reassembler's exact byte count
432
+ // at the push seam — chunked tunnel-data frames only (this is the
433
+ // sole reassembly path for them). Everything downstream of this
434
+ // subscription queue (mux relay admission, relayBytes charging)
435
+ // reads the WeakMap instead of re-serializing the frame.
436
+ if (out.rawBytes !== undefined) reassembledFrameBytes.set(out.value, out.rawBytes);
437
+ sub.push(out.value);
438
+ } else {
439
+ sub.push({
440
+ type: "fault",
441
+ error: { code: "invalid", message: "Invalid device stream frame" },
442
+ });
443
+ }
444
+ }
421
445
  return;
422
446
  }
423
447
  return;
@@ -670,7 +694,10 @@ export class TunnelDispatcher {
670
694
  queue.push({
671
695
  frame: {
672
696
  type: "fault",
673
- error: { code: "invalid", message: "device stream exceeded this device's relay budget" },
697
+ error: {
698
+ code: "invalid",
699
+ message: "device stream exceeded this device's relay budget",
700
+ },
674
701
  } as unknown as Frame,
675
702
  reservation: null,
676
703
  });
@@ -154,6 +154,55 @@ export interface GitOpResult {
154
154
  prs?: { n: number; title: string; state: string; draft: boolean; branch: string; url: string }[];
155
155
  }
156
156
 
157
+
158
+ /** r10 h3-1: the SDK client is the trust-boundary reader — every hub leg is
159
+ * capped (transport.ts readBodyCapped 16MiB textual / 12MB binary), but this
160
+ * client buffered `response.text()` / `arrayBuffer()` whole. A compromised
161
+ * device answering a multi-GB body OOMs the operator's TUI / net scripts /
162
+ * browser export. Cap with hub parity: content-length precheck, then a
163
+ * byte-counting stream read that aborts at the ceiling. Isomorphic: no Buffer. */
164
+ const TEXT_BODY_MAX = 16 * 1024 * 1024;
165
+ const BINARY_BODY_MAX = 12 * 1024 * 1024;
166
+
167
+ async function readBodyCapped(response: Response, cap: number, what: string): Promise<Uint8Array> {
168
+ const declared = Number(response.headers.get("content-length") ?? "");
169
+ if (Number.isFinite(declared) && declared > cap)
170
+ throw new DpiError("invalid", `${what} over ${cap} bytes (content-length ${declared})`, 413);
171
+ const body = (response as { body?: ReadableStream<Uint8Array> | null }).body;
172
+ if (body && typeof body.getReader === "function") {
173
+ const reader = body.getReader();
174
+ const chunks: Uint8Array[] = [];
175
+ let total = 0;
176
+ for (;;) {
177
+ const { done, value } = await reader.read();
178
+ if (done) break;
179
+ total += value.byteLength;
180
+ if (total > cap) {
181
+ try {
182
+ await reader.cancel();
183
+ } catch {
184
+ /* already closed */
185
+ }
186
+ throw new DpiError("invalid", `${what} over ${cap} bytes`, 413);
187
+ }
188
+ chunks.push(value);
189
+ }
190
+ const merged = new Uint8Array(total);
191
+ let off = 0;
192
+ for (const c of chunks) {
193
+ merged.set(c, off);
194
+ off += c.byteLength;
195
+ }
196
+ return merged;
197
+ }
198
+ // No stream (mocks / very old runtimes): read once, then enforce the cap.
199
+ const fallback = what === "response body"
200
+ ? new TextEncoder().encode(await response.text())
201
+ : new Uint8Array(await response.arrayBuffer());
202
+ if (fallback.byteLength > cap) throw new DpiError("invalid", `${what} over ${cap} bytes`, 413);
203
+ return fallback;
204
+ }
205
+
157
206
  export class DpiClient {
158
207
  readonly baseUrl: string;
159
208
  constructor(
@@ -199,7 +248,8 @@ export class DpiClient {
199
248
  if (options.signal?.aborted) throw cause;
200
249
  throw new DpiError("offline", `Cannot reach ${this.baseUrl}`, 0, { cause });
201
250
  }
202
- const text = await response.text();
251
+ // r10 h3-1: capped read — the hub legs cap at 16MiB textual; mirror here.
252
+ const text = new TextDecoder().decode(await readBodyCapped(response, TEXT_BODY_MAX, "response body"));
203
253
  let data: unknown;
204
254
  try {
205
255
  data = text ? JSON.parse(text) : undefined;
@@ -436,7 +486,8 @@ export class DpiClient {
436
486
  response.status,
437
487
  );
438
488
  }
439
- const bytes = new Uint8Array(await response.arrayBuffer());
489
+ // r10 h3-1: binary leg — 12MB parity with the hub's readBodyCapped.
490
+ const bytes = await readBodyCapped(response, BINARY_BODY_MAX, "export body");
440
491
  // `filename="quoted"` (the device's form) or a bare token, per RFC 6266.
441
492
  const disposition = response.headers.get("content-disposition") ?? "";
442
493
  const quoted = /filename="((?:[^"\\]|\\.)*)"/i.exec(disposition)?.[1];
@@ -195,8 +195,12 @@ export function rsync(device: NetDevice, sources: string[], dest: string, cwd: s
195
195
  /** The full exe.dev argv, built explicitly from guarded args (pure, testable). */
196
196
  export function exeDevArgv(args: string[]): string[] {
197
197
  for (const a of args)
198
- if (!a || !EXE_ARG_RE.test(a))
199
- throw Error(`exe.dev argument rejected (allowed charset [A-Za-z0-9._=-], no whitespace/metacharacters): ${JSON.stringify(a)}`);
198
+ if (!a || !EXE_ARG_RE.test(a) || /^-[^-]/.test(a) || a === "-" || a === "--")
199
+ // r10 h3-4: ssh re-parses single-dash words as ITS options (-o, -L…) —
200
+ // those die at the sink. Double-dash `--name=x` flags are exe.dev's own
201
+ // grammar (call sites pass them as constants) and stay legal; the
202
+ // charset gate already blocks everything else.
203
+ throw Error(`exe.dev argument rejected (allowed charset [A-Za-z0-9._=-], no whitespace/metacharacters, no single-dash options): ${JSON.stringify(a)}`);
200
204
  return ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15", "exe.dev", ...args, "--json"];
201
205
  }
202
206
 
@@ -10,7 +10,7 @@
10
10
  * crashes the caller: it reports and returns false so the boot can continue and
11
11
  * a later pass can retry.
12
12
  */
13
- import { chmodSync, closeSync, fsyncSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
13
+ import { chmodSync, closeSync, fsyncSync, openSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
14
14
  import { execFile } from "node:child_process";
15
15
  import { basename, dirname, join } from "node:path";
16
16
  import { randomBytes } from "node:crypto";
@@ -114,6 +114,38 @@ export async function restrictDirToOwner(path: string, deps: RestrictDeps = {}):
114
114
  const tempSiblingName = (path: string) =>
115
115
  join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);
116
116
 
117
+ /** r10 h3-2: a SIGKILL between writeSync and renameSync strands a
118
+ * secret-bearing temp sibling that nothing ever cleaned — random names never
119
+ * collide, so one stale copy of EVERY rotated-away credential could
120
+ * accumulate. Prune the target's stale temps (grace window keeps a concurrent
121
+ * writer's live temp safe) at the top of every atomic write. */
122
+ const TEMP_GRACE_MS = 60 * 60 * 1000;
123
+ function pruneStaleTemps(path: string, deps: RestrictDeps = {}): void {
124
+ if ((deps.platform ?? process.platform) === "win32") {
125
+ // win32 rename-refusal races make pruning riskier than the residue; the
126
+ // 0700 dir already bounds exposure there.
127
+ return;
128
+ }
129
+ const dir = dirname(path);
130
+ const prefix = `.${basename(path)}.`;
131
+ let names: string[];
132
+ try {
133
+ names = readdirSync(dir);
134
+ } catch {
135
+ return;
136
+ }
137
+ const now = Date.now();
138
+ for (const name of names) {
139
+ if (!name.startsWith(prefix) || !name.endsWith(".tmp")) continue;
140
+ try {
141
+ const full = join(dir, name);
142
+ if (now - statSync(full).mtimeMs > TEMP_GRACE_MS) rmSync(full, { force: true });
143
+ } catch {
144
+ /* someone else's temp racing us — leave it */
145
+ }
146
+ }
147
+ }
148
+
117
149
  /**
118
150
  * Atomic write for credential files (orca STA-3941 / paseo writePrivateFileAtomicSync):
119
151
  * temp file 0600 + fsync + rename, so readers only ever see the old bytes or the
@@ -131,6 +163,7 @@ export async function writePrivateFileAtomic(
131
163
  deps: RestrictDeps = {},
132
164
  ): Promise<boolean> {
133
165
  ensurePrivateDir(dirname(path));
166
+ pruneStaleTemps(path, deps);
134
167
  const temp = (deps.tempName ?? tempSiblingName)(path);
135
168
  let fd: number | undefined;
136
169
  try {
@@ -297,7 +297,11 @@ export class NetworkRegistry {
297
297
  },
298
298
  ) {
299
299
  const sets = ["last_status=?", "last_error=?"];
300
- const values: (string | number | null)[] = [patch.status, patch.error ?? null];
300
+ // r10 h3-3: last_error is device-authored too (error.message from the LAN
301
+ // leg is bounded only by the 16MiB transport cap) — the info/tree caps
302
+ // above must not leave this column as the one uncapped rewrite target.
303
+ const errCap = (e: string | null | undefined) => (e == null ? null : e.slice(0, 2048));
304
+ const values: (string | number | null)[] = [patch.status, errCap(patch.error)];
301
305
  if (patch.seenAt !== undefined) sets.push("last_seen_at=?"), values.push(patch.seenAt);
302
306
  // run-7 B4: device-authored JSON is untrusted — cap what a hostile device
303
307
  // can rewrite into the registry row every 10s (the uiSet sibling caps UI
@@ -15,6 +15,10 @@ export const CHUNK_RAW_BYTES = 65_536;
15
15
  export const MAX_CHUNKS_PER_MESSAGE = 256;
16
16
  /** Maximum logical message size including envelope. 16 MiB. */
17
17
  export const LOGICAL_MESSAGE_MAX_BYTES = 16_777_216;
18
+ // Run-11 h1-2 layer 1 — per-event transport gate: a serialized SSE frame over
19
+ // this is FAULTED by the hub's stream send(), never queued (mux.ts "Stream
20
+ // event exceeds ..."), and the hub's REST legs read-cap bodies at the same
21
+ // number (transport.ts readBodyCapped).
18
22
  /** Handshake/control/fault frames must fit without chunking. 4 KiB. */
19
23
  export const CONTROL_FRAME_MAX_BYTES = 4_096;
20
24
  /** Per-message reassembly timeout. 30 s. */
@@ -23,11 +27,28 @@ export const REASSEMBLY_TIMEOUT_MS = 30_000;
23
27
  export const REASSEMBLY_CONCURRENT_PER_CONNECTION = 4;
24
28
  /** Total reassembly + outbound queue budget per device connection. 32 MiB. */
25
29
  export const CONNECTION_BUFFER_BUDGET_BYTES = 33_554_432;
30
+ // Run-11 h1-2 layer 2 — per-writer/per-connection queue bound: every paced SSE
31
+ // writer also holds a LOCAL "sse-viewer" ByteBudget at this same size bounding
32
+ // its active+queued events (node/sse-writer.ts), so one slow tab cannot pin
33
+ // more than 32 MiB before its per-socket cut (layer 3) fires.
26
34
  /** Total hub-wide budget (reassembly + outbound queues + pending REST). 64 MiB. */
27
35
  export const HUB_BUFFER_BUDGET_BYTES = 67_108_864;
36
+ // Run-11 h1-2 layer 4 — hub-wide shared budget: ONE ByteBudget("hub") per hub
37
+ // process (main.ts) is threaded through the stream mux (every browser tab
38
+ // writer) AND the tunnel dispatcher (device reassembly + relay/REST queues),
39
+ // so aggregate fan-out across tabs and devices stays bounded by 64 MiB total.
28
40
 
29
41
  /** Hub → browser SSE buffered-output cap before the viewer is ended. 4 MB. */
30
42
  export const SSE_HUB_VIEWER_BYTES = 4_000_000;
43
+ // Run-11 h1-2 layer 3 — per-socket: this is the socket output cap
44
+ // (writableLength/buffered amount), NOT a logical event size — a viewer that
45
+ // keeps it full is ended (pacedSseWriter maxBufferedBytes) instead of letting
46
+ // the kernel queue grow without bound. Effective SSE chain, in order:
47
+ // per-event 16 MiB (LOGICAL_MESSAGE_MAX_BYTES) → queued ≤32 MiB per writer
48
+ // local ByteBudget (CONNECTION_BUFFER_BUDGET_BYTES; each device connection
49
+ // additionally 32 MiB) → 4 MB per socket (SSE_HUB_VIEWER_BYTES) → 64 MiB
50
+ // hub-wide shared (HUB_BUFFER_BUDGET_BYTES, all tab writers + device
51
+ // reassembly/relay queues). Docs: docs/verification.md "Effective SSE bounds".
31
52
  /** Hub ↔ device WS buffered-output cap per direction before close(1011). 4 MB. */
32
53
  export const WS_BACKPRESSURE_BYTES = 4_000_000;
33
54
  /**