@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,109 @@
|
|
|
1
|
+
import type { Logger } from "./log.js";
|
|
2
|
+
import type { Store } from "./store.js";
|
|
3
|
+
/** Grants one sponsor may hold at once; the oldest goes first. */
|
|
4
|
+
export declare const GRANTS_PER_SPONSOR = 64;
|
|
5
|
+
/** Provisional members one sponsor may have at once. */
|
|
6
|
+
export declare const PROVISIONAL_PER_SPONSOR = 64;
|
|
7
|
+
export declare const PROVISIONAL_MAX = 10000;
|
|
8
|
+
/** Versions accepted in one `circle-put` frame. */
|
|
9
|
+
export declare const CIRCLE_PUT_MAX_VERSIONS = 64;
|
|
10
|
+
/** An admission key or its hash: 32 bytes, base64url. */
|
|
11
|
+
export declare const ADMIT_RE: RegExp;
|
|
12
|
+
export interface MembershipOptions {
|
|
13
|
+
allow?: readonly string[];
|
|
14
|
+
/** Never admitted, whatever the list, the circle or an invite says (RELAY_DENY, `!` lines). */
|
|
15
|
+
deny?: readonly string[];
|
|
16
|
+
circle?: string;
|
|
17
|
+
inviteAdmitSec: number;
|
|
18
|
+
store: Store;
|
|
19
|
+
now: () => number;
|
|
20
|
+
log: Logger;
|
|
21
|
+
}
|
|
22
|
+
export type CirclePutResult = {
|
|
23
|
+
ok: true;
|
|
24
|
+
ver: number;
|
|
25
|
+
changed: boolean;
|
|
26
|
+
status: string;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
code: "forbidden" | "bad-request" | "not-found";
|
|
30
|
+
reason: string;
|
|
31
|
+
};
|
|
32
|
+
/** Hashes an admission key the way the grant stores it. */
|
|
33
|
+
export declare function admitHash(key: string): string;
|
|
34
|
+
export declare class Membership {
|
|
35
|
+
private allow?;
|
|
36
|
+
private deny;
|
|
37
|
+
/**
|
|
38
|
+
* The followed circle's head is open (anyone may join it): admitting its
|
|
39
|
+
* members would admit the public, so the circle admits nobody until a later
|
|
40
|
+
* head is invite-only again. Shown as `attention` in the relay info.
|
|
41
|
+
*/
|
|
42
|
+
private circleOpen;
|
|
43
|
+
readonly circleId?: string;
|
|
44
|
+
readonly inviteAdmitSec: number;
|
|
45
|
+
private chain?;
|
|
46
|
+
private circleMembers;
|
|
47
|
+
private grants;
|
|
48
|
+
private provisional;
|
|
49
|
+
private readonly store;
|
|
50
|
+
private readonly now;
|
|
51
|
+
private readonly log;
|
|
52
|
+
constructor(o: MembershipOptions);
|
|
53
|
+
/** Reads persisted state (after the store's init). */
|
|
54
|
+
load(): void;
|
|
55
|
+
private readMeta;
|
|
56
|
+
get enabled(): boolean;
|
|
57
|
+
/** On the allowlist, or a member of the circle's head. */
|
|
58
|
+
isFull(iss: string): boolean;
|
|
59
|
+
/** May authenticate (always true on an open relay). */
|
|
60
|
+
admitted(iss: string): boolean;
|
|
61
|
+
allowlisted(iss: string): boolean;
|
|
62
|
+
/** Something needs the operator (the followed circle turned open). No details: they're in the logs. */
|
|
63
|
+
get attention(): boolean;
|
|
64
|
+
/** What an authenticated member is told about the circle the relay follows: `ver` 0 until seeded. */
|
|
65
|
+
circleInfo(): {
|
|
66
|
+
cid: string;
|
|
67
|
+
ver: number;
|
|
68
|
+
} | undefined;
|
|
69
|
+
/** Replaces the allowlist (undefined: none) and, when given, the deny list. */
|
|
70
|
+
setAllow(list: readonly string[] | undefined, deny?: readonly string[]): void;
|
|
71
|
+
/**
|
|
72
|
+
* Records the grant an `invite-put` carries. Only full members sponsor one.
|
|
73
|
+
* Returns false when the sponsor may not.
|
|
74
|
+
*/
|
|
75
|
+
grant(lid: string, h: string, by: string, exp: number): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* `invite-del` by the sponsor revokes what the code admits: its grant, taken
|
|
78
|
+
* or not, and the provisional member it already admitted. Returns whether
|
|
79
|
+
* someone lost admission (their connections must close).
|
|
80
|
+
*/
|
|
81
|
+
revokeInvite(lid: string, by: string): boolean;
|
|
82
|
+
/**
|
|
83
|
+
* At auth, a userId that isn't admitted may present an admission key: a live
|
|
84
|
+
* grant from a sponsor who is still a full member admits it provisionally.
|
|
85
|
+
* The grant is single-use.
|
|
86
|
+
*/
|
|
87
|
+
redeem(key: string, iss: string): boolean;
|
|
88
|
+
/** Drops expired grants and provisional members. Returns whether a provisional member lapsed. */
|
|
89
|
+
expire(): boolean;
|
|
90
|
+
/**
|
|
91
|
+
* After the full membership changed: provisional members who became full
|
|
92
|
+
* ones are provisional no more (so a later removal from the list or circle
|
|
93
|
+
* cuts them off), and grants of sponsors who are no longer full members go.
|
|
94
|
+
*/
|
|
95
|
+
private settle;
|
|
96
|
+
private saveGrants;
|
|
97
|
+
private saveProvisional;
|
|
98
|
+
private setChain;
|
|
99
|
+
/**
|
|
100
|
+
* Versions of the configured circle from an authenticated member. The first
|
|
101
|
+
* (the bootstrap, from version 1) only from an allowlisted userId; after
|
|
102
|
+
* that any member may push newer versions, which the chain accepts only
|
|
103
|
+
* when owner-signed and on top of what it holds.
|
|
104
|
+
*/
|
|
105
|
+
putCircle(iss: string, versions: unknown): CirclePutResult;
|
|
106
|
+
private saveChain;
|
|
107
|
+
/** Aggregates for logs and /debug/stats. */
|
|
108
|
+
stats(): Record<string, number>;
|
|
109
|
+
}
|
package/dist/members.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Members-only mode (docs/run-a-relay.md "Members-only relays"). With
|
|
4
|
+
// `allow` and/or `allowCircle` configured, only these userIds may
|
|
5
|
+
// authenticate:
|
|
6
|
+
//
|
|
7
|
+
// - full members: every userId on the allowlist, and every current member of
|
|
8
|
+
// the configured circle (the head of a chain the relay verifies itself,
|
|
9
|
+
// from version 1, with core's CircleChain: owner-signed versions only);
|
|
10
|
+
// - provisional members: a userId that redeemed an admission grant an
|
|
11
|
+
// allowed member attached to a short-code invite (`invite-put` `admit`),
|
|
12
|
+
// for `inviteAdmitSec`, or until it becomes a full member (then the circle
|
|
13
|
+
// or the list alone decides), or its sponsor stops being a full member.
|
|
14
|
+
//
|
|
15
|
+
// With neither configured the relay is open and nothing here applies.
|
|
16
|
+
//
|
|
17
|
+
// State that must survive a restart (the circle chain, outstanding grants,
|
|
18
|
+
// provisional members) lives in the store's meta table as JSON. All of it is
|
|
19
|
+
// bounded: grants per sponsor, provisional members per sponsor and in total,
|
|
20
|
+
// and the stored chain's size.
|
|
21
|
+
import { b64uDecode, b64uEncode, sha256 } from "@peer2peer/core";
|
|
22
|
+
import { CircleChain, circlePolicy } from "@peer2peer/core/v3";
|
|
23
|
+
/** Grants one sponsor may hold at once; the oldest goes first. */
|
|
24
|
+
export const GRANTS_PER_SPONSOR = 64;
|
|
25
|
+
/** Provisional members one sponsor may have at once. */
|
|
26
|
+
export const PROVISIONAL_PER_SPONSOR = 64;
|
|
27
|
+
export const PROVISIONAL_MAX = 10_000;
|
|
28
|
+
/** Versions accepted in one `circle-put` frame. */
|
|
29
|
+
export const CIRCLE_PUT_MAX_VERSIONS = 64;
|
|
30
|
+
/** A stored chain larger than this is kept in memory only (and the operator warned). */
|
|
31
|
+
const CIRCLE_STORE_MAX_BYTES = 32 * 1024 * 1024;
|
|
32
|
+
const META_CIRCLE = "members.circle";
|
|
33
|
+
const META_GRANTS = "members.grants";
|
|
34
|
+
const META_PROVISIONAL = "members.provisional";
|
|
35
|
+
/** An admission key or its hash: 32 bytes, base64url. */
|
|
36
|
+
export const ADMIT_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
37
|
+
/** Hashes an admission key the way the grant stores it. */
|
|
38
|
+
export function admitHash(key) {
|
|
39
|
+
return b64uEncode(sha256(b64uDecode(key, 32)));
|
|
40
|
+
}
|
|
41
|
+
export class Membership {
|
|
42
|
+
allow;
|
|
43
|
+
deny;
|
|
44
|
+
/**
|
|
45
|
+
* The followed circle's head is open (anyone may join it): admitting its
|
|
46
|
+
* members would admit the public, so the circle admits nobody until a later
|
|
47
|
+
* head is invite-only again. Shown as `attention` in the relay info.
|
|
48
|
+
*/
|
|
49
|
+
circleOpen = false;
|
|
50
|
+
circleId;
|
|
51
|
+
inviteAdmitSec;
|
|
52
|
+
chain;
|
|
53
|
+
circleMembers = new Set();
|
|
54
|
+
grants = new Map();
|
|
55
|
+
provisional = new Map();
|
|
56
|
+
store;
|
|
57
|
+
now;
|
|
58
|
+
log;
|
|
59
|
+
constructor(o) {
|
|
60
|
+
this.allow = o.allow ? new Set(o.allow) : undefined;
|
|
61
|
+
this.deny = new Set(o.deny ?? []);
|
|
62
|
+
this.circleId = o.circle;
|
|
63
|
+
this.inviteAdmitSec = o.inviteAdmitSec;
|
|
64
|
+
this.store = o.store;
|
|
65
|
+
this.now = o.now;
|
|
66
|
+
this.log = o.log;
|
|
67
|
+
}
|
|
68
|
+
/** Reads persisted state (after the store's init). */
|
|
69
|
+
load() {
|
|
70
|
+
if (this.circleId) {
|
|
71
|
+
const raw = this.store.getMeta(META_CIRCLE);
|
|
72
|
+
if (raw) {
|
|
73
|
+
try {
|
|
74
|
+
const s = JSON.parse(raw);
|
|
75
|
+
if (s.cid !== this.circleId) {
|
|
76
|
+
this.log.warn("members-only: the stored circle is not the configured one; waiting for a member to seed it");
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
this.setChain(CircleChain.fromStored(s));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
this.log.error("members-only: the stored circle chain did not verify; waiting for a member to seed it", { error: e.message });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const grants = this.readMeta(META_GRANTS) ?? [];
|
|
88
|
+
for (const g of grants)
|
|
89
|
+
this.grants.set(g.h, g);
|
|
90
|
+
const prov = this.readMeta(META_PROVISIONAL) ?? {};
|
|
91
|
+
for (const [u, p] of Object.entries(prov))
|
|
92
|
+
this.provisional.set(u, p);
|
|
93
|
+
this.expire();
|
|
94
|
+
if (this.enabled) {
|
|
95
|
+
this.log.info("members-only relay", {
|
|
96
|
+
allowlisted: this.allow?.size ?? 0,
|
|
97
|
+
circle: this.circleId ?? undefined,
|
|
98
|
+
circleVer: this.chain?.head.ver,
|
|
99
|
+
circleMembers: this.chain ? this.circleMembers.size : undefined,
|
|
100
|
+
inviteAdmitSec: this.inviteAdmitSec,
|
|
101
|
+
});
|
|
102
|
+
if (this.circleId && !this.chain && (this.allow?.size ?? 0) === 0) {
|
|
103
|
+
this.log.warn("members-only: RELAY_ALLOW_CIRCLE is set but the circle isn't seeded and RELAY_ALLOW is empty, so nobody can authenticate");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
readMeta(key) {
|
|
108
|
+
const raw = this.store.getMeta(key);
|
|
109
|
+
if (!raw)
|
|
110
|
+
return undefined;
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(raw);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
get enabled() {
|
|
119
|
+
return this.allow !== undefined || this.circleId !== undefined;
|
|
120
|
+
}
|
|
121
|
+
/** On the allowlist, or a member of the circle's head. */
|
|
122
|
+
isFull(iss) {
|
|
123
|
+
if (this.deny.has(iss))
|
|
124
|
+
return false;
|
|
125
|
+
return (this.allow?.has(iss) ?? false) || this.circleMembers.has(iss);
|
|
126
|
+
}
|
|
127
|
+
/** May authenticate (always true on an open relay). */
|
|
128
|
+
admitted(iss) {
|
|
129
|
+
if (!this.enabled)
|
|
130
|
+
return true;
|
|
131
|
+
if (this.deny.has(iss))
|
|
132
|
+
return false;
|
|
133
|
+
if (this.isFull(iss))
|
|
134
|
+
return true;
|
|
135
|
+
const p = this.provisional.get(iss);
|
|
136
|
+
return p !== undefined && p.until > this.now() && this.isFull(p.by);
|
|
137
|
+
}
|
|
138
|
+
allowlisted(iss) {
|
|
139
|
+
return !this.deny.has(iss) && (this.allow?.has(iss) ?? false);
|
|
140
|
+
}
|
|
141
|
+
/** Something needs the operator (the followed circle turned open). No details: they're in the logs. */
|
|
142
|
+
get attention() {
|
|
143
|
+
return this.circleOpen;
|
|
144
|
+
}
|
|
145
|
+
/** What an authenticated member is told about the circle the relay follows: `ver` 0 until seeded. */
|
|
146
|
+
circleInfo() {
|
|
147
|
+
if (!this.circleId)
|
|
148
|
+
return undefined;
|
|
149
|
+
return { cid: this.circleId, ver: this.chain?.head.ver ?? 0 };
|
|
150
|
+
}
|
|
151
|
+
/** Replaces the allowlist (undefined: none) and, when given, the deny list. */
|
|
152
|
+
setAllow(list, deny) {
|
|
153
|
+
this.allow = list ? new Set(list) : undefined;
|
|
154
|
+
if (deny)
|
|
155
|
+
this.deny = new Set(deny);
|
|
156
|
+
this.settle();
|
|
157
|
+
}
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
// Invite admission
|
|
160
|
+
/**
|
|
161
|
+
* Records the grant an `invite-put` carries. Only full members sponsor one.
|
|
162
|
+
* Returns false when the sponsor may not.
|
|
163
|
+
*/
|
|
164
|
+
grant(lid, h, by, exp) {
|
|
165
|
+
if (!this.enabled || this.inviteAdmitSec <= 0 || !this.isFull(by))
|
|
166
|
+
return false;
|
|
167
|
+
const mine = [...this.grants.values()].filter((g) => g.by === by).sort((a, b) => a.exp - b.exp);
|
|
168
|
+
while (mine.length >= GRANTS_PER_SPONSOR)
|
|
169
|
+
this.grants.delete(mine.shift().h);
|
|
170
|
+
this.grants.set(h, { lid, h, by, exp });
|
|
171
|
+
this.saveGrants();
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* `invite-del` by the sponsor revokes what the code admits: its grant, taken
|
|
176
|
+
* or not, and the provisional member it already admitted. Returns whether
|
|
177
|
+
* someone lost admission (their connections must close).
|
|
178
|
+
*/
|
|
179
|
+
revokeInvite(lid, by) {
|
|
180
|
+
for (const g of this.grants.values()) {
|
|
181
|
+
if (g.lid === lid && g.by === by) {
|
|
182
|
+
this.grants.delete(g.h);
|
|
183
|
+
this.saveGrants();
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
let removed = false;
|
|
188
|
+
for (const [u, p] of this.provisional) {
|
|
189
|
+
if (p.lid === lid && p.by === by) {
|
|
190
|
+
this.provisional.delete(u);
|
|
191
|
+
removed = true;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (removed)
|
|
195
|
+
this.saveProvisional();
|
|
196
|
+
return removed;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* At auth, a userId that isn't admitted may present an admission key: a live
|
|
200
|
+
* grant from a sponsor who is still a full member admits it provisionally.
|
|
201
|
+
* The grant is single-use.
|
|
202
|
+
*/
|
|
203
|
+
redeem(key, iss) {
|
|
204
|
+
if (!this.enabled || this.inviteAdmitSec <= 0 || !ADMIT_RE.test(key))
|
|
205
|
+
return false;
|
|
206
|
+
// A denied userId never redeems: checked before the grant is touched, so it isn't spent.
|
|
207
|
+
if (this.deny.has(iss))
|
|
208
|
+
return false;
|
|
209
|
+
let h;
|
|
210
|
+
try {
|
|
211
|
+
h = admitHash(key);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
const g = this.grants.get(h);
|
|
217
|
+
const now = this.now();
|
|
218
|
+
if (!g || g.exp <= now || !this.isFull(g.by) || g.by === iss)
|
|
219
|
+
return false;
|
|
220
|
+
let sponsored = 0;
|
|
221
|
+
for (const p of this.provisional.values())
|
|
222
|
+
if (p.by === g.by && p.until > now)
|
|
223
|
+
sponsored++;
|
|
224
|
+
if (sponsored >= PROVISIONAL_PER_SPONSOR || this.provisional.size >= PROVISIONAL_MAX) {
|
|
225
|
+
this.log.warn("members-only: provisional member cap reached; admission refused");
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
this.grants.delete(h);
|
|
229
|
+
this.saveGrants();
|
|
230
|
+
this.provisional.set(iss, { by: g.by, lid: g.lid, until: now + this.inviteAdmitSec * 1000 });
|
|
231
|
+
this.saveProvisional();
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
/** Drops expired grants and provisional members. Returns whether a provisional member lapsed. */
|
|
235
|
+
expire() {
|
|
236
|
+
const now = this.now();
|
|
237
|
+
let g = false;
|
|
238
|
+
for (const [h, x] of this.grants) {
|
|
239
|
+
if (x.exp <= now) {
|
|
240
|
+
this.grants.delete(h);
|
|
241
|
+
g = true;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (g)
|
|
245
|
+
this.saveGrants();
|
|
246
|
+
let p = false;
|
|
247
|
+
for (const [u, x] of this.provisional) {
|
|
248
|
+
if (x.until <= now) {
|
|
249
|
+
this.provisional.delete(u);
|
|
250
|
+
p = true;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (p)
|
|
254
|
+
this.saveProvisional();
|
|
255
|
+
return p;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* After the full membership changed: provisional members who became full
|
|
259
|
+
* ones are provisional no more (so a later removal from the list or circle
|
|
260
|
+
* cuts them off), and grants of sponsors who are no longer full members go.
|
|
261
|
+
*/
|
|
262
|
+
settle() {
|
|
263
|
+
let p = false;
|
|
264
|
+
for (const [u] of this.provisional) {
|
|
265
|
+
// Full now (the list or circle decides from here), or denied (gone for good, not only while denied).
|
|
266
|
+
if (this.isFull(u) || this.deny.has(u)) {
|
|
267
|
+
this.provisional.delete(u);
|
|
268
|
+
p = true;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (p)
|
|
272
|
+
this.saveProvisional();
|
|
273
|
+
let g = false;
|
|
274
|
+
for (const [h, x] of this.grants) {
|
|
275
|
+
if (!this.isFull(x.by)) {
|
|
276
|
+
this.grants.delete(h);
|
|
277
|
+
g = true;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (g)
|
|
281
|
+
this.saveGrants();
|
|
282
|
+
}
|
|
283
|
+
saveGrants() {
|
|
284
|
+
this.store.setMeta(META_GRANTS, JSON.stringify([...this.grants.values()]));
|
|
285
|
+
}
|
|
286
|
+
saveProvisional() {
|
|
287
|
+
this.store.setMeta(META_PROVISIONAL, JSON.stringify(Object.fromEntries(this.provisional)));
|
|
288
|
+
}
|
|
289
|
+
// ---------------------------------------------------------------------------
|
|
290
|
+
// Circle admission
|
|
291
|
+
setChain(c) {
|
|
292
|
+
this.chain = c;
|
|
293
|
+
const open = circlePolicy(c.head) === "open";
|
|
294
|
+
if (open && !this.circleOpen) {
|
|
295
|
+
this.log.error("members-only: the followed circle is now OPEN (anyone may join it), so it admits nobody here; only the allowlist does until its owner makes it invite-only again", { ver: c.head.ver });
|
|
296
|
+
}
|
|
297
|
+
else if (!open && this.circleOpen) {
|
|
298
|
+
this.log.warn("members-only: the followed circle is invite-only again; its members are admitted", { ver: c.head.ver });
|
|
299
|
+
}
|
|
300
|
+
this.circleOpen = open;
|
|
301
|
+
// Fail closed: an open circle's members are whoever asked, i.e. the public.
|
|
302
|
+
this.circleMembers = open ? new Set() : new Set(c.head.members);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Versions of the configured circle from an authenticated member. The first
|
|
306
|
+
* (the bootstrap, from version 1) only from an allowlisted userId; after
|
|
307
|
+
* that any member may push newer versions, which the chain accepts only
|
|
308
|
+
* when owner-signed and on top of what it holds.
|
|
309
|
+
*/
|
|
310
|
+
putCircle(iss, versions) {
|
|
311
|
+
if (!this.circleId)
|
|
312
|
+
return { ok: false, code: "not-found", reason: "no circle configured" };
|
|
313
|
+
if (!Array.isArray(versions) || versions.length === 0 || versions.length > CIRCLE_PUT_MAX_VERSIONS || !versions.every((v) => typeof v === "string")) {
|
|
314
|
+
return { ok: false, code: "bad-request", reason: "versions" };
|
|
315
|
+
}
|
|
316
|
+
const list = versions;
|
|
317
|
+
const before = this.chain?.head.hash;
|
|
318
|
+
let status;
|
|
319
|
+
let chain = this.chain;
|
|
320
|
+
try {
|
|
321
|
+
if (!chain) {
|
|
322
|
+
if (!this.allowlisted(iss))
|
|
323
|
+
return { ok: false, code: "forbidden", reason: "only an allowlisted member seeds the circle" };
|
|
324
|
+
chain = CircleChain.bootstrap(list, { now: Math.floor(this.now() / 1000) });
|
|
325
|
+
if (chain.cid !== this.circleId)
|
|
326
|
+
return { ok: false, code: "bad-request", reason: "another circle" };
|
|
327
|
+
if (circlePolicy(chain.head) === "open")
|
|
328
|
+
return { ok: false, code: "bad-request", reason: "an open circle can't admit members (anyone may join it)" };
|
|
329
|
+
status = "seeded";
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
const rs = chain.receive(list, { now: Math.floor(this.now() / 1000) });
|
|
333
|
+
status = rs.some((r) => r.status === "accepted" || r.status === "replaced")
|
|
334
|
+
? "accepted"
|
|
335
|
+
: (rs.find((r) => r.status !== "duplicate")?.status ?? "duplicate");
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
catch (e) {
|
|
339
|
+
return { ok: false, code: "bad-request", reason: e.message };
|
|
340
|
+
}
|
|
341
|
+
this.setChain(chain);
|
|
342
|
+
const changed = chain.head.hash !== before;
|
|
343
|
+
if (changed || status === "gap")
|
|
344
|
+
this.saveChain();
|
|
345
|
+
if (changed)
|
|
346
|
+
this.settle();
|
|
347
|
+
return { ok: true, ver: chain.head.ver, changed, status };
|
|
348
|
+
}
|
|
349
|
+
saveChain() {
|
|
350
|
+
if (!this.chain)
|
|
351
|
+
return;
|
|
352
|
+
const json = JSON.stringify(this.chain.toStored());
|
|
353
|
+
if (json.length > CIRCLE_STORE_MAX_BYTES) {
|
|
354
|
+
this.log.warn("members-only: the circle chain is too large to store; it is held in memory only", { bytes: json.length });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
this.store.setMeta(META_CIRCLE, json);
|
|
358
|
+
}
|
|
359
|
+
/** Aggregates for logs and /debug/stats. */
|
|
360
|
+
stats() {
|
|
361
|
+
return {
|
|
362
|
+
allowlisted: this.allow?.size ?? 0,
|
|
363
|
+
circleMembers: this.circleMembers.size,
|
|
364
|
+
circleVer: this.chain?.head.ver ?? 0,
|
|
365
|
+
grants: this.grants.size,
|
|
366
|
+
provisional: this.provisional.size,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare class Metrics {
|
|
2
|
+
private readonly prefix;
|
|
3
|
+
private readonly counters;
|
|
4
|
+
private readonly gauges;
|
|
5
|
+
constructor(prefix?: string);
|
|
6
|
+
counter(name: string, help: string): void;
|
|
7
|
+
gauge(name: string, help: string, read: () => number): void;
|
|
8
|
+
/** Increments counter `name`. Label values must come from a small fixed set. */
|
|
9
|
+
inc(name: string, labels?: Record<string, string>, by?: number): void;
|
|
10
|
+
/** A counter's value (summed over labels when none are given). */
|
|
11
|
+
get(name: string, labels?: Record<string, string>): number;
|
|
12
|
+
render(): string;
|
|
13
|
+
}
|
package/dist/metrics.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Prometheus text-format metrics. Counts only: no label ever carries a
|
|
4
|
+
// userId, device id, capability or IP.
|
|
5
|
+
function labelKey(labels) {
|
|
6
|
+
if (!labels)
|
|
7
|
+
return "";
|
|
8
|
+
return Object.entries(labels)
|
|
9
|
+
.map(([k, v]) => `${k}="${v.replace(/["\\\n]/g, "_")}"`)
|
|
10
|
+
.join(",");
|
|
11
|
+
}
|
|
12
|
+
export class Metrics {
|
|
13
|
+
prefix;
|
|
14
|
+
counters = new Map();
|
|
15
|
+
gauges = new Map();
|
|
16
|
+
constructor(prefix = "p2p_relay_") {
|
|
17
|
+
this.prefix = prefix;
|
|
18
|
+
}
|
|
19
|
+
counter(name, help) {
|
|
20
|
+
if (!this.counters.has(name))
|
|
21
|
+
this.counters.set(name, { help, values: new Map() });
|
|
22
|
+
}
|
|
23
|
+
gauge(name, help, read) {
|
|
24
|
+
this.gauges.set(name, { help, read });
|
|
25
|
+
}
|
|
26
|
+
/** Increments counter `name`. Label values must come from a small fixed set. */
|
|
27
|
+
inc(name, labels, by = 1) {
|
|
28
|
+
const c = this.counters.get(name);
|
|
29
|
+
if (!c)
|
|
30
|
+
throw new Error(`metrics: unknown counter ${name}`);
|
|
31
|
+
const key = labelKey(labels);
|
|
32
|
+
c.values.set(key, (c.values.get(key) ?? 0) + by);
|
|
33
|
+
}
|
|
34
|
+
/** A counter's value (summed over labels when none are given). */
|
|
35
|
+
get(name, labels) {
|
|
36
|
+
const c = this.counters.get(name);
|
|
37
|
+
if (!c)
|
|
38
|
+
return 0;
|
|
39
|
+
if (!labels)
|
|
40
|
+
return [...c.values.values()].reduce((a, b) => a + b, 0);
|
|
41
|
+
return c.values.get(labelKey(labels)) ?? 0;
|
|
42
|
+
}
|
|
43
|
+
render() {
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const [name, c] of this.counters) {
|
|
46
|
+
const full = `${this.prefix}${name}_total`;
|
|
47
|
+
out.push(`# HELP ${full} ${c.help}`, `# TYPE ${full} counter`);
|
|
48
|
+
if (c.values.size === 0)
|
|
49
|
+
out.push(`${full} 0`);
|
|
50
|
+
for (const [labels, v] of c.values)
|
|
51
|
+
out.push(labels ? `${full}{${labels}} ${v}` : `${full} ${v}`);
|
|
52
|
+
}
|
|
53
|
+
for (const [name, g] of this.gauges) {
|
|
54
|
+
const full = `${this.prefix}${name}`;
|
|
55
|
+
let v;
|
|
56
|
+
try {
|
|
57
|
+
v = g.read();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
v = NaN;
|
|
61
|
+
}
|
|
62
|
+
out.push(`# HELP ${full} ${g.help}`, `# TYPE ${full} gauge`, `${full} ${v}`);
|
|
63
|
+
}
|
|
64
|
+
return `${out.join("\n")}\n`;
|
|
65
|
+
}
|
|
66
|
+
}
|
package/dist/net.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strips what proxies and sockets wrap around an address: brackets
|
|
3
|
+
* (`[2001:db8::1]`), a port (`203.0.113.5:4433`, `[2001:db8::1]:443`).
|
|
4
|
+
*/
|
|
5
|
+
export declare function bareAddress(raw: string): string;
|
|
6
|
+
/**
|
|
7
|
+
* The key per-IP limits use: the IPv4 address itself, or `<first 4 hextets>::/64`
|
|
8
|
+
* for IPv6, after stripping brackets and ports. Anything unparseable is
|
|
9
|
+
* returned unchanged.
|
|
10
|
+
*/
|
|
11
|
+
export declare function ipBucket(raw: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* A coarser bucket for budgets one network shouldn't exhaust on its own (P4
|
|
14
|
+
* invite bytes): an IPv6 /64 bucket widens to its /48 (what one site is
|
|
15
|
+
* typically assigned); IPv4 stays the address.
|
|
16
|
+
*/
|
|
17
|
+
export declare function ipBucket48(bucket: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* The client address of a request. With `trustProxy = n > 0`, the relay sits
|
|
20
|
+
* behind n proxies it runs, each appending to X-Forwarded-For, so the client
|
|
21
|
+
* is the n-th entry from the right. With 0 (the default) the header is ignored.
|
|
22
|
+
*/
|
|
23
|
+
export declare function clientAddress(remote: string | undefined, xff: string | string[] | undefined, trustProxy: number, onShortHeader?: (hops: number) => void): string;
|
package/dist/net.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Client addresses for per-IP limits.
|
|
4
|
+
//
|
|
5
|
+
// An IPv6 user typically controls a whole /64 (often far more), so per-IP
|
|
6
|
+
// limits key IPv6 addresses by their /64 prefix; otherwise one host could
|
|
7
|
+
// rotate through 2^64 addresses and defeat every limit. IPv4-mapped IPv6
|
|
8
|
+
// addresses (::ffff:a.b.c.d) are treated as the IPv4 address.
|
|
9
|
+
import { isIPv4, isIPv6 } from "node:net";
|
|
10
|
+
/** Expands an IPv6 address to 8 hextets (no zone id), or undefined. */
|
|
11
|
+
function expandIPv6(ip) {
|
|
12
|
+
const addr = ip.split("%")[0];
|
|
13
|
+
if (!isIPv6(addr))
|
|
14
|
+
return undefined;
|
|
15
|
+
let head;
|
|
16
|
+
let tail;
|
|
17
|
+
if (addr.includes("::")) {
|
|
18
|
+
const [h, t] = addr.split("::");
|
|
19
|
+
head = h ? h.split(":") : [];
|
|
20
|
+
tail = t ? t.split(":") : [];
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
head = addr.split(":");
|
|
24
|
+
tail = [];
|
|
25
|
+
}
|
|
26
|
+
// An embedded IPv4 tail (a.b.c.d) counts as two hextets.
|
|
27
|
+
const last = tail.length > 0 ? tail[tail.length - 1] : head[head.length - 1];
|
|
28
|
+
if (last && isIPv4(last)) {
|
|
29
|
+
const o = last.split(".").map(Number);
|
|
30
|
+
const hex = [((o[0] << 8) | o[1]).toString(16), ((o[2] << 8) | o[3]).toString(16)];
|
|
31
|
+
if (tail.length > 0)
|
|
32
|
+
tail.splice(tail.length - 1, 1, ...hex);
|
|
33
|
+
else
|
|
34
|
+
head.splice(head.length - 1, 1, ...hex);
|
|
35
|
+
}
|
|
36
|
+
const fill = 8 - head.length - tail.length;
|
|
37
|
+
if (fill < 0)
|
|
38
|
+
return undefined;
|
|
39
|
+
return [...head, ...Array(fill).fill("0"), ...tail].map((h) => h.toLowerCase().replace(/^0+(?=.)/, ""));
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Strips what proxies and sockets wrap around an address: brackets
|
|
43
|
+
* (`[2001:db8::1]`), a port (`203.0.113.5:4433`, `[2001:db8::1]:443`).
|
|
44
|
+
*/
|
|
45
|
+
export function bareAddress(raw) {
|
|
46
|
+
const v = raw.trim();
|
|
47
|
+
const bracketed = /^\[([^\]]+)\](?::\d+)?$/.exec(v);
|
|
48
|
+
if (bracketed)
|
|
49
|
+
return bracketed[1];
|
|
50
|
+
const v4port = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/.exec(v);
|
|
51
|
+
if (v4port)
|
|
52
|
+
return v4port[1];
|
|
53
|
+
return v;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The key per-IP limits use: the IPv4 address itself, or `<first 4 hextets>::/64`
|
|
57
|
+
* for IPv6, after stripping brackets and ports. Anything unparseable is
|
|
58
|
+
* returned unchanged.
|
|
59
|
+
*/
|
|
60
|
+
export function ipBucket(raw) {
|
|
61
|
+
const ip = bareAddress(raw);
|
|
62
|
+
if (isIPv4(ip))
|
|
63
|
+
return ip;
|
|
64
|
+
const h = expandIPv6(ip);
|
|
65
|
+
if (!h)
|
|
66
|
+
return ip;
|
|
67
|
+
// ::ffff:a.b.c.d
|
|
68
|
+
if (h.slice(0, 5).every((x) => x === "0") && h[5] === "ffff") {
|
|
69
|
+
const a = parseInt(h[6], 16);
|
|
70
|
+
const b = parseInt(h[7], 16);
|
|
71
|
+
return `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`;
|
|
72
|
+
}
|
|
73
|
+
return `${h.slice(0, 4).join(":")}::/64`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* A coarser bucket for budgets one network shouldn't exhaust on its own (P4
|
|
77
|
+
* invite bytes): an IPv6 /64 bucket widens to its /48 (what one site is
|
|
78
|
+
* typically assigned); IPv4 stays the address.
|
|
79
|
+
*/
|
|
80
|
+
export function ipBucket48(bucket) {
|
|
81
|
+
const m = /^([0-9a-f]+:[0-9a-f]+:[0-9a-f]+):[0-9a-f]+::\/64$/.exec(bucket);
|
|
82
|
+
return m ? `${m[1]}::/48` : bucket;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The client address of a request. With `trustProxy = n > 0`, the relay sits
|
|
86
|
+
* behind n proxies it runs, each appending to X-Forwarded-For, so the client
|
|
87
|
+
* is the n-th entry from the right. With 0 (the default) the header is ignored.
|
|
88
|
+
*/
|
|
89
|
+
export function clientAddress(remote, xff, trustProxy, onShortHeader) {
|
|
90
|
+
if (trustProxy > 0) {
|
|
91
|
+
const hops = (Array.isArray(xff) ? xff.join(",") : (xff ?? ""))
|
|
92
|
+
.split(",")
|
|
93
|
+
.map((s) => s.trim())
|
|
94
|
+
.filter(Boolean);
|
|
95
|
+
if (hops.length >= trustProxy)
|
|
96
|
+
return bareAddress(hops[hops.length - trustProxy]);
|
|
97
|
+
// Fewer hops than trusted proxies: the header isn't what the operator
|
|
98
|
+
// said it would be (a header-replacing proxy, or a request that bypassed
|
|
99
|
+
// one), so trust only the socket, and say so.
|
|
100
|
+
onShortHeader?.(hops.length);
|
|
101
|
+
}
|
|
102
|
+
return bareAddress(remote ?? "unknown");
|
|
103
|
+
}
|