my-durable 0.0.68 → 0.0.70

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.
@@ -361,6 +361,7 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
361
361
  }
362
362
 
363
363
  const entries: ZipArchiveEntry[] = [];
364
+ let totalDeclared = 0;
364
365
  let p = centralOffset;
365
366
  for (let i = 0; i < count; i += 1) {
366
367
  if (p + 46 > eocd) throw bad(`central directory entry ${i} overruns the archive`);
@@ -378,6 +379,15 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
378
379
  }
379
380
  const name = buf.toString("utf8", p + 46, p + 46 + nameLength);
380
381
  validateEntryName(name);
382
+ // R15 (run-2 h8): the WHOLE archive may never promise more than the
383
+ // backup ceiling — a pile of individually-legal entries must not add up
384
+ // to an unbounded restore either. Entry 0 is the writer's own manifest,
385
+ // which the write-side budget (walkHome) never counts, so a ceiling-sized
386
+ // home must stay restorable (R15 cold review P2-1).
387
+ if (i > 0 || name !== "manifest.json") totalDeclared += uncompressedSize;
388
+ if (totalDeclared > MAX_BACKUP_BYTES) {
389
+ throw bad(`archive declares more than ${MAX_BACKUP_BYTES} bytes of entries`);
390
+ }
381
391
 
382
392
  if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== LOCAL_SIG) {
383
393
  throw bad(`local header for ${name} is corrupt`);
@@ -390,8 +400,14 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
390
400
  let out: Buffer;
391
401
  if (method === 0) out = buf.subarray(start, start + compressedSize);
392
402
  else if (method === 8) {
403
+ // R15 (run-2 h8): a hostile "backup" can declare a tiny uncompressedSize
404
+ // while the deflate stream expands ~1000x — the old check ran only AFTER
405
+ // the full allocation. Cap the inflate itself: the entry may never
406
+ // produce more than the smaller of its declared size (cross-checked
407
+ // right below anyway) and the backup ceiling.
408
+ const declaredCap = Math.min(Math.max(uncompressedSize, 1), MAX_BACKUP_BYTES);
393
409
  try {
394
- out = inflateRawSync(buf.subarray(start, start + compressedSize));
410
+ out = inflateRawSync(buf.subarray(start, start + compressedSize), { maxOutputLength: declaredCap });
395
411
  } catch (error) {
396
412
  throw bad(`cannot inflate ${name} (${describeError(error)})`);
397
413
  }
@@ -62,7 +62,18 @@ export const PAIR_PAGE_HTML = `<!doctype html>
62
62
  var statusEl = document.getElementById("status");
63
63
  var meta = document.getElementById("meta");
64
64
  var H = { "content-type": "application/json", "x-dpi-pair": "1" };
65
- function say(text, cls) { statusEl.innerHTML = text ? '<span class="' + (cls || "") + '">' + text + "</span>" : ""; }
65
+ // R15 (run-2 h1): the enrollment page renders HUB-CONTROLLED text here
66
+ // (lastError, error.message from the offer the operator pasted) — that is a
67
+ // remote principal, so the status line must be text-only. The page's own
68
+ // static strings stopped needing markup at the same time.
69
+ function say(text, cls) {
70
+ statusEl.textContent = "";
71
+ if (!text) return;
72
+ var span = document.createElement("span");
73
+ if (cls) span.className = cls;
74
+ span.textContent = text;
75
+ statusEl.appendChild(span);
76
+ }
66
77
  // The hub handoff link put the offer in THIS page's fragment.
67
78
  if (location.hash.indexOf("#offer=") === 0) offerEl.value = location.href;
68
79
  function poll() {
@@ -70,8 +81,8 @@ export const PAIR_PAGE_HTML = `<!doctype html>
70
81
  .then(function (r) { return r.json(); })
71
82
  .then(function (s) {
72
83
  render(s);
73
- if (s.state === "pairing") { say('<span class="spin">&#9696;</span> waiting for approval on the hub…', "warn"); setTimeout(poll, 2000); }
74
- else if (s.state === "paired") say("paired — credential saved. You can close this page and open <b>dpi tui</b>.", "ok");
84
+ if (s.state === "pairing") { say("⠿ waiting for approval on the hub…", "spin warn"); setTimeout(poll, 2000); }
85
+ else if (s.state === "paired") say("paired — credential saved. You can close this page and open dpi tui.", "ok");
75
86
  })
76
87
  .catch(function () { setTimeout(poll, 3000); });
77
88
  }
@@ -101,7 +112,7 @@ export const PAIR_PAGE_HTML = `<!doctype html>
101
112
  if (!o.ok) { say((o.b && o.b.error && o.b.error.message) || "refused", "err"); go.disabled = false; return; }
102
113
  poll();
103
114
  })
104
- .catch(function () { say("cannot reach the local backend — is <b>dpi device</b> running?", "err"); go.disabled = false; });
115
+ .catch(function () { say("cannot reach the local backend — is dpi device running?", "err"); go.disabled = false; });
105
116
  });
106
117
  load();
107
118
  })();
@@ -984,14 +984,39 @@ export class Store {
984
984
 
985
985
  /** A caller-supplied path that must stay inside the start dirs: `~` expands,
986
986
  * symlinks resolve, and anything outside answers 400 `invalid`. A path that
987
- * does not exist is judged lexically (git then reports "not a repository"). */
987
+ * does not exist is judged by its deepest EXISTING ancestor (R15, run-2 h6):
988
+ * a not-yet-existing tail spelled under an in-start-dir symlink must not
989
+ * pass a lexical prefix check — walk dirname until realpath succeeds,
990
+ * re-append the missing tail, then judge that (git worktree-add targets
991
+ * never exist, so the old lexical fallback was the branch every
992
+ * worktree-add took). */
988
993
  async containedPath(input: string): Promise<string> {
989
994
  const expanded = input === "~" ? homedir() : input.startsWith("~/") ? join(homedir(), input.slice(2)) : input;
990
995
  let candidate: string;
991
996
  try {
992
997
  candidate = await realpath(resolve(expanded));
993
998
  } catch {
994
- candidate = resolve(expanded);
999
+ // Not yet existing: resolve the deepest existing ancestor so symlink
1000
+ // components are honored, then re-append the missing tail verbatim.
1001
+ const absolute = resolve(expanded);
1002
+ const tail: string[] = [];
1003
+ let current = absolute;
1004
+ let resolvedAncestor: string | undefined;
1005
+ for (let depth = 0; depth < 64; depth++) {
1006
+ const parent = dirname(current);
1007
+ if (parent === current) break;
1008
+ tail.unshift(current.slice(parent.length + 1));
1009
+ current = parent;
1010
+ try {
1011
+ resolvedAncestor = await realpath(current);
1012
+ break;
1013
+ } catch {}
1014
+ }
1015
+ // Fail CLOSED on exhaustion (R15 cold review P1-2): when no existing
1016
+ // ancestor was found at all, judging the raw spelling lexically would
1017
+ // resurrect the exact symlink escape this walk exists to close.
1018
+ if (resolvedAncestor === undefined) throw invalid("path must live under a start dir");
1019
+ candidate = join(resolvedAncestor, ...tail);
995
1020
  }
996
1021
  if (!this.underRoots(candidate, await this.startDirRoots())) throw invalid("path must live under a start dir");
997
1022
  return candidate;
@@ -395,6 +395,9 @@ export class TelegramBridge {
395
395
  return bridge;
396
396
  }
397
397
 
398
+ /** Last registry text this process loaded or wrote (R15 h14 foreign-writer sync). */
399
+ private registryText: string | null = null;
400
+
398
401
  /** True while the poll loop is scheduled or in flight. */
399
402
  get running(): boolean {
400
403
  return this.runningValue;
@@ -509,6 +512,7 @@ export class TelegramBridge {
509
512
  const main = await this.readRegistry(this.filePath);
510
513
  if (main.ok) {
511
514
  this.adopt(main.file);
515
+ this.registryText = main.text ?? null;
512
516
  this.mainIsGood = true;
513
517
  return;
514
518
  }
@@ -539,7 +543,9 @@ export class TelegramBridge {
539
543
 
540
544
  private async readRegistry(
541
545
  path: string,
542
- ): Promise<{ ok: true; file: TelegramRegistryFile } | { ok: false; missing: boolean; text?: string; error?: unknown }> {
546
+ ): Promise<
547
+ { ok: true; file: TelegramRegistryFile; text?: string } | { ok: false; missing: boolean; text?: string; error?: unknown }
548
+ > {
543
549
  if (!(await this.io.exists(path))) return { ok: false, missing: true };
544
550
  let text: string;
545
551
  try {
@@ -548,7 +554,7 @@ export class TelegramBridge {
548
554
  return { ok: false, missing: false, error };
549
555
  }
550
556
  try {
551
- return { ok: true, file: coerceRegistry(JSON.parse(text), this.now()) };
557
+ return { ok: true, file: coerceRegistry(JSON.parse(text), this.now()), text };
552
558
  } catch (error) {
553
559
  return { ok: false, missing: false, text, error };
554
560
  }
@@ -583,6 +589,31 @@ export class TelegramBridge {
583
589
  this.codes = file.codes.map((code) => ({ ...code }));
584
590
  }
585
591
 
592
+ /**
593
+ * R15 (run-2 h14): the `dpi telegram` CLI is a designed second writer of the
594
+ * registry file. Before authorizing ANY update, re-read the file and adopt
595
+ * foreign changes (bindings removed/added by the CLI, its minted codes), so
596
+ * a revocation takes effect on the live bridge and is never resurrected by
597
+ * the next offset persist. The ack offset only ever moves forward.
598
+ */
599
+ private async syncForeign(): Promise<boolean> {
600
+ try {
601
+ if (!(await this.io.exists(this.filePath))) return true;
602
+ const text = await this.io.readFile(this.filePath);
603
+ if (text === this.registryText) return true; // still our own last write
604
+ const file = coerceRegistry(JSON.parse(text), this.now());
605
+ this.adopt({ ...file, offset: Math.max(this.offset, file.offset) });
606
+ this.registryText = text;
607
+ return true;
608
+ } catch (error) {
609
+ // Fail CLOSED (R15 cold review P3-1): with an unreadable/unparseable
610
+ // registry the in-memory bindings cannot be trusted to reflect the
611
+ // operator's intent — authorize nothing until the file is healthy.
612
+ this.warn(`could not re-read ${this.filePath} before dispatch; skipping the update`, error);
613
+ return false;
614
+ }
615
+ }
616
+
586
617
  /** Stage → persist → swap. A failed write leaves memory exactly as it was. */
587
618
  private commit(apply: (draft: TelegramRegistryFile) => void): Promise<void> {
588
619
  return this.run(async () => {
@@ -620,6 +651,7 @@ export class TelegramBridge {
620
651
  const payload = `${JSON.stringify(draft satisfies TelegramRegistryFile, null, 2)}\n`;
621
652
  await this.io.writeFile(this.filePath, payload);
622
653
  await this.io.chmod(this.filePath, 0o600);
654
+ this.registryText = payload;
623
655
  this.mainIsGood = true;
624
656
  }
625
657
 
@@ -691,9 +723,11 @@ export class TelegramBridge {
691
723
 
692
724
  /** Acknowledge first (persist the new offset), then handle. Never both-half-heartedly. */
693
725
  private async handle(update: TelegramUpdate): Promise<void> {
726
+ const synced = await this.syncForeign();
694
727
  await this.commit((draft) => {
695
728
  draft.offset = Math.max(draft.offset, update.updateId + 1);
696
729
  });
730
+ if (!synced) return; // acknowledged, but NOT authorized on stale state
697
731
  if (!update.message) return; // non-message or non-text: acknowledged, ignored
698
732
  await this.dispatch(
699
733
  update.message.chatId,
@@ -605,6 +605,19 @@ if (args.includes("--dev")) {
605
605
  },
606
606
  }),
607
607
  );
608
+ // R15 (run-2 h12): unmatched /share/ paths (empty, multi-segment) must get
609
+ // the share 404 page — NOT fall through to the SPA fallback, which serves
610
+ // the operator app shell to anyone the edge exempted for /share/*.
611
+ app.get("/share/{*rest}", (_req, res) => {
612
+ res.status(404);
613
+ res.set("Cache-Control", "no-cache");
614
+ res.set("Content-Type", "text/html; charset=utf-8");
615
+ // Same lockdown as the /share/:token 404 — renderShareNotFound is
616
+ // inline-styled, so the shell CSP (style-src 'self') must not apply.
617
+ res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
618
+ res.set("X-Frame-Options", "DENY");
619
+ res.send(renderShareNotFound());
620
+ });
608
621
  app.get("/{*path}", (req, res, next) => {
609
622
  // A path that names a file is an asset that does not exist, not a page of the app.
610
623
  if (extname(req.path)) return void next();
@@ -275,7 +275,7 @@ export class PairingService {
275
275
  }
276
276
 
277
277
  /** Mint a single-use code entry (shared by the admin and device-initiated flows). */
278
- private mintEntry(actor: "admin" | "device"): CodeEntry {
278
+ private mintEntry(actor: "admin" | "device", audit = true): CodeEntry {
279
279
  const now = this.now();
280
280
  let code = "";
281
281
  do {
@@ -290,15 +290,25 @@ export class PairingService {
290
290
  cancelled: false,
291
291
  ...(actor === "device" ? { deviceMinted: true as const } : {}),
292
292
  };
293
+ // R15 (run-2 h11b): for the UNAUTH device surface the persistent audit row
294
+ // is written only when the mint SURVIVES — a failed anonymous attempt
295
+ // already leaves an aggregated denial record (failWindows) and its RAM
296
+ // slot is recycled instantly, so appending here let an anonymous flood
297
+ // persist one append-only row per request at per-IP rates only. Successful
298
+ // mints stay bounded by the RAM caps (100 live device codes, 5-7 min TTL).
299
+ if (audit) this.auditCodeCreated(entry, actor);
300
+ this.codes.set(entry.codeId, entry);
301
+ this.byCode.set(code, entry.codeId);
302
+ return entry;
303
+ }
304
+
305
+ private auditCodeCreated(entry: CodeEntry, actor: "admin" | "device"): void {
293
306
  this.deps.audit.append({
294
307
  actor,
295
308
  action: "pair.code_created",
296
309
  outcome: "ok",
297
310
  detail: { codeId: entry.codeId, expiresAt: entry.expiresAt, ...(actor === "device" ? { initiated: "device" } : {}) },
298
311
  });
299
- this.codes.set(entry.codeId, entry);
300
- this.byCode.set(code, entry.codeId);
301
- return entry;
302
312
  }
303
313
 
304
314
  /** POST /api/pair/code (admin) — mint a fresh single-use code. */
@@ -348,7 +358,7 @@ export class PairingService {
348
358
  if (request?.type !== "pair.device-request" || !checkPairingDto(PairDeviceRequestSchema, request))
349
359
  return this.fail(400, "invalid", "pair.device-request body failed schema validation");
350
360
 
351
- const entry = this.mintEntry("device");
361
+ const entry = this.mintEntry("device", false);
352
362
  const started = this.start({ ...(request as object), type: "pair.request", v: 1, code: entry.code }, address);
353
363
  if (!started.ok) {
354
364
  // The enrollment never existed: drop the code so a failed request leaves nothing behind.
@@ -356,6 +366,7 @@ export class PairingService {
356
366
  this.byCode.delete(entry.code);
357
367
  return started;
358
368
  }
369
+ this.auditCodeCreated(entry, "device");
359
370
  return this.ok({
360
371
  type: "pair.device-ack",
361
372
  v: 1,
@@ -72,7 +72,18 @@ const emptyAgentState = (): AgentViewState => ({
72
72
  ready: false,
73
73
  });
74
74
 
75
+ /** Wire-controlled path elements that must never be walked or written:
76
+ * reading node["__proto__"] returns Object.prototype and the walk descends
77
+ * onto it silently, and "constructor" reaches the inherited Function — both
78
+ * end in process-wide prototype pollution from a hostile/corrupt delta
79
+ * (R15: run-1 NV v3-13). A delta carrying any of these is dropped whole
80
+ * rather than partially applied. */
81
+ const FORBIDDEN_PATH_KEYS = new Set(["__proto__", "constructor", "prototype"]);
82
+
75
83
  function setPath(target: Record<string | number, unknown>, path: readonly (string | number)[], delta: string) {
84
+ for (const key of path) {
85
+ if (typeof key === "string" && FORBIDDEN_PATH_KEYS.has(key)) return;
86
+ }
76
87
  let node = target;
77
88
  for (let i = 0; i < path.length - 1; i++) {
78
89
  const key = path[i];
@@ -708,7 +708,7 @@ export class App {
708
708
  this.input!.value = "/";
709
709
  } else if (data === "f") this.beginInput("filter", "filter ❯ ");
710
710
  else if (data === "n") this.beginInput("new", "new session › ");
711
- else if (data === "x") this.beginInput("kill", `reset ${this.sessionSummary()?.name ?? "context"}? y/n`);
711
+ else if (data === "x") this.beginInput("kill", `reset ${sanitizeTerminal(this.sessionSummary()?.name ?? "context")}? y/n`);
712
712
  else if (data === "g") this.setView("herd");
713
713
  else if (data === "N") this.setView("network");
714
714
  else if (data === "L") this.setView("log");
@@ -1062,7 +1062,9 @@ export class App {
1062
1062
  )}${c.muted(". Reattach:")}\n just tui attach ${target}\n\n`,
1063
1063
  );
1064
1064
  }
1065
- process.exit(0);
1065
+ // Under `node --test` a process.exit(0) in teardown would swallow assertion
1066
+ // failures of the very tests that drive this class (R15 cold review P1-1).
1067
+ if (!process.env.NODE_TEST_CONTEXT) process.exit(0);
1066
1068
  }
1067
1069
 
1068
1070
  private reattachRef() {
@@ -1153,7 +1155,7 @@ export class App {
1153
1155
  const session = this.sessions.find((x) => x.id === this.sessionId);
1154
1156
  const right =
1155
1157
  this.view === "agent" && session
1156
- ? `${this.device.id}:${session.name}:${this.agentId ?? 1}`
1158
+ ? `${sanitizeTerminal(this.device.id)}:${sanitizeTerminal(session.name)}:${this.agentId ?? 1}`
1157
1159
  : this.view === "agent"
1158
1160
  ? "no workspace"
1159
1161
  : "j/k move · ↵ open";
@@ -1218,10 +1220,10 @@ export class App {
1218
1220
  // the web shows a banner — the TUI used to show a healthy branch chip
1219
1221
  // while the repo was mid-merge with conflicts.
1220
1222
  const gitChip = g?.repo
1221
- ? ` ${c.muted("⎇")} ${c.text(g.branch ?? g.head ?? "")}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
1223
+ ? ` ${c.muted("⎇")} ${c.text(sanitizeTerminal(g.branch ?? g.head ?? ""))}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
1222
1224
  : "";
1223
1225
  lines.push(
1224
- `${c.muted(this.device.id)} ${c.muted("›")} ${c.text(session?.name ?? "—")} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
1226
+ `${c.muted(sanitizeTerminal(this.device.id))} ${c.muted("›")} ${c.text(sanitizeTerminal(session?.name ?? "—"))} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
1225
1227
  `${STATE_COLOR[state](STATE_GLYPH[state] + " " + (this.busy() ? "working" : "idle"))} ` +
1226
1228
  // Catalog miss renders "?" not "—" (R5 finding 5): unknown window ≠ no usage.
1227
1229
  `${c.muted("ctx")} ${ctx === undefined ? c.muted("?") : c.accent(rep("█", filled)) + c.muted(rep("░", barW - filled)) + " " + c.muted(`${ctx}%`)}`,
@@ -1271,7 +1273,9 @@ export class App {
1271
1273
  const s = this.model.state;
1272
1274
  // Display-width loop wrap (R5 finding 1): the old single-split leaked the
1273
1275
  // remainder of every overlong line to pi-tui's hard clip. See wrap.ts.
1274
- const wrap = (text: string, indent = " ") => wrapByColumn(text, w, indent);
1276
+ // R15 (run-2 h15): transcript payloads are model/tool-controlled — the
1277
+ // sanitize happens HERE, at the data boundary, before any styling/wrap.
1278
+ const wrap = (text: string, indent = " ") => wrapByColumn(sanitizeTerminal(text), w, indent);
1275
1279
  if (this.tab === "transcript") {
1276
1280
  const lines: string[] = [];
1277
1281
  let turn = 0;
@@ -1288,15 +1292,15 @@ export class App {
1288
1292
  else if (b.type === "text") lines.push(...wrap(b.text));
1289
1293
  else if (b.type === "tool") {
1290
1294
  const glyph = b.call.status === "error" ? c.err("✗") : b.call.status === "running" ? c.warn("◐") : c.ok("✓");
1291
- const args = JSON.stringify(b.call.args ?? {}) || "";
1292
- lines.push(` ${glyph} ${c.bold(b.call.name)} ${c.muted(this.expand ? args.slice(0, w - 8) : args.slice(0, Math.max(10, w - 20)))}`);
1295
+ const args = sanitizeTerminal(JSON.stringify(b.call.args ?? {}) || "");
1296
+ lines.push(` ${glyph} ${c.bold(sanitizeTerminal(b.call.name))} ${c.muted(this.expand ? args.slice(0, w - 8) : args.slice(0, Math.max(10, w - 20)))}`);
1293
1297
  const out = b.call.output ?? b.call.result ?? "";
1294
1298
  if (typeof out === "string" && out)
1295
1299
  for (const l of (this.expand ? out.split("\n") : out.split("\n").slice(0, 6)))
1296
- lines.push(` ${c.muted(l.slice(0, w - 6))}`);
1300
+ lines.push(` ${c.muted(sanitizeTerminal(l).slice(0, w - 6))}`);
1297
1301
  }
1298
1302
  }
1299
- if (item.error) lines.push(` ${c.err(item.error.slice(0, w - 4))}`);
1303
+ if (item.error) lines.push(` ${c.err(sanitizeTerminal(item.error).slice(0, w - 4))}`);
1300
1304
  lines.push("");
1301
1305
  }
1302
1306
  }
@@ -1307,7 +1311,7 @@ export class App {
1307
1311
  const lines: string[] = [];
1308
1312
  for (const item of s.inbox)
1309
1313
  lines.push(
1310
- ` ${c.warn("◆")} ${c.text(`${item.mode === "steer" ? "steer" : "queued"}: ${(item.content ?? "context update").replace(/\s+/g, " ").slice(0, w - 20)}`)}`,
1314
+ ` ${c.warn("◆")} ${c.text(`${item.mode === "steer" ? "steer" : "queued"}: ${sanitizeTerminal(item.content ?? "context update").replace(/\s+/g, " ").slice(0, w - 20)}`)}`,
1311
1315
  );
1312
1316
  const bg = this.agentId === undefined ? [] : this.session.backgroundTasks(this.agentId);
1313
1317
  for (const t of bg) lines.push(` ${c.accent("◐")} ${c.text(String(t).slice(0, w - 6))}`);
@@ -1325,7 +1329,7 @@ export class App {
1325
1329
  for (const [name, n] of [...counts.entries()].sort((a, b) => b[1] - a[1])) {
1326
1330
  const barW = 16;
1327
1331
  const filled = Math.round((n / max) * barW);
1328
- lines.push(` ${c.text(name.padEnd(14))} ${c.muted(rep("▮", filled))}${c.muted(rep("▯", barW - filled))} ${c.muted(String(n))}`);
1332
+ lines.push(` ${c.text(sanitizeTerminal(name).padEnd(14))} ${c.muted(rep("▮", filled))}${c.muted(rep("▯", barW - filled))} ${c.muted(String(n))}`);
1329
1333
  }
1330
1334
  if (!counts.size) lines.push(c.muted(" no tool calls yet"));
1331
1335
  return lines;
@@ -1371,7 +1375,7 @@ export class App {
1371
1375
  if (this.filter)
1372
1376
  lines.push(c.warn(` filter: ${this.filter} · ${rows.length}/${this.events.length} shown — esc clears`));
1373
1377
  const visible = h - lines.length;
1374
- for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(e.text.slice(0, w - 18))}`);
1378
+ for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(sanitizeTerminal(e.text).slice(0, w - 18))}`);
1375
1379
  return lines;
1376
1380
  }
1377
1381
 
@@ -2,6 +2,7 @@
2
2
  import type { SlashCommand } from "@earendil-works/pi-tui";
3
3
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
4
4
  import type { App } from "./app.ts";
5
+ import { sanitizeTerminal } from "./sanitize.ts";
5
6
  import { Panel, pickAgent, pickDevice, pickModel, pickSession, pickThinking } from "./pickers.ts";
6
7
  import { parsePairArgs, runPairing } from "./pairing.ts";
7
8
  import { gitStateSuffix } from "./views.ts";
@@ -242,7 +243,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
242
243
  new Panel(
243
244
  () => [
244
245
  c.bold(c.accent("dpi-tui")),
245
- c.muted(`${app.device.id} │ ${app.device.url}`),
246
+ c.muted(`${sanitizeTerminal(app.device.id)} │ ${sanitizeTerminal(app.device.url)}`),
246
247
  "",
247
248
  ...KEYS.map(([k, d]) => `${c.secondary(k.padEnd(11))} ${d}`),
248
249
  "",
@@ -13,6 +13,7 @@ import { syncConfigToRegistry, tryLoadNetworkConfig } from "../../dpi-sdk/src/no
13
13
  import { App, type DeviceRef } from "./app.ts";
14
14
  import { pickDevice } from "./pickers.ts";
15
15
  import { emptyDeviceInfo, resolveStartupAction, showWelcome, WELCOME_DEVICE } from "./welcome.ts";
16
+ import { sanitizeTerminal } from "./sanitize.ts";
16
17
 
17
18
  const USAGE = `usage: dpi-tui [device[:session[:agent]]] [options]
18
19
  dpi-tui --url <url> --token <token> [--save <id>]
@@ -213,10 +214,11 @@ if (startup.kind === "welcome") {
213
214
  hubEnv,
214
215
  ),
215
216
  {
216
- notice:
217
+ notice: sanitizeTerminal(
217
218
  isDpiError(e) && e.code === "unauthorized"
218
219
  ? `${device.id}: token rejected by ${device.url}`
219
220
  : `${device.id} is offline at ${device.url} (${(e as Error).message})`,
221
+ ),
220
222
  },
221
223
  );
222
224
  }
@@ -13,6 +13,7 @@ import {
13
13
  } from "@earendil-works/pi-tui";
14
14
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
15
15
  import { agentTree, type TreeNode } from "../../dpi-sdk/src/models.ts";
16
+ import { sanitizeTerminal } from "./sanitize.ts";
16
17
  import type { App } from "./app.ts";
17
18
  import { c, selectTheme } from "./theme.ts";
18
19
 
@@ -259,15 +260,15 @@ export class Panel extends Box {
259
260
  export async function pickSession(app: App) {
260
261
  const tree = await app.client.tree();
261
262
  const items: SelectItem[] = [
262
- { value: "+new", label: "+ New session", description: `choose a directory on ${app.device.id}` },
263
+ { value: "+new", label: "+ New session", description: `choose a directory on ${sanitizeTerminal(app.device.id)}` },
263
264
  ...tree.sessions.map((s) => ({
264
265
  value: s.id,
265
- label: s.name,
266
- description: `${s.cwd.split("/").slice(-2).join("/")} │ ${s.agents.length} agent${s.agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
266
+ label: sanitizeTerminal(s.name),
267
+ description: `${sanitizeTerminal(s.cwd.split("/").slice(-2).join("/"))} │ ${s.agents.length} agent${s.agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
267
268
  })),
268
269
  ];
269
270
  app.overlay(
270
- new Picker(`Sessions on ${app.device.id}`, items, (item) => {
271
+ new Picker(`Sessions on ${sanitizeTerminal(app.device.id)}`, items, (item) => {
271
272
  app.closeOverlay();
272
273
  if (item.value === "+new") return void newSession(app);
273
274
  const s = tree.sessions.find((x) => x.id === item.value)!;
@@ -343,12 +344,12 @@ export function walkDirs(app: App, path: string): Promise<string | undefined | n
343
344
  app.setPending(null);
344
345
  if (!listing) return done(null);
345
346
  const items: SelectItem[] = [
346
- ...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${listing.path}` }] : []),
347
+ ...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${sanitizeTerminal(listing.path)}` }] : []),
347
348
  ...(listing.path ? [{ value: listing.parent ?? "", label: listing.parent ? ".." : "⌂ start dirs" }] : []),
348
- ...listing.dirs.map((d) => ({ value: d.path, label: `${d.name}/` })),
349
+ ...listing.dirs.map((d) => ({ value: d.path, label: `${sanitizeTerminal(d.name)}/` })),
349
350
  ];
350
351
  app.overlay(
351
- new Picker(`Working directory on ${app.device.name}`, items, (item) => {
352
+ new Picker(`Working directory on ${sanitizeTerminal(app.device.name)}`, items, (item) => {
352
353
  app.closeOverlay();
353
354
  if (item.value.startsWith("use:")) done(item.value.slice(4));
354
355
  else void step(item.value);
@@ -366,8 +367,8 @@ function chooseModel(app: App, current?: string) {
366
367
  return new Promise<(typeof app.info.models)[number] | undefined>((done) => {
367
368
  const models = app.info.models;
368
369
  const picker = new Picker(
369
- `Model (${app.device.name})`,
370
- models.map((m) => ({ value: `${m.provider}/${m.id}`, label: m.name, description: `${m.tier} │ ${m.provider}` })),
370
+ `Model (${sanitizeTerminal(app.device.name)})`,
371
+ models.map((m) => ({ value: `${m.provider}/${m.id}`, label: sanitizeTerminal(m.name), description: `${sanitizeTerminal(m.tier)} │ ${sanitizeTerminal(m.provider)}` })),
371
372
  (item) => {
372
373
  app.closeOverlay();
373
374
  done(models.find((m) => `${m.provider}/${m.id}` === item.value));
@@ -436,7 +437,7 @@ export function pickAgent(app: App) {
436
437
  const icon = a.kind === "fork" ? "⑂" : a.kind === "subagent" ? "↳" : "◆";
437
438
  rows.push({
438
439
  value: String(a.id),
439
- label: `${" ".repeat(depth)}${icon} ${a.name}${a.busy ? " ●" : ""}`,
440
+ label: `${" ".repeat(depth)}${icon} ${sanitizeTerminal(a.name)}${a.busy ? " ●" : ""}`,
440
441
  description: [a.kind === "fork" ? `fork @ #${a.forkedAt}` : a.kind, a.background ? `${a.background} bg` : ""]
441
442
  .filter(Boolean)
442
443
  .join(" │ "),
@@ -445,7 +446,7 @@ export function pickAgent(app: App) {
445
446
  }
446
447
  };
447
448
  walk(agentTree(app.device.id, summary, false), 0);
448
- const picker = new Picker(`Agents in ${summary.name}`, rows, (item) => {
449
+ const picker = new Picker(`Agents in ${sanitizeTerminal(summary.name)}`, rows, (item) => {
449
450
  app.closeOverlay();
450
451
  void app.attach(summary.id, Number(item.value));
451
452
  }, () => app.closeOverlay());
@@ -21,6 +21,7 @@ import type { App, DeviceRef } from "./app.ts";
21
21
  import { Picker } from "./pickers.ts";
22
22
  import { parsePairArgs, runPairing, type PairArgs } from "./pairing.ts";
23
23
  import { c } from "./theme.ts";
24
+ import { sanitizeTerminal } from "./sanitize.ts";
24
25
 
25
26
  const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
26
27
 
@@ -277,7 +278,7 @@ export class WelcomePicker extends Picker {
277
278
  export function showWelcome(app: App, opts: { notice?: string } = {}) {
278
279
  const devices = app.registry?.list() ?? [];
279
280
  const subtitle = opts.notice
280
- ? c.err(opts.notice)
281
+ ? c.err(sanitizeTerminal(opts.notice))
281
282
  : c.muted("This is the app — connect a device to get started:");
282
283
  let picked = false; // an action was chosen: closing the overlay is a step, not a quit
283
284
  app.overlay(
package/bin/update.mjs CHANGED
@@ -12,6 +12,8 @@
12
12
  // Everything here is dependency-injected so it can be tested without npm, a
13
13
  // network, or a real daemon.
14
14
  import { spawn } from "node:child_process";
15
+ import { dirname, isAbsolute, join } from "node:path";
16
+ import { accessSync, constants } from "node:fs";
15
17
 
16
18
  /** Numeric triple + prerelease flag. A prerelease counts as older. */
17
19
  export function rank(version) {
@@ -152,15 +154,52 @@ export async function runUpdate(deps) {
152
154
 
153
155
  // ------------------------------------------------------------------ real deps
154
156
 
155
- /** Spawn npm correctly on every platform (npm is npm.cmd on Windows). */
156
- export function spawnNpm(args) {
157
+ function readableFile(p) {
158
+ try {
159
+ accessSync(p, constants.R_OK);
160
+ return true;
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Resolve npm's cli script to an ABSOLUTE .js path (R15: run-1 NV v3-06).
168
+ * cmd.exe resolves a bare `npm.cmd` CURRENT-DIRECTORY-FIRST unless
169
+ * NoDefaultCurrentDirectoryInExePath is set, so a planted npm.cmd in the
170
+ * operator's invoking cwd would execute as the operator during self-update.
171
+ * Spawning node + npm-cli.js with shell:false removes cmd.exe — and therefore
172
+ * any cwd/PATH .cmd search — from the resolution path entirely. Returns null
173
+ * when no known layout matches; the caller then uses the hardened fallback.
174
+ */
175
+ export function resolveNpmCli(nodePath = process.execPath, env = process.env) {
176
+ const binDir = dirname(nodePath);
177
+ const rootDir = dirname(binDir);
178
+ const candidates = [
179
+ env.npm_execpath, // npm itself exports its cli path
180
+ join(binDir, "node_modules", "npm", "bin", "npm-cli.js"), // nodejs.org / nvm4windows layout
181
+ join(rootDir, "lib", "node_modules", "npm", "bin", "npm-cli.js"), // POSIX nvm/prefix layout
182
+ ];
183
+ for (const c of candidates) {
184
+ if (typeof c === "string" && isAbsolute(c) && c.endsWith(".js") && readableFile(c)) return c;
185
+ }
186
+ return null;
187
+ }
188
+
189
+ /** Hardened fallback env for the (unusual) no-npm-cli.js layouts: suppress
190
+ * cmd.exe's current-directory-first .cmd resolution in the child. */
191
+ export function windowsFallbackEnv(env = process.env) {
192
+ return { ...env, NoDefaultCurrentDirectoryInExePath: "1" };
193
+ }
194
+
195
+ /** The fallback child cwd is pinned to a trusted directory — never the
196
+ * operator's invoking cwd, where a planted npm.cmd could live. */
197
+ export function windowsFallbackCwd(env = process.env, nodePath = process.execPath) {
198
+ return env.SystemRoot || dirname(nodePath);
199
+ }
200
+
201
+ function settle(child) {
157
202
  return new Promise((resolve) => {
158
- const onWindows = process.platform === "win32";
159
- const child = spawn(onWindows ? "npm.cmd" : "npm", args, {
160
- stdio: ["ignore", "pipe", "pipe"],
161
- shell: onWindows,
162
- windowsHide: true,
163
- });
164
203
  let output = "";
165
204
  child.stdout?.on("data", (x) => {
166
205
  output += x;
@@ -175,6 +214,29 @@ export function spawnNpm(args) {
175
214
  });
176
215
  }
177
216
 
217
+ /** Spawn npm correctly on every platform (npm is npm.cmd on Windows).
218
+ * win32 NEVER spawns a bare `npm.cmd` through a cwd-searching shell when an
219
+ * absolute npm-cli.js can be resolved (R15). */
220
+ export function spawnNpm(args) {
221
+ const onWindows = process.platform === "win32";
222
+ if (!onWindows) {
223
+ return settle(spawn("npm", args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));
224
+ }
225
+ const cli = resolveNpmCli();
226
+ if (cli) {
227
+ return settle(spawn(process.execPath, [cli, ...args], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));
228
+ }
229
+ return settle(
230
+ spawn("npm.cmd", args, {
231
+ stdio: ["ignore", "pipe", "pipe"],
232
+ shell: true,
233
+ windowsHide: true,
234
+ env: windowsFallbackEnv(),
235
+ cwd: windowsFallbackCwd(),
236
+ }),
237
+ );
238
+ }
239
+
178
240
  export async function fetchLatestVersion() {
179
241
  const res = await fetch("https://registry.npmjs.org/my-durable/latest", {
180
242
  headers: { accept: "application/json" },
package/deploy/Caddyfile CHANGED
@@ -12,7 +12,7 @@
12
12
  # exempt (exact path+method): GET /healthz · POST /api/pair/start ·
13
13
  # POST /api/pair/verify · POST /api/pair/request (device-initiated
14
14
  # enrollment — the device holds no Basic credential by design) ·
15
- # GET /share/* (public capability page — the 18-byte token IS the boundary) ·
15
+ # GET /share/<token> (public capability page — the 20-32-char token IS the boundary; R15 narrowed the matcher to the token shape) ·
16
16
  # GET /api/tunnel (WS upgrade) — everything else — including WRONG METHODS
17
17
  # on the exempt paths — requires HTTP Basic auth, and the Authorization
18
18
  # header is STRIPPED before the hub so device tokens and admin credentials
@@ -77,7 +77,10 @@ https://{$DPI_PUBLIC_HOST} {
77
77
  }
78
78
  @share {
79
79
  method GET
80
- path /share/*
80
+ # R15 (run-2 h12): exempt ONLY the token-shaped share page (mirrors
81
+ # shares.ts isToken) — a bare /share/* wildcard also exempted the hub's
82
+ # SPA fallback, serving the operator app shell anonymously.
83
+ path_regexp ^/share/[A-Za-z0-9_-]{20,32}$
81
84
  }
82
85
  @healthz {
83
86
  method GET
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.68",
3
+ "version": "0.0.70",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {