@bom-pi/core 0.2.3 → 0.2.5

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.
@@ -17,6 +17,7 @@ import {
17
17
  PROTOCOL_VERSION,
18
18
  parseDecision,
19
19
  verifyDecisionSignature,
20
+ checkDecisionBinding,
20
21
  DecisionError,
21
22
  type DecisionCertificate,
22
23
  type ParsedDecision,
@@ -93,6 +94,9 @@ const TRANSACTION_DEADLINE = 120;
93
94
  const MAX_OFFERS_PER_TARGET = 64;
94
95
  const MAX_PENDING_PER_TARGET = 64;
95
96
  const MAX_CHALLENGES = 256;
97
+ /** ADR-22: RAM tombstone ceiling for consumed code hashes — a footprint bound, never a
98
+ * correctness bound (expired entries are pruned on insert). */
99
+ const MAX_CONSUMED_CODES = 1024;
96
100
 
97
101
  const FP = /^[0-9a-f]{64}$/;
98
102
  const ID = /^[0-9a-f]{32,128}$/;
@@ -973,6 +977,102 @@ export function signRegistrationProof(input: {
973
977
  return { ...payload, signature: b64(signature) } as RegistrationProof;
974
978
  }
975
979
 
980
+ /** ADR-22: B-side pre-redemption verification of a cloud-fetched device-pair offer (the
981
+ * `b-accept --code` lane). X is untrusted for OFFER CONTENT: every binding A signed at
982
+ * registration time is recomputed here, and the owner-pinned target fingerprint is compared
983
+ * last, so a lying or malicious cloud can neither swap the target key, alter the offer facts,
984
+ * extend the expiry, nor attach the code to a different registration. The order of the checks
985
+ * only serves diagnostics (the failure names the broken point); every point must pass before
986
+ * the caller may hand the offer to a redemption. */
987
+ export function verifyOfferForAcceptByCode(input: {
988
+ offer: DeviceOffer;
989
+ registration: RegistrationProof;
990
+ code: string;
991
+ expectedTargetFp: string;
992
+ now: number;
993
+ }): void {
994
+ const { offer, registration: proof } = input;
995
+
996
+ // §14/M3 binding first: the fingerprint IS the SPKI's hash, so the owner-pinned fingerprint
997
+ // (point 5) names the same key the signature below verifies on.
998
+ if (
999
+ Buffer.from(offer.targetSpki, "base64url").length !== 44 ||
1000
+ sha256Hex(Buffer.from(offer.targetSpki, "base64url")) !== offer.targetFp
1001
+ ) {
1002
+ fail(400, "Offer target SPKI does not hash to the target fingerprint");
1003
+ }
1004
+
1005
+ const record = exactFields(
1006
+ proof as unknown as CanonicalValue,
1007
+ [
1008
+ "v",
1009
+ "domain",
1010
+ "offerId",
1011
+ "offerBodyHash",
1012
+ "offerCodeHash",
1013
+ "cloudId",
1014
+ "fingerprint",
1015
+ "generation",
1016
+ "issuedAt",
1017
+ "nonce",
1018
+ "signature",
1019
+ ],
1020
+ "registration proof",
1021
+ );
1022
+
1023
+ // Type sanity on the two numbers (canonical positive integers); their VALUES are only
1024
+ // meaningful to A and X — B binds everything else by signature and expiry.
1025
+ integer(record.generation, "generation", true);
1026
+ integer(record.issuedAt, "issuedAt", true);
1027
+
1028
+ // Point 1 (bindings): the proof must name THIS offer, this cloud and the target identity.
1029
+ if (
1030
+ record.v !== 1 ||
1031
+ record.domain !== DEVICE_OFFER_REGISTRATION_DOMAIN ||
1032
+ record.offerId !== offer.offerId ||
1033
+ record.cloudId !== offer.cloudId ||
1034
+ record.fingerprint !== offer.targetFp
1035
+ ) {
1036
+ fail(409, "Registration proof does not bind this offer");
1037
+ }
1038
+
1039
+ // Point 2: the offer bytes are exactly what A signed — no field was altered in transit.
1040
+ if (record.offerBodyHash !== offerBodyHash(offer)) {
1041
+ fail(409, "Offer body does not match the signed registration (offerBodyHash)");
1042
+ }
1043
+
1044
+ // Point 3: the code the owner typed is the code A registered.
1045
+ if (record.offerCodeHash !== codeHash(input.code)) {
1046
+ fail(409, "Offer code does not match the signed registration (offerCodeHash)");
1047
+ }
1048
+
1049
+ // Point 1 (signature): Ed25519 over the exact canonical proof bytes, verified on the
1050
+ // offer's own targetSpki — the cloud cannot forge it and cannot re-point it.
1051
+ const { signature: proofSignature, ...proofPayload } = record as Record<string, CanonicalValue>;
1052
+
1053
+ if (!ed25519Verify(canonicalJson(proofPayload), proof.signature, offer.targetSpki)) {
1054
+ fail(401, "Offer registration signature does not verify on offer.targetSpki");
1055
+ }
1056
+
1057
+ void proofSignature;
1058
+
1059
+ // Point 4: still live at B's clock; the expiry is a number A signed, so the cloud cannot
1060
+ // have extended it (point 2 pins the bytes).
1061
+ if (offer.codeExpiresAt <= input.now) {
1062
+ fail(410, "Offer code is expired");
1063
+ }
1064
+
1065
+ // Point 5: the owner's pinned fingerprint — the one human check that also survives a fully
1066
+ // malicious cloud serving A's genuine offer for a DIFFERENT target machine. The real fp is
1067
+ // in the message so the owner can compare and decide.
1068
+ if (offer.targetFp !== input.expectedTargetFp) {
1069
+ fail(
1070
+ 403,
1071
+ `Offer target fingerprint ${offer.targetFp} does not match --expect-target-fp ${input.expectedTargetFp}`,
1072
+ );
1073
+ }
1074
+ }
1075
+
976
1076
  export interface BrokerEnvironment {
977
1077
  cloudId: string;
978
1078
  now(): number;
@@ -1157,11 +1257,21 @@ const rfc3339 = (seconds: number): string =>
1157
1257
  new Date(seconds * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
1158
1258
 
1159
1259
  export class DevicePairBroker {
1160
- /** RAM-only offer hashes; an unredeemed code is invalid after restart (§4.2/§11). */
1260
+ /** RAM-only offer hashes; an unredeemed code is invalid after restart (§4.2/§11). The
1261
+ * registration proof rides the entry so ADR-22's read-only lookup can return it. */
1161
1262
  private readonly offers = new Map<
1162
1263
  string,
1163
- { offer: DeviceOffer; generation: number; targetFp: string }
1264
+ {
1265
+ offer: DeviceOffer;
1266
+ generation: number;
1267
+ targetFp: string;
1268
+ registration: RegistrationProof;
1269
+ }
1164
1270
  >();
1271
+ /** ADR-22 RAM tombstones: code hashes consumed by a completed §7 commit, kept until the
1272
+ * code's own expiry so a post-redemption lookup answers a typed 410 instead of an
1273
+ * ambiguous 404. Never persisted; pruned and capped in `markCodeConsumed`. */
1274
+ private readonly consumedCodes = new Map<string, number>();
1165
1275
  private state: PendingSnapshot = { version: 1, requests: [] };
1166
1276
  private relations: RelationSnapshot = { version: 1, relations: [], notices: [] };
1167
1277
  /** §14 RAM one-use pickup challenges per request; a new status mint replaces the old. */
@@ -1399,12 +1509,66 @@ export class DevicePairBroker {
1399
1509
  offer,
1400
1510
  generation,
1401
1511
  targetFp: offer.targetFp,
1512
+ registration: structuredClone(input.registration),
1402
1513
  });
1403
1514
 
1404
1515
  return { registeredUntil: offer.codeExpiresAt };
1405
1516
  });
1406
1517
  }
1407
1518
 
1519
+ /** ADR-22: the read-only offer fetch behind `pair-lookup` — B's `b-accept --code` pulls the
1520
+ * offer plus its §4.2 registration proof before redeeming, then re-verifies every signed
1521
+ * binding client-side (`verifyOfferForAcceptByCode`); the cloud is never trusted for offer
1522
+ * content. NEVER consumes: the map is untouched and the code stays redeemable for its full
1523
+ * TTL. A consumed code is answered from the RAM tombstone as a typed 410, an unknown code
1524
+ * as 404 — neither ever reveals the existence of any other offer. */
1525
+ lookupDeviceOffer(input: { code: string }): {
1526
+ offer: DeviceOffer;
1527
+ registration: RegistrationProof;
1528
+ } {
1529
+ const hash = codeHash(input.code);
1530
+ const entry = this.offers.get(hash);
1531
+
1532
+ if (entry === undefined) {
1533
+ if (this.consumedCodes.has(hash)) {
1534
+ fail(410, "Offer code is expired or consumed");
1535
+ }
1536
+
1537
+ fail(404, "No live offer for that code");
1538
+ }
1539
+
1540
+ if (entry.offer.codeExpiresAt <= this.env.now()) {
1541
+ fail(410, "Offer code is expired or consumed");
1542
+ }
1543
+
1544
+ return {
1545
+ offer: structuredClone(entry.offer),
1546
+ registration: structuredClone(entry.registration),
1547
+ };
1548
+ }
1549
+
1550
+ /** Records a consumed code's tombstone until its own expiry passes. Bounded: expired
1551
+ * entries are pruned on insert and the map holds at most MAX_CONSUMED_CODES hashes. */
1552
+ private markCodeConsumed(hash: string, until: number): void {
1553
+ const now = this.env.now();
1554
+
1555
+ for (const [key, expiry] of this.consumedCodes) {
1556
+ if (expiry <= now) {
1557
+ this.consumedCodes.delete(key);
1558
+ }
1559
+ }
1560
+
1561
+ if (this.consumedCodes.size >= MAX_CONSUMED_CODES) {
1562
+ const oldest = this.consumedCodes.keys().next();
1563
+
1564
+ if (!oldest.done) {
1565
+ this.consumedCodes.delete(oldest.value);
1566
+ }
1567
+ }
1568
+
1569
+ this.consumedCodes.set(hash, until);
1570
+ }
1571
+
1408
1572
  /** §4.2 step 2 + §7 prepare/commit: validate, verify A live, prepare, consume, provisional. */
1409
1573
  redeemDeviceOffer(input: { code: string; requestBytes: Uint8Array }): Promise<{
1410
1574
  requestId: string;
@@ -1573,6 +1737,7 @@ export class DevicePairBroker {
1573
1737
  }
1574
1738
 
1575
1739
  this.offers.delete(hash);
1740
+ this.markCodeConsumed(hash, offer.codeExpiresAt);
1576
1741
 
1577
1742
  const provisionalReceipt = await this.env.signReceipt({
1578
1743
  kind: "pair-provisional",
@@ -1886,12 +2051,18 @@ export class DevicePairBroker {
1886
2051
  this.challenges,
1887
2052
  );
1888
2053
 
2054
+ const certificateBytes = Buffer.from(
2055
+ canonicalJson(input.decision as unknown as CanonicalValue),
2056
+ );
1889
2057
  const receiptBody: Record<string, CanonicalValue> = {
1890
2058
  kind: "pair-decision",
1891
2059
  requestId: record.requestId,
1892
2060
  revision: record.revision,
1893
2061
  decision,
1894
2062
  pendingRequestBodyHash: record.pendingRequestBodyHash,
2063
+ // D2 defense-in-depth: the certified bytes ride the receipt itself, so a
2064
+ // swapped certificate can never be presented against an honest receipt.
2065
+ certificateHash: sha256Hex(certificateBytes),
1895
2066
  };
1896
2067
 
1897
2068
  if (decision === "approve") {
@@ -1905,9 +2076,7 @@ export class DevicePairBroker {
1905
2076
  record.approvedExpiry =
1906
2077
  decision === "approve" ? approvedExpiryOf(input.decision) : null;
1907
2078
  record.decisionReceipt = receipt;
1908
- record.decisionBytes = Buffer.from(
1909
- canonicalJson(input.decision as unknown as CanonicalValue),
1910
- ).toString("utf8");
2079
+ record.decisionBytes = certificateBytes.toString("utf8");
1911
2080
 
1912
2081
  await this.commitPending();
1913
2082
 
@@ -1920,10 +2089,17 @@ export class DevicePairBroker {
1920
2089
 
1921
2090
  /** §6 status for the requester or target; the REQUESTER of an approved request also gets a
1922
2091
  * fresh one-use X-signed pickup challenge (replacing any prior one, §14). */
1923
- async requestStatus(input: {
1924
- requestId: string;
1925
- viewerFp: string;
1926
- }): Promise<{ view: PendingView; challengeReceipt: string | null }> {
2092
+ async requestStatus(input: { requestId: string; viewerFp: string }): Promise<{
2093
+ view: PendingView;
2094
+ challengeReceipt: string | null;
2095
+ /** D2 recovery: X's own signed decision receipt plus the exact owner-signed certificate
2096
+ * bytes it verified, published ONLY to the target of a terminally-decided record. A
2097
+ * target ledger that missed its decide-time commit (a crash the intent replay cannot
2098
+ * cover, or a pre-intent build) heals from this verified evidence instead of wedging
2099
+ * undecided while the cloud row stays approved. Null in every other case. */
2100
+ decisionReceipt: string | null;
2101
+ decisionBytes: string | null;
2102
+ }> {
1927
2103
  return this.mutate(async () => {
1928
2104
  this.requireReady();
1929
2105
 
@@ -1941,6 +2117,21 @@ export class DevicePairBroker {
1941
2117
  fail(403, "Only the requester or target may view this request");
1942
2118
  }
1943
2119
 
2120
+ // The target of a terminal record gets the decision evidence: the X-signed receipt
2121
+ // and the exact certificate bytes X verified against the pinned §13 signer before
2122
+ // recording the decision. Nonsecret (a decision is not a credential) and bounded
2123
+ // (one certificate), and it lets the target re-verify everything locally.
2124
+ const decisionEvidence =
2125
+ input.viewerFp === record.offer.targetFp &&
2126
+ (record.state === "approved" || record.state === "denied") &&
2127
+ record.decisionReceipt !== null &&
2128
+ record.decisionBytes !== null
2129
+ ? {
2130
+ decisionReceipt: record.decisionReceipt,
2131
+ decisionBytes: record.decisionBytes,
2132
+ }
2133
+ : { decisionReceipt: null, decisionBytes: null };
2134
+
1944
2135
  const view = this.pendingView(input.requestId, input.viewerFp);
1945
2136
 
1946
2137
  if (
@@ -1948,7 +2139,7 @@ export class DevicePairBroker {
1948
2139
  input.viewerFp !== requesterFp ||
1949
2140
  record.decisionReceipt === null
1950
2141
  ) {
1951
- return { view, challengeReceipt: null };
2142
+ return { view, challengeReceipt: null, ...decisionEvidence };
1952
2143
  }
1953
2144
 
1954
2145
  // P7 M1: minting an X-signed pickup challenge is authority-bearing — a revoked
@@ -1958,7 +2149,7 @@ export class DevicePairBroker {
1958
2149
  const now = this.env.now();
1959
2150
 
1960
2151
  if (record.pendingExpiresAt !== null && now >= record.pendingExpiresAt) {
1961
- return { view, challengeReceipt: null };
2152
+ return { view, challengeReceipt: null, ...decisionEvidence };
1962
2153
  }
1963
2154
 
1964
2155
  const challenge = randomBytes(32).toString("base64url");
@@ -1973,7 +2164,7 @@ export class DevicePairBroker {
1973
2164
 
1974
2165
  this.pickupChallenges.set(record.requestId, { challenge, expiresAt, receipt });
1975
2166
 
1976
- return { view, challengeReceipt: receipt };
2167
+ return { view, challengeReceipt: receipt, ...decisionEvidence };
1977
2168
  });
1978
2169
  }
1979
2170
 
@@ -2571,6 +2762,15 @@ export interface LedgerEnvironment {
2571
2762
  identityPrivateDer(): Uint8Array;
2572
2763
  /** Verifies an X-signed nonsecret receipt against the pinned X key; null fails closed. */
2573
2764
  verifyCloudReceipt(receipt: string): Promise<Record<string, CanonicalValue> | null>;
2765
+ /** The currently pinned §13 owner-signer facts for THIS daemon (recovery lane only): the
2766
+ * D2 heal verifies replayed decision certificates offline against exactly this pin —
2767
+ * the verifying key always derives from the pin, never from the certificate. Optional —
2768
+ * absent fails the heal closed, resumable, and never touches the live decision lane. */
2769
+ signerPin?(): {
2770
+ signerFingerprint: string;
2771
+ signerEpoch: number;
2772
+ publicKeySpki: string;
2773
+ } | null;
2574
2774
  /** Registers a freshly minted offer with X over the live connector; rejects while offline. */
2575
2775
  registerOffer(input: {
2576
2776
  offer: DeviceOffer;
@@ -2583,10 +2783,15 @@ export interface LedgerEnvironment {
2583
2783
  /** Delivers an owner-signed decision envelope; returns X's nonsecret receipt. */
2584
2784
  sendDecision(bytes: Uint8Array): Promise<{ receipt: string }>;
2585
2785
  /** 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 }>;
2786
+ * decision reconcile skips gracefully when the surface is absent (test rigs). The D2
2787
+ * recovery fields carry X's signed decision evidence for the target of a terminal
2788
+ * record; absent on clouds that predate the lane. */
2789
+ requestStatus?(requestId: string): Promise<{
2790
+ view: { [key: string]: CanonicalValue };
2791
+ challengeReceipt: string | null;
2792
+ decisionReceipt?: string | null;
2793
+ decisionBytes?: Uint8Array | null;
2794
+ }>;
2590
2795
  /** Delivers a termination notice; returns X's signed deleted/already-absent ACK. */
2591
2796
  sendTermination(bytes: Uint8Array): Promise<string>;
2592
2797
  }
@@ -3500,6 +3705,230 @@ export class PairingLedger {
3500
3705
  }
3501
3706
  }
3502
3707
 
3708
+ /* ---- D2 recovery: undecided pendings X has already decided (no local intent) ---- */
3709
+
3710
+ // The intent replay above covers the crash window THIS build records. It cannot heal a
3711
+ // ledger that went undecided through a path with no intent at all — a pre-MINOR-4
3712
+ // build that sent the decision but never committed locally (the fleet wedge: X
3713
+ // approved, the target's pending stayed decided:null, every pickup 404'd). For every
3714
+ // still-undecided pending, TWO independent proofs must agree before anything heals:
3715
+ // X's signed receipt (pinned X key, binding request, revision, decision class,
3716
+ // pending hash — and, on binding-aware clouds, the sha256 of the certified bytes) AND
3717
+ // the owner-signed §13 certificate itself, verified OFFLINE against the daemon's
3718
+ // pinned signer key with every binding a live decide() checks. X's row alone proves
3719
+ // nothing about the owner's choice — a Byzantine X must never be able to approve a
3720
+ // relation the owner never signed (DESIGN-cloud-pairing §2). No owner RE-approval:
3721
+ // the owner's own past signature is the proof. Expired approvals, absent pins,
3722
+ // unverifiable bytes and every transport error stay resumable — never a throw, never
3723
+ // a partial heal.
3724
+ for (const record of [...this.state.pending]) {
3725
+ if (
3726
+ record.decided !== null ||
3727
+ this.state.decisionIntents.some((entry) => entry.requestId === record.requestId)
3728
+ ) {
3729
+ continue; // decided already, or the stronger intent replay owns it
3730
+ }
3731
+
3732
+ let status: Awaited<ReturnType<NonNullable<LedgerEnvironment["requestStatus"]>>>;
3733
+
3734
+ try {
3735
+ const read = await this.env.requestStatus?.(record.requestId);
3736
+
3737
+ if (read === undefined) {
3738
+ resumable.push({
3739
+ requestId: record.requestId,
3740
+ reason: "no status surface for undecided recovery",
3741
+ });
3742
+
3743
+ continue;
3744
+ }
3745
+
3746
+ status = read;
3747
+ } catch {
3748
+ resumable.push({ requestId: record.requestId, reason: "X status unavailable" });
3749
+
3750
+ continue;
3751
+ }
3752
+
3753
+ const state = typeof status.view.state === "string" ? status.view.state : null;
3754
+ const terminal = state === "approved" ? "approve" : state === "denied" ? "deny" : null;
3755
+
3756
+ if (terminal === null) {
3757
+ resumable.push({
3758
+ requestId: record.requestId,
3759
+ reason: state === null ? "status unavailable" : `X still ${state}`,
3760
+ });
3761
+
3762
+ continue;
3763
+ }
3764
+
3765
+ if (
3766
+ typeof status.decisionReceipt !== "string" ||
3767
+ status.decisionReceipt.length === 0 ||
3768
+ !(status.decisionBytes instanceof Uint8Array) ||
3769
+ status.decisionBytes.length === 0
3770
+ ) {
3771
+ resumable.push({
3772
+ requestId: record.requestId,
3773
+ reason: `X is ${state} but published no decision evidence`,
3774
+ });
3775
+
3776
+ continue;
3777
+ }
3778
+
3779
+ try {
3780
+ const bytes = status.decisionBytes;
3781
+ const verified = await this.env.verifyCloudReceipt(status.decisionReceipt);
3782
+
3783
+ if (
3784
+ verified === null ||
3785
+ verified.kind !== "pair-decision" ||
3786
+ verified.requestId !== record.requestId ||
3787
+ verified.revision !== record.revision ||
3788
+ verified.decision !== terminal ||
3789
+ // M1: the receipt's pending hash must bind THIS record, not just any
3790
+ // request with the same ID/revision.
3791
+ verified.pendingRequestBodyHash !== record.pendingRequestBodyHash ||
3792
+ // T2: on clouds that bind the certified bytes into the receipt, the bytes
3793
+ // presented must be exactly the bytes X hashed when it signed.
3794
+ (typeof verified.certificateHash === "string" &&
3795
+ verified.certificateHash !== sha256Hex(bytes))
3796
+ ) {
3797
+ resumable.push({
3798
+ requestId: record.requestId,
3799
+ reason: "X decision evidence did not verify for this record",
3800
+ });
3801
+
3802
+ continue;
3803
+ }
3804
+
3805
+ // H1: X's receipt alone authorizes nothing here. The certificate bytes are the
3806
+ // owner-signed §13 decision, and the OWNER's pinned key — never a key from the
3807
+ // certificate, never X's key — must verify it offline: full signature, pin
3808
+ // fingerprint and epoch, plus every binding a live decide() checks (request,
3809
+ // revision, offer, proposer, pending hash, identity tuple, memberships,
3810
+ // approved-expiry semantics). A Byzantine or buggy X cannot mint an approval
3811
+ // the owner never signed: fail → resumable, no heal. Only the live lane's
3812
+ // freshness window and one-use challenge burn are skipped — this is a replay
3813
+ // of a decision X already recorded, not a fresh decision (§13/D2).
3814
+ const pin = this.env.signerPin?.() ?? null;
3815
+
3816
+ if (pin === null) {
3817
+ resumable.push({
3818
+ requestId: record.requestId,
3819
+ reason: "no pinned §13 signer available to verify recovery offline",
3820
+ });
3821
+
3822
+ continue;
3823
+ }
3824
+
3825
+ let parsed: ParsedDecision;
3826
+
3827
+ try {
3828
+ parsed = parseDecision(bytes);
3829
+ verifyDecisionSignature(parsed, {
3830
+ signerPublicKeyDer: Buffer.from(pin.publicKeySpki, "base64url"),
3831
+ pinnedSignerEpoch: pin.signerEpoch,
3832
+ nowSec: this.env.now(),
3833
+ recovery: true,
3834
+ });
3835
+ checkDecisionBinding(parsed, {
3836
+ requestId: record.requestId,
3837
+ expectedRevision: record.revision,
3838
+ offerId: record.offerId,
3839
+ offerBodyHash: record.offerBodyHash,
3840
+ proposer: record.proposer,
3841
+ pendingRequestBodyHash: record.pendingRequestBodyHash,
3842
+ requesterFp: record.requester.fingerprint,
3843
+ targetFp: this.env.identityFingerprint(),
3844
+ transport: "cloud",
3845
+ cloudId: this.env.cloudId,
3846
+ targetMembership: record.targetMembership,
3847
+ requesterMembership: record.requesterMembership,
3848
+ direction: "requester-to-target",
3849
+ requestedGrantExpiresAt: record.requestedGrantExpiresAt,
3850
+ nowSec: this.env.now(),
3851
+ });
3852
+ } catch {
3853
+ resumable.push({
3854
+ requestId: record.requestId,
3855
+ reason: "decision certificate failed offline §13 verification",
3856
+ });
3857
+
3858
+ continue;
3859
+ }
3860
+
3861
+ const certificate = parseCanonicalJson(Buffer.from(bytes));
3862
+
3863
+ if (
3864
+ !isRecord(certificate) ||
3865
+ certificate.requestId !== record.requestId ||
3866
+ Number(certificate.expectedRevision) !== record.revision ||
3867
+ Number(certificate.expectedRevision) !== record.revision ||
3868
+ certificate.decision !== terminal
3869
+ ) {
3870
+ resumable.push({
3871
+ requestId: record.requestId,
3872
+ reason: "X decision bytes do not match the verified receipt",
3873
+ });
3874
+
3875
+ continue;
3876
+ }
3877
+
3878
+ const approvedExpiry =
3879
+ terminal === "approve"
3880
+ ? integer(verified.approvedExpiry, "approvedExpiry", true)
3881
+ : null;
3882
+
3883
+ // M2: an approval whose grant window has already closed never heals — the
3884
+ // pending stays undecided and every pickup keeps 410-ing like before, so a
3885
+ // stale recovery cannot resurrect an expired grant.
3886
+ const now = this.env.now();
3887
+
3888
+ if (approvedExpiry !== null && approvedExpiry <= now) {
3889
+ resumable.push({
3890
+ requestId: record.requestId,
3891
+ reason: "recovered approval has already expired",
3892
+ });
3893
+
3894
+ continue;
3895
+ }
3896
+
3897
+ // M2 cross-check: X's receipt and the owner's certificate must agree on the
3898
+ // exact approved expiry — two independent signatures, one number.
3899
+ if (approvedExpiry !== null && parsed.core.approvedExpiry !== approvedExpiry) {
3900
+ resumable.push({
3901
+ requestId: record.requestId,
3902
+ reason: "receipt and certificate disagree on the approved expiry",
3903
+ });
3904
+
3905
+ continue;
3906
+ }
3907
+
3908
+ await this.mutate(async () => {
3909
+ const current = this.state.pending.find(
3910
+ (entry) => entry.requestId === record.requestId,
3911
+ );
3912
+
3913
+ if (current === undefined || current.decided !== null) {
3914
+ return; // raced with another writer; the durable truth already moved
3915
+ }
3916
+
3917
+ current.decided = {
3918
+ decision: terminal,
3919
+ approvedExpiry,
3920
+ certificateHash: sha256Hex(bytes),
3921
+ };
3922
+ current.lastSyncedAt = this.env.now();
3923
+ await this.commit();
3924
+ });
3925
+
3926
+ committed.push(record.requestId);
3927
+ } catch {
3928
+ resumable.push({ requestId: record.requestId, reason: "decision recovery failed" });
3929
+ }
3930
+ }
3931
+
3503
3932
  return { committed, resumable };
3504
3933
  }
3505
3934
 
@@ -111,32 +111,32 @@ async function syncDirectory(directory: string): Promise<void> {
111
111
  }
112
112
  }
113
113
 
114
- /** A finished lease names its holder: `pid:uuid`. A lease that is malformed, legacy
115
- * (pre-pid build) or names a provably dead holder never guarded a completed mutation — every
116
- * mutation requires a finished lease and re-validates the lease inode first (assertLock), and
117
- * the app's single-instance lock rules out a second live daemon on one data directory — so
118
- * such leases are crash leftovers and are reclaimed instead of blocking the next boot. */
119
- function leaseHeldByLiveWriter(content: string): boolean {
114
+ /** The pid of a live lease holder, or null for a lease that is malformed, legacy (pre-pid
115
+ * build) or names a provably dead holder. Such leases never guarded a completed mutation —
116
+ * every mutation requires a finished lease and re-validates the lease inode first (assertLock),
117
+ * and the app's single-instance lock rules out a second live daemon on one data directory — so
118
+ * they are crash leftovers and get reclaimed instead of blocking the next boot. */
119
+ function liveLeaseHolderPid(content: string): number | null {
120
120
  const trimmed = content.trim();
121
121
 
122
122
  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
123
- return false; // legacy bare-uuid build: the lease cannot name a live holder
123
+ return null; // legacy bare-uuid build: the lease cannot name a live holder
124
124
  }
125
125
 
126
126
  const separator = trimmed.indexOf(":");
127
127
  const pid = Number.parseInt(separator > 0 ? trimmed.slice(0, separator) : "", 10);
128
128
 
129
129
  if (!Number.isSafeInteger(pid) || pid <= 0) {
130
- return false; // the writer died before finishing its own identity
130
+ return null; // the writer died before finishing its own identity
131
131
  }
132
132
 
133
133
  try {
134
134
  process.kill(pid, 0);
135
135
 
136
- return true;
136
+ return pid;
137
137
  } catch (error) {
138
138
  // EPERM names a live process under another user; anything else is dead or invalid.
139
- return (error as NodeJS.ErrnoException).code !== "EPERM";
139
+ return (error as NodeJS.ErrnoException).code === "EPERM" ? pid : null;
140
140
  }
141
141
  }
142
142
 
@@ -153,18 +153,20 @@ async function acquireLock(directory: string, lockFile: string): Promise<LockLea
153
153
 
154
154
  // An EEXIST lease nobody live holds is a crash leftover: reclaim it once, fail-closed.
155
155
  const existing = await readFile(path, "utf8").catch(() => "");
156
+ const holder = liveLeaseHolderPid(existing);
156
157
 
157
- if (!leaseHeldByLiveWriter(existing)) {
158
- await rm(path, { force: true });
158
+ if (holder !== null) {
159
+ fail(
160
+ `writer lock exists; a live writer (pid ${holder}) holds this store ` +
161
+ "(stop it, or verify and recover explicitly)",
162
+ );
163
+ }
159
164
 
160
- try {
161
- handle = await open(path, "wx", 0o600);
162
- } catch (race) {
163
- fail(
164
- "writer lock exists; a live writer holds this store (explicit recovery required)",
165
- );
166
- }
167
- } else {
165
+ await rm(path, { force: true });
166
+
167
+ try {
168
+ handle = await open(path, "wx", 0o600);
169
+ } catch (race) {
168
170
  fail("writer lock exists; a live writer holds this store (explicit recovery required)");
169
171
  }
170
172
  }