@uuaid/pillar 2.4.1 → 2.5.3

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.
@@ -48,6 +48,19 @@ export class InMemoryChallengeBroker {
48
48
  return { challengeId, state: rec.state };
49
49
  }
50
50
 
51
+ /**
52
+ * Drop a reservation that will never be finalized (2.5.3, AC7-Kimi k):
53
+ * prepareBlobSend calls it when the upload fails. Only a still-reserved
54
+ * challenge goes; a finalized one is never touched. The hosted broker has no
55
+ * such call: its unfinalized reservations expire on their own (1 h).
56
+ */
57
+ async release({ challengeId }) {
58
+ const rec = this.challenges.get(challengeId);
59
+ if (!rec || rec.state !== "reserved") return { released: false };
60
+ this.challenges.delete(challengeId);
61
+ return { released: true };
62
+ }
63
+
51
64
  /** Step 3: single-use redemption. Throws on replay, expiry, bad state. */
52
65
  async redeem({ challengeId, object = null, hash = null, sender = null, now = null }) {
53
66
  const rec = this.challenges.get(challengeId);
@@ -104,6 +117,8 @@ export class JournalingBlobBroker extends InMemoryChallengeBroker {
104
117
  } else if (e.op === "redeem") {
105
118
  const rec = this.challenges.get(cid);
106
119
  if (rec) { rec.state = "redeemed"; rec.redeemedAt = e.at; }
120
+ } else if (e.op === "release") {
121
+ if (this.challenges.get(cid)?.state === "reserved") this.challenges.delete(cid);
107
122
  }
108
123
  }
109
124
  }
@@ -122,6 +137,11 @@ export class JournalingBlobBroker extends InMemoryChallengeBroker {
122
137
  this._log({ op: "redeem", challengeId: o.challengeId, sender: r.sender, at: r.redeemedAt });
123
138
  return r;
124
139
  }
140
+ async release(o) {
141
+ const r = await super.release(o);
142
+ if (r.released) this._log({ op: "release", challengeId: o.challengeId, at: this.now() });
143
+ return r;
144
+ }
125
145
  _log(entry) {
126
146
  this.journal.push(entry);
127
147
  if (this.journalPath) appendFileSync(this.journalPath, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
@@ -15,7 +15,12 @@ import { BlobUploadError } from "./blob.mjs";
15
15
 
16
16
  export class MemoryBlobStore {
17
17
  constructor() { this._map = new Map(); }
18
- async put(object, buf) { this._map.set(object, Buffer.from(buf)); return { object, bytes: buf.length }; }
18
+ async put(object, buf) {
19
+ // An object id is written once (2.5.3, AC7-Kimi j): a second put for it is refused, never a silent replace.
20
+ if (this._map.has(object)) throw new BlobUploadError(`MemoryBlobStore: object ${object} already exists`);
21
+ this._map.set(object, Buffer.from(buf));
22
+ return { object, bytes: buf.length };
23
+ }
19
24
  async get(object) { return this._map.get(object) ?? null; }
20
25
  async has(object) { return this._map.has(object); }
21
26
  async delete(object) { return this._map.delete(object); }
@@ -34,9 +39,11 @@ export class FsBlobStore {
34
39
  }
35
40
  async put(object, buf) {
36
41
  try {
37
- await writeFile(this._path(object), buf);
42
+ // "wx": an object id is written once (2.5.3, AC7-Kimi j); an existing one is refused, never replaced.
43
+ await writeFile(this._path(object), buf, { flag: "wx" });
38
44
  return { object, bytes: buf.length };
39
45
  } catch (e) {
46
+ if (e?.code === "EEXIST") throw new BlobUploadError(`FsBlobStore: object ${object} already exists`, e);
40
47
  throw new BlobUploadError(`FsBlobStore write failed for ${object}: ${e.message}`, e);
41
48
  }
42
49
  }
@@ -25,7 +25,7 @@
25
25
  * layer — carriers stay payload-blind). Party pubkeys ride in the terms, so
26
26
  * no directory lookups are needed.
27
27
  */
28
- import { appendFileSync, readFileSync, mkdirSync } from "node:fs";
28
+ import { appendFileSync, readFileSync, mkdirSync, existsSync, chmodSync } from "node:fs";
29
29
  import { dirname } from "node:path";
30
30
  import {
31
31
  validateTerms, verifyTermsSig, verifyReceiptSig,
@@ -37,6 +37,9 @@ import { Observability } from "../observability.mjs";
37
37
  const HEX64 = /^[0-9a-f]{64}$/i;
38
38
 
39
39
  export const STATES = { OPEN: "open", ACCEPTED: "accepted", PAID: "paid", RELEASED: "released" };
40
+ // A PAID offer whose payment is not attested is re-checked this many times by the
41
+ // reconcile timer (2 hours at the default 30 s), then left until a new paid claim.
42
+ export const MAX_RECONCILE_ATTEMPTS = 240;
40
43
 
41
44
  export class EscrowService {
42
45
  /**
@@ -67,6 +70,9 @@ export class EscrowService {
67
70
  this.consumedPayTx = new Map(); // "railKey|tx|<txId>" / "railKey|src|<sourceId>" -> offerId
68
71
  if (journalPath) {
69
72
  mkdirSync(dirname(journalPath), { recursive: true });
73
+ // The journal holds every open offer's content key: owner-only, also when
74
+ // an earlier build created it under the umask (2.5.3, AC7-Kimi g).
75
+ if (existsSync(journalPath)) chmodSync(journalPath, 0o600);
70
76
  this._loadJournal();
71
77
  }
72
78
  }
@@ -75,7 +81,7 @@ export class EscrowService {
75
81
 
76
82
  _append(event) {
77
83
  if (!this.journalPath) return;
78
- appendFileSync(this.journalPath, JSON.stringify({ ...event, at: new Date().toISOString() }) + "\n");
84
+ appendFileSync(this.journalPath, JSON.stringify({ ...event, at: new Date().toISOString() }) + "\n", { mode: 0o600 });
79
85
  }
80
86
 
81
87
  _loadJournal() {
@@ -131,6 +137,9 @@ export class EscrowService {
131
137
  case "pay-consumed":
132
138
  for (const k of ev.keys ?? []) this.consumedPayTx.set(k, ev.offerId);
133
139
  break;
140
+ case "expired":
141
+ this.offers.delete(ev.offerId); // 2.5.3: an open or accepted offer past its expiry (+ grace)
142
+ continue;
134
143
  }
135
144
  this.offers.set(ev.offerId, o);
136
145
  }
@@ -179,9 +188,25 @@ export class EscrowService {
179
188
  return { stop: () => clearInterval(t) };
180
189
  }
181
190
 
182
- async reconcileOnce() {
191
+ /**
192
+ * One pass (2.5.3, AC7-Kimi h): an OPEN or ACCEPTED offer past its expiry plus
193
+ * PAID_GRACE_MS (the latest a paid claim is accepted) is dropped and journaled
194
+ * as expired; a PAID offer whose payout was never attempted is re-checked at
195
+ * most MAX_RECONCILE_ATTEMPTS times (a fresh paid claim starts it again). A
196
+ * payout already attempted is always retried: money may be in flight.
197
+ */
198
+ async reconcileOnce(now = Date.now()) {
183
199
  for (const [offerId, o] of this.offers) {
184
- if (o.state === STATES.PAID) await this._release(offerId, o);
200
+ if ((o.state === STATES.OPEN || o.state === STATES.ACCEPTED) && o.terms && now > Date.parse(o.terms.expiresAt) + PAID_GRACE_MS) {
201
+ this.offers.delete(offerId);
202
+ this._append({ event: "expired", offerId });
203
+ this.metrics.inc("escrow.offer.expired");
204
+ continue;
205
+ }
206
+ if (o.state !== STATES.PAID) continue;
207
+ if (!o.payoutAttempted && (o.reconcileAttempts ?? 0) >= MAX_RECONCILE_ATTEMPTS) continue;
208
+ o.reconcileAttempts = (o.reconcileAttempts ?? 0) + 1;
209
+ await this._release(offerId, o);
185
210
  }
186
211
  }
187
212
 
@@ -192,21 +217,27 @@ export class EscrowService {
192
217
  const { terms, sellerSig, contentKeyHex } = p;
193
218
  // escrowHandle is rail-scoped: this escrow's identity on the rail the
194
219
  // terms name (v1: the zilligon handle; v2 evm: the 0x address).
195
- const rail = this.rails.for(terms ?? {});
196
- const v = validateTerms(terms, { escrowUuaid: this.keychain._identity.uuaid, escrowHandle: rail?.handle ?? this.railHandle });
197
- const senderOk = env.sender === terms?.seller;
220
+ // 2.5.3 (AC7-Kimi i1): who sent it, with which key, and the seller's
221
+ // signature are checked BEFORE the terms are validated, so unsigned input
222
+ // never reaches the payout math. An offer whose transport sender and key are
223
+ // not the seller its terms name gets no reply: that seller is unauthenticated,
224
+ // and an error envelope to it would let anyone aim the escrow at any uuaid.
225
+ if (!terms || typeof terms !== "object" || Array.isArray(terms)) return this.metrics.inc("escrow.error.bad-terms");
226
+ const senderOk = env.sender === terms.seller;
198
227
  const keyOk =
199
- env.transportSignature?.publicKey != null && env.transportSignature.publicKey === terms?.sellerPubKeyHex;
228
+ env.transportSignature?.publicKey != null && env.transportSignature.publicKey === terms.sellerPubKeyHex;
229
+ if (!senderOk || !keyOk) return this.metrics.inc("escrow.error.identity-mismatch");
200
230
  const bad = (code, message) => this._errorTo(terms, "seller", code, message);
201
- if (!terms || !v.ok) return bad(v?.reason ?? "bad-terms", "terms invalid");
231
+ if (!HEX64.test(contentKeyHex ?? "")) return bad("bad-key", "contentKeyHex must be 64 hex chars (32 bytes)");
232
+ if (!verifyTermsSig(terms.sellerPubKeyHex, terms, sellerSig)) return bad("bad-signature", "seller signature invalid");
233
+ const rail = this.rails.for(terms);
234
+ const v = validateTerms(terms, { escrowUuaid: this.keychain._identity.uuaid, escrowHandle: rail?.handle ?? this.railHandle });
235
+ if (!v.ok) return bad(v.reason ?? "bad-terms", "terms invalid");
202
236
  if (!rail) return bad("rail-unsupported", "this escrow has no rail for these terms");
203
237
  if (this.tokenRegistry) {
204
238
  const pol = this.tokenRegistry.checkTerms(terms);
205
239
  if (!pol.ok) return bad(pol.reason, pol.message);
206
240
  }
207
- if (!senderOk || !keyOk) return bad("identity-mismatch", "offer sender does not match signed terms");
208
- if (!HEX64.test(contentKeyHex ?? "")) return bad("bad-key", "contentKeyHex must be 64 hex chars (32 bytes)");
209
- if (!verifyTermsSig(terms.sellerPubKeyHex, terms, sellerSig)) return bad("bad-signature", "seller signature invalid");
210
241
 
211
242
  const existing = this.offers.get(terms.offerId);
212
243
  if (!existing) {
@@ -268,6 +299,7 @@ export class EscrowService {
268
299
  (txId !== o.payTxId || (sourceId ?? null) !== (o.paySourceId ?? null));
269
300
  if (o.state === STATES.ACCEPTED || !o.payTxId || (claimChanged && !o.payoutAttempted)) {
270
301
  o.state = STATES.PAID;
302
+ o.reconcileAttempts = 0; // a fresh claim gets a fresh set of reconcile passes
271
303
  o.payTxId = txId;
272
304
  o.paySourceId = sourceId ?? undefined;
273
305
  this._append({ event: "paid", offerId, txId, sourceId: sourceId ?? null });
@@ -34,6 +34,15 @@ export const TERMS_VERSION = 1;
34
34
  export const TERMS_VERSION_2 = 2; // multi-rail terms: string base-unit amounts
35
35
  export const RAIL = "zilligon";
36
36
  export const DEFAULT_TIP_FEE = 0.005;
37
+ /**
38
+ * The largest v1 amount (priceGons, sellerPayoutGons), 2^52 Gons. Every v1
39
+ * amount, and every transfer derived from one, then stays an exact integer in a
40
+ * double, so feeFor (which mirrors the rail's own floor(amount * 0.005) in
41
+ * doubles) and the payment matcher's exact compare hold. Above 2^53, x++ stopped
42
+ * changing x and smallestSendFor's search never ended: one unsigned offer froze
43
+ * the escrow process (AC7-Kimi i1, 2.5.3).
44
+ */
45
+ export const V1_MAX_GONS = 2 ** 52;
37
46
  export const TERMS_MAX_LIFETIME_MS = 30 * 24 * 3600 * 1000; // bound the escrow's liability window
38
47
  export const PAID_GRACE_MS = 15 * 60 * 1000; // accept a paid-claim this late after expiry (clock skew)
39
48
 
@@ -65,11 +74,24 @@ export function feeFor(amount, tipFeePercent = DEFAULT_TIP_FEE) {
65
74
  */
66
75
  export function smallestSendFor(payout, tipFeePercent = DEFAULT_TIP_FEE) {
67
76
  if (!(tipFeePercent >= 0 && tipFeePercent < 1)) throw new Error("smallestSendFor: tipFeePercent must be in [0, 1)");
68
- const max = Math.ceil(payout / (1 - tipFeePercent));
69
- for (let x = payout; x <= max; x++) {
70
- if (x - feeFor(x, tipFeePercent) >= payout) return x;
77
+ if (!Number.isSafeInteger(payout) || payout < 0 || payout > V1_MAX_GONS) {
78
+ throw new RangeError(`smallestSendFor: payout must be an integer from 0 to ${V1_MAX_GONS}`);
71
79
  }
72
- return max; // exact at the boundary: net(max) >= payout
80
+ const net = (x) => x - feeFor(x, tipFeePercent);
81
+ let hi = Math.ceil(payout / (1 - tipFeePercent));
82
+ if (!Number.isSafeInteger(hi)) throw new RangeError("smallestSendFor: the transfer would not be an exact integer");
83
+ // net(max) >= payout in exact arithmetic; allow for one rounding step in doubles.
84
+ for (let i = 0; i < 8 && net(hi) < payout; i++) hi++;
85
+ if (net(hi) < payout) throw new RangeError("smallestSendFor: no transfer nets the payout");
86
+ // net() never decreases (each step adds 1 minus 0 or 1), so the minimal x is a
87
+ // binary search away: O(log payout), where the old ascending scan took about
88
+ // payout/199 steps (2.5.3).
89
+ let lo = payout;
90
+ while (lo < hi) {
91
+ const mid = lo + Math.floor((hi - lo) / 2);
92
+ if (net(mid) >= payout) hi = mid; else lo = mid + 1;
93
+ }
94
+ return lo;
73
95
  }
74
96
 
75
97
  /**
@@ -91,7 +113,7 @@ export function smallestSendFor(payout, tipFeePercent = DEFAULT_TIP_FEE) {
91
113
  * (the CLI then REQUIRES --payout).
92
114
  */
93
115
  export function allocateFee(priceGons, allocation = "mutual", tipFeePercent = DEFAULT_TIP_FEE) {
94
- if (!Number.isInteger(priceGons) || priceGons < 1) throw new Error("allocateFee: priceGons must be an integer >= 1");
116
+ if (!Number.isInteger(priceGons) || priceGons < 1 || priceGons > V1_MAX_GONS) throw new Error(`allocateFee: priceGons must be an integer from 1 to ${V1_MAX_GONS}`);
95
117
  switch (allocation) {
96
118
  case "seller": {
97
119
  const escrowReceived = priceGons - feeFor(priceGons, tipFeePercent);
@@ -119,8 +141,13 @@ export function allocateFee(priceGons, allocation = "mutual", tipFeePercent = DE
119
141
  * (usually 0) remainder.
120
142
  */
121
143
  export function validatePayout(priceGons, sellerPayoutGons, tipFeePercent = DEFAULT_TIP_FEE) {
144
+ if (!Number.isSafeInteger(priceGons) || priceGons < 1 || priceGons > V1_MAX_GONS
145
+ || !Number.isSafeInteger(sellerPayoutGons) || sellerPayoutGons < 0 || sellerPayoutGons > V1_MAX_GONS) {
146
+ return { ok: false, reason: "amount-out-of-range" };
147
+ }
122
148
  const escrowReceived = priceGons - feeFor(priceGons, tipFeePercent);
123
- const escrowSend = smallestSendFor(sellerPayoutGons, tipFeePercent);
149
+ let escrowSend;
150
+ try { escrowSend = smallestSendFor(sellerPayoutGons, tipFeePercent); } catch (_e) { return { ok: false, reason: "amount-out-of-range" }; }
124
151
  if (escrowSend > escrowReceived) {
125
152
  return { ok: false, reason: "payout-exceeds-received", escrowReceived, escrowSend };
126
153
  }
@@ -229,8 +256,8 @@ function validateTermsV1(terms, { now = Date.now(), escrowUuaid, escrowHandle }
229
256
  if (escrowUuaid && terms.escrow !== escrowUuaid) return { ok: false, reason: "not-my-offer" };
230
257
  if (escrowHandle && terms.escrowHandle !== escrowHandle) return { ok: false, reason: "not-my-rail-handle" };
231
258
  if (typeof terms.itemHash !== "string" || !HEX64.test(terms.itemHash)) return { ok: false, reason: "bad-itemHash" };
232
- if (!Number.isInteger(terms.priceGons) || terms.priceGons < 1) return { ok: false, reason: "bad-price" };
233
- if (!Number.isInteger(terms.sellerPayoutGons) || terms.sellerPayoutGons < 0) return { ok: false, reason: "bad-payout" };
259
+ if (!Number.isInteger(terms.priceGons) || terms.priceGons < 1 || terms.priceGons > V1_MAX_GONS) return { ok: false, reason: "bad-price" };
260
+ if (!Number.isInteger(terms.sellerPayoutGons) || terms.sellerPayoutGons < 0 || terms.sellerPayoutGons > V1_MAX_GONS) return { ok: false, reason: "bad-payout" };
234
261
  let fp;
235
262
  try {
236
263
  fp = fingerprint(terms);
@@ -119,7 +119,7 @@ export class TokenRegistry {
119
119
  }
120
120
 
121
121
  _saveRegistry() {
122
- writeFileSync(this.registryPath, JSON.stringify({ v: 1, chains: this.chains, tokens: this.tokens }, null, 2) + "\n");
122
+ writeFileSync(this.registryPath, JSON.stringify({ v: 1, chains: this.chains, tokens: this.tokens }, null, 2) + "\n", { mode: 0o600 });
123
123
  }
124
124
 
125
125
  _appPath(id) { return join(this.appsDir, `${id}.json`); }
@@ -172,7 +172,7 @@ export class TokenRegistry {
172
172
  const existing = this._readApp(id);
173
173
  if (existing) return { ok: true, id, status: existing.status, duplicate: true };
174
174
  const app = { id, status: "pending", submittedAt: new Date().toISOString(), submission: sub };
175
- writeFileSync(this._appPath(id), JSON.stringify(app, null, 2) + "\n");
175
+ writeFileSync(this._appPath(id), JSON.stringify(app, null, 2) + "\n", { mode: 0o600 });
176
176
  return { ok: true, id, status: "pending" };
177
177
  }
178
178
 
@@ -209,7 +209,7 @@ export class TokenRegistry {
209
209
  app.decidedAt = new Date().toISOString();
210
210
  app.reviewer = reviewer;
211
211
  if (notes) app.notes = notes;
212
- writeFileSync(this._appPath(id), JSON.stringify(app, null, 2) + "\n");
212
+ writeFileSync(this._appPath(id), JSON.stringify(app, null, 2) + "\n", { mode: 0o600 });
213
213
  if (approve) {
214
214
  const provenance = { applicationId: id, reviewer, approvedAt: app.decidedAt };
215
215
  if (sub.kind === "chain") {
package/src/groups-v2.mjs CHANGED
@@ -40,6 +40,13 @@ export const MAX_ANSWER = 64; // manifests per manifest.request answer
40
40
  export const SEEN_CAP = 10_000; // accepted (sender, msgId) pairs kept per group; the oldest go first
41
41
  export const COMMUNITY_SEND_BUDGET = 120; // envelopes per minute per sender
42
42
  export const DEFAULT_LIMITS = Object.freeze({ holdPerSender: 20, holdPerGroup: 100, holdMs: 600_000 });
43
+ // Invitation/recovery buffer (2.5.3, AC7-Kimi f): at most 64 pending invitations,
44
+ // 4 from any one sender, and 32 MiB of buffered manifests in all (4 MiB per
45
+ // sender, so one sender cannot fill it for everyone). Each
46
+ // "group id | sender" key used to buffer up to 1,024 unchecked manifests with no
47
+ // limit on the number of keys, so a sender rotating fresh group ids could hold
48
+ // hundreds of MB per ten minutes.
49
+ export const BUFFER_LIMITS = Object.freeze({ invites: 64, invitesPerSender: 4, bytes: 32 * 1024 * 1024, bytesPerSender: 4 * 1024 * 1024 });
43
50
  export const ACTIONS = Object.freeze(["create", "invite", "accept", "leave", "remove", "rename", "ext_update", "admin_transfer"]);
44
51
  export const V2_OPS = Object.freeze([
45
52
  "message", "manifest", "accept.request", "leave.request", "rename.request", "manifest.request", "equivocation",
@@ -1038,16 +1045,57 @@ export class GroupReceiver {
1038
1045
  * Design cap: a buffered invitation or recovery keeps versions 1..4096 and at
1039
1046
  * most 1,024 manifests. A group past version 4096 cannot be adopted by
1040
1047
  * invitation or recovery; its members keep it by applying each version.
1048
+ * From 2.5.3 also BUFFER_LIMITS: only a manifest that passes checkShape and
1049
+ * fits MAX_MANIFEST_BYTES is kept; a new invitation past the per-sender or
1050
+ * total cap evicts the oldest pending one (of that sender first); and
1051
+ * manifests past the 32 MiB total are not kept, so such a group, too, is kept
1052
+ * by applying each version.
1041
1053
  */
1042
1054
  _buffer(map, key, m, now, extra = {}) {
1043
- const b = map.get(key) ?? { manifests: new Map(), firstAt: now, requested: false, ...extra };
1044
- if (Number.isSafeInteger(m.version) && m.version >= 1 && m.version <= 4096 && !b.manifests.has(m.version) && b.manifests.size < 1024) {
1045
- b.manifests.set(m.version, m);
1055
+ let b = map.get(key);
1056
+ // V1 -069 fix: a manifest that will not be kept takes no slot and evicts nothing.
1057
+ const keepable = Number.isSafeInteger(m.version) && m.version >= 1 && m.version <= 4096 && checkShape(m) === null;
1058
+ if (!keepable || Buffer.byteLength(JSON.stringify(m)) > MAX_MANIFEST_BYTES) return b ?? { manifests: new Map(), firstAt: now, requested: false, bytes: 0, ...extra };
1059
+ if (!b) {
1060
+ b = { manifests: new Map(), firstAt: now, requested: false, bytes: 0, ...extra };
1061
+ if (map === this.invites) this._makeRoomForInvite(key);
1062
+ }
1063
+ if (!b.manifests.has(m.version) && b.manifests.size < 1024) {
1064
+ const size = Buffer.byteLength(JSON.stringify(m));
1065
+ const senderOk = map !== this.invites || this._bufferedBytes(key.slice(key.indexOf("|") + 1)) + size <= BUFFER_LIMITS.bytesPerSender;
1066
+ if (size <= MAX_MANIFEST_BYTES && senderOk && this._bufferedBytes() + size <= BUFFER_LIMITS.bytes) {
1067
+ b.manifests.set(m.version, m);
1068
+ b.bytes = (b.bytes ?? 0) + size;
1069
+ }
1046
1070
  }
1047
1071
  map.set(key, b);
1048
1072
  return b;
1049
1073
  }
1050
1074
 
1075
+ /** Bytes buffered in all, or (with `sender`) in that sender's pending invitations. */
1076
+ _bufferedBytes(sender = null) {
1077
+ let n = 0;
1078
+ if (sender !== null) {
1079
+ for (const [k, b] of this.invites) if (k.slice(k.indexOf("|") + 1) === sender) n += b.bytes ?? 0;
1080
+ return n;
1081
+ }
1082
+ for (const map of [this.invites, this.recovery]) for (const b of map.values()) n += b.bytes ?? 0;
1083
+ return n;
1084
+ }
1085
+
1086
+ /** Before a new invitation key: drop the oldest pending one from the same sender, then the oldest overall, until both caps hold. */
1087
+ _makeRoomForInvite(key) {
1088
+ const sender = key.slice(key.indexOf("|") + 1);
1089
+ // V1 -069 fix: a pending invitation that names this receiver as invited is evicted only when every
1090
+ // pending one does; junk and invitations for someone else go first (oldest first within each class).
1091
+ const namesMe = (b) => [...b.manifests.values()].some((m) => Array.isArray(m.members)
1092
+ && m.members.some((r) => plain(r) && r.uuaid === this.self.uuaid && r.status === "invited" && r.key === this.self.key));
1093
+ const victim = (keys) => keys.find((k) => !namesMe(this.invites.get(k))) ?? keys[0];
1094
+ const fromSender = () => [...this.invites.keys()].filter((k) => k.slice(k.indexOf("|") + 1) === sender);
1095
+ while (fromSender().length >= BUFFER_LIMITS.invitesPerSender) this.invites.delete(victim(fromSender()));
1096
+ while (this.invites.size >= BUFFER_LIMITS.invites) this.invites.delete(victim([...this.invites.keys()]));
1097
+ }
1098
+
1051
1099
  _invitationStep(env, g, now, out) {
1052
1100
  const m = g.manifest;
1053
1101
  if (m.id !== g.id) return drop("unknown-group");
@@ -11,10 +11,41 @@
11
11
  */
12
12
  import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from "node:fs";
13
13
  import { dirname } from "node:path";
14
- import { randomBytes, createHash, generateKeyPairSync, sign, verify, createPublicKey, createPrivateKey, hkdfSync, createCipheriv, createDecipheriv } from "node:crypto";
14
+ import { randomBytes, createHash, generateKeyPairSync, sign, verify, createPublicKey, createPrivateKey, hkdfSync, scryptSync, createCipheriv, createDecipheriv } from "node:crypto";
15
15
  import { ed25519 } from "@noble/curves/ed25519.js";
16
16
 
17
+ // Version 1: the AES-256-GCM key is one HKDF-SHA256 of the passphrase, with no
18
+ // work factor. Version 2 (2.5.3): scrypt, for a key saved under a non-empty
19
+ // passphrase, so a copied key file cannot be guessed at HKDF speed. A key saved
20
+ // without a passphrase stays version 1: a work factor on the empty string adds
21
+ // nothing, and version 1 is what 2.5.2 and earlier, and @uuaid/pillar-client-node's
22
+ // CLI-keychain import, can read. Every version-1 file still opens (back-compat).
17
23
  const KEYCHAIN_VERSION = 1;
24
+ const KEYCHAIN_VERSION_SCRYPT = 2;
25
+ const HKDF_INFO = "uuaid-pillar-keychain-v1";
26
+ // OWASP's scrypt floor (N=2^17, r=8, p=1): about 0.2 s and 128 MiB per open.
27
+ export const SCRYPT_PARAMS = Object.freeze({ name: "scrypt", N: 131072, r: 8, p: 1 });
28
+ // A key file names its own scrypt parameters; these bounds keep a crafted file
29
+ // from asking for an unbounded amount of memory or time.
30
+ const SCRYPT_LIMITS = { minN: 16384, maxN: 1048576, maxR: 32, maxP: 16, maxMem: 512 * 1024 * 1024 };
31
+
32
+ /** The 32-byte AES key for `blob` (a parsed key file) and `passphrase`; throws on an unknown format. */
33
+ function fileKey(blob, passphrase) {
34
+ const pw = Buffer.from(passphrase ?? "", "utf-8");
35
+ const salt = Buffer.from(blob.salt, "hex");
36
+ if (blob.version === KEYCHAIN_VERSION) return Buffer.from(hkdfSync("sha256", pw, salt, HKDF_INFO, 32));
37
+ if (blob.version === KEYCHAIN_VERSION_SCRYPT) {
38
+ const k = blob.kdf ?? {};
39
+ const pow2 = Number.isInteger(k.N) && (k.N & (k.N - 1)) === 0;
40
+ if (k.name !== "scrypt" || !pow2 || k.N < SCRYPT_LIMITS.minN || k.N > SCRYPT_LIMITS.maxN
41
+ || !Number.isInteger(k.r) || k.r < 1 || k.r > SCRYPT_LIMITS.maxR || !Number.isInteger(k.p) || k.p < 1 || k.p > SCRYPT_LIMITS.maxP
42
+ || 128 * k.N * k.r > SCRYPT_LIMITS.maxMem) {
43
+ throw new Error("keychain kdf parameters are missing or out of bounds");
44
+ }
45
+ return scryptSync(pw, salt, 32, { N: k.N, r: k.r, p: k.p, maxmem: 128 * k.N * k.r + 16 * 1024 * 1024 });
46
+ }
47
+ throw new Error(`unsupported keychain version ${blob.version}`);
48
+ }
18
49
 
19
50
  /**
20
51
  * RFC 8032 / FIPS 186-5 rule for an Ed25519 public key: the canonical encoding
@@ -167,9 +198,7 @@ export class Keychain {
167
198
  load({ passphrase } = {}) {
168
199
  if (!this.exists()) throw new Error("keychain not initialized; run `pillar init` first");
169
200
  const blob = JSON.parse(readFileSync(this.path, "utf-8"));
170
- if (blob.version !== KEYCHAIN_VERSION) throw new Error(`unsupported keychain version ${blob.version}`);
171
- const salt = Buffer.from(blob.salt, "hex");
172
- const key = hkdfSync("sha256", Buffer.from(passphrase ?? "", "utf-8"), salt, "uuaid-pillar-keychain-v1", 32);
201
+ const key = fileKey(blob, passphrase);
173
202
  const iv = Buffer.from(blob.iv, "hex");
174
203
  const ct = Buffer.from(blob.ciphertext, "base64");
175
204
  const tag = Buffer.from(blob.tag, "hex");
@@ -194,19 +223,22 @@ export class Keychain {
194
223
  }
195
224
 
196
225
  /**
197
- * Save identity to disk, encrypted with the passphrase.
226
+ * Save identity to disk, encrypted with the passphrase: version 2 (scrypt)
227
+ * under a non-empty passphrase, version 1 (HKDF) without one.
198
228
  */
199
229
  save(identity, { passphrase } = {}) {
200
230
  const seedDer = identity.privateKey.export({ type: "pkcs8", format: "der" });
201
231
  const seed = seedDer.slice(seedDer.length - 32);
202
232
  const salt = randomBytes(16);
203
- const key = hkdfSync("sha256", Buffer.from(passphrase ?? "", "utf-8"), salt, "uuaid-pillar-keychain-v1", 32);
233
+ const scrypt = typeof passphrase === "string" && passphrase !== "";
234
+ const head = scrypt ? { version: KEYCHAIN_VERSION_SCRYPT, kdf: { ...SCRYPT_PARAMS } } : { version: KEYCHAIN_VERSION };
235
+ const key = fileKey({ ...head, salt: salt.toString("hex") }, passphrase);
204
236
  const iv = randomBytes(12);
205
237
  const cipher = createCipheriv("aes-256-gcm", Buffer.from(key), iv);
206
238
  const ct = Buffer.concat([cipher.update(seed), cipher.final()]);
207
239
  const tag = cipher.getAuthTag();
208
240
  const blob = {
209
- version: KEYCHAIN_VERSION,
241
+ ...head,
210
242
  uuaid: identity.uuaid,
211
243
  createdAt: identity.createdAt,
212
244
  salt: salt.toString("hex"),
@@ -217,7 +249,10 @@ export class Keychain {
217
249
  publicKeyHex: identity.publicKeyHex,
218
250
  };
219
251
  mkdirSync(dirname(this.path), { recursive: true });
220
- writeFileSync(this.path, JSON.stringify(blob, null, 2));
252
+ // Created owner-only (2.5.3): writing first and chmodding after left a moment
253
+ // in which a new key file had the umask's mode. The chmod still tightens a
254
+ // file that already existed.
255
+ writeFileSync(this.path, JSON.stringify(blob, null, 2), { mode: 0o600 });
221
256
  chmodSync(this.path, 0o600);
222
257
  this._identity = identity;
223
258
  }
@@ -63,6 +63,7 @@
63
63
  * and drops are detectable by sequence gaps + sender outbox audit.
64
64
  */
65
65
  import { createServer } from "node:http";
66
+ import { clientIpOf, DEFAULT_TRUSTED_PROXIES } from "./client-ip.mjs";
66
67
  import { createHash } from "node:crypto";
67
68
  import Database from "better-sqlite3";
68
69
  import { open as openEnvelope, envelopeSha as canonicalEnvelopeSha } from "./envelope.mjs";
@@ -112,6 +113,14 @@ export function parseCommunityWaits(value) {
112
113
  const MAX_PRIORITY_GOOD_PER_MIN = 600; // priority senders bill to their own per-IP bucket
113
114
  const CHECKPOINT_ATTEMPTS = 3; // TRUNCATE checkpoint tries per vacuum pass
114
115
  const CHECKPOINT_BUSY_MS = 250; // per try; a busy pass is retried next hour
116
+ // The longest envelope lifetime, and the latest deadline a row can hold. retain_until
117
+ // is an ISO-8601 string compared as text in vacuum(). Past year 9999 toISOString()
118
+ // writes "+010000-…", which sorts BELOW "2026-…", so the next pass deleted a row
119
+ // accepted with a long TTL (from about 2,912,144 days; above about 99,979,245
120
+ // toISOString() threw and every POST failed). Both bounds keep every deadline a
121
+ // four-digit year (2.5.3).
122
+ export const MAX_TTL_DAYS = 36500; // 100 years
123
+ const MAX_RETAIN_MS = Date.UTC(9999, 11, 31, 23, 59, 59, 999); // 9999-12-31T23:59:59.999Z
115
124
  /** Row columns a receipt is built from (plus the legacy `sha` the 202 has always echoed). */
116
125
  const ROW_COLUMNS = "seq, envelope_id, recipient, sender, sha, created_at, retain_until, envelope_sha";
117
126
 
@@ -153,12 +162,13 @@ const ENVELOPES_COLUMNS = `
153
162
  const ENVELOPES_INDEX = "create index if not exists idx_envelopes_recipient on envelopes(recipient, seq);";
154
163
 
155
164
  export class CarrierServer {
156
- constructor({ dbPath = "carrier.db", ttlDays = 14, cryptoInventory, trustedTierIssuers = [], keychain = null, publicUrl = null, secureDelete = true, receiptKeychain = null, communityInboxWaits = COMMUNITY_CONCURRENT_WAITS } = {}) {
165
+ constructor({ dbPath = "carrier.db", ttlDays = 14, cryptoInventory, trustedTierIssuers = [], keychain = null, publicUrl = null, secureDelete = true, receiptKeychain = null, communityInboxWaits = COMMUNITY_CONCURRENT_WAITS, trustedProxies = DEFAULT_TRUSTED_PROXIES } = {}) {
157
166
  // Every row's retain_until is created_at + ttlDays, so the TTL must be a
158
167
  // real positive duration (a NaN here used to surface only as a vacuum crash).
159
168
  if (typeof ttlDays !== "number" || !Number.isFinite(ttlDays) || ttlDays <= 0) {
160
169
  throw new Error(`ttlDays must be a positive number of days, not ${ttlDays}`);
161
170
  }
171
+ if (ttlDays > MAX_TTL_DAYS) throw new Error(`ttlDays must be at most ${MAX_TTL_DAYS} days (100 years), not ${ttlDays}`);
162
172
  // Receipt key: optional and separate from the seed `keychain`. Fail closed
163
173
  // on a key that is not loaded or not a strict Ed25519 key, rather than
164
174
  // running a carrier that silently signs nothing or signs under a weak key.
@@ -193,6 +203,10 @@ export class CarrierServer {
193
203
  const cols = new Set(this.db.prepare("pragma table_info(envelopes)").all().map(c => c.name));
194
204
  if (!cols.has("retain_until")) this.db.exec("alter table envelopes add column retain_until text");
195
205
  if (!cols.has("envelope_sha")) this.db.exec("alter table envelopes add column envelope_sha text");
206
+ // A deadline written past year 9999 by an earlier build ("+0YYYYY-…") would
207
+ // sort before today and be deleted on the next pass: it gets the latest
208
+ // four-digit deadline instead, which keeps the row as long as it was promised.
209
+ this.db.prepare("update envelopes set retain_until = ? where retain_until like '+%'").run(new Date(MAX_RETAIN_MS).toISOString());
196
210
  this.db.prepare("insert or ignore into seed_stats (k, v) values ('first_seen', ?)")
197
211
  .run(new Date().toISOString());
198
212
  // Secure delete promises an expired envelope leaves the disk; a kept backup
@@ -223,6 +237,7 @@ export class CarrierServer {
223
237
  }
224
238
  }
225
239
  this.ttlDays = ttlDays;
240
+ this.trustedProxies = [...trustedProxies]; // whose X-Forwarded-For counts (client-ip.mjs)
226
241
  this._backfillRetention(); // @rule carrier.retention-backfill
227
242
  this.cryptoInventory = cryptoInventory ?? { ed25519: "active" };
228
243
  this.startedAt = Date.now();
@@ -247,11 +262,15 @@ export class CarrierServer {
247
262
  this.receiptCarrier = this.receiptKeychain ? carrierUuaidFromKey(this.receiptKeychain._identity.publicKeyHex) : null;
248
263
  }
249
264
 
250
- /** created_at + the current TTL, as ISO-8601 UTC with milliseconds; null if created_at does not parse. */
265
+ /**
266
+ * created_at + the current TTL, as ISO-8601 UTC with milliseconds; null if
267
+ * created_at does not parse. Never later than 9999-12-31T23:59:59.999Z, so
268
+ * the deadline always compares correctly as text (MAX_RETAIN_MS).
269
+ */
251
270
  _retainUntilFor(createdAt) {
252
271
  const ms = Date.parse(createdAt);
253
272
  if (!Number.isFinite(ms)) return null;
254
- return new Date(ms + this.ttlDays * 86400_000).toISOString();
273
+ return new Date(Math.min(ms + this.ttlDays * 86400_000, MAX_RETAIN_MS)).toISOString();
255
274
  }
256
275
 
257
276
  /**
@@ -393,9 +412,7 @@ export class CarrierServer {
393
412
 
394
413
  /** F2: best-effort client identity, nginx-aware (XFF set by proxy). */
395
414
  _clientIp(req) {
396
- const fwd = req.headers["x-forwarded-for"];
397
- if (fwd) return String(fwd).split(",")[0].trim();
398
- return req.socket.remoteAddress ?? "unknown";
415
+ return clientIpOf(req, this.trustedProxies);
399
416
  }
400
417
 
401
418
  /** F2: sliding-window allow. Returns false when over budget. */
@@ -682,6 +699,13 @@ export class CarrierServer {
682
699
  }
683
700
  }
684
701
 
702
+ /**
703
+ * Listen on `port` and `host`; or take over a listener that is already bound,
704
+ * passed instead of the port (a net.Server, or anything Node's listen(handle)
705
+ * accepts), in which case `host` is ignored. pillar-seed binds once before it
706
+ * mints its key and hands that listener here, so the port cannot be taken in
707
+ * between (2.5.3).
708
+ */
685
709
  listen(port = 0, host = "127.0.0.1") {
686
710
  this.server = createServer(async (req, res) => {
687
711
  try {
@@ -719,7 +743,8 @@ export class CarrierServer {
719
743
  }
720
744
  });
721
745
  return new Promise((resolve) => {
722
- this.server.listen(port, host, () => resolve(this.server.address()));
746
+ if (port !== null && typeof port === "object") this.server.listen(port, () => resolve(this.server.address()));
747
+ else this.server.listen(port, host, () => resolve(this.server.address()));
723
748
  });
724
749
  }
725
750
 
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The client address a per-IP budget is charged to (2.5.3, AC7-Kimi a).
3
+ *
4
+ * Up to 2.5.2 the carrier and the directory took the FIRST X-Forwarded-For
5
+ * entry from anyone. Behind a proxy that appends to the header, a client could
6
+ * then pick its own rate bucket by sending one. Now X-Forwarded-For counts only
7
+ * when the TCP peer is a trusted proxy (by default this machine: 127.0.0.1 and
8
+ * ::1), and the address taken is the right-most one that is not itself a
9
+ * trusted proxy: what the nearest untrusted hop really was. Behind a proxy that
10
+ * replaces the header (the HOSTING-LIMITS §5 templates) that is the same single
11
+ * address as before.
12
+ */
13
+ import { isIP } from "node:net";
14
+
15
+ export const DEFAULT_TRUSTED_PROXIES = Object.freeze(["127.0.0.1", "::1"]);
16
+
17
+ /** "::ffff:127.0.0.1" -> "127.0.0.1"; anything else as given, trimmed. */
18
+ function norm(addr) {
19
+ const a = String(addr ?? "").trim();
20
+ return a.toLowerCase().startsWith("::ffff:") && isIP(a.slice(7)) === 4 ? a.slice(7) : a;
21
+ }
22
+
23
+ /**
24
+ * Parse a comma-separated list of proxy addresses (exact IPv4 or IPv6
25
+ * addresses; no ranges). Throws on anything that is not an address, naming it.
26
+ */
27
+ export function parseTrustedProxies(value) {
28
+ if (value === undefined || value === null) return [...DEFAULT_TRUSTED_PROXIES];
29
+ const list = String(value).split(",").map((s) => s.trim()).filter(Boolean);
30
+ for (const a of list) {
31
+ if (!isIP(norm(a))) throw new Error(`--trusted-proxy takes IP addresses separated by commas, not ${JSON.stringify(a)}`);
32
+ }
33
+ return list.map(norm);
34
+ }
35
+
36
+ /** The address to charge for `req`, given the trusted proxy list. */
37
+ export function clientIpOf(req, trusted = DEFAULT_TRUSTED_PROXIES) {
38
+ const peer = norm(req.socket?.remoteAddress);
39
+ const trust = new Set(trusted.map(norm));
40
+ const fwd = req.headers?.["x-forwarded-for"];
41
+ if (!fwd || !trust.has(peer)) return peer || "unknown";
42
+ const hops = String(fwd).split(",").map(norm).filter(Boolean);
43
+ for (let i = hops.length - 1; i >= 0; i--) if (!trust.has(hops[i])) return hops[i];
44
+ return peer || "unknown";
45
+ }
@@ -31,7 +31,7 @@ import { dcutr } from "@libp2p/dcutr";
31
31
  import { autoNAT } from "@libp2p/autonat";
32
32
  import { ping } from "@libp2p/ping";
33
33
  import { privateKeyFromRaw, publicKeyFromRaw } from "@libp2p/crypto/keys";
34
- import { peerIdFromPublicKey } from "@libp2p/peer-id";
34
+ import { peerIdFromPublicKey, peerIdFromPrivateKey } from "@libp2p/peer-id";
35
35
  import { createHash } from "node:crypto";
36
36
 
37
37
  export const PILLAR_PROTOCOL = "/uuaid/pillar/1.0.0";
@@ -98,6 +98,18 @@ export function uuaidToDhtKey(uuaid) {
98
98
  return createHash("sha256").update(uuaid, "utf-8").digest();
99
99
  }
100
100
 
101
+ /**
102
+ * The libp2p PeerId of a node that createTransport starts with this 32-byte
103
+ * seed. privateKeyFromRaw reads 32 raw bytes as a secp256k1 key, so the PeerId
104
+ * cannot be derived from the identity's Ed25519 public key; `pillar id` uses
105
+ * this to print it without starting a node (2.5.3).
106
+ */
107
+ export function peerIdFromSeedHex(seedHex) {
108
+ const seed = Buffer.from(seedHex, "hex");
109
+ if (seed.length !== 32) throw new Error("seedHex must be 32 raw bytes hex");
110
+ return peerIdFromPrivateKey(privateKeyFromRaw(seed));
111
+ }
112
+
101
113
  /**
102
114
  * Convert a raw Ed25519 public key hex to a libp2p PeerId. This is how
103
115
  * a peer given only a UUAID's public key can dial that peer.