my-durable 0.0.76 → 0.0.78

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 (31) hide show
  1. package/apps/dpi-backend/src/archived.ts +54 -9
  2. package/apps/dpi-backend/src/git.ts +178 -78
  3. package/apps/dpi-backend/src/pairing.ts +3 -1
  4. package/apps/dpi-backend/src/salvage.ts +70 -4
  5. package/apps/dpi-backend/src/store.ts +273 -15
  6. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-h81haD43.css → index-BF6mtGF4.css} +1 -1
  7. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DAF9D074.js +82 -0
  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/git-rules.ts +38 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-store.ts +64 -19
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +26 -2
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GitPanel.vue +46 -2
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +11 -3
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +25 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +44 -4
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +52 -6
  17. package/apps/dpi-sdk/src/api.ts +5 -1
  18. package/apps/dpi-sdk/src/models.ts +180 -19
  19. package/apps/dpi-sdk/src/node/config.ts +13 -2
  20. package/apps/dpi-sdk/src/node/ops.ts +33 -6
  21. package/apps/dpi-sdk/src/node/registry-migration.ts +76 -3
  22. package/apps/dpi-sdk/src/node/registry.ts +5 -2
  23. package/apps/dpi-sdk/src/transcript.ts +1 -0
  24. package/apps/dpi-tui/src/app.ts +7 -6
  25. package/apps/dpi-tui/src/pairing.ts +15 -11
  26. package/apps/dpi-tui/src/pickers.ts +11 -8
  27. package/apps/dpi-tui/src/sanitize.ts +5 -0
  28. package/apps/dpi-tui/src/views.ts +16 -16
  29. package/apps/dpi-tui/src/welcome.ts +9 -4
  30. package/package.json +1 -1
  31. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +0 -82
@@ -7,8 +7,8 @@
7
7
  <meta name="referrer" content="no-referrer" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icons/durable-pi.svg" />
9
9
  <title>Durable Pi | Network</title>
10
- <script type="module" crossorigin src="/assets/index-BmxTF5DB.js"></script>
11
- <link rel="stylesheet" crossorigin href="/assets/index-h81haD43.css">
10
+ <script type="module" crossorigin src="/assets/index-DAF9D074.js"></script>
11
+ <link rel="stylesheet" crossorigin href="/assets/index-BF6mtGF4.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="app"></div>
@@ -0,0 +1,38 @@
1
+ // One place for the FE's copy of the device's git-containment rule.
2
+ // A device serves git ONLY under its configured start dirs (the device stays
3
+ // the enforcer — this is the advisory pre-check that keeps doomed requests off
4
+ // the wire). Kept import-free so both the store and the client wrapper can use
5
+ // it without a cycle.
6
+ export interface GitDeviceFacts {
7
+ startDirs?: unknown;
8
+ platform?: unknown;
9
+ }
10
+
11
+ /** Normalised spelling used for the comparison (win32: slash-fold + case-fold). */
12
+ export function normGitPath(p: string, win: boolean): string {
13
+ const trimmed = String(p ?? "").trim();
14
+ return win
15
+ ? trimmed.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase()
16
+ : trimmed.replace(/\/+$/, "");
17
+ }
18
+
19
+ /** True when the device's start dirs are unknown (allow: the device decides) or
20
+ * `path` IS a start dir / lives under one. */
21
+ export function pathUnderStartDirs(info: GitDeviceFacts | undefined, path: string): boolean {
22
+ const dirs = info?.startDirs;
23
+ if (!Array.isArray(dirs) || dirs.length === 0) return true;
24
+ const win = String(info?.platform ?? "").startsWith("win32");
25
+ const a = normGitPath(path, win);
26
+ return dirs.some((raw) => {
27
+ const b = normGitPath(String(raw), win);
28
+ return !!b && (a === b || a.startsWith(win ? `${b}\\` : `${b}/`));
29
+ });
30
+ }
31
+
32
+ /** Operator-facing sentence naming the roots the device actually serves. */
33
+ export function outsideStartDirsReason(info: GitDeviceFacts | undefined): string {
34
+ const dirs = Array.isArray(info?.startDirs) ? (info!.startDirs as unknown[]).map(String) : [];
35
+ return dirs.length
36
+ ? `outside the device's start dirs (it serves: ${dirs.join(", ")})`
37
+ : "outside the device's start dirs";
38
+ }
@@ -6,6 +6,7 @@ import { reactive, watch } from "vue";
6
6
  import type { GitStatus } from "@sdk/client";
7
7
  import { deviceClient } from "./hub";
8
8
  import { network } from "./store";
9
+ import { pathUnderStartDirs } from "./git-rules";
9
10
 
10
11
  export interface GitEntry {
11
12
  at: number; // last settled fetch (0 = never)
@@ -17,6 +18,17 @@ export interface GitEntry {
17
18
 
18
19
  const entries = new Map<string, GitEntry>();
19
20
  const inflight = new Map<string, Promise<void>>();
21
+ /** run-7 D2: the module-global entry map had NO ceiling — a hostile device's
22
+ * status-batch response (or a hostile tree's cwds) grew it forever until the
23
+ * tab OOMs. Same discipline as the SDK caps: bounded slots, oldest evicted. */
24
+ const MAX_GIT_ENTRIES = 2000;
25
+ function capEntries() {
26
+ while (entries.size > MAX_GIT_ENTRIES) {
27
+ const oldest = entries.keys().next().value as string | undefined;
28
+ if (oldest === undefined) break;
29
+ entries.delete(oldest);
30
+ }
31
+ }
20
32
 
21
33
  /** A device's git surface is bounded by its start dirs (R21, index 400s): a
22
34
  * project left over from OTHER start dirs answers 400 on the device, and
@@ -28,16 +40,29 @@ function gitPathAllowed(deviceId: string, path: string): boolean {
28
40
  const dev = network.devices.value.find((d) => d.id === deviceId) as
29
41
  | { info?: { startDirs?: unknown; platform?: unknown } }
30
42
  | undefined;
31
- const dirs = dev?.info?.startDirs;
32
- if (!Array.isArray(dirs) || dirs.length === 0) return true;
33
- const win = String(dev?.info?.platform ?? "").startsWith("win32");
34
- const norm = (p: string) =>
35
- win ? p.trim().replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase() : p.trim().replace(/\/+$/, "");
36
- const a = norm(path);
37
- return dirs.some((raw) => {
38
- const b = norm(String(raw));
39
- return !!b && (a === b || a.startsWith(win ? b + "\\" : b + "/"));
40
- });
43
+ // One rule, shared with the client wrapper (client/git-rules.ts).
44
+ return pathUnderStartDirs(dev?.info, path);
45
+ }
46
+
47
+ /**
48
+ * run-8 (live console report): panels that call gitOp DIRECTLY (the commit
49
+ * log, PR list, turn list) skipped the pre-check above, so a project left over
50
+ * from other start dirs — or a plain non-repo project — produced a 400 storm
51
+ * on every mount and every network frame. Exported so every git caller asks
52
+ * the same question. `reason` is the operator-facing sentence.
53
+ */
54
+ export function gitAllowedFor(
55
+ deviceId: string,
56
+ path: string,
57
+ ): { ok: true } | { ok: false; reason: string } {
58
+ if (!gitPathAllowed(deviceId, path)) return { ok: false, reason: "outside the device's start dirs" };
59
+ const entry = gitEntry(deviceId, path);
60
+ // cold-3 L9: `repo:false` is only advisory — a folder that became a repo
61
+ // after the page loaded (git init) must be reachable, or the panel reporting
62
+ // it can never refresh. A stale verdict stops blocking after 5s.
63
+ if (entry.status && entry.status.repo === false && Date.now() - entry.at < 5_000)
64
+ return { ok: false, reason: "not a git repository" };
65
+ return { ok: true };
41
66
  }
42
67
 
43
68
  /** Settle an entry from either a real status or the batch's `{error}` shape. */
@@ -58,14 +83,28 @@ function settleEntry(e: GitEntry, s: GitStatus | { error: string } | undefined)
58
83
  export async function ensureGitBatch(deviceId: string, paths: string[]) {
59
84
  const stale = paths.filter((p) => !fresh(gitEntry(deviceId, p), staleMsForBatch) && gitPathAllowed(deviceId, p));
60
85
  if (!stale.length) return;
61
- try {
62
- const map = await deviceClient(deviceId).gitStatusBatch(stale, { timeoutMs: 60_000 });
63
- for (const [p, s] of Object.entries(map)) {
64
- settleEntry(gitEntry(deviceId, p), s as GitStatus | { error: string });
86
+ // run-7 D2: (a) the device truncates at 50 paths — chunk so every stale
87
+ // path actually settles (beyond-50 paths used to ride every batch forever);
88
+ // (b) 10 chunks max per pass keeps a hostile tree from fanning requests.
89
+ for (let i = 0; i < stale.length && i < 500; i += 50) {
90
+ const chunk = stale.slice(i, i + 50);
91
+ try {
92
+ const map = (await deviceClient(deviceId).gitStatusBatch(chunk, { timeoutMs: 60_000 })) as Record<
93
+ string,
94
+ GitStatus | { error: string }
95
+ >;
96
+ // run-7 D2: settle ONLY the keys WE sent — the response map is hostile-
97
+ // device-controlled and used to be iterated wholesale, letting a device
98
+ // grow this tab's retained state with keys the FE never asked for.
99
+ for (const p of chunk) {
100
+ const s = map[p];
101
+ if (s !== undefined) settleEntry(gitEntry(deviceId, p), s);
102
+ }
103
+ } catch {
104
+ /* decorative: never surface batch failures */
65
105
  }
66
- } catch {
67
- /* decorative: never surface batch failures */
68
106
  }
107
+ capEntries();
69
108
  }
70
109
  const staleMsForBatch = 60_000;
71
110
 
@@ -84,8 +123,14 @@ export function wireGitAutoRefresh() {
84
123
  );
85
124
  if (!marks.length) continue;
86
125
  for (const key of [...entries.keys()]) {
87
- const [devId, cwd] = key.split("::");
88
- if (devId !== d.id || !cwd) continue;
126
+ // run-8 U4: decode at the FIRST '::' — a cwd containing '::' (legal
127
+ // POSIX bytes, device-controlled per R23) truncated the split() form at
128
+ // its own first '::', never refreshing the real entry and force-
129
+ // refreshing a phantom prefix entry on a matching prefix mark.
130
+ const sep = key.indexOf("::");
131
+ const devId = key.slice(0, sep);
132
+ const cwd = key.slice(sep + 2);
133
+ if (sep < 0 || !devId || devId !== d.id || !cwd) continue;
89
134
  const e = entries.get(key)!;
90
135
  if (!marks.some((m) => cwd === m.root || cwd.startsWith(m.root + "/") || cwd.startsWith(m.root + "\\"))) continue;
91
136
  if (e.loading || now - e.at < 4000) continue; // throttle: bursts coalesce
@@ -135,7 +180,7 @@ export async function ensureGit(
135
180
  if (!gitPathAllowed(deviceId, cwd)) {
136
181
  settleEntry(e, { error: "outside the device's start dirs" });
137
182
  return;
138
- }
183
+ } capEntries();
139
184
  const running = inflight.get(k);
140
185
  if (running) return running;
141
186
  const first = e.status === null && !e.error;
@@ -3,14 +3,15 @@
3
3
  import { DpiClient } from "@sdk/client";
4
4
  import { DpiError } from "@sdk/errors";
5
5
  import type { ErrorCode, NetworkDevice } from "@sdk/api";
6
- import { notify } from "./store";
6
+ import { network, notify } from "./store";
7
+ import { outsideStartDirsReason, pathUnderStartDirs, type GitDeviceFacts } from "./git-rules";
7
8
 
8
9
  // R13 (R9-6.3 FE): the collapse of identical un-keyed creates is an accepted
9
10
  // retry-safety tradeoff — but it must be VISIBLE. The device's replay verdict
10
11
  // rides the tunnel envelope, the hub surfaces Idempotent-Replay, and the SDK
11
12
  // hook turns it into a toast naming the escape hatch (own idempotency-key).
12
13
  let replayToastAt = 0;
13
- export const deviceClient = (id: string) =>
14
+ const rawDeviceClient = (id: string) =>
14
15
  new DpiClient(`/api/devices/${encodeURIComponent(id)}`, undefined, {
15
16
  onIdempotentReplay: (path) => {
16
17
  // Replays can arrive in bursts (a re-connected UI re-firing identical
@@ -21,6 +22,29 @@ export const deviceClient = (id: string) =>
21
22
  },
22
23
  });
23
24
 
25
+ /**
26
+ * run-8 (live console report): EVERY git caller goes through here, so the
27
+ * start-dirs pre-check belongs here too — not only in the git store. Panels
28
+ * that call gitOp directly (commit log, PR list, toolbar ops) used to send
29
+ * doomed requests for a project left over from other start dirs and answer 400
30
+ * on every mount and every network frame. A rejected call never leaves the tab:
31
+ * the operator sees the verdict instead of a network error storm.
32
+ */
33
+ export const deviceClient = (id: string) => {
34
+ const client = rawDeviceClient(id);
35
+ const facts = (): GitDeviceFacts | undefined =>
36
+ (network.devices.value as { id: string; info?: GitDeviceFacts }[]).find((d) => d.id === id)?.info;
37
+ const rawGitOp = client.gitOp.bind(client);
38
+ client.gitOp = ((path: string, op: never, opts?: never) => {
39
+ const info = facts();
40
+ if (info && path && !pathUnderStartDirs(info, path)) {
41
+ return Promise.reject(new DpiError("invalid", `git ${op} skipped: ${outsideStartDirsReason(info)}`, 400));
42
+ }
43
+ return rawGitOp(path, op, opts);
44
+ }) as typeof client.gitOp;
45
+ return client;
46
+ };
47
+
24
48
  async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
25
49
  const r = await fetch(`/api${path}`, {
26
50
  method,
@@ -34,7 +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 { ensureGit, gitEntry, wireGitAutoRefresh } from "../client/git-store";
37
+ import { ensureGit, gitAllowedFor, gitEntry, wireGitAutoRefresh } from "../client/git-store";
38
38
  import { addWorktree as gitAddWorktree, createSessionOn } from "../client/worktree";
39
39
  import type { GitStatus } from "@sdk/client";
40
40
 
@@ -45,6 +45,17 @@ const devId = computed(() => props.deviceId ?? deviceId.value);
45
45
  const entry = computed(() => gitEntry(devId.value || "?", cwd.value || "?"));
46
46
  const status = computed(() => entry.value.status);
47
47
  const loading = computed(() => entry.value.loading);
48
+ /** run-8 (live report): a folder the device does not serve is NOT a transient
49
+ * failure — a retry re-runs the same local verdict forever. Render it as a
50
+ * callout that names the served dirs and says what would actually fix it. */
51
+ const unserved = computed(() => {
52
+ const e = entry.value;
53
+ if (!e.error || !/start dirs/i.test(e.error)) return "";
54
+ const dirs = (network.devices.value.find((d) => d.id === devId.value) as
55
+ | { info?: { startDirs?: unknown } }
56
+ | undefined)?.info?.startDirs;
57
+ return Array.isArray(dirs) && dirs.length ? dirs.map(String).join(", ") : "";
58
+ });
48
59
  const refreshing = computed(() => entry.value.refreshing);
49
60
  const error = computed(() => entry.value.error);
50
61
  const sessionId = computed(() => {
@@ -114,6 +125,12 @@ const prBusy = ref(false);
114
125
  const isGitHub = computed(() => /github\.com|gitlab/i.test(status.value?.remoteUrl ?? ""));
115
126
  const loadPRs = async () => {
116
127
  if (!devId.value || !cwd.value) return;
128
+ const allowed = gitAllowedFor(devId.value, cwd.value);
129
+ if (!allowed.ok) {
130
+ prs.value = [];
131
+ notify(`pull requests unavailable: ${allowed.reason}`);
132
+ return;
133
+ }
117
134
  prBusy.value = true;
118
135
  try {
119
136
  const r = await deviceClient(devId.value).gitOp(cwd.value, "pr-list");
@@ -346,6 +363,11 @@ async function op(
346
363
  extra: { message?: string; rebase?: boolean; setUpstream?: boolean; ref?: string } = {},
347
364
  ) {
348
365
  if (!devId.value || !cwd.value) return;
366
+ const allowed = gitAllowedFor(devId.value, cwd.value);
367
+ if (!allowed.ok) {
368
+ notify(`git ${name} skipped: ${allowed.reason}`);
369
+ return;
370
+ }
349
371
  busy.value = name;
350
372
  out.value = "";
351
373
  try {
@@ -813,6 +835,16 @@ let logAt = 0;
813
835
  async function loadLog(force = false) {
814
836
  if (!devId.value || !cwd.value) return;
815
837
  if (!force && commits.value.length && Date.now() - logAt < 120_000) return;
838
+ // run-8 (live console report): this call bypassed the store's pre-check, so a
839
+ // project outside the device's start dirs (or a plain non-repo project) sent
840
+ // log-list on every mount/frame and answered 400 each time. Ask first.
841
+ const allowed = gitAllowedFor(devId.value, cwd.value);
842
+ if (!allowed.ok) {
843
+ commits.value = [];
844
+ logError.value = allowed.reason;
845
+ logAt = Date.now();
846
+ return;
847
+ }
816
848
  logLoading.value = true;
817
849
  try {
818
850
  const r = await deviceClient(devId.value).gitOp(cwd.value, "log-list");
@@ -879,7 +911,19 @@ const laneX = (lane: number) => lane * 12 + 7;
879
911
  <template v-else>
880
912
  <p v-if="loading" class="hint">loading git…</p>
881
913
  <p v-else-if="refreshing" class="muted-line">refreshing…</p>
882
- <p v-if="error" class="message-error">{{ error }} <button @click="refresh()">retry</button></p>
914
+ <!-- run-8 (live report): a folder the DEVICE does not serve can never be
915
+ fixed by retrying — name the roots it does serve and the real fix. -->
916
+ <div v-if="unserved" class="message-error">
917
+ <p>
918
+ <strong>{{ cwd }}</strong> is not served by this device — its start dirs are
919
+ <code>{{ unserved }}</code>.
920
+ </p>
921
+ <p class="muted-line">
922
+ Add the folder to <code>DPI_START_DIRS</code> on the device (then restart it), or open a session under one of
923
+ the served folders. Retrying will not change this.
924
+ </p>
925
+ </div>
926
+ <p v-else-if="error" class="message-error">{{ error }} <button @click="refresh()">retry</button></p>
883
927
 
884
928
  <div v-if="status" :class="{ stale: !!error || !!refreshing }">
885
929
  <p v-if="!status.repo" class="hint">Not a git repository — run <code>git init</code> (or open a session inside a repo).</p>
@@ -147,6 +147,9 @@ export function scrubSecrets(value: string): string {
147
147
  // redacts before any decode). The anchor needs a non-word char before
148
148
  // "share" ("/share", "?shares="), so plain prose never triggers this.
149
149
  if (/(?:^|[^\w\s])shares?/i.test(out)) {
150
+ // run-7 D5: encoded capability shapes must not depend on decode depth —
151
+ // in share-anchor context, any dense %XX cluster is capability material.
152
+ out = out.replace(/(?:%[0-9a-fA-F]{2}){8,}/g, "<redacted>");
150
153
  // Keep the R19 M4 decision: a run whose FIRST char is preceded by
151
154
  // whitespace is prose, not a capability — everything else in anchor
152
155
  // context is redacted (callback sees the true run start; a lookbehind
@@ -173,9 +176,14 @@ export function scrubSecrets(value: string): string {
173
176
  let out = applyRules(value);
174
177
  // The decoded pass sees through %XX spellings of the separator, the first
175
178
  // token characters, or the segment itself; the sample is bounded (≤200
176
- // chars) so a pathological decode cannot explode it. Two rounds: the first
177
- // decode can still carry second-encoding (%2573…) for the second pass.
178
- for (let round = 0; round < 2; round++) {
179
+ // chars) so a pathological decode cannot explode it. run-7 D5 (leader-
180
+ // probed): 2 rounds was one depth short — a 3x-percent-encoded capability
181
+ // never presented a ≥20-char run in ANY pass and exited one decode away
182
+ // from plaintext, persisting in the append-only row past the share's TTL.
183
+ // Eight rounds: denial samples are ≤200 chars, but scrubValue feeds
184
+ // 8192-char values where a 5x-encoded token (~5.8KB) still exits one
185
+ // decode short — loop-until-stable with a generous cap; input-bounded.
186
+ for (let round = 0; round < 8; round++) {
179
187
  try {
180
188
  const decoded = decodeURIComponent(out);
181
189
  if (decoded === out) break;
@@ -11,6 +11,12 @@ import type {
11
11
  TunnelDiagnostics,
12
12
  } from "../../../../dpi-sdk/src/api.js";
13
13
  import { toPublic, type NetworkRegistry } from "../../../../dpi-sdk/src/node/registry.js";
14
+
15
+ /** run-7 B4 admission bounds: device-authored status payloads are untrusted —
16
+ * 32 devices x 256KiB keeps the AGGREGATE network frame under the 16MiB
17
+ * writer cap even when every paired device is hostile. */
18
+ const TREE_MAX_BYTES = 256 * 1024;
19
+ const TREE_MAX_SESSIONS = 2000;
14
20
  import { Backoff } from "../../../../dpi-sdk/src/protocol/backoff.js";
15
21
  import { MONITOR_BACKOFF_S } from "../../../../dpi-sdk/src/protocol/limits.js";
16
22
 
@@ -272,7 +278,7 @@ export class DeviceMonitor {
272
278
  if (device.deviceUid && device.deviceUid !== info.uid) {
273
279
  this.update(id, {
274
280
  status: "mismatch",
275
- error: `${device.url} now answers as "${info.name}" (uid ${info.uid.slice(0, 8)}), not the device first seen there (uid ${device.deviceUid.slice(0, 8)})`,
281
+ error: `${device.url} now answers as "${String(info.name ?? "").slice(0, 200)}" (uid ${String(info.uid ?? "").slice(0, 8)}), not the device first seen there (uid ${String(device.deviceUid ?? "").slice(0, 8)})`,
276
282
  });
277
283
  await sleep(30_000, signal);
278
284
  continue;
@@ -294,13 +300,30 @@ export class DeviceMonitor {
294
300
  { path: "/v1/events", consumerId: `monitor:${id}` },
295
301
  signal,
296
302
  )) {
297
- if (frame.type === "tree")
303
+ if (frame.type === "tree") {
304
+ // run-7 B4: the monitor seam had NO admission bound — a hostile
305
+ // device's ≤16MiB wire-legal tree was retained verbatim, persisted
306
+ // uncapped, and fanned out; aggregate network frames over the
307
+ // writer cap were REPLACED by faults, blinding every viewer's
308
+ // network view. Degrade oversized/hostile-shaped trees at the seam.
309
+ const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
310
+ const size = JSON.stringify(frame.tree)?.length ?? 0;
311
+ if (size > TREE_MAX_BYTES || sessions.length > TREE_MAX_SESSIONS) {
312
+ this.update(id, {
313
+ status: "faulted",
314
+ error: `oversized tree frame (${size} bytes, ${sessions.length} sessions)`,
315
+ tree: undefined,
316
+ lastSeenAt: Date.now(),
317
+ });
318
+ continue;
319
+ }
298
320
  this.update(id, {
299
321
  status: "online",
300
322
  error: undefined,
301
323
  tree: frame.tree,
302
324
  lastSeenAt: Date.now(),
303
325
  });
326
+ }
304
327
  }
305
328
  if (signal.aborted) return;
306
329
  // The stream was live until now: that is the last time the device was seen.
@@ -28,10 +28,22 @@ import {
28
28
  } from "../../../../dpi-sdk/src/protocol/limits.js";
29
29
 
30
30
  interface BrowserStream {
31
- send(frame: MuxFrame): void;
31
+ /** run-8 U5: `preSerialized` lets the relay seam (follow) admit on and send
32
+ * the SAME serialization — one stringify per inbound frame, not one per tab. */
33
+ send(frame: MuxFrame, preSerialized?: string): void;
32
34
  upstreams: Map<string, AbortController>;
33
35
  }
34
36
 
37
+ /** run-8 U5: relay admission cap for device->browser frames — the B4
38
+ * discipline (TREE_MAX_BYTES at the monitor seam) applied to EVERY frame the
39
+ * mux forwards, so a hostile device cannot push ~16MiB agent-event frames
40
+ * into per-tab stringify/copy work below the transport ceiling. */
41
+ const RELAY_FRAME_CAP_BYTES = 1024 * 1024;
42
+ /** Trees are legitimately larger (the device-scope tree path is bounded by its
43
+ * own monitor-seam caps) — still far below the 16MiB transport ceiling so a
44
+ * hostile device cannot drive ~16MiB parse/copy work per frame. */
45
+ const RELAY_TREE_CAP_BYTES = 4 * 1024 * 1024;
46
+
35
47
  const sseBudget = new ByteBudget("hub-sse", HUB_BUFFER_BUDGET_BYTES);
36
48
 
37
49
  /**
@@ -155,8 +167,9 @@ export class StreamMux {
155
167
  const writer = pacedSseWriter(res, { budget: this.options.budget, onClose: cleanup });
156
168
  const stream: BrowserStream = {
157
169
  upstreams: new Map(),
158
- send: (frame) => {
159
- if (writer.write(`data: ${JSON.stringify(frame)}\n\n`) === "too-large") {
170
+ send: (frame, preSerialized) => {
171
+ const text = preSerialized ?? JSON.stringify(frame);
172
+ if (writer.write(`data: ${text}\n\n`) === "too-large") {
160
173
  stream.send({
161
174
  sub: frame.sub,
162
175
  frame: {
@@ -267,7 +280,34 @@ export class StreamMux {
267
280
  )) {
268
281
  if (!checkDeviceFrame(frame))
269
282
  throw new DpiError("invalid", "Invalid device stream frame");
270
- stream.send({ sub: sub.key, frame });
283
+ // run-8 U5: admission bound at the relay seam — checkDeviceFrame is
284
+ // shape-only, so agent-event frames rode the ~16MiB transport
285
+ // ceiling into per-tab stringify (B4 capped TREE frames at the
286
+ // monitor seam only). Serialize ONCE here, admit on its byte size,
287
+ // and hand the same string to every tab.
288
+ const text = JSON.stringify({ sub: sub.key, frame });
289
+ // snapshot/agents/network carry whole-document payloads by design
290
+ // (a session snapshot includes entries + inbox) and legitimately
291
+ // exceed the per-event cap — capping them turned a large session's
292
+ // live view into a fault with no reconnect path.
293
+ const cap =
294
+ frame.type === "tree" || frame.type === "snapshot" || frame.type === "agents"
295
+ ? RELAY_TREE_CAP_BYTES
296
+ : RELAY_FRAME_CAP_BYTES;
297
+ if (Buffer.byteLength(text) > cap) {
298
+ stream.send({
299
+ sub: sub.key,
300
+ frame: {
301
+ type: "fault",
302
+ error: {
303
+ code: "invalid",
304
+ message: `Device stream frame exceeds the relay cap (${cap} bytes)`,
305
+ },
306
+ },
307
+ });
308
+ continue;
309
+ }
310
+ stream.send({ sub: sub.key, frame }, text);
271
311
  if (frame.type === "hello") backoff.reset();
272
312
  }
273
313
  if (signal.aborted) return;
@@ -62,12 +62,26 @@ interface PendingRest {
62
62
  interface Subscription {
63
63
  connectionId: string;
64
64
  deviceId: string;
65
+ /** run-8 U8: every relayed device frame is charged to THIS device's
66
+ * connection share before it is queued (released when consumed), so a
67
+ * hostile device exhausts its own 32 MiB — never the shared hub pool that
68
+ * other devices' REST reservations and chunk assemblies draw from. */
65
69
  push: (frame: Frame) => void;
66
70
  close: (reason: string) => void;
67
71
  signal: AbortSignal;
68
72
  onAbort: () => void;
69
73
  }
70
74
 
75
+ /** run-8 U8: the byte size a relayed frame holds in a viewer queue. One extra
76
+ * serialization per device frame, bounded by the mux relay caps. */
77
+ function relayBytes(frame: Frame): number {
78
+ try {
79
+ return Buffer.byteLength(JSON.stringify(frame));
80
+ } catch {
81
+ return 0;
82
+ }
83
+ }
84
+
71
85
  /** A grace-set entry: which connection owned the correlation, and when it left the pending maps. */
72
86
  interface GraceEntry {
73
87
  connectionId: string;
@@ -636,14 +650,36 @@ export class TunnelDispatcher {
636
650
  throw new DpiError("offline", "No tunnel connection is live", 0);
637
651
  const connectionId = this.server.connectionIdOf(deviceId)!;
638
652
  const subscriptionId = randomUUID();
639
- const queue: Frame[] = [];
653
+ const queue: { frame: Frame; reservation: { release(): void } | null }[] = [];
640
654
  let wakeup: (() => void) | undefined;
641
655
  let closed: string | undefined;
656
+ let budgetFaulted = false;
642
657
  const sub: Subscription = {
643
658
  connectionId,
644
659
  deviceId,
645
660
  push: (frame) => {
646
- queue.push(frame);
661
+ const bytes = relayBytes(frame);
662
+ const reservation = bytes > 0 ? this.budgetFor(connectionId).reserve(bytes) : null;
663
+ if (bytes > 0 && !reservation) {
664
+ // No share left. One fault, then CLOSE: pushing a fault per dropped
665
+ // frame would put an uncharged entry in the queue for every device
666
+ // frame (the cap would stop bounding anything) and relay a fault to
667
+ // every tab until their viewer budgets cut them off.
668
+ if (!budgetFaulted) {
669
+ budgetFaulted = true;
670
+ queue.push({
671
+ frame: {
672
+ type: "fault",
673
+ error: { code: "invalid", message: "device stream exceeded this device's relay budget" },
674
+ } as unknown as Frame,
675
+ reservation: null,
676
+ });
677
+ closed = closed ?? "device stream exceeded this device's relay budget";
678
+ }
679
+ wakeup?.();
680
+ return;
681
+ }
682
+ queue.push({ frame, reservation });
647
683
  wakeup?.();
648
684
  },
649
685
  close: (reason) => {
@@ -663,10 +699,17 @@ export class TunnelDispatcher {
663
699
  sub: input.path,
664
700
  });
665
701
  if (!sent) throw new DpiError("offline", "Tunnel connection closed while subscribing", 0);
666
- while (!closed && !signal.aborted) {
667
- const frame = queue.shift();
668
- if (frame) {
669
- yield frame;
702
+ // Frames already in the queue are CHARGED and delivered before a close
703
+ // takes effect — a budget fault must not swallow the frames that fit.
704
+ while (!signal.aborted) {
705
+ if (closed && queue.length === 0) break;
706
+ const next = queue.shift();
707
+ if (next) {
708
+ try {
709
+ yield next.frame;
710
+ } finally {
711
+ next.reservation?.release();
712
+ }
670
713
  continue;
671
714
  }
672
715
  await new Promise<void>((resolve) => {
@@ -676,6 +719,9 @@ export class TunnelDispatcher {
676
719
  }
677
720
  if (closed && closed !== "consumer aborted") throw new DpiError("offline", closed, 0);
678
721
  } finally {
722
+ // Release every queued byte the device never got to deliver.
723
+ for (const pending of queue) pending.reservation?.release();
724
+ queue.length = 0;
679
725
  this.subs.delete(subscriptionId);
680
726
  this.rememberClosedSubscription(subscriptionId, connectionId);
681
727
  this.reassemblers
@@ -41,7 +41,11 @@ export type DeviceStatus =
41
41
  | "offline"
42
42
  | "unauthorized"
43
43
  | "mismatch"
44
- | "incompatible";
44
+ | "incompatible"
45
+ /** run-7 B4: the hub faulted this device's status payload at the admission
46
+ * seam (oversized/hostile tree frame) — the tree is dropped, the error
47
+ * says why; UIs render it like any unknown-but-textual status. */
48
+ | "faulted";
45
49
  export type ErrorCode =
46
50
  | "unauthorized"
47
51
  | "not_found"