@peer2peer/relay 0.0.0-stage → 0.1.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/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/config.js
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Relay configuration: defaults (docs/protocol.md §5.4, §5.7), then an
|
|
4
|
+
// optional preset (RELAY_PRESET), then an optional JSON file (RELAY_CONFIG),
|
|
5
|
+
// then environment variables.
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
export const DEFAULT_LIMITS = Object.freeze({
|
|
8
|
+
frameBytes: 96 * 1024,
|
|
9
|
+
envelopeBytes: 64 * 1024,
|
|
10
|
+
mailboxEnvelopes: 10_000,
|
|
11
|
+
mailboxBytes: 64 * 1024 * 1024,
|
|
12
|
+
retentionSec: 7 * 24 * 3600,
|
|
13
|
+
sendsPerMinute: 120,
|
|
14
|
+
contactPerSenderPerHour: 60,
|
|
15
|
+
contactPerPairPerHour: 3,
|
|
16
|
+
contactPerIpPerHour: 120,
|
|
17
|
+
linkOpsPerIpPerMinute: 60,
|
|
18
|
+
linkTtlSec: 600,
|
|
19
|
+
linkReqEntries: 4,
|
|
20
|
+
linkEntryBytes: 16 * 1024,
|
|
21
|
+
linkOpenPerDevice: 4,
|
|
22
|
+
identityVersionRetentionSec: 90 * 24 * 3600,
|
|
23
|
+
chainMaxN: 64,
|
|
24
|
+
maxConnections: 10_000,
|
|
25
|
+
maxConnectionsPerIp: 64,
|
|
26
|
+
maxConnectionsPerIpv4: 512,
|
|
27
|
+
httpPerIpPerMinute: 600,
|
|
28
|
+
unauthTimeoutSec: 15,
|
|
29
|
+
maxUnauthConnections: 2_000,
|
|
30
|
+
maxConnectionsPerIss: 16,
|
|
31
|
+
restrictedPerIss: 2,
|
|
32
|
+
restrictedTimeoutSec: 60,
|
|
33
|
+
restrictedIdentityPerIssPerHour: 6,
|
|
34
|
+
framesPerConnPerMinute: 600,
|
|
35
|
+
sendBytesPerConnPerMinute: 8 * 1024 * 1024,
|
|
36
|
+
sendBytesPerIpPerMinute: 32 * 1024 * 1024,
|
|
37
|
+
storeMaxBytes: 4 * 1024 * 1024 * 1024,
|
|
38
|
+
storeHardMaxBytes: 5 * 1024 * 1024 * 1024,
|
|
39
|
+
recipientMaxBytes: 256 * 1024 * 1024,
|
|
40
|
+
sourceMaxBytes: 512 * 1024 * 1024,
|
|
41
|
+
sourceAcceptedBytesPerHour: 256 * 1024 * 1024,
|
|
42
|
+
maxUnauthPerIp: 8,
|
|
43
|
+
newDevicesPerIpPerDay: 50,
|
|
44
|
+
newDevicesPerIpv4PerDay: 1000,
|
|
45
|
+
connectsPerIpPerMinute: 120,
|
|
46
|
+
authsPerIpPerMinute: 60,
|
|
47
|
+
authsPerIpv4PerMinute: 600,
|
|
48
|
+
maxDevices: 1_000_000,
|
|
49
|
+
revokesPerConnPerMinute: 30,
|
|
50
|
+
revokesPerIssPerHour: 600,
|
|
51
|
+
deviceRetentionSec: 90 * 24 * 3600,
|
|
52
|
+
identityPublishPerIssPerHour: 30,
|
|
53
|
+
identityPublishPerIpPerHour: 120,
|
|
54
|
+
identityMaxTips: 4,
|
|
55
|
+
identityMaxVersions: 128,
|
|
56
|
+
identityExpiredRetentionSec: 90 * 24 * 3600,
|
|
57
|
+
identityTombstoneRetentionSec: 91 * 24 * 3600,
|
|
58
|
+
linkOpenPerIssPerHour: 20,
|
|
59
|
+
linkOpenPerIpPerHour: 60,
|
|
60
|
+
linkOpenPerIp: 8,
|
|
61
|
+
linkTotalBytes: 64 * 1024 * 1024,
|
|
62
|
+
inviteTtlMaxSec: 7 * 24 * 3600,
|
|
63
|
+
inviteBlobBytes: 32 * 1024,
|
|
64
|
+
invitePutPerIssPerHour: 20,
|
|
65
|
+
invitePutPerIpPerHour: 60,
|
|
66
|
+
inviteOpenPerIss: 20,
|
|
67
|
+
inviteTotalBytes: 256 * 1024 * 1024,
|
|
68
|
+
inviteBytesPerIp: 2 * 1024 * 1024,
|
|
69
|
+
inviteYoungIdentitySec: 24 * 3600,
|
|
70
|
+
inviteGetsPerIpPerMinute: 10,
|
|
71
|
+
inviteMissesPerIpPerHour: 30,
|
|
72
|
+
});
|
|
73
|
+
const MiB = 1024 * 1024;
|
|
74
|
+
/**
|
|
75
|
+
* Named presets that sit between DEFAULT_LIMITS and the JSON file / env vars.
|
|
76
|
+
* They only lower capacity limits; the protocol sizes (frames, envelopes,
|
|
77
|
+
* retention, link and invite formats) stay the protocol's.
|
|
78
|
+
*
|
|
79
|
+
* `small`: a private team relay (up to about 50 people) on a 2 GB single-board
|
|
80
|
+
* computer such as a Jetson Nano or a Raspberry Pi, with its database on a USB
|
|
81
|
+
* SSD. About 512 MiB of envelopes at most, a few hundred connections, and a
|
|
82
|
+
* smaller write-ahead log. Pair it with NODE_OPTIONS=--max-old-space-size=384
|
|
83
|
+
* and a container memory limit of 768 MiB (docs/run-a-relay-on-any-machine.md).
|
|
84
|
+
* Per-address limits are moderate: still far above what a 50-person team
|
|
85
|
+
* needs, but low enough that one outside address can't take every connection
|
|
86
|
+
* or fill the device table when the relay sits behind a public tunnel. An
|
|
87
|
+
* office behind one NAT address can raise them (docs/run-a-relay-on-any-machine.md).
|
|
88
|
+
*/
|
|
89
|
+
export const RELAY_PRESETS = Object.freeze({
|
|
90
|
+
small: Object.freeze({
|
|
91
|
+
limits: Object.freeze({
|
|
92
|
+
mailboxEnvelopes: 2_000,
|
|
93
|
+
mailboxBytes: 16 * MiB,
|
|
94
|
+
maxConnections: 400,
|
|
95
|
+
maxConnectionsPerIp: 64,
|
|
96
|
+
maxConnectionsPerIpv4: 64,
|
|
97
|
+
maxUnauthConnections: 100,
|
|
98
|
+
maxUnauthPerIp: 8,
|
|
99
|
+
sendBytesPerConnPerMinute: 4 * MiB,
|
|
100
|
+
sendBytesPerIpPerMinute: 16 * MiB,
|
|
101
|
+
storeMaxBytes: 448 * MiB,
|
|
102
|
+
storeHardMaxBytes: 512 * MiB,
|
|
103
|
+
recipientMaxBytes: 32 * MiB,
|
|
104
|
+
sourceMaxBytes: 256 * MiB,
|
|
105
|
+
sourceAcceptedBytesPerHour: 128 * MiB,
|
|
106
|
+
newDevicesPerIpPerDay: 100,
|
|
107
|
+
newDevicesPerIpv4PerDay: 100,
|
|
108
|
+
authsPerIpPerMinute: 60,
|
|
109
|
+
authsPerIpv4PerMinute: 60,
|
|
110
|
+
maxDevices: 10_000,
|
|
111
|
+
linkTotalBytes: 8 * MiB,
|
|
112
|
+
inviteTotalBytes: 16 * MiB,
|
|
113
|
+
}),
|
|
114
|
+
storage: Object.freeze({
|
|
115
|
+
walLimitBytes: 64 * MiB,
|
|
116
|
+
journalSizeLimitBytes: 16 * MiB,
|
|
117
|
+
checkpointIntervalMs: 500,
|
|
118
|
+
}),
|
|
119
|
+
}),
|
|
120
|
+
});
|
|
121
|
+
/** Members-only: a redeemed invite admits its redeemer for 7 days unless the list or circle does first. */
|
|
122
|
+
export const DEFAULT_INVITE_ADMIT_SEC = 7 * 24 * 3600;
|
|
123
|
+
const LEVELS = ["debug", "info", "warn", "error"];
|
|
124
|
+
/** `contactPerPairPerHour` → `LIMIT_CONTACT_PER_PAIR_PER_HOUR`. */
|
|
125
|
+
export function limitEnvName(key) {
|
|
126
|
+
return `LIMIT_${key.replace(/([A-Z])/g, "_$1").toUpperCase()}`;
|
|
127
|
+
}
|
|
128
|
+
function intIn(name, raw, min, max) {
|
|
129
|
+
const n = typeof raw === "string" ? Number(raw.trim()) : raw;
|
|
130
|
+
if (typeof n !== "number" || !Number.isSafeInteger(n) || n < min || n > max) {
|
|
131
|
+
throw new Error(`config: ${name} must be an integer in [${min}, ${max}]`);
|
|
132
|
+
}
|
|
133
|
+
return n;
|
|
134
|
+
}
|
|
135
|
+
/** TRUST_PROXY: a hop count; true/yes/on mean 1, false/no/off/empty mean 0. */
|
|
136
|
+
function proxyHops(raw) {
|
|
137
|
+
if (typeof raw === "boolean")
|
|
138
|
+
return raw ? 1 : 0;
|
|
139
|
+
if (typeof raw === "string") {
|
|
140
|
+
const v = raw.trim().toLowerCase();
|
|
141
|
+
if (/^(true|yes|on)$/.test(v))
|
|
142
|
+
return 1;
|
|
143
|
+
if (v === "" || /^(false|no|off)$/.test(v))
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
return intIn("TRUST_PROXY", raw, 0, 16);
|
|
147
|
+
}
|
|
148
|
+
/** DEBUG_STATS: 1/true/yes/on enable it; anything else (or unset) leaves it off. */
|
|
149
|
+
function flag(raw) {
|
|
150
|
+
if (typeof raw === "boolean")
|
|
151
|
+
return raw;
|
|
152
|
+
return typeof raw === "string" && /^(1|true|yes|on)$/i.test(raw.trim());
|
|
153
|
+
}
|
|
154
|
+
/** METRICS_PORT: a port, or off/none/false to disable the metrics listener. */
|
|
155
|
+
function metricsPort(raw) {
|
|
156
|
+
if (raw === null || (typeof raw === "string" && /^(off|none|false|)$/i.test(raw.trim())))
|
|
157
|
+
return null;
|
|
158
|
+
return intIn("METRICS_PORT", raw, 0, 65535);
|
|
159
|
+
}
|
|
160
|
+
const ALLOW_SPLIT = /[\s,]+/;
|
|
161
|
+
const CIRCLE_ID_RE = /^c_[a-z2-7]{26}$/;
|
|
162
|
+
/**
|
|
163
|
+
* The text of an allow file: one userId per line, blank lines and `#`
|
|
164
|
+
* comments ignored. A line `!<userId>` denies that userId (never admitted,
|
|
165
|
+
* whatever the list, the circle or an invite says).
|
|
166
|
+
*/
|
|
167
|
+
export function parseAllowFile(text) {
|
|
168
|
+
const ids = text
|
|
169
|
+
.split("\n")
|
|
170
|
+
.map((l) => l.replace(/#.*$/, "").trim())
|
|
171
|
+
.filter((l) => l !== "")
|
|
172
|
+
.flatMap((l) => l.split(ALLOW_SPLIT));
|
|
173
|
+
return { allow: ids.filter((x) => !x.startsWith("!")), deny: ids.filter((x) => x.startsWith("!")).map((x) => x.slice(1)) };
|
|
174
|
+
}
|
|
175
|
+
function allowList(crypto, sources) {
|
|
176
|
+
let out;
|
|
177
|
+
for (const { name, ids } of sources) {
|
|
178
|
+
if (ids === undefined)
|
|
179
|
+
continue;
|
|
180
|
+
const list = typeof ids === "string" ? ids.split(ALLOW_SPLIT).filter((x) => x !== "") : ids;
|
|
181
|
+
if (!Array.isArray(list))
|
|
182
|
+
throw new Error(`config: ${name} must be a list of userIds`);
|
|
183
|
+
out ??= new Set();
|
|
184
|
+
for (const u of list) {
|
|
185
|
+
if (!crypto.isUserId(u))
|
|
186
|
+
throw new Error(`config: ${name}: ${String(u).slice(0, 80)} is not a full userId`);
|
|
187
|
+
out.add(u);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return out ? [...out] : undefined;
|
|
191
|
+
}
|
|
192
|
+
/** StorageTuning field → env var. */
|
|
193
|
+
const STORAGE_ENV = {
|
|
194
|
+
walLimitBytes: { env: "SQLITE_WAL_LIMIT_BYTES", min: 1 * MiB, max: Number.MAX_SAFE_INTEGER },
|
|
195
|
+
journalSizeLimitBytes: { env: "SQLITE_JOURNAL_SIZE_LIMIT_BYTES", min: 0, max: Number.MAX_SAFE_INTEGER },
|
|
196
|
+
// Capped at 10 s: a longer interval lets the WAL grow unchecked between passes on a busy relay.
|
|
197
|
+
checkpointIntervalMs: { env: "SQLITE_CHECKPOINT_INTERVAL_MS", min: 10, max: 10_000 },
|
|
198
|
+
};
|
|
199
|
+
function presetName(raw) {
|
|
200
|
+
if (raw === undefined || raw === null)
|
|
201
|
+
return undefined;
|
|
202
|
+
const v = typeof raw === "string" ? raw.trim().toLowerCase() : raw;
|
|
203
|
+
if (v === "" || v === "default" || v === "none")
|
|
204
|
+
return undefined;
|
|
205
|
+
if (typeof v === "string" && Object.hasOwn(RELAY_PRESETS, v))
|
|
206
|
+
return v;
|
|
207
|
+
throw new Error(`config: RELAY_PRESET must be one of default, ${Object.keys(RELAY_PRESETS).join(", ")}`);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Builds the config from defaults, the RELAY_CONFIG JSON file and env vars
|
|
211
|
+
* (env wins). Throws with a readable message on any bad value.
|
|
212
|
+
*/
|
|
213
|
+
export function loadConfig(crypto, opts = {}) {
|
|
214
|
+
const env = opts.env ?? process.env;
|
|
215
|
+
const readFile = opts.readFile ?? ((p) => readFileSync(p, "utf8"));
|
|
216
|
+
let file = {};
|
|
217
|
+
if (env.RELAY_CONFIG) {
|
|
218
|
+
const parsed = JSON.parse(readFile(env.RELAY_CONFIG));
|
|
219
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
220
|
+
throw new Error("config: RELAY_CONFIG must hold a JSON object");
|
|
221
|
+
}
|
|
222
|
+
file = parsed;
|
|
223
|
+
}
|
|
224
|
+
const port = intIn("PORT", env.PORT ?? file.port ?? 8080, 0, 65535);
|
|
225
|
+
const rawUrl = env.RELAY_URL ?? file.relayUrl ?? `wss://localhost:${port === 0 ? 8080 : port}/v3`;
|
|
226
|
+
const relayUrl = crypto.canonicalRelayUrl(rawUrl);
|
|
227
|
+
const preset = presetName(env.RELAY_PRESET ?? file.preset);
|
|
228
|
+
const limits = { ...DEFAULT_LIMITS, ...(preset ? RELAY_PRESETS[preset].limits : {}) };
|
|
229
|
+
for (const key of Object.keys(DEFAULT_LIMITS)) {
|
|
230
|
+
const raw = env[limitEnvName(key)] ?? file.limits?.[key];
|
|
231
|
+
if (raw !== undefined)
|
|
232
|
+
limits[key] = intIn(key, raw, 0, Number.MAX_SAFE_INTEGER);
|
|
233
|
+
}
|
|
234
|
+
if (limits.storeHardMaxBytes < limits.storeMaxBytes) {
|
|
235
|
+
throw new Error("config: storeHardMaxBytes must be at least storeMaxBytes");
|
|
236
|
+
}
|
|
237
|
+
if (limits.frameBytes < limits.envelopeBytes + 1024) {
|
|
238
|
+
throw new Error("config: frameBytes must leave room for an envelope plus its send frame");
|
|
239
|
+
}
|
|
240
|
+
if (limits.frameBytes < limits.inviteBlobBytes + 1024) {
|
|
241
|
+
throw new Error("config: frameBytes must leave room for an invite blob plus its put frame");
|
|
242
|
+
}
|
|
243
|
+
const storage = { ...(preset ? RELAY_PRESETS[preset].storage : {}) };
|
|
244
|
+
for (const key of Object.keys(STORAGE_ENV)) {
|
|
245
|
+
const { env: name, min, max } = STORAGE_ENV[key];
|
|
246
|
+
const raw = env[name] ?? file.storage?.[key];
|
|
247
|
+
if (raw !== undefined)
|
|
248
|
+
storage[key] = intIn(name, raw, min, max);
|
|
249
|
+
}
|
|
250
|
+
const logLevel = (env.LOG_LEVEL ?? file.logLevel ?? "info");
|
|
251
|
+
if (!LEVELS.includes(logLevel))
|
|
252
|
+
throw new Error(`config: LOG_LEVEL must be one of ${LEVELS.join(", ")}`);
|
|
253
|
+
const cfg = {
|
|
254
|
+
relayUrl,
|
|
255
|
+
host: env.HOST ?? file.host ?? "0.0.0.0",
|
|
256
|
+
port,
|
|
257
|
+
dbPath: env.DB_PATH ?? file.dbPath ?? "./relay.db",
|
|
258
|
+
powBits: intIn("POW_BITS", env.POW_BITS ?? file.powBits ?? 0, 0, 24),
|
|
259
|
+
limits,
|
|
260
|
+
trustProxy: proxyHops(env.TRUST_PROXY ?? file.trustProxy ?? 0),
|
|
261
|
+
metricsPort: metricsPort(env.METRICS_PORT ?? (file.metricsPort === undefined ? 9464 : file.metricsPort)),
|
|
262
|
+
metricsHost: env.METRICS_HOST ?? file.metricsHost ?? "127.0.0.1",
|
|
263
|
+
logLevel,
|
|
264
|
+
sweepIntervalSec: intIn("SWEEP_INTERVAL_SEC", env.SWEEP_INTERVAL_SEC ?? file.sweepIntervalSec ?? 300, 1, 86400),
|
|
265
|
+
debugStats: flag(env.DEBUG_STATS ?? file.debugStats ?? false),
|
|
266
|
+
storage,
|
|
267
|
+
inviteAdmitSec: intIn("RELAY_INVITE_ADMIT_SEC", env.RELAY_INVITE_ADMIT_SEC ?? file.inviteAdmitSec ?? DEFAULT_INVITE_ADMIT_SEC, 0, 90 * 86400),
|
|
268
|
+
};
|
|
269
|
+
if (preset)
|
|
270
|
+
cfg.preset = preset;
|
|
271
|
+
const name = env.RELAY_NAME ?? file.name;
|
|
272
|
+
if (name)
|
|
273
|
+
cfg.name = name;
|
|
274
|
+
const contact = env.OPERATOR_CONTACT ?? file.operatorContact;
|
|
275
|
+
if (contact)
|
|
276
|
+
cfg.operatorContact = contact;
|
|
277
|
+
const policy = env.RELAY_POLICY ?? file.policy;
|
|
278
|
+
if (policy)
|
|
279
|
+
cfg.policy = policy;
|
|
280
|
+
const token = env.METRICS_TOKEN ?? file.metricsToken;
|
|
281
|
+
if (token)
|
|
282
|
+
cfg.metricsToken = token;
|
|
283
|
+
const allowFile = env.RELAY_ALLOW_FILE ?? file.allowFile;
|
|
284
|
+
if (allowFile)
|
|
285
|
+
cfg.allowFile = allowFile;
|
|
286
|
+
const fromFile = allowFile ? parseAllowFile(readFile(allowFile)) : undefined;
|
|
287
|
+
const allow = allowList(crypto, [
|
|
288
|
+
{ name: "RELAY_ALLOW", ids: env.RELAY_ALLOW ?? file.allow },
|
|
289
|
+
{ name: allowFile ?? "RELAY_ALLOW_FILE", ids: fromFile?.allow },
|
|
290
|
+
]);
|
|
291
|
+
if (allow)
|
|
292
|
+
cfg.allow = allow;
|
|
293
|
+
const deny = allowList(crypto, [
|
|
294
|
+
{ name: "RELAY_DENY", ids: env.RELAY_DENY ?? file.deny },
|
|
295
|
+
{ name: allowFile ?? "RELAY_ALLOW_FILE", ids: fromFile?.deny },
|
|
296
|
+
]);
|
|
297
|
+
if (deny && deny.length > 0)
|
|
298
|
+
cfg.deny = deny;
|
|
299
|
+
const circle = env.RELAY_ALLOW_CIRCLE ?? file.allowCircle;
|
|
300
|
+
if (circle) {
|
|
301
|
+
if (!CIRCLE_ID_RE.test(circle))
|
|
302
|
+
throw new Error("config: RELAY_ALLOW_CIRCLE must be a circle id (c_…)");
|
|
303
|
+
cfg.allowCircle = circle;
|
|
304
|
+
}
|
|
305
|
+
return cfg;
|
|
306
|
+
}
|
|
307
|
+
/** A config for tests and embedding: defaults plus overrides, no env or file. */
|
|
308
|
+
export function makeConfig(crypto, over = {}) {
|
|
309
|
+
const { limits, ...rest } = over;
|
|
310
|
+
return {
|
|
311
|
+
host: "127.0.0.1",
|
|
312
|
+
port: 0,
|
|
313
|
+
dbPath: ":memory:",
|
|
314
|
+
powBits: 0,
|
|
315
|
+
trustProxy: 0,
|
|
316
|
+
metricsPort: null,
|
|
317
|
+
metricsHost: "127.0.0.1",
|
|
318
|
+
logLevel: "info",
|
|
319
|
+
sweepIntervalSec: 300,
|
|
320
|
+
debugStats: false,
|
|
321
|
+
inviteAdmitSec: DEFAULT_INVITE_ADMIT_SEC,
|
|
322
|
+
...rest,
|
|
323
|
+
relayUrl: crypto.canonicalRelayUrl(rest.relayUrl ?? "wss://relay.test/v3"),
|
|
324
|
+
limits: { ...DEFAULT_LIMITS, ...limits },
|
|
325
|
+
};
|
|
326
|
+
}
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/** A device certificate that passed §2.3 rules 1–5. */
|
|
2
|
+
export interface VerifiedDeviceCert {
|
|
3
|
+
jws: string;
|
|
4
|
+
iss: string;
|
|
5
|
+
did: string;
|
|
6
|
+
/** Raw Ed25519 device signing key. */
|
|
7
|
+
spk: Uint8Array;
|
|
8
|
+
iat: number;
|
|
9
|
+
exp: number;
|
|
10
|
+
}
|
|
11
|
+
/** The outer, routing-visible fields of a `p2p-msg+jws` envelope (§4.1). Not yet signature-checked. */
|
|
12
|
+
export interface OuterEnvelope {
|
|
13
|
+
jws: string;
|
|
14
|
+
/** UTF-8 bytes of the compact JWS, exactly as received (the PoW input). */
|
|
15
|
+
bytes: Uint8Array;
|
|
16
|
+
v: number;
|
|
17
|
+
from: string;
|
|
18
|
+
fdid: string;
|
|
19
|
+
fcert: string;
|
|
20
|
+
to: string;
|
|
21
|
+
tdid: string;
|
|
22
|
+
kind: string;
|
|
23
|
+
/** The JWS header `kid`. */
|
|
24
|
+
kid: string;
|
|
25
|
+
}
|
|
26
|
+
/** A mailbox capability (§5.3) that passed every stateless check for one send. */
|
|
27
|
+
export interface VerifiedCap {
|
|
28
|
+
iss: string;
|
|
29
|
+
/** The did of the device that signed the cap (its `cert.did`). */
|
|
30
|
+
signerDid: string;
|
|
31
|
+
sub: string;
|
|
32
|
+
capid: string;
|
|
33
|
+
relays: string[];
|
|
34
|
+
kinds: string[];
|
|
35
|
+
iat: number;
|
|
36
|
+
exp: number;
|
|
37
|
+
uses?: number;
|
|
38
|
+
}
|
|
39
|
+
/** A self-signed identity document (§2.5) whose signature and shape verified. */
|
|
40
|
+
export interface IdentityDoc {
|
|
41
|
+
jws: string;
|
|
42
|
+
/** jwsHash(jws) = b64u(H(utf8(jws))). */
|
|
43
|
+
hash: string;
|
|
44
|
+
iss: string;
|
|
45
|
+
ver: number;
|
|
46
|
+
prev: string | null;
|
|
47
|
+
merge?: string;
|
|
48
|
+
relays: string[];
|
|
49
|
+
devices: string[];
|
|
50
|
+
keyholders: string[];
|
|
51
|
+
iat: number;
|
|
52
|
+
exp: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Codes a RelayCrypto method throws (as RelayCryptoError). The relay maps them
|
|
56
|
+
* onto its own wire codes and never forwards them, so they can be specific.
|
|
57
|
+
*/
|
|
58
|
+
export type RelayCryptoCode = "malformed" | "too-large" | "bad-signature" | "weak-key" | "expired" | "not-yet-valid" | "mismatch" | "not-allowed" | "bad-link" | "unsupported-critical";
|
|
59
|
+
export declare class RelayCryptoError extends Error {
|
|
60
|
+
readonly code: RelayCryptoCode;
|
|
61
|
+
constructor(code: RelayCryptoCode, message?: string);
|
|
62
|
+
}
|
|
63
|
+
export interface CapSendContext {
|
|
64
|
+
/** This relay's canonical URL. */
|
|
65
|
+
relayUrl: string;
|
|
66
|
+
/** `send.to`, the recipient userId. */
|
|
67
|
+
to: string;
|
|
68
|
+
/** `env.from`, already bound to a verified fcert. */
|
|
69
|
+
envFrom: string;
|
|
70
|
+
/** `env.kind`. */
|
|
71
|
+
kind: string;
|
|
72
|
+
/** Seconds since the epoch. */
|
|
73
|
+
now: number;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The seam between the relay and v3 cryptography. Methods throw
|
|
77
|
+
* RelayCryptoError on any failure unless they return a boolean.
|
|
78
|
+
* Times are seconds since the epoch, as on the wire.
|
|
79
|
+
*/
|
|
80
|
+
export interface RelayCrypto {
|
|
81
|
+
/** §5.1 canonical relay URL. Throws `malformed` when it can't be canonicalised. */
|
|
82
|
+
canonicalRelayUrl(url: string): string;
|
|
83
|
+
/** `utf8("p2p/v3/relay-auth|" + relay + "|" + nonce)` (§5.2). */
|
|
84
|
+
relayAuthMessage(relay: string, nonce: string): Uint8Array;
|
|
85
|
+
/** Checks `auth.sig` (b64u) under the certificate's `spk`. */
|
|
86
|
+
verifyRelayAuth(cert: VerifiedDeviceCert, relay: string, nonce: string, sig: string): boolean;
|
|
87
|
+
/**
|
|
88
|
+
* §2.3 rules 1–5. Rule 6 (the identity-document allowlist) is applied by the
|
|
89
|
+
* relay itself, because during a fork it is the intersection over every tip.
|
|
90
|
+
*/
|
|
91
|
+
verifyDeviceCert(jws: string, opts: {
|
|
92
|
+
now: number;
|
|
93
|
+
}): VerifiedDeviceCert;
|
|
94
|
+
/** §5.4 step 1: parse (≤ 64 KiB). No signature check. */
|
|
95
|
+
parseOuterEnvelope(jws: string): OuterEnvelope;
|
|
96
|
+
/** §5.4 step 2: binds `from`/`fdid`/`kid` to `fcert` and checks the JWS under `fcert.spk`. */
|
|
97
|
+
verifyEnvelope(env: OuterEnvelope, fcert: VerifiedDeviceCert): void;
|
|
98
|
+
/** §5.4 step 3, stateless part: validity, cert, iss, sub, relays, kinds, expiry. */
|
|
99
|
+
verifyCapForSend(capJws: string, ctx: CapSendContext): VerifiedCap;
|
|
100
|
+
/** `H(envBytes || powNonce)` has at least `bits` leading zero bits (§5.4). */
|
|
101
|
+
powOk(envBytes: Uint8Array, powNonce: Uint8Array, bits: number): boolean;
|
|
102
|
+
/** §2.5: signature under `ik`, `iss == H(ik)`, shape and caps. Expiry is NOT checked (relays ignore it). */
|
|
103
|
+
parseIdentityDoc(jws: string): IdentityDoc;
|
|
104
|
+
/**
|
|
105
|
+
* §2.5/§5.6 chain link: `doc` extends `prev` (`ver = prev.ver + 1`), or, when
|
|
106
|
+
* `doc.merge` is set, merges `prev` and `merge` (`ver = max + 1`, `prev` the
|
|
107
|
+
* higher tip, devices only shrink). Throws `bad-link`.
|
|
108
|
+
*/
|
|
109
|
+
verifyIdentityDocLink(prev: IdentityDoc, doc: IdentityDoc, merge?: IdentityDoc): void;
|
|
110
|
+
isUserId(s: unknown): s is string;
|
|
111
|
+
isDeviceId(s: unknown): s is string;
|
|
112
|
+
}
|
|
113
|
+
export declare const TYP_DEVICE = "p2p-device+jws";
|
|
114
|
+
export declare const TYP_MSG = "p2p-msg+jws";
|
|
115
|
+
export declare const TYP_CAP = "p2p-cap+jws";
|
|
116
|
+
export declare const TYP_IDENTITY = "p2p-identity+jws";
|
|
117
|
+
export declare const MAX_JWS_BYTES: number;
|
|
118
|
+
export declare const MAX_ENVELOPE_BYTES: number;
|
|
119
|
+
/** RFC 4648 base32, lowercase, no padding (§1). */
|
|
120
|
+
export declare function b32Encode(bytes: Uint8Array): string;
|
|
121
|
+
/** `"p2p:" + b32(H(ik_pub))` (§2.1). */
|
|
122
|
+
export declare function userIdFromIk(ik: Uint8Array): string;
|
|
123
|
+
/** `"d_" + b32(H(spk))[:26]` (§2.3). */
|
|
124
|
+
export declare function didFromSpk(spk: Uint8Array): string;
|
|
125
|
+
/** `jwsHash(j) = b64u(H(utf8(j)))` (§1). */
|
|
126
|
+
export declare function jwsHash(jws: string): string;
|
|
127
|
+
/**
|
|
128
|
+
* Messages up to this size are verified natively. Node copies the whole
|
|
129
|
+
* message into a native buffer for every one-shot verify; for large inputs
|
|
130
|
+
* (envelopes approach 64 KiB) that churn grew the relay's RSS by 20-40 MB
|
|
131
|
+
* under a flood of large envelopes (resilience #7), so they use core's strict
|
|
132
|
+
* pure-JS verifier instead. Hot traffic (statuses, messages, caps, certs,
|
|
133
|
+
* auth) is far below this.
|
|
134
|
+
*/
|
|
135
|
+
export declare const NATIVE_VERIFY_MAX_BYTES: number;
|
|
136
|
+
/** Strict Ed25519 verification: native up to NATIVE_VERIFY_MAX_BYTES, core's noble-strict above. */
|
|
137
|
+
export declare function ed25519VerifyStrict(sig: Uint8Array, msg: Uint8Array, pk: Uint8Array): boolean;
|
|
138
|
+
/**
|
|
139
|
+
* Strict Ed25519 verification with native crypto. `pk` must already have
|
|
140
|
+
* passed assertStrongEd25519.
|
|
141
|
+
*/
|
|
142
|
+
export declare function ed25519VerifyNative(sig: Uint8Array, msg: Uint8Array, pk: Uint8Array): boolean;
|
|
143
|
+
export interface RelayCryptoOptions {
|
|
144
|
+
/**
|
|
145
|
+
* Verified device certificates remembered, keyed by a hash of the exact
|
|
146
|
+
* JWS bytes. A hit skips only the signature and small-order work (about
|
|
147
|
+
* 3 ms, mostly the torsion check); the validity window is re-checked every
|
|
148
|
+
* time, and revocation and allowlist checks are the relay's, on every send.
|
|
149
|
+
*/
|
|
150
|
+
certCacheSize?: number;
|
|
151
|
+
}
|
|
152
|
+
export declare function relayCritCheck(p: Record<string, unknown>, known: readonly string[], what: string): void;
|
|
153
|
+
export declare function createRelayCrypto(opts?: RelayCryptoOptions): RelayCrypto;
|
|
154
|
+
/**
|
|
155
|
+
* Test double: the real adapter with any methods replaced. Lets a test force
|
|
156
|
+
* one crypto outcome (a cap that "verifies", a PoW that always passes) without
|
|
157
|
+
* minting objects, and proves the relay reaches crypto only through this seam.
|
|
158
|
+
*/
|
|
159
|
+
export declare function testRelayCrypto(overrides?: Partial<RelayCrypto>): RelayCrypto;
|