@uuaid/pillar 2.7.3 → 2.8.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.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Which carriers a client takes from a directory on its own (`pillar init
3
+ * --directory`, `--refresh`, `--force --directory`).
4
+ *
5
+ * 2.8.0 (RedTeam 22f6c3 Q2): no relayed seed URL (`<relay origin>/e/<id>`,
6
+ * src/net/tunnel.mjs) is configured automatically, whether the directory
7
+ * marks it with `relay` metadata or not, and whatever relays it pins. Inbox
8
+ * auth headers sent through a relay can be replayed for 5 minutes, so a
9
+ * client reaches a relayed seed only when its operator names it explicitly
10
+ * (`pillar init --carriers <url>`). Automatic discovery of relayed seeds
11
+ * waits for versioned, audience-bound, single-use inbox auth. Direct carrier
12
+ * and seed entries are taken exactly as before.
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { isRelayedSeedUrl } from "./tunnel.mjs";
16
+
17
+ /**
18
+ * @param {object} d a directory document ({ carrier, seeds: [{ url, relay? }] })
19
+ * @returns {{ carriers: string[], skippedRelayed: number }}
20
+ * carriers in directory order: the bootstrap carrier, then each seed URL.
21
+ */
22
+ export function directoryCarriers(d) {
23
+ const carriers = [];
24
+ let skippedRelayed = 0;
25
+ let carrier = d?.carrier;
26
+ if (carrier && isRelayedSeedUrl(carrier)) { carrier = null; skippedRelayed++; } // @rule discovery.carrier-not-relayed
27
+ if (carrier) carriers.push(carrier);
28
+ for (const s of Array.isArray(d?.seeds) ? d.seeds : []) {
29
+ let url = s?.url;
30
+ if (url && s?.relay !== undefined) { url = null; skippedRelayed++; } // @rule discovery.seed-relay-metadata
31
+ if (url && isRelayedSeedUrl(url)) { url = null; skippedRelayed++; } // @rule discovery.seed-relayed-shape
32
+ if (url) carriers.push(url);
33
+ }
34
+ return { carriers, skippedRelayed };
35
+ }
36
+
37
+ /** The carrier list alone, in the shape init-cli has always used. */
38
+ export function carriersFromDirectory(d) {
39
+ return directoryCarriers(d).carriers;
40
+ }
41
+
42
+ /**
43
+ * Read a home's config.json back after a write and check its carriers are
44
+ * exactly `expected` (RedTeam 995f4c Q2: when `pillar init --refresh` is used
45
+ * to clean relayed URLs out of a home, what is on disk is the evidence, not
46
+ * what was meant to be written).
47
+ * @returns {{ ok: true, carriers: string[] } | { ok: false, reason: string, carriers?: string[] }}
48
+ */
49
+ export function readBackCarriers(cfgPath, expected) {
50
+ let carriers;
51
+ try {
52
+ carriers = JSON.parse(readFileSync(cfgPath, "utf-8"))?.carriers;
53
+ } catch (e) {
54
+ return { ok: false, reason: `cannot read it back (${e.code ?? "not JSON"})` };
55
+ }
56
+ if (!Array.isArray(carriers)) return { ok: false, reason: "no carriers list in it" };
57
+ // Element by element, so a relayed URL left on disk (or any other drift) fails.
58
+ let same = true;
59
+ if (carriers.length !== expected.length || carriers.some((c, i) => c !== expected[i])) same = false; // @rule discovery.readback-equal
60
+ if (!same) return { ok: false, reason: "its carriers differ from what was written", carriers };
61
+ return { ok: true, carriers };
62
+ }
63
+
64
+ /** The relayed seed URLs a home's config.json lists now ([] if none or unreadable). */
65
+ export function relayedCarriersIn(cfgPath) {
66
+ try {
67
+ const carriers = JSON.parse(readFileSync(cfgPath, "utf-8"))?.carriers;
68
+ return Array.isArray(carriers) ? carriers.filter((c) => isRelayedSeedUrl(c)) : [];
69
+ } catch (_e) {
70
+ return [];
71
+ }
72
+ }
@@ -66,6 +66,16 @@ export const REFUSAL_FIXES = Object.freeze({
66
66
  "not-found": "use POST /v1/envelopes or GET /v1/inbox/<uuaid>",
67
67
  "not-a-seed": "do not list this carrier as a seed; it runs without a seed identity",
68
68
  "internal-error": "retry later; if it repeats, tell the carrier operator",
69
+ // Seed over egress (2.8.0): a registry's challenge, and a tunnel relay's /v1/tunnel and /e/*
70
+ "bad-challenge": "send challenge as 64 lowercase hex characters (32 random bytes), or leave it out",
71
+ "upgrade-required": "open /v1/tunnel as a WebSocket, as pillar-seed --relay does",
72
+ "seed-offline": "retry later or use another carrier; this seed's tunnel to the relay is down",
73
+ "tunnel-busy": "back off: retry after 5 s with jitter, doubling to 60 s, or use another carrier",
74
+ "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",
75
+ "seed-timeout": "retry, or use another carrier; the seed behind this relay did not answer in time",
76
+ "seed-bad-answer": "retry, or use another carrier; the seed behind this relay answered badly",
77
+ "seed-reset": "retry, or use another carrier; the seed behind this relay dropped the request",
78
+ "seed-answer-too-large": "ask with a smaller page, or use another carrier; the seed's answer passed the relay's size cap",
69
79
  // Client side: no server gave a code
70
80
  "carrier-unreachable": "check the carrier URLs and your network, then retry",
71
81
  "carrier-bad-response": "retry, or use another carrier; the carrier or its proxy answered without a reason",
@@ -75,6 +85,11 @@ export const REFUSAL_FIXES = Object.freeze({
75
85
  "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
86
  "p2p-not-installed": "install the optional libp2p transport with npm i @uuaid/pillar-p2p, or omit --libp2p to run in carrier-only mode",
77
87
  "sqlite-not-installed": "install or rebuild optional dependency better-sqlite3 with npm i better-sqlite3",
88
+ "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",
89
+ "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",
90
+ "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",
91
+ "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)",
92
+ "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
93
  });
79
94
 
80
95
  /**
@@ -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";
@@ -43,12 +43,65 @@ import { Keychain } from "../identity/keychain.mjs";
43
43
  import { makeTierGrant } from "../identity/tier.mjs";
44
44
  import { seal } from "./envelope.mjs";
45
45
  import { evaluateSeedTier, seedTier, GRANT_TTL_DAYS, DEMOTE_AFTER_FAILURES } from "./seed-tier.mjs";
46
+ import {
47
+ canonicalOrigin, relayShapeOrigin, relayedUrlFor, relayPathFor, decodeAttestHeader, isRelayedSeedUrl,
48
+ verifyRelayAttest, verifyServedProof, CHALLENGE_RE,
49
+ } from "./tunnel.mjs";
46
50
 
47
51
  const PROBE_TIMEOUT_MS = 10_000;
48
52
  const ROUND_TRIP_WAIT_S = 5;
49
53
  const MAX_RESPONSE_BYTES = 1024 * 1024;
54
+ const DAY_MS = 86_400_000;
50
55
  /** Keep the observation window bounded so uptime reflects recent behaviour. */
51
56
  export const PROBE_WINDOW = 1000;
57
+ /** The probe interval a registry assumes when none is given (pillar-directory's default). */
58
+ export const DEFAULT_PROBE_INTERVAL_MS = 10 * 60_000;
59
+ /** The longest a fleet-relay attestation vets a relayed seed (RedTeam 22f6c3 Q1). */
60
+ export const VETTING_LEASE_MAX_MS = 30 * 60_000;
61
+
62
+ /**
63
+ * How long one fresh fleet-relay attestation vets a relayed seed: min(3 x
64
+ * the effective probe interval, 30 minutes) (RedTeam 22f6c3 Q1; 085b71 C3).
65
+ * Three intervals let one probe be late or fail to arrive without a lapse;
66
+ * a seed that stops being probed, or fails a probe, loses priority within
67
+ * the lease. Only a passing challenge probe starts a lease; minting a grant
68
+ * never renews it, and a relayed seed's grant never outlives it.
69
+ */
70
+ export function vettingLeaseMs(probeIntervalMs = DEFAULT_PROBE_INTERVAL_MS) {
71
+ const interval = Number.isFinite(probeIntervalMs) && probeIntervalMs > 0 ? probeIntervalMs : DEFAULT_PROBE_INTERVAL_MS;
72
+ let lease = 3 * interval;
73
+ lease = Math.min(lease, VETTING_LEASE_MAX_MS); // @rule reg.vetting-lease-cap
74
+ return lease;
75
+ }
76
+
77
+ /**
78
+ * Parse a registry's fleet-relay pins: one `<origin> <ed25519 public key hex>`
79
+ * per line; blank lines and `#` comments are skipped. The origin must already
80
+ * be canonical. Throws naming the line on anything else, or a repeated origin.
81
+ */
82
+ export function parseFleetRelays(text) {
83
+ const out = new Map();
84
+ String(text).split(/\r?\n/).forEach((raw, i) => {
85
+ const line = raw.trim();
86
+ if (!line || line.startsWith("#")) return;
87
+ const parts = line.split(/\s+/);
88
+ const c = parts.length === 2 ? canonicalOrigin(parts[0]) : { ok: false, reason: "want <origin> <key>" };
89
+ if (!c.ok || c.origin !== parts[0]) throw new Error(`fleet relays line ${i + 1}: not a canonical origin (${c.reason ?? "not canonical"})`);
90
+ if (!/^[0-9a-f]{64}$/i.test(parts[1])) throw new Error(`fleet relays line ${i + 1}: the key must be 64 hex characters`);
91
+ if (out.has(c.origin)) throw new Error(`fleet relays line ${i + 1}: ${c.origin} is listed twice`);
92
+ out.set(c.origin, parts[1].toLowerCase());
93
+ });
94
+ return out;
95
+ }
96
+
97
+ /** A response header from either fetch flavour (Headers object or Node's plain object). */
98
+ function headerOf(res, name) {
99
+ const h = res?.headers;
100
+ if (!h) return undefined;
101
+ if (typeof h.get === "function") return h.get(name) ?? undefined;
102
+ const v = h[name];
103
+ return Array.isArray(v) ? v[0] : v;
104
+ }
52
105
 
53
106
  function unwrapHost(host) {
54
107
  const raw = String(host ?? "").trim().toLowerCase();
@@ -406,6 +459,9 @@ export class SeedRegistry {
406
459
  lookupImpl,
407
460
  allowPrivateUrls = false,
408
461
  probeTimeoutMs = PROBE_TIMEOUT_MS,
462
+ fleetRelays = null,
463
+ probeIntervalMs = DEFAULT_PROBE_INTERVAL_MS,
464
+ clock = () => Date.now(),
409
465
  } = {}) {
410
466
  if (!keychain?._identity) throw new Error("SeedRegistry needs a loaded keychain");
411
467
  this.keychain = keychain;
@@ -415,6 +471,20 @@ export class SeedRegistry {
415
471
  this.lookup = lookupImpl ?? lookup;
416
472
  this.allowPrivateUrls = allowPrivateUrls;
417
473
  this.probeTimeoutMs = probeTimeoutMs;
474
+ // Fleet relays this registry pins (origin -> relay key hex). Only a seed
475
+ // on one of these can be listed, vetted or granted while relayed.
476
+ this.fleetRelays = new Map(
477
+ [...(fleetRelays instanceof Map ? fleetRelays : Object.entries(fleetRelays ?? {}))]
478
+ .map(([o, k]) => [String(o), String(k).toLowerCase()]),
479
+ );
480
+ // The probe interval this registry runs at (pillar-directory passes its
481
+ // effective interval), and the vetting lease it implies.
482
+ this.probeIntervalMs = probeIntervalMs;
483
+ this.vettingLeaseMs = vettingLeaseMs(probeIntervalMs);
484
+ // The wall clock a relay attestation's `at` is checked against, read at the
485
+ // moment of the check (injectable for tests). Never a round's or a caller's
486
+ // `now`, which can be minutes old by then (Lead review C-P1).
487
+ this.clock = clock;
418
488
  const Database = requireBetterSqlite3("SeedRegistry");
419
489
  this.db = new Database(dbPath);
420
490
  this.db.pragma("journal_mode = WAL");
@@ -448,6 +518,62 @@ export class SeedRegistry {
448
518
  if (!cols.includes("probe_log")) {
449
519
  this.db.exec("alter table seeds add column probe_log text not null default ''");
450
520
  }
521
+ // 2.8.0 egress seeds: the pinned relay origin and key, how long the last
522
+ // fresh attestation vets it, and the row's pin state ('direct',
523
+ // 'pending-challenge' or 'relayed').
524
+ if (!cols.includes("relay")) this.db.exec("alter table seeds add column relay text");
525
+ if (!cols.includes("relay_key")) this.db.exec("alter table seeds add column relay_key text");
526
+ if (!cols.includes("vetted_until")) this.db.exec("alter table seeds add column vetted_until text");
527
+ if (!cols.includes("pin_state")) this.db.exec("alter table seeds add column pin_state text not null default 'direct'");
528
+ this._migrateRelayedRows();
529
+ this._migrateVettingToLease();
530
+ this._clampStoredVetting();
531
+ }
532
+
533
+ /**
534
+ * One-time, versioned (RedTeam 995f4c): every vetting stored before this
535
+ * registry first ran with the lease rule is cleared, however little time
536
+ * it has left, so every relayed seed proves itself again with a fresh
537
+ * challenge before it holds priority. A 24-hour vetting with 15 minutes
538
+ * left would otherwise survive the length check in _clampStoredVetting.
539
+ * Grants already signed keep their own expiry.
540
+ */
541
+ _migrateVettingToLease() {
542
+ this.db.exec("create table if not exists seed_registry_meta (k text primary key, v text not null)");
543
+ // Check and write in one IMMEDIATE transaction (RedTeam 87bb0b P3): two
544
+ // registries opening one database at once never both run it, and the
545
+ // second never fails on the marker. Sharing one database between
546
+ // registries is not a supported deployment; this only keeps it safe.
547
+ this.db.transaction(() => {
548
+ const claimed = this.db.prepare("insert or ignore into seed_registry_meta (k, v) values ('vetting-lease', '1')").run().changes === 1;
549
+ if (!claimed) return;
550
+ this.db.prepare("update seeds set vetted_until = null where vetted_until is not null").run(); // @rule reg.vetting-lease-migration
551
+ }).immediate();
552
+ }
553
+
554
+ /**
555
+ * A vetting stored under a longer lease than this registry grants now (its
556
+ * probe interval was shortened since) is cleared on open: the seed proves
557
+ * itself again with a fresh challenge before it holds priority (RedTeam
558
+ * 22f6c3 Q1). Vettings from before the lease rule are cleared once by
559
+ * _migrateVettingToLease. Grants already signed keep their own expiry.
560
+ */
561
+ _clampStoredVetting(now = this.clock()) {
562
+ const limit = new Date(now + this.vettingLeaseMs).toISOString();
563
+ 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
564
+ }
565
+
566
+ /**
567
+ * A row enrolled before 2.8.0 at a URL of the relayed shape
568
+ * (`<origin>/e/<localId of its key>`) was never challenged through its
569
+ * relay: it waits, unlisted and ungranted, until one challenge probe passes.
570
+ */
571
+ _migrateRelayedRows() {
572
+ const rows = this.db.prepare("select uuaid, url, public_key from seeds where pin_state = 'direct' and relay is null").all();
573
+ const mark = this.db.prepare("update seeds set pin_state = 'pending-challenge' where uuaid = ?");
574
+ for (const r of rows) {
575
+ if (relayShapeOrigin(r.url, r.public_key)) mark.run(r.uuaid); // @rule reg.migrate-pending
576
+ }
451
577
  }
452
578
 
453
579
  close() { if (this.db.open) this.db.close(); }
@@ -490,10 +616,15 @@ export class SeedRegistry {
490
616
  return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "probe timed out"}` };
491
617
  }
492
618
 
619
+ // A one-use challenge (2.8.0): a relayed seed must echo it inside its
620
+ // signed seed-info, and a fleet relay must attest it. A 2.7 seed ignores
621
+ // the query and still enrolls as a direct seed.
622
+ const challenge = randomBytes(32).toString("hex");
493
623
  let doc;
624
+ let attestHeader;
494
625
  try {
495
626
  const res = await raceSignal(
496
- this.fetch(`${resolved.url}/v1/seed-info`, {
627
+ this.fetch(`${resolved.url}/v1/seed-info?challenge=${challenge}`, {
497
628
  signal,
498
629
  redirect: "manual",
499
630
  ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
@@ -501,12 +632,15 @@ export class SeedRegistry {
501
632
  signal,
502
633
  );
503
634
  if (!res.ok) return { ok: false, reason: `seed-info-${res.status}` };
635
+ attestHeader = headerOf(res, "x-pillar-relay-attest");
504
636
  doc = await raceSignal(res.json(), signal);
505
637
  } catch (e) {
506
638
  return { ok: false, reason: `seed-unreachable: ${e?.message ?? e}` };
507
639
  }
508
640
  const v = verifySeedInfo(doc, resolved.url);
509
641
  if (!v.ok) return { ok: false, reason: `seed-info-invalid:${v.reason}` };
642
+ const topo = this._checkTopology(doc, { url: resolved.url, challenge, attestHeader, now });
643
+ if (!topo.ok) return { ok: false, reason: `seed-info-invalid:${topo.reason}` };
510
644
 
511
645
  const existing = this.get(doc.uuaid);
512
646
  if (existing) {
@@ -519,13 +653,55 @@ export class SeedRegistry {
519
653
  if (urlTaken) return { ok: false, reason: "url-already-enrolled" };
520
654
 
521
655
  this.db.prepare(`
522
- insert into seeds (uuaid, url, public_key, operator, region, enrolled_at, tier, claimed)
523
- values (?,?,?,?,?,?,'probation',?)
656
+ insert into seeds (uuaid, url, public_key, operator, region, enrolled_at, tier, claimed, relay, relay_key, vetted_until, pin_state)
657
+ values (?,?,?,?,?,?,'probation',?,?,?,?,?)
524
658
  `).run(doc.uuaid, resolved.url, doc.publicKey.toLowerCase(), operator, region,
525
- new Date(now).toISOString(), JSON.stringify(doc.stats ?? {}));
659
+ new Date(now).toISOString(), JSON.stringify(doc.stats ?? {}),
660
+ topo.relay, topo.relayKey, topo.vettedUntil, topo.relay ? "relayed" : "direct");
526
661
  return { ok: true, already: false, ...this.status(doc.uuaid) };
527
662
  }
528
663
 
664
+ /**
665
+ * What a signed seed-info says about the seed's topology, checked against
666
+ * the URL it was fetched from and the one-use challenge just sent.
667
+ *
668
+ * Direct: no `relay`, and the URL is not of the relayed shape; an echoed
669
+ * challenge must match. Relayed: `relay` is a canonical origin, the URL is
670
+ * exactly `<relay>/e/<localId of the key>`, and the challenge is echoed.
671
+ * When the relay is a fleet relay this registry pins, its attestation must
672
+ * verify under the configured key; that vets the seed until now + validity.
673
+ */
674
+ _checkTopology(doc, { url, challenge, attestHeader, now = Date.now() }) {
675
+ if (doc.challenge !== undefined && doc.challenge !== challenge) return { ok: false, reason: "challenge-mismatch" }; // @rule reg.challenge-echo
676
+ if (doc.relay === undefined) {
677
+ if (relayShapeOrigin(url, doc.publicKey)) return { ok: false, reason: "relay-undeclared" }; // @rule reg.relay-declared
678
+ return { ok: true, relay: null, relayKey: null, vettedUntil: null };
679
+ }
680
+ const c = canonicalOrigin(doc.relay);
681
+ if (!c.ok || c.origin !== doc.relay) return { ok: false, reason: "relay-not-canonical" };
682
+ if (url !== relayedUrlFor(doc.relay, doc.publicKey.toLowerCase())) return { ok: false, reason: "relay-url-mismatch" }; // @rule reg.relay-url-shape
683
+ if (doc.challenge !== challenge) return { ok: false, reason: "challenge-missing" }; // @rule reg.relayed-must-echo
684
+ const relayKey = this.fleetRelays.get(doc.relay);
685
+ if (!relayKey) return { ok: true, relay: doc.relay, relayKey: null, vettedUntil: null };
686
+ // `at` is the relay's clock when it answered, so it is checked against this
687
+ // registry's clock now that the answer is here (C-P1).
688
+ let attestNow = now;
689
+ attestNow = this.clock(); // @rule reg.attest-real-clock
690
+ const att = verifyRelayAttest(decodeAttestHeader(attestHeader), {
691
+ relayKey, origin: doc.relay, path: `${relayPathFor(doc.publicKey.toLowerCase())}/v1/seed-info`,
692
+ uuaid: doc.uuaid, publicKey: doc.publicKey, challenge, now: attestNow,
693
+ });
694
+ if (!att.ok) return { ok: false, reason: att.reason }; // @rule reg.fleet-relay-must-attest
695
+ // The lease runs from this seed's own observation time (`now`, per seed
696
+ // since C-P1), never from a mint.
697
+ return { ok: true, relay: doc.relay, relayKey, vettedUntil: new Date(now + this.vettingLeaseMs).toISOString() };
698
+ }
699
+
700
+ /** A relayed seed stops being vetted the moment any probe of it fails. */
701
+ _clearVetting(uuaid) {
702
+ this.db.prepare("update seeds set vetted_until = null where uuaid = ?").run(uuaid);
703
+ }
704
+
529
705
  /**
530
706
  * Record one health-probe outcome into an exact sliding window of the last
531
707
  * PROBE_WINDOW probes.
@@ -567,8 +743,13 @@ export class SeedRegistry {
567
743
  `).run(passed ? 1 : 0, uuaid);
568
744
  }
569
745
 
570
- /** GET <url>/v1/health — the liveness half of an observation. */
571
- async healthProbe(row) {
746
+ /**
747
+ * GET <url>/v1/health — the liveness half of an observation. A relayed or
748
+ * pending seed is instead challenged (see _challengeProbe): through a relay,
749
+ * an unsigned health answer proves only that the relay is up.
750
+ */
751
+ async healthProbe(row, { now = Date.now() } = {}) {
752
+ if ((row.pin_state ?? "direct") !== "direct") return this._challengeProbe(row, { now }); // @rule reg.relayed-health-is-challenge
572
753
  try {
573
754
  const signal = AbortSignal.timeout(this.probeTimeoutMs);
574
755
  const resolved = await resolveSeedUrl(row.url, {
@@ -591,6 +772,43 @@ export class SeedRegistry {
591
772
  } catch (_e) { return false; }
592
773
  }
593
774
 
775
+ /**
776
+ * One challenge probe of a relayed (or pending) seed: GET seed-info with a
777
+ * fresh one-use challenge. Passes only if the doc is signed by the pinned
778
+ * key for the pinned uuaid and URL, declares the pinned relay, echoes the
779
+ * challenge, and (for a fleet relay) carries a valid attestation. Any error
780
+ * fails the probe and clears vetting; nothing falls back to /v1/health.
781
+ */
782
+ async _challengeProbe(row, { now = Date.now() } = {}) {
783
+ const fail = () => { this._clearVetting(row.uuaid); return false; };
784
+ const challenge = randomBytes(32).toString("hex");
785
+ try {
786
+ const signal = AbortSignal.timeout(this.probeTimeoutMs);
787
+ const resolved = await resolveSeedUrl(row.url, { allowPrivateUrls: this.allowPrivateUrls, lookup: this.lookup, signal });
788
+ if (!resolved.ok || signal.aborted) return fail();
789
+ const res = await raceSignal(
790
+ this.fetch(`${resolved.url}/v1/seed-info?challenge=${challenge}`, {
791
+ signal, redirect: "manual", ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
792
+ }),
793
+ signal,
794
+ );
795
+ if (!res.ok) return fail();
796
+ const attestHeader = headerOf(res, "x-pillar-relay-attest");
797
+ const doc = await raceSignal(res.json(), signal);
798
+ if (!verifySeedInfo(doc, row.url).ok) return fail();
799
+ if (doc.uuaid !== row.uuaid || String(doc.publicKey).toLowerCase() !== row.public_key) return fail(); // @rule reg.pin-identity
800
+ const topo = this._checkTopology(doc, { url: row.url, challenge, attestHeader, now });
801
+ // A pass means url === <relay>/e/<localId of the pinned key>, and the URL is
802
+ // pinned, so the relay origin it declares is the pinned one too.
803
+ if (!topo.ok || !topo.relay) return fail(); // @rule reg.pin-stays-relayed
804
+ this.db.prepare("update seeds set pin_state = 'relayed', relay = ?, relay_key = ?, vetted_until = ? where uuaid = ?")
805
+ .run(topo.relay, topo.relayKey, topo.vettedUntil, row.uuaid);
806
+ return true;
807
+ } catch (_e) {
808
+ return fail();
809
+ }
810
+ }
811
+
594
812
  /**
595
813
  * Push a real signed envelope THROUGH the seed and read it back out.
596
814
  *
@@ -646,10 +864,14 @@ export class SeedRegistry {
646
864
  const path = `GET /v1/inbox/${me.uuaid}?since=${since}`;
647
865
  const ts = String(Date.now());
648
866
  const sig = this.keychain.sign(Buffer.from(`${path}\n${ts}`, "utf-8")).toString("hex");
867
+ // 2.8.0: a one-use challenge the seed binds, with the digest of the exact
868
+ // page it returns, into a signed served proof (RedTeam 085b71 C4). A 2.7
869
+ // seed ignores it; the inbox signature does not cover the query.
870
+ const rt = randomBytes(32).toString("hex");
649
871
  const getSignal = AbortSignal.timeout(this.probeTimeoutMs + ROUND_TRIP_WAIT_S * 1000);
650
872
  const res = await raceSignal(
651
873
  this.fetch(
652
- `${resolved.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}`,
874
+ `${resolved.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}&challenge=${rt}`,
653
875
  {
654
876
  headers: { "x-pillar-pubkey": me.publicKeyHex, "x-pillar-ts": ts, "x-pillar-sig": sig },
655
877
  signal: getSignal,
@@ -662,7 +884,21 @@ export class SeedRegistry {
662
884
  if (res.status !== 200) return { ok: false, reason: `inbox-${res.status}` };
663
885
  const body = await raceSignal(res.json(), getSignal);
664
886
  const found = (body?.envelopes ?? []).some(e => e?.envelope?.id === envelope.id);
665
- return found ? { ok: true } : { ok: false, reason: "envelope-not-returned" };
887
+ if (!found) return { ok: false, reason: "envelope-not-returned" };
888
+ // A relay can answer a round trip from its own store; only the seed key
889
+ // can sign what the seed served. Required for relayed and pending rows
890
+ // (which fail closed without a pinned key); a direct seed's proof, when
891
+ // present, must verify against the row's key. A caller passing a partial
892
+ // direct row with no key (the 2.7.1 API allowed it) gets 2.7.1 behaviour.
893
+ let needProof = body?.proof !== undefined && typeof row.public_key === "string";
894
+ if ((row.pin_state ?? "direct") !== "direct") needProof = true; // @rule reg.relayed-needs-proof
895
+ if (needProof) {
896
+ const p = verifyServedProof(body?.proof, {
897
+ publicKey: row.public_key, seed: row.uuaid, inbox: me.uuaid, since, challenge: rt, envelopes: body?.envelopes,
898
+ });
899
+ if (!p.ok) return { ok: false, reason: p.reason };
900
+ }
901
+ return { ok: true };
666
902
  } catch (e) {
667
903
  return { ok: false, reason: `probe-threw: ${e?.message ?? e}` };
668
904
  }
@@ -674,24 +910,67 @@ export class SeedRegistry {
674
910
  * failed health probe — one outage, one mark.
675
911
  */
676
912
  async observe(row, { now = Date.now() } = {}) {
677
- const alive = await this.healthProbe(row);
913
+ const alive = await this.healthProbe(row, { now });
678
914
  this.recordProbe(row.uuaid, alive, now);
679
915
  let rt = null;
680
916
  if (alive) {
681
- rt = await this.roundTripProbe(row, { now });
917
+ const current = this.get(row.uuaid) ?? row; // the challenge probe may have pinned it
918
+ rt = await this.roundTripProbe(current, { now });
682
919
  this.recordRoundTrip(row.uuaid, rt.ok);
920
+ if (!rt.ok && (current.pin_state ?? "direct") !== "direct") this._clearVetting(row.uuaid); // @rule reg.rt-failure-clears-vetting
683
921
  }
684
922
  const evaluated = this.evaluate(row.uuaid, now);
685
923
  return { uuaid: row.uuaid, url: row.url, alive, roundTrip: rt, ...evaluated };
686
924
  }
687
925
 
688
- /** Observe every enrolled seed. Sequential: probes are cheap and ordering keeps logs readable. */
689
- async observeAll({ now = Date.now() } = {}) {
926
+ /**
927
+ * Observe every enrolled seed. Sequential: probes are cheap and ordering
928
+ * keeps logs readable. Each seed is observed at its own time, so one slow
929
+ * seed never ages the clock the next one is judged by (C-P1); a caller that
930
+ * passes `now` (a synthetic clock, in tests) gets that clock for every seed.
931
+ */
932
+ async observeAll({ now } = {}) {
690
933
  const out = [];
691
- for (const row of this.all()) out.push(await this.observe(row, { now }));
934
+ for (const row of this.all()) out.push(await this.observe(row, now === undefined ? {} : { now }));
692
935
  return out;
693
936
  }
694
937
 
938
+ /**
939
+ * A row's topology NOW (2.8.0). Rechecked on every status, directory,
940
+ * evaluation and grant: the pin must still match this registry's fleet
941
+ * relay config, and vetting must not have lapsed.
942
+ */
943
+ _topology(row, now = Date.now()) {
944
+ const state = row.pin_state ?? "direct";
945
+ if (state === "direct") return "direct";
946
+ if (state !== "relayed") return "pending";
947
+ const configured = this.fleetRelays.get(row.relay);
948
+ if (!configured || configured !== row.relay_key) return "relayed-unvetted"; // @rule reg.pin-presence
949
+ const until = Date.parse(row.vetted_until ?? "");
950
+ if (!(until > now)) return "relayed-lapsed"; // @rule reg.vetting-fresh
951
+ return "relayed-vetted";
952
+ }
953
+
954
+ /**
955
+ * One evaluation of a row, shared by status, directory, evaluate and
956
+ * grantFor, so the topology cap, listing and grant rules cannot drift apart.
957
+ */
958
+ _standing(row, now = Date.now()) {
959
+ const topology = this._topology(row, now);
960
+ const ev = evaluateSeedTier({ ...SeedRegistry._record(row), topology }, now);
961
+ const rung = seedTier(ev.tier);
962
+ let grantTier = rung.grant;
963
+ if (topology !== "direct" && topology !== "relayed-vetted") grantTier = null; // @rule reg.grant-needs-vetting
964
+ let grantExpiresMs = now + GRANT_TTL_DAYS * DAY_MS;
965
+ if (topology !== "direct") grantExpiresMs = Math.min(grantExpiresMs, Date.parse(row.vetted_until ?? "") || now); // @rule reg.grant-expiry-at-vetting
966
+ let listed = !ev.demoted;
967
+ // 2.8.0 (RedTeam 22f6c3 Q2): no relayed seed is listed, vetted or not;
968
+ // clients reach one only by explicit config. Its status and probes stay.
969
+ if (topology !== "direct") listed = false; // @rule reg.list-direct-only
970
+ if (isRelayedSeedUrl(row.url)) listed = false; // @rule reg.list-no-relayed-shape
971
+ return { ev, rung, topology, grantTier, priority: grantTier !== null && rung.priority, listed, grantExpiresMs };
972
+ }
973
+
695
974
  /**
696
975
  * Recompute a seed's rung from observations and persist it. Returns the
697
976
  * evaluation plus whether the rung moved, so callers can log promotions
@@ -701,7 +980,7 @@ export class SeedRegistry {
701
980
  const row = this.get(uuaid);
702
981
  if (!row) return { ok: false, reason: "unknown-seed" };
703
982
  const before = row.tier;
704
- const ev = evaluateSeedTier(SeedRegistry._record(row), now);
983
+ const { ev } = this._standing(row, now);
705
984
  if (ev.tier !== before) {
706
985
  this.db.prepare("update seeds set tier = ?, promoted_at = ? where uuaid = ?")
707
986
  .run(ev.tier, new Date(now).toISOString(), uuaid);
@@ -714,19 +993,21 @@ export class SeedRegistry {
714
993
  *
715
994
  * Issued fresh each call with a GRANT_TTL_DAYS expiry. That TTL is the
716
995
  * whole revocation story: a seed that stops serving stops being re-issued,
717
- * and its last grant dies on its own within the window.
996
+ * and its last grant dies on its own within the window. A relayed seed is
997
+ * granted only while a fleet relay's attestation vets it, and its grant
998
+ * never outlives that vetting (2.8.0, RedTeam 085b71 C3).
718
999
  */
719
1000
  grantFor(uuaid, now = Date.now()) {
720
1001
  const row = this.get(uuaid);
721
1002
  if (!row) return null;
722
- const rung = seedTier(row.tier);
723
- if (!rung.grant) return null;
1003
+ const s = this._standing(row, now);
1004
+ if (!s.grantTier) return null;
724
1005
  return makeTierGrant(this.keychain, {
725
1006
  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,
1007
+ tier: s.grantTier,
1008
+ expires: new Date(s.grantExpiresMs).toISOString(),
1009
+ priority: s.priority,
1010
+ seedTier: s.rung.name,
730
1011
  seedUrl: row.url,
731
1012
  });
732
1013
  }
@@ -735,8 +1016,7 @@ export class SeedRegistry {
735
1016
  status(uuaid, now = Date.now()) {
736
1017
  const row = this.get(uuaid);
737
1018
  if (!row) return { ok: false, reason: "unknown-seed" };
738
- const ev = evaluateSeedTier(SeedRegistry._record(row), now);
739
- const rung = seedTier(ev.tier);
1019
+ const { ev, rung, topology, grantTier, priority, listed } = this._standing(row, now);
740
1020
  return {
741
1021
  ok: true,
742
1022
  uuaid: row.uuaid,
@@ -746,11 +1026,18 @@ export class SeedRegistry {
746
1026
  enrolledAt: row.enrolled_at,
747
1027
  tier: ev.tier,
748
1028
  blurb: rung.blurb,
749
- priority: rung.priority,
750
- grantTier: rung.grant,
1029
+ priority,
1030
+ grantTier,
751
1031
  demoted: ev.demoted,
752
1032
  next: ev.next,
753
1033
  missing: ev.missing,
1034
+ // 2.8.0: declared topology. A 2.7 registry omits these, and a client
1035
+ // reading a relayed URL's standing without them knows its liveness was
1036
+ // only relay-attested.
1037
+ topology,
1038
+ pinState: row.pin_state ?? "direct",
1039
+ ...(row.relay ? { relay: row.relay, vettedUntil: row.vetted_until } : {}),
1040
+ listed,
754
1041
  observed: {
755
1042
  probes: { total: row.probes_total, passed: row.probes_passed },
756
1043
  roundTrips: { total: row.rt_total, passed: row.rt_passed },
@@ -769,39 +1056,51 @@ export class SeedRegistry {
769
1056
  * entirely: the directory is what a fresh agent bootstraps its carrier list
770
1057
  * from, and handing it a host that failed its last three probes is how you
771
1058
  * get a first-run experience of silent message loss.
1059
+ *
1060
+ * 2.8.0 (RedTeam 22f6c3 Q2): no relayed seed URL is published here, in
1061
+ * seeds[] or as the bootstrap carrier, whatever its vetting. Automatic
1062
+ * discovery of relayed seeds waits for audience-bound inbox auth; until
1063
+ * then a client names one explicitly. Served at /directory.json and /.
772
1064
  */
773
1065
  directory({ agents = [], now = Date.now(), includeProbation = true } = {}) {
774
1066
  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")
1067
+ .map(r => ({ r, s: this._standing(r, now) }))
1068
+ .filter(({ s }) => s.listed)
1069
+ .filter(({ s }) => includeProbation || s.ev.tier !== "probation")
778
1070
  .sort((a, b) => {
779
- const d = seedTier(a.ev.tier).listRank - seedTier(b.ev.tier).listRank;
1071
+ const d = seedTier(a.s.ev.tier).listRank - seedTier(b.s.ev.tier).listRank;
780
1072
  return d !== 0 ? d : a.r.enrolled_at.localeCompare(b.r.enrolled_at);
781
1073
  });
782
1074
  return {
783
1075
  protocol: this.protocol,
784
- carrier: this.carrierUrl,
1076
+ carrier: this._bootstrapCarrier(),
785
1077
  updated: new Date(now).toISOString(),
786
1078
  issuer: this.issuerKey,
787
1079
  agents,
788
- seeds: rows.map(({ r, ev }) => ({
1080
+ seeds: rows.map(({ r, s }) => ({
789
1081
  url: r.url,
790
1082
  operator: r.operator ?? undefined,
791
1083
  region: r.region ?? undefined,
792
1084
  since: r.enrolled_at.slice(0, 10),
793
1085
  // Published so a client can rank carriers without asking the
794
1086
  // registry a second question (see CarrierClient carrierTiers).
795
- tier: ev.tier,
796
- priority: seedTier(ev.tier).priority,
1087
+ tier: s.ev.tier,
1088
+ priority: s.rung.priority,
797
1089
  // String decimal, not a float: directory.json has to survive JCS
798
1090
  // canonicalization (directoryEtag, and any future signed directory),
799
1091
  // and JCS admits no non-integer number.
800
- uptime: ev.uptime.toFixed(4),
1092
+ uptime: s.ev.uptime.toFixed(4),
801
1093
  })),
802
1094
  };
803
1095
  }
804
1096
 
1097
+ /** The bootstrap carrier, unless it is a relayed seed URL (RedTeam 22f6c3 Q2). */
1098
+ _bootstrapCarrier() {
1099
+ let carrier = this.carrierUrl;
1100
+ if (carrier && isRelayedSeedUrl(carrier)) carrier = null; // @rule reg.carrier-not-relayed
1101
+ return carrier;
1102
+ }
1103
+
805
1104
  /** Stable id for a directory render — lets a publisher skip no-op writes. */
806
1105
  static directoryEtag(dir) {
807
1106
  const { updated, ...rest } = dir;