@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/dist/store.js ADDED
@@ -0,0 +1,492 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Relay storage. Two implementations: SqliteStore (node:sqlite, production)
4
+ // and MemoryStore (tests, ephemeral relays). Both keep only:
5
+ // - device bindings: did -> iss (§5.2: one iss per did), with last-seen time;
6
+ // - envelopes: the opaque JWS plus its mailbox (to, tdid), size, arrival
7
+ // time, and `src`: a keyed hash of the sender's IP bucket under a key held
8
+ // ONLY in the relay's memory (for source-first eviction). Nothing on disk
9
+ // links an envelope to a network: once the process that made a tag is
10
+ // gone, so is its key, and the tag is an anonymous group (R-M1);
11
+ // - capability state: revoked / uses, keyed by a hash of (iss, capid), so the
12
+ // store never holds a capability or the friend graph in readable form;
13
+ // - identity documents, which are public by design (§5.6), plus a small
14
+ // per-userId index (head, tips, allowed devices; or a tombstone) so request
15
+ // paths never rescan documents.
16
+ // Times are milliseconds since the epoch unless named `...Sec`.
17
+ /** Seen-device rows kept per userId (128 versions × 10 devices, with headroom). */
18
+ export const MAX_SEEN_PER_ISS = 2048;
19
+ // ---------------------------------------------------------------------------
20
+ const mbox = (to, tdid) => `${to}\n${tdid}`;
21
+ /** Every identity version referenced as `prev` or `merge` by another held version. */
22
+ export function referencedHashes(docs) {
23
+ const refs = new Set();
24
+ for (const d of docs) {
25
+ if (d.prev)
26
+ refs.add(d.prev);
27
+ if (d.merge)
28
+ refs.add(d.merge);
29
+ }
30
+ return refs;
31
+ }
32
+ /** Picks the group to evict from, per EvictPolicy. `groups` defaults to the candidates' count. */
33
+ export function pickSource(cands, policy = {}, groups = cands.length) {
34
+ const floor = policy.floor ?? 0;
35
+ if (policy.sender !== undefined) {
36
+ const own = cands.find((c) => c.src === policy.sender);
37
+ const fairShare = policy.quota !== undefined && groups > 0 ? policy.quota / groups : 0;
38
+ if (own && own.bytes > Math.max(floor, fairShare))
39
+ return own.src;
40
+ }
41
+ const largest = (xs) => xs.reduce((b, x) => (!b || x.bytes > b.bytes ? x : b), undefined)?.src;
42
+ const above = cands.filter((c) => c.bytes > floor);
43
+ return largest(above.length > 0 ? above : cands);
44
+ }
45
+ /** The running totals an envelope counts toward: (kind, key). */
46
+ export function totalKeys(to, tdid, src) {
47
+ return [
48
+ ["all", ""],
49
+ ["mbox", `${to}\n${tdid}`],
50
+ ["rcpt", to],
51
+ ["src", src],
52
+ ["rsrc", `${to}\n${src}`],
53
+ ["smbox", `${src}\n${to}\n${tdid}`],
54
+ ];
55
+ }
56
+ const copyIndex = (i) => ({
57
+ ...i,
58
+ tips: [...i.tips],
59
+ allowed: [...i.allowed],
60
+ cap: i.cap ? [...i.cap] : null,
61
+ });
62
+ export class MemoryStore {
63
+ devices = new Map();
64
+ mailboxes = new Map();
65
+ caps = new Map();
66
+ docs = new Map();
67
+ index = new Map();
68
+ seen = new Map();
69
+ revoked = new Map();
70
+ meta = new Map();
71
+ invites = new Map();
72
+ /** Invite bytes per userId (eviction picks the biggest holder without a scan). */
73
+ inviteIss = new Map();
74
+ /** Evicted lids, until their invite would have expired (so the inviter can tell evicted from taken). */
75
+ evicted = new Map();
76
+ inviteTotal = 0;
77
+ nextRid = 1;
78
+ async init() { }
79
+ transaction(fn) {
80
+ return fn();
81
+ }
82
+ getMeta(key) {
83
+ return this.meta.get(key);
84
+ }
85
+ setMeta(key, value) {
86
+ this.meta.set(key, value);
87
+ }
88
+ evictableDevices(limit, after) {
89
+ // Only the device's OWN issuer's allowlist pins it: another identity's
90
+ // document listing this did means nothing (matched on (iss, did)).
91
+ const listed = (iss, did) => this.index.get(iss)?.allowed.includes(did) ?? false;
92
+ return [...this.devices.entries()]
93
+ .filter(([did, d]) => !listed(d.iss, did) && this.mailboxBytes(d.iss, did) === 0)
94
+ .filter(([did, d]) => !after || d.lastSeen > after.lastSeen || (d.lastSeen === after.lastSeen && did > after.did))
95
+ .sort((a, b) => a[1].lastSeen - b[1].lastSeen || (a[0] < b[0] ? -1 : 1))
96
+ .slice(0, limit)
97
+ .map(([did, d]) => ({ did, iss: d.iss, lastSeen: d.lastSeen }));
98
+ }
99
+ deleteDevice(did) {
100
+ this.devices.delete(did);
101
+ }
102
+ deviceIssuer(did) {
103
+ return this.devices.get(did)?.iss;
104
+ }
105
+ touchDevice(did, iss, now) {
106
+ const d = this.devices.get(did);
107
+ if (!d) {
108
+ this.devices.set(did, { iss, lastSeen: now });
109
+ return true;
110
+ }
111
+ if (d.iss === iss)
112
+ d.lastSeen = now;
113
+ return false;
114
+ }
115
+ putEnvelope(e, caps) {
116
+ const key = mbox(e.to, e.tdid);
117
+ let box = this.mailboxes.get(key);
118
+ if (!box)
119
+ this.mailboxes.set(key, (box = []));
120
+ const rid = this.nextRid++;
121
+ box.push({ rid, ...e });
122
+ let bytes = box.reduce((n, x) => n + x.size, 0);
123
+ let dropped = 0;
124
+ let droppedBytes = 0;
125
+ while (box.length > 0 && (box.length > caps.maxEnvelopes || bytes > caps.maxBytes)) {
126
+ const size = box.shift().size;
127
+ bytes -= size;
128
+ droppedBytes += size;
129
+ dropped++;
130
+ }
131
+ return { rid, dropped, droppedBytes };
132
+ }
133
+ envelopesAfter(to, tdid, afterRid, notBefore, limit) {
134
+ const box = this.mailboxes.get(mbox(to, tdid)) ?? [];
135
+ return box
136
+ .filter((x) => x.rid > afterRid && x.receivedAt >= notBefore)
137
+ .slice(0, limit)
138
+ .map(({ src: _src, ...e }) => e);
139
+ }
140
+ ackEnvelopes(to, tdid, rids) {
141
+ const key = mbox(to, tdid);
142
+ const box = this.mailboxes.get(key);
143
+ if (!box)
144
+ return { count: 0, bytes: 0 };
145
+ const drop = new Set(rids);
146
+ const keep = [];
147
+ let bytes = 0;
148
+ for (const x of box) {
149
+ if (drop.has(x.rid))
150
+ bytes += x.size;
151
+ else
152
+ keep.push(x);
153
+ }
154
+ const count = box.length - keep.length;
155
+ if (keep.length === 0)
156
+ this.mailboxes.delete(key);
157
+ else
158
+ this.mailboxes.set(key, keep);
159
+ return { count, bytes };
160
+ }
161
+ bytesForRecipient(to) {
162
+ let n = 0;
163
+ for (const box of this.mailboxes.values())
164
+ for (const x of box)
165
+ if (x.to === to)
166
+ n += x.size;
167
+ return n;
168
+ }
169
+ mailboxBytes(to, tdid) {
170
+ return (this.mailboxes.get(mbox(to, tdid)) ?? []).reduce((n, x) => n + x.size, 0);
171
+ }
172
+ all() {
173
+ return [...this.mailboxes.values()].flat();
174
+ }
175
+ remove(e) {
176
+ const key = mbox(e.to, e.tdid);
177
+ const box = this.mailboxes.get(key);
178
+ box.splice(box.indexOf(e), 1);
179
+ if (box.length === 0)
180
+ this.mailboxes.delete(key);
181
+ return e.size;
182
+ }
183
+ /** The key with the most bytes, grouping `items` by `keyOf`. */
184
+ static largest(items, keyOf) {
185
+ const sums = new Map();
186
+ for (const x of items)
187
+ sums.set(keyOf(x), (sums.get(keyOf(x)) ?? 0) + x.size);
188
+ let best;
189
+ let max = -1;
190
+ for (const [k, v] of sums)
191
+ if (v > max)
192
+ [best, max] = [k, v];
193
+ return best;
194
+ }
195
+ /** Bytes per source among `items`. */
196
+ static sums(items) {
197
+ const m = new Map();
198
+ for (const x of items)
199
+ m.set(x.src, (m.get(x.src) ?? 0) + x.size);
200
+ return [...m].map(([src, bytes]) => ({ src, bytes }));
201
+ }
202
+ evictRecipient(to, bytes, policy = {}) {
203
+ let freed = 0;
204
+ while (freed < bytes) {
205
+ const mine = this.all().filter((x) => x.to === to);
206
+ const src = pickSource(MemoryStore.sums(mine), policy);
207
+ if (src === undefined)
208
+ break;
209
+ const oldest = mine.filter((x) => x.src === src).sort((a, b) => a.rid - b.rid)[0];
210
+ freed += this.remove(oldest);
211
+ }
212
+ return freed;
213
+ }
214
+ evictGlobal(bytes, policy = {}) {
215
+ let freed = 0;
216
+ while (freed < bytes) {
217
+ const all = this.all();
218
+ const src = pickSource(MemoryStore.sums(all), policy);
219
+ if (src === undefined)
220
+ break;
221
+ const fromSrc = all.filter((x) => x.src === src);
222
+ const box = MemoryStore.largest(fromSrc, (x) => mbox(x.to, x.tdid));
223
+ const oldest = fromSrc.filter((x) => mbox(x.to, x.tdid) === box).sort((a, b) => a.rid - b.rid)[0];
224
+ freed += this.remove(oldest);
225
+ }
226
+ return freed;
227
+ }
228
+ sourceBytes(src) {
229
+ return this.all()
230
+ .filter((x) => x.src === src)
231
+ .reduce((n, x) => n + x.size, 0);
232
+ }
233
+ evictSource(src, bytes) {
234
+ let freed = 0;
235
+ while (freed < bytes) {
236
+ const fromSrc = this.all().filter((x) => x.src === src);
237
+ const box = MemoryStore.largest(fromSrc, (x) => mbox(x.to, x.tdid));
238
+ if (box === undefined)
239
+ break;
240
+ const oldest = fromSrc.filter((x) => mbox(x.to, x.tdid) === box).sort((a, b) => a.rid - b.rid)[0];
241
+ freed += this.remove(oldest);
242
+ }
243
+ return freed;
244
+ }
245
+ expireBatch(before, limit) {
246
+ const victims = this.all()
247
+ .filter((x) => x.receivedAt < before)
248
+ .sort((a, b) => a.receivedAt - b.receivedAt || a.rid - b.rid)
249
+ .slice(0, limit);
250
+ let bytes = 0;
251
+ for (const v of victims)
252
+ bytes += this.remove(v);
253
+ return { count: victims.length, bytes };
254
+ }
255
+ capState(key) {
256
+ const c = this.caps.get(key);
257
+ return { revoked: c?.revoked ?? false, uses: c?.uses ?? 0 };
258
+ }
259
+ revokeCap(key, now) {
260
+ const c = this.caps.get(key) ?? { revoked: false, uses: 0, updatedAt: now };
261
+ this.caps.set(key, { ...c, revoked: true, updatedAt: now });
262
+ }
263
+ useCap(key, now) {
264
+ const c = this.caps.get(key) ?? { revoked: false, uses: 0, updatedAt: now };
265
+ this.caps.set(key, { ...c, uses: c.uses + 1, updatedAt: now });
266
+ }
267
+ identityDoc(hash) {
268
+ return this.docs.get(hash);
269
+ }
270
+ identityDocs(iss) {
271
+ return [...this.docs.values()].filter((d) => d.iss === iss).sort((a, b) => a.ver - b.ver);
272
+ }
273
+ putIdentityDoc(d) {
274
+ if (this.docs.has(d.hash))
275
+ return false;
276
+ this.docs.set(d.hash, { ...d, devices: [...d.devices] });
277
+ return true;
278
+ }
279
+ deleteIdentityDocs(hashes) {
280
+ for (const h of hashes)
281
+ this.docs.delete(h);
282
+ }
283
+ deleteIdentityDocsOf(iss) {
284
+ for (const [h, d] of this.docs)
285
+ if (d.iss === iss)
286
+ this.docs.delete(h);
287
+ }
288
+ identityIndex(iss) {
289
+ const i = this.index.get(iss);
290
+ return i && copyIndex(i);
291
+ }
292
+ putIdentityIndex(idx) {
293
+ this.index.set(idx.iss, copyIndex(idx));
294
+ }
295
+ deleteIdentity(iss) {
296
+ this.deleteIdentityDocsOf(iss);
297
+ this.index.delete(iss);
298
+ this.seen.delete(iss);
299
+ }
300
+ seenDevices(iss, sinceMs) {
301
+ return [...(this.seen.get(iss) ?? new Map())].filter(([, at]) => at >= sinceMs).map(([d]) => d);
302
+ }
303
+ addSeen(iss, dids, at) {
304
+ if (dids.length === 0)
305
+ return;
306
+ let m = this.seen.get(iss);
307
+ if (!m)
308
+ this.seen.set(iss, (m = new Map()));
309
+ for (const d of dids) {
310
+ m.delete(d);
311
+ m.set(d, at);
312
+ }
313
+ // Oldest first: keep the newest MAX_SEEN_PER_ISS.
314
+ while (m.size > MAX_SEEN_PER_ISS)
315
+ m.delete(m.keys().next().value);
316
+ }
317
+ expiredIdentities(headExpBeforeSec, limit) {
318
+ return [...this.index.values()]
319
+ .filter((i) => i.leftAt === null && i.headExp < headExpBeforeSec)
320
+ .slice(0, limit)
321
+ .map((i) => i.iss);
322
+ }
323
+ staleTombstones(leftBefore, limit) {
324
+ return [...this.index.values()]
325
+ .filter((i) => i.leftAt !== null && i.leftAt < leftBefore)
326
+ .slice(0, limit)
327
+ .map((i) => i.iss);
328
+ }
329
+ envelopeTotals() {
330
+ const c = this.counts();
331
+ return { envelopes: c.envelopes, bytes: c.envelopeBytes };
332
+ }
333
+ sweep(c, limit) {
334
+ let caps = 0;
335
+ for (const [k, v] of this.caps) {
336
+ if (caps >= limit)
337
+ break;
338
+ if (v.updatedAt < c.capsBefore) {
339
+ this.caps.delete(k);
340
+ caps++;
341
+ }
342
+ }
343
+ const refs = referencedHashes([...this.docs.values()]);
344
+ let identityDocs = 0;
345
+ for (const [h, d] of this.docs) {
346
+ if (identityDocs >= limit)
347
+ break;
348
+ if (d.receivedAt < c.identityVersionsBefore && refs.has(h)) {
349
+ const allowed = new Set(this.index.get(d.iss)?.allowed ?? []);
350
+ const gone = d.devices.filter((x) => !allowed.has(x));
351
+ if (gone.length > 0 && c.nowMs !== undefined)
352
+ this.addSeen(d.iss, gone, c.nowMs);
353
+ this.docs.delete(h);
354
+ identityDocs++;
355
+ }
356
+ }
357
+ if (c.seenBefore !== undefined) {
358
+ for (const [iss, m] of this.seen) {
359
+ for (const [d, at] of m)
360
+ if (at < c.seenBefore)
361
+ m.delete(d);
362
+ if (m.size === 0)
363
+ this.seen.delete(iss);
364
+ }
365
+ }
366
+ let devices = 0;
367
+ for (const [did, d] of this.devices) {
368
+ if (devices >= limit)
369
+ break;
370
+ if (d.lastSeen < c.devicesBefore) {
371
+ this.devices.delete(did);
372
+ devices++;
373
+ }
374
+ }
375
+ return { caps, identityDocs, devices };
376
+ }
377
+ issAdd(iss, d) {
378
+ const n = (this.inviteIss.get(iss) ?? 0) + d;
379
+ if (n <= 0)
380
+ this.inviteIss.delete(iss);
381
+ else
382
+ this.inviteIss.set(iss, n);
383
+ }
384
+ dropInvite(i) {
385
+ this.invites.delete(i.lid);
386
+ this.inviteTotal -= i.size;
387
+ this.issAdd(i.iss, -i.size);
388
+ }
389
+ putInvite(i) {
390
+ if (this.invites.has(i.lid))
391
+ return false;
392
+ this.invites.set(i.lid, { ...i });
393
+ this.inviteTotal += i.size;
394
+ this.issAdd(i.iss, i.size);
395
+ return true;
396
+ }
397
+ takeInvite(lid, now) {
398
+ const i = this.invites.get(lid);
399
+ if (!i)
400
+ return undefined;
401
+ this.dropInvite(i);
402
+ return i.expiresAt > now ? i : undefined;
403
+ }
404
+ deleteInvite(lid, iss) {
405
+ const i = this.invites.get(lid);
406
+ if (!i || i.iss !== iss)
407
+ return false;
408
+ this.dropInvite(i);
409
+ return true;
410
+ }
411
+ invitesOf(iss, now) {
412
+ return [...this.invites.values()]
413
+ .filter((i) => i.iss === iss && i.expiresAt > now)
414
+ .sort((a, b) => a.createdAt - b.createdAt || (a.lid < b.lid ? -1 : 1))
415
+ .map((i) => i.lid);
416
+ }
417
+ evictedInvitesOf(iss, now) {
418
+ return [...this.evicted.entries()].filter(([, e]) => e.iss === iss && e.expiresAt > now).map(([lid]) => lid);
419
+ }
420
+ inviteBytes() {
421
+ return this.inviteTotal;
422
+ }
423
+ inviteBytesOfIss(iss) {
424
+ return this.inviteIss.get(iss) ?? 0;
425
+ }
426
+ inviteBytesOfSrc(src) {
427
+ let n = 0;
428
+ for (const i of this.invites.values())
429
+ if (i.src === src)
430
+ n += i.size;
431
+ return n;
432
+ }
433
+ evictInvites(bytes, now) {
434
+ let freed = 0;
435
+ if (now !== undefined) {
436
+ const expired = [...this.invites.values()].filter((i) => i.expiresAt <= now).sort((a, b) => a.expiresAt - b.expiresAt || (a.lid < b.lid ? -1 : 1));
437
+ for (const i of expired) {
438
+ if (freed >= bytes)
439
+ break;
440
+ this.dropInvite(i);
441
+ freed += i.size;
442
+ }
443
+ }
444
+ while (freed < bytes && this.inviteIss.size > 0) {
445
+ let top = "";
446
+ let most = -1;
447
+ for (const [iss, b] of this.inviteIss)
448
+ if (b > most || (b === most && iss < top))
449
+ [top, most] = [iss, b];
450
+ let newest;
451
+ for (const i of this.invites.values()) {
452
+ if (i.iss === top && (!newest || i.createdAt > newest.createdAt || (i.createdAt === newest.createdAt && i.lid > newest.lid)))
453
+ newest = i;
454
+ }
455
+ if (!newest)
456
+ break;
457
+ this.dropInvite(newest);
458
+ this.evicted.set(newest.lid, { iss: newest.iss, expiresAt: newest.expiresAt });
459
+ freed += newest.size;
460
+ }
461
+ return freed;
462
+ }
463
+ sweepInvites(now, limit) {
464
+ const expired = [...this.invites.values()].filter((i) => i.expiresAt <= now).sort((a, b) => a.expiresAt - b.expiresAt || (a.lid < b.lid ? -1 : 1));
465
+ for (const i of expired.slice(0, limit))
466
+ this.dropInvite(i);
467
+ let evicted = 0;
468
+ for (const [lid, e] of this.evicted) {
469
+ if (evicted >= limit)
470
+ break;
471
+ if (e.expiresAt <= now) {
472
+ this.evicted.delete(lid);
473
+ evicted++;
474
+ }
475
+ }
476
+ return { invites: Math.min(limit, expired.length), evicted };
477
+ }
478
+ counts() {
479
+ let envelopes = 0;
480
+ let envelopeBytes = 0;
481
+ for (const box of this.mailboxes.values()) {
482
+ envelopes += box.length;
483
+ for (const x of box)
484
+ envelopeBytes += x.size;
485
+ }
486
+ return { envelopes, envelopeBytes, devices: this.devices.size, identityDocs: this.docs.size };
487
+ }
488
+ ping() {
489
+ return true;
490
+ }
491
+ close() { }
492
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@peer2peer/relay",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Peer2Peer v3 open relay: dumb store-and-forward for end-to-end encrypted envelopes, identity documents and device-link mailboxes",
5
+ "keywords": [
6
+ "peer2peer",
7
+ "p2p",
8
+ "relay",
9
+ "store-and-forward",
10
+ "websocket",
11
+ "e2ee",
12
+ "self-hosted",
13
+ "ai-agents"
14
+ ],
15
+ "homepage": "https://github.com/ix-infrastructure/Peer2Peer/tree/main/packages/relay#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/ix-infrastructure/Peer2Peer/issues"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "Ix Infrastructure",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/ix-infrastructure/Peer2Peer.git",
24
+ "directory": "packages/relay"
25
+ },
26
+ "type": "module",
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ }
34
+ },
35
+ "bin": {
36
+ "p2p-relay": "./dist/bin.js"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "!dist/**/__tests__",
41
+ "!dist/**/*.test.*",
42
+ "!dist/**/*.map",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "engines": {
47
+ "node": ">=22.13"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public",
51
+ "provenance": true,
52
+ "registry": "https://registry.npmjs.org/"
53
+ },
54
+ "dependencies": {
55
+ "@noble/curves": "2.4.0",
56
+ "@peer2peer/core": "0.1.0",
57
+ "ws": "8.22.0"
58
+ }
59
+ }