@peer2peer/relay 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,386 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Identity documents on the relay (docs/protocol.md §5.6, chain rules §2.5).
4
+ //
5
+ // - Scope: only documents whose `relays` list this relay are stored.
6
+ // - Leaving: a document that drops this relay and chains from the current
7
+ // head (or merges all current tips) is the owner leaving. The relay deletes
8
+ // the documents and stops serving them, but keeps a TOMBSTONE: the last
9
+ // allowlist and head version. Rule 6 keeps applying to that userId, so
10
+ // deleting documents never re-opens auth to revoked devices. Any other
11
+ // document that doesn't list this relay is refused.
12
+ // - Publish: accepted when its `prev` (and, for a merge, its `merge`) is a
13
+ // version the relay holds, or when the relay holds no version of that
14
+ // userId. Every branch is kept, up to `maxTips` tips.
15
+ // - Roots the relay can't vouch for (L5, N4): with nothing held, any version
16
+ // is accepted as the root, including an OLD version replayed by someone who
17
+ // has a copy (for example a since-revoked device). Such a history is
18
+ // "unanchored" (no ver-1 root held). A later document from the same
19
+ // identity key with a higher `ver` than the head, which doesn't chain,
20
+ // replaces an unanchored history; an anchored one is only ever extended,
21
+ // and its owner back-fills gaps. Re-entry after a tombstone also needs a
22
+ // higher `ver` than the tombstoned head. In both cases the new root's
23
+ // allowlist is CAPPED by (intersected with) the previous allowlist until a
24
+ // document chains onto the new root, so a replay can't re-admit a device.
25
+ // - Head: the highest `ver` held (a tie goes to the higher jwsHash, so every
26
+ // relay picks the same one). Tips: versions no held version names as
27
+ // `prev` or `merge`.
28
+ // - Retention: non-tip versions for 90 days and at most `maxVersions` per
29
+ // userId (oldest non-tips go first). A userId whose head has been expired
30
+ // for `expiredRetentionSec` is tombstoned; tombstones are deleted after
31
+ // `tombstoneRetentionSec` (longer than any device certificate can outlive
32
+ // its revocation).
33
+ // - State-based acceptance (review R3): a version is checked against what the
34
+ // relay holds now: chain and merge shape, `by` a key holder, a merge's
35
+ // devices within both parents', and, over a restricted connection, being on
36
+ // top of the tips. No-return (a revoked did never re-listed) is NOT checked
37
+ // here: only identity-key holders publish versions, so a revoked ordinary
38
+ // device can't re-list itself, and clients enforce no-return from their own
39
+ // chains (core revokedAlong). What the relay must know is which dids were
40
+ // listed and aren't now, to refuse them even a restricted connection: the
41
+ // dids of every held version, plus those of history it discarded
42
+ // (tombstones, replaced roots) for 91 days, longer than any certificate.
43
+ // - Request paths (auth, send, GETs) read only the per-userId index and single
44
+ // documents by hash, never a full scan. Every publish's prune, insert and
45
+ // reindex is one store transaction.
46
+ import { referencedHashes } from "./store.js";
47
+ const MAX_DOC_BYTES = 16 * 1024;
48
+ const SKEW_SEC = 300;
49
+ function higher(a, b) {
50
+ return a.ver > b.ver || (a.ver === b.ver && a.hash > b.hash);
51
+ }
52
+ /**
53
+ * Builds the index of a userId from its full set of held documents. With a
54
+ * `cap`, the allowlist is intersected with it.
55
+ */
56
+ export function buildIndex(iss, docs, cap = null) {
57
+ if (docs.length === 0)
58
+ return undefined;
59
+ const refs = referencedHashes(docs);
60
+ const tips = docs.filter((d) => !refs.has(d.hash)).sort((a, b) => (higher(a, b) ? -1 : 1));
61
+ let head = docs[0];
62
+ for (const d of docs)
63
+ if (higher(d, head))
64
+ head = d;
65
+ let allowed = new Set(tips[0].devices);
66
+ for (const t of tips.slice(1))
67
+ allowed = new Set(t.devices.filter((x) => allowed.has(x)));
68
+ if (cap)
69
+ allowed = new Set([...allowed].filter((x) => cap.includes(x)));
70
+ return {
71
+ iss,
72
+ head: head.hash,
73
+ headVer: head.ver,
74
+ headExp: head.exp,
75
+ tips: tips.map((t) => t.hash),
76
+ allowed: [...allowed],
77
+ cap,
78
+ leftAt: null,
79
+ };
80
+ }
81
+ export class IdentityService {
82
+ store;
83
+ crypto;
84
+ relayUrl;
85
+ now;
86
+ limits;
87
+ constructor(store, crypto, relayUrl, now, limits) {
88
+ this.store = store;
89
+ this.crypto = crypto;
90
+ this.relayUrl = relayUrl;
91
+ this.now = now;
92
+ this.limits = limits;
93
+ }
94
+ /** How long dids of discarded history are remembered (the tombstone window, > 90-day certificates). */
95
+ get seenWindowMs() {
96
+ return this.limits.tombstoneRetentionSec * 1000;
97
+ }
98
+ /** Every did any held version of `iss` lists. */
99
+ heldDids(iss) {
100
+ const out = new Set();
101
+ for (const d of this.store.identityDocs(iss))
102
+ for (const x of d.devices)
103
+ out.add(x);
104
+ return out;
105
+ }
106
+ /**
107
+ * Dids that were listed and aren't in the current allowlist: refused even a
108
+ * restricted connection (H1). A restore always brings a brand-new did, which
109
+ * isn't here. Bounded by the held versions (≤ maxVersions × 10) and the seen
110
+ * rows (91 days, capped).
111
+ */
112
+ revoked(iss) {
113
+ const allowed = new Set(this.store.identityIndex(iss)?.allowed ?? []);
114
+ const out = new Set();
115
+ for (const d of this.heldDids(iss))
116
+ if (!allowed.has(d))
117
+ out.add(d);
118
+ for (const d of this.store.seenDevices(iss, this.now() - this.seenWindowMs))
119
+ if (!allowed.has(d))
120
+ out.add(d);
121
+ return out;
122
+ }
123
+ reindex(iss, cap) {
124
+ const before = this.store.identityIndex(iss)?.allowed ?? [];
125
+ const idx = buildIndex(iss, this.store.identityDocs(iss), cap);
126
+ if (idx) {
127
+ this.store.putIdentityIndex(idx);
128
+ // R4-M1: a did leaving the allowlist is remembered for the window from now, so pruning the
129
+ // versions that listed it can't re-open even a restricted connection while its cert lives.
130
+ const dropped = before.filter((d) => !idx.allowed.includes(d));
131
+ if (dropped.length > 0)
132
+ this.store.addSeen(iss, dropped, this.now());
133
+ }
134
+ else
135
+ this.store.deleteIdentity(iss);
136
+ }
137
+ /** Deletes the documents of `iss` but keeps its allowlist and head version. */
138
+ tombstone(idx) {
139
+ this.store.transaction(() => {
140
+ // Remember which dids this history listed, for the tombstone window.
141
+ this.store.addSeen(idx.iss, [...this.heldDids(idx.iss), ...idx.allowed], this.now());
142
+ this.store.deleteIdentityDocsOf(idx.iss);
143
+ this.store.putIdentityIndex({ ...idx, head: "", tips: [], cap: null, leftAt: this.now() });
144
+ });
145
+ }
146
+ chainsFrom(doc) {
147
+ if (doc.prev === null)
148
+ return "gap";
149
+ const prev = this.store.identityDoc(doc.prev);
150
+ if (!prev || prev.iss !== doc.iss)
151
+ return "gap";
152
+ let merge;
153
+ if (doc.merge !== undefined) {
154
+ merge = this.store.identityDoc(doc.merge);
155
+ if (!merge || merge.iss !== doc.iss)
156
+ return "gap";
157
+ }
158
+ try {
159
+ // Stored versions were verified on the way in; re-parse to hand the seam
160
+ // full documents (publishes are rate-limited and rare).
161
+ this.crypto.verifyIdentityDocLink(this.crypto.parseIdentityDoc(prev.jws), doc, merge ? this.crypto.parseIdentityDoc(merge.jws) : undefined);
162
+ return "ok";
163
+ }
164
+ catch {
165
+ return "bad";
166
+ }
167
+ }
168
+ /**
169
+ * N4/L-c: "owner left" only from the top of the held history: a document
170
+ * extending the ONLY tip, or a merge of every tip. During a fork, extending
171
+ * one branch says nothing about the others, which still list this relay.
172
+ */
173
+ chainsFromTop(doc, idx) {
174
+ const extendsOnlyTip = idx.tips.length === 1 && doc.prev === idx.tips[0] && doc.merge === undefined;
175
+ const mergesAllTips = doc.merge !== undefined && idx.tips.every((t) => t === doc.prev || t === doc.merge);
176
+ return (extendsOnlyTip || mergesAllTips) && this.chainsFrom(doc) === "ok";
177
+ }
178
+ mergesTwoTips(doc, idx) {
179
+ return doc.merge !== undefined && doc.prev !== null && idx.tips.includes(doc.prev) && idx.tips.includes(doc.merge) && this.chainsFrom(doc) === "ok";
180
+ }
181
+ publish(jws, publisherIss, opts = {}) {
182
+ if (typeof jws !== "string")
183
+ return { ok: false, code: "bad-identity" };
184
+ if (jws.length > MAX_DOC_BYTES)
185
+ return { ok: false, code: "too-large" };
186
+ let doc;
187
+ try {
188
+ doc = this.crypto.parseIdentityDoc(jws);
189
+ }
190
+ catch {
191
+ return { ok: false, code: "bad-identity" };
192
+ }
193
+ if (doc.iss !== publisherIss)
194
+ return { ok: false, code: "forbidden" };
195
+ if (doc.iat > Math.floor(this.now() / 1000) + SKEW_SEC)
196
+ return { ok: false, code: "bad-identity" };
197
+ if (this.store.identityDoc(doc.hash))
198
+ return { ok: true, duplicate: true };
199
+ const idx = this.store.identityIndex(doc.iss);
200
+ const live = idx !== undefined && idx.leftAt === null;
201
+ // Restricted publishers (§2.7 restore): only on top of the held history, never a fork or a new
202
+ // root: extend the only tip, or merge two current tips (a merge never adds a device, so three
203
+ // or more tips are merged pairwise).
204
+ // A version whose parent isn't held is a gap (R3-M2): the publisher back-fills the missing
205
+ // versions, each of which then extends the only tip. Genuine forks stay forbidden.
206
+ if (opts.topOnly && !(live && (this.chainsFromTop(doc, idx) || this.mergesTwoTips(doc, idx)))) {
207
+ return { ok: false, code: live && this.chainsFrom(doc) === "gap" ? "identity-gap" : "forbidden" };
208
+ }
209
+ if (!doc.relays.includes(this.relayUrl)) {
210
+ if (live && this.chainsFromTop(doc, idx)) {
211
+ this.tombstone(idx);
212
+ return { ok: true, duplicate: false, left: true };
213
+ }
214
+ return { ok: false, code: "forbidden" };
215
+ }
216
+ // Decide the new history: extend, or start a (capped) new root.
217
+ let newTips;
218
+ let cap;
219
+ let replace = false;
220
+ if (!idx) {
221
+ newTips = [doc.hash];
222
+ cap = null;
223
+ }
224
+ else if (!live) {
225
+ // Re-entry after a tombstone: newer than what was known, and capped.
226
+ if (doc.ver <= idx.headVer)
227
+ return { ok: false, code: "identity-gap" };
228
+ newTips = [doc.hash];
229
+ cap = idx.allowed;
230
+ }
231
+ else {
232
+ const link = this.chainsFrom(doc);
233
+ if (link === "bad")
234
+ return { ok: false, code: "bad-identity" };
235
+ if (link === "gap") {
236
+ // Anchored = a ver-1 root is still held. Computed from the documents
237
+ // at publish time (never cached), so sweeping old versions can't leave
238
+ // it stale (N7). An anchored history is only ever extended; its owner
239
+ // back-fills gaps (§2.5).
240
+ const anchored = this.store.identityDocs(doc.iss).some((d) => d.ver === 1);
241
+ if (anchored || doc.ver <= idx.headVer)
242
+ return { ok: false, code: "identity-gap" };
243
+ // A newer version replaces history it doesn't chain to; the allowlist
244
+ // can't grow past the previous one until a document chains.
245
+ replace = true;
246
+ newTips = [doc.hash];
247
+ cap = idx.allowed;
248
+ }
249
+ else {
250
+ newTips = [doc.hash, ...idx.tips.filter((t) => t !== doc.prev && t !== doc.merge)];
251
+ if (newTips.length > this.limits.maxTips)
252
+ return { ok: false, code: "full" };
253
+ // A document that chains onto the held history lifts any cap.
254
+ cap = null;
255
+ }
256
+ }
257
+ let inserted = false;
258
+ const prunedDids = new Set();
259
+ this.store.transaction(() => {
260
+ // History about to be replaced: remember which dids it listed, for the tombstone window.
261
+ if (replace && idx)
262
+ this.store.addSeen(doc.iss, [...this.heldDids(doc.iss), ...idx.allowed], this.now());
263
+ if (replace || (idx && !live))
264
+ this.store.deleteIdentityDocsOf(doc.iss);
265
+ // Make room under maxVersions by dropping the oldest non-tip versions.
266
+ const held = this.store.identityDocs(doc.iss);
267
+ const over = held.length + 1 - this.limits.maxVersions;
268
+ if (over > 0) {
269
+ const keep = new Set(newTips);
270
+ const victimDocs = held
271
+ .filter((d) => !keep.has(d.hash))
272
+ .sort((a, b) => a.ver - b.ver || a.receivedAt - b.receivedAt)
273
+ .slice(0, over);
274
+ for (const v of victimDocs)
275
+ for (const d of v.devices)
276
+ prunedDids.add(d);
277
+ this.store.deleteIdentityDocs(victimDocs.map((d) => d.hash));
278
+ }
279
+ inserted = this.store.putIdentityDoc({
280
+ hash: doc.hash,
281
+ iss: doc.iss,
282
+ ver: doc.ver,
283
+ prev: doc.prev,
284
+ merge: doc.merge ?? null,
285
+ jws: doc.jws,
286
+ devices: doc.devices,
287
+ iat: doc.iat,
288
+ exp: doc.exp,
289
+ receivedAt: this.now(),
290
+ });
291
+ this.reindex(doc.iss, cap);
292
+ // R4-M1: dids of versions pruned by the cap that the allowlist doesn't hold are remembered.
293
+ const allowed = new Set(this.store.identityIndex(doc.iss)?.allowed ?? []);
294
+ const gone = [...prunedDids].filter((d) => !allowed.has(d));
295
+ if (gone.length > 0)
296
+ this.store.addSeen(doc.iss, gone, this.now());
297
+ });
298
+ return { ok: true, duplicate: !inserted };
299
+ }
300
+ /**
301
+ * §2.3 rule 6 as the relay applies it: undefined when the relay knows
302
+ * nothing of `iss`; otherwise the devices listed in EVERY tip (during a fork
303
+ * the intersection applies, §2.5), capped as above, or a tombstone's last
304
+ * allowlist.
305
+ */
306
+ allowedDevices(iss) {
307
+ const idx = this.store.identityIndex(iss);
308
+ return idx ? new Set(idx.allowed) : undefined;
309
+ }
310
+ /** The allowlist of `iss` and whether it is a tombstone; undefined when nothing is known. */
311
+ status(iss) {
312
+ const idx = this.store.identityIndex(iss);
313
+ return idx ? { allowed: new Set(idx.allowed), left: idx.leftAt !== null } : undefined;
314
+ }
315
+ head(iss) {
316
+ const idx = this.store.identityIndex(iss);
317
+ return idx && idx.leftAt === null ? this.store.identityDoc(idx.head) : undefined;
318
+ }
319
+ /** Every tip, highest first. */
320
+ tips(iss) {
321
+ const idx = this.store.identityIndex(iss);
322
+ if (!idx || idx.leftAt !== null)
323
+ return [];
324
+ return idx.tips.map((h) => this.store.identityDoc(h)).filter((d) => d !== undefined);
325
+ }
326
+ /**
327
+ * Walks back from `to` along `prev`, and along `merge` for merge versions,
328
+ * returning at most `n` versions, highest first.
329
+ */
330
+ chain(iss, to, n) {
331
+ const start = this.store.identityDoc(to);
332
+ if (!start || start.iss !== iss)
333
+ return undefined;
334
+ const out = [];
335
+ const seen = new Set([start.hash]);
336
+ const frontier = [start];
337
+ while (frontier.length > 0 && out.length < n) {
338
+ // Always expand the highest version next, so the result is highest-first.
339
+ frontier.sort((a, b) => (higher(a, b) ? -1 : 1));
340
+ const d = frontier.shift();
341
+ out.push(d);
342
+ for (const parent of [d.prev, d.merge]) {
343
+ if (!parent || seen.has(parent))
344
+ continue;
345
+ seen.add(parent);
346
+ const p = this.store.identityDoc(parent);
347
+ if (p && p.iss === iss)
348
+ frontier.push(p);
349
+ }
350
+ }
351
+ return out;
352
+ }
353
+ /**
354
+ * Tombstones userIds whose head expired more than `expiredRetentionSec`
355
+ * ago, and deletes tombstones older than `tombstoneRetentionSec`.
356
+ */
357
+ sweep(limit = Infinity) {
358
+ // F-4: at most `limit` of each per call, so the caller can yield between calls.
359
+ const nowMs = this.now();
360
+ const cutoff = Math.floor(nowMs / 1000) - this.limits.expiredRetentionSec;
361
+ const page = Math.min(500, limit);
362
+ let tombstoned = 0;
363
+ while (tombstoned < limit) {
364
+ const batch = this.store.expiredIdentities(cutoff, Math.min(page, limit - tombstoned));
365
+ for (const iss of batch) {
366
+ const idx = this.store.identityIndex(iss);
367
+ if (idx)
368
+ this.tombstone(idx);
369
+ }
370
+ tombstoned += batch.length;
371
+ if (batch.length < page)
372
+ break;
373
+ }
374
+ let deleted = 0;
375
+ const tombCutoff = nowMs - this.limits.tombstoneRetentionSec * 1000;
376
+ while (deleted < limit) {
377
+ const batch = this.store.staleTombstones(tombCutoff, Math.min(page, limit - deleted));
378
+ for (const iss of batch)
379
+ this.store.deleteIdentity(iss);
380
+ deleted += batch.length;
381
+ if (batch.length < page)
382
+ break;
383
+ }
384
+ return { tombstoned, deleted };
385
+ }
386
+ }
@@ -0,0 +1,11 @@
1
+ export * from "./config.js";
2
+ export * from "./crypto.js";
3
+ export * from "./client.js";
4
+ export * from "./identity.js";
5
+ export * from "./links.js";
6
+ export * from "./log.js";
7
+ export * from "./metrics.js";
8
+ export * from "./ratelimit.js";
9
+ export * from "./store.js";
10
+ export * from "./sqlite-store.js";
11
+ export * from "./server.js";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // @peer2peer/relay: the open Peer2Peer v3 relay (docs/protocol.md §5).
4
+ export * from "./config.js";
5
+ export * from "./crypto.js";
6
+ export * from "./client.js";
7
+ export * from "./identity.js";
8
+ export * from "./links.js";
9
+ export * from "./log.js";
10
+ export * from "./metrics.js";
11
+ export * from "./ratelimit.js";
12
+ export * from "./store.js";
13
+ export * from "./sqlite-store.js";
14
+ export * from "./server.js";
@@ -0,0 +1,29 @@
1
+ export type LinkSlot = "req" | "resp";
2
+ export type LinkResult = "ok" | "not-found" | "full" | "forbidden" | "exists" | "too-large";
3
+ export interface LinkLimits {
4
+ ttlMs: number;
5
+ reqEntries: number;
6
+ entryBytes: number;
7
+ openPerDevice: number;
8
+ openPerIp: number;
9
+ maxOpen: number;
10
+ totalBytes: number;
11
+ }
12
+ export declare const LID_RE: RegExp;
13
+ export declare class LinkMailboxes {
14
+ private readonly limits;
15
+ private readonly now;
16
+ private readonly boxes;
17
+ private reserved;
18
+ /** Bytes reserved per open mailbox. */
19
+ private readonly perBox;
20
+ constructor(limits: LinkLimits, now: () => number);
21
+ private live;
22
+ open(lid: string, conn: number, did: string, ip: string): LinkResult;
23
+ put(lid: string, slot: LinkSlot, data: string, conn: number): LinkResult;
24
+ get(lid: string, slot: LinkSlot): string[] | undefined;
25
+ sweep(): number;
26
+ get size(): number;
27
+ /** Bytes reserved across every open link mailbox. */
28
+ get reservedBytes(): number;
29
+ }
package/dist/links.js ADDED
@@ -0,0 +1,98 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Pre-auth link mailboxes (docs/protocol.md §5.7, used by device linking §2.4).
4
+ //
5
+ // Opened by an authenticated device, keyed by `lid`, alive 10 minutes. One
6
+ // `req` slot (up to 4 entries) and one `resp` slot (1 entry). `req` puts and
7
+ // all gets are unauthenticated (the relay rate-limits them per IP); a `resp`
8
+ // put is accepted only on the connection that opened the mailbox.
9
+ //
10
+ // Held in memory: a link lives minutes, and a relay restart simply means the
11
+ // user starts the link again. Memory is bounded three ways: open mailboxes per
12
+ // device and per source IP, a global count, and a global byte budget. The
13
+ // budget is RESERVED at open (a mailbox's maximum: every req entry plus the
14
+ // resp entry), so a full budget refuses new opens, which are authenticated
15
+ // and rate-limited, and never refuses puts into a mailbox already open.
16
+ export const LID_RE = /^[a-z2-7]{26}$/;
17
+ export class LinkMailboxes {
18
+ limits;
19
+ now;
20
+ boxes = new Map();
21
+ reserved = 0;
22
+ /** Bytes reserved per open mailbox. */
23
+ perBox;
24
+ constructor(limits, now) {
25
+ this.limits = limits;
26
+ this.now = now;
27
+ this.perBox = (limits.reqEntries + 1) * limits.entryBytes;
28
+ }
29
+ live(lid) {
30
+ const b = this.boxes.get(lid);
31
+ if (b && b.expiresAt <= this.now()) {
32
+ this.boxes.delete(lid);
33
+ this.reserved -= this.perBox;
34
+ return undefined;
35
+ }
36
+ return b;
37
+ }
38
+ open(lid, conn, did, ip) {
39
+ if (this.live(lid))
40
+ return "exists";
41
+ this.sweep();
42
+ let mine = 0;
43
+ let fromIp = 0;
44
+ for (const b of this.boxes.values()) {
45
+ if (b.ownerDid === did)
46
+ mine++;
47
+ if (b.ownerIp === ip)
48
+ fromIp++;
49
+ }
50
+ if (mine >= this.limits.openPerDevice ||
51
+ fromIp >= this.limits.openPerIp ||
52
+ this.boxes.size >= this.limits.maxOpen ||
53
+ this.reserved + this.perBox > this.limits.totalBytes) {
54
+ return "full";
55
+ }
56
+ this.boxes.set(lid, { ownerConn: conn, ownerDid: did, ownerIp: ip, expiresAt: this.now() + this.limits.ttlMs, req: [], resp: [] });
57
+ this.reserved += this.perBox;
58
+ return "ok";
59
+ }
60
+ put(lid, slot, data, conn) {
61
+ const size = Buffer.byteLength(data, "utf8");
62
+ if (size > this.limits.entryBytes)
63
+ return "too-large";
64
+ const b = this.live(lid);
65
+ if (!b)
66
+ return "not-found";
67
+ if (slot === "resp") {
68
+ if (conn !== b.ownerConn)
69
+ return "forbidden";
70
+ if (b.resp.length >= 1)
71
+ return "full";
72
+ }
73
+ else if (b.req.length >= this.limits.reqEntries) {
74
+ return "full";
75
+ }
76
+ // Fits: the open reserved room for every entry this mailbox can hold.
77
+ b[slot].push(data);
78
+ return "ok";
79
+ }
80
+ get(lid, slot) {
81
+ const b = this.live(lid);
82
+ return b ? [...b[slot]] : undefined;
83
+ }
84
+ sweep() {
85
+ let n = 0;
86
+ for (const lid of [...this.boxes.keys()])
87
+ if (!this.live(lid))
88
+ n++;
89
+ return n;
90
+ }
91
+ get size() {
92
+ return this.boxes.size;
93
+ }
94
+ /** Bytes reserved across every open link mailbox. */
95
+ get reservedBytes() {
96
+ return this.reserved;
97
+ }
98
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { LogLevel } from "./config.js";
2
+ export type LogFields = Record<string, string | number | boolean | undefined>;
3
+ export interface Logger {
4
+ debug(msg: string, fields?: LogFields): void;
5
+ info(msg: string, fields?: LogFields): void;
6
+ warn(msg: string, fields?: LogFields): void;
7
+ error(msg: string, fields?: LogFields): void;
8
+ /** True when debug lines are emitted, so callers can skip computing them. */
9
+ readonly debugEnabled: boolean;
10
+ }
11
+ export interface LoggerOptions {
12
+ level?: LogLevel;
13
+ /** Receives each line (without the newline). Default: stdout. */
14
+ sink?: (line: string) => void;
15
+ now?: () => number;
16
+ }
17
+ export declare function createLogger(opts?: LoggerOptions): Logger;
18
+ /** A 12-character salted hash of an identifier, for debug-level correlation only. */
19
+ export declare function redact(id: string): string;
package/dist/log.js ADDED
@@ -0,0 +1,35 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Structured JSON logs, one object per line.
4
+ //
5
+ // Privacy rule: the relay never logs envelope contents, capabilities,
6
+ // certificates, link data or raw IP addresses. Identifiers (userIds, dids,
7
+ // IPs) appear only at debug level, and only through redact(), which keeps a
8
+ // short salted hash: enough to correlate lines, not to recover the id.
9
+ import { b64uEncode, randomBytes, sha256 } from "@peer2peer/core";
10
+ const ORDER = { debug: 10, info: 20, warn: 30, error: 40 };
11
+ export function createLogger(opts = {}) {
12
+ const min = ORDER[opts.level ?? "info"];
13
+ const sink = opts.sink ?? ((line) => process.stdout.write(`${line}\n`));
14
+ const now = opts.now ?? Date.now;
15
+ const emit = (level) => (msg, fields) => {
16
+ if (ORDER[level] < min)
17
+ return;
18
+ sink(JSON.stringify({ ts: new Date(now()).toISOString(), level, msg, ...fields }));
19
+ };
20
+ return {
21
+ debug: emit("debug"),
22
+ info: emit("info"),
23
+ warn: emit("warn"),
24
+ error: emit("error"),
25
+ debugEnabled: min <= ORDER.debug,
26
+ };
27
+ }
28
+ // A per-process salt, so a redacted id in one relay's logs can't be matched
29
+ // against another relay's logs or a precomputed table of userIds.
30
+ const SALT = b64uEncode(randomBytes(16));
31
+ const enc = new TextEncoder();
32
+ /** A 12-character salted hash of an identifier, for debug-level correlation only. */
33
+ export function redact(id) {
34
+ return `h:${b64uEncode(sha256(enc.encode(`${SALT}|${id}`))).slice(0, 12)}`;
35
+ }