my-durable 0.0.66 → 0.0.68

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.
@@ -7,7 +7,7 @@
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-d3YKeCCM.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-CpNu1wqa.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-DSU1QhGO.css">
12
12
  </head>
13
13
  <body>
@@ -3,8 +3,23 @@
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
7
 
7
- export const deviceClient = (id: string) => new DpiClient(`/api/devices/${encodeURIComponent(id)}`);
8
+ // R13 (R9-6.3 FE): the collapse of identical un-keyed creates is an accepted
9
+ // retry-safety tradeoff — but it must be VISIBLE. The device's replay verdict
10
+ // rides the tunnel envelope, the hub surfaces Idempotent-Replay, and the SDK
11
+ // hook turns it into a toast naming the escape hatch (own idempotency-key).
12
+ let replayToastAt = 0;
13
+ export const deviceClient = (id: string) =>
14
+ new DpiClient(`/api/devices/${encodeURIComponent(id)}`, undefined, {
15
+ onIdempotentReplay: (path) => {
16
+ // Replays can arrive in bursts (a re-connected UI re-firing identical
17
+ // creates) — one toast per 30 s is plenty of signal.
18
+ if (Date.now() - replayToastAt < 30_000) return;
19
+ replayToastAt = Date.now();
20
+ notify(`Replayed an earlier identical request (${path}) — send a custom idempotency key for deliberate repeats.`);
21
+ },
22
+ });
8
23
 
9
24
  async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
10
25
  const r = await fetch(`/api${path}`, {
@@ -109,6 +109,12 @@ export class SlidingWindows {
109
109
  constructor(
110
110
  private readonly policy: WindowPolicy,
111
111
  private readonly now: () => number = Date.now,
112
+ /** Audit run-1: per-key live count at/above this floor ENFORCES a block for
113
+ * the caller (GA-06 — never forgotten while anything weaker could go). A
114
+ * sub-threshold entry blocks nobody, so when the table is full it is
115
+ * evicted to admit a fresh key instead of refusing it. 0 = every entry is
116
+ * evictable. */
117
+ private readonly enforcingFloor = 0,
112
118
  ) {}
113
119
 
114
120
  size(): number {
@@ -130,6 +136,7 @@ export class SlidingWindows {
130
136
  const list = known ? this.prune(key, known, t) : [];
131
137
  if (!this.map.has(key)) {
132
138
  if (this.map.size >= this.policy.maxKeys) this.reclaim(t);
139
+ if (this.map.size >= this.policy.maxKeys) this.evictNonEnforcing(t);
133
140
  if (this.map.size >= this.policy.maxKeys) return false;
134
141
  }
135
142
  // Past the cap the oldest entries are kept: the key stays over any sane threshold until they expire.
@@ -142,6 +149,7 @@ export class SlidingWindows {
142
149
  saturatedFor(key: string): boolean {
143
150
  if (this.map.has(key) || this.map.size < this.policy.maxKeys) return false;
144
151
  this.reclaim(this.now());
152
+ if (this.map.size >= this.policy.maxKeys) this.evictNonEnforcing(this.now());
145
153
  return this.map.size >= this.policy.maxKeys;
146
154
  }
147
155
 
@@ -162,4 +170,18 @@ export class SlidingWindows {
162
170
  this.lastReclaim = t;
163
171
  for (const [key, list] of this.map) this.prune(key, list, t);
164
172
  }
173
+
174
+ /** Audit run-1: make room for a fresh key by dropping the OLDEST-inserted
175
+ * entry whose live count is below the enforcing floor (Map iterates in
176
+ * insertion order). GA-06 intact: an enforced counter is only ever evicted
177
+ * when nothing weaker remains. */
178
+ private evictNonEnforcing(t: number): void {
179
+ for (const [key, list] of this.map) {
180
+ const live = list.filter((ts) => t - ts < this.policy.windowMs);
181
+ if (live.length < this.enforcingFloor) {
182
+ this.map.delete(key);
183
+ return;
184
+ }
185
+ }
186
+ }
165
187
  }
@@ -117,6 +117,9 @@ interface CodeEntry {
117
117
  expiresAt: number;
118
118
  cancelled: boolean;
119
119
  enrollmentId?: string;
120
+ /** Audit run-1: minted by the UNAUTHENTICATED device-initiated flow — counts
121
+ * against the deviceMintedCodes sub-cap, not the operator's reserve. */
122
+ deviceMinted?: true;
120
123
  }
121
124
 
122
125
  /** One live pairing request as the admin list renders it (no secrets). */
@@ -199,6 +202,12 @@ export class PairingService {
199
202
  maxKeys: IP_BUCKET_MAX_KEYS,
200
203
  },
201
204
  this.now,
205
+ // Audit run-1: only counters AT/ABOVE the enforcement threshold are
206
+ // protected from eviction when the table is full; a sub-threshold entry
207
+ // blocks nobody, so a fresh key is admitted instead of inheriting a 429
208
+ // created by other keys' failures (a zero-failure source must never be
209
+ // blocked by table pressure).
210
+ PAIR_RATE_LIMITS.verifyFails.perWindow,
202
211
  );
203
212
  }
204
213
 
@@ -279,6 +288,7 @@ export class PairingService {
279
288
  code,
280
289
  expiresAt: now + CODE_TTL_MS,
281
290
  cancelled: false,
291
+ ...(actor === "device" ? { deviceMinted: true as const } : {}),
282
292
  };
283
293
  this.deps.audit.append({
284
294
  actor,
@@ -327,6 +337,11 @@ export class PairingService {
327
337
  return this.fail(429, "rate_limited", "Too many pairing failures; slow down", 60_000);
328
338
  const taken = this.createLimiter.take(ip);
329
339
  if (!taken.ok) return this.rateLimited(taken, "Too many pairing requests; slow down");
340
+ // Audit run-1: the UNAUTH mint draws from its own sub-cap — the operator's
341
+ // reserve (codes − deviceMintedCodes slots) can never be exhausted by
342
+ // anonymous visitors, so admin minting stays available under attack.
343
+ if (this.deviceMintedCount() >= PAIR_RAM_CAPS.deviceMintedCodes)
344
+ return this.fail(429, "rate_limited", "Too many device-initiated requests; retry later", 60_000);
330
345
  if (this.codes.size >= PAIR_RAM_CAPS.codes)
331
346
  return this.fail(429, "rate_limited", "Pairing capacity reached; retry later", 60_000);
332
347
  const request = body as { type?: unknown } | null;
@@ -950,7 +965,12 @@ export class PairingService {
950
965
  const code = this.codes.get(codeId);
951
966
  if (!code) return this.fail(404, "code_invalid", "Unknown code");
952
967
  const enrollment = code.enrollmentId ? this.enrollments.get(code.enrollmentId) : undefined;
953
- if (enrollment?.issued)
968
+ // R14 cold review: an IN-FLIGHT issuance is already committing a credential
969
+ // (registry row + tunnel token) — cancelling mid-flight would delete the
970
+ // bookkeeping while the device still receives a live pair.token, stranding
971
+ // a ghost credential no sweep can ever see. Treat in-flight as issued:
972
+ // the operator revokes the resulting credential instead.
973
+ if (enrollment?.issued || enrollment?.issuing)
954
974
  return this.fail(409, "already_issued", "Credential already issued; revoke it instead");
955
975
  // Audit row first (as for approve): a cancel that cannot be audited does not take effect.
956
976
  this.deps.audit.append({
@@ -966,7 +986,15 @@ export class PairingService {
966
986
  enrollment.invalidated = true;
967
987
  }
968
988
  const s = this.status(codeId);
969
- return s.ok ? this.ok(s.value) : s;
989
+ if (!s.ok) return s;
990
+ // Audit run-1 (capacity reclaim): an UNISSUED code holds a RAM slot for
991
+ // nothing — cancel now frees it immediately instead of waiting out
992
+ // TTL+grace+sweep, so the operator's own remediation actually restores
993
+ // minting capacity (nothing was issued; no receipt can exist).
994
+ this.byCode.delete(code.code);
995
+ this.codes.delete(codeId);
996
+ if (enrollment) this.enrollments.delete(code.enrollmentId!);
997
+ return s;
970
998
  }
971
999
 
972
1000
  /** GET /api/pair/codes/:codeId (admin) — phase metadata, never a token. */
@@ -1029,6 +1057,14 @@ export class PairingService {
1029
1057
  : this.fail(500, "internal", "status serialization failed");
1030
1058
  }
1031
1059
 
1060
+ /** Audit run-1: live device-minted codes (derived from the map — it cannot
1061
+ * drift from mint/delete/sweep/cancel paths). */
1062
+ private deviceMintedCount(): number {
1063
+ let n = 0;
1064
+ for (const entry of this.codes.values()) if (entry.deviceMinted) n += 1;
1065
+ return n;
1066
+ }
1067
+
1032
1068
  /** Drop expired entries (hub housekeeping). F15: past expiry+grace the
1033
1069
  * entry goes REGARDLESS of issued — receipts hold a plaintext token and
1034
1070
  * grace is exactly how long the device may re-read it. Also forgets idle
@@ -91,23 +91,39 @@ export function proxy(
91
91
  const contentType =
92
92
  typeof upstream.contentType === "string" ? upstream.contentType : undefined;
93
93
  res.status(status).set(LOCKED_DOWN_HEADERS);
94
+ // R13 (R9-6.3 FE): the device's replay verdict surfaces as the standard
95
+ // header — a hub-controlled literal (never a passthrough of arbitrary
96
+ // device header names/values), same trust boundary as the zip label.
97
+ if (upstream.idempotentReplay === true) res.set("Idempotent-Replay", "true");
94
98
  if (!contentType || mediaType(contentType) === "application/json")
95
99
  res.type("application/json").send(body);
96
100
  else {
97
101
  // R8 binary passthrough: base64-flagged device payloads are decoded byte-exact for
98
- // EVERY type; the LABEL is controlled by the hub. Only application/zip (the export
99
- // contract) keeps its type + the device's sanitized download filename — every other
100
- // non-JSON type stays an inert octet-stream attachment (Gate A GA-01), so a hostile
101
- // device cannot rebrand its bytes as html/svg/js at the ADMIN origin.
102
+ // EVERY type; the LABEL is authored by the hub. Only application/zip (the export
103
+ // contract) keeps its type — every other non-JSON type stays an inert octet-stream
104
+ // attachment (Gate A GA-01), and since audit run-1 the zip LABEL is hub-authored
105
+ // too: the device's filename is parsed for convenience, stripped of any extension
106
+ // and charset risk, and ALWAYS re-issued with a forced .zip suffix — a hostile
107
+ // device may not choose the operator's download name (the saved-file rebrand
108
+ // residual of GA-01; the honest device contract is already *.bundle.zip).
102
109
  const payload =
103
110
  upstream.bodyEncoding === "base64"
104
111
  ? Buffer.from(String(upstream.body ?? ""), "base64")
105
112
  : Buffer.from(body, "utf8");
106
113
  const isZip = mediaType(contentType) === "application/zip";
107
- const disposition =
114
+ const m =
108
115
  isZip && typeof upstream.contentDisposition === "string"
109
- ? upstream.contentDisposition
110
- : 'attachment; filename="device-response.bin"';
116
+ ? /filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;\s]+))/i.exec(upstream.contentDisposition)
117
+ : null;
118
+ const stem =
119
+ ((m?.[1]?.replace(/\\(.)/g, "$1") ?? m?.[2] ?? "")
120
+ .replace(/\.[^./\\]*$/, "")
121
+ .replace(/[^A-Za-z0-9._-]/g, "_")
122
+ .replace(/^\.+/, "")
123
+ .slice(0, 80)) || "device-response";
124
+ const disposition = isZip
125
+ ? `attachment; filename="${stem}.zip"`
126
+ : 'attachment; filename="device-response.bin"';
111
127
  res.type(isZip ? contentType : "application/octet-stream")
112
128
  .set("Content-Disposition", disposition)
113
129
  .send(payload);
@@ -29,6 +29,10 @@ export interface TransportResponse {
29
29
  bodyEncoding?: "base64";
30
30
  /** Sanitized Content-Disposition from the device (binary responses); may be undefined. */
31
31
  contentDisposition?: string;
32
+ /** R13 (R9-6.3 FE): the device answered this request with an idempotency
33
+ * REPLAY — the proxy surfaces it as the Idempotent-Replay response header
34
+ * so clients can tell a replay from a fresh create. */
35
+ idempotentReplay?: true;
32
36
  /** Diagnostics: assembled byte count for chunked responses. */
33
37
  rawBytes?: number;
34
38
  }
@@ -103,6 +107,9 @@ export class LanTransport implements DeviceTransport {
103
107
  body: textual ? raw.toString("utf8") : raw.toString("base64"),
104
108
  ...(textual ? {} : { bodyEncoding: "base64" as const }),
105
109
  ...(textual ? {} : { contentDisposition: safeHeaderValue(response.headers.get("content-disposition")) }),
110
+ // R13 (R9-6.3 FE): same replay verdict on the LAN leg — one TransportResponse
111
+ // contract, both transports.
112
+ ...(response.headers.get("idempotent-replay") === "true" ? { idempotentReplay: true as const } : {}),
106
113
  };
107
114
  }
108
115
 
@@ -293,6 +293,7 @@ export class TunnelDispatcher {
293
293
  ...(frame.bodyEncoding === "base64"
294
294
  ? { contentDisposition: safeHeaderValue(frame.contentDisposition) }
295
295
  : {}),
296
+ ...(frame.idempotentReplay === true ? { idempotentReplay: true as const } : {}),
296
297
  });
297
298
  return;
298
299
  }
@@ -335,6 +336,7 @@ export class TunnelDispatcher {
335
336
  body?: unknown;
336
337
  bodyEncoding?: unknown;
337
338
  contentDisposition?: unknown;
339
+ idempotentReplay?: unknown;
338
340
  }
339
341
  | undefined;
340
342
  if (typeof env?.status !== "number" || !Number.isFinite(env.status)) {
@@ -354,6 +356,7 @@ export class TunnelDispatcher {
354
356
  ...(env.bodyEncoding === "base64"
355
357
  ? { contentDisposition: safeHeaderValue(env.contentDisposition) }
356
358
  : {}),
359
+ ...(env.idempotentReplay === true ? { idempotentReplay: true as const } : {}),
357
360
  rawBytes: out.rawBytes,
358
361
  });
359
362
  }
@@ -152,6 +152,11 @@ export class DpiClient {
152
152
  constructor(
153
153
  baseUrl: string,
154
154
  private readonly token?: string,
155
+ /** R13 (R9-6.3 FE): fired when a request's response carried
156
+ * Idempotent-Replay: true — the answer is a REPLAY of an earlier
157
+ * identical request, not a fresh effect. UIs use it to tell the user;
158
+ * clients that need deliberate repeats send their own idempotencyKey. */
159
+ private readonly hooks: { onIdempotentReplay?: (path: string) => void } = {},
155
160
  ) {
156
161
  this.baseUrl = baseUrl.replace(/\/+$/, "");
157
162
  }
@@ -201,6 +206,7 @@ export class DpiClient {
201
206
  (response.status === 401 ? "unauthorized" : response.status === 404 ? "not_found" : "internal");
202
207
  throw new DpiError(code, error?.message ?? `${response.status} ${response.statusText}`, response.status);
203
208
  }
209
+ if (response.headers.get("idempotent-replay") === "true") this.hooks.onIdempotentReplay?.(path);
204
210
  return data as T;
205
211
  }
206
212
 
@@ -120,8 +120,11 @@ export const PAIR_RATE_LIMITS = {
120
120
  verifyTotal: { perMinute: 300, capacity: 300 },
121
121
  } as const;
122
122
 
123
- /** RAM caps for pending pairing state. */
124
- export const PAIR_RAM_CAPS = { codes: 1_000, enrollments: 1_000 } as const;
123
+ /** RAM caps for pending pairing state. `deviceMintedCodes` is the sub-cap for
124
+ * UNAUTHENTICATED device-initiated mints (audit run-1): it keeps ≥ codes −
125
+ * deviceMintedCodes slots reserved for the operator's admin mints, so an
126
+ * anonymous visitor can never 429-lock the operator's own pairing flow. */
127
+ export const PAIR_RAM_CAPS = { codes: 1_000, enrollments: 1_000, deviceMintedCodes: 100 } as const;
125
128
  /** Pairing endpoint body cap. 16 KiB. */
126
129
  export const PAIRING_BODY_MAX_BYTES = 16_384;
127
130
  /** HTTP pairing operation timeout / retry budget. */
@@ -232,6 +232,10 @@ export const TunnelFrame = Type.Union([
232
232
  // sanitized download filename. Absent on the legacy textual envelope.
233
233
  bodyEncoding: Type.Optional(Type.Union([Type.Literal("base64")])),
234
234
  contentDisposition: Type.Optional(Type.String({ maxLength: 200 })),
235
+ // R13 (R9-6.3 FE): the device sets this literal when the loopback response
236
+ // was an idempotency REPLAY; hubs forward it as the Idempotent-Replay
237
+ // response header so clients can tell a replay from a fresh create.
238
+ idempotentReplay: Type.Optional(Type.Literal(true)),
235
239
  }),
236
240
  TunnelControl,
237
241
  Type.Object(
@@ -49,6 +49,7 @@ import { HubMux, type MuxState } from "./hub-mux.ts";
49
49
  import { FOLLOW_TAIL, scrollBy, viewportTop, type ScrollState } from "./scroll.ts";
50
50
  import { wrapByColumn } from "./wrap.ts";
51
51
  import { box, c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
52
+ import { sanitizeTerminal } from "./sanitize.ts";
52
53
 
53
54
  export interface DeviceRef {
54
55
  id: string;
@@ -1021,7 +1022,9 @@ export class App {
1021
1022
  }
1022
1023
 
1023
1024
  notify(message: string, error = false) {
1024
- this.toast = (error ? "✗ " : "") + message;
1025
+ // Audit run-1: toast text often carries device/hub error messages —
1026
+ // strip control sequences before the toast renders to the terminal.
1027
+ this.toast = (error ? "✗ " : "") + sanitizeTerminal(message);
1025
1028
  this.toastTicks = 50;
1026
1029
  this.requestRender();
1027
1030
  }
@@ -1050,10 +1053,13 @@ export class App {
1050
1053
  if (ref) {
1051
1054
  const adhoc = this.device.id === "adhoc";
1052
1055
  const target = adhoc
1053
- ? `--url ${this.device.url} --token <token> -s ${shellWord(ref.session)} -a ${shellWord(ref.agent)}`
1054
- : shellWord(`${this.device.id}:${ref.session}:${ref.agent}`);
1056
+ ? `--url ${this.device.url} --token <token> -s ${shellWord(sanitizeTerminal(ref.session))} -a ${shellWord(sanitizeTerminal(ref.agent))}`
1057
+ : shellWord(`${sanitizeTerminal(this.device.id)}:${sanitizeTerminal(ref.session)}:${sanitizeTerminal(ref.agent)}`);
1058
+ // Audit run-1: the device name/id is hub-supplied — never write it raw to stdout.
1055
1059
  process.stdout.write(
1056
- `\n${c.muted("The agent keeps running on")} ${adhoc ? this.device.name : this.device.id}${c.muted(". Reattach:")}\n just tui attach ${target}\n\n`,
1060
+ `\n${c.muted("The agent keeps running on")} ${sanitizeTerminal(
1061
+ adhoc ? this.device.name : this.device.id,
1062
+ )}${c.muted(". Reattach:")}\n just tui attach ${target}\n\n`,
1057
1063
  );
1058
1064
  }
1059
1065
  process.exit(0);
@@ -9,13 +9,17 @@ import {
9
9
  } from "@earendil-works/pi-tui";
10
10
  import type { ToolCallView, TranscriptItem } from "../../dpi-sdk/src/transcript.ts";
11
11
  import { c, markdownTheme } from "./theme.ts";
12
+ import { sanitizeTerminal } from "./sanitize.ts";
12
13
 
13
14
  const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
14
15
  /** Advanced by the app while a tool runs; running tool rows read it at render time. */
15
16
  export const spinner = { frame: 0 };
16
17
  const TAIL = 6;
17
18
 
18
- /** One styled line, cut to the width. */
19
+ /** One styled line, cut to the width. A STYLED primitive (R14 cold review):
20
+ * inputs are usually pre-styled with the theme's own SGR, so this class must
21
+ * NOT strip escapes — callers sanitize the untrusted PAYLOAD before styling
22
+ * (same data-boundary rule as views.ts). */
19
23
  export class Line implements Component {
20
24
  constructor(public text: string) {}
21
25
  render(width: number) {
@@ -31,7 +35,9 @@ class Wrapped implements Component {
31
35
  private prefix: string,
32
36
  private style: (s: string) => string,
33
37
  private indent = " ",
34
- ) {}
38
+ ) {
39
+ this.text = sanitizeTerminal(text);
40
+ }
35
41
  render(width: number) {
36
42
  const inner = Math.max(1, width - 2);
37
43
  const lines = this.text.split("\n").flatMap((l) => (l ? wrapTextWithAnsi(l, inner) : [""]));
@@ -59,8 +65,11 @@ export class ToolRow implements Component {
59
65
  const s = this.call.status;
60
66
  const icon =
61
67
  s === "running" ? c.warn(SPIN[spinner.frame % SPIN.length]) : s === "done" ? c.ok("✓") : s === "error" ? c.err("✗") : c.muted("○");
62
- const head = truncateToWidth(`${icon} ${c.bold(this.call.name)} ${c.muted(argsPreview(this.call))}`, width);
63
- const body = (this.call.result ?? this.call.output ?? "").replace(/\s+$/, "");
68
+ const head = truncateToWidth(
69
+ `${icon} ${c.bold(sanitizeTerminal(this.call.name))} ${c.muted(sanitizeTerminal(argsPreview(this.call)))}`,
70
+ width,
71
+ );
72
+ const body = sanitizeTerminal(this.call.result ?? this.call.output ?? "").replace(/\s+$/, "");
64
73
  if (!body) return [head];
65
74
  const all = body.split("\n");
66
75
  const shown = this.expand ? all : all.slice(-TAIL);
@@ -93,22 +102,23 @@ class AssistantView extends Stack {
93
102
  const parts: Component[] = [new Line("")];
94
103
  item.blocks.forEach((block, i) => {
95
104
  if (block.type === "text") {
105
+ const safe = sanitizeTerminal(block.text);
96
106
  let md = this.markdown.get(i);
97
107
  if (!md) {
98
- md = new Markdown(block.text, 0, 0, markdownTheme);
108
+ md = new Markdown(safe, 0, 0, markdownTheme);
99
109
  this.markdown.set(i, md);
100
- } else md.setText(block.text);
110
+ } else md.setText(safe);
101
111
  parts.push(md);
102
112
  } else if (block.type === "thinking") {
103
113
  parts.push(
104
114
  expand
105
115
  ? new Wrapped(block.text, c.muted("∴ "), (s) => c.italic(c.muted(s)))
106
- : new Line(c.italic(c.muted(`∴ ${block.text.replace(/\s+/g, " ")}`))),
116
+ : new Line(c.italic(c.muted(`∴ ${sanitizeTerminal(block.text).replace(/\s+/g, " ")}`))),
107
117
  );
108
118
  } else parts.push(new ToolRow(block.call, expand));
109
119
  });
110
120
  if (item.streaming && !item.blocks.length) parts.push(new Line(c.muted("…")));
111
- if (item.error) parts.push(new Line(c.err(`! ${item.error}`)));
121
+ if (item.error) parts.push(new Line(c.err(`! ${sanitizeTerminal(item.error)}`)));
112
122
  this.parts = parts;
113
123
  }
114
124
  }
@@ -130,7 +140,7 @@ export function itemComponent(item: TranscriptItem, expand: boolean): Component
130
140
  case "tool":
131
141
  return new ToolRow(item.call, expand);
132
142
  default:
133
- return new Line(c.muted(`── ${item.text} `));
143
+ return new Line(c.muted(`── ${sanitizeTerminal(item.text)} `));
134
144
  }
135
145
  }
136
146
 
@@ -0,0 +1,16 @@
1
+ // Audit run-1 (terminal escape injection): strings from lower-trust principals
2
+ // (model/tool output inside a session, paired-device names/status/git fields,
3
+ // hub relays) must never carry terminal control sequences into the operator's
4
+ // terminal. The vendored pi-tui passes ESC-initiated sequences through as
5
+ // zero-width text and writes document lines verbatim to process.stdout, so the
6
+ // APP layer owns this invariant: strip ESC-initiated sequences (OSC/CSI/DCS/
7
+ // APC/anything ESC-led), C0 controls except \n (0A) and \t (09), and the C1
8
+ // range (U+0080-U+009F — U+009B is CSI in 8-bit-mode emulators). A trailing
9
+ // lone ESC is dropped too. Width accounting then matches what is emitted.
10
+ const ESC_SEQ = /\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[PX^_][^\x1b]*\x1b\\|.)/g;
11
+ const C0 = /[\u0000-\u0008\u000B-\u001F\u007F\u0080-\u009F]/g;
12
+
13
+ /** Neutralize terminal control sequences in an untrusted string before render/stdout. */
14
+ export function sanitizeTerminal(s: string): string {
15
+ return s.replace(ESC_SEQ, "").replace(C0, "");
16
+ }
@@ -7,6 +7,7 @@ import type { SessionSummary } from "../../dpi-sdk/src/api.ts";
7
7
  import type { GitStatus } from "../../dpi-sdk/src/client.ts";
8
8
  import type { DeviceRow } from "../../dpi-sdk/src/node/registry.ts";
9
9
  import { c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
10
+ import { sanitizeTerminal } from "./sanitize.ts";
10
11
 
11
12
  export type View = "herd" | "network" | "agent" | "log";
12
13
 
@@ -40,6 +41,9 @@ export class DynamicBlock implements Component {
40
41
  invalidate() {}
41
42
  }
42
43
  const padTo = (s: string, w: number) => s + rep(" ", Math.max(0, w - visibleWidth(s)));
44
+ // NOTE (audit run-1): untrusted row DATA is sanitized at the data boundary
45
+ // (herdRows/networkRows/… builders), NOT here — styled composites pass through
46
+ // fit() and would lose the theme's own SGR colors to the strip.
43
47
  const fit = (s: string, w: number) =>
44
48
  padTo(truncateToWidth(s, Math.max(0, w), "…"), Math.max(0, w));
45
49
  const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
@@ -104,9 +108,14 @@ export function herdRows(sessions: SessionSummary[], filter = "", branchOf?: (cw
104
108
  groups.set(key, list);
105
109
  }
106
110
  for (const [dir, list] of groups) {
107
- out.push({ kind: "group", label: dir });
111
+ out.push({ kind: "group", label: sanitizeTerminal(dir) });
108
112
  for (const s of list)
109
- out.push({ kind: "session", label: s.name, sessionId: s.id, branch: branchOf?.(s.cwd) });
113
+ out.push({
114
+ kind: "session",
115
+ label: sanitizeTerminal(s.name),
116
+ sessionId: s.id,
117
+ branch: branchOf ? sanitizeTerminal(branchOf(s.cwd) ?? "") || undefined : undefined,
118
+ });
110
119
  }
111
120
  return out;
112
121
  }
@@ -138,7 +147,7 @@ export function renderHerd(
138
147
  const cursorRow = rows[opts.cursor ?? 0];
139
148
  for (const row of rows) {
140
149
  if (row.kind === "group") {
141
- const group = sessions.filter((s) => basename(s.cwd) === row.label);
150
+ const group = sessions.filter((s) => sanitizeTerminal(basename(s.cwd)) === row.label);
142
151
  const busy = group.filter((s) => s.busy).length;
143
152
  const header = `${c.muted("~/")}${c.text(row.label)}${c.muted("/")} ${c.muted(`· ${group.length} agent${group.length === 1 ? "" : "s"} · ${busy} busy`)}`;
144
153
  // The cursor is drawn on headers too: a keypress must always be visible,
@@ -157,8 +166,8 @@ export function renderHerd(
157
166
  const agents = `${s.agents.length}${forks ? `⑂${forks}` : ""}${subs ? `↳${subs}` : ""}`;
158
167
  const branch = row.branch ? ` ${c.muted(`⎇ ${fit(row.branch, 10)}`)}` : "";
159
168
  let line =
160
- `${marker}${fit(selected ? c.bold(s.name) : s.name, cols.name - visibleWidth(branch))}${branch} ${fit(state, cols.state)}` +
161
- (showModel ? ` ${fit(c.muted(basename(s.model) || s.model), cols.model)}` : "") +
169
+ `${marker}${fit(selected ? c.bold(row.label) : row.label, cols.name - visibleWidth(branch))}${branch} ${fit(state, cols.state)}` +
170
+ (showModel ? ` ${fit(c.muted(sanitizeTerminal(basename(s.model) || s.model)), cols.model)}` : "") +
162
171
  ` ${fit(c.muted(agents), cols.agents)}`;
163
172
  if (showAge) line += ` ${fit(c.muted(ageOf(s.createdAt)), cols.age)}`;
164
173
  lines.push(atCursor && !selected ? c.inverse(fit(line, w)) : fit(line, w));
@@ -199,12 +208,12 @@ export function networkRows(devices: DeviceRow[], currentDeviceId: string, filte
199
208
  continue;
200
209
  out.push({
201
210
  kind: "device",
202
- label: d.name || d.id,
211
+ label: sanitizeTerminal(d.name || d.id),
203
212
  deviceId: d.id,
204
213
  current: d.id === currentDeviceId,
205
214
  });
206
215
  for (const s of d.lastTree?.sessions ?? [])
207
- out.push({ kind: "session", label: s.name, deviceId: d.id, sessionId: s.id });
216
+ out.push({ kind: "session", label: sanitizeTerminal(s.name), deviceId: d.id, sessionId: s.id });
208
217
  }
209
218
  return out;
210
219
  }
@@ -274,7 +283,7 @@ export function renderStatusbar(
274
283
  : ["j/k move", "↵ open", "1-4 views", "⇥ tabs", "esc agent"];
275
284
  // Catalog miss degrades to "?" (R5 finding 5): "—" read as "no usage yet",
276
285
  // when it actually means the window is unknown — a different problem.
277
- const right = `${c.muted("ctx")} ${opts.ctxLeft === undefined ? c.muted("?") : c.text(`${opts.ctxLeft}%`)}${opts.background ? c.muted(` · ${opts.background} bg`) : ""} ${c.muted("dev")} ${c.text(fit(opts.device, 18))}`;
286
+ const right = `${c.muted("ctx")} ${opts.ctxLeft === undefined ? c.muted("?") : c.text(`${opts.ctxLeft}%`)}${opts.background ? c.muted(` · ${opts.background} bg`) : ""} ${c.muted("dev")} ${c.text(fit(sanitizeTerminal(opts.device), 18))}`;
278
287
  const left = `${chip} ${keys.map((k) => c.muted(k)).join(c.muted(" • "))}`;
279
288
  const gap = Math.max(1, w - visibleWidth(left) - visibleWidth(right));
280
289
  return c.inverse(padTo(fit(`${left}${rep(" ", gap)}${right}`, w), w));
@@ -325,7 +334,7 @@ export function renderHerdPanel(
325
334
  if (!s) {
326
335
  const lines = [
327
336
  c.muted(" OVERVIEW"),
328
- ` ${c.bold(device ?? "device")}`,
337
+ ` ${c.bold(sanitizeTerminal(device ?? "device"))}`,
329
338
  ` ${c.muted("no session selected")}`,
330
339
  "",
331
340
  ` ${c.muted("n")} ${c.text("new session")}`,
@@ -335,18 +344,21 @@ export function renderHerdPanel(
335
344
  ];
336
345
  return lines.slice(0, h).map((l) => fit(l, w));
337
346
  }
347
+ // R14 cold review: the panel renders the SAME device-sourced fields as the
348
+ // table — name, cwd basename, model, agent names — so it sanitizes them at
349
+ // the data boundary exactly like herdRows/renderHerd do.
338
350
  const agents = s.agents.map((a) =>
339
- a.kind === "fork" ? `⑂ ${a.name}` : a.kind === "subagent" ? `↳ ${a.name}` : `● ${a.name}`,
351
+ a.kind === "fork" ? `⑂ ${sanitizeTerminal(a.name)}` : a.kind === "subagent" ? `↳ ${sanitizeTerminal(a.name)}` : `● ${sanitizeTerminal(a.name)}`,
340
352
  );
341
353
  // A session on exactly the device's default model says so, muted — the same
342
354
  // signal the web dialog's "(device default)" row carries.
343
355
  const onDefault = defaultModel !== undefined && s.model === defaultModel;
344
356
  const lines = [
345
357
  c.muted(" OVERVIEW"),
346
- ` ${c.bold(s.name)}`,
347
- ` ${c.muted(basename(s.cwd))} ${c.muted("·")} ${c.text(basename(s.model) || s.model)}${onDefault ? c.muted(" (default)") : ""}`,
358
+ ` ${c.bold(sanitizeTerminal(s.name))}`,
359
+ ` ${c.muted(sanitizeTerminal(basename(s.cwd)))} ${c.muted("·")} ${c.text(sanitizeTerminal(basename(s.model) || s.model))}${onDefault ? c.muted(" (default)") : ""}`,
348
360
  git?.repo
349
- ? ` ${c.muted("⎇")} ${c.text(git.branch ?? git.head ?? "?")}${c.muted("±")}${c.text(String((git.staged ?? 0) + (git.unstaged ?? 0) + (git.untracked ?? 0)))}${git.ahead ? c.text(` ↑${git.ahead}`) : ""}${git.behind ? c.text(` ↓${git.behind}`) : ""}${git.worktreeOf ? c.muted(" · worktree") : ""}`
361
+ ? ` ${c.muted("⎇")} ${c.text(sanitizeTerminal(git.branch ?? git.head ?? "?"))}${c.muted("±")}${c.text(String((git.staged ?? 0) + (git.unstaged ?? 0) + (git.untracked ?? 0)))}${git.ahead ? c.text(` ↑${git.ahead}`) : ""}${git.behind ? c.text(` ↓${git.behind}`) : ""}${git.worktreeOf ? c.muted(" · worktree") : ""}`
350
362
  : "",
351
363
  "",
352
364
  ` ${c.muted("state")} ${STATE_COLOR[sessionState(s)](sessionState(s))}`,