@peer2peer/relay 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +19 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +88 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +23 -0
- package/dist/config.d.ts +266 -0
- package/dist/config.js +326 -0
- package/dist/crypto.d.ts +159 -0
- package/dist/crypto.js +514 -0
- package/dist/identity.d.ts +84 -0
- package/dist/identity.js +386 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +14 -0
- package/dist/links.d.ts +29 -0
- package/dist/links.js +98 -0
- package/dist/log.d.ts +19 -0
- package/dist/log.js +35 -0
- package/dist/members.d.ts +109 -0
- package/dist/members.js +369 -0
- package/dist/metrics.d.ts +13 -0
- package/dist/metrics.js +66 -0
- package/dist/net.d.ts +23 -0
- package/dist/net.js +103 -0
- package/dist/ratelimit.d.ts +16 -0
- package/dist/ratelimit.js +70 -0
- package/dist/server.d.ts +271 -0
- package/dist/server.js +1951 -0
- package/dist/sqlite-store.d.ts +184 -0
- package/dist/sqlite-store.js +1068 -0
- package/dist/store.d.ts +368 -0
- package/dist/store.js +492 -0
- package/package.json +57 -4
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// The relay's only window onto Peer2Peer v3 cryptography (docs/protocol.md).
|
|
4
|
+
//
|
|
5
|
+
// Everything the relay needs to check (device certificates, the relay-auth
|
|
6
|
+
// signature, outer envelopes, capabilities, proof-of-work, identity-document
|
|
7
|
+
// links) goes through the RelayCrypto interface below. The rest of the relay
|
|
8
|
+
// never parses a JWS itself.
|
|
9
|
+
//
|
|
10
|
+
// The implementation here is a TEMPORARY ADAPTER built on @peer2peer/core's
|
|
11
|
+
// v2 primitives (decodeJws, verifyJws, sha256, b64u) plus @noble/curves for the
|
|
12
|
+
// two things core does not export (raw Ed25519 verify, small-order checks).
|
|
13
|
+
// When Phase 2 (`@peer2peer/core/v3`) merges, `createRelayCrypto()` is
|
|
14
|
+
// re-implemented on top of it and nothing else in packages/relay changes.
|
|
15
|
+
// Every place that must change at that point is marked `TODO(phase2-wire)`.
|
|
16
|
+
import { createPublicKey, verify as nodeVerify } from "node:crypto";
|
|
17
|
+
import { b64uDecode, b64uEncode, decodeJws, sha256 } from "@peer2peer/core";
|
|
18
|
+
import { assertStrongEd25519PublicKey, assertStrongX25519PublicKey, ed25519Verify as ed25519VerifyNoble, verifyIdentityDocLink as coreVerifyIdentityDocLink, verifyIdentityDocSignature, } from "@peer2peer/core/v3";
|
|
19
|
+
export class RelayCryptoError extends Error {
|
|
20
|
+
code;
|
|
21
|
+
constructor(code, message) {
|
|
22
|
+
super(message ?? code);
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.name = "RelayCryptoError";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Constants (§1, §2.3, §2.5, §5.3)
|
|
29
|
+
export const TYP_DEVICE = "p2p-device+jws";
|
|
30
|
+
export const TYP_MSG = "p2p-msg+jws";
|
|
31
|
+
export const TYP_CAP = "p2p-cap+jws";
|
|
32
|
+
export const TYP_IDENTITY = "p2p-identity+jws";
|
|
33
|
+
export const MAX_JWS_BYTES = 16 * 1024;
|
|
34
|
+
export const MAX_ENVELOPE_BYTES = 64 * 1024;
|
|
35
|
+
const DAY = 24 * 3600;
|
|
36
|
+
const CERT_MAX_TTL = 90 * DAY;
|
|
37
|
+
const CAP_MAX_TTL = 90 * DAY;
|
|
38
|
+
const SKEW = 300;
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
// Temporary helpers. TODO(phase2-wire): replace with core/v3's b32, userId and
|
|
41
|
+
// did derivations so there is exactly one implementation of each.
|
|
42
|
+
const B32 = "abcdefghijklmnopqrstuvwxyz234567";
|
|
43
|
+
/** RFC 4648 base32, lowercase, no padding (§1). */
|
|
44
|
+
export function b32Encode(bytes) {
|
|
45
|
+
let out = "";
|
|
46
|
+
let bits = 0;
|
|
47
|
+
let acc = 0;
|
|
48
|
+
for (const b of bytes) {
|
|
49
|
+
acc = (acc << 8) | b;
|
|
50
|
+
bits += 8;
|
|
51
|
+
while (bits >= 5) {
|
|
52
|
+
out += B32[(acc >>> (bits - 5)) & 31];
|
|
53
|
+
bits -= 5;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (bits > 0)
|
|
57
|
+
out += B32[(acc << (5 - bits)) & 31];
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
const enc = new TextEncoder();
|
|
61
|
+
const utf8 = (s) => enc.encode(s);
|
|
62
|
+
/** `"p2p:" + b32(H(ik_pub))` (§2.1). */
|
|
63
|
+
export function userIdFromIk(ik) {
|
|
64
|
+
return `p2p:${b32Encode(sha256(ik))}`;
|
|
65
|
+
}
|
|
66
|
+
/** `"d_" + b32(H(spk))[:26]` (§2.3). */
|
|
67
|
+
export function didFromSpk(spk) {
|
|
68
|
+
return `d_${b32Encode(sha256(spk)).slice(0, 26)}`;
|
|
69
|
+
}
|
|
70
|
+
/** `jwsHash(j) = b64u(H(utf8(j)))` (§1). */
|
|
71
|
+
export function jwsHash(jws) {
|
|
72
|
+
return b64uEncode(sha256(utf8(jws)));
|
|
73
|
+
}
|
|
74
|
+
const USER_ID_RE = /^p2p:[a-z2-7]{52}$/;
|
|
75
|
+
const DID_RE = /^d_[a-z2-7]{26}$/;
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
// The adapter
|
|
78
|
+
function err(code, message) {
|
|
79
|
+
throw new RelayCryptoError(code, message);
|
|
80
|
+
}
|
|
81
|
+
/** Runs a core call and turns its P2PError (or anything else) into a RelayCryptoError. */
|
|
82
|
+
function guard(code, fn) {
|
|
83
|
+
try {
|
|
84
|
+
return fn();
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
if (e instanceof RelayCryptoError)
|
|
88
|
+
throw e;
|
|
89
|
+
const reason = e.reason;
|
|
90
|
+
if (reason === "bad-signature")
|
|
91
|
+
err("bad-signature");
|
|
92
|
+
if (reason === "small-order-key")
|
|
93
|
+
err("weak-key");
|
|
94
|
+
return err(code, e instanceof Error ? e.message : String(e));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function str(p, k) {
|
|
98
|
+
const v = p[k];
|
|
99
|
+
if (typeof v !== "string" || v === "")
|
|
100
|
+
err("malformed", `${k} must be a non-empty string`);
|
|
101
|
+
return v;
|
|
102
|
+
}
|
|
103
|
+
function int(p, k) {
|
|
104
|
+
const v = p[k];
|
|
105
|
+
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0)
|
|
106
|
+
err("malformed", `${k} must be a non-negative integer`);
|
|
107
|
+
return v;
|
|
108
|
+
}
|
|
109
|
+
function strArray(p, k, max) {
|
|
110
|
+
const v = p[k];
|
|
111
|
+
if (!Array.isArray(v) || v.length > max || !v.every((x) => typeof x === "string" && x !== "")) {
|
|
112
|
+
err("malformed", `${k} must be an array of at most ${max} strings`);
|
|
113
|
+
}
|
|
114
|
+
if (new Set(v).size !== v.length)
|
|
115
|
+
err("malformed", `${k} has duplicates`);
|
|
116
|
+
return v;
|
|
117
|
+
}
|
|
118
|
+
function key32(p, k) {
|
|
119
|
+
return guard("malformed", () => b64uDecode(str(p, k), 32));
|
|
120
|
+
}
|
|
121
|
+
/** Core's strict key checks (canonical, not small order, torsion-free), mapped to `weak-key`. */
|
|
122
|
+
function assertStrongEd25519(pk) {
|
|
123
|
+
guard("weak-key", () => assertStrongEd25519PublicKey(pk));
|
|
124
|
+
}
|
|
125
|
+
function assertStrongX25519(pk) {
|
|
126
|
+
guard("weak-key", () => assertStrongX25519PublicKey(pk));
|
|
127
|
+
}
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
// Native Ed25519 (F-2)
|
|
130
|
+
//
|
|
131
|
+
// Signature checks run in node:crypto (OpenSSL), about 10x faster than the
|
|
132
|
+
// pure-JS verifier. The strict RFC 8032 rules the relay relied on noble for
|
|
133
|
+
// are kept explicitly:
|
|
134
|
+
// - the public key was already checked by assertStrongEd25519 (canonical
|
|
135
|
+
// encoding, not small order, torsion-free) before any signature under it
|
|
136
|
+
// is verified: certs check ik/spk, identity docs check ik;
|
|
137
|
+
// - S must be canonical (S < L), checked here;
|
|
138
|
+
// - R must be canonical: OpenSSL compares the encoding of the recomputed R
|
|
139
|
+
// with the received bytes, and uses the cofactorless equation, so it is at
|
|
140
|
+
// least as strict as noble's zip215:false.
|
|
141
|
+
// A differential test checks native rejects everything noble-strict rejects.
|
|
142
|
+
const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
|
|
143
|
+
const ED25519_L = 2n ** 252n + 27742317777372353535851937790883648493n;
|
|
144
|
+
const KEY_CACHE_SIZE = 4096;
|
|
145
|
+
const keyObjects = new Map();
|
|
146
|
+
function ed25519KeyObject(pk) {
|
|
147
|
+
const id = Buffer.from(pk).toString("base64url");
|
|
148
|
+
let k = keyObjects.get(id);
|
|
149
|
+
if (k) {
|
|
150
|
+
keyObjects.delete(id);
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
k = createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, pk]), format: "der", type: "spki" });
|
|
154
|
+
if (keyObjects.size >= KEY_CACHE_SIZE)
|
|
155
|
+
keyObjects.delete(keyObjects.keys().next().value);
|
|
156
|
+
}
|
|
157
|
+
keyObjects.set(id, k);
|
|
158
|
+
return k;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Messages up to this size are verified natively. Node copies the whole
|
|
162
|
+
* message into a native buffer for every one-shot verify; for large inputs
|
|
163
|
+
* (envelopes approach 64 KiB) that churn grew the relay's RSS by 20-40 MB
|
|
164
|
+
* under a flood of large envelopes (resilience #7), so they use core's strict
|
|
165
|
+
* pure-JS verifier instead. Hot traffic (statuses, messages, caps, certs,
|
|
166
|
+
* auth) is far below this.
|
|
167
|
+
*/
|
|
168
|
+
export const NATIVE_VERIFY_MAX_BYTES = 16 * 1024;
|
|
169
|
+
/** Strict Ed25519 verification: native up to NATIVE_VERIFY_MAX_BYTES, core's noble-strict above. */
|
|
170
|
+
export function ed25519VerifyStrict(sig, msg, pk) {
|
|
171
|
+
return msg.length <= NATIVE_VERIFY_MAX_BYTES ? ed25519VerifyNative(sig, msg, pk) : ed25519VerifyNoble(sig, msg, pk);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Strict Ed25519 verification with native crypto. `pk` must already have
|
|
175
|
+
* passed assertStrongEd25519.
|
|
176
|
+
*/
|
|
177
|
+
export function ed25519VerifyNative(sig, msg, pk) {
|
|
178
|
+
if (sig.length !== 64 || pk.length !== 32)
|
|
179
|
+
return false;
|
|
180
|
+
let s = 0n;
|
|
181
|
+
for (let i = 63; i >= 32; i--)
|
|
182
|
+
s = (s << 8n) | BigInt(sig[i]);
|
|
183
|
+
if (s >= ED25519_L)
|
|
184
|
+
return false;
|
|
185
|
+
try {
|
|
186
|
+
return nodeVerify(null, msg, ed25519KeyObject(pk), sig);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** Structural decode (core), typ/kid checks, then the native signature check over the exact bytes. */
|
|
193
|
+
function verifyJwsNative(jws, typ, kid, pk, maxBytes = MAX_JWS_BYTES) {
|
|
194
|
+
const d = guard("malformed", () => decodeJws(jws, maxBytes));
|
|
195
|
+
if (d.header.typ !== typ)
|
|
196
|
+
err("malformed", `typ ${d.header.typ} != ${typ}`);
|
|
197
|
+
if (d.header.kid !== kid)
|
|
198
|
+
err("mismatch", "kid mismatch");
|
|
199
|
+
if (!ed25519VerifyStrict(d.signature, d.signingInput, pk))
|
|
200
|
+
err("bad-signature");
|
|
201
|
+
return d;
|
|
202
|
+
}
|
|
203
|
+
function checkTimes(iat, exp, maxTtl, now) {
|
|
204
|
+
if (exp > iat + maxTtl)
|
|
205
|
+
err("malformed", "lifetime too long");
|
|
206
|
+
if (exp <= iat)
|
|
207
|
+
err("malformed", "exp before iat");
|
|
208
|
+
if (iat > now + SKEW)
|
|
209
|
+
err("not-yet-valid");
|
|
210
|
+
if (now >= exp)
|
|
211
|
+
err("expired");
|
|
212
|
+
}
|
|
213
|
+
function decode(jws, typ, maxBytes) {
|
|
214
|
+
if (typeof jws !== "string")
|
|
215
|
+
err("malformed", "JWS must be a string");
|
|
216
|
+
if (jws.length > maxBytes)
|
|
217
|
+
err("too-large");
|
|
218
|
+
const d = guard("malformed", () => decodeJws(jws, maxBytes));
|
|
219
|
+
if (d.header.typ !== typ)
|
|
220
|
+
err("malformed", `typ ${d.header.typ} != ${typ}`);
|
|
221
|
+
return d;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The crit rule (docs/compatibility.md): a field the relay doesn't know is ignored unless the object
|
|
225
|
+
* lists it in `crit`, and then the object is refused. The relay's own parsers below read only the
|
|
226
|
+
* fields they know, so this is the whole of it: an issuer that adds a field restricting what a cap,
|
|
227
|
+
* cert or envelope allows lists it in `crit`, and this relay refuses rather than allow more.
|
|
228
|
+
*/
|
|
229
|
+
const CRIT_FIELD_RE = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
|
|
230
|
+
export function relayCritCheck(p, known, what) {
|
|
231
|
+
if (!Object.prototype.hasOwnProperty.call(p, "crit"))
|
|
232
|
+
return;
|
|
233
|
+
const crit = p.crit;
|
|
234
|
+
// core's checkFields shape: 1-16 distinct names, each a field the object itself carries, never `crit`.
|
|
235
|
+
if (!Array.isArray(crit) || crit.length === 0 || crit.length > 16 || crit.some((c) => typeof c !== "string" || !CRIT_FIELD_RE.test(c)) || new Set(crit).size !== crit.length) {
|
|
236
|
+
err("malformed", `${what}.crit must be 1-16 distinct field names`);
|
|
237
|
+
}
|
|
238
|
+
for (const c of crit) {
|
|
239
|
+
if (c === "crit" || !Object.prototype.hasOwnProperty.call(p, c))
|
|
240
|
+
err("malformed", `${what}.crit names ${c}, which it doesn't carry`);
|
|
241
|
+
if (!known.includes(c))
|
|
242
|
+
err("unsupported-critical", `${what}: critical field ${c} isn't understood`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const CERT_FIELDS = ["iss", "ik", "did", "spk", "kpk", "label", "iat", "exp"];
|
|
246
|
+
const CAP_FIELDS = ["iss", "sub", "cert", "capid", "relays", "kinds", "iat", "exp", "uses"];
|
|
247
|
+
const ENVELOPE_FIELDS = ["v", "from", "fdid", "fcert", "to", "tdid", "own", "sid", "seq", "ts", "n", "epk", "ct", "kind"];
|
|
248
|
+
export function createRelayCrypto(opts = {}) {
|
|
249
|
+
const cacheSize = opts.certCacheSize ?? 10_000;
|
|
250
|
+
/** LRU (Map insertion order) of verified certs. Only successes are cached. */
|
|
251
|
+
const certCache = new Map();
|
|
252
|
+
/** LRU of caps whose stateless checks passed (F-2). Only successes are cached. */
|
|
253
|
+
const capCache = new Map();
|
|
254
|
+
/** §2.3 rules 1–5, no cache. */
|
|
255
|
+
function verifyDeviceCertUncached(jws, opts) {
|
|
256
|
+
// TODO(phase2-wire): core/v3 verifyDeviceCertV3(jws, {now}); keep the cache in front of it.
|
|
257
|
+
const d = decode(jws, TYP_DEVICE, MAX_JWS_BYTES);
|
|
258
|
+
if (d.header.kid !== "ik")
|
|
259
|
+
err("malformed", "device cert kid must be ik");
|
|
260
|
+
const p = d.payload;
|
|
261
|
+
relayCritCheck(p, CERT_FIELDS, "device cert");
|
|
262
|
+
const ik = key32(p, "ik");
|
|
263
|
+
const spk = key32(p, "spk");
|
|
264
|
+
const kpk = key32(p, "kpk");
|
|
265
|
+
const iss = str(p, "iss");
|
|
266
|
+
const did = str(p, "did");
|
|
267
|
+
const iat = int(p, "iat");
|
|
268
|
+
const exp = int(p, "exp");
|
|
269
|
+
if ("label" in p && typeof p.label !== "string")
|
|
270
|
+
err("malformed", "label must be a string");
|
|
271
|
+
// Rule 4 before any signature work.
|
|
272
|
+
assertStrongEd25519(ik);
|
|
273
|
+
assertStrongEd25519(spk);
|
|
274
|
+
assertStrongX25519(kpk);
|
|
275
|
+
// Rule 1.
|
|
276
|
+
if (iss !== userIdFromIk(ik))
|
|
277
|
+
err("mismatch", "iss != H(ik)");
|
|
278
|
+
// Rule 2.
|
|
279
|
+
verifyJwsNative(jws, TYP_DEVICE, "ik", ik);
|
|
280
|
+
// Rule 3.
|
|
281
|
+
if (did !== didFromSpk(spk))
|
|
282
|
+
err("mismatch", "did != H(spk)");
|
|
283
|
+
// Rule 5.
|
|
284
|
+
checkTimes(iat, exp, CERT_MAX_TTL, opts.now);
|
|
285
|
+
return { jws, iss, did, spk, iat, exp };
|
|
286
|
+
}
|
|
287
|
+
/** The stateless part of a cap check: parse, cert (rules 1–5), signature. */
|
|
288
|
+
function capCrypto(capJws, now) {
|
|
289
|
+
const d = decode(capJws, TYP_CAP, MAX_JWS_BYTES);
|
|
290
|
+
const p = d.payload;
|
|
291
|
+
relayCritCheck(p, CAP_FIELDS, "cap");
|
|
292
|
+
const cert = self.verifyDeviceCert(str(p, "cert"), { now });
|
|
293
|
+
if (cert.did !== d.header.kid)
|
|
294
|
+
err("mismatch", "cap kid != cert.did");
|
|
295
|
+
const cap = {
|
|
296
|
+
iss: str(p, "iss"),
|
|
297
|
+
signerDid: cert.did,
|
|
298
|
+
sub: str(p, "sub"),
|
|
299
|
+
capid: str(p, "capid"),
|
|
300
|
+
relays: strArray(p, "relays", 16),
|
|
301
|
+
kinds: strArray(p, "kinds", 16),
|
|
302
|
+
iat: int(p, "iat"),
|
|
303
|
+
exp: int(p, "exp"),
|
|
304
|
+
};
|
|
305
|
+
guard("malformed", () => b64uDecode(cap.capid, 16));
|
|
306
|
+
if ("uses" in p) {
|
|
307
|
+
const uses = int(p, "uses");
|
|
308
|
+
if (uses < 1)
|
|
309
|
+
err("malformed", "uses must be positive");
|
|
310
|
+
cap.uses = uses;
|
|
311
|
+
}
|
|
312
|
+
if (cert.iss !== cap.iss)
|
|
313
|
+
err("mismatch", "cap cert.iss != cap.iss");
|
|
314
|
+
verifyJwsNative(capJws, TYP_CAP, cert.did, cert.spk);
|
|
315
|
+
// The cap's own lifetime shape (exp ≤ iat + 90 d) is stateless; the clock check runs per send.
|
|
316
|
+
if (cap.exp > cap.iat + CAP_MAX_TTL || cap.exp <= cap.iat)
|
|
317
|
+
err("malformed", "bad cap lifetime");
|
|
318
|
+
return { cap, certIat: cert.iat, certExp: cert.exp };
|
|
319
|
+
}
|
|
320
|
+
const self = {
|
|
321
|
+
canonicalRelayUrl(url) {
|
|
322
|
+
// TODO(phase2-wire): core/v3 canonicalRelayUrl.
|
|
323
|
+
let u;
|
|
324
|
+
try {
|
|
325
|
+
u = new URL(url);
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
return err("malformed", "not a URL");
|
|
329
|
+
}
|
|
330
|
+
if (u.protocol !== "wss:")
|
|
331
|
+
err("malformed", "relay URLs use wss");
|
|
332
|
+
if (u.username || u.password || u.search || u.hash || url.includes("?") || url.includes("#")) {
|
|
333
|
+
err("malformed", "relay URLs carry no credentials, query or fragment");
|
|
334
|
+
}
|
|
335
|
+
if (u.hostname === "")
|
|
336
|
+
err("malformed", "missing host");
|
|
337
|
+
// WHATWG URL lowercases the host, converts it to an IDNA A-label and
|
|
338
|
+
// drops the scheme's default port (443 for wss).
|
|
339
|
+
let path = u.pathname;
|
|
340
|
+
if (path === "" || path === "/")
|
|
341
|
+
path = "/v3";
|
|
342
|
+
else if (path.endsWith("/"))
|
|
343
|
+
path = path.slice(0, -1);
|
|
344
|
+
return `wss://${u.host}${path}`;
|
|
345
|
+
},
|
|
346
|
+
relayAuthMessage(relay, nonce) {
|
|
347
|
+
return utf8(`p2p/v3/relay-auth|${relay}|${nonce}`);
|
|
348
|
+
},
|
|
349
|
+
verifyRelayAuth(cert, relay, nonce, sig) {
|
|
350
|
+
// TODO(phase2-wire): core/v3's relay-auth verification.
|
|
351
|
+
let s;
|
|
352
|
+
try {
|
|
353
|
+
s = b64uDecode(sig, 64);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
return ed25519VerifyStrict(s, self.relayAuthMessage(relay, nonce), cert.spk);
|
|
359
|
+
},
|
|
360
|
+
verifyDeviceCert(jws, opts) {
|
|
361
|
+
if (typeof jws === "string" && jws.length <= MAX_JWS_BYTES && cacheSize > 0) {
|
|
362
|
+
const key = jwsHash(jws);
|
|
363
|
+
const hit = certCache.get(key);
|
|
364
|
+
if (hit) {
|
|
365
|
+
// Rule 5 again: a cached cert still expires on time.
|
|
366
|
+
checkTimes(hit.iat, hit.exp, CERT_MAX_TTL, opts.now);
|
|
367
|
+
certCache.delete(key);
|
|
368
|
+
certCache.set(key, hit);
|
|
369
|
+
return hit;
|
|
370
|
+
}
|
|
371
|
+
const v = verifyDeviceCertUncached(jws, opts);
|
|
372
|
+
certCache.set(key, v);
|
|
373
|
+
if (certCache.size > cacheSize)
|
|
374
|
+
certCache.delete(certCache.keys().next().value);
|
|
375
|
+
return v;
|
|
376
|
+
}
|
|
377
|
+
return verifyDeviceCertUncached(jws, opts);
|
|
378
|
+
},
|
|
379
|
+
parseOuterEnvelope(jws) {
|
|
380
|
+
// TODO(phase2-wire): core/v3 parseOuterEnvelope.
|
|
381
|
+
const d = decode(jws, TYP_MSG, MAX_ENVELOPE_BYTES);
|
|
382
|
+
const p = d.payload;
|
|
383
|
+
if (p.v !== 3)
|
|
384
|
+
err("malformed", "envelope v must be 3");
|
|
385
|
+
relayCritCheck(p, ENVELOPE_FIELDS, "envelope");
|
|
386
|
+
const env = {
|
|
387
|
+
jws,
|
|
388
|
+
bytes: utf8(jws),
|
|
389
|
+
v: 3,
|
|
390
|
+
from: str(p, "from"),
|
|
391
|
+
fdid: str(p, "fdid"),
|
|
392
|
+
fcert: str(p, "fcert"),
|
|
393
|
+
to: str(p, "to"),
|
|
394
|
+
tdid: str(p, "tdid"),
|
|
395
|
+
kind: str(p, "kind"),
|
|
396
|
+
kid: d.header.kid,
|
|
397
|
+
};
|
|
398
|
+
if (!self.isUserId(env.from) || !self.isUserId(env.to))
|
|
399
|
+
err("malformed", "bad userId");
|
|
400
|
+
if (!self.isDeviceId(env.fdid) || !self.isDeviceId(env.tdid))
|
|
401
|
+
err("malformed", "bad device id");
|
|
402
|
+
return env;
|
|
403
|
+
},
|
|
404
|
+
verifyEnvelope(env, fcert) {
|
|
405
|
+
// TODO(phase2-wire): core/v3's outer-envelope signature check against fcert.
|
|
406
|
+
if (fcert.iss !== env.from)
|
|
407
|
+
err("mismatch", "fcert.iss != from");
|
|
408
|
+
if (fcert.did !== env.fdid || env.kid !== env.fdid)
|
|
409
|
+
err("mismatch", "fcert.did, fdid and kid differ");
|
|
410
|
+
verifyJwsNative(env.jws, TYP_MSG, env.fdid, fcert.spk, MAX_ENVELOPE_BYTES);
|
|
411
|
+
},
|
|
412
|
+
verifyCapForSend(capJws, ctx) {
|
|
413
|
+
// TODO(phase2-wire): core/v3 verifyCapForSend(cap, {relayUrl, to, envFrom, kind, now}); keep the cache in front.
|
|
414
|
+
// F-2: the stateless crypto result (parse, cert, signature) is cached by
|
|
415
|
+
// JWS hash. Times and the per-send context are checked on every call;
|
|
416
|
+
// revocation, `uses` and the allowlist are the relay's, on every send.
|
|
417
|
+
const key = cacheSize > 0 && typeof capJws === "string" && capJws.length <= MAX_JWS_BYTES ? jwsHash(capJws) : undefined;
|
|
418
|
+
let entry = key !== undefined ? capCache.get(key) : undefined;
|
|
419
|
+
if (entry) {
|
|
420
|
+
// Rule 5 for the cap's cert, again on every send.
|
|
421
|
+
checkTimes(entry.certIat, entry.certExp, CERT_MAX_TTL, ctx.now);
|
|
422
|
+
capCache.delete(key);
|
|
423
|
+
}
|
|
424
|
+
else {
|
|
425
|
+
entry = capCrypto(capJws, ctx.now);
|
|
426
|
+
if (key !== undefined && capCache.size >= cacheSize)
|
|
427
|
+
capCache.delete(capCache.keys().next().value);
|
|
428
|
+
}
|
|
429
|
+
if (key !== undefined)
|
|
430
|
+
capCache.set(key, entry);
|
|
431
|
+
const cap = entry.cap;
|
|
432
|
+
if (cap.iss !== ctx.to)
|
|
433
|
+
err("not-allowed", "cap.iss != to");
|
|
434
|
+
if (cap.sub !== "*" && cap.sub !== ctx.envFrom)
|
|
435
|
+
err("not-allowed", "cap.sub");
|
|
436
|
+
if (!cap.relays.includes(ctx.relayUrl))
|
|
437
|
+
err("not-allowed", "relay not in cap.relays");
|
|
438
|
+
if (!cap.kinds.includes("*") && !cap.kinds.includes(ctx.kind))
|
|
439
|
+
err("not-allowed", "kind not in cap.kinds");
|
|
440
|
+
checkTimes(cap.iat, cap.exp, CAP_MAX_TTL, ctx.now);
|
|
441
|
+
return { ...cap, relays: [...cap.relays], kinds: [...cap.kinds] };
|
|
442
|
+
},
|
|
443
|
+
powOk(envBytes, powNonce, bits) {
|
|
444
|
+
// TODO(phase2-wire): core/v3 powOk.
|
|
445
|
+
if (bits <= 0)
|
|
446
|
+
return true;
|
|
447
|
+
const buf = new Uint8Array(envBytes.length + powNonce.length);
|
|
448
|
+
buf.set(envBytes, 0);
|
|
449
|
+
buf.set(powNonce, envBytes.length);
|
|
450
|
+
const h = sha256(buf);
|
|
451
|
+
let remaining = bits;
|
|
452
|
+
for (const byte of h) {
|
|
453
|
+
if (remaining <= 0)
|
|
454
|
+
return true;
|
|
455
|
+
if (remaining >= 8) {
|
|
456
|
+
if (byte !== 0)
|
|
457
|
+
return false;
|
|
458
|
+
remaining -= 8;
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
return byte >> (8 - remaining) === 0;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return remaining <= 0;
|
|
465
|
+
},
|
|
466
|
+
parseIdentityDoc(jws) {
|
|
467
|
+
// core/v3: typ, kid, the full payload rules (keyholders ⊆ devices, `by` a key
|
|
468
|
+
// holder, canonical relays, lifetime), small-order ik, iss == H(ik), signature.
|
|
469
|
+
if (typeof jws !== "string")
|
|
470
|
+
err("malformed", "JWS must be a string");
|
|
471
|
+
if (jws.length > MAX_JWS_BYTES)
|
|
472
|
+
err("too-large");
|
|
473
|
+
const d = guard("malformed", () => verifyIdentityDocSignature(jws));
|
|
474
|
+
const doc = {
|
|
475
|
+
jws,
|
|
476
|
+
hash: d.hash,
|
|
477
|
+
iss: d.iss,
|
|
478
|
+
ver: d.ver,
|
|
479
|
+
prev: d.prev,
|
|
480
|
+
relays: d.relays,
|
|
481
|
+
devices: d.devices,
|
|
482
|
+
keyholders: d.keyholders,
|
|
483
|
+
iat: d.iat,
|
|
484
|
+
exp: d.exp,
|
|
485
|
+
};
|
|
486
|
+
if (d.merge !== undefined)
|
|
487
|
+
doc.merge = d.merge;
|
|
488
|
+
return doc;
|
|
489
|
+
},
|
|
490
|
+
verifyIdentityDocLink(prev, doc, merge) {
|
|
491
|
+
// core/v3 verifyIdentityDocLink: chain, merge shape, devices and keyholders
|
|
492
|
+
// only shrink in a merge. Time checks are the relay's own (iat skew), so
|
|
493
|
+
// `now` is the document's iat.
|
|
494
|
+
if (doc.merge === undefined && merge !== undefined)
|
|
495
|
+
err("bad-link", "unexpected merge parent");
|
|
496
|
+
guard("bad-link", () => coreVerifyIdentityDocLink(prev.jws, doc.jws, { now: doc.iat, ...(merge ? { merge: merge.jws } : {}) }));
|
|
497
|
+
},
|
|
498
|
+
isUserId(s) {
|
|
499
|
+
return typeof s === "string" && USER_ID_RE.test(s);
|
|
500
|
+
},
|
|
501
|
+
isDeviceId(s) {
|
|
502
|
+
return typeof s === "string" && DID_RE.test(s);
|
|
503
|
+
},
|
|
504
|
+
};
|
|
505
|
+
return self;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Test double: the real adapter with any methods replaced. Lets a test force
|
|
509
|
+
* one crypto outcome (a cap that "verifies", a PoW that always passes) without
|
|
510
|
+
* minting objects, and proves the relay reaches crypto only through this seam.
|
|
511
|
+
*/
|
|
512
|
+
export function testRelayCrypto(overrides = {}) {
|
|
513
|
+
return { ...createRelayCrypto(), ...overrides };
|
|
514
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { RelayCrypto } from "./crypto.js";
|
|
2
|
+
import { type IdentityIndex, type Store, type StoredIdentityDoc } from "./store.js";
|
|
3
|
+
export type PublishResult = {
|
|
4
|
+
ok: true;
|
|
5
|
+
duplicate: boolean;
|
|
6
|
+
left?: boolean;
|
|
7
|
+
} | {
|
|
8
|
+
ok: false;
|
|
9
|
+
code: "bad-identity" | "identity-gap" | "forbidden" | "too-large" | "full";
|
|
10
|
+
};
|
|
11
|
+
export interface IdentityLimits {
|
|
12
|
+
maxTips: number;
|
|
13
|
+
maxVersions: number;
|
|
14
|
+
/** Seconds a head may be expired before the userId is tombstoned. */
|
|
15
|
+
expiredRetentionSec: number;
|
|
16
|
+
/** Seconds a tombstone is kept. */
|
|
17
|
+
tombstoneRetentionSec: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Builds the index of a userId from its full set of held documents. With a
|
|
21
|
+
* `cap`, the allowlist is intersected with it.
|
|
22
|
+
*/
|
|
23
|
+
export declare function buildIndex(iss: string, docs: readonly StoredIdentityDoc[], cap?: string[] | null): IdentityIndex | undefined;
|
|
24
|
+
export declare class IdentityService {
|
|
25
|
+
private readonly store;
|
|
26
|
+
private readonly crypto;
|
|
27
|
+
private readonly relayUrl;
|
|
28
|
+
private readonly now;
|
|
29
|
+
private readonly limits;
|
|
30
|
+
constructor(store: Store, crypto: RelayCrypto, relayUrl: string, now: () => number, limits: IdentityLimits);
|
|
31
|
+
/** How long dids of discarded history are remembered (the tombstone window, > 90-day certificates). */
|
|
32
|
+
private get seenWindowMs();
|
|
33
|
+
/** Every did any held version of `iss` lists. */
|
|
34
|
+
private heldDids;
|
|
35
|
+
/**
|
|
36
|
+
* Dids that were listed and aren't in the current allowlist: refused even a
|
|
37
|
+
* restricted connection (H1). A restore always brings a brand-new did, which
|
|
38
|
+
* isn't here. Bounded by the held versions (≤ maxVersions × 10) and the seen
|
|
39
|
+
* rows (91 days, capped).
|
|
40
|
+
*/
|
|
41
|
+
revoked(iss: string): Set<string>;
|
|
42
|
+
private reindex;
|
|
43
|
+
/** Deletes the documents of `iss` but keeps its allowlist and head version. */
|
|
44
|
+
private tombstone;
|
|
45
|
+
private chainsFrom;
|
|
46
|
+
/**
|
|
47
|
+
* N4/L-c: "owner left" only from the top of the held history: a document
|
|
48
|
+
* extending the ONLY tip, or a merge of every tip. During a fork, extending
|
|
49
|
+
* one branch says nothing about the others, which still list this relay.
|
|
50
|
+
*/
|
|
51
|
+
private chainsFromTop;
|
|
52
|
+
private mergesTwoTips;
|
|
53
|
+
publish(jws: unknown, publisherIss: string, opts?: {
|
|
54
|
+
topOnly?: boolean;
|
|
55
|
+
}): PublishResult;
|
|
56
|
+
/**
|
|
57
|
+
* §2.3 rule 6 as the relay applies it: undefined when the relay knows
|
|
58
|
+
* nothing of `iss`; otherwise the devices listed in EVERY tip (during a fork
|
|
59
|
+
* the intersection applies, §2.5), capped as above, or a tombstone's last
|
|
60
|
+
* allowlist.
|
|
61
|
+
*/
|
|
62
|
+
allowedDevices(iss: string): Set<string> | undefined;
|
|
63
|
+
/** The allowlist of `iss` and whether it is a tombstone; undefined when nothing is known. */
|
|
64
|
+
status(iss: string): {
|
|
65
|
+
allowed: Set<string>;
|
|
66
|
+
left: boolean;
|
|
67
|
+
} | undefined;
|
|
68
|
+
head(iss: string): StoredIdentityDoc | undefined;
|
|
69
|
+
/** Every tip, highest first. */
|
|
70
|
+
tips(iss: string): StoredIdentityDoc[];
|
|
71
|
+
/**
|
|
72
|
+
* Walks back from `to` along `prev`, and along `merge` for merge versions,
|
|
73
|
+
* returning at most `n` versions, highest first.
|
|
74
|
+
*/
|
|
75
|
+
chain(iss: string, to: string, n: number): StoredIdentityDoc[] | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Tombstones userIds whose head expired more than `expiredRetentionSec`
|
|
78
|
+
* ago, and deletes tombstones older than `tombstoneRetentionSec`.
|
|
79
|
+
*/
|
|
80
|
+
sweep(limit?: number): {
|
|
81
|
+
tombstoned: number;
|
|
82
|
+
deleted: number;
|
|
83
|
+
};
|
|
84
|
+
}
|