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.
- package/apps/dpi-backend/src/gc-cli.ts +87 -1
- package/apps/dpi-backend/src/gc.ts +48 -1
- package/apps/dpi-backend/src/graphs.ts +28 -0
- package/apps/dpi-backend/src/pairing-files.ts +65 -0
- package/apps/dpi-backend/src/pairing.ts +25 -9
- package/apps/dpi-backend/src/routes.ts +6 -0
- package/apps/dpi-backend/src/salvage.ts +34 -13
- package/apps/dpi-backend/src/schedules.ts +98 -3
- package/apps/dpi-backend/src/store.ts +92 -9
- 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/api.ts +8 -0
- 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
|
@@ -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) {
|
package/apps/dpi-sdk/src/api.ts
CHANGED
|
@@ -390,6 +390,10 @@ export interface ScheduleRecord {
|
|
|
390
390
|
lastSessionId?: string;
|
|
391
391
|
lastOutcome?: "ok" | "failed";
|
|
392
392
|
lastError?: string;
|
|
393
|
+
/** R10: keep the last N runs' sessions live, archive older ones. Absent = never. */
|
|
394
|
+
keepRuns?: number;
|
|
395
|
+
/** R10: the retention window (newest keepRuns run session ids). */
|
|
396
|
+
recentSessionIds?: string[];
|
|
393
397
|
createdAt: number;
|
|
394
398
|
updatedAt: number;
|
|
395
399
|
}
|
|
@@ -399,6 +403,8 @@ export interface ScheduleView extends ScheduleRecord {
|
|
|
399
403
|
nextRunAt: number | null;
|
|
400
404
|
/** A turn is in flight for this schedule right now. */
|
|
401
405
|
running: boolean;
|
|
406
|
+
/** R10: count of retention-ring ids no longer live (so "keeping last N" renders truthfully). */
|
|
407
|
+
archivedRuns?: number;
|
|
402
408
|
}
|
|
403
409
|
|
|
404
410
|
export interface SchedulePatchBody {
|
|
@@ -409,6 +415,8 @@ export interface SchedulePatchBody {
|
|
|
409
415
|
everyMinutes?: number;
|
|
410
416
|
dailyAt?: string;
|
|
411
417
|
enabled?: boolean;
|
|
418
|
+
/** R10: set retention (1–100) or null to clear it. */
|
|
419
|
+
keepRuns?: number | null;
|
|
412
420
|
}
|
|
413
421
|
|
|
414
422
|
/** Device usage rollup over the sessions it still holds (archived are closed). */
|
|
@@ -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.64",
|
|
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": {
|