dsh-remote 0.8.89 → 0.8.90

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,58 @@
1
+ // Audit-log routes: /audit.
2
+ //
3
+ // Extracted from lib/index.js (issue #82: the god-file split). Handler bodies
4
+ // moved VERBATIM; the mechanism lives in ./audit.js, this file only adapts the
5
+ // HTTP surface to it. Dependencies that belong to the plugin entry (config,
6
+ // the audit-file locator, the JSON body helpers, the OS file opener) arrive
7
+ // as `deps`.
8
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
9
+ import path from 'node:path'
10
+
11
+ /**
12
+ * @param {object} deps
13
+ * @param {(res: object, status: number, body: object) => void} deps.sendJson
14
+ * @param {(req: object) => Promise<string>} deps.readBody
15
+ * @param {object} deps.config - validated plugin Config.
16
+ * @param {() => string} deps.auditFile - absolute path of the audit log file.
17
+ * @param {(limit: string|null) => string[]} deps.readAudit - parsed tail of the log.
18
+ * @param {(raw: string) => object} deps.parseJsonObject - 400-throwing object parser.
19
+ * @param {(target: string, action?: 'open'|'reveal') => Promise<object>} deps.openLocalPath
20
+ * @returns {Array<object>} route descriptors for registerHttpTransports.
21
+ */
22
+ export function createAuditRoutes({ sendJson, readBody, config, auditFile, readAudit, parseJsonObject, openLocalPath }) {
23
+ return [
24
+ {
25
+ kind: 'exact',
26
+ path: '/dsh-remote/audit',
27
+ handler: async (req, res) => {
28
+ if (req.method === 'GET') {
29
+ const q = new URL(req.url, 'http://localhost').searchParams
30
+ return sendJson(res, 200, { ok: true, auditEnabled: !!config.auditLog, file: auditFile(), lines: readAudit(q.get('limit')) })
31
+ }
32
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
33
+ // Open the audit FILE itself in the user's own viewer. The browser cannot do
34
+ // this — the log lives on the machine running the DSH host — so the host
35
+ // performs the open and reports what it did:
36
+ // action 'reveal' → highlight the file in the OS file manager
37
+ // action 'open' → open it with the OS default application (a text editor)
38
+ // A missing file is created first: "no log yet" would otherwise be
39
+ // indistinguishable from a broken button.
40
+ try {
41
+ const body = parseJsonObject(await readBody(req))
42
+ const action = String(body.action || 'open')
43
+ if (action !== 'open' && action !== 'reveal') {
44
+ return sendJson(res, 400, { ok: false, error: 'action must be open | reveal' })
45
+ }
46
+ const file = auditFile()
47
+ mkdirSync(path.dirname(file), { recursive: true })
48
+ if (!existsSync(file)) writeFileSync(file, '', 'utf8')
49
+ const r = await openLocalPath(file, action)
50
+ if (!r.ok) return sendJson(res, r.httpStatus || 500, { ok: false, error: r.error, file })
51
+ return sendJson(res, 200, { ok: true, action, file, how: r.how })
52
+ } catch (err) {
53
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
54
+ }
55
+ },
56
+ },
57
+ ]
58
+ }
@@ -0,0 +1,72 @@
1
+ // Port-forward routes: /forwards.
2
+ //
3
+ // Extracted from lib/index.js (issue #82: the god-file split). Handler bodies
4
+ // moved VERBATIM; the mechanism lives in ./forwards.js (ForwardManager), this
5
+ // file only adapts the HTTP surface to it. Dependencies that belong to the
6
+ // plugin entry (the manager instance, the registry store for the owning
7
+ // machine id) arrive as `deps`.
8
+ /**
9
+ * @param {object} deps
10
+ * @param {(res: object, status: number, body: object) => void} deps.sendJson
11
+ * @param {(req: object) => Promise<string>} deps.readBody
12
+ * @param {object} deps.forwards - the ForwardManager instance.
13
+ * @param {object} deps.store - machine-registry store (`currentId` tags new definitions).
14
+ * @returns {Array<object>} route descriptors for registerHttpTransports.
15
+ */
16
+ export function createForwardRoutes({ sendJson, readBody, forwards, store }) {
17
+ return [
18
+ {
19
+ kind: 'exact',
20
+ path: '/dsh-remote/forwards',
21
+ handler: async (req, res) => {
22
+ if (req.method === 'GET') return sendJson(res, 200, { forwards: forwards.list() })
23
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
24
+ try {
25
+ const body = JSON.parse((await readBody(req)) || '{}')
26
+ const action = String(body.action || '')
27
+ if (action === 'define') {
28
+ // Validate the port HERE, not at start time: `listen(0)` would silently
29
+ // pick an ephemeral port and the user would be looking at a forward
30
+ // that listens nowhere they asked for. The settings UI cannot produce
31
+ // this, but the HTTP API (and therefore an agent) can.
32
+ const listenPort = Number(body.listenPort)
33
+ if (!Number.isInteger(listenPort) || listenPort < 1 || listenPort > 65535) {
34
+ return sendJson(res, 400, { ok: false, error: 'listenPort 必须是 1–65535 的整数' })
35
+ }
36
+ const targetPort = Number(body.targetPort) || listenPort
37
+ if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535) {
38
+ return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' })
39
+ }
40
+ const d = forwards.define({
41
+ direction: body.direction === 'reverse' ? 'reverse' : 'local',
42
+ listenPort,
43
+ targetHost: body.targetHost || '127.0.0.1',
44
+ targetPort,
45
+ autoStart: !!body.autoStart,
46
+ machineId: store.currentId,
47
+ })
48
+ return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
49
+ }
50
+ if (action === 'start' || action === 'stop') {
51
+ const d = forwards.list().find((f) => f.id === body.id)
52
+ if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found' })
53
+ if (action === 'start') {
54
+ const r = await forwards.start(d)
55
+ if (!r.ok) return sendJson(res, 500, { ok: false, error: r.error })
56
+ } else {
57
+ forwards.stop(d.id)
58
+ }
59
+ return sendJson(res, 200, { ok: true, forwards: forwards.list() })
60
+ }
61
+ if (action === 'remove') {
62
+ forwards.remove(String(body.id || ''))
63
+ return sendJson(res, 200, { ok: true, forwards: forwards.list() })
64
+ }
65
+ return sendJson(res, 400, { ok: false, error: 'unknown action' })
66
+ } catch (err) {
67
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
68
+ }
69
+ },
70
+ },
71
+ ]
72
+ }
@@ -0,0 +1,186 @@
1
+ // Machine-registry routes: /machines (GET|POST) and /ssh-config.
2
+ //
3
+ // Extracted from lib/index.js (issue #82: the god-file split). Handler bodies
4
+ // moved VERBATIM; the record mechanics live in ./registry.js and ./sshconfig.js
5
+ // while the ENTRY owns the live store (machines array, current pointer) and the
6
+ // upsert/remove/probe orchestration closures — those arrive as `deps` because
7
+ // they are shared with the in-process API assembled in the entry.
8
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
9
+ import path from 'node:path'
10
+ import { listAliases, sshConfigPath, readSshConfigText } from './sshconfig.js'
11
+
12
+ /**
13
+ * @param {object} deps
14
+ * @param {(res: object, status: number, body: object) => void} deps.sendJson
15
+ * @param {(req: object) => Promise<string>} deps.readBody
16
+ * @param {(raw: string) => object} deps.parseJsonObject - 400-throwing object parser.
17
+ * @param {object} deps.store - machine-registry store (`currentId`).
18
+ * @param {Array<object>} deps.machines - the LIVE registry array (shared reference).
19
+ * @param {() => Array<object>} deps.machinesForClient - sanitized list view.
20
+ * @param {(body: object) => Promise<object>} deps.upsertMachineRecord
21
+ * @param {(id: string) => Promise<object>} deps.removeMachineRecord
22
+ * @param {(id: string) => Promise<boolean>} deps.setCurrent
23
+ * @param {(list: Array<object>, currentId: string|null, keepCurrentKey: boolean) => void} deps.saveMachines
24
+ * @param {(m: object) => object} deps.sanitizeMachine
25
+ * @param {() => string} deps.machineId - fresh record id.
26
+ * @param {() => string} deps.sshConfigText - memoised ~/.ssh/config text.
27
+ * @param {(m: object) => boolean} deps.nativeUsableCredential
28
+ * @param {() => object} deps.status - the entry's status snapshot.
29
+ * @param {(target: string, action?: 'open'|'reveal') => Promise<object>} deps.openLocalPath
30
+ * @returns {Array<object>} route descriptors for registerHttpTransports.
31
+ */
32
+ export function createMachineRoutes({ sendJson, readBody, parseJsonObject, store, machines, machinesForClient, upsertMachineRecord, removeMachineRecord, setCurrent, saveMachines, sanitizeMachine, machineId, sshConfigText, nativeUsableCredential, status, openLocalPath }) {
33
+ return [
34
+ {
35
+ kind: 'exact',
36
+ path: '/dsh-remote/machines',
37
+ handler: async (req, res) => {
38
+ if (req.method === 'GET') {
39
+ return sendJson(res, 200, { machines: machinesForClient(), currentId: store.currentId })
40
+ }
41
+ if (req.method === 'POST') {
42
+ try {
43
+ const body = JSON.parse((await readBody(req)) || '{}')
44
+ const action = body.action || 'add'
45
+ if (action === 'add' || action === 'update') {
46
+ try {
47
+ return sendJson(res, 200, { ok: true, ...(await upsertMachineRecord(body)) })
48
+ } catch (err) {
49
+ return sendJson(res, (err && err.httpStatus) || 500, { ok: false, error: String((err && err.message) || err) })
50
+ }
51
+ }
52
+ // Issue #73: one click on a host listed from ~/.ssh/config. The settings
53
+ // page no longer asks the user to understand "alias" vs "copy": it lists
54
+ // the file's hosts and this action adopts one — upsert an alias machine
55
+ // (never a duplicate), make it the current machine, and let the caller
56
+ // connect/probe next. Nothing about the user's file is rewritten here:
57
+ // the alias IS the source of truth (issue #50).
58
+ if (action === 'from-ssh-config') {
59
+ const alias = String(body.alias || body.host || '').trim()
60
+ if (!alias) return sendJson(res, 400, { ok: false, error: 'alias required' })
61
+ const known = listAliases(sshConfigText()).find((a) => a.alias === alias)
62
+ if (!known) {
63
+ return sendJson(res, 404, {
64
+ ok: false,
65
+ error: `~/.ssh/config 里没有 "${alias}"(改完文件后重新打开设置页即可刷新)`,
66
+ })
67
+ }
68
+ const existing = machines.find((m) => m.useSshConfig && String(m.host) === alias)
69
+ let rec = existing
70
+ if (!rec) {
71
+ rec = {
72
+ id: machineId(),
73
+ name: alias,
74
+ host: alias,
75
+ useSshConfig: true,
76
+ port: Number(known.port) || 22,
77
+ username: String(known.user || ''),
78
+ password: '',
79
+ privateKeyPath: '',
80
+ passphrase: '',
81
+ workspace: '',
82
+ hostKeyMode: '',
83
+ useAgent: false,
84
+ keyboardInteractive: false,
85
+ // ~/.ssh/config defines this machine, and the user's own `ssh`
86
+ // is what interprets that file (default identity discovery,
87
+ // agent/keychain, ProxyJump, GSSAPI). Native cannot see any of
88
+ // it, so a Host block with no IdentityFile would be reported as
89
+ // "no credentials".
90
+ backend: 'openssh',
91
+ sshBinary: '',
92
+ credentialBackend: 'plain',
93
+ recentWorkspaces: [],
94
+ lastConnectedAt: null,
95
+ latencyMs: null,
96
+ }
97
+ machines.push(rec)
98
+ saveMachines(machines, store.currentId, false)
99
+ } else if (String(rec.backend || 'native') !== 'openssh' && !nativeUsableCredential(rec)) {
100
+ // A record adopted before this fix carries `native` with no
101
+ // credential: upgrade it in place, so clicking Connect dials what
102
+ // `ssh <alias>` already does.
103
+ rec.backend = 'openssh'
104
+ saveMachines(machines, store.currentId, false)
105
+ }
106
+ // Making it current is the whole point of the click: the picker and
107
+ // every session route then act on this machine.
108
+ const okSet = await setCurrent(rec.id)
109
+ if (!okSet) return sendJson(res, 500, { ok: false, error: 'could not activate the machine' })
110
+ return sendJson(res, 200, {
111
+ ok: true,
112
+ created: !existing,
113
+ machine: sanitizeMachine(rec),
114
+ machines: machinesForClient(),
115
+ currentId: store.currentId,
116
+ ...status(),
117
+ })
118
+ }
119
+ if (action === 'delete') {
120
+ try {
121
+ return sendJson(res, 200, { ok: true, ...(await removeMachineRecord(String(body.id || ''))) })
122
+ } catch (err) {
123
+ return sendJson(res, (err && err.httpStatus) || 500, { ok: false, error: String((err && err.message) || err) })
124
+ }
125
+ }
126
+ return sendJson(res, 400, { ok: false, error: 'unknown action' })
127
+ } catch (err) {
128
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
129
+ }
130
+ }
131
+ return sendJson(res, 405, { ok: false, error: 'method not allowed' })
132
+ },
133
+ },
134
+ {
135
+ kind: 'exact',
136
+ path: '/dsh-remote/ssh-config',
137
+ handler: async (req, res) => {
138
+ // GET lists hosts. POST {action:'open'|'reveal'} opens THAT file on the
139
+ // machine running DSH — the same affordance as the audit log. The path
140
+ // is always sshConfigPath(); a path in the body is ignored, so this is
141
+ // not a general file launcher.
142
+ if (req.method === 'POST') {
143
+ try {
144
+ const body = parseJsonObject(await readBody(req))
145
+ const action = String(body.action || '')
146
+ if (action !== 'open' && action !== 'reveal') {
147
+ return sendJson(res, 400, { ok: false, error: 'action must be open | reveal' })
148
+ }
149
+ const file = sshConfigPath()
150
+ mkdirSync(path.dirname(file), { recursive: true })
151
+ // Create an empty config so the editor has a file. Never truncate
152
+ // one the user already wrote.
153
+ if (!existsSync(file)) writeFileSync(file, '', { encoding: 'utf8', mode: 0o600 })
154
+ const r = await openLocalPath(file, action)
155
+ if (!r.ok) return sendJson(res, r.httpStatus || 500, { ok: false, error: r.error, file })
156
+ return sendJson(res, 200, { ok: true, action, file, how: r.how })
157
+ } catch (err) {
158
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
159
+ }
160
+ }
161
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
162
+ try {
163
+ const text = readSshConfigText()
164
+ // Issue #73: the settings page lists the hosts of ~/.ssh/config the way
165
+ // VSCode Remote-SSH does, so this must include EVERY concrete alias —
166
+ // `importableEntries` filtered out a bare `Host mybox` with no options,
167
+ // which is a perfectly normal entry to connect to. `host` is kept as an
168
+ // alias of `alias` so existing callers keep working.
169
+ const entries = listAliases(text).map((a) => ({
170
+ host: a.alias,
171
+ alias: a.alias,
172
+ hostName: a.hostName || a.alias,
173
+ user: a.user || '',
174
+ port: Number(a.port) || 22,
175
+ identityFile: a.identityFile || '',
176
+ proxyJump: a.proxyJump || '',
177
+ proxyCommand: a.proxyCommand || '',
178
+ }))
179
+ return sendJson(res, 200, { ok: true, file: sshConfigPath(), present: !!text, entries })
180
+ } catch (err) {
181
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
182
+ }
183
+ },
184
+ },
185
+ ]
186
+ }
@@ -0,0 +1,150 @@
1
+ // Misc singleton routes: /telemetry, /term-secret, /workspace-mirrors,
2
+ // /workspace-cleanup — small surfaces grouped so no one-route file accretes.
3
+ //
4
+ // Extracted from lib/index.js (issue #82: the god-file split). Handler bodies
5
+ // moved VERBATIM; the mechanisms live in ./telemetry.js, ./workspace-cleanup.js
6
+ // and the entry's term-secret closures — this file only adapts the HTTP
7
+ // surface to them. Entry-owned state (machines, the secret payload writers,
8
+ // the late-assembled in-process API) arrives as `deps`.
9
+ //
10
+ // `heartbeatEnabled` for the GET /telemetry branch is imported above from
11
+ // ./telemetry.js: in the god-file it was an UNBOUND name (a latent
12
+ // ReferenceError on every GET, masked because no test drove a real GET). Fixed
13
+ // upstream as v0.8.89; this file's import converges with that repair — after
14
+ // the rebase onto main the new GET route test passes against the moved handler.
15
+ import { existsSync } from 'node:fs'
16
+ import { heartbeatEnabled, telemetryAllowed, persistTelemetryOpt } from './telemetry.js'
17
+
18
+ /**
19
+ * @param {object} deps
20
+ * @param {(res: object, status: number, body: object) => void} deps.sendJson
21
+ * @param {(req: object) => Promise<string>} deps.readBody
22
+ * @param {object} deps.config - validated plugin Config.
23
+ * @param {() => string} deps.dshBase - $DSH_HOME of the RUNNING host.
24
+ * @param {object} deps.ctx - the plugin context (term-secret republish reads webServer).
25
+ * @param {() => string} deps.termSecretFile - path of the bearer payload file.
26
+ * @param {(origin: string) => boolean} deps.writeTermSecretPayload
27
+ * @param {(presented: string) => boolean} deps.termSecretOk - timing-safe token check.
28
+ * @param {Array<object>} deps.machines - the LIVE registry array (shared reference).
29
+ * @param {(m: object) => Promise<string|undefined>} deps.machinePassword - credential chain.
30
+ * @param {() => object} deps.getHostApi - LATE-BOUND: the in-process API is
31
+ * assembled AFTER route registration, so handlers resolve it per request.
32
+ * @returns {Array<object>} route descriptors for registerHttpTransports.
33
+ */
34
+ export function createMiscRoutes({ sendJson, readBody, config, dshBase, ctx, termSecretFile, writeTermSecretPayload, termSecretOk, machines, machinePassword, getHostApi }) {
35
+ return [
36
+ {
37
+ kind: 'exact',
38
+ path: '/dsh-remote/telemetry',
39
+ handler: async (req, res) => {
40
+ // The anonymous-heartbeat toggle (settings page). GET reads the
41
+ // EFFECTIVE value (user override > profile config > default true);
42
+ // POST persists the user's choice under $DSH_HOME so it survives
43
+ // plugin upgrades (the install dir gets overwritten).
44
+ if (req.method === 'GET') {
45
+ return sendJson(res, 200, { ok: true, enabled: telemetryAllowed(dshBase(), config.telemetry), configurable: heartbeatEnabled() })
46
+ }
47
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
48
+ try {
49
+ const body = JSON.parse((await readBody(req)) || '{}')
50
+ if (typeof body.enabled !== 'boolean') return sendJson(res, 400, { ok: false, error: 'enabled must be boolean' })
51
+ if (!persistTelemetryOpt(dshBase(), body.enabled)) return sendJson(res, 500, { ok: false, error: 'cannot persist the setting (read-only home?)' })
52
+ return sendJson(res, 200, { ok: true, enabled: telemetryAllowed(dshBase(), config.telemetry) })
53
+ } catch (err) {
54
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
55
+ }
56
+ },
57
+ },
58
+ {
59
+ kind: 'exact',
60
+ path: '/dsh-remote/term-secret',
61
+ // Owns its bearer token (per boot, 0600 file): the caller is a local
62
+ // PROCESS (the askpass helper), not a browser, so the Connection cookie
63
+ // fence would 401 it. The fallback fence still locks out cross-site pages
64
+ // (they cannot read the token file).
65
+ fence: 'bearer',
66
+ handler: async (req, res) => {
67
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
68
+ // Self-heal: a caller exists but the payload was never published (the
69
+ // origin arrived after the first write attempts).
70
+ if (!existsSync(termSecretFile())) {
71
+ try {
72
+ const ws = ctx.get('webServer')
73
+ if (ws && typeof ws.getOrigin === 'function') writeTermSecretPayload(ws.getOrigin())
74
+ } catch { /* still no listener: the 403 below answers honestly */ }
75
+ }
76
+ // Malformed bodies are a 400 with a reason even before the token check
77
+ // (the routes matrix pins that readability contract for every POST).
78
+ let body = {}
79
+ try { body = JSON.parse((await readBody(req)) || '{}') } catch { return sendJson(res, 400, { ok: false, error: 'invalid JSON body' }) }
80
+ const presented = String((req.headers && req.headers.authorization) || '').replace(/^Bearer\s+/i, '')
81
+ if (!presented || !termSecretOk(presented)) return sendJson(res, 403, { ok: false, error: 'forbidden' })
82
+ const alias = String(body.alias || '')
83
+ let m = null
84
+ if (alias) m = machines.find((x) => x && x.useSshConfig && String(x.host) === alias) || null
85
+ if (!m) {
86
+ const host = String(body.host || '')
87
+ const port = Number(body.port) || 22
88
+ const user = String(body.username || '')
89
+ m = machines.find((x) => x && !x.useSshConfig && String(x.host) === host && (Number(x.port) || 22) === port && String(x.username || '') === user) || null
90
+ }
91
+ if (!m) return sendJson(res, 404, { ok: false, error: 'unknown machine' })
92
+ const password = await machinePassword(m)
93
+ return sendJson(res, 200, { ok: true, password })
94
+ },
95
+ },
96
+ {
97
+ kind: 'exact',
98
+ path: '/dsh-remote/workspace-mirrors',
99
+ handler: async (req, res) => {
100
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
101
+ // Late-bound: the in-process API is assembled after route registration.
102
+ const hostApi = getHostApi()
103
+ // The settings page's cleanup section: every local mirror with its
104
+ // sessions, sizes and occupancy, straight off the in-process API (same
105
+ // object the TUI consumes — one implementation, two faces).
106
+ if (!hostApi) return sendJson(res, 503, { ok: false, error: 'in-process API unavailable' })
107
+ try {
108
+ return sendJson(res, 200, { ok: true, mirrors: await hostApi.listWorkspaceMirrors({}) })
109
+ } catch (err) {
110
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
111
+ }
112
+ },
113
+ },
114
+ {
115
+ kind: 'exact',
116
+ path: '/dsh-remote/workspace-cleanup',
117
+ handler: async (req, res) => {
118
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
119
+ // Late-bound: the in-process API is assembled after route registration.
120
+ const hostApi = getHostApi()
121
+ if (!hostApi) return sendJson(res, 503, { ok: false, error: 'in-process API unavailable' })
122
+ try {
123
+ const body = JSON.parse((await readBody(req)) || '{}')
124
+ const localMirror = String(body.localMirror || '')
125
+ const mode = String(body.mode || '')
126
+ if (!localMirror) return sendJson(res, 400, { ok: false, error: 'localMirror is required' })
127
+ let result
128
+ if (mode === 'all') {
129
+ result = await hostApi.deleteRemoteWorkspace({ localMirror, force: body.force === true })
130
+ } else if (mode === 'sessions') {
131
+ result = await hostApi.deleteWorkspaceSessions({ localMirror, force: body.force === true })
132
+ } else if (mode === 'recent') {
133
+ result = await hostApi.forgetWorkspaceRecent({ localMirror })
134
+ } else {
135
+ return sendJson(res, 400, { ok: false, error: 'mode must be all | sessions | recent' })
136
+ }
137
+ return sendJson(res, 200, { ok: true, ...result })
138
+ } catch (err) {
139
+ // Coded errors carry user-facing messages; WORKSPACE_BUSY must reach
140
+ // the UI as 409 so the page can say WHICH sessions hold the workspace.
141
+ const status = (err && err.code === 'WORKSPACE_BUSY') ? 409 : (err && err.code === 'VALIDATION') ? 400 : 500
142
+ const out = { ok: false, error: String((err && err.message) || err) }
143
+ if (err && err.code) out.code = err.code
144
+ if (err && Array.isArray(err.liveSessions)) out.liveSessions = err.liveSessions
145
+ return sendJson(res, status, out)
146
+ }
147
+ },
148
+ },
149
+ ]
150
+ }
@@ -0,0 +1,112 @@
1
+ // Remote-Web-UI attach routes: /web-attach.
2
+ //
3
+ // Extracted from lib/index.js (issue #82: the god-file split). Handler bodies
4
+ // moved VERBATIM; the mechanism lives in ./web-attach.js (WebAttach), this
5
+ // file only adapts the HTTP surface to it. The state it drives belongs to the
6
+ // plugin entry and arrives as `deps`: the live-attach map, the machine
7
+ // registry array, the per-identity pool resolver, and the audit sink.
8
+ import { WebAttach } from './web-attach.js'
9
+
10
+ /**
11
+ * @param {object} deps
12
+ * @param {(res: object, status: number, body: object) => void} deps.sendJson
13
+ * @param {(req: object) => Promise<string>} deps.readBody
14
+ * @param {(raw: string) => object} deps.parseJsonObject - 400-throwing object parser.
15
+ * @param {object} deps.config - validated plugin Config.
16
+ * @param {Map<string, WebAttach>} deps.webAttaches - machineId → live attach session.
17
+ * @param {object} deps.store - machine-registry store (`currentId` default target).
18
+ * @param {Array<object>} deps.machines - the LIVE registry array (shared reference).
19
+ * @param {(target: object) => object} deps.poolForMachine - per-identity pool resolver.
20
+ * @param {(m: object) => {host: string, port: number, username: string}} deps.identityOf
21
+ * @param {(machine: object) => string} deps.webAttachCommandFor - remote launch command.
22
+ * @param {(op: string, cmd: string, code: number, target?: object) => void} deps.audit
23
+ * @returns {Array<object>} route descriptors for registerHttpTransports.
24
+ */
25
+ export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, config, webAttaches, store, machines, poolForMachine, identityOf, webAttachCommandFor, audit }) {
26
+ return [
27
+ {
28
+ kind: 'exact',
29
+ path: '/dsh-remote/web-attach',
30
+ // Issue #46: open/reuse/close a tunnel to a remote machine's DSH Web UI.
31
+ // Actions: status (GET) | open | close. `open` either starts a remote
32
+ // `dsh web` (default) or attaches to one the user already runs by passing
33
+ // its `http://127.0.0.1:<port>/?token=…` URL.
34
+ handler: async (req, res) => {
35
+ try {
36
+ if (req.method === 'GET') {
37
+ const q = new URL(req.url, 'http://localhost').searchParams
38
+ const id = q.get('machineId') || ''
39
+ const attach = id ? webAttaches.get(id) : undefined
40
+ return sendJson(res, 200, {
41
+ ok: true,
42
+ attach: attach ? attach.describe() : null,
43
+ attaches: [...webAttaches.values()].map((a) => a.describe()),
44
+ })
45
+ }
46
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
47
+ const body = parseJsonObject(await readBody(req))
48
+ const action = String(body.action || '')
49
+ const machineId = String(body.machineId || store.currentId || '').trim()
50
+ if (!machineId) return sendJson(res, 400, { ok: false, error: '选择一台机器后再操作(missing machineId)' })
51
+
52
+ if (action === 'open') {
53
+ // Reuse a live tunnel for this machine: re-opening would start a
54
+ // second remote DSH and leak the first one's process.
55
+ const live = webAttaches.get(machineId)
56
+ if (live && live.active) return sendJson(res, 200, { ok: true, attach: live.describe(), reused: true })
57
+ // A tunnel that is no longer listening still owns sockets and a log
58
+ // path; release it before this machine gets a fresh session. Its
59
+ // remote process is left alone — stopping it stays an explicit act.
60
+ if (live) { try { await live.close() } catch { /* already torn down */ } }
61
+ const machine = machines.find((m) => m.id === machineId)
62
+ if (!machine) return sendJson(res, 404, { ok: false, error: `机器不存在:${machineId}` })
63
+ const attachPool = poolForMachine(identityOf(machine))
64
+ const attach = new WebAttach({
65
+ localPortStart: config.webAttachPortStart,
66
+ // Issue #54: follow the chosen pool's lifecycle so a dropped SSH
67
+ // connection degrades to "disconnected" and then self-heals,
68
+ // instead of leaving a dead client that crashes the host process.
69
+ trackPool: true,
70
+ })
71
+ try {
72
+ await attach.open({
73
+ pool: attachPool,
74
+ machineId,
75
+ command: String(body.command || '').trim() || webAttachCommandFor(machine),
76
+ profile: 'web',
77
+ existingUrl: String(body.existingUrl || ''),
78
+ dshHome: config.webAttachDshHome || '',
79
+ waitSeconds: config.webAttachWaitSeconds,
80
+ })
81
+ } catch (err) {
82
+ try { await attach.close() } catch { /* nothing was listening */ }
83
+ const msg = String((err && err.message) || err)
84
+ audit('web-attach', `open ${machine.host} failed: ${msg}`, 1, machine)
85
+ return sendJson(res, 500, { ok: false, error: msg })
86
+ }
87
+ webAttaches.set(machineId, attach)
88
+ audit('web-attach', `open ${machine.host} → 127.0.0.1:${attach.localPort}`, 0, machine)
89
+ return sendJson(res, 200, { ok: true, attach: attach.describe() })
90
+ }
91
+
92
+ if (action === 'close') {
93
+ const attach = webAttaches.get(machineId)
94
+ if (!attach) return sendJson(res, 200, { ok: true, closed: false, error: '该机器没有活动的远程界面' })
95
+ const stopRemote = body.stopRemote === true
96
+ // `close()` refuses to signal anything without a recorded PID, so a
97
+ // tunnel onto the user's own running instance stays hands-off.
98
+ const exec = (cmd) => poolForMachine(identityOf(machines.find((m) => m.id === machineId) || {})).exec(cmd, { timeoutMs: 10000 })
99
+ await attach.close({ stopRemote, exec })
100
+ webAttaches.delete(machineId)
101
+ audit('web-attach', `close ${attach.cleanUrl}${stopRemote ? ' (remote stopped)' : ''}`, 0)
102
+ return sendJson(res, 200, { ok: true, closed: true, stoppedRemote: stopRemote && !!attach.remotePid })
103
+ }
104
+
105
+ return sendJson(res, 400, { ok: false, error: 'action must be open | close' })
106
+ } catch (err) {
107
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
108
+ }
109
+ },
110
+ },
111
+ ]
112
+ }