@uuaid/pillar 2.5.2 → 2.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOSTING-LIMITS.md +58 -43
- package/README.md +37 -18
- 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/seed-registry.mjs +385 -41
- 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
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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,
|
|
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
|
+
}
|