@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/server.js
ADDED
|
@@ -0,0 +1,1951 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// The Peer2Peer v3 relay (docs/protocol.md §5): a WebSocket endpoint at the
|
|
4
|
+
// configured path (default /v3) plus a few public HTTP GETs.
|
|
5
|
+
//
|
|
6
|
+
// The relay is dumb store-and-forward. It sees outer envelope fields,
|
|
7
|
+
// capabilities, identity documents and connection metadata, and enforces only
|
|
8
|
+
// device-signature auth, mailbox capabilities and rate limits. It never
|
|
9
|
+
// stores or logs envelope contents, capabilities, link data or invite blobs.
|
|
10
|
+
//
|
|
11
|
+
// Resource rule: every write path (envelopes, cap state, identity documents,
|
|
12
|
+
// device bindings, link mailboxes, invite mailboxes) has a rate limit and a
|
|
13
|
+
// size or count cap,
|
|
14
|
+
// and per-IP limits key IPv6 clients by /64.
|
|
15
|
+
import { createCipheriv, createDecipheriv, createHmac, timingSafeEqual } from "node:crypto";
|
|
16
|
+
import { createServer } from "node:http";
|
|
17
|
+
import { isIPv4 } from "node:net";
|
|
18
|
+
import { readFileSync } from "node:fs";
|
|
19
|
+
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
20
|
+
import { b64uDecode, b64uEncode, randomBytes, sha256 } from "@peer2peer/core";
|
|
21
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
22
|
+
import { createRelayCrypto } from "./crypto.js";
|
|
23
|
+
import { IdentityService } from "./identity.js";
|
|
24
|
+
import { LID_RE, LinkMailboxes } from "./links.js";
|
|
25
|
+
import { ADMIT_RE, Membership } from "./members.js";
|
|
26
|
+
import { createLogger, redact } from "./log.js";
|
|
27
|
+
import { Metrics } from "./metrics.js";
|
|
28
|
+
import { clientAddress, ipBucket, ipBucket48 } from "./net.js";
|
|
29
|
+
import { RateLimiter } from "./ratelimit.js";
|
|
30
|
+
import { MemoryStore } from "./store.js";
|
|
31
|
+
export const RELAY_SOFTWARE = "@peer2peer/relay";
|
|
32
|
+
function readVersion() {
|
|
33
|
+
try {
|
|
34
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
35
|
+
return pkg.version ?? "0.0.0";
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return "0.0.0";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export const RELAY_VERSION = readVersion();
|
|
42
|
+
/** docs/compatibility.md: this relay's protocol minor (3.1: the crit rule on what it parses). */
|
|
43
|
+
export const RELAY_PROTOCOL_MINOR = 1;
|
|
44
|
+
/** The frames this relay answers (handleFrame's cases), listed in /.well-known/p2p-relay.json. */
|
|
45
|
+
export const RELAY_FRAMES = ["auth", "link-put", "link-get", "invite-get", "send", "ack", "revoke", "identity", "link-open", "invite-put", "invite-del", "invite-list", "circle-put"];
|
|
46
|
+
/**
|
|
47
|
+
* What it supports beyond the frames:
|
|
48
|
+
* - `identity.lenient`: identity documents, device certs and caps with fields it doesn't know are
|
|
49
|
+
* stored and served (refused only for a field listed in `crit`);
|
|
50
|
+
* - `envelope.lenient`: envelopes of kinds it doesn't know, and with unknown outer fields, are
|
|
51
|
+
* relayed (refused only for an unknown field listed in `crit`);
|
|
52
|
+
* - `invite-mailbox`: short-code invite mailboxes (P4);
|
|
53
|
+
* - `link-mailbox`: pre-auth device-link mailboxes (§5.7);
|
|
54
|
+
* - `members`: this software can run members-only: it honours `admit` on `auth` and
|
|
55
|
+
* `invite-put`, and answers `circle-put`. Whether this relay does run so is `access`
|
|
56
|
+
* ("members" or "open") in the same document; `attention` asks its operator to look at the logs.
|
|
57
|
+
* Frames ignore fields the relay doesn't know (they are requests, not signed objects); a client that
|
|
58
|
+
* needs a frame field honoured checks the relay's features first.
|
|
59
|
+
*/
|
|
60
|
+
export const RELAY_FEATURES = ["identity.lenient", "envelope.lenient", "invite-mailbox", "link-mailbox", "members"];
|
|
61
|
+
/**
|
|
62
|
+
* Parses a request target against a dummy base. Node's HTTP parser lets
|
|
63
|
+
* through targets that WHATWG URL rejects (`http://[::1`), and an exception in
|
|
64
|
+
* an `upgrade` handler would take the process down, so callers get undefined.
|
|
65
|
+
*/
|
|
66
|
+
function parseTarget(target) {
|
|
67
|
+
try {
|
|
68
|
+
return new URL(target ?? "/", "http://relay.invalid");
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Close codes the relay uses. */
|
|
75
|
+
export const CLOSE = {
|
|
76
|
+
shutdown: 1001,
|
|
77
|
+
tooBig: 1009,
|
|
78
|
+
authFailed: 4001,
|
|
79
|
+
/** The device certificate expired: reconnect with a renewed one (not a revocation, R4-L1). */
|
|
80
|
+
certExpired: 4003,
|
|
81
|
+
unauthTimeout: 4008,
|
|
82
|
+
tooManyConnections: 4029,
|
|
83
|
+
};
|
|
84
|
+
const DAY_MS = 24 * 3600 * 1000;
|
|
85
|
+
/** Capability state outlives any cap it could apply to (exp ≤ iat + 90 d). */
|
|
86
|
+
const CAP_STATE_RETENTION_MS = 91 * DAY_MS;
|
|
87
|
+
/** Stop queueing deliveries above this much unsent data per connection. */
|
|
88
|
+
const HIGH_WATER_BYTES = 1024 * 1024;
|
|
89
|
+
const DELIVERY_PAGE = 64;
|
|
90
|
+
const HEARTBEAT_MS = 30_000;
|
|
91
|
+
const MAX_ID_LEN = 128;
|
|
92
|
+
const MAX_ACK_RIDS = 1024;
|
|
93
|
+
/** Gauges read store counts at most this often, so scrapes never scan tables. */
|
|
94
|
+
const COUNTS_TTL_MS = 60_000;
|
|
95
|
+
const WIRE_RID_RE = /^[A-Za-z0-9_-]{22}$/;
|
|
96
|
+
/**
|
|
97
|
+
* F-4: each expiry step aims at EXPIRE_STEP_MS of work; the row count adapts
|
|
98
|
+
* between these bounds. Sweep prelude steps delete at most SWEEP_STEP rows per
|
|
99
|
+
* table before yielding.
|
|
100
|
+
*/
|
|
101
|
+
const EXPIRE_STEP_MS = 10;
|
|
102
|
+
/** Above this share of a global cap (connections, device rows), per-address limits fall back to the strict IPv6 values. */
|
|
103
|
+
const POOL_PRESSURE = 0.8;
|
|
104
|
+
/** Pool evictions one newcomer address may cause per minute (pre-release re-review M-1). */
|
|
105
|
+
const POOL_EVICTIONS_PER_IP_PER_MINUTE = 10;
|
|
106
|
+
const EXPIRE_ROWS_MIN = 20;
|
|
107
|
+
const EXPIRE_ROWS_MAX = 2000;
|
|
108
|
+
const SWEEP_STEP = 200;
|
|
109
|
+
/** Members-only: `circle-put` frames per userId per hour. */
|
|
110
|
+
const CIRCLE_PUTS_PER_ISS_PER_HOUR = 120;
|
|
111
|
+
/** At most one "X-Forwarded-For has fewer hops than TRUST_PROXY" warning per this long. */
|
|
112
|
+
const SHORT_XFF_WARN_MS = 60_000;
|
|
113
|
+
const mboxKey = (iss, did) => `${iss}\n${did}`;
|
|
114
|
+
export class Relay {
|
|
115
|
+
config;
|
|
116
|
+
store;
|
|
117
|
+
crypto;
|
|
118
|
+
log;
|
|
119
|
+
metrics = new Metrics();
|
|
120
|
+
identity;
|
|
121
|
+
now;
|
|
122
|
+
links;
|
|
123
|
+
/** Members-only mode; admits everyone when neither an allowlist nor a circle is configured. */
|
|
124
|
+
members;
|
|
125
|
+
http;
|
|
126
|
+
metricsHttp;
|
|
127
|
+
wss;
|
|
128
|
+
conns = new Set();
|
|
129
|
+
byMailbox = new Map();
|
|
130
|
+
byIss = new Map();
|
|
131
|
+
/** Restricted connections per userId (never in byIss or a mailbox map). */
|
|
132
|
+
restrictedByIss = new Map();
|
|
133
|
+
perIp = new Map();
|
|
134
|
+
/** Unauthenticated connections, oldest first, and their count per IP bucket. */
|
|
135
|
+
unauthConns = new Set();
|
|
136
|
+
unauthPerIp = new Map();
|
|
137
|
+
limiters;
|
|
138
|
+
path;
|
|
139
|
+
/** Per-process AES-128 key: the wire rid is the internal rid encrypted as one block (L3, N2). */
|
|
140
|
+
ridKey = randomBytes(16);
|
|
141
|
+
/**
|
|
142
|
+
* Key for `src`, the stored keyed hash of a sender's IP bucket (N1). Held
|
|
143
|
+
* ONLY in memory (N-M3): nothing on disk can link an envelope to a network.
|
|
144
|
+
* After a restart, older rows keep their tags as anonymous groups (R-M1).
|
|
145
|
+
*/
|
|
146
|
+
srcKey = Buffer.from(randomBytes(32));
|
|
147
|
+
/** Device bindings held, for the maxDevices cap (N3). Re-synced on sweep. */
|
|
148
|
+
deviceCount;
|
|
149
|
+
lastShortXffWarn = -Infinity;
|
|
150
|
+
nextConnId = 1;
|
|
151
|
+
timers = [];
|
|
152
|
+
closing = false;
|
|
153
|
+
/** Running total of stored envelope bytes, for the global quota. Re-synced on sweep. */
|
|
154
|
+
storedBytes;
|
|
155
|
+
cachedCounts;
|
|
156
|
+
/** Event-loop delay, sampled only when `debugStats` is on. */
|
|
157
|
+
lagHist;
|
|
158
|
+
constructor(opts) {
|
|
159
|
+
this.config = opts.config;
|
|
160
|
+
this.crypto = opts.crypto ?? createRelayCrypto();
|
|
161
|
+
this.store = opts.store ?? new MemoryStore();
|
|
162
|
+
this.now = opts.now ?? Date.now;
|
|
163
|
+
this.log = opts.logger ?? createLogger({ level: opts.config.logLevel, now: this.now });
|
|
164
|
+
const L = this.config.limits;
|
|
165
|
+
this.identity = new IdentityService(this.store, this.crypto, this.config.relayUrl, this.now, {
|
|
166
|
+
maxTips: L.identityMaxTips,
|
|
167
|
+
maxVersions: L.identityMaxVersions,
|
|
168
|
+
expiredRetentionSec: L.identityExpiredRetentionSec,
|
|
169
|
+
tombstoneRetentionSec: L.identityTombstoneRetentionSec,
|
|
170
|
+
});
|
|
171
|
+
this.links = new LinkMailboxes({
|
|
172
|
+
ttlMs: L.linkTtlSec * 1000,
|
|
173
|
+
reqEntries: L.linkReqEntries,
|
|
174
|
+
entryBytes: L.linkEntryBytes,
|
|
175
|
+
openPerDevice: L.linkOpenPerDevice,
|
|
176
|
+
openPerIp: L.linkOpenPerIp,
|
|
177
|
+
// L-d: never more mailboxes than the byte budget can reserve.
|
|
178
|
+
maxOpen: Math.min(10_000, Math.floor(L.linkTotalBytes / ((L.linkReqEntries + 1) * L.linkEntryBytes))),
|
|
179
|
+
totalBytes: L.linkTotalBytes,
|
|
180
|
+
}, this.now);
|
|
181
|
+
const MIN = 60_000;
|
|
182
|
+
const HOUR = 3_600_000;
|
|
183
|
+
const rl = (limit, period) => new RateLimiter(limit, period, this.now);
|
|
184
|
+
this.limiters = {
|
|
185
|
+
sends: rl(L.sendsPerMinute, MIN),
|
|
186
|
+
contactSender: rl(L.contactPerSenderPerHour, HOUR),
|
|
187
|
+
contactPair: rl(L.contactPerPairPerHour, HOUR),
|
|
188
|
+
contactIp: rl(L.contactPerIpPerHour, HOUR),
|
|
189
|
+
link: rl(L.linkOpsPerIpPerMinute, MIN),
|
|
190
|
+
http: rl(L.httpPerIpPerMinute, MIN),
|
|
191
|
+
frames: rl(L.framesPerConnPerMinute, MIN),
|
|
192
|
+
sendBytesConn: rl(L.sendBytesPerConnPerMinute, MIN),
|
|
193
|
+
sendBytesIp: rl(L.sendBytesPerIpPerMinute, MIN),
|
|
194
|
+
revokeConn: rl(L.revokesPerConnPerMinute, MIN),
|
|
195
|
+
revokeIss: rl(L.revokesPerIssPerHour, HOUR),
|
|
196
|
+
identityIss: rl(L.identityPublishPerIssPerHour, HOUR),
|
|
197
|
+
identityIp: rl(L.identityPublishPerIpPerHour, HOUR),
|
|
198
|
+
identityRestricted: rl(L.restrictedIdentityPerIssPerHour, HOUR),
|
|
199
|
+
linkOpenIss: rl(L.linkOpenPerIssPerHour, HOUR),
|
|
200
|
+
linkOpenIp: rl(L.linkOpenPerIpPerHour, HOUR),
|
|
201
|
+
invitePutIss: rl(L.invitePutPerIssPerHour, HOUR),
|
|
202
|
+
invitePutIp: rl(L.invitePutPerIpPerHour, HOUR),
|
|
203
|
+
inviteGet: rl(L.inviteGetsPerIpPerMinute, MIN),
|
|
204
|
+
inviteMiss: rl(L.inviteMissesPerIpPerHour, HOUR),
|
|
205
|
+
connectsIp: rl(L.connectsPerIpPerMinute, MIN),
|
|
206
|
+
poolEvictIp: rl(POOL_EVICTIONS_PER_IP_PER_MINUTE, MIN),
|
|
207
|
+
authsIp: rl(L.authsPerIpPerMinute, MIN),
|
|
208
|
+
authsIp4: rl(L.authsPerIpv4PerMinute, MIN),
|
|
209
|
+
newDevicesIp: rl(L.newDevicesPerIpPerDay, DAY_MS),
|
|
210
|
+
newDevicesIp4: rl(L.newDevicesPerIpv4PerDay, DAY_MS),
|
|
211
|
+
// M-3/N-M2: bytes ACCEPTED from a source, refilling continuously over an
|
|
212
|
+
// hour. Silently dropped contacts count too, and acks or evictions never
|
|
213
|
+
// give bytes back, so the budget says nothing about mailboxes or receivers.
|
|
214
|
+
sourceAccepted: rl(L.sourceAcceptedBytesPerHour, HOUR),
|
|
215
|
+
circlePut: rl(CIRCLE_PUTS_PER_ISS_PER_HOUR, HOUR),
|
|
216
|
+
};
|
|
217
|
+
this.members = new Membership({
|
|
218
|
+
allow: this.config.allow,
|
|
219
|
+
deny: this.config.deny,
|
|
220
|
+
circle: this.config.allowCircle,
|
|
221
|
+
inviteAdmitSec: this.config.inviteAdmitSec,
|
|
222
|
+
store: this.store,
|
|
223
|
+
now: this.now,
|
|
224
|
+
log: this.log,
|
|
225
|
+
});
|
|
226
|
+
this.path = new URL(this.config.relayUrl).pathname;
|
|
227
|
+
const counts = this.store.counts();
|
|
228
|
+
this.storedBytes = counts.envelopeBytes;
|
|
229
|
+
this.deviceCount = counts.devices;
|
|
230
|
+
this.cachedCounts = { at: this.now(), counts };
|
|
231
|
+
this.registerMetrics();
|
|
232
|
+
// F-2: allowSynchronousEvents=false makes ws emit at most one message per
|
|
233
|
+
// connection per macrotask (setImmediate between frames). A pipelined burst
|
|
234
|
+
// on one socket therefore yields to everything else between frames, and
|
|
235
|
+
// ws's receiver stops reading the socket meanwhile (TCP backpressure), so
|
|
236
|
+
// nothing queues up in relay memory.
|
|
237
|
+
this.wss = new WebSocketServer({ noServer: true, maxPayload: L.frameBytes, perMessageDeflate: false, allowSynchronousEvents: false });
|
|
238
|
+
this.http = createServer((req, res) => this.onHttp(req, res));
|
|
239
|
+
this.http.on("upgrade", (req, socket, head) => this.onUpgrade(req, socket, head));
|
|
240
|
+
}
|
|
241
|
+
// -------------------------------------------------------------------------
|
|
242
|
+
// Lifecycle
|
|
243
|
+
/** Starts listening; resolves with the bound port. */
|
|
244
|
+
async listen() {
|
|
245
|
+
// Startup work (re-attributing old rows, rebuilding totals) finishes,
|
|
246
|
+
// in yielding chunks, before the relay accepts any connection.
|
|
247
|
+
await this.store.init();
|
|
248
|
+
this.members.load();
|
|
249
|
+
const counts = this.store.counts();
|
|
250
|
+
this.storedBytes = counts.envelopeBytes;
|
|
251
|
+
this.deviceCount = counts.devices;
|
|
252
|
+
this.cachedCounts = { at: this.now(), counts };
|
|
253
|
+
const port = await new Promise((resolve, reject) => {
|
|
254
|
+
this.http.once("error", reject);
|
|
255
|
+
this.http.listen(this.config.port, this.config.host, () => {
|
|
256
|
+
this.http.off("error", reject);
|
|
257
|
+
const addr = this.http.address();
|
|
258
|
+
resolve(typeof addr === "object" && addr ? addr.port : this.config.port);
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
if (this.config.metricsPort !== null) {
|
|
262
|
+
const m = createServer((req, res) => this.onMetricsHttp(req, res));
|
|
263
|
+
this.metricsHttp = m;
|
|
264
|
+
await new Promise((resolve, reject) => {
|
|
265
|
+
m.once("error", reject);
|
|
266
|
+
m.listen(this.config.metricsPort ?? 0, this.config.metricsHost, () => {
|
|
267
|
+
m.off("error", reject);
|
|
268
|
+
resolve();
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
if (this.config.debugStats) {
|
|
273
|
+
this.lagHist = monitorEventLoopDelay({ resolution: 10 });
|
|
274
|
+
this.lagHist.enable();
|
|
275
|
+
}
|
|
276
|
+
this.timers.push(setInterval(() => void this.sweep(), this.config.sweepIntervalSec * 1000));
|
|
277
|
+
this.timers.push(setInterval(() => this.heartbeat(), HEARTBEAT_MS));
|
|
278
|
+
for (const t of this.timers)
|
|
279
|
+
t.unref();
|
|
280
|
+
this.log.info("relay listening", {
|
|
281
|
+
port,
|
|
282
|
+
relay: this.config.relayUrl,
|
|
283
|
+
version: RELAY_VERSION,
|
|
284
|
+
pow: this.config.powBits,
|
|
285
|
+
metricsPort: this.metricsPort ?? undefined,
|
|
286
|
+
});
|
|
287
|
+
return port;
|
|
288
|
+
}
|
|
289
|
+
/** The bound port of the separate /metrics listener, if it is running. */
|
|
290
|
+
get metricsPort() {
|
|
291
|
+
const a = this.metricsHttp?.address();
|
|
292
|
+
return typeof a === "object" && a ? a.port : undefined;
|
|
293
|
+
}
|
|
294
|
+
/** Graceful shutdown: refuse new work, close every connection with 1001, flush the store. */
|
|
295
|
+
async close() {
|
|
296
|
+
if (this.closing)
|
|
297
|
+
return;
|
|
298
|
+
this.closing = true;
|
|
299
|
+
for (const t of this.timers)
|
|
300
|
+
clearInterval(t);
|
|
301
|
+
this.timers = [];
|
|
302
|
+
this.lagHist?.disable();
|
|
303
|
+
for (const c of this.conns) {
|
|
304
|
+
if (c.pumpTimer)
|
|
305
|
+
clearTimeout(c.pumpTimer);
|
|
306
|
+
c.ws.close(CLOSE.shutdown, "relay shutting down");
|
|
307
|
+
}
|
|
308
|
+
await new Promise((resolve) => {
|
|
309
|
+
const force = setTimeout(() => {
|
|
310
|
+
for (const c of this.conns)
|
|
311
|
+
c.ws.terminate();
|
|
312
|
+
}, 2000);
|
|
313
|
+
force.unref();
|
|
314
|
+
const done = () => {
|
|
315
|
+
clearTimeout(force);
|
|
316
|
+
resolve();
|
|
317
|
+
};
|
|
318
|
+
if (this.conns.size === 0)
|
|
319
|
+
done();
|
|
320
|
+
else {
|
|
321
|
+
const check = setInterval(() => {
|
|
322
|
+
if (this.conns.size === 0) {
|
|
323
|
+
clearInterval(check);
|
|
324
|
+
done();
|
|
325
|
+
}
|
|
326
|
+
}, 10);
|
|
327
|
+
check.unref();
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
this.wss.close();
|
|
331
|
+
for (const srv of [this.http, this.metricsHttp]) {
|
|
332
|
+
if (!srv)
|
|
333
|
+
continue;
|
|
334
|
+
await new Promise((resolve) => {
|
|
335
|
+
if (!srv.listening)
|
|
336
|
+
return resolve();
|
|
337
|
+
srv.close(() => resolve());
|
|
338
|
+
srv.closeAllConnections();
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
this.store.close();
|
|
342
|
+
this.log.info("relay stopped");
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Deletes expired envelopes (in batches that yield, N-M1), cap state,
|
|
346
|
+
* identity versions and userIds, stale device bindings and link mailboxes.
|
|
347
|
+
* Resolves when the envelope expiry has caught up.
|
|
348
|
+
*/
|
|
349
|
+
async sweep() {
|
|
350
|
+
const now = this.now();
|
|
351
|
+
const L = this.config.limits;
|
|
352
|
+
const yieldNow = () => new Promise((res) => setImmediate(res));
|
|
353
|
+
try {
|
|
354
|
+
// F-4: every step is bounded and followed by a yield.
|
|
355
|
+
const r = { caps: 0, identityDocs: 0, devices: 0 };
|
|
356
|
+
const cutoffs = {
|
|
357
|
+
capsBefore: now - CAP_STATE_RETENTION_MS,
|
|
358
|
+
identityVersionsBefore: now - L.identityVersionRetentionSec * 1000,
|
|
359
|
+
devicesBefore: now - L.deviceRetentionSec * 1000,
|
|
360
|
+
seenBefore: now - L.identityTombstoneRetentionSec * 1000,
|
|
361
|
+
nowMs: now,
|
|
362
|
+
};
|
|
363
|
+
for (;;) {
|
|
364
|
+
const step = this.store.sweep(cutoffs, SWEEP_STEP);
|
|
365
|
+
r.caps += step.caps;
|
|
366
|
+
r.identityDocs += step.identityDocs;
|
|
367
|
+
r.devices += step.devices;
|
|
368
|
+
this.deviceCount = Math.max(0, this.deviceCount - step.devices);
|
|
369
|
+
const seen = step.seen ?? 0;
|
|
370
|
+
if (step.caps < SWEEP_STEP && step.identityDocs < SWEEP_STEP && step.devices < SWEEP_STEP && seen < SWEEP_STEP)
|
|
371
|
+
break;
|
|
372
|
+
await yieldNow();
|
|
373
|
+
}
|
|
374
|
+
await yieldNow();
|
|
375
|
+
const ids = { tombstoned: 0, deleted: 0 };
|
|
376
|
+
for (;;) {
|
|
377
|
+
const step = this.identity.sweep(SWEEP_STEP / 2);
|
|
378
|
+
ids.tombstoned += step.tombstoned;
|
|
379
|
+
ids.deleted += step.deleted;
|
|
380
|
+
if (step.tombstoned < SWEEP_STEP / 2 && step.deleted < SWEEP_STEP / 2)
|
|
381
|
+
break;
|
|
382
|
+
await yieldNow();
|
|
383
|
+
}
|
|
384
|
+
const links = this.links.sweep();
|
|
385
|
+
await yieldNow();
|
|
386
|
+
const invites = await this.sweepInvites(now);
|
|
387
|
+
if (this.members.enabled && this.members.expire())
|
|
388
|
+
this.enforceMembers();
|
|
389
|
+
for (const l of Object.values(this.limiters))
|
|
390
|
+
l.prune();
|
|
391
|
+
// A counter read, not a table scan; device rows are counted as they go.
|
|
392
|
+
this.storedBytes = this.store.envelopeTotals().bytes;
|
|
393
|
+
if (r.caps + r.identityDocs + r.devices + ids.tombstoned + ids.deleted + links + invites > 0) {
|
|
394
|
+
this.log.info("sweep", {
|
|
395
|
+
caps: r.caps,
|
|
396
|
+
identityDocs: r.identityDocs,
|
|
397
|
+
devices: r.devices,
|
|
398
|
+
identitiesTombstoned: ids.tombstoned,
|
|
399
|
+
tombstonesDeleted: ids.deleted,
|
|
400
|
+
links,
|
|
401
|
+
invites,
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
catch (e) {
|
|
406
|
+
this.log.error("sweep failed", { error: e.message });
|
|
407
|
+
}
|
|
408
|
+
await this.expire();
|
|
409
|
+
}
|
|
410
|
+
/** Rows per invite-sweep step, adapted like expireRows (F-4). */
|
|
411
|
+
inviteSweepRows = 200;
|
|
412
|
+
/**
|
|
413
|
+
* F-4: deletes expired invites (and their `evicted` tombstones) in batches,
|
|
414
|
+
* yielding between them; each batch adapts to about EXPIRE_STEP_MS. Returns
|
|
415
|
+
* how many invites went.
|
|
416
|
+
*/
|
|
417
|
+
async sweepInvites(now) {
|
|
418
|
+
let total = 0;
|
|
419
|
+
for (;;) {
|
|
420
|
+
if (this.closing)
|
|
421
|
+
break;
|
|
422
|
+
const rows = this.inviteSweepRows;
|
|
423
|
+
const t0 = performance.now();
|
|
424
|
+
const step = this.store.sweepInvites(now, rows);
|
|
425
|
+
const ms = performance.now() - t0;
|
|
426
|
+
if (ms > EXPIRE_STEP_MS)
|
|
427
|
+
this.inviteSweepRows = Math.max(EXPIRE_ROWS_MIN, Math.floor(rows / 2));
|
|
428
|
+
else if (ms < EXPIRE_STEP_MS / 2 && (step.invites === rows || step.evicted === rows))
|
|
429
|
+
this.inviteSweepRows = Math.min(EXPIRE_ROWS_MAX, Math.ceil(rows * 1.5));
|
|
430
|
+
total += step.invites;
|
|
431
|
+
if (step.invites < rows && step.evicted < rows)
|
|
432
|
+
break;
|
|
433
|
+
await new Promise((res) => setImmediate(res));
|
|
434
|
+
}
|
|
435
|
+
return total;
|
|
436
|
+
}
|
|
437
|
+
expiring;
|
|
438
|
+
/** Rows per expiry step, adapted to keep each step near EXPIRE_STEP_MS (F-4). */
|
|
439
|
+
expireRows = 200;
|
|
440
|
+
/**
|
|
441
|
+
* N-M1/F-4: deletes expired envelopes in batches through the received_at
|
|
442
|
+
* index, yielding to the event loop between batches. The batch size adapts
|
|
443
|
+
* so each one takes about EXPIRE_STEP_MS, so a large expiry never holds the
|
|
444
|
+
* loop (or the write lock) for long.
|
|
445
|
+
*/
|
|
446
|
+
expire() {
|
|
447
|
+
this.expiring ??= (async () => {
|
|
448
|
+
let total = 0;
|
|
449
|
+
try {
|
|
450
|
+
for (;;) {
|
|
451
|
+
if (this.closing)
|
|
452
|
+
break;
|
|
453
|
+
const before = this.now() - this.config.limits.retentionSec * 1000;
|
|
454
|
+
const rows = this.expireRows;
|
|
455
|
+
const t0 = performance.now();
|
|
456
|
+
const { count, bytes } = this.store.expireBatch(before, rows);
|
|
457
|
+
const ms = performance.now() - t0;
|
|
458
|
+
if (ms > EXPIRE_STEP_MS)
|
|
459
|
+
this.expireRows = Math.max(EXPIRE_ROWS_MIN, Math.floor(rows / 2));
|
|
460
|
+
else if (ms < EXPIRE_STEP_MS / 2 && count === rows)
|
|
461
|
+
this.expireRows = Math.min(EXPIRE_ROWS_MAX, Math.ceil(rows * 1.5));
|
|
462
|
+
total += count;
|
|
463
|
+
this.storedBytes = Math.max(0, this.storedBytes - bytes);
|
|
464
|
+
if (count < rows)
|
|
465
|
+
break;
|
|
466
|
+
await new Promise((res) => setImmediate(res));
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
catch (e) {
|
|
470
|
+
this.log.error("expiry failed", { error: e.message });
|
|
471
|
+
}
|
|
472
|
+
finally {
|
|
473
|
+
this.expiring = undefined;
|
|
474
|
+
}
|
|
475
|
+
if (total > 0) {
|
|
476
|
+
this.metrics.inc("envelopes_expired", undefined, total);
|
|
477
|
+
this.log.info("expired", { envelopes: total });
|
|
478
|
+
}
|
|
479
|
+
})();
|
|
480
|
+
return this.expiring;
|
|
481
|
+
}
|
|
482
|
+
heartbeat() {
|
|
483
|
+
if (this.members.enabled && this.members.expire())
|
|
484
|
+
this.enforceMembers();
|
|
485
|
+
for (const c of this.conns) {
|
|
486
|
+
if (!c.alive) {
|
|
487
|
+
c.ws.terminate();
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
c.alive = false;
|
|
491
|
+
c.ws.ping();
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
counts() {
|
|
495
|
+
const now = this.now();
|
|
496
|
+
if (now - this.cachedCounts.at >= COUNTS_TTL_MS)
|
|
497
|
+
this.cachedCounts = { at: now, counts: this.store.counts() };
|
|
498
|
+
return this.cachedCounts.counts;
|
|
499
|
+
}
|
|
500
|
+
registerMetrics() {
|
|
501
|
+
// Only aggregate counts. Nothing here may tell apart outcomes a sender
|
|
502
|
+
// can't distinguish on the wire (stored vs silently dropped, delivered or
|
|
503
|
+
// not), or it becomes a mailbox-existence / presence oracle.
|
|
504
|
+
const m = this.metrics;
|
|
505
|
+
m.counter("connections", "WebSocket connections accepted");
|
|
506
|
+
m.counter("connections_rejected", "WebSocket upgrades refused (limits, wrong path)");
|
|
507
|
+
m.counter("auth", "Authentication attempts by result");
|
|
508
|
+
m.counter("sends", "send frames by wire result");
|
|
509
|
+
m.counter("envelopes_expired", "Envelopes deleted after the retention period");
|
|
510
|
+
m.counter("envelopes_evicted", "Envelopes evicted to stay under the store or per-recipient quota");
|
|
511
|
+
m.counter("revokes", "Capability revocations recorded");
|
|
512
|
+
m.counter("identity_publish", "Identity document publishes by result");
|
|
513
|
+
m.counter("link", "Link mailbox operations by op and result");
|
|
514
|
+
m.counter("invite", "Short-code invite mailbox operations by op and result");
|
|
515
|
+
m.counter("http_requests", "HTTP requests by route");
|
|
516
|
+
m.counter("frames_rejected", "Frames rejected as malformed, unknown or over the frame rate");
|
|
517
|
+
m.counter("circle_put", "Members-only circle-put frames by result");
|
|
518
|
+
m.gauge("connections_open", "Open WebSocket connections", () => this.conns.size);
|
|
519
|
+
m.gauge("connections_authenticated", "Authenticated WebSocket connections", () => this.conns.size - this.unauthConns.size);
|
|
520
|
+
m.gauge("envelopes_stored_now", "Envelopes stored (refreshed at most once a minute)", () => this.counts().envelopes);
|
|
521
|
+
m.gauge("envelope_bytes_stored_now", "Envelope bytes stored (refreshed at most once a minute)", () => this.counts().envelopeBytes);
|
|
522
|
+
m.gauge("link_mailboxes_open", "Link mailboxes currently open", () => this.links.size);
|
|
523
|
+
m.gauge("invite_bytes_stored_now", "Bytes held in short-code invite mailboxes", () => this.store.inviteBytes());
|
|
524
|
+
}
|
|
525
|
+
// -------------------------------------------------------------------------
|
|
526
|
+
// Discovery
|
|
527
|
+
/** The `hello.limits` object and the limits block of the relay-info document. */
|
|
528
|
+
advertisedLimits() {
|
|
529
|
+
const L = this.config.limits;
|
|
530
|
+
return {
|
|
531
|
+
frameBytes: L.frameBytes,
|
|
532
|
+
envelopeBytes: L.envelopeBytes,
|
|
533
|
+
mailboxEnvelopes: L.mailboxEnvelopes,
|
|
534
|
+
mailboxBytes: L.mailboxBytes,
|
|
535
|
+
retentionSec: L.retentionSec,
|
|
536
|
+
sendsPerMinute: L.sendsPerMinute,
|
|
537
|
+
contactPerSenderPerHour: L.contactPerSenderPerHour,
|
|
538
|
+
contactPerPairPerHour: L.contactPerPairPerHour,
|
|
539
|
+
contactPerIpPerHour: L.contactPerIpPerHour,
|
|
540
|
+
linkOpsPerIpPerMinute: L.linkOpsPerIpPerMinute,
|
|
541
|
+
// R-L1: link pollers (unauthenticated) must reconnect within this.
|
|
542
|
+
unauthTimeoutSec: L.unauthTimeoutSec,
|
|
543
|
+
framesPerConnPerMinute: L.framesPerConnPerMinute,
|
|
544
|
+
sendBytesPerConnPerMinute: L.sendBytesPerConnPerMinute,
|
|
545
|
+
inviteTtlMaxSec: L.inviteTtlMaxSec,
|
|
546
|
+
inviteBlobBytes: L.inviteBlobBytes,
|
|
547
|
+
inviteGetsPerIpPerMinute: L.inviteGetsPerIpPerMinute,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
/** GET /.well-known/p2p-relay.json: how communities discover and compare relays, and what this one supports. */
|
|
551
|
+
relayInfo() {
|
|
552
|
+
return {
|
|
553
|
+
protocol: "p2p/v3",
|
|
554
|
+
// docs/compatibility.md: what this relay answers, so a client can degrade against an older one.
|
|
555
|
+
// A relay from before these fields lists neither, and counts as protocol 3.0, baseline frames.
|
|
556
|
+
protocolMinor: RELAY_PROTOCOL_MINOR,
|
|
557
|
+
frames: [...RELAY_FRAMES],
|
|
558
|
+
features: [...RELAY_FEATURES],
|
|
559
|
+
relay: this.config.relayUrl,
|
|
560
|
+
name: this.config.name ?? null,
|
|
561
|
+
software: { name: RELAY_SOFTWARE, version: RELAY_VERSION },
|
|
562
|
+
limits: this.advertisedLimits(),
|
|
563
|
+
pow: this.config.powBits,
|
|
564
|
+
operator: { contact: this.config.operatorContact ?? null },
|
|
565
|
+
policy: this.config.policy ?? null,
|
|
566
|
+
// Members-only relays say so (not who the members are), so a refused client can explain why.
|
|
567
|
+
access: this.members.enabled ? "members" : "open",
|
|
568
|
+
// The operator should look at the logs (e.g. the followed circle turned open); no details here.
|
|
569
|
+
...(this.members.attention ? { attention: true } : {}),
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
// -------------------------------------------------------------------------
|
|
573
|
+
// HTTP
|
|
574
|
+
clientIp(req) {
|
|
575
|
+
// A local health check (e.g. Docker's HEALTHCHECK on 127.0.0.1) has no proxy in front: not a misconfiguration.
|
|
576
|
+
const remote = req.socket.remoteAddress ?? "";
|
|
577
|
+
const localHealth = /^(127\.|::1$|::ffff:127\.)/.test(remote) && (req.url ?? "").split("?")[0] === "/healthz";
|
|
578
|
+
const addr = clientAddress(remote, req.headers["x-forwarded-for"], this.config.trustProxy, (hops) => {
|
|
579
|
+
if (localHealth)
|
|
580
|
+
return;
|
|
581
|
+
// N8: the proxy chain isn't what TRUST_PROXY says; every client may be
|
|
582
|
+
// sharing the proxy's limits. Warn, but not on every request.
|
|
583
|
+
const now = this.now();
|
|
584
|
+
if (now - this.lastShortXffWarn < SHORT_XFF_WARN_MS)
|
|
585
|
+
return;
|
|
586
|
+
this.lastShortXffWarn = now;
|
|
587
|
+
this.log.warn("X-Forwarded-For has fewer hops than TRUST_PROXY; using the socket address", {
|
|
588
|
+
hops,
|
|
589
|
+
trustProxy: this.config.trustProxy,
|
|
590
|
+
});
|
|
591
|
+
});
|
|
592
|
+
return ipBucket(addr);
|
|
593
|
+
}
|
|
594
|
+
sendMetrics(res) {
|
|
595
|
+
res.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8", "cache-control": "no-store" });
|
|
596
|
+
res.end(this.metrics.render());
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* GET /debug/stats on the metrics listener, only when `debugStats` is on:
|
|
600
|
+
* event-loop delay, process memory and the sizes of every in-memory map, for
|
|
601
|
+
* the resilience suite (packages/relay/resilience). Aggregates only, like /metrics.
|
|
602
|
+
* `?reset=1` restarts the delay histogram after reading it; `?store=1` adds
|
|
603
|
+
* live store counts (a table scan, so the harness asks only at checkpoints).
|
|
604
|
+
*/
|
|
605
|
+
debugStats(opts = {}) {
|
|
606
|
+
const h = this.lagHist;
|
|
607
|
+
const ms = (ns) => (Number.isFinite(ns) ? ns / 1e6 : 0);
|
|
608
|
+
const lag = h
|
|
609
|
+
? { p50: ms(h.percentile(50)), p99: ms(h.percentile(99)), max: ms(h.max), mean: ms(h.mean), count: h.count }
|
|
610
|
+
: null;
|
|
611
|
+
if (opts.reset)
|
|
612
|
+
h?.reset();
|
|
613
|
+
const mem = process.memoryUsage();
|
|
614
|
+
const limiterKeys = {};
|
|
615
|
+
for (const [name, l] of Object.entries(this.limiters))
|
|
616
|
+
limiterKeys[name] = l.size;
|
|
617
|
+
const out = {
|
|
618
|
+
lagMs: lag,
|
|
619
|
+
rssBytes: mem.rss,
|
|
620
|
+
heapUsedBytes: mem.heapUsed,
|
|
621
|
+
heapTotalBytes: mem.heapTotal,
|
|
622
|
+
externalBytes: mem.external,
|
|
623
|
+
arrayBuffersBytes: mem.arrayBuffers,
|
|
624
|
+
connections: this.conns.size,
|
|
625
|
+
unauthConnections: this.unauthConns.size,
|
|
626
|
+
maps: {
|
|
627
|
+
byMailbox: this.byMailbox.size,
|
|
628
|
+
byIss: this.byIss.size,
|
|
629
|
+
perIp: this.perIp.size,
|
|
630
|
+
unauthPerIp: this.unauthPerIp.size,
|
|
631
|
+
limiterKeys,
|
|
632
|
+
},
|
|
633
|
+
links: { open: this.links.size, reservedBytes: this.links.reservedBytes },
|
|
634
|
+
storedBytes: this.storedBytes,
|
|
635
|
+
};
|
|
636
|
+
if (opts.store)
|
|
637
|
+
out.store = this.store.counts();
|
|
638
|
+
return out;
|
|
639
|
+
}
|
|
640
|
+
/** The separate (by default localhost-only) metrics listener. */
|
|
641
|
+
onMetricsHttp(req, res) {
|
|
642
|
+
try {
|
|
643
|
+
const url = parseTarget(req.url);
|
|
644
|
+
if (!url)
|
|
645
|
+
return void res.writeHead(400).end();
|
|
646
|
+
if (req.method === "GET" && url.pathname === "/metrics")
|
|
647
|
+
return this.sendMetrics(res);
|
|
648
|
+
if (req.method === "GET" && url.pathname === "/debug/stats" && this.config.debugStats) {
|
|
649
|
+
const body = this.debugStats({ reset: url.searchParams.get("reset") === "1", store: url.searchParams.get("store") === "1" });
|
|
650
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
651
|
+
res.end(JSON.stringify(body));
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
res.writeHead(404).end();
|
|
655
|
+
}
|
|
656
|
+
catch (e) {
|
|
657
|
+
this.log.error("metrics handler failed", { error: e.message });
|
|
658
|
+
if (!res.headersSent)
|
|
659
|
+
res.writeHead(500);
|
|
660
|
+
res.end();
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
metricsTokenOk(req) {
|
|
664
|
+
const token = this.config.metricsToken;
|
|
665
|
+
const header = req.headers.authorization;
|
|
666
|
+
if (!token || typeof header !== "string" || !header.startsWith("Bearer "))
|
|
667
|
+
return false;
|
|
668
|
+
const a = Buffer.from(header.slice(7));
|
|
669
|
+
const b = Buffer.from(token);
|
|
670
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
671
|
+
}
|
|
672
|
+
onHttp(req, res) {
|
|
673
|
+
const send = (status, body) => {
|
|
674
|
+
res.writeHead(status, {
|
|
675
|
+
"content-type": "application/json; charset=utf-8",
|
|
676
|
+
"cache-control": "no-store",
|
|
677
|
+
"access-control-allow-origin": "*",
|
|
678
|
+
"x-content-type-options": "nosniff",
|
|
679
|
+
});
|
|
680
|
+
res.end(req.method === "HEAD" ? undefined : JSON.stringify(body));
|
|
681
|
+
};
|
|
682
|
+
let route = "other";
|
|
683
|
+
try {
|
|
684
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
685
|
+
route = "method";
|
|
686
|
+
return send(405, { error: "method-not-allowed" });
|
|
687
|
+
}
|
|
688
|
+
if (!this.limiters.http.take(this.clientIp(req))) {
|
|
689
|
+
route = "rate-limited";
|
|
690
|
+
return send(429, { error: "rate-limited" });
|
|
691
|
+
}
|
|
692
|
+
const url = parseTarget(req.url);
|
|
693
|
+
if (!url) {
|
|
694
|
+
route = "bad-target";
|
|
695
|
+
return send(400, { error: "bad-request" });
|
|
696
|
+
}
|
|
697
|
+
const p = url.pathname;
|
|
698
|
+
if (p === "/healthz") {
|
|
699
|
+
route = "healthz";
|
|
700
|
+
let ok = false;
|
|
701
|
+
try {
|
|
702
|
+
ok = !this.closing && this.store.ping();
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
ok = false;
|
|
706
|
+
}
|
|
707
|
+
return send(ok ? 200 : 503, { ok });
|
|
708
|
+
}
|
|
709
|
+
if (p === "/metrics") {
|
|
710
|
+
// Public only with the operator's token; otherwise it lives on the metrics listener.
|
|
711
|
+
route = "metrics";
|
|
712
|
+
if (this.metricsTokenOk(req))
|
|
713
|
+
return this.sendMetrics(res);
|
|
714
|
+
return send(404, { error: "not-found" });
|
|
715
|
+
}
|
|
716
|
+
if (p === "/.well-known/p2p-relay.json") {
|
|
717
|
+
route = "relay-info";
|
|
718
|
+
return send(200, this.relayInfo());
|
|
719
|
+
}
|
|
720
|
+
if (p === this.path) {
|
|
721
|
+
route = "ws-path";
|
|
722
|
+
return send(426, { error: "upgrade-required" });
|
|
723
|
+
}
|
|
724
|
+
const prefix = `${this.path === "/" ? "" : this.path}/identity/`;
|
|
725
|
+
if (p.startsWith(prefix)) {
|
|
726
|
+
route = "identity";
|
|
727
|
+
return this.identityRoute(p.slice(prefix.length), url, send);
|
|
728
|
+
}
|
|
729
|
+
return send(404, { error: "not-found" });
|
|
730
|
+
}
|
|
731
|
+
catch (e) {
|
|
732
|
+
this.log.error("http handler failed", { error: e.message });
|
|
733
|
+
if (!res.headersSent)
|
|
734
|
+
send(500, { error: "internal" });
|
|
735
|
+
else
|
|
736
|
+
res.end();
|
|
737
|
+
}
|
|
738
|
+
finally {
|
|
739
|
+
this.metrics.inc("http_requests", { route });
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
identityRoute(rest, url, send) {
|
|
743
|
+
const parts = rest.split("/");
|
|
744
|
+
let userId;
|
|
745
|
+
try {
|
|
746
|
+
userId = decodeURIComponent(parts[0]);
|
|
747
|
+
}
|
|
748
|
+
catch {
|
|
749
|
+
return send(400, { error: "bad-request" });
|
|
750
|
+
}
|
|
751
|
+
if (!this.crypto.isUserId(userId) || parts.length > 2)
|
|
752
|
+
return send(404, { error: "not-found" });
|
|
753
|
+
// Members-only: documents of members only, so the relay is no public directory; a
|
|
754
|
+
// non-member's userId looks exactly like an unknown one.
|
|
755
|
+
if (!this.members.admitted(userId))
|
|
756
|
+
return send(404, { error: "not-found" });
|
|
757
|
+
const sub = parts[1];
|
|
758
|
+
if (sub === undefined || sub === "") {
|
|
759
|
+
const head = this.identity.head(userId);
|
|
760
|
+
return head ? send(200, { doc: head.jws }) : send(404, { error: "not-found" });
|
|
761
|
+
}
|
|
762
|
+
if (sub === "tips") {
|
|
763
|
+
const tips = this.identity.tips(userId);
|
|
764
|
+
return tips.length > 0 ? send(200, { tips: tips.map((t) => t.jws) }) : send(404, { error: "not-found" });
|
|
765
|
+
}
|
|
766
|
+
if (sub === "chain") {
|
|
767
|
+
const to = url.searchParams.get("to");
|
|
768
|
+
const nRaw = url.searchParams.get("n");
|
|
769
|
+
const max = this.config.limits.chainMaxN;
|
|
770
|
+
const n = nRaw === null ? max : Number(nRaw);
|
|
771
|
+
if (!to || !/^[A-Za-z0-9_-]{43}$/.test(to) || !Number.isSafeInteger(n) || n < 1 || n > max) {
|
|
772
|
+
return send(400, { error: "bad-request" });
|
|
773
|
+
}
|
|
774
|
+
const docs = this.identity.chain(userId, to, n);
|
|
775
|
+
return docs ? send(200, { docs: docs.map((d) => d.jws) }) : send(404, { error: "not-found" });
|
|
776
|
+
}
|
|
777
|
+
return send(404, { error: "not-found" });
|
|
778
|
+
}
|
|
779
|
+
// -------------------------------------------------------------------------
|
|
780
|
+
// WebSocket
|
|
781
|
+
onUpgrade(req, socket, head) {
|
|
782
|
+
const reject = (status, why) => {
|
|
783
|
+
this.metrics.inc("connections_rejected", { reason: why });
|
|
784
|
+
socket.write(`HTTP/1.1 ${status} ${why}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
785
|
+
socket.destroy();
|
|
786
|
+
};
|
|
787
|
+
try {
|
|
788
|
+
const url = parseTarget(req.url);
|
|
789
|
+
if (!url)
|
|
790
|
+
return reject(400, "bad-request");
|
|
791
|
+
if (this.closing)
|
|
792
|
+
return reject(503, "shutting-down");
|
|
793
|
+
if (url.pathname !== this.path)
|
|
794
|
+
return reject(404, "not-found");
|
|
795
|
+
const ip = this.clientIp(req);
|
|
796
|
+
const L = this.config.limits;
|
|
797
|
+
// F-5 / pre-release review: the higher IPv4 per-address cap is for shared NAT.
|
|
798
|
+
// Past POOL_PRESSURE of the global cap, every address gets the strict
|
|
799
|
+
// per-IP cap, so a few addresses can't take the whole pool.
|
|
800
|
+
const pressured = this.conns.size >= Math.floor(L.maxConnections * POOL_PRESSURE);
|
|
801
|
+
const perIpCap = isIPv4(ip) && !pressured ? L.maxConnectionsPerIpv4 : L.maxConnectionsPerIp;
|
|
802
|
+
if ((this.perIp.get(ip) ?? 0) >= perIpCap)
|
|
803
|
+
return reject(429, "too-many-connections");
|
|
804
|
+
// Full (pre-release re-review M-1): room comes only from an address holding
|
|
805
|
+
// more than the strict per-IP cap, so every address keeps up to that
|
|
806
|
+
// many connections whatever others do. When none is over it, the
|
|
807
|
+
// newcomer is refused as before. One newcomer address may cause only
|
|
808
|
+
// POOL_EVICTIONS_PER_IP_PER_MINUTE evictions.
|
|
809
|
+
const full = this.conns.size >= L.maxConnections;
|
|
810
|
+
if (full && !this.poolVictim())
|
|
811
|
+
return reject(503, "too-many-connections");
|
|
812
|
+
// Unauthenticated sockets: a small per-IP cap, and a global cap that,
|
|
813
|
+
// when full, drops the OLDEST unauthenticated socket instead of refusing
|
|
814
|
+
// the newcomer, so stale sockets can't lock honest clients out.
|
|
815
|
+
if ((this.unauthPerIp.get(ip) ?? 0) >= L.maxUnauthPerIp)
|
|
816
|
+
return reject(429, "too-many-connections");
|
|
817
|
+
// N3: new connections per IP bucket per minute.
|
|
818
|
+
if (!this.limiters.connectsIp.take(ip))
|
|
819
|
+
return reject(429, "rate-limited");
|
|
820
|
+
while (this.unauthConns.size >= L.maxUnauthConnections) {
|
|
821
|
+
const oldest = this.unauthConns.values().next().value;
|
|
822
|
+
this.leaveUnauth(oldest);
|
|
823
|
+
oldest.ws.close(CLOSE.unauthTimeout, "make room");
|
|
824
|
+
setTimeout(() => oldest.ws.terminate(), 1000).unref();
|
|
825
|
+
}
|
|
826
|
+
if (full && !this.limiters.poolEvictIp.take(ip))
|
|
827
|
+
return reject(503, "too-many-connections");
|
|
828
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
829
|
+
// L-4: evict only once the upgrade has succeeded, so a failed
|
|
830
|
+
// upgrade costs nobody a connection. If the room went meanwhile and
|
|
831
|
+
// no address is over the strict cap any more, the newcomer leaves.
|
|
832
|
+
if (this.conns.size >= L.maxConnections) {
|
|
833
|
+
const victim = this.poolVictim();
|
|
834
|
+
if (!victim) {
|
|
835
|
+
this.metrics.inc("connections_rejected", { reason: "too-many-connections" });
|
|
836
|
+
ws.close(CLOSE.tooManyConnections, "relay full");
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
this.evict(victim);
|
|
840
|
+
}
|
|
841
|
+
this.onConnection(ws, ip);
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
catch (e) {
|
|
845
|
+
this.log.error("upgrade failed", { error: e.message });
|
|
846
|
+
socket.destroy();
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* The global cap is full: the connection to close for a newcomer, or
|
|
851
|
+
* undefined when none may go (pre-release re-review M-1).
|
|
852
|
+
* - Only an address bucket holding MORE than the strict per-IP cap gives
|
|
853
|
+
* one up (the biggest such bucket), so no address is pushed below it.
|
|
854
|
+
* - In that bucket, the userId with the most connections there gives one
|
|
855
|
+
* up (ties: all of the tied userIds), its least recently active one, so
|
|
856
|
+
* one user's churn can't cycle through the others' idle receivers.
|
|
857
|
+
* - A bucket with no authenticated connection gives up its least recently
|
|
858
|
+
* active unauthenticated one.
|
|
859
|
+
*/
|
|
860
|
+
poolVictim() {
|
|
861
|
+
const strict = this.config.limits.maxConnectionsPerIp;
|
|
862
|
+
let bucket;
|
|
863
|
+
let most = strict;
|
|
864
|
+
for (const [ip, n] of this.perIp) {
|
|
865
|
+
if (n > most)
|
|
866
|
+
[bucket, most] = [ip, n];
|
|
867
|
+
}
|
|
868
|
+
if (bucket === undefined)
|
|
869
|
+
return undefined;
|
|
870
|
+
const perIss = new Map();
|
|
871
|
+
let unauth;
|
|
872
|
+
for (const c of this.conns) {
|
|
873
|
+
if (c.ip !== bucket || c.kicked)
|
|
874
|
+
continue;
|
|
875
|
+
if (!c.auth) {
|
|
876
|
+
if (!unauth || c.lastActive < unauth.lastActive)
|
|
877
|
+
unauth = c;
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
const list = perIss.get(c.auth.iss);
|
|
881
|
+
if (list)
|
|
882
|
+
list.push(c);
|
|
883
|
+
else
|
|
884
|
+
perIss.set(c.auth.iss, [c]);
|
|
885
|
+
}
|
|
886
|
+
let top = 0;
|
|
887
|
+
for (const l of perIss.values())
|
|
888
|
+
top = Math.max(top, l.length);
|
|
889
|
+
let victim;
|
|
890
|
+
for (const l of perIss.values()) {
|
|
891
|
+
if (l.length !== top)
|
|
892
|
+
continue;
|
|
893
|
+
for (const c of l)
|
|
894
|
+
if (!victim || c.lastActive < victim.lastActive)
|
|
895
|
+
victim = c;
|
|
896
|
+
}
|
|
897
|
+
return victim ?? unauth;
|
|
898
|
+
}
|
|
899
|
+
evict(victim) {
|
|
900
|
+
this.metrics.inc("connections_rejected", { reason: "evicted-pool-full" });
|
|
901
|
+
if (this.log.debugEnabled)
|
|
902
|
+
this.log.debug("connection evicted for a newcomer", { conn: victim.id });
|
|
903
|
+
victim.ws.close(CLOSE.tooManyConnections, "relay full");
|
|
904
|
+
victim.ws.terminate();
|
|
905
|
+
this.onClose(victim);
|
|
906
|
+
}
|
|
907
|
+
/** Removes `conn` from the unauthenticated set (on auth, close or eviction). */
|
|
908
|
+
leaveUnauth(conn) {
|
|
909
|
+
if (!this.unauthConns.delete(conn))
|
|
910
|
+
return;
|
|
911
|
+
if (conn.unauthTimer)
|
|
912
|
+
clearTimeout(conn.unauthTimer);
|
|
913
|
+
const n = (this.unauthPerIp.get(conn.ip) ?? 1) - 1;
|
|
914
|
+
if (n <= 0)
|
|
915
|
+
this.unauthPerIp.delete(conn.ip);
|
|
916
|
+
else
|
|
917
|
+
this.unauthPerIp.set(conn.ip, n);
|
|
918
|
+
}
|
|
919
|
+
onConnection(ws, ip) {
|
|
920
|
+
const conn = {
|
|
921
|
+
id: this.nextConnId++,
|
|
922
|
+
ws,
|
|
923
|
+
ip,
|
|
924
|
+
nonce: b64uEncode(randomBytes(32)),
|
|
925
|
+
pow: this.config.powBits,
|
|
926
|
+
lastSentRid: 0,
|
|
927
|
+
pumping: false,
|
|
928
|
+
kicked: false,
|
|
929
|
+
alive: true,
|
|
930
|
+
lastActive: this.now(),
|
|
931
|
+
};
|
|
932
|
+
this.conns.add(conn);
|
|
933
|
+
this.unauthConns.add(conn);
|
|
934
|
+
this.unauthPerIp.set(ip, (this.unauthPerIp.get(ip) ?? 0) + 1);
|
|
935
|
+
conn.unauthTimer = setTimeout(() => {
|
|
936
|
+
if (!conn.auth)
|
|
937
|
+
ws.close(CLOSE.unauthTimeout, "authenticate or leave");
|
|
938
|
+
}, this.config.limits.unauthTimeoutSec * 1000);
|
|
939
|
+
conn.unauthTimer.unref();
|
|
940
|
+
this.perIp.set(ip, (this.perIp.get(ip) ?? 0) + 1);
|
|
941
|
+
this.metrics.inc("connections");
|
|
942
|
+
if (this.log.debugEnabled)
|
|
943
|
+
this.log.debug("connection open", { conn: conn.id, ip: redact(ip) });
|
|
944
|
+
ws.on("pong", () => (conn.alive = true));
|
|
945
|
+
ws.on("message", (data, isBinary) => this.onFrame(conn, data, isBinary));
|
|
946
|
+
ws.on("error", (e) => {
|
|
947
|
+
// ws closes with 1009 by itself when a frame exceeds maxPayload.
|
|
948
|
+
if (this.log.debugEnabled)
|
|
949
|
+
this.log.debug("connection error", { conn: conn.id, error: e.message });
|
|
950
|
+
});
|
|
951
|
+
ws.on("close", () => this.onClose(conn));
|
|
952
|
+
this.reply(conn, {
|
|
953
|
+
t: "hello",
|
|
954
|
+
relay: this.config.relayUrl,
|
|
955
|
+
nonce: conn.nonce,
|
|
956
|
+
pow: conn.pow,
|
|
957
|
+
limits: this.advertisedLimits(),
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
onClose(conn) {
|
|
961
|
+
if (!this.conns.delete(conn))
|
|
962
|
+
return;
|
|
963
|
+
if (conn.pumpTimer)
|
|
964
|
+
clearTimeout(conn.pumpTimer);
|
|
965
|
+
if (conn.unauthTimer)
|
|
966
|
+
clearTimeout(conn.unauthTimer);
|
|
967
|
+
const n = (this.perIp.get(conn.ip) ?? 1) - 1;
|
|
968
|
+
if (n <= 0)
|
|
969
|
+
this.perIp.delete(conn.ip);
|
|
970
|
+
else
|
|
971
|
+
this.perIp.set(conn.ip, n);
|
|
972
|
+
if (conn.auth)
|
|
973
|
+
this.unregister(conn, conn.auth);
|
|
974
|
+
this.leaveUnauth(conn);
|
|
975
|
+
if (this.log.debugEnabled)
|
|
976
|
+
this.log.debug("connection closed", { conn: conn.id });
|
|
977
|
+
}
|
|
978
|
+
/** Removes an authenticated connection from the mailbox and userId maps. */
|
|
979
|
+
unregister(conn, auth) {
|
|
980
|
+
const key = mboxKey(auth.iss, auth.did);
|
|
981
|
+
const set = this.byMailbox.get(key);
|
|
982
|
+
set?.delete(conn);
|
|
983
|
+
if (set && set.size === 0)
|
|
984
|
+
this.byMailbox.delete(key);
|
|
985
|
+
const mine = this.byIss.get(auth.iss);
|
|
986
|
+
mine?.delete(conn);
|
|
987
|
+
if (mine && mine.size === 0)
|
|
988
|
+
this.byIss.delete(auth.iss);
|
|
989
|
+
const r = this.restrictedByIss.get(auth.iss);
|
|
990
|
+
r?.delete(conn);
|
|
991
|
+
if (r && r.size === 0)
|
|
992
|
+
this.restrictedByIss.delete(auth.iss);
|
|
993
|
+
if (conn.restrictedTimer)
|
|
994
|
+
clearTimeout(conn.restrictedTimer);
|
|
995
|
+
conn.restrictedTimer = undefined;
|
|
996
|
+
if (conn.certTimer)
|
|
997
|
+
clearTimeout(conn.certTimer);
|
|
998
|
+
conn.certTimer = undefined;
|
|
999
|
+
}
|
|
1000
|
+
reply(conn, msg) {
|
|
1001
|
+
if (conn.ws.readyState === WebSocket.OPEN)
|
|
1002
|
+
conn.ws.send(JSON.stringify(msg));
|
|
1003
|
+
}
|
|
1004
|
+
ok(conn, id) {
|
|
1005
|
+
this.reply(conn, id === undefined ? { t: "ok" } : { t: "ok", id });
|
|
1006
|
+
}
|
|
1007
|
+
error(conn, id, code) {
|
|
1008
|
+
this.reply(conn, id === undefined ? { t: "error", code } : { t: "error", id, code });
|
|
1009
|
+
}
|
|
1010
|
+
onFrame(conn, data, isBinary) {
|
|
1011
|
+
if (conn.kicked)
|
|
1012
|
+
return;
|
|
1013
|
+
conn.alive = true;
|
|
1014
|
+
conn.lastActive = this.now();
|
|
1015
|
+
// Every frame type costs a token before any parsing (M3).
|
|
1016
|
+
if (!this.limiters.frames.take(String(conn.id))) {
|
|
1017
|
+
this.metrics.inc("frames_rejected", { reason: "rate-limited" });
|
|
1018
|
+
return this.error(conn, undefined, "rate-limited");
|
|
1019
|
+
}
|
|
1020
|
+
let msg;
|
|
1021
|
+
try {
|
|
1022
|
+
if (isBinary)
|
|
1023
|
+
throw new Error("binary");
|
|
1024
|
+
const text = Array.isArray(data) ? Buffer.concat(data).toString("utf8") : Buffer.from(data).toString("utf8");
|
|
1025
|
+
const v = JSON.parse(text);
|
|
1026
|
+
if (typeof v !== "object" || v === null || Array.isArray(v) || typeof v.t !== "string") {
|
|
1027
|
+
throw new Error("shape");
|
|
1028
|
+
}
|
|
1029
|
+
msg = v;
|
|
1030
|
+
}
|
|
1031
|
+
catch {
|
|
1032
|
+
this.metrics.inc("frames_rejected", { reason: "malformed" });
|
|
1033
|
+
return this.error(conn, undefined, "bad-request");
|
|
1034
|
+
}
|
|
1035
|
+
const rawId = msg.id;
|
|
1036
|
+
if (rawId !== undefined && (typeof rawId !== "string" || rawId.length > MAX_ID_LEN)) {
|
|
1037
|
+
this.metrics.inc("frames_rejected", { reason: "bad-id" });
|
|
1038
|
+
return this.error(conn, undefined, "bad-request");
|
|
1039
|
+
}
|
|
1040
|
+
const id = rawId;
|
|
1041
|
+
try {
|
|
1042
|
+
switch (msg.t) {
|
|
1043
|
+
case "auth":
|
|
1044
|
+
return this.onAuth(conn, msg, id);
|
|
1045
|
+
case "link-put":
|
|
1046
|
+
return this.onLinkPut(conn, msg, id);
|
|
1047
|
+
case "link-get":
|
|
1048
|
+
return this.onLinkGet(conn, msg, id);
|
|
1049
|
+
case "invite-get":
|
|
1050
|
+
return this.onInviteGet(conn, msg, id);
|
|
1051
|
+
}
|
|
1052
|
+
if (!conn.auth)
|
|
1053
|
+
return this.error(conn, id, "auth-required");
|
|
1054
|
+
const auth = conn.auth;
|
|
1055
|
+
// An unlisted device may only publish the identity document that lists it.
|
|
1056
|
+
if (auth.restricted && msg.t !== "identity")
|
|
1057
|
+
return this.error(conn, id, "forbidden");
|
|
1058
|
+
switch (msg.t) {
|
|
1059
|
+
case "send":
|
|
1060
|
+
return this.onSend(conn, auth, msg, id);
|
|
1061
|
+
case "ack":
|
|
1062
|
+
return this.onAck(conn, auth, msg, id);
|
|
1063
|
+
case "revoke":
|
|
1064
|
+
return this.onRevoke(conn, auth, msg, id);
|
|
1065
|
+
case "identity":
|
|
1066
|
+
return this.onIdentity(conn, auth, msg, id);
|
|
1067
|
+
case "link-open":
|
|
1068
|
+
return this.onLinkOpen(conn, auth, msg, id);
|
|
1069
|
+
case "invite-put":
|
|
1070
|
+
return this.onInvitePut(conn, auth, msg, id);
|
|
1071
|
+
case "invite-del":
|
|
1072
|
+
return this.onInviteDel(conn, auth, msg, id);
|
|
1073
|
+
case "invite-list":
|
|
1074
|
+
return this.onInviteList(conn, auth, id);
|
|
1075
|
+
case "circle-put":
|
|
1076
|
+
return this.onCirclePut(conn, auth, msg, id);
|
|
1077
|
+
default:
|
|
1078
|
+
this.metrics.inc("frames_rejected", { reason: "unknown-type" });
|
|
1079
|
+
return this.error(conn, id, "bad-request");
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
catch (e) {
|
|
1083
|
+
// A bug, not a client error; never echo details to the client.
|
|
1084
|
+
this.log.error("frame handler failed", { t: String(msg.t).slice(0, 32), error: e.message });
|
|
1085
|
+
this.error(conn, id, "bad-request");
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
// -------------------------------------------------------------------------
|
|
1089
|
+
// §5.2 auth, and keeping rule 6 true for live sessions
|
|
1090
|
+
/**
|
|
1091
|
+
* Closes `conn` as no longer authorised (N5): its auth is cleared and it
|
|
1092
|
+
* leaves the mailbox and userId maps at once, so nothing more is delivered
|
|
1093
|
+
* to it and none of its frames are processed during the close handshake.
|
|
1094
|
+
* The socket is terminated if the peer doesn't finish the handshake.
|
|
1095
|
+
*/
|
|
1096
|
+
kick(conn, id, why, code = CLOSE.authFailed) {
|
|
1097
|
+
if (this.log.debugEnabled)
|
|
1098
|
+
this.log.debug("connection deauthorised", { conn: conn.id, why });
|
|
1099
|
+
const notMember = why === "not-member";
|
|
1100
|
+
this.error(conn, id, notMember ? "not-member" : "auth-failed");
|
|
1101
|
+
if (conn.auth)
|
|
1102
|
+
this.unregister(conn, conn.auth);
|
|
1103
|
+
conn.auth = undefined;
|
|
1104
|
+
conn.kicked = true;
|
|
1105
|
+
if (conn.pumpTimer)
|
|
1106
|
+
clearTimeout(conn.pumpTimer);
|
|
1107
|
+
conn.ws.close(code, code === CLOSE.certExpired ? "certificate expired" : notMember ? "not a member" : "device not allowed");
|
|
1108
|
+
setTimeout(() => conn.ws.terminate(), 1000).unref();
|
|
1109
|
+
}
|
|
1110
|
+
/** M1: after the allowlist of `iss` changes, close every live connection of a device it no longer lists. */
|
|
1111
|
+
enforceAllowlist(iss) {
|
|
1112
|
+
const allowed = this.identity.allowedDevices(iss);
|
|
1113
|
+
if (!allowed)
|
|
1114
|
+
return;
|
|
1115
|
+
for (const c of this.byIss.get(iss) ?? []) {
|
|
1116
|
+
if (c.auth && !c.auth.restricted && !allowed.has(c.auth.did))
|
|
1117
|
+
this.kick(c, undefined, "revoked");
|
|
1118
|
+
}
|
|
1119
|
+
const restricted = this.restrictedByIss.get(iss);
|
|
1120
|
+
if (restricted && restricted.size > 0) {
|
|
1121
|
+
const revoked = this.identity.revoked(iss);
|
|
1122
|
+
for (const c of [...restricted])
|
|
1123
|
+
if (c.auth && revoked.has(c.auth.did))
|
|
1124
|
+
this.kick(c, undefined, "revoked");
|
|
1125
|
+
this.promoteRestricted(iss);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Members-only: after the allowlist, the circle or a provisional admission
|
|
1130
|
+
* changed, every live connection of a userId no longer admitted is closed.
|
|
1131
|
+
*/
|
|
1132
|
+
enforceMembers() {
|
|
1133
|
+
const gone = new Set();
|
|
1134
|
+
for (const iss of [...this.byIss.keys(), ...this.restrictedByIss.keys()]) {
|
|
1135
|
+
if (!this.members.admitted(iss))
|
|
1136
|
+
gone.add(iss);
|
|
1137
|
+
}
|
|
1138
|
+
for (const iss of gone) {
|
|
1139
|
+
for (const c of [...(this.byIss.get(iss) ?? []), ...(this.restrictedByIss.get(iss) ?? [])])
|
|
1140
|
+
this.kick(c, undefined, "not-member");
|
|
1141
|
+
}
|
|
1142
|
+
if (gone.size > 0)
|
|
1143
|
+
this.log.info("members-only: closed the connections of removed members", { userIds: gone.size });
|
|
1144
|
+
}
|
|
1145
|
+
/** Replaces the members-only allowlist (and deny list) at runtime (SIGHUP), closing the connections of anyone removed. */
|
|
1146
|
+
setAllow(list, deny) {
|
|
1147
|
+
this.members.setAllow(list, deny);
|
|
1148
|
+
this.enforceMembers();
|
|
1149
|
+
}
|
|
1150
|
+
onAuth(conn, msg, id) {
|
|
1151
|
+
const fail = (why, code = "auth-failed", close = CLOSE.authFailed) => {
|
|
1152
|
+
this.metrics.inc("auth", { result: "fail" });
|
|
1153
|
+
if (this.log.debugEnabled)
|
|
1154
|
+
this.log.debug("auth failed", { conn: conn.id, why });
|
|
1155
|
+
this.error(conn, id, code);
|
|
1156
|
+
conn.ws.close(close, "auth failed");
|
|
1157
|
+
};
|
|
1158
|
+
if (conn.auth)
|
|
1159
|
+
return this.error(conn, id, "bad-request");
|
|
1160
|
+
// N3: auth attempts per IP bucket (each can create a device row).
|
|
1161
|
+
const v4 = isIPv4(conn.ip);
|
|
1162
|
+
if (!(v4 ? this.limiters.authsIp4 : this.limiters.authsIp).take(conn.ip))
|
|
1163
|
+
return fail("rate-limited", "rate-limited", CLOSE.tooManyConnections);
|
|
1164
|
+
if (typeof msg.cert !== "string" || typeof msg.sig !== "string")
|
|
1165
|
+
return fail("shape");
|
|
1166
|
+
const nowSec = Math.floor(this.now() / 1000);
|
|
1167
|
+
let cert;
|
|
1168
|
+
try {
|
|
1169
|
+
cert = this.crypto.verifyDeviceCert(msg.cert, { now: nowSec });
|
|
1170
|
+
}
|
|
1171
|
+
catch {
|
|
1172
|
+
return fail("cert");
|
|
1173
|
+
}
|
|
1174
|
+
// The signature binds this relay's canonical URL and this connection's nonce.
|
|
1175
|
+
if (!this.crypto.verifyRelayAuth(cert, this.config.relayUrl, conn.nonce, msg.sig))
|
|
1176
|
+
return fail("sig");
|
|
1177
|
+
// Members-only: refused before anything is stored for this device. A redeemed
|
|
1178
|
+
// invite admission (`admit`, the key the inviter's grant hashes) admits it provisionally.
|
|
1179
|
+
let admittedBy;
|
|
1180
|
+
if (!this.members.admitted(cert.iss)) {
|
|
1181
|
+
// Re-checked after redeeming: a redemption admits only someone the relay would admit (not a denied userId).
|
|
1182
|
+
if (!(typeof msg.admit === "string" && this.members.redeem(msg.admit, cert.iss) && this.members.admitted(cert.iss))) {
|
|
1183
|
+
this.metrics.inc("auth", { result: "not-member" });
|
|
1184
|
+
if (this.log.debugEnabled)
|
|
1185
|
+
this.log.debug("auth refused: not a member", { conn: conn.id, iss: redact(cert.iss) });
|
|
1186
|
+
this.error(conn, id, "not-member");
|
|
1187
|
+
conn.ws.close(CLOSE.authFailed, "not a member");
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
admittedBy = "invite";
|
|
1191
|
+
this.log.info("members-only: admitted a userId through a member's invite", { until: Math.floor(this.now() / 1000) + this.config.inviteAdmitSec });
|
|
1192
|
+
}
|
|
1193
|
+
// §2.3 rule 6, when the relay holds the issuer's identity document.
|
|
1194
|
+
const allowed = this.identity.allowedDevices(cert.iss);
|
|
1195
|
+
const restricted = allowed !== undefined && !allowed.has(cert.did);
|
|
1196
|
+
// §5.2: one iss per did.
|
|
1197
|
+
const bound = this.store.deviceIssuer(cert.did);
|
|
1198
|
+
if (bound !== undefined && bound !== cert.iss)
|
|
1199
|
+
return fail("did-bound");
|
|
1200
|
+
if (restricted) {
|
|
1201
|
+
// A did a held (or recently discarded) version listed, and the allowlist doesn't: revoked.
|
|
1202
|
+
// Not even a restricted connection; a restore always brings a new did.
|
|
1203
|
+
if (this.identity.revoked(cert.iss).has(cert.did))
|
|
1204
|
+
return fail("revoked");
|
|
1205
|
+
// Restricted connections have their own small cap, so they can't crowd out listed devices.
|
|
1206
|
+
if ((this.restrictedByIss.get(cert.iss)?.size ?? 0) >= this.config.limits.restrictedPerIss) {
|
|
1207
|
+
return fail("too-many-restricted", "full", CLOSE.tooManyConnections);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
else if ((this.byIss.get(cert.iss)?.size ?? 0) >= this.config.limits.maxConnectionsPerIss) {
|
|
1211
|
+
return fail("too-many-for-iss", "full", CLOSE.tooManyConnections);
|
|
1212
|
+
}
|
|
1213
|
+
if (bound === undefined) {
|
|
1214
|
+
// N3/M-4: new device rows are bounded per IP per day and globally. A did
|
|
1215
|
+
// listed in its issuer's held identity document is always admitted.
|
|
1216
|
+
const listed = allowed?.has(cert.did) ?? false;
|
|
1217
|
+
// The IPv4 allowance applies only while the device table has room (pre-release review).
|
|
1218
|
+
const devicesPressured = this.deviceCount >= Math.floor(this.config.limits.maxDevices * POOL_PRESSURE);
|
|
1219
|
+
const newDevices = v4 && !devicesPressured ? this.limiters.newDevicesIp4 : this.limiters.newDevicesIp;
|
|
1220
|
+
if (!listed && !newDevices.has(conn.ip))
|
|
1221
|
+
return fail("new-device-rate", "rate-limited", CLOSE.tooManyConnections);
|
|
1222
|
+
if (this.deviceCount >= this.config.limits.maxDevices && !this.evictDevice() && !listed) {
|
|
1223
|
+
return fail("device-cap", "full", CLOSE.tooManyConnections);
|
|
1224
|
+
}
|
|
1225
|
+
if (!listed)
|
|
1226
|
+
newDevices.take(conn.ip);
|
|
1227
|
+
}
|
|
1228
|
+
if (this.store.touchDevice(cert.did, cert.iss, this.now()))
|
|
1229
|
+
this.deviceCount++;
|
|
1230
|
+
conn.auth = { iss: cert.iss, did: cert.did, cert: msg.cert, certExp: cert.exp, verified: cert, ...(restricted ? { restricted } : {}) };
|
|
1231
|
+
this.leaveUnauth(conn);
|
|
1232
|
+
this.metrics.inc("auth", { result: restricted ? "restricted" : "ok" });
|
|
1233
|
+
if (this.log.debugEnabled)
|
|
1234
|
+
this.log.debug("auth ok", { conn: conn.id, iss: redact(cert.iss), did: redact(cert.did), restricted });
|
|
1235
|
+
if (restricted) {
|
|
1236
|
+
let rs = this.restrictedByIss.get(cert.iss);
|
|
1237
|
+
if (!rs)
|
|
1238
|
+
this.restrictedByIss.set(cert.iss, (rs = new Set()));
|
|
1239
|
+
rs.add(conn);
|
|
1240
|
+
// Closed if not upgraded in time, and in any case when its certificate expires.
|
|
1241
|
+
const untilExp = cert.exp * 1000 - this.now();
|
|
1242
|
+
conn.restrictedTimer = setTimeout(() => this.kick(conn, undefined, "restricted-expired"), Math.max(0, Math.min(this.config.limits.restrictedTimeoutSec * 1000, untilExp)));
|
|
1243
|
+
conn.restrictedTimer.unref();
|
|
1244
|
+
const out = { t: "ok", restricted: true };
|
|
1245
|
+
if (id !== undefined)
|
|
1246
|
+
out.id = id;
|
|
1247
|
+
if (admittedBy)
|
|
1248
|
+
out.admitted = admittedBy;
|
|
1249
|
+
this.reply(conn, out);
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
let mine = this.byIss.get(cert.iss);
|
|
1253
|
+
if (!mine)
|
|
1254
|
+
this.byIss.set(cert.iss, (mine = new Set()));
|
|
1255
|
+
mine.add(conn);
|
|
1256
|
+
this.bindMailbox(conn, conn.auth);
|
|
1257
|
+
this.armCertExpiry(conn);
|
|
1258
|
+
const circle = this.members.circleInfo();
|
|
1259
|
+
if (circle || admittedBy) {
|
|
1260
|
+
// Members-only: the circle this relay follows (so members push its new versions), and
|
|
1261
|
+
// whether this auth used an invite admission (so the client can forget the key).
|
|
1262
|
+
const out = { t: "ok" };
|
|
1263
|
+
if (id !== undefined)
|
|
1264
|
+
out.id = id;
|
|
1265
|
+
if (circle)
|
|
1266
|
+
out.circle = circle;
|
|
1267
|
+
if (admittedBy)
|
|
1268
|
+
out.admitted = admittedBy;
|
|
1269
|
+
this.reply(conn, out);
|
|
1270
|
+
}
|
|
1271
|
+
else
|
|
1272
|
+
this.ok(conn, id);
|
|
1273
|
+
// Everything un-acked, in arrival order (§5.4 redelivery).
|
|
1274
|
+
this.pump(conn);
|
|
1275
|
+
}
|
|
1276
|
+
/**
|
|
1277
|
+
* A connection lives no longer than its device certificate (review R3: what
|
|
1278
|
+
* makes the 91-day memory of discarded dids enough). Timers longer than
|
|
1279
|
+
* Node's ~24.8-day maximum re-arm in steps.
|
|
1280
|
+
*/
|
|
1281
|
+
armCertExpiry(conn) {
|
|
1282
|
+
if (conn.certTimer)
|
|
1283
|
+
clearTimeout(conn.certTimer);
|
|
1284
|
+
conn.certTimer = undefined;
|
|
1285
|
+
if (!conn.auth || conn.ws.readyState !== WebSocket.OPEN)
|
|
1286
|
+
return;
|
|
1287
|
+
const ms = conn.auth.certExp * 1000 - this.now();
|
|
1288
|
+
if (ms <= 0)
|
|
1289
|
+
return this.kick(conn, undefined, "cert-expired", CLOSE.certExpired);
|
|
1290
|
+
const max = 2 ** 31 - 1;
|
|
1291
|
+
conn.certTimer = setTimeout(() => (ms <= max ? this.kick(conn, undefined, "cert-expired", CLOSE.certExpired) : this.armCertExpiry(conn)), Math.min(ms, max));
|
|
1292
|
+
conn.certTimer.unref();
|
|
1293
|
+
}
|
|
1294
|
+
/** Binds an authenticated, listed connection to its mailbox (iss, did). */
|
|
1295
|
+
bindMailbox(conn, auth) {
|
|
1296
|
+
const key = mboxKey(auth.iss, auth.did);
|
|
1297
|
+
let set = this.byMailbox.get(key);
|
|
1298
|
+
if (!set)
|
|
1299
|
+
this.byMailbox.set(key, (set = new Set()));
|
|
1300
|
+
set.add(conn);
|
|
1301
|
+
}
|
|
1302
|
+
// -------------------------------------------------------------------------
|
|
1303
|
+
// §5.4 send
|
|
1304
|
+
/**
|
|
1305
|
+
* M-4: frees one device row: the least recently seen binding with no stored
|
|
1306
|
+
* envelopes, no live connection, and not in its issuer's held allowlist.
|
|
1307
|
+
*/
|
|
1308
|
+
evictDevice() {
|
|
1309
|
+
// N-L2: the store selects candidates (no envelopes, not in any allowlist)
|
|
1310
|
+
// with an indexed query; only live connections are skipped here, and
|
|
1311
|
+
// those are bounded by the connection caps.
|
|
1312
|
+
let after;
|
|
1313
|
+
for (;;) {
|
|
1314
|
+
const page = this.store.evictableDevices(64, after);
|
|
1315
|
+
if (page.length === 0)
|
|
1316
|
+
return false;
|
|
1317
|
+
for (const { did, iss } of page) {
|
|
1318
|
+
if (this.byMailbox.has(mboxKey(iss, did)))
|
|
1319
|
+
continue;
|
|
1320
|
+
this.store.deleteDevice(did);
|
|
1321
|
+
this.deviceCount--;
|
|
1322
|
+
return true;
|
|
1323
|
+
}
|
|
1324
|
+
const last = page[page.length - 1];
|
|
1325
|
+
after = { lastSeen: last.lastSeen, did: last.did };
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* A mailbox exists when the relay holds the recipient's identity document
|
|
1330
|
+
* and it lists `tdid` (rule 6 for receivers), or, with no document held,
|
|
1331
|
+
* when `tdid` has authenticated here bound to `to`.
|
|
1332
|
+
*/
|
|
1333
|
+
mailboxKnown(to, tdid) {
|
|
1334
|
+
const bound = this.store.deviceIssuer(tdid);
|
|
1335
|
+
if (bound !== undefined && bound !== to)
|
|
1336
|
+
return false;
|
|
1337
|
+
const st = this.identity.status(to);
|
|
1338
|
+
// L-b: a tombstoned identity has no mailboxes here (its allowlist still gates auth).
|
|
1339
|
+
if (st?.left)
|
|
1340
|
+
return false;
|
|
1341
|
+
if (st)
|
|
1342
|
+
return st.allowed.has(tdid);
|
|
1343
|
+
return bound === to;
|
|
1344
|
+
}
|
|
1345
|
+
capKey(iss, capid) {
|
|
1346
|
+
return b64uEncode(sha256(new TextEncoder().encode(`p2p/relay/cap|${iss}|${capid}`)));
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* L3/N2: what receivers see as `rid`: the internal rid (8 bytes, big-endian,
|
|
1350
|
+
* then 8 zero bytes) encrypted as one AES-128 block under a per-process key.
|
|
1351
|
+
* Opaque, deterministic (redelivery keeps the rid), and reversible without
|
|
1352
|
+
* any per-connection state.
|
|
1353
|
+
*/
|
|
1354
|
+
wireRid(rid) {
|
|
1355
|
+
const block = Buffer.alloc(16);
|
|
1356
|
+
block.writeBigUInt64BE(BigInt(rid), 0);
|
|
1357
|
+
const c = createCipheriv("aes-128-ecb", this.ridKey, null).setAutoPadding(false);
|
|
1358
|
+
return Buffer.concat([c.update(block), c.final()]).toString("base64url");
|
|
1359
|
+
}
|
|
1360
|
+
/** The internal rid of a wire rid, or undefined when it isn't one this process issued. */
|
|
1361
|
+
ridFromWire(wire) {
|
|
1362
|
+
const bytes = Buffer.from(wire, "base64url");
|
|
1363
|
+
if (bytes.length !== 16)
|
|
1364
|
+
return undefined;
|
|
1365
|
+
const d = createDecipheriv("aes-128-ecb", this.ridKey, null).setAutoPadding(false);
|
|
1366
|
+
const block = Buffer.concat([d.update(bytes), d.final()]);
|
|
1367
|
+
if (!block.subarray(8).equals(Buffer.alloc(8)))
|
|
1368
|
+
return undefined;
|
|
1369
|
+
const rid = block.readBigUInt64BE(0);
|
|
1370
|
+
return rid <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(rid) : undefined;
|
|
1371
|
+
}
|
|
1372
|
+
/** N1: the stored tag of a sender's IP bucket, keyed per process. */
|
|
1373
|
+
srcTag(ip) {
|
|
1374
|
+
return createHmac("sha256", this.srcKey).update(ip).digest().subarray(0, 12).toString("base64url");
|
|
1375
|
+
}
|
|
1376
|
+
/** F-6: eviction ranking for an envelope from `src` (the sender pays first, then the largest group). */
|
|
1377
|
+
evictPolicy(quota, src) {
|
|
1378
|
+
return { floor: Math.max(4096, Math.floor(quota / 16)), sender: src, quota };
|
|
1379
|
+
}
|
|
1380
|
+
onSend(conn, auth, msg, id) {
|
|
1381
|
+
const result = (code) => {
|
|
1382
|
+
this.metrics.inc("sends", { result: code });
|
|
1383
|
+
if (code === "sent")
|
|
1384
|
+
this.reply(conn, id === undefined ? { t: "sent" } : { t: "sent", id });
|
|
1385
|
+
else
|
|
1386
|
+
this.error(conn, id, code);
|
|
1387
|
+
};
|
|
1388
|
+
const { to, tdid, env: envJws, cap: capJws, pow } = msg;
|
|
1389
|
+
if (typeof to !== "string" || typeof tdid !== "string" || typeof envJws !== "string")
|
|
1390
|
+
return result("bad-envelope");
|
|
1391
|
+
if (capJws !== undefined && typeof capJws !== "string")
|
|
1392
|
+
return result("bad-envelope");
|
|
1393
|
+
if (pow !== undefined && typeof pow !== "string")
|
|
1394
|
+
return result("bad-envelope");
|
|
1395
|
+
// 1. Parses, ≤ 64 KiB, and env.to/tdid match the routing fields.
|
|
1396
|
+
const size = Buffer.byteLength(envJws, "utf8");
|
|
1397
|
+
if (size > this.config.limits.envelopeBytes)
|
|
1398
|
+
return result("too-large");
|
|
1399
|
+
let env;
|
|
1400
|
+
try {
|
|
1401
|
+
env = this.crypto.parseOuterEnvelope(envJws);
|
|
1402
|
+
}
|
|
1403
|
+
catch {
|
|
1404
|
+
return result("bad-envelope");
|
|
1405
|
+
}
|
|
1406
|
+
if (env.to !== to || env.tdid !== tdid)
|
|
1407
|
+
return result("bad-envelope");
|
|
1408
|
+
// Cheap checks before any signature work (M3). Relay policy: a connection
|
|
1409
|
+
// sends only its own device's envelopes, so a captured envelope can't be
|
|
1410
|
+
// replayed into this relay by someone else.
|
|
1411
|
+
if (env.from !== auth.iss || env.fdid !== auth.did)
|
|
1412
|
+
return result("bad-envelope");
|
|
1413
|
+
// Members-only: nothing is stored for someone who can't come and get it.
|
|
1414
|
+
if (!this.members.admitted(env.to))
|
|
1415
|
+
return result("undeliverable");
|
|
1416
|
+
// Rule 6 for the sender, from the cached allowlist (M1).
|
|
1417
|
+
const senderAllowed = this.identity.allowedDevices(auth.iss);
|
|
1418
|
+
if (senderAllowed && !senderAllowed.has(auth.did))
|
|
1419
|
+
return this.kick(conn, id, "sender-revoked");
|
|
1420
|
+
// 120 sends/min per env.from, and byte budgets per connection and per IP
|
|
1421
|
+
// (H2), all before signatures and before a cap's `uses` can be spent.
|
|
1422
|
+
const L = this.limiters;
|
|
1423
|
+
const connKey = String(conn.id);
|
|
1424
|
+
if (!L.sends.has(env.from) || !L.sendBytesConn.has(connKey, size) || !L.sendBytesIp.has(conn.ip, size)) {
|
|
1425
|
+
return result("rate-limited");
|
|
1426
|
+
}
|
|
1427
|
+
L.sends.take(env.from);
|
|
1428
|
+
L.sendBytesConn.take(connKey, size);
|
|
1429
|
+
L.sendBytesIp.take(conn.ip, size);
|
|
1430
|
+
// 2. fcert (§2.3 rules 1–5) and the envelope signature under fcert.spk.
|
|
1431
|
+
// An fcert byte-identical to the authenticated cert was verified at auth.
|
|
1432
|
+
const nowMs = this.now();
|
|
1433
|
+
const nowSec = Math.floor(nowMs / 1000);
|
|
1434
|
+
try {
|
|
1435
|
+
let fcert;
|
|
1436
|
+
if (env.fcert === auth.cert) {
|
|
1437
|
+
if (nowSec >= auth.certExp)
|
|
1438
|
+
return result("bad-envelope");
|
|
1439
|
+
fcert = auth.verified;
|
|
1440
|
+
}
|
|
1441
|
+
else {
|
|
1442
|
+
fcert = this.crypto.verifyDeviceCert(env.fcert, { now: nowSec });
|
|
1443
|
+
}
|
|
1444
|
+
this.crypto.verifyEnvelope(env, fcert);
|
|
1445
|
+
}
|
|
1446
|
+
catch {
|
|
1447
|
+
return result("bad-envelope");
|
|
1448
|
+
}
|
|
1449
|
+
// N1: quotas checked before the mailbox lookup, so known and unknown
|
|
1450
|
+
// mailboxes always get the same answer. The store-wide hard ceiling is a
|
|
1451
|
+
// last resort: normally eviction keeps the store under storeMaxBytes.
|
|
1452
|
+
const src = this.srcTag(conn.ip);
|
|
1453
|
+
const quota = () => {
|
|
1454
|
+
if (this.storedBytes + size > this.config.limits.storeHardMaxBytes)
|
|
1455
|
+
return "undeliverable";
|
|
1456
|
+
if (!this.limiters.sourceAccepted.has(conn.ip, size))
|
|
1457
|
+
return "rate-limited";
|
|
1458
|
+
return undefined;
|
|
1459
|
+
};
|
|
1460
|
+
if (capJws !== undefined) {
|
|
1461
|
+
// 3. With a cap: every failure is the one `undeliverable` code.
|
|
1462
|
+
let cap;
|
|
1463
|
+
try {
|
|
1464
|
+
cap = this.crypto.verifyCapForSend(capJws, {
|
|
1465
|
+
relayUrl: this.config.relayUrl,
|
|
1466
|
+
to,
|
|
1467
|
+
envFrom: env.from,
|
|
1468
|
+
kind: env.kind,
|
|
1469
|
+
now: nowSec,
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
catch {
|
|
1473
|
+
return result("undeliverable");
|
|
1474
|
+
}
|
|
1475
|
+
// L1: a cap signed by a device the issuer's document no longer lists.
|
|
1476
|
+
const issuerAllowed = this.identity.allowedDevices(cap.iss);
|
|
1477
|
+
if (issuerAllowed && !issuerAllowed.has(cap.signerDid))
|
|
1478
|
+
return result("undeliverable");
|
|
1479
|
+
const key = this.capKey(cap.iss, cap.capid);
|
|
1480
|
+
const state = this.store.capState(key);
|
|
1481
|
+
if (state.revoked)
|
|
1482
|
+
return result("undeliverable");
|
|
1483
|
+
if (cap.uses !== undefined && state.uses >= cap.uses)
|
|
1484
|
+
return result("undeliverable");
|
|
1485
|
+
const over = quota();
|
|
1486
|
+
if (over)
|
|
1487
|
+
return result(over);
|
|
1488
|
+
if (!this.mailboxKnown(to, tdid))
|
|
1489
|
+
return result("undeliverable");
|
|
1490
|
+
if (cap.uses !== undefined)
|
|
1491
|
+
this.store.useCap(key, nowMs);
|
|
1492
|
+
this.limiters.sourceAccepted.take(conn.ip, size);
|
|
1493
|
+
result("sent");
|
|
1494
|
+
return this.storeAndDeliver(to, tdid, envJws, size, nowMs, src);
|
|
1495
|
+
}
|
|
1496
|
+
// 4. Without a cap: contact only, rate-limited three ways, PoW when asked.
|
|
1497
|
+
if (env.kind !== "contact")
|
|
1498
|
+
return result("undeliverable");
|
|
1499
|
+
const pairKey = `${env.from}\n${to}`;
|
|
1500
|
+
if (!L.contactSender.has(env.from) || !L.contactPair.has(pairKey) || !L.contactIp.has(conn.ip)) {
|
|
1501
|
+
return result("rate-limited");
|
|
1502
|
+
}
|
|
1503
|
+
if (conn.pow > 0) {
|
|
1504
|
+
let nonce;
|
|
1505
|
+
try {
|
|
1506
|
+
if (pow === undefined || pow.length > 128)
|
|
1507
|
+
throw new Error("pow");
|
|
1508
|
+
nonce = b64uDecode(pow);
|
|
1509
|
+
}
|
|
1510
|
+
catch {
|
|
1511
|
+
return result("undeliverable");
|
|
1512
|
+
}
|
|
1513
|
+
if (!this.crypto.powOk(env.bytes, nonce, conn.pow))
|
|
1514
|
+
return result("undeliverable");
|
|
1515
|
+
}
|
|
1516
|
+
L.contactSender.take(env.from);
|
|
1517
|
+
L.contactPair.take(pairKey);
|
|
1518
|
+
L.contactIp.take(conn.ip);
|
|
1519
|
+
// The quota is checked before the mailbox lookup, so a full relay answers
|
|
1520
|
+
// known and unknown mailboxes alike.
|
|
1521
|
+
const over = quota();
|
|
1522
|
+
if (over)
|
|
1523
|
+
return result(over);
|
|
1524
|
+
// Charged whether or not the mailbox exists (M-3).
|
|
1525
|
+
this.limiters.sourceAccepted.take(conn.ip, size);
|
|
1526
|
+
const known = this.mailboxKnown(to, tdid);
|
|
1527
|
+
// L2: answer before any store work, so timing doesn't tell a stored
|
|
1528
|
+
// contact from a silently dropped one (unknown mailbox, §5.4).
|
|
1529
|
+
result("sent");
|
|
1530
|
+
if (known)
|
|
1531
|
+
this.storeAndDeliver(to, tdid, envJws, size, nowMs, src);
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Stores an envelope, first evicting to stay under the quotas (N1): the
|
|
1535
|
+
* recipient's own oldest envelopes past recipientMaxBytes, then the oldest
|
|
1536
|
+
* envelopes of the largest mailboxes past storeMaxBytes. Filling the relay
|
|
1537
|
+
* therefore churns the biggest (usually the attacker's) mailboxes instead of
|
|
1538
|
+
* refusing everyone.
|
|
1539
|
+
*/
|
|
1540
|
+
storeAndDeliver(to, tdid, env, size, now, src) {
|
|
1541
|
+
const L = this.config.limits;
|
|
1542
|
+
try {
|
|
1543
|
+
this.store.transaction(() => {
|
|
1544
|
+
let evicted = 0;
|
|
1545
|
+
// N-M2: a source over its stored-bytes share loses its own oldest first.
|
|
1546
|
+
const forSource = this.store.sourceBytes(src) + size - L.sourceMaxBytes;
|
|
1547
|
+
if (forSource > 0)
|
|
1548
|
+
evicted += this.store.evictSource(src, forSource);
|
|
1549
|
+
const forRecipient = this.store.bytesForRecipient(to) + size - L.recipientMaxBytes;
|
|
1550
|
+
if (forRecipient > 0)
|
|
1551
|
+
evicted += this.store.evictRecipient(to, forRecipient, this.evictPolicy(L.recipientMaxBytes, src));
|
|
1552
|
+
const global = this.storedBytes - evicted + size - L.storeMaxBytes;
|
|
1553
|
+
if (global > 0)
|
|
1554
|
+
evicted += this.store.evictGlobal(global, this.evictPolicy(L.storeMaxBytes, src));
|
|
1555
|
+
const { droppedBytes } = this.store.putEnvelope({ to, tdid, env, size, receivedAt: now, src }, { maxEnvelopes: L.mailboxEnvelopes, maxBytes: L.mailboxBytes });
|
|
1556
|
+
this.storedBytes = Math.max(0, this.storedBytes - evicted + size - droppedBytes);
|
|
1557
|
+
if (evicted > 0)
|
|
1558
|
+
this.metrics.inc("envelopes_evicted");
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
catch (e) {
|
|
1562
|
+
this.log.error("store failed", { error: e.message });
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
for (const c of this.byMailbox.get(mboxKey(to, tdid)) ?? [])
|
|
1566
|
+
this.pump(c);
|
|
1567
|
+
}
|
|
1568
|
+
/** Sends the connection every stored envelope after the last one it was sent, in rid order, with backpressure. */
|
|
1569
|
+
pump(conn) {
|
|
1570
|
+
if (!conn.auth || conn.pumping)
|
|
1571
|
+
return;
|
|
1572
|
+
conn.pumping = true;
|
|
1573
|
+
try {
|
|
1574
|
+
const { iss, did } = conn.auth;
|
|
1575
|
+
const notBefore = this.now() - this.config.limits.retentionSec * 1000;
|
|
1576
|
+
while (conn.ws.readyState === WebSocket.OPEN) {
|
|
1577
|
+
if (conn.ws.bufferedAmount > HIGH_WATER_BYTES) {
|
|
1578
|
+
if (!conn.pumpTimer) {
|
|
1579
|
+
conn.pumpTimer = setTimeout(() => {
|
|
1580
|
+
conn.pumpTimer = undefined;
|
|
1581
|
+
this.pump(conn);
|
|
1582
|
+
}, 25);
|
|
1583
|
+
}
|
|
1584
|
+
break;
|
|
1585
|
+
}
|
|
1586
|
+
const rows = this.store.envelopesAfter(iss, did, conn.lastSentRid, notBefore, DELIVERY_PAGE);
|
|
1587
|
+
if (rows.length === 0) {
|
|
1588
|
+
// §5.4: the backlog is out. Once per connection, so a short command can stop listening
|
|
1589
|
+
// for queued envelopes at once instead of waiting out a quiet period.
|
|
1590
|
+
if (!conn.caughtUp) {
|
|
1591
|
+
conn.caughtUp = true;
|
|
1592
|
+
conn.ws.send('{"t":"caught-up"}');
|
|
1593
|
+
}
|
|
1594
|
+
break;
|
|
1595
|
+
}
|
|
1596
|
+
for (const r of rows) {
|
|
1597
|
+
conn.ws.send(JSON.stringify({ t: "env", rid: this.wireRid(r.rid), env: r.env }));
|
|
1598
|
+
conn.lastSentRid = r.rid;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
finally {
|
|
1603
|
+
conn.pumping = false;
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
onAck(conn, auth, msg, id) {
|
|
1607
|
+
const rids = msg.rids;
|
|
1608
|
+
if (!Array.isArray(rids) || rids.length > MAX_ACK_RIDS)
|
|
1609
|
+
return this.error(conn, id, "bad-request");
|
|
1610
|
+
if (!rids.every((r) => typeof r === "string" && WIRE_RID_RE.test(r)))
|
|
1611
|
+
return this.error(conn, id, "bad-request");
|
|
1612
|
+
const internal = [];
|
|
1613
|
+
for (const r of rids) {
|
|
1614
|
+
const rid = this.ridFromWire(r);
|
|
1615
|
+
if (rid !== undefined)
|
|
1616
|
+
internal.push(rid);
|
|
1617
|
+
}
|
|
1618
|
+
// Scoped to this connection's mailbox by the store.
|
|
1619
|
+
const { bytes } = this.store.ackEnvelopes(auth.iss, auth.did, internal);
|
|
1620
|
+
this.storedBytes = Math.max(0, this.storedBytes - bytes);
|
|
1621
|
+
}
|
|
1622
|
+
// -------------------------------------------------------------------------
|
|
1623
|
+
// §5.3 revoke
|
|
1624
|
+
onRevoke(conn, auth, msg, id) {
|
|
1625
|
+
const capid = msg.capid;
|
|
1626
|
+
let ok = typeof capid === "string";
|
|
1627
|
+
if (ok) {
|
|
1628
|
+
try {
|
|
1629
|
+
b64uDecode(capid, 16);
|
|
1630
|
+
}
|
|
1631
|
+
catch {
|
|
1632
|
+
ok = false;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (!ok)
|
|
1636
|
+
return this.error(conn, id, "bad-request");
|
|
1637
|
+
// H2: each revoke writes a row, so it's rate-limited per connection and per userId.
|
|
1638
|
+
if (!this.limiters.revokeConn.has(String(conn.id)) || !this.limiters.revokeIss.has(auth.iss)) {
|
|
1639
|
+
return this.error(conn, id, "rate-limited");
|
|
1640
|
+
}
|
|
1641
|
+
this.limiters.revokeConn.take(String(conn.id));
|
|
1642
|
+
this.limiters.revokeIss.take(auth.iss);
|
|
1643
|
+
// Keyed by (revoker's iss, capid): it can only ever affect caps whose
|
|
1644
|
+
// `iss` is the revoker, which is "only an authenticated device of cap.iss".
|
|
1645
|
+
this.store.revokeCap(this.capKey(auth.iss, capid), this.now());
|
|
1646
|
+
this.metrics.inc("revokes");
|
|
1647
|
+
this.ok(conn, id);
|
|
1648
|
+
}
|
|
1649
|
+
// -------------------------------------------------------------------------
|
|
1650
|
+
// §5.6 identity publish
|
|
1651
|
+
onIdentity(conn, auth, msg, id) {
|
|
1652
|
+
if (auth.restricted)
|
|
1653
|
+
return this.onRestrictedIdentity(conn, auth, msg, id);
|
|
1654
|
+
if (!this.limiters.identityIss.has(auth.iss) || !this.limiters.identityIp.has(conn.ip)) {
|
|
1655
|
+
this.metrics.inc("identity_publish", { result: "rate-limited" });
|
|
1656
|
+
return this.error(conn, id, "rate-limited");
|
|
1657
|
+
}
|
|
1658
|
+
this.limiters.identityIss.take(auth.iss);
|
|
1659
|
+
this.limiters.identityIp.take(conn.ip);
|
|
1660
|
+
const r = this.identity.publish(msg.doc, auth.iss);
|
|
1661
|
+
this.metrics.inc("identity_publish", { result: r.ok ? (r.left ? "left" : r.duplicate ? "duplicate" : "ok") : r.code });
|
|
1662
|
+
if (!r.ok)
|
|
1663
|
+
return this.error(conn, id, r.code);
|
|
1664
|
+
this.ok(conn, id);
|
|
1665
|
+
// M1: a new version may have dropped devices with live sessions.
|
|
1666
|
+
if (!r.duplicate)
|
|
1667
|
+
this.enforceAllowlist(auth.iss);
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* §2.7 restore over a restricted connection (H1/H2). The document is parsed
|
|
1671
|
+
* before anything is charged, and charged to its own limiter. Only a
|
|
1672
|
+
* version on top of the held history is accepted (one that extends every
|
|
1673
|
+
* tip, or merges them): never a fork, so a stale or stolen key holder can't
|
|
1674
|
+
* split the allowlist away from the restored device. When the version lists
|
|
1675
|
+
* this device (and its certificate is still valid), the connection becomes
|
|
1676
|
+
* a full one.
|
|
1677
|
+
*/
|
|
1678
|
+
onRestrictedIdentity(conn, auth, msg, id) {
|
|
1679
|
+
if (typeof msg.doc !== "string")
|
|
1680
|
+
return this.error(conn, id, "bad-identity");
|
|
1681
|
+
try {
|
|
1682
|
+
this.crypto.parseIdentityDoc(msg.doc);
|
|
1683
|
+
}
|
|
1684
|
+
catch {
|
|
1685
|
+
return this.error(conn, id, "bad-identity");
|
|
1686
|
+
}
|
|
1687
|
+
// Charged once per restricted connection: a restore that back-fills a lagging relay sends
|
|
1688
|
+
// several chaining versions in a row (review N-L1).
|
|
1689
|
+
if (!auth.charged) {
|
|
1690
|
+
if (!this.limiters.identityRestricted.take(auth.iss)) {
|
|
1691
|
+
this.metrics.inc("identity_publish", { result: "rate-limited" });
|
|
1692
|
+
return this.error(conn, id, "rate-limited");
|
|
1693
|
+
}
|
|
1694
|
+
auth.charged = true;
|
|
1695
|
+
}
|
|
1696
|
+
const r = this.identity.publish(msg.doc, auth.iss, { topOnly: true });
|
|
1697
|
+
this.metrics.inc("identity_publish", { result: r.ok ? (r.duplicate ? "duplicate" : "restricted") : r.code });
|
|
1698
|
+
if (!r.ok)
|
|
1699
|
+
return this.error(conn, id, r.code);
|
|
1700
|
+
this.ok(conn, id);
|
|
1701
|
+
if (!r.duplicate)
|
|
1702
|
+
this.enforceAllowlist(auth.iss);
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* After the allowlist of `iss` changes: every restricted connection whose
|
|
1706
|
+
* device it now lists becomes a full one (not only the publishing one,
|
|
1707
|
+
* pre-release review), its certificate re-checked.
|
|
1708
|
+
*/
|
|
1709
|
+
promoteRestricted(iss) {
|
|
1710
|
+
const allowed = this.identity.allowedDevices(iss);
|
|
1711
|
+
const set = this.restrictedByIss.get(iss);
|
|
1712
|
+
if (!allowed || !set)
|
|
1713
|
+
return;
|
|
1714
|
+
const nowSec = Math.floor(this.now() / 1000);
|
|
1715
|
+
for (const conn of [...set]) {
|
|
1716
|
+
const auth = conn.auth;
|
|
1717
|
+
if (!auth || !allowed.has(auth.did) || conn.ws.readyState !== WebSocket.OPEN)
|
|
1718
|
+
continue;
|
|
1719
|
+
if (nowSec >= auth.certExp) {
|
|
1720
|
+
this.kick(conn, undefined, "cert-expired", CLOSE.certExpired);
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
if ((this.byIss.get(iss)?.size ?? 0) >= this.config.limits.maxConnectionsPerIss) {
|
|
1724
|
+
this.kick(conn, undefined, "too-many-for-iss");
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
this.unregister(conn, auth);
|
|
1728
|
+
auth.restricted = undefined;
|
|
1729
|
+
let mine = this.byIss.get(iss);
|
|
1730
|
+
if (!mine)
|
|
1731
|
+
this.byIss.set(iss, (mine = new Set()));
|
|
1732
|
+
mine.add(conn);
|
|
1733
|
+
this.bindMailbox(conn, auth);
|
|
1734
|
+
this.armCertExpiry(conn);
|
|
1735
|
+
this.pump(conn);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
// -------------------------------------------------------------------------
|
|
1739
|
+
// §5.7 link mailboxes
|
|
1740
|
+
onLinkOpen(conn, auth, msg, id) {
|
|
1741
|
+
if (typeof msg.lid !== "string" || !LID_RE.test(msg.lid))
|
|
1742
|
+
return this.error(conn, id, "bad-request");
|
|
1743
|
+
if (!this.limiters.linkOpenIss.has(auth.iss) || !this.limiters.linkOpenIp.has(conn.ip)) {
|
|
1744
|
+
this.metrics.inc("link", { op: "open", result: "rate-limited" });
|
|
1745
|
+
return this.error(conn, id, "rate-limited");
|
|
1746
|
+
}
|
|
1747
|
+
this.limiters.linkOpenIss.take(auth.iss);
|
|
1748
|
+
this.limiters.linkOpenIp.take(conn.ip);
|
|
1749
|
+
const r = this.links.open(msg.lid, conn.id, auth.did, conn.ip);
|
|
1750
|
+
this.metrics.inc("link", { op: "open", result: r });
|
|
1751
|
+
if (r !== "ok")
|
|
1752
|
+
return this.error(conn, id, r === "exists" ? "exists" : "full");
|
|
1753
|
+
this.ok(conn, id);
|
|
1754
|
+
}
|
|
1755
|
+
linkArgs(msg) {
|
|
1756
|
+
const { lid, slot } = msg;
|
|
1757
|
+
if (typeof lid !== "string" || !LID_RE.test(lid))
|
|
1758
|
+
return undefined;
|
|
1759
|
+
if (slot !== "req" && slot !== "resp")
|
|
1760
|
+
return undefined;
|
|
1761
|
+
return { lid, slot };
|
|
1762
|
+
}
|
|
1763
|
+
onLinkPut(conn, msg, id) {
|
|
1764
|
+
if (!this.limiters.link.take(conn.ip)) {
|
|
1765
|
+
this.metrics.inc("link", { op: "put", result: "rate-limited" });
|
|
1766
|
+
return this.error(conn, id, "rate-limited");
|
|
1767
|
+
}
|
|
1768
|
+
const a = this.linkArgs(msg);
|
|
1769
|
+
if (!a || typeof msg.data !== "string")
|
|
1770
|
+
return this.error(conn, id, "bad-request");
|
|
1771
|
+
const r = this.links.put(a.lid, a.slot, msg.data, conn.id);
|
|
1772
|
+
this.metrics.inc("link", { op: "put", result: r });
|
|
1773
|
+
if (r !== "ok")
|
|
1774
|
+
return this.error(conn, id, r === "too-large" ? "too-large" : r === "forbidden" ? "forbidden" : r === "full" ? "full" : "not-found");
|
|
1775
|
+
this.ok(conn, id);
|
|
1776
|
+
}
|
|
1777
|
+
onLinkGet(conn, msg, id) {
|
|
1778
|
+
if (!this.limiters.link.take(conn.ip)) {
|
|
1779
|
+
this.metrics.inc("link", { op: "get", result: "rate-limited" });
|
|
1780
|
+
return this.error(conn, id, "rate-limited");
|
|
1781
|
+
}
|
|
1782
|
+
const a = this.linkArgs(msg);
|
|
1783
|
+
if (!a)
|
|
1784
|
+
return this.error(conn, id, "bad-request");
|
|
1785
|
+
const entries = this.links.get(a.lid, a.slot);
|
|
1786
|
+
this.metrics.inc("link", { op: "get", result: entries ? "ok" : "not-found" });
|
|
1787
|
+
if (!entries)
|
|
1788
|
+
return this.error(conn, id, "not-found");
|
|
1789
|
+
const out = { t: "link", lid: a.lid, slot: a.slot, entries };
|
|
1790
|
+
if (id !== undefined)
|
|
1791
|
+
out.id = id;
|
|
1792
|
+
this.reply(conn, out);
|
|
1793
|
+
}
|
|
1794
|
+
// -------------------------------------------------------------------------
|
|
1795
|
+
// P4 short-code invite mailboxes
|
|
1796
|
+
//
|
|
1797
|
+
// An authenticated device puts a sealed blob under `lid`, a hash of a code
|
|
1798
|
+
// secret the relay never sees; anyone may take it once (unauthenticated,
|
|
1799
|
+
// per-IP limited, misses limited harder). There is deliberately no
|
|
1800
|
+
// non-consuming read: a take is what lets the inviter notice an intercepted
|
|
1801
|
+
// code (docs/protocol.md P4).
|
|
1802
|
+
onInvitePut(conn, auth, msg, id) {
|
|
1803
|
+
const L = this.config.limits;
|
|
1804
|
+
const { lid, blob, ttl, admit } = msg;
|
|
1805
|
+
if (typeof lid !== "string" || !LID_RE.test(lid) || typeof blob !== "string" || blob.length === 0)
|
|
1806
|
+
return this.error(conn, id, "bad-request");
|
|
1807
|
+
if (typeof ttl !== "number" || !Number.isSafeInteger(ttl) || ttl < 1)
|
|
1808
|
+
return this.error(conn, id, "bad-request");
|
|
1809
|
+
if (admit !== undefined && (typeof admit !== "string" || !ADMIT_RE.test(admit)))
|
|
1810
|
+
return this.error(conn, id, "bad-request");
|
|
1811
|
+
// Members-only: only a full member's code may admit its redeemer (a provisional member's can't).
|
|
1812
|
+
const admits = this.members.enabled && this.config.inviteAdmitSec > 0 && typeof admit === "string";
|
|
1813
|
+
if (admits && !this.members.isFull(auth.iss)) {
|
|
1814
|
+
this.metrics.inc("invite", { op: "put", result: "forbidden" });
|
|
1815
|
+
return this.error(conn, id, "forbidden");
|
|
1816
|
+
}
|
|
1817
|
+
const size = Buffer.byteLength(blob, "utf8");
|
|
1818
|
+
if (size > L.inviteBlobBytes) {
|
|
1819
|
+
this.metrics.inc("invite", { op: "put", result: "too-large" });
|
|
1820
|
+
return this.error(conn, id, "too-large");
|
|
1821
|
+
}
|
|
1822
|
+
if (!this.limiters.invitePutIss.has(auth.iss) || !this.limiters.invitePutIp.has(conn.ip)) {
|
|
1823
|
+
this.metrics.inc("invite", { op: "put", result: "rate-limited" });
|
|
1824
|
+
return this.error(conn, id, "rate-limited");
|
|
1825
|
+
}
|
|
1826
|
+
this.limiters.invitePutIss.take(auth.iss);
|
|
1827
|
+
this.limiters.invitePutIp.take(conn.ip);
|
|
1828
|
+
const now = this.now();
|
|
1829
|
+
if (this.store.invitesOf(auth.iss, now).length >= L.inviteOpenPerIss) {
|
|
1830
|
+
this.metrics.inc("invite", { op: "put", result: "full" });
|
|
1831
|
+
return this.error(conn, id, "full");
|
|
1832
|
+
}
|
|
1833
|
+
const full = (why) => {
|
|
1834
|
+
this.metrics.inc("invite", { op: "put", result: why });
|
|
1835
|
+
return this.error(conn, id, "full");
|
|
1836
|
+
};
|
|
1837
|
+
// M2: one network can hold only so many bytes (IPv6 counted per /48), so a handful of
|
|
1838
|
+
// addresses can't fill the store.
|
|
1839
|
+
const src = this.srcTag(ipBucket48(conn.ip));
|
|
1840
|
+
if (this.store.inviteBytesOfSrc(src) + size > L.inviteBytesPerIp)
|
|
1841
|
+
return full("full-ip");
|
|
1842
|
+
if (this.store.inviteBytes() + size > L.inviteTotalBytes * 0.9) {
|
|
1843
|
+
// One bounded step here (F-4); the periodic sweep does the rest, and
|
|
1844
|
+
// eviction below takes expired invites before any live one.
|
|
1845
|
+
this.store.sweepInvites(now, this.inviteSweepRows);
|
|
1846
|
+
// The last tenth is reserved for identities the relay has known for a while.
|
|
1847
|
+
if (this.store.inviteBytes() + size > L.inviteTotalBytes * 0.9 && this.identityYoung(auth.iss, now))
|
|
1848
|
+
return full("full-young");
|
|
1849
|
+
// Completely full: the userIds holding the most bytes lose their newest invites, rather
|
|
1850
|
+
// than everyone being refused.
|
|
1851
|
+
const over = this.store.inviteBytes() + size - L.inviteTotalBytes;
|
|
1852
|
+
if (over > 0 && this.store.evictInvites(over, now) < over)
|
|
1853
|
+
return full("full");
|
|
1854
|
+
}
|
|
1855
|
+
const expiresAt = now + Math.min(ttl, L.inviteTtlMaxSec) * 1000;
|
|
1856
|
+
if (!this.store.putInvite({ lid, iss: auth.iss, blob, size, createdAt: now, expiresAt, src })) {
|
|
1857
|
+
this.metrics.inc("invite", { op: "put", result: "exists" });
|
|
1858
|
+
return this.error(conn, id, "exists");
|
|
1859
|
+
}
|
|
1860
|
+
this.metrics.inc("invite", { op: "put", result: "ok" });
|
|
1861
|
+
const out = { t: "ok", exp: Math.floor(expiresAt / 1000) };
|
|
1862
|
+
// The grant outlives the take (the redeemer authenticates after taking the blob) but not the code.
|
|
1863
|
+
if (admits && this.members.grant(lid, admit, auth.iss, expiresAt))
|
|
1864
|
+
out.admits = true;
|
|
1865
|
+
if (id !== undefined)
|
|
1866
|
+
out.id = id;
|
|
1867
|
+
this.reply(conn, out);
|
|
1868
|
+
}
|
|
1869
|
+
/** Whether the relay first saw `iss` (its oldest held document) less than inviteYoungIdentitySec ago. */
|
|
1870
|
+
identityYoung(iss, now) {
|
|
1871
|
+
const docs = this.store.identityDocs(iss);
|
|
1872
|
+
if (docs.length === 0)
|
|
1873
|
+
return true;
|
|
1874
|
+
const first = Math.min(...docs.map((d) => d.receivedAt));
|
|
1875
|
+
return now - first < this.config.limits.inviteYoungIdentitySec * 1000;
|
|
1876
|
+
}
|
|
1877
|
+
onInviteGet(conn, msg, id) {
|
|
1878
|
+
// Every get costs a token; a miss costs one more from a much smaller hourly budget, which
|
|
1879
|
+
// gates every further get from that IP bucket: guessing 100-bit codes stays hopeless.
|
|
1880
|
+
if (!this.limiters.inviteMiss.has(conn.ip) || !this.limiters.inviteGet.take(conn.ip)) {
|
|
1881
|
+
this.metrics.inc("invite", { op: "get", result: "rate-limited" });
|
|
1882
|
+
return this.error(conn, id, "rate-limited");
|
|
1883
|
+
}
|
|
1884
|
+
if (typeof msg.lid !== "string" || !LID_RE.test(msg.lid))
|
|
1885
|
+
return this.error(conn, id, "bad-request");
|
|
1886
|
+
const inv = this.store.takeInvite(msg.lid, this.now());
|
|
1887
|
+
if (!inv) {
|
|
1888
|
+
this.limiters.inviteMiss.take(conn.ip);
|
|
1889
|
+
this.metrics.inc("invite", { op: "get", result: "not-found" });
|
|
1890
|
+
return this.error(conn, id, "not-found");
|
|
1891
|
+
}
|
|
1892
|
+
this.metrics.inc("invite", { op: "get", result: "ok" });
|
|
1893
|
+
const out = { t: "invite", lid: inv.lid, blob: inv.blob };
|
|
1894
|
+
if (id !== undefined)
|
|
1895
|
+
out.id = id;
|
|
1896
|
+
this.reply(conn, out);
|
|
1897
|
+
}
|
|
1898
|
+
onInviteDel(conn, auth, msg, id) {
|
|
1899
|
+
if (typeof msg.lid !== "string" || !LID_RE.test(msg.lid))
|
|
1900
|
+
return this.error(conn, id, "bad-request");
|
|
1901
|
+
// A revoked code admits nobody, even when its blob was already taken (the reply still says
|
|
1902
|
+
// whether the invite itself was there, so the inviter can tell a taken code).
|
|
1903
|
+
// Whoever the code already admitted provisionally loses that too.
|
|
1904
|
+
if (this.members.revokeInvite(msg.lid, auth.iss))
|
|
1905
|
+
this.enforceMembers();
|
|
1906
|
+
const ok = this.store.deleteInvite(msg.lid, auth.iss);
|
|
1907
|
+
this.metrics.inc("invite", { op: "del", result: ok ? "ok" : "not-found" });
|
|
1908
|
+
if (!ok)
|
|
1909
|
+
return this.error(conn, id, "not-found");
|
|
1910
|
+
this.ok(conn, id);
|
|
1911
|
+
}
|
|
1912
|
+
onInviteList(conn, auth, id) {
|
|
1913
|
+
const now = this.now();
|
|
1914
|
+
// `evicted`: lids the relay dropped to make room (full store), until they would have expired,
|
|
1915
|
+
// so the inviter can tell an evicted code from one somebody took.
|
|
1916
|
+
const out = { t: "invites", lids: this.store.invitesOf(auth.iss, now), evicted: this.store.evictedInvitesOf(auth.iss, now) };
|
|
1917
|
+
if (id !== undefined)
|
|
1918
|
+
out.id = id;
|
|
1919
|
+
this.reply(conn, out);
|
|
1920
|
+
}
|
|
1921
|
+
// -------------------------------------------------------------------------
|
|
1922
|
+
// Members-only circle admission
|
|
1923
|
+
/**
|
|
1924
|
+
* `{t: "circle-put", versions: [jws…]}`: versions of the circle named by
|
|
1925
|
+
* RELAY_ALLOW_CIRCLE. The relay verifies them itself (owner-signed, chained
|
|
1926
|
+
* from version 1); a new head re-decides who is admitted at once.
|
|
1927
|
+
*/
|
|
1928
|
+
onCirclePut(conn, auth, msg, id) {
|
|
1929
|
+
if (!this.members.circleId)
|
|
1930
|
+
return this.error(conn, id, "not-found");
|
|
1931
|
+
if (!this.limiters.circlePut.take(auth.iss)) {
|
|
1932
|
+
this.metrics.inc("circle_put", { result: "rate-limited" });
|
|
1933
|
+
return this.error(conn, id, "rate-limited");
|
|
1934
|
+
}
|
|
1935
|
+
const r = this.members.putCircle(auth.iss, msg.versions);
|
|
1936
|
+
this.metrics.inc("circle_put", { result: r.ok ? r.status : r.code });
|
|
1937
|
+
if (!r.ok) {
|
|
1938
|
+
if (this.log.debugEnabled)
|
|
1939
|
+
this.log.debug("circle-put refused", { conn: conn.id, why: r.reason.slice(0, 120) });
|
|
1940
|
+
return this.error(conn, id, r.code);
|
|
1941
|
+
}
|
|
1942
|
+
const out = { t: "ok", ver: r.ver, status: r.status };
|
|
1943
|
+
if (id !== undefined)
|
|
1944
|
+
out.id = id;
|
|
1945
|
+
this.reply(conn, out);
|
|
1946
|
+
if (r.changed) {
|
|
1947
|
+
this.log.info("members-only: circle head", r.status === "seeded" ? { ver: r.ver, seeded: true } : { ver: r.ver });
|
|
1948
|
+
this.enforceMembers();
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
}
|