@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.
- package/HOSTING-LIMITS.md +122 -0
- package/README.md +288 -1
- package/bin/carrier.mjs +104 -1
- package/bin/pillar-directory.mjs +34 -5
- package/bin/pillar-seed.mjs +129 -11
- package/bin/pillar.mjs +11 -4
- package/package.json +1 -1
- package/src/mailbox/mailbox.mjs +12 -0
- package/src/net/carrier-client.mjs +37 -9
- package/src/net/carrier-server.mjs +287 -25
- package/src/net/discovery.mjs +94 -0
- package/src/net/inbox-auth.mjs +100 -0
- package/src/net/refusals.mjs +24 -0
- package/src/net/seed-registry.mjs +374 -39
- package/src/net/seed-tier.mjs +35 -1
- package/src/net/tunnel-client.mjs +456 -0
- package/src/net/tunnel-relay.mjs +786 -0
- package/src/net/tunnel.mjs +292 -0
- package/src/notify-store.mjs +4 -1
- package/src/pillar.mjs +541 -9
- package/src/registry/directory-flags.mjs +7 -0
- package/src/registry/stats.mjs +1 -1
- package/src/vnext/continuity-cli.mjs +399 -0
- package/src/vnext/continuity.mjs +1801 -0
- package/src/vnext/init-cli.mjs +23 -7
- package/src/vnext/json-dir-mailbox.mjs +6 -0
- package/src/vnext/jsonl-mailbox.mjs +177 -23
- package/src/vnext/knock-cli.mjs +18 -0
- package/src/vnext/retired-import.mjs +556 -0
- package/src/vnext/verify-cli.mjs +1 -1
|
@@ -30,6 +30,11 @@
|
|
|
30
30
|
* x-pillar-delegation: (optional) JSON delegation document letting a
|
|
31
31
|
* delegate key read <uuaid>'s inbox; must be signed by <uuaid> and
|
|
32
32
|
* cover kind "inbox" (or "*")
|
|
33
|
+
* 2.8.1 inbox auth v2 (src/net/inbox-auth.mjs): x-pillar-auth: 2 and
|
|
34
|
+
* x-pillar-nonce; the signature covers this server's public URL as the
|
|
35
|
+
* audience and the since, wait and challenge values, and the nonce is
|
|
36
|
+
* used once (at most MAX_INBOX_AUTH_NONCES kept; full: 503
|
|
37
|
+
* inbox-auth-busy). A relayed seed takes v2 only.
|
|
33
38
|
* - carrier derives UUAID from pubkey; must equal <uuaid> (self-authenticating,
|
|
34
39
|
* zero registration) unless a valid inbox delegation is presented
|
|
35
40
|
* - long-polls up to `wait` seconds (max 30)
|
|
@@ -64,7 +69,7 @@
|
|
|
64
69
|
*/
|
|
65
70
|
import { createServer } from "node:http";
|
|
66
71
|
import { clientIpOf, DEFAULT_TRUSTED_PROXIES } from "./client-ip.mjs";
|
|
67
|
-
import { createHash } from "node:crypto";
|
|
72
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
68
73
|
import { requireBetterSqlite3 } from "../sqlite-loader.mjs";
|
|
69
74
|
import { open as openEnvelope, envelopeSha as canonicalEnvelopeSha } from "./envelope.mjs";
|
|
70
75
|
import { Keychain, keyDerivesUuaid, isStrictEd25519PublicKey } from "../identity/keychain.mjs";
|
|
@@ -74,8 +79,83 @@ import { verifyDelegationDoc, delegationCoversKind } from "./delegation.mjs";
|
|
|
74
79
|
import { withCarrierFix } from "./refusals.mjs"; // additive `fix` on refusals; reason/error/status unchanged
|
|
75
80
|
import { carrierReceiptSigningString, carrierReceiptShapeOk, carrierUuaidFromKey } from "./carrier-receipt.mjs";
|
|
76
81
|
import { rekeyToSenderUnique } from "../sqlite-rekey.mjs";
|
|
82
|
+
import { CHALLENGE_RE, makeServedProof } from "./tunnel.mjs";
|
|
83
|
+
import { NONCE_RE, canonicalInboxQuery, inboxAuthV2Bytes } from "./inbox-auth.mjs";
|
|
77
84
|
|
|
78
85
|
const MAX_WAIT_S = 30;
|
|
86
|
+
/**
|
|
87
|
+
* Inbox auth v2 nonces kept at once (2.8.1, RedTeam 57c79a item 3). A nonce is
|
|
88
|
+
* kept until its request's time window ends: at most ts + 5 min + 1 s, so up to
|
|
89
|
+
* about 10 minutes for a ts 5 minutes ahead. One client address at a relay's
|
|
90
|
+
* 600 reads a minute fills 6,000 rows in that time; 100,000 rows hold about 16
|
|
91
|
+
* such addresses, about 10 MiB on disk (measured 10.4 MiB with both indexes).
|
|
92
|
+
* A direct carrier with a public URL has no per-address limit on wait=0
|
|
93
|
+
* reads, so one address can fill it there. Full: new v2 reads get 503
|
|
94
|
+
* inbox-auth-busy, and no live marker is dropped early.
|
|
95
|
+
*/
|
|
96
|
+
const MAX_INBOX_AUTH_NONCES = 100_000;
|
|
97
|
+
/** Most rows in one inbox page. */
|
|
98
|
+
export const INBOX_PAGE_ROWS = 200;
|
|
99
|
+
/**
|
|
100
|
+
* Most stored-body bytes in one inbox page (2.8.0, RedTeam 82902d): a page
|
|
101
|
+
* ends before the row that would pass this, always with whole envelopes. It
|
|
102
|
+
* is the largest envelope the carrier accepts, so a page always holds at
|
|
103
|
+
* least one; a row larger than this (stored by an older build) is served
|
|
104
|
+
* alone. `more: true` says rows remain after the cut.
|
|
105
|
+
*/
|
|
106
|
+
export const INBOX_PAGE_BYTES = 2 * 1024 * 1024 + 8192;
|
|
107
|
+
/** Bytes a page row costs beyond its body (seq, JSON framing), for reservations. */
|
|
108
|
+
const INBOX_ROW_OVERHEAD = 64;
|
|
109
|
+
/** A page's JSON is held about twice while it is serialized and sent; reserve for both. */
|
|
110
|
+
const INBOX_RESERVE_FACTOR = 2;
|
|
111
|
+
// Pages whose reservation is at most this are "small" (chat-sized mail);
|
|
112
|
+
// large pages leave 1/INBOX_SMALL_SLICE of the budget to them, so small
|
|
113
|
+
// mail is still served while large pages hold the rest.
|
|
114
|
+
const INBOX_SMALL_PAGE_COST = 256 * 1024;
|
|
115
|
+
const INBOX_SMALL_SLICE = 8;
|
|
116
|
+
// One client address holds at most 1/INBOX_ADDRESS_SHARE of the budget (C7-2):
|
|
117
|
+
// past that, its reads get 503 seed-busy at once, and other addresses still
|
|
118
|
+
// find room. An address that holds no page may always take one.
|
|
119
|
+
export const INBOX_ADDRESS_SHARE = 4;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Bytes of inbox pages a seed holds for clients at once (2.8.0, RedTeam
|
|
123
|
+
* 82902d). A page is reserved before it is read or built. The reservation is
|
|
124
|
+
* returned when the page has left this process: when its HTTP answer
|
|
125
|
+
* finishes, or, for a request the seed's own tunnel client made with a
|
|
126
|
+
* ticket from ticket(), when the tunnel client calls end(ticket) after it has
|
|
127
|
+
* sent the page to the relay or dropped the stream. Until then the page sits
|
|
128
|
+
* in the loopback socket and the tunnel client's queue, inside this process
|
|
129
|
+
* and its kernel buffers, so finishing the local answer is not enough.
|
|
130
|
+
*/
|
|
131
|
+
export class ResponseBudget {
|
|
132
|
+
constructor(limitBytes) {
|
|
133
|
+
this.limit = limitBytes;
|
|
134
|
+
this.used = 0;
|
|
135
|
+
this._tickets = new Map();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Tunnel client: a one-use ticket for one local request. */
|
|
139
|
+
ticket() {
|
|
140
|
+
const t = randomBytes(16).toString("hex");
|
|
141
|
+
this._tickets.set(t, null);
|
|
142
|
+
return t;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Carrier: run `release` when `ticket` ends. False when the ticket is not a live one. */
|
|
146
|
+
holdUntil(ticket, release) {
|
|
147
|
+
if (typeof ticket !== "string" || !this._tickets.has(ticket) || this._tickets.get(ticket) !== null) return false;
|
|
148
|
+
this._tickets.set(ticket, release);
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Tunnel client: the stream is over (sent or dropped); return what it held. */
|
|
153
|
+
end(ticket) {
|
|
154
|
+
const release = this._tickets.get(ticket);
|
|
155
|
+
this._tickets.delete(ticket);
|
|
156
|
+
if (typeof release === "function") release();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
79
159
|
const MAX_BODY = 512 * 1024; // 512 KiB per envelope (community tier)
|
|
80
160
|
const MAX_BODY_STREAM = 2 * 1024 * 1024 + 8192; // absolute read cap: max tier body + grant/header slack
|
|
81
161
|
const MAX_SKEW_MS = 5 * 60 * 1000;
|
|
@@ -162,7 +242,7 @@ const ENVELOPES_COLUMNS = `
|
|
|
162
242
|
const ENVELOPES_INDEX = "create index if not exists idx_envelopes_recipient on envelopes(recipient, seq);";
|
|
163
243
|
|
|
164
244
|
export class CarrierServer {
|
|
165
|
-
constructor({ dbPath = "carrier.db", ttlDays = 14, cryptoInventory, trustedTierIssuers = [], keychain = null, publicUrl = null, secureDelete = true, receiptKeychain = null, communityInboxWaits = COMMUNITY_CONCURRENT_WAITS, trustedProxies = DEFAULT_TRUSTED_PROXIES } = {}) {
|
|
245
|
+
constructor({ dbPath = "carrier.db", ttlDays = 14, cryptoInventory, trustedTierIssuers = [], keychain = null, publicUrl = null, secureDelete = true, receiptKeychain = null, communityInboxWaits = COMMUNITY_CONCURRENT_WAITS, trustedProxies = DEFAULT_TRUSTED_PROXIES, relayOrigin = null, tunnelRelay = null, responseBudget = null, maxInboxAuthNonces = MAX_INBOX_AUTH_NONCES, clock = () => Date.now() } = {}) {
|
|
166
246
|
// Every row's retain_until is created_at + ttlDays, so the TTL must be a
|
|
167
247
|
// real positive duration (a NaN here used to surface only as a vacuum crash).
|
|
168
248
|
if (typeof ttlDays !== "number" || !Number.isFinite(ttlDays) || ttlDays <= 0) {
|
|
@@ -195,7 +275,18 @@ export class CarrierServer {
|
|
|
195
275
|
k text primary key,
|
|
196
276
|
v text not null
|
|
197
277
|
);
|
|
278
|
+
-- 2.8.1: inbox auth v2 nonces, each usable once until its ts window ends.
|
|
279
|
+
create table if not exists inbox_auth_nonces (
|
|
280
|
+
nonce text primary key,
|
|
281
|
+
expires integer not null
|
|
282
|
+
);
|
|
283
|
+
create index if not exists idx_inbox_auth_nonces_expires on inbox_auth_nonces(expires);
|
|
198
284
|
`);
|
|
285
|
+
if (!Number.isSafeInteger(maxInboxAuthNonces) || maxInboxAuthNonces < 1) throw new Error("maxInboxAuthNonces must be a whole number of at least 1");
|
|
286
|
+
this.maxInboxAuthNonces = maxInboxAuthNonces;
|
|
287
|
+
this.clock = clock;
|
|
288
|
+
this._noncePrunedAt = -Infinity;
|
|
289
|
+
this._nonceCount = this.db.prepare("select count(*) as n from inbox_auth_nonces").get().n;
|
|
199
290
|
// Migration for stores created before carrier receipts: add the per-row
|
|
200
291
|
// retention deadline and canonical envelope hash. Existing rows get
|
|
201
292
|
// retain_until = created_at + ttlDays (what the old vacuum would have
|
|
@@ -259,6 +350,21 @@ export class CarrierServer {
|
|
|
259
350
|
// does not expose /v1/seed-info.
|
|
260
351
|
this.keychain = keychain;
|
|
261
352
|
this.publicUrl = publicUrl ? String(publicUrl).replace(/\/+$/, "") : null;
|
|
353
|
+
// 2.8.0 egress seed: the relay origin this seed is served through, declared
|
|
354
|
+
// inside its signed /v1/seed-info. Null for a seed with its own public URL.
|
|
355
|
+
this.relayOrigin = relayOrigin ? String(relayOrigin) : null;
|
|
356
|
+
// 2.8.0 relay side: a TunnelRelay (./tunnel-relay.mjs) that serves
|
|
357
|
+
// /v1/tunnel and /e/<localId>/... Null (the default): both stay 404.
|
|
358
|
+
this.tunnelRelay = tunnelRelay ?? null;
|
|
359
|
+
// 2.8.0 (RedTeam 82902d): an optional ResponseBudget (any { limit, used }
|
|
360
|
+
// works; tickets need the class) every inbox page is reserved against
|
|
361
|
+
// BEFORE it is read from the store and built; a seed served through a
|
|
362
|
+
// relay sets one, so the pages it holds while clients read them stay
|
|
363
|
+
// bounded. Null: unlimited, as before.
|
|
364
|
+
this.responseBudget = responseBudget ?? null;
|
|
365
|
+
// Response-budget bytes reserved per client address, for the addresses
|
|
366
|
+
// that hold some (C7-2, INBOX_ADDRESS_SHARE).
|
|
367
|
+
this.reservedByAddress = new Map();
|
|
262
368
|
// Receipt identity: the carrier uuaid is DERIVED from the receipt key
|
|
263
369
|
// (uuaid:foundation:agent:<localId>), never read from the keychain file,
|
|
264
370
|
// so it is always the uuaid a client's pin check derives.
|
|
@@ -358,11 +464,15 @@ export class CarrierServer {
|
|
|
358
464
|
* net/seed-tier.mjs). What the signature does prove is the thing enrollment
|
|
359
465
|
* actually needs — that whoever controls this URL also controls this key.
|
|
360
466
|
*/
|
|
361
|
-
seedInfo() {
|
|
467
|
+
seedInfo({ challenge } = {}) {
|
|
362
468
|
if (!this.keychain?._identity || !this.publicUrl) return null;
|
|
363
469
|
const doc = {
|
|
364
470
|
v: 1,
|
|
365
471
|
url: this.publicUrl,
|
|
472
|
+
// 2.8.0: a relayed seed declares its relay, and echoes a registry's
|
|
473
|
+
// one-use challenge, both under its signature (RedTeam c3ff4d).
|
|
474
|
+
...(this.relayOrigin ? { relay: this.relayOrigin } : {}),
|
|
475
|
+
...(challenge ? { challenge } : {}),
|
|
366
476
|
uuaid: this.keychain._identity.uuaid,
|
|
367
477
|
publicKey: this.keychain._identity.publicKeyHex,
|
|
368
478
|
startedAt: new Date(this.startedAt).toISOString(),
|
|
@@ -394,10 +504,20 @@ export class CarrierServer {
|
|
|
394
504
|
try { grant = JSON.parse(Buffer.from(String(hdr), "base64").toString("utf-8")); }
|
|
395
505
|
catch (_e) { return fallback; }
|
|
396
506
|
if (grant?.uuaid !== sender) return fallback; // grant must name the claimed sender
|
|
507
|
+
const now = Date.now();
|
|
397
508
|
const cached = this._grantCache.get(sender);
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
509
|
+
let warm = Boolean(cached && cached.sig === grant.sig && now - cached.at < 60_000);
|
|
510
|
+
// A cached decision never outlives the grant it came from: at the grant's
|
|
511
|
+
// expiry the sender is verified again and falls to community (2.8.0,
|
|
512
|
+
// RedTeam 22f6c3 Q1: relayed seeds' grants can last minutes, not days).
|
|
513
|
+
if (warm && !(now < cached.expiresAt)) warm = false; // @rule tier.grant-cache-until-expiry
|
|
514
|
+
if (warm) return cached.resolved;
|
|
515
|
+
const v = verifyTierGrant(grant, this.trustedTierIssuers, now);
|
|
516
|
+
// verifyTierGrant still accepts a grant at the very millisecond it
|
|
517
|
+
// expires; here the sender falls to community at now >= expiry.
|
|
518
|
+
let granted = v.ok;
|
|
519
|
+
if (granted && !(now < Date.parse(grant.expires))) granted = false; // @rule tier.grant-expiry-exclusive
|
|
520
|
+
const resolved = granted
|
|
401
521
|
? {
|
|
402
522
|
tier: grant.tier,
|
|
403
523
|
envelopesPerMin: grant.envelopesPerMin,
|
|
@@ -410,7 +530,9 @@ export class CarrierServer {
|
|
|
410
530
|
}
|
|
411
531
|
: fallback;
|
|
412
532
|
if (this._grantCache.size > 4096) this._grantCache.clear(); // bounded
|
|
413
|
-
|
|
533
|
+
// NaN (an unparseable expiry) is never `now <` it, so such an entry is never reused.
|
|
534
|
+
const expiresAt = granted ? Date.parse(grant.expires) : Infinity;
|
|
535
|
+
this._grantCache.set(sender, { sig: grant.sig, at: now, resolved, expiresAt });
|
|
414
536
|
return resolved;
|
|
415
537
|
}
|
|
416
538
|
|
|
@@ -623,7 +745,16 @@ export class CarrierServer {
|
|
|
623
745
|
});
|
|
624
746
|
}
|
|
625
747
|
|
|
626
|
-
|
|
748
|
+
/**
|
|
749
|
+
* Inbox auth, v1 or v2 (src/net/inbox-auth.mjs). v2 (x-pillar-auth: 2) is
|
|
750
|
+
* checked against this server's own audience (its public URL) and its
|
|
751
|
+
* nonce is consumed only after the signature verifies. A relayed seed
|
|
752
|
+
* (relayOrigin set) takes v2 only (2.8.1, Lead 5e8cf6).
|
|
753
|
+
*/
|
|
754
|
+
_verifyInboxAuth(req, uuaid, sincePath, query = null) {
|
|
755
|
+
const version = req.headers["x-pillar-auth"];
|
|
756
|
+
if (version !== undefined && version !== "2") return { ok: false, reason: "inbox-auth-version" };
|
|
757
|
+
if (version === undefined && this.relayOrigin) return { ok: false, reason: "inbox-auth-v2-required" };
|
|
627
758
|
const pubkey = req.headers["x-pillar-pubkey"];
|
|
628
759
|
const ts = req.headers["x-pillar-ts"];
|
|
629
760
|
const sig = req.headers["x-pillar-sig"];
|
|
@@ -631,7 +762,7 @@ export class CarrierServer {
|
|
|
631
762
|
if (!/^[0-9a-f]{64}$/i.test(pubkey)) return { ok: false, reason: "bad-pubkey" };
|
|
632
763
|
if (!/^[0-9a-f]{128}$/i.test(sig)) return { ok: false, reason: "bad-sig-encoding" };
|
|
633
764
|
const tsNum = Number(ts);
|
|
634
|
-
if (!Number.isFinite(tsNum) || Math.abs(Date.now() - tsNum) > MAX_SKEW_MS) {
|
|
765
|
+
if (!Number.isFinite(tsNum) || Math.abs((typeof this.clock === "function" ? this.clock() : Date.now()) - tsNum) > MAX_SKEW_MS) {
|
|
635
766
|
return { ok: false, reason: "clock-skew" };
|
|
636
767
|
}
|
|
637
768
|
// Self-authenticating: UUAID must derive from the presented pubkey.
|
|
@@ -646,12 +777,61 @@ export class CarrierServer {
|
|
|
646
777
|
}
|
|
647
778
|
// Either the principal's own key or an authorized delegate key: in both
|
|
648
779
|
// cases it must have signed THIS request.
|
|
649
|
-
|
|
780
|
+
let message;
|
|
781
|
+
let nonce = null;
|
|
782
|
+
let v2 = null;
|
|
783
|
+
if (version === "2") {
|
|
784
|
+
if (!this.publicUrl) return { ok: false, reason: "inbox-audience-unknown" };
|
|
785
|
+
nonce = req.headers["x-pillar-nonce"];
|
|
786
|
+
if (typeof nonce !== "string" || !NONCE_RE.test(nonce)) return { ok: false, reason: "bad-nonce" };
|
|
787
|
+
if (!/^[0-9]{1,16}$/.test(ts)) return { ok: false, reason: "clock-skew" };
|
|
788
|
+
// Every query value that changes the read is signed; the handler acts on
|
|
789
|
+
// these values only (RedTeam 57c79a item 1).
|
|
790
|
+
v2 = query ? canonicalInboxQuery(query) : { ok: false };
|
|
791
|
+
if (!v2.ok) return { ok: false, reason: "inbox-auth-query" }; // @rule inbox.v2-canonical-query
|
|
792
|
+
message = inboxAuthV2Bytes({ audience: this.publicUrl, uuaid, since: v2.since, wait: v2.wait, challenge: v2.challenge, ts: Number(ts), nonce });
|
|
793
|
+
} else {
|
|
794
|
+
message = Buffer.from(`${sincePath}\n${ts}`, "utf-8");
|
|
795
|
+
}
|
|
650
796
|
let verified = false;
|
|
651
797
|
try { verified = Keychain.verifyDetached(pubkey, message, Buffer.from(sig, "hex")); }
|
|
652
798
|
catch (_e) { return { ok: false, reason: "verify-threw" }; }
|
|
653
799
|
if (!verified) return { ok: false, reason: "bad-signature" };
|
|
654
|
-
|
|
800
|
+
if (nonce !== null) {
|
|
801
|
+
const used = this._consumeNonce(nonce, Number(ts));
|
|
802
|
+
if (used === "full") return { ok: false, status: 503, reason: "inbox-auth-busy" };
|
|
803
|
+
if (!used) return { ok: false, reason: "nonce-used" };
|
|
804
|
+
}
|
|
805
|
+
return { ok: true, ...(v2 ? { v2: { since: v2.since, wait: v2.wait, challenge: v2.challenge } } : {}) };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Use a v2 nonce once: true the first time, false after, "full" when the
|
|
810
|
+
* store holds maxInboxAuthNonces live markers. The insert is one statement,
|
|
811
|
+
* so two requests with one nonce cannot both pass. A marker is kept until
|
|
812
|
+
* its request's ts window has ended (expires = ts + 5 min + 1 s); only
|
|
813
|
+
* markers past that are pruned, by the expiry index, and a request with such
|
|
814
|
+
* an old ts is refused by the clock check first. A live marker is never
|
|
815
|
+
* dropped to make room (RedTeam 57c79a item 3).
|
|
816
|
+
*/
|
|
817
|
+
_consumeNonce(nonce, ts) {
|
|
818
|
+
const now = this.clock();
|
|
819
|
+
const prune = () => {
|
|
820
|
+
this._nonceCount -= this.db.prepare("delete from inbox_auth_nonces where expires < ?").run(now).changes;
|
|
821
|
+
this._noncePrunedAt = now;
|
|
822
|
+
};
|
|
823
|
+
if (now - this._noncePrunedAt > 10_000) prune();
|
|
824
|
+
if (this.db.prepare("select 1 from inbox_auth_nonces where nonce = ?").get(nonce)) return false;
|
|
825
|
+
if (this._nonceCount >= this.maxInboxAuthNonces) prune();
|
|
826
|
+
if (this._nonceCount >= this.maxInboxAuthNonces) return "full"; // @rule inbox.nonce-store-cap
|
|
827
|
+
try {
|
|
828
|
+
this.db.prepare("insert into inbox_auth_nonces (nonce, expires) values (?, ?)").run(nonce, ts + MAX_SKEW_MS + 1000);
|
|
829
|
+
this._nonceCount++;
|
|
830
|
+
return true;
|
|
831
|
+
} catch (e) {
|
|
832
|
+
if (String(e?.code).startsWith("SQLITE_CONSTRAINT")) return false;
|
|
833
|
+
throw e;
|
|
834
|
+
}
|
|
655
835
|
}
|
|
656
836
|
|
|
657
837
|
/**
|
|
@@ -685,12 +865,22 @@ export class CarrierServer {
|
|
|
685
865
|
return { ok: true };
|
|
686
866
|
}
|
|
687
867
|
|
|
868
|
+
/** Reserve (n > 0) or return (n < 0) response-budget bytes for client address `ip`. */
|
|
869
|
+
_reserve(ip, n) {
|
|
870
|
+
this.responseBudget.used += n;
|
|
871
|
+
const left = (this.reservedByAddress.get(ip) ?? 0) + n;
|
|
872
|
+
if (left > 0) this.reservedByAddress.set(ip, left); else this.reservedByAddress.delete(ip);
|
|
873
|
+
}
|
|
874
|
+
|
|
688
875
|
async _handleInbox(req, res, uuaid, url) {
|
|
689
|
-
|
|
690
|
-
|
|
876
|
+
let since = Number(url.searchParams.get("since") ?? 0);
|
|
877
|
+
let wait = Math.min(Number(url.searchParams.get("wait") ?? 0), MAX_WAIT_S);
|
|
878
|
+
let challenge = url.searchParams.get("challenge");
|
|
691
879
|
const sincePath = `GET /v1/inbox/${uuaid}?since=${since}`;
|
|
692
|
-
const auth = this._verifyInboxAuth(req, uuaid, sincePath);
|
|
693
|
-
if (!auth.ok) return this._json(res, 401, { error: auth.reason });
|
|
880
|
+
const auth = this._verifyInboxAuth(req, uuaid, sincePath, url.searchParams);
|
|
881
|
+
if (!auth.ok) return this._json(res, auth.status ?? 401, { error: auth.reason });
|
|
882
|
+
// v2: the read uses exactly the signed values (RedTeam 57c79a item 1).
|
|
883
|
+
if (auth.v2) { since = auth.v2.since; wait = Math.min(auth.v2.wait, MAX_WAIT_S); challenge = auth.v2.challenge; } // the same values as the raw query when canonical; kept so no other read of the query can drift
|
|
694
884
|
|
|
695
885
|
// F2: cap concurrent long-polls so sleeping connections cannot pin the
|
|
696
886
|
// event loop / fd table. The grant is resolved against the PRINCIPAL
|
|
@@ -704,27 +894,90 @@ export class CarrierServer {
|
|
|
704
894
|
}
|
|
705
895
|
if (wait > 0) this.activeWaits++;
|
|
706
896
|
|
|
707
|
-
|
|
897
|
+
// A page is sized from body lengths first (no body is read), cut at
|
|
898
|
+
// INBOX_PAGE_BYTES with whole envelopes, reserved against the response
|
|
899
|
+
// budget, and only then read and built (RedTeam 82902d).
|
|
900
|
+
const sizeRows = () => {
|
|
708
901
|
// closed → the DB is gone; a long-poll timer armed before close() can
|
|
709
902
|
// fire afterwards. Never touch a closed connection.
|
|
710
903
|
if (this._closed) return [];
|
|
711
904
|
return this.db.prepare(
|
|
712
|
-
|
|
905
|
+
// octet_length: UTF-8 bytes. length() would count characters and
|
|
906
|
+
// undercount a non-ASCII body (SQLite >= 3.43; better-sqlite3 ships 3.53).
|
|
907
|
+
`select seq, octet_length(body) as n from envelopes where recipient = ? and seq > ? order by seq asc limit ${INBOX_PAGE_ROWS + 1}`
|
|
713
908
|
).all(uuaid, since);
|
|
714
909
|
};
|
|
715
910
|
|
|
911
|
+
let reserved = 0;
|
|
912
|
+
const ip = this._clientIp(req);
|
|
716
913
|
try {
|
|
717
|
-
let
|
|
914
|
+
let sized = sizeRows();
|
|
718
915
|
const deadline = Date.now() + wait * 1000;
|
|
719
|
-
while (
|
|
916
|
+
while (sized.length === 0 && Date.now() < deadline && !this._closed) {
|
|
720
917
|
await this._sleepOrWake(uuaid, 400);
|
|
721
|
-
|
|
918
|
+
sized = sizeRows();
|
|
919
|
+
}
|
|
920
|
+
// Whole envelopes up to the byte limit and, with a response budget, up
|
|
921
|
+
// to what the free budget holds; the first row always, so a page is
|
|
922
|
+
// never empty while mail waits (a single row may pass either limit:
|
|
923
|
+
// one envelope, alone, when nothing else is reserved).
|
|
924
|
+
const budget = this.responseBudget;
|
|
925
|
+
const cost = (b, n) => (b + n * INBOX_ROW_OVERHEAD) * INBOX_RESERVE_FACTOR;
|
|
926
|
+
const free = budget ? budget.limit - budget.used : Infinity;
|
|
927
|
+
let smallSlice = 0;
|
|
928
|
+
if (budget) smallSlice = Math.floor(budget.limit / INBOX_SMALL_SLICE); // @rule inbox.small-slice
|
|
929
|
+
// What this client address may still reserve: its share, less what its
|
|
930
|
+
// other pages hold; no limit while it holds none (C7-2).
|
|
931
|
+
const mine = this.reservedByAddress.get(ip) ?? 0;
|
|
932
|
+
let addressRoom = Infinity;
|
|
933
|
+
if (mine > 0) addressRoom = Math.floor(budget.limit / INBOX_ADDRESS_SHARE) - mine; // @rule inbox.address-share
|
|
934
|
+
const roomFor = (c) => Math.min(c <= INBOX_SMALL_PAGE_COST ? free : free - smallSlice, addressRoom);
|
|
935
|
+
let take = 0;
|
|
936
|
+
let bytes = 0;
|
|
937
|
+
while (take < sized.length && take < INBOX_PAGE_ROWS) {
|
|
938
|
+
const next = bytes + sized[take].n;
|
|
939
|
+
if (take > 0 && next > INBOX_PAGE_BYTES) break; // @rule inbox.page-bytes
|
|
940
|
+
const c = cost(next, take + 1);
|
|
941
|
+
if (take > 0 && c > roomFor(c)) break; // @rule inbox.page-fits-budget
|
|
942
|
+
bytes = next;
|
|
943
|
+
take++;
|
|
722
944
|
}
|
|
945
|
+
const more = take < sized.length;
|
|
946
|
+
if (take > 0 && budget) {
|
|
947
|
+
// Nobody left to send to (the client went during a long-poll): build nothing.
|
|
948
|
+
if (res.destroyed) return;
|
|
949
|
+
const need = cost(bytes, take);
|
|
950
|
+
// Refused only while other pages hold the budget; an idle budget
|
|
951
|
+
// always serves one page, so no mail is unreadable for good.
|
|
952
|
+
if (budget.used > 0 && need > roomFor(need)) return this._json(res, 503, { error: "seed-busy" }); // @rule inbox.reserve-first
|
|
953
|
+
this._reserve(ip, need);
|
|
954
|
+
reserved = need;
|
|
955
|
+
const release = () => { if (reserved) { this._reserve(ip, -reserved); reserved = 0; } };
|
|
956
|
+
// The seed's own tunnel client returns it once the page has gone to
|
|
957
|
+
// the relay; any other client, when its answer finishes.
|
|
958
|
+
let held = false;
|
|
959
|
+
held = budget.holdUntil?.(req.headers["x-pillar-budget-ticket"], release) === true; // @rule inbox.hold-until-sent
|
|
960
|
+
// Node 22 emits finish also when the client goes mid-page; close is
|
|
961
|
+
// the fallback. A ticket's page is returned by the tunnel client,
|
|
962
|
+
// which ends the ticket when the stream ends, resets or the tunnel goes.
|
|
963
|
+
if (!held) { res.once("finish", release); res.once("close", release); }
|
|
964
|
+
}
|
|
965
|
+
const rows = take === 0 ? [] : this.db.prepare(
|
|
966
|
+
"select seq, body from envelopes where recipient = ? and seq >= ? and seq <= ? order by seq asc"
|
|
967
|
+
).all(uuaid, sized[0].seq, sized[take - 1].seq);
|
|
723
968
|
if (rows.length) this._bump("served", rows.length);
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
969
|
+
const envelopes = rows.map(r => ({ seq: r.seq, envelope: JSON.parse(r.body) }));
|
|
970
|
+
// 2.8.0 served proof (RedTeam 085b71 C4): a seed asked with a one-use
|
|
971
|
+
// challenge signs the digest of this exact page, on this authenticated
|
|
972
|
+
// read, so a relay cannot answer a registry's round trip by itself.
|
|
973
|
+
const proof = this.keychain?._identity && challenge !== null && CHALLENGE_RE.test(challenge) && Number.isSafeInteger(since)
|
|
974
|
+
? makeServedProof(this.keychain, { inbox: uuaid, since, challenge, envelopes })
|
|
975
|
+
: undefined;
|
|
976
|
+
this._json(res, 200, { envelopes, now: Date.now(), ...(more ? { more: true } : {}), ...(proof ? { proof } : {}) });
|
|
977
|
+
} catch (e) {
|
|
978
|
+
// Nothing was sent: give the reservation back before the error answer.
|
|
979
|
+
if (reserved && this.responseBudget) { this._reserve(ip, -reserved); reserved = 0; }
|
|
980
|
+
throw e;
|
|
728
981
|
} finally {
|
|
729
982
|
if (wait > 0) this.activeWaits--;
|
|
730
983
|
}
|
|
@@ -741,6 +994,9 @@ export class CarrierServer {
|
|
|
741
994
|
this.server = createServer(async (req, res) => {
|
|
742
995
|
try {
|
|
743
996
|
const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
|
|
997
|
+
// 2.8.0 relay routes, only when this carrier accepts tunnels.
|
|
998
|
+
if (this.tunnelRelay && url.pathname.startsWith("/e/")) return await this.tunnelRelay.handleRequest(req, res, url);
|
|
999
|
+
if (this.tunnelRelay && url.pathname === "/v1/tunnel") return this._json(res, 426, { error: "upgrade-required" });
|
|
744
1000
|
if (req.method === "POST" && url.pathname === "/v1/envelopes") {
|
|
745
1001
|
const raw = await this._readBody(req);
|
|
746
1002
|
let envelope;
|
|
@@ -756,7 +1012,11 @@ export class CarrierServer {
|
|
|
756
1012
|
return await this._handleInbox(req, res, uuaid, url);
|
|
757
1013
|
}
|
|
758
1014
|
if (req.method === "GET" && url.pathname === "/v1/seed-info") {
|
|
759
|
-
const
|
|
1015
|
+
const challenge = url.searchParams.get("challenge");
|
|
1016
|
+
if (challenge !== null && this.keychain?._identity && this.publicUrl && !CHALLENGE_RE.test(challenge)) {
|
|
1017
|
+
return this._json(res, 400, { error: "bad-challenge" });
|
|
1018
|
+
}
|
|
1019
|
+
const info = this.seedInfo({ challenge: challenge ?? undefined });
|
|
760
1020
|
// A relay with no seed identity is not a seed and must not look
|
|
761
1021
|
// like one to the registry.
|
|
762
1022
|
if (!info) return this._json(res, 404, { error: "not-a-seed" });
|
|
@@ -773,6 +1033,7 @@ export class CarrierServer {
|
|
|
773
1033
|
this._json(res, 500, { error: "internal-error" });
|
|
774
1034
|
}
|
|
775
1035
|
});
|
|
1036
|
+
if (this.tunnelRelay) this.server.on("upgrade", (req, socket, head) => this.tunnelRelay.handleUpgrade(req, socket, head));
|
|
776
1037
|
return new Promise((resolve) => {
|
|
777
1038
|
if (port !== null && typeof port === "object") this.server.listen(port, () => resolve(this.server.address()));
|
|
778
1039
|
else this.server.listen(port, host, () => resolve(this.server.address()));
|
|
@@ -781,6 +1042,7 @@ export class CarrierServer {
|
|
|
781
1042
|
|
|
782
1043
|
async close() {
|
|
783
1044
|
this._closed = true;
|
|
1045
|
+
this.tunnelRelay?.close();
|
|
784
1046
|
for (const set of this._inboxWakers.values()) for (const wake of [...set]) wake();
|
|
785
1047
|
if (this.server) {
|
|
786
1048
|
// close() must not wait for in-flight connections: a client long-polling
|
|
@@ -0,0 +1,94 @@
|
|
|
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) was configured automatically, because inbox auth sent
|
|
7
|
+
* through a relay could be replayed for 5 minutes.
|
|
8
|
+
*
|
|
9
|
+
* 2.8.1 (Lead 5e8cf6, owner order 2026-12-04): a client sends a relayed seed
|
|
10
|
+
* only inbox auth v2, bound to that seed URL and single-use
|
|
11
|
+
* (src/net/inbox-auth.mjs), so a relayed seed is taken from a directory when
|
|
12
|
+
* its entry names its relay and its URL is `<relay>/e/<id>` (the registry
|
|
13
|
+
* lists it only after a round trip with inbox auth v2 and the seed's served
|
|
14
|
+
* proof passed for its current URL, key and relay pin; RedTeam 57c79a). At
|
|
15
|
+
* most MAX_RELAYED_FROM_DIRECTORY are taken, in directory order, so a
|
|
16
|
+
* directory full of relayed seeds cannot fan one client's mail out to all of
|
|
17
|
+
* them. The bootstrap carrier is never a relayed seed. A relayed-shape URL
|
|
18
|
+
* with no `relay`, or `relay` on a URL of another shape, is skipped. Direct
|
|
19
|
+
* carrier and seed entries are taken exactly as before.
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import { isRelayedSeedUrl } from "./tunnel.mjs";
|
|
23
|
+
|
|
24
|
+
export const MAX_RELAYED_FROM_DIRECTORY = 4;
|
|
25
|
+
|
|
26
|
+
/** A directory seed entry that names its relay, at exactly `<relay>/e/<id>`. */
|
|
27
|
+
function provenRelayed(s) {
|
|
28
|
+
if (typeof s?.relay !== "string" || typeof s?.url !== "string") return false;
|
|
29
|
+
return isRelayedSeedUrl(s.url) && s.url.replace(/\/+$/, "").startsWith(`${s.relay.replace(/\/+$/, "")}/e/`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {object} d a directory document ({ carrier, seeds: [{ url, relay? }] })
|
|
34
|
+
* @returns {{ carriers: string[], skippedRelayed: number }}
|
|
35
|
+
* carriers in directory order: the bootstrap carrier, then each seed URL.
|
|
36
|
+
*/
|
|
37
|
+
export function directoryCarriers(d) {
|
|
38
|
+
const carriers = [];
|
|
39
|
+
let skippedRelayed = 0;
|
|
40
|
+
let relayedTaken = 0;
|
|
41
|
+
let carrier = d?.carrier;
|
|
42
|
+
if (carrier && isRelayedSeedUrl(carrier)) { carrier = null; skippedRelayed++; } // @rule discovery.carrier-not-relayed
|
|
43
|
+
if (carrier) carriers.push(carrier);
|
|
44
|
+
for (const s of Array.isArray(d?.seeds) ? d.seeds : []) {
|
|
45
|
+
let url = s?.url;
|
|
46
|
+
let relayed = false;
|
|
47
|
+
if (url && s?.relay !== undefined) {
|
|
48
|
+
relayed = provenRelayed(s);
|
|
49
|
+
if (!relayed) { url = null; skippedRelayed++; } // @rule discovery.seed-relay-metadata
|
|
50
|
+
}
|
|
51
|
+
if (url && !relayed && isRelayedSeedUrl(url)) { url = null; skippedRelayed++; } // @rule discovery.seed-relayed-shape
|
|
52
|
+
if (url && relayed && relayedTaken >= MAX_RELAYED_FROM_DIRECTORY) { url = null; skippedRelayed++; } // @rule discovery.relayed-cap
|
|
53
|
+
if (url && relayed) relayedTaken++;
|
|
54
|
+
if (url) carriers.push(url);
|
|
55
|
+
}
|
|
56
|
+
return { carriers, skippedRelayed };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The carrier list alone, in the shape init-cli has always used. */
|
|
60
|
+
export function carriersFromDirectory(d) {
|
|
61
|
+
return directoryCarriers(d).carriers;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Read a home's config.json back after a write and check its carriers are
|
|
66
|
+
* exactly `expected` (RedTeam 995f4c Q2: when `pillar init --refresh` is used
|
|
67
|
+
* to clean relayed URLs out of a home, what is on disk is the evidence, not
|
|
68
|
+
* what was meant to be written).
|
|
69
|
+
* @returns {{ ok: true, carriers: string[] } | { ok: false, reason: string, carriers?: string[] }}
|
|
70
|
+
*/
|
|
71
|
+
export function readBackCarriers(cfgPath, expected) {
|
|
72
|
+
let carriers;
|
|
73
|
+
try {
|
|
74
|
+
carriers = JSON.parse(readFileSync(cfgPath, "utf-8"))?.carriers;
|
|
75
|
+
} catch (e) {
|
|
76
|
+
return { ok: false, reason: `cannot read it back (${e.code ?? "not JSON"})` };
|
|
77
|
+
}
|
|
78
|
+
if (!Array.isArray(carriers)) return { ok: false, reason: "no carriers list in it" };
|
|
79
|
+
// Element by element, so a relayed URL left on disk (or any other drift) fails.
|
|
80
|
+
let same = true;
|
|
81
|
+
if (carriers.length !== expected.length || carriers.some((c, i) => c !== expected[i])) same = false; // @rule discovery.readback-equal
|
|
82
|
+
if (!same) return { ok: false, reason: "its carriers differ from what was written", carriers };
|
|
83
|
+
return { ok: true, carriers };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The relayed seed URLs a home's config.json lists now ([] if none or unreadable). */
|
|
87
|
+
export function relayedCarriersIn(cfgPath) {
|
|
88
|
+
try {
|
|
89
|
+
const carriers = JSON.parse(readFileSync(cfgPath, "utf-8"))?.carriers;
|
|
90
|
+
return Array.isArray(carriers) ? carriers.filter((c) => isRelayedSeedUrl(c)) : [];
|
|
91
|
+
} catch (_e) {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbox auth v2 (2.8.1, Lead 5e8cf6; scope fixed per RedTeam 57c79a item 1):
|
|
3
|
+
* bound to its audience, to every query value that changes the read, and
|
|
4
|
+
* single-use.
|
|
5
|
+
*
|
|
6
|
+
* v1 (`x-pillar-sig` over "GET /v1/inbox/<uuaid>?since=<n>\n<ts>") names no
|
|
7
|
+
* carrier and can be sent again for 5 minutes, so whoever receives it (a seed,
|
|
8
|
+
* or the relay in front of one) could read the same inbox at the client's
|
|
9
|
+
* other carriers. v2 signs, as JCS:
|
|
10
|
+
*
|
|
11
|
+
* { t: "pillar-inbox-auth/2", method: "GET", audience, inbox, since, wait,
|
|
12
|
+
* challenge, ts, nonce }
|
|
13
|
+
*
|
|
14
|
+
* audience the carrier base URL the client sends to, as configured, with
|
|
15
|
+
* no trailing slash (a relayed seed: <relay origin>/e/<id>)
|
|
16
|
+
* inbox the inbox uuaid in the path
|
|
17
|
+
* since the `since` query value (a whole number; absent = 0)
|
|
18
|
+
* wait the `wait` query value in seconds (a whole number; absent = 0)
|
|
19
|
+
* challenge the `challenge` query value (64 hex) the seed signs its served
|
|
20
|
+
* proof for, or null when absent
|
|
21
|
+
* ts unix ms (the same 5-minute window as v1)
|
|
22
|
+
* nonce 32 hex characters, random per request
|
|
23
|
+
*
|
|
24
|
+
* Both sides build these values with canonicalInboxQuery, so the verifier
|
|
25
|
+
* checks the signature over exactly the values it then acts on. A v2 query
|
|
26
|
+
* with any other key, a repeated key, or a value not in canonical form is
|
|
27
|
+
* refused (`inbox-auth-query`) before the signature is checked and before
|
|
28
|
+
* the nonce is used.
|
|
29
|
+
*
|
|
30
|
+
* Headers: x-pillar-auth: 2, x-pillar-pubkey, x-pillar-ts, x-pillar-nonce,
|
|
31
|
+
* x-pillar-sig (and x-pillar-delegation, as v1). The receiver checks the
|
|
32
|
+
* signature against ITS OWN audience, then uses the nonce once
|
|
33
|
+
* (src/net/carrier-server.mjs). A second use is refused (`nonce-used`).
|
|
34
|
+
*
|
|
35
|
+
* Who sends which: a client sends v2 to a relayed seed URL and v1 to a direct
|
|
36
|
+
* carrier (as 2.8.0). A relayed seed and a 2.8.1 relay refuse v1. v1 bytes
|
|
37
|
+
* and v1 parsing are unchanged.
|
|
38
|
+
*/
|
|
39
|
+
import { randomBytes } from "node:crypto";
|
|
40
|
+
import { jcs } from "../identity/jcs.mjs";
|
|
41
|
+
|
|
42
|
+
export const INBOX_AUTH_V2 = "pillar-inbox-auth/2";
|
|
43
|
+
export const NONCE_RE = /^[0-9a-f]{32}$/;
|
|
44
|
+
const WHOLE = /^(0|[1-9][0-9]{0,14})$/;
|
|
45
|
+
const CHALLENGE = /^[0-9a-f]{64}$/;
|
|
46
|
+
const V2_QUERY_KEYS = new Set(["since", "wait", "challenge"]);
|
|
47
|
+
|
|
48
|
+
/** A carrier base URL as an audience: the configured URL without trailing slashes. */
|
|
49
|
+
export function canonicalAudience(url) {
|
|
50
|
+
return String(url).replace(/\/+$/, "");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The canonical v2 query values from URLSearchParams: { ok, since, wait,
|
|
55
|
+
* challenge } or { ok:false }. Only since, wait and challenge, each at most
|
|
56
|
+
* once; since and wait whole numbers in plain decimal; challenge 64 hex.
|
|
57
|
+
*/
|
|
58
|
+
export function canonicalInboxQuery(params) {
|
|
59
|
+
const seen = new Set();
|
|
60
|
+
for (const k of params.keys()) {
|
|
61
|
+
if (!V2_QUERY_KEYS.has(k) || seen.has(k)) return { ok: false };
|
|
62
|
+
seen.add(k);
|
|
63
|
+
}
|
|
64
|
+
const s = params.get("since") ?? "0";
|
|
65
|
+
const w = params.get("wait") ?? "0";
|
|
66
|
+
const c = params.get("challenge");
|
|
67
|
+
if (!WHOLE.test(s) || !WHOLE.test(w)) return { ok: false };
|
|
68
|
+
if (c !== null && !CHALLENGE.test(c)) return { ok: false };
|
|
69
|
+
return { ok: true, since: Number(s), wait: Number(w), challenge: c };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The query string a v2 signer sends for these values (canonical order). */
|
|
73
|
+
export function inboxQueryString({ since = 0, wait = 0, challenge = null }) {
|
|
74
|
+
return `since=${since}&wait=${wait}${challenge === null ? "" : `&challenge=${challenge}`}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The signed bytes of a v2 inbox auth. */
|
|
78
|
+
export function inboxAuthV2Bytes({ audience, uuaid, since, wait, challenge, ts, nonce }) {
|
|
79
|
+
return Buffer.from(jcs({ t: INBOX_AUTH_V2, method: "GET", audience, inbox: uuaid, since, wait, challenge, ts, nonce }), "utf-8");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** v2 inbox auth headers for one request to `audience`, with the query it signs. */
|
|
83
|
+
export function signInboxAuthV2(keychain, { audience, uuaid, since = 0, wait = 0, challenge = null, ts = Date.now(), nonce = randomBytes(16).toString("hex") }) {
|
|
84
|
+
const q = canonicalInboxQuery(new URLSearchParams(inboxQueryString({ since, wait, challenge })));
|
|
85
|
+
if (!q.ok) throw new Error("signInboxAuthV2: since and wait must be whole numbers and challenge 64 hex or null");
|
|
86
|
+
const sig = keychain.sign(inboxAuthV2Bytes({ audience: canonicalAudience(audience), uuaid, since: q.since, wait: q.wait, challenge: q.challenge, ts, nonce })).toString("hex");
|
|
87
|
+
return {
|
|
88
|
+
"x-pillar-auth": "2",
|
|
89
|
+
"x-pillar-pubkey": keychain._identity.publicKeyHex,
|
|
90
|
+
"x-pillar-ts": String(ts),
|
|
91
|
+
"x-pillar-nonce": nonce,
|
|
92
|
+
"x-pillar-sig": sig,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** v1 inbox auth headers (2.8.0 and earlier; direct carriers only). */
|
|
97
|
+
export function signInboxAuthV1(keychain, { uuaid, since, ts = Date.now() }) {
|
|
98
|
+
const sig = keychain.sign(Buffer.from(`GET /v1/inbox/${uuaid}?since=${since}\n${ts}`, "utf-8")).toString("hex");
|
|
99
|
+
return { "x-pillar-pubkey": keychain._identity.publicKeyHex, "x-pillar-ts": String(ts), "x-pillar-sig": sig };
|
|
100
|
+
}
|