dsh-remote-vs 0.16.0 → 0.18.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/src/forward.ts ADDED
@@ -0,0 +1,445 @@
1
+ /**
2
+ * Local TCP port forwards (`ssh -L` semantics) for the port panel.
3
+ *
4
+ * Design contract (see `docs/.feasibility/ports.md` for the reasoning):
5
+ *
6
+ * - **The listener is the resident object; every accepted TCP connection opens
7
+ * its own `direct-tcpip` channel.** That is what makes the feature compose
8
+ * with the rest of the plugin: the pool's 30-minute idle eviction, a host
9
+ * edit/delete (`drop`), and an `sync()`-driven route re-registration all
10
+ * leave the listener alone, and the next local connection simply re-dials
11
+ * through `RemotePool.forwardOut`.
12
+ * - **Loopback only.** The listener binds `127.0.0.1`, never `0.0.0.0`: this is
13
+ * `ssh -L`, so reach = the local machine's trust domain. `Expose on the LAN`
14
+ * is a different product decision and would need its own confirmation.
15
+ * - **Its own channel budget, not the pool's slot table.** Forward channels are
16
+ * long-lived by nature (a browser alone opens several per page); the pool's
17
+ * `CHANNEL_LIMIT` deliberately excludes long-lived channels from its own
18
+ * accounting, so the manager bounds them per alias and per rule instead of
19
+ * starving git/SFTP/terminal traffic.
20
+ * - **A failed connection is the RULE's error, not the link's.** A closed
21
+ * remote port or `AllowTcpForwarding no` must not paint the connection chip
22
+ * red; the row says which rule failed and the next attempt retries.
23
+ *
24
+ * The manager is deliberately not a cordis service: only this plugin's routes
25
+ * consume it. It gets a fiber-scoped effect in `index.ts` so a settings-driven
26
+ * route rebuild cannot tear down live forwards.
27
+ */
28
+ import { createServer, type AddressInfo, type Server, type Socket } from 'node:net'
29
+ import type { ClientChannel } from 'ssh2'
30
+ import type { RemoteForwardRequest, RemoteForwardState } from './protocol.ts'
31
+
32
+ /** Most simultaneous forward rules one host may carry. */
33
+ export const FORWARD_MAX_PER_ALIAS = 16
34
+
35
+ /** Most TCP connections one rule accepts at once (browsers open several). */
36
+ export const FORWARD_MAX_CONNECTIONS = 32
37
+
38
+ /** What every forward binds to (never a LAN address). */
39
+ const LOOPBACK = '127.0.0.1'
40
+
41
+ /**
42
+ * The pool surface the manager needs.
43
+ *
44
+ * Structural on purpose: the gate drives a fake pool without an SSH server, and
45
+ * the manager never reaches into the pool beyond one call.
46
+ */
47
+ export interface ForwardPoolLike {
48
+ forwardOut(alias: string, dstHost: string, dstPort: number, srcPort?: number): Promise<ClientChannel>
49
+ }
50
+
51
+ export interface ForwardManagerDeps {
52
+ pool: ForwardPoolLike
53
+ /** Diagnostic sink; defaults to a no-op (the Host wires its logger). */
54
+ log?: (level: 'info' | 'warn', message: string) => void
55
+ /** Test seam: bound rules per alias. */
56
+ maxPerAlias?: number
57
+ /** Test seam: concurrent connections per rule. */
58
+ maxConnections?: number
59
+ }
60
+
61
+ /** One validated rule request. */
62
+ export type ForwardValidation =
63
+ | { ok: true; value: RemoteForwardRequest }
64
+ | { ok: false; error: string }
65
+
66
+ /** Alias grammar (same rule the host store enforces). */
67
+ const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
68
+
69
+ /**
70
+ * Hostname / IPv4 / IPv6 accepted as the REMOTE target.
71
+ *
72
+ * The string never reaches a shell — ssh2 hands it to the server as the
73
+ * direct-tcpip destination — so this is a sanity fence (no whitespace, no
74
+ * control characters, bounded length) rather than escaping. A hostname with
75
+ * underscores and an IPv6 literal with brackets are both legal here.
76
+ */
77
+ const REMOTE_HOST_RE = /^[A-Za-z0-9._:[\]%-]{1,255}$/
78
+
79
+ function messageOf(error: unknown): string {
80
+ return error instanceof Error ? error.message : String(error ?? '')
81
+ }
82
+
83
+ /**
84
+ * Validate one request from the browser.
85
+ *
86
+ * `localPort` deliberately accepts 0 = "let the OS pick": the panel defaults to
87
+ * auto-assignment because a fixed port invites EADDRINUSE from whatever else
88
+ * the developer runs locally.
89
+ */
90
+ export function validateForwardRequest(input: unknown): ForwardValidation {
91
+ if (typeof input !== 'object' || input === null) return { ok: false, error: 'a JSON object is required' }
92
+ const raw = input as Record<string, unknown>
93
+ if (typeof raw.alias !== 'string' || !ALIAS_RE.test(raw.alias)) {
94
+ return { ok: false, error: 'alias must be 1-64 chars of letters/digits/._- and start with an alphanumeric' }
95
+ }
96
+ if (typeof raw.remoteHost !== 'string' || !REMOTE_HOST_RE.test(raw.remoteHost)) {
97
+ return { ok: false, error: 'remoteHost must be a hostname or IP address' }
98
+ }
99
+ const remotePort = raw.remotePort
100
+ if (typeof remotePort !== 'number' || !Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65535) {
101
+ return { ok: false, error: 'remotePort must be an integer between 1 and 65535' }
102
+ }
103
+ const localRaw = raw.localPort
104
+ let localPort = 0
105
+ if (localRaw !== undefined && localRaw !== null) {
106
+ if (typeof localRaw !== 'number' || !Number.isInteger(localRaw) || localRaw < 0 || localRaw > 65535) {
107
+ return { ok: false, error: 'localPort must be 0 (auto) or an integer between 1 and 65535' }
108
+ }
109
+ localPort = localRaw
110
+ }
111
+ return {
112
+ ok: true,
113
+ value: {
114
+ alias: raw.alias,
115
+ remoteHost: raw.remoteHost,
116
+ remotePort,
117
+ ...(localPort === 0 ? {} : { localPort }),
118
+ },
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Stable rule identity.
124
+ *
125
+ * `localPort` is the port the CALLER asked for (0 = auto), not the one the OS
126
+ * assigned: asking twice for the same automatic rule must return the running
127
+ * forward instead of opening a second listener on a second random port.
128
+ */
129
+ export function forwardIdOf(alias: string, remoteHost: string, remotePort: number, localPort: number): string {
130
+ return `${alias}|${remoteHost}|${remotePort}|${localPort}`
131
+ }
132
+
133
+ /** What the panel copies / opens for one forward. */
134
+ export function forwardLocalUrl(localPort: number): string {
135
+ return `http://127.0.0.1:${localPort}/`
136
+ }
137
+
138
+ interface Forward {
139
+ id: string
140
+ alias: string
141
+ remoteHost: string
142
+ remotePort: number
143
+ localPort: number
144
+ server: Server
145
+ sockets: Set<Socket>
146
+ channels: Set<ClientChannel>
147
+ bytesIn: number
148
+ bytesOut: number
149
+ lastError: string | undefined
150
+ startedAt: number
151
+ }
152
+
153
+ /** Listens on loopback and proxies every accepted connection over SSH. */
154
+ export class ForwardManager {
155
+ private readonly forwards = new Map<string, Forward>()
156
+ /**
157
+ * Rules whose listener is still BINDING.
158
+ *
159
+ * Two clicks (or a restore racing the panel's own poll) must share one bind:
160
+ * without this map the second call binds a SECOND listener on a different
161
+ * automatic port, overwrites the first entry in `forwards`, and leaves the
162
+ * first listener orphaned — unreachable from the panel and never closed.
163
+ */
164
+ private readonly starting = new Map<string, Promise<RemoteForwardState>>()
165
+ /** Set on unload so a bind that settles afterwards closes itself. */
166
+ private disposed = false
167
+
168
+ constructor(private readonly deps: ForwardManagerDeps) {}
169
+
170
+ /**
171
+ * Start one rule (idempotent for the same requested tuple).
172
+ *
173
+ * Resolves with the state once the local listener is BOUND; a bind failure
174
+ * (EADDRINUSE, permission) rejects, which the route maps to a caller-visible
175
+ * status. A remote-side failure cannot be known yet — the first connection
176
+ * discovers it and records it on the rule.
177
+ */
178
+ async start(request: RemoteForwardRequest): Promise<RemoteForwardState> {
179
+ const requestedLocalPort = request.localPort ?? 0
180
+ const id = forwardIdOf(request.alias, request.remoteHost, request.remotePort, requestedLocalPort)
181
+ const existing = this.forwards.get(id)
182
+ if (existing !== undefined) return this.stateOf(existing)
183
+ const inFlight = this.starting.get(id)
184
+ if (inFlight !== undefined) return inFlight
185
+ const pendingOnAlias = [...this.starting.keys()].filter(key => key.startsWith(`${request.alias}|`)).length
186
+ const perAlias = [...this.forwards.values()].filter(forward => forward.alias === request.alias).length + pendingOnAlias
187
+ const maxPerAlias = this.deps.maxPerAlias ?? FORWARD_MAX_PER_ALIAS
188
+ if (perAlias >= maxPerAlias) {
189
+ throw new Error(`host ${request.alias} already has ${maxPerAlias} local forwards; stop one first`)
190
+ }
191
+ const pending = this.bindForward(id, request, requestedLocalPort).then((forward) => {
192
+ // Unloaded while the bind was in flight: nobody can ever stop this
193
+ // listener, so it closes itself instead of leaking.
194
+ if (this.disposed) {
195
+ this.closeForward(forward)
196
+ throw new Error('the port-forward manager was unloaded while the rule was binding')
197
+ }
198
+ this.forwards.set(id, forward)
199
+ this.log('info', `forward ${id} listening on 127.0.0.1:${forward.localPort}`)
200
+ return this.stateOf(forward)
201
+ }).finally(() => {
202
+ this.starting.delete(id)
203
+ })
204
+ this.starting.set(id, pending)
205
+ return pending
206
+ }
207
+
208
+ /** Stop one rule. Returns false when the id is unknown (already stopped). */
209
+ stop(id: string): boolean {
210
+ const forward = this.forwards.get(id)
211
+ if (forward === undefined) return false
212
+ this.forwards.delete(id)
213
+ this.closeForward(forward)
214
+ this.log('info', `forward ${id} stopped`)
215
+ return true
216
+ }
217
+
218
+ /**
219
+ * Stop every rule for one host alias (the host was deleted).
220
+ *
221
+ * A deleted host disappears from the panel — there is no row left to press
222
+ * "stop" on — so leaving its listeners bound would squat the local ports
223
+ * until the Host restarts. Returns how many rules were closed.
224
+ */
225
+ stopAlias(alias: string): number {
226
+ let stopped = 0
227
+ for (const [id, forward] of [...this.forwards]) {
228
+ if (forward.alias !== alias) continue
229
+ this.forwards.delete(id)
230
+ this.closeForward(forward)
231
+ stopped += 1
232
+ }
233
+ if (stopped > 0) this.log('info', `stopped ${stopped} forward(s) for deleted host ${alias}`)
234
+ return stopped
235
+ }
236
+
237
+ /**
238
+ * Stop every rule but keep the manager alive (plugin disabled).
239
+ *
240
+ * `dispose()` is the unload path and flips a flag that makes later binds
241
+ * throw; a settings toggle needs the listeners gone without burning the
242
+ * instance, because re-enabling the plugin must be able to start rules again.
243
+ */
244
+ stopAll(): number {
245
+ let stopped = 0
246
+ for (const id of [...this.forwards.keys()]) {
247
+ if (this.stop(id)) stopped += 1
248
+ }
249
+ return stopped
250
+ }
251
+
252
+ /** Every rule, optionally narrowed to one host alias. */
253
+ list(alias?: string): RemoteForwardState[] {
254
+ const all = [...this.forwards.values()]
255
+ .filter(forward => alias === undefined || forward.alias === alias)
256
+ .sort((left, right) => left.alias.localeCompare(right.alias) || left.localPort - right.localPort)
257
+ return all.map(forward => this.stateOf(forward))
258
+ }
259
+
260
+ /** Close every listener and every proxied connection (plugin unload). */
261
+ dispose(): void {
262
+ this.disposed = true
263
+ for (const id of [...this.forwards.keys()]) this.stop(id)
264
+ }
265
+
266
+ /** Bind the loopback listener. Split out so the error path is one place. */
267
+ private async bindForward(id: string, request: RemoteForwardRequest, requestedLocalPort: number): Promise<Forward> {
268
+ const server = createServer()
269
+ const forward: Forward = {
270
+ id,
271
+ alias: request.alias,
272
+ remoteHost: request.remoteHost,
273
+ remotePort: request.remotePort,
274
+ localPort: 0,
275
+ server,
276
+ sockets: new Set(),
277
+ channels: new Set(),
278
+ bytesIn: 0,
279
+ bytesOut: 0,
280
+ lastError: undefined,
281
+ startedAt: Date.now(),
282
+ }
283
+ server.on('connection', (socket) => { this.accept(forward, socket) })
284
+ await new Promise<void>((resolve, reject) => {
285
+ const onError = (error: Error): void => {
286
+ server.removeListener('listening', onListening)
287
+ reject(error)
288
+ }
289
+ const onListening = (): void => {
290
+ server.removeListener('error', onError)
291
+ resolve()
292
+ }
293
+ server.once('error', onError)
294
+ server.once('listening', onListening)
295
+ // Loopback only — see the module docstring. `requestedLocalPort === 0`
296
+ // lets the OS assign, and the actual port is read back below.
297
+ server.listen(requestedLocalPort, LOOPBACK)
298
+ })
299
+ forward.localPort = (server.address() as AddressInfo).port
300
+ // Errors AFTER a successful bind (rare: the listener never fails on its
301
+ // own, but a platform may emit one) must not throw into nothing.
302
+ server.on('error', (error) => {
303
+ forward.lastError = messageOf(error)
304
+ this.log('warn', `forward ${id} listener error: ${forward.lastError}`)
305
+ })
306
+ return forward
307
+ }
308
+
309
+ /** One accepted local TCP connection: bound, or refused when the rule is full. */
310
+ private accept(forward: Forward, socket: Socket): void {
311
+ const maxConnections = this.deps.maxConnections ?? FORWARD_MAX_CONNECTIONS
312
+ if (forward.sockets.size >= maxConnections) {
313
+ forward.lastError = `too many simultaneous connections (limit ${maxConnections}); close one and retry`
314
+ this.log('warn', `forward ${forward.id}: ${forward.lastError}`)
315
+ socket.destroy()
316
+ return
317
+ }
318
+ forward.sockets.add(socket)
319
+ /**
320
+ * A reset in the DIAL WINDOW must never crash the Host.
321
+ *
322
+ * `finish` — the handler that owns the socket/channel pair and absorbs both
323
+ * errors — is attached only AFTER a channel exists. A cold dial takes
324
+ * seconds (up to the 15 s channel-open deadline), and a client that resets
325
+ * in that window emits `error` on a socket with no listener: Node turns
326
+ * that into an `uncaughtException`, and the DSH Host exits on those. This
327
+ * accept-time handler ends the local half; the later `finish` closes the
328
+ * channel if the dial wins the race.
329
+ */
330
+ const dropSocket = (): void => {
331
+ forward.sockets.delete(socket)
332
+ socket.destroy()
333
+ }
334
+ socket.once('close', dropSocket)
335
+ socket.once('error', dropSocket)
336
+ void this.connect(forward, socket)
337
+ }
338
+
339
+ /**
340
+ * Open one direct-tcpip channel for a local socket and pipe both ways.
341
+ *
342
+ * The channel is opened through the pool, so a dropped SSH connection is
343
+ * re-dialed per new local connection; an in-flight one fails with the pool's
344
+ * reason and is recorded on the rule.
345
+ */
346
+ private async connect(forward: Forward, socket: Socket): Promise<void> {
347
+ let channel: ClientChannel
348
+ try {
349
+ channel = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort)
350
+ } catch (error) {
351
+ forward.lastError = messageOf(error)
352
+ this.log('warn', `forward ${forward.id} -> ${forward.remoteHost}:${forward.remotePort} failed: ${forward.lastError}`)
353
+ forward.sockets.delete(socket)
354
+ socket.destroy()
355
+ return
356
+ }
357
+ // The local socket can be gone by the time the channel opens (a cold dial
358
+ // takes seconds); never leak a channel for nobody.
359
+ if (socket.destroyed) {
360
+ try {
361
+ channel.close()
362
+ } catch {
363
+ // Already gone.
364
+ }
365
+ return
366
+ }
367
+ forward.channels.add(channel)
368
+ forward.lastError = undefined
369
+ // Byte counters are diagnostic only: `prependListener` would duplicate the
370
+ // pipe; a plain listener sees the same chunks without consuming them.
371
+ socket.on('data', (chunk: Buffer) => { forward.bytesIn += chunk.length })
372
+ channel.on('data', (chunk: Buffer) => { forward.bytesOut += chunk.length })
373
+ let finished = false
374
+ const finish = (): void => {
375
+ if (finished) return
376
+ finished = true
377
+ forward.sockets.delete(socket)
378
+ forward.channels.delete(channel)
379
+ socket.destroy()
380
+ try {
381
+ channel.close()
382
+ } catch {
383
+ // Already gone.
384
+ }
385
+ }
386
+ socket.once('close', finish)
387
+ socket.once('error', finish)
388
+ channel.once('close', finish)
389
+ channel.once('error', finish)
390
+ // `pipe` carries backpressure in both directions; a close on either side
391
+ // ends both halves.
392
+ socket.pipe(channel)
393
+ channel.pipe(socket)
394
+ }
395
+
396
+ /** Tear one rule down: listener, then every proxied connection. */
397
+ private closeForward(forward: Forward): void {
398
+ try {
399
+ forward.server.close()
400
+ } catch {
401
+ // Already closed.
402
+ }
403
+ for (const socket of [...forward.sockets]) {
404
+ try {
405
+ socket.destroy()
406
+ } catch {
407
+ // Already gone.
408
+ }
409
+ }
410
+ forward.sockets.clear()
411
+ for (const channel of [...forward.channels]) {
412
+ try {
413
+ channel.close()
414
+ } catch {
415
+ // Already gone.
416
+ }
417
+ }
418
+ forward.channels.clear()
419
+ }
420
+
421
+ private stateOf(forward: Forward): RemoteForwardState {
422
+ return {
423
+ id: forward.id,
424
+ alias: forward.alias,
425
+ remoteHost: forward.remoteHost,
426
+ remotePort: forward.remotePort,
427
+ localPort: forward.localPort,
428
+ localUrl: forwardLocalUrl(forward.localPort),
429
+ state: forward.lastError === undefined ? 'listening' : 'error',
430
+ connections: forward.sockets.size,
431
+ bytesIn: forward.bytesIn,
432
+ bytesOut: forward.bytesOut,
433
+ ...(forward.lastError === undefined ? {} : { lastError: forward.lastError }),
434
+ startedAt: forward.startedAt,
435
+ }
436
+ }
437
+
438
+ private log(level: 'info' | 'warn', message: string): void {
439
+ try {
440
+ this.deps.log?.(level, message)
441
+ } catch {
442
+ // Logging must never break a forward.
443
+ }
444
+ }
445
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ import type {} from '@deepseek-ai/dsh-working-directory'
17
17
  import { RemoteStore } from './store.ts'
18
18
  import type { RemoteTimeouts } from './protocol.ts'
19
19
  import { RemotePool } from './pool.ts'
20
+ import { ForwardManager } from './forward.ts'
20
21
  import { seedHelperCache } from './deploy.ts'
21
22
  import { makeRoutes } from './routes.ts'
22
23
  import {
@@ -321,6 +322,28 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
321
322
  })
322
323
  ctx.effect(() => () => { changes.dispose() }, 'dsh-remote-vs: changes ledger')
323
324
 
325
+ /**
326
+ * Local port forwards (`ssh -L`) — resident listeners with their own
327
+ * lifecycle, on purpose.
328
+ *
329
+ * A forward's listener must survive `sync()` erasing and re-registering the
330
+ * route table (a settings edit must not kill a tunnel), so the manager is not
331
+ * created inside `makeRoutes`; the routes only see its CRUD face. Its effect
332
+ * is registered BEFORE the routes effect, so unload closes routes first, then
333
+ * the forwards (their channels still need a live pool), and the pool last.
334
+ */
335
+ const forwards = new ForwardManager({
336
+ pool,
337
+ log: (level, message) => {
338
+ try {
339
+ if (level === 'warn') ctx.logger.warn(`[remote-vs] forwards: ${message}`)
340
+ else ctx.logger.info(`[remote-vs] forwards: ${message}`)
341
+ } catch {
342
+ // Logging must never break a forward.
343
+ }
344
+ },
345
+ })
346
+
324
347
  const { routes, upgrade, terminalSessions } = makeRoutes({
325
348
  store,
326
349
  pool,
@@ -328,6 +351,7 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
328
351
  ctx,
329
352
  timeouts: resolveTimeoutsNow,
330
353
  changes,
354
+ forwards,
331
355
  })
332
356
 
333
357
  /**
@@ -349,6 +373,14 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
349
373
  */
350
374
  ctx.effect(() => () => { terminalSessions.dispose() }, 'dsh-remote-vs: terminal sessions')
351
375
 
376
+ /**
377
+ * Forwards close after routes (no new local connection can arrive once the
378
+ * route table is gone) and BEFORE the pool is disposed (a channel close still
379
+ * needs a live connection). Registered before `sync()` creates the routes
380
+ * effect, so the reverse-order cleanup above holds.
381
+ */
382
+ ctx.effect(() => () => { forwards.dispose() }, 'dsh-remote-vs: port forwards')
383
+
352
384
  let disposeRoutes: (() => void) | undefined
353
385
 
354
386
  const tools = [
@@ -375,7 +407,14 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
375
407
  disposeTools = undefined
376
408
  }
377
409
  const value = resolve()
378
- if (!value.enabled) return
410
+ if (!value.enabled) {
411
+ // Turning the plugin off must release the local ports too: with the
412
+ // routes gone there is no panel left to stop a tunnel, and a listener
413
+ // nobody can reach would keep its 127.0.0.1 port bound until restart.
414
+ // `stopAll` (not `dispose`) keeps the manager reusable when re-enabled.
415
+ forwards.stopAll()
416
+ return
417
+ }
379
418
  if (value.announceToAgent) {
380
419
  disposeSection = ctx.systemPrompt.section({
381
420
  name: 'plugin:dsh-remote-vs',