dsh-remote-go 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +126 -7
  2. package/client.js +5972 -0
  3. package/cordis.patch.yml +3 -0
  4. package/index.js +4 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +76 -3
  8. package/src/api.js +340 -0
  9. package/src/atomic-json.js +208 -0
  10. package/src/bootstrap.js +100 -0
  11. package/src/connect-log.js +39 -0
  12. package/src/connect-pipeline.js +463 -0
  13. package/src/connect-progress.js +135 -0
  14. package/src/constants.js +31 -0
  15. package/src/diagnostics.js +157 -0
  16. package/src/download-jobs.js +217 -0
  17. package/src/errors.js +316 -0
  18. package/src/host-lifecycle.js +187 -0
  19. package/src/host-registry.js +145 -0
  20. package/src/host-runtime.js +53 -0
  21. package/src/host-view.js +51 -0
  22. package/src/index.js +162 -0
  23. package/src/key-files.js +49 -0
  24. package/src/known-hosts.js +94 -0
  25. package/src/layout.js +35 -0
  26. package/src/local-download.js +162 -0
  27. package/src/local-ssh.js +27 -0
  28. package/src/local-version.js +88 -0
  29. package/src/node-runtime.js +521 -0
  30. package/src/probe.js +89 -0
  31. package/src/prompts.js +132 -0
  32. package/src/redact.js +54 -0
  33. package/src/remote-files.js +71 -0
  34. package/src/remote-path.js +73 -0
  35. package/src/remote-proc.js +208 -0
  36. package/src/remote-web.js +300 -0
  37. package/src/secrets.js +79 -0
  38. package/src/service.js +250 -0
  39. package/src/settings.js +135 -0
  40. package/src/ssh-config.js +271 -0
  41. package/src/ssh.js +652 -0
  42. package/src/store.js +143 -0
  43. package/src/tunnel.js +73 -0
  44. package/src/util.js +153 -0
  45. package/src/version.js +103 -0
  46. package/src/webapp.js +28 -0
  47. package/vendor/THIRD_PARTY_NOTICES.md +10 -0
  48. package/vendor/ssh2-entry.mjs +12 -0
  49. package/vendor/ssh2.bundle.cjs +25 -0
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-remote-go
3
+ name: dsh-remote-go
package/index.js ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Package entry for the DSH Loader. The implementation lives in `src/`.
3
+ */
4
+ export { apply, inject, name, optional } from './src/index.js'
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "dsh remote go",
4
+ "description": "Use a remote DSH over SSH in the whole window of the local DSH: one sidebar switcher moves between “Local” and each host, and a connected remote comes back instantly. The remote runs on a plugin-managed Node with npx pinned to the local version, keeps its data in the user’s own ~/.dsh, and ships the connect log and diagnostics."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "dsh remote go",
4
+ "description": "通过 SSH 在本地 DSH 的整窗里使用远端 DSH:侧边栏主机条在「本地」与各主机间切换,已连接的远端一点即回;远端由插件自托管的 Node 加 npx 按本机版本启动,数据留在远端用户自己的 ~/.dsh,含连接日志与诊断。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "dsh-remote-go",
3
- "version": "0.0.1",
4
- "description": "Placeholder release reserving the npm name for the dsh-remote-go DeepSeek Harness plugin; the plugin ships in 0.1.0 and later.",
3
+ "version": "0.1.0",
4
+ "description": "DSH 插件:通过 SSH 在本地 DSH 的整窗里使用远端 DSH(主机条切换、插件托管 Node + npx 固定本机版本、数据留在远端 ~/.dsh) | DSH plugin: use a remote DSH over SSH in the whole local window with one host switcher; the remote runs on a plugin-managed Node with npx pinned to the local version and keeps its data in the remote ~/.dsh",
5
5
  "keywords": [
6
6
  "deepseek",
7
7
  "harness",
8
8
  "dsh",
9
9
  "dsh-plugin",
10
10
  "remote",
11
- "ssh"
11
+ "ssh",
12
+ "remote-development"
12
13
  ],
13
14
  "license": "MIT",
14
15
  "author": "Solaris136",
@@ -20,8 +21,80 @@
20
21
  "type": "git",
21
22
  "url": "git+https://github.com/Solaris136/dsh-remote-go.git"
22
23
  },
24
+ "type": "module",
25
+ "packageManager": "pnpm@11.28.9",
26
+ "engines": {
27
+ "dsh": ">=0.2.2-rc.3",
28
+ "node": ">=24"
29
+ },
30
+ "sideEffects": [
31
+ "./client.js"
32
+ ],
33
+ "exports": {
34
+ ".": "./index.js",
35
+ "./client": "./client.js",
36
+ "./locale/*.json": "./locale/*.json",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "index.js",
41
+ "client.js",
42
+ "src",
43
+ "vendor",
44
+ "locale",
45
+ "cordis.patch.yml",
46
+ "README.md",
47
+ "LICENSE"
48
+ ],
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ },
53
+ "client": {
54
+ "platform": "web",
55
+ "immediately": true,
56
+ "inject": [
57
+ "@deepseek-ai/dsh-client-ui-layout",
58
+ "@deepseek-ai/dsh-client-locale"
59
+ ]
60
+ }
61
+ },
23
62
  "publishConfig": {
24
63
  "access": "public",
25
64
  "registry": "https://registry.npmjs.org/"
65
+ },
66
+ "dependencies": {},
67
+ "devDependencies": {
68
+ "@deepseek-ai/dsh-plugin-market-index": "0.2.2-rc.2",
69
+ "esbuild": "^0.28.2",
70
+ "js-yaml": "^5.5.0",
71
+ "prettier": "^3.10.0",
72
+ "puppeteer-core": "^25.17.0",
73
+ "react": "^19.3.1",
74
+ "react-dom": "^19.3.1",
75
+ "ssh2": "1.17.0"
76
+ },
77
+ "scripts": {
78
+ "test": "node --test \"test/unit/*.test.js\"",
79
+ "test:unit": "node --test \"test/unit/*.test.js\"",
80
+ "test:web": "node --test \"test/integration/web.e2e.js\"",
81
+ "test:desktop": "node --test \"test/integration/desktop.e2e.js\"",
82
+ "test:integration": "node --test \"test/integration/*.test.js\" \"test/integration/*.e2e.js\"",
83
+ "sim:remote": "node e2e/sim/simulated-remote.mjs --self-test",
84
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude=vendor/** --test-coverage-exclude=test/** --test-coverage-lines=85 --test-coverage-branches=70 --test-coverage-functions=80 \"test/unit/*.test.js\"",
85
+ "lint": "node scripts/check-repo.mjs",
86
+ "check:repo": "node scripts/check-repo.mjs",
87
+ "check:syntax": "node scripts/check-syntax.mjs",
88
+ "check:workflows": "node scripts/check-workflows.mjs",
89
+ "check:pr-title": "node scripts/check-pr-title.mjs",
90
+ "format": "prettier --write .",
91
+ "format:check": "prettier --check .",
92
+ "verify": "node scripts/check-repo.mjs && prettier --check . && node scripts/check-syntax.mjs && node scripts/check-workflows.mjs && node scripts/market-entry.mjs --check && node scripts/pack-check.mjs && node --test \"test/unit/*.test.js\" && node --test --test-concurrency=1 \"test/integration/*.test.js\" \"test/integration/*.e2e.js\"",
93
+ "build:vendor": "node scripts/build-vendor.mjs",
94
+ "market:entry": "node scripts/market-entry.mjs",
95
+ "market:check": "node scripts/market-entry.mjs --check",
96
+ "pack:check": "node scripts/pack-check.mjs",
97
+ "pack:check:tarball": "node scripts/pack-check.mjs --find artifacts",
98
+ "prepack": "node scripts/market-entry.mjs --check"
26
99
  }
27
100
  }
package/src/api.js ADDED
@@ -0,0 +1,340 @@
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
+ }
@@ -0,0 +1,208 @@
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
+ }