@uuaid/pillar 2.6.1 → 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/README.md +201 -5
- package/bin/carrier.mjs +21 -0
- 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,571 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pillar vNext §4 / Plan Row A8 — Staging Greeter mode helpers and guards.
|
|
3
|
+
*
|
|
4
|
+
* Enforces the A8 greeter contract:
|
|
5
|
+
* 1. Greeter mode enablement (`--greeter` or `config.json` `responder.greeter === true`).
|
|
6
|
+
* 2. Signed `pillar-card/1` with `does: [{ tag: "greeter" }]` saved at `<home>/card/card.json`
|
|
7
|
+
* (`mode: 0o600`) and verified with `verifyCard`.
|
|
8
|
+
* 3. Optional staging registry enrollment (`POST /v1/lineage` + W-10 stamped `POST /v1/listings`)
|
|
9
|
+
* using only vendored `pillar-core.mjs` primitives (zero external package-dist dependency).
|
|
10
|
+
* 4. Default `onPow`, `onIntroduction`, and `onStake` to `"accept"`.
|
|
11
|
+
* 5. At-most-one `knock.answer` per `senderLineage` (and `sender` UUAID), persisted in
|
|
12
|
+
* `<home>/knock-responder-journal.jsonl` (`mode: 0o600`) across restarts and concurrent calls.
|
|
13
|
+
* 6. Total silence after that one `knock.answer`: zero `ack`/`reply`/`message` sends, zero shell
|
|
14
|
+
* hooks, zero forwarding, zero delivery/read receipts, zero pending-request replays.
|
|
15
|
+
*/
|
|
16
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
import {
|
|
19
|
+
CARD_VERSION,
|
|
20
|
+
DEFAULT_CARD_CARRIER,
|
|
21
|
+
DEFAULT_CARD_HOME,
|
|
22
|
+
DEFAULT_STAMP_BITS,
|
|
23
|
+
MAX_STAMP_BITS,
|
|
24
|
+
MIN_STAMP_BITS,
|
|
25
|
+
buildCard,
|
|
26
|
+
eventDigest,
|
|
27
|
+
hexToBytes,
|
|
28
|
+
identityFromSeed,
|
|
29
|
+
isKeyDerivedUuaid,
|
|
30
|
+
isStrictEd25519PublicKey,
|
|
31
|
+
mintStamp,
|
|
32
|
+
signLineageDoc,
|
|
33
|
+
verifyCard,
|
|
34
|
+
verifyLineage,
|
|
35
|
+
verifyLineageDoc,
|
|
36
|
+
} from "../vendor/pillar-core.mjs";
|
|
37
|
+
import { resolveRequiredBits, isValidUuaid } from "./knock-lane.mjs";
|
|
38
|
+
import { nowIsoSeconds, seedHexFromKeychainIdentity, writeFileAtomic } from "./wave-a.mjs";
|
|
39
|
+
|
|
40
|
+
export const GREETER_TAG = "greeter";
|
|
41
|
+
export const GREETER_JOURNAL_FILE = "knock-responder-journal.jsonl";
|
|
42
|
+
export const LISTING_VERSION = "pillar-listing/1";
|
|
43
|
+
|
|
44
|
+
const STRICT_HTTPS_URI_RE =
|
|
45
|
+
/^https:\/\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})+)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
|
46
|
+
|
|
47
|
+
const LOOPBACK_IPV4_RE = /^127\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
|
|
48
|
+
|
|
49
|
+
function isStrictHttpsUri(u) {
|
|
50
|
+
if (typeof u !== "string" || !u.startsWith("https://")) return false;
|
|
51
|
+
if (!STRICT_HTTPS_URI_RE.test(u)) return false;
|
|
52
|
+
try {
|
|
53
|
+
return new URL(u).protocol === "https:";
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function isLoopbackHost(hostname) {
|
|
60
|
+
const h = String(hostname ?? "").toLowerCase();
|
|
61
|
+
return h === "localhost" || h === "::1" || h === "[::1]" || LOOPBACK_IPV4_RE.test(h);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function toHttpsCardUri(raw) {
|
|
65
|
+
if (typeof raw !== "string") return null;
|
|
66
|
+
const trimmed = raw.trim().replace(/\/+$/, "");
|
|
67
|
+
if (isStrictHttpsUri(trimmed)) return trimmed;
|
|
68
|
+
try {
|
|
69
|
+
const u = new URL(trimmed);
|
|
70
|
+
if (u.protocol === "http:" && isLoopbackHost(u.hostname)) {
|
|
71
|
+
const upgraded = `https://${u.host}${u.pathname === "/" ? "" : u.pathname}`;
|
|
72
|
+
return isStrictHttpsUri(upgraded) ? upgraded : null;
|
|
73
|
+
}
|
|
74
|
+
} catch { /* ignore invalid URL */ }
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Determine whether greeter mode is active from CLI args and `config.json` `responder`.
|
|
80
|
+
*/
|
|
81
|
+
export function isGreeterMode(args = {}, rcfg = {}) {
|
|
82
|
+
if (args?.greeter === false || args?.greeter === "false") return false; // @rule greeter.cli-flag-false-overrides
|
|
83
|
+
if (args?.greeter === true || args?.greeter === "true") return true; // @rule greeter.cli-flag-enables
|
|
84
|
+
return rcfg?.greeter === true;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Resolve optional registry enrollment URL from CLI `--enroll-registry` or `responder.registryUrl`.
|
|
89
|
+
*/
|
|
90
|
+
export function resolveRegistryUrl(args = {}, rcfg = {}) {
|
|
91
|
+
const raw = typeof args?.["enroll-registry"] === "string"
|
|
92
|
+
? args["enroll-registry"]
|
|
93
|
+
: (typeof rcfg?.registryUrl === "string" ? rcfg.registryUrl : null);
|
|
94
|
+
return raw && raw.trim().length > 0 ? raw.trim().replace(/\/+$/, "") : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Silence guards for greeter mode (Done check 2).
|
|
99
|
+
*/
|
|
100
|
+
export function shouldHandleNonKnockEnvelope(greeterMode) {
|
|
101
|
+
if (greeterMode) return false; // @rule greeter.silence-no-non-knock
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function shouldReplayPendingRequests(greeterMode) {
|
|
106
|
+
if (greeterMode) return false; // @rule greeter.silence-no-replay
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function resolveResponderHookCmd(greeterMode, hookCmd) {
|
|
111
|
+
if (greeterMode) return null; // @rule greeter.silence-no-hook
|
|
112
|
+
return hookCmd ?? null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function resolveResponderForward(greeterMode, fwd) {
|
|
116
|
+
if (greeterMode) return null; // @rule greeter.silence-no-forward
|
|
117
|
+
return fwd ?? null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function resolveResponderReceipts(greeterMode, receiptsCfg = null) {
|
|
121
|
+
if (greeterMode) return { delivered: false, read: false }; // @rule greeter.silence-no-receipts
|
|
122
|
+
return { delivered: Boolean(receiptsCfg?.delivered), read: Boolean(receiptsCfg?.read) };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Build knock auto-answer rules for greeter mode (defaults `onPow`, `onIntroduction`,
|
|
127
|
+
* `onStake`, and `defaultDecision` to `"accept"`).
|
|
128
|
+
*/
|
|
129
|
+
export function resolveGreeterKnockRules(args = {}, kcfg = {}) {
|
|
130
|
+
const base = {
|
|
131
|
+
enabled: kcfg?.enabled !== false && args?.["knock-auto"] !== "false",
|
|
132
|
+
onIntroduction: args?.["knock-intro"] ?? kcfg?.onIntroduction ?? "accept",
|
|
133
|
+
onPow: args?.["knock-pow"] ?? kcfg?.onPow ?? "accept", // @rule greeter.rules-default-pow-accept
|
|
134
|
+
onStake: args?.["knock-stake"] ?? kcfg?.onStake ?? "accept", // @rule greeter.rules-default-stake-accept
|
|
135
|
+
defaultDecision: kcfg?.defaultDecision ?? "accept", // @rule greeter.rules-default-decision-accept
|
|
136
|
+
...(Array.isArray(kcfg?.acceptScope) ? { acceptScope: kcfg.acceptScope } : {}),
|
|
137
|
+
...(typeof (args?.["knock-note"] ?? kcfg?.note) === "string" ? { note: args?.["knock-note"] ?? kcfg.note } : {}),
|
|
138
|
+
...(kcfg?.tagRules && typeof kcfg.tagRules === "object" ? { tagRules: kcfg.tagRules } : {}),
|
|
139
|
+
};
|
|
140
|
+
return base;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Normalize knock rules passed directly to `new KnockResponder({ greeter: true, rules })`.
|
|
145
|
+
*/
|
|
146
|
+
export function normalizeGreeterRules(rules = null) {
|
|
147
|
+
const r = rules && typeof rules === "object" ? rules : {};
|
|
148
|
+
return {
|
|
149
|
+
...r,
|
|
150
|
+
enabled: r.enabled !== false,
|
|
151
|
+
onIntroduction: r.onIntroduction ?? "accept",
|
|
152
|
+
onPow: r.onPow ?? "accept", // @rule greeter.normalize-pow-accept
|
|
153
|
+
onStake: r.onStake ?? "accept", // @rule greeter.normalize-stake-accept
|
|
154
|
+
defaultDecision: r.defaultDecision ?? "accept",
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* True if `card.does` includes `{ tag: "greeter" }`.
|
|
160
|
+
*/
|
|
161
|
+
export function hasGreeterTag(card) {
|
|
162
|
+
if (!card || typeof card !== "object" || !Array.isArray(card.does)) return false;
|
|
163
|
+
return card.does.some((d) => d && typeof d === "object" && d.tag === GREETER_TAG);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Validate that `card` is a signed, verified `pillar-card/1` belonging to `expectedUuaid`
|
|
168
|
+
* and advertising `does: [{ tag: "greeter" }]` (plus compatible `knock.pow` when requested).
|
|
169
|
+
*/
|
|
170
|
+
export function hasValidGreeterCard(card, expectedUuaid, { now = nowIsoSeconds(), lineage = null, minPowBits = null } = {}) {
|
|
171
|
+
if (!card || typeof card !== "object" || Array.isArray(card) || card.v !== CARD_VERSION) return false; // @rule greeter.card-version
|
|
172
|
+
if (card.uuaid !== expectedUuaid) return false; // @rule greeter.card-uuaid-match
|
|
173
|
+
if (!hasGreeterTag(card)) return false; // @rule greeter.card-has-does-tag
|
|
174
|
+
if (Number.isInteger(minPowBits) && (!Number.isInteger(card.knock?.pow) || card.knock.pow < minPowBits)) return false; // @rule greeter.card-knock-pow-bits
|
|
175
|
+
if (Array.isArray(lineage) && lineage.length > 0) {
|
|
176
|
+
const v = verifyCard(card, { now, lineage });
|
|
177
|
+
if (v.verdict !== "valid") return false; // @rule greeter.card-lineage-verify
|
|
178
|
+
} else {
|
|
179
|
+
if (card.lineage !== expectedUuaid) return false; // @rule greeter.card-self-lineage
|
|
180
|
+
const v = verifyCard(card, { now });
|
|
181
|
+
if (v.verdict === "invalid") return false; // @rule greeter.card-self-verify
|
|
182
|
+
if (!isStrictEd25519PublicKey(card.publicKey) || !isKeyDerivedUuaid(card.uuaid, card.publicKey)) return false; // @rule greeter.card-key-binding
|
|
183
|
+
if (!verifyLineageDoc(card, card.publicKey, card.sig)) return false; // @rule greeter.card-sig-valid
|
|
184
|
+
}
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Load Wave A lineage events from `<home>/lineage/log.json` if present.
|
|
190
|
+
* Accepts either a raw array `[inception, ...]` (written by `pillar init`)
|
|
191
|
+
* or a `uuaid-lineage-log/1` presentation `{ v, events, receipts }`.
|
|
192
|
+
*/
|
|
193
|
+
export function loadHomeLineageEvents(home) {
|
|
194
|
+
if (!home) return null;
|
|
195
|
+
const logPath = join(home, "lineage", "log.json");
|
|
196
|
+
if (!existsSync(logPath)) return null;
|
|
197
|
+
try {
|
|
198
|
+
const parsed = JSON.parse(readFileSync(logPath, "utf8"));
|
|
199
|
+
const events = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.events) ? parsed.events : null);
|
|
200
|
+
if (!events || events.length === 0) return null;
|
|
201
|
+
return [...events].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
|
|
202
|
+
} catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function coreIdentityFromKeychain(identity) {
|
|
208
|
+
const parts = identity.uuaid.split(":");
|
|
209
|
+
const namespace = parts[1] || "pillar";
|
|
210
|
+
const objectType = parts[2] || "agent";
|
|
211
|
+
const seedHex = seedHexFromKeychainIdentity(identity);
|
|
212
|
+
return {
|
|
213
|
+
coreId: identityFromSeed(hexToBytes(seedHex), { namespace, objectType }),
|
|
214
|
+
namespace,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function buildDoesWithGreeter(existingDoes) {
|
|
219
|
+
const list = Array.isArray(existingDoes)
|
|
220
|
+
? existingDoes.filter((d) => d && typeof d === "object" && (d.tag !== undefined || d.action !== undefined))
|
|
221
|
+
: [];
|
|
222
|
+
if (list.some((d) => d.tag === GREETER_TAG)) return list;
|
|
223
|
+
return [{ tag: GREETER_TAG }, ...list].slice(0, 32);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Ensure `<home>/card/card.json` exists, carries `does: [{ tag: "greeter" }]`,
|
|
228
|
+
* and passes `verifyCard`. Builds and saves atomically (`mode: 0o600`) if absent,
|
|
229
|
+
* invalid, or missing `{ tag: "greeter" }`.
|
|
230
|
+
*/
|
|
231
|
+
export function ensureGreeterCard({
|
|
232
|
+
home,
|
|
233
|
+
identity,
|
|
234
|
+
carriers = [],
|
|
235
|
+
registryUrl = null,
|
|
236
|
+
knockConfig = {},
|
|
237
|
+
name = null,
|
|
238
|
+
about = null,
|
|
239
|
+
cardCarriers = null,
|
|
240
|
+
cardHomes = null,
|
|
241
|
+
now = nowIsoSeconds(),
|
|
242
|
+
}) {
|
|
243
|
+
const lineageEvents = loadHomeLineageEvents(home);
|
|
244
|
+
let verifiedLineage = null;
|
|
245
|
+
let lineageId = identity.uuaid;
|
|
246
|
+
let lineageHead = undefined;
|
|
247
|
+
if (lineageEvents) {
|
|
248
|
+
const lv = verifyLineage(lineageEvents, { now });
|
|
249
|
+
if (lv.verdict === "valid" && lv.facts?.current === identity.uuaid) {
|
|
250
|
+
verifiedLineage = lineageEvents;
|
|
251
|
+
lineageId = lv.subject;
|
|
252
|
+
lineageHead = `sha256:${eventDigest(lineageEvents[lineageEvents.length - 1])}`;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const requiredBits = resolveRequiredBits(knockConfig);
|
|
257
|
+
const cardPath = join(home, "card", "card.json");
|
|
258
|
+
let existing = null;
|
|
259
|
+
if (existsSync(cardPath)) {
|
|
260
|
+
try {
|
|
261
|
+
const parsed = JSON.parse(readFileSync(cardPath, "utf8"));
|
|
262
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) existing = parsed;
|
|
263
|
+
} catch { /* rebuild malformed card */ }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (existing && hasValidGreeterCard(existing, identity.uuaid, { now, lineage: verifiedLineage, minPowBits: requiredBits })) {
|
|
267
|
+
return { card: existing, cardPath, rebuilt: false, lineageEvents: verifiedLineage, lineageHead };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const { coreId, namespace } = coreIdentityFromKeychain(identity);
|
|
271
|
+
|
|
272
|
+
const allStagingUrls = [
|
|
273
|
+
...(Array.isArray(cardCarriers) ? cardCarriers : []),
|
|
274
|
+
...(Array.isArray(carriers) ? carriers : []),
|
|
275
|
+
...(Array.isArray(cardHomes) ? cardHomes : []),
|
|
276
|
+
...(registryUrl ? [registryUrl] : []),
|
|
277
|
+
];
|
|
278
|
+
let loopbackStaging = false;
|
|
279
|
+
loopbackStaging = allStagingUrls.some((u) => { try { return typeof u === "string" && isLoopbackHost(new URL(u).hostname); } catch { return false; } }); // @rule greeter.loopback-no-prod-fallback
|
|
280
|
+
|
|
281
|
+
const httpsCarriers = [
|
|
282
|
+
...(Array.isArray(cardCarriers) ? cardCarriers : []),
|
|
283
|
+
...(Array.isArray(carriers) ? carriers : []),
|
|
284
|
+
]
|
|
285
|
+
.map(toHttpsCardUri)
|
|
286
|
+
.filter(Boolean);
|
|
287
|
+
const httpsHomes = [
|
|
288
|
+
...(Array.isArray(cardHomes) ? cardHomes : []),
|
|
289
|
+
...(registryUrl ? [registryUrl] : []),
|
|
290
|
+
]
|
|
291
|
+
.map(toHttpsCardUri)
|
|
292
|
+
.filter(Boolean);
|
|
293
|
+
|
|
294
|
+
const fallbackCarrier = loopbackStaging ? (httpsHomes[0] ?? "https://127.0.0.1") : DEFAULT_CARD_CARRIER;
|
|
295
|
+
const fallbackHome = loopbackStaging ? (httpsCarriers[0] ?? "https://127.0.0.1") : DEFAULT_CARD_HOME;
|
|
296
|
+
|
|
297
|
+
const resolvedCarriers = httpsCarriers.length > 0
|
|
298
|
+
? [...new Set(httpsCarriers)].slice(0, 8)
|
|
299
|
+
: (Array.isArray(existing?.carriers) && existing.carriers.every(isStrictHttpsUri) && existing.carriers.length > 0
|
|
300
|
+
? existing.carriers
|
|
301
|
+
: [fallbackCarrier]);
|
|
302
|
+
|
|
303
|
+
const resolvedHomes = httpsHomes.length > 0
|
|
304
|
+
? [...new Set(httpsHomes)].slice(0, 4)
|
|
305
|
+
: (Array.isArray(existing?.homes) && existing.homes.every(isStrictHttpsUri) && existing.homes.length > 0
|
|
306
|
+
? existing.homes
|
|
307
|
+
: [fallbackHome]);
|
|
308
|
+
|
|
309
|
+
const existingKnock = existing?.knock && typeof existing.knock === "object" && !Array.isArray(existing.knock)
|
|
310
|
+
? existing.knock
|
|
311
|
+
: {};
|
|
312
|
+
const knock = {
|
|
313
|
+
pow: requiredBits,
|
|
314
|
+
...(typeof (knockConfig?.introductions ?? existingKnock.introductions) === "boolean"
|
|
315
|
+
? { introductions: knockConfig?.introductions ?? existingKnock.introductions }
|
|
316
|
+
: {}),
|
|
317
|
+
...(Number.isInteger(knockConfig?.maxBytes ?? existingKnock.maxBytes)
|
|
318
|
+
? { maxBytes: knockConfig?.maxBytes ?? existingKnock.maxBytes }
|
|
319
|
+
: {}),
|
|
320
|
+
...(Array.isArray(knockConfig?.stake ?? existingKnock.stake)
|
|
321
|
+
? { stake: knockConfig?.stake ?? existingKnock.stake }
|
|
322
|
+
: {}),
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const cardName = (typeof name === "string" && name.trim())
|
|
326
|
+
? name.trim()
|
|
327
|
+
: ((typeof existing?.name === "string" && existing.name.trim())
|
|
328
|
+
? existing.name.trim()
|
|
329
|
+
: `pillar-greeter-${identity.uuaid.slice(-8)}`);
|
|
330
|
+
const cardAbout = typeof about === "string"
|
|
331
|
+
? about
|
|
332
|
+
: (typeof existing?.about === "string" ? existing.about : undefined);
|
|
333
|
+
|
|
334
|
+
const card = buildCard(coreId, {
|
|
335
|
+
namespace,
|
|
336
|
+
lineage: lineageId,
|
|
337
|
+
name: cardName,
|
|
338
|
+
...(cardAbout !== undefined ? { about: cardAbout } : {}),
|
|
339
|
+
does: buildDoesWithGreeter(existing?.does),
|
|
340
|
+
...(Array.isArray(existing?.wants) ? { wants: existing.wants } : {}),
|
|
341
|
+
...(Array.isArray(existing?.languages) ? { languages: existing.languages } : {}),
|
|
342
|
+
...(Array.isArray(existing?.doors) ? { doors: existing.doors } : {}),
|
|
343
|
+
...(Array.isArray(existing?.interfaces) ? { interfaces: existing.interfaces } : {}),
|
|
344
|
+
carriers: resolvedCarriers,
|
|
345
|
+
homes: resolvedHomes,
|
|
346
|
+
knock,
|
|
347
|
+
...(lineageHead && registryUrl ? { lineageHead } : {}),
|
|
348
|
+
updatedAt: now,
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
// Defensive postcondition: every freshly built greeter card must pass verifyCard.
|
|
352
|
+
if (!hasValidGreeterCard(card, identity.uuaid, { now, lineage: verifiedLineage, minPowBits: requiredBits })) {
|
|
353
|
+
throw new Error("ensureGreeterCard: built greeter card failed verifyCard");
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
writeFileAtomic(cardPath, `${JSON.stringify(card, null, 2)}\n`, 0o600);
|
|
357
|
+
return { card, cardPath, rebuilt: true, lineageEvents: verifiedLineage, lineageHead };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Resolve the sender's lineage UUAID from a knock view/meta.
|
|
362
|
+
* Fails closed (`null`) if missing or not a valid UUAID.
|
|
363
|
+
*/
|
|
364
|
+
export function resolveGreeterSenderLineage(view, meta = {}) {
|
|
365
|
+
const candidate = meta?.senderLineage ?? view?.payload?.card?.lineage ?? view?.sender ?? null;
|
|
366
|
+
if (!isValidUuaid(candidate)) return null; // @rule greeter.lineage-required
|
|
367
|
+
return candidate;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Persistent once-per-sender-lineage journal (`<home>/knock-responder-journal.jsonl`, `mode: 0o600`).
|
|
372
|
+
* Enforces that each `senderLineage` (and `sender` UUAID) is answered at most once EVER across
|
|
373
|
+
* concurrent calls, K6 resets after `accept`, and responder process restarts.
|
|
374
|
+
*/
|
|
375
|
+
export class GreeterJournal {
|
|
376
|
+
constructor({ journalPath = null } = {}) {
|
|
377
|
+
this.journalPath = journalPath;
|
|
378
|
+
this._greetedLineages = new Set();
|
|
379
|
+
this._greetedSenders = new Set();
|
|
380
|
+
this._inFlightLineages = new Set();
|
|
381
|
+
this._load();
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
_load() {
|
|
385
|
+
if (!this.journalPath || !existsSync(this.journalPath)) return;
|
|
386
|
+
for (const line of readFileSync(this.journalPath, "utf8").split("\n")) {
|
|
387
|
+
if (!line.trim()) continue;
|
|
388
|
+
try {
|
|
389
|
+
const rec = JSON.parse(line);
|
|
390
|
+
if (rec?.event !== "knock-answered") continue;
|
|
391
|
+
if (typeof rec.senderLineage === "string" && rec.senderLineage.length > 0) this._greetedLineages.add(rec.senderLineage); // @rule greeter.journal-load-lineage
|
|
392
|
+
if (typeof rec.sender === "string" && rec.sender.length > 0) this._greetedSenders.add(rec.sender); // @rule greeter.journal-load-sender
|
|
393
|
+
} catch { /* skip torn line */ }
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
hasGreeted(senderLineage, sender = null) {
|
|
398
|
+
if (typeof senderLineage === "string" && this._greetedLineages.has(senderLineage)) return true; // @rule greeter.once-per-lineage
|
|
399
|
+
if (typeof sender === "string" && this._greetedSenders.has(sender)) return true; // @rule greeter.once-per-sender
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
tryBegin(senderLineage, sender = null) {
|
|
404
|
+
if (!isValidUuaid(senderLineage)) return { allow: false, reason: "missing-lineage" }; // @rule greeter.begin-valid-lineage
|
|
405
|
+
if (this.hasGreeted(senderLineage, sender)) return { allow: false, reason: "already-greeted" }; // @rule greeter.begin-already-greeted
|
|
406
|
+
if (this._inFlightLineages.has(senderLineage)) return { allow: false, reason: "lineage-in-flight" }; // @rule greeter.begin-in-flight-lineage
|
|
407
|
+
this._inFlightLineages.add(senderLineage);
|
|
408
|
+
return { allow: true };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
endInFlight(senderLineage) {
|
|
412
|
+
if (typeof senderLineage === "string") this._inFlightLineages.delete(senderLineage);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
markGreeted({ id, sender, senderLineage, decision = "accept", paymentType = null, ts = nowIsoSeconds() }) {
|
|
416
|
+
if (typeof senderLineage === "string" && senderLineage.length > 0) this._greetedLineages.add(senderLineage);
|
|
417
|
+
if (typeof sender === "string" && sender.length > 0) this._greetedSenders.add(sender);
|
|
418
|
+
if (!this.journalPath) return;
|
|
419
|
+
mkdirSync(dirname(this.journalPath), { recursive: true });
|
|
420
|
+
appendFileSync(this.journalPath, `${JSON.stringify({
|
|
421
|
+
ts,
|
|
422
|
+
event: "knock-answered",
|
|
423
|
+
id,
|
|
424
|
+
sender,
|
|
425
|
+
senderLineage,
|
|
426
|
+
decision,
|
|
427
|
+
paymentType,
|
|
428
|
+
})}\n`, { mode: 0o600 });
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Build and sign a W-10 stamped `pillar-listing/1` document using `signLineageDoc`
|
|
434
|
+
* and `mintStamp` from `src/vendor/pillar-core.mjs`.
|
|
435
|
+
*/
|
|
436
|
+
export function buildGreeterListing({
|
|
437
|
+
identity,
|
|
438
|
+
card,
|
|
439
|
+
registryUuaid,
|
|
440
|
+
homes = null,
|
|
441
|
+
stampBits = DEFAULT_STAMP_BITS,
|
|
442
|
+
issuedAt = nowIsoSeconds(),
|
|
443
|
+
includeStamp = true,
|
|
444
|
+
}) {
|
|
445
|
+
if (!hasGreeterTag(card)) throw new TypeError("buildGreeterListing: card must carry does: [{ tag: \"greeter\" }]"); // @rule greeter.listing-requires-greeter-tag
|
|
446
|
+
if (!Number.isInteger(stampBits) || stampBits < MIN_STAMP_BITS || stampBits > MAX_STAMP_BITS) throw new TypeError("buildGreeterListing: stampBits must be an integer 12..24"); // @rule greeter.listing-stamp-bits
|
|
447
|
+
const rawHomes = homes ?? card.homes;
|
|
448
|
+
if (!Array.isArray(rawHomes) || rawHomes.length < 1 || rawHomes.length > 4 || !rawHomes.every(isStrictHttpsUri)) throw new TypeError("buildGreeterListing: homes must contain 1..4 valid https URIs"); // @rule greeter.listing-homes-https
|
|
449
|
+
const { coreId } = coreIdentityFromKeychain(identity);
|
|
450
|
+
const day = issuedAt.slice(0, 10);
|
|
451
|
+
const stamp = includeStamp
|
|
452
|
+
? mintStamp(card.lineage, `${LISTING_VERSION}:${registryUuaid}`, day, stampBits)
|
|
453
|
+
: undefined;
|
|
454
|
+
const unsigned = {
|
|
455
|
+
v: LISTING_VERSION,
|
|
456
|
+
lineage: card.lineage,
|
|
457
|
+
uuaid: card.uuaid,
|
|
458
|
+
card,
|
|
459
|
+
homes: [...rawHomes],
|
|
460
|
+
issuedAt,
|
|
461
|
+
...(stamp !== undefined ? { stamp } : {}),
|
|
462
|
+
};
|
|
463
|
+
const signed = { ...unsigned, sig: signLineageDoc(unsigned, coreId) };
|
|
464
|
+
if (!verifyLineageDoc(signed, card.publicKey, signed.sig)) throw new TypeError("buildGreeterListing: listing signature failed self-verification"); // @rule greeter.listing-self-sig
|
|
465
|
+
return signed;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Enroll the greeter's `lineage/log.json` (`POST /v1/lineage`) and signed W-10 stamped
|
|
470
|
+
* `pillar-listing/1` (`POST /v1/listings`) in a staging `pillar-directory` on startup.
|
|
471
|
+
*/
|
|
472
|
+
export async function enrollGreeterInRegistry({
|
|
473
|
+
registryUrl,
|
|
474
|
+
identity,
|
|
475
|
+
card,
|
|
476
|
+
lineageEvents = null,
|
|
477
|
+
stampBits = DEFAULT_STAMP_BITS,
|
|
478
|
+
now = nowIsoSeconds(),
|
|
479
|
+
fetchImpl = globalThis.fetch,
|
|
480
|
+
}) {
|
|
481
|
+
let parsedUrl;
|
|
482
|
+
try {
|
|
483
|
+
parsedUrl = new URL(registryUrl);
|
|
484
|
+
} catch {
|
|
485
|
+
throw new TypeError(`enrollGreeterInRegistry: invalid registry URL ${String(registryUrl)}`);
|
|
486
|
+
}
|
|
487
|
+
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") throw new TypeError("enrollGreeterInRegistry: registry URL must use http:// or https://"); // @rule greeter.enroll-url-scheme
|
|
488
|
+
if (!hasGreeterTag(card)) throw new TypeError("enrollGreeterInRegistry: refusing to enroll non-greeter card"); // @rule greeter.enroll-card-greeter-tag
|
|
489
|
+
|
|
490
|
+
const base = registryUrl.replace(/\/+$/, "");
|
|
491
|
+
|
|
492
|
+
const healthRes = await fetchImpl(`${base}/v1/health`, {
|
|
493
|
+
method: "GET",
|
|
494
|
+
headers: { accept: "application/json" },
|
|
495
|
+
});
|
|
496
|
+
if (!healthRes.ok) {
|
|
497
|
+
throw new Error(`enrollGreeterInRegistry: GET /v1/health failed (${healthRes.status})`);
|
|
498
|
+
}
|
|
499
|
+
const health = await healthRes.json();
|
|
500
|
+
if (!isValidUuaid(health?.uuaid)) {
|
|
501
|
+
throw new Error("enrollGreeterInRegistry: registry /v1/health returned no valid uuaid");
|
|
502
|
+
}
|
|
503
|
+
const registryUuaid = health.uuaid;
|
|
504
|
+
|
|
505
|
+
let lineageEventsPosted = 0;
|
|
506
|
+
if (Array.isArray(lineageEvents) && lineageEvents.length > 0) {
|
|
507
|
+
for (const ev of lineageEvents) {
|
|
508
|
+
const linRes = await fetchImpl(`${base}/v1/lineage`, {
|
|
509
|
+
method: "POST",
|
|
510
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
511
|
+
body: JSON.stringify(ev),
|
|
512
|
+
});
|
|
513
|
+
const linBody = await linRes.json().catch(() => ({}));
|
|
514
|
+
if (!linRes.ok || !linBody?.ok) {
|
|
515
|
+
throw new Error(`enrollGreeterInRegistry: POST /v1/lineage failed (${linRes.status}: ${linBody?.reason ?? "unknown"})`);
|
|
516
|
+
}
|
|
517
|
+
lineageEventsPosted++;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const homesCandidate = toHttpsCardUri(base);
|
|
522
|
+
const homes = homesCandidate ? [homesCandidate] : card.homes;
|
|
523
|
+
const listing = buildGreeterListing({
|
|
524
|
+
identity,
|
|
525
|
+
card,
|
|
526
|
+
registryUuaid,
|
|
527
|
+
homes,
|
|
528
|
+
stampBits,
|
|
529
|
+
issuedAt: now,
|
|
530
|
+
includeStamp: true,
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
const postRes = await fetchImpl(`${base}/v1/listings`, {
|
|
534
|
+
method: "POST",
|
|
535
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
536
|
+
body: JSON.stringify(listing),
|
|
537
|
+
});
|
|
538
|
+
const postBody = await postRes.json().catch(() => ({}));
|
|
539
|
+
if (postRes.ok && postBody?.ok) {
|
|
540
|
+
return {
|
|
541
|
+
ok: true,
|
|
542
|
+
registryUuaid,
|
|
543
|
+
lineageEventsPosted,
|
|
544
|
+
updated: Boolean(postBody.updated),
|
|
545
|
+
alreadyEnrolled: false,
|
|
546
|
+
listing,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// Fast restart within the same wall-clock second can hit `stale-listing` when the
|
|
551
|
+
// existing listing already matches this greeter's uuaid and greeter card.
|
|
552
|
+
if (postBody?.reason === "stale-listing") {
|
|
553
|
+
const checkRes = await fetchImpl(`${base}/v1/resolve/${encodeURIComponent(card.uuaid)}`, {
|
|
554
|
+
method: "GET",
|
|
555
|
+
headers: { accept: "application/json" },
|
|
556
|
+
});
|
|
557
|
+
const checkBody = await checkRes.json().catch(() => null);
|
|
558
|
+
if (checkRes.ok && checkBody?.current === card.uuaid && hasGreeterTag(checkBody?.card)) {
|
|
559
|
+
return {
|
|
560
|
+
ok: true,
|
|
561
|
+
registryUuaid,
|
|
562
|
+
lineageEventsPosted,
|
|
563
|
+
updated: false,
|
|
564
|
+
alreadyEnrolled: true,
|
|
565
|
+
listing,
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
throw new Error(`enrollGreeterInRegistry: POST /v1/listings failed (${postRes.status}: ${postBody?.reason ?? "unknown"})`);
|
|
571
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pillar vNext §2 / §3 / #23 D-5 — Multi-operator home picker (`selectHomes`),
|
|
3
|
+
* `uuaid-lineage-seen/1` receipt verification, and home-reachability watch for `@uuaid/pillar`.
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import {
|
|
8
|
+
HOMES_DEGRADED_CODE,
|
|
9
|
+
LINEAGE_SEEN_VERSION,
|
|
10
|
+
REGISTRY_LIST_VERSION,
|
|
11
|
+
checkHomeReachability,
|
|
12
|
+
publishSeq0ToHomes,
|
|
13
|
+
selectHomes,
|
|
14
|
+
signRegistryList,
|
|
15
|
+
verifySeenReceipt,
|
|
16
|
+
watchHomeReachability,
|
|
17
|
+
} from "../vendor/pillar-core.mjs";
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
HOMES_DEGRADED_CODE,
|
|
21
|
+
LINEAGE_SEEN_VERSION,
|
|
22
|
+
REGISTRY_LIST_VERSION,
|
|
23
|
+
checkHomeReachability,
|
|
24
|
+
publishSeq0ToHomes,
|
|
25
|
+
selectHomes,
|
|
26
|
+
signRegistryList,
|
|
27
|
+
verifySeenReceipt,
|
|
28
|
+
watchHomeReachability,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Extract the active declared `homes[]` from a Pillar home directory's `lineage/log.json`
|
|
33
|
+
* and run `checkHomeReachability` against them.
|
|
34
|
+
*/
|
|
35
|
+
export async function checkHomeDirReachability(homeDir, opts = {}) {
|
|
36
|
+
if (typeof homeDir !== "string" || !homeDir.trim()) throw new TypeError("checkHomeDirReachability: homeDir is required"); // @rule vnext-homes.homedir-string
|
|
37
|
+
const logPath = join(homeDir, "lineage", "log.json");
|
|
38
|
+
if (!existsSync(logPath)) return { ok: false, reason: "not-initialized" }; // @rule vnext-homes.log-exists
|
|
39
|
+
const events = JSON.parse(readFileSync(logPath, "utf8"));
|
|
40
|
+
if (!Array.isArray(events) || events.length === 0) return { ok: false, reason: "empty-lineage" }; // @rule vnext-homes.log-nonempty
|
|
41
|
+
const lineage = events[0]?.lineage;
|
|
42
|
+
let activeHomes = [];
|
|
43
|
+
for (const ev of events) {
|
|
44
|
+
if (Array.isArray(ev?.homes)) activeHomes = ev.homes;
|
|
45
|
+
}
|
|
46
|
+
if (!activeHomes.length) return { ok: true, degraded: false, healthyCount: 0, totalHomes: 0, degradedHomes: [], results: [], prompt: null }; // @rule vnext-homes.no-homes-noop
|
|
47
|
+
return checkHomeReachability(lineage, activeHomes, opts);
|
|
48
|
+
}
|