@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.
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Seed over egress (2.8.0): the shared, pure parts of the tunnel protocol.
3
+ *
4
+ * A seed with outbound-only network opens one WebSocket to a relay carrier
5
+ * (`pillar-carrier --accept-tunnels`). The relay serves the seed at
6
+ * `<relay origin>/e/<localId>/v1/...` and forwards each request over that
7
+ * tunnel. Nothing here opens a socket: tunnel-relay.mjs and tunnel-client.mjs
8
+ * do. This module holds what both sides, and the seed registry, must agree on:
9
+ *
10
+ * - canonical relay origins and the relayed URL shape;
11
+ * - tunnel authentication (pillar-tunnel-auth/1): the seed signs the relay
12
+ * origin, the relay's one-use connection nonce, its full uuaid and key;
13
+ * - the relay attestation (pillar-relay-attest/1): a fleet relay signs that
14
+ * a seed-info answer came through the exact active tunnel of a seed on its
15
+ * current allow-file, for the registry's one-use challenge;
16
+ * - the served proof (pillar-seed-served/1): the seed signs the exact inbox
17
+ * page it returned, bound to the registry's one-use challenge;
18
+ * - the binary stream frames and the route and header allow-lists.
19
+ *
20
+ * Design: DESIGN-egress-seed.md Rev 6 (RedTeam c3ff4d, 085b71).
21
+ */
22
+ import { createHash, randomBytes } from "node:crypto";
23
+ import { isIP } from "node:net";
24
+ import { jcs, jcsRfc8785 } from "../identity/jcs.mjs";
25
+ import { Keychain, keyDerivesUuaid, localIdFromKey } from "../identity/keychain.mjs";
26
+
27
+ /** Tunnel auth, attestation and challenge clock tolerance. */
28
+ export const TUNNEL_SKEW_MS = 60_000;
29
+ /** A challenge or nonce: 32 random bytes as lowercase hex. */
30
+ export const CHALLENGE_RE = /^[0-9a-f]{64}$/;
31
+ const LOCAL_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
32
+ const HEX64 = /^[0-9a-f]{64}$/i;
33
+ const SIG_RE = /^[0-9a-f]{128}$/i;
34
+
35
+ /** Frame kinds (byte 0 of every binary tunnel message; bytes 1-4 = stream id). */
36
+ export const FRAME = Object.freeze({ REQ: 0x01, REQ_DATA: 0x02, REQ_END: 0x03, RES: 0x11, RES_DATA: 0x12, RES_END: 0x13, RESET: 0x20 });
37
+ /** Raw bytes per data frame; the WebSocket payload cap leaves room for the 5-byte header. */
38
+ export const FRAME_DATA_BYTES = 48 * 1024;
39
+ export const MAX_FRAME_PAYLOAD = 64 * 1024 + 5;
40
+
41
+ function isLoopbackHost(hostname) {
42
+ const h = String(hostname ?? "").replace(/^\[|\]$/g, "").toLowerCase();
43
+ if (h === "::1") return true;
44
+ return isIP(h) === 4 && h.startsWith("127.");
45
+ }
46
+
47
+ /**
48
+ * The canonical form of a relay origin: `new URL(x).origin` (lowercase host,
49
+ * punycode, default port dropped). Refused: a path other than "/", a query,
50
+ * a fragment, credentials, and any scheme but https (http only for a loopback
51
+ * host, which is how tests run).
52
+ */
53
+ export function canonicalOrigin(raw) {
54
+ let u;
55
+ try { u = new URL(String(raw)); } catch (_e) { return { ok: false, reason: "bad-origin" }; }
56
+ if (u.username || u.password) return { ok: false, reason: "credentials-in-origin" };
57
+ if (u.search || u.hash || String(raw).includes("?") || String(raw).includes("#")) return { ok: false, reason: "query-in-origin" };
58
+ if (u.pathname !== "/" && u.pathname !== "") return { ok: false, reason: "path-in-origin" };
59
+ const loopback = isLoopbackHost(u.hostname);
60
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && loopback)) return { ok: false, reason: "https-required" };
61
+ return { ok: true, origin: u.origin, loopback };
62
+ }
63
+
64
+ /** True for an origin whose host is 127.0.0.0/8 or ::1. */
65
+ export function isLoopbackOrigin(origin) {
66
+ try { return isLoopbackHost(new URL(origin).hostname); } catch (_e) { return false; }
67
+ }
68
+
69
+ /** `/e/<localId>` for a seed key (hex). */
70
+ export function relayPathFor(publicKeyHex) {
71
+ return `/e/${localIdFromKey(Buffer.from(publicKeyHex, "hex"))}`;
72
+ }
73
+
74
+ /** The relayed URL a seed key is served at on `origin`. */
75
+ export function relayedUrlFor(origin, publicKeyHex) {
76
+ return `${origin}${relayPathFor(publicKeyHex)}`;
77
+ }
78
+
79
+ /**
80
+ * The relay origin a URL claims by its shape: `<origin>/e/<localId of key>`,
81
+ * else null. A seed URL of that shape must declare its relay (registry).
82
+ */
83
+ export function relayShapeOrigin(url, publicKeyHex) {
84
+ let u;
85
+ try { u = new URL(String(url)); } catch (_e) { return null; }
86
+ if (typeof publicKeyHex !== "string" || !HEX64.test(publicKeyHex)) return null;
87
+ return u.pathname === relayPathFor(publicKeyHex.toLowerCase()) ? u.origin : null;
88
+ }
89
+
90
+ /**
91
+ * True when `url` has the relayed seed shape `<origin>/e/<localId>`, for any
92
+ * key: the URL a tunnel relay serves a seed at. Such a URL is never taken
93
+ * from a directory automatically in 2.8.0 (RedTeam 22f6c3 Q2).
94
+ */
95
+ export function isRelayedSeedUrl(url) {
96
+ let u;
97
+ try { u = new URL(String(url)); } catch (_e) { return false; }
98
+ const p = parseRelayPath(u.pathname.replace(/\/+$/, ""));
99
+ return p !== null && p.rest === "/";
100
+ }
101
+
102
+ /** Split `/e/<localId>/rest` into { localId, rest }, else null. */
103
+ export function parseRelayPath(pathname) {
104
+ const m = /^\/e\/([^/]+)(\/.*)?$/.exec(pathname);
105
+ if (!m || !LOCAL_ID_RE.test(m[1])) return null;
106
+ return { localId: m[1], rest: m[2] ?? "/" };
107
+ }
108
+
109
+ /**
110
+ * The only requests a tunnel carries, as a route template for logs (no uuaid,
111
+ * no query), else null. Checked by the relay and again by the seed.
112
+ */
113
+ export function allowedRoute(method, path) {
114
+ const pathname = String(path).split("?")[0];
115
+ if (method === "POST" && pathname === "/v1/envelopes") return "/v1/envelopes";
116
+ if (method === "GET" && /^\/v1\/inbox\/[^/]+$/.test(pathname)) return "/v1/inbox/:uuaid";
117
+ if (method === "GET" && pathname === "/v1/seed-info") return "/v1/seed-info";
118
+ if (method === "GET" && pathname === "/v1/health") return "/v1/health";
119
+ return null;
120
+ }
121
+
122
+ /** Request headers a tunnel forwards; every other header is dropped. */
123
+ export const FORWARDED_REQUEST_HEADERS = Object.freeze([
124
+ "content-type", "content-length",
125
+ "x-pillar-pubkey", "x-pillar-ts", "x-pillar-sig", "x-pillar-delegation", "x-pillar-tier-grant",
126
+ "x-pillar-auth", "x-pillar-nonce", // inbox auth v2 (2.8.1)
127
+ ]);
128
+
129
+ /** The allow-listed request headers of `headers` (a Node header object). */
130
+ export function pickRequestHeaders(headers) {
131
+ const out = {};
132
+ for (const name of FORWARDED_REQUEST_HEADERS) {
133
+ const v = headers?.[name];
134
+ if (typeof v === "string") out[name] = v;
135
+ }
136
+ return out;
137
+ }
138
+
139
+ // ---------------------------------------------------------------- frames
140
+
141
+ export function encodeFrame(kind, streamId, payload = Buffer.alloc(0)) {
142
+ const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
143
+ const head = Buffer.alloc(5);
144
+ head[0] = kind;
145
+ head.writeUInt32BE(streamId >>> 0, 1);
146
+ return Buffer.concat([head, body]);
147
+ }
148
+
149
+ export function decodeFrame(buf) {
150
+ if (!Buffer.isBuffer(buf) || buf.length < 5) return null;
151
+ return { kind: buf[0], id: buf.readUInt32BE(1), payload: buf.subarray(5) };
152
+ }
153
+
154
+ export function encodeJsonFrame(kind, streamId, obj) {
155
+ return encodeFrame(kind, streamId, Buffer.from(JSON.stringify(obj), "utf-8"));
156
+ }
157
+
158
+ // ---------------------------------------------------------------- tunnel auth
159
+
160
+ /**
161
+ * Every reason a relay sends a seed in a `{t:"error"}` message. A seed logs
162
+ * and reports only these; any other text from the peer reads as "refused"
163
+ * (RedTeam 995f4c P3: peer-supplied text never reaches a log line).
164
+ */
165
+ export const RELAY_REASONS = Object.freeze(new Set([
166
+ "auth-timeout", "bad-auth", "bad-public-key", "bad-sig-encoding", "bad-signature", "clock-skew",
167
+ "nonce-used", "not-allowed", "relay-full", "replaced", "revoked", "unexpected-message",
168
+ "uuaid-key-mismatch", "seed-already-connected", "flow-violation",
169
+ ]));
170
+
171
+ /** A process instance id: 16 random bytes as lowercase hex. */
172
+ export const INSTANCE_RE = /^[0-9a-f]{32}$/;
173
+
174
+ /** A fresh instance id for one seed process (one TunnelClient). */
175
+ export function newInstanceId() {
176
+ return randomBytes(16).toString("hex");
177
+ }
178
+
179
+ function authBody({ origin, nonce, uuaid, publicKey, ts, instance }) {
180
+ return { t: "pillar-tunnel-auth/1", origin, nonce, uuaid, publicKey, ts, instance };
181
+ }
182
+
183
+ /**
184
+ * The seed's `auth` message for a relay's `hello`. `instance` names the seed
185
+ * process (one per TunnelClient), so a relay can tell a reconnect of the
186
+ * same process from a second process holding the same key (V1 2b5070).
187
+ * Omitted, it is a fresh one: a connection from a process the relay has not
188
+ * seen.
189
+ */
190
+ export function signTunnelAuth(keychain, { origin, nonce, ts = Date.now(), instance = newInstanceId() }) {
191
+ const id = keychain._identity;
192
+ const body = authBody({ origin, nonce, uuaid: id.uuaid, publicKey: id.publicKeyHex, ts, instance });
193
+ return { t: "auth", v: 1, uuaid: id.uuaid, publicKey: id.publicKeyHex, ts, instance, sig: keychain.sign(Buffer.from(jcs(body), "utf-8")).toString("hex") };
194
+ }
195
+
196
+ /**
197
+ * Check a seed's `auth` against this relay's origin and the connection's
198
+ * one-use nonce. Returns { ok, uuaid, publicKey, localId } or { ok:false, reason }.
199
+ */
200
+ export function verifyTunnelAuth(msg, { origin, nonce, now = Date.now() }) {
201
+ if (msg?.t !== "auth" || msg.v !== 1) return { ok: false, reason: "bad-auth" };
202
+ if (typeof nonce !== "string" || !CHALLENGE_RE.test(nonce)) return { ok: false, reason: "nonce-used" };
203
+ if (typeof msg.publicKey !== "string" || !HEX64.test(msg.publicKey)) return { ok: false, reason: "bad-public-key" };
204
+ if (typeof msg.sig !== "string" || !SIG_RE.test(msg.sig)) return { ok: false, reason: "bad-sig-encoding" };
205
+ if (typeof msg.instance !== "string" || !INSTANCE_RE.test(msg.instance)) return { ok: false, reason: "bad-auth" };
206
+ if (!Number.isSafeInteger(msg.ts) || Math.abs(now - msg.ts) > TUNNEL_SKEW_MS) return { ok: false, reason: "clock-skew" }; // @rule tunnel.auth-skew
207
+ const publicKey = msg.publicKey.toLowerCase();
208
+ if (!keyDerivesUuaid(publicKey, msg.uuaid)) return { ok: false, reason: "uuaid-key-mismatch" }; // @rule tunnel.auth-uuaid-from-key
209
+ const body = authBody({ origin, nonce, uuaid: msg.uuaid, publicKey: msg.publicKey, ts: msg.ts, instance: msg.instance });
210
+ let good = false;
211
+ try { good = Keychain.verifyDetached(publicKey, Buffer.from(jcs(body), "utf-8"), Buffer.from(msg.sig, "hex")); } catch (_e) { good = false; }
212
+ if (!good) return { ok: false, reason: "bad-signature" }; // @rule tunnel.auth-signature
213
+ return { ok: true, uuaid: msg.uuaid, publicKey, instance: msg.instance, localId: localIdFromKey(Buffer.from(publicKey, "hex")) };
214
+ }
215
+
216
+ // ---------------------------------------------------------------- relay attestation
217
+
218
+ const ATTEST_FIELDS = ["origin", "path", "uuaid", "publicKey", "challenge", "tunnelId", "tunnelSince", "admission", "allowSha256", "at"];
219
+
220
+ /** A fleet relay's signed statement about one seed-info answer (header value: base64 JSON). */
221
+ export function makeRelayAttest(keychain, fields) {
222
+ const body = { t: "pillar-relay-attest/1" };
223
+ for (const k of ATTEST_FIELDS) body[k] = fields[k];
224
+ const sig = keychain.sign(Buffer.from(jcs(body), "utf-8")).toString("hex");
225
+ return { ...body, relayKey: keychain._identity.publicKeyHex, sig };
226
+ }
227
+
228
+ export function encodeAttestHeader(att) {
229
+ return Buffer.from(JSON.stringify(att), "utf-8").toString("base64");
230
+ }
231
+
232
+ export function decodeAttestHeader(value) {
233
+ if (typeof value !== "string" || value.length > 8192) return null;
234
+ try { return JSON.parse(Buffer.from(value, "base64").toString("utf-8")); } catch (_e) { return null; }
235
+ }
236
+
237
+ /**
238
+ * Verify an attestation against what the registry expects: the configured
239
+ * key for this origin, the seed's pinned identity, the seed-info path, the
240
+ * challenge it just sent, allow-file or open admission (2.8.1) and a fresh `at`.
241
+ */
242
+ export function verifyRelayAttest(att, { relayKey, origin, path, uuaid, publicKey, challenge, now = Date.now() }) {
243
+ if (!att || att.t !== "pillar-relay-attest/1") return { ok: false, reason: "attest-missing" };
244
+ if (typeof relayKey !== "string" || att.relayKey?.toLowerCase?.() !== relayKey.toLowerCase()) return { ok: false, reason: "attest-key" };
245
+ if (att.origin !== origin) return { ok: false, reason: "attest-origin" }; // @rule reg.attest-origin
246
+ if (att.path !== path) return { ok: false, reason: "attest-path" };
247
+ if (att.uuaid !== uuaid || String(att.publicKey).toLowerCase() !== String(publicKey).toLowerCase()) return { ok: false, reason: "attest-identity" }; // @rule reg.attest-identity
248
+ if (att.challenge !== challenge) return { ok: false, reason: "attest-challenge" }; // @rule reg.attest-challenge
249
+ // 2.8.1 (V1 via Lead 3f4436): an open relay attests too. "open" says only
250
+ // that the answer came through this relay's live tunnel for this seed key;
251
+ // the registry still trusts it only from a relay key it pins (--fleet-relays).
252
+ if (att.admission !== "allow-file" && att.admission !== "open") return { ok: false, reason: "attest-admission" }; // @rule reg.attest-admission
253
+ if (typeof att.tunnelId !== "string" || !/^[0-9a-f]{32}$/.test(att.tunnelId)) return { ok: false, reason: "attest-tunnel" };
254
+ if (!Number.isSafeInteger(att.at) || Math.abs(now - att.at) > TUNNEL_SKEW_MS) return { ok: false, reason: "attest-stale" }; // @rule reg.attest-fresh
255
+ if (typeof att.sig !== "string" || !SIG_RE.test(att.sig)) return { ok: false, reason: "attest-sig" };
256
+ const body = { t: att.t };
257
+ for (const k of ATTEST_FIELDS) body[k] = att[k];
258
+ let good = false;
259
+ try { good = Keychain.verifyDetached(relayKey.toLowerCase(), Buffer.from(jcs(body), "utf-8"), Buffer.from(att.sig, "hex")); } catch (_e) { good = false; }
260
+ if (!good) return { ok: false, reason: "attest-sig" }; // @rule reg.attest-signature
261
+ return { ok: true };
262
+ }
263
+
264
+ // ---------------------------------------------------------------- served proof
265
+
266
+ /** sha256 over the exact `envelopes` array an inbox page returned (RFC 8785 JCS). */
267
+ export function servedDigest(envelopes) {
268
+ return createHash("sha256").update(jcsRfc8785(envelopes ?? []), "utf-8").digest("hex");
269
+ }
270
+
271
+ function servedBody({ seed, inbox, since, challenge, digest }) {
272
+ return { t: "pillar-seed-served/1", seed, inbox, since, challenge, digest };
273
+ }
274
+
275
+ /** Built by the seed's carrier inside its authenticated inbox read. */
276
+ export function makeServedProof(keychain, { inbox, since, challenge, envelopes }) {
277
+ const body = servedBody({ seed: keychain._identity.uuaid, inbox, since, challenge, digest: servedDigest(envelopes) });
278
+ return { ...body, sig: keychain.sign(Buffer.from(jcs(body), "utf-8")).toString("hex") };
279
+ }
280
+
281
+ /** Check a served proof against the page the registry received. */
282
+ export function verifyServedProof(proof, { publicKey, seed, inbox, since, challenge, envelopes }) {
283
+ if (!proof || proof.t !== "pillar-seed-served/1") return { ok: false, reason: "proof-missing" };
284
+ if (proof.seed !== seed || proof.inbox !== inbox || proof.since !== since) return { ok: false, reason: "proof-scope" };
285
+ if (proof.challenge !== challenge) return { ok: false, reason: "proof-challenge" }; // @rule reg.proof-challenge
286
+ if (proof.digest !== servedDigest(envelopes)) return { ok: false, reason: "proof-digest" }; // @rule reg.proof-digest
287
+ if (typeof proof.sig !== "string" || !SIG_RE.test(proof.sig)) return { ok: false, reason: "proof-sig" };
288
+ let good = false;
289
+ try { good = Keychain.verifyDetached(String(publicKey).toLowerCase(), Buffer.from(jcs(servedBody(proof)), "utf-8"), Buffer.from(proof.sig, "hex")); } catch (_e) { good = false; }
290
+ if (!good) return { ok: false, reason: "proof-sig" }; // @rule reg.proof-signature
291
+ return { ok: true };
292
+ }
@@ -91,7 +91,10 @@ export function ensurePrivateDir(dir, uid = currentUid()) {
91
91
  try { st = lstatSync(dir); }
92
92
  catch (e) {
93
93
  if (e.code !== "ENOENT") throw e;
94
- mkdirSync(dir, { mode: 0o700 });
94
+ // Another process may create it between our lstat and mkdir (two first
95
+ // writers on one home). Only that is tolerated: a fresh lstat follows, and
96
+ // every check below still runs on whatever is there now.
97
+ try { mkdirSync(dir, { mode: 0o700 }); } catch (e2) { if (e2.code !== "EEXIST") throw e2; }
95
98
  st = lstatSync(dir);
96
99
  }
97
100
  if (st.isSymbolicLink()) throw new NotifyCustodyError(`${dir} is a symlink; notify refuses to follow it`, dir); // @rule notify.custody-dir-symlink