@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,500 @@
1
+ /**
2
+ // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
+ * clawser-peer-terminal.js -- Remote terminal access over peer sessions.
4
+ *
5
+ * Allows one peer to execute commands on another's virtual shell via
6
+ * TerminalHost (accepts and executes) and TerminalClient (sends and
7
+ * awaits results). Built on top of PeerSession's service handler system
8
+ * using the 'terminal' service type.
9
+ *
10
+ * Dependencies are injected (PeerSession, shell).
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-terminal.test.mjs
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Constants
19
+ // ---------------------------------------------------------------------------
20
+
21
+ export const TERMINAL_DEFAULTS = Object.freeze({
22
+ maxOutputLength: 65536, // 64KB
23
+ timeout: 30000, // 30s
24
+ blockedCommands: ['exit', 'shutdown', 'reboot', 'halt', 'poweroff'],
25
+ })
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Internal — extract the command name (first token) from a command string.
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /**
32
+ * Extract the first token from a command string after trimming.
33
+ * Handles quoted prefixes (e.g. `"my cmd" arg`) by stripping quotes.
34
+ *
35
+ * @param {string} command - Full command string
36
+ * @returns {string} First token, lowercased
37
+ */
38
+ function extractCommandName(command) {
39
+ const trimmed = (command || '').trim()
40
+ if (!trimmed) return ''
41
+
42
+ // Handle quoted first token
43
+ if (trimmed[0] === '"' || trimmed[0] === "'") {
44
+ const quote = trimmed[0]
45
+ const end = trimmed.indexOf(quote, 1)
46
+ if (end > 1) {
47
+ return trimmed.slice(1, end).toLowerCase()
48
+ }
49
+ // Unterminated quote — strip leading quote and fall through
50
+ }
51
+
52
+ // Split on whitespace and take first token, strip any remaining quotes
53
+ const first = trimmed.split(/\s+/)[0].replace(/^["']|["']$/g, '')
54
+ return first.toLowerCase()
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // TerminalHost
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * Accepts incoming terminal requests from remote peers and executes
63
+ * commands on the local shell.
64
+ *
65
+ * Registers a handler on the PeerSession for the 'terminal' service
66
+ * type. Incoming command requests are validated against an allowlist /
67
+ * blocklist before execution. The remote peer must hold the
68
+ * 'terminal:execute' capability on the session.
69
+ */
70
+ export class TerminalHost {
71
+ /** @type {object} PeerSession */
72
+ #session
73
+
74
+ /** @type {object} shell with execute(command) → { output, exitCode } */
75
+ #shell
76
+
77
+ /** @type {Set<string>|null} null means all commands allowed (minus blocked) */
78
+ #allowedCommands
79
+
80
+ /** @type {Set<string>} always blocked */
81
+ #blockedCommands
82
+
83
+ /** @type {number} */
84
+ #maxOutputLength
85
+
86
+ /** @type {Function} */
87
+ #onLog
88
+
89
+ /** @type {number} commands executed */
90
+ #executionCount = 0
91
+
92
+ /**
93
+ * @param {object} opts
94
+ * @param {object} opts.session - PeerSession instance
95
+ * @param {object} opts.shell - Object with execute(command) → { output, exitCode }
96
+ * @param {string[]|Set<string>} [opts.allowedCommands] - Whitelist; null/undefined means all allowed
97
+ * @param {string[]|Set<string>} [opts.blockedCommands] - Always blocked commands
98
+ * @param {number} [opts.maxOutputLength=65536] - Truncate output beyond this length
99
+ * @param {Function} [opts.onLog] - Logging callback
100
+ */
101
+ constructor({ session, shell, allowedCommands, blockedCommands, maxOutputLength, onLog }) {
102
+ if (!session) {
103
+ throw new Error('session is required')
104
+ }
105
+ if (!shell || typeof shell.execute !== 'function') {
106
+ throw new Error('shell with execute() method is required')
107
+ }
108
+
109
+ this.#session = session
110
+ this.#shell = shell
111
+ this.#onLog = onLog || (() => {})
112
+ this.#maxOutputLength = maxOutputLength ?? TERMINAL_DEFAULTS.maxOutputLength
113
+
114
+ // Normalize allowedCommands
115
+ if (allowedCommands != null) {
116
+ this.#allowedCommands = new Set(
117
+ (Array.isArray(allowedCommands) ? allowedCommands : [...allowedCommands])
118
+ .map(c => c.toLowerCase())
119
+ )
120
+ } else {
121
+ this.#allowedCommands = null
122
+ }
123
+
124
+ // Normalize blockedCommands — merge with defaults
125
+ const defaultBlocked = TERMINAL_DEFAULTS.blockedCommands
126
+ const userBlocked = blockedCommands
127
+ ? (Array.isArray(blockedCommands) ? blockedCommands : [...blockedCommands])
128
+ : []
129
+ this.#blockedCommands = new Set(
130
+ [...defaultBlocked, ...userBlocked].map(c => c.toLowerCase())
131
+ )
132
+
133
+ // Register handler on session for 'terminal' service type
134
+ this.#session.registerHandler('terminal', (envelope) => this.#handleCommand(envelope))
135
+ }
136
+
137
+ // -- Command handling (private) -------------------------------------------
138
+
139
+ /**
140
+ * Handle an incoming terminal command request.
141
+ *
142
+ * 1. Checks 'terminal:execute' capability on session
143
+ * 2. Validates command against allowlist/blocklist
144
+ * 3. Executes on the local shell
145
+ * 4. Truncates output if necessary
146
+ * 5. Sends response back via session
147
+ *
148
+ * @param {object} envelope - Session envelope with payload
149
+ */
150
+ async #handleCommand(envelope) {
151
+ const payload = envelope.payload || envelope
152
+ const { command, requestId, resize } = payload
153
+
154
+ // Build base response
155
+ const response = { requestId: requestId || null }
156
+
157
+ try {
158
+ // 0. Handle resize events (informational, no response needed)
159
+ if (resize && typeof resize === 'object' && !command) {
160
+ this.#onLog(2, `Terminal resize from ${this.#session.remotePodId}: ${resize.cols}x${resize.rows}`)
161
+ return
162
+ }
163
+
164
+ // 1. Check capability
165
+ this.#session.requireCapability('terminal:execute')
166
+
167
+ // 2. Validate command is a non-empty string
168
+ if (!command || typeof command !== 'string') {
169
+ response.output = 'Error: command must be a non-empty string'
170
+ response.exitCode = 1
171
+ this.#session.send('terminal', response)
172
+ return
173
+ }
174
+
175
+ // 3. Check against allowlist / blocklist
176
+ if (!this.isCommandAllowed(command)) {
177
+ const name = extractCommandName(command)
178
+ response.output = `Error: command "${name}" is not allowed`
179
+ response.exitCode = 126
180
+ this.#session.send('terminal', response)
181
+ this.#onLog(1, `Blocked terminal command "${name}" from ${this.#session.remotePodId}`)
182
+ return
183
+ }
184
+
185
+ // 4. Execute on the local shell
186
+ this.#onLog(2, `Executing terminal command from ${this.#session.remotePodId}: ${command}`)
187
+ const result = await this.#shell.execute(command)
188
+ this.#executionCount++
189
+
190
+ let output = result.output != null ? String(result.output) : ''
191
+ let truncated = false
192
+
193
+ // 5. Truncate if needed
194
+ if (output.length > this.#maxOutputLength) {
195
+ output = output.slice(0, this.#maxOutputLength)
196
+ truncated = true
197
+ }
198
+
199
+ response.output = output
200
+ response.exitCode = result.exitCode ?? 0
201
+ if (truncated) {
202
+ response.truncated = true
203
+ }
204
+ } catch (err) {
205
+ response.output = `Error: ${err.message}`
206
+ response.exitCode = 1
207
+ this.#onLog(0, `Terminal command error: ${err.message}`)
208
+ }
209
+
210
+ // Send response back
211
+ this.#session.send('terminal', response)
212
+ }
213
+
214
+ // -- Command filtering ----------------------------------------------------
215
+
216
+ /**
217
+ * Check whether a command string is allowed to execute.
218
+ *
219
+ * Extracts the first token (command name), checks against the
220
+ * blocklist first, then the allowlist.
221
+ *
222
+ * @param {string} command - Full command string
223
+ * @returns {boolean}
224
+ */
225
+ isCommandAllowed(command) {
226
+ const name = extractCommandName(command)
227
+ if (!name) return false
228
+
229
+ // Blocklist always wins
230
+ if (this.#blockedCommands.has(name)) {
231
+ return false
232
+ }
233
+
234
+ // If no allowlist is set, all non-blocked commands are allowed
235
+ if (this.#allowedCommands === null) {
236
+ return true
237
+ }
238
+
239
+ // Check against allowlist
240
+ return this.#allowedCommands.has(name)
241
+ }
242
+
243
+ // -- Lifecycle ------------------------------------------------------------
244
+
245
+ /**
246
+ * Close the terminal host. Removes the handler from the session.
247
+ */
248
+ close() {
249
+ this.#session.removeHandler('terminal')
250
+ }
251
+
252
+ // -- Serialization --------------------------------------------------------
253
+
254
+ /**
255
+ * Serialize to a JSON-safe object.
256
+ *
257
+ * @returns {object}
258
+ */
259
+ toJSON() {
260
+ return {
261
+ sessionId: this.#session.sessionId,
262
+ localPodId: this.#session.localPodId,
263
+ remotePodId: this.#session.remotePodId,
264
+ allowedCommands: this.#allowedCommands ? [...this.#allowedCommands] : null,
265
+ blockedCommands: [...this.#blockedCommands],
266
+ maxOutputLength: this.#maxOutputLength,
267
+ executionCount: this.#executionCount,
268
+ }
269
+ }
270
+ }
271
+
272
+ // ---------------------------------------------------------------------------
273
+ // TerminalClient
274
+ // ---------------------------------------------------------------------------
275
+
276
+ /**
277
+ * Client-side interface for executing commands on a remote peer's terminal.
278
+ *
279
+ * Sends command requests via the PeerSession and waits for responses
280
+ * matched by requestId. Supports configurable timeout per command and
281
+ * emits events for output and errors.
282
+ */
283
+ export class TerminalClient {
284
+ /** @type {object} PeerSession */
285
+ #session
286
+
287
+ /** @type {Map<string, { resolve: Function, reject: Function, timer: * }>} */
288
+ #pendingRequests = new Map()
289
+
290
+ /** @type {number} default timeout in ms */
291
+ #timeout
292
+
293
+ /** @type {Function} */
294
+ #onLog
295
+
296
+ /** @type {Map<string, Set<Function>>} */
297
+ #listeners = new Map()
298
+
299
+ /**
300
+ * @param {object} opts
301
+ * @param {object} opts.session - PeerSession instance
302
+ * @param {number} [opts.timeout=30000] - Default timeout for commands in ms
303
+ * @param {Function} [opts.onLog] - Logging callback
304
+ */
305
+ constructor({ session, timeout, onLog }) {
306
+ if (!session) {
307
+ throw new Error('session is required')
308
+ }
309
+
310
+ this.#session = session
311
+ this.#timeout = timeout ?? TERMINAL_DEFAULTS.timeout
312
+ this.#onLog = onLog || (() => {})
313
+
314
+ // Register handler on session for 'terminal' response messages
315
+ this.#session.registerHandler('terminal', (envelope) => this.#handleResponse(envelope))
316
+ }
317
+
318
+ // -- Command execution ----------------------------------------------------
319
+
320
+ /**
321
+ * Execute a command on the remote peer's terminal.
322
+ *
323
+ * Sends the command with a unique requestId, then waits for the
324
+ * matching response or times out.
325
+ *
326
+ * @param {string} command - Command to execute
327
+ * @param {object} [opts]
328
+ * @param {number} [opts.timeout] - Override the default timeout for this command
329
+ * @returns {Promise<{ output: string, exitCode: number, truncated?: boolean }>}
330
+ */
331
+ async execute(command, opts) {
332
+ if (!command || typeof command !== 'string') {
333
+ throw new Error('command must be a non-empty string')
334
+ }
335
+
336
+ const requestId = crypto.randomUUID()
337
+ const timeoutMs = opts?.timeout ?? this.#timeout
338
+
339
+ return new Promise((resolve, reject) => {
340
+ // Set up timeout
341
+ const timer = setTimeout(() => {
342
+ const pending = this.#pendingRequests.get(requestId)
343
+ if (pending) {
344
+ this.#pendingRequests.delete(requestId)
345
+ const err = new Error(`Terminal command timed out after ${timeoutMs}ms`)
346
+ err.code = 'TERMINAL_TIMEOUT'
347
+ this.#emit('error', { requestId, error: err.message })
348
+ reject(err)
349
+ }
350
+ }, timeoutMs)
351
+
352
+ // Register pending request
353
+ this.#pendingRequests.set(requestId, { resolve, reject, timer })
354
+
355
+ // Send command to remote host
356
+ try {
357
+ this.#session.send('terminal', { command, requestId })
358
+ this.#onLog(2, `Sent terminal command to ${this.#session.remotePodId}: ${command}`)
359
+ } catch (err) {
360
+ clearTimeout(timer)
361
+ this.#pendingRequests.delete(requestId)
362
+ reject(err)
363
+ }
364
+ })
365
+ }
366
+
367
+ // -- Resize ---------------------------------------------------------------
368
+
369
+ /**
370
+ * Send a resize event to the remote terminal (informational).
371
+ * Does not wait for a response.
372
+ *
373
+ * @param {number} cols - Number of columns
374
+ * @param {number} rows - Number of rows
375
+ */
376
+ sendResize(cols, rows) {
377
+ this.#session.send('terminal', {
378
+ resize: { cols, rows },
379
+ })
380
+ }
381
+
382
+ // -- Response handling (private) ------------------------------------------
383
+
384
+ /**
385
+ * Handle an incoming terminal response from the remote host.
386
+ * Matches by requestId and resolves the pending promise.
387
+ *
388
+ * @param {object} envelope - Session envelope with payload
389
+ */
390
+ #handleResponse(envelope) {
391
+ const payload = envelope.payload || envelope
392
+ const { requestId, output, exitCode, truncated } = payload
393
+
394
+ if (!requestId) return
395
+
396
+ const pending = this.#pendingRequests.get(requestId)
397
+ if (!pending) return
398
+
399
+ // Clean up
400
+ clearTimeout(pending.timer)
401
+ this.#pendingRequests.delete(requestId)
402
+
403
+ const result = {
404
+ output: output != null ? String(output) : '',
405
+ exitCode: exitCode ?? 0,
406
+ }
407
+ if (truncated) {
408
+ result.truncated = true
409
+ }
410
+
411
+ // Emit output event
412
+ this.#emit('output', result)
413
+
414
+ // Resolve the pending promise
415
+ pending.resolve(result)
416
+ }
417
+
418
+ // -- Events ---------------------------------------------------------------
419
+
420
+ /**
421
+ * Register a listener for a terminal client event.
422
+ * Events: 'output', 'error'
423
+ *
424
+ * @param {string} event - Event name
425
+ * @param {Function} cb - Callback function
426
+ */
427
+ on(event, cb) {
428
+ if (!this.#listeners.has(event)) {
429
+ this.#listeners.set(event, new Set())
430
+ }
431
+ this.#listeners.get(event).add(cb)
432
+ }
433
+
434
+ /**
435
+ * Remove a listener for a terminal client event.
436
+ *
437
+ * @param {string} event - Event name
438
+ * @param {Function} cb - Callback function
439
+ */
440
+ off(event, cb) {
441
+ const set = this.#listeners.get(event)
442
+ if (set) set.delete(cb)
443
+ }
444
+
445
+ /**
446
+ * Emit an event to all registered listeners.
447
+ *
448
+ * @param {string} event - Event name
449
+ * @param {*} data - Event data
450
+ */
451
+ #emit(event, data) {
452
+ const set = this.#listeners.get(event)
453
+ if (!set) return
454
+ for (const cb of [...set]) {
455
+ try {
456
+ cb(data)
457
+ } catch {
458
+ /* listener errors do not propagate */
459
+ }
460
+ }
461
+ }
462
+
463
+ // -- Cleanup --------------------------------------------------------------
464
+
465
+ /**
466
+ * Close the terminal client. Removes the handler from the session
467
+ * and rejects all pending requests.
468
+ */
469
+ close() {
470
+ // Reject all pending requests
471
+ for (const [requestId, pending] of this.#pendingRequests) {
472
+ clearTimeout(pending.timer)
473
+ pending.reject(new Error('TerminalClient closed'))
474
+ }
475
+ this.#pendingRequests.clear()
476
+
477
+ // Remove handler from session
478
+ this.#session.removeHandler('terminal')
479
+
480
+ // Clear listeners
481
+ this.#listeners.clear()
482
+ }
483
+
484
+ // -- Serialization --------------------------------------------------------
485
+
486
+ /**
487
+ * Serialize to a JSON-safe object.
488
+ *
489
+ * @returns {object}
490
+ */
491
+ toJSON() {
492
+ return {
493
+ sessionId: this.#session.sessionId,
494
+ localPodId: this.#session.localPodId,
495
+ remotePodId: this.#session.remotePodId,
496
+ pendingRequests: this.#pendingRequests.size,
497
+ timeout: this.#timeout,
498
+ }
499
+ }
500
+ }