@johnhenry/browsermesh-apps 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.
@@ -0,0 +1,381 @@
1
+ /**
2
+ // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
+ * clawser-peer-chat.js -- P2P chat over peer sessions.
4
+ *
5
+ * Provides direct chat between two peers on top of PeerSession, with
6
+ * message signing/verification and optional agent auto-response.
7
+ *
8
+ * Dependencies are injected (PeerSession, signing functions).
9
+ * No browser-only imports at module level.
10
+ *
11
+ * Run tests:
12
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-chat.test.mjs
13
+ */
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // ID generation
17
+ // ---------------------------------------------------------------------------
18
+
19
+ let _chatMsgSeq = 0
20
+
21
+ function generateChatMessageId() {
22
+ return `cmsg_${Date.now().toString(36)}_${(++_chatMsgSeq).toString(36)}`
23
+ }
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Signature helpers
27
+ // ---------------------------------------------------------------------------
28
+
29
+ /**
30
+ * Encode a Uint8Array to a base64 string.
31
+ * Falls back to manual encoding when btoa is unavailable (Node tests).
32
+ *
33
+ * @param {Uint8Array} bytes
34
+ * @returns {string}
35
+ */
36
+ function bytesToBase64(bytes) {
37
+ if (typeof btoa === 'function') {
38
+ let binary = ''
39
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
40
+ return btoa(binary)
41
+ }
42
+ // Node.js fallback
43
+ if (typeof Buffer !== 'undefined') {
44
+ return Buffer.from(bytes).toString('base64')
45
+ }
46
+ throw new Error('No base64 encoder available')
47
+ }
48
+
49
+ /**
50
+ * Decode a base64 string to a Uint8Array.
51
+ *
52
+ * @param {string} b64
53
+ * @returns {Uint8Array}
54
+ */
55
+ function base64ToBytes(b64) {
56
+ if (typeof atob === 'function') {
57
+ const binary = atob(b64)
58
+ const bytes = new Uint8Array(binary.length)
59
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
60
+ return bytes
61
+ }
62
+ if (typeof Buffer !== 'undefined') {
63
+ return new Uint8Array(Buffer.from(b64, 'base64'))
64
+ }
65
+ throw new Error('No base64 decoder available')
66
+ }
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // PeerChat
70
+ // ---------------------------------------------------------------------------
71
+
72
+ /**
73
+ * P2P chat over a single PeerSession.
74
+ *
75
+ * Sends and receives chat messages on the 'chat' service type, with
76
+ * optional cryptographic signing/verification and an auto-responder
77
+ * hook for agent-driven replies.
78
+ */
79
+ export class PeerChat {
80
+ /** @type {object} PeerSession */
81
+ #session
82
+
83
+ /** @type {((data: Uint8Array) => Promise<Uint8Array>)|null} */
84
+ #signFn
85
+
86
+ /** @type {((pubKey: Uint8Array, data: Uint8Array, sig: Uint8Array) => Promise<boolean>)|null} */
87
+ #verifyFn
88
+
89
+ /** @type {Uint8Array|null} */
90
+ #remotePubKey
91
+
92
+ /** @type {Array<object>} ChatMessage objects */
93
+ #messageHistory = []
94
+
95
+ /** @type {number} */
96
+ #maxHistory
97
+
98
+ /** @type {((message: object) => Promise<string|null>)|null} */
99
+ #autoResponder
100
+
101
+ /** @type {Map<string, Set<Function>>} */
102
+ #listeners = new Map()
103
+
104
+ /** @type {Function} */
105
+ #onLog
106
+
107
+ /**
108
+ * @param {object} opts
109
+ * @param {object} opts.session - PeerSession instance
110
+ * @param {Function} [opts.signFn] - async (data: Uint8Array) => Uint8Array
111
+ * @param {Function} [opts.verifyFn] - async (pubKey, data, sig) => boolean
112
+ * @param {Uint8Array} [opts.remotePubKey] - Remote peer's public key
113
+ * @param {number} [opts.maxHistory=1000] - Maximum messages to retain
114
+ * @param {Function} [opts.autoResponder] - async (message) => string|null
115
+ * @param {Function} [opts.onLog] - Logging callback
116
+ */
117
+ constructor({ session, signFn, verifyFn, remotePubKey, maxHistory, autoResponder, onLog }) {
118
+ if (!session) {
119
+ throw new Error('session is required')
120
+ }
121
+
122
+ this.#session = session
123
+ this.#signFn = signFn || null
124
+ this.#verifyFn = verifyFn || null
125
+ this.#remotePubKey = remotePubKey || null
126
+ this.#maxHistory = maxHistory ?? 1000
127
+ this.#autoResponder = autoResponder || null
128
+ this.#onLog = onLog || (() => {})
129
+
130
+ // Register handler on session for 'chat' service type
131
+ this.#session.registerHandler('chat', (envelope) => this.#handleIncoming(envelope))
132
+ }
133
+
134
+ // -- Sending --------------------------------------------------------------
135
+
136
+ /**
137
+ * Send a text message to the remote peer.
138
+ *
139
+ * Creates a ChatMessage envelope, optionally signs it, transmits via
140
+ * the session, records in history, and emits 'message:sent'.
141
+ *
142
+ * @param {string} text - Message text
143
+ * @param {object} [opts] - Options
144
+ * @param {boolean} [opts.isAutoResponse] - Mark as auto-response to prevent loops
145
+ * @returns {Promise<object>} The sent ChatMessage
146
+ */
147
+ async sendMessage(text, opts) {
148
+ const message = {
149
+ id: generateChatMessageId(),
150
+ from: this.#session.localPodId,
151
+ to: this.#session.remotePodId,
152
+ text,
153
+ timestamp: Date.now(),
154
+ }
155
+ if (opts?.isAutoResponse) {
156
+ message.isAutoResponse = true
157
+ }
158
+
159
+ // Sign if signing function is available
160
+ if (this.#signFn) {
161
+ try {
162
+ const data = new TextEncoder().encode(JSON.stringify({
163
+ id: message.id,
164
+ from: message.from,
165
+ to: message.to,
166
+ text: message.text,
167
+ timestamp: message.timestamp,
168
+ }))
169
+ const sigBytes = await this.#signFn(data)
170
+ message.signature = bytesToBase64(sigBytes)
171
+ } catch (err) {
172
+ this.#onLog(1, `Failed to sign message: ${err.message}`)
173
+ }
174
+ }
175
+
176
+ // Send over session
177
+ this.#session.send('chat', message)
178
+
179
+ // Add to history
180
+ this.#addToHistory(message)
181
+
182
+ // Emit event
183
+ this.#emit('message:sent', message)
184
+
185
+ return message
186
+ }
187
+
188
+ // -- Typing indicators ----------------------------------------------------
189
+
190
+ /**
191
+ * Send a typing indicator to the remote peer.
192
+ */
193
+ sendTyping() {
194
+ this.#session.send('chat', {
195
+ type: 'typing',
196
+ from: this.#session.localPodId,
197
+ })
198
+ }
199
+
200
+ // -- Incoming handler (private) -------------------------------------------
201
+
202
+ /**
203
+ * Handle an incoming chat message from the session transport.
204
+ *
205
+ * Verifies signature if verification is available, adds to history,
206
+ * emits the appropriate event, and triggers auto-response if configured.
207
+ *
208
+ * @param {object} envelope - Session envelope with payload
209
+ */
210
+ async #handleIncoming(envelope) {
211
+ const payload = envelope.payload || envelope
212
+
213
+ // Handle typing indicators
214
+ if (payload.type === 'typing') {
215
+ this.#emit('typing', { from: payload.from })
216
+ return
217
+ }
218
+
219
+ // Validate required fields
220
+ if (!payload.text || typeof payload.text !== 'string') {
221
+ this.#onLog(1, 'Dropping incoming chat message with missing/invalid text')
222
+ return
223
+ }
224
+
225
+ // Build chat message from payload
226
+ const message = {
227
+ id: payload.id || generateChatMessageId(),
228
+ from: payload.from || 'unknown',
229
+ to: payload.to || this.#session.localPodId,
230
+ text: payload.text,
231
+ timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : Date.now(),
232
+ signature: payload.signature || undefined,
233
+ }
234
+
235
+ // Verify signature if verify function and remote public key are available
236
+ if (this.#verifyFn && this.#remotePubKey && message.signature) {
237
+ try {
238
+ const data = new TextEncoder().encode(JSON.stringify({
239
+ id: message.id,
240
+ from: message.from,
241
+ to: message.to,
242
+ text: message.text,
243
+ timestamp: message.timestamp,
244
+ }))
245
+ const sigBytes = base64ToBytes(message.signature)
246
+ message.verified = await this.#verifyFn(this.#remotePubKey, data, sigBytes)
247
+ } catch (err) {
248
+ this.#onLog(1, `Signature verification failed: ${err.message}`)
249
+ message.verified = false
250
+ }
251
+ } else if (this.#verifyFn && this.#remotePubKey && !message.signature) {
252
+ // Expected a signature but none was provided
253
+ message.verified = false
254
+ }
255
+
256
+ // Add to history
257
+ this.#addToHistory(message)
258
+
259
+ // Emit event
260
+ this.#emit('message:received', message)
261
+
262
+ // Auto-respond if configured, but never auto-respond to auto-responses
263
+ if (this.#autoResponder && !payload.isAutoResponse) {
264
+ try {
265
+ const reply = await this.#autoResponder(message)
266
+ if (reply && typeof reply === 'string') {
267
+ await this.sendMessage(reply, { isAutoResponse: true })
268
+ }
269
+ } catch (err) {
270
+ this.#onLog(0, `Auto-responder error: ${err.message}`)
271
+ }
272
+ }
273
+ }
274
+
275
+ // -- History --------------------------------------------------------------
276
+
277
+ /**
278
+ * Get the full message history.
279
+ *
280
+ * @returns {object[]} Array of ChatMessage objects (copy)
281
+ */
282
+ getHistory() {
283
+ return [...this.#messageHistory]
284
+ }
285
+
286
+ /**
287
+ * Clear the message history.
288
+ */
289
+ clearHistory() {
290
+ this.#messageHistory = []
291
+ }
292
+
293
+ /**
294
+ * Add a message to history, enforcing the max history limit.
295
+ *
296
+ * @param {object} message - ChatMessage to add
297
+ */
298
+ #addToHistory(message) {
299
+ this.#messageHistory.push(message)
300
+ if (this.#messageHistory.length > this.#maxHistory) {
301
+ this.#messageHistory = this.#messageHistory.slice(-this.#maxHistory)
302
+ }
303
+ }
304
+
305
+ // -- Events ---------------------------------------------------------------
306
+
307
+ /**
308
+ * Register a listener for a chat event.
309
+ * Events: 'message:sent', 'message:received', 'typing'
310
+ *
311
+ * @param {string} event - Event name
312
+ * @param {Function} cb - Callback function
313
+ */
314
+ on(event, cb) {
315
+ if (!this.#listeners.has(event)) {
316
+ this.#listeners.set(event, new Set())
317
+ }
318
+ this.#listeners.get(event).add(cb)
319
+ }
320
+
321
+ /**
322
+ * Remove a listener for a chat event.
323
+ *
324
+ * @param {string} event - Event name
325
+ * @param {Function} cb - Callback function
326
+ */
327
+ off(event, cb) {
328
+ const set = this.#listeners.get(event)
329
+ if (set) set.delete(cb)
330
+ }
331
+
332
+ /**
333
+ * Emit an event to all registered listeners.
334
+ *
335
+ * @param {string} event - Event name
336
+ * @param {*} data - Event data
337
+ */
338
+ #emit(event, data) {
339
+ const set = this.#listeners.get(event)
340
+ if (!set) return
341
+ for (const cb of [...set]) {
342
+ try {
343
+ cb(data)
344
+ } catch {
345
+ /* listener errors do not propagate */
346
+ }
347
+ }
348
+ }
349
+
350
+ // -- Cleanup --------------------------------------------------------------
351
+
352
+ /**
353
+ * Close the peer chat. Removes the handler from the session.
354
+ */
355
+ close() {
356
+ this.#session.removeHandler('chat')
357
+ this.#listeners.clear()
358
+ }
359
+
360
+ // -- Serialization --------------------------------------------------------
361
+
362
+ /**
363
+ * Serialize to a JSON-safe object.
364
+ *
365
+ * @returns {object}
366
+ */
367
+ toJSON() {
368
+ return {
369
+ sessionId: this.#session.sessionId,
370
+ localPodId: this.#session.localPodId,
371
+ remotePodId: this.#session.remotePodId,
372
+ messageCount: this.#messageHistory.length,
373
+ maxHistory: this.#maxHistory,
374
+ hasSignFn: !!this.#signFn,
375
+ hasVerifyFn: !!this.#verifyFn,
376
+ hasRemotePubKey: !!this.#remotePubKey,
377
+ hasAutoResponder: !!this.#autoResponder,
378
+ messages: this.#messageHistory.map(m => ({ ...m })),
379
+ }
380
+ }
381
+ }