@narumitw/pi-chat 0.1.6 → 0.1.8

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
package/src/protocol.ts CHANGED
@@ -5,12 +5,12 @@ import { normalizeNickname } from "./nickname.js";
5
5
  import type { RoomDescriptor } from "./room.js";
6
6
 
7
7
  export {
8
- createPrivateRoom,
9
- createPublicRoom,
10
- isCompatibleRoomId,
11
- legacyRoomId,
12
- parseInvite,
13
- type RoomDescriptor,
8
+ createPrivateRoom,
9
+ createPublicRoom,
10
+ isCompatibleRoomId,
11
+ legacyRoomId,
12
+ parseInvite,
13
+ type RoomDescriptor,
14
14
  } from "./room.js";
15
15
 
16
16
  export const PROTOCOL_VERSION = 2;
@@ -23,408 +23,369 @@ const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
23
23
  const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
24
24
 
25
25
  export interface HelloMessage {
26
- v: 2;
27
- type: "hello";
28
- roomId: string;
29
- nonce: string;
30
- nickname: string;
31
- proof: string;
26
+ v: 2;
27
+ type: "hello";
28
+ roomId: string;
29
+ nonce: string;
30
+ nickname: string;
31
+ proof: string;
32
32
  }
33
33
 
34
34
  export interface ChatEvent {
35
- v: 2;
36
- kind: "chat";
37
- roomId: string;
38
- origin: string;
39
- id: string;
40
- issuedAt: number;
41
- nickname: string;
42
- text: string;
43
- signature: string;
35
+ v: 2;
36
+ kind: "chat";
37
+ roomId: string;
38
+ origin: string;
39
+ id: string;
40
+ issuedAt: number;
41
+ nickname: string;
42
+ text: string;
43
+ signature: string;
44
44
  }
45
45
 
46
46
  export interface PresenceEvent {
47
- v: 2;
48
- kind: "presence";
49
- roomId: string;
50
- origin: string;
51
- id: string;
52
- issuedAt: number;
53
- nickname: string;
54
- status: "online" | "leaving";
55
- signature: string;
47
+ v: 2;
48
+ kind: "presence";
49
+ roomId: string;
50
+ origin: string;
51
+ id: string;
52
+ issuedAt: number;
53
+ nickname: string;
54
+ status: "online" | "leaving";
55
+ signature: string;
56
56
  }
57
57
 
58
58
  export type RoomEvent = ChatEvent | PresenceEvent;
59
59
  type UnsignedRoomEvent = Omit<ChatEvent, "signature"> | Omit<PresenceEvent, "signature">;
60
60
 
61
61
  export interface GossipMessage {
62
- v: 2;
63
- type: "gossip";
64
- event: RoomEvent;
65
- hops: number;
62
+ v: 2;
63
+ type: "gossip";
64
+ event: RoomEvent;
65
+ hops: number;
66
66
  }
67
67
 
68
68
  export interface GoodbyeMessage {
69
- v: 2;
70
- type: "goodbye";
69
+ v: 2;
70
+ type: "goodbye";
71
71
  }
72
72
 
73
73
  export type ProtocolMessage = HelloMessage | GossipMessage | GoodbyeMessage;
74
74
 
75
75
  export function createHello(
76
- room: RoomDescriptor,
77
- nicknameValue: string,
78
- senderPublicKey: Uint8Array,
79
- receiverPublicKey: Uint8Array,
80
- nonceBytes: Uint8Array,
76
+ room: RoomDescriptor,
77
+ nicknameValue: string,
78
+ senderPublicKey: Uint8Array,
79
+ receiverPublicKey: Uint8Array,
80
+ nonceBytes: Uint8Array,
81
81
  ): HelloMessage {
82
- const nickname = normalizeNickname(nicknameValue);
83
- if (!nickname) throw new Error("Nickname is invalid.");
84
- if (senderPublicKey.byteLength !== 32 || receiverPublicKey.byteLength !== 32) {
85
- throw new Error("Peer public keys must be 32 bytes.");
86
- }
87
- if (nonceBytes.byteLength !== 16) throw new Error("Handshake nonces must be 16 bytes.");
88
- const nonce = Buffer.from(nonceBytes).toString("base64url");
89
- return {
90
- v: 2,
91
- type: "hello",
92
- roomId: room.id,
93
- nonce,
94
- nickname,
95
- proof: helloProof(room, nickname, senderPublicKey, receiverPublicKey, nonce),
96
- };
82
+ const nickname = normalizeNickname(nicknameValue);
83
+ if (!nickname) throw new Error("Nickname is invalid.");
84
+ if (senderPublicKey.byteLength !== 32 || receiverPublicKey.byteLength !== 32) {
85
+ throw new Error("Peer public keys must be 32 bytes.");
86
+ }
87
+ if (nonceBytes.byteLength !== 16) throw new Error("Handshake nonces must be 16 bytes.");
88
+ const nonce = Buffer.from(nonceBytes).toString("base64url");
89
+ return {
90
+ v: 2,
91
+ type: "hello",
92
+ roomId: room.id,
93
+ nonce,
94
+ nickname,
95
+ proof: helloProof(room, nickname, senderPublicKey, receiverPublicKey, nonce),
96
+ };
97
97
  }
98
98
 
99
99
  export function verifyHello(
100
- value: unknown,
101
- room: RoomDescriptor,
102
- senderPublicKey: Uint8Array,
103
- receiverPublicKey: Uint8Array,
100
+ value: unknown,
101
+ room: RoomDescriptor,
102
+ senderPublicKey: Uint8Array,
103
+ receiverPublicKey: Uint8Array,
104
104
  ): HelloMessage | undefined {
105
- if (!isRecord(value) || value.v !== 2 || value.type !== "hello") return undefined;
106
- if (
107
- value.roomId !== room.id ||
108
- typeof value.nonce !== "string" ||
109
- typeof value.proof !== "string"
110
- ) {
111
- return undefined;
112
- }
113
- const nickname = normalizeNickname(value.nickname);
114
- if (!nickname || !/^[A-Za-z0-9_-]{22}$/u.test(value.nonce)) return undefined;
115
- const expected = helloProof(room, nickname, senderPublicKey, receiverPublicKey, value.nonce);
116
- const actualBytes = Buffer.from(value.proof, "base64url");
117
- const expectedBytes = Buffer.from(expected, "base64url");
118
- if (actualBytes.length !== expectedBytes.length || !timingSafeEqual(actualBytes, expectedBytes)) {
119
- return undefined;
120
- }
121
- return {
122
- v: 2,
123
- type: "hello",
124
- roomId: room.id,
125
- nonce: value.nonce,
126
- nickname,
127
- proof: value.proof,
128
- };
105
+ if (!isRecord(value) || value.v !== 2 || value.type !== "hello") return undefined;
106
+ if (value.roomId !== room.id || typeof value.nonce !== "string" || typeof value.proof !== "string") {
107
+ return undefined;
108
+ }
109
+ const nickname = normalizeNickname(value.nickname);
110
+ if (!nickname || !/^[A-Za-z0-9_-]{22}$/u.test(value.nonce)) return undefined;
111
+ const expected = helloProof(room, nickname, senderPublicKey, receiverPublicKey, value.nonce);
112
+ const actualBytes = Buffer.from(value.proof, "base64url");
113
+ const expectedBytes = Buffer.from(expected, "base64url");
114
+ if (actualBytes.length !== expectedBytes.length || !timingSafeEqual(actualBytes, expectedBytes)) {
115
+ return undefined;
116
+ }
117
+ return {
118
+ v: 2,
119
+ type: "hello",
120
+ roomId: room.id,
121
+ nonce: value.nonce,
122
+ nickname,
123
+ proof: value.proof,
124
+ };
129
125
  }
130
126
 
131
127
  export function createChatEvent(
132
- room: RoomDescriptor,
133
- identity: ChatIdentity,
134
- nicknameValue: string,
135
- text: string,
136
- issuedAt: number,
137
- id: string,
128
+ room: RoomDescriptor,
129
+ identity: ChatIdentity,
130
+ nicknameValue: string,
131
+ text: string,
132
+ issuedAt: number,
133
+ id: string,
138
134
  ): ChatEvent {
139
- const nickname = normalizeNickname(nicknameValue);
140
- if (!nickname) throw new Error("Nickname is invalid.");
141
- if (!text || Buffer.byteLength(text, "utf8") > MAX_MESSAGE_BYTES) {
142
- throw new Error("Chat message is empty or too large.");
143
- }
144
- validateEventFields(issuedAt, id);
145
- const unsigned: Omit<ChatEvent, "signature"> = {
146
- v: 2,
147
- kind: "chat",
148
- roomId: room.id,
149
- origin: identity.publicKey.toString("hex"),
150
- id,
151
- issuedAt,
152
- nickname,
153
- text,
154
- };
155
- return { ...unsigned, signature: signIdentityPayload(identity, canonicalEvent(unsigned)) };
135
+ const nickname = normalizeNickname(nicknameValue);
136
+ if (!nickname) throw new Error("Nickname is invalid.");
137
+ if (!text || Buffer.byteLength(text, "utf8") > MAX_MESSAGE_BYTES) {
138
+ throw new Error("Chat message is empty or too large.");
139
+ }
140
+ validateEventFields(issuedAt, id);
141
+ const unsigned: Omit<ChatEvent, "signature"> = {
142
+ v: 2,
143
+ kind: "chat",
144
+ roomId: room.id,
145
+ origin: identity.publicKey.toString("hex"),
146
+ id,
147
+ issuedAt,
148
+ nickname,
149
+ text,
150
+ };
151
+ return { ...unsigned, signature: signIdentityPayload(identity, canonicalEvent(unsigned)) };
156
152
  }
157
153
 
158
154
  export function createPresenceEvent(
159
- room: RoomDescriptor,
160
- identity: ChatIdentity,
161
- nicknameValue: string,
162
- status: PresenceEvent["status"],
163
- issuedAt: number,
164
- id: string,
155
+ room: RoomDescriptor,
156
+ identity: ChatIdentity,
157
+ nicknameValue: string,
158
+ status: PresenceEvent["status"],
159
+ issuedAt: number,
160
+ id: string,
165
161
  ): PresenceEvent {
166
- const nickname = normalizeNickname(nicknameValue);
167
- if (!nickname) throw new Error("Nickname is invalid.");
168
- if (status !== "online" && status !== "leaving") throw new Error("Presence state is invalid.");
169
- validateEventFields(issuedAt, id);
170
- const unsigned: Omit<PresenceEvent, "signature"> = {
171
- v: 2,
172
- kind: "presence",
173
- roomId: room.id,
174
- origin: identity.publicKey.toString("hex"),
175
- id,
176
- issuedAt,
177
- nickname,
178
- status,
179
- };
180
- return { ...unsigned, signature: signIdentityPayload(identity, canonicalEvent(unsigned)) };
162
+ const nickname = normalizeNickname(nicknameValue);
163
+ if (!nickname) throw new Error("Nickname is invalid.");
164
+ if (status !== "online" && status !== "leaving") throw new Error("Presence state is invalid.");
165
+ validateEventFields(issuedAt, id);
166
+ const unsigned: Omit<PresenceEvent, "signature"> = {
167
+ v: 2,
168
+ kind: "presence",
169
+ roomId: room.id,
170
+ origin: identity.publicKey.toString("hex"),
171
+ id,
172
+ issuedAt,
173
+ nickname,
174
+ status,
175
+ };
176
+ return { ...unsigned, signature: signIdentityPayload(identity, canonicalEvent(unsigned)) };
181
177
  }
182
178
 
183
- export function createGossipMessage(
184
- event: RoomEvent,
185
- hops: number = MAX_GOSSIP_HOPS,
186
- ): GossipMessage {
187
- if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
188
- throw new Error("Gossip hop budget is invalid.");
189
- }
190
- return { v: 2, type: "gossip", event, hops };
179
+ export function createGossipMessage(event: RoomEvent, hops: number = MAX_GOSSIP_HOPS): GossipMessage {
180
+ if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
181
+ throw new Error("Gossip hop budget is invalid.");
182
+ }
183
+ return { v: 2, type: "gossip", event, hops };
191
184
  }
192
185
 
193
186
  export function verifyRoomEvent(event: RoomEvent, room: RoomDescriptor, now = Date.now()): boolean {
194
- const parsed = parseRoomEvent(event);
195
- if (!parsed || parsed.roomId !== room.id) return false;
196
- if (parsed.issuedAt < now - MAX_EVENT_AGE_MS || parsed.issuedAt > now + MAX_EVENT_FUTURE_MS) {
197
- return false;
198
- }
199
- return verifyIdentityPayload(
200
- Buffer.from(parsed.origin, "hex"),
201
- canonicalEvent(withoutSignature(parsed)),
202
- parsed.signature,
203
- );
187
+ const parsed = parseRoomEvent(event);
188
+ if (!parsed || parsed.roomId !== room.id) return false;
189
+ if (parsed.issuedAt < now - MAX_EVENT_AGE_MS || parsed.issuedAt > now + MAX_EVENT_FUTURE_MS) {
190
+ return false;
191
+ }
192
+ return verifyIdentityPayload(
193
+ Buffer.from(parsed.origin, "hex"),
194
+ canonicalEvent(withoutSignature(parsed)),
195
+ parsed.signature,
196
+ );
204
197
  }
205
198
 
206
199
  export function parseProtocolMessage(value: unknown): ProtocolMessage | undefined {
207
- if (!isRecord(value) || typeof value.type !== "string") return undefined;
208
- if (value.v === 2 && value.type === "gossip") {
209
- if (
210
- !Number.isSafeInteger(value.hops) ||
211
- (value.hops as number) < 1 ||
212
- (value.hops as number) > MAX_GOSSIP_HOPS
213
- ) {
214
- return undefined;
215
- }
216
- const event = parseRoomEvent(value.event);
217
- return event ? { v: 2, type: "gossip", event, hops: value.hops as number } : undefined;
218
- }
219
- if (value.v === 2 && value.type === "hello") {
220
- if (
221
- typeof value.roomId !== "string" ||
222
- typeof value.nonce !== "string" ||
223
- typeof value.proof !== "string" ||
224
- !normalizeNickname(value.nickname)
225
- ) {
226
- return undefined;
227
- }
228
- return value as unknown as HelloMessage;
229
- }
230
- if (value.v === 2 && value.type === "goodbye") return { v: 2, type: "goodbye" };
231
- return undefined;
200
+ if (!isRecord(value) || typeof value.type !== "string") return undefined;
201
+ if (value.v === 2 && value.type === "gossip") {
202
+ if (!Number.isSafeInteger(value.hops) || (value.hops as number) < 1 || (value.hops as number) > MAX_GOSSIP_HOPS) {
203
+ return undefined;
204
+ }
205
+ const event = parseRoomEvent(value.event);
206
+ return event ? { v: 2, type: "gossip", event, hops: value.hops as number } : undefined;
207
+ }
208
+ if (value.v === 2 && value.type === "hello") {
209
+ if (
210
+ typeof value.roomId !== "string" ||
211
+ typeof value.nonce !== "string" ||
212
+ typeof value.proof !== "string" ||
213
+ !normalizeNickname(value.nickname)
214
+ ) {
215
+ return undefined;
216
+ }
217
+ return value as unknown as HelloMessage;
218
+ }
219
+ if (value.v === 2 && value.type === "goodbye") return { v: 2, type: "goodbye" };
220
+ return undefined;
232
221
  }
233
222
 
234
223
  export function encodeFrame(message: ProtocolMessage): Buffer {
235
- const payload = Buffer.from(JSON.stringify(message), "utf8");
236
- if (payload.length > MAX_FRAME_BYTES) throw new Error("Protocol frame exceeds the size limit.");
237
- const header = Buffer.allocUnsafe(4);
238
- header.writeUInt32BE(payload.length);
239
- return Buffer.concat([header, payload]);
224
+ const payload = Buffer.from(JSON.stringify(message), "utf8");
225
+ if (payload.length > MAX_FRAME_BYTES) throw new Error("Protocol frame exceeds the size limit.");
226
+ const header = Buffer.allocUnsafe(4);
227
+ header.writeUInt32BE(payload.length);
228
+ return Buffer.concat([header, payload]);
240
229
  }
241
230
 
242
231
  export class FrameDecoder {
243
- private buffer = Buffer.alloc(0);
232
+ private buffer = Buffer.alloc(0);
244
233
 
245
- push(chunk: Uint8Array): ProtocolMessage[] {
246
- if (chunk.byteLength === 0) return [];
247
- const incoming = Buffer.from(chunk);
248
- const messages: ProtocolMessage[] = [];
249
- let offset = 0;
250
- while (offset < incoming.length) {
251
- if (this.buffer.length < 4) {
252
- const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
253
- this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
254
- offset += headerBytes;
255
- if (this.buffer.length < 4) break;
256
- }
257
- const length = this.buffer.readUInt32BE(0);
258
- if (length > MAX_FRAME_BYTES) {
259
- this.buffer = Buffer.alloc(0);
260
- throw new Error("Protocol frame exceeds the size limit.");
261
- }
262
- const frameBytes = length + 4;
263
- if (this.buffer.length < frameBytes) {
264
- const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
265
- this.buffer = Buffer.concat([
266
- this.buffer,
267
- incoming.subarray(offset, offset + payloadBytes),
268
- ]);
269
- offset += payloadBytes;
270
- if (this.buffer.length < frameBytes) break;
271
- }
272
- const payload = this.buffer.subarray(4, frameBytes);
273
- this.buffer = Buffer.alloc(0);
274
- let text: string;
275
- try {
276
- text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
277
- } catch {
278
- throw new Error("Protocol frame contains invalid UTF-8.");
279
- }
280
- let value: unknown;
281
- try {
282
- value = JSON.parse(text) as unknown;
283
- } catch {
284
- throw new Error("Protocol frame contains invalid JSON.");
285
- }
286
- const parsed = parseProtocolMessage(value);
287
- if (!parsed) throw new Error("Protocol frame has an invalid message shape.");
288
- messages.push(parsed);
289
- }
290
- return messages;
291
- }
234
+ push(chunk: Uint8Array): ProtocolMessage[] {
235
+ if (chunk.byteLength === 0) return [];
236
+ const incoming = Buffer.from(chunk);
237
+ const messages: ProtocolMessage[] = [];
238
+ let offset = 0;
239
+ while (offset < incoming.length) {
240
+ if (this.buffer.length < 4) {
241
+ const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
242
+ this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
243
+ offset += headerBytes;
244
+ if (this.buffer.length < 4) break;
245
+ }
246
+ const length = this.buffer.readUInt32BE(0);
247
+ if (length > MAX_FRAME_BYTES) {
248
+ this.buffer = Buffer.alloc(0);
249
+ throw new Error("Protocol frame exceeds the size limit.");
250
+ }
251
+ const frameBytes = length + 4;
252
+ if (this.buffer.length < frameBytes) {
253
+ const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
254
+ this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + payloadBytes)]);
255
+ offset += payloadBytes;
256
+ if (this.buffer.length < frameBytes) break;
257
+ }
258
+ const payload = this.buffer.subarray(4, frameBytes);
259
+ this.buffer = Buffer.alloc(0);
260
+ let text: string;
261
+ try {
262
+ text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
263
+ } catch {
264
+ throw new Error("Protocol frame contains invalid UTF-8.");
265
+ }
266
+ let value: unknown;
267
+ try {
268
+ value = JSON.parse(text) as unknown;
269
+ } catch {
270
+ throw new Error("Protocol frame contains invalid JSON.");
271
+ }
272
+ const parsed = parseProtocolMessage(value);
273
+ if (!parsed) throw new Error("Protocol frame has an invalid message shape.");
274
+ messages.push(parsed);
275
+ }
276
+ return messages;
277
+ }
292
278
  }
293
279
 
294
280
  export class PeerRateLimiter {
295
- private tokens: number;
296
- private lastRefill: number;
297
- private readonly burst: number;
298
- private readonly refillPerSecond: number;
299
- private readonly now: () => number;
281
+ private tokens: number;
282
+ private lastRefill: number;
283
+ private readonly burst: number;
284
+ private readonly refillPerSecond: number;
285
+ private readonly now: () => number;
300
286
 
301
- constructor(options: { burst: number; refillPerSecond: number; now?: () => number }) {
302
- if (options.burst <= 0 || options.refillPerSecond <= 0) {
303
- throw new Error("Rate limiter values must be positive.");
304
- }
305
- this.burst = options.burst;
306
- this.tokens = options.burst;
307
- this.refillPerSecond = options.refillPerSecond;
308
- this.now = options.now ?? Date.now;
309
- this.lastRefill = this.now();
310
- }
287
+ constructor(options: { burst: number; refillPerSecond: number; now?: () => number }) {
288
+ if (options.burst <= 0 || options.refillPerSecond <= 0) {
289
+ throw new Error("Rate limiter values must be positive.");
290
+ }
291
+ this.burst = options.burst;
292
+ this.tokens = options.burst;
293
+ this.refillPerSecond = options.refillPerSecond;
294
+ this.now = options.now ?? Date.now;
295
+ this.lastRefill = this.now();
296
+ }
311
297
 
312
- accept(): boolean {
313
- const current = this.now();
314
- const elapsed = Math.max(0, current - this.lastRefill);
315
- this.lastRefill = current;
316
- this.tokens = Math.min(this.burst, this.tokens + (elapsed / 1000) * this.refillPerSecond);
317
- if (this.tokens < 1) return false;
318
- this.tokens -= 1;
319
- return true;
320
- }
298
+ accept(): boolean {
299
+ const current = this.now();
300
+ const elapsed = Math.max(0, current - this.lastRefill);
301
+ this.lastRefill = current;
302
+ this.tokens = Math.min(this.burst, this.tokens + (elapsed / 1000) * this.refillPerSecond);
303
+ if (this.tokens < 1) return false;
304
+ this.tokens -= 1;
305
+ return true;
306
+ }
321
307
  }
322
308
 
323
309
  function parseRoomEvent(value: unknown): RoomEvent | undefined {
324
- if (!isRecord(value) || value.v !== 2 || (value.kind !== "chat" && value.kind !== "presence")) {
325
- return undefined;
326
- }
327
- const nickname = normalizeNickname(value.nickname);
328
- if (
329
- typeof value.roomId !== "string" ||
330
- !PUBLIC_KEY.test(String(value.origin)) ||
331
- !validId(value.id) ||
332
- !Number.isSafeInteger(value.issuedAt) ||
333
- (value.issuedAt as number) < 0 ||
334
- !nickname ||
335
- typeof value.signature !== "string" ||
336
- !SIGNATURE.test(value.signature)
337
- ) {
338
- return undefined;
339
- }
340
- const common = {
341
- v: 2 as const,
342
- roomId: value.roomId,
343
- origin: value.origin as string,
344
- id: value.id,
345
- issuedAt: value.issuedAt as number,
346
- nickname,
347
- signature: value.signature,
348
- };
349
- if (value.kind === "chat") {
350
- if (
351
- typeof value.text !== "string" ||
352
- !value.text ||
353
- Buffer.byteLength(value.text, "utf8") > MAX_MESSAGE_BYTES
354
- ) {
355
- return undefined;
356
- }
357
- return { ...common, kind: "chat", text: value.text };
358
- }
359
- if (value.status !== "online" && value.status !== "leaving") return undefined;
360
- return { ...common, kind: "presence", status: value.status };
310
+ if (!isRecord(value) || value.v !== 2 || (value.kind !== "chat" && value.kind !== "presence")) {
311
+ return undefined;
312
+ }
313
+ const nickname = normalizeNickname(value.nickname);
314
+ if (
315
+ typeof value.roomId !== "string" ||
316
+ !PUBLIC_KEY.test(String(value.origin)) ||
317
+ !validId(value.id) ||
318
+ !Number.isSafeInteger(value.issuedAt) ||
319
+ (value.issuedAt as number) < 0 ||
320
+ !nickname ||
321
+ typeof value.signature !== "string" ||
322
+ !SIGNATURE.test(value.signature)
323
+ ) {
324
+ return undefined;
325
+ }
326
+ const common = {
327
+ v: 2 as const,
328
+ roomId: value.roomId,
329
+ origin: value.origin as string,
330
+ id: value.id,
331
+ issuedAt: value.issuedAt as number,
332
+ nickname,
333
+ signature: value.signature,
334
+ };
335
+ if (value.kind === "chat") {
336
+ if (typeof value.text !== "string" || !value.text || Buffer.byteLength(value.text, "utf8") > MAX_MESSAGE_BYTES) {
337
+ return undefined;
338
+ }
339
+ return { ...common, kind: "chat", text: value.text };
340
+ }
341
+ if (value.status !== "online" && value.status !== "leaving") return undefined;
342
+ return { ...common, kind: "presence", status: value.status };
361
343
  }
362
344
 
363
345
  function canonicalEvent(event: UnsignedRoomEvent): Buffer {
364
- const payload =
365
- event.kind === "chat"
366
- ? [
367
- 2,
368
- "chat",
369
- event.roomId,
370
- event.origin,
371
- event.id,
372
- event.issuedAt,
373
- event.nickname,
374
- event.text,
375
- ]
376
- : [
377
- 2,
378
- "presence",
379
- event.roomId,
380
- event.origin,
381
- event.id,
382
- event.issuedAt,
383
- event.nickname,
384
- event.status,
385
- ];
386
- return Buffer.from(JSON.stringify(payload), "utf8");
346
+ const payload =
347
+ event.kind === "chat"
348
+ ? [2, "chat", event.roomId, event.origin, event.id, event.issuedAt, event.nickname, event.text]
349
+ : [2, "presence", event.roomId, event.origin, event.id, event.issuedAt, event.nickname, event.status];
350
+ return Buffer.from(JSON.stringify(payload), "utf8");
387
351
  }
388
352
 
389
353
  function withoutSignature(event: RoomEvent): UnsignedRoomEvent {
390
- if (event.kind === "chat") {
391
- const { signature: _signature, ...unsigned } = event;
392
- return unsigned;
393
- }
394
- const { signature: _signature, ...unsigned } = event;
395
- return unsigned;
354
+ if (event.kind === "chat") {
355
+ const { signature: _signature, ...unsigned } = event;
356
+ return unsigned;
357
+ }
358
+ const { signature: _signature, ...unsigned } = event;
359
+ return unsigned;
396
360
  }
397
361
 
398
362
  function validateEventFields(issuedAt: number, id: string): void {
399
- if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
400
- throw new Error("Message timestamp is invalid.");
401
- if (!validId(id)) throw new Error("Message id is invalid.");
363
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0) throw new Error("Message timestamp is invalid.");
364
+ if (!validId(id)) throw new Error("Message id is invalid.");
402
365
  }
403
366
 
404
367
  function helloProof(
405
- room: RoomDescriptor,
406
- nickname: string,
407
- senderPublicKey: Uint8Array,
408
- receiverPublicKey: Uint8Array,
409
- nonce: string,
368
+ room: RoomDescriptor,
369
+ nickname: string,
370
+ senderPublicKey: Uint8Array,
371
+ receiverPublicKey: Uint8Array,
372
+ nonce: string,
410
373
  ): string {
411
- const canonical = JSON.stringify([
412
- PROTOCOL_VERSION,
413
- room.id,
414
- nonce,
415
- nickname,
416
- Buffer.from(senderPublicKey).toString("hex"),
417
- Buffer.from(receiverPublicKey).toString("hex"),
418
- ]);
419
- return createHmac("sha256", room.key).update(canonical).digest("base64url");
374
+ const canonical = JSON.stringify([
375
+ PROTOCOL_VERSION,
376
+ room.id,
377
+ nonce,
378
+ nickname,
379
+ Buffer.from(senderPublicKey).toString("hex"),
380
+ Buffer.from(receiverPublicKey).toString("hex"),
381
+ ]);
382
+ return createHmac("sha256", room.key).update(canonical).digest("base64url");
420
383
  }
421
384
 
422
385
  function validId(value: unknown): value is string {
423
- return (
424
- typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value)
425
- );
386
+ return typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value);
426
387
  }
427
388
 
428
389
  function isRecord(value: unknown): value is Record<string, unknown> {
429
- return typeof value === "object" && value !== null && !Array.isArray(value);
390
+ return typeof value === "object" && value !== null && !Array.isArray(value);
430
391
  }