dsh-remote-go 0.1.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.
- package/README.md +64 -95
- package/{client.js → dist/client.js} +7805 -5486
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/dist/src/constants.js +67 -0
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +40 -21
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/src/api.js +0 -340
- package/src/atomic-json.js +0 -208
- package/src/bootstrap.js +0 -100
- package/src/connect-log.js +0 -39
- package/src/connect-pipeline.js +0 -463
- package/src/connect-progress.js +0 -135
- package/src/constants.js +0 -31
- package/src/diagnostics.js +0 -157
- package/src/download-jobs.js +0 -217
- package/src/errors.js +0 -316
- package/src/host-lifecycle.js +0 -187
- package/src/host-registry.js +0 -145
- package/src/host-runtime.js +0 -53
- package/src/host-view.js +0 -51
- package/src/index.js +0 -162
- package/src/key-files.js +0 -49
- package/src/known-hosts.js +0 -94
- package/src/layout.js +0 -35
- package/src/local-download.js +0 -162
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -89
- package/src/prompts.js +0 -132
- package/src/redact.js +0 -54
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -73
- package/src/remote-proc.js +0 -208
- package/src/remote-web.js +0 -300
- package/src/secrets.js +0 -79
- package/src/service.js +0 -250
- package/src/settings.js +0 -135
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -652
- package/src/store.js +0 -143
- package/src/tunnel.js +0 -73
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -28
- package/vendor/ssh2-entry.mjs +0 -12
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/api.js
DELETED
|
@@ -1,340 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Local HTTP API for the browser half (contract: docs/api.md); every request needs the marker header and, with an Origin, same-origin.
|
|
3
|
-
*/
|
|
4
|
-
import { API_HEADER, API_PREFIX, API_VERSION, PLUGIN_VERSION } from './constants.js'
|
|
5
|
-
import { errors, isRemoteGoError, toErrorView } from './errors.js'
|
|
6
|
-
import { nowIso } from './util.js'
|
|
7
|
-
|
|
8
|
-
const MAX_BODY_BYTES = 1 * 1024 * 1024
|
|
9
|
-
|
|
10
|
-
/** Rows shared by the `/version` and `/diagnostics/self` responses. */
|
|
11
|
-
const VERSION_ROW = { version: PLUGIN_VERSION, apiVersion: API_VERSION }
|
|
12
|
-
const PLUGIN_ROW = { id: 'dsh-remote-go', version: PLUGIN_VERSION }
|
|
13
|
-
|
|
14
|
-
export function createApi(options) {
|
|
15
|
-
const { service } = options
|
|
16
|
-
const logger = options.logger ?? console
|
|
17
|
-
const sseClients = new Set()
|
|
18
|
-
|
|
19
|
-
/** Write one SSE frame to every subscriber, dropping the ones that already went away. */
|
|
20
|
-
function writeAll(frame) {
|
|
21
|
-
for (const client of sseClients) {
|
|
22
|
-
try {
|
|
23
|
-
client.write(frame)
|
|
24
|
-
} catch {
|
|
25
|
-
sseClients.delete(client)
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const broadcastState = () => writeAll(`event: state\ndata: ${JSON.stringify(service.snapshot())}\n\n`)
|
|
31
|
-
service.on('state', broadcastState)
|
|
32
|
-
const broadcastDownload = (job) => writeAll(`event: download\ndata: ${JSON.stringify(job)}\n\n`)
|
|
33
|
-
service.on('download', broadcastDownload)
|
|
34
|
-
|
|
35
|
-
const heartbeat = setInterval(() => writeAll('event: ping\ndata: {}\n\n'), 15_000)
|
|
36
|
-
heartbeat.unref?.()
|
|
37
|
-
|
|
38
|
-
const crossSite = () => ({
|
|
39
|
-
ok: false,
|
|
40
|
-
status: 403,
|
|
41
|
-
error: toErrorView(
|
|
42
|
-
errors.invalidInput('origin', { zh: '跨站请求被拒绝。', en: 'Cross-site requests are rejected.' }),
|
|
43
|
-
),
|
|
44
|
-
})
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Browser trust for same-origin reads (used by SSE, which cannot set custom
|
|
48
|
-
* headers): an absent Origin is a non-browser local caller; a present Origin
|
|
49
|
-
* must be this GUI's origin and the request must not be cross-site.
|
|
50
|
-
*/
|
|
51
|
-
function authorizeOrigin(req) {
|
|
52
|
-
const origin = req.headers.origin
|
|
53
|
-
if (typeof origin === 'string' && origin !== '') {
|
|
54
|
-
const expected = options.getOrigin()
|
|
55
|
-
if (!expected || origin.replace(/\/$/, '') !== expected.replace(/\/$/, '')) return crossSite()
|
|
56
|
-
}
|
|
57
|
-
if (req.headers['sec-fetch-site'] === 'cross-site') return crossSite()
|
|
58
|
-
return { ok: true }
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function authorize(req) {
|
|
62
|
-
const origin = authorizeOrigin(req)
|
|
63
|
-
if (!origin.ok) return origin
|
|
64
|
-
if (req.headers[API_HEADER] !== '1') {
|
|
65
|
-
return {
|
|
66
|
-
ok: false,
|
|
67
|
-
status: 403,
|
|
68
|
-
error: toErrorView(
|
|
69
|
-
errors.invalidInput(API_HEADER, {
|
|
70
|
-
zh: '请求缺少本地插件标识头。',
|
|
71
|
-
en: 'The request is missing the local plugin header.',
|
|
72
|
-
}),
|
|
73
|
-
),
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
return { ok: true }
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function readJson(req) {
|
|
80
|
-
return new Promise((resolve, reject) => {
|
|
81
|
-
const chunks = []
|
|
82
|
-
let size = 0
|
|
83
|
-
req.on('data', (chunk) => {
|
|
84
|
-
size += chunk.length
|
|
85
|
-
if (size > MAX_BODY_BYTES) {
|
|
86
|
-
reject(errors.invalidInput('body', { zh: '请求体过大。', en: 'The request body is too large.' }))
|
|
87
|
-
req.destroy()
|
|
88
|
-
return
|
|
89
|
-
}
|
|
90
|
-
chunks.push(Buffer.from(chunk))
|
|
91
|
-
})
|
|
92
|
-
req.on('end', () => {
|
|
93
|
-
if (chunks.length === 0) {
|
|
94
|
-
resolve({})
|
|
95
|
-
return
|
|
96
|
-
}
|
|
97
|
-
try {
|
|
98
|
-
const text = Buffer.concat(chunks).toString('utf8').trim()
|
|
99
|
-
resolve(text === '' ? {} : JSON.parse(text))
|
|
100
|
-
} catch {
|
|
101
|
-
reject(
|
|
102
|
-
errors.invalidInput('body', { zh: '请求体不是合法 JSON。', en: 'The request body is not valid JSON.' }),
|
|
103
|
-
)
|
|
104
|
-
}
|
|
105
|
-
})
|
|
106
|
-
req.on('error', reject)
|
|
107
|
-
})
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function sendJson(res, status, payload) {
|
|
111
|
-
const body = JSON.stringify(payload)
|
|
112
|
-
res.writeHead(status, {
|
|
113
|
-
'content-type': 'application/json; charset=utf-8',
|
|
114
|
-
'cache-control': 'no-store',
|
|
115
|
-
'content-length': Buffer.byteLength(body),
|
|
116
|
-
})
|
|
117
|
-
res.end(body)
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function handleSse(req, res) {
|
|
121
|
-
res.writeHead(200, {
|
|
122
|
-
'content-type': 'text/event-stream; charset=utf-8',
|
|
123
|
-
'cache-control': 'no-cache, no-transform',
|
|
124
|
-
connection: 'keep-alive',
|
|
125
|
-
'x-accel-buffering': 'no',
|
|
126
|
-
})
|
|
127
|
-
res.write(`event: state\ndata: ${JSON.stringify(service.snapshot())}\n\n`)
|
|
128
|
-
sseClients.add(res)
|
|
129
|
-
req.on('close', () => {
|
|
130
|
-
sseClients.delete(res)
|
|
131
|
-
})
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// One entry per route: `(req, url) => response body`. The dispatcher owns auth,
|
|
135
|
-
// init, status codes and the error envelope, so handlers only shape data.
|
|
136
|
-
const ROUTES = {
|
|
137
|
-
'GET /health': () => ({ ok: true, version: PLUGIN_VERSION, at: nowIso() }),
|
|
138
|
-
'GET /state': () => ({ ok: true, state: service.snapshot() }),
|
|
139
|
-
'GET /version': () => ({ ok: true, ...VERSION_ROW, hostVersion: service.localVersion }),
|
|
140
|
-
'GET /ssh/aliases': async () => ({ ok: true, ...(await service.discoverSshAliases()) }),
|
|
141
|
-
'GET /keyfile/list': async (req, url) => ({
|
|
142
|
-
ok: true,
|
|
143
|
-
...(await service.listKeyFiles(url.searchParams.get('path') ?? '')),
|
|
144
|
-
}),
|
|
145
|
-
'GET /diagnostics/self': () => ({
|
|
146
|
-
ok: true,
|
|
147
|
-
plugin: PLUGIN_ROW,
|
|
148
|
-
at: nowIso(),
|
|
149
|
-
...(typeof options.diagnostics === 'function' ? options.diagnostics() : {}),
|
|
150
|
-
}),
|
|
151
|
-
'POST /hosts': async (req) => {
|
|
152
|
-
const body = await readJson(req)
|
|
153
|
-
return { ok: true, host: await service.saveHost(body.host ?? body) }
|
|
154
|
-
},
|
|
155
|
-
'POST /settings': async (req) => {
|
|
156
|
-
const body = await readJson(req)
|
|
157
|
-
return { ok: true, settings: await service.saveSettings(body.patch ?? body) }
|
|
158
|
-
},
|
|
159
|
-
'POST /local-version': async (req) => {
|
|
160
|
-
const { version } = await readJson(req)
|
|
161
|
-
service.setLocalVersion(String(version ?? ''), 'client')
|
|
162
|
-
return { ok: true }
|
|
163
|
-
},
|
|
164
|
-
'POST /active': async (req) => {
|
|
165
|
-
const { id } = await readJson(req)
|
|
166
|
-
service.setActiveHost(typeof id === 'string' ? id : null)
|
|
167
|
-
return { ok: true }
|
|
168
|
-
},
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// `/hosts/:id` and `/hosts/:id/<action>`, keyed the same way.
|
|
172
|
-
const HOST_ACTIONS = {
|
|
173
|
-
DELETE: async (id) => {
|
|
174
|
-
await service.removeHost(id)
|
|
175
|
-
return { ok: true }
|
|
176
|
-
},
|
|
177
|
-
'POST connect': async (id, req) => {
|
|
178
|
-
const body = await readJson(req)
|
|
179
|
-
const result = await service.connect(id, {
|
|
180
|
-
password: typeof body.password === 'string' ? body.password : undefined,
|
|
181
|
-
rememberPassword: body.rememberPassword === true,
|
|
182
|
-
})
|
|
183
|
-
return { ok: true, ...result }
|
|
184
|
-
},
|
|
185
|
-
'POST conflict': async (id, req) => {
|
|
186
|
-
const { action } = await readJson(req)
|
|
187
|
-
return { ok: true, ...(await service.confirmConflict(id, { action })) }
|
|
188
|
-
},
|
|
189
|
-
'POST disconnect': async (id, req) => {
|
|
190
|
-
const { stopRemote } = await readJson(req)
|
|
191
|
-
await service.disconnect(id, { stopRemote: stopRemote === true })
|
|
192
|
-
return { ok: true }
|
|
193
|
-
},
|
|
194
|
-
'POST reconnect': async (id) => {
|
|
195
|
-
await service.reconnect(id)
|
|
196
|
-
return { ok: true }
|
|
197
|
-
},
|
|
198
|
-
'POST fingerprint': async (id, req) => {
|
|
199
|
-
const body = await readJson(req)
|
|
200
|
-
await service.confirmFingerprint(id, {
|
|
201
|
-
accept: body.accept === true,
|
|
202
|
-
remember: body.remember === true,
|
|
203
|
-
sha256: typeof body.sha256 === 'string' ? body.sha256 : undefined,
|
|
204
|
-
})
|
|
205
|
-
return { ok: true }
|
|
206
|
-
},
|
|
207
|
-
'POST diagnose': async (id) => ({ ok: true, report: await service.diagnose(id) }),
|
|
208
|
-
'GET open': (id) => ({ ok: true, ...service.openInfo(id) }),
|
|
209
|
-
'POST activate': (id) => {
|
|
210
|
-
service.setActiveHost(id)
|
|
211
|
-
return { ok: true }
|
|
212
|
-
},
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/** Resolve `/hosts/:id[/action]` to `{ id, run }`, or null for an unknown shape. */
|
|
216
|
-
function hostHandler(hostPath, method) {
|
|
217
|
-
const segments = hostPath.split('/').filter(Boolean)
|
|
218
|
-
if (segments[0] !== 'hosts' || segments.length < 2) return null
|
|
219
|
-
const key = segments[2] ? `${method} ${segments[2]}` : method
|
|
220
|
-
if (!Object.hasOwn(HOST_ACTIONS, key)) return null
|
|
221
|
-
return { id: decodeURIComponent(segments[1]), run: HOST_ACTIONS[key] }
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async function handler(req, res) {
|
|
225
|
-
try {
|
|
226
|
-
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
227
|
-
if (!url.pathname.startsWith(API_PREFIX)) {
|
|
228
|
-
sendJson(res, 404, {
|
|
229
|
-
ok: false,
|
|
230
|
-
error: toErrorView(errors.invalidInput('path', { zh: '未知 API 路径。', en: 'Unknown API path.' })),
|
|
231
|
-
})
|
|
232
|
-
return
|
|
233
|
-
}
|
|
234
|
-
const path = url.pathname.slice(API_PREFIX.length) || '/'
|
|
235
|
-
const method = (req.method ?? 'GET').toUpperCase()
|
|
236
|
-
|
|
237
|
-
if (path === '/health' && method === 'GET') {
|
|
238
|
-
sendJson(res, 200, ROUTES['GET /health']())
|
|
239
|
-
return
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// SSE cannot carry the custom header; trusting only the same-origin fence
|
|
243
|
-
// is enough for a read-only state stream (browsers block cross-origin
|
|
244
|
-
// EventSource without CORS headers, which this route never sends).
|
|
245
|
-
if (path === '/events' && method === 'GET') {
|
|
246
|
-
const originOnly = authorizeOrigin(req)
|
|
247
|
-
if (!originOnly.ok) {
|
|
248
|
-
sendJson(res, originOnly.status, { ok: false, error: originOnly.error })
|
|
249
|
-
return
|
|
250
|
-
}
|
|
251
|
-
await service.init()
|
|
252
|
-
handleSse(req, res)
|
|
253
|
-
return
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
const auth = authorize(req)
|
|
257
|
-
if (!auth.ok) {
|
|
258
|
-
sendJson(res, auth.status, { ok: false, error: auth.error })
|
|
259
|
-
return
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
await service.init()
|
|
263
|
-
|
|
264
|
-
// Download jobs save through the Host directly; no binary response route is
|
|
265
|
-
// needed, so these handlers only shape JSON.
|
|
266
|
-
const segments = path.split('/').filter(Boolean)
|
|
267
|
-
if (method === 'POST' && path === '/downloads') {
|
|
268
|
-
const body = await readJson(req)
|
|
269
|
-
const job = await service.startRemoteDownload(body.hostId, body.path, {
|
|
270
|
-
destination: body.destination,
|
|
271
|
-
})
|
|
272
|
-
sendJson(res, 200, { ok: true, job })
|
|
273
|
-
return
|
|
274
|
-
}
|
|
275
|
-
if (segments[0] === 'downloads' && segments.length >= 2 && segments.length <= 3) {
|
|
276
|
-
let jobId = ''
|
|
277
|
-
try {
|
|
278
|
-
jobId = decodeURIComponent(segments[1])
|
|
279
|
-
} catch {
|
|
280
|
-
throw errors.invalidInput('id', {
|
|
281
|
-
zh: '下载任务 id 不是合法的 URL 编码。',
|
|
282
|
-
en: 'The download job id is not valid URL encoding.',
|
|
283
|
-
})
|
|
284
|
-
}
|
|
285
|
-
if (method === 'GET' && segments.length === 3 && segments[2] === 'status') {
|
|
286
|
-
sendJson(res, 200, { ok: true, job: await service.remoteDownloadStatus(jobId) })
|
|
287
|
-
return
|
|
288
|
-
}
|
|
289
|
-
if (method === 'DELETE' && segments.length === 2) {
|
|
290
|
-
await service.cancelRemoteDownload(jobId)
|
|
291
|
-
sendJson(res, 200, { ok: true })
|
|
292
|
-
return
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
const routeKey = `${method} ${path}`
|
|
297
|
-
if (Object.hasOwn(ROUTES, routeKey)) {
|
|
298
|
-
sendJson(res, 200, await ROUTES[routeKey](req, url))
|
|
299
|
-
return
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
const host = hostHandler(path, method)
|
|
303
|
-
if (host) {
|
|
304
|
-
sendJson(res, 200, await host.run(host.id, req))
|
|
305
|
-
return
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
sendJson(res, 404, {
|
|
309
|
-
ok: false,
|
|
310
|
-
error: toErrorView(
|
|
311
|
-
errors.invalidInput('path', { zh: `未知路径 ${method} ${path}`, en: `Unknown path ${method} ${path}` }),
|
|
312
|
-
),
|
|
313
|
-
})
|
|
314
|
-
} catch (error) {
|
|
315
|
-
const view = toErrorView(error)
|
|
316
|
-
const status = isRemoteGoError(error) ? (view.code === 'invalid-input' ? 400 : 409) : 500
|
|
317
|
-
logger.error?.('[dsh-remote-go] API error:', error)
|
|
318
|
-
try {
|
|
319
|
-
sendJson(res, status, { ok: false, error: view })
|
|
320
|
-
} catch {
|
|
321
|
-
/* response already gone */
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
return {
|
|
327
|
-
handler,
|
|
328
|
-
dispose() {
|
|
329
|
-
service.removeListener('state', broadcastState)
|
|
330
|
-
service.removeListener('download', broadcastDownload)
|
|
331
|
-
clearInterval(heartbeat)
|
|
332
|
-
for (const client of sseClients) {
|
|
333
|
-
try {
|
|
334
|
-
client.end()
|
|
335
|
-
} catch {}
|
|
336
|
-
}
|
|
337
|
-
sseClients.clear()
|
|
338
|
-
},
|
|
339
|
-
}
|
|
340
|
-
}
|
package/src/atomic-json.js
DELETED
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Atomic JSON persistence: 0700 dir, 0600 file, fsynced temp, rename retry and a cross-process lock; a bad file is reported, never thrown.
|
|
3
|
-
*/
|
|
4
|
-
import { promises as fs } from 'node:fs'
|
|
5
|
-
import { existsSync } from 'node:fs'
|
|
6
|
-
import { randomUUID } from 'node:crypto'
|
|
7
|
-
import path from 'node:path'
|
|
8
|
-
import { sleep } from './util.js'
|
|
9
|
-
|
|
10
|
-
const RENAME_RETRY_ATTEMPTS = 5
|
|
11
|
-
const RENAME_RETRY_BASE_MS = 20
|
|
12
|
-
const LOCK_STALE_MS = 10_000
|
|
13
|
-
const LOCK_WAIT_MS = 20_000
|
|
14
|
-
const LOCK_RETRY_MS = 10
|
|
15
|
-
/**
|
|
16
|
-
* How long a non-`EEXIST` lock error counts as contention without the lock present.
|
|
17
|
-
* Windows reports mid-create/mid-delete races as EPERM/EACCES, but those codes also
|
|
18
|
-
* mean a lock that can never be created (ACL denial, read-only mount); past this
|
|
19
|
-
* window the original error is surfaced instead of a misleading timeout.
|
|
20
|
-
*/
|
|
21
|
-
const LOCK_TRANSIENT_MS = 250
|
|
22
|
-
const LOCK_UNLINK_ATTEMPTS = 3
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* In-process chains keyed by lock path; the value is the always-settled tail so a
|
|
26
|
-
* rejected write never poisons the next waiter.
|
|
27
|
-
*/
|
|
28
|
-
const LOCAL_CHAINS = new Map()
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Run `task` under the cross-process lock, serialized with every in-process holder
|
|
32
|
-
* of the same lock path.
|
|
33
|
-
*/
|
|
34
|
-
export function withProcessLock(lockFile, options, task) {
|
|
35
|
-
const previous = LOCAL_CHAINS.get(lockFile) ?? Promise.resolve()
|
|
36
|
-
const run = previous.then(
|
|
37
|
-
() => runExclusive(lockFile, options ?? {}, task),
|
|
38
|
-
() => runExclusive(lockFile, options ?? {}, task),
|
|
39
|
-
)
|
|
40
|
-
LOCAL_CHAINS.set(
|
|
41
|
-
lockFile,
|
|
42
|
-
run.catch(() => undefined),
|
|
43
|
-
)
|
|
44
|
-
return run
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function runExclusive(lockFile, options, task) {
|
|
48
|
-
const release = await acquireLock(lockFile, options)
|
|
49
|
-
try {
|
|
50
|
-
return await task()
|
|
51
|
-
} finally {
|
|
52
|
-
await release()
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
async function acquireLock(lockFile, options) {
|
|
57
|
-
const fsImpl = options.fs ?? fs
|
|
58
|
-
const staleMs = options.staleMs ?? LOCK_STALE_MS
|
|
59
|
-
const waitMs = options.waitMs ?? LOCK_WAIT_MS
|
|
60
|
-
const retryMs = options.retryMs ?? LOCK_RETRY_MS
|
|
61
|
-
const started = Date.now()
|
|
62
|
-
// Only a lock we never once observed can be a permanent permission error: under
|
|
63
|
-
// real contention the lock is created and unlinked constantly.
|
|
64
|
-
let sawLock = false
|
|
65
|
-
while (true) {
|
|
66
|
-
try {
|
|
67
|
-
const handle = await fsImpl.open(lockFile, 'wx', 0o600)
|
|
68
|
-
return async () => {
|
|
69
|
-
try {
|
|
70
|
-
await handle.close()
|
|
71
|
-
} catch {}
|
|
72
|
-
// A leaked lock costs the next writer a full stale wait, so retry the unlink
|
|
73
|
-
// (Windows can hold it briefly after close).
|
|
74
|
-
for (let attempt = 0; attempt < LOCK_UNLINK_ATTEMPTS; attempt += 1) {
|
|
75
|
-
try {
|
|
76
|
-
await fsImpl.unlink(lockFile)
|
|
77
|
-
return
|
|
78
|
-
} catch (unlinkError) {
|
|
79
|
-
const unlinkCode = /** @type {any} */ (unlinkError)?.code
|
|
80
|
-
if (unlinkCode === 'ENOENT') return
|
|
81
|
-
if (attempt === LOCK_UNLINK_ATTEMPTS - 1) return
|
|
82
|
-
await sleep(retryMs)
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
} catch (error) {
|
|
87
|
-
// Windows reports contention on an exclusive create as EPERM/EACCES/EBUSY
|
|
88
|
-
// rather than EEXIST when the other process is mid-create or mid-delete.
|
|
89
|
-
const code = /** @type {any} */ (error)?.code
|
|
90
|
-
if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') throw error
|
|
91
|
-
if (code !== 'EEXIST' && !sawLock && Date.now() - started > LOCK_TRANSIENT_MS) {
|
|
92
|
-
if (!(await lockExists(fsImpl, lockFile))) throw error
|
|
93
|
-
}
|
|
94
|
-
if (code === 'EEXIST' || (await lockExists(fsImpl, lockFile))) sawLock = true
|
|
95
|
-
await breakStaleLock(fsImpl, lockFile, staleMs)
|
|
96
|
-
if (Date.now() - started > waitMs) {
|
|
97
|
-
const timeout = new Error('timed out waiting for another process to release the store lock')
|
|
98
|
-
timeout.code = 'ELOCKTIMEOUT'
|
|
99
|
-
throw timeout
|
|
100
|
-
}
|
|
101
|
-
await sleep(retryMs)
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
async function breakStaleLock(fsImpl, lockFile, staleMs) {
|
|
107
|
-
try {
|
|
108
|
-
const info = await fsImpl.stat(lockFile)
|
|
109
|
-
if (Date.now() - info.mtimeMs > staleMs) await removeQuietly(fsImpl, lockFile)
|
|
110
|
-
} catch {
|
|
111
|
-
/* the lock disappeared or cannot be inspected: retry the create */
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export async function writeJsonAtomic(file, value, options = {}) {
|
|
116
|
-
const fsImpl = options.fs ?? fs
|
|
117
|
-
const logger = options.logger ?? console
|
|
118
|
-
const dir = options.dir ?? path.dirname(file)
|
|
119
|
-
const dirMode = options.dirMode ?? 0o700
|
|
120
|
-
const fileMode = options.fileMode ?? 0o600
|
|
121
|
-
try {
|
|
122
|
-
await fsImpl.mkdir(dir, { recursive: true, mode: dirMode })
|
|
123
|
-
} catch (error) {
|
|
124
|
-
logger.warn?.(`[dsh-remote-go] cannot create ${dir}:`, error)
|
|
125
|
-
}
|
|
126
|
-
const tmp = `${file}.${randomUUID()}.tmp`
|
|
127
|
-
const text = `${JSON.stringify(value, null, 2)}\n`
|
|
128
|
-
let handle = null
|
|
129
|
-
try {
|
|
130
|
-
handle = await fsImpl.open(tmp, 'wx', fileMode)
|
|
131
|
-
await handle.writeFile(text, 'utf8')
|
|
132
|
-
await handle.sync()
|
|
133
|
-
await handle.close()
|
|
134
|
-
handle = null
|
|
135
|
-
} catch (error) {
|
|
136
|
-
if (handle) {
|
|
137
|
-
try {
|
|
138
|
-
await handle.close()
|
|
139
|
-
} catch {}
|
|
140
|
-
}
|
|
141
|
-
await removeQuietly(fsImpl, tmp)
|
|
142
|
-
throw error
|
|
143
|
-
}
|
|
144
|
-
await renameWithRetry(fsImpl, tmp, file)
|
|
145
|
-
await syncDir(fsImpl, dir)
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
async function renameWithRetry(fsImpl, tmp, file) {
|
|
149
|
-
for (let attempt = 1; attempt <= RENAME_RETRY_ATTEMPTS; attempt += 1) {
|
|
150
|
-
try {
|
|
151
|
-
await fsImpl.rename(tmp, file)
|
|
152
|
-
return
|
|
153
|
-
} catch (error) {
|
|
154
|
-
const code = /** @type {any} */ (error)?.code
|
|
155
|
-
const retryable = code === 'EPERM' || code === 'EBUSY' || code === 'EACCES'
|
|
156
|
-
if (retryable && attempt < RENAME_RETRY_ATTEMPTS) {
|
|
157
|
-
await sleep(RENAME_RETRY_BASE_MS * attempt)
|
|
158
|
-
continue
|
|
159
|
-
}
|
|
160
|
-
await removeQuietly(fsImpl, tmp)
|
|
161
|
-
throw error
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
async function syncDir(fsImpl, dir) {
|
|
167
|
-
let handle = null
|
|
168
|
-
try {
|
|
169
|
-
handle = await fsImpl.open(dir, 'r')
|
|
170
|
-
await handle.sync()
|
|
171
|
-
} catch {
|
|
172
|
-
/* not supported on this platform/filesystem */
|
|
173
|
-
} finally {
|
|
174
|
-
if (handle) {
|
|
175
|
-
try {
|
|
176
|
-
await handle.close()
|
|
177
|
-
} catch {}
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export async function readJsonFile(file, options = {}) {
|
|
183
|
-
const fsImpl = options.fs ?? fs
|
|
184
|
-
const logger = options.logger ?? console
|
|
185
|
-
try {
|
|
186
|
-
if (!existsSync(file)) return { status: 'missing', value: null }
|
|
187
|
-
const text = await fsImpl.readFile(file, 'utf8')
|
|
188
|
-
return { status: 'ok', value: JSON.parse(text) }
|
|
189
|
-
} catch (error) {
|
|
190
|
-
logger.warn?.(`[dsh-remote-go] cannot read ${path.basename(file)}:`, error)
|
|
191
|
-
return { status: 'corrupt', value: null }
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
async function removeQuietly(fsImpl, target) {
|
|
196
|
-
try {
|
|
197
|
-
await fsImpl.unlink(target)
|
|
198
|
-
} catch {}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
async function lockExists(fsImpl, lockFile) {
|
|
202
|
-
try {
|
|
203
|
-
await fsImpl.stat(lockFile)
|
|
204
|
-
return true
|
|
205
|
-
} catch {
|
|
206
|
-
return false
|
|
207
|
-
}
|
|
208
|
-
}
|
package/src/bootstrap.js
DELETED
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Remote runtime preparation: `npx` pinned to the local DSH version against the remote's real `$DSH_HOME`; the executor runs only fixed templates.
|
|
3
|
-
*/
|
|
4
|
-
import { errors } from './errors.js'
|
|
5
|
-
import { headTail, shellQuote } from './util.js'
|
|
6
|
-
import { isNodeVersionSupported, normalizeVersion, parseVersion, versionsEqual } from './version.js'
|
|
7
|
-
|
|
8
|
-
export function assertSupportedRemote(facts) {
|
|
9
|
-
if (facts.os !== 'Linux') {
|
|
10
|
-
throw errors.unsupportedOs(`${facts.os} ${facts.arch}`.trim())
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function planNpx(input) {
|
|
15
|
-
const targetVersion = normalizeVersion(input.targetVersion)
|
|
16
|
-
if (!parseVersion(targetVersion)) {
|
|
17
|
-
throw errors.invalidInput('targetVersion', {
|
|
18
|
-
zh: `目标版本「${input.targetVersion}」不是合法版本号。`,
|
|
19
|
-
en: `Target version "${input.targetVersion}" is not a valid version.`,
|
|
20
|
-
})
|
|
21
|
-
}
|
|
22
|
-
assertSupportedRemote(input.facts)
|
|
23
|
-
if (!isNodeVersionSupported(input.facts.nodeVersion)) {
|
|
24
|
-
throw errors.remoteDshMissing({
|
|
25
|
-
zh: `远端 Node 不可用或版本过低(需要 ≥ 24.9.0,检测到 ${input.facts.nodeVersion ?? '无'}),自动准备也没有完成。请检查远端网络,或在远端安装 Node 后重试。`,
|
|
26
|
-
en: `The remote Node is missing or too old (>= 24.9.0 required, detected ${input.facts.nodeVersion ?? 'none'}) and automatic preparation did not finish. Check the remote network, or install Node on the remote and retry.`,
|
|
27
|
-
})
|
|
28
|
-
}
|
|
29
|
-
if (!input.facts.npxPath) {
|
|
30
|
-
throw errors.remoteDshMissing({
|
|
31
|
-
zh: '远端没有找到 npx。请安装 npm(随 Node 一起提供),或把 npm 的 bin 目录加入远程 shell 的 PATH。',
|
|
32
|
-
en: 'npx was not found on the remote. Install npm (shipped with Node) or add its bin directory to the remote shell PATH.',
|
|
33
|
-
})
|
|
34
|
-
}
|
|
35
|
-
if (!input.facts.curlPath && !input.facts.wgetPath) {
|
|
36
|
-
throw errors.remoteDshMissing({
|
|
37
|
-
zh: '远端既没有 curl 也没有 wget,无法在启动后探活远端界面。请安装其中之一。',
|
|
38
|
-
en: 'The remote has neither curl nor wget, so the remote UI cannot be health-checked after start. Install one of them.',
|
|
39
|
-
})
|
|
40
|
-
}
|
|
41
|
-
const nodeBinDir = input.facts.nodePath ? input.facts.nodePath.replace(/\/node$/, '') : undefined
|
|
42
|
-
return {
|
|
43
|
-
level: 'npx',
|
|
44
|
-
profile: input.profile,
|
|
45
|
-
targetVersion,
|
|
46
|
-
reason: {
|
|
47
|
-
zh: `用 npx 精确版本 ${targetVersion} 启动远端 DSH(Node 运行时由插件准备)`,
|
|
48
|
-
en: `Launch the remote DSH with npx pinned to ${targetVersion} (Node runtime prepared by the plugin)`,
|
|
49
|
-
},
|
|
50
|
-
start: {
|
|
51
|
-
kind: 'npx',
|
|
52
|
-
npxPath: input.facts.npxPath,
|
|
53
|
-
nodePath: input.facts.nodePath ?? undefined,
|
|
54
|
-
nodeBinDir,
|
|
55
|
-
targetVersion,
|
|
56
|
-
},
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* The npx preflight: resolve and run the exact package once, so a first-run
|
|
62
|
-
* download happens in the foreground (and fails with a readable error) instead
|
|
63
|
-
* of inside the detached start script.
|
|
64
|
-
*
|
|
65
|
-
* `npm_config_loglevel=http` is deliberate: over an SSH channel npm has no TTY and
|
|
66
|
-
* would otherwise print nothing until it finishes. At `http` it reports fetches
|
|
67
|
-
* on stderr, which the caller turns into progress.
|
|
68
|
-
*/
|
|
69
|
-
export function buildPreflightCommand(plan) {
|
|
70
|
-
const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
|
|
71
|
-
return `set -eu
|
|
72
|
-
${pathPrefix}npm_config_loglevel=http ${shellQuote(plan.start.npxPath)} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --version`
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export async function verifyNpxVersion(ssh, plan, options = {}) {
|
|
76
|
-
const result = await ssh.exec(buildPreflightCommand(plan), {
|
|
77
|
-
timeoutMs: options.timeoutMs ?? 0,
|
|
78
|
-
maxBytes: options.maxBytes ?? 4 * 1024 * 1024,
|
|
79
|
-
onStdout: options.onStdout,
|
|
80
|
-
onStderr: options.onStderr,
|
|
81
|
-
})
|
|
82
|
-
const combined = `${result.stdout}\n${result.stderr}`
|
|
83
|
-
if (result.code !== 0) {
|
|
84
|
-
const failure = errors.remoteDshMissing({
|
|
85
|
-
zh: `无法通过 npx 运行 @deepseek-ai/dsh@${plan.start.targetVersion}(退出码 ${result.code})。请确认远端能访问 npm registry,且 Node/npm 版本满足要求。`,
|
|
86
|
-
en: `Could not run @deepseek-ai/dsh@${plan.start.targetVersion} through npx (exit ${result.code}). Make sure the remote can reach the npm registry and Node/npm meet the requirements.`,
|
|
87
|
-
})
|
|
88
|
-
failure.technical = headTail(combined, 1500)
|
|
89
|
-
throw failure
|
|
90
|
-
}
|
|
91
|
-
const lines = String(result.stdout ?? '')
|
|
92
|
-
.split(/\r?\n/)
|
|
93
|
-
.map((line) => line.trim())
|
|
94
|
-
.filter(Boolean)
|
|
95
|
-
const reported = normalizeVersion(lines[lines.length - 1] ?? '')
|
|
96
|
-
if (!versionsEqual(reported, plan.targetVersion)) {
|
|
97
|
-
throw errors.versionMismatch(plan.targetVersion, reported || 'unknown')
|
|
98
|
-
}
|
|
99
|
-
return reported
|
|
100
|
-
}
|
package/src/connect-log.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The connect log behind `HostView.logs`: the per-host ring, its bounded `/state` tail and which statuses print it; lines travel as written, unredacted.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
export const CONNECT_LOG_STATUSES = Object.freeze(['connecting', 'fingerprint-pending', 'error'])
|
|
6
|
-
|
|
7
|
-
export const LOG_RING_LIMIT = 200
|
|
8
|
-
|
|
9
|
-
export const LOG_TAIL_LIMIT = 120
|
|
10
|
-
|
|
11
|
-
export function connectLogVisible(status) {
|
|
12
|
-
return typeof status === 'string' && CONNECT_LOG_STATUSES.includes(status)
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function appendConnectLog(runtime, input) {
|
|
16
|
-
const message = typeof input.message === 'string' ? input.message : String(input.message ?? '')
|
|
17
|
-
const entry = {
|
|
18
|
-
seq: (typeof runtime.logSeq === 'number' ? runtime.logSeq : 0) + 1,
|
|
19
|
-
at: typeof input.at === 'string' ? input.at : '',
|
|
20
|
-
level: typeof input.level === 'string' ? input.level : 'info',
|
|
21
|
-
message,
|
|
22
|
-
line: `[dsh-remote-go:${runtime.id}] ${message}`,
|
|
23
|
-
}
|
|
24
|
-
if (!Array.isArray(runtime.logs)) runtime.logs = []
|
|
25
|
-
if (runtime.logs.length >= LOG_RING_LIMIT) runtime.logs.shift()
|
|
26
|
-
runtime.logSeq = entry.seq
|
|
27
|
-
runtime.logs.push(entry)
|
|
28
|
-
return entry
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function connectLogTail(runtime) {
|
|
32
|
-
const entries = runtime && Array.isArray(runtime.logs) ? runtime.logs : []
|
|
33
|
-
return entries.slice(-LOG_TAIL_LIMIT).map((entry) => ({
|
|
34
|
-
seq: typeof entry.seq === 'number' ? entry.seq : 0,
|
|
35
|
-
at: typeof entry.at === 'string' ? entry.at : '',
|
|
36
|
-
level: typeof entry.level === 'string' ? entry.level : 'info',
|
|
37
|
-
message: typeof entry.message === 'string' ? entry.message : String(entry.line ?? ''),
|
|
38
|
-
}))
|
|
39
|
-
}
|