@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
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare class RateLimiter {
|
|
2
|
+
readonly limit: number;
|
|
3
|
+
readonly periodMs: number;
|
|
4
|
+
private readonly now;
|
|
5
|
+
readonly maxKeys: number;
|
|
6
|
+
private readonly buckets;
|
|
7
|
+
constructor(limit: number, periodMs: number, now: () => number, maxKeys?: number);
|
|
8
|
+
private bucket;
|
|
9
|
+
/** Whether `key` has `cost` tokens, without taking them. */
|
|
10
|
+
has(key: string, cost?: number): boolean;
|
|
11
|
+
/** Takes `cost` tokens from `key`; false (and nothing taken) when there aren't enough. */
|
|
12
|
+
take(key: string, cost?: number): boolean;
|
|
13
|
+
/** Drops buckets that have refilled completely: they carry no state. */
|
|
14
|
+
prune(): void;
|
|
15
|
+
get size(): number;
|
|
16
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// In-memory token buckets. A bucket holds `limit` tokens and refills at
|
|
4
|
+
// `limit` per `periodMs`, so a key can burst to its limit and then sustain the
|
|
5
|
+
// average rate. A take may cost more than one token (byte budgets).
|
|
6
|
+
//
|
|
7
|
+
// Memory is bounded: at most `maxKeys` buckets. Buckets are kept in
|
|
8
|
+
// least-recently-used order; when the map is full, refilled buckets are
|
|
9
|
+
// pruned first and then the least recently used one is evicted. State is per
|
|
10
|
+
// relay process, so limits reset on restart, which is acceptable for spam
|
|
11
|
+
// control.
|
|
12
|
+
export class RateLimiter {
|
|
13
|
+
limit;
|
|
14
|
+
periodMs;
|
|
15
|
+
now;
|
|
16
|
+
maxKeys;
|
|
17
|
+
buckets = new Map();
|
|
18
|
+
constructor(limit, periodMs, now, maxKeys = 100_000) {
|
|
19
|
+
this.limit = limit;
|
|
20
|
+
this.periodMs = periodMs;
|
|
21
|
+
this.now = now;
|
|
22
|
+
this.maxKeys = maxKeys;
|
|
23
|
+
}
|
|
24
|
+
bucket(key) {
|
|
25
|
+
const now = this.now();
|
|
26
|
+
let b = this.buckets.get(key);
|
|
27
|
+
if (b) {
|
|
28
|
+
// Refresh the LRU position.
|
|
29
|
+
this.buckets.delete(key);
|
|
30
|
+
if (now > b.t) {
|
|
31
|
+
b.tokens = Math.min(this.limit, b.tokens + ((now - b.t) * this.limit) / this.periodMs);
|
|
32
|
+
b.t = now;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
if (this.buckets.size >= this.maxKeys)
|
|
37
|
+
this.prune();
|
|
38
|
+
while (this.buckets.size >= this.maxKeys) {
|
|
39
|
+
const oldest = this.buckets.keys().next().value;
|
|
40
|
+
this.buckets.delete(oldest);
|
|
41
|
+
}
|
|
42
|
+
b = { tokens: this.limit, t: now };
|
|
43
|
+
}
|
|
44
|
+
this.buckets.set(key, b);
|
|
45
|
+
return b;
|
|
46
|
+
}
|
|
47
|
+
/** Whether `key` has `cost` tokens, without taking them. */
|
|
48
|
+
has(key, cost = 1) {
|
|
49
|
+
return this.bucket(key).tokens >= cost;
|
|
50
|
+
}
|
|
51
|
+
/** Takes `cost` tokens from `key`; false (and nothing taken) when there aren't enough. */
|
|
52
|
+
take(key, cost = 1) {
|
|
53
|
+
const b = this.bucket(key);
|
|
54
|
+
if (b.tokens < cost)
|
|
55
|
+
return false;
|
|
56
|
+
b.tokens -= cost;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
/** Drops buckets that have refilled completely: they carry no state. */
|
|
60
|
+
prune() {
|
|
61
|
+
const now = this.now();
|
|
62
|
+
for (const [k, b] of this.buckets) {
|
|
63
|
+
if (b.tokens + ((now - b.t) * this.limit) / this.periodMs >= this.limit)
|
|
64
|
+
this.buckets.delete(k);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
get size() {
|
|
68
|
+
return this.buckets.size;
|
|
69
|
+
}
|
|
70
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import type { RelayConfig } from "./config.js";
|
|
2
|
+
import { type RelayCrypto } from "./crypto.js";
|
|
3
|
+
import { IdentityService } from "./identity.js";
|
|
4
|
+
import { Membership } from "./members.js";
|
|
5
|
+
import { type Logger } from "./log.js";
|
|
6
|
+
import { Metrics } from "./metrics.js";
|
|
7
|
+
import { type Store } from "./store.js";
|
|
8
|
+
export declare const RELAY_SOFTWARE = "@peer2peer/relay";
|
|
9
|
+
export declare const RELAY_VERSION: string;
|
|
10
|
+
/** docs/compatibility.md: this relay's protocol minor (3.1: the crit rule on what it parses). */
|
|
11
|
+
export declare const RELAY_PROTOCOL_MINOR = 1;
|
|
12
|
+
/** The frames this relay answers (handleFrame's cases), listed in /.well-known/p2p-relay.json. */
|
|
13
|
+
export declare const RELAY_FRAMES: readonly string[];
|
|
14
|
+
/**
|
|
15
|
+
* What it supports beyond the frames:
|
|
16
|
+
* - `identity.lenient`: identity documents, device certs and caps with fields it doesn't know are
|
|
17
|
+
* stored and served (refused only for a field listed in `crit`);
|
|
18
|
+
* - `envelope.lenient`: envelopes of kinds it doesn't know, and with unknown outer fields, are
|
|
19
|
+
* relayed (refused only for an unknown field listed in `crit`);
|
|
20
|
+
* - `invite-mailbox`: short-code invite mailboxes (P4);
|
|
21
|
+
* - `link-mailbox`: pre-auth device-link mailboxes (§5.7);
|
|
22
|
+
* - `members`: this software can run members-only: it honours `admit` on `auth` and
|
|
23
|
+
* `invite-put`, and answers `circle-put`. Whether this relay does run so is `access`
|
|
24
|
+
* ("members" or "open") in the same document; `attention` asks its operator to look at the logs.
|
|
25
|
+
* Frames ignore fields the relay doesn't know (they are requests, not signed objects); a client that
|
|
26
|
+
* needs a frame field honoured checks the relay's features first.
|
|
27
|
+
*/
|
|
28
|
+
export declare const RELAY_FEATURES: readonly string[];
|
|
29
|
+
/** Wire error codes. `send` uses only the four from §5.4; the rest are for the other frames. */
|
|
30
|
+
export type ErrorCode = "undeliverable" | "rate-limited" | "too-large" | "bad-envelope" | "bad-request" | "auth-required" | "auth-failed" | "bad-identity" | "identity-gap" | "forbidden" | "not-found" | "full" | "exists"
|
|
31
|
+
/** Members-only relay: this userId isn't admitted (an auth refusal, closed with 4001). */
|
|
32
|
+
| "not-member";
|
|
33
|
+
/** Close codes the relay uses. */
|
|
34
|
+
export declare const CLOSE: {
|
|
35
|
+
readonly shutdown: 1001;
|
|
36
|
+
readonly tooBig: 1009;
|
|
37
|
+
readonly authFailed: 4001;
|
|
38
|
+
/** The device certificate expired: reconnect with a renewed one (not a revocation, R4-L1). */
|
|
39
|
+
readonly certExpired: 4003;
|
|
40
|
+
readonly unauthTimeout: 4008;
|
|
41
|
+
readonly tooManyConnections: 4029;
|
|
42
|
+
};
|
|
43
|
+
export interface RelayOptions {
|
|
44
|
+
config: RelayConfig;
|
|
45
|
+
store?: Store;
|
|
46
|
+
crypto?: RelayCrypto;
|
|
47
|
+
logger?: Logger;
|
|
48
|
+
/** Milliseconds since the epoch. Injectable for tests. */
|
|
49
|
+
now?: () => number;
|
|
50
|
+
}
|
|
51
|
+
export declare class Relay {
|
|
52
|
+
readonly config: RelayConfig;
|
|
53
|
+
readonly store: Store;
|
|
54
|
+
readonly crypto: RelayCrypto;
|
|
55
|
+
readonly log: Logger;
|
|
56
|
+
readonly metrics: Metrics;
|
|
57
|
+
readonly identity: IdentityService;
|
|
58
|
+
private readonly now;
|
|
59
|
+
private readonly links;
|
|
60
|
+
/** Members-only mode; admits everyone when neither an allowlist nor a circle is configured. */
|
|
61
|
+
readonly members: Membership;
|
|
62
|
+
private readonly http;
|
|
63
|
+
private metricsHttp?;
|
|
64
|
+
private readonly wss;
|
|
65
|
+
private readonly conns;
|
|
66
|
+
private readonly byMailbox;
|
|
67
|
+
private readonly byIss;
|
|
68
|
+
/** Restricted connections per userId (never in byIss or a mailbox map). */
|
|
69
|
+
private readonly restrictedByIss;
|
|
70
|
+
private readonly perIp;
|
|
71
|
+
/** Unauthenticated connections, oldest first, and their count per IP bucket. */
|
|
72
|
+
private readonly unauthConns;
|
|
73
|
+
private readonly unauthPerIp;
|
|
74
|
+
private readonly limiters;
|
|
75
|
+
private readonly path;
|
|
76
|
+
/** Per-process AES-128 key: the wire rid is the internal rid encrypted as one block (L3, N2). */
|
|
77
|
+
private readonly ridKey;
|
|
78
|
+
/**
|
|
79
|
+
* Key for `src`, the stored keyed hash of a sender's IP bucket (N1). Held
|
|
80
|
+
* ONLY in memory (N-M3): nothing on disk can link an envelope to a network.
|
|
81
|
+
* After a restart, older rows keep their tags as anonymous groups (R-M1).
|
|
82
|
+
*/
|
|
83
|
+
private readonly srcKey;
|
|
84
|
+
/** Device bindings held, for the maxDevices cap (N3). Re-synced on sweep. */
|
|
85
|
+
private deviceCount;
|
|
86
|
+
private lastShortXffWarn;
|
|
87
|
+
private nextConnId;
|
|
88
|
+
private timers;
|
|
89
|
+
private closing;
|
|
90
|
+
/** Running total of stored envelope bytes, for the global quota. Re-synced on sweep. */
|
|
91
|
+
private storedBytes;
|
|
92
|
+
private cachedCounts;
|
|
93
|
+
/** Event-loop delay, sampled only when `debugStats` is on. */
|
|
94
|
+
private lagHist?;
|
|
95
|
+
constructor(opts: RelayOptions);
|
|
96
|
+
/** Starts listening; resolves with the bound port. */
|
|
97
|
+
listen(): Promise<number>;
|
|
98
|
+
/** The bound port of the separate /metrics listener, if it is running. */
|
|
99
|
+
get metricsPort(): number | undefined;
|
|
100
|
+
/** Graceful shutdown: refuse new work, close every connection with 1001, flush the store. */
|
|
101
|
+
close(): Promise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* Deletes expired envelopes (in batches that yield, N-M1), cap state,
|
|
104
|
+
* identity versions and userIds, stale device bindings and link mailboxes.
|
|
105
|
+
* Resolves when the envelope expiry has caught up.
|
|
106
|
+
*/
|
|
107
|
+
sweep(): Promise<void>;
|
|
108
|
+
/** Rows per invite-sweep step, adapted like expireRows (F-4). */
|
|
109
|
+
private inviteSweepRows;
|
|
110
|
+
/**
|
|
111
|
+
* F-4: deletes expired invites (and their `evicted` tombstones) in batches,
|
|
112
|
+
* yielding between them; each batch adapts to about EXPIRE_STEP_MS. Returns
|
|
113
|
+
* how many invites went.
|
|
114
|
+
*/
|
|
115
|
+
private sweepInvites;
|
|
116
|
+
private expiring?;
|
|
117
|
+
/** Rows per expiry step, adapted to keep each step near EXPIRE_STEP_MS (F-4). */
|
|
118
|
+
private expireRows;
|
|
119
|
+
/**
|
|
120
|
+
* N-M1/F-4: deletes expired envelopes in batches through the received_at
|
|
121
|
+
* index, yielding to the event loop between batches. The batch size adapts
|
|
122
|
+
* so each one takes about EXPIRE_STEP_MS, so a large expiry never holds the
|
|
123
|
+
* loop (or the write lock) for long.
|
|
124
|
+
*/
|
|
125
|
+
expire(): Promise<void>;
|
|
126
|
+
private heartbeat;
|
|
127
|
+
private counts;
|
|
128
|
+
private registerMetrics;
|
|
129
|
+
/** The `hello.limits` object and the limits block of the relay-info document. */
|
|
130
|
+
advertisedLimits(): Record<string, number>;
|
|
131
|
+
/** GET /.well-known/p2p-relay.json: how communities discover and compare relays, and what this one supports. */
|
|
132
|
+
relayInfo(): Record<string, unknown>;
|
|
133
|
+
private clientIp;
|
|
134
|
+
private sendMetrics;
|
|
135
|
+
/**
|
|
136
|
+
* GET /debug/stats on the metrics listener, only when `debugStats` is on:
|
|
137
|
+
* event-loop delay, process memory and the sizes of every in-memory map, for
|
|
138
|
+
* the resilience suite (packages/relay/resilience). Aggregates only, like /metrics.
|
|
139
|
+
* `?reset=1` restarts the delay histogram after reading it; `?store=1` adds
|
|
140
|
+
* live store counts (a table scan, so the harness asks only at checkpoints).
|
|
141
|
+
*/
|
|
142
|
+
debugStats(opts?: {
|
|
143
|
+
reset?: boolean;
|
|
144
|
+
store?: boolean;
|
|
145
|
+
}): Record<string, unknown>;
|
|
146
|
+
/** The separate (by default localhost-only) metrics listener. */
|
|
147
|
+
private onMetricsHttp;
|
|
148
|
+
private metricsTokenOk;
|
|
149
|
+
private onHttp;
|
|
150
|
+
private identityRoute;
|
|
151
|
+
private onUpgrade;
|
|
152
|
+
/**
|
|
153
|
+
* The global cap is full: the connection to close for a newcomer, or
|
|
154
|
+
* undefined when none may go (pre-release re-review M-1).
|
|
155
|
+
* - Only an address bucket holding MORE than the strict per-IP cap gives
|
|
156
|
+
* one up (the biggest such bucket), so no address is pushed below it.
|
|
157
|
+
* - In that bucket, the userId with the most connections there gives one
|
|
158
|
+
* up (ties: all of the tied userIds), its least recently active one, so
|
|
159
|
+
* one user's churn can't cycle through the others' idle receivers.
|
|
160
|
+
* - A bucket with no authenticated connection gives up its least recently
|
|
161
|
+
* active unauthenticated one.
|
|
162
|
+
*/
|
|
163
|
+
private poolVictim;
|
|
164
|
+
private evict;
|
|
165
|
+
/** Removes `conn` from the unauthenticated set (on auth, close or eviction). */
|
|
166
|
+
private leaveUnauth;
|
|
167
|
+
private onConnection;
|
|
168
|
+
private onClose;
|
|
169
|
+
/** Removes an authenticated connection from the mailbox and userId maps. */
|
|
170
|
+
private unregister;
|
|
171
|
+
private reply;
|
|
172
|
+
private ok;
|
|
173
|
+
private error;
|
|
174
|
+
private onFrame;
|
|
175
|
+
/**
|
|
176
|
+
* Closes `conn` as no longer authorised (N5): its auth is cleared and it
|
|
177
|
+
* leaves the mailbox and userId maps at once, so nothing more is delivered
|
|
178
|
+
* to it and none of its frames are processed during the close handshake.
|
|
179
|
+
* The socket is terminated if the peer doesn't finish the handshake.
|
|
180
|
+
*/
|
|
181
|
+
private kick;
|
|
182
|
+
/** M1: after the allowlist of `iss` changes, close every live connection of a device it no longer lists. */
|
|
183
|
+
private enforceAllowlist;
|
|
184
|
+
/**
|
|
185
|
+
* Members-only: after the allowlist, the circle or a provisional admission
|
|
186
|
+
* changed, every live connection of a userId no longer admitted is closed.
|
|
187
|
+
*/
|
|
188
|
+
enforceMembers(): void;
|
|
189
|
+
/** Replaces the members-only allowlist (and deny list) at runtime (SIGHUP), closing the connections of anyone removed. */
|
|
190
|
+
setAllow(list: readonly string[] | undefined, deny?: readonly string[]): void;
|
|
191
|
+
private onAuth;
|
|
192
|
+
/**
|
|
193
|
+
* A connection lives no longer than its device certificate (review R3: what
|
|
194
|
+
* makes the 91-day memory of discarded dids enough). Timers longer than
|
|
195
|
+
* Node's ~24.8-day maximum re-arm in steps.
|
|
196
|
+
*/
|
|
197
|
+
private armCertExpiry;
|
|
198
|
+
/** Binds an authenticated, listed connection to its mailbox (iss, did). */
|
|
199
|
+
private bindMailbox;
|
|
200
|
+
/**
|
|
201
|
+
* M-4: frees one device row: the least recently seen binding with no stored
|
|
202
|
+
* envelopes, no live connection, and not in its issuer's held allowlist.
|
|
203
|
+
*/
|
|
204
|
+
private evictDevice;
|
|
205
|
+
/**
|
|
206
|
+
* A mailbox exists when the relay holds the recipient's identity document
|
|
207
|
+
* and it lists `tdid` (rule 6 for receivers), or, with no document held,
|
|
208
|
+
* when `tdid` has authenticated here bound to `to`.
|
|
209
|
+
*/
|
|
210
|
+
private mailboxKnown;
|
|
211
|
+
private capKey;
|
|
212
|
+
/**
|
|
213
|
+
* L3/N2: what receivers see as `rid`: the internal rid (8 bytes, big-endian,
|
|
214
|
+
* then 8 zero bytes) encrypted as one AES-128 block under a per-process key.
|
|
215
|
+
* Opaque, deterministic (redelivery keeps the rid), and reversible without
|
|
216
|
+
* any per-connection state.
|
|
217
|
+
*/
|
|
218
|
+
private wireRid;
|
|
219
|
+
/** The internal rid of a wire rid, or undefined when it isn't one this process issued. */
|
|
220
|
+
private ridFromWire;
|
|
221
|
+
/** N1: the stored tag of a sender's IP bucket, keyed per process. */
|
|
222
|
+
private srcTag;
|
|
223
|
+
/** F-6: eviction ranking for an envelope from `src` (the sender pays first, then the largest group). */
|
|
224
|
+
private evictPolicy;
|
|
225
|
+
private onSend;
|
|
226
|
+
/**
|
|
227
|
+
* Stores an envelope, first evicting to stay under the quotas (N1): the
|
|
228
|
+
* recipient's own oldest envelopes past recipientMaxBytes, then the oldest
|
|
229
|
+
* envelopes of the largest mailboxes past storeMaxBytes. Filling the relay
|
|
230
|
+
* therefore churns the biggest (usually the attacker's) mailboxes instead of
|
|
231
|
+
* refusing everyone.
|
|
232
|
+
*/
|
|
233
|
+
private storeAndDeliver;
|
|
234
|
+
/** Sends the connection every stored envelope after the last one it was sent, in rid order, with backpressure. */
|
|
235
|
+
private pump;
|
|
236
|
+
private onAck;
|
|
237
|
+
private onRevoke;
|
|
238
|
+
private onIdentity;
|
|
239
|
+
/**
|
|
240
|
+
* §2.7 restore over a restricted connection (H1/H2). The document is parsed
|
|
241
|
+
* before anything is charged, and charged to its own limiter. Only a
|
|
242
|
+
* version on top of the held history is accepted (one that extends every
|
|
243
|
+
* tip, or merges them): never a fork, so a stale or stolen key holder can't
|
|
244
|
+
* split the allowlist away from the restored device. When the version lists
|
|
245
|
+
* this device (and its certificate is still valid), the connection becomes
|
|
246
|
+
* a full one.
|
|
247
|
+
*/
|
|
248
|
+
private onRestrictedIdentity;
|
|
249
|
+
/**
|
|
250
|
+
* After the allowlist of `iss` changes: every restricted connection whose
|
|
251
|
+
* device it now lists becomes a full one (not only the publishing one,
|
|
252
|
+
* pre-release review), its certificate re-checked.
|
|
253
|
+
*/
|
|
254
|
+
private promoteRestricted;
|
|
255
|
+
private onLinkOpen;
|
|
256
|
+
private linkArgs;
|
|
257
|
+
private onLinkPut;
|
|
258
|
+
private onLinkGet;
|
|
259
|
+
private onInvitePut;
|
|
260
|
+
/** Whether the relay first saw `iss` (its oldest held document) less than inviteYoungIdentitySec ago. */
|
|
261
|
+
private identityYoung;
|
|
262
|
+
private onInviteGet;
|
|
263
|
+
private onInviteDel;
|
|
264
|
+
private onInviteList;
|
|
265
|
+
/**
|
|
266
|
+
* `{t: "circle-put", versions: [jws…]}`: versions of the circle named by
|
|
267
|
+
* RELAY_ALLOW_CIRCLE. The relay verifies them itself (owner-signed, chained
|
|
268
|
+
* from version 1); a new head re-decides who is admitted at once.
|
|
269
|
+
*/
|
|
270
|
+
private onCirclePut;
|
|
271
|
+
}
|