@johnhenry/browsermesh-apps 0.2.0 → 0.3.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.
Files changed (41) hide show
  1. package/README.md +232 -1
  2. package/package.json +2 -2
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +25 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/peer-session.mjs +0 -937
@@ -1,17 +1,130 @@
1
1
  /**
2
- // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
- * clawser-peer-terminal.js -- Remote terminal access over peer sessions.
2
+ * peer-terminal.mjs -- Remote terminal/shell execution over the mesh.
4
3
  *
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.
4
+ * Allows one peer to execute commands on another's shell through
5
+ * `TerminalHost` (accepts and executes) and `TerminalClient` (sends and
6
+ * awaits results). Built as a `MeshService` (`mesh-service.mjs`, the same
7
+ * `attach(peerNode, ctx) -> {teardown, api}` convention `mesh-rpc.mjs`/
8
+ * `peer-files.mjs`/`peer-escrow.mjs` etc. already use), NOT on top of
9
+ * `peer-session.mjs`'s `PeerSession`/`SessionManager` -- see "Migration
10
+ * history" below.
9
11
  *
10
- * Dependencies are injected (PeerSession, shell).
11
- * No browser-only imports at module level.
12
+ * ---------------------------------------------------------------------------
13
+ * Migration history (issue #84, Phase 10 of the app-layer migration plan;
14
+ * blocked on issue #86 until its design pass resolved what gates remote
15
+ * shell execution):
16
+ *
17
+ * This file used to depend on `peer-session.mjs`'s `PeerSession` --
18
+ * `TerminalHost`'s constructor called `session.registerHandler('terminal', ...)`
19
+ * directly and `#handleCommand()` called `session.requireCapability('terminal:execute')`/
20
+ * `session.send()`/`session.remotePodId`; `TerminalClient` did the same for
21
+ * its own `registerHandler('terminal', ...)`/`session.send()`. Nothing in
22
+ * this repo ever constructed a live `PeerSession` (`SessionManager` is never
23
+ * instantiated outside its own tests) -- exactly the same dead-dependency
24
+ * situation Phase 8 (`peer-files.mjs`) and Phase 9 (`peer-chat.mjs`) already
25
+ * found and fixed -- so this migration removes the `PeerSession` dependency
26
+ * entirely rather than bridging it.
27
+ *
28
+ * Issue #86's resolved design pass (see that issue's closing comment) settled
29
+ * TWO things this file depends on directly:
30
+ *
31
+ * 1. GATE MECHANISM: `ctx.registry.checkAccess(pubKey, resource, action)`,
32
+ * the SAME mechanism `mesh-relay-host.mjs` already used and Phases 3/4/
33
+ * 8/9 of this plan (`peer-escrow.mjs`/`mesh-verification.mjs`/
34
+ * `peer-files.mjs`/`peer-chat.mjs`) independently converged on for their
35
+ * own peer-initiated risky actions -- NOT `WasmSandbox`
36
+ * (`browsermesh-core/src/capabilities.mjs`), which has zero real target
37
+ * anywhere in this repo (no `WebAssembly.*` calls, no `.wasm` files),
38
+ * and not `browsermesh-kernel`'s tenant capability model, which gates
39
+ * *local* application code with no concept of a remote requester.
40
+ * `session.requireCapability('terminal:execute')` (a static,
41
+ * per-session capability list check) becomes
42
+ * `checkAccess(fromPubKey, TERMINAL_RESOURCE, TERMINAL_ACTION)` --
43
+ * live, per-request, per-sender ACL/capability-token checking via
44
+ * `PeerRegistry` (`peer-registry.mjs`), called from the SAME place in
45
+ * the request-handling flow the old `requireCapability()` call sat
46
+ * (`TerminalHost#handleRequest()`'s step 1, before any command
47
+ * validation/allowlist/execution) -- see `TERMINAL_RESOURCE`/
48
+ * `TERMINAL_ACTION` below. No default template in
49
+ * `@johnhenry/browsermesh-core`'s `acl.mjs` (`guest`/`collaborator`/
50
+ * `admin`) grants `terminal:execute` -- unlike `files:read`/
51
+ * `chat:*`/`compute:submit`, a peer gets NOTHING here until the node
52
+ * operator explicitly calls `registry.grantCapabilities(peerPubKey,
53
+ * ['terminal:execute'])`, a deliberate omission given the subject
54
+ * matter (real remote command execution, not a read/write file or chat
55
+ * message).
56
+ * A single coarse `'terminal'`/`'execute'` scope (not per-command or
57
+ * per-target-pod) is used -- mirroring `mesh-verification.mjs`'s own
58
+ * single `'verification'`/`'execute'` gate for the same reason that
59
+ * file documents: there is no natural per-resource id to scope against
60
+ * the way `peer-escrow.mjs`'s per-contract `escrow:<contractId>:release`
61
+ * grants exist (a contract id is created by `create()` and can be
62
+ * auto-granted to its real payer/payee; a terminal command has no
63
+ * equivalent identity to grant against before it's even sent). A node
64
+ * operator who wants finer-grained terminal access per peer should grant/
65
+ * revoke the single `terminal:execute` scope per peer via
66
+ * `registry.grantCapabilities()`/`revokeCapabilities()`, and rely on
67
+ * `TerminalHost`'s own `allowedCommands`/`blockedCommands` allow/deny
68
+ * list (unchanged from the pre-migration version) for per-command
69
+ * restriction.
70
+ *
71
+ * 2. EXECUTION BACKEND: bring-your-own, REQUIRED, no default shipped.
72
+ * Neither the pre-migration nor this file has ever had a real `shell`
73
+ * implementation anywhere in this repo -- only `createMockShell()` in
74
+ * this file's own test. This migration does NOT add one (no
75
+ * `child_process`, no OS command execution) -- that would be a much
76
+ * bigger, separately-decided scope. `createTerminalService()` requires
77
+ * `opts.shell` (an object with `execute(command) -> {output, exitCode}`);
78
+ * omitting it throws immediately when the descriptor is `attach()`ed
79
+ * (the same point `TerminalHost`'s own pre-migration constructor already
80
+ * threw at), and `createMeshNode({enableTerminal: true})` throws even
81
+ * earlier, before attaching anything, if `terminalOptions.shell` is
82
+ * missing -- mirroring `enableEscrow`'s required-dependency-throws-if-
83
+ * missing precedent for `escrowOptions.creditLedger` (see
84
+ * `mesh-bootstrap.mjs`). This is deliberate, safe-by-construction
85
+ * design: nobody gets real remote shell execution just by flipping
86
+ * `enableTerminal: true` -- they must also consciously wire up a real
87
+ * executor.
88
+ *
89
+ * `TerminalHost#handleRequest()`'s command-filtering/execution/truncation
90
+ * logic (`isCommandAllowed()`, blocklist-always-wins-over-allowlist,
91
+ * `maxOutputLength` truncation) is UNCHANGED from the `PeerSession`-era
92
+ * version -- only the transport/correlation/authorization plumbing changed:
93
+ * - `TerminalHost` no longer owns "who do I reply to" (a `PeerSession`
94
+ * bound to exactly one remote peer) -- `handleRequest(fromPubKey, payload)`
95
+ * is now a pure function that COMPUTES and RETURNS a response (or `null`
96
+ * for an informational resize event, which needs no response); the
97
+ * caller (`createTerminalService()`'s `attach()`, below) sends it via
98
+ * `ctx.sendTo()`. This is the same necessary shape change `peer-files.mjs`
99
+ * went through: a `MeshService` is attached once per NODE and can be
100
+ * asked to execute commands by any connected peer holding
101
+ * `terminal:execute`, not once per peer-pair the way a `PeerSession` was.
102
+ * - `TerminalClient` no longer wraps one `PeerSession` bound to one remote
103
+ * peer -- `execute(pubKey, command, opts)`/`sendResize(pubKey, cols, rows)`
104
+ * now take a leading `pubKey` argument, since one `TerminalClient` (like
105
+ * `peer-files.mjs`'s `FileClient`) can request execution from ANY
106
+ * connected peer, not just one fixed session. Internally it still does
107
+ * exactly what it did before: generate a `requestId`, track a
108
+ * `{resolve, reject, timer}` in a pending-requests map, and correlate the
109
+ * eventual response by that id -- this was ALREADY a self-contained
110
+ * `requestId`-based correlation mechanism (not something `PeerSession`
111
+ * provided), so no new correlation primitive had to be invented; it's the
112
+ * exact same shape `peer-files.mjs`'s `FileClient` and `mesh-rpc.mjs`'s
113
+ * `request()` use. The one addition: each pending entry also records the
114
+ * `pubKey` the request targeted, and `handleResponse()` ignores a reply
115
+ * from any OTHER peer even if it happens to guess/replay a `requestId` --
116
+ * a property the old design got "for free" (a `PeerSession`'s transport
117
+ * only ever delivered messages from the one peer it was bound to) that a
118
+ * shared, node-wide `onIncomingData()` subscription does not.
119
+ *
120
+ * `createTerminalService()` is ONE `MeshService` covering both directions
121
+ * (hosting a shell to others, and requesting execution from others) -- both
122
+ * share the same `terminal-request`/`terminal-response` envelope-type pair
123
+ * and the same `ctx.onIncomingData()` subscription, mirroring
124
+ * `peer-files.mjs`'s `createFileShareService()` exactly.
12
125
  *
13
126
  * Run tests:
14
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-terminal.test.mjs
127
+ * node --import ./test/_setup-globals.mjs --test test/peer-terminal.test.mjs
15
128
  */
16
129
 
17
130
  // ---------------------------------------------------------------------------
@@ -24,6 +137,16 @@ export const TERMINAL_DEFAULTS = Object.freeze({
24
137
  blockedCommands: ['exit', 'shutdown', 'reboot', 'halt', 'poweroff'],
25
138
  })
26
139
 
140
+ /** `ctx.registry.checkAccess()` resource name used for exec requests (see module doc comment's "Migration history", point 1). */
141
+ export const TERMINAL_RESOURCE = 'terminal'
142
+ /** `ctx.registry.checkAccess()` action name used for exec requests. A single coarse scope -- see module doc comment for why there is no finer-grained per-command/per-target scope. */
143
+ export const TERMINAL_ACTION = 'execute'
144
+
145
+ /** Default `envelope.type` for a terminal request (exec or resize), on the shared `ctx.onIncomingData()` bus. */
146
+ const DEFAULT_TERMINAL_REQUEST_ENVELOPE_TYPE = 'terminal-request'
147
+ /** Default `envelope.type` for a terminal response. */
148
+ const DEFAULT_TERMINAL_RESPONSE_ENVELOPE_TYPE = 'terminal-response'
149
+
27
150
  // ---------------------------------------------------------------------------
28
151
  // Internal — extract the command name (first token) from a command string.
29
152
  // ---------------------------------------------------------------------------
@@ -59,18 +182,15 @@ function extractCommandName(command) {
59
182
  // ---------------------------------------------------------------------------
60
183
 
61
184
  /**
62
- * Accepts incoming terminal requests from remote peers and executes
63
- * commands on the local shell.
185
+ * Serves terminal-execution requests from the local shell to remote peers.
64
186
  *
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.
187
+ * Framework-agnostic: `handleRequest()` is a pure function that computes and
188
+ * RETURNS a response (or `null` for an informational resize event), it does
189
+ * not send anything itself -- see module doc comment's "Migration history".
190
+ * `createTerminalService()` (below) is what actually wires this to
191
+ * `ctx.onIncomingData()`/`ctx.sendTo()`.
69
192
  */
70
193
  export class TerminalHost {
71
- /** @type {object} PeerSession */
72
- #session
73
-
74
194
  /** @type {object} shell with execute(command) → { output, exitCode } */
75
195
  #shell
76
196
 
@@ -86,30 +206,40 @@ export class TerminalHost {
86
206
  /** @type {Function} */
87
207
  #onLog
88
208
 
209
+ /** @type {(fromPubKey: string) => ({allowed: boolean, reason?: string})} */
210
+ #checkAccess
211
+
89
212
  /** @type {number} commands executed */
90
213
  #executionCount = 0
91
214
 
92
215
  /**
93
216
  * @param {object} opts
94
- * @param {object} opts.session - PeerSession instance
95
- * @param {object} opts.shell - Object with execute(command) → { output, exitCode }
217
+ * @param {object} opts.shell - Object with execute(command) → { output, exitCode }.
218
+ * REQUIRED -- there is no default shell (see module doc comment's
219
+ * "Migration history", point 2). Constructing a `TerminalHost` with no
220
+ * real `shell` throws immediately.
96
221
  * @param {string[]|Set<string>} [opts.allowedCommands] - Whitelist; null/undefined means all allowed
97
222
  * @param {string[]|Set<string>} [opts.blockedCommands] - Always blocked commands
98
223
  * @param {number} [opts.maxOutputLength=65536] - Truncate output beyond this length
99
224
  * @param {Function} [opts.onLog] - Logging callback
225
+ * @param {(fromPubKey: string) => ({allowed: boolean, reason?: string})} [opts.checkAccess]
226
+ * Capability check for a given requester. `createTerminalService()`
227
+ * supplies `(fromPubKey) => ctx.registry.checkAccess(fromPubKey, TERMINAL_RESOURCE, TERMINAL_ACTION)`.
228
+ * Defaults to permissive (`{ allowed: true }` for everyone) when
229
+ * constructed directly without one -- a `TerminalHost` built by hand
230
+ * (e.g. in a unit test) has no registry of its own to consult; supplying
231
+ * real gating is the caller's responsibility, exactly like
232
+ * `peer-files.mjs`'s `FileHost`.
100
233
  */
101
- constructor({ session, shell, allowedCommands, blockedCommands, maxOutputLength, onLog }) {
102
- if (!session) {
103
- throw new Error('session is required')
104
- }
234
+ constructor({ shell, allowedCommands, blockedCommands, maxOutputLength, onLog, checkAccess }) {
105
235
  if (!shell || typeof shell.execute !== 'function') {
106
236
  throw new Error('shell with execute() method is required')
107
237
  }
108
238
 
109
- this.#session = session
110
239
  this.#shell = shell
111
240
  this.#onLog = onLog || (() => {})
112
241
  this.#maxOutputLength = maxOutputLength ?? TERMINAL_DEFAULTS.maxOutputLength
242
+ this.#checkAccess = typeof checkAccess === 'function' ? checkAccess : () => ({ allowed: true })
113
243
 
114
244
  // Normalize allowedCommands
115
245
  if (allowedCommands != null) {
@@ -129,68 +259,70 @@ export class TerminalHost {
129
259
  this.#blockedCommands = new Set(
130
260
  [...defaultBlocked, ...userBlocked].map(c => c.toLowerCase())
131
261
  )
132
-
133
- // Register handler on session for 'terminal' service type
134
- this.#session.registerHandler('terminal', (envelope) => this.#handleCommand(envelope))
135
262
  }
136
263
 
137
- // -- Command handling (private) -------------------------------------------
264
+ // -- Request handling -------------------------------------------------------
138
265
 
139
266
  /**
140
- * Handle an incoming terminal command request.
267
+ * Handle an incoming terminal request from `fromPubKey`.
141
268
  *
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
269
+ * 1. Handles resize events (informational -- returns `null`, no response needed)
270
+ * 2. Checks access via the injected `checkAccess`
271
+ * 3. Validates command is a non-empty string
272
+ * 4. Validates command against allowlist/blocklist
273
+ * 5. Executes on the local shell, truncating output if necessary
147
274
  *
148
- * @param {object} envelope - Session envelope with payload
275
+ * @param {string} fromPubKey - Requesting peer's public key
276
+ * @param {object} payload - `{ command, requestId, resize }`
277
+ * @returns {Promise<{requestId: string|null, output: string, exitCode: number, truncated?: boolean}|null>}
278
+ * `null` for a resize event (no response should be sent).
149
279
  */
150
- async #handleCommand(envelope) {
151
- const payload = envelope.payload || envelope
152
- const { command, requestId, resize } = payload
280
+ async handleRequest(fromPubKey, payload) {
281
+ const { command, requestId, resize } = payload || {}
153
282
 
154
- // Build base response
155
- const response = { requestId: requestId || null }
283
+ // 1. Handle resize events (informational, no response needed)
284
+ if (resize && typeof resize === 'object' && !command) {
285
+ this.#onLog(2, `Terminal resize from ${fromPubKey}: ${resize.cols}x${resize.rows}`)
286
+ return null
287
+ }
156
288
 
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
- }
289
+ const response = { requestId: requestId || null }
163
290
 
164
- // 1. Check capability
165
- this.#session.requireCapability('terminal:execute')
291
+ // 2. Check access
292
+ const { allowed, reason } = this.#checkAccess(fromPubKey) || {}
293
+ if (!allowed) {
294
+ response.output = `Error: capability "${TERMINAL_RESOURCE}:${TERMINAL_ACTION}" not granted for ${fromPubKey}${reason ? ` (${reason})` : ''}`
295
+ response.exitCode = 1
296
+ response.denied = true
297
+ this.#onLog(1, `Denied terminal request from ${fromPubKey}${reason ? `: ${reason}` : ''}`)
298
+ return response
299
+ }
166
300
 
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
- }
301
+ // 3. Validate command is a non-empty string
302
+ if (!command || typeof command !== 'string') {
303
+ response.output = 'Error: command must be a non-empty string'
304
+ response.exitCode = 1
305
+ return response
306
+ }
174
307
 
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
- }
308
+ // 4. Check against allowlist / blocklist
309
+ if (!this.isCommandAllowed(command)) {
310
+ const name = extractCommandName(command)
311
+ response.output = `Error: command "${name}" is not allowed`
312
+ response.exitCode = 126
313
+ this.#onLog(1, `Blocked terminal command "${name}" from ${fromPubKey}`)
314
+ return response
315
+ }
184
316
 
185
- // 4. Execute on the local shell
186
- this.#onLog(2, `Executing terminal command from ${this.#session.remotePodId}: ${command}`)
317
+ try {
318
+ // 5. Execute on the local shell
319
+ this.#onLog(2, `Executing terminal command from ${fromPubKey}: ${command}`)
187
320
  const result = await this.#shell.execute(command)
188
321
  this.#executionCount++
189
322
 
190
323
  let output = result.output != null ? String(result.output) : ''
191
324
  let truncated = false
192
325
 
193
- // 5. Truncate if needed
194
326
  if (output.length > this.#maxOutputLength) {
195
327
  output = output.slice(0, this.#maxOutputLength)
196
328
  truncated = true
@@ -207,8 +339,7 @@ export class TerminalHost {
207
339
  this.#onLog(0, `Terminal command error: ${err.message}`)
208
340
  }
209
341
 
210
- // Send response back
211
- this.#session.send('terminal', response)
342
+ return response
212
343
  }
213
344
 
214
345
  // -- Command filtering ----------------------------------------------------
@@ -240,15 +371,6 @@ export class TerminalHost {
240
371
  return this.#allowedCommands.has(name)
241
372
  }
242
373
 
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
374
  // -- Serialization --------------------------------------------------------
253
375
 
254
376
  /**
@@ -258,9 +380,6 @@ export class TerminalHost {
258
380
  */
259
381
  toJSON() {
260
382
  return {
261
- sessionId: this.#session.sessionId,
262
- localPodId: this.#session.localPodId,
263
- remotePodId: this.#session.remotePodId,
264
383
  allowedCommands: this.#allowedCommands ? [...this.#allowedCommands] : null,
265
384
  blockedCommands: [...this.#blockedCommands],
266
385
  maxOutputLength: this.#maxOutputLength,
@@ -276,15 +395,22 @@ export class TerminalHost {
276
395
  /**
277
396
  * Client-side interface for executing commands on a remote peer's terminal.
278
397
  *
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.
398
+ * One `TerminalClient` can request execution from ANY connected peer (not
399
+ * bound to a single remote peer the way the `PeerSession`-era version was)
400
+ * -- every public method takes a leading `pubKey` argument. Requests are
401
+ * correlated to their responses by a generated `requestId`, exactly like the
402
+ * `PeerSession`-era version already did (see module doc comment's
403
+ * "Migration history"); the only addition is also recording which `pubKey`
404
+ * a request targeted, so a response claiming a stale/guessed `requestId`
405
+ * from the WRONG peer is ignored rather than resolving/rejecting the wrong
406
+ * caller's promise -- a property a per-peer `PeerSession` transport provided
407
+ * for free that a shared, node-wide subscription does not.
282
408
  */
283
409
  export class TerminalClient {
284
- /** @type {object} PeerSession */
285
- #session
410
+ /** @type {(pubKey: string, payload: object) => Promise<void>} */
411
+ #sendRequest
286
412
 
287
- /** @type {Map<string, { resolve: Function, reject: Function, timer: * }>} */
413
+ /** @type {Map<string, { resolve: Function, reject: Function, timer: *, pubKey: string }>} */
288
414
  #pendingRequests = new Map()
289
415
 
290
416
  /** @type {number} default timeout in ms */
@@ -298,37 +424,40 @@ export class TerminalClient {
298
424
 
299
425
  /**
300
426
  * @param {object} opts
301
- * @param {object} opts.session - PeerSession instance
427
+ * @param {(pubKey: string, payload: object) => Promise<void>} opts.sendRequest
428
+ * Sends a `terminal-request`-shaped payload to `pubKey`. `createTerminalService()`
429
+ * supplies `(pubKey, payload) => ctx.sendTo(pubKey, 'terminal-request', payload)`.
302
430
  * @param {number} [opts.timeout=30000] - Default timeout for commands in ms
303
431
  * @param {Function} [opts.onLog] - Logging callback
304
432
  */
305
- constructor({ session, timeout, onLog }) {
306
- if (!session) {
307
- throw new Error('session is required')
433
+ constructor({ sendRequest, timeout, onLog }) {
434
+ if (typeof sendRequest !== 'function') {
435
+ throw new Error('sendRequest function is required')
308
436
  }
309
437
 
310
- this.#session = session
438
+ this.#sendRequest = sendRequest
311
439
  this.#timeout = timeout ?? TERMINAL_DEFAULTS.timeout
312
440
  this.#onLog = onLog || (() => {})
313
-
314
- // Register handler on session for 'terminal' response messages
315
- this.#session.registerHandler('terminal', (envelope) => this.#handleResponse(envelope))
316
441
  }
317
442
 
318
443
  // -- Command execution ----------------------------------------------------
319
444
 
320
445
  /**
321
- * Execute a command on the remote peer's terminal.
446
+ * Execute a command on a remote peer's terminal.
322
447
  *
323
448
  * Sends the command with a unique requestId, then waits for the
324
449
  * matching response or times out.
325
450
  *
451
+ * @param {string} pubKey - Remote peer to execute on
326
452
  * @param {string} command - Command to execute
327
453
  * @param {object} [opts]
328
454
  * @param {number} [opts.timeout] - Override the default timeout for this command
329
455
  * @returns {Promise<{ output: string, exitCode: number, truncated?: boolean }>}
330
456
  */
331
- async execute(command, opts) {
457
+ async execute(pubKey, command, opts) {
458
+ if (!pubKey || typeof pubKey !== 'string') {
459
+ throw new Error('pubKey must be a non-empty string')
460
+ }
332
461
  if (!command || typeof command !== 'string') {
333
462
  throw new Error('command must be a non-empty string')
334
463
  }
@@ -350,52 +479,63 @@ export class TerminalClient {
350
479
  }, timeoutMs)
351
480
 
352
481
  // Register pending request
353
- this.#pendingRequests.set(requestId, { resolve, reject, timer })
482
+ this.#pendingRequests.set(requestId, { resolve, reject, timer, pubKey })
354
483
 
355
484
  // 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
- }
485
+ Promise.resolve(this.#sendRequest(pubKey, { command, requestId }))
486
+ .then(() => {
487
+ this.#onLog(2, `Sent terminal command to ${pubKey}: ${command}`)
488
+ })
489
+ .catch((err) => {
490
+ clearTimeout(timer)
491
+ this.#pendingRequests.delete(requestId)
492
+ reject(err)
493
+ })
364
494
  })
365
495
  }
366
496
 
367
497
  // -- Resize ---------------------------------------------------------------
368
498
 
369
499
  /**
370
- * Send a resize event to the remote terminal (informational).
500
+ * Send a resize event to a remote peer's terminal (informational).
371
501
  * Does not wait for a response.
372
502
  *
503
+ * @param {string} pubKey - Remote peer to notify
373
504
  * @param {number} cols - Number of columns
374
505
  * @param {number} rows - Number of rows
375
506
  */
376
- sendResize(cols, rows) {
377
- this.#session.send('terminal', {
378
- resize: { cols, rows },
507
+ sendResize(pubKey, cols, rows) {
508
+ if (!pubKey || typeof pubKey !== 'string') {
509
+ throw new Error('pubKey must be a non-empty string')
510
+ }
511
+ Promise.resolve(this.#sendRequest(pubKey, { resize: { cols, rows } })).catch((err) => {
512
+ this.#onLog(0, `Failed to send terminal resize to ${pubKey}: ${err.message}`)
379
513
  })
380
514
  }
381
515
 
382
- // -- Response handling (private) ------------------------------------------
516
+ // -- Response handling ------------------------------------------------------
383
517
 
384
518
  /**
385
- * Handle an incoming terminal response from the remote host.
386
- * Matches by requestId and resolves the pending promise.
519
+ * Handle an incoming terminal response. Matches by requestId (AND the peer
520
+ * it was sent to -- see class doc comment) and resolves the pending
521
+ * promise.
387
522
  *
388
- * @param {object} envelope - Session envelope with payload
523
+ * @param {string} fromPubKey - Peer the response actually arrived from
524
+ * @param {object} payload - `{ requestId, output, exitCode, truncated? }`
389
525
  */
390
- #handleResponse(envelope) {
391
- const payload = envelope.payload || envelope
392
- const { requestId, output, exitCode, truncated } = payload
526
+ handleResponse(fromPubKey, payload) {
527
+ const { requestId, output, exitCode, truncated } = payload || {}
393
528
 
394
529
  if (!requestId) return
395
530
 
396
531
  const pending = this.#pendingRequests.get(requestId)
397
532
  if (!pending) return
398
533
 
534
+ // A response claiming this requestId but arriving from a different peer
535
+ // than the one it was sent to is never valid -- ignore it rather than
536
+ // resolving the wrong caller's promise (see class doc comment).
537
+ if (pending.pubKey !== fromPubKey) return
538
+
399
539
  // Clean up
400
540
  clearTimeout(pending.timer)
401
541
  this.#pendingRequests.delete(requestId)
@@ -463,21 +603,15 @@ export class TerminalClient {
463
603
  // -- Cleanup --------------------------------------------------------------
464
604
 
465
605
  /**
466
- * Close the terminal client. Removes the handler from the session
467
- * and rejects all pending requests.
606
+ * Close the terminal client. Rejects all pending requests and clears
607
+ * listeners.
468
608
  */
469
609
  close() {
470
- // Reject all pending requests
471
- for (const [requestId, pending] of this.#pendingRequests) {
610
+ for (const [, pending] of this.#pendingRequests) {
472
611
  clearTimeout(pending.timer)
473
612
  pending.reject(new Error('TerminalClient closed'))
474
613
  }
475
614
  this.#pendingRequests.clear()
476
-
477
- // Remove handler from session
478
- this.#session.removeHandler('terminal')
479
-
480
- // Clear listeners
481
615
  this.#listeners.clear()
482
616
  }
483
617
 
@@ -490,11 +624,147 @@ export class TerminalClient {
490
624
  */
491
625
  toJSON() {
492
626
  return {
493
- sessionId: this.#session.sessionId,
494
- localPodId: this.#session.localPodId,
495
- remotePodId: this.#session.remotePodId,
496
627
  pendingRequests: this.#pendingRequests.size,
497
628
  timeout: this.#timeout,
498
629
  }
499
630
  }
500
631
  }
632
+
633
+ // ---------------------------------------------------------------------------
634
+ // createTerminalService -- the MeshService descriptor (issue #84, Phase 10)
635
+ // ---------------------------------------------------------------------------
636
+
637
+ /**
638
+ * Build a `MeshService` descriptor (`mesh-service.mjs`) wiring `TerminalHost`/
639
+ * `TerminalClient` onto `ctx.sendTo()`/`ctx.onIncomingData()`. One service
640
+ * covers both directions -- hosting a shell to other peers (always, since
641
+ * `shell` is required -- see below) and requesting execution from other
642
+ * peers (always available via the returned `api`) -- see module doc comment
643
+ * for why this isn't split into two descriptors.
644
+ *
645
+ * `shell` is REQUIRED -- unlike `peer-files.mjs`'s `fs` (optional, "client-
646
+ * only" if omitted), there is no client-only mode here: `attach()` throws
647
+ * immediately (via `TerminalHost`'s own constructor check) if `opts.shell`
648
+ * is missing or doesn't implement `execute()`. See module doc comment's
649
+ * "Migration history", point 2, for why this is deliberate. A node that only
650
+ * ever wants to REQUEST execution from other peers still must supply *some*
651
+ * `shell` to attach this service at all today -- if a request-only mode
652
+ * becomes a real need, that's a follow-up, not a silent default.
653
+ *
654
+ * @param {object} opts
655
+ * @param {object} opts.shell - Object with `execute(command) -> {output, exitCode}`.
656
+ * REQUIRED. No default is provided by this package (see module doc comment).
657
+ * @param {string[]|Set<string>} [opts.allowedCommands] - See `TerminalHost`.
658
+ * @param {string[]|Set<string>} [opts.blockedCommands] - See `TerminalHost`.
659
+ * @param {number} [opts.maxOutputLength] - See `TerminalHost`.
660
+ * @param {number} [opts.timeout] - See `TerminalClient`.
661
+ * @param {Function} [opts.onLog]
662
+ * @param {string} [opts.accessResource='terminal'] - `resource` passed to
663
+ * `ctx.registry.checkAccess()` for inbound exec requests (see `TERMINAL_RESOURCE`).
664
+ * @param {string} [opts.accessAction='execute'] - `action` passed to
665
+ * `ctx.registry.checkAccess()` for inbound exec requests (see `TERMINAL_ACTION`).
666
+ * @param {string} [opts.requestEnvelopeType='terminal-request']
667
+ * @param {string} [opts.responseEnvelopeType='terminal-response']
668
+ * @returns {import('./mesh-service.mjs').MeshService}
669
+ */
670
+ export function createTerminalService(opts = {}) {
671
+ const {
672
+ shell,
673
+ allowedCommands,
674
+ blockedCommands,
675
+ maxOutputLength,
676
+ timeout,
677
+ onLog,
678
+ accessResource = TERMINAL_RESOURCE,
679
+ accessAction = TERMINAL_ACTION,
680
+ requestEnvelopeType = DEFAULT_TERMINAL_REQUEST_ENVELOPE_TYPE,
681
+ responseEnvelopeType = DEFAULT_TERMINAL_RESPONSE_ENVELOPE_TYPE,
682
+ } = opts
683
+ const log = onLog || (() => {})
684
+
685
+ return {
686
+ name: 'terminal',
687
+
688
+ attach(peerNode, ctx) {
689
+ // Throws here (inside attach(), not createTerminalService() itself) if
690
+ // shell is missing/invalid -- mirrors peer-escrow.mjs's EscrowManager
691
+ // throwing inside createEscrowService()'s attach() when creditLedger
692
+ // is missing. See module doc comment's "Migration history", point 2.
693
+ const host = new TerminalHost({
694
+ shell,
695
+ allowedCommands,
696
+ blockedCommands,
697
+ maxOutputLength,
698
+ onLog,
699
+ checkAccess: (fromPubKey) => ctx.registry.checkAccess(fromPubKey, accessResource, accessAction),
700
+ })
701
+
702
+ const client = new TerminalClient({
703
+ timeout,
704
+ onLog,
705
+ sendRequest: (pubKey, payload) => ctx.sendTo(pubKey, requestEnvelopeType, payload),
706
+ })
707
+
708
+ // Bridge TerminalClient's own pre-existing on()/off() events through
709
+ // ctx.emit() -- see mesh-service.mjs's "Observability events" section
710
+ // and peer-escrow.mjs's/mesh-verification.mjs's own bridging precedent.
711
+ const onOutput = (data) => ctx.emit('terminal:output', data)
712
+ const onError = (data) => ctx.emit('terminal:error', data)
713
+ client.on('output', onOutput)
714
+ client.on('error', onError)
715
+
716
+ const unsubscribeRequests = ctx.onIncomingData(requestEnvelopeType, async (fromPubKey, msg) => {
717
+ let response
718
+ try {
719
+ response = await host.handleRequest(fromPubKey, msg)
720
+ } catch (err) {
721
+ // TerminalHost#handleRequest() already catches every shell-execution
722
+ // error itself -- reaching here would mean something unexpected
723
+ // (e.g. checkAccess() throwing). Never let it become an unhandled
724
+ // rejection or crash the shared onIncomingData() dispatch loop.
725
+ log('terminal:request-handling-failed', { from: fromPubKey, requestId: msg?.requestId, error: err?.message || String(err) })
726
+ response = { requestId: msg?.requestId ?? null, output: `Error: ${err?.message || String(err)}`, exitCode: 1 }
727
+ }
728
+
729
+ // null means an informational resize event -- no response to send.
730
+ if (response === null) return
731
+
732
+ if (response.denied) {
733
+ ctx.emit('terminal:request-denied', { from: fromPubKey, requestId: response.requestId })
734
+ } else {
735
+ ctx.emit('terminal:request-served', { from: fromPubKey, requestId: response.requestId, exitCode: response.exitCode })
736
+ }
737
+
738
+ try {
739
+ await ctx.sendTo(fromPubKey, responseEnvelopeType, response)
740
+ } catch (err) {
741
+ log('terminal:response-send-failed', { to: fromPubKey, requestId: response.requestId, error: err?.message || String(err) })
742
+ }
743
+ })
744
+
745
+ const unsubscribeResponses = ctx.onIncomingData(responseEnvelopeType, (fromPubKey, msg) => {
746
+ client.handleResponse(fromPubKey, msg)
747
+ })
748
+
749
+ const api = {
750
+ host,
751
+ client,
752
+ execute: (pubKey, command, execOpts) => client.execute(pubKey, command, execOpts),
753
+ sendResize: (pubKey, cols, rows) => client.sendResize(pubKey, cols, rows),
754
+ }
755
+
756
+ return {
757
+ api,
758
+ teardown() {
759
+ client.off('output', onOutput)
760
+ client.off('error', onError)
761
+ unsubscribeRequests()
762
+ unsubscribeResponses()
763
+ client.close()
764
+ },
765
+ }
766
+ },
767
+ }
768
+ }
769
+
770
+ export { DEFAULT_TERMINAL_REQUEST_ENVELOPE_TYPE, DEFAULT_TERMINAL_RESPONSE_ENVELOPE_TYPE }