my-durable 0.0.77 → 0.0.79

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.
@@ -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,25 @@ 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
+ /** Device platform decides the DPI_START_DIRS separator in the hint. */
52
+ const winDevice = computed(() =>
53
+ String(
54
+ (network.devices.value.find((d) => d.id === devId.value) as { info?: { platform?: unknown } } | undefined)?.info
55
+ ?.platform ?? "",
56
+ ).startsWith("win32"),
57
+ );
58
+
59
+ const unserved = computed(() => {
60
+ const e = entry.value;
61
+ if (!e.error || !/start dirs/i.test(e.error)) return "";
62
+ const dirs = (network.devices.value.find((d) => d.id === devId.value) as
63
+ | { info?: { startDirs?: unknown } }
64
+ | undefined)?.info?.startDirs;
65
+ return Array.isArray(dirs) && dirs.length ? dirs.map(String).join(", ") : "";
66
+ });
48
67
  const refreshing = computed(() => entry.value.refreshing);
49
68
  const error = computed(() => entry.value.error);
50
69
  const sessionId = computed(() => {
@@ -114,6 +133,12 @@ const prBusy = ref(false);
114
133
  const isGitHub = computed(() => /github\.com|gitlab/i.test(status.value?.remoteUrl ?? ""));
115
134
  const loadPRs = async () => {
116
135
  if (!devId.value || !cwd.value) return;
136
+ const allowed = gitAllowedFor(devId.value, cwd.value);
137
+ if (!allowed.ok) {
138
+ prs.value = [];
139
+ notify(`pull requests unavailable: ${allowed.reason}`);
140
+ return;
141
+ }
117
142
  prBusy.value = true;
118
143
  try {
119
144
  const r = await deviceClient(devId.value).gitOp(cwd.value, "pr-list");
@@ -346,6 +371,11 @@ async function op(
346
371
  extra: { message?: string; rebase?: boolean; setUpstream?: boolean; ref?: string } = {},
347
372
  ) {
348
373
  if (!devId.value || !cwd.value) return;
374
+ const allowed = gitAllowedFor(devId.value, cwd.value);
375
+ if (!allowed.ok) {
376
+ notify(`git ${name} skipped: ${allowed.reason}`);
377
+ return;
378
+ }
349
379
  busy.value = name;
350
380
  out.value = "";
351
381
  try {
@@ -813,6 +843,16 @@ let logAt = 0;
813
843
  async function loadLog(force = false) {
814
844
  if (!devId.value || !cwd.value) return;
815
845
  if (!force && commits.value.length && Date.now() - logAt < 120_000) return;
846
+ // run-8 (live console report): this call bypassed the store's pre-check, so a
847
+ // project outside the device's start dirs (or a plain non-repo project) sent
848
+ // log-list on every mount/frame and answered 400 each time. Ask first.
849
+ const allowed = gitAllowedFor(devId.value, cwd.value);
850
+ if (!allowed.ok) {
851
+ commits.value = [];
852
+ logError.value = allowed.reason;
853
+ logAt = Date.now();
854
+ return;
855
+ }
816
856
  logLoading.value = true;
817
857
  try {
818
858
  const r = await deviceClient(devId.value).gitOp(cwd.value, "log-list");
@@ -879,7 +919,24 @@ const laneX = (lane: number) => lane * 12 + 7;
879
919
  <template v-else>
880
920
  <p v-if="loading" class="hint">loading git…</p>
881
921
  <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>
922
+ <!-- run-8 (live report): a folder the DEVICE does not serve can never be
923
+ fixed by retrying — name the roots it does serve and the real fix. -->
924
+ <div v-if="unserved" class="message-error">
925
+ <p>
926
+ <strong>{{ cwd }}</strong> is outside the folders this device serves — it serves
927
+ <code>{{ unserved }}</code>.
928
+ </p>
929
+ <p class="muted-line">
930
+ Your session and its history are intact, and the agent still runs in that folder; only the Git and Files panels
931
+ (the device's HTTP surface) are confined. Nothing has to be recreated: add the folder to
932
+ <code>DPI_START_DIRS</code> and restart the device, and this panel works again for the same session.
933
+ </p>
934
+ <p class="muted-line">
935
+ Example ({{ winDevice ? "Windows: separate with ;" : "Linux/macOS: separate with :" }}) —
936
+ <code>{{ winDevice ? "setx DPI_START_DIRS \"%USERPROFILE%\\dpi-work;D:\\source\"" : "DPI_START_DIRS=\"$HOME/dpi-work:/srv/src\"" }}</code>
937
+ </p>
938
+ </div>
939
+ <p v-else-if="error" class="message-error">{{ error }} <button @click="refresh()">retry</button></p>
883
940
 
884
941
  <div v-if="status" :class="{ stale: !!error || !!refreshing }">
885
942
  <p v-if="!status.repo" class="hint">Not a git repository — run <code>git init</code> (or open a session inside a repo).</p>
@@ -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
@@ -98,15 +98,77 @@ function setPath(target: Record<string | number, unknown>, path: readonly (strin
98
98
  }
99
99
 
100
100
  /** run-7 D4-B: inbox items are wire JSON — non-array or null-element shapes
101
- * threw in every tasks-tab consumer; same discipline as safeTasks. */
101
+ * threw in every tasks-tab consumer; same discipline as safeTasks.
102
+ * run-8 U5: items also rode the ~16MiB frame ceiling VERBATIM (probe: a
103
+ * 1MiB InboxItem.content retained whole) — cap item count and per-item
104
+ * content like every other retained wire string. */
105
+ const INBOX_MAX_ITEMS = 128;
106
+ const INBOX_ITEM_TEXT_CAP = 64 * 1024;
102
107
  function safeInbox(items: unknown): AgentViewState["inbox"] {
103
- return (Array.isArray(items) ? items : []).filter((x) => !!x && typeof x === "object") as AgentViewState["inbox"];
108
+ const list = (Array.isArray(items) ? items : []).filter((x) => !!x && typeof x === "object") as AgentViewState["inbox"];
109
+ return list.slice(-INBOX_MAX_ITEMS).map((item) => {
110
+ const content = (item as { content?: unknown }).content;
111
+ if (typeof content === "string" && content.length > INBOX_ITEM_TEXT_CAP) {
112
+ return { ...item, content: Buffer.from(content.slice(0, INBOX_ITEM_TEXT_CAP), "utf8").toString("utf8") + "…[truncated]" } as AgentViewState["inbox"][number];
113
+ }
114
+ return item;
115
+ });
104
116
  }
105
117
 
106
118
  /** run-7 D3 F3: live message blocks append unbounded deltas between
107
119
  * message_start/message_end — keep a 256Ki flattened tail (the capToolOutput
108
120
  * principle, applied to the live accumulator). */
109
121
  const LIVE_TEXT_CAP = 256 * 1024;
122
+
123
+ /** run-8 U5: notice strings rode the frame ceiling verbatim — bounded tail,
124
+ * flat slice (V8 SlicedString retention), explicit marker. */
125
+ const NOTICE_TEXT_CAP = 4 * 1024;
126
+ function capNoticeText(text: string): string {
127
+ return text.length > NOTICE_TEXT_CAP
128
+ ? Buffer.from(text.slice(-NOTICE_TEXT_CAP), "utf8").toString("utf8") + "…[truncated]"
129
+ : text;
130
+ }
131
+
132
+ /** run-8 U5: the live assistant message cloned VERBATIM from message_start /
133
+ * snapshot.generation bypassed every delta cap (probe: 1MiB text block
134
+ * retained whole) — cap the text-bearing blocks at clone time. */
135
+ function capLiveMessage(message: WireAssistantMessage): WireAssistantMessage {
136
+ const cloned = structuredClone(message);
137
+ const content = (cloned as { content?: unknown }).content;
138
+ if (!Array.isArray(content)) return cloned;
139
+ for (const block of content) {
140
+ if (!block || typeof block !== "object") continue;
141
+ const b = block as { text?: unknown; thinking?: unknown; arguments?: unknown };
142
+ if (typeof b.text === "string" && b.text.length > LIVE_TEXT_CAP)
143
+ b.text = capLiveText(b.text.slice(-LIVE_TEXT_CAP));
144
+ if (typeof b.thinking === "string" && b.thinking.length > LIVE_TEXT_CAP)
145
+ b.thinking = capLiveText(b.thinking.slice(-LIVE_TEXT_CAP));
146
+ // cold-3 M5: a toolCall block's arguments rode the same frame ceiling in
147
+ // verbatim — the exact defect this clone cap exists for, one block type over.
148
+ if (b.arguments !== undefined) {
149
+ try {
150
+ if (JSON.stringify(b.arguments).length > MAX_LIVE_ARGS) b.arguments = capLiveArgs(b.arguments);
151
+ } catch {
152
+ b.arguments = { truncated: true };
153
+ }
154
+ }
155
+ }
156
+ return cloned;
157
+ }
158
+
159
+ /** cold-3 M5: bound for a cloned toolCall block's arguments (module scope: the
160
+ * clone helper runs before the class body). */
161
+ const MAX_LIVE_ARGS = 64 * 1024;
162
+ function capLiveArgs(args: unknown): unknown {
163
+ try {
164
+ const text = JSON.stringify(args);
165
+ if (text.length <= MAX_LIVE_ARGS) return args;
166
+ return { truncated: true, preview: Buffer.from(text.slice(0, 4_096), "utf8").toString("utf8") };
167
+ } catch {
168
+ return { truncated: true };
169
+ }
170
+ }
171
+
110
172
  function capLiveText(text: string): string {
111
173
  return text.length > LIVE_TEXT_CAP ? AgentModel.flatSlice(text.slice(text.length - LIVE_TEXT_CAP)) : text;
112
174
  }
@@ -251,7 +313,7 @@ export class AgentModel extends Emitter {
251
313
  const snapCompactions = (Array.isArray(snapshot.compactions) ? snapshot.compactions : []).filter((x) => !!x && typeof x === "object");
252
314
  this.entries = new Map(snapEntries.map((entry) => [entry.id, entry]));
253
315
  this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
254
- this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
316
+ this.live = snapshot.generation?.message ? capLiveMessage(snapshot.generation.message) : undefined;
255
317
  this.tools = new Map(
256
318
  snapTools
257
319
  .filter((slot) => typeof slot.callId === "string" && slot.callId.length <= 4_096 && typeof slot.name === "string" && slot.name.length <= 4_096) // R20 cold-3 M1: oversized ids/names are dropped, not retained
@@ -404,8 +466,7 @@ export class AgentModel extends Emitter {
404
466
  this.live = undefined;
405
467
  return;
406
468
  case "message_start":
407
- if (event.message.role === "assistant")
408
- this.live = structuredClone(event.message as WireAssistantMessage);
469
+ if (event.message.role === "assistant") this.live = capLiveMessage(event.message as WireAssistantMessage);
409
470
  return;
410
471
  case "message_update":
411
472
  if (!this.live)
@@ -516,7 +577,14 @@ export class AgentModel extends Emitter {
516
577
  : undefined;
517
578
  return;
518
579
  case "task_failed":
519
- this.state.notices = [...this.state.notices.slice(-9), `${event.kind} failed: ${event.message}`];
580
+ // run-8 U5: kind/message rode the frame ceiling verbatim — 10 x 16MiB
581
+ // notices froze the FE tab (probe: notice[0].length === 1048592).
582
+ // Same discipline as capToolOutput: bounded tail, flat slice.
583
+ if (typeof event.kind !== "string" || event.kind.length > 64) return;
584
+ this.state.notices = [
585
+ ...this.state.notices.slice(-9),
586
+ `${event.kind} failed: ${capNoticeText(String(event.message ?? ""))}`,
587
+ ];
520
588
  return;
521
589
  default:
522
590
  return;
@@ -155,10 +155,21 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
155
155
  device.ssh = `${device.vm}.exe.xyz`;
156
156
  device.service ??= "systemd";
157
157
  const create = (d.create ?? {}) as Raw;
158
+ // run-8 U9: memory/disk were the ONLY config scalars with no charset gate
159
+ // and they ride `ssh exe.dev new --memory=<v>` argv, which OpenSSH joins
160
+ // into one remote command string the remote shell re-parses. Gate them at
161
+ // parse time like pathish does for every other shell-bound value.
162
+ const sized = (v: unknown, field: string): string | undefined => {
163
+ if (v === undefined) return undefined;
164
+ const text = String(v);
165
+ if (!/^[0-9]+(\.[0-9]+)?[KMGTP]?i?B?$/i.test(text))
166
+ throw Error(`${where}.create.${field} is not a size (e.g. 4G, 512M)`);
167
+ return text;
168
+ };
158
169
  device.create = {
159
170
  ...(create.cpu !== undefined ? { cpu: Number(create.cpu) } : {}),
160
- ...(typeof create.memory === "string" ? { memory: create.memory } : {}),
161
- ...(typeof create.disk === "string" ? { disk: create.disk } : {}),
171
+ ...(sized(create.memory, "memory") !== undefined ? { memory: sized(create.memory, "memory")! } : {}),
172
+ ...(sized(create.disk, "disk") !== undefined ? { disk: sized(create.disk, "disk")! } : {}),
162
173
  };
163
174
  }
164
175
  if ((kind === "ssh" || kind === "exe-dev") && !device.service) throw Error(`${where}.service is required for kind ${kind}`);
@@ -3,6 +3,10 @@
3
3
  import { spawn } from "node:child_process";
4
4
  import type { NetDevice } from "./config.js";
5
5
 
6
+ /** run-8 U9: every device-facing step gets a deadline by default, so a hung or
7
+ * hostile host cannot block the operator's CLI indefinitely. */
8
+ const DEFAULT_TIMEOUT_MS = 60_000;
9
+
6
10
  export interface RunResult {
7
11
  code: number;
8
12
  stdout: string;
@@ -12,6 +16,8 @@ export interface RunResult {
12
16
  export interface RunOptions {
13
17
  stdin?: string;
14
18
  timeoutMs?: number;
19
+ /** run-8 U9: cap on captured stdout/stderr per stream (default 1 MiB). */
20
+ maxBytes?: number;
15
21
  /** Stream output to this process's stdout/stderr while capturing it. */
16
22
  echo?: boolean;
17
23
  cwd?: string;
@@ -29,18 +35,33 @@ export function run(cmd: string, args: string[], options: RunOptions = {}): Prom
29
35
  });
30
36
  let stdout = "";
31
37
  let stderr = "";
32
- const timer = options.timeoutMs
38
+ // run-8 U9: a hostile/hung device controls every byte on these pipes and
39
+ // run() accumulated them without limit, so `net status`/`up` could OOM or
40
+ // hang forever (facts/register/logs passed no timeout at all).
41
+ const cap = options.maxBytes ?? 1024 * 1024;
42
+ let truncatedStdout = false;
43
+ let truncatedStderr = false;
44
+ const take = (current: string, chunk: Buffer, mark: (v: boolean) => void): string => {
45
+ if (current.length >= cap) {
46
+ mark(true);
47
+ return current;
48
+ }
49
+ return current + chunk.toString().slice(0, cap - current.length);
50
+ };
51
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
52
+ const timer = timeoutMs
33
53
  ? setTimeout(() => {
34
54
  child.kill("SIGTERM");
35
- stderr += `\n[timeout after ${options.timeoutMs}ms]`;
36
- }, options.timeoutMs)
55
+ setTimeout(() => child.kill("SIGKILL"), 2000).unref?.();
56
+ stderr = take(stderr, Buffer.from(`\n[timeout after ${timeoutMs}ms]`), (v) => (truncatedStderr = v));
57
+ }, timeoutMs)
37
58
  : undefined;
38
59
  child.stdout.on("data", (chunk: Buffer) => {
39
- stdout += chunk;
60
+ stdout = take(stdout, chunk, (v) => (truncatedStdout = v));
40
61
  if (options.echo) process.stdout.write(chunk);
41
62
  });
42
63
  child.stderr.on("data", (chunk: Buffer) => {
43
- stderr += chunk;
64
+ stderr = take(stderr, chunk, (v) => (truncatedStderr = v));
44
65
  if (options.echo) process.stderr.write(chunk);
45
66
  });
46
67
  child.on("error", (e) => {
@@ -49,7 +70,13 @@ export function run(cmd: string, args: string[], options: RunOptions = {}): Prom
49
70
  });
50
71
  child.on("close", (code) => {
51
72
  if (timer) clearTimeout(timer);
52
- const result = { code: code ?? 1, stdout, stderr };
73
+ // cold-3 L10: a silent cut is indistinguishable from a complete log.
74
+ const marker = `\n[truncated at ${cap} bytes]`;
75
+ const result = {
76
+ code: code ?? 1,
77
+ stdout: truncatedStdout ? stdout + marker : stdout,
78
+ stderr: truncatedStderr ? stderr + marker : stderr,
79
+ };
53
80
  if (result.code !== 0 && !options.allowFail)
54
81
  reject(Object.assign(Error(`${cmd} ${args.slice(0, 3).join(" ")} … failed (exit ${result.code}): ${stderr.trim().slice(-800)}`), { result }));
55
82
  else resolve(result);
@@ -21,6 +21,7 @@ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, openSync, rmSyn
21
21
  import { dirname } from "node:path";
22
22
  import { randomUUID } from "node:crypto";
23
23
  import { ensurePrivateDir } from "./private-dir.js";
24
+ import { normalizeUrl, validateToken } from "./registry.js";
24
25
 
25
26
  export const REGISTRY_SCHEMA_VERSION = 1;
26
27
  const UUID_CANONICAL = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -346,7 +347,19 @@ function openExclusive(path: string, busyTimeoutMs: number): DatabaseSync {
346
347
  }
347
348
 
348
349
  /** v0 preflight: no stray v1 objects, exact column set per v0 table, canonical ids/uids, no duplicates. */
349
- function preflightV0(db: DatabaseSync): void {
350
+ /** Sanitized replacement values for rows whose legacy fields the live writers
351
+ * would refuse or cap. Applied INSIDE the migration transaction (never in the
352
+ * read-only preflight): a preflight write would mutate the v0 file before the
353
+ * WAL-safe backup and before BEGIN, so an aborted migration would silently
354
+ * drop operator tokens. */
355
+ export interface V0Overrides {
356
+ url?: string;
357
+ token?: string | null;
358
+ info?: string | null;
359
+ tree?: string | null;
360
+ }
361
+
362
+ function preflightV0(db: DatabaseSync): Map<string, V0Overrides> {
350
363
  // First: anything the v1 schema owns means this is not a v0 file at all. Refused before
351
364
  // the backup is written and before any write touches the registry (the caller's
352
365
  // `reached(opts, "preflight")` hook still fires only after preflightV0 returns).
@@ -373,9 +386,21 @@ function preflightV0(db: DatabaseSync): void {
373
386
  );
374
387
  }
375
388
  }
376
- const rows = db.prepare("SELECT id, url, device_uid FROM devices").all() as {
389
+ // run-8 U9: the v0 rows predate the writer-side caps and normalisation, and
390
+ // the copy below is verbatim — a pre-run-7 registry could carry a hostile
391
+ // 16MiB last_tree_json (parsed by EVERY NetworkRegistry.list() forever) or a
392
+ // token with CRLF (breaking every client construction). Enforce the same
393
+ // per-field policy at the migration seam: cap the JSON blobs and NULL out a
394
+ // url/token that the live writers would have refused.
395
+ const rows = db.prepare(
396
+ "SELECT id, url, device_uid, token, last_info_json, last_tree_json FROM devices",
397
+ ).all() as {
377
398
  id: string; url: string | null; device_uid: string | null;
399
+ token: string | null; last_info_json: string | null; last_tree_json: string | null;
378
400
  }[];
401
+ const INFO_CAP = 64 * 1024;
402
+ const TREE_CAP = 288 * 1024;
403
+ const overrides = new Map<string, V0Overrides>();
379
404
  const seenUid = new Set<string>();
380
405
  for (const row of rows) {
381
406
  if (!DEVICE_ID_PATTERN.test(row.id)) throw new MigrationError(`non-canonical device id ${JSON.stringify(row.id)} — resolve manually (no trim)`);
@@ -385,7 +410,34 @@ function preflightV0(db: DatabaseSync): void {
385
410
  if (seenUid.has(row.device_uid)) throw new MigrationError(`duplicate device_uid ${row.device_uid} — operator must resolve before migration`);
386
411
  seenUid.add(row.device_uid);
387
412
  }
413
+ let url: string = row.url;
414
+ try {
415
+ url = normalizeUrl(row.url);
416
+ } catch {
417
+ // The live writer would have refused this url; carrying it over would put
418
+ // an arbitrary scheme in every consumer. Fail closed (url is NOT NULL).
419
+ throw new MigrationError(`device ${row.id} has a url the live writer refuses — resolve manually`);
420
+ }
421
+ let token: string | null = row.token;
422
+ if (token !== null) {
423
+ try {
424
+ validateToken(token);
425
+ } catch {
426
+ token = null;
427
+ }
428
+ }
429
+ const capJson = (text: string | null, cap: number): string | null =>
430
+ text !== null && text.length > cap ? null : text;
431
+ const info = capJson(row.last_info_json, INFO_CAP);
432
+ const tree = capJson(row.last_tree_json, TREE_CAP);
433
+ const patch: V0Overrides = {};
434
+ if (url !== row.url) patch.url = url;
435
+ if (token !== row.token) patch.token = token;
436
+ if (info !== row.last_info_json) patch.info = info;
437
+ if (tree !== row.last_tree_json) patch.tree = tree;
438
+ if (Object.keys(patch).length) overrides.set(row.id, patch);
388
439
  }
440
+ return overrides;
389
441
  }
390
442
 
391
443
  /**
@@ -462,7 +514,7 @@ function migrateV0(db: DatabaseSync, path: string, opts: MigrationOptions): Regi
462
514
  }
463
515
  assertMigratable(version);
464
516
 
465
- preflightV0(db);
517
+ const overrides = preflightV0(db);
466
518
  reached(opts, "preflight");
467
519
 
468
520
  const preCount = (db.prepare("SELECT count(*) AS n FROM devices").get() as { n: number }).n;
@@ -484,6 +536,27 @@ function migrateV0(db: DatabaseSync, path: string, opts: MigrationOptions): Regi
484
536
  created_at,updated_at,'lan'
485
537
  FROM devices`,
486
538
  );
539
+ // The sanitized legacy values land on the NEW table, inside this
540
+ // transaction: the v0 file is never modified by a migration that aborts.
541
+ if (overrides.size) {
542
+ // cold-3 L11: dropping a legacy token is a behaviour change the operator
543
+ // must be able to see (the refused URL aborts loudly; this must not be
544
+ // silent). Ids + field names only, never the values.
545
+ const fields = [...overrides].map(([id, patch]) => `${id}(${Object.keys(patch).join(",")})`);
546
+ process.emitWarning(
547
+ `registry migration: sanitised ${overrides.size} legacy row(s) — ${fields.join(" ")}; those devices may need re-pairing`,
548
+ );
549
+ const setUrl = db.prepare("UPDATE devices_v1_new SET url=? WHERE id=?");
550
+ const setToken = db.prepare("UPDATE devices_v1_new SET token=? WHERE id=?");
551
+ const setInfo = db.prepare("UPDATE devices_v1_new SET last_info_json=? WHERE id=?");
552
+ const setTree = db.prepare("UPDATE devices_v1_new SET last_tree_json=? WHERE id=?");
553
+ for (const [id, patch] of overrides) {
554
+ if (patch.url !== undefined) setUrl.run(patch.url, id);
555
+ if (patch.token !== undefined) setToken.run(patch.token, id);
556
+ if (patch.info !== undefined) setInfo.run(patch.info, id);
557
+ if (patch.tree !== undefined) setTree.run(patch.tree, id);
558
+ }
559
+ }
487
560
  reached(opts, "mid-transaction");
488
561
  db.exec("DROP TABLE devices; ALTER TABLE devices_v1_new RENAME TO devices;");
489
562
  db.exec(V1_SCHEMA_SQL);
@@ -16,7 +16,7 @@ import type { App } from "./app.ts";
16
16
  import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
17
17
  import { Panel } from "./pickers.ts";
18
18
  import { c } from "./theme.ts";
19
- import { sanitizeTerminal } from "./sanitize.ts";
19
+ import { oneLine } from "./sanitize.ts";
20
20
 
21
21
  export interface PairArgs {
22
22
  code?: string;
@@ -152,32 +152,36 @@ export function pairingViewLines(
152
152
  hubOrigin?: string,
153
153
  ): string[] {
154
154
  const lines: string[] = [c.bold(c.accent("Pair this device"))];
155
- if (hubOrigin) lines.push(c.muted(`hub: ${sanitizeTerminal(hubOrigin)}`));
155
+ if (hubOrigin) lines.push(c.muted(`hub: ${oneLine(hubOrigin)}`));
156
156
  if (!status) {
157
- lines.push(c.muted(sanitizeTerminal(note)));
157
+ lines.push(c.muted(oneLine(note)));
158
158
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
159
159
  }
160
- lines.push(c.muted(sanitizeTerminal(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
160
+ lines.push(c.muted(oneLine(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
161
161
  lines.push("");
162
162
  lines.push(c.bold("key fingerprint (compare with the hub wizard):"));
163
- for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(sanitizeTerminal(line))}`);
163
+ for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(oneLine(line))}`);
164
164
  lines.push("");
165
165
  if (status.pending) {
166
166
  lines.push(c.warn("Awaiting approval on the hub…"));
167
- if (status.pending.note) lines.push(c.muted(` ${sanitizeTerminal(status.pending.note)}`));
167
+ if (status.pending.note) lines.push(c.muted(` ${oneLine(status.pending.note)}`));
168
168
  } else if (status.lastError) {
169
- lines.push(c.err(sanitizeTerminal(describePairingError(status.lastError))));
169
+ // run-8 U6: the hub relays its own error.message here unbounded, and
170
+ // wrapTextWithAnsi SPLITS on LF — a hostile message forged panel rows
171
+ // right below the real TOFU fingerprint block (probe: 2 rows, one read
172
+ // "Paired to https://good.example (generation 9)").
173
+ lines.push(c.err(oneLine(describePairingError(status.lastError))));
170
174
  if (status.state === "paired")
171
- lines.push(c.muted(sanitizeTerminal(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
175
+ lines.push(c.muted(oneLine(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
172
176
  } else if (status.state === "paired") {
173
- lines.push(c.ok(sanitizeTerminal(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
177
+ lines.push(c.ok(oneLine(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
174
178
  lines.push(c.muted("The connector keeps the tunnel up; /pair again to re-pair."));
175
179
  } else if (status.state === "revoked") {
176
180
  lines.push(c.warn("Revoked on the hub. /pair CODE to pair again."));
177
181
  } else {
178
- lines.push(c.muted(sanitizeTerminal(note)));
182
+ lines.push(c.muted(oneLine(note)));
179
183
  }
180
- if (note && status.state !== "pairing") lines.push(c.muted(sanitizeTerminal(note)));
184
+ if (note && status.state !== "pairing") lines.push(c.muted(oneLine(note)));
181
185
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
182
186
  }
183
187