dsh-ris-ide 1.8.2 → 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.
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
  })
@@ -17,7 +17,7 @@
17
17
  import { spawn } from 'node:child_process'
18
18
  import { createServer, request } from 'node:http'
19
19
  import { request as httpsRequest } from 'node:https'
20
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
20
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
21
21
  import { isAbsolute, join, win32 } from 'node:path'
22
22
  import { timingSafeEqual } from 'node:crypto'
23
23
  import { fileURLToPath } from 'node:url'
@@ -39,7 +39,7 @@ import { reconcileStartupLeftovers } from '../startup.js'
39
39
  import { createDebugEngine } from './debug.js'
40
40
  import { mergeLifecycle, readLifecycle, writeLifecycle } from './lifecycle.js'
41
41
  import { risdUiHtml } from './ui.js'
42
- import { pingSocks } from './ping.js'
42
+ import { pingSocks, probeTarget } from './ping.js'
43
43
  import { buildStamp } from './build.js'
44
44
  import { DebugError, debugErrorStatus } from '../debug/engine.js'
45
45
  import { createHealthCache } from '../proxybridge-health.js'
@@ -695,10 +695,10 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
695
695
  }
696
696
  // Per-resource policy: "follow dsh" stops it with the last window; the
697
697
  // daemon-owned ones stay until the daemon itself stops (or forever).
698
- if (lifecycle.debug.followDsh === true) await debug.stopAll().catch(() => {})
699
- if (lifecycle.programs.followDsh === true) await stopAllPrograms()
698
+ if (lifecycle.debug.stopWithDsh === true) await debug.stopAll().catch(() => {})
699
+ if (lifecycle.programs.stopWithDsh === true) await stopAllPrograms()
700
700
  const cwd = engineCwd
701
- if (lifecycle.proxy.followDsh === true) {
701
+ if (lifecycle.proxy.stopWithDsh === true) {
702
702
  await teardownNetwork(cwd)
703
703
  if (engineCwd === cwd) engineCwd = null
704
704
  }
@@ -749,14 +749,14 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
749
749
  }
750
750
  function scheduleIdleExit() {
751
751
  // "daemon follows dsh = false" means: stay up until someone stops me.
752
- if (lifecycle.daemon.followDsh !== true) return
752
+ if (lifecycle.daemon.stopWithDsh !== true) return
753
753
  if (idleTimer !== null) return
754
754
  idleTimer = setTimeout(() => {
755
755
  idleTimer = null
756
756
  // A daemon opened from the maintenance page has no lease at all, yet may be
757
757
  // supervising programs or a debug session: idling out would kill them.
758
758
  void hasActiveWork().then((active) => {
759
- // An owned engine means the network is a service (proxy.followDsh=false) or
759
+ // An owned engine means the network is a service (proxy.stopWithDsh=false) or
760
760
  // somebody is using it without a lease: retiring would tear it down, which
761
761
  // is exactly what "follow daemon" promised not to do (review A2-P2-3).
762
762
  if (!active && engineCwd === null) return stop()
@@ -797,6 +797,9 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
797
797
  }
798
798
  } catch { /* the workspace may have vanished */ }
799
799
  }
800
+ // Record the now-empty set so a later `programs.startWithDsh` restore does not
801
+ // resurrect what this policy just stopped.
802
+ await saveProgramsSnapshot()
800
803
  }
801
804
  const startedAt = new Date().toISOString()
802
805
  // The daemon code the page will render: captured NOW, because Node caches the
@@ -830,13 +833,14 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
830
833
  engineOp = run.then(() => undefined, () => undefined)
831
834
  return run
832
835
  }
833
- // 「代理引擎跟随 dsh」的启动半边(m13950):与拆除共用**租约**这一条链路——
834
- // 拆除看 leases.count() 归零,启动看第一份租约到达,两边读同一个
835
- // lifecycle.proxy.followDsh,所以不会出现「启动跟了、停止没跟」的错位。
836
+ // 「代理引擎跟随 dsh」的启动半边(m13950 / m03397):与拆除共用**租约**这一条
837
+ // 链路——拆除看 leases.count() 归零(proxy.stopWithDsh),启动看第一份租约到达
838
+ // (proxy.startWithDsh),两边读同一条 lifecycle 的对应半边,所以不会出现
839
+ // 「启动跟了、停止没跟」的错位。
836
840
  // 自动启动永不 interactive:dsh 接入的副作用不许弹密码框(m13910),需要 root
837
841
  // 的桥接只在页面组件卡里提示。失败被吞掉并留给页面,那里还有显式按钮。
838
842
  function followStartForLease(cwd) {
839
- if (lifecycle.proxy.followDsh !== true) return Promise.resolve({ action: 'skipped', reason: 'not-following-dsh' })
843
+ if (lifecycle.proxy.startWithDsh !== true) return Promise.resolve({ action: 'skipped', reason: 'not-following-dsh' })
840
844
  if (followStarting !== null) return Promise.resolve({ action: 'skipped', reason: 'starting' })
841
845
  if (engineSummary().state === 'running') return Promise.resolve({ action: 'skipped', reason: 'running' })
842
846
  // The in-flight promise stays reachable: teardown must be able to wait for a
@@ -877,6 +881,97 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
877
881
  }
878
882
  // Program start/stop share one queue so two clicks cannot spawn the same row twice.
879
883
  let programOp = Promise.resolve()
884
+
885
+ // The programs that were still running when this daemon last wrote its state.
886
+ // `programs.startWithDsh` (m03397) restores them on the first dsh lease: a
887
+ // program is started per workspace and only the daemon knows what was live, so
888
+ // the alternative would be guessing from config — which starts programs the user
889
+ // had just stopped.
890
+ const PROGRAMS_SNAPSHOT_FILENAME = 'risd-programs-last.json'
891
+ /** Absolute path of the snapshot file (daemon home). */
892
+ function programsSnapshotPath() { return join(home, PROGRAMS_SNAPSHOT_FILENAME) }
893
+ /**
894
+ * Read the last snapshot. A broken or foreign file is "nothing was running":
895
+ * restoring a program is a convenience, never a correctness requirement.
896
+ * @returns `{cwd, id, dir}[]`.
897
+ */
898
+ function readProgramsSnapshot() {
899
+ try {
900
+ const parsed = JSON.parse(readFileSync(programsSnapshotPath(), 'utf8'))
901
+ const rows = Array.isArray(parsed?.programs) ? parsed.programs : []
902
+ return rows
903
+ .filter((row) => typeof row?.cwd === 'string' && isAbsolute(row.cwd) && typeof row.id === 'string' && row.id !== '')
904
+ .map((row) => ({ cwd: row.cwd, id: row.id, dir: typeof row.dir === 'string' ? row.dir : '' }))
905
+ } catch { return [] }
906
+ }
907
+ // Serialized so two program actions cannot write a half-finished snapshot (a
908
+ // restore that reads while a stop is being recorded would resurrect a program).
909
+ let programSnapshotWork = Promise.resolve()
910
+ /** Record what is running right now (atomic write; failures are non-fatal). */
911
+ function saveProgramsSnapshot() {
912
+ const run = programSnapshotWork.then(async () => {
913
+ const rows = []
914
+ const cwds = new Set(workspaces)
915
+ if (typeof engineCwd === 'string' && engineCwd !== '') cwds.add(engineCwd)
916
+ for (const cwd of cwds) {
917
+ if (!existsSync(cwd)) continue
918
+ try {
919
+ const listed = await listPrograms(cwd, {})
920
+ for (const row of listed.programs) {
921
+ if (row.running === null || row.running === undefined || row.running.alive !== true) continue
922
+ rows.push({ cwd, id: row.id, dir: listed.dir })
923
+ }
924
+ } catch { /* a vanished workspace cannot be running anything we know */ }
925
+ }
926
+ try {
927
+ mkdirSync(home, { recursive: true, mode: 0o700 })
928
+ const path = programsSnapshotPath()
929
+ const tmp = `${path}.${process.pid}.tmp`
930
+ writeFileSync(tmp, `${JSON.stringify({ at: new Date().toISOString(), programs: rows }, null, 2)}\n`, { mode: 0o600 })
931
+ renameSync(tmp, path)
932
+ } catch { /* an unwritable home must not fail the program action */ }
933
+ }, () => {})
934
+ programSnapshotWork = run
935
+ return run
936
+ }
937
+ // One restore per daemon instance: a later lease must not undo a manual stop by
938
+ // starting the same programs again.
939
+ let programsRestored = false
940
+ /**
941
+ * Start the programs the snapshot remembers (first lease only).
942
+ * Never interactive and never fatal: a program that cannot start is left to the
943
+ * page, which has the explicit start button and the log that says why.
944
+ * @returns `{action, started, failed}`.
945
+ */
946
+ async function restoreProgramsForLease() {
947
+ if (programsRestored === true) return { action: 'skipped', reason: 'already-restored' }
948
+ programsRestored = true
949
+ if (lifecycle.programs.startWithDsh !== true) return { action: 'skipped', reason: 'not-following-dsh' }
950
+ const rows = readProgramsSnapshot()
951
+ if (rows.length === 0) return { action: 'skipped', reason: 'nothing-to-restore' }
952
+ const started = []
953
+ const failed = []
954
+ for (const row of rows) {
955
+ // The lease that triggered this may already be gone (a window that opened and
956
+ // closed): starting programs for nobody is exactly the leak teardown avoids.
957
+ if (leases.count() === 0) break
958
+ if (!existsSync(row.cwd)) continue
959
+ try {
960
+ const listed = await listPrograms(row.cwd, { dir: row.dir })
961
+ const live = listed.programs.find((item) => item.id === row.id)
962
+ if (live !== undefined && live.running !== null && live.running !== undefined && live.running.alive === true) continue
963
+ rememberWorkspace(row.cwd)
964
+ const result = await (programOp = programOp.then(
965
+ async () => startProgramByKey(row.cwd, row.id, { dir: row.dir }),
966
+ () => ({ ok: false }),
967
+ ))
968
+ if (result !== null && result !== undefined && result.ok === true) started.push(row.id)
969
+ else failed.push(row.id)
970
+ } catch { failed.push(row.id) }
971
+ }
972
+ if (started.length > 0) await saveProgramsSnapshot()
973
+ return { action: 'restored', started, failed }
974
+ }
880
975
  // Bridge (ProxyBridge) operations are serialized too (E8): a rule reload and a
881
976
  // stop are two single-file handshakes with the elevated watchdog, and running
882
977
  // them concurrently can reload a profile the other side is already tearing down.
@@ -1092,11 +1187,15 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1092
1187
  if (path === '/v1/proxy/ping' && method === 'GET') {
1093
1188
  // Reachability of the configured SOCKS upstream, for the status chip on the
1094
1189
  // proxy tab. Query overrides let the page test an edited-but-unsaved value.
1095
- const stored = readProxyConfig(url.searchParams.get('cwd') ?? home).socks
1190
+ const config = readProxyConfig(url.searchParams.get('cwd') ?? home)
1191
+ const stored = config.socks
1096
1192
  const host = url.searchParams.get('host') ?? stored.host
1097
1193
  const rawPort = url.searchParams.get('port')
1098
1194
  const port = rawPort === null ? stored.port : Number(rawPort)
1099
- const result = await pingSocks({ host, port })
1195
+ // m03429: a greeting only proves "something speaks SOCKS5 here". When the
1196
+ // config names a concrete destination, finish the handshake with a real
1197
+ // CONNECT so "usable" means the tunnel actually forwards.
1198
+ const result = await pingSocks({ host, port, target: probeTarget(config) })
1100
1199
  return json(res, 200, result)
1101
1200
  }
1102
1201
 
@@ -1507,6 +1606,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1507
1606
  return fail(res, error?.status ?? 500, error?.code ?? 'program-failed', error?.message ?? String(error))
1508
1607
  }
1509
1608
  if (result.ok !== true) return fail(res, result.status ?? 500, result.code ?? 'program-failed', result.message ?? 'program operation failed')
1609
+ // Keep `risd-programs-last.json` in step with reality: `programs.startWithDsh`
1610
+ // restores exactly this set on the next dsh attach (m03397).
1611
+ await saveProgramsSnapshot()
1510
1612
  return json(res, 200, Object.assign({ ok: true, action }, result))
1511
1613
  }
1512
1614
 
@@ -1641,9 +1743,14 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1641
1743
  // The start half of 「跟随 dsh」: the policy is read when the lease arrives,
1642
1744
  // the same signal the teardown watches. Off the response path (starting the
1643
1745
  // engine costs seconds), and never interactive.
1644
- if (lifecycle.proxy.followDsh === true && engineSummary().state !== 'running') {
1746
+ if (lifecycle.proxy.startWithDsh === true && engineSummary().state !== 'running') {
1645
1747
  setImmediate(() => { followStartForLease(lease.cwd).catch(() => {}) })
1646
1748
  }
1749
+ // The programs start half (m03397) rides the same signal: the first dsh of
1750
+ // this daemon instance restores what was running when it last went away.
1751
+ if (programsRestored !== true && lifecycle.programs.startWithDsh === true) {
1752
+ setImmediate(() => { restoreProgramsForLease().catch(() => {}) })
1753
+ }
1647
1754
  return json(res, 200, { ok: true, lease })
1648
1755
  }
1649
1756
 
@@ -1682,7 +1789,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1682
1789
  lifecycle = written.value
1683
1790
  // Re-arm the idle timer with the new policy: turning "follow dsh" off
1684
1791
  // must not leave a timer armed from before the change.
1685
- if (lifecycle.daemon.followDsh !== true) cancelIdleExit()
1792
+ if (lifecycle.daemon.stopWithDsh !== true) cancelIdleExit()
1686
1793
  else if (leases.count() === 0 && engineCwd === null) scheduleIdleExit()
1687
1794
  return json(res, 200, { ok: true, lifecycle, configPath: join(home, 'risd-lifecycle.json') })
1688
1795
  }
package/lib/risd/ui.js CHANGED
@@ -143,6 +143,8 @@ export function risdUiHtml(options) {
143
143
  .life { display:flex; align-items:center; gap:10px; padding:6px 0; font-size:13px; }
144
144
  .life b { min-width:96px; font-weight:600; }
145
145
  .life input { margin:0; }
146
+ .life-col { width:132px; display:flex; align-items:center; gap:6px; }
147
+ .life-head { padding:0 0 2px; font-size:12px; }
146
148
  .modal { position:fixed; inset:0; display:flex; align-items:center; justify-content:center; background:rgba(17,24,39,.45); z-index:50; }
147
149
  .modal[hidden] { display:none; }
148
150
  .modal-card { width:440px; max-width:calc(100% - 32px); background:#fff; border-radius:12px; padding:20px 22px; box-shadow:0 24px 48px rgba(17,24,39,.22); }
@@ -194,7 +196,7 @@ export function risdUiHtml(options) {
194
196
  <span class="pill" id="proxy-pill">未知</span>
195
197
  <span class="muted" id="proxy-detail"></span>
196
198
  <span class="grow"></span>
197
- <button id="engine-toggle" disabled>启动</button>
199
+ <button id="engine-toggle" disabled>启动引擎</button>
198
200
  </div>
199
201
  </section>
200
202
  <section>
@@ -206,12 +208,25 @@ export function risdUiHtml(options) {
206
208
  <div id="debugs"><p class="empty">加载中…</p></div>
207
209
  </section>
208
210
  <section>
209
- <h2>生命周期 <span class="sub">只配置是否跟随 dsh;所有资源强制跟随 daemon(停止 daemon 时一并停止)</span></h2>
211
+ <h2>生命周期</h2>
210
212
  <div id="lifecycle-rows">
211
- <label class="life"><b>守护进程</b><input type="checkbox" data-life="daemon.followDsh"><span class="muted">跟随 dsh:最后一个 dsh 窗口退出后,空闲 10 分钟自动退出;关掉则一直运行到手动停止</span></label>
212
- <label class="life"><b>代理引擎</b><input type="checkbox" data-life="proxy.followDsh"><span class="muted">跟随 dsh:dsh 接入时启动引擎,没有 dsh 租约时拆除隧道(含系统层拦截);拦截需要 root 时不会自动弹窗</span></label>
213
- <label class="life"><b>程序(JVM)</b><input type="checkbox" data-life="programs.followDsh"><span class="muted">跟随 dsh:最后一个窗口退出后停止程序</span></label>
214
- <label class="life"><b>调试会话</b><input type="checkbox" data-life="debug.followDsh"><span class="muted">跟随 dsh:最后一个窗口退出后断开调试</span></label>
213
+ <div class="life life-head"><b></b><span class="life-col">跟随 dsh 启动</span><span class="life-col">跟随 dsh 停止</span></div>
214
+ <label class="life"><b>守护进程</b>
215
+ <span class="life-col"><input type="checkbox" data-life="daemon.startWithDsh" checked disabled title="dsh 需要时按需拉起守护进程(强制,不可关)"></span>
216
+ <span class="life-col"><input type="checkbox" data-life="daemon.stopWithDsh" title="最后一个 dsh 窗口退出后,空闲 10 分钟自动退出;关掉则一直运行到手动停止"></span>
217
+ </label>
218
+ <label class="life"><b>代理引擎</b>
219
+ <span class="life-col"><input type="checkbox" data-life="proxy.startWithDsh" title="dsh 接入时启动引擎(自动启动不会弹提权框,需要 root 的桥接只在组件卡里提示)"></span>
220
+ <span class="life-col"><input type="checkbox" data-life="proxy.stopWithDsh" title="没有 dsh 租约时拆除隧道(含系统层拦截)"></span>
221
+ </label>
222
+ <label class="life"><b>程序(JVM)</b>
223
+ <span class="life-col"><input type="checkbox" data-life="programs.startWithDsh" title="dsh 接入时恢复上次 daemon 退出时仍在运行的程序"></span>
224
+ <span class="life-col"><input type="checkbox" data-life="programs.stopWithDsh" title="最后一个 dsh 窗口退出后停止程序"></span>
225
+ </label>
226
+ <label class="life"><b>调试会话</b>
227
+ <span class="life-col"><input type="checkbox" data-life="debug.startWithDsh" disabled title="调试会话没有可自动启动的对象"></span>
228
+ <span class="life-col"><input type="checkbox" data-life="debug.stopWithDsh" title="最后一个 dsh 窗口退出后断开调试"></span>
229
+ </label>
215
230
  </div>
216
231
  <div class="row" style="margin-top:10px">
217
232
  <span class="muted">勾选即自动保存,不用点按钮</span>
@@ -250,7 +265,7 @@ export function risdUiHtml(options) {
250
265
  <span class="pill off" id="proxy-engine-pill">未知</span>
251
266
  <span class="grow"></span>
252
267
  <span class="muted" id="proxy-revision"></span>
253
- <button id="proxy-engine-toggle" disabled>启动</button>
268
+ <button id="proxy-engine-toggle" disabled>启动引擎</button>
254
269
  </div>
255
270
  <div class="row" style="margin-bottom:10px">
256
271
  <label class="muted">SOCKS 主机</label><input id="proxy-socks-host" class="narrow" placeholder="host">
@@ -516,6 +531,9 @@ export function risdUiHtml(options) {
516
531
  function lifecycleFromBoxes() {
517
532
  var policy = { daemon: {}, proxy: {}, programs: {}, debug: {} };
518
533
  document.querySelectorAll('#lifecycle-rows input[data-life]').forEach(function (box) {
534
+ // A disabled half is not part of the policy (the daemon start is forced, the
535
+ // debug start does not exist) — sending it would be rejected as unknown.
536
+ if (box.disabled === true) return;
519
537
  var parts = box.getAttribute('data-life').split('.');
520
538
  if (policy[parts[0]] === undefined) policy[parts[0]] = {};
521
539
  policy[parts[0]][parts[1]] = box.checked;
@@ -1260,16 +1278,24 @@ export function risdUiHtml(options) {
1260
1278
  if (result === null || result === undefined) { cls += ' busy'; text = '检测中…'; }
1261
1279
  // 没填 SOCKS 地址不是故障:灰色「未配置」,别用红点吓人(review C3-P2-9)。
1262
1280
  else if (result.configured === false) { cls += ' off'; text = '未配置'; }
1263
- else if (result.ok === true) { cls += ' on'; text = '连通 ' + ((result.ms || 0) + ' ms'); }
1264
- else if (result.socks === true) { cls += ' warn'; text = '需认证'; }
1281
+ else if (result.ok === true && result.usable === true) { cls += ' on'; text = '可用 ' + ((result.ms || 0) + ' ms'); }
1282
+ // m03429: nothing concrete to dial — the greeting is all the evidence there is.
1283
+ else if (result.ok === true) { cls += ' on'; text = '握手正常'; }
1284
+ else if (result.socks === true) { cls += ' warn'; text = /认证/.test(String(result.error || '')) ? '需认证' : '无法转发'; }
1265
1285
  else { cls += ' err'; text = '无法连接'; }
1286
+ var target = result === null || result === undefined ? null : result.target;
1287
+ var targetText = target === null || target === undefined ? '' : ' → ' + target.host + ':' + target.port;
1266
1288
  chip.className = cls;
1267
1289
  chip.textContent = text;
1268
1290
  chip.title = result === null || result === undefined
1269
1291
  ? '正在检测代理服务器连通性…'
1270
1292
  : (result.configured === false
1271
1293
  ? '还没有填写代理服务器地址'
1272
- : (result.ok === true ? '代理服务器可达(' + (result.host || '') + ':' + (result.port || '') + ',' + result.at + ')' : String(result.error || '连接失败')));
1294
+ : (result.ok === true
1295
+ ? (result.usable === true
1296
+ ? '代理服务器可用(' + (result.host || '') + ':' + (result.port || '') + targetText + ',' + result.ms + ' ms)'
1297
+ : 'SOCKS5 握手正常(' + (result.host || '') + ':' + (result.port || '') + ');配置里没有可验证的转发目标,只确认了协议')
1298
+ : String(result.error || '连接失败')));
1273
1299
  }
1274
1300
  function refreshPing() {
1275
1301
  var host = el('proxy-socks-host').value.trim();
@@ -1356,7 +1382,12 @@ export function risdUiHtml(options) {
1356
1382
  }
1357
1383
 
1358
1384
  function selectIdeWindow(windows, cwd) {
1359
- var win = windows.filter(function (row) { return (row.cwd || '') === cwd; })[0] || windows[0];
1385
+ var win = windows.filter(function (row) { return (row.cwd || '') === cwd; })[0];
1386
+ // The pane may show a workspace dsh no longer mirrors (the user opened it
1387
+ // earlier and dsh has since switched): keep that row instead of jumping to
1388
+ // whatever dsh switched to (m04873).
1389
+ if (!win && cwd) win = { cwd: cwd, live: false, active: false };
1390
+ if (!win) win = windows[0];
1360
1391
  if (!win) return;
1361
1392
  var key = win.cwd || '';
1362
1393
  if (win.live !== false) delete state.staleDismissed[key];
@@ -1408,6 +1439,28 @@ export function risdUiHtml(options) {
1408
1439
  }
1409
1440
  }
1410
1441
 
1442
+ /**
1443
+ * Which workspace the IDE pane shows.
1444
+ *
1445
+ * This page keeps its OWN choice (state.cwd, persisted as risd.cwd): dsh
1446
+ * switching workspace must not move the IDE embedded here, and this page must
1447
+ * not move the dsh sidebar console either (m04873). So when the remembered
1448
+ * workspace is no longer in dsh's mirror the pane KEEPS it instead of falling
1449
+ * back to whatever dsh switched to — the iframe URL does not change, so the
1450
+ * embedded document (and its unsaved edits) survives.
1451
+ * @param {Array<object>} windows - rows from /v1/dsh.
1452
+ * @returns {object|undefined} the row to render, or a cwd-only stub.
1453
+ */
1454
+ function pickIdeWindow(windows) {
1455
+ var preferred = state.cwd;
1456
+ if (preferred) {
1457
+ var match = windows.filter(function (win) { return (win.cwd || '') === preferred; })[0];
1458
+ if (match) return match;
1459
+ return { cwd: preferred, live: false, active: false };
1460
+ }
1461
+ return windows.filter(function (win) { return win.live !== false; })[0] || windows[0];
1462
+ }
1463
+
1411
1464
  function renderIde(windows, current) {
1412
1465
  var selected = current || windows[0];
1413
1466
  el('ide-ws-list').innerHTML = windows.map(function (win) {
@@ -1465,9 +1518,7 @@ export function risdUiHtml(options) {
1465
1518
  ideUnavailable(body);
1466
1519
  return;
1467
1520
  }
1468
- var preferred = state.cwd;
1469
- var selected = windows.filter(function (win) { return (win.cwd || '') === preferred; })[0] ||
1470
- windows.filter(function (win) { return win.live !== false; })[0] || windows[0];
1521
+ var selected = pickIdeWindow(windows);
1471
1522
  renderIde(windows, selected);
1472
1523
  }).catch(function (error) {
1473
1524
  ideMessage('err', 'IDE 状态读取失败:' + error.message);
@@ -1488,9 +1539,7 @@ export function risdUiHtml(options) {
1488
1539
  ideUnavailable(body);
1489
1540
  return;
1490
1541
  }
1491
- var preferred = state.cwd;
1492
- var selected = windows.filter(function (win) { return (win.cwd || '') === preferred; })[0] ||
1493
- windows.filter(function (win) { return win.live !== false; })[0] || windows[0];
1542
+ var selected = pickIdeWindow(windows);
1494
1543
  renderIde(windows, selected);
1495
1544
  }).catch(function (error) {
1496
1545
  ideMessage('err', 'IDE 状态读取失败:' + error.message);
@@ -1637,11 +1686,14 @@ export function risdUiHtml(options) {
1637
1686
  }
1638
1687
  button.removeAttribute('aria-busy');
1639
1688
  button.disabled = false;
1640
- button.textContent = running ? '停止' : '启动';
1689
+ button.textContent = running ? '停止' : '启动引擎';
1641
1690
  button.className = running ? 'danger' : '';
1691
+ // m05590: starting the engine never asks for a password. The system-layer
1692
+ // component is a separate click (bridge-fix), so a dialog can only appear
1693
+ // after the user asked for it by name.
1642
1694
  button.title = running
1643
1695
  ? '停止引擎、系统层拦截与 git 代理'
1644
- : '按当前规则表启动代理引擎(系统层拦截可能需要提权)';
1696
+ : '按当前规则表启动代理引擎(不需要 root;系统层拦截起来后再单独点「启动系统层拦截」)';
1645
1697
  });
1646
1698
  }
1647
1699
  function toggleProxyEngine() {
@@ -1653,10 +1705,10 @@ export function risdUiHtml(options) {
1653
1705
  engineBusy = true;
1654
1706
  engineBusyAction = action;
1655
1707
  paintEngineButtons();
1656
- // A click is the one place allowed to ask for elevation (m13910); the
1657
- // save-triggered auto-start calls the same route without the flag.
1708
+ // m05590: this click starts the ENGINE only and therefore never asks for a
1709
+ // password. Elevation lives on the separate 「启动系统层拦截」button (fixBridge),
1710
+ // so no dialog can appear as a side effect of starting or stopping the engine.
1658
1711
  var body = { action: action, cwd: state.cwd };
1659
- if (action === 'start') body.interactive = true;
1660
1712
  api('/v1/action', { method: 'POST', body: body })
1661
1713
  .then(function (response) {
1662
1714
  var result = (response && response.result) || {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ris-ide",
3
- "version": "1.8.2",
3
+ "version": "1.8.3",
4
4
  "license": "MIT",
5
5
  "description": "RIS-IDE local dev panel for the DSH web GUI: live log tail, one-click start/stop of workspace programs, JDWP debugging, file tree + editor, and a standalone IDE window that carries no session history. · DSH 右侧栏本地开发面板:日志实时跟随、一键启停本地程序、Java 断点调试、文件树与编辑器、独立 IDE 窗口。",
6
6
  "keywords": [