@bom-pi/core 0.1.2 → 0.1.4
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/package.json +20 -19
- package/src/cloud-connector.ts +190 -5
- package/src/cloud-wss-transport.ts +309 -4
- package/src/device-ceremony.ts +232 -8
- package/src/pairing-storage.ts +233 -21
- package/src/relay-boundary.ts +499 -0
- package/src/secure-transport.ts +116 -11
- package/src/session-gateway.ts +151 -13
package/src/device-ceremony.ts
CHANGED
|
@@ -1848,6 +1848,15 @@ export class DevicePairBroker {
|
|
|
1848
1848
|
fail(503, "No independent owner signer is pinned for this target");
|
|
1849
1849
|
}
|
|
1850
1850
|
|
|
1851
|
+
// R2: the decision re-checks the target's LIVE membership against the create-time
|
|
1852
|
+
// binding in the offer. A rotation (new id/epoch) or removal between request-create
|
|
1853
|
+
// and decide leaves that binding stale — refuse before any receipt is signed.
|
|
1854
|
+
const liveTarget = await this.env.members.membership(record.offer.targetFp);
|
|
1855
|
+
|
|
1856
|
+
if (liveTarget === null || !equalRef(liveTarget.ref, record.offer.targetMembership)) {
|
|
1857
|
+
fail(503, "Target membership changed since the request was created");
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1851
1860
|
const subjectMembership = memberRef(
|
|
1852
1861
|
record.request.envelope.subjectMembership,
|
|
1853
1862
|
"subjectMembership",
|
|
@@ -2322,18 +2331,22 @@ export class DevicePairBroker {
|
|
|
2322
2331
|
});
|
|
2323
2332
|
}
|
|
2324
2333
|
|
|
2325
|
-
/** P7 MINOR-3: drop
|
|
2326
|
-
*
|
|
2334
|
+
/** P7 MINOR-3 + M4 R3: drop records past the bounded replay window. §3 forbids permanent
|
|
2335
|
+
* pair history; expired/decided records carry signed requester material. Terminal and
|
|
2336
|
+
* expired-undecided records age out past pendingExpiresAt + 24h; a provisional crash
|
|
2337
|
+
* leftover that outlived its §7 transaction deadline by the same window goes too. Records
|
|
2338
|
+
* still inside the window always stay (replay semantics). */
|
|
2327
2339
|
private async purgeTerminalRecords(now: number): Promise<void> {
|
|
2328
2340
|
const before = this.state.requests.length;
|
|
2329
2341
|
|
|
2330
2342
|
this.state.requests = this.state.requests.filter(
|
|
2331
2343
|
(record) =>
|
|
2332
2344
|
!(
|
|
2333
|
-
record.state
|
|
2334
|
-
|
|
2335
|
-
record.
|
|
2336
|
-
|
|
2345
|
+
(record.state === "provisional" &&
|
|
2346
|
+
now >= record.transactionDeadline + TERMINAL_RETENTION_SECONDS) ||
|
|
2347
|
+
(record.state !== "provisional" &&
|
|
2348
|
+
record.pendingExpiresAt !== null &&
|
|
2349
|
+
now >= record.pendingExpiresAt + TERMINAL_RETENTION_SECONDS)
|
|
2337
2350
|
),
|
|
2338
2351
|
);
|
|
2339
2352
|
|
|
@@ -2482,6 +2495,18 @@ export type LedgerCleanup = {
|
|
|
2482
2495
|
requestNonce: string;
|
|
2483
2496
|
};
|
|
2484
2497
|
|
|
2498
|
+
/** P7 MINOR-4 (§13): crash-window intent — the exact signed decision bytes, durably recorded
|
|
2499
|
+
* BEFORE they are sent to X and kept until the local decided commit lands. Secret-free: the
|
|
2500
|
+
* bytes are the owner-signed public certificate X itself retains for its replay lane. */
|
|
2501
|
+
export type LedgerDecisionIntent = {
|
|
2502
|
+
requestId: string;
|
|
2503
|
+
revision: number;
|
|
2504
|
+
decision: "approve" | "deny";
|
|
2505
|
+
/** Canonical JSON of the signed §13 envelope; identical bytes re-hit X's replay lane. */
|
|
2506
|
+
bytes: string;
|
|
2507
|
+
sentAt: number;
|
|
2508
|
+
};
|
|
2509
|
+
|
|
2485
2510
|
export type LedgerSnapshot = {
|
|
2486
2511
|
version: 1;
|
|
2487
2512
|
revision: number;
|
|
@@ -2491,6 +2516,7 @@ export type LedgerSnapshot = {
|
|
|
2491
2516
|
grants: LedgerGrant[];
|
|
2492
2517
|
cleanups: LedgerCleanup[];
|
|
2493
2518
|
pending: PendingDisplayRecord[];
|
|
2519
|
+
decisionIntents: LedgerDecisionIntent[];
|
|
2494
2520
|
};
|
|
2495
2521
|
|
|
2496
2522
|
export type PendingDisplayRecord = {
|
|
@@ -2556,6 +2582,11 @@ export interface LedgerEnvironment {
|
|
|
2556
2582
|
fetchFinalReceipt(requestId: string): Promise<string>;
|
|
2557
2583
|
/** Delivers an owner-signed decision envelope; returns X's nonsecret receipt. */
|
|
2558
2584
|
sendDecision(bytes: Uint8Array): Promise<{ receipt: string }>;
|
|
2585
|
+
/** P7 MINOR-4: X's live §6 view of a request (state only is consumed); optional — the
|
|
2586
|
+
* decision reconcile skips gracefully when the surface is absent (test rigs). */
|
|
2587
|
+
requestStatus?(
|
|
2588
|
+
requestId: string,
|
|
2589
|
+
): Promise<{ view: { [key: string]: CanonicalValue }; challengeReceipt: string | null }>;
|
|
2559
2590
|
/** Delivers a termination notice; returns X's signed deleted/already-absent ACK. */
|
|
2560
2591
|
sendTermination(bytes: Uint8Array): Promise<string>;
|
|
2561
2592
|
}
|
|
@@ -2569,12 +2600,17 @@ export const emptyLedgerSnapshot = (): LedgerSnapshot => ({
|
|
|
2569
2600
|
grants: [],
|
|
2570
2601
|
cleanups: [],
|
|
2571
2602
|
pending: [],
|
|
2603
|
+
decisionIntents: [],
|
|
2572
2604
|
});
|
|
2573
2605
|
|
|
2574
2606
|
export class PairingLedger {
|
|
2575
2607
|
private state: LedgerSnapshot = emptyLedgerSnapshot();
|
|
2576
2608
|
private sealed = false;
|
|
2577
2609
|
private queue: Promise<unknown> = Promise.resolve();
|
|
2610
|
+
/** P7 MINOR-4: the intent set as of the last SUCCESSFUL durable write. Rollbacks restore
|
|
2611
|
+
* it so a committed intent always survives a failed operation (memory never diverges
|
|
2612
|
+
* from disk about which crash-window intents exist). */
|
|
2613
|
+
private committedIntents: LedgerDecisionIntent[] = [];
|
|
2578
2614
|
|
|
2579
2615
|
private readonly env: LedgerEnvironment;
|
|
2580
2616
|
private readonly store: LedgerStore;
|
|
@@ -2601,6 +2637,14 @@ export class PairingLedger {
|
|
|
2601
2637
|
}
|
|
2602
2638
|
|
|
2603
2639
|
ledger.state = structuredClone(snapshot);
|
|
2640
|
+
|
|
2641
|
+
// Snapshots written before P7 MINOR-4 carry no decision intents: normalize the
|
|
2642
|
+
// missing field instead of failing, then seed the rollback mirror from disk.
|
|
2643
|
+
if (!Array.isArray(ledger.state.decisionIntents)) {
|
|
2644
|
+
ledger.state.decisionIntents = [];
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
ledger.committedIntents = structuredClone(ledger.state.decisionIntents);
|
|
2604
2648
|
}
|
|
2605
2649
|
|
|
2606
2650
|
return ledger;
|
|
@@ -2618,6 +2662,9 @@ export class PairingLedger {
|
|
|
2618
2662
|
try {
|
|
2619
2663
|
await this.store.write(next);
|
|
2620
2664
|
this.state = next;
|
|
2665
|
+
// The rollback mirror only ever advances on a SUCCESSFUL write: memory and disk
|
|
2666
|
+
// never disagree about which decision intents exist (P7 MINOR-4).
|
|
2667
|
+
this.committedIntents = structuredClone(next.decisionIntents);
|
|
2621
2668
|
} catch (error) {
|
|
2622
2669
|
this.sealed = true;
|
|
2623
2670
|
|
|
@@ -2636,6 +2683,12 @@ export class PairingLedger {
|
|
|
2636
2683
|
} catch (error) {
|
|
2637
2684
|
this.state = before;
|
|
2638
2685
|
|
|
2686
|
+
// P7 MINOR-4: a decision intent is a deliberate out-of-band sentinel — one
|
|
2687
|
+
// already durably committed inside this failed operation must SURVIVE the
|
|
2688
|
+
// rollback (memory stays equal to disk), or the next unrelated commit would
|
|
2689
|
+
// erase the crash-window evidence and resurrect the 409 wedge on restart.
|
|
2690
|
+
this.state.decisionIntents = structuredClone(this.committedIntents);
|
|
2691
|
+
|
|
2639
2692
|
throw error;
|
|
2640
2693
|
}
|
|
2641
2694
|
});
|
|
@@ -3250,6 +3303,22 @@ export class PairingLedger {
|
|
|
3250
3303
|
});
|
|
3251
3304
|
const signed = await signDecision(input.signer, decision);
|
|
3252
3305
|
const bytes = canonicalJson(signed as unknown as CanonicalValue);
|
|
3306
|
+
|
|
3307
|
+
// P7 MINOR-4 (§13): the exact signed bytes are durable BEFORE they leave A — a
|
|
3308
|
+
// crash after X processed the decision but before the local commit leaves an
|
|
3309
|
+
// intent that reconcileDecisions() replays through X's identical-bytes lane.
|
|
3310
|
+
this.state.decisionIntents = this.state.decisionIntents.filter(
|
|
3311
|
+
(entry) => entry.requestId !== record.requestId,
|
|
3312
|
+
);
|
|
3313
|
+
this.state.decisionIntents.push({
|
|
3314
|
+
requestId: record.requestId,
|
|
3315
|
+
revision: record.revision,
|
|
3316
|
+
decision: input.decision,
|
|
3317
|
+
bytes: Buffer.from(bytes).toString("utf8"),
|
|
3318
|
+
sentAt: now,
|
|
3319
|
+
});
|
|
3320
|
+
await this.commit();
|
|
3321
|
+
|
|
3253
3322
|
const { receipt } = await this.env.sendDecision(bytes);
|
|
3254
3323
|
|
|
3255
3324
|
// P7 MINOR-4 (§7): A never marks its own record decided on an UNVERIFIED word from
|
|
@@ -3267,18 +3336,173 @@ export class PairingLedger {
|
|
|
3267
3336
|
fail(503, "X decision receipt does not verify; the request stays undecided");
|
|
3268
3337
|
}
|
|
3269
3338
|
|
|
3270
|
-
record
|
|
3339
|
+
// The intent commit advanced the snapshot generation: `record` aliases the stale
|
|
3340
|
+
// clone now, so the decided commit must re-bind the LIVE record (P7 MINOR-4).
|
|
3341
|
+
const current = this.state.pending.find(
|
|
3342
|
+
(entry) => entry.requestId === record.requestId,
|
|
3343
|
+
);
|
|
3344
|
+
|
|
3345
|
+
if (current === undefined) {
|
|
3346
|
+
fail(503, "The decided request vanished mid-decision; the intent stays replayable");
|
|
3347
|
+
}
|
|
3348
|
+
|
|
3349
|
+
current.decided = {
|
|
3271
3350
|
decision: input.decision,
|
|
3272
3351
|
approvedExpiry: input.approvedExpiry,
|
|
3273
3352
|
certificateHash: sha256Hex(bytes),
|
|
3274
3353
|
};
|
|
3275
|
-
|
|
3354
|
+
current.lastSyncedAt = now;
|
|
3355
|
+
this.state.decisionIntents = this.state.decisionIntents.filter(
|
|
3356
|
+
(entry) => entry.requestId !== record.requestId,
|
|
3357
|
+
);
|
|
3276
3358
|
await this.commit();
|
|
3277
3359
|
|
|
3278
3360
|
return { receipt };
|
|
3279
3361
|
});
|
|
3280
3362
|
}
|
|
3281
3363
|
|
|
3364
|
+
/* --------- P7 MINOR-4: crash-window decision reconcile on boot/reconnect --------- */
|
|
3365
|
+
|
|
3366
|
+
/** P7 MINOR-4 (§7/§13): reconciliation for decisions caught in the send↔commit crash
|
|
3367
|
+
* window. For every sent-but-uncommitted decision intent, X's live request state decides
|
|
3368
|
+
* the outcome: a TERMINAL state matching the intent is committed locally by replaying
|
|
3369
|
+
* the intent's exact signed bytes through X's identical-bytes lane and verifying the
|
|
3370
|
+
* returned receipt against the pinned X key (A never acts on an unverified word); X
|
|
3371
|
+
* undecided or absent stays RESUMABLE — the record remains undecided, so the owner may
|
|
3372
|
+
* simply re-decide and no fresh-envelope 409 wedge can arise. Read-only except for the
|
|
3373
|
+
* single local commit it performs; every transport error is a skip, never a throw, so a
|
|
3374
|
+
* boot or reconnect can never fail on reconcile. */
|
|
3375
|
+
async reconcileDecisions(): Promise<{
|
|
3376
|
+
committed: string[];
|
|
3377
|
+
resumable: { requestId: string; reason: string }[];
|
|
3378
|
+
}> {
|
|
3379
|
+
const committed: string[] = [];
|
|
3380
|
+
const resumable: { requestId: string; reason: string }[] = [];
|
|
3381
|
+
|
|
3382
|
+
for (const intent of [...this.state.decisionIntents]) {
|
|
3383
|
+
const record = this.state.pending.find((entry) => entry.requestId === intent.requestId);
|
|
3384
|
+
|
|
3385
|
+
if (record === undefined) {
|
|
3386
|
+
if (this.env.now() - intent.sentAt >= TERMINAL_RETENTION_SECONDS) {
|
|
3387
|
+
// M4 R5 residue: an orphan intent whose local record never came back
|
|
3388
|
+
// within the retention window is dropped — the residue cannot grow
|
|
3389
|
+
// unbounded and reconcile noise stays bounded (fail-closed: replay of
|
|
3390
|
+
// dropped bytes still only ever hits X's identical-bytes lane).
|
|
3391
|
+
this.state.decisionIntents = this.state.decisionIntents.filter(
|
|
3392
|
+
(entry) => entry.requestId !== intent.requestId,
|
|
3393
|
+
);
|
|
3394
|
+
await this.commit();
|
|
3395
|
+
} else {
|
|
3396
|
+
resumable.push({ requestId: intent.requestId, reason: "no local record" });
|
|
3397
|
+
}
|
|
3398
|
+
|
|
3399
|
+
continue;
|
|
3400
|
+
}
|
|
3401
|
+
|
|
3402
|
+
if (record.decided !== null) {
|
|
3403
|
+
// The decided commit consumes its intent in the same snapshot; a survivor is
|
|
3404
|
+
// a stale leftover — drop it so it cannot shadow a later decision.
|
|
3405
|
+
this.state.decisionIntents = this.state.decisionIntents.filter(
|
|
3406
|
+
(entry) => entry.requestId !== intent.requestId,
|
|
3407
|
+
);
|
|
3408
|
+
await this.commit();
|
|
3409
|
+
|
|
3410
|
+
continue;
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
let state: string | null = null;
|
|
3414
|
+
|
|
3415
|
+
try {
|
|
3416
|
+
const status = await this.env.requestStatus?.(intent.requestId);
|
|
3417
|
+
|
|
3418
|
+
state =
|
|
3419
|
+
status === undefined || typeof status.view.state !== "string"
|
|
3420
|
+
? null
|
|
3421
|
+
: status.view.state;
|
|
3422
|
+
} catch {
|
|
3423
|
+
resumable.push({ requestId: intent.requestId, reason: "X status unavailable" });
|
|
3424
|
+
|
|
3425
|
+
continue;
|
|
3426
|
+
}
|
|
3427
|
+
|
|
3428
|
+
const terminal = state === "approved" ? "approve" : state === "denied" ? "deny" : null;
|
|
3429
|
+
|
|
3430
|
+
if (terminal === null) {
|
|
3431
|
+
resumable.push({
|
|
3432
|
+
requestId: intent.requestId,
|
|
3433
|
+
reason: state === null ? "status unavailable" : `X still ${state}`,
|
|
3434
|
+
});
|
|
3435
|
+
|
|
3436
|
+
continue;
|
|
3437
|
+
}
|
|
3438
|
+
|
|
3439
|
+
if (terminal !== intent.decision) {
|
|
3440
|
+
resumable.push({
|
|
3441
|
+
requestId: intent.requestId,
|
|
3442
|
+
reason: `X is ${state} but the local intent is ${intent.decision}`,
|
|
3443
|
+
});
|
|
3444
|
+
|
|
3445
|
+
continue;
|
|
3446
|
+
}
|
|
3447
|
+
|
|
3448
|
+
try {
|
|
3449
|
+
// Identical bytes re-hit X's replay lane and return the ORIGINAL receipt; the
|
|
3450
|
+
// utf8 round-trip is exact (canonical JSON), so the certificate hash matches
|
|
3451
|
+
// the one decide() itself would have committed.
|
|
3452
|
+
const replay = Buffer.from(intent.bytes, "utf8");
|
|
3453
|
+
const { receipt } = await this.env.sendDecision(replay);
|
|
3454
|
+
const verified = await this.env.verifyCloudReceipt(receipt);
|
|
3455
|
+
|
|
3456
|
+
if (
|
|
3457
|
+
verified === null ||
|
|
3458
|
+
verified.kind !== "pair-decision" ||
|
|
3459
|
+
verified.requestId !== intent.requestId ||
|
|
3460
|
+
verified.revision !== intent.revision ||
|
|
3461
|
+
verified.decision !== intent.decision
|
|
3462
|
+
) {
|
|
3463
|
+
resumable.push({
|
|
3464
|
+
requestId: intent.requestId,
|
|
3465
|
+
reason: "X receipt did not verify against the intent",
|
|
3466
|
+
});
|
|
3467
|
+
|
|
3468
|
+
continue;
|
|
3469
|
+
}
|
|
3470
|
+
|
|
3471
|
+
const approvedExpiry =
|
|
3472
|
+
intent.decision === "approve"
|
|
3473
|
+
? integer(verified.approvedExpiry, "approvedExpiry", true)
|
|
3474
|
+
: null;
|
|
3475
|
+
|
|
3476
|
+
await this.mutate(async () => {
|
|
3477
|
+
const current = this.state.pending.find(
|
|
3478
|
+
(entry) => entry.requestId === intent.requestId,
|
|
3479
|
+
);
|
|
3480
|
+
|
|
3481
|
+
if (current === undefined || current.decided !== null) {
|
|
3482
|
+
return; // raced with another writer; the durable truth already moved
|
|
3483
|
+
}
|
|
3484
|
+
|
|
3485
|
+
current.decided = {
|
|
3486
|
+
decision: intent.decision,
|
|
3487
|
+
approvedExpiry,
|
|
3488
|
+
certificateHash: sha256Hex(replay),
|
|
3489
|
+
};
|
|
3490
|
+
current.lastSyncedAt = this.env.now();
|
|
3491
|
+
this.state.decisionIntents = this.state.decisionIntents.filter(
|
|
3492
|
+
(entry) => entry.requestId !== intent.requestId,
|
|
3493
|
+
);
|
|
3494
|
+
await this.commit();
|
|
3495
|
+
});
|
|
3496
|
+
|
|
3497
|
+
committed.push(intent.requestId);
|
|
3498
|
+
} catch {
|
|
3499
|
+
resumable.push({ requestId: intent.requestId, reason: "replay send failed" });
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
|
|
3503
|
+
return { committed, resumable };
|
|
3504
|
+
}
|
|
3505
|
+
|
|
3282
3506
|
/* --------------- §4.2/§14 issuance lane: sealed relation pickup --------------- */
|
|
3283
3507
|
|
|
3284
3508
|
/** §7/§14: verifies B's signed X25519 pickup request against the APPROVED §13 decision and
|
package/src/pairing-storage.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
/** Offline pairing storage exercise. This module is not an authorization or restore mechanism.
|
|
1
|
+
/** Offline pairing storage exercise. This module is not an authorization or restore mechanism.
|
|
2
|
+
* It also hosts the owner's M4 relay activation record: a durable off-by-default switch with the
|
|
3
|
+
* same single-writer, atomic, fail-closed discipline as the pairing record itself. */
|
|
2
4
|
import { randomUUID } from "node:crypto";
|
|
3
5
|
import { lstat, mkdir, open, readFile, rename, unlink, type FileHandle } from "node:fs/promises";
|
|
4
6
|
import { join } from "node:path";
|
|
5
7
|
|
|
6
8
|
const FILE = "pairing-storage.json";
|
|
7
9
|
const LOCK = ".pairing-storage.lock";
|
|
10
|
+
const RELAY_FILE = "relay-switch.json";
|
|
11
|
+
const RELAY_LOCK = ".relay-switch.lock";
|
|
8
12
|
const HEX_ID = /^[a-f0-9]{64}$/;
|
|
9
13
|
|
|
10
14
|
type LockLease = { handle: FileHandle; identity: string };
|
|
@@ -94,11 +98,11 @@ async function syncDirectory(directory: string): Promise<void> {
|
|
|
94
98
|
}
|
|
95
99
|
}
|
|
96
100
|
|
|
97
|
-
async function acquireLock(directory: string): Promise<LockLease> {
|
|
101
|
+
async function acquireLock(directory: string, lockFile: string): Promise<LockLease> {
|
|
98
102
|
let handle: FileHandle;
|
|
99
103
|
|
|
100
104
|
try {
|
|
101
|
-
handle = await open(join(directory,
|
|
105
|
+
handle = await open(join(directory, lockFile), "wx", 0o600);
|
|
102
106
|
} catch (error) {
|
|
103
107
|
if ((error as NodeJS.ErrnoException).code === "EEXIST") {
|
|
104
108
|
fail("writer lock exists; explicit recovery required");
|
|
@@ -123,10 +127,10 @@ async function acquireLock(directory: string): Promise<LockLease> {
|
|
|
123
127
|
}
|
|
124
128
|
}
|
|
125
129
|
|
|
126
|
-
async function assertLock(directory: string, lock: LockLease): Promise<void> {
|
|
130
|
+
async function assertLock(directory: string, lockFile: string, lock: LockLease): Promise<void> {
|
|
127
131
|
try {
|
|
128
132
|
const owned = await lock.handle.stat();
|
|
129
|
-
const present = await lstat(join(directory,
|
|
133
|
+
const present = await lstat(join(directory, lockFile));
|
|
130
134
|
|
|
131
135
|
if (
|
|
132
136
|
!owned.isFile() ||
|
|
@@ -137,7 +141,7 @@ async function assertLock(directory: string, lock: LockLease): Promise<void> {
|
|
|
137
141
|
owned.nlink !== 1 ||
|
|
138
142
|
present.nlink !== 1 ||
|
|
139
143
|
(process.getuid !== undefined && present.uid !== process.getuid()) ||
|
|
140
|
-
(await readFile(join(directory,
|
|
144
|
+
(await readFile(join(directory, lockFile), "utf8")) !== lock.identity
|
|
141
145
|
) {
|
|
142
146
|
fail("writer lock changed; explicit recovery required");
|
|
143
147
|
}
|
|
@@ -146,16 +150,224 @@ async function assertLock(directory: string, lock: LockLease): Promise<void> {
|
|
|
146
150
|
}
|
|
147
151
|
}
|
|
148
152
|
|
|
149
|
-
async function releaseLock(directory: string, lock: LockLease): Promise<void> {
|
|
153
|
+
async function releaseLock(directory: string, lockFile: string, lock: LockLease): Promise<void> {
|
|
150
154
|
try {
|
|
151
|
-
await assertLock(directory, lock);
|
|
152
|
-
await unlink(join(directory,
|
|
155
|
+
await assertLock(directory, lockFile, lock);
|
|
156
|
+
await unlink(join(directory, lockFile));
|
|
153
157
|
await syncDirectory(directory);
|
|
154
158
|
} finally {
|
|
155
159
|
await lock.handle.close();
|
|
156
160
|
}
|
|
157
161
|
}
|
|
158
162
|
|
|
163
|
+
// ------------------------- M4 relay owner switch (§11/§16) -------------------------
|
|
164
|
+
|
|
165
|
+
/** The owner's explicit, durable M4 relay activation snapshot: only ever this record. There is
|
|
166
|
+
* deliberately no environment-variable or memory-only activation path, and the record carries no
|
|
167
|
+
* grant data — the GRANT switch is a separate, not-yet-implemented surface. */
|
|
168
|
+
export type RelaySwitchSnapshot = { version: 1; relay: { enabled: boolean } };
|
|
169
|
+
|
|
170
|
+
/** The switch-read seam relay lanes consume: a plain synchronous read of the durable record.
|
|
171
|
+
* Implementations must fail closed — anything other than a healthy, open record reads OFF. */
|
|
172
|
+
export type RelaySwitchRead = () => boolean;
|
|
173
|
+
|
|
174
|
+
function parseRelaySwitch(text: string): RelaySwitchSnapshot {
|
|
175
|
+
let value: unknown;
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
value = JSON.parse(text);
|
|
179
|
+
} catch {
|
|
180
|
+
return fail("corrupt relay switch record");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const relay =
|
|
184
|
+
value !== null &&
|
|
185
|
+
typeof value === "object" &&
|
|
186
|
+
keys(value, ["version", "relay"]) &&
|
|
187
|
+
(value as RelaySwitchSnapshot).version === 1
|
|
188
|
+
? (value as RelaySwitchSnapshot).relay
|
|
189
|
+
: null;
|
|
190
|
+
|
|
191
|
+
if (
|
|
192
|
+
relay === null ||
|
|
193
|
+
typeof relay !== "object" ||
|
|
194
|
+
!keys(relay, ["enabled"]) ||
|
|
195
|
+
typeof relay.enabled !== "boolean" ||
|
|
196
|
+
JSON.stringify(value) !== text
|
|
197
|
+
) {
|
|
198
|
+
return fail("corrupt or unsupported relay switch record");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return value as RelaySwitchSnapshot;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** One writer only; caller supplies an isolated directory. The switch is off-by-default, reads
|
|
205
|
+
* OFF when closed or uncertain, and never authorizes anything by being read. */
|
|
206
|
+
export class RelaySwitchStore {
|
|
207
|
+
private closed = false;
|
|
208
|
+
private writing = false;
|
|
209
|
+
private readonly lock: LockLease;
|
|
210
|
+
private readonly directory: string;
|
|
211
|
+
private record: RelaySwitchSnapshot;
|
|
212
|
+
|
|
213
|
+
private constructor(directory: string, record: RelaySwitchSnapshot, lock: LockLease) {
|
|
214
|
+
this.directory = directory;
|
|
215
|
+
this.record = record;
|
|
216
|
+
this.lock = lock;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
static async create(directory: string): Promise<RelaySwitchStore> {
|
|
220
|
+
await mkdir(directory, { mode: 0o700 });
|
|
221
|
+
await checkDirectory(directory);
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
await lstat(join(directory, RELAY_FILE));
|
|
225
|
+
fail("relay switch record already exists; cannot initialize over prior state");
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const lock = await acquireLock(directory, RELAY_LOCK);
|
|
233
|
+
const store = new RelaySwitchStore(
|
|
234
|
+
directory,
|
|
235
|
+
{ version: 1, relay: { enabled: false } },
|
|
236
|
+
lock,
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
await store.persist(store.record);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
// Failed initialization is not safe to retry as a fresh store.
|
|
243
|
+
await lock.handle.close();
|
|
244
|
+
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return store;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
static async open(directory: string): Promise<RelaySwitchStore> {
|
|
252
|
+
await checkDirectory(directory);
|
|
253
|
+
const lock = await acquireLock(directory, RELAY_LOCK);
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
const file = join(directory, RELAY_FILE);
|
|
257
|
+
const stat = await lstat(file).catch(() =>
|
|
258
|
+
fail("missing or unreadable relay switch record"),
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) {
|
|
262
|
+
fail("relay switch record must be a private (0600) regular file");
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Parity with the pairing record: a re-owned record is never adopted.
|
|
266
|
+
if (process.getuid !== undefined && stat.uid !== process.getuid()) {
|
|
267
|
+
fail("relay switch record must be owned by the current user");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const record = parseRelaySwitch(
|
|
271
|
+
await readFile(file, "utf8").catch(() => fail("unreadable relay switch record")),
|
|
272
|
+
);
|
|
273
|
+
|
|
274
|
+
return new RelaySwitchStore(directory, record, lock);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
await releaseLock(directory, RELAY_LOCK, lock);
|
|
277
|
+
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Release only this instance's lock; parity with PairingStorage.close. */
|
|
283
|
+
async close(): Promise<void> {
|
|
284
|
+
if (this.writing) {
|
|
285
|
+
fail("concurrent writer rejected");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (this.closed) {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
this.closed = true;
|
|
293
|
+
await releaseLock(this.directory, RELAY_LOCK, this.lock);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The RelaySwitchRead seam: OFF unless the durable record of a healthy, open store says
|
|
297
|
+
* otherwise; a closed instance (clean stop or uncertain write) reads OFF again. */
|
|
298
|
+
enabled(): boolean {
|
|
299
|
+
return !this.closed && this.record.relay.enabled;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Secret-free record inspection. */
|
|
303
|
+
inspect(): RelaySwitchSnapshot {
|
|
304
|
+
return structuredClone(this.record);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Durably flips the switch: single-writer, atomic, fsync'd like every commit here. A failed
|
|
308
|
+
* write closes the instance — reads fail closed to OFF until an explicit restart recovery. */
|
|
309
|
+
async set(enabled: boolean): Promise<void> {
|
|
310
|
+
if (typeof enabled !== "boolean") {
|
|
311
|
+
fail("relay switch needs a boolean");
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (this.closed) {
|
|
315
|
+
fail("closed or uncertain relay switch store; restart recovery required");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (this.writing) {
|
|
319
|
+
fail("concurrent writer rejected");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (this.record.relay.enabled === enabled) {
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const next: RelaySwitchSnapshot = { version: 1, relay: { enabled } };
|
|
327
|
+
|
|
328
|
+
this.writing = true;
|
|
329
|
+
|
|
330
|
+
try {
|
|
331
|
+
await this.persist(next);
|
|
332
|
+
this.record = next;
|
|
333
|
+
} catch (error) {
|
|
334
|
+
// Rename may have succeeded while the directory fsync did not: never claim state.
|
|
335
|
+
this.closed = true;
|
|
336
|
+
await this.lock.handle.close();
|
|
337
|
+
|
|
338
|
+
throw error;
|
|
339
|
+
} finally {
|
|
340
|
+
this.writing = false;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
private async persist(next: RelaySwitchSnapshot): Promise<void> {
|
|
345
|
+
const temp = join(this.directory, `.${RELAY_FILE}.${randomUUID()}.tmp`);
|
|
346
|
+
let handle: FileHandle | undefined;
|
|
347
|
+
|
|
348
|
+
try {
|
|
349
|
+
await assertLock(this.directory, RELAY_LOCK, this.lock);
|
|
350
|
+
handle = await open(temp, "wx", 0o600);
|
|
351
|
+
await handle.writeFile(JSON.stringify(next));
|
|
352
|
+
await handle.sync();
|
|
353
|
+
await handle.close();
|
|
354
|
+
handle = undefined;
|
|
355
|
+
await assertLock(this.directory, RELAY_LOCK, this.lock);
|
|
356
|
+
await rename(temp, join(this.directory, RELAY_FILE));
|
|
357
|
+
await assertLock(this.directory, RELAY_LOCK, this.lock);
|
|
358
|
+
await syncDirectory(this.directory);
|
|
359
|
+
await assertLock(this.directory, RELAY_LOCK, this.lock);
|
|
360
|
+
} finally {
|
|
361
|
+
await handle?.close();
|
|
362
|
+
await unlink(temp).catch((error: NodeJS.ErrnoException) => {
|
|
363
|
+
if (error.code !== "ENOENT") {
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
159
371
|
/** One writer only; caller supplies an isolated directory. No backup import or grant restore API. */
|
|
160
372
|
export class PairingStorage {
|
|
161
373
|
private closed = false;
|
|
@@ -205,7 +417,7 @@ export class PairingStorage {
|
|
|
205
417
|
}
|
|
206
418
|
}
|
|
207
419
|
|
|
208
|
-
const lock = await acquireLock(directory);
|
|
420
|
+
const lock = await acquireLock(directory, LOCK);
|
|
209
421
|
const store = new PairingStorage(
|
|
210
422
|
directory,
|
|
211
423
|
capacity,
|
|
@@ -241,7 +453,7 @@ export class PairingStorage {
|
|
|
241
453
|
}
|
|
242
454
|
|
|
243
455
|
await checkDirectory(directory);
|
|
244
|
-
const lock = await acquireLock(directory);
|
|
456
|
+
const lock = await acquireLock(directory, LOCK);
|
|
245
457
|
|
|
246
458
|
try {
|
|
247
459
|
const file = join(directory, FILE);
|
|
@@ -273,7 +485,7 @@ export class PairingStorage {
|
|
|
273
485
|
state.reserved.length > 0,
|
|
274
486
|
);
|
|
275
487
|
} catch (error) {
|
|
276
|
-
await releaseLock(directory, lock);
|
|
488
|
+
await releaseLock(directory, LOCK, lock);
|
|
277
489
|
|
|
278
490
|
throw error;
|
|
279
491
|
}
|
|
@@ -290,7 +502,7 @@ export class PairingStorage {
|
|
|
290
502
|
}
|
|
291
503
|
|
|
292
504
|
this.closed = true;
|
|
293
|
-
await releaseLock(this.directory, this.lock);
|
|
505
|
+
await releaseLock(this.directory, LOCK, this.lock);
|
|
294
506
|
}
|
|
295
507
|
|
|
296
508
|
/** Inspection never authorizes a restored grant. */
|
|
@@ -422,29 +634,29 @@ export class PairingStorage {
|
|
|
422
634
|
let handle;
|
|
423
635
|
|
|
424
636
|
try {
|
|
425
|
-
await assertLock(this.directory, this.lock);
|
|
637
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
426
638
|
await this.assertRecord(expected);
|
|
427
639
|
// The 0700 directory assumes a trusted OS user. This detects accidental lock loss,
|
|
428
640
|
// not malicious unlink/replacement in the small window between checks and writes.
|
|
429
|
-
await assertLock(this.directory, this.lock);
|
|
641
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
430
642
|
handle = await open(temp, "wx", 0o600);
|
|
431
643
|
await handle.writeFile(JSON.stringify(next));
|
|
432
644
|
this.fault?.("beforeFileSync");
|
|
433
|
-
await assertLock(this.directory, this.lock);
|
|
645
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
434
646
|
await handle.sync();
|
|
435
647
|
await handle.close();
|
|
436
648
|
handle = undefined;
|
|
437
649
|
this.fault?.("beforeRename");
|
|
438
|
-
await assertLock(this.directory, this.lock);
|
|
650
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
439
651
|
await this.assertRecord(expected);
|
|
440
|
-
await assertLock(this.directory, this.lock);
|
|
652
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
441
653
|
await rename(temp, join(this.directory, FILE));
|
|
442
654
|
this.fault?.("beforeDirSync");
|
|
443
|
-
await assertLock(this.directory, this.lock);
|
|
655
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
444
656
|
await syncDirectory(this.directory);
|
|
445
|
-
await assertLock(this.directory, this.lock);
|
|
657
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
446
658
|
await this.assertRecord(next);
|
|
447
|
-
await assertLock(this.directory, this.lock);
|
|
659
|
+
await assertLock(this.directory, LOCK, this.lock);
|
|
448
660
|
} finally {
|
|
449
661
|
await handle?.close();
|
|
450
662
|
await unlink(temp).catch((error: NodeJS.ErrnoException) => {
|