@narumitw/pi-chat 0.1.6 → 0.1.7

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.
Files changed (49) hide show
  1. package/README.md +17 -34
  2. package/dist/chunks/{chat-view-EZ24L3LM.js → chat-view-7OBZGYZM.ts} +2 -2
  3. package/dist/chunks/chat-view-7OBZGYZM.ts.map +7 -0
  4. package/dist/chunks/{chunk-ZR2JESR5.js → chunk-7FD7DDSU.ts} +6 -36
  5. package/dist/chunks/chunk-7FD7DDSU.ts.map +7 -0
  6. package/dist/chunks/{chunk-XYZZR6DW.js → chunk-EOZIFFAD.ts} +6 -23
  7. package/dist/chunks/chunk-EOZIFFAD.ts.map +7 -0
  8. package/dist/chunks/{chunk-UE3UAOJX.js → chunk-LN3NAZRC.ts} +1 -1
  9. package/dist/chunks/{chunk-UE3UAOJX.js.map → chunk-LN3NAZRC.ts.map} +1 -1
  10. package/dist/chunks/{chunk-OQLAKS7O.js → chunk-MHSYNYS3.ts} +4 -7
  11. package/dist/chunks/chunk-MHSYNYS3.ts.map +7 -0
  12. package/dist/chunks/{chunk-UQPD3L6X.js → chunk-WUCSLYAK.ts} +1 -1
  13. package/dist/chunks/chunk-WUCSLYAK.ts.map +7 -0
  14. package/dist/chunks/{directory-network-EWFZFLGK.js → directory-network-6OPGA4EH.ts} +7 -19
  15. package/dist/chunks/directory-network-6OPGA4EH.ts.map +7 -0
  16. package/dist/chunks/{menu-2KEDM6NJ.js → menu-S7MZCVYM.ts} +5 -5
  17. package/dist/chunks/menu-S7MZCVYM.ts.map +7 -0
  18. package/dist/chunks/{network-MXCIGGQ2.js → network-Y4Z4JJ5J.ts} +3 -3
  19. package/dist/chunks/network-Y4Z4JJ5J.ts.map +7 -0
  20. package/dist/chunks/{widget-4OBABJDY.js → widget-QT53EBN6.ts} +4 -10
  21. package/dist/chunks/widget-QT53EBN6.ts.map +7 -0
  22. package/dist/index.ts +20 -66
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +54 -55
  25. package/src/chat-session.ts +571 -594
  26. package/src/chat-view.ts +221 -226
  27. package/src/directory-network.ts +347 -365
  28. package/src/external.d.ts +56 -66
  29. package/src/identity.ts +74 -88
  30. package/src/menu.ts +535 -541
  31. package/src/network-contract.ts +5 -5
  32. package/src/network.ts +154 -157
  33. package/src/nickname.ts +6 -6
  34. package/src/pi-chat.ts +700 -774
  35. package/src/protocol.ts +296 -335
  36. package/src/public-room-directory.ts +276 -310
  37. package/src/room.ts +54 -58
  38. package/src/settings.ts +234 -259
  39. package/src/text.ts +57 -57
  40. package/src/widget.ts +56 -72
  41. package/dist/chunks/chat-view-EZ24L3LM.js.map +0 -7
  42. package/dist/chunks/chunk-OQLAKS7O.js.map +0 -7
  43. package/dist/chunks/chunk-UQPD3L6X.js.map +0 -7
  44. package/dist/chunks/chunk-XYZZR6DW.js.map +0 -7
  45. package/dist/chunks/chunk-ZR2JESR5.js.map +0 -7
  46. package/dist/chunks/directory-network-EWFZFLGK.js.map +0 -7
  47. package/dist/chunks/menu-2KEDM6NJ.js.map +0 -7
  48. package/dist/chunks/network-MXCIGGQ2.js.map +0 -7
  49. package/dist/chunks/widget-4OBABJDY.js.map +0 -7
@@ -2,19 +2,19 @@ import { randomBytes, randomUUID } from "node:crypto";
2
2
  import type { ChatIdentity } from "./identity.js";
3
3
  import { formatIdentityLabel, normalizeNickname, uniqueIdentityTags } from "./identity.js";
4
4
  import {
5
- createChatEvent,
6
- createGossipMessage,
7
- createHello,
8
- createPresenceEvent,
9
- type GossipMessage,
10
- MAX_EVENT_AGE_MS,
11
- PeerRateLimiter,
12
- type PresenceEvent,
13
- type ProtocolMessage,
14
- type RoomDescriptor,
15
- type RoomEvent,
16
- verifyHello,
17
- verifyRoomEvent,
5
+ createChatEvent,
6
+ createGossipMessage,
7
+ createHello,
8
+ createPresenceEvent,
9
+ type GossipMessage,
10
+ MAX_EVENT_AGE_MS,
11
+ PeerRateLimiter,
12
+ type PresenceEvent,
13
+ type ProtocolMessage,
14
+ type RoomDescriptor,
15
+ type RoomEvent,
16
+ verifyHello,
17
+ verifyRoomEvent,
18
18
  } from "./protocol.js";
19
19
 
20
20
  const MAX_TRANSCRIPT = 256;
@@ -27,631 +27,608 @@ const PRESENCE_HEARTBEAT_MS = 30_000;
27
27
  const MAX_ORIGIN_LIMITERS = 512;
28
28
 
29
29
  export interface TransportPeer {
30
- publicKey: Buffer;
31
- send(message: ProtocolMessage): void;
32
- close(): void;
30
+ publicKey: Buffer;
31
+ send(message: ProtocolMessage): void;
32
+ close(): void;
33
33
  }
34
34
 
35
35
  export interface ChatTransportListener {
36
- onPeer(peer: TransportPeer): void;
37
- onMessage(peer: TransportPeer, message: ProtocolMessage): void;
38
- onDisconnect(peer: TransportPeer): void;
39
- onError(error: Error): void;
36
+ onPeer(peer: TransportPeer): void;
37
+ onMessage(peer: TransportPeer, message: ProtocolMessage): void;
38
+ onDisconnect(peer: TransportPeer): void;
39
+ onError(error: Error): void;
40
40
  }
41
41
 
42
42
  export interface ChatTransport {
43
- start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void>;
44
- stop(): Promise<void>;
43
+ start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void>;
44
+ stop(): Promise<void>;
45
45
  }
46
46
 
47
47
  export interface TranscriptEntry {
48
- id: string;
49
- author: "local" | "remote";
50
- label: string;
51
- publicKey: string;
52
- text: string;
53
- sentAt: number;
54
- delivery?: "relayed" | "not-relayed";
55
- relayedTo?: number;
48
+ id: string;
49
+ author: "local" | "remote";
50
+ label: string;
51
+ publicKey: string;
52
+ text: string;
53
+ sentAt: number;
54
+ delivery?: "relayed" | "not-relayed";
55
+ relayedTo?: number;
56
56
  }
57
57
 
58
58
  export interface ParticipantSnapshot {
59
- publicKey: string;
60
- label: string;
61
- nickname: string;
62
- muted: boolean;
59
+ publicKey: string;
60
+ label: string;
61
+ nickname: string;
62
+ muted: boolean;
63
63
  }
64
64
 
65
65
  export interface ChatSnapshot {
66
- state: "connecting" | "connected" | "degraded" | "disconnected";
67
- room: RoomDescriptor;
68
- localLabel: string;
69
- participants: ParticipantSnapshot[];
70
- directNeighbors: number;
71
- participantCatalogFull: boolean;
72
- transcript: TranscriptEntry[];
73
- unread: number;
74
- composerOpen: boolean;
75
- lastError?: string;
66
+ state: "connecting" | "connected" | "degraded" | "disconnected";
67
+ room: RoomDescriptor;
68
+ localLabel: string;
69
+ participants: ParticipantSnapshot[];
70
+ directNeighbors: number;
71
+ participantCatalogFull: boolean;
72
+ transcript: TranscriptEntry[];
73
+ unread: number;
74
+ composerOpen: boolean;
75
+ lastError?: string;
76
76
  }
77
77
 
78
78
  export interface ChatSessionOptions {
79
- room: RoomDescriptor;
80
- identity: ChatIdentity;
81
- nickname: string;
82
- transport: ChatTransport;
83
- now?: () => number;
84
- onChange?: (snapshot: ChatSnapshot) => void;
79
+ room: RoomDescriptor;
80
+ identity: ChatIdentity;
81
+ nickname: string;
82
+ transport: ChatTransport;
83
+ now?: () => number;
84
+ onChange?: (snapshot: ChatSnapshot) => void;
85
85
  }
86
86
 
87
87
  interface PeerState {
88
- peer: TransportPeer;
89
- authenticated: boolean;
90
- nickname?: string;
91
- violations: number;
92
- limiter: PeerRateLimiter;
88
+ peer: TransportPeer;
89
+ authenticated: boolean;
90
+ nickname?: string;
91
+ violations: number;
92
+ limiter: PeerRateLimiter;
93
93
  }
94
94
 
95
95
  interface ParticipantState {
96
- publicKey: Buffer;
97
- nickname: string;
98
- muted: boolean;
99
- lastSeen: number;
96
+ publicKey: Buffer;
97
+ nickname: string;
98
+ muted: boolean;
99
+ lastSeen: number;
100
100
  }
101
101
 
102
102
  interface OriginLimiterState {
103
- limiter: PeerRateLimiter;
104
- lastSeen: number;
103
+ limiter: PeerRateLimiter;
104
+ lastSeen: number;
105
105
  }
106
106
 
107
107
  interface ParticipantVersionState {
108
- issuedAt: number;
109
- id: string;
108
+ issuedAt: number;
109
+ id: string;
110
110
  }
111
111
 
112
112
  export class ChatSession {
113
- private readonly room: RoomDescriptor;
114
- private readonly identity: ChatIdentity;
115
- private nickname: string;
116
- private readonly transport: ChatTransport;
117
- private readonly now: () => number;
118
- private readonly onChange?: (snapshot: ChatSnapshot) => void;
119
- private readonly peers = new Map<string, PeerState>();
120
- private readonly participants = new Map<string, ParticipantState>();
121
- private readonly mutedOrigins = new Set<string>();
122
- private readonly transcript: TranscriptEntry[] = [];
123
- private readonly seen = new Map<string, number>();
124
- private readonly seenOrder: Array<{ key: string; expiresAt: number }> = [];
125
- private readonly originLimiters = new Map<string, OriginLimiterState>();
126
- private readonly participantVersions = new Map<string, ParticipantVersionState>();
127
- private readonly listeners = new Set<(snapshot: ChatSnapshot) => void>();
128
- private state: ChatSnapshot["state"] = "disconnected";
129
- private unread = 0;
130
- private viewOpen = false;
131
- private lastError: string | undefined;
132
- private generation = 0;
133
- private leavePromise: Promise<void> | undefined;
134
- private heartbeatTimer: NodeJS.Timeout | undefined;
135
- private currentPresence: PresenceEvent | undefined;
136
- private participantCatalogFull = false;
137
-
138
- constructor(options: ChatSessionOptions) {
139
- const nickname = normalizeNickname(options.nickname);
140
- if (!nickname) throw new Error("Pi Chat nickname is invalid.");
141
- this.room = options.room;
142
- this.identity = options.identity;
143
- this.nickname = nickname;
144
- this.transport = options.transport;
145
- this.now = options.now ?? Date.now;
146
- this.onChange = options.onChange;
147
- }
148
-
149
- async start(signal?: AbortSignal): Promise<void> {
150
- if (this.state !== "disconnected" || this.leavePromise) {
151
- throw new Error("Pi Chat session has already started.");
152
- }
153
- const owner = ++this.generation;
154
- this.state = "connecting";
155
- this.emit();
156
- try {
157
- await this.transport.start(
158
- {
159
- onPeer: (peer) => this.onPeer(owner, peer),
160
- onMessage: (peer, message) => this.onMessage(owner, peer, message),
161
- onDisconnect: (peer) => this.onDisconnect(owner, peer),
162
- onError: (error) => this.onError(owner, error),
163
- },
164
- signal,
165
- );
166
- signal?.throwIfAborted();
167
- if (owner !== this.generation) return;
168
- this.state = "connected";
169
- this.startHeartbeat(owner);
170
- this.emit();
171
- } catch (error) {
172
- if (owner === this.generation) {
173
- this.state = "disconnected";
174
- this.lastError = safeError(error);
175
- this.emit();
176
- }
177
- await this.transport.stop().catch(() => undefined);
178
- throw error;
179
- }
180
- }
181
-
182
- send(text: string): { id: string; relayedTo: number } {
183
- if (this.state !== "connected" && this.state !== "degraded") {
184
- throw new Error("Pi Chat is not connected.");
185
- }
186
- const id = randomUUID();
187
- const event = createChatEvent(this.room, this.identity, this.nickname, text, this.now(), id);
188
- this.remember(eventKey(event));
189
- const relayedTo = this.broadcast(createGossipMessage(event));
190
- this.pushTranscript({
191
- id,
192
- author: "local",
193
- label: formatIdentityLabel(this.nickname, this.identity.publicKey),
194
- publicKey: this.identity.publicKey.toString("hex"),
195
- text,
196
- sentAt: event.issuedAt,
197
- delivery: relayedTo > 0 ? "relayed" : "not-relayed",
198
- relayedTo,
199
- });
200
- this.emit();
201
- return { id, relayedTo };
202
- }
203
-
204
- updateNickname(value: string): void {
205
- const nickname = normalizeNickname(value);
206
- if (!nickname) throw new Error("Pi Chat nickname is invalid.");
207
- this.nickname = nickname;
208
- this.publishPresence("online");
209
- this.emit();
210
- }
211
-
212
- mute(publicKey: Uint8Array): void {
213
- const id = keyId(publicKey);
214
- if (!this.participants.has(id)) return;
215
- this.mutedOrigins.add(id);
216
- const participant = this.participants.get(id);
217
- if (participant) participant.muted = true;
218
- this.emit();
219
- }
220
-
221
- toggleMute(publicKey: Uint8Array): boolean | undefined {
222
- const id = keyId(publicKey);
223
- const participant = this.participants.get(id);
224
- if (!participant) return undefined;
225
- if (this.mutedOrigins.has(id)) {
226
- this.mutedOrigins.delete(id);
227
- participant.muted = false;
228
- } else {
229
- this.mutedOrigins.add(id);
230
- participant.muted = true;
231
- }
232
- this.emit();
233
- return participant.muted;
234
- }
235
-
236
- subscribe(listener: (snapshot: ChatSnapshot) => void): () => void {
237
- this.listeners.add(listener);
238
- return () => this.listeners.delete(listener);
239
- }
240
-
241
- setViewOpen(open: boolean): void {
242
- if (this.viewOpen === open) return;
243
- this.viewOpen = open;
244
- if (open) this.unread = 0;
245
- this.emit();
246
- }
247
-
248
- leave(): Promise<void> {
249
- if (this.leavePromise) return this.leavePromise;
250
- this.leavePromise = this.leaveOwned();
251
- return this.leavePromise;
252
- }
253
-
254
- snapshot(): ChatSnapshot {
255
- this.pruneParticipants();
256
- const active = [...this.participants.entries()];
257
- const tags = uniqueIdentityTags([
258
- this.identity.publicKey,
259
- ...active.map(([, value]) => value.publicKey),
260
- ]);
261
- const localKey = this.identity.publicKey.toString("hex");
262
- const participants = active
263
- .map(([publicKey, value]) => ({
264
- publicKey,
265
- nickname: value.nickname,
266
- label: `${value.nickname}~${tags.get(publicKey) ?? formatIdentityLabel(value.nickname, value.publicKey).split("~").at(-1)}`,
267
- muted: value.muted,
268
- }))
269
- .sort((left, right) => left.label.localeCompare(right.label));
270
- return {
271
- state: this.state,
272
- room: this.room,
273
- localLabel: `${this.nickname}~${tags.get(localKey) ?? formatIdentityLabel(this.nickname, this.identity.publicKey).split("~").at(-1)}`,
274
- participants,
275
- directNeighbors: [...this.peers.values()].filter(({ authenticated }) => authenticated).length,
276
- participantCatalogFull: this.participantCatalogFull,
277
- transcript: this.transcript.map((entry) => {
278
- const tag = tags.get(entry.publicKey);
279
- const nickname = entry.label.split("~", 1)[0] ?? entry.label;
280
- return { ...entry, label: tag ? `${nickname}~${tag}` : entry.label };
281
- }),
282
- unread: this.unread,
283
- composerOpen: this.viewOpen,
284
- ...(this.lastError ? { lastError: this.lastError } : {}),
285
- };
286
- }
287
-
288
- private onPeer(owner: number, peer: TransportPeer): void {
289
- if (owner !== this.generation || this.state === "disconnected") {
290
- peer.close();
291
- return;
292
- }
293
- const id = keyId(peer.publicKey);
294
- if (id === this.identity.publicKey.toString("hex")) {
295
- peer.close();
296
- return;
297
- }
298
- const previous = this.peers.get(id);
299
- if (previous && previous.peer !== peer) previous.peer.close();
300
- const state: PeerState = {
301
- peer,
302
- authenticated: false,
303
- nickname: previous?.nickname,
304
- violations: 0,
305
- limiter: new PeerRateLimiter({ burst: 12, refillPerSecond: 4, now: this.now }),
306
- };
307
- this.peers.set(id, state);
308
- try {
309
- peer.send(
310
- createHello(
311
- this.room,
312
- this.nickname,
313
- this.identity.publicKey,
314
- peer.publicKey,
315
- randomBytes(16),
316
- ),
317
- );
318
- } catch {
319
- peer.close();
320
- this.peers.delete(id);
321
- }
322
- }
323
-
324
- private onMessage(owner: number, peer: TransportPeer, message: ProtocolMessage): void {
325
- if (owner !== this.generation) return;
326
- const id = keyId(peer.publicKey);
327
- const state = this.peers.get(id);
328
- if (!state || state.peer !== peer) return;
329
- if (!state.authenticated) {
330
- const hello = verifyHello(message, this.room, peer.publicKey, this.identity.publicKey);
331
- if (!hello) {
332
- this.violate(id, state);
333
- return;
334
- }
335
- state.authenticated = true;
336
- state.nickname = hello.nickname;
337
- this.upsertParticipant(id, peer.publicKey, hello.nickname, this.now());
338
- this.sendPresenceTo(state.peer);
339
- this.emit();
340
- return;
341
- }
342
- if (message.type === "hello") return;
343
- if (message.type === "goodbye") {
344
- this.peers.delete(id);
345
- peer.close();
346
- this.emit();
347
- return;
348
- }
349
- if (message.type !== "gossip") {
350
- this.violate(id, state);
351
- return;
352
- }
353
- this.onGossip(id, state, message);
354
- }
355
-
356
- private onGossip(peerId: string, state: PeerState, message: GossipMessage): void {
357
- const event = message.event;
358
- const key = eventKey(event);
359
- if (event.origin === this.identity.publicKey.toString("hex") || this.hasSeen(key)) return;
360
- if (!state.limiter.accept()) {
361
- this.violate(peerId, state);
362
- return;
363
- }
364
- if (!verifyRoomEvent(event, this.room, this.now())) {
365
- this.violate(peerId, state);
366
- return;
367
- }
368
- if (!this.acceptOrigin(event.origin)) return;
369
- this.remember(key);
370
- if (!this.applyEvent(event)) return;
371
- if (message.hops > 1) {
372
- this.broadcast(createGossipMessage(event, message.hops - 1), state.peer);
373
- }
374
- }
375
-
376
- private applyEvent(event: RoomEvent): boolean {
377
- const publicKey = Buffer.from(event.origin, "hex");
378
- const participantStateIsNew = this.acceptParticipantVersion(event);
379
- if (event.kind === "presence") {
380
- if (!participantStateIsNew) return false;
381
- if (event.status === "leaving") {
382
- this.participants.delete(event.origin);
383
- this.originLimiters.delete(event.origin);
384
- } else {
385
- this.upsertParticipant(event.origin, publicKey, event.nickname, this.now());
386
- }
387
- this.emit();
388
- return true;
389
- }
390
- if (participantStateIsNew) {
391
- this.upsertParticipant(event.origin, publicKey, event.nickname, this.now());
392
- }
393
- if (!this.mutedOrigins.has(event.origin)) {
394
- this.pushTranscript({
395
- id: event.id,
396
- author: "remote",
397
- label: formatIdentityLabel(event.nickname, publicKey),
398
- publicKey: event.origin,
399
- text: event.text,
400
- sentAt: event.issuedAt,
401
- });
402
- if (!this.viewOpen) this.unread += 1;
403
- }
404
- this.emit();
405
- return true;
406
- }
407
-
408
- private acceptParticipantVersion(event: RoomEvent): boolean {
409
- this.pruneParticipantVersions();
410
- const existing = this.participantVersions.get(event.origin);
411
- if (existing && compareEventVersion(existing, event) >= 0) return false;
412
- if (!existing && this.participantVersions.size >= MAX_SEEN_MESSAGES) {
413
- let oldestOrigin: string | undefined;
414
- let oldestVersion: ParticipantVersionState | undefined;
415
- for (const [origin, candidate] of this.participantVersions) {
416
- if (!oldestVersion || compareEventVersion(candidate, oldestVersion) < 0) {
417
- oldestOrigin = origin;
418
- oldestVersion = candidate;
419
- }
420
- }
421
- if (oldestOrigin) this.participantVersions.delete(oldestOrigin);
422
- }
423
- this.participantVersions.set(event.origin, {
424
- issuedAt: event.issuedAt,
425
- id: event.id,
426
- });
427
- return true;
428
- }
429
-
430
- private pruneParticipantVersions(): void {
431
- const oldest = this.now() - MAX_EVENT_AGE_MS;
432
- for (const [origin, version] of this.participantVersions) {
433
- if (version.issuedAt < oldest) this.participantVersions.delete(origin);
434
- }
435
- }
436
-
437
- private onDisconnect(owner: number, peer: TransportPeer): void {
438
- if (owner !== this.generation) return;
439
- const id = keyId(peer.publicKey);
440
- if (this.peers.get(id)?.peer === peer) {
441
- this.peers.delete(id);
442
- this.emit();
443
- }
444
- }
445
-
446
- private onError(owner: number, error: Error): void {
447
- if (owner !== this.generation) return;
448
- this.state = "degraded";
449
- this.lastError = safeError(error);
450
- this.emit();
451
- }
452
-
453
- private startHeartbeat(owner: number): void {
454
- this.heartbeatTimer = setInterval(() => {
455
- if (owner !== this.generation || this.state === "disconnected") return;
456
- this.publishPresence("online");
457
- this.pruneParticipants();
458
- this.emit();
459
- }, PRESENCE_HEARTBEAT_MS);
460
- this.heartbeatTimer.unref();
461
- }
462
-
463
- private publishPresence(status: "online" | "leaving"): void {
464
- const event = this.newPresence(status);
465
- this.broadcast(createGossipMessage(event));
466
- }
467
-
468
- private sendPresenceTo(peer: TransportPeer): void {
469
- const event = this.currentPresence ?? this.newPresence("online");
470
- try {
471
- peer.send(createGossipMessage(event));
472
- } catch {
473
- // The transport will publish disconnect state.
474
- }
475
- }
476
-
477
- private newPresence(status: "online" | "leaving"): PresenceEvent {
478
- const event = createPresenceEvent(
479
- this.room,
480
- this.identity,
481
- this.nickname,
482
- status,
483
- this.now(),
484
- randomUUID(),
485
- );
486
- this.currentPresence = status === "online" ? event : undefined;
487
- this.remember(eventKey(event));
488
- return event;
489
- }
490
-
491
- private broadcast(message: GossipMessage, exclude?: TransportPeer): number {
492
- let relayedTo = 0;
493
- for (const state of this.peers.values()) {
494
- if (!state.authenticated || state.peer === exclude) continue;
495
- try {
496
- state.peer.send(message);
497
- relayedTo += 1;
498
- } catch {
499
- state.violations += 1;
500
- }
501
- }
502
- return relayedTo;
503
- }
504
-
505
- private upsertParticipant(
506
- id: string,
507
- publicKey: Buffer,
508
- nickname: string,
509
- lastSeen: number,
510
- ): void {
511
- const existing = this.participants.get(id);
512
- if (!existing && this.participants.size >= MAX_PARTICIPANTS) {
513
- this.participantCatalogFull = true;
514
- return;
515
- }
516
- this.participants.set(id, {
517
- publicKey: Buffer.from(publicKey),
518
- nickname,
519
- muted: this.mutedOrigins.has(id),
520
- lastSeen,
521
- });
522
- }
523
-
524
- private pruneParticipants(): void {
525
- this.pruneParticipantVersions();
526
- const oldest = this.now() - PARTICIPANT_TTL_MS;
527
- for (const [id, participant] of this.participants) {
528
- if (participant.lastSeen < oldest) {
529
- this.participants.delete(id);
530
- this.originLimiters.delete(id);
531
- }
532
- }
533
- if (this.participants.size < MAX_PARTICIPANTS) this.participantCatalogFull = false;
534
- }
535
-
536
- private acceptOrigin(origin: string): boolean {
537
- const current = this.now();
538
- let state = this.originLimiters.get(origin);
539
- if (!state) {
540
- if (this.originLimiters.size >= MAX_ORIGIN_LIMITERS) {
541
- let oldestKey: string | undefined;
542
- let oldest = Number.POSITIVE_INFINITY;
543
- for (const [key, candidate] of this.originLimiters) {
544
- if (candidate.lastSeen < oldest) {
545
- oldest = candidate.lastSeen;
546
- oldestKey = key;
547
- }
548
- }
549
- if (oldestKey) this.originLimiters.delete(oldestKey);
550
- }
551
- state = {
552
- limiter: new PeerRateLimiter({ burst: 6, refillPerSecond: 1, now: this.now }),
553
- lastSeen: current,
554
- };
555
- this.originLimiters.set(origin, state);
556
- }
557
- state.lastSeen = current;
558
- return state.limiter.accept();
559
- }
560
-
561
- private hasSeen(key: string): boolean {
562
- this.pruneSeen();
563
- return this.seen.has(key);
564
- }
565
-
566
- private remember(key: string): void {
567
- this.pruneSeen();
568
- const expiresAt = this.now() + SEEN_MESSAGE_TTL_MS;
569
- this.seen.set(key, expiresAt);
570
- this.seenOrder.push({ key, expiresAt });
571
- while (this.seen.size > MAX_SEEN_MESSAGES) {
572
- const removed = this.seenOrder.shift();
573
- if (removed && this.seen.get(removed.key) === removed.expiresAt) {
574
- this.seen.delete(removed.key);
575
- }
576
- }
577
- }
578
-
579
- private pruneSeen(): void {
580
- const current = this.now();
581
- while (this.seenOrder[0] && this.seenOrder[0].expiresAt <= current) {
582
- const removed = this.seenOrder.shift();
583
- if (removed && this.seen.get(removed.key) === removed.expiresAt) {
584
- this.seen.delete(removed.key);
585
- }
586
- }
587
- }
588
-
589
- private violate(id: string, state: PeerState): void {
590
- state.violations += 1;
591
- if (state.violations > MAX_PROTOCOL_VIOLATIONS) {
592
- state.peer.close();
593
- this.peers.delete(id);
594
- this.emit();
595
- }
596
- }
597
-
598
- private pushTranscript(entry: TranscriptEntry): void {
599
- this.transcript.push(entry);
600
- if (this.transcript.length > MAX_TRANSCRIPT) this.transcript.shift();
601
- }
602
-
603
- private async leaveOwned(): Promise<void> {
604
- this.generation += 1;
605
- if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
606
- this.heartbeatTimer = undefined;
607
- if (this.state !== "disconnected") this.publishPresence("leaving");
608
- for (const state of this.peers.values()) {
609
- if (state.authenticated) {
610
- try {
611
- state.peer.send({ v: 2, type: "goodbye" });
612
- } catch {
613
- // Best-effort departure notice.
614
- }
615
- }
616
- state.peer.close();
617
- }
618
- this.peers.clear();
619
- this.participants.clear();
620
- this.originLimiters.clear();
621
- this.participantVersions.clear();
622
- this.seen.clear();
623
- this.seenOrder.length = 0;
624
- await this.transport.stop().catch((error) => {
625
- this.lastError = safeError(error);
626
- });
627
- this.state = "disconnected";
628
- this.unread = 0;
629
- this.transcript.length = 0;
630
- this.emit();
631
- }
632
-
633
- private emit(): void {
634
- const snapshot = this.snapshot();
635
- this.onChange?.(snapshot);
636
- for (const listener of this.listeners) listener(snapshot);
637
- }
113
+ private readonly room: RoomDescriptor;
114
+ private readonly identity: ChatIdentity;
115
+ private nickname: string;
116
+ private readonly transport: ChatTransport;
117
+ private readonly now: () => number;
118
+ private readonly onChange?: (snapshot: ChatSnapshot) => void;
119
+ private readonly peers = new Map<string, PeerState>();
120
+ private readonly participants = new Map<string, ParticipantState>();
121
+ private readonly mutedOrigins = new Set<string>();
122
+ private readonly transcript: TranscriptEntry[] = [];
123
+ private readonly seen = new Map<string, number>();
124
+ private readonly seenOrder: Array<{ key: string; expiresAt: number }> = [];
125
+ private readonly originLimiters = new Map<string, OriginLimiterState>();
126
+ private readonly participantVersions = new Map<string, ParticipantVersionState>();
127
+ private readonly listeners = new Set<(snapshot: ChatSnapshot) => void>();
128
+ private state: ChatSnapshot["state"] = "disconnected";
129
+ private unread = 0;
130
+ private viewOpen = false;
131
+ private lastError: string | undefined;
132
+ private generation = 0;
133
+ private leavePromise: Promise<void> | undefined;
134
+ private heartbeatTimer: NodeJS.Timeout | undefined;
135
+ private currentPresence: PresenceEvent | undefined;
136
+ private participantCatalogFull = false;
137
+
138
+ constructor(options: ChatSessionOptions) {
139
+ const nickname = normalizeNickname(options.nickname);
140
+ if (!nickname) throw new Error("Pi Chat nickname is invalid.");
141
+ this.room = options.room;
142
+ this.identity = options.identity;
143
+ this.nickname = nickname;
144
+ this.transport = options.transport;
145
+ this.now = options.now ?? Date.now;
146
+ this.onChange = options.onChange;
147
+ }
148
+
149
+ async start(signal?: AbortSignal): Promise<void> {
150
+ if (this.state !== "disconnected" || this.leavePromise) {
151
+ throw new Error("Pi Chat session has already started.");
152
+ }
153
+ const owner = ++this.generation;
154
+ this.state = "connecting";
155
+ this.emit();
156
+ try {
157
+ await this.transport.start(
158
+ {
159
+ onPeer: (peer) => this.onPeer(owner, peer),
160
+ onMessage: (peer, message) => this.onMessage(owner, peer, message),
161
+ onDisconnect: (peer) => this.onDisconnect(owner, peer),
162
+ onError: (error) => this.onError(owner, error),
163
+ },
164
+ signal,
165
+ );
166
+ signal?.throwIfAborted();
167
+ if (owner !== this.generation) return;
168
+ this.state = "connected";
169
+ this.startHeartbeat(owner);
170
+ this.emit();
171
+ } catch (error) {
172
+ if (owner === this.generation) {
173
+ this.state = "disconnected";
174
+ this.lastError = safeError(error);
175
+ this.emit();
176
+ }
177
+ await this.transport.stop().catch(() => undefined);
178
+ throw error;
179
+ }
180
+ }
181
+
182
+ send(text: string): { id: string; relayedTo: number } {
183
+ if (this.state !== "connected" && this.state !== "degraded") {
184
+ throw new Error("Pi Chat is not connected.");
185
+ }
186
+ const id = randomUUID();
187
+ const event = createChatEvent(this.room, this.identity, this.nickname, text, this.now(), id);
188
+ this.remember(eventKey(event));
189
+ const relayedTo = this.broadcast(createGossipMessage(event));
190
+ this.pushTranscript({
191
+ id,
192
+ author: "local",
193
+ label: formatIdentityLabel(this.nickname, this.identity.publicKey),
194
+ publicKey: this.identity.publicKey.toString("hex"),
195
+ text,
196
+ sentAt: event.issuedAt,
197
+ delivery: relayedTo > 0 ? "relayed" : "not-relayed",
198
+ relayedTo,
199
+ });
200
+ this.emit();
201
+ return { id, relayedTo };
202
+ }
203
+
204
+ updateNickname(value: string): void {
205
+ const nickname = normalizeNickname(value);
206
+ if (!nickname) throw new Error("Pi Chat nickname is invalid.");
207
+ this.nickname = nickname;
208
+ this.publishPresence("online");
209
+ this.emit();
210
+ }
211
+
212
+ mute(publicKey: Uint8Array): void {
213
+ const id = keyId(publicKey);
214
+ if (!this.participants.has(id)) return;
215
+ this.mutedOrigins.add(id);
216
+ const participant = this.participants.get(id);
217
+ if (participant) participant.muted = true;
218
+ this.emit();
219
+ }
220
+
221
+ toggleMute(publicKey: Uint8Array): boolean | undefined {
222
+ const id = keyId(publicKey);
223
+ const participant = this.participants.get(id);
224
+ if (!participant) return undefined;
225
+ if (this.mutedOrigins.has(id)) {
226
+ this.mutedOrigins.delete(id);
227
+ participant.muted = false;
228
+ } else {
229
+ this.mutedOrigins.add(id);
230
+ participant.muted = true;
231
+ }
232
+ this.emit();
233
+ return participant.muted;
234
+ }
235
+
236
+ subscribe(listener: (snapshot: ChatSnapshot) => void): () => void {
237
+ this.listeners.add(listener);
238
+ return () => this.listeners.delete(listener);
239
+ }
240
+
241
+ setViewOpen(open: boolean): void {
242
+ if (this.viewOpen === open) return;
243
+ this.viewOpen = open;
244
+ if (open) this.unread = 0;
245
+ this.emit();
246
+ }
247
+
248
+ leave(): Promise<void> {
249
+ if (this.leavePromise) return this.leavePromise;
250
+ this.leavePromise = this.leaveOwned();
251
+ return this.leavePromise;
252
+ }
253
+
254
+ snapshot(): ChatSnapshot {
255
+ this.pruneParticipants();
256
+ const active = [...this.participants.entries()];
257
+ const tags = uniqueIdentityTags([this.identity.publicKey, ...active.map(([, value]) => value.publicKey)]);
258
+ const localKey = this.identity.publicKey.toString("hex");
259
+ const participants = active
260
+ .map(([publicKey, value]) => ({
261
+ publicKey,
262
+ nickname: value.nickname,
263
+ label: `${value.nickname}~${tags.get(publicKey) ?? formatIdentityLabel(value.nickname, value.publicKey).split("~").at(-1)}`,
264
+ muted: value.muted,
265
+ }))
266
+ .sort((left, right) => left.label.localeCompare(right.label));
267
+ return {
268
+ state: this.state,
269
+ room: this.room,
270
+ localLabel: `${this.nickname}~${tags.get(localKey) ?? formatIdentityLabel(this.nickname, this.identity.publicKey).split("~").at(-1)}`,
271
+ participants,
272
+ directNeighbors: [...this.peers.values()].filter(({ authenticated }) => authenticated).length,
273
+ participantCatalogFull: this.participantCatalogFull,
274
+ transcript: this.transcript.map((entry) => {
275
+ const tag = tags.get(entry.publicKey);
276
+ const nickname = entry.label.split("~", 1)[0] ?? entry.label;
277
+ return { ...entry, label: tag ? `${nickname}~${tag}` : entry.label };
278
+ }),
279
+ unread: this.unread,
280
+ composerOpen: this.viewOpen,
281
+ ...(this.lastError ? { lastError: this.lastError } : {}),
282
+ };
283
+ }
284
+
285
+ private onPeer(owner: number, peer: TransportPeer): void {
286
+ if (owner !== this.generation || this.state === "disconnected") {
287
+ peer.close();
288
+ return;
289
+ }
290
+ const id = keyId(peer.publicKey);
291
+ if (id === this.identity.publicKey.toString("hex")) {
292
+ peer.close();
293
+ return;
294
+ }
295
+ const previous = this.peers.get(id);
296
+ if (previous && previous.peer !== peer) previous.peer.close();
297
+ const state: PeerState = {
298
+ peer,
299
+ authenticated: false,
300
+ nickname: previous?.nickname,
301
+ violations: 0,
302
+ limiter: new PeerRateLimiter({ burst: 12, refillPerSecond: 4, now: this.now }),
303
+ };
304
+ this.peers.set(id, state);
305
+ try {
306
+ peer.send(createHello(this.room, this.nickname, this.identity.publicKey, peer.publicKey, randomBytes(16)));
307
+ } catch {
308
+ peer.close();
309
+ this.peers.delete(id);
310
+ }
311
+ }
312
+
313
+ private onMessage(owner: number, peer: TransportPeer, message: ProtocolMessage): void {
314
+ if (owner !== this.generation) return;
315
+ const id = keyId(peer.publicKey);
316
+ const state = this.peers.get(id);
317
+ if (!state || state.peer !== peer) return;
318
+ if (!state.authenticated) {
319
+ const hello = verifyHello(message, this.room, peer.publicKey, this.identity.publicKey);
320
+ if (!hello) {
321
+ this.violate(id, state);
322
+ return;
323
+ }
324
+ state.authenticated = true;
325
+ state.nickname = hello.nickname;
326
+ this.upsertParticipant(id, peer.publicKey, hello.nickname, this.now());
327
+ this.sendPresenceTo(state.peer);
328
+ this.emit();
329
+ return;
330
+ }
331
+ if (message.type === "hello") return;
332
+ if (message.type === "goodbye") {
333
+ this.peers.delete(id);
334
+ peer.close();
335
+ this.emit();
336
+ return;
337
+ }
338
+ if (message.type !== "gossip") {
339
+ this.violate(id, state);
340
+ return;
341
+ }
342
+ this.onGossip(id, state, message);
343
+ }
344
+
345
+ private onGossip(peerId: string, state: PeerState, message: GossipMessage): void {
346
+ const event = message.event;
347
+ const key = eventKey(event);
348
+ if (event.origin === this.identity.publicKey.toString("hex") || this.hasSeen(key)) return;
349
+ if (!state.limiter.accept()) {
350
+ this.violate(peerId, state);
351
+ return;
352
+ }
353
+ if (!verifyRoomEvent(event, this.room, this.now())) {
354
+ this.violate(peerId, state);
355
+ return;
356
+ }
357
+ if (!this.acceptOrigin(event.origin)) return;
358
+ this.remember(key);
359
+ if (!this.applyEvent(event)) return;
360
+ if (message.hops > 1) {
361
+ this.broadcast(createGossipMessage(event, message.hops - 1), state.peer);
362
+ }
363
+ }
364
+
365
+ private applyEvent(event: RoomEvent): boolean {
366
+ const publicKey = Buffer.from(event.origin, "hex");
367
+ const participantStateIsNew = this.acceptParticipantVersion(event);
368
+ if (event.kind === "presence") {
369
+ if (!participantStateIsNew) return false;
370
+ if (event.status === "leaving") {
371
+ this.participants.delete(event.origin);
372
+ this.originLimiters.delete(event.origin);
373
+ } else {
374
+ this.upsertParticipant(event.origin, publicKey, event.nickname, this.now());
375
+ }
376
+ this.emit();
377
+ return true;
378
+ }
379
+ if (participantStateIsNew) {
380
+ this.upsertParticipant(event.origin, publicKey, event.nickname, this.now());
381
+ }
382
+ if (!this.mutedOrigins.has(event.origin)) {
383
+ this.pushTranscript({
384
+ id: event.id,
385
+ author: "remote",
386
+ label: formatIdentityLabel(event.nickname, publicKey),
387
+ publicKey: event.origin,
388
+ text: event.text,
389
+ sentAt: event.issuedAt,
390
+ });
391
+ if (!this.viewOpen) this.unread += 1;
392
+ }
393
+ this.emit();
394
+ return true;
395
+ }
396
+
397
+ private acceptParticipantVersion(event: RoomEvent): boolean {
398
+ this.pruneParticipantVersions();
399
+ const existing = this.participantVersions.get(event.origin);
400
+ if (existing && compareEventVersion(existing, event) >= 0) return false;
401
+ if (!existing && this.participantVersions.size >= MAX_SEEN_MESSAGES) {
402
+ let oldestOrigin: string | undefined;
403
+ let oldestVersion: ParticipantVersionState | undefined;
404
+ for (const [origin, candidate] of this.participantVersions) {
405
+ if (!oldestVersion || compareEventVersion(candidate, oldestVersion) < 0) {
406
+ oldestOrigin = origin;
407
+ oldestVersion = candidate;
408
+ }
409
+ }
410
+ if (oldestOrigin) this.participantVersions.delete(oldestOrigin);
411
+ }
412
+ this.participantVersions.set(event.origin, {
413
+ issuedAt: event.issuedAt,
414
+ id: event.id,
415
+ });
416
+ return true;
417
+ }
418
+
419
+ private pruneParticipantVersions(): void {
420
+ const oldest = this.now() - MAX_EVENT_AGE_MS;
421
+ for (const [origin, version] of this.participantVersions) {
422
+ if (version.issuedAt < oldest) this.participantVersions.delete(origin);
423
+ }
424
+ }
425
+
426
+ private onDisconnect(owner: number, peer: TransportPeer): void {
427
+ if (owner !== this.generation) return;
428
+ const id = keyId(peer.publicKey);
429
+ if (this.peers.get(id)?.peer === peer) {
430
+ this.peers.delete(id);
431
+ this.emit();
432
+ }
433
+ }
434
+
435
+ private onError(owner: number, error: Error): void {
436
+ if (owner !== this.generation) return;
437
+ this.state = "degraded";
438
+ this.lastError = safeError(error);
439
+ this.emit();
440
+ }
441
+
442
+ private startHeartbeat(owner: number): void {
443
+ this.heartbeatTimer = setInterval(() => {
444
+ if (owner !== this.generation || this.state === "disconnected") return;
445
+ this.publishPresence("online");
446
+ this.pruneParticipants();
447
+ this.emit();
448
+ }, PRESENCE_HEARTBEAT_MS);
449
+ this.heartbeatTimer.unref();
450
+ }
451
+
452
+ private publishPresence(status: "online" | "leaving"): void {
453
+ const event = this.newPresence(status);
454
+ this.broadcast(createGossipMessage(event));
455
+ }
456
+
457
+ private sendPresenceTo(peer: TransportPeer): void {
458
+ const event = this.currentPresence ?? this.newPresence("online");
459
+ try {
460
+ peer.send(createGossipMessage(event));
461
+ } catch {
462
+ // The transport will publish disconnect state.
463
+ }
464
+ }
465
+
466
+ private newPresence(status: "online" | "leaving"): PresenceEvent {
467
+ const event = createPresenceEvent(this.room, this.identity, this.nickname, status, this.now(), randomUUID());
468
+ this.currentPresence = status === "online" ? event : undefined;
469
+ this.remember(eventKey(event));
470
+ return event;
471
+ }
472
+
473
+ private broadcast(message: GossipMessage, exclude?: TransportPeer): number {
474
+ let relayedTo = 0;
475
+ for (const state of this.peers.values()) {
476
+ if (!state.authenticated || state.peer === exclude) continue;
477
+ try {
478
+ state.peer.send(message);
479
+ relayedTo += 1;
480
+ } catch {
481
+ state.violations += 1;
482
+ }
483
+ }
484
+ return relayedTo;
485
+ }
486
+
487
+ private upsertParticipant(id: string, publicKey: Buffer, nickname: string, lastSeen: number): void {
488
+ const existing = this.participants.get(id);
489
+ if (!existing && this.participants.size >= MAX_PARTICIPANTS) {
490
+ this.participantCatalogFull = true;
491
+ return;
492
+ }
493
+ this.participants.set(id, {
494
+ publicKey: Buffer.from(publicKey),
495
+ nickname,
496
+ muted: this.mutedOrigins.has(id),
497
+ lastSeen,
498
+ });
499
+ }
500
+
501
+ private pruneParticipants(): void {
502
+ this.pruneParticipantVersions();
503
+ const oldest = this.now() - PARTICIPANT_TTL_MS;
504
+ for (const [id, participant] of this.participants) {
505
+ if (participant.lastSeen < oldest) {
506
+ this.participants.delete(id);
507
+ this.originLimiters.delete(id);
508
+ }
509
+ }
510
+ if (this.participants.size < MAX_PARTICIPANTS) this.participantCatalogFull = false;
511
+ }
512
+
513
+ private acceptOrigin(origin: string): boolean {
514
+ const current = this.now();
515
+ let state = this.originLimiters.get(origin);
516
+ if (!state) {
517
+ if (this.originLimiters.size >= MAX_ORIGIN_LIMITERS) {
518
+ let oldestKey: string | undefined;
519
+ let oldest = Number.POSITIVE_INFINITY;
520
+ for (const [key, candidate] of this.originLimiters) {
521
+ if (candidate.lastSeen < oldest) {
522
+ oldest = candidate.lastSeen;
523
+ oldestKey = key;
524
+ }
525
+ }
526
+ if (oldestKey) this.originLimiters.delete(oldestKey);
527
+ }
528
+ state = {
529
+ limiter: new PeerRateLimiter({ burst: 6, refillPerSecond: 1, now: this.now }),
530
+ lastSeen: current,
531
+ };
532
+ this.originLimiters.set(origin, state);
533
+ }
534
+ state.lastSeen = current;
535
+ return state.limiter.accept();
536
+ }
537
+
538
+ private hasSeen(key: string): boolean {
539
+ this.pruneSeen();
540
+ return this.seen.has(key);
541
+ }
542
+
543
+ private remember(key: string): void {
544
+ this.pruneSeen();
545
+ const expiresAt = this.now() + SEEN_MESSAGE_TTL_MS;
546
+ this.seen.set(key, expiresAt);
547
+ this.seenOrder.push({ key, expiresAt });
548
+ while (this.seen.size > MAX_SEEN_MESSAGES) {
549
+ const removed = this.seenOrder.shift();
550
+ if (removed && this.seen.get(removed.key) === removed.expiresAt) {
551
+ this.seen.delete(removed.key);
552
+ }
553
+ }
554
+ }
555
+
556
+ private pruneSeen(): void {
557
+ const current = this.now();
558
+ while (this.seenOrder[0] && this.seenOrder[0].expiresAt <= current) {
559
+ const removed = this.seenOrder.shift();
560
+ if (removed && this.seen.get(removed.key) === removed.expiresAt) {
561
+ this.seen.delete(removed.key);
562
+ }
563
+ }
564
+ }
565
+
566
+ private violate(id: string, state: PeerState): void {
567
+ state.violations += 1;
568
+ if (state.violations > MAX_PROTOCOL_VIOLATIONS) {
569
+ state.peer.close();
570
+ this.peers.delete(id);
571
+ this.emit();
572
+ }
573
+ }
574
+
575
+ private pushTranscript(entry: TranscriptEntry): void {
576
+ this.transcript.push(entry);
577
+ if (this.transcript.length > MAX_TRANSCRIPT) this.transcript.shift();
578
+ }
579
+
580
+ private async leaveOwned(): Promise<void> {
581
+ this.generation += 1;
582
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
583
+ this.heartbeatTimer = undefined;
584
+ if (this.state !== "disconnected") this.publishPresence("leaving");
585
+ for (const state of this.peers.values()) {
586
+ if (state.authenticated) {
587
+ try {
588
+ state.peer.send({ v: 2, type: "goodbye" });
589
+ } catch {
590
+ // Best-effort departure notice.
591
+ }
592
+ }
593
+ state.peer.close();
594
+ }
595
+ this.peers.clear();
596
+ this.participants.clear();
597
+ this.originLimiters.clear();
598
+ this.participantVersions.clear();
599
+ this.seen.clear();
600
+ this.seenOrder.length = 0;
601
+ await this.transport.stop().catch((error) => {
602
+ this.lastError = safeError(error);
603
+ });
604
+ this.state = "disconnected";
605
+ this.unread = 0;
606
+ this.transcript.length = 0;
607
+ this.emit();
608
+ }
609
+
610
+ private emit(): void {
611
+ const snapshot = this.snapshot();
612
+ this.onChange?.(snapshot);
613
+ for (const listener of this.listeners) listener(snapshot);
614
+ }
638
615
  }
639
616
 
640
617
  function eventKey(event: RoomEvent): string {
641
- return `${event.origin}:${event.id}`;
618
+ return `${event.origin}:${event.id}`;
642
619
  }
643
620
 
644
621
  function compareEventVersion(
645
- left: Pick<RoomEvent, "issuedAt" | "id">,
646
- right: Pick<RoomEvent, "issuedAt" | "id">,
622
+ left: Pick<RoomEvent, "issuedAt" | "id">,
623
+ right: Pick<RoomEvent, "issuedAt" | "id">,
647
624
  ): number {
648
- return left.issuedAt - right.issuedAt || left.id.localeCompare(right.id);
625
+ return left.issuedAt - right.issuedAt || left.id.localeCompare(right.id);
649
626
  }
650
627
 
651
628
  function keyId(publicKey: Uint8Array): string {
652
- return Buffer.from(publicKey).toString("hex");
629
+ return Buffer.from(publicKey).toString("hex");
653
630
  }
654
631
 
655
632
  function safeError(error: unknown): string {
656
- return error instanceof Error ? error.message : String(error);
633
+ return error instanceof Error ? error.message : String(error);
657
634
  }