my-durable 0.0.62 → 0.0.64

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.
@@ -45,6 +45,19 @@ export const MIN_EVERY_MINUTES = 5;
45
45
  /** A day: longer than this and `dailyAt` is the better trigger anyway. */
46
46
  export const MAX_EVERY_MINUTES = 1440;
47
47
 
48
+ /** R10 Design A: bounds for per-schedule session retention. 1 = keep only the
49
+ * latest run live; 100 x 5-min runs ≈ 8h of live transcripts — enough for any
50
+ * "recent context" use, small enough that a fat-finger cannot pin 100k sessions. */
51
+ export const MIN_KEEP_RUNS = 1;
52
+ export const MAX_KEEP_RUNS = 100;
53
+
54
+ /** Throws unless v is a legal keepRuns (integer 1..100). Shared by create/patch. */
55
+ function normaliseKeepRuns(v: unknown): number {
56
+ if (typeof v !== "number" || !Number.isInteger(v) || v < MIN_KEEP_RUNS || v > MAX_KEEP_RUNS)
57
+ throw invalid(`keepRuns must be an integer between ${MIN_KEEP_RUNS} and ${MAX_KEEP_RUNS}`);
58
+ return v;
59
+ }
60
+
48
61
  /** `HH:MM`, 24-hour, local time. Strict two digits so the file has one spelling per time. */
49
62
  const DAILY_AT_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/;
50
63
  const MINUTE_MS = 60_000;
@@ -98,6 +111,13 @@ export interface ScheduleRecord {
98
111
  lastOutcome?: ScheduleRunOutcome;
99
112
  /** Why the last run failed. Cleared by the next successful run. */
100
113
  lastError?: string;
114
+ /** R10 Design A: keep the last N runs' sessions live; archive older ones at
115
+ * the end of a successful dispatch. Absent = never auto-archive. */
116
+ keepRuns?: number;
117
+ /** R10 Design A: bounded ring of the newest keepRuns run session ids — the
118
+ * retention window. Pushed by markRun, trimmed to keepRuns; the ONLY
119
+ * registry growth this feature adds, bounded by construction. */
120
+ recentSessionIds?: string[];
101
121
  createdAt: number;
102
122
  updatedAt: number;
103
123
  }
@@ -113,10 +133,11 @@ export interface ScheduleInput {
113
133
  }
114
134
 
115
135
  /** `create` also takes the initial `enabled` bit, so a schedule can be staged switched-off. */
116
- export type ScheduleCreateInput = ScheduleInput & { enabled?: boolean };
136
+ export type ScheduleCreateInput = ScheduleInput & { enabled?: boolean; keepRuns?: number };
117
137
 
118
- /** What `update` accepts: everything a user owns, plus the switch. */
119
- export type SchedulePatch = Partial<ScheduleInput> & { enabled?: boolean };
138
+ /** What `update` accepts: everything a user owns, plus the switch. `keepRuns:
139
+ * null` CLEARS retention (R10 Design A). */
140
+ export type SchedulePatch = Partial<ScheduleInput> & { enabled?: boolean; keepRuns?: number | null };
120
141
 
121
142
  /** The fields `computeNextRun` reads. Narrowed so callers can pass a bare object in tests. */
122
143
  export type ScheduleTiming = Pick<
@@ -364,6 +385,18 @@ function coerceRecord(raw: unknown, now: number): ScheduleRecord {
364
385
  if (isOutcome(source.lastOutcome)) record.lastOutcome = source.lastOutcome;
365
386
  const lastError = nonEmptyString(source.lastError);
366
387
  if (lastError) record.lastError = lastError;
388
+ // R10 Design A: retention window — defensive parse (bounds enforced, ring
389
+ // trimmed, junk entries dropped) so a hand-edited or future file cannot
390
+ // unbound the registry.
391
+ if (typeof source.keepRuns === "number" && Number.isInteger(source.keepRuns)) {
392
+ const keepRuns = Math.min(Math.max(source.keepRuns, MIN_KEEP_RUNS), MAX_KEEP_RUNS);
393
+ record.keepRuns = keepRuns;
394
+ if (Array.isArray(source.recentSessionIds)) {
395
+ const ring = source.recentSessionIds.filter((id): id is string => typeof id === "string" && id.length > 0);
396
+ const unique = [...new Set(ring)].slice(-keepRuns);
397
+ if (unique.length > 0) record.recentSessionIds = unique;
398
+ }
399
+ }
367
400
  return record;
368
401
  }
369
402
 
@@ -477,6 +510,7 @@ export class ScheduleRegistry {
477
510
  throw invalid("enabled must be a boolean");
478
511
  }
479
512
  const enabled = input?.enabled ?? true;
513
+ const keepRuns = input?.keepRuns !== undefined ? normaliseKeepRuns(input.keepRuns) : undefined;
480
514
  return this.run(async () => {
481
515
  const staged = new Map(this.records);
482
516
  let id = newScheduleId();
@@ -485,6 +519,7 @@ export class ScheduleRegistry {
485
519
  const created: ScheduleRecord = { id, name, cwd, model, prompt, enabled, createdAt: now, updatedAt: now };
486
520
  if (trigger.everyMinutes !== undefined) created.everyMinutes = trigger.everyMinutes;
487
521
  if (trigger.dailyAt !== undefined) created.dailyAt = trigger.dailyAt;
522
+ if (keepRuns !== undefined) created.keepRuns = keepRuns;
488
523
  staged.set(created.id, created);
489
524
  await this.commit(staged);
490
525
  return clone(created);
@@ -501,6 +536,7 @@ export class ScheduleRegistry {
501
536
  if (patch?.enabled !== undefined && typeof patch.enabled !== "boolean") {
502
537
  throw invalid("enabled must be a boolean");
503
538
  }
539
+ if (patch?.keepRuns !== undefined && patch.keepRuns !== null) normaliseKeepRuns(patch.keepRuns);
504
540
  return this.run(async () => {
505
541
  const staged = new Map(this.records);
506
542
  const existing = staged.get(id);
@@ -511,6 +547,22 @@ export class ScheduleRegistry {
511
547
  if ("model" in patch) next.model = normaliseModel(patch.model);
512
548
  if ("prompt" in patch) next.prompt = normalisePrompt(patch.prompt);
513
549
  if ("enabled" in patch) next.enabled = patch.enabled as boolean;
550
+ if ("keepRuns" in patch) {
551
+ if (patch.keepRuns === null) {
552
+ // Clearing retention: the ring goes with it (the sessions stay live
553
+ // forever, exactly as before this feature existed).
554
+ delete next.keepRuns;
555
+ delete next.recentSessionIds;
556
+ } else if (patch.keepRuns === undefined) {
557
+ /* explicit undefined = no change */
558
+ } else {
559
+ next.keepRuns = normaliseKeepRuns(patch.keepRuns);
560
+ const ring = next.recentSessionIds ?? [];
561
+ const trimmed = ring.slice(-next.keepRuns);
562
+ if (trimmed.length > 0) next.recentSessionIds = trimmed;
563
+ else delete next.recentSessionIds;
564
+ }
565
+ }
514
566
  if ("everyMinutes" in patch || "dailyAt" in patch) {
515
567
  const trigger = normaliseTrigger({
516
568
  everyMinutes: "everyMinutes" in patch ? patch.everyMinutes : existing.everyMinutes,
@@ -595,6 +647,13 @@ export class ScheduleRegistry {
595
647
  const sessionId = nonEmptyString(result.sessionId);
596
648
  if (sessionId) next.lastSessionId = sessionId;
597
649
  else delete next.lastSessionId;
650
+ // R10 Design A: the retention window ring — push the run's session, trim
651
+ // to keepRuns. The ids that FALL OFF the window (evicted) are the prune
652
+ // candidates; the caller snapshots the ring before this call and diffs.
653
+ if (sessionId && typeof next.keepRuns === "number") {
654
+ const ring = [...(next.recentSessionIds ?? []).filter((id) => id !== sessionId), sessionId];
655
+ next.recentSessionIds = ring.slice(-next.keepRuns);
656
+ }
598
657
  const error = nonEmptyString(result.error);
599
658
  if (result.outcome !== "ok" && error) next.lastError = error;
600
659
  else delete next.lastError; // a success (or a fresh intent) clears the reason the last one failed
@@ -604,6 +663,42 @@ export class ScheduleRegistry {
604
663
  });
605
664
  }
606
665
 
666
+ /** R10 Design B: clear `lastSessionId` (and retention-ring entries) pointing
667
+ * at sessions a gc pass removed. The run outcome/error/history STAY — only
668
+ * the link goes. Idempotent; returns how many records were touched. */
669
+ async clearSessionRefs(ids: Set<string>): Promise<number> {
670
+ if (ids.size === 0) return 0;
671
+ return this.run(async () => {
672
+ let touched = 0;
673
+ const staged = new Map(this.records);
674
+ for (const [id, existing] of staged) {
675
+ let next = existing;
676
+ let changed = false;
677
+ if (existing.lastSessionId !== undefined && ids.has(existing.lastSessionId)) {
678
+ const { lastSessionId, ...rest } = existing;
679
+ void lastSessionId;
680
+ next = rest as ScheduleRecord;
681
+ changed = true;
682
+ }
683
+ // Design A interplay: ring ids pointing at removed sessions are dangling
684
+ // too — drop them so archivedRuns does not count ghosts forever.
685
+ if (next.recentSessionIds?.some((sid) => ids.has(sid))) {
686
+ const kept = next.recentSessionIds.filter((sid) => !ids.has(sid));
687
+ next = { ...next, recentSessionIds: kept.length > 0 ? kept : undefined } as ScheduleRecord;
688
+ if (kept.length === 0) delete next.recentSessionIds;
689
+ changed = true;
690
+ }
691
+ if (changed) {
692
+ next.updatedAt = this.now();
693
+ staged.set(id, next);
694
+ touched += 1;
695
+ }
696
+ }
697
+ if (touched > 0) await this.commit(staged);
698
+ return touched;
699
+ });
700
+ }
701
+
607
702
  /**
608
703
  * Boot-time recovery (R8 2.4): a run still marked `started` never recorded its
609
704
  * outcome — the daemon died between the intent marker and the write-back. Flip
@@ -216,6 +216,14 @@ const SCHEDULE_DISPATCH_TIMEOUT_MS = 60_000;
216
216
  * `timeout` — an explicit intermediate outcome, never a green "ok". */
217
217
  const SCHEDULE_SETTLE_CAP_MS = 120_000;
218
218
 
219
+ /** R9 2.1: schedule registry persists (markRun) run OUTSIDE the dispatch
220
+ * deadline — a hung dataDir fs would hold the in-flight guard forever
221
+ * (Run-now 409s indefinitely, due-skips forever). Every markRun await is
222
+ * bounded by this cap; the write itself is fire-and-forget-safe (the registry
223
+ * queue still completes it if the fs recovers, and markRun is idempotent per
224
+ * run), so a timed-out persist only loses the CRASH-safety record, never the guard. */
225
+ const SCHEDULE_REGISTRY_IO_MS = 10_000;
226
+
219
227
  /**
220
228
  * Race `work` against a wall-clock budget. The loser is NOT cancelled: a create
221
229
  * that timed out may still complete later (its session shows up in the tree);
@@ -1585,7 +1593,15 @@ export class Store {
1585
1593
  storage = await openNodeSqliteStorage(row.dbPath);
1586
1594
  } catch (error) {
1587
1595
  if (create || !isUnreadableStorage(error)) throw error;
1588
- const outcome = await salvageSessionDb(row.dbPath);
1596
+ // R10 5.2: single-flight per session — two routes opening one corrupt db
1597
+ // (UI refresh fetching git-files + agents) used to spawn two salvage
1598
+ // workers racing on shared scratch; both attempts now share ONE outcome.
1599
+ const inFlight = this.salvageInFlight.get(row.id) ?? salvageSessionDb(row.dbPath).then((outcome) => {
1600
+ this.salvageInFlight.delete(row.id);
1601
+ return outcome;
1602
+ });
1603
+ this.salvageInFlight.set(row.id, inFlight);
1604
+ const outcome = await inFlight;
1589
1605
  if (!outcome.recovered) {
1590
1606
  const note = salvageFailureNote(outcome);
1591
1607
  const previous = this.errors.get(row.id);
@@ -1603,7 +1619,8 @@ export class Store {
1603
1619
  throw new ApiFault("unavailable", note);
1604
1620
  }
1605
1621
  process.emitWarning(
1606
- `[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs})`,
1622
+ `[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs}). ` +
1623
+ `The copy reflects the database's last consistent state — if its write-ahead log was lost in the crash, the final turns may be missing (the quarantined original retains every byte).`,
1607
1624
  );
1608
1625
  storage = await openNodeSqliteStorage(row.dbPath); // the ONE retry, on the promoted copy
1609
1626
  }
@@ -2562,6 +2579,22 @@ export class Store {
2562
2579
  return this.scheduleView(record);
2563
2580
  }
2564
2581
 
2582
+ /** R10 Design B: clear schedule/graph refs pointing at sessions a gc pass
2583
+ * removed (the daemon-side sweep — the CLI routes here when the device is
2584
+ * up, so registry mutations happen in-process with no file race). The
2585
+ * registries keep outcome/error history; only the links go. Cap 10k ids. */
2586
+ async gcSweepRefs(sessionIds: unknown): Promise<{ schedules: number; graphRuns: number }> {
2587
+ if (!Array.isArray(sessionIds)) throw new ApiFault("invalid", "sessionIds must be an array");
2588
+ if (sessionIds.length > 10_000) throw new ApiFault("invalid", "sessionIds capped at 10000");
2589
+ const ids = new Set(
2590
+ sessionIds.filter((id): id is string => typeof id === "string" && id.length > 0 && id.length <= 64),
2591
+ );
2592
+ const schedules = await this.schedules.clearSessionRefs(ids);
2593
+ const graphRuns = await this.graphs.clearSessionRefs(ids);
2594
+ if (schedules > 0 || graphRuns > 0) this.notify();
2595
+ return { schedules, graphRuns };
2596
+ }
2597
+
2565
2598
  async removeSchedule(id: string): Promise<{ removed: boolean }> {
2566
2599
  const removed = await this.schedules.remove(id);
2567
2600
  this.notify();
@@ -2586,9 +2619,18 @@ export class Store {
2586
2619
  // dpi-sdk is not this fix's file, so carry the recorded value through with
2587
2620
  // a narrowing cast. UIs treat the field as opaque text.
2588
2621
  const { lastOutcome, ...rest } = record;
2622
+ // R10 Design A: derived count of ring ids no longer live (archived or gone)
2623
+ // so the UI can render "keeping last N" truthfully. Bounded: ring ≤ 100.
2624
+ let archivedRuns: number | undefined;
2625
+ if (record.keepRuns !== undefined && record.recentSessionIds?.length) {
2626
+ archivedRuns = record.recentSessionIds.filter(
2627
+ (id) => !this.catalog.prepare("SELECT 1 FROM sessions WHERE id=?").get(id),
2628
+ ).length;
2629
+ }
2589
2630
  return {
2590
2631
  ...rest,
2591
2632
  ...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
2633
+ ...(archivedRuns !== undefined ? { archivedRuns } : {}),
2592
2634
  nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
2593
2635
  running: this.scheduleInFlight.has(record.id),
2594
2636
  };
@@ -2600,6 +2642,10 @@ export class Store {
2600
2642
  private scheduleInFlight = new Set<string>();
2601
2643
  private scheduleTimer?: ReturnType<typeof setTimeout>;
2602
2644
 
2645
+ /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2646
+ * corrupt session share ONE bounded attempt instead of racing scratch files. */
2647
+ private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
2648
+
2603
2649
  /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2604
2650
  * dispatches in milliseconds instead of minutes). */
2605
2651
  private get scheduleTickMs(): number {
@@ -2675,7 +2721,11 @@ export class Store {
2675
2721
  // Persist the intent before any await that can wedge. If this persist
2676
2722
  // itself fails (disk full), the run still proceeds — it just loses the
2677
2723
  // crash-safety guarantee, like every version before R8.
2678
- await this.schedules.markRun(record.id, { outcome: "started" }).catch(() => undefined);
2724
+ await deadline(
2725
+ this.schedules.markRun(record.id, { outcome: "started" }),
2726
+ SCHEDULE_REGISTRY_IO_MS,
2727
+ "schedule registry write timed out (started)",
2728
+ ).catch(() => undefined);
2679
2729
  await this.dispatchBounded(record);
2680
2730
  } finally {
2681
2731
  this.scheduleInFlight.delete(record.id);
@@ -2698,11 +2748,15 @@ export class Store {
2698
2748
  private async dispatchBounded(record: ScheduleRecord): Promise<void> {
2699
2749
  let sessionId: string | undefined;
2700
2750
  const recordFailure = async (outcome: "failed" | "timeout", detail: string) => {
2701
- await this.schedules.markRun(record.id, {
2702
- ...(sessionId ? { sessionId } : {}),
2703
- outcome,
2704
- error: detail.slice(0, 300),
2705
- }).catch(() => undefined);
2751
+ await deadline(
2752
+ this.schedules.markRun(record.id, {
2753
+ ...(sessionId ? { sessionId } : {}),
2754
+ outcome,
2755
+ error: detail.slice(0, 300),
2756
+ }),
2757
+ SCHEDULE_REGISTRY_IO_MS,
2758
+ "schedule registry write timed out (failure)",
2759
+ ).catch(() => undefined);
2706
2760
  void this.notifyEvent({
2707
2761
  kind: "schedule.failed",
2708
2762
  title: `Schedule failed: ${record.name}`,
@@ -2738,7 +2792,16 @@ export class Store {
2738
2792
  return;
2739
2793
  }
2740
2794
  if (result.status === "done") {
2741
- await this.schedules.markRun(record.id, { sessionId, outcome: "ok" }).catch(() => undefined);
2795
+ // R10 Design A: snapshot the retention ring BEFORE markRun pushes+trims,
2796
+ // then prune whatever fell out of the window (void: never blocks the
2797
+ // guard release, no new timers — best-effort archive with retry next run).
2798
+ const ringBefore = [...(record.recentSessionIds ?? [])];
2799
+ const okRecord = await deadline(
2800
+ this.schedules.markRun(record.id, { sessionId, outcome: "ok" }),
2801
+ SCHEDULE_REGISTRY_IO_MS,
2802
+ "schedule registry write timed out (ok)",
2803
+ ).catch(() => undefined);
2804
+ if (okRecord?.keepRuns) void this.pruneScheduleSessions(okRecord, ringBefore).catch(() => undefined);
2742
2805
  void this.notifyEvent({
2743
2806
  kind: "schedule.ok",
2744
2807
  title: `Schedule ran: ${record.name}`,
@@ -2766,6 +2829,26 @@ export class Store {
2766
2829
  }
2767
2830
  }
2768
2831
 
2832
+ /** R10 Design A: archive run sessions that fell out of the schedule's
2833
+ * keepRuns window. Called (void, best-effort) only from the ok-path of a
2834
+ * successful dispatch, with the ring as it was BEFORE markRun trimmed it.
2835
+ * `ringBefore \ ringAfter` = evicted ids; each LIVE evicted session is
2836
+ * archived via the existing store.archive path (abort-open → atomic rename
2837
+ * to archive/ → catalog row deleted — nothing deleted, restorable, ages into
2838
+ * the gc plan). Archive failure leaves the session live; the id is already
2839
+ * gone from the ring, but the session stays restorable and the operator can
2840
+ * archive it manually — at most keepRuns stragglers can overstay (bounded). */
2841
+ private async pruneScheduleSessions(record: ScheduleRecord, ringBefore: string[]): Promise<void> {
2842
+ if (typeof record.keepRuns !== "number") return;
2843
+ const ringNow = new Set(record.recentSessionIds ?? []);
2844
+ const evicted = [...new Set(ringBefore)].filter((id) => !ringNow.has(id));
2845
+ for (const id of evicted) {
2846
+ const row = this.catalog.prepare("SELECT * FROM sessions WHERE id=?").get(id) as SessionRow | undefined;
2847
+ if (!row) continue; // already gone (archived/corrupt-removed) — nothing to do
2848
+ await this.archive(row);
2849
+ }
2850
+ }
2851
+
2769
2852
  // ------------------------------------------------- projects (Wave 2)
2770
2853
 
2771
2854
  /** The project a path belongs to: its longest registered root. */
@@ -32,6 +32,7 @@ export const AUDIT_ACTIONS = [
32
32
  "pair.approved",
33
33
  "pair.cancelled",
34
34
  "pair.success",
35
+ "pair.abandoned",
35
36
  "pair.revoke",
36
37
  "token.rotate_started",
37
38
  "token.rotate_completed",
@@ -267,3 +267,49 @@ export class CredentialService {
267
267
  return "invalid";
268
268
  }
269
269
  }
270
+
271
+ /**
272
+ * R9 (audit 1.3): retire a credential whose pairing receipt was NEVER delivered
273
+ * (the device cancelled/crashed mid-poll and the receipt grace lapsed — the
274
+ * plaintext only ever lived in the hub's RAM cache). Same state machine as an
275
+ * operator revoke: pairing paired→revoked, every live credential of that epoch
276
+ * → revoked, tunnel state dropped, one `pair.abandoned` audit row — all in ONE
277
+ * transaction. Scoped to the issuance's OWN epoch, so a device that already
278
+ * re-paired (new epoch) is never touched. Returns true only when the pairing
279
+ * row actually flipped; a no-op (already revoked / re-paired / harness registry
280
+ * without rows) changes nothing and audits nothing.
281
+ */
282
+ export function revokeAbandonedCredential(
283
+ registry: NetworkRegistry,
284
+ audit: Audit,
285
+ tokenIssue: Pick<TokenIssue, "deviceUid" | "deviceId" | "pairingEpoch" | "credentialId">,
286
+ ): boolean {
287
+ const now = Date.now();
288
+ return audit.withTransaction(() => {
289
+ const flipped = registry.db
290
+ .prepare(
291
+ "UPDATE pairings SET status='revoked', updated_at=? WHERE device_id=? AND pairing_epoch=? AND status='paired'",
292
+ )
293
+ .run(now, tokenIssue.deviceId, tokenIssue.pairingEpoch).changes;
294
+ if (!flipped) return false;
295
+ registry.db
296
+ .prepare(
297
+ "UPDATE tunnel_credentials SET status='revoked', revoked_at=? WHERE device_id=? AND pairing_epoch=? AND status IN ('current','previous','retired')",
298
+ )
299
+ .run(now, tokenIssue.deviceId, tokenIssue.pairingEpoch);
300
+ registry.db.prepare("DELETE FROM tunnel_state WHERE device_id=?").run(tokenIssue.deviceId);
301
+ audit.append({
302
+ actor: "hub",
303
+ action: "pair.abandoned",
304
+ outcome: "ok",
305
+ detail: {
306
+ deviceId: tokenIssue.deviceId,
307
+ deviceUid: tokenIssue.deviceUid,
308
+ pairingEpoch: tokenIssue.pairingEpoch,
309
+ credentialId: tokenIssue.credentialId,
310
+ reason: "receipt grace lapsed with the token never delivered; the credential was undeliverable",
311
+ },
312
+ });
313
+ return true;
314
+ });
315
+ }
@@ -280,7 +280,27 @@ app.post("/api/pair/verify", ...pairGuard, express.json({ limit: "16kb" }), asyn
280
280
  // origin_mismatch (with the DPI_HUB_ORIGIN hint) instead of counting an
281
281
  // invalid signature toward the enrollment cancel limit.
282
282
  const r = await pairing.verify(req.body, req.ip ?? "unknown", `${req.protocol}://${req.get("host")}`);
283
- if (r.ok) return res.status(r.status).json(r.value);
283
+ if (r.ok) {
284
+ // R9 (audit 1.3): a token 200 counts as DELIVERED only once it flushes to
285
+ // the socket. A client that vanished mid-poll (local cancel, crash) never
286
+ // reads it — report the loss so the receipt-grace sweep can revoke the
287
+ // undeliverable credential instead of stranding a permanent ghost pairing.
288
+ if (
289
+ r.status === 200 &&
290
+ r.receiptSeq !== undefined &&
291
+ (r.value as { type?: string }).type === "pair.token"
292
+ ) {
293
+ const enrollmentId = (r.value as { enrollmentId?: string }).enrollmentId;
294
+ let flushed = false;
295
+ res.on("finish", () => {
296
+ flushed = true;
297
+ });
298
+ res.on("close", () => {
299
+ if (!flushed && enrollmentId) pairing.markReceiptLost(enrollmentId, r.receiptSeq!);
300
+ });
301
+ }
302
+ return res.status(r.status).json(r.value);
303
+ }
284
304
  pairErr(r, res);
285
305
  });
286
306
  /**
@@ -49,6 +49,7 @@ import {
49
49
  import type { PairCodeIssue, TokenIssue } from "../../../../dpi-sdk/src/protocol/pairing.js";
50
50
  import type { Audit } from "./audit.js";
51
51
  import { AuditUnavailableError } from "./audit.js";
52
+ import { revokeAbandonedCredential } from "./credentials.js";
52
53
  import { ipKey } from "./client-ip.js";
53
54
  import { observeIdentity } from "./identity.js";
54
55
  import { SlidingWindows, TokenBuckets, type Take } from "./limiter.js";
@@ -104,6 +105,10 @@ interface Enrollment {
104
105
  issued?: { tokenIssue: TokenIssue; at: number };
105
106
  /** In-flight issuance (F03): concurrent polls share ONE promise and ONE credential. */
106
107
  issuing?: Promise<TokenIssue>;
108
+ /** R9 1.3: first time the token was served on a 200 (optimistic — the route voids it if the socket died before the flush). */
109
+ receiptDeliveredAt?: number;
110
+ /** Monotonic 200-with-token counter: lets the route void a stale optimistic marker without erasing a newer delivery. */
111
+ receiptSeq?: number;
107
112
  }
108
113
 
109
114
  interface CodeEntry {
@@ -475,16 +480,24 @@ export class PairingService {
475
480
  if (live === "cancelled")
476
481
  return this.fail(410, "enrollment_cancelled", "Pairing code cancelled");
477
482
 
478
- // Same requestId + same tuple → same live challenge (idempotent retry).
483
+ // Same identity → the SAME live ceremony (R9 audit 1.2). The tuple is the
484
+ // device's real identity — deviceUid + deviceName + declared fingerprint +
485
+ // the public key itself; requestId is deliberately IGNORED on a match: the
486
+ // device mints one per start(), so a retry after a lost hub response (the
487
+ // enrollment committed but the challenge never arrived) would otherwise
488
+ // 409-lock the code against its own owner for the rest of the TTL. A match
489
+ // re-enters the existing enrollment — same challenge nonce, same state —
490
+ // which is only usable by the holder of that key. A DIFFERENT identity
491
+ // still gets 409 code_in_use (double-claim stays dead), and the enrollment
492
+ // creation below is untouched (sync check-then-set).
479
493
  if (live.enrollmentId) {
480
494
  const existing = this.enrollments.get(live.enrollmentId)!;
481
- const sameTuple =
482
- existing.requestId === req.requestId &&
495
+ const sameIdentity =
483
496
  existing.deviceUid === req.deviceUid &&
484
497
  existing.deviceName === req.deviceName &&
485
498
  existing.declaredFingerprint === req.keyFingerprint &&
486
499
  existing.publicKeyPem === req.publicKey;
487
- if (!sameTuple)
500
+ if (!sameIdentity)
488
501
  return this.fail(409, "code_in_use", "This code is reserved for another enrollment");
489
502
  if (existing.cancelled) return this.fail(410, "enrollment_cancelled", "Enrollment cancelled");
490
503
  if (now >= live.expiresAt) return this.fail(410, "code_expired", "Pairing code expired");
@@ -568,7 +581,9 @@ export class PairingService {
568
581
  body: unknown,
569
582
  address: string,
570
583
  requestOrigin?: string,
571
- ): Promise<{ ok: true; value: PairPendingOut | TokenIssue; status: number } | PairingFailure> {
584
+ ): Promise<
585
+ { ok: true; value: PairPendingOut | TokenIssue; status: number; receiptSeq?: number } | PairingFailure
586
+ > {
572
587
  const now = this.now();
573
588
  const ip = ipKey(address);
574
589
  if (this.failureBlocked(ip))
@@ -646,7 +661,11 @@ export class PairingService {
646
661
  );
647
662
  }
648
663
  }
649
- return { ok: true, value: enrollment.issued.tokenIssue, status: 200 };
664
+ return this.markReceiptServed(enrollment, {
665
+ ok: true,
666
+ value: enrollment.issued.tokenIssue,
667
+ status: 200,
668
+ });
650
669
  }
651
670
  if (now >= code.expiresAt)
652
671
  return this.fail(410, "code_expired", "Pairing code expired before approval");
@@ -689,7 +708,7 @@ export class PairingService {
689
708
  enrollment.issuing = inflight;
690
709
  try {
691
710
  const tokenIssue = await inflight;
692
- return { ok: true, value: tokenIssue, status: 200 };
711
+ return this.markReceiptServed(enrollment, { ok: true, value: tokenIssue, status: 200 });
693
712
  } catch (e) {
694
713
  const code = (e as { code?: unknown }).code;
695
714
  if (code === "identity_changed" || code === "key_replacement_required") {
@@ -799,6 +818,35 @@ export class PairingService {
799
818
  return this.verifySignature(enrollment, signature, this.deps.hubOrigin);
800
819
  }
801
820
 
821
+ /**
822
+ * R9 (audit 1.3): stamp the optimistic "delivered" marker on every 200 that
823
+ * carries the token, with a monotonic sequence so the route can void exactly
824
+ * the serve it is reporting (see markReceiptLost). Fail-safe default: without
825
+ * any route feedback the marker stays set — forgetting the hook can never
826
+ * mass-retire receipts; only an observed dead socket can.
827
+ */
828
+ private markReceiptServed(
829
+ enrollment: Enrollment,
830
+ outcome: { ok: true; value: TokenIssue; status: number },
831
+ ): { ok: true; value: TokenIssue; status: number; receiptSeq: number } {
832
+ enrollment.receiptSeq = (enrollment.receiptSeq ?? 0) + 1;
833
+ enrollment.receiptDeliveredAt = this.now();
834
+ return { ...outcome, receiptSeq: enrollment.receiptSeq };
835
+ }
836
+
837
+ /**
838
+ * R9 (audit 1.3): the verify route reports the token response never flushed —
839
+ * the client vanished mid-poll (local cancel, crash), so the plaintext died
840
+ * with the socket. Void the optimistic marker for THAT serve only: a newer
841
+ * 200 since then is a real delivery and must survive. If the receipt grace
842
+ * then lapses still undelivered, sweep() revokes the orphan credential.
843
+ */
844
+ markReceiptLost(enrollmentId: string, servedSeq: number): void {
845
+ const enrollment = this.enrollments.get(enrollmentId);
846
+ if (!enrollment || enrollment.receiptSeq !== servedSeq) return;
847
+ enrollment.receiptDeliveredAt = undefined;
848
+ }
849
+
802
850
  /** Ed25519 proof check for a given hub origin — the signing payload binds it,
803
851
  * so the SAME signature can be retried under the request's origin (F02 + R6
804
852
  * cli finding 5: origin-mismatch detection without a protocol change). */
@@ -993,12 +1041,58 @@ export class PairingService {
993
1041
  this.failWindows.sweep();
994
1042
  for (const [codeId, code] of this.codes) {
995
1043
  if (now > code.expiresAt + RECEIPT_GRACE_MS) {
1044
+ this.retireUndeliveredReceipt(code);
996
1045
  this.byCode.delete(code.code);
997
1046
  this.codes.delete(codeId);
998
1047
  if (code.enrollmentId) this.enrollments.delete(code.enrollmentId);
999
1048
  }
1000
1049
  }
1001
1050
  }
1051
+
1052
+ /**
1053
+ * R9 (audit 1.3): the receipt grace lapsed with the token never delivered —
1054
+ * its plaintext only ever existed in this RAM cache, so the committed
1055
+ * credential is permanently unusable (device cancelled locally / crashed
1056
+ * mid-poll, operator approved anyway). Retire it through the normal revoke
1057
+ * state machine instead of stranding a `paired` ghost forever. A DELIVERED
1058
+ * receipt is never touched; re-pairing remains the device's recovery path.
1059
+ */
1060
+ private retireUndeliveredReceipt(code: CodeEntry): void {
1061
+ const enrollment = code.enrollmentId ? this.enrollments.get(code.enrollmentId) : undefined;
1062
+ const issue = enrollment?.issued;
1063
+ if (!enrollment || !issue || enrollment.receiptDeliveredAt !== undefined) return;
1064
+ // R9 6.2 (false-positive guard): markReceiptLost can fire when `close` races
1065
+ // `finish` AFTER a fully-flushed response — revoking then would kill a WORKING
1066
+ // pairing. If the device ever CONNECTED with this credential (a tunnel.connect
1067
+ // audit row naming it), the receipt self-evidently reached it: never revoke.
1068
+ try {
1069
+ const inUse = this.deps.registry.db
1070
+ .prepare("SELECT COUNT(*) AS n FROM events WHERE action='tunnel.connect' AND detail_json LIKE ?")
1071
+ .get(`%${issue.tokenIssue.credentialId}%`) as { n: number };
1072
+ if (inUse.n > 0) {
1073
+ enrollment.receiptDeliveredAt = this.now(); // correct the marker, not just skip
1074
+ return;
1075
+ }
1076
+ } catch {
1077
+ // Audit table unreadable: fall through and revoke (pre-R9 behavior) — a
1078
+ // stray ghost is a lesser evil than never cleaning abandoned credentials.
1079
+ }
1080
+ try {
1081
+ const retired = revokeAbandonedCredential(this.deps.registry, this.deps.audit, issue.tokenIssue);
1082
+ if (retired)
1083
+ console.warn(
1084
+ `[pairing] receipt for enrollment ${enrollment.enrollmentId} was never delivered; abandoned credential ${issue.tokenIssue.credentialId} revoked (pair.abandoned)`,
1085
+ );
1086
+ } catch (error) {
1087
+ // F15 still wins: the RAM entry must go at expiry+grace even if the
1088
+ // revoke could not commit (e.g. audit outage). The credential then lives
1089
+ // on as before this fix — an operator revoke cleans it up.
1090
+ console.warn(
1091
+ `[pairing] could not revoke the undelivered credential for enrollment ${enrollment.enrollmentId}`,
1092
+ error,
1093
+ );
1094
+ }
1095
+ }
1002
1096
  }
1003
1097
 
1004
1098
  export type PairChallengeOut = {