@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
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ChatIdentity } from "./identity.js";
|
|
3
|
+
import { signIdentityPayload, verifyIdentityPayload } from "./identity.js";
|
|
4
|
+
import {
|
|
5
|
+
createPublicRoom,
|
|
6
|
+
MAX_EVENT_AGE_MS,
|
|
7
|
+
MAX_FRAME_BYTES,
|
|
8
|
+
MAX_GOSSIP_HOPS,
|
|
9
|
+
} from "./protocol.js";
|
|
10
|
+
|
|
11
|
+
const MAX_EVENT_FUTURE_MS = 60_000;
|
|
12
|
+
const DIRECTORY_RECORD_TTL_MS = 90_000;
|
|
13
|
+
const MAX_DIRECTORY_RECORDS = 4_096;
|
|
14
|
+
const MAX_DIRECTORY_ROOMS = 512;
|
|
15
|
+
const MAX_DIRECTORY_SEEN = 16_384;
|
|
16
|
+
const DIRECTORY_SEEN_TTL_MS = 10 * 60_000;
|
|
17
|
+
const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
|
|
18
|
+
const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
|
|
19
|
+
|
|
20
|
+
export const PUBLIC_ROOM_DIRECTORY_TOPIC = createHash("sha256")
|
|
21
|
+
.update("pi-chat/public-room-directory/v2", "utf8")
|
|
22
|
+
.digest();
|
|
23
|
+
|
|
24
|
+
export interface DirectoryPresence {
|
|
25
|
+
v: 2;
|
|
26
|
+
kind: "directory-presence";
|
|
27
|
+
slug: string;
|
|
28
|
+
origin: string;
|
|
29
|
+
id: string;
|
|
30
|
+
issuedAt: number;
|
|
31
|
+
status: "online" | "leaving";
|
|
32
|
+
signature: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface DirectoryWireMessage {
|
|
36
|
+
v: 2;
|
|
37
|
+
type: "directory";
|
|
38
|
+
event: DirectoryPresence;
|
|
39
|
+
hops: number;
|
|
40
|
+
partial?: true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface PublicRoomListing {
|
|
44
|
+
slug: string;
|
|
45
|
+
estimatedParticipants: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface PublicRoomBrowseResult {
|
|
49
|
+
rooms: PublicRoomListing[];
|
|
50
|
+
partial: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface DirectoryCatalogOptions {
|
|
54
|
+
now?: () => number;
|
|
55
|
+
maxRecords?: number;
|
|
56
|
+
maxRooms?: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface SeenRecord {
|
|
60
|
+
key: string;
|
|
61
|
+
expiresAt: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class DirectoryCatalog {
|
|
65
|
+
private readonly now: () => number;
|
|
66
|
+
private readonly maxRecords: number;
|
|
67
|
+
private readonly maxRooms: number;
|
|
68
|
+
private readonly records = new Map<string, DirectoryPresence>();
|
|
69
|
+
private readonly seen = new Map<string, number>();
|
|
70
|
+
private readonly seenOrder: SeenRecord[] = [];
|
|
71
|
+
private truncated = false;
|
|
72
|
+
|
|
73
|
+
constructor(options: DirectoryCatalogOptions = {}) {
|
|
74
|
+
this.now = options.now ?? Date.now;
|
|
75
|
+
this.maxRecords = positiveBound(options.maxRecords, MAX_DIRECTORY_RECORDS);
|
|
76
|
+
this.maxRooms = positiveBound(options.maxRooms, MAX_DIRECTORY_ROOMS);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
accept(event: DirectoryPresence): boolean {
|
|
80
|
+
const now = this.now();
|
|
81
|
+
if (!verifyDirectoryPresence(event, now)) return false;
|
|
82
|
+
const seenKey = `${event.origin}:${event.id}`;
|
|
83
|
+
if (this.hasSeen(seenKey)) return false;
|
|
84
|
+
this.remember(seenKey);
|
|
85
|
+
const existing = this.records.get(event.origin);
|
|
86
|
+
if (
|
|
87
|
+
existing &&
|
|
88
|
+
(existing.issuedAt > event.issuedAt ||
|
|
89
|
+
(existing.issuedAt === event.issuedAt && existing.id.localeCompare(event.id) >= 0))
|
|
90
|
+
) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
if (!existing && this.records.size >= this.maxRecords) {
|
|
94
|
+
this.truncated = true;
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
const knownSlugs = new Set(
|
|
98
|
+
[...this.records.values()]
|
|
99
|
+
.filter(({ status }) => status === "online")
|
|
100
|
+
.map(({ slug }) => slug),
|
|
101
|
+
);
|
|
102
|
+
if (
|
|
103
|
+
event.status === "online" &&
|
|
104
|
+
!knownSlugs.has(event.slug) &&
|
|
105
|
+
knownSlugs.size >= this.maxRooms
|
|
106
|
+
) {
|
|
107
|
+
this.truncated = true;
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
this.records.set(event.origin, event);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
snapshot(): PublicRoomBrowseResult {
|
|
115
|
+
this.prune();
|
|
116
|
+
const counts = new Map<string, number>();
|
|
117
|
+
for (const event of this.records.values()) {
|
|
118
|
+
if (event.status === "online") {
|
|
119
|
+
counts.set(event.slug, (counts.get(event.slug) ?? 0) + 1);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
rooms: sortDirectoryRooms(
|
|
124
|
+
[...counts].map(([slug, estimatedParticipants]) => ({ slug, estimatedParticipants })),
|
|
125
|
+
),
|
|
126
|
+
partial: this.truncated,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
currentEvents(): DirectoryPresence[] {
|
|
131
|
+
this.prune();
|
|
132
|
+
return [...this.records.values()].sort(
|
|
133
|
+
(left, right) => right.issuedAt - left.issuedAt || left.origin.localeCompare(right.origin),
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
markPartial(): void {
|
|
138
|
+
this.truncated = true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private prune(): void {
|
|
142
|
+
const now = this.now();
|
|
143
|
+
for (const [origin, event] of this.records) {
|
|
144
|
+
const ttl = event.status === "leaving" ? MAX_EVENT_AGE_MS : DIRECTORY_RECORD_TTL_MS;
|
|
145
|
+
if (event.issuedAt < now - ttl) this.records.delete(origin);
|
|
146
|
+
}
|
|
147
|
+
this.pruneSeen();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private hasSeen(key: string): boolean {
|
|
151
|
+
this.pruneSeen();
|
|
152
|
+
return this.seen.has(key);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private remember(key: string): void {
|
|
156
|
+
const expiresAt = this.now() + DIRECTORY_SEEN_TTL_MS;
|
|
157
|
+
this.seen.set(key, expiresAt);
|
|
158
|
+
this.seenOrder.push({ key, expiresAt });
|
|
159
|
+
while (this.seen.size > MAX_DIRECTORY_SEEN) {
|
|
160
|
+
const removed = this.seenOrder.shift();
|
|
161
|
+
if (removed && this.seen.get(removed.key) === removed.expiresAt) {
|
|
162
|
+
this.seen.delete(removed.key);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private pruneSeen(): void {
|
|
168
|
+
const now = this.now();
|
|
169
|
+
while (this.seenOrder[0] && this.seenOrder[0].expiresAt <= now) {
|
|
170
|
+
const removed = this.seenOrder.shift();
|
|
171
|
+
if (removed && this.seen.get(removed.key) === removed.expiresAt) {
|
|
172
|
+
this.seen.delete(removed.key);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function createDirectoryPresence(
|
|
179
|
+
identity: ChatIdentity,
|
|
180
|
+
slugValue: string,
|
|
181
|
+
status: DirectoryPresence["status"],
|
|
182
|
+
issuedAt: number,
|
|
183
|
+
id: string,
|
|
184
|
+
): DirectoryPresence {
|
|
185
|
+
const slug = validatedSlug(slugValue);
|
|
186
|
+
if (!slug) throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
|
|
187
|
+
if (status !== "online" && status !== "leaving") {
|
|
188
|
+
throw new Error("Directory presence state is invalid.");
|
|
189
|
+
}
|
|
190
|
+
if (!Number.isSafeInteger(issuedAt) || issuedAt < 0) {
|
|
191
|
+
throw new Error("Directory presence timestamp is invalid.");
|
|
192
|
+
}
|
|
193
|
+
if (!validId(id)) throw new Error("Directory presence id is invalid.");
|
|
194
|
+
const unsigned: Omit<DirectoryPresence, "signature"> = {
|
|
195
|
+
v: 2,
|
|
196
|
+
kind: "directory-presence",
|
|
197
|
+
slug,
|
|
198
|
+
origin: identity.publicKey.toString("hex"),
|
|
199
|
+
id,
|
|
200
|
+
issuedAt,
|
|
201
|
+
status,
|
|
202
|
+
};
|
|
203
|
+
return {
|
|
204
|
+
...unsigned,
|
|
205
|
+
signature: signIdentityPayload(identity, canonicalDirectoryPresence(unsigned)),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function verifyDirectoryPresence(value: DirectoryPresence, now = Date.now()): boolean {
|
|
210
|
+
const event = parseDirectoryPresence(value);
|
|
211
|
+
if (!event) return false;
|
|
212
|
+
if (event.issuedAt < now - MAX_EVENT_AGE_MS || event.issuedAt > now + MAX_EVENT_FUTURE_MS) {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
const { signature, ...unsigned } = event;
|
|
216
|
+
return verifyIdentityPayload(
|
|
217
|
+
Buffer.from(event.origin, "hex"),
|
|
218
|
+
canonicalDirectoryPresence(unsigned),
|
|
219
|
+
signature,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function createDirectoryWireMessage(
|
|
224
|
+
event: DirectoryPresence,
|
|
225
|
+
hops = MAX_GOSSIP_HOPS,
|
|
226
|
+
partial = false,
|
|
227
|
+
): DirectoryWireMessage {
|
|
228
|
+
if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
|
|
229
|
+
throw new Error("Directory gossip hop budget is invalid.");
|
|
230
|
+
}
|
|
231
|
+
return { v: 2, type: "directory", event, hops, ...(partial ? { partial: true as const } : {}) };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function parseDirectoryWireMessage(value: unknown): DirectoryWireMessage | undefined {
|
|
235
|
+
if (
|
|
236
|
+
!isRecord(value) ||
|
|
237
|
+
value.v !== 2 ||
|
|
238
|
+
value.type !== "directory" ||
|
|
239
|
+
!Number.isSafeInteger(value.hops) ||
|
|
240
|
+
(value.hops as number) < 1 ||
|
|
241
|
+
(value.hops as number) > MAX_GOSSIP_HOPS
|
|
242
|
+
) {
|
|
243
|
+
return undefined;
|
|
244
|
+
}
|
|
245
|
+
if (value.partial !== undefined && value.partial !== true) return undefined;
|
|
246
|
+
const event = parseDirectoryPresence(value.event);
|
|
247
|
+
return event
|
|
248
|
+
? {
|
|
249
|
+
v: 2,
|
|
250
|
+
type: "directory",
|
|
251
|
+
event,
|
|
252
|
+
hops: value.hops as number,
|
|
253
|
+
...(value.partial === true ? { partial: true as const } : {}),
|
|
254
|
+
}
|
|
255
|
+
: undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function encodeDirectoryFrame(message: DirectoryWireMessage): Buffer {
|
|
259
|
+
const payload = Buffer.from(JSON.stringify(message), "utf8");
|
|
260
|
+
if (payload.length > MAX_FRAME_BYTES) throw new Error("Directory frame exceeds the size limit.");
|
|
261
|
+
const header = Buffer.allocUnsafe(4);
|
|
262
|
+
header.writeUInt32BE(payload.length);
|
|
263
|
+
return Buffer.concat([header, payload]);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export class DirectoryFrameDecoder {
|
|
267
|
+
private buffer = Buffer.alloc(0);
|
|
268
|
+
|
|
269
|
+
push(chunk: Uint8Array): DirectoryWireMessage[] {
|
|
270
|
+
if (chunk.byteLength === 0) return [];
|
|
271
|
+
const incoming = Buffer.from(chunk);
|
|
272
|
+
const messages: DirectoryWireMessage[] = [];
|
|
273
|
+
let offset = 0;
|
|
274
|
+
while (offset < incoming.length) {
|
|
275
|
+
if (this.buffer.length < 4) {
|
|
276
|
+
const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
|
|
277
|
+
this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
|
|
278
|
+
offset += headerBytes;
|
|
279
|
+
if (this.buffer.length < 4) break;
|
|
280
|
+
}
|
|
281
|
+
const length = this.buffer.readUInt32BE(0);
|
|
282
|
+
if (length > MAX_FRAME_BYTES) {
|
|
283
|
+
this.buffer = Buffer.alloc(0);
|
|
284
|
+
throw new Error("Directory frame exceeds the size limit.");
|
|
285
|
+
}
|
|
286
|
+
const frameBytes = length + 4;
|
|
287
|
+
if (this.buffer.length < frameBytes) {
|
|
288
|
+
const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
|
|
289
|
+
this.buffer = Buffer.concat([
|
|
290
|
+
this.buffer,
|
|
291
|
+
incoming.subarray(offset, offset + payloadBytes),
|
|
292
|
+
]);
|
|
293
|
+
offset += payloadBytes;
|
|
294
|
+
if (this.buffer.length < frameBytes) break;
|
|
295
|
+
}
|
|
296
|
+
const payload = this.buffer.subarray(4, frameBytes);
|
|
297
|
+
this.buffer = Buffer.alloc(0);
|
|
298
|
+
let value: unknown;
|
|
299
|
+
try {
|
|
300
|
+
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload)) as unknown;
|
|
301
|
+
} catch {
|
|
302
|
+
throw new Error("Directory frame is not valid UTF-8 JSON.");
|
|
303
|
+
}
|
|
304
|
+
const parsed = parseDirectoryWireMessage(value);
|
|
305
|
+
if (!parsed) throw new Error("Directory frame has an invalid message shape.");
|
|
306
|
+
messages.push(parsed);
|
|
307
|
+
}
|
|
308
|
+
return messages;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function sortDirectoryRooms(rooms: readonly PublicRoomListing[]): PublicRoomListing[] {
|
|
313
|
+
return [...rooms].sort(
|
|
314
|
+
(left, right) =>
|
|
315
|
+
right.estimatedParticipants - left.estimatedParticipants ||
|
|
316
|
+
left.slug.localeCompare(right.slug),
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function parseDirectoryPresence(value: unknown): DirectoryPresence | undefined {
|
|
321
|
+
if (
|
|
322
|
+
!isRecord(value) ||
|
|
323
|
+
value.v !== 2 ||
|
|
324
|
+
value.kind !== "directory-presence" ||
|
|
325
|
+
!validatedSlug(value.slug) ||
|
|
326
|
+
!PUBLIC_KEY.test(String(value.origin)) ||
|
|
327
|
+
!validId(value.id) ||
|
|
328
|
+
!Number.isSafeInteger(value.issuedAt) ||
|
|
329
|
+
(value.issuedAt as number) < 0 ||
|
|
330
|
+
(value.status !== "online" && value.status !== "leaving") ||
|
|
331
|
+
typeof value.signature !== "string" ||
|
|
332
|
+
!SIGNATURE.test(value.signature)
|
|
333
|
+
) {
|
|
334
|
+
return undefined;
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
v: 2,
|
|
338
|
+
kind: "directory-presence",
|
|
339
|
+
slug: value.slug as string,
|
|
340
|
+
origin: value.origin as string,
|
|
341
|
+
id: value.id,
|
|
342
|
+
issuedAt: value.issuedAt as number,
|
|
343
|
+
status: value.status,
|
|
344
|
+
signature: value.signature,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function canonicalDirectoryPresence(event: Omit<DirectoryPresence, "signature">): Buffer {
|
|
349
|
+
return Buffer.from(
|
|
350
|
+
JSON.stringify([
|
|
351
|
+
2,
|
|
352
|
+
"directory-presence",
|
|
353
|
+
event.slug,
|
|
354
|
+
event.origin,
|
|
355
|
+
event.id,
|
|
356
|
+
event.issuedAt,
|
|
357
|
+
event.status,
|
|
358
|
+
]),
|
|
359
|
+
"utf8",
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function validatedSlug(value: unknown): string | undefined {
|
|
364
|
+
if (typeof value !== "string") return undefined;
|
|
365
|
+
try {
|
|
366
|
+
return createPublicRoom(value).slug;
|
|
367
|
+
} catch {
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function positiveBound(value: number | undefined, fallback: number): number {
|
|
373
|
+
return Number.isSafeInteger(value) && (value ?? 0) > 0
|
|
374
|
+
? Math.min(value ?? fallback, fallback)
|
|
375
|
+
: fallback;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function validId(value: unknown): value is string {
|
|
379
|
+
return (
|
|
380
|
+
typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value)
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
385
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
386
|
+
}
|
package/src/room.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createHash, hkdfSync } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const PUBLIC_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/u;
|
|
4
|
+
|
|
5
|
+
export interface RoomDescriptor {
|
|
6
|
+
kind: "private" | "public";
|
|
7
|
+
label: string;
|
|
8
|
+
id: string;
|
|
9
|
+
topic: Buffer;
|
|
10
|
+
key: Buffer;
|
|
11
|
+
invite?: string;
|
|
12
|
+
slug?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function createPrivateRoom(secret: Uint8Array): RoomDescriptor {
|
|
16
|
+
if (secret.byteLength !== 32) throw new Error("Private room secrets must be 32 bytes.");
|
|
17
|
+
const bytes = Buffer.from(secret);
|
|
18
|
+
const topic = domainHash("pi-chat/discovery/private/v2", bytes);
|
|
19
|
+
return {
|
|
20
|
+
kind: "private",
|
|
21
|
+
label: `private ${shortRoomId(topic)}`,
|
|
22
|
+
id: topic.toString("base64url"),
|
|
23
|
+
topic,
|
|
24
|
+
key: deriveRoomKey(bytes),
|
|
25
|
+
invite: `pichat:v2:${bytes.toString("base64url")}`,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function parseInvite(value: string): RoomDescriptor {
|
|
30
|
+
const match = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(value.trim());
|
|
31
|
+
const encodedSecret = match?.[1];
|
|
32
|
+
if (!encodedSecret) throw new Error("This is not a valid Pi Chat invite.");
|
|
33
|
+
const secret = Buffer.from(encodedSecret, "base64url");
|
|
34
|
+
if (secret.length !== 32) throw new Error("This is not a valid Pi Chat invite.");
|
|
35
|
+
return createPrivateRoom(secret);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createPublicRoom(slug: string): RoomDescriptor {
|
|
39
|
+
if (!PUBLIC_SLUG.test(slug)) {
|
|
40
|
+
throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
|
|
41
|
+
}
|
|
42
|
+
const material = Buffer.from(`pi-chat/public/v2:${slug}`, "utf8");
|
|
43
|
+
const topic = createHash("sha256").update(material).digest();
|
|
44
|
+
return {
|
|
45
|
+
kind: "public",
|
|
46
|
+
label: `#${slug}`,
|
|
47
|
+
id: topic.toString("base64url"),
|
|
48
|
+
topic,
|
|
49
|
+
key: deriveRoomKey(material),
|
|
50
|
+
slug,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function legacyRoomId(room: RoomDescriptor): string | undefined {
|
|
55
|
+
if (room.kind === "public" && room.slug) {
|
|
56
|
+
return createHash("sha256")
|
|
57
|
+
.update(Buffer.from(`pi-chat/public/v1:${room.slug}`, "utf8"))
|
|
58
|
+
.digest("base64url");
|
|
59
|
+
}
|
|
60
|
+
const encodedSecret = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(room.invite ?? "")?.[1];
|
|
61
|
+
if (!encodedSecret) return undefined;
|
|
62
|
+
const secret = Buffer.from(encodedSecret, "base64url");
|
|
63
|
+
return secret.length === 32
|
|
64
|
+
? domainHash("pi-chat/discovery/private/v1", secret).toString("base64url")
|
|
65
|
+
: undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function isCompatibleRoomId(room: RoomDescriptor, id: string): boolean {
|
|
69
|
+
return room.id === id || legacyRoomId(room) === id;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function deriveRoomKey(material: Uint8Array): Buffer {
|
|
73
|
+
return Buffer.from(
|
|
74
|
+
hkdfSync("sha256", material, Buffer.from("pi-chat/v2"), Buffer.from("room-handshake"), 32),
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function domainHash(domain: string, material: Uint8Array): Buffer {
|
|
79
|
+
return createHash("sha256")
|
|
80
|
+
.update(domain)
|
|
81
|
+
.update(Buffer.from([0]))
|
|
82
|
+
.update(material)
|
|
83
|
+
.digest();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function shortRoomId(topic: Uint8Array): string {
|
|
87
|
+
return Buffer.from(topic).subarray(0, 5).toString("base64url");
|
|
88
|
+
}
|
package/src/settings.ts
CHANGED
|
@@ -3,8 +3,8 @@ import { constants } from "node:fs";
|
|
|
3
3
|
import { chmod, lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
4
4
|
import { basename, dirname, join } from "node:path";
|
|
5
5
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
-
import { normalizeNickname } from "./
|
|
7
|
-
import { createPublicRoom, parseInvite, type RoomDescriptor } from "./
|
|
6
|
+
import { normalizeNickname } from "./nickname.js";
|
|
7
|
+
import { createPublicRoom, isCompatibleRoomId, parseInvite, type RoomDescriptor } from "./room.js";
|
|
8
8
|
|
|
9
9
|
export const CHAT_SETTINGS_FILE = "pi-chat.json";
|
|
10
10
|
const MAX_SETTINGS_BYTES = 64 * 1024;
|
|
@@ -40,6 +40,7 @@ export interface UpdateChatSettingsOptions {
|
|
|
40
40
|
settingsPath?: string;
|
|
41
41
|
signal?: AbortSignal;
|
|
42
42
|
beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
|
|
43
|
+
setPrivateMode?: (path: string) => Promise<void>;
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
type SettingsDocument = Record<string, unknown>;
|
|
@@ -239,8 +240,11 @@ async function publish(
|
|
|
239
240
|
});
|
|
240
241
|
await options.beforeRename?.(temporaryPath, path);
|
|
241
242
|
options.signal?.throwIfAborted();
|
|
243
|
+
if (process.platform !== "win32") {
|
|
244
|
+
await (options.setPrivateMode ?? ((target) => chmod(target, 0o600)))(temporaryPath);
|
|
245
|
+
options.signal?.throwIfAborted();
|
|
246
|
+
}
|
|
242
247
|
await rename(temporaryPath, path);
|
|
243
|
-
if (process.platform !== "win32") await chmod(path, 0o600);
|
|
244
248
|
} catch (error) {
|
|
245
249
|
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
246
250
|
throw error;
|
|
@@ -254,14 +258,21 @@ function normalizeResumeSettings(value: unknown): ChatResumeSettings | undefined
|
|
|
254
258
|
if (value.surface !== "chat" && value.surface !== "pi") return undefined;
|
|
255
259
|
const rooms: RememberedRoom[] = [];
|
|
256
260
|
const ids = new Set<string>();
|
|
261
|
+
let activeRoomId: string | undefined;
|
|
257
262
|
for (const candidate of value.rooms) {
|
|
258
263
|
const room = normalizeRememberedRoom(candidate);
|
|
259
264
|
if (!room || ids.has(room.id)) return undefined;
|
|
260
265
|
ids.add(room.id);
|
|
261
266
|
rooms.push(room);
|
|
267
|
+
if (
|
|
268
|
+
isRecord(candidate) &&
|
|
269
|
+
(candidate.id === value.activeRoomId || room.id === value.activeRoomId)
|
|
270
|
+
) {
|
|
271
|
+
activeRoomId = room.id;
|
|
272
|
+
}
|
|
262
273
|
}
|
|
263
|
-
if (!ids.has(
|
|
264
|
-
return { rooms, activeRoomId
|
|
274
|
+
if (!activeRoomId || !ids.has(activeRoomId)) return undefined;
|
|
275
|
+
return { rooms, activeRoomId, surface: value.surface };
|
|
265
276
|
}
|
|
266
277
|
|
|
267
278
|
function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
|
|
@@ -273,7 +284,9 @@ function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
|
|
|
273
284
|
!Object.hasOwn(value, "invite")
|
|
274
285
|
) {
|
|
275
286
|
const room = createPublicRoom(value.slug);
|
|
276
|
-
return room
|
|
287
|
+
return isCompatibleRoomId(room, value.id)
|
|
288
|
+
? { id: room.id, kind: "public", slug: value.slug }
|
|
289
|
+
: undefined;
|
|
277
290
|
}
|
|
278
291
|
if (
|
|
279
292
|
value.kind === "private" &&
|
|
@@ -281,7 +294,7 @@ function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
|
|
|
281
294
|
!Object.hasOwn(value, "slug")
|
|
282
295
|
) {
|
|
283
296
|
const room = parseInvite(value.invite);
|
|
284
|
-
return room
|
|
297
|
+
return isCompatibleRoomId(room, value.id)
|
|
285
298
|
? { id: room.id, kind: "private", invite: value.invite }
|
|
286
299
|
: undefined;
|
|
287
300
|
}
|
|
@@ -296,9 +309,8 @@ function mergeResumeDocument(current: unknown, next: ChatResumeSettings): Settin
|
|
|
296
309
|
const existingRooms = new Map<string, SettingsDocument>();
|
|
297
310
|
if (Array.isArray(currentResume.rooms)) {
|
|
298
311
|
for (const candidate of currentResume.rooms) {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
312
|
+
const normalized = normalizeRememberedRoom(candidate);
|
|
313
|
+
if (normalized && isRecord(candidate)) existingRooms.set(normalized.id, candidate);
|
|
302
314
|
}
|
|
303
315
|
}
|
|
304
316
|
return {
|
package/src/widget.ts
CHANGED
|
@@ -15,8 +15,8 @@ export function renderChatWidget(
|
|
|
15
15
|
const safeWidth = Math.max(1, width);
|
|
16
16
|
if (mode === "dock") return renderRoomDock(snapshot, safeWidth, terminalRows, theme);
|
|
17
17
|
|
|
18
|
-
const
|
|
19
|
-
const presence =
|
|
18
|
+
const participants = snapshot.participants.length;
|
|
19
|
+
const presence = `${participants} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`;
|
|
20
20
|
const unread = snapshot.unread > 0 ? `${snapshot.unread} unread · ` : "";
|
|
21
21
|
const attention = snapshot.state === "degraded" ? " · reconnecting" : "";
|
|
22
22
|
const header = truncateToWidth(
|
|
@@ -42,16 +42,15 @@ function renderRoomDock(
|
|
|
42
42
|
terminalRows: number,
|
|
43
43
|
theme: Theme,
|
|
44
44
|
): string[] {
|
|
45
|
-
const
|
|
46
|
-
const peerText = `${peers} direct peer${peers === 1 ? "" : "s"}`;
|
|
45
|
+
const participantText = `${snapshot.participants.length} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`;
|
|
47
46
|
const stateText =
|
|
48
47
|
snapshot.state === "connecting"
|
|
49
48
|
? "joining…"
|
|
50
49
|
: snapshot.state === "degraded"
|
|
51
|
-
? `reconnecting · ${
|
|
52
|
-
:
|
|
53
|
-
? "waiting for
|
|
54
|
-
:
|
|
50
|
+
? `reconnecting · ${participantText}`
|
|
51
|
+
: snapshot.directNeighbors === 0
|
|
52
|
+
? "waiting for neighbors"
|
|
53
|
+
: participantText;
|
|
55
54
|
const unread = snapshot.unread > 0 ? ` · ${snapshot.unread} unread` : "";
|
|
56
55
|
const roomTitle = `ROOM ${sanitizeSingleLine(snapshot.room.label)}`;
|
|
57
56
|
const status = `${stateText}${unread}`;
|