dsh-remote-go 0.0.1 → 0.2.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 (52) hide show
  1. package/README.md +87 -7
  2. package/client.js +8763 -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 +77 -3
  8. package/src/admission.js +43 -0
  9. package/src/api.js +536 -0
  10. package/src/atomic-json.js +225 -0
  11. package/src/bootstrap.js +113 -0
  12. package/src/connect-log.js +176 -0
  13. package/src/connect-pipeline.js +1900 -0
  14. package/src/connect-progress.js +155 -0
  15. package/src/constants.js +93 -0
  16. package/src/diagnostics.js +160 -0
  17. package/src/download-jobs.js +234 -0
  18. package/src/errors.js +412 -0
  19. package/src/host-lifecycle.js +604 -0
  20. package/src/host-registry.js +217 -0
  21. package/src/host-runtime.js +127 -0
  22. package/src/host-view.js +75 -0
  23. package/src/index.js +206 -0
  24. package/src/key-files.js +54 -0
  25. package/src/known-hosts.js +133 -0
  26. package/src/layout.js +53 -0
  27. package/src/local-download.js +381 -0
  28. package/src/local-ssh.js +27 -0
  29. package/src/local-version.js +88 -0
  30. package/src/node-runtime.js +521 -0
  31. package/src/probe.js +101 -0
  32. package/src/prompts.js +229 -0
  33. package/src/redact.js +68 -0
  34. package/src/remote-files.js +71 -0
  35. package/src/remote-path.js +137 -0
  36. package/src/remote-proc.js +343 -0
  37. package/src/remote-proxy.js +815 -0
  38. package/src/remote-web.js +751 -0
  39. package/src/request-trust.js +89 -0
  40. package/src/secrets.js +109 -0
  41. package/src/service.js +459 -0
  42. package/src/settings.js +163 -0
  43. package/src/ssh-config.js +271 -0
  44. package/src/ssh.js +731 -0
  45. package/src/store.js +193 -0
  46. package/src/tools.js +386 -0
  47. package/src/tunnel.js +132 -0
  48. package/src/util.js +153 -0
  49. package/src/version.js +103 -0
  50. package/src/webapp.js +43 -0
  51. package/vendor/THIRD_PARTY_NOTICES.md +36 -0
  52. package/vendor/ssh2.bundle.cjs +25 -0
package/src/tunnel.js ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Local loopback TCP listener piped through the SSH transport; the guest points at it, so its cookies never mix with the local GUI's.
3
+ */
4
+ import http from 'node:http'
5
+ import net from 'node:net'
6
+
7
+ /**
8
+ * Ask the *local* listener whether it still serves, without trusting the SSH-side probe:
9
+ * any HTTP answer (even 401/404) proves the tunnel forwards, while a refused/destroyed
10
+ * socket means it is broken. Used before rebuilding a tunnel for a transient proxy failure.
11
+ * @param {number | null} localPort - tunnel's local port, if any.
12
+ * @param {{ timeoutMs?: number }} [options]
13
+ * @returns {Promise<boolean>} whether the listener answered.
14
+ */
15
+ export function probeLoopback(localPort, options = {}) {
16
+ const port = Number(localPort)
17
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return Promise.resolve(false)
18
+ return new Promise((resolve) => {
19
+ let settled = false
20
+ const finish = (ok) => {
21
+ if (settled) return
22
+ settled = true
23
+ resolve(ok)
24
+ }
25
+ const request = http.get(
26
+ { host: '127.0.0.1', port, path: '/', timeout: options.timeoutMs ?? 1_500 },
27
+ (response) => {
28
+ response.resume()
29
+ finish(true)
30
+ },
31
+ )
32
+ request.on('timeout', () => {
33
+ request.destroy()
34
+ finish(false)
35
+ })
36
+ request.on('error', () => finish(false))
37
+ })
38
+ }
39
+
40
+ export async function createTunnel(options) {
41
+ const remoteHost = options.remoteHost ?? '127.0.0.1'
42
+ const listenHost = options.listenHost ?? '127.0.0.1'
43
+ const sockets = new Set()
44
+ // The forwarded SSH channels this listener opened: a closed listener must destroy them too,
45
+ // otherwise an established pipe keeps the (already released) SSH transport busy.
46
+ const streams = new Set()
47
+ let closed = false
48
+
49
+ const server = net.createServer((socket) => {
50
+ if (closed) {
51
+ socket.destroy()
52
+ return
53
+ }
54
+ sockets.add(socket)
55
+ const cleanup = () => {
56
+ sockets.delete(socket)
57
+ }
58
+ socket.once('close', cleanup)
59
+ socket.once('error', cleanup)
60
+ const ssh = options.ssh
61
+ if (!ssh) {
62
+ // A listener can outlive its transport if a caller leaks it; never throw from a net
63
+ // connection callback (an uncaught exception there ends the whole host process).
64
+ socket.destroy()
65
+ return
66
+ }
67
+ ssh
68
+ .forwardOut(remoteHost, options.remotePort, '127.0.0.1', socket.remotePort ?? 0)
69
+ .then((stream) => {
70
+ if (closed) {
71
+ stream.destroy()
72
+ socket.destroy()
73
+ return
74
+ }
75
+ streams.add(stream)
76
+ const forget = () => {
77
+ streams.delete(stream)
78
+ }
79
+ stream.once('close', forget)
80
+ stream.once('error', forget)
81
+ socket.pipe(stream).pipe(socket)
82
+ stream.once('close', () => {
83
+ if (!socket.destroyed) socket.end()
84
+ })
85
+ stream.once('error', () => {
86
+ socket.destroy()
87
+ })
88
+ })
89
+ .catch((error) => {
90
+ options.onError?.(error instanceof Error ? error : new Error(String(error)))
91
+ socket.destroy()
92
+ })
93
+ })
94
+
95
+ await new Promise((resolve, reject) => {
96
+ server.once('error', reject)
97
+ server.listen(options.listenPort ?? 0, listenHost, () => {
98
+ server.removeListener('error', reject)
99
+ resolve(undefined)
100
+ })
101
+ })
102
+ const address = server.address()
103
+ if (!address || typeof address === 'string') {
104
+ server.close()
105
+ throw new Error('tunnel listener did not expose a TCP address')
106
+ }
107
+
108
+ return {
109
+ localPort: address.port,
110
+ listenHost,
111
+ urlHost: listenHost.includes(':') ? `[${listenHost}]` : listenHost,
112
+ get connections() {
113
+ return sockets.size
114
+ },
115
+ async close() {
116
+ if (closed) return
117
+ closed = true
118
+ for (const socket of sockets) socket.destroy()
119
+ sockets.clear()
120
+ // Destroy the forwarded channels as well: the SSH session may already be disposed.
121
+ for (const stream of streams) {
122
+ try {
123
+ stream.destroy()
124
+ } catch {
125
+ /* the channel may already be gone */
126
+ }
127
+ }
128
+ streams.clear()
129
+ await new Promise((resolve) => server.close(() => resolve(undefined)))
130
+ },
131
+ }
132
+ }
package/src/util.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Small pure helpers shared by the host half, unit-tested with node:test.
3
+ */
4
+
5
+ export function sleep(ms) {
6
+ return new Promise((resolve) => setTimeout(resolve, ms))
7
+ }
8
+
9
+ export function randomDelay(min, max) {
10
+ return Math.round(min + Math.random() * Math.max(0, max - min))
11
+ }
12
+
13
+ const ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'
14
+
15
+ export function randomId(prefix = 'h') {
16
+ let out = ''
17
+ for (let i = 0; i < 10; i += 1) out += ID_ALPHABET[Math.floor(Math.random() * ID_ALPHABET.length)]
18
+ return `${prefix}_${out}`
19
+ }
20
+
21
+ export function nowIso() {
22
+ return new Date().toISOString()
23
+ }
24
+
25
+ export function isPlainObject(value) {
26
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
27
+ }
28
+
29
+ const LOG_LEVELS = { error: 0, warn: 1, info: 2, debug: 3 }
30
+
31
+ /** Prototype-chain names that must never be written by a merge. */
32
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
33
+
34
+ /**
35
+ * Recursively merge `patch` into `base` (arrays and scalars replace). Only keys
36
+ * `base` declares are written, so untrusted input can change known values but
37
+ * never invent a property or poison the prototype.
38
+ */
39
+ export function deepMerge(base, patch) {
40
+ if (!isPlainObject(base) || !isPlainObject(patch)) return /** @type {T} */ (patch === undefined ? base : patch)
41
+ const out = { ...base }
42
+ for (const key of Object.keys(base)) {
43
+ if (UNSAFE_KEYS.has(key)) continue
44
+ const value = patch[key]
45
+ if (value === undefined) continue
46
+ out[key] = isPlainObject(value) && isPlainObject(base[key]) ? deepMerge(base[key], value) : value
47
+ }
48
+ return out
49
+ }
50
+
51
+ export function clamp(value, min, max) {
52
+ return Math.min(max, Math.max(min, value))
53
+ }
54
+
55
+ export function expandHome(value, home) {
56
+ const text = typeof value === 'string' ? value.trim() : ''
57
+ if (text === '') return ''
58
+ if (text === '~') return home
59
+ if (text.startsWith('~/') || text.startsWith('~\\')) return home.replace(/[\\/]+$/, '') + text.slice(1)
60
+ return text
61
+ }
62
+
63
+ export function parseSshDestination(raw) {
64
+ const text = String(raw ?? '').trim()
65
+ if (text === '') return { user: null, host: '', port: null }
66
+ let user = null
67
+ let rest = text
68
+ const at = rest.lastIndexOf('@')
69
+ if (at >= 0) {
70
+ user = rest.slice(0, at)
71
+ rest = rest.slice(at + 1)
72
+ }
73
+ let host = rest
74
+ let port = null
75
+ if (rest.startsWith('[')) {
76
+ const close = rest.indexOf(']')
77
+ if (close > 0) {
78
+ host = rest.slice(1, close)
79
+ const tail = rest.slice(close + 1)
80
+ if (/^:\d+$/.test(tail)) port = Number(tail.slice(1))
81
+ }
82
+ } else {
83
+ const colon = rest.lastIndexOf(':')
84
+ if (colon > 0 && rest.indexOf(':') === colon) {
85
+ const maybePort = rest.slice(colon + 1)
86
+ if (/^\d{1,5}$/.test(maybePort)) {
87
+ host = rest.slice(0, colon)
88
+ port = Number(maybePort)
89
+ }
90
+ }
91
+ }
92
+ return { user: user || null, host, port }
93
+ }
94
+
95
+ export function isLoopbackHost(host) {
96
+ if (!host) return false
97
+ const normalized = host
98
+ .trim()
99
+ .toLowerCase()
100
+ .replace(/^\[|\]$/g, '')
101
+ if (normalized === 'localhost' || normalized === '::1') return true
102
+ if (normalized === '::ffff:127.0.0.1') return true
103
+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)
104
+ }
105
+
106
+ export function shellQuote(value) {
107
+ return `'${String(value).replaceAll("'", `'\\''`)}'`
108
+ }
109
+
110
+ export function headTail(text, max = 4000) {
111
+ const value = String(text ?? '')
112
+ if (value.length <= max) return value
113
+ const head = value.slice(0, Math.floor(max / 2))
114
+ const tail = value.slice(-Math.floor(max / 2))
115
+ return `${head}\n…\n${tail}`
116
+ }
117
+
118
+ export function logVisible(level, threshold = 'info') {
119
+ const rank = LOG_LEVELS[level] ?? LOG_LEVELS.info
120
+ const floor = LOG_LEVELS[threshold] ?? LOG_LEVELS.info
121
+ return rank >= floor
122
+ }
123
+
124
+ /** Message of an unknown thrown value, so catch blocks need not spell the ternary. */
125
+ export function messageOf(error) {
126
+ return String(error?.message ?? error)
127
+ }
128
+
129
+ /** A positive integer — the only shape `kill`, `/proc` and a TCP port accept. */
130
+ export function isPid(value) {
131
+ return Number.isInteger(value) && value > 0
132
+ }
133
+
134
+ /**
135
+ * A promise that resolves at most once: through `settle`, or with `onTimeout()`
136
+ * when the deadline passes first. `onSettled` runs before the promise resolves so
137
+ * a caller can clear the pending slot it installed on both paths.
138
+ */
139
+ export function createDecision(timeoutMs, onTimeout, onSettled) {
140
+ let settle
141
+ const promise = new Promise((resolve) => {
142
+ let done = false
143
+ const timer = setTimeout(() => settle(onTimeout?.()), timeoutMs)
144
+ settle = (value) => {
145
+ if (done) return
146
+ done = true
147
+ clearTimeout(timer)
148
+ onSettled?.(value)
149
+ resolve(value)
150
+ }
151
+ })
152
+ return { promise, settle }
153
+ }
package/src/version.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Version parsing/comparison and the exact-version parity rule, covering the shapes DSH and Node publish (`0.2.2-rc.1`, `24.22.2`, optional `v`).
3
+ */
4
+
5
+ const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/
6
+
7
+ export function parseVersion(input) {
8
+ if (typeof input !== 'string') return null
9
+ const match = VERSION_RE.exec(input.trim())
10
+ if (!match) return null
11
+ const [, major, minor, patch, prerelease, build] = match
12
+ return {
13
+ raw: input.trim(),
14
+ major: Number(major),
15
+ minor: Number(minor),
16
+ patch: Number(patch),
17
+ prerelease: prerelease ? prerelease.split('.').map((part) => (/^\d+$/.test(part) ? Number(part) : part)) : [],
18
+ build: build ?? null,
19
+ }
20
+ }
21
+
22
+ export function normalizeVersion(input) {
23
+ const parsed = parseVersion(input)
24
+ if (!parsed) return String(input ?? '').trim()
25
+ const core = `${parsed.major}.${parsed.minor}.${parsed.patch}`
26
+ return parsed.prerelease.length > 0 ? `${core}-${parsed.prerelease.join('.')}` : core
27
+ }
28
+
29
+ function compareIdentifiers(a, b) {
30
+ const aNum = typeof a === 'number'
31
+ const bNum = typeof b === 'number'
32
+ if (aNum && bNum) return a === b ? 0 : a < b ? -1 : 1
33
+ if (aNum) return -1 // numeric identifiers sort before alphanumeric ones
34
+ if (bNum) return 1
35
+ return a === b ? 0 : String(a) < String(b) ? -1 : 1
36
+ }
37
+
38
+ export function compareVersions(a, b) {
39
+ const pa = parseVersion(a)
40
+ const pb = parseVersion(b)
41
+ if (!pa || !pb) {
42
+ const sa = String(a ?? '')
43
+ const sb = String(b ?? '')
44
+ return sa === sb ? 0 : sa < sb ? -1 : 1
45
+ }
46
+ for (const key of ['major', 'minor', 'patch']) {
47
+ if (pa[key] !== pb[key]) return pa[key] < pb[key] ? -1 : 1
48
+ }
49
+ if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0
50
+ if (pa.prerelease.length === 0) return 1
51
+ if (pb.prerelease.length === 0) return -1
52
+ const length = Math.max(pa.prerelease.length, pb.prerelease.length)
53
+ for (let i = 0; i < length; i += 1) {
54
+ const left = pa.prerelease[i]
55
+ const right = pb.prerelease[i]
56
+ if (left === undefined) return -1
57
+ if (right === undefined) return 1
58
+ const result = compareIdentifiers(left, right)
59
+ if (result !== 0) return result
60
+ }
61
+ return 0
62
+ }
63
+
64
+ export function versionsEqual(a, b) {
65
+ return compareVersions(normalizeVersion(a), normalizeVersion(b)) === 0
66
+ }
67
+
68
+ export function versionParity(localVersion, remoteVersion) {
69
+ if (!localVersion || !remoteVersion) {
70
+ return {
71
+ status: /** @type {'unknown'} */ ('unknown'),
72
+ local: localVersion ?? null,
73
+ remote: remoteVersion ?? null,
74
+ same: false,
75
+ message: {
76
+ zh: '无法确定版本一致性(缺少本机或远端版本)。',
77
+ en: 'Version parity is unknown (a local or remote version is missing).',
78
+ },
79
+ }
80
+ }
81
+ const same = versionsEqual(localVersion, remoteVersion)
82
+ return {
83
+ status: /** @type {'same' | 'different'} */ (same ? 'same' : 'different'),
84
+ local: normalizeVersion(localVersion),
85
+ remote: normalizeVersion(remoteVersion),
86
+ same,
87
+ message: same
88
+ ? { zh: '远端与本机 DSH 版本一致。', en: 'The remote DSH version matches this machine.' }
89
+ : {
90
+ zh: `远端 DSH(${normalizeVersion(remoteVersion)})与本机(${normalizeVersion(localVersion)})不一致。`,
91
+ en: `Remote DSH (${normalizeVersion(remoteVersion)}) differs from this machine (${normalizeVersion(localVersion)}).`,
92
+ },
93
+ }
94
+ }
95
+
96
+ export const MIN_NODE_VERSION = '24.9.0'
97
+
98
+ export function isNodeVersionSupported(version) {
99
+ if (!version) return false
100
+ // node -v prints "v24.22.2"; a bare "24" from a fallback should not pass.
101
+ if (!parseVersion(version)) return false
102
+ return compareVersions(normalizeVersion(version), MIN_NODE_VERSION) >= 0
103
+ }
package/src/webapp.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Remote DSH web lifecycle — the surface callers import: `remote-web.js` owns start/stop/adopt, `remote-proc.js` the scan and reachability primitives.
3
+ */
4
+ export {
5
+ LAUNCH_MARKER,
6
+ BROWSER_CARRIER_PATCH_FILE,
7
+ parseWebLine,
8
+ buildStartCommand,
9
+ buildBrowserCarrierProbe,
10
+ ensureBrowserCarrier,
11
+ buildStartScript,
12
+ parseLaunchedPid,
13
+ startRemoteWeb,
14
+ stopRemoteWeb,
15
+ clearRunRegistry,
16
+ parseRunRegistry,
17
+ readRunRegistry,
18
+ readWebLineFromLog,
19
+ remotePidAlive,
20
+ adoptRemoteWeb,
21
+ buildRunRegistryRecord,
22
+ writeRunRegistry,
23
+ commandMatchesProfile,
24
+ versionFromCommand,
25
+ dshPackageDirFromCommand,
26
+ remoteDshVersion,
27
+ resolveRemoteWeb,
28
+ } from './remote-web.js'
29
+
30
+ export {
31
+ buildForeignDshCommand,
32
+ parseForeignDshOutput,
33
+ findForeignDshProcesses,
34
+ stopForeignDshProcesses,
35
+ parseListenPorts,
36
+ remoteListenPorts,
37
+ remotePortOwnerPid,
38
+ parseProcessIdentity,
39
+ remoteProcessIdentity,
40
+ remoteHttpStatus,
41
+ waitForRemoteUi,
42
+ exchangeTokenOverTunnel,
43
+ } from './remote-proc.js'
@@ -0,0 +1,36 @@
1
+ # Third-party notices
2
+
3
+ The published plugin has no runtime dependencies; the only third-party code it ships is
4
+ vendored below. This file is generated by `scripts/build-vendor.mjs`; do not edit by hand.
5
+
6
+ ## ssh2
7
+
8
+ - Package: `ssh2` (MIT)
9
+ - Source: https://github.com/mscdex/ssh2
10
+ - Bundled file: `vendor/ssh2.bundle.cjs` (329 KiB, minified)
11
+
12
+ License text from `node_modules/ssh2/LICENSE`:
13
+
14
+ ```text
15
+ Copyright Brian White. All rights reserved.
16
+
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy
18
+ of this software and associated documentation files (the "Software"), to
19
+ deal in the Software without restriction, including without limitation the
20
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
21
+ sell copies of the Software, and to permit persons to whom the Software is
22
+ furnished to do so, subject to the following conditions:
23
+
24
+ The above copyright notice and this permission notice shall be included in
25
+ all copies or substantial portions of the Software.
26
+
27
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
32
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
33
+ IN THE SOFTWARE.
34
+ ```
35
+
36
+ The bundle excludes the optional native accelerator `cpu-features`; ssh2 uses its pure-JavaScript fallback then.