@narumitw/pi-chat 0.0.0 → 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.
- package/README.md +67 -35
- package/package.json +3 -2
- package/src/chat-session.ts +325 -104
- package/src/chat-view.ts +14 -14
- package/src/directory-network.ts +416 -0
- package/src/external.d.ts +14 -0
- package/src/identity.ts +62 -14
- package/src/menu.ts +120 -30
- package/src/network-contract.ts +12 -0
- package/src/network.ts +18 -30
- package/src/nickname.ts +11 -0
- package/src/pi-chat.ts +209 -20
- package/src/protocol.ts +229 -124
- package/src/public-room-directory.ts +386 -0
- package/src/room.ts +88 -0
- package/src/settings.ts +22 -10
- package/src/widget.ts +7 -8
package/src/chat-session.ts
CHANGED
|
@@ -2,17 +2,29 @@ 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
|
-
|
|
5
|
+
createChatEvent,
|
|
6
|
+
createGossipMessage,
|
|
6
7
|
createHello,
|
|
8
|
+
createPresenceEvent,
|
|
9
|
+
type GossipMessage,
|
|
10
|
+
MAX_EVENT_AGE_MS,
|
|
7
11
|
PeerRateLimiter,
|
|
12
|
+
type PresenceEvent,
|
|
8
13
|
type ProtocolMessage,
|
|
9
14
|
type RoomDescriptor,
|
|
15
|
+
type RoomEvent,
|
|
10
16
|
verifyHello,
|
|
17
|
+
verifyRoomEvent,
|
|
11
18
|
} from "./protocol.js";
|
|
12
19
|
|
|
13
20
|
const MAX_TRANSCRIPT = 256;
|
|
14
|
-
const MAX_SEEN_MESSAGES =
|
|
21
|
+
const MAX_SEEN_MESSAGES = 8_192;
|
|
22
|
+
const SEEN_MESSAGE_TTL_MS = 10 * 60_000;
|
|
15
23
|
const MAX_PROTOCOL_VIOLATIONS = 3;
|
|
24
|
+
const MAX_PARTICIPANTS = 256;
|
|
25
|
+
const PARTICIPANT_TTL_MS = 90_000;
|
|
26
|
+
const PRESENCE_HEARTBEAT_MS = 30_000;
|
|
27
|
+
const MAX_ORIGIN_LIMITERS = 512;
|
|
16
28
|
|
|
17
29
|
export interface TransportPeer {
|
|
18
30
|
publicKey: Buffer;
|
|
@@ -29,7 +41,6 @@ export interface ChatTransportListener {
|
|
|
29
41
|
|
|
30
42
|
export interface ChatTransport {
|
|
31
43
|
start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void>;
|
|
32
|
-
connectPeer?(publicKey: Buffer): void;
|
|
33
44
|
stop(): Promise<void>;
|
|
34
45
|
}
|
|
35
46
|
|
|
@@ -40,8 +51,8 @@ export interface TranscriptEntry {
|
|
|
40
51
|
publicKey: string;
|
|
41
52
|
text: string;
|
|
42
53
|
sentAt: number;
|
|
43
|
-
delivery?: "
|
|
44
|
-
|
|
54
|
+
delivery?: "relayed" | "not-relayed";
|
|
55
|
+
relayedTo?: number;
|
|
45
56
|
}
|
|
46
57
|
|
|
47
58
|
export interface ParticipantSnapshot {
|
|
@@ -55,7 +66,9 @@ export interface ChatSnapshot {
|
|
|
55
66
|
state: "connecting" | "connected" | "degraded" | "disconnected";
|
|
56
67
|
room: RoomDescriptor;
|
|
57
68
|
localLabel: string;
|
|
58
|
-
|
|
69
|
+
participants: ParticipantSnapshot[];
|
|
70
|
+
directNeighbors: number;
|
|
71
|
+
participantCatalogFull: boolean;
|
|
59
72
|
transcript: TranscriptEntry[];
|
|
60
73
|
unread: number;
|
|
61
74
|
composerOpen: boolean;
|
|
@@ -75,11 +88,27 @@ interface PeerState {
|
|
|
75
88
|
peer: TransportPeer;
|
|
76
89
|
authenticated: boolean;
|
|
77
90
|
nickname?: string;
|
|
78
|
-
muted: boolean;
|
|
79
91
|
violations: number;
|
|
80
92
|
limiter: PeerRateLimiter;
|
|
81
93
|
}
|
|
82
94
|
|
|
95
|
+
interface ParticipantState {
|
|
96
|
+
publicKey: Buffer;
|
|
97
|
+
nickname: string;
|
|
98
|
+
muted: boolean;
|
|
99
|
+
lastSeen: number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface OriginLimiterState {
|
|
103
|
+
limiter: PeerRateLimiter;
|
|
104
|
+
lastSeen: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
interface ParticipantVersionState {
|
|
108
|
+
issuedAt: number;
|
|
109
|
+
id: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
83
112
|
export class ChatSession {
|
|
84
113
|
private readonly room: RoomDescriptor;
|
|
85
114
|
private readonly identity: ChatIdentity;
|
|
@@ -88,9 +117,13 @@ export class ChatSession {
|
|
|
88
117
|
private readonly now: () => number;
|
|
89
118
|
private readonly onChange?: (snapshot: ChatSnapshot) => void;
|
|
90
119
|
private readonly peers = new Map<string, PeerState>();
|
|
120
|
+
private readonly participants = new Map<string, ParticipantState>();
|
|
121
|
+
private readonly mutedOrigins = new Set<string>();
|
|
91
122
|
private readonly transcript: TranscriptEntry[] = [];
|
|
92
|
-
private readonly seen = new
|
|
93
|
-
private readonly seenOrder: string
|
|
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>();
|
|
94
127
|
private readonly listeners = new Set<(snapshot: ChatSnapshot) => void>();
|
|
95
128
|
private state: ChatSnapshot["state"] = "disconnected";
|
|
96
129
|
private unread = 0;
|
|
@@ -98,6 +131,9 @@ export class ChatSession {
|
|
|
98
131
|
private lastError: string | undefined;
|
|
99
132
|
private generation = 0;
|
|
100
133
|
private leavePromise: Promise<void> | undefined;
|
|
134
|
+
private heartbeatTimer: NodeJS.Timeout | undefined;
|
|
135
|
+
private currentPresence: PresenceEvent | undefined;
|
|
136
|
+
private participantCatalogFull = false;
|
|
101
137
|
|
|
102
138
|
constructor(options: ChatSessionOptions) {
|
|
103
139
|
const nickname = normalizeNickname(options.nickname);
|
|
@@ -130,6 +166,7 @@ export class ChatSession {
|
|
|
130
166
|
signal?.throwIfAborted();
|
|
131
167
|
if (owner !== this.generation) return;
|
|
132
168
|
this.state = "connected";
|
|
169
|
+
this.startHeartbeat(owner);
|
|
133
170
|
this.emit();
|
|
134
171
|
} catch (error) {
|
|
135
172
|
if (owner === this.generation) {
|
|
@@ -142,64 +179,58 @@ export class ChatSession {
|
|
|
142
179
|
}
|
|
143
180
|
}
|
|
144
181
|
|
|
145
|
-
send(text: string): { id: string;
|
|
182
|
+
send(text: string): { id: string; relayedTo: number } {
|
|
146
183
|
if (this.state !== "connected" && this.state !== "degraded") {
|
|
147
184
|
throw new Error("Pi Chat is not connected.");
|
|
148
185
|
}
|
|
149
186
|
const id = randomUUID();
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if (!state.authenticated || state.muted) continue;
|
|
154
|
-
try {
|
|
155
|
-
state.peer.send(message);
|
|
156
|
-
deliveredTo += 1;
|
|
157
|
-
} catch {
|
|
158
|
-
state.violations += 1;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
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));
|
|
161
190
|
this.pushTranscript({
|
|
162
191
|
id,
|
|
163
192
|
author: "local",
|
|
164
193
|
label: formatIdentityLabel(this.nickname, this.identity.publicKey),
|
|
165
194
|
publicKey: this.identity.publicKey.toString("hex"),
|
|
166
195
|
text,
|
|
167
|
-
sentAt:
|
|
168
|
-
delivery:
|
|
169
|
-
|
|
196
|
+
sentAt: event.issuedAt,
|
|
197
|
+
delivery: relayedTo > 0 ? "relayed" : "not-relayed",
|
|
198
|
+
relayedTo,
|
|
170
199
|
});
|
|
171
200
|
this.emit();
|
|
172
|
-
return { id,
|
|
201
|
+
return { id, relayedTo };
|
|
173
202
|
}
|
|
174
203
|
|
|
175
204
|
updateNickname(value: string): void {
|
|
176
205
|
const nickname = normalizeNickname(value);
|
|
177
206
|
if (!nickname) throw new Error("Pi Chat nickname is invalid.");
|
|
178
207
|
this.nickname = nickname;
|
|
179
|
-
|
|
180
|
-
if (!state.authenticated) continue;
|
|
181
|
-
try {
|
|
182
|
-
state.peer.send({ v: 1, type: "nickname-update", nickname });
|
|
183
|
-
} catch {
|
|
184
|
-
state.violations += 1;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
208
|
+
this.publishPresence("online");
|
|
187
209
|
this.emit();
|
|
188
210
|
}
|
|
189
211
|
|
|
190
212
|
mute(publicKey: Uint8Array): void {
|
|
191
|
-
const
|
|
192
|
-
if (!
|
|
193
|
-
|
|
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;
|
|
194
218
|
this.emit();
|
|
195
219
|
}
|
|
196
220
|
|
|
197
221
|
toggleMute(publicKey: Uint8Array): boolean | undefined {
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
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
|
+
}
|
|
201
232
|
this.emit();
|
|
202
|
-
return
|
|
233
|
+
return participant.muted;
|
|
203
234
|
}
|
|
204
235
|
|
|
205
236
|
subscribe(listener: (snapshot: ChatSnapshot) => void): () => void {
|
|
@@ -221,22 +252,18 @@ export class ChatSession {
|
|
|
221
252
|
}
|
|
222
253
|
|
|
223
254
|
snapshot(): ChatSnapshot {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
if (value.authenticated && value.nickname) {
|
|
227
|
-
authenticated.push([publicKey, value, value.nickname]);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
255
|
+
this.pruneParticipants();
|
|
256
|
+
const active = [...this.participants.entries()];
|
|
230
257
|
const tags = uniqueIdentityTags([
|
|
231
258
|
this.identity.publicKey,
|
|
232
|
-
...
|
|
259
|
+
...active.map(([, value]) => value.publicKey),
|
|
233
260
|
]);
|
|
234
261
|
const localKey = this.identity.publicKey.toString("hex");
|
|
235
|
-
const
|
|
236
|
-
.map(([publicKey, value
|
|
262
|
+
const participants = active
|
|
263
|
+
.map(([publicKey, value]) => ({
|
|
237
264
|
publicKey,
|
|
238
|
-
nickname,
|
|
239
|
-
label: `${nickname}~${tags.get(publicKey) ?? formatIdentityLabel(nickname, value.
|
|
265
|
+
nickname: value.nickname,
|
|
266
|
+
label: `${value.nickname}~${tags.get(publicKey) ?? formatIdentityLabel(value.nickname, value.publicKey).split("~").at(-1)}`,
|
|
240
267
|
muted: value.muted,
|
|
241
268
|
}))
|
|
242
269
|
.sort((left, right) => left.label.localeCompare(right.label));
|
|
@@ -244,7 +271,9 @@ export class ChatSession {
|
|
|
244
271
|
state: this.state,
|
|
245
272
|
room: this.room,
|
|
246
273
|
localLabel: `${this.nickname}~${tags.get(localKey) ?? formatIdentityLabel(this.nickname, this.identity.publicKey).split("~").at(-1)}`,
|
|
247
|
-
|
|
274
|
+
participants,
|
|
275
|
+
directNeighbors: [...this.peers.values()].filter(({ authenticated }) => authenticated).length,
|
|
276
|
+
participantCatalogFull: this.participantCatalogFull,
|
|
248
277
|
transcript: this.transcript.map((entry) => {
|
|
249
278
|
const tag = tags.get(entry.publicKey);
|
|
250
279
|
const nickname = entry.label.split("~", 1)[0] ?? entry.label;
|
|
@@ -262,14 +291,18 @@ export class ChatSession {
|
|
|
262
291
|
return;
|
|
263
292
|
}
|
|
264
293
|
const id = keyId(peer.publicKey);
|
|
294
|
+
if (id === this.identity.publicKey.toString("hex")) {
|
|
295
|
+
peer.close();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
265
298
|
const previous = this.peers.get(id);
|
|
266
299
|
if (previous && previous.peer !== peer) previous.peer.close();
|
|
267
300
|
const state: PeerState = {
|
|
268
301
|
peer,
|
|
269
302
|
authenticated: false,
|
|
270
|
-
|
|
303
|
+
nickname: previous?.nickname,
|
|
271
304
|
violations: 0,
|
|
272
|
-
limiter: new PeerRateLimiter({ burst:
|
|
305
|
+
limiter: new PeerRateLimiter({ burst: 12, refillPerSecond: 4, now: this.now }),
|
|
273
306
|
};
|
|
274
307
|
this.peers.set(id, state);
|
|
275
308
|
try {
|
|
@@ -301,62 +334,104 @@ export class ChatSession {
|
|
|
301
334
|
}
|
|
302
335
|
state.authenticated = true;
|
|
303
336
|
state.nickname = hello.nickname;
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
.map((candidate) => candidate.peer.publicKey.toString("hex"));
|
|
307
|
-
if (knownPeers.length > 0) {
|
|
308
|
-
state.peer.send({ v: 1, type: "peer-list", publicKeys: knownPeers.slice(0, 16) });
|
|
309
|
-
}
|
|
310
|
-
for (const candidate of this.peers.values()) {
|
|
311
|
-
if (candidate !== state && candidate.authenticated) {
|
|
312
|
-
candidate.peer.send({ v: 1, type: "peer-list", publicKeys: [id] });
|
|
313
|
-
}
|
|
314
|
-
}
|
|
337
|
+
this.upsertParticipant(id, peer.publicKey, hello.nickname, this.now());
|
|
338
|
+
this.sendPresenceTo(state.peer);
|
|
315
339
|
this.emit();
|
|
316
340
|
return;
|
|
317
341
|
}
|
|
318
342
|
if (message.type === "hello") return;
|
|
319
|
-
if (message.type === "peer-list") {
|
|
320
|
-
for (const publicKey of message.publicKeys) {
|
|
321
|
-
if (publicKey !== this.identity.publicKey.toString("hex") && !this.peers.has(publicKey)) {
|
|
322
|
-
this.transport.connectPeer?.(Buffer.from(publicKey, "hex"));
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
343
|
if (message.type === "goodbye") {
|
|
328
344
|
this.peers.delete(id);
|
|
329
345
|
peer.close();
|
|
330
346
|
this.emit();
|
|
331
347
|
return;
|
|
332
348
|
}
|
|
333
|
-
if (message.type
|
|
334
|
-
|
|
335
|
-
if (!nickname) this.violate(id, state);
|
|
336
|
-
else {
|
|
337
|
-
state.nickname = nickname;
|
|
338
|
-
this.emit();
|
|
339
|
-
}
|
|
349
|
+
if (message.type !== "gossip") {
|
|
350
|
+
this.violate(id, state);
|
|
340
351
|
return;
|
|
341
352
|
}
|
|
342
|
-
|
|
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;
|
|
343
360
|
if (!state.limiter.accept()) {
|
|
344
|
-
this.violate(
|
|
361
|
+
this.violate(peerId, state);
|
|
345
362
|
return;
|
|
346
363
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
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
|
+
}
|
|
359
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
|
+
}
|
|
360
435
|
}
|
|
361
436
|
|
|
362
437
|
private onDisconnect(owner: number, peer: TransportPeer): void {
|
|
@@ -375,6 +450,142 @@ export class ChatSession {
|
|
|
375
450
|
this.emit();
|
|
376
451
|
}
|
|
377
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
|
+
|
|
378
589
|
private violate(id: string, state: PeerState): void {
|
|
379
590
|
state.violations += 1;
|
|
380
591
|
if (state.violations > MAX_PROTOCOL_VIOLATIONS) {
|
|
@@ -384,15 +595,6 @@ export class ChatSession {
|
|
|
384
595
|
}
|
|
385
596
|
}
|
|
386
597
|
|
|
387
|
-
private remember(id: string): void {
|
|
388
|
-
this.seen.add(id);
|
|
389
|
-
this.seenOrder.push(id);
|
|
390
|
-
if (this.seenOrder.length > MAX_SEEN_MESSAGES) {
|
|
391
|
-
const removed = this.seenOrder.shift();
|
|
392
|
-
if (removed) this.seen.delete(removed);
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
598
|
private pushTranscript(entry: TranscriptEntry): void {
|
|
397
599
|
this.transcript.push(entry);
|
|
398
600
|
if (this.transcript.length > MAX_TRANSCRIPT) this.transcript.shift();
|
|
@@ -400,10 +602,13 @@ export class ChatSession {
|
|
|
400
602
|
|
|
401
603
|
private async leaveOwned(): Promise<void> {
|
|
402
604
|
this.generation += 1;
|
|
605
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
606
|
+
this.heartbeatTimer = undefined;
|
|
607
|
+
if (this.state !== "disconnected") this.publishPresence("leaving");
|
|
403
608
|
for (const state of this.peers.values()) {
|
|
404
609
|
if (state.authenticated) {
|
|
405
610
|
try {
|
|
406
|
-
state.peer.send({ v:
|
|
611
|
+
state.peer.send({ v: 2, type: "goodbye" });
|
|
407
612
|
} catch {
|
|
408
613
|
// Best-effort departure notice.
|
|
409
614
|
}
|
|
@@ -411,6 +616,11 @@ export class ChatSession {
|
|
|
411
616
|
state.peer.close();
|
|
412
617
|
}
|
|
413
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;
|
|
414
624
|
await this.transport.stop().catch((error) => {
|
|
415
625
|
this.lastError = safeError(error);
|
|
416
626
|
});
|
|
@@ -427,6 +637,17 @@ export class ChatSession {
|
|
|
427
637
|
}
|
|
428
638
|
}
|
|
429
639
|
|
|
640
|
+
function eventKey(event: RoomEvent): string {
|
|
641
|
+
return `${event.origin}:${event.id}`;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function compareEventVersion(
|
|
645
|
+
left: Pick<RoomEvent, "issuedAt" | "id">,
|
|
646
|
+
right: Pick<RoomEvent, "issuedAt" | "id">,
|
|
647
|
+
): number {
|
|
648
|
+
return left.issuedAt - right.issuedAt || left.id.localeCompare(right.id);
|
|
649
|
+
}
|
|
650
|
+
|
|
430
651
|
function keyId(publicKey: Uint8Array): string {
|
|
431
652
|
return Buffer.from(publicKey).toString("hex");
|
|
432
653
|
}
|