@uuaid/pillar 2.6.1 → 2.7.1

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.
Files changed (61) hide show
  1. package/README.md +325 -7
  2. package/bin/carrier.mjs +21 -0
  3. package/bin/pillar-ask.mjs +4 -1
  4. package/bin/pillar-blob.mjs +6 -0
  5. package/bin/pillar-directory.mjs +282 -16
  6. package/bin/pillar-escrow.mjs +4 -1
  7. package/bin/pillar-group-v2.mjs +6 -0
  8. package/bin/pillar-notify.mjs +13 -0
  9. package/bin/pillar-responder.mjs +266 -23
  10. package/bin/pillar.mjs +512 -257
  11. package/package.json +17 -25
  12. package/src/cli-help.mjs +23 -0
  13. package/src/group-v2-cli.mjs +1 -1
  14. package/src/identity/trust.mjs +72 -6
  15. package/src/mailbox/mailbox.mjs +313 -12
  16. package/src/net/carrier-server.mjs +34 -2
  17. package/src/net/refusals.mjs +2 -0
  18. package/src/net/seed-registry.mjs +2 -1
  19. package/src/net/transport.mjs +320 -91
  20. package/src/node-check.mjs +29 -8
  21. package/src/notify-events.mjs +148 -0
  22. package/src/notify-log.mjs +124 -0
  23. package/src/notify-runner.mjs +372 -0
  24. package/src/notify-store.mjs +736 -0
  25. package/src/notify.mjs +350 -0
  26. package/src/pillar.mjs +382 -27
  27. package/src/readers.mjs +2 -2
  28. package/src/registry/federation.mjs +3056 -0
  29. package/src/registry/gossip.mjs +294 -0
  30. package/src/registry/heartbeats.mjs +205 -0
  31. package/src/registry/lineage-verifier.mjs +972 -0
  32. package/src/registry/lineage.mjs +984 -0
  33. package/src/registry/listings.mjs +612 -0
  34. package/src/registry/resolve.mjs +376 -0
  35. package/src/registry/stats.mjs +508 -0
  36. package/src/sqlite-loader.mjs +40 -0
  37. package/src/vendor/pillar-core.mjs +22 -0
  38. package/src/vendor/uuaid-soul.mjs +2246 -0
  39. package/src/vnext/a6b-common.mjs +270 -0
  40. package/src/vnext/b1-cli.mjs +970 -0
  41. package/src/vnext/card-cli.mjs +370 -0
  42. package/src/vnext/greeter-operator.mjs +160 -0
  43. package/src/vnext/greeter-suggest.mjs +318 -0
  44. package/src/vnext/greeter.mjs +571 -0
  45. package/src/vnext/homes.mjs +48 -0
  46. package/src/vnext/init-cli.mjs +489 -0
  47. package/src/vnext/intro-cli.mjs +81 -0
  48. package/src/vnext/json-dir-mailbox.mjs +304 -0
  49. package/src/vnext/jsonl-mailbox.mjs +1132 -0
  50. package/src/vnext/knock-answer.mjs +162 -0
  51. package/src/vnext/knock-cli.mjs +520 -0
  52. package/src/vnext/knock-lane.mjs +312 -0
  53. package/src/vnext/knock-responder.mjs +344 -0
  54. package/src/vnext/lineage-cli.mjs +653 -0
  55. package/src/vnext/listing-cli.mjs +323 -0
  56. package/src/vnext/resolve-cli.mjs +104 -0
  57. package/src/vnext/soul-cli.mjs +666 -0
  58. package/src/vnext/verify-cli.mjs +333 -0
  59. package/src/vnext/w4-redirect.mjs +178 -0
  60. package/src/vnext/wave-a.mjs +193 -0
  61. package/src/vnext/witness-cli.mjs +547 -0
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Pillar vNext §4 (K0–K6, T4.3, T4.4) — Knock verification and lane separation.
3
+ *
4
+ * Reuses the byte-pinned vendored core (`../vendor/pillar-core.mjs`):
5
+ * checkKnock, checkIntro, verifyCard, verifyArtifact, verifyKnockBinding,
6
+ * verifyLineageDoc, isKeyDerivedUuaid, CARD_MAX_BYTES, KNOCK_VERSION.
7
+ */
8
+ import {
9
+ CARD_MAX_BYTES,
10
+ DEFAULT_STAMP_BITS,
11
+ KNOCK_MAX_SUMMARY_CHARS,
12
+ KNOCK_VERSION,
13
+ MAX_STAMP_BITS,
14
+ MIN_STAMP_BITS,
15
+ checkIntro,
16
+ checkKnock,
17
+ isKeyDerivedUuaid,
18
+ isStrictEd25519PublicKey,
19
+ jcs,
20
+ utf8ToBytes,
21
+ verifyArtifact,
22
+ verifyCard,
23
+ verifyKnockBinding,
24
+ verifyLineageDoc,
25
+ } from "../vendor/pillar-core.mjs";
26
+ import { isStrictIsoDateTime, nowIsoSeconds } from "./wave-a.mjs";
27
+
28
+ export const KNOCK_LANE = "knocks";
29
+ export const KNOCK_LANE_CAP = 50;
30
+ export const KNOCK_RATE_WINDOW_MS = 24 * 3600_000;
31
+ export const DEFAULT_KNOCK_MAX_BYTES = 4096;
32
+ export const MIN_KNOCK_MAX_BYTES = 1024;
33
+ export const MAX_KNOCK_MAX_BYTES = 16384;
34
+
35
+ const UUAID_RE = /^uuaid:[a-z0-9-]+:[a-z0-9-]+:[a-z0-9][a-z0-9-]*$/;
36
+ const INTENT_TAG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
37
+ const PUBKEY_RE = /^[0-9a-f]{64}$/;
38
+
39
+ const KNOCK_KEYS = new Set(["v", "from", "to", "card", "intent", "payment", "ts"]);
40
+ const INTENT_KEYS = new Set(["tag", "summary"]);
41
+ const POW_PAYMENT_KEYS = new Set(["type", "bits", "nonce", "day"]);
42
+ const INTRO_PAYMENT_KEYS = new Set(["type", "letter"]);
43
+ const STAKE_PAYMENT_KEYS = new Set(["type", "grant"]);
44
+
45
+ const RUNG_RANK = { steady: 1, durable: 2, anchor: 3 };
46
+ const TIER_TO_RUNG_RANK = {
47
+ community: 0,
48
+ Doric: 0,
49
+ supporter: 1,
50
+ Ionic: 1,
51
+ org: 2,
52
+ Corinthian: 2,
53
+ enterprise: 3,
54
+ foundation: 3,
55
+ };
56
+
57
+ function isPlainObject(v) {
58
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
59
+ const proto = Object.getPrototypeOf(v);
60
+ return proto === Object.prototype || proto === null;
61
+ }
62
+
63
+ function hasOnlyKeys(obj, allowed) {
64
+ for (const k of Object.keys(obj)) {
65
+ if (!allowed.has(k)) return false;
66
+ }
67
+ return true;
68
+ }
69
+
70
+ export function isValidUuaid(v) {
71
+ return typeof v === "string" && UUAID_RE.test(v);
72
+ }
73
+
74
+ function isValidIntent(intent) {
75
+ if (!isPlainObject(intent) || !hasOnlyKeys(intent, INTENT_KEYS)) return false; // @rule knock.intent-shape
76
+ if (typeof intent.tag !== "string" || !INTENT_TAG_RE.test(intent.tag)) return false; // @rule knock.intent-tag
77
+ if (Object.hasOwn(intent, "summary") && (typeof intent.summary !== "string" || [...intent.summary].length > KNOCK_MAX_SUMMARY_CHARS)) return false; // @rule knock.intent-summary
78
+ return true;
79
+ }
80
+
81
+ function isBlockedSender(trust, sender, senderLineage) {
82
+ if (!trust || !Array.isArray(trust.block) || trust.block.length === 0) return false;
83
+ if (typeof sender === "string" && trust.block.includes(sender)) return true; // @rule knock.blocked-uuaid
84
+ if (typeof senderLineage === "string" && trust.block.includes(senderLineage)) return true; // @rule knock.blocked-lineage
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * Resolve recipient's configured knock maxBytes (K1: default 4096, clamped to [1024, 16384]).
90
+ */
91
+ export function resolveKnockMaxBytes(knockConfig) {
92
+ const raw = knockConfig?.maxBytes;
93
+ if (Number.isInteger(raw)) {
94
+ return Math.min(Math.max(raw, MIN_KNOCK_MAX_BYTES), MAX_KNOCK_MAX_BYTES);
95
+ }
96
+ return DEFAULT_KNOCK_MAX_BYTES;
97
+ }
98
+
99
+ /**
100
+ * Resolve recipient's required PoW bits (K2: default 18, clamped to [12, 24]).
101
+ */
102
+ export function resolveRequiredBits(knockConfig) {
103
+ const raw = knockConfig?.requiredBits ?? knockConfig?.pow;
104
+ if (Number.isInteger(raw) && raw >= MIN_STAMP_BITS && raw <= MAX_STAMP_BITS) return raw;
105
+ return DEFAULT_STAMP_BITS;
106
+ }
107
+
108
+ /**
109
+ * Lookup an introducer's 64-hex lowercase Ed25519 public key in recipient contacts
110
+ * (`addressBook` Map or `knockConfig.trustedContacts` Map/object). Blocked introducers
111
+ * are never treated as contacts.
112
+ */
113
+ export function resolveContactPublicKey(introducer, { addressBook = null, trustedContacts = null, trust = null } = {}) {
114
+ if (!isValidUuaid(introducer)) return null; // @rule knock.k3-introducer-uuaid
115
+ if (Array.isArray(trust?.block) && trust.block.includes(introducer)) return null; // @rule knock.k3-blocked-introducer
116
+ let key = addressBook?.get?.(introducer)?.publicKey ?? null;
117
+ if (!key && trustedContacts) {
118
+ const entry = trustedContacts instanceof Map ? trustedContacts.get(introducer) : trustedContacts[introducer];
119
+ key = typeof entry === "string" ? entry : entry?.publicKey ?? null;
120
+ }
121
+ if (typeof key !== "string") return null;
122
+ const lower = key.toLowerCase();
123
+ return PUBKEY_RE.test(lower) ? lower : null;
124
+ }
125
+
126
+ /**
127
+ * Check whether a tier grant satisfies the recipient's configured stake rungs (K4).
128
+ * Seed tier rungs map onto tier-grant levels: steady=supporter(1), durable=org(2), anchor=enterprise/foundation(3).
129
+ */
130
+ export function grantMeetsStakeRungs(grant, acceptedRungs) {
131
+ if (!Array.isArray(acceptedRungs) || acceptedRungs.length === 0) return false;
132
+ let minAccepted = Infinity;
133
+ for (const rung of acceptedRungs) {
134
+ const r = typeof rung === "string" && Object.hasOwn(RUNG_RANK, rung) ? RUNG_RANK[rung] : undefined;
135
+ if (r !== undefined && r < minAccepted) minAccepted = r;
136
+ }
137
+ if (!Number.isFinite(minAccepted)) return false;
138
+ let tierRank = TIER_TO_RUNG_RANK[grant?.tier];
139
+ if (typeof grant?.tier !== "string" || !Object.hasOwn(TIER_TO_RUNG_RANK, grant.tier)) tierRank = undefined; // @rule knock.k4-stake-tier-own
140
+ if (!tierRank || tierRank <= 0) return false; // @rule knock.k4-stake-tier-known
141
+ if (grant.seedTier !== undefined) {
142
+ let seedRank = RUNG_RANK[grant.seedTier];
143
+ if (typeof grant.seedTier !== "string" || !Object.hasOwn(RUNG_RANK, grant.seedTier)) seedRank = undefined; // @rule knock.k4-stake-seedtier-own
144
+ if (!seedRank) return false; // @rule knock.k4-stake-seedtier-known
145
+ if (Math.min(seedRank, tierRank) < minAccepted) return false; // @rule knock.k4-stake-seedtier-rung
146
+ }
147
+ if (tierRank < minAccepted) return false; // @rule knock.k4-stake-tier-rung
148
+ return true;
149
+ }
150
+
151
+ /**
152
+ * Compute K1 effective knock size in UTF-8 bytes, excluding `payload.card` bytes
153
+ * (capped at CARD_MAX_BYTES, doubled for hex-encoded enc.ct), clamped to >= 0.
154
+ */
155
+ export function computeKnockEffectiveBytes(serializedBytes, cardBytes, { hexEncoded = false } = {}) {
156
+ const cardMultiplier = hexEncoded ? 2 : 1;
157
+ let effectiveBytes = serializedBytes - cardMultiplier * Math.min(cardBytes, CARD_MAX_BYTES);
158
+ if (effectiveBytes < 0) effectiveBytes = 0; // @rule knock.k1-effective-bytes-non-negative
159
+ return effectiveBytes;
160
+ }
161
+
162
+ /**
163
+ * Resolve trusted issuer keys for stake tier grants (accepts `trustedIssuers`,
164
+ * `trustedStakeIssuers`, or `trustedIssuerPublicKeys` in knockConfig).
165
+ */
166
+ function resolveTrustedIssuers(knockConfig) {
167
+ const src = knockConfig?.trustedIssuers ?? knockConfig?.trustedStakeIssuers ?? knockConfig?.trustedIssuerPublicKeys;
168
+ if (!Array.isArray(src)) return [];
169
+ return src.filter((k) => typeof k === "string" && PUBKEY_RE.test(k.toLowerCase())).map((k) => k.toLowerCase());
170
+ }
171
+
172
+ /**
173
+ * Verify a decrypted `kind === "knock"` envelope against K0–K4 and C1.
174
+ *
175
+ * Precondition (K0): caller has already run `open()` and `decrypt()`.
176
+ * Returns:
177
+ * { ok: true, paymentType: "pow"|"introduction"|"stake", senderLineage, card }
178
+ * or
179
+ * { ok: false, quarantine: string, detail?: string }
180
+ */
181
+ export function validateKnockEnvelope(envelope, payload, {
182
+ rawEnvelopeJson = null,
183
+ trust = null,
184
+ addressBook = null,
185
+ knockConfig = null,
186
+ now = nowIsoSeconds(),
187
+ } = {}) {
188
+ // Blocked senders ALWAYS quarantine as `blocked`, even for knocks.
189
+ const senderLineageHint = isPlainObject(payload?.card) && typeof payload.card.lineage === "string" ? payload.card.lineage : null;
190
+ if (isBlockedSender(trust, envelope?.sender, senderLineageHint)) return { ok: false, quarantine: "blocked" }; // @rule knock.blocked-sender
191
+
192
+ // K1: Serialized envelope size <= knock.maxBytes (default 4096, max 16384),
193
+ // excluding payload.card UTF-8 bytes up to 16384 (2x for hex-encoded enc.ct).
194
+ const maxBytes = resolveKnockMaxBytes(knockConfig);
195
+ const serializedBytes = Buffer.byteLength(typeof rawEnvelopeJson === "string" ? rawEnvelopeJson : JSON.stringify(envelope), "utf8");
196
+ let cardBytes = 0;
197
+ if (isPlainObject(payload) && isPlainObject(payload.card)) {
198
+ try { cardBytes = Buffer.byteLength(jcs(payload.card), "utf8"); } catch { cardBytes = 0; }
199
+ }
200
+ const effectiveBytes = computeKnockEffectiveBytes(serializedBytes, cardBytes, {
201
+ hexEncoded: Boolean(envelope?.enc && typeof envelope.enc.ct === "string"),
202
+ });
203
+ if (effectiveBytes > maxBytes) return { ok: false, quarantine: "knock-too-large" }; // @rule knock.k1-size-limit
204
+
205
+ // K0: Envelope kind & payload schema structure.
206
+ if (envelope?.kind !== "knock") return { ok: false, quarantine: "knock-kind-mismatch" }; // @rule knock.kind-required
207
+ if (!isPlainObject(payload) || payload.v !== KNOCK_VERSION || !hasOnlyKeys(payload, KNOCK_KEYS)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.payload-shape
208
+ if (!isValidIntent(payload.intent)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.intent-valid
209
+ if (!isStrictIsoDateTime(payload.ts)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.ts-valid
210
+ if (!isValidUuaid(payload.from) || !isValidUuaid(payload.to)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.k0-from-to-uuaid
211
+
212
+ // K0: Binding of payload.from/to to envelope.sender/recipient.
213
+ const bindErr = verifyKnockBinding({ from: payload.from, to: payload.to }, { sender: envelope.sender, recipient: envelope.recipient });
214
+ if (bindErr !== null) return { ok: false, quarantine: bindErr }; // @rule knock.k0-binding
215
+
216
+ // C1: Card verification + card.uuaid === envelope.sender.
217
+ const card = payload.card;
218
+ if (!isPlainObject(card) || card.uuaid !== envelope.sender) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.card-sender-match
219
+ const lineage = typeof knockConfig?.lineageResolver === "function"
220
+ ? knockConfig.lineageResolver(envelope.sender, card)
221
+ : (knockConfig?.lineages instanceof Map ? knockConfig.lineages.get(card.lineage) : knockConfig?.lineages?.[card.lineage]);
222
+
223
+ if (lineage !== undefined && lineage !== null) {
224
+ const cardVerdict = verifyCard(card, { now, lineage });
225
+ if (cardVerdict.reasons?.includes("card-key-not-current")) return { ok: false, quarantine: "card-key-not-current" }; // @rule knock.card-lineage-current
226
+ if (cardVerdict.verdict !== "valid") return { ok: false, quarantine: "knock-malformed", detail: cardVerdict.reasons?.[0] }; // @rule knock.card-lineage-valid
227
+ } else {
228
+ if (card.lineage !== envelope.sender) return { ok: false, quarantine: "card-lineage-unverified" }; // @rule knock.card-lineage-unverified
229
+ const cardVerdict = verifyCard(card, { now });
230
+ if (cardVerdict.verdict === "invalid") return { ok: false, quarantine: "knock-malformed", detail: cardVerdict.reasons?.[0] }; // @rule knock.card-schema-valid
231
+ let cardJcs;
232
+ try { cardJcs = jcs(card); } catch { return { ok: false, quarantine: "knock-malformed" }; }
233
+ if (utf8ToBytes(cardJcs).length > CARD_MAX_BYTES) return { ok: false, quarantine: "knock-too-large" }; // @rule knock.card-max-bytes
234
+ if (!isStrictEd25519PublicKey(card.publicKey)) return { ok: false, quarantine: "knock-malformed" };
235
+ if (!isKeyDerivedUuaid(card.uuaid, card.publicKey)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.card-key-derives
236
+ if (!verifyLineageDoc(card, card.publicKey, card.sig)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.card-sig-valid
237
+ }
238
+
239
+ // K2 / K3 / K4: Payment verification.
240
+ const payment = payload.payment;
241
+ if (!isPlainObject(payment) || typeof payment.type !== "string") return { ok: false, quarantine: "knock-malformed" }; // @rule knock.payment-object
242
+
243
+ if (payment.type === "pow") {
244
+ if (!hasOnlyKeys(payment, POW_PAYMENT_KEYS)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.k2-pow-keys
245
+ const requiredBits = resolveRequiredBits(knockConfig);
246
+ const powRes = checkKnock(payload, envelope, { now, requiredBits });
247
+ if (!powRes.ok) return { ok: false, quarantine: powRes.quarantine, ...(powRes.detail ? { detail: powRes.detail } : {}) }; // @rule knock.k2-pow-valid
248
+ return { ok: true, paymentType: "pow", senderLineage: card.lineage, card };
249
+ }
250
+
251
+ if (payment.type === "introduction") {
252
+ if (knockConfig?.introductions === false) return { ok: false, quarantine: "knock-payment-invalid" }; // @rule knock.k3-intros-enabled
253
+ if (!hasOnlyKeys(payment, INTRO_PAYMENT_KEYS) || !isPlainObject(payment.letter)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.k3-intro-shape
254
+ const letter = payment.letter;
255
+ if (letter.introducee !== payload.from || letter.to !== payload.to) return { ok: false, quarantine: "knock-payment-invalid" }; // @rule knock.k3-intro-binding
256
+ const introducerKey = resolveContactPublicKey(letter.introducer, {
257
+ addressBook,
258
+ trustedContacts: knockConfig?.trustedContacts ?? null,
259
+ trust,
260
+ });
261
+ if (!introducerKey) return { ok: false, quarantine: "intro-not-contact" }; // @rule knock.k3-intro-contact
262
+ const introRes = checkIntro(letter, { now, introducerPublicKey: introducerKey });
263
+ if (!introRes.ok) return { ok: false, quarantine: "knock-payment-invalid", detail: introRes.reason }; // @rule knock.k3-intro-sig-valid
264
+ return { ok: true, paymentType: "introduction", senderLineage: card.lineage, card };
265
+ }
266
+
267
+ if (payment.type === "stake") {
268
+ if (!hasOnlyKeys(payment, STAKE_PAYMENT_KEYS) || !isPlainObject(payment.grant)) return { ok: false, quarantine: "knock-malformed" }; // @rule knock.k4-stake-shape
269
+ const grant = payment.grant;
270
+ if (grant.uuaid !== payload.from) return { ok: false, quarantine: "knock-payment-invalid" }; // @rule knock.k4-stake-uuaid
271
+ if (!grantMeetsStakeRungs(grant, knockConfig?.stake)) return { ok: false, quarantine: "knock-payment-invalid" }; // @rule knock.k4-stake-rung
272
+ const trustedIssuers = resolveTrustedIssuers(knockConfig);
273
+ const grantVerdict = verifyArtifact(grant, { type: "tier-grant", now, trustedIssuers });
274
+ if (grantVerdict.verdict !== "valid") return { ok: false, quarantine: "knock-payment-invalid", detail: grantVerdict.reasons?.[0] }; // @rule knock.k4-stake-verify
275
+ return { ok: true, paymentType: "stake", senderLineage: card.lineage, card };
276
+ }
277
+
278
+ return { ok: false, quarantine: "knock-malformed" }; // @rule knock.payment-type-known
279
+ }
280
+
281
+ /**
282
+ * True if an inbox row (SQLite or JSON-dir) carries a `kind === "knock"` envelope or
283
+ * is filed in the `knocks` lane. Used by K5 separation across both mailbox backends.
284
+ */
285
+ export function isKnockInboxRow(row) {
286
+ if (!row || typeof row !== "object") return false;
287
+ if (row.lane === KNOCK_LANE) return true;
288
+ if (typeof row.envelope_json === "string") {
289
+ try {
290
+ const env = JSON.parse(row.envelope_json);
291
+ if (env && typeof env === "object" && env.kind === "knock") return true;
292
+ } catch { /* ignore unparseable */ }
293
+ }
294
+ return false;
295
+ }
296
+
297
+ /** K5: Filter out knock rows from regular inbox views (used by JSON-dir and mailbox queries). */
298
+ export function filterRegularInboxRows(rows) {
299
+ return rows.filter((row) => {
300
+ if (isKnockInboxRow(row)) return false; // @rule knock.k5-exclude-regular-inbox
301
+ return true;
302
+ });
303
+ }
304
+
305
+ /** K5: Keep only non-quarantined knock rows (used by JSON-dir knocks-lane queries). */
306
+ export function filterKnockInboxRows(rows) {
307
+ return rows.filter((row) => {
308
+ if (!isKnockInboxRow(row)) return false; // @rule knock.k5-only-knock-rows
309
+ if (row.quarantined != null) return false; // @rule knock.k5-exclude-quarantined-knocks
310
+ return true;
311
+ });
312
+ }
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Pillar vNext §4 (K8, SEC-1, T4.7) — Injection-safe knock auto-responder.
3
+ *
4
+ * Security invariants (SEC-1 / OWASP ASI01 & ASI09 / T4.7):
5
+ * 1. Every untrusted text field (`intent.summary`, `card.about`,
6
+ * `card.does[*].summary`, `card.wants[*].summary`, `payment.letter.note`,
7
+ * `card.name`, `note`) is inert data. It is ALWAYS rendered JSON-quoted
8
+ * inside a structured inert-data block and NEVER passed as instructions.
9
+ * 2. Strangers' knock payloads are NEVER passed to a shell command hook or
10
+ * tool executor, even when the responder has a `command` hook configured
11
+ * for trusted `request` envelopes.
12
+ * 3. Auto-answer decisions depend ONLY on typed fields (`payment.type`,
13
+ * `intent.tag`), are idempotent across restarts via an append-only
14
+ * 0600 journal, and emit at most 1 answer per knock.
15
+ */
16
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+ import { SUGGESTION_WAIT_MS } from "./greeter-suggest.mjs";
19
+ import { KNOCK_ANSWER_DECISIONS } from "./knock-answer.mjs";
20
+ import { nowIsoSeconds } from "./wave-a.mjs";
21
+ import {
22
+ GREETER_JOURNAL_FILE,
23
+ GreeterJournal,
24
+ normalizeGreeterRules,
25
+ resolveGreeterSenderLineage,
26
+ resolveResponderHookCmd,
27
+ } from "./greeter.mjs";
28
+
29
+ const VALID_RULE_ACTIONS = new Set([...KNOCK_ANSWER_DECISIONS, "none"]);
30
+
31
+ /**
32
+ * Quote untrusted peer text as a JSON string literal (SEC-1 / T4.7).
33
+ * Escapes quotes, backslashes, control characters, and Unicode line separators.
34
+ */
35
+ export function quoteInertText(value) {
36
+ return JSON.stringify(String(value ?? "")).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); // @rule responder.inert-quote
37
+ }
38
+
39
+ /**
40
+ * Produce a structured, inert-data-only summary object for a knock envelope.
41
+ * Every text field is preserved as raw data under `inertData: true` (never a prompt).
42
+ */
43
+ export function buildInertKnockRecord(envelope, payload) {
44
+ const card = payload?.card ?? {};
45
+ const does = Array.isArray(card.does)
46
+ ? card.does.map((d) => ({
47
+ ...(d?.tag !== undefined ? { tag: d.tag } : {}),
48
+ ...(d?.action !== undefined ? { action: d.action } : {}),
49
+ ...(d?.summary !== undefined ? { summary: String(d.summary) } : {}),
50
+ }))
51
+ : [];
52
+ const wants = Array.isArray(card.wants)
53
+ ? card.wants.map((w) => ({
54
+ ...(w?.tag !== undefined ? { tag: w.tag } : {}),
55
+ ...(w?.action !== undefined ? { action: w.action } : {}),
56
+ ...(w?.summary !== undefined ? { summary: String(w.summary) } : {}),
57
+ }))
58
+ : [];
59
+ return {
60
+ inertData: true,
61
+ knockId: envelope?.id ?? null,
62
+ from: envelope?.sender ?? payload?.from ?? null,
63
+ lineage: card.lineage ?? null,
64
+ paymentType: payload?.payment?.type ?? null,
65
+ intent: {
66
+ tag: payload?.intent?.tag ?? null,
67
+ ...(payload?.intent?.summary !== undefined ? { summary: String(payload.intent.summary) } : {}),
68
+ },
69
+ card: {
70
+ name: card.name !== undefined ? String(card.name) : null,
71
+ ...(card.about !== undefined ? { about: String(card.about) } : {}),
72
+ does,
73
+ wants,
74
+ },
75
+ ...(payload?.payment?.type === "introduction" && payload?.payment?.letter?.note !== undefined
76
+ ? { introNote: String(payload.payment.letter.note) }
77
+ : {}),
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Render a knock into a structured inert-data text block where EVERY untrusted
83
+ * text field (`about`, `summary`, `intent.summary`, `note`, `name`) is JSON-quoted
84
+ * (SEC-1 / T4.7).
85
+ */
86
+ export function renderKnockDataBlock(envelope, payload) {
87
+ const rec = buildInertKnockRecord(envelope, payload);
88
+ const lines = [
89
+ "[INERT_KNOCK_DATA — UNTRUSTED PEER TEXT; DATA ONLY]",
90
+ `knock_id: ${quoteInertText(rec.knockId ?? "")}`,
91
+ `from: ${quoteInertText(rec.from ?? "")}`,
92
+ `payment_type: ${quoteInertText(rec.paymentType ?? "")}`,
93
+ `intent.tag: ${quoteInertText(rec.intent.tag ?? "")}`,
94
+ ];
95
+ if (rec.intent.summary !== undefined) {
96
+ lines.push(`intent.summary: ${quoteInertText(rec.intent.summary)}`);
97
+ }
98
+ if (rec.card.name !== null) {
99
+ lines.push(`card.name: ${quoteInertText(rec.card.name)}`);
100
+ }
101
+ if (rec.card.about !== undefined) {
102
+ lines.push(`card.about: ${quoteInertText(rec.card.about)}`);
103
+ }
104
+ rec.card.does.forEach((d, idx) => {
105
+ const label = d.tag ?? d.action ?? "";
106
+ lines.push(`card.does[${idx}].id: ${quoteInertText(label)}`);
107
+ if (d.summary !== undefined) {
108
+ lines.push(`card.does[${idx}].summary: ${quoteInertText(d.summary)}`);
109
+ }
110
+ });
111
+ rec.card.wants.forEach((w, idx) => {
112
+ const label = w.tag ?? w.action ?? "";
113
+ lines.push(`card.wants[${idx}].id: ${quoteInertText(label)}`);
114
+ if (w.summary !== undefined) {
115
+ lines.push(`card.wants[${idx}].summary: ${quoteInertText(w.summary)}`);
116
+ }
117
+ });
118
+ if (rec.introNote !== undefined) {
119
+ lines.push(`payment.letter.note: ${quoteInertText(rec.introNote)}`);
120
+ }
121
+ lines.push("[/INERT_KNOCK_DATA]");
122
+ return lines.join("\n");
123
+ }
124
+
125
+ /**
126
+ * Render an inert `note` field (e.g. from a knock answer) JSON-quoted.
127
+ */
128
+ export function renderInertNote(note) {
129
+ if (note === undefined || note === null) return "";
130
+ return `note: ${quoteInertText(note)}`;
131
+ }
132
+
133
+ /**
134
+ * Guard deciding whether a responder shell command hook may run for an envelope.
135
+ * Knocks are NEVER passed to a shell command hook (SEC-1 / T4.7).
136
+ */
137
+ export function shouldRunResponderHook(envelope, gate, hookCmd) {
138
+ if (!hookCmd) return false; // @rule responder.hook-cmd-required
139
+ if (envelope?.kind === "knock") return false; // @rule responder.knock-never-spawns-hook
140
+ return Boolean(gate?.deliver);
141
+ }
142
+
143
+ /**
144
+ * Decide an auto-answer action from typed knock fields ONLY (`payment.type`,
145
+ * `intent.tag`). Untrusted free text (`summary`, `about`, `note`) is never read.
146
+ */
147
+ export function decideKnockAutoAnswer(knockView, rules = null) {
148
+ if (!rules || rules.enabled === false) return { action: "none" }; // @rule responder.rules-enabled
149
+ const payload = knockView?.payload ?? knockView;
150
+ const paymentType = payload?.payment?.type;
151
+ const intentTag = payload?.intent?.tag;
152
+
153
+ let decision;
154
+ let tagRuleHit = false;
155
+ if (rules.tagRules && typeof intentTag === "string") {
156
+ tagRuleHit = true;
157
+ if (!Object.hasOwn(rules.tagRules, intentTag)) tagRuleHit = false; // @rule responder.tag-rules-own-prop
158
+ }
159
+ if (tagRuleHit) {
160
+ decision = rules.tagRules[intentTag];
161
+ } else if (paymentType === "introduction") {
162
+ decision = rules.onIntroduction ?? "accept";
163
+ } else if (paymentType === "stake") {
164
+ decision = rules.onStake ?? rules.defaultDecision ?? "later";
165
+ } else if (paymentType === "pow") {
166
+ decision = rules.onPow ?? rules.defaultDecision ?? "later";
167
+ } else {
168
+ decision = "none";
169
+ }
170
+
171
+ if (!VALID_RULE_ACTIONS.has(decision)) return { action: "none" }; // @rule responder.rule-decision-closed
172
+ const out = { action: decision };
173
+ if (decision === "accept" && Array.isArray(rules.acceptScope) && rules.acceptScope.length > 0) {
174
+ out.scope = [...rules.acceptScope];
175
+ }
176
+ if (typeof rules.note === "string" && rules.note.length > 0) {
177
+ out.note = rules.note;
178
+ }
179
+ return out;
180
+ }
181
+
182
+ function loadAnsweredSet(journalPath) {
183
+ const answered = new Set();
184
+ if (!journalPath || !existsSync(journalPath)) return answered;
185
+ for (const line of readFileSync(journalPath, "utf8").split("\n")) {
186
+ if (!line.trim()) continue;
187
+ try {
188
+ const rec = JSON.parse(line);
189
+ if (rec?.event === "knock-answered" && typeof rec.sender === "string" && typeof rec.id === "string") {
190
+ answered.add(`${rec.sender}\u0000${rec.id}`);
191
+ }
192
+ } catch { /* ignore torn line */ }
193
+ }
194
+ return answered;
195
+ }
196
+
197
+ /**
198
+ * Stateful, idempotent knock auto-responder with a 0600 journal and zero
199
+ * shell/tool invocation for knocks.
200
+ */
201
+ export class KnockResponder {
202
+ constructor({
203
+ pillar,
204
+ card,
205
+ rules = undefined,
206
+ journalPath = null,
207
+ home = null,
208
+ hookCmd = null,
209
+ onHookAttempt = null,
210
+ now = nowIsoSeconds,
211
+ greeter = false,
212
+ suggest = null,
213
+ suggestBudgetMs = SUGGESTION_WAIT_MS,
214
+ }) {
215
+ this.pillar = pillar;
216
+ this.card = card;
217
+ this.greeter = Boolean(greeter || rules?.greeter === true);
218
+ // B7: only greeters attach suggestions, computed by the published rule (src/vnext/greeter-suggest.mjs).
219
+ this._suggest = typeof suggest === "function" ? suggest : null;
220
+ if (!this.greeter) this._suggest = null; // @rule responder.suggest-greeter-only
221
+ // B7 fix round 2: the longest one accept waits for suggestions (wall clock, not the knock `now`).
222
+ this._suggestBudgetMs = Number.isFinite(suggestBudgetMs) && suggestBudgetMs > 0 ? suggestBudgetMs : SUGGESTION_WAIT_MS;
223
+ this.rules = this.greeter
224
+ ? normalizeGreeterRules(rules)
225
+ : (rules === undefined ? { enabled: true, onIntroduction: "accept", onPow: "later", onStake: "later" } : rules);
226
+ this.journalPath = journalPath ?? (home ? join(home, this.greeter ? GREETER_JOURNAL_FILE : "responder-journal.jsonl") : null);
227
+ this._hookCmd = resolveResponderHookCmd(this.greeter, hookCmd);
228
+ this._onHookAttempt = onHookAttempt;
229
+ this._now = typeof now === "function" ? now : () => String(now);
230
+ this._answered = loadAnsweredSet(this.journalPath);
231
+ this._inFlight = new Set();
232
+ this._greeterJournal = this.greeter ? new GreeterJournal({ journalPath: this.journalPath }) : null;
233
+ }
234
+
235
+ _recordJournal(entry) {
236
+ if (!this.journalPath) return;
237
+ mkdirSync(dirname(this.journalPath), { recursive: true });
238
+ appendFileSync(this.journalPath, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
239
+ }
240
+
241
+ /**
242
+ * B7: compute suggestions for one knock. Any failure omits the field, so the knock still gets
243
+ * its one answer (Wave A silence rules: one answer, no follow-ups, no receipts). The wait is
244
+ * bounded by `suggestBudgetMs`: past it, the accept goes out without suggestions.
245
+ */
246
+ async _safeSuggest(view, now) {
247
+ let timer = null;
248
+ try {
249
+ let pending = this._suggest({ knocker: view.sender, knockerCard: view.payload?.card ?? null, now });
250
+ const budget = new Promise((resolveBudget) => { timer = setTimeout(resolveBudget, this._suggestBudgetMs, undefined); });
251
+ pending = Promise.race([pending, budget]); // @rule responder.suggest-budget
252
+ const list = await pending;
253
+ return Array.isArray(list) ? list.slice(0, 3) : undefined;
254
+ } catch {
255
+ return undefined;
256
+ } finally {
257
+ clearTimeout(timer);
258
+ }
259
+ }
260
+
261
+ hasAnswered(sender, id) {
262
+ return this._answered.has(`${sender}\u0000${id}`);
263
+ }
264
+
265
+ hasGreeted(senderLineage, sender = null) {
266
+ return this._greeterJournal ? this._greeterJournal.hasGreeted(senderLineage, sender) : false;
267
+ }
268
+
269
+ async handleKnock(view, meta = {}) {
270
+ if (view?.kind !== "knock") return { handled: false, reason: "not-knock" }; // @rule responder.knock-kind-only
271
+ const key = `${view.sender}\u0000${view.id}`;
272
+ if (this._answered.has(key)) return { handled: false, reason: "already-answered" }; // @rule responder.knock-idempotent
273
+ if (this._inFlight.has(key)) return { handled: false, reason: "in-flight" }; // @rule responder.knock-in-flight
274
+
275
+ let senderLineage = null;
276
+ if (this.greeter) {
277
+ senderLineage = resolveGreeterSenderLineage(view, meta);
278
+ const gate = this._greeterJournal.tryBegin(senderLineage, view.sender);
279
+ if (!gate.allow) return { handled: false, reason: gate.reason };
280
+ }
281
+
282
+ try {
283
+ // SEC-1 / T4.7: Render untrusted fields strictly JSON-quoted in an inert data block.
284
+ const rendered = renderKnockDataBlock(view, view.payload);
285
+ const data = buildInertKnockRecord(view, view.payload);
286
+
287
+ // Explicitly verify hook gate refuses knocks even when a hook command is configured.
288
+ if (shouldRunResponderHook(view, { deliver: true }, this._hookCmd)) {
289
+ this._onHookAttempt?.(view);
290
+ throw new Error("SEC-1 violation: responder attempted to run shell hook for a knock");
291
+ }
292
+
293
+ const plan = decideKnockAutoAnswer(view, this.rules);
294
+ if (plan.action === "none") return { handled: false, reason: "rule-none", rendered, data }; // @rule responder.rule-none-skips-send
295
+
296
+ const ts = this._now();
297
+ this._inFlight.add(key);
298
+ let answer;
299
+ let suggestions;
300
+ try {
301
+ let suggestAllowed = this._suggest !== null;
302
+ if (plan.action !== "accept") suggestAllowed = false; // @rule responder.suggest-on-accept
303
+ if (suggestAllowed) suggestions = await this._safeSuggest(view, ts);
304
+ answer = await this.pillar.answerKnock({
305
+ knockId: view.id,
306
+ sender: view.sender,
307
+ decision: plan.action,
308
+ card: this.card,
309
+ ...(plan.note !== undefined ? { note: plan.note } : {}),
310
+ ...(plan.scope !== undefined ? { scope: plan.scope } : {}),
311
+ ...(suggestions !== undefined ? { suggestions } : {}),
312
+ now: ts,
313
+ });
314
+ } finally {
315
+ this._inFlight.delete(key);
316
+ }
317
+
318
+ this._answered.add(key);
319
+ if (this.greeter) {
320
+ this._greeterJournal.markGreeted({
321
+ id: view.id,
322
+ sender: view.sender,
323
+ senderLineage,
324
+ decision: plan.action,
325
+ paymentType: view.payload?.payment?.type ?? null,
326
+ ts,
327
+ });
328
+ } else {
329
+ this._recordJournal({
330
+ ts,
331
+ event: "knock-answered",
332
+ id: view.id,
333
+ sender: view.sender,
334
+ decision: plan.action,
335
+ paymentType: view.payload?.payment?.type ?? null,
336
+ });
337
+ }
338
+
339
+ return { handled: true, decision: plan.action, rendered, data, answer };
340
+ } finally {
341
+ if (this.greeter && senderLineage) this._greeterJournal.endInFlight(senderLineage);
342
+ }
343
+ }
344
+ }