@uuaid/pillar 2.7.3 → 2.8.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.
@@ -56,6 +56,14 @@ export const REFUSAL_FIXES = Object.freeze({
56
56
  "bad-sig-encoding": "send x-pillar-sig as 128 hex characters",
57
57
  "clock-skew": "fix your clock (NTP) to within 5 min of the carrier; retrying does not help",
58
58
  "uuaid-pubkey-mismatch": "read the inbox of the UUAID your key derives, or send that UUAID's delegation in x-pillar-delegation",
59
+ // Inbox auth v2 (2.8.1, src/net/inbox-auth.mjs)
60
+ "inbox-auth-v2-required": "update pillar to 2.8.1 or later: a relayed seed takes only audience-bound, single-use inbox auth (x-pillar-auth: 2)",
61
+ "inbox-auth-version": "send x-pillar-auth: 2, or no x-pillar-auth header for v1 at a direct carrier",
62
+ "inbox-audience-unknown": "send v1 inbox auth to this carrier: it has no public URL to check a v2 audience against",
63
+ "bad-nonce": "send x-pillar-nonce as 32 random hex characters, new for each request",
64
+ "nonce-used": "sign the request again with a new x-pillar-nonce; each v2 inbox auth is used once",
65
+ "inbox-auth-query": "send only since and wait (whole numbers) and challenge (64 hex), each at most once: v2 signs them",
66
+ "inbox-auth-busy": "retry in a few seconds: this carrier holds as many live inbox auth nonces as it may",
59
67
  "delegation-unparseable": "send x-pillar-delegation as the JSON delegation document",
60
68
  "delegation-too-large": "send a delegation document under 8,192 bytes",
61
69
  "delegation-principal-mismatch": "use a delegation whose principal is the inbox UUAID",
@@ -66,15 +74,31 @@ export const REFUSAL_FIXES = Object.freeze({
66
74
  "not-found": "use POST /v1/envelopes or GET /v1/inbox/<uuaid>",
67
75
  "not-a-seed": "do not list this carrier as a seed; it runs without a seed identity",
68
76
  "internal-error": "retry later; if it repeats, tell the carrier operator",
77
+ // Seed over egress (2.8.0): a registry's challenge, and a tunnel relay's /v1/tunnel and /e/*
78
+ "bad-challenge": "send challenge as 64 lowercase hex characters (32 random bytes), or leave it out",
79
+ "upgrade-required": "open /v1/tunnel as a WebSocket, as pillar-seed --relay does",
80
+ "seed-offline": "retry later or use another carrier; this seed's tunnel to the relay is down",
81
+ "tunnel-busy": "back off: retry after 5 s with jitter, doubling to 60 s, or use another carrier",
82
+ "seed-busy": "back off: retry after 5 s with jitter, doubling to 60 s; this seed holds as many inbox pages as its response budget allows",
83
+ "seed-timeout": "retry, or use another carrier; the seed behind this relay did not answer in time",
84
+ "seed-bad-answer": "retry, or use another carrier; the seed behind this relay answered badly",
85
+ "seed-reset": "retry, or use another carrier; the seed behind this relay dropped the request",
86
+ "seed-answer-too-large": "ask with a smaller page, or use another carrier; the seed's answer passed the relay's size cap",
69
87
  // Client side: no server gave a code
70
88
  "carrier-unreachable": "check the carrier URLs and your network, then retry",
71
89
  "carrier-bad-response": "retry, or use another carrier; the carrier or its proxy answered without a reason",
90
+ "carrier-redirect-refused": "configure the carrier's final https URL; it answered a redirect, and pillar never follows one, so its headers never reach another host",
72
91
  "over-tier-limit": "send the payload as a blob (pillar-blob send, or Pillar.sendBlob)",
73
92
  "blob-key-unproven": "use a self-certifying agent UUAID derived from this key (pillar init), or get a registry badge that names this key",
74
93
  "sender-key-not-active": "ask the sender to send from a self-certifying agent UUAID derived from its own key, or to get a registry badge naming its key",
75
94
  "group-v2-use-v2-send": "send to this pillar-group/2 group with pillar group send <group>; v1 group sends (send-group, sendGroup) do not reach it",
76
95
  "p2p-not-installed": "install the optional libp2p transport with npm i @uuaid/pillar-p2p, or omit --libp2p to run in carrier-only mode",
77
96
  "sqlite-not-installed": "install or rebuild optional dependency better-sqlite3 with npm i better-sqlite3",
97
+ "continuity-store-unreadable": "run pillar continuity repair (add --home DIR if not the default); it moves the file aside and starts an empty store, then re-confirm or re-pin your contacts",
98
+ "continuity-holds-unreadable": "restore <home>/continuity/holds.json from a backup; it lists keys that were retired or forked, and removing it would let sends reach them again",
99
+ "continuity-held": "ask the contact over another channel (not pillar) for its new uuaid and lineage head, compare them with pillar continuity show, then run pillar continuity confirm with the values the contact gave you",
100
+ "continuity-suspended": "the evidence conflicts, so nothing is sent; get the contact's genuine lineage log over another channel and run pillar continuity recover (pillar continuity show says why)",
101
+ "redirect-blocked:direct-redirect": "the key retired: send with pillar send or Pillar.send, which route to the new key, or call sendDirect for the new key with that key's own peer id and address",
78
102
  });
79
103
 
80
104
  /**
@@ -32,7 +32,7 @@
32
32
  * this issuer. The incentive points the right way: the cheapest route to
33
33
  * priority is to become infrastructure for everyone else.
34
34
  */
35
- import { createHash } from "node:crypto";
35
+ import { createHash, randomBytes } from "node:crypto";
36
36
  import dns from "node:dns";
37
37
  import { request as httpRequest } from "node:http";
38
38
  import { request as httpsRequest } from "node:https";
@@ -42,13 +42,67 @@ import { jcs } from "../identity/jcs.mjs";
42
42
  import { Keychain } from "../identity/keychain.mjs";
43
43
  import { makeTierGrant } from "../identity/tier.mjs";
44
44
  import { seal } from "./envelope.mjs";
45
+ import { signInboxAuthV1, signInboxAuthV2 } from "./inbox-auth.mjs";
45
46
  import { evaluateSeedTier, seedTier, GRANT_TTL_DAYS, DEMOTE_AFTER_FAILURES } from "./seed-tier.mjs";
47
+ import {
48
+ canonicalOrigin, relayShapeOrigin, relayedUrlFor, relayPathFor, decodeAttestHeader, isRelayedSeedUrl,
49
+ verifyRelayAttest, verifyServedProof, CHALLENGE_RE,
50
+ } from "./tunnel.mjs";
46
51
 
47
52
  const PROBE_TIMEOUT_MS = 10_000;
48
53
  const ROUND_TRIP_WAIT_S = 5;
49
54
  const MAX_RESPONSE_BYTES = 1024 * 1024;
55
+ const DAY_MS = 86_400_000;
50
56
  /** Keep the observation window bounded so uptime reflects recent behaviour. */
51
57
  export const PROBE_WINDOW = 1000;
58
+ /** The probe interval a registry assumes when none is given (pillar-directory's default). */
59
+ export const DEFAULT_PROBE_INTERVAL_MS = 10 * 60_000;
60
+ /** The longest a fleet-relay attestation vets a relayed seed (RedTeam 22f6c3 Q1). */
61
+ export const VETTING_LEASE_MAX_MS = 30 * 60_000;
62
+
63
+ /**
64
+ * How long one fresh fleet-relay attestation vets a relayed seed: min(3 x
65
+ * the effective probe interval, 30 minutes) (RedTeam 22f6c3 Q1; 085b71 C3).
66
+ * Three intervals let one probe be late or fail to arrive without a lapse;
67
+ * a seed that stops being probed, or fails a probe, loses priority within
68
+ * the lease. Only a passing challenge probe starts a lease; minting a grant
69
+ * never renews it, and a relayed seed's grant never outlives it.
70
+ */
71
+ export function vettingLeaseMs(probeIntervalMs = DEFAULT_PROBE_INTERVAL_MS) {
72
+ const interval = Number.isFinite(probeIntervalMs) && probeIntervalMs > 0 ? probeIntervalMs : DEFAULT_PROBE_INTERVAL_MS;
73
+ let lease = 3 * interval;
74
+ lease = Math.min(lease, VETTING_LEASE_MAX_MS); // @rule reg.vetting-lease-cap
75
+ return lease;
76
+ }
77
+
78
+ /**
79
+ * Parse a registry's fleet-relay pins: one `<origin> <ed25519 public key hex>`
80
+ * per line; blank lines and `#` comments are skipped. The origin must already
81
+ * be canonical. Throws naming the line on anything else, or a repeated origin.
82
+ */
83
+ export function parseFleetRelays(text) {
84
+ const out = new Map();
85
+ String(text).split(/\r?\n/).forEach((raw, i) => {
86
+ const line = raw.trim();
87
+ if (!line || line.startsWith("#")) return;
88
+ const parts = line.split(/\s+/);
89
+ const c = parts.length === 2 ? canonicalOrigin(parts[0]) : { ok: false, reason: "want <origin> <key>" };
90
+ if (!c.ok || c.origin !== parts[0]) throw new Error(`fleet relays line ${i + 1}: not a canonical origin (${c.reason ?? "not canonical"})`);
91
+ if (!/^[0-9a-f]{64}$/i.test(parts[1])) throw new Error(`fleet relays line ${i + 1}: the key must be 64 hex characters`);
92
+ if (out.has(c.origin)) throw new Error(`fleet relays line ${i + 1}: ${c.origin} is listed twice`);
93
+ out.set(c.origin, parts[1].toLowerCase());
94
+ });
95
+ return out;
96
+ }
97
+
98
+ /** A response header from either fetch flavour (Headers object or Node's plain object). */
99
+ function headerOf(res, name) {
100
+ const h = res?.headers;
101
+ if (!h) return undefined;
102
+ if (typeof h.get === "function") return h.get(name) ?? undefined;
103
+ const v = h[name];
104
+ return Array.isArray(v) ? v[0] : v;
105
+ }
52
106
 
53
107
  function unwrapHost(host) {
54
108
  const raw = String(host ?? "").trim().toLowerCase();
@@ -406,6 +460,9 @@ export class SeedRegistry {
406
460
  lookupImpl,
407
461
  allowPrivateUrls = false,
408
462
  probeTimeoutMs = PROBE_TIMEOUT_MS,
463
+ fleetRelays = null,
464
+ probeIntervalMs = DEFAULT_PROBE_INTERVAL_MS,
465
+ clock = () => Date.now(),
409
466
  } = {}) {
410
467
  if (!keychain?._identity) throw new Error("SeedRegistry needs a loaded keychain");
411
468
  this.keychain = keychain;
@@ -415,6 +472,20 @@ export class SeedRegistry {
415
472
  this.lookup = lookupImpl ?? lookup;
416
473
  this.allowPrivateUrls = allowPrivateUrls;
417
474
  this.probeTimeoutMs = probeTimeoutMs;
475
+ // Fleet relays this registry pins (origin -> relay key hex). Only a seed
476
+ // on one of these can be listed, vetted or granted while relayed.
477
+ this.fleetRelays = new Map(
478
+ [...(fleetRelays instanceof Map ? fleetRelays : Object.entries(fleetRelays ?? {}))]
479
+ .map(([o, k]) => [String(o), String(k).toLowerCase()]),
480
+ );
481
+ // The probe interval this registry runs at (pillar-directory passes its
482
+ // effective interval), and the vetting lease it implies.
483
+ this.probeIntervalMs = probeIntervalMs;
484
+ this.vettingLeaseMs = vettingLeaseMs(probeIntervalMs);
485
+ // The wall clock a relay attestation's `at` is checked against, read at the
486
+ // moment of the check (injectable for tests). Never a round's or a caller's
487
+ // `now`, which can be minutes old by then (Lead review C-P1).
488
+ this.clock = clock;
418
489
  const Database = requireBetterSqlite3("SeedRegistry");
419
490
  this.db = new Database(dbPath);
420
491
  this.db.pragma("journal_mode = WAL");
@@ -448,6 +519,66 @@ export class SeedRegistry {
448
519
  if (!cols.includes("probe_log")) {
449
520
  this.db.exec("alter table seeds add column probe_log text not null default ''");
450
521
  }
522
+ // 2.8.0 egress seeds: the pinned relay origin and key, how long the last
523
+ // fresh attestation vets it, and the row's pin state ('direct',
524
+ // 'pending-challenge' or 'relayed').
525
+ if (!cols.includes("relay")) this.db.exec("alter table seeds add column relay text");
526
+ if (!cols.includes("relay_key")) this.db.exec("alter table seeds add column relay_key text");
527
+ if (!cols.includes("vetted_until")) this.db.exec("alter table seeds add column vetted_until text");
528
+ if (!cols.includes("pin_state")) this.db.exec("alter table seeds add column pin_state text not null default 'direct'");
529
+ // 2.8.1 (RedTeam 57c79a item 2): the endpoint and pin (pinKey) a round trip
530
+ // with inbox auth v2 and a served proof last passed for. Null until one
531
+ // passes, also for every row stored before this column existed.
532
+ if (!cols.includes("v2_rt_pin")) this.db.exec("alter table seeds add column v2_rt_pin text");
533
+ this._migrateRelayedRows();
534
+ this._migrateVettingToLease();
535
+ this._clampStoredVetting();
536
+ }
537
+
538
+ /**
539
+ * One-time, versioned (RedTeam 995f4c): every vetting stored before this
540
+ * registry first ran with the lease rule is cleared, however little time
541
+ * it has left, so every relayed seed proves itself again with a fresh
542
+ * challenge before it holds priority. A 24-hour vetting with 15 minutes
543
+ * left would otherwise survive the length check in _clampStoredVetting.
544
+ * Grants already signed keep their own expiry.
545
+ */
546
+ _migrateVettingToLease() {
547
+ this.db.exec("create table if not exists seed_registry_meta (k text primary key, v text not null)");
548
+ // Check and write in one IMMEDIATE transaction (RedTeam 87bb0b P3): two
549
+ // registries opening one database at once never both run it, and the
550
+ // second never fails on the marker. Sharing one database between
551
+ // registries is not a supported deployment; this only keeps it safe.
552
+ this.db.transaction(() => {
553
+ const claimed = this.db.prepare("insert or ignore into seed_registry_meta (k, v) values ('vetting-lease', '1')").run().changes === 1;
554
+ if (!claimed) return;
555
+ this.db.prepare("update seeds set vetted_until = null where vetted_until is not null").run(); // @rule reg.vetting-lease-migration
556
+ }).immediate();
557
+ }
558
+
559
+ /**
560
+ * A vetting stored under a longer lease than this registry grants now (its
561
+ * probe interval was shortened since) is cleared on open: the seed proves
562
+ * itself again with a fresh challenge before it holds priority (RedTeam
563
+ * 22f6c3 Q1). Vettings from before the lease rule are cleared once by
564
+ * _migrateVettingToLease. Grants already signed keep their own expiry.
565
+ */
566
+ _clampStoredVetting(now = this.clock()) {
567
+ const limit = new Date(now + this.vettingLeaseMs).toISOString();
568
+ this.db.prepare("update seeds set vetted_until = null where vetted_until is not null and vetted_until > ?").run(limit); // @rule reg.vetting-clamp-on-open
569
+ }
570
+
571
+ /**
572
+ * A row enrolled before 2.8.0 at a URL of the relayed shape
573
+ * (`<origin>/e/<localId of its key>`) was never challenged through its
574
+ * relay: it waits, unlisted and ungranted, until one challenge probe passes.
575
+ */
576
+ _migrateRelayedRows() {
577
+ const rows = this.db.prepare("select uuaid, url, public_key from seeds where pin_state = 'direct' and relay is null").all();
578
+ const mark = this.db.prepare("update seeds set pin_state = 'pending-challenge' where uuaid = ?");
579
+ for (const r of rows) {
580
+ if (relayShapeOrigin(r.url, r.public_key)) mark.run(r.uuaid); // @rule reg.migrate-pending
581
+ }
451
582
  }
452
583
 
453
584
  close() { if (this.db.open) this.db.close(); }
@@ -465,6 +596,11 @@ export class SeedRegistry {
465
596
  };
466
597
  }
467
598
 
599
+ /** A relayed row's endpoint and pin, as the v2 round-trip marker records it. */
600
+ static pinKey(row) {
601
+ return JSON.stringify([row.url, row.public_key, row.relay ?? null, row.relay_key ?? null]);
602
+ }
603
+
468
604
  get(uuaid) { return this.db.prepare("select * from seeds where uuaid = ?").get(uuaid); }
469
605
  all() { return this.db.prepare("select * from seeds").all(); }
470
606
 
@@ -490,10 +626,15 @@ export class SeedRegistry {
490
626
  return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "probe timed out"}` };
491
627
  }
492
628
 
629
+ // A one-use challenge (2.8.0): a relayed seed must echo it inside its
630
+ // signed seed-info, and a fleet relay must attest it. A 2.7 seed ignores
631
+ // the query and still enrolls as a direct seed.
632
+ const challenge = randomBytes(32).toString("hex");
493
633
  let doc;
634
+ let attestHeader;
494
635
  try {
495
636
  const res = await raceSignal(
496
- this.fetch(`${resolved.url}/v1/seed-info`, {
637
+ this.fetch(`${resolved.url}/v1/seed-info?challenge=${challenge}`, {
497
638
  signal,
498
639
  redirect: "manual",
499
640
  ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
@@ -501,12 +642,15 @@ export class SeedRegistry {
501
642
  signal,
502
643
  );
503
644
  if (!res.ok) return { ok: false, reason: `seed-info-${res.status}` };
645
+ attestHeader = headerOf(res, "x-pillar-relay-attest");
504
646
  doc = await raceSignal(res.json(), signal);
505
647
  } catch (e) {
506
648
  return { ok: false, reason: `seed-unreachable: ${e?.message ?? e}` };
507
649
  }
508
650
  const v = verifySeedInfo(doc, resolved.url);
509
651
  if (!v.ok) return { ok: false, reason: `seed-info-invalid:${v.reason}` };
652
+ const topo = this._checkTopology(doc, { url: resolved.url, challenge, attestHeader, now });
653
+ if (!topo.ok) return { ok: false, reason: `seed-info-invalid:${topo.reason}` };
510
654
 
511
655
  const existing = this.get(doc.uuaid);
512
656
  if (existing) {
@@ -519,13 +663,55 @@ export class SeedRegistry {
519
663
  if (urlTaken) return { ok: false, reason: "url-already-enrolled" };
520
664
 
521
665
  this.db.prepare(`
522
- insert into seeds (uuaid, url, public_key, operator, region, enrolled_at, tier, claimed)
523
- values (?,?,?,?,?,?,'probation',?)
666
+ insert into seeds (uuaid, url, public_key, operator, region, enrolled_at, tier, claimed, relay, relay_key, vetted_until, pin_state)
667
+ values (?,?,?,?,?,?,'probation',?,?,?,?,?)
524
668
  `).run(doc.uuaid, resolved.url, doc.publicKey.toLowerCase(), operator, region,
525
- new Date(now).toISOString(), JSON.stringify(doc.stats ?? {}));
669
+ new Date(now).toISOString(), JSON.stringify(doc.stats ?? {}),
670
+ topo.relay, topo.relayKey, topo.vettedUntil, topo.relay ? "relayed" : "direct");
526
671
  return { ok: true, already: false, ...this.status(doc.uuaid) };
527
672
  }
528
673
 
674
+ /**
675
+ * What a signed seed-info says about the seed's topology, checked against
676
+ * the URL it was fetched from and the one-use challenge just sent.
677
+ *
678
+ * Direct: no `relay`, and the URL is not of the relayed shape; an echoed
679
+ * challenge must match. Relayed: `relay` is a canonical origin, the URL is
680
+ * exactly `<relay>/e/<localId of the key>`, and the challenge is echoed.
681
+ * When the relay is a fleet relay this registry pins, its attestation must
682
+ * verify under the configured key; that vets the seed until now + validity.
683
+ */
684
+ _checkTopology(doc, { url, challenge, attestHeader, now = Date.now() }) {
685
+ if (doc.challenge !== undefined && doc.challenge !== challenge) return { ok: false, reason: "challenge-mismatch" }; // @rule reg.challenge-echo
686
+ if (doc.relay === undefined) {
687
+ if (relayShapeOrigin(url, doc.publicKey)) return { ok: false, reason: "relay-undeclared" }; // @rule reg.relay-declared
688
+ return { ok: true, relay: null, relayKey: null, vettedUntil: null };
689
+ }
690
+ const c = canonicalOrigin(doc.relay);
691
+ if (!c.ok || c.origin !== doc.relay) return { ok: false, reason: "relay-not-canonical" };
692
+ if (url !== relayedUrlFor(doc.relay, doc.publicKey.toLowerCase())) return { ok: false, reason: "relay-url-mismatch" }; // @rule reg.relay-url-shape
693
+ if (doc.challenge !== challenge) return { ok: false, reason: "challenge-missing" }; // @rule reg.relayed-must-echo
694
+ const relayKey = this.fleetRelays.get(doc.relay);
695
+ if (!relayKey) return { ok: true, relay: doc.relay, relayKey: null, vettedUntil: null };
696
+ // `at` is the relay's clock when it answered, so it is checked against this
697
+ // registry's clock now that the answer is here (C-P1).
698
+ let attestNow = now;
699
+ attestNow = this.clock(); // @rule reg.attest-real-clock
700
+ const att = verifyRelayAttest(decodeAttestHeader(attestHeader), {
701
+ relayKey, origin: doc.relay, path: `${relayPathFor(doc.publicKey.toLowerCase())}/v1/seed-info`,
702
+ uuaid: doc.uuaid, publicKey: doc.publicKey, challenge, now: attestNow,
703
+ });
704
+ if (!att.ok) return { ok: false, reason: att.reason }; // @rule reg.fleet-relay-must-attest
705
+ // The lease runs from this seed's own observation time (`now`, per seed
706
+ // since C-P1), never from a mint.
707
+ return { ok: true, relay: doc.relay, relayKey, vettedUntil: new Date(now + this.vettingLeaseMs).toISOString() };
708
+ }
709
+
710
+ /** A relayed seed stops being vetted the moment any probe of it fails. */
711
+ _clearVetting(uuaid) {
712
+ this.db.prepare("update seeds set vetted_until = null where uuaid = ?").run(uuaid);
713
+ }
714
+
529
715
  /**
530
716
  * Record one health-probe outcome into an exact sliding window of the last
531
717
  * PROBE_WINDOW probes.
@@ -567,8 +753,13 @@ export class SeedRegistry {
567
753
  `).run(passed ? 1 : 0, uuaid);
568
754
  }
569
755
 
570
- /** GET <url>/v1/health — the liveness half of an observation. */
571
- async healthProbe(row) {
756
+ /**
757
+ * GET <url>/v1/health — the liveness half of an observation. A relayed or
758
+ * pending seed is instead challenged (see _challengeProbe): through a relay,
759
+ * an unsigned health answer proves only that the relay is up.
760
+ */
761
+ async healthProbe(row, { now = Date.now() } = {}) {
762
+ if ((row.pin_state ?? "direct") !== "direct") return this._challengeProbe(row, { now }); // @rule reg.relayed-health-is-challenge
572
763
  try {
573
764
  const signal = AbortSignal.timeout(this.probeTimeoutMs);
574
765
  const resolved = await resolveSeedUrl(row.url, {
@@ -591,6 +782,43 @@ export class SeedRegistry {
591
782
  } catch (_e) { return false; }
592
783
  }
593
784
 
785
+ /**
786
+ * One challenge probe of a relayed (or pending) seed: GET seed-info with a
787
+ * fresh one-use challenge. Passes only if the doc is signed by the pinned
788
+ * key for the pinned uuaid and URL, declares the pinned relay, echoes the
789
+ * challenge, and (for a fleet relay) carries a valid attestation. Any error
790
+ * fails the probe and clears vetting; nothing falls back to /v1/health.
791
+ */
792
+ async _challengeProbe(row, { now = Date.now() } = {}) {
793
+ const fail = () => { this._clearVetting(row.uuaid); return false; };
794
+ const challenge = randomBytes(32).toString("hex");
795
+ try {
796
+ const signal = AbortSignal.timeout(this.probeTimeoutMs);
797
+ const resolved = await resolveSeedUrl(row.url, { allowPrivateUrls: this.allowPrivateUrls, lookup: this.lookup, signal });
798
+ if (!resolved.ok || signal.aborted) return fail();
799
+ const res = await raceSignal(
800
+ this.fetch(`${resolved.url}/v1/seed-info?challenge=${challenge}`, {
801
+ signal, redirect: "manual", ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
802
+ }),
803
+ signal,
804
+ );
805
+ if (!res.ok) return fail();
806
+ const attestHeader = headerOf(res, "x-pillar-relay-attest");
807
+ const doc = await raceSignal(res.json(), signal);
808
+ if (!verifySeedInfo(doc, row.url).ok) return fail();
809
+ if (doc.uuaid !== row.uuaid || String(doc.publicKey).toLowerCase() !== row.public_key) return fail(); // @rule reg.pin-identity
810
+ const topo = this._checkTopology(doc, { url: row.url, challenge, attestHeader, now });
811
+ // A pass means url === <relay>/e/<localId of the pinned key>, and the URL is
812
+ // pinned, so the relay origin it declares is the pinned one too.
813
+ if (!topo.ok || !topo.relay) return fail(); // @rule reg.pin-stays-relayed
814
+ this.db.prepare("update seeds set pin_state = 'relayed', relay = ?, relay_key = ?, vetted_until = ? where uuaid = ?")
815
+ .run(topo.relay, topo.relayKey, topo.vettedUntil, row.uuaid);
816
+ return true;
817
+ } catch (_e) {
818
+ return fail();
819
+ }
820
+ }
821
+
594
822
  /**
595
823
  * Push a real signed envelope THROUGH the seed and read it back out.
596
824
  *
@@ -643,15 +871,23 @@ export class SeedRegistry {
643
871
  // Poll from just below the receipt seq so the probe envelope is in
644
872
  // range regardless of how much unrelated traffic the seed carries.
645
873
  const since = Math.max(0, Number(receipt.seq) - 1);
646
- const path = `GET /v1/inbox/${me.uuaid}?since=${since}`;
647
- const ts = String(Date.now());
648
- const sig = this.keychain.sign(Buffer.from(`${path}\n${ts}`, "utf-8")).toString("hex");
874
+ // 2.8.0: a one-use challenge the seed binds, with the digest of the exact
875
+ // page it returns, into a signed served proof (RedTeam 085b71 C4). A 2.7
876
+ // seed ignores it; v1 inbox auth does not cover the query.
877
+ const rt = randomBytes(32).toString("hex");
878
+ // 2.8.1: a relayed seed takes only inbox auth v2, bound to its URL (the
879
+ // enrolled row URL, not the resolved one), to since, wait and this
880
+ // challenge, and single-use (RedTeam 57c79a item 1).
881
+ const viaV2 = isRelayedSeedUrl(row.url);
882
+ const authHeaders = viaV2
883
+ ? signInboxAuthV2(this.keychain, { audience: row.url, uuaid: me.uuaid, since, wait: ROUND_TRIP_WAIT_S, challenge: rt })
884
+ : signInboxAuthV1(this.keychain, { uuaid: me.uuaid, since });
649
885
  const getSignal = AbortSignal.timeout(this.probeTimeoutMs + ROUND_TRIP_WAIT_S * 1000);
650
886
  const res = await raceSignal(
651
887
  this.fetch(
652
- `${resolved.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}`,
888
+ `${resolved.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}&challenge=${rt}`,
653
889
  {
654
- headers: { "x-pillar-pubkey": me.publicKeyHex, "x-pillar-ts": ts, "x-pillar-sig": sig },
890
+ headers: authHeaders,
655
891
  signal: getSignal,
656
892
  redirect: "manual",
657
893
  ...lookupOpt,
@@ -662,7 +898,22 @@ export class SeedRegistry {
662
898
  if (res.status !== 200) return { ok: false, reason: `inbox-${res.status}` };
663
899
  const body = await raceSignal(res.json(), getSignal);
664
900
  const found = (body?.envelopes ?? []).some(e => e?.envelope?.id === envelope.id);
665
- return found ? { ok: true } : { ok: false, reason: "envelope-not-returned" };
901
+ if (!found) return { ok: false, reason: "envelope-not-returned" };
902
+ // A relay can answer a round trip from its own store; only the seed key
903
+ // can sign what the seed served. Required for relayed and pending rows
904
+ // (which fail closed without a pinned key); a direct seed's proof, when
905
+ // present, must verify against the row's key. A caller passing a partial
906
+ // direct row with no key (the 2.7.1 API allowed it) gets 2.7.1 behaviour.
907
+ let needProof = body?.proof !== undefined && typeof row.public_key === "string";
908
+ if ((row.pin_state ?? "direct") !== "direct") needProof = true; // @rule reg.relayed-needs-proof
909
+ if (needProof) {
910
+ const p = verifyServedProof(body?.proof, {
911
+ publicKey: row.public_key, seed: row.uuaid, inbox: me.uuaid, since, challenge: rt, envelopes: body?.envelopes,
912
+ });
913
+ if (!p.ok) return { ok: false, reason: p.reason };
914
+ }
915
+ // v2: this read used inbox auth v2 and the seed signed what it served.
916
+ return { ok: true, v2: viaV2 && needProof };
666
917
  } catch (e) {
667
918
  return { ok: false, reason: `probe-threw: ${e?.message ?? e}` };
668
919
  }
@@ -674,24 +925,80 @@ export class SeedRegistry {
674
925
  * failed health probe — one outage, one mark.
675
926
  */
676
927
  async observe(row, { now = Date.now() } = {}) {
677
- const alive = await this.healthProbe(row);
928
+ const alive = await this.healthProbe(row, { now });
678
929
  this.recordProbe(row.uuaid, alive, now);
679
930
  let rt = null;
680
931
  if (alive) {
681
- rt = await this.roundTripProbe(row, { now });
932
+ const current = this.get(row.uuaid) ?? row; // the challenge probe may have pinned it
933
+ rt = await this.roundTripProbe(current, { now });
682
934
  this.recordRoundTrip(row.uuaid, rt.ok);
935
+ if (!rt.ok && (current.pin_state ?? "direct") !== "direct") this._clearVetting(row.uuaid); // @rule reg.rt-failure-clears-vetting
936
+ // 2.8.1 (RedTeam 57c79a item 2): the endpoint and pin a v2 round trip
937
+ // last passed for; a failed round trip clears it.
938
+ this.db.prepare("update seeds set v2_rt_pin = ? where uuaid = ?").run(rt.ok && rt.v2 === true ? SeedRegistry.pinKey(current) : null, row.uuaid);
683
939
  }
684
940
  const evaluated = this.evaluate(row.uuaid, now);
685
941
  return { uuaid: row.uuaid, url: row.url, alive, roundTrip: rt, ...evaluated };
686
942
  }
687
943
 
688
- /** Observe every enrolled seed. Sequential: probes are cheap and ordering keeps logs readable. */
689
- async observeAll({ now = Date.now() } = {}) {
944
+ /**
945
+ * Observe every enrolled seed. Sequential: probes are cheap and ordering
946
+ * keeps logs readable. Each seed is observed at its own time, so one slow
947
+ * seed never ages the clock the next one is judged by (C-P1); a caller that
948
+ * passes `now` (a synthetic clock, in tests) gets that clock for every seed.
949
+ */
950
+ async observeAll({ now } = {}) {
690
951
  const out = [];
691
- for (const row of this.all()) out.push(await this.observe(row, { now }));
952
+ for (const row of this.all()) out.push(await this.observe(row, now === undefined ? {} : { now }));
692
953
  return out;
693
954
  }
694
955
 
956
+ /**
957
+ * A row's topology NOW (2.8.0). Rechecked on every status, directory,
958
+ * evaluation and grant: the pin must still match this registry's fleet
959
+ * relay config, and vetting must not have lapsed.
960
+ */
961
+ _topology(row, now = Date.now()) {
962
+ const state = row.pin_state ?? "direct";
963
+ if (state === "direct") return "direct";
964
+ if (state !== "relayed") return "pending";
965
+ const configured = this.fleetRelays.get(row.relay);
966
+ if (!configured || configured !== row.relay_key) return "relayed-unvetted"; // @rule reg.pin-presence
967
+ const until = Date.parse(row.vetted_until ?? "");
968
+ if (!(until > now)) return "relayed-lapsed"; // @rule reg.vetting-fresh
969
+ return "relayed-vetted";
970
+ }
971
+
972
+ /**
973
+ * One evaluation of a row, shared by status, directory, evaluate and
974
+ * grantFor, so the topology cap, listing and grant rules cannot drift apart.
975
+ */
976
+ _standing(row, now = Date.now()) {
977
+ const topology = this._topology(row, now);
978
+ const ev = evaluateSeedTier({ ...SeedRegistry._record(row), topology }, now);
979
+ const rung = seedTier(ev.tier);
980
+ let grantTier = rung.grant;
981
+ if (topology !== "direct" && topology !== "relayed-vetted") grantTier = null; // @rule reg.grant-needs-vetting
982
+ let grantExpiresMs = now + GRANT_TTL_DAYS * DAY_MS;
983
+ if (topology !== "direct") grantExpiresMs = Math.min(grantExpiresMs, Date.parse(row.vetted_until ?? "") || now); // @rule reg.grant-expiry-at-vetting
984
+ let listed = !ev.demoted;
985
+ // 2.8.1 (owner order 2026-12-04): a relayed seed at exactly <relay>/e/<id>
986
+ // is listed with its uuaid and relay, so it can be found and reached by
987
+ // uuaid, once a round trip with inbox auth v2 and a served proof passed
988
+ // for its current endpoint and pin (RedTeam 57c79a item 2: signed
989
+ // seed-info alone does not show that clients can read it). Listing gives
990
+ // no vetting and no grant. A 2.8.1 client takes up to 4 such entries and
991
+ // reads them only with v2 (src/net/discovery.mjs); a 2.8.0 client takes
992
+ // none. A pending row, or a relayed-shape URL with no proven relay, stays
993
+ // unlisted.
994
+ let relayedOk = false;
995
+ relayedOk = topology.startsWith("relayed-") && typeof row.relay === "string" && row.url === relayedUrlFor(row.relay, row.public_key); // @rule reg.list-relayed-proven
996
+ if (row.v2_rt_pin !== SeedRegistry.pinKey(row)) relayedOk = false; // @rule reg.list-needs-v2-round-trip
997
+ if (topology !== "direct" && !relayedOk) listed = false; // @rule reg.list-direct-or-proven-relayed
998
+ if (isRelayedSeedUrl(row.url) && !relayedOk) listed = false; // @rule reg.list-no-unproven-relayed-shape
999
+ return { ev, rung, topology, grantTier, priority: grantTier !== null && rung.priority, listed, grantExpiresMs };
1000
+ }
1001
+
695
1002
  /**
696
1003
  * Recompute a seed's rung from observations and persist it. Returns the
697
1004
  * evaluation plus whether the rung moved, so callers can log promotions
@@ -701,7 +1008,7 @@ export class SeedRegistry {
701
1008
  const row = this.get(uuaid);
702
1009
  if (!row) return { ok: false, reason: "unknown-seed" };
703
1010
  const before = row.tier;
704
- const ev = evaluateSeedTier(SeedRegistry._record(row), now);
1011
+ const { ev } = this._standing(row, now);
705
1012
  if (ev.tier !== before) {
706
1013
  this.db.prepare("update seeds set tier = ?, promoted_at = ? where uuaid = ?")
707
1014
  .run(ev.tier, new Date(now).toISOString(), uuaid);
@@ -714,19 +1021,21 @@ export class SeedRegistry {
714
1021
  *
715
1022
  * Issued fresh each call with a GRANT_TTL_DAYS expiry. That TTL is the
716
1023
  * whole revocation story: a seed that stops serving stops being re-issued,
717
- * and its last grant dies on its own within the window.
1024
+ * and its last grant dies on its own within the window. A relayed seed is
1025
+ * granted only while a fleet relay's attestation vets it, and its grant
1026
+ * never outlives that vetting (2.8.0, RedTeam 085b71 C3).
718
1027
  */
719
1028
  grantFor(uuaid, now = Date.now()) {
720
1029
  const row = this.get(uuaid);
721
1030
  if (!row) return null;
722
- const rung = seedTier(row.tier);
723
- if (!rung.grant) return null;
1031
+ const s = this._standing(row, now);
1032
+ if (!s.grantTier) return null;
724
1033
  return makeTierGrant(this.keychain, {
725
1034
  uuaid: row.uuaid,
726
- tier: rung.grant,
727
- expires: new Date(now + GRANT_TTL_DAYS * 86_400_000).toISOString(),
728
- priority: rung.priority,
729
- seedTier: rung.name,
1035
+ tier: s.grantTier,
1036
+ expires: new Date(s.grantExpiresMs).toISOString(),
1037
+ priority: s.priority,
1038
+ seedTier: s.rung.name,
730
1039
  seedUrl: row.url,
731
1040
  });
732
1041
  }
@@ -735,8 +1044,7 @@ export class SeedRegistry {
735
1044
  status(uuaid, now = Date.now()) {
736
1045
  const row = this.get(uuaid);
737
1046
  if (!row) return { ok: false, reason: "unknown-seed" };
738
- const ev = evaluateSeedTier(SeedRegistry._record(row), now);
739
- const rung = seedTier(ev.tier);
1047
+ const { ev, rung, topology, grantTier, priority, listed } = this._standing(row, now);
740
1048
  return {
741
1049
  ok: true,
742
1050
  uuaid: row.uuaid,
@@ -746,11 +1054,18 @@ export class SeedRegistry {
746
1054
  enrolledAt: row.enrolled_at,
747
1055
  tier: ev.tier,
748
1056
  blurb: rung.blurb,
749
- priority: rung.priority,
750
- grantTier: rung.grant,
1057
+ priority,
1058
+ grantTier,
751
1059
  demoted: ev.demoted,
752
1060
  next: ev.next,
753
1061
  missing: ev.missing,
1062
+ // 2.8.0: declared topology. A 2.7 registry omits these, and a client
1063
+ // reading a relayed URL's standing without them knows its liveness was
1064
+ // only relay-attested.
1065
+ topology,
1066
+ pinState: row.pin_state ?? "direct",
1067
+ ...(row.relay ? { relay: row.relay, vettedUntil: row.vetted_until } : {}),
1068
+ listed,
754
1069
  observed: {
755
1070
  probes: { total: row.probes_total, passed: row.probes_passed },
756
1071
  roundTrips: { total: row.rt_total, passed: row.rt_passed },
@@ -769,39 +1084,59 @@ export class SeedRegistry {
769
1084
  * entirely: the directory is what a fresh agent bootstraps its carrier list
770
1085
  * from, and handing it a host that failed its last three probes is how you
771
1086
  * get a first-run experience of silent message loss.
1087
+ *
1088
+ * 2.8.1: every seed entry names its uuaid. A relayed seed that proved itself
1089
+ * through its relay, and passed a round trip with inbox auth v2 for its
1090
+ * current pin, is listed with `relay` (its reach). A 2.8.0 client
1091
+ * never configures one as a carrier; a 2.8.1 client takes the first 4, in
1092
+ * this order, and reads them only with inbox auth v2 (src/net/discovery.mjs,
1093
+ * src/net/inbox-auth.mjs). The bootstrap carrier is never a relayed URL.
1094
+ * Served at /directory.json and /.
772
1095
  */
773
1096
  directory({ agents = [], now = Date.now(), includeProbation = true } = {}) {
774
1097
  const rows = this.all()
775
- .map(r => ({ r, ev: evaluateSeedTier(SeedRegistry._record(r), now) }))
776
- .filter(({ ev }) => !ev.demoted)
777
- .filter(({ ev }) => includeProbation || ev.tier !== "probation")
1098
+ .map(r => ({ r, s: this._standing(r, now) }))
1099
+ .filter(({ s }) => s.listed)
1100
+ .filter(({ s }) => includeProbation || s.ev.tier !== "probation")
778
1101
  .sort((a, b) => {
779
- const d = seedTier(a.ev.tier).listRank - seedTier(b.ev.tier).listRank;
1102
+ const d = seedTier(a.s.ev.tier).listRank - seedTier(b.s.ev.tier).listRank;
780
1103
  return d !== 0 ? d : a.r.enrolled_at.localeCompare(b.r.enrolled_at);
781
1104
  });
782
1105
  return {
783
1106
  protocol: this.protocol,
784
- carrier: this.carrierUrl,
1107
+ carrier: this._bootstrapCarrier(),
785
1108
  updated: new Date(now).toISOString(),
786
1109
  issuer: this.issuerKey,
787
1110
  agents,
788
- seeds: rows.map(({ r, ev }) => ({
1111
+ seeds: rows.map(({ r, s }) => ({
789
1112
  url: r.url,
1113
+ // 2.8.1: the seed's identity, so a seed (and an agent's reach) is found by uuaid.
1114
+ uuaid: r.uuaid,
1115
+ // 2.8.1: a relayed seed carries its relay origin; a client takes it
1116
+ // only with that relay named for its URL (src/net/discovery.mjs).
1117
+ ...(s.topology === "direct" ? {} : { relay: r.relay }),
790
1118
  operator: r.operator ?? undefined,
791
1119
  region: r.region ?? undefined,
792
1120
  since: r.enrolled_at.slice(0, 10),
793
1121
  // Published so a client can rank carriers without asking the
794
1122
  // registry a second question (see CarrierClient carrierTiers).
795
- tier: ev.tier,
796
- priority: seedTier(ev.tier).priority,
1123
+ tier: s.ev.tier,
1124
+ priority: s.rung.priority,
797
1125
  // String decimal, not a float: directory.json has to survive JCS
798
1126
  // canonicalization (directoryEtag, and any future signed directory),
799
1127
  // and JCS admits no non-integer number.
800
- uptime: ev.uptime.toFixed(4),
1128
+ uptime: s.ev.uptime.toFixed(4),
801
1129
  })),
802
1130
  };
803
1131
  }
804
1132
 
1133
+ /** The bootstrap carrier, unless it is a relayed seed URL (RedTeam 22f6c3 Q2). */
1134
+ _bootstrapCarrier() {
1135
+ let carrier = this.carrierUrl;
1136
+ if (carrier && isRelayedSeedUrl(carrier)) carrier = null; // @rule reg.carrier-not-relayed
1137
+ return carrier;
1138
+ }
1139
+
805
1140
  /** Stable id for a directory render — lets a publisher skip no-op writes. */
806
1141
  static directoryEtag(dir) {
807
1142
  const { updated, ...rest } = dir;