dsh-remote 1.2.1 → 1.3.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/README.en.md +4 -2
- package/README.md +4 -2
- package/lib/binding.js +86 -26
- package/lib/client.js +422 -154
- package/lib/deck-bridge.js +17 -0
- package/lib/errors.js +5 -2
- package/lib/forwards.js +18 -6
- package/lib/main.js +45 -12
- package/lib/mirror-paths.js +17 -0
- package/lib/pool.js +46 -4
- package/lib/registry.js +6 -1
- package/lib/routes-forwards.js +81 -10
- package/lib/update.js +209 -25
- package/package.json +4 -3
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// lib/deck-bridge.js —— 给 dsh-mattpocock-skills-deck 的远端工作区适配层用的公开入口。
|
|
2
|
+
//
|
|
3
|
+
// 背景:外挂插件 dsh-deck-remote-exec 让 deck 在 dsh-remote 的远端工作区里工作,
|
|
4
|
+
// 它需要的只是 dsh-remote 已有的几个纯能力(镜像识别、路径翻译、SSH 连接池)。
|
|
5
|
+
// 在此之前它靠「绝对路径动态 import lib/*.js」绕过 package.json 的 exports 限制,
|
|
6
|
+
// 因为那些内部模块没有公开导出。这种做法依赖 dsh-remote 的内部文件布局,
|
|
7
|
+
// 一旦文件改名或 exports 收紧就会失效,而且无法被 Node 的模块解析静态检查。
|
|
8
|
+
//
|
|
9
|
+
// 本文件把这些能力里插件实际用到的符号正式导出,插件改成
|
|
10
|
+
// `import { ... } from 'dsh-remote/deck-bridge'` 即可,不再碰内部路径。
|
|
11
|
+
// 只导出插件真正需要的 6 个符号,不把整个内部模块摊开——公开面越小,
|
|
12
|
+
// 内部实现越能自由演进;要加符号时按插件的实际需要再加。
|
|
13
|
+
//
|
|
14
|
+
// 这些函数/类本身的实现仍在各自原模块里,这里只做转发,零逻辑。
|
|
15
|
+
export { resolveMirror } from './binding.js'
|
|
16
|
+
export { SystemOpenSshPool } from './openssh.js'
|
|
17
|
+
export { resolveRemoteWorkspacePath, relPathUnder, remoteDirname, shq } from './paths.js'
|
package/lib/errors.js
CHANGED
|
@@ -55,10 +55,13 @@ export function classifyError(err, opts = {}) {
|
|
|
55
55
|
// the message a user sees when the port is open but nothing speaks SSH on it,
|
|
56
56
|
// or when a firewall/security group cuts the connection after the TCP accept;
|
|
57
57
|
// it is indistinguishable from "wrong credentials" unless it is classified.
|
|
58
|
-
if (/
|
|
58
|
+
if (/handshake failed|no matching (?:key exchange|host key|cipher|kex|mac)|no matching.*(?:algorithm|cipher)|unsupported.*algorithm/i.test(msg)) {
|
|
59
|
+
return { category: 'network', hint: `SSH 握手未完成${where}:客户端与服务器的 SSH 算法协商失败。若本机 ssh 能连接,请在主机编辑页把「连接后端」改为 openssh 后测试;插件不会自动启用弱算法或跳过主机指纹校验。`, raw: msg }
|
|
60
|
+
}
|
|
61
|
+
if (/connection lost before handshake/i.test(msg)) {
|
|
59
62
|
return {
|
|
60
63
|
category: 'network',
|
|
61
|
-
hint: `SSH 握手未完成${where}
|
|
64
|
+
hint: `SSH 握手未完成${where}:连接在 SSH 认证前断开,当前错误无法确定是服务端限流、网络设备断开还是协议兼容问题,也不能据此判断密码错误。请稍后重试;若同一台电脑的 ssh 可以连接,请在主机编辑页把「连接后端」改为 openssh 后测试。持续失败时再检查 sshd 日志及来源 IP 限制。`,
|
|
62
65
|
raw: msg,
|
|
63
66
|
}
|
|
64
67
|
}
|
package/lib/forwards.js
CHANGED
|
@@ -207,22 +207,34 @@ export class ForwardManager {
|
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
/**
|
|
210
|
-
* Patch an existing definition's mutable fields and persist it.
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
210
|
+
* Patch an existing definition's mutable fields and persist it.
|
|
211
|
+
*
|
|
212
|
+
* Two callers share this: the row's 自动重连 checkbox patches only
|
|
213
|
+
* `autoStart`; the edit form sends the whole definition (direction, ports,
|
|
214
|
+
* target host, owning machine). Fields that are absent stay untouched — the
|
|
215
|
+
* route validates them first, so a typo never reaches this merge.
|
|
216
|
+
*
|
|
217
|
+
* It does NOT start or stop the tunnel. Changing a BIND of a running forward
|
|
218
|
+
* is refused by the route (the live socket would keep the old bind); toggling
|
|
219
|
+
* `autoStart` on a running forward is fine.
|
|
214
220
|
*
|
|
215
221
|
* @param {string} id
|
|
216
|
-
* @param {{autoStart?: boolean
|
|
222
|
+
* @param {{autoStart?: boolean, direction?: 'local'|'reverse', listenPort?: number,
|
|
223
|
+
* targetHost?: string, targetPort?: number, machineId?: string|null}} patch
|
|
217
224
|
* @returns {object|null} the updated definition, or null when the id is unknown.
|
|
218
225
|
*/
|
|
219
|
-
update(id, { autoStart } = {}) {
|
|
226
|
+
update(id, { autoStart, direction, listenPort, targetHost, targetPort, machineId } = {}) {
|
|
220
227
|
const d = this.defs.find((x) => x.id === id)
|
|
221
228
|
if (!d) return null
|
|
222
229
|
if (typeof autoStart === 'boolean') {
|
|
223
230
|
d.autoStart = autoStart
|
|
224
231
|
delete d.needsReconsent
|
|
225
232
|
}
|
|
233
|
+
if (direction === 'local' || direction === 'reverse') d.direction = direction
|
|
234
|
+
if (Number.isInteger(listenPort)) d.listenPort = listenPort
|
|
235
|
+
if (typeof targetHost === 'string' && targetHost) d.targetHost = targetHost
|
|
236
|
+
if (Number.isInteger(targetPort)) d.targetPort = targetPort
|
|
237
|
+
if (machineId !== undefined) d.machineId = machineId || null
|
|
226
238
|
this._save()
|
|
227
239
|
return d
|
|
228
240
|
}
|
package/lib/main.js
CHANGED
|
@@ -51,6 +51,7 @@ import { createInstructionIndex, formatInstructionIndex } from './instructions.j
|
|
|
51
51
|
import { resolveExecTimeout, formatExecResult, startExecJob, execWithOptionalPromotion } from './exec-job.js'
|
|
52
52
|
import { createInjectionTracker, refreshTouched, buildInstructionMessage, pickUserMessageFactory, loadBundledUserMessageFactory } from './instructions-dynamic.js'
|
|
53
53
|
import { REMOTE_SANDBOX_MODES, checkRemoteSandbox, remoteSandboxDenial } from './remote-sandbox.js'
|
|
54
|
+
import { mirrorConstrainLocalTarget, mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
|
|
54
55
|
import { createTerminalManager } from './terminal.js'
|
|
55
56
|
import { createTerminalRoutes } from './routes-term.js'
|
|
56
57
|
import { searchRemote } from './search.js'
|
|
@@ -3116,34 +3117,51 @@ export async function apply(ctx, config) {
|
|
|
3116
3117
|
defineTool({
|
|
3117
3118
|
name: 'rw_download',
|
|
3118
3119
|
description:
|
|
3119
|
-
'Download a single remote file over SFTP into the local mirror of the current workspace
|
|
3120
|
+
'Download a single remote file over SFTP into the local mirror of the current workspace. Use when you need the actual file content locally, not just its text. Streams to disk (fastGet). The destination must stay inside that mirror, and the session sandbox must allow a write.',
|
|
3120
3121
|
parameters: {
|
|
3121
3122
|
path: { type: 'string', required: true, description: 'Absolute remote file path' },
|
|
3122
|
-
localPath: { type: 'string', description: '
|
|
3123
|
+
localPath: { type: 'string', description: 'Destination INSIDE the workspace mirror (default: the mirror path that preserves the remote relative path). Paths outside the mirror are refused.' },
|
|
3123
3124
|
},
|
|
3124
3125
|
output: okOut,
|
|
3125
3126
|
async execute(args, exec) {
|
|
3126
3127
|
const b = requireMachine(exec, 'rw_download')
|
|
3128
|
+
// Landing a file on THIS machine is a state change the session's
|
|
3129
|
+
// sandbox must have a say over: read-only refuses it outright, and
|
|
3130
|
+
// workspace-write keeps the remote source inside the workspace.
|
|
3131
|
+
requireRemoteSandbox(exec, 'write', { tool: 'rw_download', path: String(args.path || '') })
|
|
3127
3132
|
const p = resolveRemoteArg(b, args.path)
|
|
3128
3133
|
if (!p || p === '/') throw new Error('rw_download: a remote file path is required')
|
|
3129
|
-
const
|
|
3130
|
-
let
|
|
3131
|
-
if (
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3134
|
+
const ws = b.ws
|
|
3135
|
+
let base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port) : '')
|
|
3136
|
+
if (!ws || !base) throw new Error('rw_download: no remote workspace set — downloads land inside the local mirror of the workspace')
|
|
3137
|
+
// Both destination forms resolve inside the mirror with the same
|
|
3138
|
+
// grammar-aware mapping + symlink guard the HTTP download route applies
|
|
3139
|
+
// (routes-fs.js op=download): an unchecked local path can no longer
|
|
3140
|
+
// write outside the mirror or through a symlinked target.
|
|
3141
|
+
const local = args.localPath
|
|
3142
|
+
? mirrorConstrainLocalTarget(base, String(args.localPath))
|
|
3143
|
+
: mirrorDownloadTarget(base, ws, p)
|
|
3144
|
+
assertDownloadHasNoSymlinks(base, local)
|
|
3145
|
+
// Persist the mirror meta once downloads start landing here: the
|
|
3146
|
+
// registry lookup is only idempotent when the meta exists, and a
|
|
3147
|
+
// session opened inside this mirror binds to the machine through it.
|
|
3148
|
+
// Persist the mirror meta before landing anything: the directory
|
|
3149
|
+
// lookup is only idempotent once the meta exists, and a bare download
|
|
3150
|
+
// used to leave the dir anonymous — the next call would then resolve
|
|
3151
|
+
// to a hashed sibling and "move" the mirror. Also lets a session
|
|
3152
|
+
// opened inside this mirror bind back to the machine.
|
|
3153
|
+
if (!existsSync(path.join(base, '.dsh-remote-meta.json'))) {
|
|
3154
|
+
try { ensureMirror(ws, b.host, b.username, b.port) } catch { /* meta is an optimization, not a gate */ }
|
|
3139
3155
|
}
|
|
3140
3156
|
mkdirSync(path.dirname(local), { recursive: true })
|
|
3157
|
+
const sftp = await b.pool.sftp()
|
|
3141
3158
|
const st = await sftp.stat(p).catch(() => null)
|
|
3142
3159
|
if (config.maxFileBytes > 0 && st && st.size > config.maxFileBytes) {
|
|
3143
3160
|
throw new Error(`rw_download: file is ${st.size} bytes (over ${config.maxFileBytes} cap)`)
|
|
3144
3161
|
}
|
|
3145
3162
|
await sftp.fastGet(p, local)
|
|
3146
3163
|
const bytes = existsSync(local) ? statSync(local).size : 0
|
|
3164
|
+
audit('download', `download ${p} → ${local}`, 0, b)
|
|
3147
3165
|
return { ok: true, bytes, text: `downloaded ${bytes} bytes from ${p} → ${local}` }
|
|
3148
3166
|
},
|
|
3149
3167
|
}),
|
|
@@ -3872,6 +3890,20 @@ export async function apply(ctx, config) {
|
|
|
3872
3890
|
// alone, so a fresh registry stays "no choice yet" (not an
|
|
3873
3891
|
// explicit none) and a previously-cleared registry stays cleared.
|
|
3874
3892
|
saveMachines(machines, store.currentId, false)
|
|
3893
|
+
// Editing the ACTIVE machine must re-point the live pool, not just the
|
|
3894
|
+
// registry. The pool keeps the target it was APPLIED with, and every
|
|
3895
|
+
// forward start / rw_* call dials through it — so without this the settings
|
|
3896
|
+
// page showed the new address while 启动 still connected to the old one
|
|
3897
|
+
// ("ssh: connect to host <old>: Host is down"). setTarget() closes a live
|
|
3898
|
+
// connection only when an identity field actually changed.
|
|
3899
|
+
let poolWarning = ''
|
|
3900
|
+
if (!ephemeral && store.currentId === rec.id) {
|
|
3901
|
+
try {
|
|
3902
|
+
await applyActiveMachine()
|
|
3903
|
+
} catch (err) {
|
|
3904
|
+
poolWarning = String((err && err.message) || err)
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3875
3907
|
// Issue #67: an EDITED connection identity (host/user/port) must
|
|
3876
3908
|
// carry the machine's existing workspaces over — without this the
|
|
3877
3909
|
// mirrors stayed bound to the old address and the user had to
|
|
@@ -3923,6 +3955,7 @@ export async function apply(ctx, config) {
|
|
|
3923
3955
|
...(reboundMirrors ? { reboundMirrors } : {}),
|
|
3924
3956
|
...(warning ? { warning, warningDetail } : {}),
|
|
3925
3957
|
...(sshConfigWarning ? { sshConfigWarning } : {}),
|
|
3958
|
+
...(poolWarning ? { poolWarning } : {}),
|
|
3926
3959
|
}
|
|
3927
3960
|
}
|
|
3928
3961
|
|
package/lib/mirror-paths.js
CHANGED
|
@@ -32,3 +32,20 @@ export function assertDownloadHasNoSymlinks(base, target) {
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
|
|
36
|
+
// An explicit `localPath` argument (the rw_download tool surface) must land
|
|
37
|
+
// inside the same mirror the HTTP route writes into. Resolve it in the local
|
|
38
|
+
// grammar and refuse anything that would escape the root, alias the meta
|
|
39
|
+
// record, or smuggle Windows-unusable names — the same guarantees the
|
|
40
|
+
// remote-derived form gets from mirrorDownloadTarget.
|
|
41
|
+
export function mirrorConstrainLocalTarget(base, localPathArg, localPathApi = path) {
|
|
42
|
+
const root = localPathApi.resolve(base)
|
|
43
|
+
const target = localPathApi.resolve(String(localPathArg || ''))
|
|
44
|
+
const within = localPathApi.relative(root, target)
|
|
45
|
+
if (!within || localPathApi.isAbsolute(within) || within.split(localPathApi.sep).some(part => part === '..')) throw unsafeDownload()
|
|
46
|
+
const parts = within.split(localPathApi.sep)
|
|
47
|
+
// This local-only record determines the session's remote identity.
|
|
48
|
+
if (parts.length === 1 && (localPathApi.sep === '\\' ? parts[0].toLowerCase() : parts[0]) === '.dsh-remote-meta.json') throw unsafeDownload()
|
|
49
|
+
if (localPathApi.sep === '\\' && parts.some(part => /[<>:"|?*\\\x00-\x1f]/.test(part) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw unsafeDownload()
|
|
50
|
+
return target
|
|
51
|
+
}
|
package/lib/pool.js
CHANGED
|
@@ -7,6 +7,7 @@ import { truncate } from './paths.js'
|
|
|
7
7
|
import { createHostKeyGuard } from './hostkey.js'
|
|
8
8
|
import { buildSftpSurface } from './sftp-surface.js'
|
|
9
9
|
import { friendlyMessage } from './errors.js'
|
|
10
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
10
11
|
import { SystemOpenSshPool, isSystemOpenSshBackend } from './openssh.js'
|
|
11
12
|
|
|
12
13
|
const { Client } = ssh2
|
|
@@ -323,7 +324,7 @@ export class SshPool {
|
|
|
323
324
|
if (this.client) return Promise.resolve(this.client)
|
|
324
325
|
if (this.connecting) return this.connecting
|
|
325
326
|
const epoch = this.epoch
|
|
326
|
-
const pending = this.
|
|
327
|
+
const pending = this._connectWithRetry(epoch)
|
|
327
328
|
this.connecting = pending
|
|
328
329
|
const clear = () => {
|
|
329
330
|
if (this.epoch === epoch && this.connecting === pending) this.connecting = null
|
|
@@ -332,22 +333,48 @@ export class SshPool {
|
|
|
332
333
|
return pending
|
|
333
334
|
}
|
|
334
335
|
|
|
336
|
+
async _connectWithRetry(epoch) {
|
|
337
|
+
try { return await this._doConnect(epoch) }
|
|
338
|
+
catch (error) {
|
|
339
|
+
if (error.code !== 'SSH_HANDSHAKE_CLOSED' || this.epoch !== epoch) throw error
|
|
340
|
+
// MaxStartups / middlebox resets may be transient. Share ONE bounded
|
|
341
|
+
// retry across all callers; never replay an authenticated command.
|
|
342
|
+
await delay(350)
|
|
343
|
+
if (this.epoch !== epoch) throw new Error('ssh target changed during handshake retry')
|
|
344
|
+
return this._doConnect(epoch)
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
335
348
|
async _doConnect(epoch) {
|
|
336
349
|
const isCurrent = () => this.epoch === epoch
|
|
350
|
+
const target = { host: this.config.host, port: this.config.port }
|
|
337
351
|
const knownHostsFile = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
|
|
338
352
|
const guard = createHostKeyGuard(this.config, knownHostsFile)
|
|
339
353
|
const client = new Client()
|
|
340
|
-
|
|
354
|
+
this._connectingClient = client
|
|
355
|
+
let settled = false, handshakeCompleted = false
|
|
356
|
+
client.on('handshake', () => { handshakeCompleted = true })
|
|
341
357
|
// Every connect-stage failure is classified HERE, at the layer that knows
|
|
342
358
|
// which machine was being dialed: a bare ssh2 errno ("Timed out while
|
|
343
359
|
// waiting for handshake") names no host, and on a multi-machine plugin the
|
|
344
360
|
// user cannot tell WHICH box failed. friendlyMessage is idempotent, so
|
|
345
361
|
// callers that classify again (rw_connect, routes) do not double-wrap.
|
|
346
|
-
const classify = (err) =>
|
|
362
|
+
const classify = (err) => {
|
|
363
|
+
const error = new Error(friendlyMessage(err, target))
|
|
364
|
+
error.cause = err
|
|
365
|
+
if (!handshakeCompleted && /^(?:Connection lost before handshake|ssh connection closed|read ECONNRESET)$/i.test(String(err.message || err))) error.code = 'SSH_HANDSHAKE_CLOSED'
|
|
366
|
+
return error
|
|
367
|
+
}
|
|
347
368
|
const fail = (err) => {
|
|
348
369
|
if (settled) return
|
|
349
370
|
settled = true
|
|
350
371
|
if (isCurrent() && this.client === client) this.client = null
|
|
372
|
+
if (this._connectingClient === client) this._connectingClient = null
|
|
373
|
+
try { client.destroy() } catch {}
|
|
374
|
+
if (isCurrent() && this.proxyPool) {
|
|
375
|
+
try { this.proxyPool.close() } catch {}
|
|
376
|
+
this.proxyPool = null
|
|
377
|
+
}
|
|
351
378
|
throw classify(guard.lastError ? new Error(guard.lastError) : err)
|
|
352
379
|
}
|
|
353
380
|
|
|
@@ -408,9 +435,17 @@ export class SshPool {
|
|
|
408
435
|
if (settled) return
|
|
409
436
|
settled = true
|
|
410
437
|
if (isCurrent() && this.client === client) this.client = null
|
|
411
|
-
|
|
438
|
+
if (this._connectingClient === client) this._connectingClient = null
|
|
439
|
+
const failure = classify(guard.lastError ? new Error(guard.lastError) : err)
|
|
440
|
+
if (isCurrent() && this.proxyPool) {
|
|
441
|
+
try { this.proxyPool.close() } catch {}
|
|
442
|
+
this.proxyPool = null
|
|
443
|
+
}
|
|
444
|
+
try { client.destroy() } catch {}
|
|
445
|
+
reject(failure)
|
|
412
446
|
}
|
|
413
447
|
client.on('ready', () => {
|
|
448
|
+
if (this._connectingClient === client) this._connectingClient = null
|
|
414
449
|
if (settled) return
|
|
415
450
|
settled = true
|
|
416
451
|
if (!isCurrent()) {
|
|
@@ -521,6 +556,7 @@ export class SshPool {
|
|
|
521
556
|
// Convert it into a normal rejection so every caller's try/catch —
|
|
522
557
|
// boot restore, test-connect, rw_connect — sees a regular failure.
|
|
523
558
|
try {
|
|
559
|
+
if (!isCurrent() || settled) throw new Error('ssh target changed during connect')
|
|
524
560
|
client.connect(opts)
|
|
525
561
|
} catch (err) {
|
|
526
562
|
rejectOnce(err)
|
|
@@ -982,6 +1018,9 @@ export class SshPool {
|
|
|
982
1018
|
const client = this.client
|
|
983
1019
|
this.client = null
|
|
984
1020
|
this._dropSftpSession()
|
|
1021
|
+
const pendingClient = this._connectingClient
|
|
1022
|
+
this._connectingClient = null
|
|
1023
|
+
if (pendingClient) { try { pendingClient.destroy() } catch {} }
|
|
985
1024
|
const pending = this.connecting
|
|
986
1025
|
this.connecting = null
|
|
987
1026
|
if (pending && typeof pending.catch === 'function') {
|
|
@@ -1008,6 +1047,9 @@ export class SshPool {
|
|
|
1008
1047
|
const client = this.client
|
|
1009
1048
|
this.client = null
|
|
1010
1049
|
this._dropSftpSession()
|
|
1050
|
+
const pendingClient = this._connectingClient
|
|
1051
|
+
this._connectingClient = null
|
|
1052
|
+
if (pendingClient) { try { pendingClient.destroy() } catch {} }
|
|
1011
1053
|
const pending = this.connecting
|
|
1012
1054
|
this.connecting = null
|
|
1013
1055
|
if (pending && typeof pending.catch === 'function') {
|
package/lib/registry.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// Keeping this logic in one module makes the guarantee unit-testable and
|
|
11
11
|
// shared between the HTTP routes and the tools (rw_connect).
|
|
12
12
|
|
|
13
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs'
|
|
14
14
|
import path from 'node:path'
|
|
15
15
|
|
|
16
16
|
/** Load { list, currentId, explicitNone } from the registry file. */
|
|
@@ -56,6 +56,11 @@ export function saveMachines(file, list, currentId, keepCurrentKey = true) {
|
|
|
56
56
|
const payload = { list }
|
|
57
57
|
if (hasStored) payload.currentId = stored
|
|
58
58
|
writeFileSync(file, JSON.stringify(payload, null, 2))
|
|
59
|
+
// This file can carry plaintext credentials (password / passphrase under
|
|
60
|
+
// the default 'plain' backend), so keep it user-private — the same rule
|
|
61
|
+
// term-secret.json (main.js) and the ssh-config writer (routes-machines.js)
|
|
62
|
+
// already follow. A pre-existing looser mode is tightened on every save.
|
|
63
|
+
try { chmodSync(file, 0o600) } catch { /* Windows: the parent dir is already user-private */ }
|
|
59
64
|
}
|
|
60
65
|
|
|
61
66
|
/**
|
package/lib/routes-forwards.js
CHANGED
|
@@ -37,27 +37,98 @@ export function createForwardRoutes({ sendJson, readBody, forwards, store, activ
|
|
|
37
37
|
if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535) {
|
|
38
38
|
return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' })
|
|
39
39
|
}
|
|
40
|
+
// Which host the tunnel belongs to. The settings form names it
|
|
41
|
+
// explicitly (`machineId`): a forward can be DEFINED for a host that
|
|
42
|
+
// is not connected right now — it simply cannot start until that host
|
|
43
|
+
// is. Omitting the field keeps the historical behaviour: tag what the
|
|
44
|
+
// ACTIVE POOL is actually on (ephemeral included), not the registry's
|
|
45
|
+
// currentId, because rw_connect(save:false) keeps currentId on the old
|
|
46
|
+
// machine while the pool talks to the new one.
|
|
47
|
+
//
|
|
48
|
+
// An explicit id must be a real registry record: persisting a typo
|
|
49
|
+
// would create a forward that no machine can ever start and that no
|
|
50
|
+
// UI row can explain.
|
|
51
|
+
let machineId = typeof activeMachineId === 'function' ? activeMachineId() : store.currentId
|
|
52
|
+
if (Object.prototype.hasOwnProperty.call(body, 'machineId') && body.machineId !== null && body.machineId !== '') {
|
|
53
|
+
const wanted = String(body.machineId)
|
|
54
|
+
const known = Array.isArray(store.list) && store.list.some((m) => m && m.id === wanted)
|
|
55
|
+
if (!known) return sendJson(res, 404, { ok: false, error: 'machine not found', forwards: forwards.list() })
|
|
56
|
+
machineId = wanted
|
|
57
|
+
}
|
|
40
58
|
const d = forwards.define({
|
|
41
59
|
direction: body.direction === 'reverse' ? 'reverse' : 'local',
|
|
42
60
|
listenPort,
|
|
43
61
|
targetHost: body.targetHost || '127.0.0.1',
|
|
44
62
|
targetPort,
|
|
45
63
|
autoStart: !!body.autoStart,
|
|
46
|
-
|
|
47
|
-
// not the registry's currentId: rw_connect(save:false) keeps
|
|
48
|
-
// currentId on the old machine while the pool talks to the new one.
|
|
49
|
-
machineId: typeof activeMachineId === 'function' ? activeMachineId() : store.currentId,
|
|
64
|
+
machineId,
|
|
50
65
|
})
|
|
51
66
|
return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
|
|
52
67
|
}
|
|
53
68
|
if (action === 'update') {
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
|
|
69
|
+
// Partial patch: the row's 自动重连 checkbox sends only `autoStart`,
|
|
70
|
+
// the edit form sends the whole definition. Every field that IS
|
|
71
|
+
// present is validated; a missing field is left untouched (it must
|
|
72
|
+
// not silently reset anything). `autoStart`, when present, still has
|
|
73
|
+
// to be a real boolean.
|
|
74
|
+
const has = (k) => Object.prototype.hasOwnProperty.call(body, k)
|
|
75
|
+
const id = String(body.id || '')
|
|
76
|
+
const current = forwards.list().find((f) => f.id === id)
|
|
77
|
+
if (!current) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() })
|
|
78
|
+
const patch = {}
|
|
79
|
+
if (has('autoStart')) {
|
|
80
|
+
if (typeof body.autoStart !== 'boolean') {
|
|
81
|
+
return sendJson(res, 400, { ok: false, error: 'autoStart 必须是布尔值' })
|
|
82
|
+
}
|
|
83
|
+
patch.autoStart = body.autoStart
|
|
84
|
+
}
|
|
85
|
+
if (has('direction')) {
|
|
86
|
+
if (body.direction !== 'local' && body.direction !== 'reverse') {
|
|
87
|
+
return sendJson(res, 400, { ok: false, error: 'direction 只能是 local 或 reverse' })
|
|
88
|
+
}
|
|
89
|
+
patch.direction = body.direction
|
|
90
|
+
}
|
|
91
|
+
if (has('listenPort')) {
|
|
92
|
+
const p = Number(body.listenPort)
|
|
93
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) {
|
|
94
|
+
return sendJson(res, 400, { ok: false, error: 'listenPort 必须是 1–65535 的整数' })
|
|
95
|
+
}
|
|
96
|
+
patch.listenPort = p
|
|
97
|
+
}
|
|
98
|
+
if (has('targetPort')) {
|
|
99
|
+
// An empty target port means "same as the listen port", exactly
|
|
100
|
+
// like the add form.
|
|
101
|
+
const p = body.targetPort === '' || body.targetPort == null
|
|
102
|
+
? (patch.listenPort !== undefined ? patch.listenPort : current.listenPort)
|
|
103
|
+
: Number(body.targetPort)
|
|
104
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) {
|
|
105
|
+
return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' })
|
|
106
|
+
}
|
|
107
|
+
patch.targetPort = p
|
|
108
|
+
}
|
|
109
|
+
if (has('targetHost')) {
|
|
110
|
+
const host = String(body.targetHost || '').trim() || '127.0.0.1'
|
|
111
|
+
patch.targetHost = host
|
|
112
|
+
}
|
|
113
|
+
if (has('machineId')) {
|
|
114
|
+
if (body.machineId === null || body.machineId === '') {
|
|
115
|
+
patch.machineId = null
|
|
116
|
+
} else {
|
|
117
|
+
const wanted = String(body.machineId)
|
|
118
|
+
const known = Array.isArray(store.list) && store.list.some((m) => m && m.id === wanted)
|
|
119
|
+
if (!known) return sendJson(res, 404, { ok: false, error: 'machine not found', forwards: forwards.list() })
|
|
120
|
+
patch.machineId = wanted
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// A live tunnel keeps its OLD bind until it is torn down; editing it
|
|
124
|
+
// in place would show one port while the socket listens on another.
|
|
125
|
+
// Only the bind matters — 自动重连 may still be toggled while running.
|
|
126
|
+
const bindChanged = ['direction', 'listenPort', 'targetHost', 'targetPort', 'machineId']
|
|
127
|
+
.some((k) => k in patch && patch[k] !== (current[k] === undefined ? null : current[k]))
|
|
128
|
+
if (current.active && bindChanged) {
|
|
129
|
+
return sendJson(res, 409, { ok: false, error: '先停止这条转发再修改监听/目标/主机', forwards: forwards.list() })
|
|
59
130
|
}
|
|
60
|
-
const d = forwards.update(
|
|
131
|
+
const d = forwards.update(id, patch)
|
|
61
132
|
if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() })
|
|
62
133
|
return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
|
|
63
134
|
}
|