my-durable 0.0.67 → 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.
@@ -468,6 +468,29 @@ export class DevicePairing {
468
468
  // Offer v3: challenge the hub to prove it owns the pinned identity key.
469
469
  const hubNonce = kfp ? randomBytes(32).toString("base64url") : undefined;
470
470
 
471
+ // Synchronous slot reservation (audit run-1 HIGH, pairing TOCTOU): the busy
472
+ // gate and status() must hold from HERE — before the first await — not from
473
+ // the tail of completeChallenge, or a concurrent start() slips through the
474
+ // window between the check above and that assignment and hijacks the
475
+ // enrollment. completeChallenge upgrades the reservation in place (same
476
+ // operationId); any throw below clears it; cancel() in the window wins
477
+ // (completeChallenge refuses to resurrect a cancelled slot).
478
+ this.pending = {
479
+ operationId,
480
+ hubOrigin: origin,
481
+ code,
482
+ requestId,
483
+ deviceUid,
484
+ deviceName: this.deviceName,
485
+ keyFingerprint: keypair.fingerprint,
486
+ proof: { type: "pair.response", v: 1, enrollmentId: "", nonce: "", signature: "" },
487
+ hubId: "",
488
+ ...(kfp ? { kfp } : {}),
489
+ expiresAt: this.now() + 300_000,
490
+ startedAt: this.now(),
491
+ abort: new AbortController(),
492
+ };
493
+
471
494
  // Device-initiated enrollment (code-less): the hub mints the code and answers
472
495
  // with its challenge in ONE round trip, so the request carries the machine's
473
496
  // full identity — the shape the operator approves against.
@@ -482,18 +505,37 @@ export class DevicePairing {
482
505
  clientTime: this.now(),
483
506
  ...(hubNonce ? { hubNonce } : {}),
484
507
  };
485
- if (!code) {
486
- const ack = (await this.hubFetch(origin, "/api/pair/request", {
487
- type: "pair.device-request",
508
+ try {
509
+ if (!code) {
510
+ const ack = (await this.hubFetch(origin, "/api/pair/request", {
511
+ type: "pair.device-request",
512
+ v: 1,
513
+ ...body,
514
+ })) as { code?: string; challenge?: unknown };
515
+ if (typeof ack.code !== "string" || !ack.challenge)
516
+ throw err("invalid", `Unexpected hub response: ${JSON.stringify(ack).slice(0, 200)}`);
517
+ code = ack.code;
518
+ return this.completeChallenge(
519
+ origin,
520
+ ack.challenge as Challenge,
521
+ code,
522
+ kfp,
523
+ hubNonce,
524
+ operationId,
525
+ requestId,
526
+ deviceUid,
527
+ keypair,
528
+ );
529
+ }
530
+ const challenge = (await this.hubFetch(origin, "/api/pair/start", {
531
+ type: "pair.request",
488
532
  v: 1,
489
533
  ...body,
490
- })) as { code?: string; challenge?: unknown };
491
- if (typeof ack.code !== "string" || !ack.challenge)
492
- throw err("invalid", `Unexpected hub response: ${JSON.stringify(ack).slice(0, 200)}`);
493
- code = ack.code;
534
+ code,
535
+ })) as Challenge;
494
536
  return this.completeChallenge(
495
537
  origin,
496
- ack.challenge as Challenge,
538
+ challenge,
497
539
  code,
498
540
  kfp,
499
541
  hubNonce,
@@ -502,24 +544,15 @@ export class DevicePairing {
502
544
  deviceUid,
503
545
  keypair,
504
546
  );
547
+ } catch (e) {
548
+ // The reservation dies with this attempt unless cancel()/a rival already
549
+ // replaced it (operationId mismatch → leave the survivor alone).
550
+ if (this.pending?.operationId === operationId) {
551
+ this.pending.abort.abort();
552
+ this.pending = undefined;
553
+ }
554
+ throw e;
505
555
  }
506
- const challenge = (await this.hubFetch(origin, "/api/pair/start", {
507
- type: "pair.request",
508
- v: 1,
509
- ...body,
510
- code,
511
- })) as Challenge;
512
- return this.completeChallenge(
513
- origin,
514
- challenge,
515
- code,
516
- kfp,
517
- hubNonce,
518
- operationId,
519
- requestId,
520
- deviceUid,
521
- keypair,
522
- );
523
556
  }
524
557
 
525
558
  /**
@@ -597,6 +630,13 @@ export class DevicePairing {
597
630
  startedAt: this.now(),
598
631
  abort: new AbortController(),
599
632
  };
633
+ // cancel() may have aborted the reservation while the hub challenge was in
634
+ // flight — cancel promised to stop the LOCAL operation, so never resurrect
635
+ // the slot: abort this attempt and report the (no longer pairing) state.
636
+ if (this.pending?.operationId !== operationId) {
637
+ pending.abort.abort();
638
+ return this.status();
639
+ }
600
640
  this.pending = pending;
601
641
  void this.pollLoop(pending).catch(() => undefined);
602
642
  return this.status();
@@ -1,6 +1,7 @@
1
1
  // REST v1. Every route requires the device token (see auth.ts). Session refs are a UUID or a
2
2
  // unique name; agent refs are a numeric id, `main`, or a unique name.
3
3
  import { Router, type Request, type Response, type NextFunction } from "express";
4
+ import { isAbsolute, resolve } from "node:path";
4
5
  import { createReadStream } from "node:fs";
5
6
  import { pipeline } from "node:stream/promises";
6
7
  import type { Conversation, Harness } from "@earendil-works/pi-durable";
@@ -191,12 +192,29 @@ export function v1(
191
192
  const op = String(body.op ?? "") as GitOp;
192
193
  if (!GIT_OPS.includes(op)) throw invalid(`Unknown git op ${String(body.op ?? "")}`);
193
194
  const path = await gitPath(body.path);
195
+ // Audit run-1 (worktree-target containment): the worktree DESTINATION is an
196
+ // fs path like any other — it must pass the same start-dir choke point as
197
+ // `path` above, or worktree-add/remove plants/deletes checkouts anywhere
198
+ // the daemon user can write (routes.ts is the enforcing layer; git.ts has
199
+ // no store/start-dir context).
200
+ const rawTarget =
201
+ (op === "worktree-add" || op === "worktree-remove") && typeof body.target === "string"
202
+ ? // Relative targets keep git's own semantics — resolved against the
203
+ // REPO, not the daemon cwd — before the containment choke point.
204
+ isAbsolute(body.target)
205
+ ? body.target
206
+ : resolve(path, body.target)
207
+ : body.target;
208
+ const target =
209
+ typeof rawTarget === "string" && (op === "worktree-add" || op === "worktree-remove")
210
+ ? await store.containedPath(rawTarget)
211
+ : rawTarget;
194
212
  try {
195
213
  const out = await gitOp(path, op, {
196
214
  ref: body.ref,
197
215
  branch: body.branch,
198
216
  message: body.message,
199
- target: body.target,
217
+ target,
200
218
  files: Array.isArray(body.files) ? body.files.map(String).slice(0, 500) : undefined,
201
219
  // booleans stay booleans: gitOp validates names/refs itself.
202
220
  create: body.create === true,
@@ -71,7 +71,15 @@ const CODE_PATTERN = /^[0-9a-f]{8}$/;
71
71
  */
72
72
  export interface TelegramUpdate {
73
73
  updateId: number;
74
- message?: { chatId: number; text: string; from?: string };
74
+ message?: {
75
+ chatId: number;
76
+ text: string;
77
+ from?: string;
78
+ /** Audit run-1: the sender's STABLE Telegram id (usernames are mutable). */
79
+ fromId?: number;
80
+ /** Audit run-1: chat.type from the wire — "private" vs group/supergroup/channel. */
81
+ chatType?: string;
82
+ };
75
83
  }
76
84
 
77
85
  /**
@@ -150,6 +158,9 @@ export interface TelegramChatBinding {
150
158
  sessionId: string;
151
159
  /** ISO. When this binding was made. */
152
160
  createdAt: string;
161
+ /** Audit run-1: the /start sender's stable Telegram id — only that sender may
162
+ * act on this binding. Absent on legacy rows (treated as chat-wide until re-bound). */
163
+ boundFromId?: number;
153
164
  }
154
165
 
155
166
  /** One minted `/start` code. `sessionId` is the session the code grants (the CLI's default is the first session). */
@@ -237,6 +248,7 @@ export function flattenUpdates(rows: readonly unknown[]): TelegramUpdate[] {
237
248
  if (typeof msg.text === "string" && typeof chatId === "number" && Number.isFinite(chatId)) {
238
249
  const from = msg.from;
239
250
  let fromName: string | undefined;
251
+ let fromId: number | undefined;
240
252
  if (from !== null && typeof from === "object") {
241
253
  const f = from as Record<string, unknown>;
242
254
  fromName =
@@ -245,8 +257,19 @@ export function flattenUpdates(rows: readonly unknown[]): TelegramUpdate[] {
245
257
  : typeof f.first_name === "string" && f.first_name
246
258
  ? f.first_name
247
259
  : undefined;
260
+ if (typeof f.id === "number" && Number.isFinite(f.id)) fromId = Math.trunc(f.id);
248
261
  }
249
- message = { chatId: Math.trunc(chatId), text: msg.text, ...(fromName ? { from: fromName } : {}) };
262
+ const chatType =
263
+ chat !== null && typeof chat === "object" && typeof (chat as Record<string, unknown>).type === "string"
264
+ ? ((chat as Record<string, unknown>).type as string)
265
+ : undefined;
266
+ message = {
267
+ chatId: Math.trunc(chatId),
268
+ text: msg.text,
269
+ ...(fromName ? { from: fromName } : {}),
270
+ ...(fromId !== undefined ? { fromId } : {}),
271
+ ...(chatType ? { chatType } : {}),
272
+ };
250
273
  }
251
274
  }
252
275
  out.push({ updateId: Math.trunc(updateId), ...(message ? { message } : {}) });
@@ -277,7 +300,16 @@ function coerceRegistry(raw: unknown, now: number): TelegramRegistryFile {
277
300
  typeof source.createdAt === "string" && Number.isFinite(Date.parse(source.createdAt))
278
301
  ? source.createdAt
279
302
  : isoTime(now);
280
- chats.push({ chatId: Math.trunc(source.chatId), sessionId: source.sessionId, createdAt });
303
+ const boundFromId =
304
+ typeof source.boundFromId === "number" && Number.isFinite(source.boundFromId)
305
+ ? Math.trunc(source.boundFromId)
306
+ : undefined;
307
+ chats.push({
308
+ chatId: Math.trunc(source.chatId),
309
+ sessionId: source.sessionId,
310
+ createdAt,
311
+ ...(boundFromId !== undefined ? { boundFromId } : {}),
312
+ });
281
313
  }
282
314
  }
283
315
 
@@ -663,7 +695,13 @@ export class TelegramBridge {
663
695
  draft.offset = Math.max(draft.offset, update.updateId + 1);
664
696
  });
665
697
  if (!update.message) return; // non-message or non-text: acknowledged, ignored
666
- await this.dispatch(update.message.chatId, update.message.from, update.message.text);
698
+ await this.dispatch(
699
+ update.message.chatId,
700
+ update.message.from,
701
+ update.message.text,
702
+ update.message.fromId,
703
+ update.message.chatType,
704
+ );
667
705
  }
668
706
 
669
707
  /**
@@ -671,7 +709,13 @@ export class TelegramBridge {
671
709
  * is plain text — including unknown `/words`, which the bound agent can
672
710
  * answer better than a canned "unknown command".
673
711
  */
674
- private async dispatch(chatId: number, _from: string | undefined, rawText: string): Promise<void> {
712
+ private async dispatch(
713
+ chatId: number,
714
+ _from: string | undefined,
715
+ rawText: string,
716
+ fromId?: number,
717
+ chatType?: string,
718
+ ): Promise<void> {
675
719
  const text = rawText.trim();
676
720
  const lower = text.toLowerCase();
677
721
 
@@ -679,20 +723,27 @@ export class TelegramBridge {
679
723
  await this.reply(chatId, CHAT_HELP);
680
724
  return;
681
725
  }
726
+ const binding = this.bindingOf(chatId);
727
+ // Audit run-1 (sender binding): a chat container is not a principal — every
728
+ // member of a group shares one chatId, including members added after the
729
+ // bind. When the binding pinned the /start sender's stable id, only that
730
+ // sender may act on it; anyone else's messages are dropped like a
731
+ // stranger's (they learn nothing and change nothing).
732
+ const senderAllowed = binding?.boundFromId === undefined || binding.boundFromId === fromId;
733
+ if (!senderAllowed) return;
682
734
  if (lower === "/stop") {
683
735
  await this.commit((draft) => {
684
- draft.chats = draft.chats.filter((binding) => binding.chatId !== chatId);
736
+ draft.chats = draft.chats.filter((row) => row.chatId !== chatId);
685
737
  });
686
738
  await this.reply(chatId, "unbound");
687
739
  return;
688
740
  }
689
741
  if (lower === "/status") {
690
- const binding = this.bindingOf(chatId);
691
742
  await this.reply(chatId, binding ? this.sessionNameOf(binding.sessionId) : "not bound");
692
743
  return;
693
744
  }
694
745
  if (lower === "/start" || lower.startsWith("/start ")) {
695
- await this.cmdStart(chatId, text);
746
+ await this.cmdStart(chatId, text, fromId, chatType);
696
747
  return;
697
748
  }
698
749
  if (lower === "/session" || lower.startsWith("/session ")) {
@@ -700,7 +751,6 @@ export class TelegramBridge {
700
751
  return;
701
752
  }
702
753
 
703
- const binding = this.bindingOf(chatId);
704
754
  if (!binding) return; // unbound chat: drop silently — a stranger learns nothing
705
755
  try {
706
756
  const { submissionId } = await this.broker.sendToSession(binding.sessionId, text);
@@ -712,7 +762,23 @@ export class TelegramBridge {
712
762
  }
713
763
 
714
764
  /** `/start <code>`: single-use, 10-minute code → bind this chat to the code's session. */
715
- private async cmdStart(chatId: number, text: string): Promise<void> {
765
+ private async cmdStart(
766
+ chatId: number,
767
+ text: string,
768
+ fromId: number | undefined,
769
+ chatType: string | undefined,
770
+ ): Promise<void> {
771
+ // Audit run-1 (chat-type gate): a non-private chat id is shared by every
772
+ // current and future member — binding it would hand all of them the
773
+ // operator's agent authority. Refuse; the operator binds from their own
774
+ // private chat with the bot.
775
+ if (chatType && chatType !== "private") {
776
+ await this.reply(
777
+ chatId,
778
+ "this is not a private chat — every member would inherit the binding; run /start from a private chat with the bot",
779
+ );
780
+ return;
781
+ }
716
782
  const code = text.slice("/start".length).trim().toLowerCase();
717
783
  const now = this.now();
718
784
  const hit = CODE_PATTERN.test(code) ? this.codes.find((row) => row.code === code && Date.parse(row.expiresAt) > now) : undefined;
@@ -725,7 +791,13 @@ export class TelegramBridge {
725
791
  draft.codes = draft.codes.filter((row) => row.code !== code); // single use, spent now
726
792
  draft.chats = [
727
793
  ...draft.chats.filter((binding) => binding.chatId !== chatId),
728
- { chatId, sessionId, createdAt: isoTime(now) },
794
+ {
795
+ chatId,
796
+ sessionId,
797
+ createdAt: isoTime(now),
798
+ // Pin the ceremony sender (audit run-1): stable id, not the mutable username.
799
+ ...(fromId !== undefined ? { boundFromId: fromId } : {}),
800
+ },
729
801
  ];
730
802
  });
731
803
  await this.reply(chatId, `bound to ${this.sessionNameOf(sessionId)}`);
@@ -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
@@ -99,19 +99,31 @@ export function proxy(
99
99
  res.type("application/json").send(body);
100
100
  else {
101
101
  // R8 binary passthrough: base64-flagged device payloads are decoded byte-exact for
102
- // EVERY type; the LABEL is controlled by the hub. Only application/zip (the export
103
- // contract) keeps its type + the device's sanitized download filename — every other
104
- // non-JSON type stays an inert octet-stream attachment (Gate A GA-01), so a hostile
105
- // 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).
106
109
  const payload =
107
110
  upstream.bodyEncoding === "base64"
108
111
  ? Buffer.from(String(upstream.body ?? ""), "base64")
109
112
  : Buffer.from(body, "utf8");
110
113
  const isZip = mediaType(contentType) === "application/zip";
111
- const disposition =
114
+ const m =
112
115
  isZip && typeof upstream.contentDisposition === "string"
113
- ? upstream.contentDisposition
114
- : '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"';
115
127
  res.type(isZip ? contentType : "application/octet-stream")
116
128
  .set("Content-Disposition", disposition)
117
129
  .send(payload);
@@ -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. */
@@ -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))}`,
package/deploy/Caddyfile CHANGED
@@ -8,12 +8,18 @@
8
8
  # DPI_ADMIN_HASH bcrypt hash for the single admin user (caddy hash-password;
9
9
  # the PLAINTEXT never lives in this repo or in env logs)
10
10
  #
11
- # Auth matrix (05):
12
- # exempt (exact path/method): GET /healthz · POST /api/pair/start ·
13
- # POST /api/pair/verify · GET /api/tunnel (WS) — everything else requires
14
- # HTTP Basic auth, and the Authorization header is STRIPPED before the hub
15
- # so device tokens and admin credentials can never mix. Client-supplied
16
- # XFF/XFP are overwritten from the real connection.
11
+ # Auth matrix (05) — the exemption set is EXACT and EXHAUSTIVE:
12
+ # exempt (exact path+method): GET /healthz · POST /api/pair/start ·
13
+ # POST /api/pair/verify · POST /api/pair/request (device-initiated
14
+ # enrollment — the device holds no Basic credential by design) ·
15
+ # GET /share/* (public capability page — the 18-byte token IS the boundary) ·
16
+ # GET /api/tunnel (WS upgrade) — everything else — including WRONG METHODS
17
+ # on the exempt paths — requires HTTP Basic auth, and the Authorization
18
+ # header is STRIPPED before the hub so device tokens and admin credentials
19
+ # can never mix. The final handle is a matcher-less CATCH-ALL so no request
20
+ # class falls through to Caddy's anonymous empty-200 default (audit run-1:
21
+ # admin-matcher method-gap). Client-supplied XFF/XFP are overwritten from
22
+ # the real connection.
17
23
  {
18
24
  admin off
19
25
  auto_https off
@@ -50,11 +56,13 @@ https://{$DPI_PUBLIC_HOST} {
50
56
  # Do not "harden" this file by adding one; the harness also runs without
51
57
  # Caddy, so the hub must be correct on its own either way.
52
58
 
53
- # Admin surface = everything except the four exact exemptions below.
54
- @admin {
55
- not path /api/tunnel /api/pair/start /api/pair/verify /healthz
59
+ # Admin surface = everything except the exact exemptions below. The final
60
+ # handle is a matcher-less catch-all: wrong-method requests on exempt paths
61
+ # land here (Basic challenge), never in Caddy's empty-200 default.
62
+ @tunnel {
63
+ method GET
64
+ path /api/tunnel
56
65
  }
57
- @tunnel path /api/tunnel
58
66
  @pairstart {
59
67
  method POST
60
68
  path /api/pair/start
@@ -63,6 +71,14 @@ https://{$DPI_PUBLIC_HOST} {
63
71
  method POST
64
72
  path /api/pair/verify
65
73
  }
74
+ @pairrequest {
75
+ method POST
76
+ path /api/pair/request
77
+ }
78
+ @share {
79
+ method GET
80
+ path /share/*
81
+ }
66
82
  @healthz {
67
83
  method GET
68
84
  path /healthz
@@ -97,6 +113,29 @@ https://{$DPI_PUBLIC_HOST} {
97
113
  }
98
114
  }
99
115
 
116
+ # Device-initiated enrollment (audit run-1: exemption drift): the machine
117
+ # running `dpi pair --hub` holds no Basic credential BY DESIGN — the hub
118
+ # guards this route with per-IP limits, failure windows and the device-mint
119
+ # sub-cap; approval stays the only issuance gate.
120
+ handle @pairrequest {
121
+ reverse_proxy {$DPI_HUB_ADDR} {
122
+ header_up X-Forwarded-For {remote_host}
123
+ header_up X-Forwarded-Proto https
124
+ header_up -Authorization
125
+ flush_interval -1
126
+ }
127
+ }
128
+
129
+ # Public share page (audit run-1: exemption drift): the tokenized link is
130
+ # the designed boundary; the page is server-side rendered with zero scripts.
131
+ handle @share {
132
+ reverse_proxy {$DPI_HUB_ADDR} {
133
+ header_up X-Forwarded-For {remote_host}
134
+ header_up X-Forwarded-Proto https
135
+ header_up -Authorization
136
+ }
137
+ }
138
+
100
139
  handle @healthz {
101
140
  reverse_proxy {$DPI_HUB_ADDR} {
102
141
  header_up X-Forwarded-For {remote_host}
@@ -105,8 +144,10 @@ https://{$DPI_PUBLIC_HOST} {
105
144
  }
106
145
  }
107
146
 
108
- # Everything else: basic auth, then STRIP Authorization before the hub.
109
- handle @admin {
147
+ # Everything else — every non-exempt path AND every wrong-method request
148
+ # on an exempt path: basic auth, then STRIP Authorization before the hub.
149
+ # Matcher-less = exhaustive (audit run-1: method-gap fallthrough).
150
+ handle {
110
151
  basic_auth {
111
152
  admin {$DPI_ADMIN_HASH}
112
153
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.67",
3
+ "version": "0.0.68",
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": {