dsh-ris-ide 1.7.2 → 1.8.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 +43 -4
- package/bin/check-listing.mjs +247 -0
- package/bin/proxy-janitor.mjs +183 -0
- package/bin/risd.mjs +287 -0
- package/bin/run-with-log.ps1 +43 -5
- package/lib/client-codemirror.js +92 -66
- package/lib/client.js +774 -89
- package/lib/index.js +2256 -21
- package/lib/janitor.js +377 -0
- package/lib/proxy.js +1577 -0
- package/lib/proxybridge-bundle.js +798 -0
- package/lib/redirector.js +2558 -0
- package/lib/risd/build.js +91 -0
- package/lib/risd/debug.js +374 -0
- package/lib/risd/git.js +207 -0
- package/lib/risd/leases.js +124 -0
- package/lib/risd/lifecycle.js +148 -0
- package/lib/risd/log.js +59 -0
- package/lib/risd/ping.js +94 -0
- package/lib/risd/programs.js +348 -0
- package/lib/risd/server.js +1478 -0
- package/lib/risd/state.js +137 -0
- package/lib/risd/ui.js +1705 -0
- package/lib/risd/view.js +79 -0
- package/lib/risd-client.js +282 -0
- package/lib/standalone/window.html +14 -16
- package/lib/startup.js +114 -0
- package/package.json +7 -2
- package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
- package/test/client-build.test.mjs +113 -0
- package/test/client-viewer.test.mjs +314 -20
- package/test/companion.test.mjs +65 -0
- package/test/dsh-origin.test.mjs +140 -0
- package/test/dsh-window-refresh.test.mjs +100 -0
- package/test/harness.test.mjs +9 -0
- package/test/host-noloop.test.mjs +74 -0
- package/test/host-tail.test.mjs +54 -5
- package/test/host-window.test.mjs +4 -4
- package/test/inherit-engine.test.mjs +175 -0
- package/test/install-phase.test.mjs +36 -0
- package/test/janitor.test.mjs +172 -0
- package/test/lifecycle.test.mjs +109 -0
- package/test/merge-owners.test.mjs +155 -0
- package/test/proxy-restart.test.mjs +37 -0
- package/test/proxy-route.test.mjs +599 -0
- package/test/proxy-window.test.mjs +45 -0
- package/test/proxy.test.mjs +914 -0
- package/test/proxybridge-bundle.test.mjs +687 -0
- package/test/redirector-bundle.test.mjs +391 -0
- package/test/redirector.test.mjs +571 -0
- package/test/risd-api.test.mjs +470 -0
- package/test/risd-bridge-degrade.test.mjs +101 -0
- package/test/risd-build.test.mjs +20 -0
- package/test/risd-cli-home.test.mjs +50 -0
- package/test/risd-client.test.mjs +130 -0
- package/test/risd-debug.test.mjs +261 -0
- package/test/risd-election.test.mjs +104 -0
- package/test/risd-engine.test.mjs +132 -0
- package/test/risd-entry.test.mjs +118 -0
- package/test/risd-git.test.mjs +109 -0
- package/test/risd-handoff.test.mjs +116 -0
- package/test/risd-heal.test.mjs +50 -0
- package/test/risd-helpers.mjs +108 -0
- package/test/risd-host-p2.test.mjs +147 -0
- package/test/risd-janitor-guard.test.mjs +46 -0
- package/test/risd-lease.test.mjs +83 -0
- package/test/risd-lifecycle.test.mjs +210 -0
- package/test/risd-log-follow.test.mjs +227 -0
- package/test/risd-mode.test.mjs +161 -0
- package/test/risd-ping.test.mjs +99 -0
- package/test/risd-programs.test.mjs +169 -0
- package/test/risd-review-p2.test.mjs +217 -0
- package/test/risd-shutdown.test.mjs +97 -0
- package/test/risd-teardown.test.mjs +87 -0
- package/test/risd-tools.test.mjs +211 -0
- package/test/risd-ui.test.mjs +445 -0
- package/test/risd-write.test.mjs +170 -0
- package/test/startup-reconcile.test.mjs +100 -0
- package/test/windows.test.mjs +37 -2
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* risd — session leases.
|
|
3
|
+
*
|
|
4
|
+
* A lease says "a live dsh process is using the proxy". It replaces the old
|
|
5
|
+
* "the proxy lives exactly as long as dsh" binding: the daemon polls each
|
|
6
|
+
* ownerPid every 3s, so Ctrl+C, SIGKILL, a crash and a hot reload all collapse
|
|
7
|
+
* into the same observation — the pid is gone — and every teardown decision
|
|
8
|
+
* (keepPolicy=session) becomes a consequence of that, not of catching an exit
|
|
9
|
+
* signal.
|
|
10
|
+
*
|
|
11
|
+
* Identity is `(ownerPid, sessionId, cwd)` so a session can re-acquire after a
|
|
12
|
+
* reconnect without duplicating itself; the id is random because it is what the
|
|
13
|
+
* plugin sends back on release.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-risd/leases
|
|
16
|
+
*/
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
|
+
import { pidAlive } from '../proxy.js'
|
|
19
|
+
|
|
20
|
+
export const LEASE_POLL_MS = 3000
|
|
21
|
+
|
|
22
|
+
function keyOf(ownerPid, sessionId, cwd) {
|
|
23
|
+
return `${ownerPid}\u0000${sessionId ?? ''}\u0000${cwd ?? ''}`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function iso(ms) {
|
|
27
|
+
return new Date(ms).toISOString()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param options - `{ pollMs, alive, onGone }`; `alive` is injectable for tests.
|
|
32
|
+
* @returns the registry: `acquire / release / list / snapshot / sweep / start / stop`.
|
|
33
|
+
*/
|
|
34
|
+
export function createLeaseRegistry({ pollMs = LEASE_POLL_MS, alive = pidAlive, onGone = () => {} } = {}) {
|
|
35
|
+
/** @type {Map<string, object>} */
|
|
36
|
+
const byId = new Map()
|
|
37
|
+
/** @type {Map<string, object>} */
|
|
38
|
+
const byKey = new Map()
|
|
39
|
+
let timer = null
|
|
40
|
+
|
|
41
|
+
function drop(lease) {
|
|
42
|
+
byId.delete(lease.id)
|
|
43
|
+
byKey.delete(lease.key)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function sweep(now = Date.now()) {
|
|
47
|
+
const gone = []
|
|
48
|
+
for (const lease of byId.values()) {
|
|
49
|
+
if (!alive(lease.ownerPid)) {
|
|
50
|
+
drop(lease)
|
|
51
|
+
gone.push(lease)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const lease of gone) {
|
|
55
|
+
try {
|
|
56
|
+
onGone(lease)
|
|
57
|
+
} catch {
|
|
58
|
+
/* a callback must not break the sweep */
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return gone
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
/**
|
|
66
|
+
* Create (or refresh) the lease for one owner/session/workspace.
|
|
67
|
+
* @param input - `{ ownerPid, sessionId?, cwd? }`.
|
|
68
|
+
* @returns the lease (a copy).
|
|
69
|
+
*/
|
|
70
|
+
acquire({ ownerPid, sessionId = null, cwd = null }, now = Date.now()) {
|
|
71
|
+
const key = keyOf(ownerPid, sessionId, cwd)
|
|
72
|
+
const existing = byKey.get(key)
|
|
73
|
+
if (existing !== undefined) {
|
|
74
|
+
existing.heartbeatAt = iso(now)
|
|
75
|
+
return { ...existing }
|
|
76
|
+
}
|
|
77
|
+
const lease = {
|
|
78
|
+
id: randomUUID(),
|
|
79
|
+
key,
|
|
80
|
+
ownerPid,
|
|
81
|
+
sessionId,
|
|
82
|
+
cwd,
|
|
83
|
+
createdAt: iso(now),
|
|
84
|
+
heartbeatAt: iso(now),
|
|
85
|
+
}
|
|
86
|
+
byId.set(lease.id, lease)
|
|
87
|
+
byKey.set(key, lease)
|
|
88
|
+
return { ...lease }
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
/** @returns true when a lease with that id existed. */
|
|
92
|
+
release(id) {
|
|
93
|
+
const lease = byId.get(String(id))
|
|
94
|
+
if (lease === undefined) return false
|
|
95
|
+
drop(lease)
|
|
96
|
+
return true
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
list() {
|
|
100
|
+
return [...byId.values()].map((lease) => ({ ...lease }))
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
count() {
|
|
104
|
+
return byId.size
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
sweep,
|
|
108
|
+
|
|
109
|
+
start() {
|
|
110
|
+
if (timer === null) {
|
|
111
|
+
timer = setInterval(() => sweep(), pollMs)
|
|
112
|
+
timer.unref?.()
|
|
113
|
+
}
|
|
114
|
+
return timer
|
|
115
|
+
},
|
|
116
|
+
|
|
117
|
+
stop() {
|
|
118
|
+
if (timer !== null) {
|
|
119
|
+
clearInterval(timer)
|
|
120
|
+
timer = null
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// Per-resource lifecycle policy: whether each of the four things the daemon runs
|
|
2
|
+
// follows a dsh session. Following the daemon is NOT configurable: stopping the
|
|
3
|
+
// daemon always stops everything it supervises (m07741) - a resource that outlives
|
|
4
|
+
// its supervisor would have no page left to stop it.
|
|
5
|
+
//
|
|
6
|
+
// The defaults are the shape the product had before this setting existed: the
|
|
7
|
+
// proxy follows dsh (its lease keeps the tunnel alive) and programs/debug keep
|
|
8
|
+
// running when the last dsh window closes, because the maintenance page can be the
|
|
9
|
+
// only UI on the machine.
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/** Stored beside risd.json/proxy.json in the daemon's home. */
|
|
14
|
+
export const LIFECYCLE_FILENAME = 'risd-lifecycle.json'
|
|
15
|
+
|
|
16
|
+
/** The four resources the page lets you tune, in page order. */
|
|
17
|
+
export const LIFECYCLE_RESOURCES = ['daemon', 'proxy', 'programs', 'debug']
|
|
18
|
+
|
|
19
|
+
/** Defaults: only `followDsh` exists; following the daemon is always on. */
|
|
20
|
+
export const LIFECYCLE_DEFAULTS = {
|
|
21
|
+
daemon: { followDsh: true },
|
|
22
|
+
proxy: { followDsh: true },
|
|
23
|
+
programs: { followDsh: false },
|
|
24
|
+
debug: { followDsh: false },
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Keys that used to be configurable and are now forced (m07741). */
|
|
28
|
+
const FORCED_KEYS = ['followDaemon']
|
|
29
|
+
|
|
30
|
+
/** @param home - daemon home directory. */
|
|
31
|
+
export function lifecyclePath(home) {
|
|
32
|
+
return join(home, LIFECYCLE_FILENAME)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function bool(value) { return typeof value === 'boolean' ? value : undefined }
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Merge `input` over the defaults, keeping only known resources and booleans.
|
|
39
|
+
* @param input - untrusted (file or request body).
|
|
40
|
+
* @returns `{ value, errors, changed }`.
|
|
41
|
+
*/
|
|
42
|
+
export function normalizeLifecycle(input) {
|
|
43
|
+
const errors = []
|
|
44
|
+
const value = {}
|
|
45
|
+
const seen = input !== null && typeof input === 'object' ? input : {}
|
|
46
|
+
if (input !== undefined && input !== null && typeof input !== 'object') {
|
|
47
|
+
errors.push('lifecycle 必须是对象')
|
|
48
|
+
}
|
|
49
|
+
for (const key of Object.keys(seen)) {
|
|
50
|
+
if (LIFECYCLE_RESOURCES.includes(key)) continue
|
|
51
|
+
// A payload for an unknown resource used to be saved as nothing at all.
|
|
52
|
+
errors.push(`${key} 不是生命周期资源(可用:${LIFECYCLE_RESOURCES.join('/')})`)
|
|
53
|
+
}
|
|
54
|
+
for (const resource of LIFECYCLE_RESOURCES) {
|
|
55
|
+
const defaults = LIFECYCLE_DEFAULTS[resource]
|
|
56
|
+
const given = seen[resource]
|
|
57
|
+
if (given === undefined) { value[resource] = Object.assign({}, defaults); continue }
|
|
58
|
+
if (given === null || typeof given !== 'object') {
|
|
59
|
+
errors.push(`${resource} 必须是对象`)
|
|
60
|
+
value[resource] = Object.assign({}, defaults)
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
for (const key of Object.keys(given)) {
|
|
64
|
+
if (key === 'followDsh' || FORCED_KEYS.includes(key)) continue
|
|
65
|
+
// Silently ignoring an unknown key made a typo look saved (review A2-P2-5).
|
|
66
|
+
errors.push(`${resource}.${key} 不是可配置项(只能配置 followDsh)`)
|
|
67
|
+
}
|
|
68
|
+
for (const key of FORCED_KEYS) {
|
|
69
|
+
if (given[key] !== undefined) {
|
|
70
|
+
errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 followDsh)`)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const merged = Object.assign({}, defaults)
|
|
74
|
+
for (const key of Object.keys(defaults)) {
|
|
75
|
+
const parsed = bool(given[key])
|
|
76
|
+
if (given[key] === undefined) continue
|
|
77
|
+
if (parsed === undefined) { errors.push(`${resource}.${key} 必须是 true/false`); continue }
|
|
78
|
+
merged[key] = parsed
|
|
79
|
+
}
|
|
80
|
+
value[resource] = merged
|
|
81
|
+
}
|
|
82
|
+
return { value, errors, changed: errors.length === 0 }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Merge a partial policy over the current one.
|
|
87
|
+
*
|
|
88
|
+
* `POST /v1/config` used to normalize the body alone, which silently reset the
|
|
89
|
+
* other three resources to their defaults whenever a caller saved one checkbox
|
|
90
|
+
* (review A2-P2-1).
|
|
91
|
+
* @param current - the policy in force.
|
|
92
|
+
* @param patch - only the resources/keys the caller means to change.
|
|
93
|
+
* @returns a full policy object for {@link writeLifecycle}.
|
|
94
|
+
*/
|
|
95
|
+
export function mergeLifecycle(current, patch) {
|
|
96
|
+
const base = current !== null && typeof current === 'object' && !Array.isArray(current) ? current : {}
|
|
97
|
+
const next = {}
|
|
98
|
+
for (const resource of LIFECYCLE_RESOURCES) {
|
|
99
|
+
const defaults = LIFECYCLE_DEFAULTS[resource]
|
|
100
|
+
const existing = base[resource] !== null && typeof base[resource] === 'object' && !Array.isArray(base[resource])
|
|
101
|
+
? base[resource]
|
|
102
|
+
: {}
|
|
103
|
+
next[resource] = Object.assign({}, defaults, existing)
|
|
104
|
+
}
|
|
105
|
+
if (patch !== null && typeof patch === 'object' && !Array.isArray(patch)) {
|
|
106
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
107
|
+
// An unknown resource is copied through on purpose: normalizeLifecycle is the
|
|
108
|
+
// single validator and must be able to reject it with a message instead of
|
|
109
|
+
// this merge silently dropping it (review A3-P1-2). Same for a non-object
|
|
110
|
+
// resource value (`{proxy:true}`) and unknown inner keys.
|
|
111
|
+
if (!LIFECYCLE_RESOURCES.includes(key)) { next[key] = value; continue }
|
|
112
|
+
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
113
|
+
Object.assign(next[key], value)
|
|
114
|
+
} else {
|
|
115
|
+
next[key] = value
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return next
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Read the policy, tolerating a missing or broken file (defaults win). */
|
|
123
|
+
export function readLifecycle(home) {
|
|
124
|
+
const path = lifecyclePath(home)
|
|
125
|
+
if (!existsSync(path)) return { value: normalizeLifecycle({}).value, path, exists: false, errors: [] }
|
|
126
|
+
try {
|
|
127
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
128
|
+
const normalized = normalizeLifecycle(parsed !== null && typeof parsed === 'object' ? parsed : {})
|
|
129
|
+
return { value: normalized.value, path, exists: true, errors: normalized.errors }
|
|
130
|
+
} catch {
|
|
131
|
+
return { value: normalizeLifecycle({}).value, path, exists: true, errors: ['lifecycle 文件无法解析,已按默认值运行'] }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Persist the policy atomically (tmp + rename, 0600).
|
|
137
|
+
* @returns the normalized value actually written.
|
|
138
|
+
*/
|
|
139
|
+
export function writeLifecycle(home, input) {
|
|
140
|
+
const normalized = normalizeLifecycle(input)
|
|
141
|
+
if (normalized.changed !== true) return { value: readLifecycle(home).value, errors: normalized.errors }
|
|
142
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
143
|
+
const path = lifecyclePath(home)
|
|
144
|
+
const tmp = `${path}.${process.pid}.tmp`
|
|
145
|
+
writeFileSync(tmp, `${JSON.stringify(normalized.value, null, 2)}\n`, { mode: 0o600 })
|
|
146
|
+
renameSync(tmp, path)
|
|
147
|
+
return { value: normalized.value, errors: [] }
|
|
148
|
+
}
|
package/lib/risd/log.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* risd — `risd.log`, the daemon's only output channel.
|
|
3
|
+
*
|
|
4
|
+
* The daemon may be started detached by a plugin that immediately forgets about
|
|
5
|
+
* it, so it cannot rely on stdio: it appends one line per event and rotates the
|
|
6
|
+
* file once it passes `maxBytes`. Writes are synchronous and best-effort — a
|
|
7
|
+
* daemon that cannot log must still serve.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-risd/log
|
|
10
|
+
*/
|
|
11
|
+
import { appendFileSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
import { proxyHomeDir } from '../proxy.js'
|
|
14
|
+
|
|
15
|
+
export const RISD_LOG_FILENAME = 'risd.log'
|
|
16
|
+
export const RISD_LOG_MAX_BYTES = 10 * 1024 * 1024
|
|
17
|
+
|
|
18
|
+
export function risdLogPath(home = proxyHomeDir()) {
|
|
19
|
+
return join(home, RISD_LOG_FILENAME)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param home - daemon home.
|
|
24
|
+
* @param options - `{ maxBytes }`.
|
|
25
|
+
* @returns `{ path, info, warn, error }` — line-oriented, never throws.
|
|
26
|
+
*/
|
|
27
|
+
export function createRisdLogger(home = proxyHomeDir(), { maxBytes = RISD_LOG_MAX_BYTES } = {}) {
|
|
28
|
+
const path = risdLogPath(home)
|
|
29
|
+
|
|
30
|
+
function rotate() {
|
|
31
|
+
try {
|
|
32
|
+
if (statSync(path).size < maxBytes) return
|
|
33
|
+
rmSync(`${path}.1`, { force: true })
|
|
34
|
+
renameSync(path, `${path}.1`)
|
|
35
|
+
} catch {
|
|
36
|
+
/* no file yet / rotate raced another writer: the append below is what matters */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function write(level, message) {
|
|
41
|
+
const line = `${new Date().toISOString()} ${level} ${message}\n`
|
|
42
|
+
try {
|
|
43
|
+
// The home may not exist yet on a first start; without this the first lines
|
|
44
|
+
// vanished silently (review A-P2-12).
|
|
45
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
46
|
+
rotate()
|
|
47
|
+
appendFileSync(path, line, { mode: 0o600 })
|
|
48
|
+
} catch {
|
|
49
|
+
/* logging must never take the daemon down */
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
path,
|
|
55
|
+
info: (message) => write('info', message),
|
|
56
|
+
warn: (message) => write('warn', message),
|
|
57
|
+
error: (message) => write('error', message),
|
|
58
|
+
}
|
|
59
|
+
}
|
package/lib/risd/ping.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reachability probe for the SOCKS upstream shown on the proxy tab.
|
|
3
|
+
*
|
|
4
|
+
* The page used to render "unreachable" only after the engine failed to reload, so a
|
|
5
|
+
* wrong host/port looked identical to a healthy one until the first request failed.
|
|
6
|
+
* The probe connects to the configured SOCKS endpoint and performs the SOCKS5
|
|
7
|
+
* greeting: a plain TCP accept is not enough (a random service on that port answers
|
|
8
|
+
* too), while requiring a `05 00` answer also tells the user their SOCKS server is
|
|
9
|
+
* up and does not need authentication.
|
|
10
|
+
*
|
|
11
|
+
* Deliberately dependency-free and side-effect-free (one short-lived socket, no
|
|
12
|
+
* retries): the page polls it every few seconds.
|
|
13
|
+
*
|
|
14
|
+
* @module risd/ping
|
|
15
|
+
*/
|
|
16
|
+
import { createConnection } from 'node:net'
|
|
17
|
+
|
|
18
|
+
const GREETING = Buffer.from([0x05, 0x01, 0x00])
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 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}>}
|
|
25
|
+
*/
|
|
26
|
+
export function pingSocks(options = {}) {
|
|
27
|
+
const host = typeof options.host === 'string' ? options.host.trim() : ''
|
|
28
|
+
const port = Number(options.port)
|
|
29
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(200, Number(options.timeoutMs)) : 2000
|
|
30
|
+
const at = new Date().toISOString()
|
|
31
|
+
const base = { host, port, at, ms: 0, socks: false }
|
|
32
|
+
if (host === '' || !Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
33
|
+
return Promise.resolve({ ...base, ok: false, error: host === '' ? '未配置代理服务器地址' : '端口无效' })
|
|
34
|
+
}
|
|
35
|
+
const started = Date.now()
|
|
36
|
+
const connect = typeof options.connect === 'function' ? options.connect : createConnection
|
|
37
|
+
return new Promise((resolve) => {
|
|
38
|
+
let settled = false
|
|
39
|
+
let socket = null
|
|
40
|
+
let timer = null
|
|
41
|
+
const finish = (result) => {
|
|
42
|
+
if (settled) return
|
|
43
|
+
settled = true
|
|
44
|
+
if (timer !== null) clearTimeout(timer)
|
|
45
|
+
try { socket?.destroy() } catch { /* already gone */ }
|
|
46
|
+
resolve({ ...base, ms: Date.now() - started, ...result })
|
|
47
|
+
}
|
|
48
|
+
timer = setTimeout(() => finish({ ok: false, error: `连接超时(${timeoutMs} ms)` }), timeoutMs)
|
|
49
|
+
timer.unref?.()
|
|
50
|
+
try {
|
|
51
|
+
socket = connect({ host, port })
|
|
52
|
+
socket.setTimeout?.(timeoutMs, () => finish({ ok: false, error: `连接超时(${timeoutMs} ms)` }))
|
|
53
|
+
socket.once('error', (error) => {
|
|
54
|
+
finish({ ok: false, error: describeError(error) })
|
|
55
|
+
})
|
|
56
|
+
socket.once('connect', () => {
|
|
57
|
+
socket.write(GREETING)
|
|
58
|
+
})
|
|
59
|
+
// A peer may accept the connection and close it without ever answering the
|
|
60
|
+
// greeting. Waiting for the timeout would report a healthy-but-silent SOCKS
|
|
61
|
+
// 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)
|
|
65
|
+
socket.on('data', (chunk) => {
|
|
66
|
+
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(握手版本不符)' })
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
if (buffer[1] !== 0x00) {
|
|
74
|
+
finish({ ok: false, socks: true, error: 'SOCKS5 要求认证(仅支持无认证代理)' })
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
finish({ ok: true, socks: true })
|
|
78
|
+
})
|
|
79
|
+
} catch (error) {
|
|
80
|
+
clearTimeout(timer)
|
|
81
|
+
finish({ ok: false, error: describeError(error) })
|
|
82
|
+
}
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function describeError(error) {
|
|
87
|
+
const code = String(error?.code ?? '')
|
|
88
|
+
if (code === 'ECONNREFUSED') return '连接被拒绝(端口没有服务)'
|
|
89
|
+
if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return '主机名解析失败'
|
|
90
|
+
if (code === 'EHOSTUNREACH' || code === 'ENETUNREACH') return '网络不可达'
|
|
91
|
+
if (code === 'ETIMEDOUT') return '连接超时'
|
|
92
|
+
if (code === 'ECONNRESET' || code === 'EPIPE') return '连接被重置(对端不是 SOCKS5 或已关闭)'
|
|
93
|
+
return String(error?.message ?? error ?? '连接失败')
|
|
94
|
+
}
|