@narumitw/pi-chat 0.0.0 → 0.1.0

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,10 +1,16 @@
1
1
  import { createHash, createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
2
- import { normalizeNickname } from "./identity.js";
2
+ import type { ChatIdentity } from "./identity.js";
3
+ import { normalizeNickname, signIdentityPayload, verifyIdentityPayload } from "./identity.js";
3
4
 
4
- export const PROTOCOL_VERSION = 1;
5
+ export const PROTOCOL_VERSION = 2;
5
6
  export const MAX_FRAME_BYTES = 16 * 1024;
6
7
  export const MAX_MESSAGE_BYTES = 4 * 1024;
8
+ export const MAX_GOSSIP_HOPS = 8;
9
+ export const MAX_EVENT_AGE_MS = 5 * 60_000;
10
+ const MAX_EVENT_FUTURE_MS = 60_000;
7
11
  const PUBLIC_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/u;
12
+ const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
13
+ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
8
14
 
9
15
  export interface RoomDescriptor {
10
16
  kind: "private" | "public";
@@ -13,10 +19,11 @@ export interface RoomDescriptor {
13
19
  topic: Buffer;
14
20
  key: Buffer;
15
21
  invite?: string;
22
+ slug?: string;
16
23
  }
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,44 +31,63 @@ export interface HelloMessage {
24
31
  proof: string;
25
32
  }
26
33
 
27
- export interface ChatMessage {
28
- v: 1;
29
- type: "chat";
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;
30
42
  text: string;
31
- sentAt: number;
43
+ signature: string;
44
+ }
45
+
46
+ export interface PresenceEvent {
47
+ v: 2;
48
+ kind: "presence";
49
+ roomId: string;
50
+ origin: string;
32
51
  id: string;
52
+ issuedAt: number;
53
+ nickname: string;
54
+ status: "online" | "leaving";
55
+ signature: string;
33
56
  }
34
57
 
35
- export interface PresenceMessage {
36
- v: 1;
37
- type: "nickname-update" | "goodbye" | "ping" | "pong";
38
- nickname?: string;
58
+ export type RoomEvent = ChatEvent | PresenceEvent;
59
+ type UnsignedRoomEvent = Omit<ChatEvent, "signature"> | Omit<PresenceEvent, "signature">;
60
+
61
+ export interface GossipMessage {
62
+ v: 2;
63
+ type: "gossip";
64
+ event: RoomEvent;
65
+ hops: number;
39
66
  }
40
67
 
41
- export interface PeerListMessage {
42
- v: 1;
43
- type: "peer-list";
44
- publicKeys: string[];
68
+ export interface GoodbyeMessage {
69
+ v: 2;
70
+ type: "goodbye";
45
71
  }
46
72
 
47
- export type ProtocolMessage = HelloMessage | ChatMessage | PresenceMessage | PeerListMessage;
73
+ export type ProtocolMessage = HelloMessage | GossipMessage | GoodbyeMessage;
48
74
 
49
75
  export function createPrivateRoom(secret: Uint8Array): RoomDescriptor {
50
76
  if (secret.byteLength !== 32) throw new Error("Private room secrets must be 32 bytes.");
51
77
  const bytes = Buffer.from(secret);
52
- const topic = domainHash("pi-chat/discovery/private/v1", bytes);
78
+ const topic = domainHash("pi-chat/discovery/private/v2", bytes);
53
79
  return {
54
80
  kind: "private",
55
81
  label: `private ${shortRoomId(topic)}`,
56
82
  id: topic.toString("base64url"),
57
83
  topic,
58
84
  key: deriveRoomKey(bytes),
59
- invite: `pichat:v1:${bytes.toString("base64url")}`,
85
+ invite: `pichat:v2:${bytes.toString("base64url")}`,
60
86
  };
61
87
  }
62
88
 
63
89
  export function parseInvite(value: string): RoomDescriptor {
64
- const match = /^pichat:v1:([A-Za-z0-9_-]{43})$/u.exec(value.trim());
90
+ const match = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(value.trim());
65
91
  const encodedSecret = match?.[1];
66
92
  if (!encodedSecret) throw new Error("This is not a valid Pi Chat invite.");
67
93
  const secret = Buffer.from(encodedSecret, "base64url");
@@ -73,7 +99,7 @@ export function createPublicRoom(slug: string): RoomDescriptor {
73
99
  if (!PUBLIC_SLUG.test(slug)) {
74
100
  throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
75
101
  }
76
- const material = Buffer.from(`pi-chat/public/v1:${slug}`, "utf8");
102
+ const material = Buffer.from(`pi-chat/public/v2:${slug}`, "utf8");
77
103
  const topic = createHash("sha256").update(material).digest();
78
104
  return {
79
105
  kind: "public",
@@ -81,9 +107,28 @@ export function createPublicRoom(slug: string): RoomDescriptor {
81
107
  id: topic.toString("base64url"),
82
108
  topic,
83
109
  key: deriveRoomKey(material),
110
+ slug,
84
111
  };
85
112
  }
86
113
 
114
+ export function legacyRoomId(room: RoomDescriptor): string | undefined {
115
+ if (room.kind === "public" && room.slug) {
116
+ return createHash("sha256")
117
+ .update(Buffer.from(`pi-chat/public/v1:${room.slug}`, "utf8"))
118
+ .digest("base64url");
119
+ }
120
+ const encodedSecret = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(room.invite ?? "")?.[1];
121
+ if (!encodedSecret) return undefined;
122
+ const secret = Buffer.from(encodedSecret, "base64url");
123
+ return secret.length === 32
124
+ ? domainHash("pi-chat/discovery/private/v1", secret).toString("base64url")
125
+ : undefined;
126
+ }
127
+
128
+ export function isCompatibleRoomId(room: RoomDescriptor, id: string): boolean {
129
+ return room.id === id || legacyRoomId(room) === id;
130
+ }
131
+
87
132
  export function createHello(
88
133
  room: RoomDescriptor,
89
134
  nicknameValue: string,
@@ -99,7 +144,7 @@ export function createHello(
99
144
  if (nonceBytes.byteLength !== 16) throw new Error("Handshake nonces must be 16 bytes.");
100
145
  const nonce = Buffer.from(nonceBytes).toString("base64url");
101
146
  return {
102
- v: 1,
147
+ v: 2,
103
148
  type: "hello",
104
149
  roomId: room.id,
105
150
  nonce,
@@ -114,7 +159,7 @@ export function verifyHello(
114
159
  senderPublicKey: Uint8Array,
115
160
  receiverPublicKey: Uint8Array,
116
161
  ): HelloMessage | undefined {
117
- if (!isRecord(value) || value.v !== 1 || value.type !== "hello") return undefined;
162
+ if (!isRecord(value) || value.v !== 2 || value.type !== "hello") return undefined;
118
163
  if (
119
164
  value.roomId !== room.id ||
120
165
  typeof value.nonce !== "string" ||
@@ -131,7 +176,7 @@ export function verifyHello(
131
176
  return undefined;
132
177
  }
133
178
  return {
134
- v: 1,
179
+ v: 2,
135
180
  type: "hello",
136
181
  roomId: room.id,
137
182
  nonce: value.nonce,
@@ -140,37 +185,95 @@ export function verifyHello(
140
185
  };
141
186
  }
142
187
 
143
- export function createChatMessage(text: string, sentAt: number, id: string): ChatMessage {
188
+ export function createChatEvent(
189
+ room: RoomDescriptor,
190
+ identity: ChatIdentity,
191
+ nicknameValue: string,
192
+ text: string,
193
+ issuedAt: number,
194
+ id: string,
195
+ ): ChatEvent {
196
+ const nickname = normalizeNickname(nicknameValue);
197
+ if (!nickname) throw new Error("Nickname is invalid.");
144
198
  if (!text || Buffer.byteLength(text, "utf8") > MAX_MESSAGE_BYTES) {
145
199
  throw new Error("Chat message is empty or too large.");
146
200
  }
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 };
201
+ validateEventFields(issuedAt, id);
202
+ const unsigned: Omit<ChatEvent, "signature"> = {
203
+ v: 2,
204
+ kind: "chat",
205
+ roomId: room.id,
206
+ origin: identity.publicKey.toString("hex"),
207
+ id,
208
+ issuedAt,
209
+ nickname,
210
+ text,
211
+ };
212
+ return { ...unsigned, signature: signIdentityPayload(identity, canonicalEvent(unsigned)) };
213
+ }
214
+
215
+ export function createPresenceEvent(
216
+ room: RoomDescriptor,
217
+ identity: ChatIdentity,
218
+ nicknameValue: string,
219
+ status: PresenceEvent["status"],
220
+ issuedAt: number,
221
+ id: string,
222
+ ): PresenceEvent {
223
+ const nickname = normalizeNickname(nicknameValue);
224
+ if (!nickname) throw new Error("Nickname is invalid.");
225
+ if (status !== "online" && status !== "leaving") throw new Error("Presence state is invalid.");
226
+ validateEventFields(issuedAt, id);
227
+ const unsigned: Omit<PresenceEvent, "signature"> = {
228
+ v: 2,
229
+ kind: "presence",
230
+ roomId: room.id,
231
+ origin: identity.publicKey.toString("hex"),
232
+ id,
233
+ issuedAt,
234
+ nickname,
235
+ status,
236
+ };
237
+ return { ...unsigned, signature: signIdentityPayload(identity, canonicalEvent(unsigned)) };
238
+ }
239
+
240
+ export function createGossipMessage(
241
+ event: RoomEvent,
242
+ hops: number = MAX_GOSSIP_HOPS,
243
+ ): GossipMessage {
244
+ if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
245
+ throw new Error("Gossip hop budget is invalid.");
246
+ }
247
+ return { v: 2, type: "gossip", event, hops };
248
+ }
249
+
250
+ export function verifyRoomEvent(event: RoomEvent, room: RoomDescriptor, now = Date.now()): boolean {
251
+ const parsed = parseRoomEvent(event);
252
+ if (!parsed || parsed.roomId !== room.id) return false;
253
+ if (parsed.issuedAt < now - MAX_EVENT_AGE_MS || parsed.issuedAt > now + MAX_EVENT_FUTURE_MS) {
254
+ return false;
255
+ }
256
+ return verifyIdentityPayload(
257
+ Buffer.from(parsed.origin, "hex"),
258
+ canonicalEvent(withoutSignature(parsed)),
259
+ parsed.signature,
260
+ );
150
261
  }
151
262
 
152
263
  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") {
264
+ if (!isRecord(value) || typeof value.type !== "string") return undefined;
265
+ if (value.v === 2 && value.type === "gossip") {
155
266
  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)
267
+ !Number.isSafeInteger(value.hops) ||
268
+ (value.hops as number) < 1 ||
269
+ (value.hops as number) > MAX_GOSSIP_HOPS
162
270
  ) {
163
271
  return undefined;
164
272
  }
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
- };
273
+ const event = parseRoomEvent(value.event);
274
+ return event ? { v: 2, type: "gossip", event, hops: value.hops as number } : undefined;
172
275
  }
173
- if (value.type === "hello") {
276
+ if (value.v === 2 && value.type === "hello") {
174
277
  if (
175
278
  typeof value.roomId !== "string" ||
176
279
  typeof value.nonce !== "string" ||
@@ -181,23 +284,7 @@ export function parseProtocolMessage(value: unknown): ProtocolMessage | undefine
181
284
  }
182
285
  return value as unknown as HelloMessage;
183
286
  }
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
- }
287
+ if (value.v === 2 && value.type === "goodbye") return { v: 2, type: "goodbye" };
201
288
  return undefined;
202
289
  }
203
290
 
@@ -214,21 +301,33 @@ export class FrameDecoder {
214
301
 
215
302
  push(chunk: Uint8Array): ProtocolMessage[] {
216
303
  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)]);
304
+ const incoming = Buffer.from(chunk);
222
305
  const messages: ProtocolMessage[] = [];
223
- while (this.buffer.length >= 4) {
306
+ let offset = 0;
307
+ while (offset < incoming.length) {
308
+ if (this.buffer.length < 4) {
309
+ const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
310
+ this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
311
+ offset += headerBytes;
312
+ if (this.buffer.length < 4) break;
313
+ }
224
314
  const length = this.buffer.readUInt32BE(0);
225
315
  if (length > MAX_FRAME_BYTES) {
226
316
  this.buffer = Buffer.alloc(0);
227
317
  throw new Error("Protocol frame exceeds the size limit.");
228
318
  }
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);
319
+ const frameBytes = length + 4;
320
+ if (this.buffer.length < frameBytes) {
321
+ const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
322
+ this.buffer = Buffer.concat([
323
+ this.buffer,
324
+ incoming.subarray(offset, offset + payloadBytes),
325
+ ]);
326
+ offset += payloadBytes;
327
+ if (this.buffer.length < frameBytes) break;
328
+ }
329
+ const payload = this.buffer.subarray(4, frameBytes);
330
+ this.buffer = Buffer.alloc(0);
232
331
  let text: string;
233
332
  try {
234
333
  text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
@@ -278,9 +377,90 @@ export class PeerRateLimiter {
278
377
  }
279
378
  }
280
379
 
380
+ function parseRoomEvent(value: unknown): RoomEvent | undefined {
381
+ if (!isRecord(value) || value.v !== 2 || (value.kind !== "chat" && value.kind !== "presence")) {
382
+ return undefined;
383
+ }
384
+ const nickname = normalizeNickname(value.nickname);
385
+ if (
386
+ typeof value.roomId !== "string" ||
387
+ !PUBLIC_KEY.test(String(value.origin)) ||
388
+ !validId(value.id) ||
389
+ !Number.isSafeInteger(value.issuedAt) ||
390
+ (value.issuedAt as number) < 0 ||
391
+ !nickname ||
392
+ typeof value.signature !== "string" ||
393
+ !SIGNATURE.test(value.signature)
394
+ ) {
395
+ return undefined;
396
+ }
397
+ const common = {
398
+ v: 2 as const,
399
+ roomId: value.roomId,
400
+ origin: value.origin as string,
401
+ id: value.id,
402
+ issuedAt: value.issuedAt as number,
403
+ nickname,
404
+ signature: value.signature,
405
+ };
406
+ if (value.kind === "chat") {
407
+ if (
408
+ typeof value.text !== "string" ||
409
+ !value.text ||
410
+ Buffer.byteLength(value.text, "utf8") > MAX_MESSAGE_BYTES
411
+ ) {
412
+ return undefined;
413
+ }
414
+ return { ...common, kind: "chat", text: value.text };
415
+ }
416
+ if (value.status !== "online" && value.status !== "leaving") return undefined;
417
+ return { ...common, kind: "presence", status: value.status };
418
+ }
419
+
420
+ function canonicalEvent(event: UnsignedRoomEvent): Buffer {
421
+ const payload =
422
+ event.kind === "chat"
423
+ ? [
424
+ 2,
425
+ "chat",
426
+ event.roomId,
427
+ event.origin,
428
+ event.id,
429
+ event.issuedAt,
430
+ event.nickname,
431
+ event.text,
432
+ ]
433
+ : [
434
+ 2,
435
+ "presence",
436
+ event.roomId,
437
+ event.origin,
438
+ event.id,
439
+ event.issuedAt,
440
+ event.nickname,
441
+ event.status,
442
+ ];
443
+ return Buffer.from(JSON.stringify(payload), "utf8");
444
+ }
445
+
446
+ function withoutSignature(event: RoomEvent): UnsignedRoomEvent {
447
+ if (event.kind === "chat") {
448
+ const { signature: _signature, ...unsigned } = event;
449
+ return unsigned;
450
+ }
451
+ const { signature: _signature, ...unsigned } = event;
452
+ return unsigned;
453
+ }
454
+
455
+ function validateEventFields(issuedAt: number, id: string): void {
456
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
457
+ throw new Error("Message timestamp is invalid.");
458
+ if (!validId(id)) throw new Error("Message id is invalid.");
459
+ }
460
+
281
461
  function deriveRoomKey(material: Uint8Array): Buffer {
282
462
  return Buffer.from(
283
- hkdfSync("sha256", material, Buffer.from("pi-chat/v1"), Buffer.from("room-handshake"), 32),
463
+ hkdfSync("sha256", material, Buffer.from("pi-chat/v2"), Buffer.from("room-handshake"), 32),
284
464
  );
285
465
  }
286
466