@uuaid/pillar 2.5.2 → 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.
- package/HOSTING-LIMITS.md +58 -43
- package/README.md +29 -12
- package/bin/carrier.mjs +35 -9
- package/bin/pillar-directory.mjs +6 -4
- package/bin/pillar-escrow.mjs +7 -7
- package/bin/pillar-responder.mjs +2 -2
- package/bin/pillar-seed.mjs +36 -20
- package/bin/pillar.mjs +64 -22
- package/package.json +1 -1
- package/src/blob/blob.mjs +3 -0
- package/src/blob/broker.mjs +20 -0
- package/src/blob/store.mjs +9 -2
- package/src/escrow/escrow-service.mjs +44 -12
- package/src/escrow/terms.mjs +35 -8
- package/src/escrow/token-registry.mjs +3 -3
- package/src/groups-v2.mjs +51 -3
- package/src/identity/keychain.mjs +43 -8
- package/src/net/carrier-server.mjs +32 -7
- package/src/net/client-ip.mjs +45 -0
- package/src/net/transport.mjs +13 -1
- package/src/observability.mjs +2 -2
- package/src/pillar.mjs +32 -13
- package/src/sqlite-rekey.mjs +3 -2
package/bin/pillar.mjs
CHANGED
|
@@ -34,7 +34,8 @@ import { mkdirSync, existsSync, readFileSync, writeFileSync, renameSync } from "
|
|
|
34
34
|
import { join, dirname } from "node:path";
|
|
35
35
|
import { homedir } from "node:os";
|
|
36
36
|
import { argv, exit } from "node:process";
|
|
37
|
-
import { Keychain, mintNamespace, SELF_CERTIFYING_NAMESPACES } from "../src/identity/keychain.mjs";
|
|
37
|
+
import { Keychain, mintNamespace, SELF_CERTIFYING_NAMESPACES, localIdFromKey } from "../src/identity/keychain.mjs";
|
|
38
|
+
import { peerIdFromSeedHex } from "../src/net/transport.mjs";
|
|
38
39
|
import { Pillar } from "../src/pillar.mjs";
|
|
39
40
|
import { loadFleetAddressBook, inspectFleetFile, resolveRecipient, explainMissingKey } from "../src/address-book.mjs";
|
|
40
41
|
import { loadTrustPolicy, POLICIES } from "../src/identity/trust.mjs";
|
|
@@ -211,7 +212,7 @@ function writeRuntimeFile(pillar, home) {
|
|
|
211
212
|
pid: process.pid,
|
|
212
213
|
startedAt: new Date().toISOString(),
|
|
213
214
|
};
|
|
214
|
-
writeFileSync(join(home, "runtime.json"), JSON.stringify(rt, null, 2));
|
|
215
|
+
writeFileSync(join(home, "runtime.json"), JSON.stringify(rt, null, 2), { mode: 0o600 });
|
|
215
216
|
}
|
|
216
217
|
|
|
217
218
|
// Carrier list + address book merge from a fetched directory — shared by
|
|
@@ -238,7 +239,7 @@ function mergeDirectoryAgents(home, d) {
|
|
|
238
239
|
};
|
|
239
240
|
if (!prev[key]) added++;
|
|
240
241
|
}
|
|
241
|
-
writeFileSync(fleetPath, JSON.stringify({ fleet }, null, 2));
|
|
242
|
+
writeFileSync(fleetPath, JSON.stringify({ fleet }, null, 2), { mode: 0o600 });
|
|
242
243
|
return { count: Object.keys(fleet).length, added };
|
|
243
244
|
}
|
|
244
245
|
|
|
@@ -277,7 +278,7 @@ async function cmdInit(args) {
|
|
|
277
278
|
const cfgPath = join(home, "config.json");
|
|
278
279
|
const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf-8")) : {};
|
|
279
280
|
cfg.carriers = list;
|
|
280
|
-
writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
|
|
281
|
+
writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 });
|
|
281
282
|
console.log(`carriers refreshed from ${args.directory}: ${list.join(", ")}`);
|
|
282
283
|
const ab = mergeDirectoryAgents(home, d);
|
|
283
284
|
if (ab) console.log(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)`);
|
|
@@ -331,7 +332,7 @@ async function cmdInit(args) {
|
|
|
331
332
|
} else if (args.carriers) {
|
|
332
333
|
cfg.carriers = args.carriers.split(",").map(s => s.trim()).filter(Boolean);
|
|
333
334
|
}
|
|
334
|
-
writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2));
|
|
335
|
+
writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2), { mode: 0o600 });
|
|
335
336
|
console.log(`initialized pillar at ${home}`);
|
|
336
337
|
console.log(`uuaid: ${id.uuaid}`);
|
|
337
338
|
console.log(`publicKey: ${id.publicKeyHex}`);
|
|
@@ -415,20 +416,59 @@ async function confirmAndArchiveIdentity(home, old, args) {
|
|
|
415
416
|
return { uuaid: current, dir };
|
|
416
417
|
}
|
|
417
418
|
|
|
419
|
+
/**
|
|
420
|
+
* pillar id — read-only (2.5.3). It reads only the key file's public part and
|
|
421
|
+
* config.json: no passphrase, no mailbox, no libp2p node. Up to 2.5.2 it ran
|
|
422
|
+
* loadPillar + start(), which opened (and migrated) the mailbox and started a
|
|
423
|
+
* node on this identity, beside any `pillar recv` already running on it.
|
|
424
|
+
* The peerId needs the key itself (createTransport reads the seed as a
|
|
425
|
+
* secp256k1 key), so it is printed when the key opens with PILLAR_PASSPHRASE
|
|
426
|
+
* (default empty); opening it only decrypts it in memory. Live addresses come
|
|
427
|
+
* from runtime.json, written by a running `pillar recv`.
|
|
428
|
+
*/
|
|
418
429
|
async function cmdId(args) {
|
|
419
|
-
const
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
430
|
+
const home = homePath(args);
|
|
431
|
+
const kc = new Keychain(join(home, "keychain.json"));
|
|
432
|
+
if (!kc.exists()) {
|
|
433
|
+
console.error(`no pillar found at ${home}. run: pillar init`);
|
|
434
|
+
exit(2);
|
|
435
|
+
}
|
|
436
|
+
let pub;
|
|
437
|
+
try { pub = kc.publicView(); } catch (e) {
|
|
438
|
+
console.error(`${kc.path} is damaged or is not a key file (${String(e.message).replace(/\s+/g, " ").slice(0, 120)})`);
|
|
439
|
+
exit(2);
|
|
440
|
+
}
|
|
441
|
+
const parts = typeof pub?.uuaid === "string" ? pub.uuaid.split(":") : [];
|
|
442
|
+
if (parts.length < 4 || typeof pub.publicKeyHex !== "string" || !/^[0-9a-f]{64}$/i.test(pub.publicKeyHex)
|
|
443
|
+
|| parts[3] !== localIdFromKey(Buffer.from(pub.publicKeyHex, "hex"))) {
|
|
444
|
+
// The same integrity rule as Keychain.load(): the uuaid's local id comes from the key.
|
|
445
|
+
console.error(`${kc.path} is damaged or is not a key file (its uuaid does not belong to its key)`);
|
|
446
|
+
exit(2);
|
|
447
|
+
}
|
|
448
|
+
const cfg = readConfig(home);
|
|
449
|
+
console.log(`uuaid: ${pub.uuaid}`);
|
|
450
|
+
console.log(`publicKey: ${pub.publicKeyHex}`);
|
|
451
|
+
if (args["carrier-only"] || cfg.carrierOnly === true) {
|
|
428
452
|
console.log(`mode: carrier-only (no libp2p)`);
|
|
453
|
+
} else {
|
|
454
|
+
let peerId = null;
|
|
455
|
+
try {
|
|
456
|
+
const der = kc.load({ passphrase: process.env.PILLAR_PASSPHRASE ?? "" }).privateKey.export({ type: "pkcs8", format: "der" });
|
|
457
|
+
peerId = peerIdFromSeedHex(Buffer.from(der.slice(der.length - 32)).toString("hex")).toString();
|
|
458
|
+
} catch { /* wrong or missing passphrase: the public part above is still right */ }
|
|
459
|
+
console.log(`peerId: ${peerId ?? "unknown: the key did not open (set PILLAR_PASSPHRASE to show it)"}`);
|
|
460
|
+
let rt = null;
|
|
461
|
+
try { rt = JSON.parse(readFileSync(join(home, "runtime.json"), "utf-8")); } catch { /* none, or unreadable */ }
|
|
462
|
+
if (rt?.uuaid === pub.uuaid && Array.isArray(rt.addrs) && rt.addrs.length) {
|
|
463
|
+
console.log(`addrs: (from runtime.json, written by pillar recv pid ${rt.pid ?? "?"} at ${rt.startedAt ?? "?"})`);
|
|
464
|
+
for (const a of rt.addrs) console.log(` ${a}`);
|
|
465
|
+
} else {
|
|
466
|
+
console.log(`addrs: none published (pillar id starts nothing; a running pillar recv writes its addresses to runtime.json)`);
|
|
467
|
+
}
|
|
429
468
|
}
|
|
430
|
-
|
|
431
|
-
|
|
469
|
+
const carriers = args.carrier ? [args.carrier]
|
|
470
|
+
: (process.env.PILLAR_CARRIERS ? process.env.PILLAR_CARRIERS.split(",") : (cfg.carriers ?? []));
|
|
471
|
+
if (carriers.length) console.log(`carriers: ${carriers.join(", ")}`);
|
|
432
472
|
}
|
|
433
473
|
|
|
434
474
|
async function cmdSend(args) {
|
|
@@ -458,15 +498,17 @@ async function cmdSend(args) {
|
|
|
458
498
|
exit(1);
|
|
459
499
|
}
|
|
460
500
|
try {
|
|
461
|
-
const
|
|
501
|
+
const sent = await p.send({
|
|
462
502
|
recipient, kind, payload,
|
|
463
503
|
recipientPublicKey: toKey, // explicit key for peers outside fleet.json
|
|
464
504
|
resolveTimeoutMs: 5000,
|
|
465
505
|
});
|
|
506
|
+
const { envelope, delivery } = sent;
|
|
466
507
|
console.log(`sent envelope ${envelope.id}`);
|
|
467
508
|
console.log(` to: ${recipient}${recipient !== recipientArg ? ` (${recipientArg})` : ""}`);
|
|
468
509
|
console.log(` kind: ${kind}`);
|
|
469
|
-
if (
|
|
510
|
+
if (sent.direct?.peerId) console.log(` via peerId: ${sent.direct.peerId}${sent.confirmed === false ? " (a direct stream only: nothing confirms it arrived)" : ""}`);
|
|
511
|
+
if (sent.confirmed === false) console.error(`warning: no carrier accepted ${envelope.id}${sent.carrierError ? ` (${sent.carrierError.message})` : ""}; it was written to a direct stream, which is not a receipt, so it stays pending until ${recipient} acks it.`);
|
|
470
512
|
if (delivery?.carrier) console.log(` accepted by carrier ${delivery.carrier} (seq ${delivery.seq}) — that is the carrier's receipt, not the recipient's`);
|
|
471
513
|
if (args["wait-ack"] !== undefined) {
|
|
472
514
|
const secs = args["wait-ack"] === true ? 60 : Number(args["wait-ack"]);
|
|
@@ -1253,7 +1295,7 @@ async function cmdReceipts(args) {
|
|
|
1253
1295
|
console.error("usage: pillar receipts [on|off] | [delivered on|off] | [read on|off]");
|
|
1254
1296
|
exit(2);
|
|
1255
1297
|
}
|
|
1256
|
-
if (a !== undefined) { cfg.receipts = r; writeFileSync(cfgPath, JSON.stringify(cfg, null, 2)); }
|
|
1298
|
+
if (a !== undefined) { cfg.receipts = r; writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 }); }
|
|
1257
1299
|
console.log(`delivery acks: ${r.delivered ? "on" : "off"} read receipts: ${r.read ? "on" : "off"} (${cfgPath})`);
|
|
1258
1300
|
console.log(`sent only to contacts (fleet.json, trust allow, members of groups you accepted); read receipts go out on --mark-read.`);
|
|
1259
1301
|
console.log(`read receipts are symmetric: with them off, incoming read receipts are ignored too. Delivery acks from others are always recorded.`);
|
|
@@ -1269,7 +1311,7 @@ async function cmdTrust(args) {
|
|
|
1269
1311
|
const tPath = join(home, "trust.json");
|
|
1270
1312
|
const t = loadTrustPolicy(home);
|
|
1271
1313
|
const sub = args._[1];
|
|
1272
|
-
const save = () => writeFileSync(tPath, JSON.stringify({ policy: t.policy, allow: t.allow, block: t.block }, null, 2));
|
|
1314
|
+
const save = () => writeFileSync(tPath, JSON.stringify({ policy: t.policy, allow: t.allow, block: t.block }, null, 2), { mode: 0o600 });
|
|
1273
1315
|
if (!sub) {
|
|
1274
1316
|
console.log(`policy: ${t.policy}${t.exists ? "" : " (no trust.json — default)"}`);
|
|
1275
1317
|
console.log(`allow (${t.allow.length}):`); for (const u of t.allow) console.log(` ${u}`);
|
|
@@ -1374,7 +1416,7 @@ async function cmdTier(args) {
|
|
|
1374
1416
|
maxBodyBytes: args["max-body"] ? Number(args["max-body"]) : undefined,
|
|
1375
1417
|
});
|
|
1376
1418
|
const out = typeof args.out === "string" ? args.out : `tier-grant-${grantFingerprint(grant)}.json`;
|
|
1377
|
-
writeFileSync(out, JSON.stringify(grant, null, 2));
|
|
1419
|
+
writeFileSync(out, JSON.stringify(grant, null, 2), { mode: 0o600 });
|
|
1378
1420
|
console.log(`issued ${tier} grant for ${uuaid}`);
|
|
1379
1421
|
console.log(` rate ${grant.envelopesPerMin}/min, maxBody ${grant.maxBodyBytes}B, expires ${expires}`);
|
|
1380
1422
|
console.log(` issuer ${grant.issuer}`);
|
|
@@ -1393,7 +1435,7 @@ async function cmdTier(args) {
|
|
|
1393
1435
|
}
|
|
1394
1436
|
const v = verifyTierGrant(g, [g.issuer]); // structural check (sig by named issuer, expiry, ceilings)
|
|
1395
1437
|
if (!v.ok) { console.error(`grant invalid: ${v.reason}`); exit(1); }
|
|
1396
|
-
writeFileSync(join(home, "tier-grant.json"), JSON.stringify(g, null, 2));
|
|
1438
|
+
writeFileSync(join(home, "tier-grant.json"), JSON.stringify(g, null, 2), { mode: 0o600 });
|
|
1397
1439
|
console.log(`installed ${g.tier} grant (fingerprint ${grantFingerprint(g)}) — sent with every carrier deliver`);
|
|
1398
1440
|
console.log(`note: budgets rise only at carriers that trust issuer ${g.issuer.slice(0, 16)}…`);
|
|
1399
1441
|
return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uuaid/pillar",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.3",
|
|
4
4
|
"description": "Pillar (Protocol for Inter-agent Linked Ledger And Relay) — the secure delivery layer of UACP, the Universal Agent Communication Protocol. UACP = UUAID (identity) + Envelope (signed, encrypted container) + Pillar (relay, mailbox, routing, store-and-forward). Reference implementation of the UACP delivery layer; includes VDA-1 (IAASO-3901, in ballot) delivery attestation and a blind escrow for the Zilligon ZGN / EVM rails.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
package/src/blob/blob.mjs
CHANGED
|
@@ -379,6 +379,9 @@ export async function prepareBlobSend(keychain, { data, envelopeId, recipient, t
|
|
|
379
379
|
try {
|
|
380
380
|
await store.put(ref.object, ct);
|
|
381
381
|
} catch (e) {
|
|
382
|
+
// The reservation will never be finalized: give it back where the broker
|
|
383
|
+
// can take it (2.5.3; the hosted broker has no such call and lets it expire).
|
|
384
|
+
if (broker && challengeId && typeof broker.release === "function") await broker.release({ challengeId }).catch(() => {});
|
|
382
385
|
if (e instanceof BlobError) throw e;
|
|
383
386
|
throw new BlobUploadError(`blob upload failed for ${ref.object}: ${e.message}`, e);
|
|
384
387
|
}
|
package/src/blob/broker.mjs
CHANGED
|
@@ -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 });
|
package/src/blob/store.mjs
CHANGED
|
@@ -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) {
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
|
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 (!
|
|
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 });
|
package/src/escrow/terms.mjs
CHANGED
|
@@ -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
|
-
|
|
69
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
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");
|