my-durable 0.0.61 → 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/scripts/bench-store.mjs +284 -0
- package/apps/dpi-backend/src/archived.ts +1 -1
- package/apps/dpi-backend/src/gc.ts +27 -6
- 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 +24 -1
- package/apps/dpi-backend/src/schedules.ts +65 -11
- package/apps/dpi-backend/src/store.ts +215 -43
- package/apps/dpi-backend/src/tunnel.ts +45 -13
- package/apps/dpi-backend/src/zip.ts +376 -10
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-4Kyozhl0.js → index-D10XyhhO.js} +23 -23
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BkSQ2clA.css → index-DCz-aq0b.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +10 -13
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +1 -1
- 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/proxy.ts +19 -5
- package/apps/dpi-playground/apps/dpi-playground-hub/src/rotation.ts +80 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +25 -4
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +183 -36
- package/apps/dpi-sdk/src/client.ts +73 -6
- package/apps/dpi-sdk/src/protocol/limits.ts +27 -0
- package/apps/dpi-sdk/src/protocol/tunnel.ts +18 -10
- package/package.json +1 -1
|
@@ -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,12 +30,21 @@ 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,
|
|
27
37
|
} from "../../../../dpi-sdk/src/protocol/limits.js";
|
|
28
38
|
import { ByteBudget, ChunkReassembler } from "../../../../dpi-sdk/src/node/chunk.js";
|
|
29
39
|
import type { DeviceTransport, TransportRequest, TransportResponse } from "./transport.js";
|
|
40
|
+
|
|
41
|
+
/** Device frames are untrusted at the ADMIN origin: printable ASCII only, bounded length
|
|
42
|
+
* (defense in depth — the device already sanitizes before putting it on the wire). */
|
|
43
|
+
const safeHeaderValue = (value: unknown): string | undefined => {
|
|
44
|
+
if (typeof value !== "string") return undefined;
|
|
45
|
+
const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
|
|
46
|
+
return clean.length > 0 ? clean : undefined;
|
|
47
|
+
};
|
|
30
48
|
import type { TunnelConnection, TunnelServer } from "./tunnel.js";
|
|
31
49
|
import type { Audit } from "./audit.js";
|
|
32
50
|
|
|
@@ -50,6 +68,19 @@ interface Subscription {
|
|
|
50
68
|
onAbort: () => void;
|
|
51
69
|
}
|
|
52
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
|
+
|
|
53
84
|
/**
|
|
54
85
|
* Routes inbound device→hub frames: rest-response resolves the matching
|
|
55
86
|
* pending request, tunnel-data feeds the matching subscription. A frame for a
|
|
@@ -61,6 +92,10 @@ export interface DispatcherOptions {
|
|
|
61
92
|
audit?: Audit;
|
|
62
93
|
/** Test-only deadline policy (production: CANON REST_TIMEOUT_MS). */
|
|
63
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;
|
|
64
99
|
/** Shared admission for REST payloads, reassembly and SSE output. */
|
|
65
100
|
budget?: ByteBudget;
|
|
66
101
|
/** Per-connection share of `budget` (production: CANON 32 MiB). */
|
|
@@ -76,14 +111,20 @@ export class TunnelDispatcher {
|
|
|
76
111
|
/** connectionId → that connection's share of the hub budget (reassembly + pending REST payloads). */
|
|
77
112
|
private readonly connectionBudgets = new Map<string, ByteBudget>();
|
|
78
113
|
private readonly reassemblers = new Map<string, ChunkReassembler>(); // connectionId → reassembler
|
|
79
|
-
/** reqId →
|
|
80
|
-
private readonly settled = new Map<string,
|
|
114
|
+
/** reqId → recently settled requests (late-response grace, TTL + capped). */
|
|
115
|
+
private readonly settled = new Map<string, GraceEntry>();
|
|
81
116
|
/** The same grace for ABANDONED requests (timeout/abort/connection loss): the device may still be
|
|
82
117
|
* writing their response right now, and normal traffic must never churn these correlations away. */
|
|
83
|
-
private readonly abandoned = new Map<string,
|
|
84
|
-
/** subscriptionId →
|
|
85
|
-
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>();
|
|
86
125
|
private readonly deadlineMs: number;
|
|
126
|
+
private readonly graceTtlMs: number;
|
|
127
|
+
private readonly now: () => number;
|
|
87
128
|
private readonly audit?: Audit;
|
|
88
129
|
|
|
89
130
|
constructor(
|
|
@@ -92,6 +133,8 @@ export class TunnelDispatcher {
|
|
|
92
133
|
) {
|
|
93
134
|
this.audit = options.audit;
|
|
94
135
|
this.deadlineMs = options.deadlineMs ?? REST_TIMEOUT_MS;
|
|
136
|
+
this.graceTtlMs = options.graceTtlMs ?? REST_GRACE_TTL_MS;
|
|
137
|
+
this.now = options.now ?? Date.now;
|
|
95
138
|
this.budget = options.budget ?? new ByteBudget("rest", 64 * 1024 * 1024);
|
|
96
139
|
this.connectionBudgetBytes = options.connectionBudgetBytes ?? CONNECTION_BUFFER_BUDGET_BYTES;
|
|
97
140
|
server.setHandlers({
|
|
@@ -113,18 +156,89 @@ export class TunnelDispatcher {
|
|
|
113
156
|
p.signal.removeEventListener("abort", p.onAbort);
|
|
114
157
|
p.reservation?.release();
|
|
115
158
|
this.reassemblers.get(p.connectionId)?.abort({ kind: "rest-response", reqId });
|
|
116
|
-
// Remember recently-settled reqIds (bounded): a late response for an
|
|
159
|
+
// Remember recently-settled reqIds (bounded + TTL'd): a late response for an
|
|
117
160
|
// aborted/timed-out OWN request on the SAME connection is benign and must
|
|
118
161
|
// not kill the connection; foreign reqIds still do (below). Abandoned
|
|
119
|
-
// correlations get their own
|
|
162
|
+
// correlations get their own map so busy normal traffic cannot evict the
|
|
120
163
|
// correlation of a response that is still legitimately in flight.
|
|
121
164
|
const map = outcome === "abandoned" ? this.abandoned : this.settled;
|
|
122
|
-
|
|
123
|
-
|
|
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) {
|
|
124
189
|
const oldest = map.keys().next().value;
|
|
125
|
-
if (oldest
|
|
190
|
+
if (oldest === undefined) break;
|
|
191
|
+
map.delete(oldest);
|
|
192
|
+
this.rememberDropped(oldest, ts);
|
|
193
|
+
}
|
|
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);
|
|
126
228
|
}
|
|
127
|
-
|
|
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);
|
|
128
242
|
}
|
|
129
243
|
|
|
130
244
|
/**
|
|
@@ -159,14 +273,10 @@ export class TunnelDispatcher {
|
|
|
159
273
|
// Foreign or already-settled responses never resolve someone else's
|
|
160
274
|
// request; matching requires the SAME connection that owns the pending.
|
|
161
275
|
if (!p || p.connectionId !== conn.connectionId) {
|
|
162
|
-
// Late response for an OWN settled request
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
(this.settled.get(reqId) === conn.connectionId ||
|
|
167
|
-
this.abandoned.get(reqId) === conn.connectionId)
|
|
168
|
-
)
|
|
169
|
-
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;
|
|
170
280
|
if (p !== undefined && p.connectionId !== conn.connectionId) {
|
|
171
281
|
// A response claiming a reqId owned by ANOTHER connection: attack.
|
|
172
282
|
}
|
|
@@ -179,6 +289,10 @@ export class TunnelDispatcher {
|
|
|
179
289
|
status: frame.status as number,
|
|
180
290
|
contentType: frame.contentType as string | undefined,
|
|
181
291
|
body: frame.body,
|
|
292
|
+
...(frame.bodyEncoding === "base64" ? { bodyEncoding: "base64" as const } : {}),
|
|
293
|
+
...(frame.bodyEncoding === "base64"
|
|
294
|
+
? { contentDisposition: safeHeaderValue(frame.contentDisposition) }
|
|
295
|
+
: {}),
|
|
182
296
|
});
|
|
183
297
|
return;
|
|
184
298
|
}
|
|
@@ -187,12 +301,7 @@ export class TunnelDispatcher {
|
|
|
187
301
|
if (chunk.kind === "rest-response") {
|
|
188
302
|
const pending = this.pending.get(chunk.reqId);
|
|
189
303
|
// Match the plain-response grace before allocating any assembly.
|
|
190
|
-
if (
|
|
191
|
-
!pending &&
|
|
192
|
-
(this.settled.get(chunk.reqId) === conn.connectionId ||
|
|
193
|
-
this.abandoned.get(chunk.reqId) === conn.connectionId)
|
|
194
|
-
)
|
|
195
|
-
return;
|
|
304
|
+
if (!pending && this.lateFrameIsBenign(chunk.reqId, conn.connectionId)) return;
|
|
196
305
|
if (!pending || pending.connectionId !== conn.connectionId) {
|
|
197
306
|
this.denyDevice(
|
|
198
307
|
conn,
|
|
@@ -220,7 +329,13 @@ export class TunnelDispatcher {
|
|
|
220
329
|
// inside chunk data with no schema. A missing or non-numeric status is the device
|
|
221
330
|
// breaking contract: answer a bad gateway, never a silently defaulted 200.
|
|
222
331
|
const env = out.value as
|
|
223
|
-
| {
|
|
332
|
+
| {
|
|
333
|
+
status?: unknown;
|
|
334
|
+
contentType?: unknown;
|
|
335
|
+
body?: unknown;
|
|
336
|
+
bodyEncoding?: unknown;
|
|
337
|
+
contentDisposition?: unknown;
|
|
338
|
+
}
|
|
224
339
|
| undefined;
|
|
225
340
|
if (typeof env?.status !== "number" || !Number.isFinite(env.status)) {
|
|
226
341
|
p?.resolve({
|
|
@@ -235,6 +350,10 @@ export class TunnelDispatcher {
|
|
|
235
350
|
status: env.status,
|
|
236
351
|
contentType: typeof env.contentType === "string" ? env.contentType : undefined,
|
|
237
352
|
body: env.body,
|
|
353
|
+
...(env.bodyEncoding === "base64" ? { bodyEncoding: "base64" as const } : {}),
|
|
354
|
+
...(env.bodyEncoding === "base64"
|
|
355
|
+
? { contentDisposition: safeHeaderValue(env.contentDisposition) }
|
|
356
|
+
: {}),
|
|
238
357
|
rawBytes: out.rawBytes,
|
|
239
358
|
});
|
|
240
359
|
}
|
|
@@ -289,8 +408,9 @@ export class TunnelDispatcher {
|
|
|
289
408
|
|
|
290
409
|
/**
|
|
291
410
|
* The live subscription a device frame addresses, if this connection owns it. A frame for a
|
|
292
|
-
* subscription it just closed
|
|
293
|
-
*
|
|
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).
|
|
294
414
|
*/
|
|
295
415
|
private ownSubscription(
|
|
296
416
|
conn: TunnelConnection,
|
|
@@ -298,7 +418,9 @@ export class TunnelDispatcher {
|
|
|
298
418
|
): Subscription | undefined {
|
|
299
419
|
const sub = this.subs.get(subscriptionId);
|
|
300
420
|
if (sub && sub.connectionId === conn.connectionId) return sub;
|
|
301
|
-
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;
|
|
302
424
|
this.denyDevice(
|
|
303
425
|
conn,
|
|
304
426
|
"foreign_subscription",
|
|
@@ -309,11 +431,7 @@ export class TunnelDispatcher {
|
|
|
309
431
|
}
|
|
310
432
|
|
|
311
433
|
private rememberClosedSubscription(subscriptionId: string, connectionId: string): void {
|
|
312
|
-
this.closedSubs
|
|
313
|
-
if (this.closedSubs.size > 4_096) {
|
|
314
|
-
const oldest = this.closedSubs.keys().next().value;
|
|
315
|
-
if (oldest !== undefined) this.closedSubs.delete(oldest);
|
|
316
|
-
}
|
|
434
|
+
this.gracePut(this.closedSubs, subscriptionId, connectionId, CLOSED_SUBS_GRACE_CAP);
|
|
317
435
|
}
|
|
318
436
|
|
|
319
437
|
/**
|
|
@@ -377,6 +495,16 @@ export class TunnelDispatcher {
|
|
|
377
495
|
pendingCount(): number {
|
|
378
496
|
return this.pending.size;
|
|
379
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
|
+
}
|
|
380
508
|
subscriptionCount(deviceId?: string): number {
|
|
381
509
|
return deviceId === undefined
|
|
382
510
|
? this.subs.size
|
|
@@ -402,6 +530,25 @@ export class TunnelDispatcher {
|
|
|
402
530
|
new DpiError("invalid", `Request body exceeds ${REST_BODY_MAX_BYTES} bytes`, 413),
|
|
403
531
|
);
|
|
404
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"));
|
|
405
552
|
// Pending caps: 32/device, 256/hub (429 when full — no silent queueing).
|
|
406
553
|
let deviceSet = this.pendingByDevice.get(deviceId);
|
|
407
554
|
if (!deviceSet) {
|
|
@@ -446,7 +593,7 @@ export class TunnelDispatcher {
|
|
|
446
593
|
reqId,
|
|
447
594
|
method: input.method as "GET",
|
|
448
595
|
path: input.path,
|
|
449
|
-
...(
|
|
596
|
+
...(idempotencyKey ? { idempotencyKey } : {}),
|
|
450
597
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
451
598
|
});
|
|
452
599
|
if (!sent) {
|
|
@@ -52,6 +52,15 @@ const enc = encodeURIComponent;
|
|
|
52
52
|
const newId = (): string =>
|
|
53
53
|
globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
54
54
|
|
|
55
|
+
/** "My session #1" → "my-session-1" — mirrors the device's download slug (zip.ts). */
|
|
56
|
+
const slugName = (input: string): string =>
|
|
57
|
+
input
|
|
58
|
+
.normalize("NFKD")
|
|
59
|
+
.replace(/[^\w.-]+/g, "-")
|
|
60
|
+
.replace(/^-+|-+$/g, "")
|
|
61
|
+
.slice(0, 60)
|
|
62
|
+
.toLowerCase() || "session";
|
|
63
|
+
|
|
55
64
|
/**
|
|
56
65
|
* Typed client for one dpi-backend. Works in browsers and Node (fetch + streams).
|
|
57
66
|
* `token` is optional: the playground hub injects it, so browsers never hold one.
|
|
@@ -113,6 +122,20 @@ export type GitOpName =
|
|
|
113
122
|
| "pr-checks"
|
|
114
123
|
| "pr-comment";
|
|
115
124
|
|
|
125
|
+
/** One zipped session bundle, downloaded as raw bytes (R8 binary contract):
|
|
126
|
+
* the device streams plain `application/zip` bytes, so there is no base64
|
|
127
|
+
* hop. Hand `bytes` straight to `new Blob(...)` in the browser or to
|
|
128
|
+
* `fs.writeFile` in Node. */
|
|
129
|
+
export interface SessionExport {
|
|
130
|
+
/** The device's download name (`${slug}.bundle.zip`), from Content-Disposition
|
|
131
|
+
* — a slug of the session ref when the peer sends no usable header. */
|
|
132
|
+
filename: string;
|
|
133
|
+
/** The response's media type; `application/zip` from the device route. */
|
|
134
|
+
mime: string;
|
|
135
|
+
/** The zip payload, byte-for-byte as the device streamed it. */
|
|
136
|
+
bytes: Uint8Array;
|
|
137
|
+
}
|
|
138
|
+
|
|
116
139
|
/** Everything a git op may return; most carry only text. */
|
|
117
140
|
export interface GitOpResult {
|
|
118
141
|
text: string;
|
|
@@ -358,12 +381,56 @@ export class DpiClient {
|
|
|
358
381
|
return this.request<GitOpResult>("POST", "/v1/git", { path, op, ...opts });
|
|
359
382
|
}
|
|
360
383
|
/** Paths this session's agents wrote/edited — the session-changelist. */
|
|
361
|
-
/** One zipped bundle of a session (manifest + record + agent transcripts/configs)
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
384
|
+
/** One zipped bundle of a session (manifest + record + agent transcripts/configs),
|
|
385
|
+
* downloaded as RAW zip bytes since R8 — the route streams `application/zip` with
|
|
386
|
+
* Content-Length + Content-Disposition instead of the old base64 JSON envelope.
|
|
387
|
+
* Returns { filename, mime, bytes }: `filename` parsed from Content-Disposition
|
|
388
|
+
* (slug-of-ref fallback), `mime` from Content-Type, `bytes` the zip payload —
|
|
389
|
+
* Blob-able in the browser, fs.writeFile-able in Node. Refusal faults keep their
|
|
390
|
+
* JSON error bodies and throw the usual DpiError. Bundles can be large — pass a
|
|
391
|
+
* longer timeoutMs on slow links (default 60s). */
|
|
392
|
+
async exportSession(sessionId: string, options: RequestOptions = {}): Promise<SessionExport> {
|
|
393
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? 60_000);
|
|
394
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
395
|
+
let response: Response;
|
|
396
|
+
try {
|
|
397
|
+
response = await fetch(this.baseUrl + `/v1/sessions/${enc(sessionId)}/export`, {
|
|
398
|
+
headers: this.headers(false),
|
|
399
|
+
signal,
|
|
400
|
+
});
|
|
401
|
+
} catch (cause) {
|
|
402
|
+
if (options.signal?.aborted) throw cause;
|
|
403
|
+
throw new DpiError("offline", `Cannot reach ${this.baseUrl}`, 0, { cause });
|
|
404
|
+
}
|
|
405
|
+
if (!response.ok) {
|
|
406
|
+
// Refusals keep speaking JSON faults even on this binary route.
|
|
407
|
+
const text = await response.text().catch(() => "");
|
|
408
|
+
let data: { error?: { code?: ErrorCode; message?: string } } | undefined;
|
|
409
|
+
try {
|
|
410
|
+
data = text ? (JSON.parse(text) as typeof data) : undefined;
|
|
411
|
+
} catch {
|
|
412
|
+
data = undefined;
|
|
413
|
+
}
|
|
414
|
+
const code: ErrorCode =
|
|
415
|
+
data?.error?.code ??
|
|
416
|
+
(response.status === 401 ? "unauthorized" : response.status === 404 ? "not_found" : "internal");
|
|
417
|
+
throw new DpiError(
|
|
418
|
+
code,
|
|
419
|
+
data?.error?.message ?? `${response.status} ${response.statusText}`,
|
|
420
|
+
response.status,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
424
|
+
// `filename="quoted"` (the device's form) or a bare token, per RFC 6266.
|
|
425
|
+
const disposition = response.headers.get("content-disposition") ?? "";
|
|
426
|
+
const quoted = /filename="((?:[^"\\]|\\.)*)"/i.exec(disposition)?.[1];
|
|
427
|
+
const bare = /filename=([^;\s]+)/i.exec(disposition)?.[1];
|
|
428
|
+
const named = quoted !== undefined ? quoted.replace(/\\(.)/g, "$1") : bare;
|
|
429
|
+
return {
|
|
430
|
+
filename: named || `${slugName(sessionId)}.bundle.zip`,
|
|
431
|
+
mime: response.headers.get("content-type") ?? "application/zip",
|
|
432
|
+
bytes,
|
|
433
|
+
};
|
|
367
434
|
}
|
|
368
435
|
sessionGitFiles(sessionId: string) {
|
|
369
436
|
return this.request<{ files: string[] }>("GET", `/v1/sessions/${enc(sessionId)}/git-files`);
|
|
@@ -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,16 +215,24 @@ export const TunnelFrame = Type.Union([
|
|
|
215
215
|
},
|
|
216
216
|
Strict,
|
|
217
217
|
),
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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
|
+
}),
|
|
228
236
|
TunnelControl,
|
|
229
237
|
Type.Object(
|
|
230
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": {
|