@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/chat-view.ts CHANGED
@@ -19,7 +19,7 @@ export interface ChatViewOptions {
19
19
  tui: TUI;
20
20
  theme: Theme;
21
21
  getSnapshot(): ChatSnapshot;
22
- send(text: string): { id: string; deliveredTo: number };
22
+ send(text: string): { id: string; relayedTo: number };
23
23
  initialDraft?: string;
24
24
  onDraftChange?(text: string): void;
25
25
  setViewOpen(open: boolean): void;
@@ -72,29 +72,29 @@ export class ChatView implements Component, Focusable {
72
72
  this.tui.requestRender();
73
73
  return;
74
74
  }
75
- if (this.options.getSnapshot().peers.length === 0) {
75
+ if (this.options.getSnapshot().directNeighbors === 0) {
76
76
  this.editor.setText(text);
77
77
  this.messageStatus = {
78
78
  kind: "warning",
79
- text: "No direct peers — message kept. Wait for connection or Esc to return.",
79
+ text: "No direct neighbors — message kept. Wait for connection or Esc to return.",
80
80
  };
81
81
  this.tui.requestRender();
82
82
  return;
83
83
  }
84
84
  try {
85
85
  const result = this.options.send(message);
86
- if (result.deliveredTo === 0) {
86
+ if (result.relayedTo === 0) {
87
87
  this.editor.setText(text);
88
88
  this.messageStatus = {
89
89
  kind: "warning",
90
- text: "No direct peers accepted it — message kept for retry.",
90
+ text: "No direct neighbors accepted it — message kept for retry.",
91
91
  };
92
92
  } else {
93
93
  this.editor.setText("");
94
94
  this.followBottom = true;
95
95
  this.messageStatus = {
96
96
  kind: "success",
97
- text: `Sent to ${result.deliveredTo} direct peer${result.deliveredTo === 1 ? "" : "s"}`,
97
+ text: `Relayed to ${result.relayedTo} direct neighbor${result.relayedTo === 1 ? "" : "s"}`,
98
98
  };
99
99
  }
100
100
  } catch (error) {
@@ -132,12 +132,12 @@ export class ChatView implements Component, Focusable {
132
132
  this.lastViewportRows = viewportRows;
133
133
  if (this.followBottom) this.scrollOffset = this.maxScroll();
134
134
  this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.maxScroll()));
135
- const peerCount = snapshot.peers.length;
135
+ const participantCount = snapshot.participants.length;
136
136
  const header = truncateToWidth(
137
137
  this.theme.fg(
138
138
  "accent",
139
139
  this.theme.bold(
140
- `CHAT INPUT → ${sanitizeSingleLine(snapshot.room.label)} · ${peerCount === 0 ? "waiting for peers" : `${peerCount} direct peer${peerCount === 1 ? "" : "s"}`}`,
140
+ `CHAT INPUT → ${sanitizeSingleLine(snapshot.room.label)} · ${participantCount} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`,
141
141
  ),
142
142
  ),
143
143
  safeWidth,
@@ -216,8 +216,8 @@ export class ChatView implements Component, Focusable {
216
216
  function renderTranscript(snapshot: ChatSnapshot, width: number, theme: Theme): string[] {
217
217
  if (snapshot.transcript.length === 0) {
218
218
  const empty =
219
- snapshot.peers.length === 0
220
- ? "You are alone; waiting for peers."
219
+ snapshot.participants.length === 0
220
+ ? "No other active participants discovered yet."
221
221
  : "No messages yet. Start the conversation below.";
222
222
  return wrapTextWithAnsi(theme.fg("muted", empty), width);
223
223
  }
@@ -225,10 +225,10 @@ function renderTranscript(snapshot: ChatSnapshot, width: number, theme: Theme):
225
225
  for (const entry of snapshot.transcript) {
226
226
  const label = sanitizeSingleLine(entry.label);
227
227
  const delivery =
228
- entry.author === "local" && entry.delivery === "not-delivered"
229
- ? " · not delivered"
230
- : entry.author === "local" && entry.deliveredTo !== undefined
231
- ? ` · broadcast to ${entry.deliveredTo}`
228
+ entry.author === "local" && entry.delivery === "not-relayed"
229
+ ? " · not relayed"
230
+ : entry.author === "local" && entry.relayedTo !== undefined
231
+ ? ` · relayed to ${entry.relayedTo}`
232
232
  : "";
233
233
  lines.push(...wrapTextWithAnsi(theme.fg("accent", `${label}${delivery}`), width));
234
234
  for (const rawLine of sanitizeChatText(entry.text).split("\n")) {
@@ -0,0 +1,416 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { Duplex } from "node:stream";
3
+ import Hyperswarm, { type PeerDiscovery, type PeerInfo } from "hyperswarm";
4
+ import type { ChatIdentity } from "./identity.js";
5
+ import { MAX_DIRECT_NEIGHBORS } from "./network-contract.js";
6
+ import { PeerRateLimiter } from "./protocol.js";
7
+ import {
8
+ createDirectoryPresence,
9
+ createDirectoryWireMessage,
10
+ DirectoryCatalog,
11
+ DirectoryFrameDecoder,
12
+ type DirectoryWireMessage,
13
+ encodeDirectoryFrame,
14
+ PUBLIC_ROOM_DIRECTORY_TOPIC,
15
+ type PublicRoomBrowseResult,
16
+ } from "./public-room-directory.js";
17
+
18
+ const DIRECTORY_HEARTBEAT_MS = 30_000;
19
+ const DIRECTORY_BROWSE_MS = 1_200;
20
+ const MAX_SYNC_RECORDS = 256;
21
+
22
+ export interface DirectoryPeer {
23
+ publicKey: Buffer;
24
+ send(message: DirectoryWireMessage): void;
25
+ close(): void;
26
+ }
27
+
28
+ export interface DirectoryTransportListener {
29
+ onPeer(peer: DirectoryPeer): void;
30
+ onMessage(peer: DirectoryPeer, message: DirectoryWireMessage): void;
31
+ onDisconnect(peer: DirectoryPeer): void;
32
+ onError(error: Error): void;
33
+ }
34
+
35
+ export interface DirectoryTransport {
36
+ start(listener: DirectoryTransportListener, signal?: AbortSignal): Promise<void>;
37
+ refresh(signal?: AbortSignal): Promise<void>;
38
+ stop(): Promise<void>;
39
+ }
40
+
41
+ export interface PublicRoomDirectory {
42
+ start(signal?: AbortSignal): Promise<void>;
43
+ browse(signal: AbortSignal, collectionMs?: number): Promise<PublicRoomBrowseResult>;
44
+ stop(): Promise<void>;
45
+ }
46
+
47
+ export interface PublicRoomDirectorySessionOptions {
48
+ identity: ChatIdentity;
49
+ transport: DirectoryTransport;
50
+ advertisedSlug?: string;
51
+ now?: () => number;
52
+ createId?: () => string;
53
+ }
54
+
55
+ interface DirectoryPeerState {
56
+ peer: DirectoryPeer;
57
+ limiter: PeerRateLimiter;
58
+ violations: number;
59
+ }
60
+
61
+ export class PublicRoomDirectorySession implements PublicRoomDirectory {
62
+ private readonly identity: ChatIdentity;
63
+ private readonly transport: DirectoryTransport;
64
+ private readonly advertisedSlug?: string;
65
+ private readonly now: () => number;
66
+ private readonly createId: () => string;
67
+ private readonly catalog: DirectoryCatalog;
68
+ private readonly peers = new Map<string, DirectoryPeerState>();
69
+ private started = false;
70
+ private startPromise: Promise<void> | undefined;
71
+ private stopPromise: Promise<void> | undefined;
72
+ private transportStopPromise: Promise<void> | undefined;
73
+ private heartbeatTimer: NodeJS.Timeout | undefined;
74
+ private generation = 0;
75
+
76
+ constructor(options: PublicRoomDirectorySessionOptions) {
77
+ this.identity = options.identity;
78
+ this.transport = options.transport;
79
+ this.advertisedSlug = options.advertisedSlug;
80
+ this.now = options.now ?? Date.now;
81
+ this.createId = options.createId ?? randomUUID;
82
+ this.catalog = new DirectoryCatalog({ now: this.now });
83
+ }
84
+
85
+ start(signal?: AbortSignal): Promise<void> {
86
+ if (this.startPromise) return this.startPromise;
87
+ if (this.stopPromise) throw new Error("Public room directory has already stopped.");
88
+ this.startPromise = this.startOwned(signal);
89
+ return this.startPromise;
90
+ }
91
+
92
+ async browse(
93
+ signal: AbortSignal,
94
+ collectionMs = DIRECTORY_BROWSE_MS,
95
+ ): Promise<PublicRoomBrowseResult> {
96
+ const temporary = !this.started && !this.advertisedSlug;
97
+ try {
98
+ await this.start(signal);
99
+ signal.throwIfAborted();
100
+ await this.transport.refresh(signal);
101
+ await abortableDelay(Math.max(0, collectionMs), signal);
102
+ signal.throwIfAborted();
103
+ return this.catalog.snapshot();
104
+ } finally {
105
+ if (temporary) await this.stop();
106
+ }
107
+ }
108
+
109
+ stop(): Promise<void> {
110
+ if (this.stopPromise) return this.stopPromise;
111
+ this.stopPromise = this.stopOwned();
112
+ return this.stopPromise;
113
+ }
114
+
115
+ private async startOwned(signal?: AbortSignal): Promise<void> {
116
+ const owner = ++this.generation;
117
+ this.started = true;
118
+ try {
119
+ await this.transport.start(
120
+ {
121
+ onPeer: (peer) => this.onPeer(owner, peer),
122
+ onMessage: (peer, message) => this.onMessage(owner, peer, message),
123
+ onDisconnect: (peer) => this.onDisconnect(owner, peer),
124
+ onError: () => this.catalog.markPartial(),
125
+ },
126
+ signal,
127
+ );
128
+ signal?.throwIfAborted();
129
+ if (owner !== this.generation) return;
130
+ if (this.advertisedSlug) this.publish("online");
131
+ this.heartbeatTimer = setInterval(() => {
132
+ if (owner === this.generation && this.started && this.advertisedSlug) {
133
+ this.publish("online");
134
+ }
135
+ }, DIRECTORY_HEARTBEAT_MS);
136
+ this.heartbeatTimer.unref();
137
+ } catch (error) {
138
+ this.started = false;
139
+ await this.stopTransport();
140
+ throw error;
141
+ }
142
+ }
143
+
144
+ private onPeer(owner: number, peer: DirectoryPeer): void {
145
+ if (owner !== this.generation || !this.started) {
146
+ peer.close();
147
+ return;
148
+ }
149
+ const id = peer.publicKey.toString("hex");
150
+ const previous = this.peers.get(id);
151
+ if (previous && previous.peer !== peer) previous.peer.close();
152
+ this.peers.set(id, {
153
+ peer,
154
+ limiter: new PeerRateLimiter({ burst: MAX_SYNC_RECORDS, refillPerSecond: 16, now: this.now }),
155
+ violations: 0,
156
+ });
157
+ const events = this.catalog.currentEvents();
158
+ const partial = events.length > MAX_SYNC_RECORDS || this.catalog.snapshot().partial;
159
+ if (events.length > MAX_SYNC_RECORDS) this.catalog.markPartial();
160
+ for (const [index, event] of events.slice(0, MAX_SYNC_RECORDS).entries()) {
161
+ try {
162
+ peer.send(createDirectoryWireMessage(event, undefined, partial && index === 0));
163
+ } catch {
164
+ break;
165
+ }
166
+ }
167
+ }
168
+
169
+ private onMessage(owner: number, peer: DirectoryPeer, message: DirectoryWireMessage): void {
170
+ if (owner !== this.generation || !this.started) return;
171
+ const state = this.peers.get(peer.publicKey.toString("hex"));
172
+ if (!state || state.peer !== peer) return;
173
+ if (!state.limiter.accept()) {
174
+ this.violate(state);
175
+ return;
176
+ }
177
+ if (message.partial) this.catalog.markPartial();
178
+ if (!this.catalog.accept(message.event)) {
179
+ return;
180
+ }
181
+ if (message.hops > 1) {
182
+ this.broadcast(
183
+ createDirectoryWireMessage(message.event, message.hops - 1, message.partial),
184
+ peer,
185
+ );
186
+ }
187
+ }
188
+
189
+ private onDisconnect(owner: number, peer: DirectoryPeer): void {
190
+ if (owner !== this.generation) return;
191
+ const id = peer.publicKey.toString("hex");
192
+ if (this.peers.get(id)?.peer === peer) this.peers.delete(id);
193
+ }
194
+
195
+ private publish(status: "online" | "leaving"): void {
196
+ if (!this.advertisedSlug) return;
197
+ const event = createDirectoryPresence(
198
+ this.identity,
199
+ this.advertisedSlug,
200
+ status,
201
+ this.now(),
202
+ this.createId(),
203
+ );
204
+ this.catalog.accept(event);
205
+ this.broadcast(createDirectoryWireMessage(event));
206
+ }
207
+
208
+ private broadcast(message: DirectoryWireMessage, exclude?: DirectoryPeer): void {
209
+ for (const state of this.peers.values()) {
210
+ if (state.peer === exclude) continue;
211
+ try {
212
+ state.peer.send(message);
213
+ } catch {
214
+ state.violations += 1;
215
+ }
216
+ }
217
+ }
218
+
219
+ private violate(state: DirectoryPeerState): void {
220
+ state.violations += 1;
221
+ if (state.violations > 3) {
222
+ state.peer.close();
223
+ this.peers.delete(state.peer.publicKey.toString("hex"));
224
+ }
225
+ }
226
+
227
+ private async stopOwned(): Promise<void> {
228
+ this.generation += 1;
229
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
230
+ this.heartbeatTimer = undefined;
231
+ if (this.started && this.advertisedSlug) this.publish("leaving");
232
+ this.started = false;
233
+ for (const state of this.peers.values()) state.peer.close();
234
+ this.peers.clear();
235
+ await this.stopTransport();
236
+ }
237
+
238
+ private stopTransport(): Promise<void> {
239
+ if (!this.transportStopPromise) {
240
+ this.transportStopPromise = this.transport.stop().catch(() => undefined);
241
+ }
242
+ return this.transportStopPromise;
243
+ }
244
+ }
245
+
246
+ export interface HyperswarmDirectoryTransportOptions {
247
+ identity: ChatIdentity;
248
+ dht?: unknown;
249
+ bootstrap?: unknown[];
250
+ }
251
+
252
+ interface ActiveConnection {
253
+ socket: Duplex;
254
+ peer: DirectoryPeer;
255
+ }
256
+
257
+ export class HyperswarmDirectoryTransport implements DirectoryTransport {
258
+ private readonly options: HyperswarmDirectoryTransportOptions;
259
+ private swarm: Hyperswarm | undefined;
260
+ private discovery: PeerDiscovery | undefined;
261
+ private listener: DirectoryTransportListener | undefined;
262
+ private readonly connections = new Map<Duplex, ActiveConnection>();
263
+ private stopPromise: Promise<void> | undefined;
264
+
265
+ constructor(options: HyperswarmDirectoryTransportOptions) {
266
+ this.options = options;
267
+ }
268
+
269
+ async start(listener: DirectoryTransportListener, signal?: AbortSignal): Promise<void> {
270
+ if (this.swarm) throw new Error("Public room directory transport has already started.");
271
+ const startupSignal = signal
272
+ ? AbortSignal.any([signal, AbortSignal.timeout(15_000)])
273
+ : AbortSignal.timeout(15_000);
274
+ startupSignal.throwIfAborted();
275
+ this.listener = listener;
276
+ const swarm = new Hyperswarm({
277
+ keyPair: {
278
+ publicKey: this.options.identity.publicKey,
279
+ secretKey: this.options.identity.secretKey,
280
+ },
281
+ maxPeers: MAX_DIRECT_NEIGHBORS,
282
+ ...(this.options.dht ? { dht: this.options.dht } : {}),
283
+ ...(this.options.bootstrap ? { bootstrap: this.options.bootstrap } : {}),
284
+ });
285
+ this.swarm = swarm;
286
+ swarm.on("connection", (socket, info) => this.accept(socket, info));
287
+ swarm.on("error", (error) => this.listener?.onError(safeNetworkError(error)));
288
+ try {
289
+ this.discovery = swarm.join(PUBLIC_ROOM_DIRECTORY_TOPIC, {
290
+ server: true,
291
+ client: true,
292
+ limit: MAX_DIRECT_NEIGHBORS,
293
+ });
294
+ await raceAbort(this.discovery.flushed(), startupSignal);
295
+ startupSignal.throwIfAborted();
296
+ } catch (error) {
297
+ await this.stop();
298
+ throw error;
299
+ }
300
+ }
301
+
302
+ async refresh(signal?: AbortSignal): Promise<void> {
303
+ if (!this.discovery) throw new Error("Public room directory is not running.");
304
+ await raceAbort(
305
+ this.discovery.refresh({ server: true, client: true, limit: MAX_DIRECT_NEIGHBORS }),
306
+ signal,
307
+ );
308
+ }
309
+
310
+ stop(): Promise<void> {
311
+ if (this.stopPromise) return this.stopPromise;
312
+ this.stopPromise = this.stopOwned();
313
+ return this.stopPromise;
314
+ }
315
+
316
+ private accept(socket: Duplex, info: PeerInfo): void {
317
+ if (!this.swarm || !this.listener || this.connections.size >= MAX_DIRECT_NEIGHBORS) {
318
+ socket.destroy();
319
+ return;
320
+ }
321
+ const decoder = new DirectoryFrameDecoder();
322
+ let closed = false;
323
+ const peer: DirectoryPeer = {
324
+ publicKey: Buffer.from(info.publicKey),
325
+ send(message) {
326
+ if (closed || socket.destroyed) throw new Error("Directory peer connection is closed.");
327
+ const accepted = socket.write(encodeDirectoryFrame(message));
328
+ if (!accepted && socket.destroyed) {
329
+ throw new Error("Directory peer connection rejected the message.");
330
+ }
331
+ },
332
+ close() {
333
+ if (closed) return;
334
+ closed = true;
335
+ socket.destroy();
336
+ },
337
+ };
338
+ this.connections.set(socket, { socket, peer });
339
+ this.listener.onPeer(peer);
340
+ socket.on("data", (chunk: unknown) => {
341
+ if (closed || !this.listener) return;
342
+ try {
343
+ const bytes =
344
+ typeof chunk === "string"
345
+ ? Buffer.from(chunk)
346
+ : Buffer.isBuffer(chunk)
347
+ ? chunk
348
+ : Buffer.from(chunk as Uint8Array);
349
+ for (const message of decoder.push(bytes)) this.listener.onMessage(peer, message);
350
+ } catch {
351
+ closed = true;
352
+ socket.destroy();
353
+ this.listener?.onError(new Error("Pi Chat rejected invalid directory protocol data."));
354
+ }
355
+ });
356
+ const disconnected = () => {
357
+ if (!this.connections.delete(socket)) return;
358
+ closed = true;
359
+ this.listener?.onDisconnect(peer);
360
+ };
361
+ socket.once("close", disconnected);
362
+ socket.once("error", (error) => {
363
+ this.listener?.onError(safeNetworkError(error));
364
+ disconnected();
365
+ });
366
+ }
367
+
368
+ private async stopOwned(): Promise<void> {
369
+ const discovery = this.discovery;
370
+ this.discovery = undefined;
371
+ if (discovery) await discovery.destroy().catch(() => undefined);
372
+ for (const { socket } of this.connections.values()) socket.destroy();
373
+ this.connections.clear();
374
+ const swarm = this.swarm;
375
+ this.swarm = undefined;
376
+ this.listener = undefined;
377
+ if (swarm) await swarm.destroy().catch(() => undefined);
378
+ }
379
+ }
380
+
381
+ async function abortableDelay(milliseconds: number, signal: AbortSignal): Promise<void> {
382
+ signal.throwIfAborted();
383
+ await new Promise<void>((resolve, reject) => {
384
+ const timer = setTimeout(done, milliseconds);
385
+ const abort = () => done(signal.reason ?? new DOMException("Aborted", "AbortError"));
386
+ function done(error?: unknown): void {
387
+ clearTimeout(timer);
388
+ signal.removeEventListener("abort", abort);
389
+ if (error) reject(error);
390
+ else resolve();
391
+ }
392
+ signal.addEventListener("abort", abort, { once: true });
393
+ });
394
+ }
395
+
396
+ async function raceAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
397
+ if (!signal) return operation;
398
+ signal.throwIfAborted();
399
+ let remove = () => {};
400
+ const aborted = new Promise<never>((_resolve, reject) => {
401
+ const onAbort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
402
+ signal.addEventListener("abort", onAbort, { once: true });
403
+ remove = () => signal.removeEventListener("abort", onAbort);
404
+ });
405
+ try {
406
+ return await Promise.race([operation, aborted]);
407
+ } finally {
408
+ remove();
409
+ }
410
+ }
411
+
412
+ function safeNetworkError(error: unknown): Error {
413
+ const code =
414
+ error instanceof Error && "code" in error ? String(Reflect.get(error, "code")) : "error";
415
+ return new Error(`Pi Chat directory network ${code}.`);
416
+ }
package/src/external.d.ts CHANGED
@@ -1,3 +1,17 @@
1
+ declare module "sodium-universal" {
2
+ interface SodiumUniversal {
3
+ crypto_sign_BYTES: number;
4
+ crypto_sign_detached(signature: Uint8Array, message: Uint8Array, secretKey: Uint8Array): void;
5
+ crypto_sign_verify_detached(
6
+ signature: Uint8Array,
7
+ message: Uint8Array,
8
+ publicKey: Uint8Array,
9
+ ): boolean;
10
+ }
11
+ const sodium: SodiumUniversal;
12
+ export default sodium;
13
+ }
14
+
1
15
  declare module "hyperdht" {
2
16
  export interface HyperDhtKeyPair {
3
17
  publicKey: Buffer;
package/src/identity.ts CHANGED
@@ -1,9 +1,25 @@
1
- import { createHash } from "node:crypto";
2
- import HyperDHT from "hyperdht";
1
+ import { createHash, hkdfSync } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+
4
+ export { normalizeNickname } from "./nickname.js";
5
+
6
+ const require = createRequire(import.meta.url);
7
+ type HyperDht = typeof import("hyperdht")["default"];
8
+ type Sodium = typeof import("sodium-universal")["default"];
9
+ let hyperDhtImplementation: HyperDht | undefined;
10
+ let sodiumImplementation: Sodium | undefined;
11
+
12
+ function hyperDht(): HyperDht {
13
+ hyperDhtImplementation ??= require("hyperdht") as HyperDht;
14
+ return hyperDhtImplementation;
15
+ }
16
+
17
+ function sodium(): Sodium {
18
+ sodiumImplementation ??= require("sodium-universal") as Sodium;
19
+ return sodiumImplementation;
20
+ }
3
21
 
4
22
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5
- const MAX_NICKNAME_GRAPHEMES = 24;
6
- const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;
7
23
 
8
24
  export interface ChatIdentity {
9
25
  seed: string;
@@ -12,19 +28,10 @@ export interface ChatIdentity {
12
28
  tag: string;
13
29
  }
14
30
 
15
- export function normalizeNickname(value: unknown): string | undefined {
16
- if (typeof value !== "string") return undefined;
17
- const normalized = value.normalize("NFKC").trim();
18
- if (!normalized || /\p{Cc}/u.test(normalized) || BIDI_CONTROLS.test(normalized)) return undefined;
19
- const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
20
- if (Array.from(segmenter.segment(normalized)).length > MAX_NICKNAME_GRAPHEMES) return undefined;
21
- return normalized;
22
- }
23
-
24
31
  export function createIdentity(seed: Uint8Array): ChatIdentity {
25
32
  if (seed.byteLength !== 32) throw new Error("Pi Chat identity seed must be exactly 32-byte.");
26
33
  const stableSeed = Buffer.from(seed);
27
- const keyPair = HyperDHT.keyPair(stableSeed);
34
+ const keyPair = hyperDht().keyPair(stableSeed);
28
35
  return {
29
36
  seed: stableSeed.toString("base64url"),
30
37
  publicKey: Buffer.from(keyPair.publicKey),
@@ -33,6 +40,47 @@ export function createIdentity(seed: Uint8Array): ChatIdentity {
33
40
  };
34
41
  }
35
42
 
43
+ export function deriveScopedIdentity(identity: ChatIdentity, scope: string): ChatIdentity {
44
+ if (!scope || Buffer.byteLength(scope, "utf8") > 256) {
45
+ throw new Error("Pi Chat identity scope is invalid.");
46
+ }
47
+ const seed = Buffer.from(identity.seed, "base64url");
48
+ return createIdentity(
49
+ Buffer.from(
50
+ hkdfSync(
51
+ "sha256",
52
+ seed,
53
+ Buffer.from("pi-chat/scoped-identity/v2", "utf8"),
54
+ Buffer.from(scope, "utf8"),
55
+ 32,
56
+ ),
57
+ ),
58
+ );
59
+ }
60
+
61
+ export function signIdentityPayload(identity: ChatIdentity, payload: Uint8Array): string {
62
+ const implementation = sodium();
63
+ const signature = Buffer.alloc(implementation.crypto_sign_BYTES);
64
+ implementation.crypto_sign_detached(signature, payload, identity.secretKey);
65
+ return signature.toString("base64url");
66
+ }
67
+
68
+ export function verifyIdentityPayload(
69
+ publicKey: Uint8Array,
70
+ payload: Uint8Array,
71
+ signatureValue: string,
72
+ ): boolean {
73
+ if (publicKey.byteLength !== 32 || !/^[A-Za-z0-9_-]{86}$/u.test(signatureValue)) return false;
74
+ const signature = Buffer.from(signatureValue, "base64url");
75
+ const implementation = sodium();
76
+ if (signature.byteLength !== implementation.crypto_sign_BYTES) return false;
77
+ try {
78
+ return implementation.crypto_sign_verify_detached(signature, payload, publicKey);
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
36
84
  export function identityTag(publicKey: Uint8Array, characters = 12): string {
37
85
  if (characters < 12 || characters > 52) throw new Error("Identity tags use 12 to 52 characters.");
38
86
  const digest = createHash("sha256").update(publicKey).digest();