@uuaid/pillar 2.6.0 → 2.7.0
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 +12 -0
- package/README.md +201 -5
- package/bin/carrier.mjs +72 -2
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +280 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +504 -255
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +308 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +308 -92
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +725 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +195 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +549 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +296 -0
- package/src/vnext/jsonl-mailbox.mjs +1066 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +86 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +251 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pillar vNext B8 — signed TTFA cohort reports (`pillar-ttfa-report/1`) and signed
|
|
3
|
+
* daily registry aggregates (`pillar-registry-stats/1`).
|
|
4
|
+
*
|
|
5
|
+
* The metric, defined so it can be measured without telemetry (spec §"The metric"):
|
|
6
|
+
*
|
|
7
|
+
* - `pillar-ttfa-report/1` is published by a cohort operator and carries ONLY
|
|
8
|
+
* cohort-level values: `metric`, `period`, `runtime`, `method`, `n`, `p50`, `p95`.
|
|
9
|
+
* It never names a measured agent, never carries a per-agent timestamp, an IP,
|
|
10
|
+
* or a carrier. `method` is one of the closed `TTFA_METHODS`. A sample below
|
|
11
|
+
* `TTFA_MIN_N` is refused. These are format rules: a valid signature proves only
|
|
12
|
+
* that the cohort key's holder published the values. It does not prove `n`
|
|
13
|
+
* distinct participants, and it cannot rule out inference across reports.
|
|
14
|
+
* - `pillar-registry-stats/1` is published once per registry per UTC day and carries
|
|
15
|
+
* ONLY counts the registry already serves publicly: live lineages and listings.
|
|
16
|
+
* The registry cannot see greeter knocks, so it never asserts such a count; the
|
|
17
|
+
* aggregate's counts are exactly the public projection's counts.
|
|
18
|
+
*
|
|
19
|
+
* Both artifacts are signed over a version-domain-separated, JCS-canonical preimage
|
|
20
|
+
* and are verified offline by `pillar verify` — no network access, no telemetry.
|
|
21
|
+
*
|
|
22
|
+
* Only primitives exported by the frozen vendored core are used here, so
|
|
23
|
+
* `pillar-core.mjs` stays byte-identical and B8 adds no runtime bytes to the core.
|
|
24
|
+
*/
|
|
25
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
26
|
+
import { closeSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
import {
|
|
29
|
+
VERDICT_VERSION,
|
|
30
|
+
isKeyDerivedUuaid,
|
|
31
|
+
isStrictEd25519PublicKey,
|
|
32
|
+
keyRecord,
|
|
33
|
+
signBytes,
|
|
34
|
+
signingBytes,
|
|
35
|
+
verifyBytesStrict,
|
|
36
|
+
} from "../vendor/pillar-core.mjs";
|
|
37
|
+
|
|
38
|
+
export const TTFA_REPORT_VERSION = "pillar-ttfa-report/1";
|
|
39
|
+
export const REGISTRY_STATS_VERSION = "pillar-registry-stats/1";
|
|
40
|
+
|
|
41
|
+
/** Verdict `type` values this module emits (see docs/vnext/AMENDMENT-B8-ttfa-stats.md). */
|
|
42
|
+
export const TTFA_VERDICT_TYPE = "ttfa-report";
|
|
43
|
+
export const REGISTRY_STATS_VERDICT_TYPE = "registry-stats";
|
|
44
|
+
|
|
45
|
+
/** The two metrics the spec defines (§"The metric"). */
|
|
46
|
+
export const TTFA_METRICS = Object.freeze(["greeter", "peer"]);
|
|
47
|
+
/** Runtime buckets from the §7 runtime matrix — coarse enough to name no version. */
|
|
48
|
+
export const TTFA_RUNTIME_BUCKETS = Object.freeze(["node", "deno", "bun", "browser", "wasm", "workers"]);
|
|
49
|
+
/** The closed set of `method` values. Any other value is `bad-method`. */
|
|
50
|
+
export const TTFA_METHODS = Object.freeze(["ci-canary", "field-cohort"]);
|
|
51
|
+
/** Privacy floor: a cohort report below this sample size is refused. */
|
|
52
|
+
export const TTFA_MIN_N = 10;
|
|
53
|
+
|
|
54
|
+
/** Tool stamped on B8 verdicts (same string the `pillar verify` CLI uses). */
|
|
55
|
+
export const STATS_VERDICT_TOOL = "pillar/2.7.0";
|
|
56
|
+
|
|
57
|
+
/** Closed key set of `pillar-ttfa-report/1`. */
|
|
58
|
+
export const TTFA_REPORT_KEYS = Object.freeze([
|
|
59
|
+
"v",
|
|
60
|
+
"cohort",
|
|
61
|
+
"publicKey",
|
|
62
|
+
"metric",
|
|
63
|
+
"period",
|
|
64
|
+
"runtime",
|
|
65
|
+
"method",
|
|
66
|
+
"n",
|
|
67
|
+
"p50",
|
|
68
|
+
"p95",
|
|
69
|
+
"sig",
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
/** Closed key set of `pillar-registry-stats/1`. */
|
|
73
|
+
export const REGISTRY_STATS_KEYS = Object.freeze([
|
|
74
|
+
"v",
|
|
75
|
+
"registry",
|
|
76
|
+
"publicKey",
|
|
77
|
+
"day",
|
|
78
|
+
"liveLineages",
|
|
79
|
+
"listings",
|
|
80
|
+
"sig",
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
const UUAID_RE = /^uuaid:[a-z0-9-]+:[a-z0-9-]+:[a-z0-9][a-z0-9-]*$/;
|
|
84
|
+
const HEX64_RE = /^[0-9a-f]{64}$/;
|
|
85
|
+
const HEX128_RE = /^[0-9a-f]{128}$/;
|
|
86
|
+
const PERIOD_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
|
|
87
|
+
const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
88
|
+
const IPV4_RE = /\b(?:\d{1,3}\.){3}\d{1,3}\b/;
|
|
89
|
+
const TIMESTAMP_RE = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
|
|
90
|
+
const URL_RE = /\bhttps?:\/\//i;
|
|
91
|
+
|
|
92
|
+
function isPlainObject(v) {
|
|
93
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function hasExactKeys(obj, keys) {
|
|
97
|
+
const own = Object.keys(obj);
|
|
98
|
+
if (own.length !== keys.length) return false;
|
|
99
|
+
for (const k of own) if (!keys.includes(k)) return false;
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isUtcDay(value) {
|
|
104
|
+
if (typeof value !== "string" || !DAY_RE.test(value)) return false;
|
|
105
|
+
const ms = Date.parse(`${value}T00:00:00Z`);
|
|
106
|
+
if (!Number.isFinite(ms)) return false;
|
|
107
|
+
return new Date(ms).toISOString().slice(0, 10) === value;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** UTC month bucket (`YYYY-MM`) of an instant. */
|
|
111
|
+
export function utcMonth(now = new Date()) {
|
|
112
|
+
const ms = now instanceof Date ? now.getTime() : Date.parse(String(now));
|
|
113
|
+
const d = new Date(Number.isFinite(ms) ? ms : Date.now());
|
|
114
|
+
return d.toISOString().slice(0, 7);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** UTC day (`YYYY-MM-DD`) of an instant. */
|
|
118
|
+
export function utcDay(now = new Date()) {
|
|
119
|
+
const ms = now instanceof Date ? now.getTime() : Date.parse(String(now));
|
|
120
|
+
const d = new Date(Number.isFinite(ms) ? ms : Date.now());
|
|
121
|
+
return d.toISOString().slice(0, 10);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Normalize a signer into `{ uuaid, publicKey, sign }`.
|
|
126
|
+
*
|
|
127
|
+
* Accepts a `Keychain` (`{ _identity, sign }`), a seed signer
|
|
128
|
+
* (`{ uuaid, publicKeyHex, seedHex }`), or a callback signer
|
|
129
|
+
* (`{ uuaid, publicKey, sign(bytes) }`).
|
|
130
|
+
*/
|
|
131
|
+
export function normalizeStatsSigner(signer) {
|
|
132
|
+
if (!signer) return null;
|
|
133
|
+
if (signer._identity && typeof signer.sign === "function") {
|
|
134
|
+
const id = signer._identity;
|
|
135
|
+
const pub = (id.publicKeyHex ?? id.publicKey ?? "").toLowerCase();
|
|
136
|
+
if (typeof id.uuaid !== "string" || !HEX64_RE.test(pub)) return null;
|
|
137
|
+
return {
|
|
138
|
+
uuaid: id.uuaid,
|
|
139
|
+
publicKey: pub,
|
|
140
|
+
sign: (bytes) => Buffer.from(signer.sign(Buffer.from(bytes))).toString("hex"),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const pub = (signer.publicKey ?? signer.publicKeyHex ?? "").toLowerCase();
|
|
144
|
+
if (typeof signer.sign === "function" && typeof signer.uuaid === "string" && HEX64_RE.test(pub)) {
|
|
145
|
+
return {
|
|
146
|
+
uuaid: signer.uuaid,
|
|
147
|
+
publicKey: pub,
|
|
148
|
+
sign: (bytes) => {
|
|
149
|
+
const out = signer.sign(Buffer.from(bytes));
|
|
150
|
+
return typeof out === "string" ? out.toLowerCase() : Buffer.from(out).toString("hex");
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const seed = (signer.seedHex ?? "").toLowerCase();
|
|
155
|
+
if (typeof signer.uuaid === "string" && HEX64_RE.test(pub) && HEX64_RE.test(seed)) {
|
|
156
|
+
return {
|
|
157
|
+
uuaid: signer.uuaid,
|
|
158
|
+
publicKey: pub,
|
|
159
|
+
sign: (bytes) => signBytes(seed, new Uint8Array(bytes)),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Sign a body over its canonical, version-domain-separated preimage. */
|
|
166
|
+
function signBody(body, norm) {
|
|
167
|
+
const sig = norm.sign(signingBytes(body));
|
|
168
|
+
return typeof sig === "string" ? sig.toLowerCase() : Buffer.from(sig).toString("hex");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function verdict(type, subject, v, reasons, facts, now) {
|
|
172
|
+
return {
|
|
173
|
+
v: VERDICT_VERSION,
|
|
174
|
+
type,
|
|
175
|
+
...(subject !== undefined ? { subject } : {}),
|
|
176
|
+
verdict: v,
|
|
177
|
+
reasons,
|
|
178
|
+
facts,
|
|
179
|
+
checkedAt: now,
|
|
180
|
+
resolved: false,
|
|
181
|
+
tool: STATS_VERDICT_TOOL,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function fail(type, subject, reasons, now, facts = {}) {
|
|
186
|
+
return verdict(type, subject, "invalid", reasons, facts, now);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function checkNow(opts) {
|
|
190
|
+
return typeof opts?.now === "string" ? opts.now : new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/* -------------------------------------------------------------------------- */
|
|
194
|
+
/* pillar-ttfa-report/1 */
|
|
195
|
+
/* -------------------------------------------------------------------------- */
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Privacy lint for a TTFA report body.
|
|
199
|
+
*
|
|
200
|
+
* A cohort report may never carry a per-agent identifier, a precise timestamp, an
|
|
201
|
+
* IP, or a carrier URL. Only the publishing cohort's own uuaid may appear.
|
|
202
|
+
*/
|
|
203
|
+
export function ttfaPrivacyViolations(obj) {
|
|
204
|
+
const violations = [];
|
|
205
|
+
if (!isPlainObject(obj)) return violations;
|
|
206
|
+
const own = obj.cohort;
|
|
207
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
208
|
+
if (key === "sig" || key === "publicKey") continue;
|
|
209
|
+
if (typeof value !== "string") continue;
|
|
210
|
+
if (value === own) continue;
|
|
211
|
+
if (UUAID_RE.test(value)) violations.push("privacy-per-agent-uuaid");
|
|
212
|
+
if (TIMESTAMP_RE.test(value)) violations.push("privacy-timestamp");
|
|
213
|
+
if (IPV4_RE.test(value)) violations.push("privacy-ip");
|
|
214
|
+
if (URL_RE.test(value)) violations.push("privacy-carrier");
|
|
215
|
+
}
|
|
216
|
+
return violations;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Structural and semantic problems of a TTFA report body.
|
|
221
|
+
* Returns an array of reason codes; empty means the body is well formed.
|
|
222
|
+
*/
|
|
223
|
+
export function ttfaReportProblems(obj, { now = null } = {}) {
|
|
224
|
+
const problems = [];
|
|
225
|
+
if (!isPlainObject(obj)) return ["malformed-artifact"]; // @rule stats.ttfa-plain-object
|
|
226
|
+
if (!hasExactKeys(obj, TTFA_REPORT_KEYS)) return ["closed-schema"]; // @rule stats.ttfa-closed-schema
|
|
227
|
+
if (obj.v !== TTFA_REPORT_VERSION) return ["bad-version"]; // @rule stats.ttfa-version
|
|
228
|
+
for (const violation of ttfaPrivacyViolations(obj)) problems.push(violation); // @rule stats.ttfa-privacy
|
|
229
|
+
if (typeof obj.cohort !== "string" || !UUAID_RE.test(obj.cohort)) problems.push("malformed-artifact"); // @rule stats.ttfa-cohort-uuaid
|
|
230
|
+
if (typeof obj.publicKey !== "string" || !HEX64_RE.test(obj.publicKey)) problems.push("malformed-artifact"); // @rule stats.ttfa-key-hex
|
|
231
|
+
if (typeof obj.publicKey === "string" && HEX64_RE.test(obj.publicKey) && !isStrictEd25519PublicKey(obj.publicKey)) problems.push("weak-key"); // @rule stats.ttfa-key-strict
|
|
232
|
+
if (typeof obj.publicKey === "string" && HEX64_RE.test(obj.publicKey) && typeof obj.cohort === "string" && !isKeyDerivedUuaid(obj.cohort, obj.publicKey)) problems.push("key-uuaid-mismatch"); // @rule stats.ttfa-key-binding
|
|
233
|
+
if (!TTFA_METRICS.includes(obj.metric)) problems.push("bad-metric"); // @rule stats.ttfa-metric-enum
|
|
234
|
+
if (typeof obj.period !== "string" || !PERIOD_RE.test(obj.period)) problems.push("bad-period"); // @rule stats.ttfa-period-format
|
|
235
|
+
if (now !== null && typeof obj.period === "string" && PERIOD_RE.test(obj.period) && obj.period > utcMonth(now)) problems.push("future-period"); // @rule stats.ttfa-period-not-future
|
|
236
|
+
if (!TTFA_RUNTIME_BUCKETS.includes(obj.runtime)) problems.push("bad-runtime"); // @rule stats.ttfa-runtime-enum
|
|
237
|
+
if (!TTFA_METHODS.includes(obj.method)) problems.push("bad-method"); // @rule stats.ttfa-method-enum
|
|
238
|
+
if (!Number.isInteger(obj.n)) problems.push("malformed-artifact"); // @rule stats.ttfa-n-integer
|
|
239
|
+
if (Number.isInteger(obj.n) && obj.n < TTFA_MIN_N) problems.push("n-below-threshold"); // @rule stats.ttfa-n-threshold
|
|
240
|
+
if (!Number.isInteger(obj.p50)) problems.push("malformed-artifact"); // @rule stats.ttfa-p50-integer
|
|
241
|
+
if (Number.isInteger(obj.p50) && obj.p50 < 0) problems.push("bad-percentile"); // @rule stats.ttfa-p50-nonneg
|
|
242
|
+
if (!Number.isInteger(obj.p95)) problems.push("malformed-artifact"); // @rule stats.ttfa-p95-integer
|
|
243
|
+
if (Number.isInteger(obj.p95) && obj.p95 < 0) problems.push("bad-percentile"); // @rule stats.ttfa-p95-nonneg
|
|
244
|
+
if (Number.isInteger(obj.p50) && Number.isInteger(obj.p95) && obj.p95 < obj.p50) problems.push("bad-percentile"); // @rule stats.ttfa-percentile-ordered
|
|
245
|
+
if (typeof obj.sig !== "string" || !HEX128_RE.test(obj.sig)) problems.push("malformed-artifact"); // @rule stats.ttfa-sig-hex
|
|
246
|
+
return problems;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Build a signed `pillar-ttfa-report/1`.
|
|
251
|
+
*
|
|
252
|
+
* `fields` carries the cohort-level values only. The publisher identity and the
|
|
253
|
+
* signature come from `signer`, so a caller cannot attribute a report to a cohort
|
|
254
|
+
* whose key it does not hold.
|
|
255
|
+
*/
|
|
256
|
+
export function buildTtfaReport(fields, signer) {
|
|
257
|
+
const norm = normalizeStatsSigner(signer);
|
|
258
|
+
if (!norm) throw new TypeError("buildTtfaReport: valid signer required");
|
|
259
|
+
const body = {
|
|
260
|
+
v: TTFA_REPORT_VERSION,
|
|
261
|
+
cohort: norm.uuaid,
|
|
262
|
+
publicKey: norm.publicKey,
|
|
263
|
+
metric: fields?.metric,
|
|
264
|
+
period: fields?.period,
|
|
265
|
+
runtime: fields?.runtime,
|
|
266
|
+
method: fields?.method,
|
|
267
|
+
n: fields?.n,
|
|
268
|
+
p50: fields?.p50,
|
|
269
|
+
p95: fields?.p95,
|
|
270
|
+
};
|
|
271
|
+
if (Number.isInteger(body.n) && body.n < TTFA_MIN_N) throw new TypeError(`buildTtfaReport: n-below-threshold: n must be >= ${TTFA_MIN_N}`); // @rule stats.ttfa-build-n-threshold
|
|
272
|
+
const problems = ttfaReportProblems({ ...body, sig: "0".repeat(128) });
|
|
273
|
+
if (problems.length) throw new TypeError(`buildTtfaReport: ${problems.join(", ")}`); // @rule stats.ttfa-build-closed
|
|
274
|
+
return { ...body, sig: signBody(body, norm) };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Verify a `pillar-ttfa-report/1` offline. Returns a `pillar-verdict/1` object.
|
|
279
|
+
*/
|
|
280
|
+
export function verifyTtfaReport(artifact, opts = {}) {
|
|
281
|
+
const now = checkNow(opts);
|
|
282
|
+
if (!isPlainObject(artifact)) return fail(TTFA_VERDICT_TYPE, undefined, ["malformed-artifact"], now);
|
|
283
|
+
const subject = typeof artifact.cohort === "string" ? artifact.cohort : undefined;
|
|
284
|
+
const problems = ttfaReportProblems(artifact, { now });
|
|
285
|
+
if (problems.length) return fail(TTFA_VERDICT_TYPE, subject, problems, now);
|
|
286
|
+
const trusted = Array.isArray(opts.trustedIssuers) ? opts.trustedIssuers : [];
|
|
287
|
+
if (trusted.length && !trusted.includes(artifact.cohort)) return fail(TTFA_VERDICT_TYPE, subject, ["untrusted-issuer"], now); // @rule stats.ttfa-trusted-issuer
|
|
288
|
+
const expectedKey = (opts.publicKey ?? opts.verifierPublicKey ?? "").toLowerCase();
|
|
289
|
+
if (expectedKey && expectedKey !== artifact.publicKey) return fail(TTFA_VERDICT_TYPE, subject, ["untrusted-issuer"], now); // @rule stats.ttfa-pinned-key
|
|
290
|
+
if (!verifyBytesStrict(artifact.publicKey, signingBytes(artifact), artifact.sig)) return fail(TTFA_VERDICT_TYPE, subject, ["bad-signature"], now); // @rule stats.ttfa-signature
|
|
291
|
+
const facts = {
|
|
292
|
+
cohort: artifact.cohort,
|
|
293
|
+
metric: artifact.metric,
|
|
294
|
+
period: artifact.period,
|
|
295
|
+
runtime: artifact.runtime,
|
|
296
|
+
method: artifact.method,
|
|
297
|
+
n: artifact.n,
|
|
298
|
+
p50: artifact.p50,
|
|
299
|
+
p95: artifact.p95,
|
|
300
|
+
};
|
|
301
|
+
// Same rule as the frozen core (verify/index.ts:44-46): a requested subject that
|
|
302
|
+
// differs from the artifact's subject turns an otherwise valid verdict invalid.
|
|
303
|
+
if (opts.uuaid !== undefined && opts.uuaid !== subject) return fail(TTFA_VERDICT_TYPE, subject, ["subject-mismatch"], now, facts); // @rule stats.ttfa-subject
|
|
304
|
+
return verdict(TTFA_VERDICT_TYPE, subject, "valid", [], facts, now);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/* -------------------------------------------------------------------------- */
|
|
308
|
+
/* pillar-registry-stats/1 */
|
|
309
|
+
/* -------------------------------------------------------------------------- */
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Structural and semantic problems of a registry aggregate body.
|
|
313
|
+
* Returns an array of reason codes; empty means the body is well formed.
|
|
314
|
+
*/
|
|
315
|
+
export function registryStatsProblems(obj, { now = null } = {}) {
|
|
316
|
+
const problems = [];
|
|
317
|
+
if (!isPlainObject(obj)) return ["malformed-artifact"]; // @rule stats.stats-plain-object
|
|
318
|
+
if (!hasExactKeys(obj, REGISTRY_STATS_KEYS)) return ["closed-schema"]; // @rule stats.stats-closed-schema
|
|
319
|
+
if (obj.v !== REGISTRY_STATS_VERSION) return ["bad-version"]; // @rule stats.stats-version
|
|
320
|
+
if (typeof obj.registry !== "string" || !UUAID_RE.test(obj.registry)) problems.push("malformed-artifact"); // @rule stats.stats-registry-uuaid
|
|
321
|
+
if (typeof obj.publicKey !== "string" || !HEX64_RE.test(obj.publicKey)) problems.push("malformed-artifact"); // @rule stats.stats-key-hex
|
|
322
|
+
if (typeof obj.publicKey === "string" && HEX64_RE.test(obj.publicKey) && !isStrictEd25519PublicKey(obj.publicKey)) problems.push("weak-key"); // @rule stats.stats-key-strict
|
|
323
|
+
if (typeof obj.publicKey === "string" && HEX64_RE.test(obj.publicKey) && typeof obj.registry === "string" && !isKeyDerivedUuaid(obj.registry, obj.publicKey)) problems.push("key-uuaid-mismatch"); // @rule stats.stats-key-binding
|
|
324
|
+
if (!isUtcDay(obj.day)) problems.push("bad-day"); // @rule stats.stats-day-format
|
|
325
|
+
if (now !== null && isUtcDay(obj.day) && obj.day > utcDay(now)) problems.push("future-day"); // @rule stats.stats-day-not-future
|
|
326
|
+
if (!Number.isInteger(obj.liveLineages)) problems.push("malformed-artifact"); // @rule stats.stats-live-lineages-integer
|
|
327
|
+
if (Number.isInteger(obj.liveLineages) && obj.liveLineages < 0) problems.push("bad-count"); // @rule stats.stats-live-lineages-nonneg
|
|
328
|
+
if (!Number.isInteger(obj.listings)) problems.push("malformed-artifact"); // @rule stats.stats-listings-integer
|
|
329
|
+
if (Number.isInteger(obj.listings) && obj.listings < 0) problems.push("bad-count"); // @rule stats.stats-listings-nonneg
|
|
330
|
+
if (typeof obj.sig !== "string" || !HEX128_RE.test(obj.sig)) problems.push("malformed-artifact"); // @rule stats.stats-sig-hex
|
|
331
|
+
return problems;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Count the registry's public projection.
|
|
336
|
+
*
|
|
337
|
+
* `listings` is the number of live listings the registry serves publicly;
|
|
338
|
+
* `liveLineages` is the number of distinct lineages behind them. Both are exactly
|
|
339
|
+
* what the registry's public listing endpoint returns, so the signed daily
|
|
340
|
+
* aggregate can never assert a count the registry does not already publish.
|
|
341
|
+
*/
|
|
342
|
+
export function collectRegistryCounts(listings) {
|
|
343
|
+
const list = Array.isArray(listings) ? listings : [];
|
|
344
|
+
const lineages = new Set();
|
|
345
|
+
for (const entry of list) {
|
|
346
|
+
const lineage = entry?.lineage;
|
|
347
|
+
if (typeof lineage === "string" && lineage.length) lineages.add(lineage); // @rule stats.counts-distinct-lineages
|
|
348
|
+
}
|
|
349
|
+
const counts = { liveLineages: 0, listings: 0 };
|
|
350
|
+
counts.liveLineages = lineages.size; // @rule stats.counts-live-lineages
|
|
351
|
+
counts.listings = list.length; // @rule stats.counts-listing-count
|
|
352
|
+
return counts;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Build a signed `pillar-registry-stats/1`.
|
|
357
|
+
*
|
|
358
|
+
* `counts` carries only what the registry already serves publicly:
|
|
359
|
+
* `{ liveLineages, listings }`.
|
|
360
|
+
*/
|
|
361
|
+
export function buildRegistryStats(counts, signer, { day = null, now = null } = {}) {
|
|
362
|
+
const norm = normalizeStatsSigner(signer);
|
|
363
|
+
if (!norm) throw new TypeError("buildRegistryStats: valid signer required");
|
|
364
|
+
const body = {
|
|
365
|
+
v: REGISTRY_STATS_VERSION,
|
|
366
|
+
registry: norm.uuaid,
|
|
367
|
+
publicKey: norm.publicKey,
|
|
368
|
+
day: day ?? utcDay(now ?? new Date()),
|
|
369
|
+
liveLineages: counts?.liveLineages,
|
|
370
|
+
listings: counts?.listings,
|
|
371
|
+
};
|
|
372
|
+
const problems = registryStatsProblems({ ...body, sig: "0".repeat(128) });
|
|
373
|
+
if (problems.length) throw new TypeError(`buildRegistryStats: ${problems.join(", ")}`); // @rule stats.stats-build-closed
|
|
374
|
+
return { ...body, sig: signBody(body, norm) };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Verify a `pillar-registry-stats/1` offline. Returns a `pillar-verdict/1` object.
|
|
379
|
+
*/
|
|
380
|
+
export function verifyRegistryStats(artifact, opts = {}) {
|
|
381
|
+
const now = checkNow(opts);
|
|
382
|
+
if (!isPlainObject(artifact)) return fail(REGISTRY_STATS_VERDICT_TYPE, undefined, ["malformed-artifact"], now);
|
|
383
|
+
const subject = typeof artifact.registry === "string" ? artifact.registry : undefined;
|
|
384
|
+
const problems = registryStatsProblems(artifact, { now });
|
|
385
|
+
if (problems.length) return fail(REGISTRY_STATS_VERDICT_TYPE, subject, problems, now);
|
|
386
|
+
const trusted = Array.isArray(opts.trustedIssuers) ? opts.trustedIssuers : [];
|
|
387
|
+
if (trusted.length && !trusted.includes(artifact.registry)) return fail(REGISTRY_STATS_VERDICT_TYPE, subject, ["untrusted-issuer"], now); // @rule stats.stats-trusted-issuer
|
|
388
|
+
const expectedKey = (opts.publicKey ?? opts.verifierPublicKey ?? "").toLowerCase();
|
|
389
|
+
if (expectedKey && expectedKey !== artifact.publicKey) return fail(REGISTRY_STATS_VERDICT_TYPE, subject, ["untrusted-issuer"], now); // @rule stats.stats-pinned-key
|
|
390
|
+
if (!verifyBytesStrict(artifact.publicKey, signingBytes(artifact), artifact.sig)) return fail(REGISTRY_STATS_VERDICT_TYPE, subject, ["bad-signature"], now); // @rule stats.stats-signature
|
|
391
|
+
const facts = {
|
|
392
|
+
registry: artifact.registry,
|
|
393
|
+
day: artifact.day,
|
|
394
|
+
liveLineages: artifact.liveLineages,
|
|
395
|
+
listings: artifact.listings,
|
|
396
|
+
};
|
|
397
|
+
// Same rule as the frozen core (verify/index.ts:44-46).
|
|
398
|
+
if (opts.uuaid !== undefined && opts.uuaid !== subject) return fail(REGISTRY_STATS_VERDICT_TYPE, subject, ["subject-mismatch"], now, facts); // @rule stats.stats-subject
|
|
399
|
+
return verdict(REGISTRY_STATS_VERDICT_TYPE, subject, "valid", [], facts, now);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/* -------------------------------------------------------------------------- */
|
|
403
|
+
/* The first signed aggregate per registry per UTC day, persisted */
|
|
404
|
+
/* -------------------------------------------------------------------------- */
|
|
405
|
+
|
|
406
|
+
/** Path of the persisted first aggregate of one registry for one UTC day. */
|
|
407
|
+
export function registryStatsSnapshotPath(dir, registryUuaid, day) {
|
|
408
|
+
if (typeof registryUuaid !== "string" || !UUAID_RE.test(registryUuaid)) throw new TypeError("registryStatsSnapshotPath: registry uuaid required");
|
|
409
|
+
if (!isUtcDay(day)) throw new TypeError("registryStatsSnapshotPath: UTC day required");
|
|
410
|
+
const tag = createHash("sha256").update(registryUuaid).digest("hex").slice(0, 32);
|
|
411
|
+
return join(dir, `registry-stats-${tag}-${day}.json`);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Load the persisted aggregate of `registryUuaid` for `day`. Returns `null` when none
|
|
416
|
+
* exists. Throws when the file is not a valid aggregate of that registry and day
|
|
417
|
+
* (signature, `publicKey` pin, registry, day), so a caller never signs a second one
|
|
418
|
+
* over a damaged or foreign file.
|
|
419
|
+
*/
|
|
420
|
+
export function loadRegistryStatsSnapshot(dir, registryUuaid, day, { now = null, publicKey = null } = {}) {
|
|
421
|
+
const path = registryStatsSnapshotPath(dir, registryUuaid, day);
|
|
422
|
+
let raw;
|
|
423
|
+
try {
|
|
424
|
+
raw = readFileSync(path, "utf8");
|
|
425
|
+
} catch (e) {
|
|
426
|
+
if (e?.code === "ENOENT") return null;
|
|
427
|
+
throw e;
|
|
428
|
+
}
|
|
429
|
+
let snap = null;
|
|
430
|
+
try { snap = JSON.parse(raw); } catch { snap = null; }
|
|
431
|
+
const v = verifyRegistryStats(snap, { now: now ?? `${day}T23:59:59Z`, ...(publicKey ? { publicKey } : {}) });
|
|
432
|
+
if (v.verdict !== "valid") throw new Error(`registry stats snapshot ${path}: ${v.reasons.join(",")}`); // @rule stats.snapshot-verify
|
|
433
|
+
if (snap.registry !== registryUuaid || snap.day !== day) throw new Error(`registry stats snapshot ${path}: not ${registryUuaid} ${day}`); // @rule stats.snapshot-binding
|
|
434
|
+
return snap;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Persist `aggregate` as the first aggregate of its registry and day, and return the
|
|
439
|
+
* aggregate that is on disk afterwards.
|
|
440
|
+
*
|
|
441
|
+
* The file is written to a temp file, fsynced, then hard-linked into place. `link`
|
|
442
|
+
* fails with `EEXIST` when a snapshot already exists, so the first writer wins across
|
|
443
|
+
* restarts and concurrent processes, and a reader never sees a partial file. When a
|
|
444
|
+
* snapshot already exists, that snapshot is returned and `aggregate` is discarded.
|
|
445
|
+
*/
|
|
446
|
+
export function persistFirstRegistryStats(dir, aggregate, { now = null } = {}) {
|
|
447
|
+
const path = registryStatsSnapshotPath(dir, aggregate?.registry, aggregate?.day);
|
|
448
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
449
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
450
|
+
writeFileSync(tmp, `${JSON.stringify(aggregate)}\n`, { mode: 0o600, flag: "wx" });
|
|
451
|
+
try {
|
|
452
|
+
const fd = openSync(tmp, "r");
|
|
453
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
454
|
+
try {
|
|
455
|
+
linkSync(tmp, path); // @rule stats.snapshot-exclusive-create
|
|
456
|
+
} catch (e) {
|
|
457
|
+
if (e?.code !== "EEXIST") throw e;
|
|
458
|
+
}
|
|
459
|
+
} finally {
|
|
460
|
+
rmSync(tmp, { force: true });
|
|
461
|
+
}
|
|
462
|
+
try {
|
|
463
|
+
const dfd = openSync(dir, "r");
|
|
464
|
+
try { fsyncSync(dfd); } finally { closeSync(dfd); }
|
|
465
|
+
} catch { /* best effort: some platforms refuse fsync on a directory */ }
|
|
466
|
+
return loadRegistryStatsSnapshot(dir, aggregate.registry, aggregate.day, { now, publicKey: aggregate.publicKey });
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Detect a B8 artifact by its `v` field.
|
|
471
|
+
* Returns `"ttfa-report"`, `"registry-stats"`, or `null`.
|
|
472
|
+
*/
|
|
473
|
+
export function detectStatsArtifact(artifact) {
|
|
474
|
+
if (!isPlainObject(artifact)) return null;
|
|
475
|
+
if (artifact.v === TTFA_REPORT_VERSION) return TTFA_VERDICT_TYPE;
|
|
476
|
+
if (artifact.v === REGISTRY_STATS_VERSION) return REGISTRY_STATS_VERDICT_TYPE;
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Verify either B8 artifact type. Returns a `pillar-verdict/1` object, or `null`
|
|
482
|
+
* when the artifact is not a B8 artifact.
|
|
483
|
+
*/
|
|
484
|
+
export function verifyStatsArtifact(artifact, opts = {}) {
|
|
485
|
+
const requested = opts.type;
|
|
486
|
+
if (requested !== undefined && requested !== TTFA_VERDICT_TYPE && requested !== REGISTRY_STATS_VERDICT_TYPE) return null;
|
|
487
|
+
const detected = detectStatsArtifact(artifact);
|
|
488
|
+
if (requested === TTFA_VERDICT_TYPE || requested === REGISTRY_STATS_VERDICT_TYPE) {
|
|
489
|
+
if (detected !== requested) {
|
|
490
|
+
const subject = typeof artifact?.[requested === TTFA_VERDICT_TYPE ? "cohort" : "registry"] === "string"
|
|
491
|
+
? artifact[requested === TTFA_VERDICT_TYPE ? "cohort" : "registry"]
|
|
492
|
+
: undefined;
|
|
493
|
+
return fail(requested, subject, ["bad-version"], checkNow(opts));
|
|
494
|
+
}
|
|
495
|
+
return requested === TTFA_VERDICT_TYPE ? verifyTtfaReport(artifact, opts) : verifyRegistryStats(artifact, opts);
|
|
496
|
+
}
|
|
497
|
+
if (detected === TTFA_VERDICT_TYPE) return verifyTtfaReport(artifact, opts);
|
|
498
|
+
if (detected === REGISTRY_STATS_VERDICT_TYPE) return verifyRegistryStats(artifact, opts);
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Key record for a signer, used to assert that a publisher's key really is the
|
|
504
|
+
* key its uuaid derives from. Throws when the key and uuaid disagree.
|
|
505
|
+
*/
|
|
506
|
+
export function statsSignerKeyRecord(signer) {
|
|
507
|
+
return keyRecord(signer);
|
|
508
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy loader for optional `better-sqlite3` native dependency.
|
|
3
|
+
*
|
|
4
|
+
* Probes `:memory:` once so both missing packages (`--omit=optional`),
|
|
5
|
+
* unbuilt bindings (`--ignore-scripts`, missing C++ toolchain), and
|
|
6
|
+
* Node ABI mismatches cleanly report unavailable instead of crashing on import.
|
|
7
|
+
*/
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import { REFUSAL_FIXES } from "./net/refusals.mjs";
|
|
10
|
+
|
|
11
|
+
const req = createRequire(import.meta.url);
|
|
12
|
+
let cachedDatabase = undefined;
|
|
13
|
+
|
|
14
|
+
export function tryLoadBetterSqlite3() {
|
|
15
|
+
if (process.env.PILLAR_DISABLE_SQLITE === "1") return null;
|
|
16
|
+
if (cachedDatabase !== undefined) return cachedDatabase;
|
|
17
|
+
try {
|
|
18
|
+
const mod = req("better-sqlite3");
|
|
19
|
+
const Database = mod?.default ?? mod;
|
|
20
|
+
const probe = new Database(":memory:");
|
|
21
|
+
probe.close();
|
|
22
|
+
cachedDatabase = Database;
|
|
23
|
+
} catch {
|
|
24
|
+
cachedDatabase = null;
|
|
25
|
+
}
|
|
26
|
+
return cachedDatabase;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function requireBetterSqlite3(component = "SQLite store") {
|
|
30
|
+
const Database = tryLoadBetterSqlite3();
|
|
31
|
+
if (!Database) {
|
|
32
|
+
const err = new Error(
|
|
33
|
+
`sqlite-not-installed: ${component} requires the optional better-sqlite3 native addon — install build tools and run: npm rebuild better-sqlite3`,
|
|
34
|
+
);
|
|
35
|
+
err.code = "sqlite-not-installed";
|
|
36
|
+
err.fix = REFUSAL_FIXES["sqlite-not-installed"];
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
return Database;
|
|
40
|
+
}
|