my-durable 0.0.62 → 0.0.63
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.
- package/apps/dpi-backend/src/pairing-files.ts +65 -0
- package/apps/dpi-backend/src/pairing.ts +25 -9
- package/apps/dpi-backend/src/store.ts +27 -7
- package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +1 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/credentials.ts +46 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +21 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +101 -7
- package/apps/dpi-playground/apps/dpi-playground-hub/src/rotation.ts +80 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +160 -35
- package/apps/dpi-sdk/src/protocol/limits.ts +27 -0
- package/apps/dpi-sdk/src/protocol/tunnel.ts +18 -14
- package/package.json +1 -1
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import {
|
|
11
11
|
chmodSync,
|
|
12
12
|
closeSync,
|
|
13
|
+
copyFileSync,
|
|
13
14
|
fsyncSync,
|
|
14
15
|
openSync,
|
|
15
16
|
readFileSync,
|
|
@@ -101,6 +102,70 @@ export function loadJson<T>(path: string): T | undefined {
|
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
|
|
105
|
+
/** Outcome of loading the device pairing state. Exactly one of `file`/`corrupt` is set; a fresh device has neither. */
|
|
106
|
+
export interface PairingFileLoad {
|
|
107
|
+
/** A parseable pairing.json (shape is judged by the caller). */
|
|
108
|
+
file?: PairingFile;
|
|
109
|
+
/** pairing.json existed but was not valid JSON — it was quarantined (or, if that failed, left in place). */
|
|
110
|
+
corrupt?: { quarantinedAs: string };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* R9 (audit 1.1): a corrupt pairing.json must never read as a silent "unpaired" —
|
|
115
|
+
* that orphans a live hub credential with no trace on disk. Following the
|
|
116
|
+
* schedules registry pattern (schedules.ts load(): move aside + warn): a parse
|
|
117
|
+
* failure renames the file aside so the bytes survive for inspection/restore,
|
|
118
|
+
* with a loud warning naming the quarantine path. A read failure (permissions,
|
|
119
|
+
* I/O) keeps the file in place — its bytes may be fine — but is warned about,
|
|
120
|
+
* never swallowed.
|
|
121
|
+
*/
|
|
122
|
+
export function loadPairingFile(home: string): PairingFileLoad {
|
|
123
|
+
const path = pairingPath(home);
|
|
124
|
+
let raw: string;
|
|
125
|
+
try {
|
|
126
|
+
raw = readFileSync(path, "utf8");
|
|
127
|
+
} catch (e) {
|
|
128
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") return {}; // fresh device: nothing to load
|
|
129
|
+
console.warn(
|
|
130
|
+
`[pairing] ${path} could not be read (${(e as Error).message}); the device reads as unpaired — fix the file before re-pairing, or a live hub credential stays orphaned`,
|
|
131
|
+
);
|
|
132
|
+
return {};
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
return { file: JSON.parse(raw) as PairingFile };
|
|
136
|
+
} catch (e) {
|
|
137
|
+
const aside = `${path}.corrupt-${Date.now()}`;
|
|
138
|
+
try {
|
|
139
|
+
renameSync(path, aside);
|
|
140
|
+
} catch {
|
|
141
|
+
console.warn(
|
|
142
|
+
`[pairing] pairing.json is not valid JSON (${(e as Error).message}) and could not be moved aside; it was left untouched in place`,
|
|
143
|
+
);
|
|
144
|
+
return { corrupt: { quarantinedAs: path } };
|
|
145
|
+
}
|
|
146
|
+
console.warn(
|
|
147
|
+
`[pairing] pairing.json was not valid JSON (${(e as Error).message}) — a live hub credential may now be orphaned. ` +
|
|
148
|
+
`The unreadable file was quarantined as ${aside}; recover it from a backup (or the last-good ${path}.bak), or re-pair this device`,
|
|
149
|
+
);
|
|
150
|
+
return { corrupt: { quarantinedAs: aside } };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Keep the previous good pairing.json as `.bak` before it is replaced (R9 1.1,
|
|
156
|
+
* same recovery story as the schedules registry): even after the corrupt
|
|
157
|
+
* original was quarantined there is a known-good recovery source on disk.
|
|
158
|
+
* Best effort — a failed backup never blocks the atomic replacement.
|
|
159
|
+
*/
|
|
160
|
+
export function backUpPairingFile(path: string): void {
|
|
161
|
+
try {
|
|
162
|
+
copyFileSync(path, `${path}.bak`);
|
|
163
|
+
ensureFileMode0600(`${path}.bak`);
|
|
164
|
+
} catch {
|
|
165
|
+
/* nothing to back up (first pairing) or the copy failed — the new file still lands atomically */
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
104
169
|
/**
|
|
105
170
|
* The device key, or undefined when there is none yet. Anything else that keeps it from being read (permissions,
|
|
106
171
|
* I/O error, truncated or damaged contents) throws: the caller must not answer that by minting a new identity
|
|
@@ -24,10 +24,11 @@ import {
|
|
|
24
24
|
import { hostname, platform } from "node:os";
|
|
25
25
|
import type { Store } from "./store.js";
|
|
26
26
|
import {
|
|
27
|
+
backUpPairingFile,
|
|
27
28
|
ensureFileMode0600,
|
|
28
29
|
ensurePrivateDir,
|
|
29
30
|
keypairPath,
|
|
30
|
-
|
|
31
|
+
loadPairingFile,
|
|
31
32
|
pairingPath,
|
|
32
33
|
readKeypairFile,
|
|
33
34
|
removeStaleTemps,
|
|
@@ -80,7 +81,8 @@ export interface PairingStartInput {
|
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
export type PairingStatus = {
|
|
83
|
-
|
|
84
|
+
/** `file-error`: pairing.json was present but unreadable/unparseable — it was quarantined (R9 1.1); lastError names the path. */
|
|
85
|
+
state: "unpaired" | "pairing" | "paired" | "revoked" | "file-error";
|
|
84
86
|
deviceUid: string;
|
|
85
87
|
deviceName: string;
|
|
86
88
|
fingerprint: string; // from the LOCAL key — never echoed from the hub
|
|
@@ -180,6 +182,8 @@ export class DevicePairing {
|
|
|
180
182
|
private keypair: DeviceKeypair | undefined;
|
|
181
183
|
private paired: PairingFile | undefined;
|
|
182
184
|
private revokedNotice = false;
|
|
185
|
+
/** R9 1.1: pairing.json was quarantined at boot — a live hub credential may be orphaned (detail names the path). */
|
|
186
|
+
private fileError: string | undefined;
|
|
183
187
|
|
|
184
188
|
constructor(
|
|
185
189
|
private readonly store: Store,
|
|
@@ -197,7 +201,12 @@ export class DevicePairing {
|
|
|
197
201
|
ensurePrivateDir(home);
|
|
198
202
|
removeStaleTemps(home);
|
|
199
203
|
this.loadKeypair();
|
|
200
|
-
|
|
204
|
+
const loaded = loadPairingFile(home);
|
|
205
|
+
if (loaded.corrupt)
|
|
206
|
+
this.fileError =
|
|
207
|
+
`pairing.json was not valid JSON and was quarantined as ${loaded.corrupt.quarantinedAs}; ` +
|
|
208
|
+
`a live hub credential may be orphaned — recover it from a backup or ${pairingPath(home)}.bak, or re-pair`;
|
|
209
|
+
this.paired = loaded.file;
|
|
201
210
|
if (this.paired) ensureFileMode0600(pairingPath(home));
|
|
202
211
|
if (this.paired) ensurePrivateDir(home);
|
|
203
212
|
}
|
|
@@ -229,11 +238,13 @@ export class DevicePairing {
|
|
|
229
238
|
const base: PairingStatus = {
|
|
230
239
|
state: this.pending
|
|
231
240
|
? "pairing"
|
|
232
|
-
: this.
|
|
233
|
-
? "
|
|
234
|
-
: this.
|
|
235
|
-
? "
|
|
236
|
-
:
|
|
241
|
+
: this.fileError
|
|
242
|
+
? "file-error"
|
|
243
|
+
: this.revokedNotice
|
|
244
|
+
? "revoked"
|
|
245
|
+
: this.paired
|
|
246
|
+
? "paired"
|
|
247
|
+
: "unpaired",
|
|
237
248
|
deviceUid: this.store.uid,
|
|
238
249
|
deviceName: this.deviceName,
|
|
239
250
|
fingerprint: this.keypair!.fingerprint,
|
|
@@ -254,7 +265,9 @@ export class DevicePairing {
|
|
|
254
265
|
},
|
|
255
266
|
}
|
|
256
267
|
: {}),
|
|
257
|
-
...(this.lastFailure
|
|
268
|
+
...((this.lastFailure ?? this.fileError)
|
|
269
|
+
? { lastError: this.lastFailure ?? this.fileError }
|
|
270
|
+
: {}),
|
|
258
271
|
};
|
|
259
272
|
return base;
|
|
260
273
|
}
|
|
@@ -680,6 +693,8 @@ export class DevicePairing {
|
|
|
680
693
|
// never authenticated (the proof was checked at the challenge, not here).
|
|
681
694
|
...(pending.kfp ? { hubKeyFingerprint: pending.kfp } : {}),
|
|
682
695
|
};
|
|
696
|
+
// R9 1.1: keep the previous good file recoverable before it is replaced.
|
|
697
|
+
backUpPairingFile(pairingPath(this.home));
|
|
683
698
|
writeAtomic(pairingPath(this.home), JSON.stringify(file, null, 2));
|
|
684
699
|
// Re-check: a newer operation/pairing must not be clobbered by this commit.
|
|
685
700
|
if (this.pending?.operationId !== pending.operationId) return;
|
|
@@ -688,6 +703,7 @@ export class DevicePairing {
|
|
|
688
703
|
this.paired = file;
|
|
689
704
|
this.pending = undefined;
|
|
690
705
|
this.lastFailure = undefined;
|
|
706
|
+
this.fileError = undefined; // a good file just landed; the quarantine notice is obsolete
|
|
691
707
|
this.revokedNotice = false;
|
|
692
708
|
// The old hub keeps its tunnel and its pairing right up to here: only a persisted replacement ends them.
|
|
693
709
|
if (previous && previous.hubOrigin !== file.hubOrigin) {
|
|
@@ -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);
|
|
@@ -2675,7 +2683,11 @@ export class Store {
|
|
|
2675
2683
|
// Persist the intent before any await that can wedge. If this persist
|
|
2676
2684
|
// itself fails (disk full), the run still proceeds — it just loses the
|
|
2677
2685
|
// crash-safety guarantee, like every version before R8.
|
|
2678
|
-
await
|
|
2686
|
+
await deadline(
|
|
2687
|
+
this.schedules.markRun(record.id, { outcome: "started" }),
|
|
2688
|
+
SCHEDULE_REGISTRY_IO_MS,
|
|
2689
|
+
"schedule registry write timed out (started)",
|
|
2690
|
+
).catch(() => undefined);
|
|
2679
2691
|
await this.dispatchBounded(record);
|
|
2680
2692
|
} finally {
|
|
2681
2693
|
this.scheduleInFlight.delete(record.id);
|
|
@@ -2698,11 +2710,15 @@ export class Store {
|
|
|
2698
2710
|
private async dispatchBounded(record: ScheduleRecord): Promise<void> {
|
|
2699
2711
|
let sessionId: string | undefined;
|
|
2700
2712
|
const recordFailure = async (outcome: "failed" | "timeout", detail: string) => {
|
|
2701
|
-
await
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2713
|
+
await deadline(
|
|
2714
|
+
this.schedules.markRun(record.id, {
|
|
2715
|
+
...(sessionId ? { sessionId } : {}),
|
|
2716
|
+
outcome,
|
|
2717
|
+
error: detail.slice(0, 300),
|
|
2718
|
+
}),
|
|
2719
|
+
SCHEDULE_REGISTRY_IO_MS,
|
|
2720
|
+
"schedule registry write timed out (failure)",
|
|
2721
|
+
).catch(() => undefined);
|
|
2706
2722
|
void this.notifyEvent({
|
|
2707
2723
|
kind: "schedule.failed",
|
|
2708
2724
|
title: `Schedule failed: ${record.name}`,
|
|
@@ -2738,7 +2754,11 @@ export class Store {
|
|
|
2738
2754
|
return;
|
|
2739
2755
|
}
|
|
2740
2756
|
if (result.status === "done") {
|
|
2741
|
-
await
|
|
2757
|
+
await deadline(
|
|
2758
|
+
this.schedules.markRun(record.id, { sessionId, outcome: "ok" }),
|
|
2759
|
+
SCHEDULE_REGISTRY_IO_MS,
|
|
2760
|
+
"schedule registry write timed out (ok)",
|
|
2761
|
+
).catch(() => undefined);
|
|
2742
2762
|
void this.notifyEvent({
|
|
2743
2763
|
kind: "schedule.ok",
|
|
2744
2764
|
title: `Schedule ran: ${record.name}`,
|
|
@@ -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)
|
|
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
|
|
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
|
|
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 (!
|
|
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<
|
|
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
|
|
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 = {
|
|
@@ -33,7 +33,11 @@
|
|
|
33
33
|
import { randomUUID, createHash } from "node:crypto";
|
|
34
34
|
import type { NetworkRegistry } from "../../../../dpi-sdk/src/node/registry.js";
|
|
35
35
|
import type { TunnelFrame } from "../../../../dpi-sdk/src/protocol/tunnel.js";
|
|
36
|
-
import {
|
|
36
|
+
import {
|
|
37
|
+
ROTATION_INTERVAL_DAYS,
|
|
38
|
+
ROTATION_RECOVERY_LIMIT_PER_HOUR,
|
|
39
|
+
ROTATION_RECOVERY_WINDOW_MS,
|
|
40
|
+
} from "../../../../dpi-sdk/src/protocol/limits.js";
|
|
37
41
|
import { Audit } from "./audit.js";
|
|
38
42
|
import { newTunnelToken } from "./tunnel-token.js";
|
|
39
43
|
import type { TunnelServer } from "./tunnel.js";
|
|
@@ -44,6 +48,10 @@ export interface RotationHooks {
|
|
|
44
48
|
cacheTtlMs?: number;
|
|
45
49
|
/** RAM cache capacity (bounded). */
|
|
46
50
|
cacheCapacity?: number;
|
|
51
|
+
/** Cache-loss recovery mints per device per hour (test policy; production CANON 6). */
|
|
52
|
+
recoveryLimitPerHour?: number;
|
|
53
|
+
/** Refusal-report window override (test policy; production 1 h). R9 6.1. */
|
|
54
|
+
recoveryWindowMs?: number;
|
|
47
55
|
/** Publish committed metadata changes to open browser streams. */
|
|
48
56
|
onChange?(): void;
|
|
49
57
|
}
|
|
@@ -74,6 +82,17 @@ export class RotationService {
|
|
|
74
82
|
*/
|
|
75
83
|
private readonly deliveries = new Map<string, string>();
|
|
76
84
|
private readonly now: () => number;
|
|
85
|
+
/**
|
|
86
|
+
* R9 (audit 4.4): recovery-mint timestamps per device (1 h sliding window, RAM). recoverFromCacheLoss
|
|
87
|
+
* used to mint one generation per post-TTL reconnect on an asymmetric flapping link — tunnel_credentials
|
|
88
|
+
* grew a row per reconnect cycle for as long as the link stayed broken. Cleared only by time; a hub
|
|
89
|
+
* restart clears it too, which is fine (the limiter targets sustained flapping within one uptime).
|
|
90
|
+
*/
|
|
91
|
+
private readonly recoveryMints = new Map<string, number[]>();
|
|
92
|
+
/** R9 6.1: refusal audit rows are sticky — one rate_limited row per device per
|
|
93
|
+
* window, not one per handshake attempt forever (a flapping link handshakes
|
|
94
|
+
* every few seconds; the row is a signal, not a log). */
|
|
95
|
+
private readonly recoveryRefusalsReported = new Map<string, number>();
|
|
77
96
|
|
|
78
97
|
constructor(
|
|
79
98
|
private readonly registry: NetworkRegistry,
|
|
@@ -316,6 +335,35 @@ export class RotationService {
|
|
|
316
335
|
this.deliveries.set(rotationId, connectionId);
|
|
317
336
|
}
|
|
318
337
|
|
|
338
|
+
// -- recovery-mint rate limit (R9 4.4) ---------------------------------
|
|
339
|
+
|
|
340
|
+
/** Recovery mints still inside the sliding window for this device (pruned as a side effect). */
|
|
341
|
+
private recentRecoveryMints(deviceId: string): number[] {
|
|
342
|
+
const windowStart = this.now() - ROTATION_RECOVERY_WINDOW_MS;
|
|
343
|
+
const kept = (this.recoveryMints.get(deviceId) ?? []).filter((t) => t >= windowStart);
|
|
344
|
+
if (kept.length > 0) this.recoveryMints.set(deviceId, kept);
|
|
345
|
+
else this.recoveryMints.delete(deviceId);
|
|
346
|
+
return kept;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private allowRecoveryMint(deviceId: string): boolean {
|
|
350
|
+
return (
|
|
351
|
+
this.recentRecoveryMints(deviceId).length <
|
|
352
|
+
(this.hooks.recoveryLimitPerHour ?? ROTATION_RECOVERY_LIMIT_PER_HOUR)
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private rememberRecoveryMint(deviceId: string, at: number): void {
|
|
357
|
+
const kept = this.recentRecoveryMints(deviceId);
|
|
358
|
+
kept.push(at);
|
|
359
|
+
this.recoveryMints.set(deviceId, kept);
|
|
360
|
+
if (this.recoveryMints.size > 4_096) {
|
|
361
|
+
// Hard backstop (same order as the tunnel grace caps): one entry per device.
|
|
362
|
+
const oldest = this.recoveryMints.keys().next().value;
|
|
363
|
+
if (oldest !== undefined && oldest !== deviceId) this.recoveryMints.delete(oldest);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
319
367
|
// -- handshake-driven recovery ---------------------------------------------
|
|
320
368
|
|
|
321
369
|
/** Called after every valid identity handshake. */
|
|
@@ -442,7 +490,10 @@ export class RotationService {
|
|
|
442
490
|
/**
|
|
443
491
|
* Cache lost/expired: retire the UNCONFIRMED current (it never reached the
|
|
444
492
|
* device), keep the previous (the credential the device still holds) and
|
|
445
|
-
* mint the next generation as the new target.
|
|
493
|
+
* mint the next generation as the new target. Rate-limited per device: a
|
|
494
|
+
* link that keeps needing recoveries is flapping asymmetrically, and minting
|
|
495
|
+
* G+n per reconnect grows tunnel_credentials without bound — past the limit
|
|
496
|
+
* the hub refuses and the pairing needs a full re-pair instead (R9 4.4).
|
|
446
497
|
*/
|
|
447
498
|
private recoverFromCacheLoss(
|
|
448
499
|
deviceId: string,
|
|
@@ -450,6 +501,31 @@ export class RotationService {
|
|
|
450
501
|
unconfirmedCredentialId: string | null,
|
|
451
502
|
): void {
|
|
452
503
|
if (!oldRotationId || !unconfirmedCredentialId) return;
|
|
504
|
+
if (!this.allowRecoveryMint(deviceId)) {
|
|
505
|
+
// Refuse WITHOUT minting: the rotation stays pending, the device stays on its
|
|
506
|
+
// previous credential and generations stop climbing. The audit row is the
|
|
507
|
+
// operator signal that this pairing needs a full re-pair (revoke + pair),
|
|
508
|
+
// not another generation — and it is reported once per window (R9 6.1).
|
|
509
|
+
const windowStart = this.now() - (this.hooks.recoveryWindowMs ?? ROTATION_RECOVERY_WINDOW_MS);
|
|
510
|
+
const lastReport = this.recoveryRefusalsReported.get(deviceId) ?? 0;
|
|
511
|
+
if (lastReport < windowStart) {
|
|
512
|
+
this.recoveryRefusalsReported.set(deviceId, this.now());
|
|
513
|
+
this.audit.withTransaction(() => {
|
|
514
|
+
this.audit.append({
|
|
515
|
+
actor: "hub",
|
|
516
|
+
action: "rate_limited",
|
|
517
|
+
outcome: "denied",
|
|
518
|
+
detail: {
|
|
519
|
+
deviceId,
|
|
520
|
+
policy: "rotation_recovery_per_hour",
|
|
521
|
+
limit: this.hooks.recoveryLimitPerHour ?? ROTATION_RECOVERY_LIMIT_PER_HOUR,
|
|
522
|
+
reason: "cache-loss recovery mints exhausted (flapping link); re-pair required",
|
|
523
|
+
},
|
|
524
|
+
});
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
453
529
|
const pairing = this.registry.db
|
|
454
530
|
.prepare(
|
|
455
531
|
"SELECT pairing_epoch, credential_generation FROM pairings WHERE device_id=? AND status='paired'",
|
|
@@ -497,6 +573,8 @@ export class RotationService {
|
|
|
497
573
|
});
|
|
498
574
|
this.cacheForget(oldRotationId);
|
|
499
575
|
this.deliveries.delete(oldRotationId);
|
|
576
|
+
// Count only mints that committed: a rolled-back recovery minted nothing.
|
|
577
|
+
this.rememberRecoveryMint(deviceId, now);
|
|
500
578
|
this.cachePut(rotationId, {
|
|
501
579
|
deviceId,
|
|
502
580
|
token,
|
|
@@ -9,8 +9,17 @@
|
|
|
9
9
|
*
|
|
10
10
|
* REST hardening (pending caps, path allowlist enforcement on the hub side,
|
|
11
11
|
* chunked responses, mutation safety) lands in P2-16; this file owns routing.
|
|
12
|
+
*
|
|
13
|
+
* R9 (audit 4.1/4.3): the late-frame grace sets evict by TTL as well as by
|
|
14
|
+
* capacity — an entry older than REST_GRACE_TTL_MS is unmatchable by any
|
|
15
|
+
* in-flight caller — and every eviction (age or capacity) is remembered in a
|
|
16
|
+
* bounded `dropped` ring so the late frame that eventually arrives for it is
|
|
17
|
+
* recognized as inert instead of foreign: reconnect churn must never cut a
|
|
18
|
+
* healthy connection. Un-keyed tunnel mutations get a deterministic
|
|
19
|
+
* idempotency key so a hub retry after a connection swap deduplicates
|
|
20
|
+
* device-side instead of double-applying.
|
|
12
21
|
*/
|
|
13
|
-
import { randomUUID } from "node:crypto";
|
|
22
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
14
23
|
import { DpiError } from "../../../../dpi-sdk/src/errors.js";
|
|
15
24
|
import type { Frame } from "../../../../dpi-sdk/src/api.js";
|
|
16
25
|
import {
|
|
@@ -21,6 +30,7 @@ import {
|
|
|
21
30
|
import {
|
|
22
31
|
CONNECTION_BUFFER_BUDGET_BYTES,
|
|
23
32
|
REST_BODY_MAX_BYTES,
|
|
33
|
+
REST_GRACE_TTL_MS,
|
|
24
34
|
REST_PENDING_PER_DEVICE,
|
|
25
35
|
REST_PENDING_PER_HUB,
|
|
26
36
|
REST_TIMEOUT_MS,
|
|
@@ -58,6 +68,19 @@ interface Subscription {
|
|
|
58
68
|
onAbort: () => void;
|
|
59
69
|
}
|
|
60
70
|
|
|
71
|
+
/** A grace-set entry: which connection owned the correlation, and when it left the pending maps. */
|
|
72
|
+
interface GraceEntry {
|
|
73
|
+
connectionId: string;
|
|
74
|
+
at: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** settled/abandoned reqId grace cap (hard memory backstop; TTL is the primary bound). */
|
|
78
|
+
const REST_GRACE_MAP_CAP = 256;
|
|
79
|
+
/** closed-subscription grace cap. */
|
|
80
|
+
const CLOSED_SUBS_GRACE_CAP = 4_096;
|
|
81
|
+
/** Hard cap for the evicted-correlation ring (same order as the grace caps). */
|
|
82
|
+
const GRACE_RING_CAP = 4_096;
|
|
83
|
+
|
|
61
84
|
/**
|
|
62
85
|
* Routes inbound device→hub frames: rest-response resolves the matching
|
|
63
86
|
* pending request, tunnel-data feeds the matching subscription. A frame for a
|
|
@@ -69,6 +92,10 @@ export interface DispatcherOptions {
|
|
|
69
92
|
audit?: Audit;
|
|
70
93
|
/** Test-only deadline policy (production: CANON REST_TIMEOUT_MS). */
|
|
71
94
|
deadlineMs?: number;
|
|
95
|
+
/** Test-only late-frame grace TTL (production: CANON REST_GRACE_TTL_MS). */
|
|
96
|
+
graceTtlMs?: number;
|
|
97
|
+
/** Test-only clock for the grace sets (production: Date.now). */
|
|
98
|
+
now?: () => number;
|
|
72
99
|
/** Shared admission for REST payloads, reassembly and SSE output. */
|
|
73
100
|
budget?: ByteBudget;
|
|
74
101
|
/** Per-connection share of `budget` (production: CANON 32 MiB). */
|
|
@@ -84,14 +111,20 @@ export class TunnelDispatcher {
|
|
|
84
111
|
/** connectionId → that connection's share of the hub budget (reassembly + pending REST payloads). */
|
|
85
112
|
private readonly connectionBudgets = new Map<string, ByteBudget>();
|
|
86
113
|
private readonly reassemblers = new Map<string, ChunkReassembler>(); // connectionId → reassembler
|
|
87
|
-
/** reqId →
|
|
88
|
-
private readonly settled = new Map<string,
|
|
114
|
+
/** reqId → recently settled requests (late-response grace, TTL + capped). */
|
|
115
|
+
private readonly settled = new Map<string, GraceEntry>();
|
|
89
116
|
/** The same grace for ABANDONED requests (timeout/abort/connection loss): the device may still be
|
|
90
117
|
* writing their response right now, and normal traffic must never churn these correlations away. */
|
|
91
|
-
private readonly abandoned = new Map<string,
|
|
92
|
-
/** subscriptionId →
|
|
93
|
-
private readonly closedSubs = new Map<string,
|
|
118
|
+
private readonly abandoned = new Map<string, GraceEntry>();
|
|
119
|
+
/** subscriptionId → recently closed subscriptions (in-flight frames after an unsubscribe are benign). */
|
|
120
|
+
private readonly closedSubs = new Map<string, GraceEntry>();
|
|
121
|
+
/** Correlations that left a grace set (TTL-expired or capacity-evicted) → removal time. Their
|
|
122
|
+
* late frames resolve nothing and are dropped, never cut — cutting them is what turned reconnect
|
|
123
|
+
* churn into connection storms (R9 4.1). Bounded like the grace sets themselves. */
|
|
124
|
+
private readonly dropped = new Map<string, number>();
|
|
94
125
|
private readonly deadlineMs: number;
|
|
126
|
+
private readonly graceTtlMs: number;
|
|
127
|
+
private readonly now: () => number;
|
|
95
128
|
private readonly audit?: Audit;
|
|
96
129
|
|
|
97
130
|
constructor(
|
|
@@ -100,6 +133,8 @@ export class TunnelDispatcher {
|
|
|
100
133
|
) {
|
|
101
134
|
this.audit = options.audit;
|
|
102
135
|
this.deadlineMs = options.deadlineMs ?? REST_TIMEOUT_MS;
|
|
136
|
+
this.graceTtlMs = options.graceTtlMs ?? REST_GRACE_TTL_MS;
|
|
137
|
+
this.now = options.now ?? Date.now;
|
|
103
138
|
this.budget = options.budget ?? new ByteBudget("rest", 64 * 1024 * 1024);
|
|
104
139
|
this.connectionBudgetBytes = options.connectionBudgetBytes ?? CONNECTION_BUFFER_BUDGET_BYTES;
|
|
105
140
|
server.setHandlers({
|
|
@@ -121,18 +156,89 @@ export class TunnelDispatcher {
|
|
|
121
156
|
p.signal.removeEventListener("abort", p.onAbort);
|
|
122
157
|
p.reservation?.release();
|
|
123
158
|
this.reassemblers.get(p.connectionId)?.abort({ kind: "rest-response", reqId });
|
|
124
|
-
// Remember recently-settled reqIds (bounded): a late response for an
|
|
159
|
+
// Remember recently-settled reqIds (bounded + TTL'd): a late response for an
|
|
125
160
|
// aborted/timed-out OWN request on the SAME connection is benign and must
|
|
126
161
|
// not kill the connection; foreign reqIds still do (below). Abandoned
|
|
127
|
-
// correlations get their own
|
|
162
|
+
// correlations get their own map so busy normal traffic cannot evict the
|
|
128
163
|
// correlation of a response that is still legitimately in flight.
|
|
129
164
|
const map = outcome === "abandoned" ? this.abandoned : this.settled;
|
|
130
|
-
|
|
131
|
-
|
|
165
|
+
this.gracePut(map, reqId, p.connectionId, REST_GRACE_MAP_CAP);
|
|
166
|
+
return p;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Insert into a grace set: TTL-evict first (an entry older than the grace TTL is unmatchable by
|
|
171
|
+
* any in-flight caller — the device's own send tail is inside the TTL, see REST_GRACE_TTL_MS),
|
|
172
|
+
* then the capacity cap as the hard memory backstop. Everything removed lands in the `dropped`
|
|
173
|
+
* ring so the late frame that eventually arrives for it is inert, not foreign (R9 4.1).
|
|
174
|
+
*/
|
|
175
|
+
private gracePut(
|
|
176
|
+
map: Map<string, GraceEntry>,
|
|
177
|
+
id: string,
|
|
178
|
+
connectionId: string,
|
|
179
|
+
cap: number,
|
|
180
|
+
): void {
|
|
181
|
+
const ts = this.now();
|
|
182
|
+
for (const [key, entry] of map) {
|
|
183
|
+
if (ts - entry.at <= this.graceTtlMs) break; // insertion order == age order
|
|
184
|
+
map.delete(key);
|
|
185
|
+
this.rememberDropped(key, ts);
|
|
186
|
+
}
|
|
187
|
+
map.set(id, { connectionId, at: ts });
|
|
188
|
+
while (map.size > cap) {
|
|
132
189
|
const oldest = map.keys().next().value;
|
|
133
|
-
if (oldest
|
|
190
|
+
if (oldest === undefined) break;
|
|
191
|
+
map.delete(oldest);
|
|
192
|
+
this.rememberDropped(oldest, ts);
|
|
134
193
|
}
|
|
135
|
-
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Grace-set lookup: an entry past its TTL retires to the ring on first touch. */
|
|
197
|
+
private graceOwns(map: Map<string, GraceEntry>, id: string, connectionId: string): boolean {
|
|
198
|
+
const entry = map.get(id);
|
|
199
|
+
if (!entry) return false;
|
|
200
|
+
if (this.now() - entry.at > this.graceTtlMs) {
|
|
201
|
+
map.delete(id);
|
|
202
|
+
this.rememberDropped(id, this.now());
|
|
203
|
+
}
|
|
204
|
+
return entry.connectionId === connectionId;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** True while a removed correlation is recent enough that its late frames are inert, not foreign. */
|
|
208
|
+
private wasDropped(id: string): boolean {
|
|
209
|
+
const at = this.dropped.get(id);
|
|
210
|
+
if (at === undefined) return false;
|
|
211
|
+
if (this.now() - at > this.graceTtlMs) {
|
|
212
|
+
this.dropped.delete(id);
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private rememberDropped(id: string, at: number): void {
|
|
219
|
+
this.dropped.set(id, at);
|
|
220
|
+
for (const [key, t] of this.dropped) {
|
|
221
|
+
if (at - t <= this.graceTtlMs) break; // front is the oldest removal
|
|
222
|
+
this.dropped.delete(key);
|
|
223
|
+
}
|
|
224
|
+
while (this.dropped.size > GRACE_RING_CAP) {
|
|
225
|
+
const oldest = this.dropped.keys().next().value;
|
|
226
|
+
if (oldest === undefined) break;
|
|
227
|
+
this.dropped.delete(oldest);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* A late rest frame for a correlation this hub recently issued: still inside a grace set, or
|
|
233
|
+
* recently expired/evicted from one (the `dropped` ring). Such a frame can resolve nothing — its
|
|
234
|
+
* pending is gone — so it is dropped silently; cutting the sender here is what turned reconnect
|
|
235
|
+
* churn into connection storms (R9 4.1). A correlation that is pending on ANOTHER connection or
|
|
236
|
+
* was never issued is still foreign and still cuts (T-7).
|
|
237
|
+
*/
|
|
238
|
+
private lateFrameIsBenign(id: string, connectionId: string): boolean {
|
|
239
|
+
if (this.graceOwns(this.settled, id, connectionId)) return true;
|
|
240
|
+
if (this.graceOwns(this.abandoned, id, connectionId)) return true;
|
|
241
|
+
return this.wasDropped(id);
|
|
136
242
|
}
|
|
137
243
|
|
|
138
244
|
/**
|
|
@@ -167,14 +273,10 @@ export class TunnelDispatcher {
|
|
|
167
273
|
// Foreign or already-settled responses never resolve someone else's
|
|
168
274
|
// request; matching requires the SAME connection that owns the pending.
|
|
169
275
|
if (!p || p.connectionId !== conn.connectionId) {
|
|
170
|
-
// Late response for an OWN settled request
|
|
171
|
-
//
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
(this.settled.get(reqId) === conn.connectionId ||
|
|
175
|
-
this.abandoned.get(reqId) === conn.connectionId)
|
|
176
|
-
)
|
|
177
|
-
return;
|
|
276
|
+
// Late response for an OWN settled/abandoned request — or one whose grace
|
|
277
|
+
// entry just expired/was evicted — on the same connection: ignore silently
|
|
278
|
+
// (the caller already moved on; the frame resolves nothing).
|
|
279
|
+
if (p === undefined && this.lateFrameIsBenign(reqId, conn.connectionId)) return;
|
|
178
280
|
if (p !== undefined && p.connectionId !== conn.connectionId) {
|
|
179
281
|
// A response claiming a reqId owned by ANOTHER connection: attack.
|
|
180
282
|
}
|
|
@@ -199,12 +301,7 @@ export class TunnelDispatcher {
|
|
|
199
301
|
if (chunk.kind === "rest-response") {
|
|
200
302
|
const pending = this.pending.get(chunk.reqId);
|
|
201
303
|
// Match the plain-response grace before allocating any assembly.
|
|
202
|
-
if (
|
|
203
|
-
!pending &&
|
|
204
|
-
(this.settled.get(chunk.reqId) === conn.connectionId ||
|
|
205
|
-
this.abandoned.get(chunk.reqId) === conn.connectionId)
|
|
206
|
-
)
|
|
207
|
-
return;
|
|
304
|
+
if (!pending && this.lateFrameIsBenign(chunk.reqId, conn.connectionId)) return;
|
|
208
305
|
if (!pending || pending.connectionId !== conn.connectionId) {
|
|
209
306
|
this.denyDevice(
|
|
210
307
|
conn,
|
|
@@ -311,8 +408,9 @@ export class TunnelDispatcher {
|
|
|
311
408
|
|
|
312
409
|
/**
|
|
313
410
|
* The live subscription a device frame addresses, if this connection owns it. A frame for a
|
|
314
|
-
* subscription it just closed
|
|
315
|
-
*
|
|
411
|
+
* subscription it just closed (or whose closed-subscription grace entry just expired) is benign
|
|
412
|
+
* (the device had it in flight) and is dropped; anything else (never issued, or owned by another
|
|
413
|
+
* connection) is a protocol violation: deny, audit, cut (T-7).
|
|
316
414
|
*/
|
|
317
415
|
private ownSubscription(
|
|
318
416
|
conn: TunnelConnection,
|
|
@@ -320,7 +418,9 @@ export class TunnelDispatcher {
|
|
|
320
418
|
): Subscription | undefined {
|
|
321
419
|
const sub = this.subs.get(subscriptionId);
|
|
322
420
|
if (sub && sub.connectionId === conn.connectionId) return sub;
|
|
323
|
-
if (!sub && this.closedSubs
|
|
421
|
+
if (!sub && this.graceOwns(this.closedSubs, subscriptionId, conn.connectionId))
|
|
422
|
+
return undefined;
|
|
423
|
+
if (!sub && this.wasDropped(subscriptionId)) return undefined;
|
|
324
424
|
this.denyDevice(
|
|
325
425
|
conn,
|
|
326
426
|
"foreign_subscription",
|
|
@@ -331,11 +431,7 @@ export class TunnelDispatcher {
|
|
|
331
431
|
}
|
|
332
432
|
|
|
333
433
|
private rememberClosedSubscription(subscriptionId: string, connectionId: string): void {
|
|
334
|
-
this.closedSubs
|
|
335
|
-
if (this.closedSubs.size > 4_096) {
|
|
336
|
-
const oldest = this.closedSubs.keys().next().value;
|
|
337
|
-
if (oldest !== undefined) this.closedSubs.delete(oldest);
|
|
338
|
-
}
|
|
434
|
+
this.gracePut(this.closedSubs, subscriptionId, connectionId, CLOSED_SUBS_GRACE_CAP);
|
|
339
435
|
}
|
|
340
436
|
|
|
341
437
|
/**
|
|
@@ -399,6 +495,16 @@ export class TunnelDispatcher {
|
|
|
399
495
|
pendingCount(): number {
|
|
400
496
|
return this.pending.size;
|
|
401
497
|
}
|
|
498
|
+
|
|
499
|
+
/** Test visibility into the bounded grace state (R9 4.1). */
|
|
500
|
+
graceSizes(): { settled: number; abandoned: number; closedSubs: number; dropped: number } {
|
|
501
|
+
return {
|
|
502
|
+
settled: this.settled.size,
|
|
503
|
+
abandoned: this.abandoned.size,
|
|
504
|
+
closedSubs: this.closedSubs.size,
|
|
505
|
+
dropped: this.dropped.size,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
402
508
|
subscriptionCount(deviceId?: string): number {
|
|
403
509
|
return deviceId === undefined
|
|
404
510
|
? this.subs.size
|
|
@@ -424,6 +530,25 @@ export class TunnelDispatcher {
|
|
|
424
530
|
new DpiError("invalid", `Request body exceeds ${REST_BODY_MAX_BYTES} bytes`, 413),
|
|
425
531
|
);
|
|
426
532
|
}
|
|
533
|
+
// R9 (audit 4.3): un-keyed tunnel MUTATIONS get a deterministic idempotency key so a
|
|
534
|
+
// hub retry after a connection swap/abandon (503 to the caller, then a re-send with a
|
|
535
|
+
// fresh reqId) lands on the SAME device-side key: the device's create-route idempotency
|
|
536
|
+
// (requests table + in-flight map) answers the replay instead of double-applying. The
|
|
537
|
+
// key is derived from the content — method + path + serialized body — so it is identical
|
|
538
|
+
// across the retry and independent of the connection that carried the first attempt.
|
|
539
|
+
// Reads (GET/HEAD) stay un-keyed: nothing to deduplicate. Collateral: two DELIBERATE
|
|
540
|
+
// identical mutations inside the device's 24 h requests retention collapse to the first
|
|
541
|
+
// outcome — accepted, because the alternative is a silent at-least-once mutation on every
|
|
542
|
+
// connection swap. The prefix marks hub-derived keys in device logs; 73 chars fits the
|
|
543
|
+
// device's 128-char header cap and the wire schema's 256.
|
|
544
|
+
const idempotencyKey =
|
|
545
|
+
input.idempotencyKey ??
|
|
546
|
+
(input.method === "GET" || input.method === "HEAD"
|
|
547
|
+
? undefined
|
|
548
|
+
: "dpi-auto-" +
|
|
549
|
+
createHash("sha256")
|
|
550
|
+
.update(`${input.method} ${input.path}\u0000${serialized ?? ""}`, "utf8")
|
|
551
|
+
.digest("hex"));
|
|
427
552
|
// Pending caps: 32/device, 256/hub (429 when full — no silent queueing).
|
|
428
553
|
let deviceSet = this.pendingByDevice.get(deviceId);
|
|
429
554
|
if (!deviceSet) {
|
|
@@ -468,7 +593,7 @@ export class TunnelDispatcher {
|
|
|
468
593
|
reqId,
|
|
469
594
|
method: input.method as "GET",
|
|
470
595
|
path: input.path,
|
|
471
|
-
...(
|
|
596
|
+
...(idempotencyKey ? { idempotencyKey } : {}),
|
|
472
597
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
473
598
|
});
|
|
474
599
|
if (!sent) {
|
|
@@ -56,6 +56,18 @@ export const REST_PENDING_PER_DEVICE = 32;
|
|
|
56
56
|
/** Pending REST requests hub-wide. */
|
|
57
57
|
export const REST_PENDING_PER_HUB = 256;
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Late-frame grace for settled/abandoned REST correlations and closed subscriptions (R9, audit 4.1).
|
|
61
|
+
* After the hub gives up on a request (REST_TIMEOUT_MS), a legitimately slow device may still be
|
|
62
|
+
* writing its answer: the device's own local REST deadline (320 s from receipt) plus per-chunk
|
|
63
|
+
* pacing (45 s idle cut) and hub-side reassembly (30 s) bound that tail, so the last honest frame
|
|
64
|
+
* lands ≈395 s after a hub-side abandonment. 420 s = that tail plus margin: entries younger than
|
|
65
|
+
* this stay matchable (normal lateness never cuts a connection); older entries are unmatchable by
|
|
66
|
+
* any in-flight caller and expire from the grace sets. The per-map capacity caps remain as the
|
|
67
|
+
* hard memory backstop.
|
|
68
|
+
*/
|
|
69
|
+
export const REST_GRACE_TTL_MS = 420_000;
|
|
70
|
+
|
|
59
71
|
/** Tunnel identity handshake deadline after 101. 5 s. */
|
|
60
72
|
export const HANDSHAKE_DEADLINE_MS = 5_000;
|
|
61
73
|
/** WS ping interval, both directions. 15 s. */
|
|
@@ -140,6 +152,21 @@ export const WS_UPGRADE_LIMITS = {
|
|
|
140
152
|
/** Routine credential rotation interval. 90 days. */
|
|
141
153
|
export const ROTATION_INTERVAL_DAYS = 90;
|
|
142
154
|
|
|
155
|
+
/**
|
|
156
|
+
* Cache-loss recovery mints per device per sliding hour (R9, audit 4.4). An asymmetric flapping
|
|
157
|
+
* link (device reconnects on the previous credential but never receives the rotate frame) mints
|
|
158
|
+
* one credential generation per post-TTL reconnect, growing tunnel_credentials without bound.
|
|
159
|
+
* 6/hour: a link that needs more than six recoveries in an hour has failed to deliver six
|
|
160
|
+
* consecutive rotations across ~12+ minutes of reconnects — minting further generations only
|
|
161
|
+
* grows the table, so the hub refuses and the pairing needs a full re-pair. Legitimate rotation
|
|
162
|
+
* (90-day expiry, admin request) mints via rotateOnline(), which this limiter never counts or
|
|
163
|
+
* blocks; a genuine cache loss heals in one or two mints, and even repeated hub restarts stay
|
|
164
|
+
* far below the cap.
|
|
165
|
+
*/
|
|
166
|
+
export const ROTATION_RECOVERY_LIMIT_PER_HOUR = 6;
|
|
167
|
+
/** Sliding window for the recovery-mint limiter. 1 h. */
|
|
168
|
+
export const ROTATION_RECOVERY_WINDOW_MS = 3_600_000;
|
|
169
|
+
|
|
143
170
|
/**
|
|
144
171
|
* Tunneled REST paths live under /v1 and must match the route allowlist (rest-routes.ts). SSE endpoints (streams
|
|
145
172
|
* are subscription-based) and the device-LOCAL control surface (pairing/tunnel status) are not on it: they belong
|
|
@@ -215,20 +215,24 @@ export const TunnelFrame = Type.Union([
|
|
|
215
215
|
},
|
|
216
216
|
Strict,
|
|
217
217
|
),
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
},
|
|
230
|
-
|
|
231
|
-
|
|
218
|
+
// R9 3.1 (version-skew tolerance): rest-response is NOT Strict. A newer
|
|
219
|
+
// device may add optional fields to this envelope (R8 added bodyEncoding /
|
|
220
|
+
// contentDisposition) — against a hub running an older schema, Strict mode
|
|
221
|
+
// turned every such frame into a protocol violation that CUT the tunnel
|
|
222
|
+
// (1008) on the common case (small binary exports). Readers consume only the
|
|
223
|
+
// known fields; unknown extras are ignored, and every other protection
|
|
224
|
+
// (foreign-reqId matching, size caps, status range) is enforced downstream.
|
|
225
|
+
Type.Object({
|
|
226
|
+
type: Type.Literal("rest-response"),
|
|
227
|
+
reqId: Uuid,
|
|
228
|
+
status: Type.Integer({ minimum: 100, maximum: 599 }),
|
|
229
|
+
contentType: Type.Optional(Type.String({ maxLength: 256 })),
|
|
230
|
+
body: Type.Optional(Type.Unknown()),
|
|
231
|
+
// R8 binary passthrough: non-textual device responses carry base64 bytes plus a
|
|
232
|
+
// sanitized download filename. Absent on the legacy textual envelope.
|
|
233
|
+
bodyEncoding: Type.Optional(Type.Union([Type.Literal("base64")])),
|
|
234
|
+
contentDisposition: Type.Optional(Type.String({ maxLength: 200 })),
|
|
235
|
+
}),
|
|
232
236
|
TunnelControl,
|
|
233
237
|
Type.Object(
|
|
234
238
|
{
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-durable",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.63",
|
|
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": {
|