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
|
@@ -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 = {
|
|
@@ -93,11 +93,25 @@ export function proxy(
|
|
|
93
93
|
res.status(status).set(LOCKED_DOWN_HEADERS);
|
|
94
94
|
if (!contentType || mediaType(contentType) === "application/json")
|
|
95
95
|
res.type("application/json").send(body);
|
|
96
|
-
else
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
96
|
+
else {
|
|
97
|
+
// R8 binary passthrough: base64-flagged device payloads are decoded byte-exact for
|
|
98
|
+
// EVERY type; the LABEL is controlled by the hub. Only application/zip (the export
|
|
99
|
+
// contract) keeps its type + the device's sanitized download filename — every other
|
|
100
|
+
// non-JSON type stays an inert octet-stream attachment (Gate A GA-01), so a hostile
|
|
101
|
+
// device cannot rebrand its bytes as html/svg/js at the ADMIN origin.
|
|
102
|
+
const payload =
|
|
103
|
+
upstream.bodyEncoding === "base64"
|
|
104
|
+
? Buffer.from(String(upstream.body ?? ""), "base64")
|
|
105
|
+
: Buffer.from(body, "utf8");
|
|
106
|
+
const isZip = mediaType(contentType) === "application/zip";
|
|
107
|
+
const disposition =
|
|
108
|
+
isZip && typeof upstream.contentDisposition === "string"
|
|
109
|
+
? upstream.contentDisposition
|
|
110
|
+
: 'attachment; filename="device-response.bin"';
|
|
111
|
+
res.type(isZip ? contentType : "application/octet-stream")
|
|
112
|
+
.set("Content-Disposition", disposition)
|
|
113
|
+
.send(payload);
|
|
114
|
+
}
|
|
101
115
|
} catch (e) {
|
|
102
116
|
if (closed.signal.aborted) return;
|
|
103
117
|
// Status-carrying tunnel outcomes keep their semantics: 413 too-large,
|
|
@@ -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,
|
|
@@ -21,8 +21,14 @@ export interface TransportRequest {
|
|
|
21
21
|
export interface TransportResponse {
|
|
22
22
|
status: number;
|
|
23
23
|
contentType?: string;
|
|
24
|
-
/** Raw text for proxy passthrough, parsed JSON where the caller knows the shape.
|
|
24
|
+
/** Raw text for proxy passthrough, parsed JSON where the caller knows the shape.
|
|
25
|
+
* When bodyEncoding is "base64" this is the base64 of the device's raw bytes. */
|
|
25
26
|
body?: unknown;
|
|
27
|
+
/** Present ("base64") only for non-textual device responses (R8 binary passthrough):
|
|
28
|
+
* absent means body is plain UTF-8 text as before. */
|
|
29
|
+
bodyEncoding?: "base64";
|
|
30
|
+
/** Sanitized Content-Disposition from the device (binary responses); may be undefined. */
|
|
31
|
+
contentDisposition?: string;
|
|
26
32
|
/** Diagnostics: assembled byte count for chunked responses. */
|
|
27
33
|
rawBytes?: number;
|
|
28
34
|
}
|
|
@@ -37,6 +43,15 @@ export interface DeviceTransport {
|
|
|
37
43
|
|
|
38
44
|
const REST_TIMEOUT_MS = 330_000;
|
|
39
45
|
|
|
46
|
+
/** Wire-textual content types — matches the device-side classifier in dpi-backend/tunnel.ts. */
|
|
47
|
+
const TEXTUAL_CT_RE = /^(?:text\/|application\/(?:json|javascript|xml|x-www-form-urlencoded)(?:;|$))/i;
|
|
48
|
+
/** Device headers are untrusted at the ADMIN origin: printable ASCII only, bounded length. */
|
|
49
|
+
const safeHeaderValue = (value: string | null | undefined): string | undefined => {
|
|
50
|
+
if (!value) return undefined;
|
|
51
|
+
const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
|
|
52
|
+
return clean.length > 0 ? clean : undefined;
|
|
53
|
+
};
|
|
54
|
+
|
|
40
55
|
/** Direct LAN device: full token injection, exactly today's behavior. */
|
|
41
56
|
export class LanTransport implements DeviceTransport {
|
|
42
57
|
readonly kind = "lan" as const;
|
|
@@ -77,11 +92,17 @@ export class LanTransport implements DeviceTransport {
|
|
|
77
92
|
if (signal?.aborted) throw cause;
|
|
78
93
|
throw new DpiError("offline", `Cannot reach ${this.client.baseUrl}`, 0, { cause });
|
|
79
94
|
}
|
|
80
|
-
const
|
|
95
|
+
const raw = Buffer.from(await response.arrayBuffer());
|
|
96
|
+
const ct = response.headers.get("content-type") ?? undefined;
|
|
97
|
+
// Textual responses keep the legacy plain-string shape; binaries are base64-flagged
|
|
98
|
+
// so the proxy can serve bytes byte-exact (R8 binary passthrough).
|
|
99
|
+
const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
|
|
81
100
|
return {
|
|
82
101
|
status: response.status,
|
|
83
|
-
contentType:
|
|
84
|
-
body:
|
|
102
|
+
contentType: ct,
|
|
103
|
+
body: textual ? raw.toString("utf8") : raw.toString("base64"),
|
|
104
|
+
...(textual ? {} : { bodyEncoding: "base64" as const }),
|
|
105
|
+
...(textual ? {} : { contentDisposition: safeHeaderValue(response.headers.get("content-disposition")) }),
|
|
85
106
|
};
|
|
86
107
|
}
|
|
87
108
|
|