@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.
Files changed (62) hide show
  1. package/HOSTING-LIMITS.md +12 -0
  2. package/README.md +201 -5
  3. package/bin/carrier.mjs +72 -2
  4. package/bin/pillar-ask.mjs +4 -1
  5. package/bin/pillar-blob.mjs +6 -0
  6. package/bin/pillar-directory.mjs +280 -16
  7. package/bin/pillar-escrow.mjs +4 -1
  8. package/bin/pillar-group-v2.mjs +6 -0
  9. package/bin/pillar-notify.mjs +13 -0
  10. package/bin/pillar-responder.mjs +266 -23
  11. package/bin/pillar.mjs +504 -255
  12. package/package.json +17 -25
  13. package/src/cli-help.mjs +23 -0
  14. package/src/group-v2-cli.mjs +1 -1
  15. package/src/identity/trust.mjs +72 -6
  16. package/src/mailbox/mailbox.mjs +308 -12
  17. package/src/net/carrier-server.mjs +34 -2
  18. package/src/net/refusals.mjs +2 -0
  19. package/src/net/seed-registry.mjs +2 -1
  20. package/src/net/transport.mjs +308 -92
  21. package/src/node-check.mjs +29 -8
  22. package/src/notify-events.mjs +148 -0
  23. package/src/notify-log.mjs +124 -0
  24. package/src/notify-runner.mjs +372 -0
  25. package/src/notify-store.mjs +725 -0
  26. package/src/notify.mjs +350 -0
  27. package/src/pillar.mjs +382 -27
  28. package/src/readers.mjs +2 -2
  29. package/src/registry/federation.mjs +3056 -0
  30. package/src/registry/gossip.mjs +294 -0
  31. package/src/registry/heartbeats.mjs +195 -0
  32. package/src/registry/lineage-verifier.mjs +972 -0
  33. package/src/registry/lineage.mjs +984 -0
  34. package/src/registry/listings.mjs +549 -0
  35. package/src/registry/resolve.mjs +376 -0
  36. package/src/registry/stats.mjs +508 -0
  37. package/src/sqlite-loader.mjs +40 -0
  38. package/src/vendor/pillar-core.mjs +22 -0
  39. package/src/vendor/uuaid-soul.mjs +2246 -0
  40. package/src/vnext/a6b-common.mjs +270 -0
  41. package/src/vnext/b1-cli.mjs +970 -0
  42. package/src/vnext/card-cli.mjs +370 -0
  43. package/src/vnext/greeter-operator.mjs +160 -0
  44. package/src/vnext/greeter-suggest.mjs +318 -0
  45. package/src/vnext/greeter.mjs +571 -0
  46. package/src/vnext/homes.mjs +48 -0
  47. package/src/vnext/init-cli.mjs +489 -0
  48. package/src/vnext/intro-cli.mjs +81 -0
  49. package/src/vnext/json-dir-mailbox.mjs +296 -0
  50. package/src/vnext/jsonl-mailbox.mjs +1066 -0
  51. package/src/vnext/knock-answer.mjs +162 -0
  52. package/src/vnext/knock-cli.mjs +520 -0
  53. package/src/vnext/knock-lane.mjs +312 -0
  54. package/src/vnext/knock-responder.mjs +344 -0
  55. package/src/vnext/lineage-cli.mjs +653 -0
  56. package/src/vnext/listing-cli.mjs +323 -0
  57. package/src/vnext/resolve-cli.mjs +86 -0
  58. package/src/vnext/soul-cli.mjs +666 -0
  59. package/src/vnext/verify-cli.mjs +251 -0
  60. package/src/vnext/w4-redirect.mjs +178 -0
  61. package/src/vnext/wave-a.mjs +193 -0
  62. package/src/vnext/witness-cli.mjs +547 -0
package/src/pillar.mjs CHANGED
@@ -14,29 +14,50 @@
14
14
  * await pillar.send({ recipient, kind, payload });
15
15
  * await pillar.stop();
16
16
  */
17
- import { fromString as u8FromString, toString as u8ToString } from "uint8arrays";
18
- import { CID } from "multiformats/cid";
19
- import * as raw from "multiformats/codecs/raw";
20
- import { sha256 } from "multiformats/hashes/sha2";
21
- import { createTransport, PILLAR_PROTOCOL, uuaidToDhtKey, peerIdFromEd25519Hex } from "./net/transport.mjs";
17
+ import {
18
+ createTransport,
19
+ PILLAR_PROTOCOL,
20
+ uuaidToDhtKey,
21
+ peerIdFromEd25519Hex,
22
+ loadP2pRuntime,
23
+ computeUuaidCidV1,
24
+ } from "./net/transport.mjs";
22
25
  import { seal, open, decrypt, envelopeSha, mkEnvelopeId, ENVELOPE_VERSION } from "./net/envelope.mjs";
23
26
  import { Mailbox, isErasedRow } from "./mailbox/mailbox.mjs";
24
27
  import { CarrierClient } from "./net/carrier-client.mjs";
25
28
  import { REFUSAL_FIXES } from "./net/refusals.mjs";
26
29
  import { Observability } from "./observability.mjs";
27
- import { evaluateTrust } from "./identity/trust.mjs";
30
+ import { evaluateTrust, allowSenderInTrust, DEFAULT_KNOCK_ACCEPT_SCOPE } from "./identity/trust.mjs";
28
31
  import { keyDerivesUuaid } from "./identity/keychain.mjs";
29
32
  import {
30
33
  extractGroupTag, buildGroupTag, absorbGroupTag, newGroupId, newGroupMsgId, normalizeMembers, isGroupId,
31
34
  } from "./groups.mjs";
32
- import { applyReceipt, answersOurSend, deliveryAck, planReadReceipts, readReceipt } from "./receipts.mjs";
35
+ import { applyReceipt, answersOurSend, deliveryAck, isReadReceipt, planReadReceipts, readReceipt } from "./receipts.mjs";
33
36
  import { GroupReceiver, RosterStore, isGroupIdV2, adminOf, buildGroupTag as buildGroupTagV2, manifestHash as manifestHashOf, loadGroupForCommand } from "./groups-v2.mjs";
34
37
  import { randomBytes } from "node:crypto";
35
38
  import { dirname } from "node:path";
39
+
40
+ /** Envelopes a carrier serves per inbox request (src/net/carrier-server.mjs _handleInbox, "limit 200"). */
41
+ export const CARRIER_INBOX_PAGE = 200;
36
42
  import {
37
43
  BLOB_KIND, MAX_INLINE_BODY_BYTES, BlobError, BlobSizeError, envelopeBodyBytes, preflightBodyBytes,
38
44
  prepareBlobSend, fetchAndDecryptBlob, prepareBrokerBlobSend, fetchBrokerBlob,
39
45
  } from "./blob/blob.mjs";
46
+ import { buildKnock, resolve as resolveListing } from "./vendor/pillar-core.mjs";
47
+ import { KNOCK_LANE, KNOCK_LANE_CAP, KNOCK_RATE_WINDOW_MS, validateKnockEnvelope } from "./vnext/knock-lane.mjs";
48
+ import { KNOCK_ANSWER_KIND, answersOurKnock, buildKnockAnswer } from "./vnext/knock-answer.mjs";
49
+ import { nowIsoSeconds } from "./vnext/wave-a.mjs";
50
+ import { W4_CONFIRM_CODE, w4ApplyPolicy, w4ClassifyVerifiedTarget, recordRedirect } from "./vnext/w4-redirect.mjs";
51
+
52
+ export class W4RefusalError extends Error {
53
+ constructor(code, fix, details = {}) {
54
+ super(`${code}: ${fix}`);
55
+ this.name = "W4RefusalError";
56
+ this.code = code;
57
+ this.fix = fix;
58
+ this.details = details;
59
+ }
60
+ }
40
61
 
41
62
  const VALUE_STORE_PREFIX = "/uuaid/1.0";
42
63
 
@@ -61,11 +82,18 @@ export class Pillar {
61
82
  senderKeyCheck = null, // registry gate for senders not derived from their key: (uuaid, pubkeyHex) => status
62
83
  reader = null, // reader key recorded on every row this process stores (src/readers.mjs)
63
84
  receipts = null, // { delivered, read }: send signed acks / read receipts (receipts.mjs); null = neither
85
+ notifySink = null, // NotifySink (src/notify-events.mjs): eligibility events after final admission; null = none
64
86
  groupsV2Home = null, // where groups-v2/ lives (pillar-group/2 store); default: the mailbox's directory
87
+ home = null, // agent home directory (for trust.json persistence on knock accept)
88
+ knockConfig = null, // vNext §4 knock policy: { requiredBits?, maxBytes?, introductions?, stake?, trustedIssuers?, trustedContacts?, lineageResolver?, lineages?, selfLineage?, card?, cap?, rateWindowMs?, now? }
89
+ registryUrl = null, // vNext §3 registry base URL; when set, sends follow W-4 sender redirect policy (B5, T2.7)
65
90
  }) {
66
91
  if (!keychain?._identity) throw new Error("Pillar: keychain must be loaded before construction");
67
92
  this.keychain = keychain;
68
93
  this.mailbox = new Mailbox(mailboxPath);
94
+ this.home = home ?? (typeof mailboxPath === "string" ? dirname(mailboxPath) : null);
95
+ this.knockConfig = knockConfig;
96
+ this.registryUrl = registryUrl;
69
97
  this.listenAddrs = listenAddrs;
70
98
  this.bootstrapPeers = bootstrapPeers;
71
99
  this.enableRelay = enableRelay;
@@ -88,7 +116,9 @@ export class Pillar {
88
116
  this.senderKeyCheck = senderKeyCheck;
89
117
  this.reader = reader;
90
118
  this.receipts = { delivered: !!receipts?.delivered, read: !!receipts?.read };
119
+ this.notifySink = notifySink;
91
120
  this._envelopeHandlers = new Set();
121
+ this._knockHandlers = new Set();
92
122
  // pillar-group/2. Starting the receiver re-syncs every stored group's
93
123
  // mailbox row from the verified store. Its `sends` are NOT executed: no
94
124
  // send path reads the v2 store until that policy is decided.
@@ -126,7 +156,7 @@ export class Pillar {
126
156
  // populate. The @libp2p/bootstrap discovery service by itself does not
127
157
  // trigger dials in every libp2p config, so we do it explicitly.
128
158
  if (this.bootstrapPeers && this.bootstrapPeers.length > 0) {
129
- const { multiaddr } = await import("@multiformats/multiaddr");
159
+ const { multiaddr } = await loadP2pRuntime();
130
160
  await Promise.allSettled(
131
161
  this.bootstrapPeers.map(async (ma) => {
132
162
  try { await this.node.dial(multiaddr(ma)); }
@@ -193,8 +223,11 @@ export class Pillar {
193
223
  * so the CID is content-addressed on the UUAID itself.
194
224
  */
195
225
  async _uuaidCid(uuaid) {
196
- const digest = await sha256.digest(u8FromString(uuaid));
197
- return CID.createV1(raw.code, digest);
226
+ if (this.node) {
227
+ const p2p = await loadP2pRuntime();
228
+ return p2p.uuaidCid(uuaid);
229
+ }
230
+ return computeUuaidCidV1(uuaid);
198
231
  }
199
232
 
200
233
  /**
@@ -232,7 +265,6 @@ export class Pillar {
232
265
  */
233
266
  async resolveUuaid(uuaid, { timeoutMs = 15000 } = {}) {
234
267
  if (!this.node) throw new Error("pillar not started");
235
- const { peerIdFromCID } = await import("@libp2p/peer-id");
236
268
  const cid = await this._uuaidCid(uuaid);
237
269
  const signal = AbortSignal.timeout(timeoutMs);
238
270
  for await (const provider of this.node.contentRouting.findProviders(cid, { signal })) {
@@ -263,6 +295,134 @@ export class Pillar {
263
295
  return () => this._envelopeHandlers.delete(handler);
264
296
  }
265
297
 
298
+ /** Subscribe to verified inbound `knock` envelopes in the capped `knocks` lane (K5). */
299
+ onKnock(handler) {
300
+ this._knockHandlers.add(handler);
301
+ return () => this._knockHandlers.delete(handler);
302
+ }
303
+
304
+ _knockNow() {
305
+ if (typeof this.knockConfig?.now === "function") return this.knockConfig.now();
306
+ if (typeof this.knockConfig?.now === "string") return this.knockConfig.now;
307
+ return nowIsoSeconds();
308
+ }
309
+
310
+ _knockRecipientLineage() {
311
+ return this.knockConfig?.selfLineage ?? this.knockConfig?.card?.lineage ?? this.uuaid;
312
+ }
313
+
314
+ /**
315
+ * Build and send a `pillar-knock/1` (`kind: "knock"`) envelope to `recipient`.
316
+ */
317
+ async sendKnock({ recipient, recipientPublicKey, card, intent, payment, bits, ts, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
318
+ const senderCard = card ?? this.knockConfig?.card;
319
+ const effTs = ts !== undefined ? ts : this._knockNow();
320
+ let w4 = { direct: true }, effTo = recipient;
321
+ w4 = await this._w4Gate(recipient, { registryUrl: registryUrl ?? this.registryUrl, recipientPublicKey, confirmRecovered, now: now ?? effTs, urlMap, allowInsecureLoopback, fetch: fetchOverride }); // @rule W-send-w4-knock-gate
322
+ if (!w4.direct) effTo = w4.target; // @rule W-send-w4-knock-target
323
+ const payload = buildKnock({
324
+ from: this.uuaid,
325
+ to: effTo,
326
+ card: senderCard,
327
+ intent,
328
+ ...(payment !== undefined ? { payment } : {}),
329
+ ...(bits !== undefined ? { bits } : {}),
330
+ ts: effTs,
331
+ });
332
+ const effPub = !w4.direct ? w4.publicKey : (recipientPublicKey ?? w4.publicKey);
333
+ const sent = await this.send({ recipient: effTo, recipientPublicKey: effPub, kind: "knock", payload, resolveTimeoutMs, registryUrl: effPub ? null : (registryUrl ?? this.registryUrl), confirmRecovered, now: now ?? effTs, urlMap, allowInsecureLoopback, fetch: fetchOverride });
334
+ return w4.record ? { ...sent, redirectedFrom: recipient, redirectedTo: w4.target } : sent;
335
+ }
336
+
337
+ /**
338
+ * Answer a knock in the `knocks` lane (K8):
339
+ * - Validates & builds `pillar-knock-answer/1`.
340
+ * - On `accept`, adds knocker to `trust.json` `allow` (mode 0600, scoped),
341
+ * registers `card.publicKey` in `addressBook`, marks the knock answered,
342
+ * and sends `kind: "knock.answer"`.
343
+ */
344
+ async answerKnock({
345
+ knockId,
346
+ sender,
347
+ decision,
348
+ card,
349
+ note,
350
+ scope,
351
+ suggestions,
352
+ now,
353
+ resolveTimeoutMs = 5000,
354
+ sealOnly = false,
355
+ }) {
356
+ const row = this.mailbox.getKnock(knockId, sender);
357
+ if (!row) throw new Error(`answerKnock: knock ${knockId} not found`);
358
+ const knockEnv = JSON.parse(row.envelope_json);
359
+ const knockPayload = decrypt(this.keychain, knockEnv);
360
+ const knockerUuaid = knockEnv.sender;
361
+ const knockerPublicKey = knockPayload?.card?.publicKey;
362
+ if (!knockerPublicKey) throw new Error(`answerKnock: knock ${knockId} carries no card publicKey`);
363
+
364
+ const answerNow = now ?? this._knockNow();
365
+ const answerCard = card ?? this.knockConfig?.card;
366
+ if (!answerCard || answerCard.uuaid !== this.uuaid) {
367
+ throw new Error("answerKnock: recipient card matching this identity is required");
368
+ }
369
+ const effectiveScope = decision === "accept"
370
+ ? (Array.isArray(scope) && scope.length ? [...scope] : [...DEFAULT_KNOCK_ACCEPT_SCOPE])
371
+ : scope;
372
+ const answerPayload = buildKnockAnswer({
373
+ to: knockerUuaid,
374
+ knock: row.envelope_id,
375
+ decision,
376
+ card: answerCard,
377
+ ...(note !== undefined ? { note } : {}),
378
+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
379
+ ...(suggestions !== undefined ? { suggestions } : {}),
380
+ now: answerNow,
381
+ });
382
+
383
+ if (decision === "accept") {
384
+ this.registerKey(knockerUuaid, knockerPublicKey);
385
+ this.trust = allowSenderInTrust(this.trust, knockerUuaid, {
386
+ home: this.home,
387
+ scope: effectiveScope,
388
+ });
389
+ }
390
+
391
+ let sent;
392
+ if (sealOnly || (!this.node && !this.carrierClient)) {
393
+ const envelope = seal(this.keychain, {
394
+ recipient: knockerUuaid,
395
+ recipientPublicKey: knockerPublicKey,
396
+ kind: KNOCK_ANSWER_KIND,
397
+ payload: answerPayload,
398
+ });
399
+ const persisted = this.mailbox.appendOutbound(envelope);
400
+ sent = { envelope, persisted, via: "sealed-only" };
401
+ } else {
402
+ sent = await this.send({
403
+ recipient: knockerUuaid,
404
+ recipientPublicKey: knockerPublicKey,
405
+ kind: KNOCK_ANSWER_KIND,
406
+ payload: answerPayload,
407
+ resolveTimeoutMs,
408
+ });
409
+ }
410
+
411
+ this.mailbox.markKnockAnswered(row.envelope_id, {
412
+ sender: knockerUuaid,
413
+ decision,
414
+ answerEnvelopeId: sent.envelope.id,
415
+ now: answerNow,
416
+ });
417
+ return {
418
+ ...sent,
419
+ decision,
420
+ knockId: row.envelope_id,
421
+ to: knockerUuaid,
422
+ payload: answerPayload,
423
+ };
424
+ }
425
+
266
426
  /**
267
427
  * Send a signed envelope. Resolution order:
268
428
  * 1. Address book: if `this.addressBook.get(recipient)` returns {peerId, multiaddr},
@@ -274,12 +434,47 @@ export class Pillar {
274
434
  * fleet deployment we bypass DHT via the address book which is populated
275
435
  * once at fleet-up time.
276
436
  */
277
- async send({ recipient, recipientPublicKey, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000 }) {
437
+ async _w4Gate(queried, { registryUrl, recipientPublicKey, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
438
+ if (!registryUrl || recipientPublicKey) return { direct: true }; // @rule W-send-w4-off-without-registry
439
+ const nowStr = now ?? nowIsoSeconds();
440
+ const res = await resolveListing(queried, { registryUrl, now: nowStr, fetch: fetchOverride ?? globalThis.fetch, urlMap, allowInsecureLoopback });
441
+ let cls = { kind: "unresolved" }, gate = false;
442
+ cls = w4ClassifyVerifiedTarget(queried, res); // @rule W-send-w4-classify
443
+ gate = cls.kind === "blocked-verdict" || cls.kind === "retired-key" || cls.kind === "retired-door"; // @rule W-send-w4-retired-gate
444
+ if (gate) {
445
+ let decision = null;
446
+ try { decision = w4ApplyPolicy(cls, { queried, confirmRecovered, now: nowStr }); } catch {}
447
+ if (!decision) throw new W4RefusalError("resolve-failed", res.reason ?? "redirect lacks verified facts", { queried }); // @rule W-send-w4-facts-missing
448
+ if (decision.action === "refuse-confirm") throw new W4RefusalError(W4_CONFIRM_CODE, `witness recovery moved ${decision.details.queried} to ${decision.details.current} (lineage ${decision.details.lineage} head ${decision.details.lineageHead}); pass --confirm-recovered to send`, decision.details); // @rule W-send-w4-refuse-recovered
449
+ if (decision.action === "blocked") throw new W4RefusalError(decision.code, `${decision.verdict} is never redirected (W-4); address the current key`, { queried, verdict: decision.verdict }); // @rule W-send-w4-blocked
450
+ if (decision.action === "redirect") {
451
+ if (!cls.card?.publicKey) throw new W4RefusalError("resolve-failed", "redirect lacks verified current card", { queried }); // @rule W-send-w4-redirect-card
452
+ if (this.home) recordRedirect(this.home, decision.record); // @rule W-send-w4-persist
453
+ return { direct: false, publicKey: cls.card?.publicKey ?? "", carrier: cls.card?.carriers?.[0], target: decision.record.current, record: decision.record };
454
+ }
455
+ }
456
+ if (!res.ok) throw new W4RefusalError("resolve-failed", res.reason ?? "resolve-failed", { queried }); // @rule W-send-w4-resolve-fail
457
+ let pubKey = cls.kind === "active-door" ? undefined : res.card?.publicKey;
458
+ if (cls.kind === "active-door") pubKey = res.lineageVerdict?.facts?.doorKeys?.[queried]; // @rule W-send-w4-active-door-key
459
+ if (typeof pubKey !== "string") throw new W4RefusalError("resolve-failed", "resolve lacks verified public key", { queried });
460
+ return { direct: true, publicKey: pubKey, carrier: res.card?.carriers?.[0] };
461
+ }
462
+
463
+ async send({ recipient, recipientPublicKey, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
278
464
  if (!this.node && !this.carrierClient) {
279
465
  this.metrics.inc("send.error.not-started");
280
466
  throw new Error("pillar not started");
281
467
  }
282
468
  const t0 = Date.now();
469
+ let w4 = { direct: true }, w4Fields = {};
470
+ w4 = await this._w4Gate(recipient, { registryUrl: registryUrl ?? this.registryUrl, recipientPublicKey, confirmRecovered, now, urlMap, allowInsecureLoopback, fetch: fetchOverride }); // @rule W-send-w4-gate
471
+ if (w4.record) w4Fields = { redirectedFrom: recipient, redirectedTo: w4.target }; // @rule W-send-w4-report
472
+ if (!w4.direct) {
473
+ recipient = w4.target; // @rule W-send-w4-redirect-target
474
+ recipientPublicKey = w4.publicKey;
475
+ } else if (!recipientPublicKey && w4.publicKey) {
476
+ recipientPublicKey = w4.publicKey;
477
+ }
283
478
 
284
479
  const book = this.addressBook?.get(recipient);
285
480
 
@@ -333,7 +528,7 @@ export class Pillar {
333
528
  const via = sentDirect ? "direct+carrier" : "carrier";
334
529
  this.metrics.inc(`send.via.${via}`);
335
530
  this.metrics.observe(`send.latencyMs.via.${via}`, Date.now() - t0);
336
- return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true };
531
+ return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true, ...w4Fields };
337
532
  }
338
533
  if (sentDirect) {
339
534
  // Written to a stream, and no carrier holds a copy: nothing confirms it
@@ -341,7 +536,7 @@ export class Pillar {
341
536
  // sends one, is recorded when it comes).
342
537
  this.metrics.inc("send.via.direct-unconfirmed");
343
538
  return { envelope, persisted, via: "direct", delivery: sentDirect, direct: sentDirect, confirmed: false,
344
- carrierError: carrier.status === "rejected" ? carrier.reason : null };
539
+ carrierError: carrier.status === "rejected" ? carrier.reason : null, ...w4Fields };
345
540
  }
346
541
  this.metrics.inc("send.error.direct-delivery-failed");
347
542
  throw carrier.status === "rejected" ? carrier.reason : direct.reason;
@@ -353,7 +548,7 @@ export class Pillar {
353
548
  this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
354
549
  this.metrics.inc("send.via.carrier");
355
550
  this.metrics.observe("send.latencyMs.via.carrier", Date.now() - t0);
356
- return { envelope, persisted, via: "carrier", delivery: receipt };
551
+ return { envelope, persisted, via: "carrier", delivery: receipt, ...w4Fields };
357
552
  }
358
553
 
359
554
  // 3. DHT path.
@@ -372,7 +567,7 @@ export class Pillar {
372
567
  this.metrics.inc("send.via.dht");
373
568
  this.metrics.observe("send.latencyMs.via.dht", Date.now() - t0);
374
569
  // No carrier: a closed stream confirms nothing, so the row stays pending.
375
- return { envelope, persisted, via: "dht", delivery, direct: delivery, confirmed: false };
570
+ return { envelope, persisted, via: "dht", delivery, direct: delivery, confirmed: false, ...w4Fields };
376
571
  }
377
572
 
378
573
  /**
@@ -644,15 +839,14 @@ export class Pillar {
644
839
  if (bytes > MAX_INLINE_BODY_BYTES) {
645
840
  throw new BlobSizeError(`direct envelope ${bytes}B exceeds the ${MAX_INLINE_BODY_BYTES}B hard cap`, { size: bytes, max: MAX_INLINE_BODY_BYTES });
646
841
  }
647
- const { peerIdFromString } = await import("@libp2p/peer-id");
648
- const { multiaddr } = await import("@multiformats/multiaddr");
842
+ const { peerIdFromString, multiaddr } = await loadP2pRuntime();
649
843
  const peerId = peerIdFromString(peerIdStr);
650
844
  if (multiaddrStr) {
651
845
  try { await this.node.peerStore.patch(peerId, { multiaddrs: [multiaddr(multiaddrStr)] }); } catch (_e) {}
652
846
  }
653
847
  const stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL);
654
848
  const line = JSON.stringify(envelope) + "\n";
655
- stream.send(u8FromString(line));
849
+ stream.send(new Uint8Array(Buffer.from(line, "utf8")));
656
850
  await stream.close();
657
851
  // Not marked delivered here: a closed stream is not a receipt (2.5.3).
658
852
  return { peerId: peerIdStr };
@@ -693,14 +887,13 @@ export class Pillar {
693
887
  throw new BlobSizeError(`direct envelope ${bytes}B exceeds the ${MAX_INLINE_BODY_BYTES}B hard cap`, { size: bytes, max: MAX_INLINE_BODY_BYTES });
694
888
  }
695
889
  this.mailbox.appendOutbound(envelope);
696
- const { peerIdFromString } = await import("@libp2p/peer-id");
697
- const { multiaddr } = await import("@multiformats/multiaddr");
890
+ const { peerIdFromString, multiaddr } = await loadP2pRuntime();
698
891
  const peerId = peerIdFromString(recipientPeerIdStr);
699
892
  const ma = multiaddr(recipientMultiaddr);
700
893
  await this.node.peerStore.patch(peerId, { multiaddrs: [ma] });
701
894
  const stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL);
702
895
  const line = JSON.stringify(envelope) + "\n";
703
- stream.send(u8FromString(line));
896
+ stream.send(new Uint8Array(Buffer.from(line, "utf8")));
704
897
  await stream.close();
705
898
  // Not marked delivered: a closed stream is not a receipt (2.5.3).
706
899
  return envelope;
@@ -714,6 +907,7 @@ export class Pillar {
714
907
  try {
715
908
  let buf = "";
716
909
  let receivedBytes = 0;
910
+ const decoder = new TextDecoder("utf-8");
717
911
  for await (const chunk of stream) {
718
912
  const bytes = chunk?.subarray ? chunk.subarray() : chunk;
719
913
  receivedBytes += bytes.byteLength ?? bytes.length;
@@ -721,7 +915,7 @@ export class Pillar {
721
915
  this.metrics.inc("received.rejected.direct-cap");
722
916
  throw new BlobSizeError(`incoming direct envelope exceeds the ${MAX_INLINE_BODY_BYTES}B hard cap`, { size: receivedBytes, max: MAX_INLINE_BODY_BYTES });
723
917
  }
724
- buf += u8ToString(bytes);
918
+ buf += decoder.decode(bytes, { stream: true });
725
919
  const newlineIdx = buf.indexOf("\n");
726
920
  if (newlineIdx < 0) continue;
727
921
  const line = buf.slice(0, newlineIdx);
@@ -864,6 +1058,8 @@ export class Pillar {
864
1058
  const envelope = JSON.parse(row.envelope_json);
865
1059
  let payload;
866
1060
  try { payload = decrypt(this.keychain, envelope); } catch { return; }
1061
+ // An accepted held-group release is final admission: it emits once (the claim key dedupes).
1062
+ if (this.notifySink) await this._emitNotify(envelope, payload, { groupId, op: payload?._group?.op ?? null, via: "group-release" });
867
1063
  const view = { ...envelope, payload };
868
1064
  for (const h of this._envelopeHandlers) {
869
1065
  try { await h(view, { duplicate: false, envelopeId, released: true }); }
@@ -875,10 +1071,127 @@ export class Pillar {
875
1071
  * Would the trust gate deliver this (already verified, decrypted) envelope?
876
1072
  * Shared by the receive path and the no-side-effect peek. { deliver, reason? }
877
1073
  */
878
- _trustVerdict(envelope, payload) {
1074
+ _trustVerdict(envelope, payload, rawLine = null) {
1075
+ if (envelope.kind === "knock") {
1076
+ const now = this._knockNow();
1077
+ const val = validateKnockEnvelope(envelope, payload, {
1078
+ rawEnvelopeJson: rawLine,
1079
+ trust: this.trust,
1080
+ addressBook: this.addressBook,
1081
+ knockConfig: this.knockConfig,
1082
+ now,
1083
+ });
1084
+ if (!val.ok) {
1085
+ return { deliver: false, lane: KNOCK_LANE, knockValid: false, reason: val.quarantine, ...(val.detail ? { detail: val.detail } : {}) };
1086
+ }
1087
+ const recipientLineage = this._knockRecipientLineage();
1088
+ const rateLimited = this.mailbox.hasUnansweredRecentKnock(val.senderLineage, recipientLineage, {
1089
+ now,
1090
+ windowMs: this.knockConfig?.rateWindowMs ?? KNOCK_RATE_WINDOW_MS,
1091
+ });
1092
+ if (rateLimited) {
1093
+ return { deliver: false, lane: KNOCK_LANE, knockValid: false, reason: "knock-rate-limited" };
1094
+ }
1095
+ if (val.paymentType === "pow") {
1096
+ const powStamp = `${payload.payment.day}:${payload.payment.nonce}`;
1097
+ if (this.mailbox.hasReplayedPowStamp(val.senderLineage, recipientLineage, powStamp, { envelopeId: envelope.id })) {
1098
+ return { deliver: false, lane: KNOCK_LANE, knockValid: false, reason: "knock-payment-invalid" };
1099
+ }
1100
+ }
1101
+ // K5: valid knocks enter the knocks lane, never regular message handlers or message peeks.
1102
+ return { deliver: false, lane: KNOCK_LANE, knockValid: true, paymentType: val.paymentType, senderLineage: val.senderLineage, card: val.card };
1103
+ }
1104
+ if (envelope.kind === KNOCK_ANSWER_KIND) {
1105
+ if (this.trust?.block?.includes(envelope.sender)) return { deliver: false, reason: "blocked" };
1106
+ if (!this.trust) return { deliver: true };
1107
+ if (answersOurKnock(this.mailbox, envelope, payload, { now: this._knockNow() })) return { deliver: true };
1108
+ return evaluateTrust(this.trust, envelope.sender, new Set(this.addressBook?.keys() ?? []), { kind: envelope.kind });
1109
+ }
879
1110
  if (!this.trust) return { deliver: true };
880
1111
  if (answersOurSend(this.mailbox, envelope, payload)) return { deliver: true };
881
- return evaluateTrust(this.trust, envelope.sender, new Set(this.addressBook?.keys() ?? []));
1112
+ return evaluateTrust(this.trust, envelope.sender, new Set(this.addressBook?.keys() ?? []), { kind: envelope.kind });
1113
+ }
1114
+
1115
+ /**
1116
+ * Receive path for `kind === "knock"` envelopes (K0–K6, T4.3, T4.4, K5).
1117
+ * Never fires `onEnvelope`, never enters regular inbox views, never auto-acks.
1118
+ */
1119
+ async _receiveKnock(rawLine, envelope, payload) {
1120
+ const existing = this.mailbox.getInbound(envelope.id, envelope.sender);
1121
+ if (existing) {
1122
+ const persisted = this.mailbox.appendInbound(envelope, { pulledBy: this.reader });
1123
+ if (persisted.collision) {
1124
+ this.metrics.inc("received.collision");
1125
+ console.warn(`pillar: dropped ${envelope.id} from ${envelope.sender}: a different envelope from that sender already holds this id`);
1126
+ } else {
1127
+ this.metrics.inc("received.duplicate");
1128
+ }
1129
+ return;
1130
+ }
1131
+
1132
+ const now = this._knockNow();
1133
+ const val = validateKnockEnvelope(envelope, payload, {
1134
+ rawEnvelopeJson: rawLine,
1135
+ trust: this.trust,
1136
+ addressBook: this.addressBook,
1137
+ knockConfig: this.knockConfig,
1138
+ now,
1139
+ });
1140
+ if (!val.ok) {
1141
+ this.mailbox.appendInbound(envelope, { pulledBy: this.reader, quarantined: val.quarantine });
1142
+ this.metrics.inc("received.kind.knock");
1143
+ this.metrics.inc(`received.quarantined.${val.quarantine}`);
1144
+ console.warn(`pillar: quarantined knock ${envelope.id} from ${envelope.sender} (${val.quarantine})`);
1145
+ return;
1146
+ }
1147
+
1148
+ const powStamp = val.paymentType === "pow" ? `${payload.payment.day}:${payload.payment.nonce}` : null;
1149
+ const admit = this.mailbox.admitKnock({
1150
+ envelope,
1151
+ senderLineage: val.senderLineage,
1152
+ recipientLineage: this._knockRecipientLineage(),
1153
+ paymentType: val.paymentType,
1154
+ powStamp,
1155
+ now,
1156
+ cap: this.knockConfig?.cap ?? KNOCK_LANE_CAP,
1157
+ windowMs: this.knockConfig?.rateWindowMs ?? KNOCK_RATE_WINDOW_MS,
1158
+ });
1159
+ if (admit.rateLimited) {
1160
+ this.mailbox.appendInbound(envelope, { pulledBy: this.reader, quarantined: "knock-rate-limited" });
1161
+ this.metrics.inc("received.kind.knock");
1162
+ this.metrics.inc("received.quarantined.knock-rate-limited");
1163
+ console.warn(`pillar: quarantined knock ${envelope.id} from ${envelope.sender} (knock-rate-limited)`);
1164
+ return;
1165
+ }
1166
+ if (admit.stampReplayed) {
1167
+ this.mailbox.appendInbound(envelope, { pulledBy: this.reader, quarantined: "knock-payment-invalid" });
1168
+ this.metrics.inc("received.kind.knock");
1169
+ this.metrics.inc("received.quarantined.knock-payment-invalid");
1170
+ console.warn(`pillar: quarantined knock ${envelope.id} from ${envelope.sender} (knock-payment-invalid)`);
1171
+ return;
1172
+ }
1173
+
1174
+ const persisted = this.mailbox.appendInbound(envelope, { pulledBy: this.reader, quarantined: null });
1175
+ this.metrics.inc("received.kind.knock");
1176
+ this.metrics.inc("received.knock.admitted");
1177
+ if (admit.evicted?.length) this.metrics.inc("received.knock.evicted", admit.evicted.length);
1178
+
1179
+ const view = { ...envelope, payload };
1180
+ const meta = {
1181
+ ...persisted,
1182
+ lane: KNOCK_LANE,
1183
+ knockSeq: admit.seq,
1184
+ paymentType: val.paymentType,
1185
+ senderLineage: val.senderLineage,
1186
+ evicted: admit.evicted ?? [],
1187
+ };
1188
+ for (const h of this._knockHandlers) {
1189
+ try { await h(view, meta); }
1190
+ catch (e) {
1191
+ this.metrics.inc("received.knock-handler-error");
1192
+ console.error("pillar: knock handler threw", e);
1193
+ }
1194
+ }
882
1195
  }
883
1196
 
884
1197
  /** A peer we may send delivery signals to: never a stranger (no liveness oracle). */
@@ -961,8 +1274,14 @@ export class Pillar {
961
1274
  * deadlineMs absolute epoch ms; null = wait for ever
962
1275
  *
963
1276
  * Throws the last carrier error when every carrier refuses outright.
1277
+ *
1278
+ * pageInfo optional object; set .full = true when a carrier answered
1279
+ * a full page (CARRIER_INBOX_PAGE envelopes: more may wait
1280
+ * behind it), .partial = true when a carrier's answer was
1281
+ * abandoned because another carrier matched first. Either
1282
+ * way the result is a lower bound (pillar notify: truncated).
964
1283
  */
965
- async peekCarrierInbox({ match = null, stopWhen = null, deadlineMs = null, waitS = 25 } = {}) {
1284
+ async peekCarrierInbox({ match = null, stopWhen = null, deadlineMs = null, waitS = 25, pageInfo = null } = {}) {
966
1285
  if (!this.carrierClient) throw new Error("peek: no carriers configured");
967
1286
  const cursors = this.mailbox.getCarrierCursors?.() ?? {};
968
1287
  const found = new Map();
@@ -985,13 +1304,14 @@ export class Pillar {
985
1304
  try {
986
1305
  r = await this.carrierClient.fetchInbox(base, { since, waitS: w, timeoutMs: (w + 15) * 1000, signal: ctl.signal });
987
1306
  } catch (e) {
988
- if (stop || ctl.signal.aborted) break;
1307
+ if (stop || ctl.signal.aborted) { if (pageInfo) pageInfo.partial = true; break; }
989
1308
  if (FATAL.has(e.code)) { dead.set(base, e); break; }
990
1309
  dead.set(base, e);
991
1310
  await new Promise((res) => setTimeout(res, Math.min(2000, Math.max(0, left))));
992
1311
  continue;
993
1312
  }
994
1313
  dead.delete(base);
1314
+ if (pageInfo && r.envelopes.length >= CARRIER_INBOX_PAGE) pageInfo.full = true;
995
1315
  for (const { seq, envelope } of r.envelopes) {
996
1316
  since = Math.max(since, seq);
997
1317
  // Keyed like the inbox, on (sender, id): another sender's envelope
@@ -1019,6 +1339,25 @@ export class Pillar {
1019
1339
  return [...found.values()];
1020
1340
  }
1021
1341
 
1342
+ /**
1343
+ * Write a notify eligibility event. Mail delivery never waits on notify
1344
+ * beyond this bounded write, and never fails because of it.
1345
+ */
1346
+ async _emitNotify(envelope, payload, facts) {
1347
+ try {
1348
+ await this.notifySink.emit(this, envelope, payload, facts);
1349
+ } catch (e) {
1350
+ this.metrics.inc("notify.emit-failed");
1351
+ this._notifyWarned ??= new Set();
1352
+ const k = e?.code ?? "error";
1353
+ if (!this._notifyWarned.has(k)) {
1354
+ this._notifyWarned.add(k);
1355
+ // eslint-disable-next-line no-console
1356
+ console.warn(`pillar: notify event not written (${e?.message ?? e}); mail delivery is unaffected`);
1357
+ }
1358
+ }
1359
+ }
1360
+
1022
1361
  async _receive(rawLine, connection) {
1023
1362
  let envelope;
1024
1363
  try { envelope = JSON.parse(rawLine); }
@@ -1049,6 +1388,11 @@ export class Pillar {
1049
1388
  console.warn("pillar: envelope decrypt failed (dropping)", envelope.id, e.message);
1050
1389
  return;
1051
1390
  }
1391
+ // K5: Knocks run their own gate and enter the capped knocks lane (never onEnvelope).
1392
+ if (envelope.kind === "knock") {
1393
+ await this._receiveKnock(rawLine, envelope, payload);
1394
+ return;
1395
+ }
1052
1396
  // Trust gate (recipient consent): quarantine-not-drop. The envelope is
1053
1397
  // persisted either way (chain-hashed evidence); a gated sender just never
1054
1398
  // reaches handlers. An ack/reply (or a read receipt) passes the gate ONLY
@@ -1082,7 +1426,13 @@ export class Pillar {
1082
1426
  return;
1083
1427
  }
1084
1428
  // The recipient's own signed word about something we sent.
1429
+ let ackFirst = false;
1085
1430
  if (envelope.kind === "ack") {
1431
+ // Notify opt-in (notify.acks "outbox"): only the first committed transition
1432
+ // of our own outbox row to this sender counts, never applyReceipt's `marked`.
1433
+ if (this.notifySink?.wantsAcks && typeof payload?.inReplyTo === "string" && !isReadReceipt(payload)) {
1434
+ ackFirst = this.mailbox.markOutboundAckedFirst(payload.inReplyTo, { from: envelope.sender, ackId: envelope.id, at: envelope.createdAt }) === true;
1435
+ }
1086
1436
  const r = applyReceipt(this.mailbox, envelope, payload, { applyRead: this.receipts.read });
1087
1437
  if (r.kind) this.metrics.inc(`received.receipt.${r.kind}${r.marked ? "" : ".unmatched"}`);
1088
1438
  }
@@ -1109,6 +1459,11 @@ export class Pillar {
1109
1459
  if ((before ?? after)?.members.includes(envelope.sender)) this.mailbox.setInboundGroup(envelope.id, tag.id, envelope.sender);
1110
1460
  else this.metrics.inc("received.group.non-member");
1111
1461
  }
1462
+ // Final admission passed (auth, decrypt, trust, group): one eligibility event.
1463
+ if (this.notifySink) {
1464
+ const grp = route === "v2" ? { groupId: g.id, op: g.op } : tag ? { groupId: tag.id, op: tag.op } : {};
1465
+ await this._emitNotify(envelope, payload, { ...grp, ackFirst });
1466
+ }
1112
1467
  if (this.receipts.delivered && envelope.kind !== "ack") await this._autoAck(envelope, payload, tag);
1113
1468
  const view = { ...envelope, payload };
1114
1469
  for (const h of this._envelopeHandlers) {
package/src/readers.mjs CHANGED
@@ -136,8 +136,8 @@ export function describeReader(mailbox, key) {
136
136
  * at the tip when everything has been read.
137
137
  */
138
138
  export function initialCursor(mailbox) {
139
- const row = mailbox.db.prepare("select min(seq) as s from inbox where read_at is null and quarantined is null").get();
140
- return row?.s ? row.s - 1 : mailbox.inboxTipSeq();
139
+ const s = mailbox.oldestUnreadSeq();
140
+ return s ? s - 1 : mailbox.inboxTipSeq();
141
141
  }
142
142
 
143
143
  /**