@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/src/protocol.ts CHANGED
@@ -1,22 +1,29 @@
1
- import { createHash, createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
2
- import { normalizeNickname } from "./identity.js";
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import type { ChatIdentity } from "./identity.js";
3
+ import { signIdentityPayload, verifyIdentityPayload } from "./identity.js";
4
+ import { normalizeNickname } from "./nickname.js";
5
+ import type { RoomDescriptor } from "./room.js";
3
6
 
4
- export const PROTOCOL_VERSION = 1;
7
+ export {
8
+ createPrivateRoom,
9
+ createPublicRoom,
10
+ isCompatibleRoomId,
11
+ legacyRoomId,
12
+ parseInvite,
13
+ type RoomDescriptor,
14
+ } from "./room.js";
15
+
16
+ export const PROTOCOL_VERSION = 2;
5
17
  export const MAX_FRAME_BYTES = 16 * 1024;
6
18
  export const MAX_MESSAGE_BYTES = 4 * 1024;
7
- const PUBLIC_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/u;
8
-
9
- export interface RoomDescriptor {
10
- kind: "private" | "public";
11
- label: string;
12
- id: string;
13
- topic: Buffer;
14
- key: Buffer;
15
- invite?: string;
16
- }
19
+ export const MAX_GOSSIP_HOPS = 8;
20
+ export const MAX_EVENT_AGE_MS = 5 * 60_000;
21
+ const MAX_EVENT_FUTURE_MS = 60_000;
22
+ const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
23
+ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
17
24
 
18
25
  export interface HelloMessage {
19
- v: 1;
26
+ v: 2;
20
27
  type: "hello";
21
28
  roomId: string;
22
29
  nonce: string;
@@ -24,65 +31,46 @@ export interface HelloMessage {
24
31
  proof: string;
25
32
  }
26
33
 
27
- export interface ChatMessage {
28
- v: 1;
29
- type: "chat";
30
- text: string;
31
- sentAt: number;
34
+ export interface ChatEvent {
35
+ v: 2;
36
+ kind: "chat";
37
+ roomId: string;
38
+ origin: string;
32
39
  id: string;
40
+ issuedAt: number;
41
+ nickname: string;
42
+ text: string;
43
+ signature: string;
33
44
  }
34
45
 
35
- export interface PresenceMessage {
36
- v: 1;
37
- type: "nickname-update" | "goodbye" | "ping" | "pong";
38
- nickname?: string;
39
- }
40
-
41
- export interface PeerListMessage {
42
- v: 1;
43
- type: "peer-list";
44
- publicKeys: string[];
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;
45
56
  }
46
57
 
47
- export type ProtocolMessage = HelloMessage | ChatMessage | PresenceMessage | PeerListMessage;
58
+ export type RoomEvent = ChatEvent | PresenceEvent;
59
+ type UnsignedRoomEvent = Omit<ChatEvent, "signature"> | Omit<PresenceEvent, "signature">;
48
60
 
49
- export function createPrivateRoom(secret: Uint8Array): RoomDescriptor {
50
- if (secret.byteLength !== 32) throw new Error("Private room secrets must be 32 bytes.");
51
- const bytes = Buffer.from(secret);
52
- const topic = domainHash("pi-chat/discovery/private/v1", bytes);
53
- return {
54
- kind: "private",
55
- label: `private ${shortRoomId(topic)}`,
56
- id: topic.toString("base64url"),
57
- topic,
58
- key: deriveRoomKey(bytes),
59
- invite: `pichat:v1:${bytes.toString("base64url")}`,
60
- };
61
+ export interface GossipMessage {
62
+ v: 2;
63
+ type: "gossip";
64
+ event: RoomEvent;
65
+ hops: number;
61
66
  }
62
67
 
63
- export function parseInvite(value: string): RoomDescriptor {
64
- const match = /^pichat:v1:([A-Za-z0-9_-]{43})$/u.exec(value.trim());
65
- const encodedSecret = match?.[1];
66
- if (!encodedSecret) throw new Error("This is not a valid Pi Chat invite.");
67
- const secret = Buffer.from(encodedSecret, "base64url");
68
- if (secret.length !== 32) throw new Error("This is not a valid Pi Chat invite.");
69
- return createPrivateRoom(secret);
68
+ export interface GoodbyeMessage {
69
+ v: 2;
70
+ type: "goodbye";
70
71
  }
71
72
 
72
- export function createPublicRoom(slug: string): RoomDescriptor {
73
- if (!PUBLIC_SLUG.test(slug)) {
74
- throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
75
- }
76
- const material = Buffer.from(`pi-chat/public/v1:${slug}`, "utf8");
77
- const topic = createHash("sha256").update(material).digest();
78
- return {
79
- kind: "public",
80
- label: `#${slug}`,
81
- id: topic.toString("base64url"),
82
- topic,
83
- key: deriveRoomKey(material),
84
- };
85
- }
73
+ export type ProtocolMessage = HelloMessage | GossipMessage | GoodbyeMessage;
86
74
 
87
75
  export function createHello(
88
76
  room: RoomDescriptor,
@@ -99,7 +87,7 @@ export function createHello(
99
87
  if (nonceBytes.byteLength !== 16) throw new Error("Handshake nonces must be 16 bytes.");
100
88
  const nonce = Buffer.from(nonceBytes).toString("base64url");
101
89
  return {
102
- v: 1,
90
+ v: 2,
103
91
  type: "hello",
104
92
  roomId: room.id,
105
93
  nonce,
@@ -114,7 +102,7 @@ export function verifyHello(
114
102
  senderPublicKey: Uint8Array,
115
103
  receiverPublicKey: Uint8Array,
116
104
  ): HelloMessage | undefined {
117
- if (!isRecord(value) || value.v !== 1 || value.type !== "hello") return undefined;
105
+ if (!isRecord(value) || value.v !== 2 || value.type !== "hello") return undefined;
118
106
  if (
119
107
  value.roomId !== room.id ||
120
108
  typeof value.nonce !== "string" ||
@@ -131,7 +119,7 @@ export function verifyHello(
131
119
  return undefined;
132
120
  }
133
121
  return {
134
- v: 1,
122
+ v: 2,
135
123
  type: "hello",
136
124
  roomId: room.id,
137
125
  nonce: value.nonce,
@@ -140,37 +128,95 @@ export function verifyHello(
140
128
  };
141
129
  }
142
130
 
143
- export function createChatMessage(text: string, sentAt: number, id: string): ChatMessage {
131
+ export function createChatEvent(
132
+ room: RoomDescriptor,
133
+ identity: ChatIdentity,
134
+ nicknameValue: string,
135
+ text: string,
136
+ issuedAt: number,
137
+ id: string,
138
+ ): ChatEvent {
139
+ const nickname = normalizeNickname(nicknameValue);
140
+ if (!nickname) throw new Error("Nickname is invalid.");
144
141
  if (!text || Buffer.byteLength(text, "utf8") > MAX_MESSAGE_BYTES) {
145
142
  throw new Error("Chat message is empty or too large.");
146
143
  }
147
- if (!Number.isSafeInteger(sentAt) || sentAt < 0) throw new Error("Message timestamp is invalid.");
148
- if (!validId(id)) throw new Error("Message id is invalid.");
149
- return { v: 1, type: "chat", text, sentAt, id };
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)) };
156
+ }
157
+
158
+ export function createPresenceEvent(
159
+ room: RoomDescriptor,
160
+ identity: ChatIdentity,
161
+ nicknameValue: string,
162
+ status: PresenceEvent["status"],
163
+ issuedAt: number,
164
+ id: string,
165
+ ): 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)) };
181
+ }
182
+
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 };
191
+ }
192
+
193
+ 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
+ );
150
204
  }
151
205
 
152
206
  export function parseProtocolMessage(value: unknown): ProtocolMessage | undefined {
153
- if (!isRecord(value) || value.v !== 1 || typeof value.type !== "string") return undefined;
154
- if (value.type === "chat") {
207
+ if (!isRecord(value) || typeof value.type !== "string") return undefined;
208
+ if (value.v === 2 && value.type === "gossip") {
155
209
  if (
156
- typeof value.text !== "string" ||
157
- !value.text ||
158
- Buffer.byteLength(value.text, "utf8") > MAX_MESSAGE_BYTES ||
159
- !Number.isSafeInteger(value.sentAt) ||
160
- (value.sentAt as number) < 0 ||
161
- !validId(value.id)
210
+ !Number.isSafeInteger(value.hops) ||
211
+ (value.hops as number) < 1 ||
212
+ (value.hops as number) > MAX_GOSSIP_HOPS
162
213
  ) {
163
214
  return undefined;
164
215
  }
165
- return {
166
- v: 1,
167
- type: "chat",
168
- text: value.text,
169
- sentAt: value.sentAt as number,
170
- id: value.id as string,
171
- };
216
+ const event = parseRoomEvent(value.event);
217
+ return event ? { v: 2, type: "gossip", event, hops: value.hops as number } : undefined;
172
218
  }
173
- if (value.type === "hello") {
219
+ if (value.v === 2 && value.type === "hello") {
174
220
  if (
175
221
  typeof value.roomId !== "string" ||
176
222
  typeof value.nonce !== "string" ||
@@ -181,23 +227,7 @@ export function parseProtocolMessage(value: unknown): ProtocolMessage | undefine
181
227
  }
182
228
  return value as unknown as HelloMessage;
183
229
  }
184
- if (value.type === "nickname-update") {
185
- const nickname = normalizeNickname(value.nickname);
186
- return nickname ? { v: 1, type: "nickname-update", nickname } : undefined;
187
- }
188
- if (value.type === "peer-list") {
189
- if (
190
- !Array.isArray(value.publicKeys) ||
191
- value.publicKeys.length > 16 ||
192
- !value.publicKeys.every((key) => typeof key === "string" && /^[0-9a-f]{64}$/u.test(key))
193
- ) {
194
- return undefined;
195
- }
196
- return { v: 1, type: "peer-list", publicKeys: [...new Set(value.publicKeys)] };
197
- }
198
- if (value.type === "goodbye" || value.type === "ping" || value.type === "pong") {
199
- return { v: 1, type: value.type };
200
- }
230
+ if (value.v === 2 && value.type === "goodbye") return { v: 2, type: "goodbye" };
201
231
  return undefined;
202
232
  }
203
233
 
@@ -214,21 +244,33 @@ export class FrameDecoder {
214
244
 
215
245
  push(chunk: Uint8Array): ProtocolMessage[] {
216
246
  if (chunk.byteLength === 0) return [];
217
- if (this.buffer.length + chunk.byteLength > MAX_FRAME_BYTES + 4) {
218
- this.buffer = Buffer.alloc(0);
219
- throw new Error("Protocol frame exceeds the size limit.");
220
- }
221
- this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk)]);
247
+ const incoming = Buffer.from(chunk);
222
248
  const messages: ProtocolMessage[] = [];
223
- while (this.buffer.length >= 4) {
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
+ }
224
257
  const length = this.buffer.readUInt32BE(0);
225
258
  if (length > MAX_FRAME_BYTES) {
226
259
  this.buffer = Buffer.alloc(0);
227
260
  throw new Error("Protocol frame exceeds the size limit.");
228
261
  }
229
- if (this.buffer.length < length + 4) break;
230
- const payload = this.buffer.subarray(4, length + 4);
231
- this.buffer = this.buffer.subarray(length + 4);
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);
232
274
  let text: string;
233
275
  try {
234
276
  text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
@@ -278,22 +320,85 @@ export class PeerRateLimiter {
278
320
  }
279
321
  }
280
322
 
281
- function deriveRoomKey(material: Uint8Array): Buffer {
282
- return Buffer.from(
283
- hkdfSync("sha256", material, Buffer.from("pi-chat/v1"), Buffer.from("room-handshake"), 32),
284
- );
323
+ 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 };
285
361
  }
286
362
 
287
- function domainHash(domain: string, material: Uint8Array): Buffer {
288
- return createHash("sha256")
289
- .update(domain)
290
- .update(Buffer.from([0]))
291
- .update(material)
292
- .digest();
363
+ 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");
293
387
  }
294
388
 
295
- function shortRoomId(topic: Uint8Array): string {
296
- return Buffer.from(topic).subarray(0, 5).toString("base64url");
389
+ 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;
396
+ }
397
+
398
+ 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.");
297
402
  }
298
403
 
299
404
  function helloProof(