dsh-ris-ide 1.8.1 → 1.8.3

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 (50) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +569 -98
  3. package/lib/debug/vendor/README.md +14 -0
  4. package/lib/debug/vendor/jdwp/client.js +9 -4
  5. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  6. package/lib/index.js +963 -64
  7. package/lib/redirector.js +76 -4
  8. package/lib/risd/lifecycle.js +54 -10
  9. package/lib/risd/ping.js +136 -17
  10. package/lib/risd/server.js +424 -22
  11. package/lib/risd/ui.js +218 -129
  12. package/lib/risd-client.js +4 -1
  13. package/lib/startup.js +27 -7
  14. package/package.json +2 -2
  15. package/test/client-viewer.test.mjs +268 -93
  16. package/test/clipboard.test.mjs +259 -0
  17. package/test/debug-engine.test.mjs +3 -1
  18. package/test/dsh-origin.test.mjs +4 -11
  19. package/test/dsh-window-refresh.test.mjs +166 -1
  20. package/test/harness.test.mjs +1 -1
  21. package/test/helpers/cmd.mjs +29 -0
  22. package/test/helpers/tgz.mjs +71 -0
  23. package/test/host-search.test.mjs +18 -11
  24. package/test/host-tail.test.mjs +190 -25
  25. package/test/proxy-route.test.mjs +61 -0
  26. package/test/proxy-window.test.mjs +5 -0
  27. package/test/proxy.test.mjs +40 -11
  28. package/test/proxybridge-bundle.test.mjs +1 -59
  29. package/test/redirector-bundle.test.mjs +21 -67
  30. package/test/redirector.test.mjs +71 -4
  31. package/test/risd-api.test.mjs +83 -29
  32. package/test/risd-bridge-degrade.test.mjs +3 -29
  33. package/test/risd-cli-home.test.mjs +41 -4
  34. package/test/risd-engine.test.mjs +13 -50
  35. package/test/risd-entry.test.mjs +0 -37
  36. package/test/risd-follow-start.test.mjs +102 -0
  37. package/test/risd-git.test.mjs +7 -5
  38. package/test/risd-handoff.test.mjs +6 -50
  39. package/test/risd-helpers.mjs +150 -3
  40. package/test/risd-host-p2.test.mjs +2 -30
  41. package/test/risd-lifecycle.test.mjs +203 -33
  42. package/test/risd-ping.test.mjs +77 -1
  43. package/test/risd-programs.test.mjs +4 -34
  44. package/test/risd-review-p2.test.mjs +0 -13
  45. package/test/risd-shutdown.test.mjs +5 -38
  46. package/test/risd-teardown.test.mjs +8 -27
  47. package/test/risd-ui.test.mjs +205 -14
  48. package/test/risd-write.test.mjs +2 -1
  49. package/test/startup-reconcile.test.mjs +44 -8
  50. package/test/proxy-restart.test.mjs +0 -39
package/lib/redirector.js CHANGED
@@ -58,6 +58,17 @@ export const REDIRECTOR_PID_FILENAMES = Object.freeze({
58
58
  export const REDIRECTOR_LOG_FILENAME = 'proxybridge.log'
59
59
  /** Substring of the redirector's command line, used to verify a pid is ours. */
60
60
  export const REDIRECTOR_MARKER = 'ProxyBridge'
61
+
62
+ /**
63
+ * Test seam for `windowsPathOf` (not a product feature).
64
+ *
65
+ * A host that is not WSL has no `wslpath` and no Windows side, so the Windows
66
+ * spelling of a Linux path cannot be computed there at all — and the tests that
67
+ * assert the shape of that spelling could only ever run on a WSL machine. The
68
+ * seam lets them inject the mapping instead, so CI (plain Linux) keeps the
69
+ * coverage; production leaves it `null` and always asks `wslpath`.
70
+ */
71
+ let windowsPathTranslator = null
61
72
  /** Profile rules are per-connection decisions, so TCP+UDP is the useful default. */
62
73
  const PROFILE_VERSION = '1.0'
63
74
 
@@ -1346,8 +1357,7 @@ export async function startRedirector(options = {}) {
1346
1357
  return { started: true, pid: child.pid, side, command: plan.display }
1347
1358
  }
1348
1359
  // Passwordless sudo only: asking for a password from a web route would hang.
1349
- const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true })
1350
- if (probe.status === 0) {
1360
+ if (sudoPasswordless(options) === true) {
1351
1361
  const child = spawn('sudo', ['-n', found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1352
1362
  child.unref()
1353
1363
  // `sudo` is a supervisor, not the CLI: recording its pid made a later stop kill
@@ -2072,7 +2082,7 @@ export async function killWindowsCliProcesses(options = {}) {
2072
2082
  * On Windows the launch itself elevates (UAC), so the command is the exe; on Linux
2073
2083
  * the whole thing is a `sudo`. In WSL the Windows command must be translated: a
2074
2084
  * `/mnt/...` path does not exist in the Windows namespace.
2075
- * @param {{cliPath: string, profilePath: string, verbose?: number, platform?: string}} options - inputs.
2085
+ * @param {{cliPath: string, profilePath: string, verbose?: number, platform?: string, translate?: boolean}} options - inputs. `translate` overrides "may this machine spell paths the Windows way" (defaults to `platform === 'win32' && engineSide() === 'wsl'`); tests on a plain-Linux host pass `true`.
2076
2086
  * @returns {{command: string, args: string[], display: string, needsElevation: boolean}} runnable plan.
2077
2087
  */
2078
2088
  export function redirectorCommand(options = {}) {
@@ -2082,7 +2092,9 @@ export function redirectorCommand(options = {}) {
2082
2092
  // one look the same — the exact ambiguity that cost us an hour of guessing.
2083
2093
  const verbose = Number.isInteger(options.verbose) ? options.verbose : 2
2084
2094
  const args = ['--profile', String(options.profilePath ?? ''), '--verbose', String(verbose)]
2085
- const translate = platform === 'win32' && engineSide() === 'wsl'
2095
+ const translate = typeof options.translate === 'boolean'
2096
+ ? options.translate
2097
+ : platform === 'win32' && engineSide() === 'wsl'
2086
2098
  const exe = translate ? windowsPathOf(String(options.cliPath ?? '')) : String(options.cliPath ?? '')
2087
2099
  const shownArgs = translate ? windowsArgsOf(args) : args
2088
2100
  const quote = (value) => (/[ \t]/.test(value) === true ? `"${value}"` : value)
@@ -2267,6 +2279,37 @@ export function hasElevation() {
2267
2279
  return typeof process.getuid === 'function' && process.getuid() === 0
2268
2280
  }
2269
2281
 
2282
+ /**
2283
+ * Does this box let us run `sudo -n` without a password?
2284
+ *
2285
+ * The answer is cached for a few minutes: sudo writes an audit line to the journal
2286
+ * on every call — success *and* failure — and the reconciler retries a background
2287
+ * start every minute, so a box without passwordless sudo used to fill its journal
2288
+ * with one "a password is required" line per minute (m03761). A user-initiated
2289
+ * start (`interactive`) always asks fresh: the user may have just added NOPASSWD,
2290
+ * and it is the one attempt where waiting for the answer is expected.
2291
+ *
2292
+ * The probe runs in the user's home directory on purpose: dsh inherits the cwd it
2293
+ * was launched from, and on WSL that is often `/mnt/c/WINDOWS/system32`, which then
2294
+ * shows up as `PWD=` in the sudo audit line (and in any relative path the probe
2295
+ * touches). Nothing about the probe depends on the caller's cwd.
2296
+ *
2297
+ * @param {{interactive?: boolean}} [options] - `interactive` bypasses the cache.
2298
+ * @returns {boolean} true when sudo needs no password.
2299
+ */
2300
+ const SUDO_PROBE_TTL_MS = 5 * 60 * 1000
2301
+ let sudoProbeCache = null
2302
+ export function sudoPasswordless(options = {}) {
2303
+ const now = Date.now()
2304
+ if (options.interactive !== true && sudoProbeCache !== null && now - sudoProbeCache.at < SUDO_PROBE_TTL_MS) {
2305
+ return sudoProbeCache.ok
2306
+ }
2307
+ const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true, cwd: homedir() })
2308
+ const ok = probe.status === 0
2309
+ sudoProbeCache = { ok, at: now }
2310
+ return ok
2311
+ }
2312
+
2270
2313
  /**
2271
2314
  * Live Windows CLI pids, cached for a few seconds.
2272
2315
  *
@@ -2653,6 +2696,7 @@ export function clearRedirectorPid(side) {
2653
2696
  * @returns {{pid: number, source: string, side: string, local: {pid: number, source: string}, windows: {pid: number, source: string}}} discovery result; `pid` is the first live hit.
2654
2697
  */
2655
2698
  export function detectRunningRedirector() {
2699
+ if (probesStubbed()) return emptyDetection()
2656
2700
  migrateLegacyPidFile()
2657
2701
  const local = detectSide('local')
2658
2702
  const windows = detectSide('windows')
@@ -2666,6 +2710,26 @@ export function detectRunningRedirector() {
2666
2710
  }
2667
2711
  }
2668
2712
 
2713
+ /**
2714
+ * Is the machine-probing test stub switched on?
2715
+ *
2716
+ * `__test.setProbeHooks` only reaches this process, but the risd tests run the
2717
+ * daemon as a CHILD process, and its save path calls `redirectorStatusCached()`
2718
+ * after every write. Two cold PowerShell probes cost ~8 s on WSL, so each save in
2719
+ * those files waited for an answer that the test must not depend on (whether the
2720
+ * developer's own ProxyBridge happens to be running) — and adoption could even
2721
+ * stomp the real pidfiles. The child inherits `DSH_RIS_IDE_STUB_PROBES=1` from
2722
+ * `test/risd-helpers.mjs`; production never sets it.
2723
+ */
2724
+ function probesStubbed() {
2725
+ return process.env.DSH_RIS_IDE_STUB_PROBES === '1'
2726
+ }
2727
+
2728
+ /** The "nothing is running" shape both stubbed detectors return. */
2729
+ function emptyDetection() {
2730
+ return { pid: 0, source: '', side: '', local: { pid: 0, source: '' }, windows: { pid: 0, source: '' } }
2731
+ }
2732
+
2669
2733
  /** @returns {object|null} discovery hit for one side. */
2670
2734
  function detectSide(side) {
2671
2735
  const record = redirectorPidRecord(side)
@@ -2690,6 +2754,7 @@ function detectSide(side) {
2690
2754
 
2691
2755
  /** Async variant of {@link detectRunningRedirector}: safe to call from HTTP routes. */
2692
2756
  export async function detectRunningRedirectorAsync() {
2757
+ if (probesStubbed()) return emptyDetection()
2693
2758
  migrateLegacyPidFile()
2694
2759
  const record = redirectorPidRecord('local')
2695
2760
  const local = record.pid > 0 && await pidAliveOnAsync(record.pid, 'local')
@@ -3490,6 +3555,10 @@ export function windowsPathOf(path, options = {}) {
3490
3555
  // answer with a \\wsl.localhost\… share that Windows cannot open).
3491
3556
  const mounted = /^\/mnt\/([A-Za-z])\/(.*)$/.exec(text)
3492
3557
  if (mounted !== null) return `${mounted[1].toUpperCase()}:\\${mounted[2].replace(/\//g, '\\')}`
3558
+ if (windowsPathTranslator !== null) {
3559
+ const injected = windowsPathTranslator(text)
3560
+ if (typeof injected === 'string' && injected !== '') return injected
3561
+ }
3493
3562
  const converted = spawnSyncText('wslpath', ['-w', text], 4000).trim()
3494
3563
  if (converted !== '' && /^[A-Za-z]:[\\/]|^\\\\/.test(converted)) return converted
3495
3564
  if (options.mustConvert === true) {
@@ -3527,6 +3596,9 @@ function spawnSyncText(command, args, timeoutMs) {
3527
3596
 
3528
3597
  export const __test = {
3529
3598
  PROFILE_VERSION,
3599
+ sudoPasswordless,
3600
+ resetSudoProbe: () => { sudoProbeCache = null },
3601
+ setWindowsPathTranslator: (fn) => { windowsPathTranslator = typeof fn === 'function' ? fn : null },
3530
3602
  bundledBundleDir,
3531
3603
  bundleCacheInstalled,
3532
3604
  ensureBundleReady,
@@ -7,6 +7,23 @@
7
7
  // proxy follows dsh (its lease keeps the tunnel alive) and programs/debug keep
8
8
  // running when the last dsh window closes, because the maintenance page can be the
9
9
  // only UI on the machine.
10
+ //
11
+ // Following dsh is two-sided (m03397): `startWithDsh` runs the resource when a dsh
12
+ // attaches, `stopWithDsh` releases it when the last one leaves. The two halves are
13
+ // separate switches because they answer different questions ("start my programs
14
+ // when I open the IDE" vs "do not kill them when I close it"). What each start half
15
+ // can mean is a property of the resource, so the page greys out what cannot exist:
16
+ // - daemon: the start half is FORCED. dsh asks for the daemon on demand; letting it
17
+ // be switched off would leave a plugin with no supervisor to talk to.
18
+ // - proxy: both halves are real (a lease starts the engine, teardown stops it).
19
+ // - programs: the start half restores the programs that were still running when
20
+ // this daemon last exited (`risd-programs-last.json`), because a program is
21
+ // started per workspace and only the daemon knows what was live.
22
+ // - debug: there is nothing to auto-start (a JDWP session belongs to a page), so
23
+ // only the stop half exists.
24
+ //
25
+ // The start half is never an elevation request — an automatic start must not pop a
26
+ // password dialog (m13910) — so a bridge that needs root is only reported on the page.
10
27
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
11
28
  import { join } from 'node:path'
12
29
 
@@ -16,17 +33,22 @@ export const LIFECYCLE_FILENAME = 'risd-lifecycle.json'
16
33
  /** The four resources the page lets you tune, in page order. */
17
34
  export const LIFECYCLE_RESOURCES = ['daemon', 'proxy', 'programs', 'debug']
18
35
 
19
- /** Defaults: only `followDsh` exists; following the daemon is always on. */
36
+ /** Defaults: everything follows dsh except programs/debug, which outlive the window. */
20
37
  export const LIFECYCLE_DEFAULTS = {
21
- daemon: { followDsh: true },
22
- proxy: { followDsh: true },
23
- programs: { followDsh: false },
24
- debug: { followDsh: false },
38
+ daemon: { startWithDsh: true, stopWithDsh: true },
39
+ proxy: { startWithDsh: true, stopWithDsh: true },
40
+ programs: { startWithDsh: false, stopWithDsh: false },
41
+ debug: { stopWithDsh: false },
25
42
  }
26
43
 
27
44
  /** Keys that used to be configurable and are now forced (m07741). */
28
45
  const FORCED_KEYS = ['followDaemon']
29
46
 
47
+ /** Resources whose start half is forced on (see the module comment). */
48
+ const FORCED_START = ['daemon']
49
+
50
+ const FORCED_DAEMON_START = 'daemon.startWithDsh 不可配置:dsh 需要时按需拉起守护进程(强制)'
51
+
30
52
  /** @param home - daemon home directory. */
31
53
  export function lifecyclePath(home) {
32
54
  return join(home, LIFECYCLE_FILENAME)
@@ -60,23 +82,45 @@ export function normalizeLifecycle(input) {
60
82
  value[resource] = Object.assign({}, defaults)
61
83
  continue
62
84
  }
85
+ const allowed = Object.keys(defaults)
86
+ // The pre-m03397 file (and any older API caller) has ONE switch per resource:
87
+ // `followDsh` governed both halves, so it migrates to both. An explicit half in
88
+ // the same payload wins — that is how a caller moves one half at a time.
89
+ let legacyFollow
90
+ if (given.followDsh !== undefined) {
91
+ legacyFollow = bool(given.followDsh)
92
+ if (legacyFollow === undefined) errors.push(`${resource}.followDsh 必须是 true/false`)
93
+ }
63
94
  for (const key of Object.keys(given)) {
64
- if (key === 'followDsh' || FORCED_KEYS.includes(key)) continue
95
+ if (key === 'followDsh' || allowed.includes(key) || FORCED_KEYS.includes(key)) continue
65
96
  // Silently ignoring an unknown key made a typo look saved (review A2-P2-5).
66
- errors.push(`${resource}.${key} 不是可配置项(只能配置 followDsh)`)
97
+ errors.push(`${resource}.${key} 不是可配置项(只能配置 ${allowed.join('/')})`)
67
98
  }
68
99
  for (const key of FORCED_KEYS) {
69
100
  if (given[key] !== undefined) {
70
- errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 followDsh)`)
101
+ errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 ${allowed.join('/')})`)
71
102
  }
72
103
  }
73
104
  const merged = Object.assign({}, defaults)
74
- for (const key of Object.keys(defaults)) {
75
- const parsed = bool(given[key])
105
+ for (const key of allowed) {
76
106
  if (given[key] === undefined) continue
107
+ const parsed = bool(given[key])
77
108
  if (parsed === undefined) { errors.push(`${resource}.${key} 必须是 true/false`); continue }
109
+ // The daemon's start half is forced on: a plugin that cannot ask for a daemon
110
+ // has no supervisor at all (see the module comment).
111
+ if (FORCED_START.includes(resource) && key === 'startWithDsh' && parsed !== true) {
112
+ errors.push(FORCED_DAEMON_START)
113
+ continue
114
+ }
78
115
  merged[key] = parsed
79
116
  }
117
+ if (legacyFollow !== undefined) {
118
+ for (const key of allowed) {
119
+ if (given[key] !== undefined) continue
120
+ if (FORCED_START.includes(resource) && key === 'startWithDsh') continue
121
+ merged[key] = legacyFollow
122
+ }
123
+ }
80
124
  value[resource] = merged
81
125
  }
82
126
  return { value, errors, changed: errors.length === 0 }
package/lib/risd/ping.js CHANGED
@@ -8,6 +8,15 @@
8
8
  * too), while requiring a `05 00` answer also tells the user their SOCKS server is
9
9
  * up and does not need authentication.
10
10
  *
11
+ * m03429: a SOCKS5 greeting is still only half the story — a server can answer
12
+ * `05 00` and then refuse (or hang on) every CONNECT, which is exactly the failure
13
+ * a tunnel user hits. When a destination is known (`target`, derived from the rule
14
+ * table/shadows on the proxy tab) the probe finishes the handshake with a real
15
+ * CONNECT and reports `usable`: `true` = the far side forwarded a connection,
16
+ * `false` = handshake fine but forwarding failed (the error says why), `null` =
17
+ * nothing to verify against (greeting only). The K8s/CI runner has no upstream, so
18
+ * this stays a single short-lived socket with no retries.
19
+ *
11
20
  * Deliberately dependency-free and side-effect-free (one short-lived socket, no
12
21
  * retries): the page polls it every few seconds.
13
22
  *
@@ -15,20 +24,90 @@
15
24
  */
16
25
  import { createConnection } from 'node:net'
17
26
 
27
+ import { parseHostSpec, parsePortSpec } from '../proxy.js'
28
+
18
29
  const GREETING = Buffer.from([0x05, 0x01, 0x00])
19
30
 
31
+ /** SOCKS5 reply codes → the phrase the chip's tooltip shows. */
32
+ const REPLY_TEXT = {
33
+ 1: '通用失败',
34
+ 2: '规则不允许该连接',
35
+ 3: '网络不可达',
36
+ 4: '主机不可达',
37
+ 5: '连接被拒绝',
38
+ 6: 'TTL 过期',
39
+ 7: '不支持该命令',
40
+ 8: '不支持该地址类型',
41
+ }
42
+
43
+ /**
44
+ * Pick a destination that proves the tunnel really forwards.
45
+ *
46
+ * The proxy tab can only verify "SOCKS is usable" against a real destination, and
47
+ * the only destinations it knows are the ones the user configured: the loopback
48
+ * mapping shadows (already concrete) or the first rule that names a literal host and
49
+ * port. A wildcard cannot be probed (which port would that be?), so such rows are
50
+ * skipped instead of guessed — a guessed port would report a healthy tunnel as broken.
51
+ *
52
+ * @param config - normalized proxy config (`lib/proxy.js#normalizeConfig`).
53
+ * @returns `{host: string, port: number}` or null when nothing is concrete enough.
54
+ */
55
+ export function probeTarget(config) {
56
+ const shadows = Array.isArray(config?.shadows) ? config.shadows : []
57
+ for (const entry of shadows) {
58
+ const host = typeof entry?.host === 'string' ? entry.host.trim() : ''
59
+ const port = Number(entry?.port)
60
+ if (host !== '' && Number.isInteger(port) && port > 0 && port < 65536) return { host, port }
61
+ }
62
+ const rules = Array.isArray(config?.rules) ? config.rules : []
63
+ for (const rule of rules) {
64
+ if (rule?.enabled !== true) continue
65
+ const hosts = parseHostSpec(rule.hosts).patterns.filter((pattern) => !pattern.includes('*'))
66
+ const ports = parsePortSpec(rule.ports).ports.filter((port) => Number.isInteger(port) && port > 0)
67
+ if (hosts.length === 0 || ports.length === 0) continue
68
+ return { host: hosts[0], port: ports[0] }
69
+ }
70
+ return null
71
+ }
72
+
73
+ /** The target shape the probe accepts, or null when it cannot be dialled. */
74
+ function normalizeTarget(target) {
75
+ if (target === null || typeof target !== 'object') return null
76
+ const host = typeof target.host === 'string' ? target.host.trim() : ''
77
+ const port = Number(target.port)
78
+ if (host === '' || !Number.isInteger(port) || port <= 0 || port > 65535) return null
79
+ return { host, port }
80
+ }
81
+
82
+ /** SOCKS5 CONNECT request for a host:port (`socks5h` semantics: name, not IP). */
83
+ function connectRequest(target) {
84
+ const ipv4 = /^\d{1,3}(\.\d{1,3}){3}$/.test(target.host)
85
+ if (ipv4) {
86
+ const parts = target.host.split('.').map(Number)
87
+ return Buffer.from([0x05, 0x01, 0x00, 0x01, ...parts, Math.floor(target.port / 256), target.port % 256])
88
+ }
89
+ const name = Buffer.from(target.host, 'utf8')
90
+ if (name.length > 255) return null
91
+ return Buffer.from([0x05, 0x01, 0x00, 0x03, name.length, ...name, Math.floor(target.port / 256), target.port % 256])
92
+ }
93
+
20
94
  /**
21
95
  * Probe a SOCKS5 endpoint.
22
- * @param {{host: string, port: number, timeoutMs?: number, connect?: Function}} options
23
- * `host`/`port` of the SOCKS server; `connect` is injectable for tests.
24
- * @returns {Promise<{ok: boolean, socks: boolean, ms: number, at: string, host: string, port: number, error?: string}>}
96
+ * @param {{host: string, port: number, timeoutMs?: number, connect?: Function, target?: {host: string, port: number}}} options
97
+ * `host`/`port` of the SOCKS server; `target` is the destination the CONNECT step
98
+ * is proven against (omit it to only verify the greeting); `connect` is injectable
99
+ * for tests.
100
+ * @returns {Promise<{ok: boolean, socks: boolean, usable: boolean|null, ms: number, at: string, host: string, port: number, target: {host: string, port: number}|null, error?: string}>}
101
+ * `ok` is the chip's "healthy" verdict, so a greeting that cannot forward to the
102
+ * configured destination is NOT ok — that is the whole point of m03429.
25
103
  */
26
104
  export function pingSocks(options = {}) {
27
105
  const host = typeof options.host === 'string' ? options.host.trim() : ''
28
106
  const port = Number(options.port)
29
107
  const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(200, Number(options.timeoutMs)) : 2000
108
+ const target = normalizeTarget(options.target)
30
109
  const at = new Date().toISOString()
31
- const base = { host, port, at, ms: 0, socks: false }
110
+ const base = { host, port, at, ms: 0, socks: false, usable: null, target }
32
111
  if (host === '' || !Number.isInteger(port) || port <= 0 || port > 65535) {
33
112
  return Promise.resolve({ ...base, ok: false, error: host === '' ? '未配置代理服务器地址' : '端口无效' })
34
113
  }
@@ -38,6 +117,8 @@ export function pingSocks(options = {}) {
38
117
  let settled = false
39
118
  let socket = null
40
119
  let timer = null
120
+ let phase = 'greeting'
121
+ let buffer = Buffer.alloc(0)
41
122
  const finish = (result) => {
42
123
  if (settled) return
43
124
  settled = true
@@ -45,11 +126,23 @@ export function pingSocks(options = {}) {
45
126
  try { socket?.destroy() } catch { /* already gone */ }
46
127
  resolve({ ...base, ms: Date.now() - started, ...result })
47
128
  }
48
- timer = setTimeout(() => finish({ ok: false, error: `连接超时(${timeoutMs} ms)` }), timeoutMs)
129
+ const forwardingError = (reason) => ({
130
+ ok: false,
131
+ socks: true,
132
+ usable: false,
133
+ error: `SOCKS5 握手正常,但无法转发到 ${target.host}:${target.port}(${reason})`,
134
+ })
135
+ timer = setTimeout(() => {
136
+ finish(phase === 'connect'
137
+ ? forwardingError('转发超时')
138
+ : { ok: false, error: `连接超时(${timeoutMs} ms)` })
139
+ }, timeoutMs)
49
140
  timer.unref?.()
50
141
  try {
51
142
  socket = connect({ host, port })
52
- socket.setTimeout?.(timeoutMs, () => finish({ ok: false, error: `连接超时(${timeoutMs} ms)` }))
143
+ socket.setTimeout?.(timeoutMs, () => finish(phase === 'connect'
144
+ ? forwardingError('转发超时')
145
+ : { ok: false, error: `连接超时(${timeoutMs} ms)` }))
53
146
  socket.once('error', (error) => {
54
147
  finish({ ok: false, error: describeError(error) })
55
148
  })
@@ -59,25 +152,51 @@ export function pingSocks(options = {}) {
59
152
  // A peer may accept the connection and close it without ever answering the
60
153
  // greeting. Waiting for the timeout would report a healthy-but-silent SOCKS
61
154
  // server as 「连接超时」 2 s later; report the FIN immediately instead.
62
- socket.once('end', () => finish({ ok: false, socks: false, error: '连接被关闭(代理未返回 SOCKS5 握手响应)' }))
63
- socket.once('close', () => finish({ ok: false, socks: false, error: '连接被关闭(代理未返回 SOCKS5 握手响应)' }))
64
- let buffer = Buffer.alloc(0)
155
+ const closedEarly = () => finish(phase === 'connect'
156
+ ? { ok: false, socks: true, usable: false, error: '连接被关闭(代理未返回 CONNECT 响应)' }
157
+ : { ok: false, socks: false, error: '连接被关闭(代理未返回 SOCKS5 握手响应)' })
158
+ socket.once('end', closedEarly)
159
+ socket.once('close', closedEarly)
65
160
  socket.on('data', (chunk) => {
66
161
  buffer = Buffer.concat([buffer, chunk])
67
- if (buffer.length < 2) return
68
- clearTimeout(timer)
69
- if (buffer[0] !== 0x05) {
70
- finish({ ok: false, socks: false, error: '端口有服务但不是 SOCKS5(握手版本不符)' })
162
+ if (phase === 'greeting') {
163
+ if (buffer.length < 2) return
164
+ if (buffer[0] !== 0x05) {
165
+ finish({ ok: false, socks: false, error: '端口有服务但不是 SOCKS5(握手版本不符)' })
166
+ return
167
+ }
168
+ if (buffer[1] !== 0x00) {
169
+ finish({ ok: false, socks: true, error: 'SOCKS5 要求认证(仅支持无认证代理)' })
170
+ return
171
+ }
172
+ // Greeting accepted. Without a concrete destination the handshake is all
173
+ // the evidence there is; say so instead of inventing a verdict.
174
+ if (target === null) {
175
+ finish({ ok: true, socks: true, usable: null })
176
+ return
177
+ }
178
+ const request = connectRequest(target)
179
+ if (request === null) {
180
+ finish({ ok: true, socks: true, usable: null })
181
+ return
182
+ }
183
+ phase = 'connect'
184
+ buffer = Buffer.alloc(0)
185
+ try { socket.write(request) } catch (error) {
186
+ finish(forwardingError(describeError(error)))
187
+ }
71
188
  return
72
189
  }
73
- if (buffer[1] !== 0x00) {
74
- finish({ ok: false, socks: true, error: 'SOCKS5 要求认证(仅支持无认证代理)' })
190
+ // CONNECT verdict: 05 | REP | 00 | ATYP | BND.ADDR | BND.PORT
191
+ if (buffer.length < 2) return
192
+ const rep = buffer[1]
193
+ if (rep !== 0x00) {
194
+ finish(forwardingError(REPLY_TEXT[rep] ?? `错误码 ${rep}`))
75
195
  return
76
196
  }
77
- finish({ ok: true, socks: true })
197
+ finish({ ok: true, socks: true, usable: true })
78
198
  })
79
199
  } catch (error) {
80
- clearTimeout(timer)
81
200
  finish({ ok: false, error: describeError(error) })
82
201
  }
83
202
  })