@narumitw/pi-chat 0.0.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/LICENSE +21 -0
- package/README.md +293 -0
- package/package.json +55 -0
- package/src/chat-session.ts +436 -0
- package/src/chat-view.ts +256 -0
- package/src/external.d.ts +69 -0
- package/src/identity.ts +80 -0
- package/src/index.ts +1 -0
- package/src/menu.ts +490 -0
- package/src/network.ts +201 -0
- package/src/pi-chat.ts +647 -0
- package/src/protocol.ts +325 -0
- package/src/settings.ts +330 -0
- package/src/text.ts +73 -0
- package/src/widget.ts +87 -0
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { createHash, createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { normalizeNickname } from "./identity.js";
|
|
3
|
+
|
|
4
|
+
export const PROTOCOL_VERSION = 1;
|
|
5
|
+
export const MAX_FRAME_BYTES = 16 * 1024;
|
|
6
|
+
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
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface HelloMessage {
|
|
19
|
+
v: 1;
|
|
20
|
+
type: "hello";
|
|
21
|
+
roomId: string;
|
|
22
|
+
nonce: string;
|
|
23
|
+
nickname: string;
|
|
24
|
+
proof: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ChatMessage {
|
|
28
|
+
v: 1;
|
|
29
|
+
type: "chat";
|
|
30
|
+
text: string;
|
|
31
|
+
sentAt: number;
|
|
32
|
+
id: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
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[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type ProtocolMessage = HelloMessage | ChatMessage | PresenceMessage | PeerListMessage;
|
|
48
|
+
|
|
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
|
+
}
|
|
62
|
+
|
|
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);
|
|
70
|
+
}
|
|
71
|
+
|
|
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
|
+
}
|
|
86
|
+
|
|
87
|
+
export function createHello(
|
|
88
|
+
room: RoomDescriptor,
|
|
89
|
+
nicknameValue: string,
|
|
90
|
+
senderPublicKey: Uint8Array,
|
|
91
|
+
receiverPublicKey: Uint8Array,
|
|
92
|
+
nonceBytes: Uint8Array,
|
|
93
|
+
): HelloMessage {
|
|
94
|
+
const nickname = normalizeNickname(nicknameValue);
|
|
95
|
+
if (!nickname) throw new Error("Nickname is invalid.");
|
|
96
|
+
if (senderPublicKey.byteLength !== 32 || receiverPublicKey.byteLength !== 32) {
|
|
97
|
+
throw new Error("Peer public keys must be 32 bytes.");
|
|
98
|
+
}
|
|
99
|
+
if (nonceBytes.byteLength !== 16) throw new Error("Handshake nonces must be 16 bytes.");
|
|
100
|
+
const nonce = Buffer.from(nonceBytes).toString("base64url");
|
|
101
|
+
return {
|
|
102
|
+
v: 1,
|
|
103
|
+
type: "hello",
|
|
104
|
+
roomId: room.id,
|
|
105
|
+
nonce,
|
|
106
|
+
nickname,
|
|
107
|
+
proof: helloProof(room, nickname, senderPublicKey, receiverPublicKey, nonce),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function verifyHello(
|
|
112
|
+
value: unknown,
|
|
113
|
+
room: RoomDescriptor,
|
|
114
|
+
senderPublicKey: Uint8Array,
|
|
115
|
+
receiverPublicKey: Uint8Array,
|
|
116
|
+
): HelloMessage | undefined {
|
|
117
|
+
if (!isRecord(value) || value.v !== 1 || value.type !== "hello") return undefined;
|
|
118
|
+
if (
|
|
119
|
+
value.roomId !== room.id ||
|
|
120
|
+
typeof value.nonce !== "string" ||
|
|
121
|
+
typeof value.proof !== "string"
|
|
122
|
+
) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
const nickname = normalizeNickname(value.nickname);
|
|
126
|
+
if (!nickname || !/^[A-Za-z0-9_-]{22}$/u.test(value.nonce)) return undefined;
|
|
127
|
+
const expected = helloProof(room, nickname, senderPublicKey, receiverPublicKey, value.nonce);
|
|
128
|
+
const actualBytes = Buffer.from(value.proof, "base64url");
|
|
129
|
+
const expectedBytes = Buffer.from(expected, "base64url");
|
|
130
|
+
if (actualBytes.length !== expectedBytes.length || !timingSafeEqual(actualBytes, expectedBytes)) {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
v: 1,
|
|
135
|
+
type: "hello",
|
|
136
|
+
roomId: room.id,
|
|
137
|
+
nonce: value.nonce,
|
|
138
|
+
nickname,
|
|
139
|
+
proof: value.proof,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function createChatMessage(text: string, sentAt: number, id: string): ChatMessage {
|
|
144
|
+
if (!text || Buffer.byteLength(text, "utf8") > MAX_MESSAGE_BYTES) {
|
|
145
|
+
throw new Error("Chat message is empty or too large.");
|
|
146
|
+
}
|
|
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 };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
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") {
|
|
155
|
+
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)
|
|
162
|
+
) {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
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
|
+
};
|
|
172
|
+
}
|
|
173
|
+
if (value.type === "hello") {
|
|
174
|
+
if (
|
|
175
|
+
typeof value.roomId !== "string" ||
|
|
176
|
+
typeof value.nonce !== "string" ||
|
|
177
|
+
typeof value.proof !== "string" ||
|
|
178
|
+
!normalizeNickname(value.nickname)
|
|
179
|
+
) {
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
return value as unknown as HelloMessage;
|
|
183
|
+
}
|
|
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
|
+
}
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function encodeFrame(message: ProtocolMessage): Buffer {
|
|
205
|
+
const payload = Buffer.from(JSON.stringify(message), "utf8");
|
|
206
|
+
if (payload.length > MAX_FRAME_BYTES) throw new Error("Protocol frame exceeds the size limit.");
|
|
207
|
+
const header = Buffer.allocUnsafe(4);
|
|
208
|
+
header.writeUInt32BE(payload.length);
|
|
209
|
+
return Buffer.concat([header, payload]);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export class FrameDecoder {
|
|
213
|
+
private buffer = Buffer.alloc(0);
|
|
214
|
+
|
|
215
|
+
push(chunk: Uint8Array): ProtocolMessage[] {
|
|
216
|
+
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)]);
|
|
222
|
+
const messages: ProtocolMessage[] = [];
|
|
223
|
+
while (this.buffer.length >= 4) {
|
|
224
|
+
const length = this.buffer.readUInt32BE(0);
|
|
225
|
+
if (length > MAX_FRAME_BYTES) {
|
|
226
|
+
this.buffer = Buffer.alloc(0);
|
|
227
|
+
throw new Error("Protocol frame exceeds the size limit.");
|
|
228
|
+
}
|
|
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);
|
|
232
|
+
let text: string;
|
|
233
|
+
try {
|
|
234
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
|
|
235
|
+
} catch {
|
|
236
|
+
throw new Error("Protocol frame contains invalid UTF-8.");
|
|
237
|
+
}
|
|
238
|
+
let value: unknown;
|
|
239
|
+
try {
|
|
240
|
+
value = JSON.parse(text) as unknown;
|
|
241
|
+
} catch {
|
|
242
|
+
throw new Error("Protocol frame contains invalid JSON.");
|
|
243
|
+
}
|
|
244
|
+
const parsed = parseProtocolMessage(value);
|
|
245
|
+
if (!parsed) throw new Error("Protocol frame has an invalid message shape.");
|
|
246
|
+
messages.push(parsed);
|
|
247
|
+
}
|
|
248
|
+
return messages;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export class PeerRateLimiter {
|
|
253
|
+
private tokens: number;
|
|
254
|
+
private lastRefill: number;
|
|
255
|
+
private readonly burst: number;
|
|
256
|
+
private readonly refillPerSecond: number;
|
|
257
|
+
private readonly now: () => number;
|
|
258
|
+
|
|
259
|
+
constructor(options: { burst: number; refillPerSecond: number; now?: () => number }) {
|
|
260
|
+
if (options.burst <= 0 || options.refillPerSecond <= 0) {
|
|
261
|
+
throw new Error("Rate limiter values must be positive.");
|
|
262
|
+
}
|
|
263
|
+
this.burst = options.burst;
|
|
264
|
+
this.tokens = options.burst;
|
|
265
|
+
this.refillPerSecond = options.refillPerSecond;
|
|
266
|
+
this.now = options.now ?? Date.now;
|
|
267
|
+
this.lastRefill = this.now();
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
accept(): boolean {
|
|
271
|
+
const current = this.now();
|
|
272
|
+
const elapsed = Math.max(0, current - this.lastRefill);
|
|
273
|
+
this.lastRefill = current;
|
|
274
|
+
this.tokens = Math.min(this.burst, this.tokens + (elapsed / 1000) * this.refillPerSecond);
|
|
275
|
+
if (this.tokens < 1) return false;
|
|
276
|
+
this.tokens -= 1;
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
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
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
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();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function shortRoomId(topic: Uint8Array): string {
|
|
296
|
+
return Buffer.from(topic).subarray(0, 5).toString("base64url");
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function helloProof(
|
|
300
|
+
room: RoomDescriptor,
|
|
301
|
+
nickname: string,
|
|
302
|
+
senderPublicKey: Uint8Array,
|
|
303
|
+
receiverPublicKey: Uint8Array,
|
|
304
|
+
nonce: string,
|
|
305
|
+
): string {
|
|
306
|
+
const canonical = JSON.stringify([
|
|
307
|
+
PROTOCOL_VERSION,
|
|
308
|
+
room.id,
|
|
309
|
+
nonce,
|
|
310
|
+
nickname,
|
|
311
|
+
Buffer.from(senderPublicKey).toString("hex"),
|
|
312
|
+
Buffer.from(receiverPublicKey).toString("hex"),
|
|
313
|
+
]);
|
|
314
|
+
return createHmac("sha256", room.key).update(canonical).digest("base64url");
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function validId(value: unknown): value is string {
|
|
318
|
+
return (
|
|
319
|
+
typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value)
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
324
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
325
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { normalizeNickname } from "./identity.js";
|
|
7
|
+
import { createPublicRoom, parseInvite, type RoomDescriptor } from "./protocol.js";
|
|
8
|
+
|
|
9
|
+
export const CHAT_SETTINGS_FILE = "pi-chat.json";
|
|
10
|
+
const MAX_SETTINGS_BYTES = 64 * 1024;
|
|
11
|
+
export type WidgetMode = "dock" | "count" | "latest" | "off";
|
|
12
|
+
|
|
13
|
+
export type RememberedRoom =
|
|
14
|
+
| { id: string; kind: "public"; slug: string }
|
|
15
|
+
| { id: string; kind: "private"; invite: string };
|
|
16
|
+
|
|
17
|
+
export interface ChatResumeSettings {
|
|
18
|
+
rooms: RememberedRoom[];
|
|
19
|
+
activeRoomId: string;
|
|
20
|
+
surface: "chat" | "pi";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ChatSettings {
|
|
24
|
+
nickname?: string;
|
|
25
|
+
identitySeed?: string;
|
|
26
|
+
widgetMode?: WidgetMode;
|
|
27
|
+
resume?: ChatResumeSettings;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type ChatSettingsPatch = Partial<Omit<ChatSettings, "resume">> & {
|
|
31
|
+
resume?: ChatResumeSettings | null;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type ChatSettingsLoadResult =
|
|
35
|
+
| { kind: "missing" }
|
|
36
|
+
| { kind: "invalid"; reason: string }
|
|
37
|
+
| { kind: "loaded"; settings: ChatSettings };
|
|
38
|
+
|
|
39
|
+
export interface UpdateChatSettingsOptions {
|
|
40
|
+
settingsPath?: string;
|
|
41
|
+
signal?: AbortSignal;
|
|
42
|
+
beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type SettingsDocument = Record<string, unknown>;
|
|
46
|
+
const queues = new Map<string, Promise<void>>();
|
|
47
|
+
|
|
48
|
+
export function chatSettingsPath(): string {
|
|
49
|
+
return join(getAgentDir(), CHAT_SETTINGS_FILE);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function normalizeChatSettings(value: unknown): ChatSettings | undefined {
|
|
53
|
+
if (!isRecord(value)) return undefined;
|
|
54
|
+
const settings: ChatSettings = {};
|
|
55
|
+
if (Object.hasOwn(value, "nickname")) {
|
|
56
|
+
const nickname = normalizeNickname(value.nickname);
|
|
57
|
+
if (!nickname) return undefined;
|
|
58
|
+
settings.nickname = nickname;
|
|
59
|
+
}
|
|
60
|
+
if (Object.hasOwn(value, "identitySeed")) {
|
|
61
|
+
if (typeof value.identitySeed !== "string" || !validSeed(value.identitySeed)) return undefined;
|
|
62
|
+
settings.identitySeed = value.identitySeed;
|
|
63
|
+
}
|
|
64
|
+
if (Object.hasOwn(value, "widgetMode")) {
|
|
65
|
+
if (
|
|
66
|
+
value.widgetMode !== "dock" &&
|
|
67
|
+
value.widgetMode !== "count" &&
|
|
68
|
+
value.widgetMode !== "latest" &&
|
|
69
|
+
value.widgetMode !== "off"
|
|
70
|
+
) {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
settings.widgetMode = value.widgetMode;
|
|
74
|
+
}
|
|
75
|
+
if (Object.hasOwn(value, "resume")) {
|
|
76
|
+
const resume = normalizeResumeSettings(value.resume);
|
|
77
|
+
if (!resume || !settings.nickname || !settings.identitySeed) return undefined;
|
|
78
|
+
settings.resume = resume;
|
|
79
|
+
}
|
|
80
|
+
return settings;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function readChatSettings(
|
|
84
|
+
settingsPath = chatSettingsPath(),
|
|
85
|
+
): Promise<ChatSettingsLoadResult> {
|
|
86
|
+
await queues.get(settingsPath);
|
|
87
|
+
try {
|
|
88
|
+
const contents = await readSettings(settingsPath);
|
|
89
|
+
try {
|
|
90
|
+
const settings = normalizeChatSettings(JSON.parse(contents) as unknown);
|
|
91
|
+
return settings
|
|
92
|
+
? { kind: "loaded", settings }
|
|
93
|
+
: { kind: "invalid", reason: `${settingsPath}: invalid settings shape` };
|
|
94
|
+
} catch {
|
|
95
|
+
return { kind: "invalid", reason: `${settingsPath}: invalid JSON` };
|
|
96
|
+
}
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (isNodeError(error) && error.code === "ENOENT") return { kind: "missing" };
|
|
99
|
+
return { kind: "invalid", reason: `${settingsPath}: ${safeError(error)}` };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function updateChatSettings(
|
|
104
|
+
patch: ChatSettingsPatch,
|
|
105
|
+
options: UpdateChatSettingsOptions = {},
|
|
106
|
+
): Promise<ChatSettings> {
|
|
107
|
+
const settingsPath = options.settingsPath ?? chatSettingsPath();
|
|
108
|
+
return enqueue(settingsPath, async () => {
|
|
109
|
+
options.signal?.throwIfAborted();
|
|
110
|
+
const current = await readDocumentForUpdate(settingsPath);
|
|
111
|
+
const updated: SettingsDocument = { ...current, ...patch };
|
|
112
|
+
if (Object.hasOwn(patch, "resume")) {
|
|
113
|
+
if (patch.resume === null) delete updated.resume;
|
|
114
|
+
else if (patch.resume === undefined) {
|
|
115
|
+
if (Object.hasOwn(current, "resume")) updated.resume = current.resume;
|
|
116
|
+
else delete updated.resume;
|
|
117
|
+
} else updated.resume = mergeResumeDocument(current.resume, patch.resume);
|
|
118
|
+
}
|
|
119
|
+
const settings = normalizeChatSettings(updated);
|
|
120
|
+
if (!settings) throw new Error(`Pi Chat settings at ${settingsPath} have an invalid shape.`);
|
|
121
|
+
await publish(settingsPath, updated, options);
|
|
122
|
+
return settings;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function rememberedRoomFromDescriptor(room: RoomDescriptor): RememberedRoom {
|
|
127
|
+
if (room.kind === "public") {
|
|
128
|
+
const slug = room.label.startsWith("#") ? room.label.slice(1) : room.label;
|
|
129
|
+
const reconstructed = createPublicRoom(slug);
|
|
130
|
+
if (reconstructed.id !== room.id) throw new Error("Public room descriptor is inconsistent.");
|
|
131
|
+
return { id: room.id, kind: "public", slug };
|
|
132
|
+
}
|
|
133
|
+
if (!room.invite || parseInvite(room.invite).id !== room.id) {
|
|
134
|
+
throw new Error("Private room descriptor is inconsistent.");
|
|
135
|
+
}
|
|
136
|
+
return { id: room.id, kind: "private", invite: room.invite };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function descriptorFromRememberedRoom(room: RememberedRoom): RoomDescriptor {
|
|
140
|
+
const descriptor =
|
|
141
|
+
room.kind === "public" ? createPublicRoom(room.slug) : parseInvite(room.invite);
|
|
142
|
+
if (descriptor.id !== room.id) throw new Error("Remembered room is inconsistent.");
|
|
143
|
+
return descriptor;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function awaitChatSettingsWrites(settingsPath = chatSettingsPath()): Promise<void> {
|
|
147
|
+
await queues.get(settingsPath);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function enqueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
|
|
151
|
+
const previous = queues.get(path) ?? Promise.resolve();
|
|
152
|
+
const result = previous.then(operation, operation);
|
|
153
|
+
const settled = result.then(
|
|
154
|
+
() => undefined,
|
|
155
|
+
() => undefined,
|
|
156
|
+
);
|
|
157
|
+
queues.set(path, settled);
|
|
158
|
+
void settled.finally(() => {
|
|
159
|
+
if (queues.get(path) === settled) queues.delete(path);
|
|
160
|
+
});
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function readDocumentForUpdate(path: string): Promise<SettingsDocument> {
|
|
165
|
+
let contents: string;
|
|
166
|
+
try {
|
|
167
|
+
contents = await readSettings(path);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (isNodeError(error) && error.code === "ENOENT") return {};
|
|
170
|
+
throw new Error(`Pi Chat settings at ${path} are invalid: ${safeError(error)}`);
|
|
171
|
+
}
|
|
172
|
+
let value: unknown;
|
|
173
|
+
try {
|
|
174
|
+
value = JSON.parse(contents) as unknown;
|
|
175
|
+
} catch {
|
|
176
|
+
throw new Error(`Pi Chat settings at ${path} are invalid: invalid JSON`);
|
|
177
|
+
}
|
|
178
|
+
if (!isRecord(value) || !normalizeChatSettings(value)) {
|
|
179
|
+
throw new Error(`Pi Chat settings at ${path} are invalid: invalid settings shape`);
|
|
180
|
+
}
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function readSettings(path: string): Promise<string> {
|
|
185
|
+
const pathStats = await lstat(path);
|
|
186
|
+
if (pathStats.isSymbolicLink() || !pathStats.isFile()) {
|
|
187
|
+
throw new Error("settings path is not a regular file");
|
|
188
|
+
}
|
|
189
|
+
const noFollow = constants.O_NOFOLLOW ?? 0;
|
|
190
|
+
const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
|
|
191
|
+
try {
|
|
192
|
+
const stats = await handle.stat();
|
|
193
|
+
if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
|
|
194
|
+
throw new Error("settings path changed while opening");
|
|
195
|
+
}
|
|
196
|
+
if (stats.size > MAX_SETTINGS_BYTES) {
|
|
197
|
+
throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
|
|
198
|
+
}
|
|
199
|
+
const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
|
|
200
|
+
let offset = 0;
|
|
201
|
+
while (offset < buffer.length) {
|
|
202
|
+
const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
|
|
203
|
+
if (bytesRead === 0) break;
|
|
204
|
+
offset += bytesRead;
|
|
205
|
+
}
|
|
206
|
+
if (offset > MAX_SETTINGS_BYTES)
|
|
207
|
+
throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
|
|
208
|
+
try {
|
|
209
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
|
210
|
+
buffer.subarray(0, offset),
|
|
211
|
+
);
|
|
212
|
+
} catch {
|
|
213
|
+
throw new Error("settings file is not valid UTF-8");
|
|
214
|
+
}
|
|
215
|
+
} finally {
|
|
216
|
+
await handle.close();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function publish(
|
|
221
|
+
path: string,
|
|
222
|
+
document: SettingsDocument,
|
|
223
|
+
options: UpdateChatSettingsOptions,
|
|
224
|
+
): Promise<void> {
|
|
225
|
+
options.signal?.throwIfAborted();
|
|
226
|
+
const contents = `${JSON.stringify(document, null, 2)}\n`;
|
|
227
|
+
if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
|
|
228
|
+
throw new Error(`Pi Chat settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
|
|
229
|
+
}
|
|
230
|
+
const directory = dirname(path);
|
|
231
|
+
await mkdir(directory, { recursive: true });
|
|
232
|
+
const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
|
|
233
|
+
try {
|
|
234
|
+
await writeFile(temporaryPath, contents, {
|
|
235
|
+
encoding: "utf8",
|
|
236
|
+
flag: "wx",
|
|
237
|
+
mode: 0o600,
|
|
238
|
+
signal: options.signal,
|
|
239
|
+
});
|
|
240
|
+
await options.beforeRename?.(temporaryPath, path);
|
|
241
|
+
options.signal?.throwIfAborted();
|
|
242
|
+
await rename(temporaryPath, path);
|
|
243
|
+
if (process.platform !== "win32") await chmod(path, 0o600);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function normalizeResumeSettings(value: unknown): ChatResumeSettings | undefined {
|
|
251
|
+
if (!isRecord(value) || !Array.isArray(value.rooms)) return undefined;
|
|
252
|
+
if (value.rooms.length === 0 || value.rooms.length > 16) return undefined;
|
|
253
|
+
if (typeof value.activeRoomId !== "string") return undefined;
|
|
254
|
+
if (value.surface !== "chat" && value.surface !== "pi") return undefined;
|
|
255
|
+
const rooms: RememberedRoom[] = [];
|
|
256
|
+
const ids = new Set<string>();
|
|
257
|
+
for (const candidate of value.rooms) {
|
|
258
|
+
const room = normalizeRememberedRoom(candidate);
|
|
259
|
+
if (!room || ids.has(room.id)) return undefined;
|
|
260
|
+
ids.add(room.id);
|
|
261
|
+
rooms.push(room);
|
|
262
|
+
}
|
|
263
|
+
if (!ids.has(value.activeRoomId)) return undefined;
|
|
264
|
+
return { rooms, activeRoomId: value.activeRoomId, surface: value.surface };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
|
|
268
|
+
if (!isRecord(value) || typeof value.id !== "string") return undefined;
|
|
269
|
+
try {
|
|
270
|
+
if (
|
|
271
|
+
value.kind === "public" &&
|
|
272
|
+
typeof value.slug === "string" &&
|
|
273
|
+
!Object.hasOwn(value, "invite")
|
|
274
|
+
) {
|
|
275
|
+
const room = createPublicRoom(value.slug);
|
|
276
|
+
return room.id === value.id ? { id: room.id, kind: "public", slug: value.slug } : undefined;
|
|
277
|
+
}
|
|
278
|
+
if (
|
|
279
|
+
value.kind === "private" &&
|
|
280
|
+
typeof value.invite === "string" &&
|
|
281
|
+
!Object.hasOwn(value, "slug")
|
|
282
|
+
) {
|
|
283
|
+
const room = parseInvite(value.invite);
|
|
284
|
+
return room.id === value.id
|
|
285
|
+
? { id: room.id, kind: "private", invite: value.invite }
|
|
286
|
+
: undefined;
|
|
287
|
+
}
|
|
288
|
+
} catch {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function mergeResumeDocument(current: unknown, next: ChatResumeSettings): SettingsDocument {
|
|
295
|
+
const currentResume = isRecord(current) ? current : {};
|
|
296
|
+
const existingRooms = new Map<string, SettingsDocument>();
|
|
297
|
+
if (Array.isArray(currentResume.rooms)) {
|
|
298
|
+
for (const candidate of currentResume.rooms) {
|
|
299
|
+
if (isRecord(candidate) && typeof candidate.id === "string") {
|
|
300
|
+
existingRooms.set(candidate.id, candidate);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return {
|
|
305
|
+
...currentResume,
|
|
306
|
+
rooms: next.rooms.map((room) => ({ ...existingRooms.get(room.id), ...room })),
|
|
307
|
+
activeRoomId: next.activeRoomId,
|
|
308
|
+
surface: next.surface,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function validSeed(value: string): boolean {
|
|
313
|
+
try {
|
|
314
|
+
return /^[A-Za-z0-9_-]{43}$/u.test(value) && Buffer.from(value, "base64url").length === 32;
|
|
315
|
+
} catch {
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function isRecord(value: unknown): value is SettingsDocument {
|
|
321
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
325
|
+
return error instanceof Error && "code" in error;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function safeError(error: unknown): string {
|
|
329
|
+
return error instanceof Error ? error.message : String(error);
|
|
330
|
+
}
|