@uuaid/pillar 2.5.3 → 2.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -169,6 +169,23 @@ themselves. Messages from members who are not your contacts still follow
169
169
  Same convention as the mobile app and agentnet.chat; `send-group` with a
170
170
  `groups.json` keeps working and now sends the same tag.
171
171
 
172
+ For signed groups-v2 invitations, an incomplete manifest chain waits in a
173
+ bounded buffer: at most 4 pending invitations per sender and 64 overall,
174
+ with 4 MiB per sender and 32 MiB total across invitation and recovery buffers.
175
+ Malformed manifests take no slot. At the count caps, invitations that do not
176
+ name your exact UUAID and key as invited are evicted before ones that do;
177
+ within each class the oldest goes first, from the same sender first when
178
+ that sender is at its cap. Malformed manifests cannot evict anything, and
179
+ existing non-self junk is removed before a pending invitation that names you.
180
+ A complete, verified invitation is adopted immediately and leaves no pending
181
+ slot.
182
+
183
+ The accepted remaining limit is that 64 genuine but incomplete invitations
184
+ that name you (16 senders with 4 each) can evict an older pending invitation
185
+ that also names you. Re-sending its manifest chain completes that invitation;
186
+ the eviction delays adoption and does not remove an adopted group. Admission
187
+ and eviction do not currently prefer contacts or trusted senders.
188
+
172
189
  ### Replacing an identity: `init --force`
173
190
 
174
191
  `init --force` mints a NEW uuaid, which silently breaks every contact that
@@ -274,13 +291,14 @@ What an outside operator needs to know before the first start:
274
291
  36500 days (100 years): for `pillar-seed` from 2.5.2, and for `pillar-carrier`
275
292
  and every `CarrierServer` from 2.5.3. Larger values used to be accepted, and
276
293
  from about 2,912,144 days the hourly pass deleted mail as soon as it was stored.
277
- - **There is no public seed registry yet** (as of 2.5.3, October 2026).
278
- `https://pillar.uuaid.org` does not answer `/v1/seeds`, so
279
- `--announce https://pillar.uuaid.org` cannot enroll.
280
- A seed runs standalone: it carries mail for every client configured with its
281
- URL (`pillar init --carriers https://seed.example.org`). `--announce` works
282
- against a registry that runs `pillar-directory`; from 2.5.3, announcing to a
283
- host with no registry says so in the seed's output.
294
+ - **Enroll a public seed at `https://pillar.uuaid.org`.** Once the public
295
+ registry is deployed, run `pillar-seed --public-url https://seed.example.org
296
+ --announce https://pillar.uuaid.org` to send `POST /v1/seeds` with your seed's
297
+ URL. The seed must serve a signed `/v1/seed-info` document naming that URL.
298
+ Private, loopback, and link-local URLs are refused. These are enrollment
299
+ instructions, not a statement that the registry deployment is live.
300
+ A seed can also carry mail for clients configured with its URL
301
+ (`pillar init --carriers https://seed.example.org`).
284
302
  - **Use a real domain.** Free no-DNS names (such as `*.sslip.io`) are blocked
285
303
  by some home and corporate network filters, so some clients cannot reach a
286
304
  seed on one.
@@ -357,8 +375,9 @@ survivors.
357
375
 
358
376
  ### Joining is permissionless
359
377
 
360
- When a registry runs `pillar-directory`, TLS-terminate a public URL and announce
361
- it there (there is no public registry yet; see "Running a seed" above):
378
+ TLS-terminate your seed's public URL and announce it to a registry running
379
+ `pillar-directory`. For the planned public registry, use
380
+ `https://pillar.uuaid.org` once deployed (see "Running a seed" above):
362
381
 
363
382
  ```sh
364
383
  pillar-seed --home /var/lib/pillar/seed --db /var/lib/pillar/seed.db \
package/bin/pillar.mjs CHANGED
@@ -52,6 +52,12 @@ import { groupCommandRoute, groupRouteLookups, RosterStore } from "../src/groups
52
52
  import { runGroupV2 } from "../src/group-v2-cli.mjs";
53
53
  import { Mailbox } from "../src/mailbox/mailbox.mjs";
54
54
 
55
+ // JSON rendered as one text line (or embedded in a Zestro command). Preserve
56
+ // parsed values while escaping the two separators JSON.stringify leaves raw.
57
+ function jsonLine(value) {
58
+ return JSON.stringify(value).replace(/[\u2028\u2029]/g, c => `\\u${c.charCodeAt(0).toString(16)}`);
59
+ }
60
+
55
61
  function parseArgs(argv) {
56
62
  const args = { _: [] };
57
63
  for (let i = 0; i < argv.length; i++) {
@@ -836,7 +842,7 @@ async function cmdGroup(args) {
836
842
  const { decrypt } = await import("../src/net/envelope.mjs");
837
843
  // A local view: it never pulls from carriers (that would take "new" away
838
844
  // from the next inbox run). Pull with pillar inbox first.
839
- console.log(JSON.stringify({ group: g.id, name: g.name, members: g.members, pending: g.pending, left: g.left, createdBy: g.createdBy, view: "local — pull new mail with pillar inbox" }));
845
+ console.log(jsonLine({ group: g.id, name: g.name, members: g.members, pending: g.pending, left: g.left, createdBy: g.createdBy, view: "local — pull new mail with pillar inbox" }));
840
846
  const items = [];
841
847
  for (const row of p.mailbox.groupInbound(g.id, limit)) {
842
848
  const { env, payload } = viewOfRow(p, row, decrypt);
@@ -855,7 +861,7 @@ async function cmdGroup(args) {
855
861
  }
856
862
  for (const [msgId, m] of byMsg) items.push({ at: m.at, line: { dir: "out", msgId, at: m.at, members: m.to, acceptedByCarrier: m.carrier, acknowledged: m.acked, read: m.read } });
857
863
  items.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
858
- for (const it of items.slice(-limit)) console.log(JSON.stringify(it.line));
864
+ for (const it of items.slice(-limit)) console.log(jsonLine(it.line));
859
865
  return;
860
866
  }
861
867
  } finally {
@@ -955,7 +961,7 @@ async function cmdRecv(args) {
955
961
  const tag = extractGroupTag(env.payload);
956
962
  if (tag) { line.group = tag.name; line.groupId = tag.id; if (tag.msgId) line.msgId = tag.msgId; if (tag.op !== "message") line.op = tag.op; }
957
963
  if (rk.named) line.id = env.id;
958
- console.log(JSON.stringify(line));
964
+ console.log(jsonLine(line));
959
965
  if (bridge && env.kind === "request") {
960
966
  // Interaction-convention return leg: ack FIRST — pillar-ask allows 120s
961
967
  // per phase but ZestroBridge times out at 30s, so the ack goes out before
@@ -970,7 +976,7 @@ async function cmdRecv(args) {
970
976
  const senderKey = env.transportSignature.publicKey; // open() F1: sender derives from this key
971
977
  try {
972
978
  if (!autoAcks) await p.send({ recipient: env.sender, recipientPublicKey: senderKey, kind: "ack", payload: { inReplyTo: env.id } });
973
- const result = await bridge.sendCommand({ command: JSON.stringify({ kind: env.kind, payload: env.payload, sender: env.sender }) });
979
+ const result = await bridge.sendCommand({ command: jsonLine({ kind: env.kind, payload: env.payload, sender: env.sender }) });
974
980
  const hasText = result && typeof result === "object" &&
975
981
  ["text", "result", "output", "response", "message"].some(k => k in result);
976
982
  const text = hasText
@@ -996,8 +1002,8 @@ async function cmdRecv(args) {
996
1002
  }
997
1003
  } else if (bridge && env.kind !== "ack" && env.kind !== "reply") {
998
1004
  try {
999
- const result = await bridge.sendCommand({ command: JSON.stringify({ kind: env.kind, payload: env.payload, sender: env.sender }) });
1000
- console.log(` → zestro result: ${JSON.stringify(result).slice(0, 200)}`);
1005
+ const result = await bridge.sendCommand({ command: jsonLine({ kind: env.kind, payload: env.payload, sender: env.sender }) });
1006
+ console.log(` → zestro result: ${jsonLine(result).slice(0, 200)}`);
1001
1007
  } catch (e) {
1002
1008
  if (e.code === "SESSION_BUSY") {
1003
1009
  console.log(` → zestro: busy (${e.message})`);
@@ -1093,7 +1099,7 @@ async function cmdInbox(args) {
1093
1099
  const rows = p.mailbox.inboxAfter(startCursor, 1000);
1094
1100
  for (const row of rows) {
1095
1101
  const { env, payload, groupId } = viewOfRow(p, row, decrypt);
1096
- console.log(JSON.stringify(inboxLine(env, payload, { new: true })));
1102
+ console.log(jsonLine(inboxLine(env, payload, { new: true })));
1097
1103
  printed.push({ id: env.id, sender: env.sender, kind: env.kind, payload, groupId });
1098
1104
  }
1099
1105
  if (rows.length && !args.peek) p.mailbox.setReaderCursor(rk.key, rows.at(-1).released_seq ?? rows.at(-1).seq);
@@ -1105,7 +1111,7 @@ async function cmdInbox(args) {
1105
1111
  // courier's auto-ack, a bot) seal back to a sender who is NOT in fleet.json
1106
1112
  // via `pillar send … --to-pubkey <fromPublicKey>`. Additive field.
1107
1113
  for (const env of fresh) {
1108
- console.log(JSON.stringify(inboxLine(env, env.payload, { new: true })));
1114
+ console.log(jsonLine(inboxLine(env, env.payload, { new: true })));
1109
1115
  printed.push({ id: env.id, sender: env.sender, kind: env.kind, payload: env.payload, groupId: extractGroupTag(env.payload)?.id ?? null });
1110
1116
  }
1111
1117
  // Backlog: rows stored earlier (e.g. by a recv daemon) but never surfaced.
@@ -1116,7 +1122,7 @@ async function cmdInbox(args) {
1116
1122
  if (args.unread) {
1117
1123
  for (const row of backlog) {
1118
1124
  const { env, payload, groupId } = viewOfRow(p, row, decrypt);
1119
- console.log(JSON.stringify(inboxLine(env, payload, { new: false })));
1125
+ console.log(jsonLine(inboxLine(env, payload, { new: false })));
1120
1126
  printed.push({ id: env.id, sender: env.sender, kind: env.kind, payload, groupId });
1121
1127
  }
1122
1128
  }
@@ -1155,7 +1161,7 @@ async function cmdInbox(args) {
1155
1161
  const { spawnSync } = await import("node:child_process");
1156
1162
  const r = spawnSync(args.notify, {
1157
1163
  shell: true,
1158
- input: JSON.stringify({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1164
+ input: jsonLine({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1159
1165
  env: { ...process.env, PILLAR_NEW: String(newCount), PILLAR_UNREAD: String(backlog.length), PILLAR_UUAID: p.uuaid },
1160
1166
  stdio: ["pipe", "inherit", "inherit"],
1161
1167
  });
@@ -1200,7 +1206,7 @@ async function cmdWait(args) {
1200
1206
  const report = (carrierViews, local) => {
1201
1207
  const kinds = {};
1202
1208
  for (const k of [...carrierViews.map((v) => v.kind), ...local.map((r) => JSON.parse(r.envelope_json).kind)]) kinds[k] = (kinds[k] ?? 0) + 1;
1203
- console.log(JSON.stringify({ uuaid: p.uuaid, ...(rk.named ? { reader: rk.key } : {}), pending: carrierViews.length + local.length, carrier: carrierViews.length, local: local.length, kinds }));
1209
+ console.log(jsonLine({ uuaid: p.uuaid, ...(rk.named ? { reader: rk.key } : {}), pending: carrierViews.length + local.length, carrier: carrierViews.length, local: local.length, kinds }));
1204
1210
  };
1205
1211
  let local = localRows();
1206
1212
  if (local.length) { report([], local); await p.stop(); exit(0); }
@@ -1209,7 +1215,7 @@ async function cmdWait(args) {
1209
1215
  local = localRows();
1210
1216
  await p.stop();
1211
1217
  if (views.length || local.length) { report(views, local); exit(0); }
1212
- console.log(JSON.stringify({ uuaid: p.uuaid, pending: 0, timedOut: true }));
1218
+ console.log(jsonLine({ uuaid: p.uuaid, pending: 0, timedOut: true }));
1213
1219
  exit(3);
1214
1220
  }
1215
1221
 
@@ -1227,7 +1233,7 @@ async function cmdReaders(args) {
1227
1233
  for (const r of readers) {
1228
1234
  const behind = mb.inboxAfter(r.cursor, 100000).length;
1229
1235
  const leases = live.filter((l) => l.reader === r.name);
1230
- console.log(JSON.stringify({
1236
+ console.log(jsonLine({
1231
1237
  reader: r.name, named: !r.name.startsWith("ctx:"), cursor: r.cursor, unseen: behind,
1232
1238
  last: describeProcess(r), live: leases.map(describeProcess),
1233
1239
  }));
@@ -1261,7 +1267,7 @@ async function cmdStatus(args) {
1261
1267
  const rows = id ? [p.mailbox.getOutbound(id)].filter(Boolean) : p.mailbox.outboxRecent(Number(args.limit ?? 20));
1262
1268
  if (id && !rows.length) { console.error(`no envelope ${id} in this home's outbox`); exit(2); }
1263
1269
  for (const r of rows) {
1264
- console.log(JSON.stringify({
1270
+ console.log(jsonLine({
1265
1271
  id: r.envelope_id, to: r.recipient, kind: r.kind ?? null, at: r.created_at,
1266
1272
  ...(r.group_id ? { groupId: r.group_id, msgId: r.group_msg_id ?? null } : {}),
1267
1273
  acceptedByCarrier: r.status === "delivered" ? (r.delivered_at ?? true) : null,
@@ -1372,7 +1378,7 @@ async function cmdTrust(args) {
1372
1378
  return;
1373
1379
  }
1374
1380
  for (const row of mb.inboxQuarantined(500)) {
1375
- console.log(JSON.stringify({ id: row.envelope_id, from: row.sender, reason: row.quarantined, at: row.received_at }));
1381
+ console.log(jsonLine({ id: row.envelope_id, from: row.sender, reason: row.quarantined, at: row.received_at }));
1376
1382
  }
1377
1383
  mb.close();
1378
1384
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.5.3",
3
+ "version": "2.5.5",
4
4
  "description": "Pillar (Protocol for Inter-agent Linked Ledger And Relay) — the secure delivery layer of UACP, the Universal Agent Communication Protocol. UACP = UUAID (identity) + Envelope (signed, encrypted container) + Pillar (relay, mailbox, routing, store-and-forward). Reference implementation of the UACP delivery layer; includes VDA-1 (IAASO-3901, in ballot) delivery attestation and a blind escrow for the Zilligon ZGN / EVM rails.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -106,7 +106,7 @@ export function withCarrierFix(status, body) {
106
106
  * terminal. Every other character is printed as received.
107
107
  */
108
108
  function oneLine(value) {
109
- return String(value).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim();
109
+ return String(value).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").trim();
110
110
  }
111
111
 
112
112
  /**
@@ -33,6 +33,9 @@
33
33
  * priority is to become infrastructure for everyone else.
34
34
  */
35
35
  import { createHash } from "node:crypto";
36
+ import dns from "node:dns";
37
+ import { request as httpRequest } from "node:http";
38
+ import { request as httpsRequest } from "node:https";
36
39
  import { isIP } from "node:net";
37
40
  import Database from "better-sqlite3";
38
41
  import { jcs } from "../identity/jcs.mjs";
@@ -43,29 +46,109 @@ import { evaluateSeedTier, seedTier, GRANT_TTL_DAYS, DEMOTE_AFTER_FAILURES } fro
43
46
 
44
47
  const PROBE_TIMEOUT_MS = 10_000;
45
48
  const ROUND_TRIP_WAIT_S = 5;
49
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
46
50
  /** Keep the observation window bounded so uptime reflects recent behaviour. */
47
51
  export const PROBE_WINDOW = 1000;
48
52
 
53
+ function unwrapHost(host) {
54
+ const raw = String(host ?? "").trim().toLowerCase();
55
+ return raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1) : raw;
56
+ }
57
+
58
+ function isPrivateIpv4Octets(a, b, c, d) {
59
+ if ([a, b, c, d].some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
60
+ if (a === 0 || a === 10 || a === 127) return true; // 0.0.0.0/8, 10.0.0.0/8, 127.0.0.0/8
61
+ if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 (CGNAT)
62
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 (link-local / cloud metadata)
63
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 (RFC 1918)
64
+ if (a === 192 && b === 0 && c === 0) return true; // 192.0.0.0/24 (IETF protocol assignments)
65
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16 (RFC 1918)
66
+ if (a === 198 && (b === 18 || b === 19)) return true; // 198.18.0.0/15 (benchmarking)
67
+ if (a >= 224) return true; // 224.0.0.0/4 (multicast) + 240.0.0.0/4 (reserved/broadcast)
68
+ return false;
69
+ }
70
+
71
+ function parseIpv6Words(addr) {
72
+ let s = addr;
73
+ const lastColon = s.lastIndexOf(":");
74
+ if (lastColon !== -1 && s.slice(lastColon + 1).includes(".")) {
75
+ const v4 = s.slice(lastColon + 1);
76
+ if (isIP(v4) !== 4) return null;
77
+ const [a, b, c, d] = v4.split(".").map(Number);
78
+ const hi = ((a << 8) | b).toString(16);
79
+ const lo = ((c << 8) | d).toString(16);
80
+ s = `${s.slice(0, lastColon + 1)}${hi}:${lo}`;
81
+ }
82
+ const halves = s.split("::");
83
+ if (halves.length > 2) return null;
84
+ let groups;
85
+ if (halves.length === 2) {
86
+ const left = halves[0] ? halves[0].split(":") : [];
87
+ const right = halves[1] ? halves[1].split(":") : [];
88
+ const fill = 8 - left.length - right.length;
89
+ if (fill < 1) return null;
90
+ groups = [...left, ...Array(fill).fill("0"), ...right];
91
+ } else {
92
+ groups = s.split(":");
93
+ }
94
+ if (groups.length !== 8) return null;
95
+ const words = groups.map((g) => (/^[0-9a-f]{1,4}$/i.test(g) ? parseInt(g, 16) : NaN));
96
+ return words.some(Number.isNaN) ? null : words;
97
+ }
98
+
49
99
  /**
50
- * Hostnames that must never be probed from a public registry. Enrollment
51
- * takes a URL from an unauthenticated stranger and makes the registry fetch
52
- * it, which is a server-side request forgery primitive unless it is fenced.
100
+ * Hostnames and IP literals that must never be probed from a public registry.
101
+ * Enrollment takes a URL from an unauthenticated stranger and makes the
102
+ * registry fetch it, which is a server-side request forgery primitive unless
103
+ * both literal addresses and resolved DNS answers are fenced.
53
104
  * Tests pass allowPrivateUrls to reach a loopback seed.
54
105
  */
55
- function isPrivateHost(host) {
56
- const h = host.toLowerCase();
57
- if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal")) return true;
106
+ export function isPrivateHost(host) {
107
+ const raw = String(host ?? "").trim().toLowerCase();
108
+ const bracketed = raw.startsWith("[") || raw.endsWith("]");
109
+ let h = unwrapHost(raw);
110
+ if (!h || h.includes("%") || h.includes("[") || h.includes("]")) return true;
111
+ if (bracketed && isIP(h) !== 6) return true;
112
+ h = h.replace(/\.+$/, "");
113
+ if (!h || h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal")) {
114
+ return true;
115
+ }
116
+ if (isIP(h) === 0) {
117
+ try {
118
+ const canonical = unwrapHost(new URL(`http://${h}`).hostname);
119
+ if (isIP(canonical) !== 0) h = canonical;
120
+ } catch (_e) { /* not an alternate IP literal */ }
121
+ }
58
122
  if (isIP(h) === 4) {
59
- const [a, b] = h.split(".").map(Number);
60
- if (a === 10 || a === 127 || a === 0) return true;
61
- if (a === 172 && b >= 16 && b <= 31) return true;
62
- if (a === 192 && b === 168) return true;
63
- if (a === 169 && b === 254) return true; // link-local / cloud metadata
64
- if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
65
- return false;
123
+ const [a, b, c, d] = h.split(".").map(Number);
124
+ return isPrivateIpv4Octets(a, b, c, d);
66
125
  }
67
126
  if (isIP(h) === 6) {
68
- return h === "::1" || h === "::" || h.startsWith("fc") || h.startsWith("fd") || h.startsWith("fe80");
127
+ const w = parseIpv6Words(h);
128
+ if (!w) return true;
129
+ const [w0, w1, w2, w3, w4, w5, w6, w7] = w;
130
+ // :: (unspecified) and ::1 (loopback)
131
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0 && w6 === 0 && (w7 === 0 || w7 === 1)) {
132
+ return true;
133
+ }
134
+ // fc00::/7 (unique local), fe80::/10 (link-local), ff00::/8 (multicast), 2001:db8::/32 (documentation)
135
+ if ((w0 & 0xfe00) === 0xfc00) return true;
136
+ if ((w0 & 0xffc0) === 0xfe80) return true;
137
+ if ((w0 & 0xff00) === 0xff00) return true;
138
+ if (w0 === 0x2001 && w1 === 0x0db8) return true;
139
+ // ::ffff:0:0/96 (IPv4-mapped) and ::/96 (IPv4-compatible)
140
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && (w5 === 0xffff || w5 === 0)) {
141
+ return isPrivateIpv4Octets(w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff);
142
+ }
143
+ // 64:ff9b::/96 (NAT64 well-known prefix)
144
+ if (w0 === 0x0064 && w1 === 0xff9b && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0) {
145
+ return isPrivateIpv4Octets(w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff);
146
+ }
147
+ // 2002::/16 (6to4: embedded IPv4 in bits 16..47 = w1, w2)
148
+ if (w0 === 0x2002) {
149
+ return isPrivateIpv4Octets(w1 >> 8, w1 & 0xff, w2 >> 8, w2 & 0xff);
150
+ }
151
+ return false;
69
152
  }
70
153
  return false;
71
154
  }
@@ -84,6 +167,200 @@ export function checkSeedUrl(raw, { allowPrivateUrls = false } = {}) {
84
167
  return { ok: true, url };
85
168
  }
86
169
 
170
+ function defaultLookup(hostname, options, callback) {
171
+ return dns.lookup(hostname, options, callback);
172
+ }
173
+
174
+ function callLookupAll(lookupFn, host, signal) {
175
+ if (signal?.aborted) {
176
+ return Promise.reject(signal.reason ?? new Error("DNS lookup timed out"));
177
+ }
178
+ let settled = false;
179
+ return new Promise((resolve, reject) => {
180
+ let onAbort;
181
+ const cleanup = () => {
182
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
183
+ };
184
+ const done = (err, res) => {
185
+ if (settled) return;
186
+ settled = true;
187
+ cleanup();
188
+ if (err) reject(err);
189
+ else resolve(res);
190
+ };
191
+ if (signal) {
192
+ onAbort = () => {
193
+ done(signal.reason ?? new Error("DNS lookup timed out"));
194
+ };
195
+ signal.addEventListener("abort", onAbort, { once: true });
196
+ }
197
+ try {
198
+ const maybePromise = lookupFn(host, { all: true }, done);
199
+ if (maybePromise && typeof maybePromise.then === "function") {
200
+ maybePromise.then((res) => done(null, res), (err) => done(err));
201
+ }
202
+ } catch (e) {
203
+ done(e);
204
+ }
205
+ });
206
+ }
207
+
208
+ function makePinnedLookup(expectedHost, addresses) {
209
+ const frozen = addresses.map((a) => Object.freeze({ address: a.address, family: a.family }));
210
+ return function pinnedLookup(hostname, options, callback) {
211
+ if (typeof options === "function") {
212
+ callback = options;
213
+ options = {};
214
+ }
215
+ if (unwrapHost(hostname) !== expectedHost) {
216
+ const err = new Error(`refused lookup for unpinned host ${hostname} (expected ${expectedHost})`);
217
+ err.code = "ENOTFOUND";
218
+ return callback(err);
219
+ }
220
+ const wantFamily = typeof options === "number"
221
+ ? options
222
+ : (options?.family === 4 || options?.family === 6 ? options.family : 0);
223
+ const matches = wantFamily ? frozen.filter((a) => a.family === wantFamily) : frozen;
224
+ if (matches.length === 0) {
225
+ const err = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
226
+ err.code = "ENOTFOUND";
227
+ return callback(err);
228
+ }
229
+ if (options && typeof options === "object" && options.all) {
230
+ return callback(null, matches.map((a) => ({ address: a.address, family: a.family })));
231
+ }
232
+ return callback(null, matches[0].address, matches[0].family);
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Normalise a candidate seed URL, resolve its hostname with `{ all: true }`,
238
+ * refuse if any returned address is non-global, and return a `lookup` callback
239
+ * pinned to the validated addresses so a DNS rebind between check and connect
240
+ * cannot re-point the socket.
241
+ */
242
+ export async function resolveSeedUrl(
243
+ raw,
244
+ { allowPrivateUrls = false, lookup = defaultLookup, signal, timeoutMs = PROBE_TIMEOUT_MS } = {},
245
+ ) {
246
+ const checked = checkSeedUrl(raw, { allowPrivateUrls });
247
+ if (!checked.ok) return checked;
248
+ if (allowPrivateUrls) return { ok: true, url: checked.url, addresses: [], lookup: undefined };
249
+
250
+ const u = new URL(checked.url);
251
+ const host = unwrapHost(u.hostname);
252
+ const literalFamily = isIP(host);
253
+ if (literalFamily !== 0) {
254
+ const addresses = [{ address: host, family: literalFamily }];
255
+ return { ok: true, url: checked.url, addresses, lookup: makePinnedLookup(host, addresses) };
256
+ }
257
+
258
+ const lookupSignal = signal ?? (Number.isFinite(timeoutMs) && timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined);
259
+ let rawAddrs;
260
+ try {
261
+ rawAddrs = await callLookupAll(lookup, host, lookupSignal);
262
+ } catch (e) {
263
+ return { ok: false, reason: `seed-unreachable: ${e?.message ?? e}` };
264
+ }
265
+ if (lookupSignal?.aborted) {
266
+ const err = lookupSignal.reason;
267
+ return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "DNS lookup timed out"}` };
268
+ }
269
+ const list = Array.isArray(rawAddrs) ? rawAddrs : (rawAddrs ? [rawAddrs] : []);
270
+ if (list.length === 0) {
271
+ return { ok: false, reason: "seed-unreachable: no addresses returned" };
272
+ }
273
+ const addresses = [];
274
+ for (const entry of list) {
275
+ const address = unwrapHost(typeof entry === "string" ? entry : entry?.address);
276
+ const family = isIP(address);
277
+ if (!family || isPrivateHost(address)) {
278
+ return { ok: false, reason: "private-address" };
279
+ }
280
+ addresses.push({ address, family });
281
+ }
282
+ return { ok: true, url: checked.url, addresses, lookup: makePinnedLookup(host, addresses) };
283
+ }
284
+
285
+ function raceSignal(promise, signal) {
286
+ if (!signal) return promise;
287
+ if (signal.aborted) return Promise.reject(signal.reason ?? new Error("probe timed out"));
288
+ return new Promise((resolve, reject) => {
289
+ const onAbort = () => reject(signal.reason ?? new Error("probe timed out"));
290
+ signal.addEventListener("abort", onAbort, { once: true });
291
+ Promise.resolve(promise).then(
292
+ (val) => {
293
+ signal.removeEventListener("abort", onAbort);
294
+ resolve(val);
295
+ },
296
+ (err) => {
297
+ signal.removeEventListener("abort", onAbort);
298
+ reject(err);
299
+ },
300
+ );
301
+ });
302
+ }
303
+
304
+ function defaultFetch(input, init = {}) {
305
+ const u = new URL(String(input));
306
+ const reqFn = u.protocol === "https:" ? httpsRequest : httpRequest;
307
+ const headers = { ...(init.headers ?? {}) };
308
+ const body = init.body !== undefined && init.body !== null ? Buffer.from(init.body) : null;
309
+ if (body && !Object.keys(headers).some((k) => k.toLowerCase() === "content-length")) {
310
+ headers["content-length"] = String(body.byteLength);
311
+ }
312
+ return new Promise((resolve, reject) => {
313
+ let settled = false;
314
+ const fail = (err) => {
315
+ if (settled) return;
316
+ settled = true;
317
+ reject(err);
318
+ };
319
+ const req = reqFn(
320
+ u,
321
+ {
322
+ method: init.method ?? "GET",
323
+ headers,
324
+ signal: init.signal,
325
+ lookup: init.lookup,
326
+ agent: false,
327
+ },
328
+ (res) => {
329
+ const chunks = [];
330
+ let bytes = 0;
331
+ res.on("data", (c) => {
332
+ bytes += c.length;
333
+ if (bytes > MAX_RESPONSE_BYTES) {
334
+ req.destroy(new Error("seed response too large"));
335
+ return;
336
+ }
337
+ chunks.push(c);
338
+ });
339
+ res.on("end", () => {
340
+ if (settled) return;
341
+ settled = true;
342
+ const buf = Buffer.concat(chunks);
343
+ const status = res.statusCode ?? 0;
344
+ resolve({
345
+ ok: status >= 200 && status < 300,
346
+ status,
347
+ headers: res.headers,
348
+ text: async () => buf.toString("utf-8"),
349
+ json: async () => JSON.parse(buf.toString("utf-8")),
350
+ });
351
+ });
352
+ res.on("error", fail);
353
+ },
354
+ );
355
+ req.on("error", fail);
356
+ req.on("close", () => {
357
+ if (!settled) fail(init.signal?.reason ?? new Error("request closed prematurely"));
358
+ });
359
+ if (body) req.write(body);
360
+ req.end();
361
+ });
362
+ }
363
+
87
364
  /** Verify a /v1/seed-info document: signature, key/uuaid binding, URL match. */
88
365
  export function verifySeedInfo(doc, expectedUrl) {
89
366
  if (doc?.v !== 1) return { ok: false, reason: "bad-version" };
@@ -116,15 +393,28 @@ export class SeedRegistry {
116
393
  * dbPath SQLite path
117
394
  * protocol directory.protocol string
118
395
  * fetchImpl injectable fetch (tests)
396
+ * lookup injectable dns.lookup (tests)
119
397
  * allowPrivateUrls permit loopback seeds (tests / local networks)
120
398
  */
121
- constructor({ keychain, carrierUrl, dbPath = "seed-registry.db", protocol = "uacp/1.0-draft", fetchImpl = globalThis.fetch, allowPrivateUrls = false } = {}) {
399
+ constructor({
400
+ keychain,
401
+ carrierUrl,
402
+ dbPath = "seed-registry.db",
403
+ protocol = "uacp/1.0-draft",
404
+ fetchImpl = defaultFetch,
405
+ lookup = defaultLookup,
406
+ lookupImpl,
407
+ allowPrivateUrls = false,
408
+ probeTimeoutMs = PROBE_TIMEOUT_MS,
409
+ } = {}) {
122
410
  if (!keychain?._identity) throw new Error("SeedRegistry needs a loaded keychain");
123
411
  this.keychain = keychain;
124
412
  this.carrierUrl = carrierUrl ? String(carrierUrl).replace(/\/+$/, "") : null;
125
413
  this.protocol = protocol;
126
414
  this.fetch = fetchImpl;
415
+ this.lookup = lookupImpl ?? lookup;
127
416
  this.allowPrivateUrls = allowPrivateUrls;
417
+ this.probeTimeoutMs = probeTimeoutMs;
128
418
  this.db = new Database(dbPath);
129
419
  this.db.pragma("journal_mode = WAL");
130
420
  this.db.exec(`
@@ -187,34 +477,50 @@ export class SeedRegistry {
187
477
  * have to care whether it enrolled before.
188
478
  */
189
479
  async enroll({ url, operator = null, region = null, now = Date.now() }) {
190
- const checked = checkSeedUrl(url, { allowPrivateUrls: this.allowPrivateUrls });
191
- if (!checked.ok) return { ok: false, reason: checked.reason };
480
+ const signal = AbortSignal.timeout(this.probeTimeoutMs);
481
+ const resolved = await resolveSeedUrl(url, {
482
+ allowPrivateUrls: this.allowPrivateUrls,
483
+ lookup: this.lookup,
484
+ signal,
485
+ });
486
+ if (!resolved.ok) return { ok: false, reason: resolved.reason };
487
+ if (signal.aborted) {
488
+ const err = signal.reason;
489
+ return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "probe timed out"}` };
490
+ }
192
491
 
193
492
  let doc;
194
493
  try {
195
- const res = await this.fetch(`${checked.url}/v1/seed-info`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
494
+ const res = await raceSignal(
495
+ this.fetch(`${resolved.url}/v1/seed-info`, {
496
+ signal,
497
+ redirect: "manual",
498
+ ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
499
+ }),
500
+ signal,
501
+ );
196
502
  if (!res.ok) return { ok: false, reason: `seed-info-${res.status}` };
197
- doc = await res.json();
503
+ doc = await raceSignal(res.json(), signal);
198
504
  } catch (e) {
199
- return { ok: false, reason: `seed-unreachable: ${e.message}` };
505
+ return { ok: false, reason: `seed-unreachable: ${e?.message ?? e}` };
200
506
  }
201
- const v = verifySeedInfo(doc, checked.url);
507
+ const v = verifySeedInfo(doc, resolved.url);
202
508
  if (!v.ok) return { ok: false, reason: `seed-info-invalid:${v.reason}` };
203
509
 
204
510
  const existing = this.get(doc.uuaid);
205
511
  if (existing) {
206
- if (existing.url !== checked.url) return { ok: false, reason: "uuaid-already-enrolled-at-other-url" };
512
+ if (existing.url !== resolved.url) return { ok: false, reason: "uuaid-already-enrolled-at-other-url" };
207
513
  return { ok: true, already: true, ...this.status(doc.uuaid) };
208
514
  }
209
515
  // A URL can only ever belong to one identity: otherwise a second key
210
516
  // could enroll the same host and inherit its observed history.
211
- const urlTaken = this.db.prepare("select uuaid from seeds where url = ?").get(checked.url);
517
+ const urlTaken = this.db.prepare("select uuaid from seeds where url = ?").get(resolved.url);
212
518
  if (urlTaken) return { ok: false, reason: "url-already-enrolled" };
213
519
 
214
520
  this.db.prepare(`
215
521
  insert into seeds (uuaid, url, public_key, operator, region, enrolled_at, tier, claimed)
216
522
  values (?,?,?,?,?,?,'probation',?)
217
- `).run(doc.uuaid, checked.url, doc.publicKey.toLowerCase(), operator, region,
523
+ `).run(doc.uuaid, resolved.url, doc.publicKey.toLowerCase(), operator, region,
218
524
  new Date(now).toISOString(), JSON.stringify(doc.stats ?? {}));
219
525
  return { ok: true, already: false, ...this.status(doc.uuaid) };
220
526
  }
@@ -263,9 +569,23 @@ export class SeedRegistry {
263
569
  /** GET <url>/v1/health — the liveness half of an observation. */
264
570
  async healthProbe(row) {
265
571
  try {
266
- const res = await this.fetch(`${row.url}/v1/health`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
572
+ const signal = AbortSignal.timeout(this.probeTimeoutMs);
573
+ const resolved = await resolveSeedUrl(row.url, {
574
+ allowPrivateUrls: this.allowPrivateUrls,
575
+ lookup: this.lookup,
576
+ signal,
577
+ });
578
+ if (!resolved.ok || signal.aborted) return false;
579
+ const res = await raceSignal(
580
+ this.fetch(`${resolved.url}/v1/health`, {
581
+ signal,
582
+ redirect: "manual",
583
+ ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
584
+ }),
585
+ signal,
586
+ );
267
587
  if (!res.ok) return false;
268
- const body = await res.json();
588
+ const body = await raceSignal(res.json(), signal);
269
589
  return body?.ok === true;
270
590
  } catch (_e) { return false; }
271
591
  }
@@ -279,6 +599,19 @@ export class SeedRegistry {
279
599
  * answers /v1/health and drops mail.
280
600
  */
281
601
  async roundTripProbe(row, { now = Date.now() } = {}) {
602
+ const postSignal = AbortSignal.timeout(this.probeTimeoutMs);
603
+ const resolved = await resolveSeedUrl(row.url, {
604
+ allowPrivateUrls: this.allowPrivateUrls,
605
+ lookup: this.lookup,
606
+ signal: postSignal,
607
+ });
608
+ if (!resolved.ok) return { ok: false, reason: resolved.reason };
609
+ if (postSignal.aborted) {
610
+ const err = postSignal.reason;
611
+ return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "probe timed out"}` };
612
+ }
613
+ const lookupOpt = resolved.lookup ? { lookup: resolved.lookup } : {};
614
+
282
615
  const me = this.keychain._identity;
283
616
  let envelope;
284
617
  try {
@@ -291,14 +624,19 @@ export class SeedRegistry {
291
624
  } catch (e) { return { ok: false, reason: `seal-failed: ${e.message}` }; }
292
625
 
293
626
  try {
294
- const post = await this.fetch(`${row.url}/v1/envelopes`, {
295
- method: "POST",
296
- headers: { "content-type": "application/json" },
297
- body: JSON.stringify(envelope),
298
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
299
- });
627
+ const post = await raceSignal(
628
+ this.fetch(`${resolved.url}/v1/envelopes`, {
629
+ method: "POST",
630
+ headers: { "content-type": "application/json" },
631
+ body: JSON.stringify(envelope),
632
+ signal: postSignal,
633
+ redirect: "manual",
634
+ ...lookupOpt,
635
+ }),
636
+ postSignal,
637
+ );
300
638
  if (post.status !== 202) return { ok: false, reason: `deliver-${post.status}` };
301
- const receipt = await post.json();
639
+ const receipt = await raceSignal(post.json(), postSignal);
302
640
  if (!receipt?.accepted) return { ok: false, reason: "deliver-not-accepted" };
303
641
 
304
642
  // Poll from just below the receipt seq so the probe envelope is in
@@ -307,19 +645,25 @@ export class SeedRegistry {
307
645
  const path = `GET /v1/inbox/${me.uuaid}?since=${since}`;
308
646
  const ts = String(Date.now());
309
647
  const sig = this.keychain.sign(Buffer.from(`${path}\n${ts}`, "utf-8")).toString("hex");
310
- const res = await this.fetch(
311
- `${row.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}`,
312
- {
313
- headers: { "x-pillar-pubkey": me.publicKeyHex, "x-pillar-ts": ts, "x-pillar-sig": sig },
314
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS + ROUND_TRIP_WAIT_S * 1000),
315
- },
648
+ const getSignal = AbortSignal.timeout(this.probeTimeoutMs + ROUND_TRIP_WAIT_S * 1000);
649
+ const res = await raceSignal(
650
+ this.fetch(
651
+ `${resolved.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}`,
652
+ {
653
+ headers: { "x-pillar-pubkey": me.publicKeyHex, "x-pillar-ts": ts, "x-pillar-sig": sig },
654
+ signal: getSignal,
655
+ redirect: "manual",
656
+ ...lookupOpt,
657
+ },
658
+ ),
659
+ getSignal,
316
660
  );
317
661
  if (res.status !== 200) return { ok: false, reason: `inbox-${res.status}` };
318
- const body = await res.json();
662
+ const body = await raceSignal(res.json(), getSignal);
319
663
  const found = (body?.envelopes ?? []).some(e => e?.envelope?.id === envelope.id);
320
664
  return found ? { ok: true } : { ok: false, reason: "envelope-not-returned" };
321
665
  } catch (e) {
322
- return { ok: false, reason: `probe-threw: ${e.message}` };
666
+ return { ok: false, reason: `probe-threw: ${e?.message ?? e}` };
323
667
  }
324
668
  }
325
669
 
@@ -2,8 +2,9 @@
2
2
  * Transport — libp2p node that speaks the UUAID pillar protocol.
3
3
  *
4
4
  * Design:
5
- * - The pillar's Ed25519 identity IS the libp2p PeerId (same private key).
6
- * One identity, one keypair, one signature primitive across every layer.
5
+ * - The transport PeerId uses a secp256k1 key read from the pillar's
6
+ * 32-byte seed. It differs from the Ed25519 identity used to sign
7
+ * envelopes; peerIdFromSeedHex derives the transport PeerId.
7
8
  * - Kad-DHT is used for two things:
8
9
  * 1. Peer routing (find PeerId -> multiaddrs)
9
10
  * 2. Content routing (publish a UUAID -> hash mapping so anyone can
@@ -38,7 +39,7 @@ export const PILLAR_PROTOCOL = "/uuaid/pillar/1.0.0";
38
39
  export const DHT_PROTOCOL_PREFIX = "/uuaid";
39
40
 
40
41
  /**
41
- * Build a libp2p node bound to the pillar's Ed25519 identity.
42
+ * Build a libp2p node with the seed-derived secp256k1 transport identity.
42
43
  *
43
44
  * @param {{seedHex: string, listenAddrs?: string[], bootstrapPeers?: string[], enableRelay?: boolean, dhtClientMode?: boolean}} opts
44
45
  */
@@ -111,8 +112,10 @@ export function peerIdFromSeedHex(seedHex) {
111
112
  }
112
113
 
113
114
  /**
114
- * Convert a raw Ed25519 public key hex to a libp2p PeerId. This is how
115
- * a peer given only a UUAID's public key can dial that peer.
115
+ * Convert a raw Ed25519 public key hex to its Ed25519 libp2p PeerId.
116
+ * This conversion does not identify the node started by createTransport,
117
+ * which uses a seed-derived secp256k1 key. Use peerIdFromSeedHex for that
118
+ * node; a UUAID's Ed25519 public key alone cannot derive its transport PeerId.
116
119
  */
117
120
  export function peerIdFromEd25519Hex(publicKeyHex) {
118
121
  const raw = Buffer.from(publicKeyHex, "hex");