dsh-ris-ide 1.7.2 → 1.7.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/README.md +29 -2
- package/bin/check-listing.mjs +247 -0
- package/bin/proxy-janitor.mjs +88 -0
- package/lib/client-codemirror.js +92 -66
- package/lib/client.js +1347 -25
- package/lib/index.js +1174 -8
- package/lib/janitor.js +286 -0
- package/lib/proxy.js +1498 -0
- package/lib/redirector.js +2109 -0
- package/package.json +4 -2
- package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
- package/test/client-viewer.test.mjs +332 -4
- package/test/companion.test.mjs +65 -0
- package/test/host-tail.test.mjs +33 -1
- package/test/inherit-engine.test.mjs +175 -0
- package/test/install-phase.test.mjs +36 -0
- package/test/janitor.test.mjs +144 -0
- package/test/lifecycle.test.mjs +88 -0
- package/test/proxy-route.test.mjs +599 -0
- package/test/proxy.test.mjs +873 -0
- package/test/redirector.test.mjs +521 -0
package/lib/index.js
CHANGED
|
@@ -51,11 +51,11 @@
|
|
|
51
51
|
* @module dsh-ris-ide
|
|
52
52
|
*/
|
|
53
53
|
import { appendFile, copyFile, cp, link, lstat, mkdir, open, readdir, readFile, readlink, rename, rm, stat, symlink, truncate, writeFile } from 'node:fs/promises'
|
|
54
|
-
import { createReadStream, createWriteStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
54
|
+
import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
55
55
|
import { watch } from 'node:fs'
|
|
56
56
|
import { createHash } from 'node:crypto'
|
|
57
|
-
import { spawn } from 'node:child_process'
|
|
58
|
-
import { homedir } from 'node:os'
|
|
57
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
58
|
+
import { homedir, tmpdir } from 'node:os'
|
|
59
59
|
import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep, parse } from 'node:path'
|
|
60
60
|
import { fileURLToPath } from 'node:url'
|
|
61
61
|
import { pipeline } from 'node:stream/promises'
|
|
@@ -65,6 +65,22 @@ import {
|
|
|
65
65
|
createDebugSessions, DebugError, debugErrorStatus, jdwpAgentArg, allocateDebugPort, waitForTcp,
|
|
66
66
|
waitForJdwpListening, toJsonSafe,
|
|
67
67
|
} from './debug/engine.js'
|
|
68
|
+
import { allowList, autoRules, engineSide, gitProxyPlan, injectionFor, isSocksCapableProgram, mergeConfigs, parseHostSpec, parsePortSpec, programKey, proxyConfigPath, proxyHomeDir, proxyPid, proxyStatus, readProxyConfig, ruleEffectiveness, runWindowsGitConfig, startProxy, stopProxy, stopProxySync, writeProxyConfig } from './proxy.js'
|
|
69
|
+
import {
|
|
70
|
+
buildProfile,
|
|
71
|
+
redirectorCommand,
|
|
72
|
+
localRedirectorRunning,
|
|
73
|
+
redirectorStatus,
|
|
74
|
+
redirectorStatusCached,
|
|
75
|
+
reloadRedirectorsWithProfile,
|
|
76
|
+
startRedirectors,
|
|
77
|
+
stopRedirector,
|
|
78
|
+
posixToWindowsPath,
|
|
79
|
+
syncRedirector,
|
|
80
|
+
windowsToPosixPath,
|
|
81
|
+
writeHeartbeat,
|
|
82
|
+
} from './redirector.js'
|
|
83
|
+
import { armJanitor, janitorStatus } from './janitor.js'
|
|
68
84
|
|
|
69
85
|
export const name = 'dsh-ris-ide'
|
|
70
86
|
/**
|
|
@@ -319,6 +335,21 @@ const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
|
|
|
319
335
|
const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
|
|
320
336
|
/** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
|
|
321
337
|
const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
|
|
338
|
+
/**
|
|
339
|
+
* Proxy rules + engine control.
|
|
340
|
+
* `GET` reports the stored rules (with per-row parse diagnostics) and whether the
|
|
341
|
+
* tunnel engine is up; `POST` saves the form; `/action` starts/stops the engine
|
|
342
|
+
* and writes the scoped git config.
|
|
343
|
+
*/
|
|
344
|
+
const PROXY_PATH = `${ROUTE_PREFIX}/proxy`
|
|
345
|
+
const PROXY_ACTION_PATH = `${ROUTE_PREFIX}/proxy/action`
|
|
346
|
+
/** Program picker for the rules table: this OS, plus Windows when reachable. */
|
|
347
|
+
const PROXY_PROGRAMS_PATH = `${ROUTE_PREFIX}/proxy/programs`
|
|
348
|
+
/**
|
|
349
|
+
* File browser for the rules table's 「固定程序」 source: a rule can name an
|
|
350
|
+
* executable that is not running yet, so it is proxied the moment it starts.
|
|
351
|
+
*/
|
|
352
|
+
const PROXY_BROWSE_PATH = `${ROUTE_PREFIX}/proxy/browse`
|
|
322
353
|
/** Workspace cache holding extracted sources / decompiled files. */
|
|
323
354
|
export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
|
|
324
355
|
/** Where the visual settings dialog persists the decompiler jar. */
|
|
@@ -419,6 +450,91 @@ export class TailError extends Error {
|
|
|
419
450
|
}
|
|
420
451
|
}
|
|
421
452
|
|
|
453
|
+
/**
|
|
454
|
+
* Process-wide lifecycle for the detached child services (proxy engine, redirector,
|
|
455
|
+
* git proxy, janitor).
|
|
456
|
+
*
|
|
457
|
+
* The child services outlive any one plugin effect: dsh disposes the fiber tree and
|
|
458
|
+
* only then calls `process.exit()`, so the synchronous `exit` listener is the last
|
|
459
|
+
* chance to stop them. That listener — and the detached janitor that covers
|
|
460
|
+
* SIGKILL/crash/closed-terminal — must NOT be removed by the effect teardown.
|
|
461
|
+
* Removing them was the Ctrl+C leak: the hook was already gone when `process.exit()`
|
|
462
|
+
* ran, so the engine kept routing with no UI left to stop it. Living here also makes
|
|
463
|
+
* a profile hot reload harmless: the listener is installed once per process and a
|
|
464
|
+
* heartbeat stopped by the teardown is simply restarted.
|
|
465
|
+
*/
|
|
466
|
+
let lifecycle = null
|
|
467
|
+
/** Engine left behind by a previous dsh process: `{ pid, owner, detectedAt } | null`. */
|
|
468
|
+
let inheritedEngine = null
|
|
469
|
+
|
|
470
|
+
/** Write the watchdog heartbeat now and keep writing it every 3 s. */
|
|
471
|
+
function startHeartbeat() {
|
|
472
|
+
try {
|
|
473
|
+
writeHeartbeat()
|
|
474
|
+
return setInterval(() => { try { writeHeartbeat() } catch { /* the next tick retries */ } }, 3000)
|
|
475
|
+
} catch {
|
|
476
|
+
return null
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Adopt an engine whose dsh is gone (`proxy.pid` alive, no watcher of ours).
|
|
482
|
+
*
|
|
483
|
+
* The pidfile is machine-wide, so an engine with a RUNNING janitor already has an
|
|
484
|
+
* owner on this machine: either another dsh (multi-instance case — leave it alone)
|
|
485
|
+
* or the watcher that is about to clean up after a crash. An engine with no watcher
|
|
486
|
+
* can only have survived the pre-fix teardown — take it over and report it, instead
|
|
487
|
+
* of letting it run invisibly or spawning a second one.
|
|
488
|
+
* @returns {{pid: number, owner: number, detectedAt: string} | null} the adopted engine.
|
|
489
|
+
*/
|
|
490
|
+
function adoptLeftoverEngine() {
|
|
491
|
+
try {
|
|
492
|
+
const pid = proxyPid()
|
|
493
|
+
if (pid === null || pid <= 0) {
|
|
494
|
+
inheritedEngine = null
|
|
495
|
+
return null
|
|
496
|
+
}
|
|
497
|
+
if (inheritedEngine !== null && inheritedEngine.pid === pid) return inheritedEngine
|
|
498
|
+
const watcher = janitorStatus()
|
|
499
|
+
if (watcher.owner === process.pid) {
|
|
500
|
+
// Ours already (e.g. a hot reload): not "left behind".
|
|
501
|
+
inheritedEngine = null
|
|
502
|
+
return null
|
|
503
|
+
}
|
|
504
|
+
if (watcher.running === true) return inheritedEngine
|
|
505
|
+
inheritedEngine = { pid, owner: watcher.owner, detectedAt: new Date().toISOString() }
|
|
506
|
+
return inheritedEngine
|
|
507
|
+
} catch {
|
|
508
|
+
return inheritedEngine
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Install (once per process) the exit hook, heartbeat and janitor, and adopt an
|
|
514
|
+
* engine left behind by a previous dsh process.
|
|
515
|
+
* @returns {{beat: NodeJS.Timeout | null, onExit: Function, owner: number}} the state.
|
|
516
|
+
*/
|
|
517
|
+
function ensureLifecycle() {
|
|
518
|
+
if (lifecycle !== null && lifecycle.owner === process.pid) {
|
|
519
|
+
if (lifecycle.beat === null) lifecycle.beat = startHeartbeat()
|
|
520
|
+
return lifecycle
|
|
521
|
+
}
|
|
522
|
+
adoptLeftoverEngine()
|
|
523
|
+
const onExit = () => {
|
|
524
|
+
try { stopProxySync() } catch { /* best effort while exiting */ }
|
|
525
|
+
try { stopRedirectorSync() } catch { /* best effort while exiting */ }
|
|
526
|
+
try { clearGitProxySync() } catch { /* best effort while exiting */ }
|
|
527
|
+
// Deliberately NO disarmJanitor(): the watcher must see our pid disappear and
|
|
528
|
+
// clean up itself — it is the only path that survives SIGKILL, a crash or a
|
|
529
|
+
// closed terminal, where no 'exit' listener runs at all.
|
|
530
|
+
}
|
|
531
|
+
process.once('exit', onExit)
|
|
532
|
+
lifecycle = { beat: startHeartbeat(), onExit, owner: process.pid }
|
|
533
|
+
// Idempotent for the same owner; replaces a watcher left watching a dead dsh.
|
|
534
|
+
try { armJanitor({ ownerPid: process.pid }) } catch { /* the watcher is optional */ }
|
|
535
|
+
return lifecycle
|
|
536
|
+
}
|
|
537
|
+
|
|
422
538
|
/**
|
|
423
539
|
* Register this plugin's two routes for its lifetime.
|
|
424
540
|
*
|
|
@@ -463,6 +579,30 @@ export function apply(ctx, config) {
|
|
|
463
579
|
}, LOG_ROTATE_INTERVAL_MS)
|
|
464
580
|
return () => clearInterval(timer)
|
|
465
581
|
}, 'dsh-ris-ide: log rotation')
|
|
582
|
+
// Child services belong to the PROCESS, not to this effect (see ensureLifecycle):
|
|
583
|
+
// dsh disposes the fiber tree first and calls process.exit() afterwards, so a
|
|
584
|
+
// teardown that removed the exit hook or disarmed the janitor left the detached
|
|
585
|
+
// engine alive with no UI to stop it.
|
|
586
|
+
ctx.effect(() => {
|
|
587
|
+
const adopted = adoptLeftoverEngine()
|
|
588
|
+
if (adopted !== null) {
|
|
589
|
+
try {
|
|
590
|
+
ctx.logger?.warn?.(`[dsh-ris-ide] 接管上一个会话留下的代理引擎(引擎 pid ${adopted.pid},原所有者 pid ${adopted.owner > 0 ? adopted.owner : '未知'})`)
|
|
591
|
+
} catch { /* logging is best effort */ }
|
|
592
|
+
}
|
|
593
|
+
const state = ensureLifecycle()
|
|
594
|
+
return () => {
|
|
595
|
+
// Only the heartbeat stops here: its stop is exactly what the elevated bridge
|
|
596
|
+
// watchdog waits for (20 s freshness), and the next apply (a profile hot
|
|
597
|
+
// reload) restarts it in the same second. The exit hook and the janitor stay
|
|
598
|
+
// armed — they are the guards for process.exit(), SIGKILL, a crash and a
|
|
599
|
+
// closed terminal.
|
|
600
|
+
if (state.beat !== null) {
|
|
601
|
+
clearInterval(state.beat)
|
|
602
|
+
state.beat = null
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}, 'dsh-ris-ide: stop child services on exit')
|
|
466
606
|
}
|
|
467
607
|
|
|
468
608
|
/**
|
|
@@ -654,6 +794,34 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
654
794
|
serveSafely(res, () => serveDebugSource(ctx, req, res, options))
|
|
655
795
|
return
|
|
656
796
|
}
|
|
797
|
+
if (pathname === PROXY_PATH) {
|
|
798
|
+
serveSafely(res, () => serveProxy(ctx, req, res, options))
|
|
799
|
+
return
|
|
800
|
+
}
|
|
801
|
+
if (pathname === PROXY_ACTION_PATH) {
|
|
802
|
+
if (method !== 'POST') {
|
|
803
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
|
|
804
|
+
return
|
|
805
|
+
}
|
|
806
|
+
serveSafely(res, () => serveProxyAction(ctx, req, res, options))
|
|
807
|
+
return
|
|
808
|
+
}
|
|
809
|
+
if (pathname === PROXY_PROGRAMS_PATH) {
|
|
810
|
+
if (method !== 'GET') {
|
|
811
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
812
|
+
return
|
|
813
|
+
}
|
|
814
|
+
serveSafely(res, () => serveProxyPrograms(ctx, req, res, options))
|
|
815
|
+
return
|
|
816
|
+
}
|
|
817
|
+
if (pathname === PROXY_BROWSE_PATH) {
|
|
818
|
+
if (method !== 'GET') {
|
|
819
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
820
|
+
return
|
|
821
|
+
}
|
|
822
|
+
serveSafely(res, () => serveProxyBrowse(ctx, req, res, options))
|
|
823
|
+
return
|
|
824
|
+
}
|
|
657
825
|
if (pathname === SETTINGS_PATH) {
|
|
658
826
|
serveSafely(res, () => serveSettings(ctx, req, res, options))
|
|
659
827
|
return
|
|
@@ -5165,6 +5333,785 @@ async function serveSettings(ctx, req, res, options) {
|
|
|
5165
5333
|
}
|
|
5166
5334
|
}
|
|
5167
5335
|
|
|
5336
|
+
|
|
5337
|
+
/**
|
|
5338
|
+
* Short, stable fingerprint of the machine-wide table.
|
|
5339
|
+
*
|
|
5340
|
+
* The dialog posts the WHOLE table, so two windows (or two people) editing at once
|
|
5341
|
+
* would silently overwrite each other: whoever saves last wins and the other row is
|
|
5342
|
+
* gone with no error. The fingerprint travels with the write, so a stale payload is
|
|
5343
|
+
* refused (409) instead of applied.
|
|
5344
|
+
* @param config - a normalised proxy config.
|
|
5345
|
+
* @returns a 12-char hex fingerprint of everything the dialog can change.
|
|
5346
|
+
*/
|
|
5347
|
+
export function configRevision(config) {
|
|
5348
|
+
const view = {
|
|
5349
|
+
socks: [String(config?.socks?.host ?? ''), Number(config?.socks?.port ?? 0)],
|
|
5350
|
+
listenPort: Number(config?.listenPort ?? 0),
|
|
5351
|
+
rules: (Array.isArray(config?.rules) ? config.rules : []).map((rule) => [
|
|
5352
|
+
String(rule.id ?? ''),
|
|
5353
|
+
String(rule.program ?? ''),
|
|
5354
|
+
String(rule.hosts ?? ''),
|
|
5355
|
+
String(rule.ports ?? ''),
|
|
5356
|
+
rule.enabled === true,
|
|
5357
|
+
rule.shadow === true,
|
|
5358
|
+
String(rule.source ?? ''),
|
|
5359
|
+
]),
|
|
5360
|
+
}
|
|
5361
|
+
return createHash('sha1').update(JSON.stringify(view)).digest('hex').slice(0, 12)
|
|
5362
|
+
}
|
|
5363
|
+
|
|
5364
|
+
/**
|
|
5365
|
+
* One stored rule, decorated with what the engine will actually make of it: the
|
|
5366
|
+
* parsed host patterns / ports plus the fragments it rejected, so the dialog can
|
|
5367
|
+
* flag a typo instead of silently dropping a destination.
|
|
5368
|
+
* @param rule - a rule from the normalised config.
|
|
5369
|
+
* @returns the rule plus `hostsParsed|hostsInvalid|portsParsed|portsInvalid`.
|
|
5370
|
+
*/
|
|
5371
|
+
function decorateProxyRule(rule) {
|
|
5372
|
+
const hosts = parseHostSpec(rule.hosts)
|
|
5373
|
+
const ports = parsePortSpec(rule.ports)
|
|
5374
|
+
// A shadow is a loopback LISTENER, so it needs ports it can actually bind: `*`
|
|
5375
|
+
// parses to port 0 ("any port"), which must not make a rule sweepable here.
|
|
5376
|
+
const bindable = ports.ports.filter((port) => port > 0)
|
|
5377
|
+
const shadowable = hosts.patterns.length > 0 && hosts.patterns.every((pattern) => /^\d{1,3}(\.\d{1,3}){3}$/.test(pattern)) && bindable.length > 0
|
|
5378
|
+
const socksCapable = isSocksCapableProgram(rule.program)
|
|
5379
|
+
const verdict = ruleEffectiveness(rule)
|
|
5380
|
+
return Object.assign({}, rule, {
|
|
5381
|
+
hostsParsed: hosts.patterns,
|
|
5382
|
+
hostsInvalid: hosts.invalid,
|
|
5383
|
+
portsParsed: ports.ports,
|
|
5384
|
+
portsInvalid: ports.invalid,
|
|
5385
|
+
// What the rule can do is NOT the same for both mechanisms: only a literal
|
|
5386
|
+
// IPv4 destination can be pre-bound on a loopback port, and a wildcard can
|
|
5387
|
+
// only be matched per connection (the CONNECT proxy).
|
|
5388
|
+
shadowable,
|
|
5389
|
+
// Which mechanism this program actually needs — the dialog shows it and the
|
|
5390
|
+
// engine defaults the mapping flag from it (SOCKS-aware programs need none,
|
|
5391
|
+
// everything else can only reach the tunnel through a mapped port).
|
|
5392
|
+
socksCapable,
|
|
5393
|
+
autoShadow: shadowable && !socksCapable,
|
|
5394
|
+
// A rule applies only when enabled AND program/IP/port are all explicit
|
|
5395
|
+
// (`*` spells "everything"); the dialog marks the others instead of letting a
|
|
5396
|
+
// half-written row look active.
|
|
5397
|
+
effective: verdict.effective,
|
|
5398
|
+
ineffectiveReason: verdict.reason,
|
|
5399
|
+
// The rule table is machine-wide (ProxyBridge hooks the kernel and matches
|
|
5400
|
+
// processes), so a row's workspace is provenance only: the dialog shows it
|
|
5401
|
+
// as「来源」 and never treats it as a boundary.
|
|
5402
|
+
origin: rule.workspace === '' ? '' : basename(rule.workspace),
|
|
5403
|
+
})
|
|
5404
|
+
}
|
|
5405
|
+
|
|
5406
|
+
/** Companion-plugin hints: `dsh-ris-yds` assists YonBIP/YMS development (local
|
|
5407
|
+
* runtime, intranet access, development config). Only the capabilities are
|
|
5408
|
+
* named here — never its internals, and never the tools it happens to patch.
|
|
5409
|
+
* We only RECOMMEND it when the workspace really looks like a YMS project: the
|
|
5410
|
+
* two plugins stay usable standalone, so this must never turn into a
|
|
5411
|
+
* requirement (and it must never guess on a plain Java/Vue repo). */
|
|
5412
|
+
function detectCompanionPlugin(cwd) {
|
|
5413
|
+
const evidence = []
|
|
5414
|
+
try {
|
|
5415
|
+
if (existsSync(join(cwd, 'yms-home'))) evidence.push('yms-home/')
|
|
5416
|
+
if (existsSync(join(cwd, '.dsh-ris-yds'))) evidence.push('.dsh-ris-yds/')
|
|
5417
|
+
if (evidence.length === 0) {
|
|
5418
|
+
const settings = join(cwd, '.vscode', 'settings.json')
|
|
5419
|
+
if (existsSync(settings) && readFileSync(settings, 'utf8').includes('"yds.')) {
|
|
5420
|
+
evidence.push('.vscode/settings.json (yds.*)')
|
|
5421
|
+
}
|
|
5422
|
+
}
|
|
5423
|
+
} catch {
|
|
5424
|
+
// Detection is best effort: an unreadable workspace simply gets no hint.
|
|
5425
|
+
}
|
|
5426
|
+
if (evidence.length === 0) return null
|
|
5427
|
+
return {
|
|
5428
|
+
plugin: 'dsh-ris-yds',
|
|
5429
|
+
detected: evidence.join(', '),
|
|
5430
|
+
hint: '检测到 YonBIP/YMS 工程:dsh-ris-yds 提供本地运行 YMS、访问内网资源、准备开发配置等辅助开发能力(可选,不装不影响本插件)。',
|
|
5431
|
+
}
|
|
5432
|
+
}
|
|
5433
|
+
|
|
5434
|
+
/**
|
|
5435
|
+
* The whole proxy state the dialog needs, in ONE round trip: rules (decorated),
|
|
5436
|
+
* upstream address, engine state, and the scoped git entry it would write.
|
|
5437
|
+
* @param cwd - workspace directory.
|
|
5438
|
+
* @param gitHost - optional host to narrow the git entry to.
|
|
5439
|
+
* @returns a JSON-safe view.
|
|
5440
|
+
*/
|
|
5441
|
+
async function proxyView(cwd, gitHost) {
|
|
5442
|
+
const status = await proxyStatus(cwd)
|
|
5443
|
+
const allow = allowList(status.config)
|
|
5444
|
+
const git = gitProxyPlan(status.config, { host: gitHost })
|
|
5445
|
+
// One machine, one table: every stored rule is shown, whoever contributed it.
|
|
5446
|
+
// EXCEPT the loopback mapping rows dsh-ris-yds keeps as a fallback: those are an
|
|
5447
|
+
// implementation detail of "no system-level interception", not something the
|
|
5448
|
+
// user configures, so they never reach the dialog (they stay in the file, which
|
|
5449
|
+
// is what the engine and the redirector profile are built from).
|
|
5450
|
+
const own = status.config.rules.filter((rule) => !(rule.source === 'yds' && rule.shadow === true))
|
|
5451
|
+
// Templates only where the machine has no row for that program yet, so the
|
|
5452
|
+
// dialog off a fresh workspace still shows the four starter rows.
|
|
5453
|
+
const covered = new Set(own.map((rule) => programKey(rule.program)))
|
|
5454
|
+
const templates = autoRules(cwd).filter((rule) => !covered.has(programKey(rule.program)))
|
|
5455
|
+
const watcher = janitorStatus()
|
|
5456
|
+
// An engine adopted from a PREVIOUS dsh process (see adoptLeftoverEngine): the
|
|
5457
|
+
// dialog shows a takeover banner with a one-click stop instead of pretending this
|
|
5458
|
+
// session started it. The flag is dropped as soon as that engine is gone.
|
|
5459
|
+
const inherited = inheritedEngine !== null && inheritedEngine.pid === status.pid ? inheritedEngine : null
|
|
5460
|
+
return {
|
|
5461
|
+
ok: true,
|
|
5462
|
+
side: engineSide(),
|
|
5463
|
+
// The dialog sends this back with its save, so a table edited in another window
|
|
5464
|
+
// is refused instead of silently overwritten.
|
|
5465
|
+
revision: configRevision(status.config),
|
|
5466
|
+
// ONE engine and ONE config per machine: the path is not workspace-derived.
|
|
5467
|
+
configPath: proxyConfigPath(),
|
|
5468
|
+
home: proxyHomeDir(),
|
|
5469
|
+
shared: true,
|
|
5470
|
+
workspace: cwd,
|
|
5471
|
+
socks: status.config.socks,
|
|
5472
|
+
listenPort: status.config.listenPort,
|
|
5473
|
+
rules: (await Promise.all(status.config.rules.map(async (rule) => {
|
|
5474
|
+
const decorated = decorateProxyRule(rule)
|
|
5475
|
+
// A rule can start its program itself (that is the only way to inject the
|
|
5476
|
+
// tunnel into something we did not launch), so the row shows whether it is
|
|
5477
|
+
// up and where its log is.
|
|
5478
|
+
const service = await readService(proxyRunLogPath(cwd, rule.id)).catch(() => undefined)
|
|
5479
|
+
return Object.assign(decorated, {
|
|
5480
|
+
runnable: decorated.socksCapable && String(rule.program ?? '').trim() !== '',
|
|
5481
|
+
runLogPath: proxyRunLogPath(cwd, rule.id),
|
|
5482
|
+
run: service === undefined ? null : { pid: service.pid, alive: service.alive },
|
|
5483
|
+
})
|
|
5484
|
+
// `template: true` marks a starter row the user has not saved yet: the dialog
|
|
5485
|
+
// shows it, but must NOT write it back (it would turn a suggestion into a stored
|
|
5486
|
+
// rule and the row would then live forever in the shared table).
|
|
5487
|
+
}))).concat(templates.map((rule) => Object.assign(decorateProxyRule(rule), { template: true }))),
|
|
5488
|
+
running: status.running,
|
|
5489
|
+
pid: status.pid,
|
|
5490
|
+
listen: status.listen,
|
|
5491
|
+
logPath: status.logPath,
|
|
5492
|
+
socksUrl: status.socksUrl,
|
|
5493
|
+
allow,
|
|
5494
|
+
git,
|
|
5495
|
+
// ProxyBridge is the PRIMARY path (kernel hook, matches by process name, so
|
|
5496
|
+
// it covers programs we never launched); the engine's loopback mappings and
|
|
5497
|
+
// the spawn-time injection remain as the fallback when it is not running.
|
|
5498
|
+
redirector: Object.assign(redirectorStatusCached(), {
|
|
5499
|
+
// What the CLI would be told to do, so the dialog can show the exact
|
|
5500
|
+
// command instead of asking the user to assemble one.
|
|
5501
|
+
rules: buildProfile(status.config).rules.length,
|
|
5502
|
+
}),
|
|
5503
|
+
// Watchdog state: it is what removes the layers if dsh itself is killed.
|
|
5504
|
+
janitor: watcher,
|
|
5505
|
+
// Who owns the child services right now (0 = no watcher state at all).
|
|
5506
|
+
owner: watcher.owner,
|
|
5507
|
+
// Takeover of a leftover engine (pid + the dsh that started it, 0 = unknown).
|
|
5508
|
+
inherited: inherited !== null,
|
|
5509
|
+
inheritedPid: inherited === null ? 0 : inherited.pid,
|
|
5510
|
+
inheritedFrom: inherited === null ? 0 : inherited.owner,
|
|
5511
|
+
inheritedSince: inherited === null ? '' : inherited.detectedAt,
|
|
5512
|
+
}
|
|
5513
|
+
}
|
|
5514
|
+
|
|
5515
|
+
/**
|
|
5516
|
+
* Where a rule's 启动/停止 button keeps its log.
|
|
5517
|
+
*
|
|
5518
|
+
* A separate directory, not `.dsh-ris-ide/logs`: those logs are scanned as panel
|
|
5519
|
+
* rows, and a program we started only to proxy it should not appear as a third
|
|
5520
|
+
* copy of itself in the program list.
|
|
5521
|
+
* @param cwd - workspace the rule belongs to.
|
|
5522
|
+
* @param ruleId - the rule's id (already validated as a plain string).
|
|
5523
|
+
* @returns absolute log path.
|
|
5524
|
+
*/
|
|
5525
|
+
function proxyRunLogPath(cwd, ruleId) {
|
|
5526
|
+
const slug = String(ruleId).replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 80)
|
|
5527
|
+
return join(cwd, '.dsh-ris-ide', 'proxy-run', `${slug}.log`)
|
|
5528
|
+
}
|
|
5529
|
+
|
|
5530
|
+
/**
|
|
5531
|
+
* Build the program row `startProgram` needs, out of one rule.
|
|
5532
|
+
*
|
|
5533
|
+
* The row is synthesised rather than scanned: the dialog's rule is the source of
|
|
5534
|
+
* truth (it names an absolute executable or a bare program on PATH), and the
|
|
5535
|
+
* start path only has to know how to run it under the wrapper.
|
|
5536
|
+
* @param cwd - workspace (log location + default working directory).
|
|
5537
|
+
* @param rule - one decorated proxy rule.
|
|
5538
|
+
* @returns the program row.
|
|
5539
|
+
*/
|
|
5540
|
+
function proxyRunProgram(cwd, rule) {
|
|
5541
|
+
const logPath = proxyRunLogPath(cwd, rule.id)
|
|
5542
|
+
const command = String(rule.program ?? '').trim()
|
|
5543
|
+
return {
|
|
5544
|
+
id: `proxy-run:${rule.id}`,
|
|
5545
|
+
name: programKey(command) || 'program',
|
|
5546
|
+
dir: cwd,
|
|
5547
|
+
// Absolute paths and bare names both work; quote so a path with spaces stays
|
|
5548
|
+
// one argument for the shell wrapper.
|
|
5549
|
+
startCommand: quoteShell(command),
|
|
5550
|
+
logName: basename(logPath, '.log'),
|
|
5551
|
+
logPath,
|
|
5552
|
+
stopGraceMs: 5000,
|
|
5553
|
+
running: null,
|
|
5554
|
+
kind: 'custom',
|
|
5555
|
+
}
|
|
5556
|
+
}
|
|
5557
|
+
|
|
5558
|
+
/** `GET` reads the proxy state, `POST` validates + saves the form. */
|
|
5559
|
+
async function serveProxy(ctx, req, res, options) {
|
|
5560
|
+
try {
|
|
5561
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
5562
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
5563
|
+
const method = req.method ?? 'GET'
|
|
5564
|
+
if (method === 'POST') {
|
|
5565
|
+
const body = await readJsonBody(req)
|
|
5566
|
+
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
5567
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5568
|
+
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
5569
|
+
// The dialog shows the WHOLE machine-wide table, so its payload is
|
|
5570
|
+
// authoritative for the rows a human owns (source user/auto): a row the
|
|
5571
|
+
// payload no longer carries was deleted. Driven rows (source yds) are owned
|
|
5572
|
+
// by the bridge, which upserts them by id and retires them itself.
|
|
5573
|
+
const incoming = body.config !== null && typeof body.config === 'object' ? body.config : {}
|
|
5574
|
+
const stored = readProxyConfig(cwd)
|
|
5575
|
+
// Optimistic concurrency: the payload names the table it was rendered from.
|
|
5576
|
+
// An empty/absent revision is accepted (the CLI writes without one), but a
|
|
5577
|
+
// MISMATCH means someone else changed the table in between — refuse and hand
|
|
5578
|
+
// the current view back, so the dialog reloads instead of dropping their rows.
|
|
5579
|
+
const baseRevision = typeof body.revision === 'string' ? body.revision.trim() : ''
|
|
5580
|
+
const currentRevision = configRevision(stored)
|
|
5581
|
+
if (baseRevision !== '' && baseRevision !== currentRevision) {
|
|
5582
|
+
const view = await proxyView(cwd)
|
|
5583
|
+
writeJson(res, 409, {
|
|
5584
|
+
ok: false,
|
|
5585
|
+
conflict: true,
|
|
5586
|
+
code: 'conflict',
|
|
5587
|
+
message: '规则表已在别处被修改,本次改动未写入',
|
|
5588
|
+
revision: currentRevision,
|
|
5589
|
+
view,
|
|
5590
|
+
})
|
|
5591
|
+
return
|
|
5592
|
+
}
|
|
5593
|
+
const rows = Array.isArray(incoming.rules)
|
|
5594
|
+
? incoming.rules
|
|
5595
|
+
.filter((rule) => rule !== null && typeof rule === 'object')
|
|
5596
|
+
.map((rule) => Object.assign({}, rule, { workspace: rule.workspace ?? cwd }))
|
|
5597
|
+
: []
|
|
5598
|
+
const keptIds = new Set(rows.map((rule) => String(rule.id ?? '')))
|
|
5599
|
+
const retired = stored.rules
|
|
5600
|
+
.filter((rule) => rule.source !== 'yds' && !keptIds.has(rule.id))
|
|
5601
|
+
.map((rule) => rule.id)
|
|
5602
|
+
const written = mergeConfigs(
|
|
5603
|
+
Object.assign({}, stored, { rules: stored.rules.filter((rule) => !retired.includes(rule.id)) }),
|
|
5604
|
+
{ socks: incoming.socks, listenPort: incoming.listenPort, rules: rows, workspace: cwd },
|
|
5605
|
+
)
|
|
5606
|
+
writeProxyConfig(cwd, written)
|
|
5607
|
+
// Apply without a manual restart: our own engine watches proxy.json and
|
|
5608
|
+
// swaps its allow-list/listeners in place; ProxyBridge reads its profile only
|
|
5609
|
+
// at start, so the elevated watchdog restarts just that process (no UAC, the
|
|
5610
|
+
// dialog never has to ask the user to stop/start).
|
|
5611
|
+
const bridge = redirectorStatusCached()
|
|
5612
|
+
let reloadNote = ''
|
|
5613
|
+
if (bridge.running === true) {
|
|
5614
|
+
// ONE call does the whole job: ProxyBridge reads its profile only at start,
|
|
5615
|
+
// so a reload that does not rewrite the profile would relaunch the OLD rules
|
|
5616
|
+
// and still report success (that was B3). The helper writes first, then
|
|
5617
|
+
// restarts, and only claims a side was reloaded when it saw the new pid.
|
|
5618
|
+
try {
|
|
5619
|
+
const reload = await reloadRedirectorsWithProfile(cwd, { sides: ['windows', 'local'] })
|
|
5620
|
+
const done = Array.isArray(reload.reloaded) ? reload.reloaded : []
|
|
5621
|
+
const skipped = Array.isArray(reload.skipped) ? reload.skipped : []
|
|
5622
|
+
reloadNote = done.length > 0
|
|
5623
|
+
? '系统层拦截已按新规则自动重启'
|
|
5624
|
+
: `系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`
|
|
5625
|
+
} catch (error) {
|
|
5626
|
+
reloadNote = `系统层拦截未重载:${error?.message ?? error}`
|
|
5627
|
+
}
|
|
5628
|
+
}
|
|
5629
|
+
const view = await proxyView(cwd, typeof body.gitHost === 'string' ? body.gitHost : undefined)
|
|
5630
|
+
writeJson(res, 200, Object.assign({}, view, { reloadNote }))
|
|
5631
|
+
return
|
|
5632
|
+
}
|
|
5633
|
+
if (method !== 'GET') throw new TailError('method-not-allowed', 'GET or POST', 405)
|
|
5634
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
5635
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5636
|
+
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
|
|
5637
|
+
writeJson(res, 200, await proxyView(cwd, url.searchParams.get('gitHost') ?? undefined))
|
|
5638
|
+
} catch (error) {
|
|
5639
|
+
writeTailError(res, error)
|
|
5640
|
+
}
|
|
5641
|
+
}
|
|
5642
|
+
|
|
5643
|
+
/**
|
|
5644
|
+
* Where the git proxy we wrote is remembered.
|
|
5645
|
+
*
|
|
5646
|
+
* `stop` (and the exit hook) must undo EXACTLY what `start` wrote: the key is
|
|
5647
|
+
* host-scoped when the repo has an origin, global otherwise, and clearing the
|
|
5648
|
+
* wrong one would either leave a dangling proxy or stomp the user's own setting.
|
|
5649
|
+
* @returns {string} absolute path of the state file.
|
|
5650
|
+
*/
|
|
5651
|
+
function gitProxyStatePath() {
|
|
5652
|
+
return join(proxyHomeDir(), 'git-proxy.json')
|
|
5653
|
+
}
|
|
5654
|
+
|
|
5655
|
+
/** @returns {{key: string, host: string}} the entry start wrote, or empty strings. */
|
|
5656
|
+
function readGitProxyState() {
|
|
5657
|
+
try {
|
|
5658
|
+
const raw = JSON.parse(readFileSync(gitProxyStatePath(), 'utf8'))
|
|
5659
|
+
return {
|
|
5660
|
+
key: typeof raw?.key === 'string' ? raw.key : '',
|
|
5661
|
+
host: typeof raw?.host === 'string' ? raw.host : '',
|
|
5662
|
+
}
|
|
5663
|
+
} catch {
|
|
5664
|
+
return { key: '', host: '' }
|
|
5665
|
+
}
|
|
5666
|
+
}
|
|
5667
|
+
|
|
5668
|
+
/**
|
|
5669
|
+
* Remember (or forget) the git proxy entry.
|
|
5670
|
+
* @param {{key: string, host: string}|null} state - null clears the file.
|
|
5671
|
+
*/
|
|
5672
|
+
function writeGitProxyState(state) {
|
|
5673
|
+
const path = gitProxyStatePath()
|
|
5674
|
+
if (state === null) {
|
|
5675
|
+
try { rmSync(path, { force: true }) } catch { /* nothing to clear */ }
|
|
5676
|
+
return
|
|
5677
|
+
}
|
|
5678
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
5679
|
+
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
|
|
5680
|
+
}
|
|
5681
|
+
|
|
5682
|
+
/**
|
|
5683
|
+
* Host of the workspace's `origin` remote, so the proxy entry is scoped to one
|
|
5684
|
+
* server instead of being a machine-wide `http.proxy`.
|
|
5685
|
+
* @param {string} cwd - workspace root.
|
|
5686
|
+
* @returns {string} hostname, or '' when there is no readable remote.
|
|
5687
|
+
*/
|
|
5688
|
+
function gitOriginHost(cwd) {
|
|
5689
|
+
const out = spawnSync('git', ['-C', cwd, 'config', '--get', 'remote.origin.url'], {
|
|
5690
|
+
encoding: 'utf8', windowsHide: true, timeout: 4000,
|
|
5691
|
+
})
|
|
5692
|
+
if (out.status !== 0 || typeof out.stdout !== 'string') return ''
|
|
5693
|
+
try { return new URL(out.stdout.trim()).host } catch { return '' }
|
|
5694
|
+
}
|
|
5695
|
+
|
|
5696
|
+
/**
|
|
5697
|
+
* Host of the enabled `git` rule, if the table declares one.
|
|
5698
|
+
*
|
|
5699
|
+
* This is the user's own statement of "git goes to this server" (yds writes it
|
|
5700
|
+
* from `git.url`), so it outranks the workspace's `origin` — a mirror or a
|
|
5701
|
+
* proxy-fronted clone must not decide where git may tunnel to.
|
|
5702
|
+
* @param {string} cwd - workspace root (only used to find the shared config).
|
|
5703
|
+
* @returns {string} the first host pattern, or ''.
|
|
5704
|
+
*/
|
|
5705
|
+
function gitRuleHost(cwd) {
|
|
5706
|
+
const rules = readProxyConfig(cwd).rules
|
|
5707
|
+
for (const rule of rules) {
|
|
5708
|
+
if (rule.enabled !== true) continue
|
|
5709
|
+
if (programKey(rule.program) !== 'git') continue
|
|
5710
|
+
const first = String(rule.hosts ?? '').split(',')[0].trim()
|
|
5711
|
+
if (first !== '') return first
|
|
5712
|
+
}
|
|
5713
|
+
return ''
|
|
5714
|
+
}
|
|
5715
|
+
|
|
5716
|
+
/**
|
|
5717
|
+
* Write or clear the git proxy that belongs to the running tunnel.
|
|
5718
|
+
*
|
|
5719
|
+
* git reads this from its own config, so a plain `git` command in any terminal —
|
|
5720
|
+
* and the dsh-git plugin — goes through the tunnel without a per-command flag.
|
|
5721
|
+
* @param {{cwd: string, host?: string, enabled: boolean}} options - target and direction.
|
|
5722
|
+
* @returns {Promise<{ok: boolean, key?: string, error?: string}>} outcome.
|
|
5723
|
+
*/
|
|
5724
|
+
async function syncGitProxy({ cwd, host, enabled }) {
|
|
5725
|
+
const previous = readGitProxyState()
|
|
5726
|
+
if (enabled !== true) {
|
|
5727
|
+
const key = previous.key
|
|
5728
|
+
if (key === '') return { ok: true, key: '' }
|
|
5729
|
+
const cleared = await runGitConfig(['--unset', key])
|
|
5730
|
+
const windowsCleared = runWindowsGitConfig(['--unset', key])
|
|
5731
|
+
writeGitProxyState(null)
|
|
5732
|
+
return { ok: true, key, cleared: cleared.ok === true, windowsCleared: windowsCleared.ok === true }
|
|
5733
|
+
}
|
|
5734
|
+
// Precedence: an explicit host, then the table's own git rule, then whatever we
|
|
5735
|
+
// wrote last time, and only then the repo's origin (a mirror is not a target).
|
|
5736
|
+
const target = (typeof host === 'string' && host !== '')
|
|
5737
|
+
? host
|
|
5738
|
+
: (gitRuleHost(cwd) || (previous.host !== '' ? previous.host : gitOriginHost(cwd)))
|
|
5739
|
+
if (target === '') return { ok: false, error: '没有 git 规则也没有 origin,无法确定代理作用域', key: '' }
|
|
5740
|
+
// A stale entry for another host would keep a dead proxy alive for that remote.
|
|
5741
|
+
if (previous.key !== '' && previous.host !== '' && previous.host !== target) {
|
|
5742
|
+
await runGitConfig(['--unset', previous.key])
|
|
5743
|
+
writeGitProxyState(null)
|
|
5744
|
+
}
|
|
5745
|
+
const plan = gitProxyPlan(readProxyConfig(cwd), { host: target, enabled: true })
|
|
5746
|
+
if (plan.value === '') return { ok: false, error: '没有可用的 SOCKS 地址', key: plan.key }
|
|
5747
|
+
const written = await runGitConfig([plan.key, plan.value])
|
|
5748
|
+
if (written.ok !== true) return { ok: false, error: written.error, key: plan.key }
|
|
5749
|
+
// The Windows-side git reads its own config file AND cannot resolve the internal
|
|
5750
|
+
// host (its DNS knows nothing about gitlab.hanslaser.com), so socks5h has to be in
|
|
5751
|
+
// that file too — otherwise YonCode's git fails before any interception can happen.
|
|
5752
|
+
const windows = runWindowsGitConfig([plan.key, plan.value])
|
|
5753
|
+
writeGitProxyState({ key: plan.key, host: target, windows: windows.ok === true })
|
|
5754
|
+
return { ok: true, key: plan.key, host: target, windows }
|
|
5755
|
+
}
|
|
5756
|
+
|
|
5757
|
+
/** Synchronous git-proxy undo for the exit hook, which cannot await anything. */
|
|
5758
|
+
function clearGitProxySync() {
|
|
5759
|
+
const { key } = readGitProxyState()
|
|
5760
|
+
if (key === '') return
|
|
5761
|
+
try { spawnSync('git', ['config', '--global', '--unset', key], { windowsHide: true, timeout: 4000 }) } catch { /* best effort */ }
|
|
5762
|
+
// Same undo on the Windows side: leaving a dead socks address there breaks git for
|
|
5763
|
+
// every Windows tool until someone notices.
|
|
5764
|
+
try { runWindowsGitConfig(['--unset', key]) } catch { /* best effort */ }
|
|
5765
|
+
writeGitProxyState(null)
|
|
5766
|
+
}
|
|
5767
|
+
|
|
5768
|
+
/** Run one `git config --global` mutation; a missing git is a reported no-op. */
|
|
5769
|
+
function runGitConfig(args) {
|
|
5770
|
+
return new Promise((resolvePromise) => {
|
|
5771
|
+
const child = spawn('git', ['config', '--global', ...args], { windowsHide: true })
|
|
5772
|
+
let stderr = ''
|
|
5773
|
+
let settled = false
|
|
5774
|
+
const done = (result) => { if (!settled) { settled = true; resolvePromise(result) } }
|
|
5775
|
+
child.stderr?.on('data', (chunk) => { if (stderr.length < 4096) stderr += chunk.toString('utf8') })
|
|
5776
|
+
child.on('error', (error) => done({ ok: false, error: isMissingExecutable(error) ? '本机没有安装 git' : String(error?.message ?? error) }))
|
|
5777
|
+
child.on('close', (code) => done(code === 0 ? { ok: true } : { ok: false, error: stderr.trim() || `git exited with ${code}` }))
|
|
5778
|
+
})
|
|
5779
|
+
}
|
|
5780
|
+
|
|
5781
|
+
/** Start/stop the engine and write/clear the scoped git proxy entry. */
|
|
5782
|
+
async function serveProxyAction(ctx, req, res, options) {
|
|
5783
|
+
try {
|
|
5784
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
5785
|
+
const body = await readJsonBody(req)
|
|
5786
|
+
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
5787
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5788
|
+
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
5789
|
+
const action = typeof body.action === 'string' ? body.action : 'status'
|
|
5790
|
+
const gitHost = typeof body.gitHost === 'string' ? body.gitHost : undefined
|
|
5791
|
+
let result
|
|
5792
|
+
if (action === 'start') {
|
|
5793
|
+
// One button, three layers: engine (spawned children) + system-level
|
|
5794
|
+
// interception (everything else, UAC/root is the expected prompt) + the git
|
|
5795
|
+
// config entry (so a plain `git` and dsh-git inherit the tunnel). Stopping
|
|
5796
|
+
// undoes all three, and so does the host exit hook.
|
|
5797
|
+
const engine = await startProxy(cwd)
|
|
5798
|
+
const redirector = await startRedirectors()
|
|
5799
|
+
const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
|
|
5800
|
+
if (engine.ok === true) inheritedEngine = null
|
|
5801
|
+
result = Object.assign({}, engine, { redirector, git })
|
|
5802
|
+
} else if (action === 'stop') {
|
|
5803
|
+
const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
|
|
5804
|
+
const redirector = await stopRedirector()
|
|
5805
|
+
const stopped = await stopProxy(cwd)
|
|
5806
|
+
// The banner must not come back once the adopted engine is really gone.
|
|
5807
|
+
if (proxyPid() === null) inheritedEngine = null
|
|
5808
|
+
result = Object.assign({}, stopped, { redirector, git })
|
|
5809
|
+
} else if (action === 'git-on' || action === 'git-off') {
|
|
5810
|
+
const plan = gitProxyPlan(readProxyConfig(cwd), { host: gitHost, enabled: action === 'git-on' })
|
|
5811
|
+
result = action === 'git-on'
|
|
5812
|
+
? Object.assign({ key: plan.key, value: plan.value }, await runGitConfig([plan.key, plan.value]))
|
|
5813
|
+
: Object.assign({ key: plan.key }, await runGitConfig(['--unset', plan.key]))
|
|
5814
|
+
} else if (action === 'run' || action === 'run-stop') {
|
|
5815
|
+
// Start/stop the rule's program OURSELVES: injection only works on a child
|
|
5816
|
+
// process, so "配置好规则 → 点启动" is the only way to proxy a program that
|
|
5817
|
+
// the user would otherwise launch by hand.
|
|
5818
|
+
const ruleId = typeof body.ruleId === 'string' ? body.ruleId : ''
|
|
5819
|
+
if (ruleId === '') throw new TailError('bad-request', 'ruleId is required', 400)
|
|
5820
|
+
const rule = readProxyConfig(cwd).rules.find((item) => item.id === ruleId)
|
|
5821
|
+
if (rule === undefined) throw new TailError('bad-request', `没有规则 ${ruleId}`, 404)
|
|
5822
|
+
const program = proxyRunProgram(cwd, rule)
|
|
5823
|
+
if (action === 'run-stop') {
|
|
5824
|
+
result = await stopLogPath(program.logPath, options?.stopGraceMs ?? DEFAULT_STOP_GRACE_MS)
|
|
5825
|
+
} else {
|
|
5826
|
+
if (rule.enabled !== true) throw new TailError('bad-request', '规则未启用,启动后不会走代理', 400)
|
|
5827
|
+
if (String(rule.program ?? '').trim() === '') throw new TailError('bad-request', '规则还没选程序', 400)
|
|
5828
|
+
if (!isSocksCapableProgram(rule.program)) throw new TailError('bad-request', `${programKey(rule.program)} 不支持 SOCKS,只能走 127.0.0.1 映射`, 400)
|
|
5829
|
+
const started = await startProgram(cwd, dirname(program.logPath), program, options)
|
|
5830
|
+
result = { started: started.alreadyRunning !== true, program: started.program?.logPath ?? program.logPath }
|
|
5831
|
+
}
|
|
5832
|
+
} else if (action === 'redirector-sync') {
|
|
5833
|
+
// Export the machine-wide table as a ProxyBridge profile and report the
|
|
5834
|
+
// exact command. Starting it needs root/UAC, which a web route cannot ask
|
|
5835
|
+
// for, so the command is returned for the user (or an agent with rights).
|
|
5836
|
+
result = await syncRedirector(cwd, { start: false })
|
|
5837
|
+
} else if (action === 'redirector-start') {
|
|
5838
|
+
result = await syncRedirector(cwd, { start: true })
|
|
5839
|
+
} else if (action === 'redirector-stop') {
|
|
5840
|
+
result = await stopRedirector()
|
|
5841
|
+
} else if (action !== 'status') {
|
|
5842
|
+
throw new TailError('bad-request', `unknown proxy action "${action}"`, 400)
|
|
5843
|
+
}
|
|
5844
|
+
writeJson(res, 200, Object.assign({ ok: true, action, result }, await proxyView(cwd, gitHost)))
|
|
5845
|
+
} catch (error) {
|
|
5846
|
+
writeTailError(res, error)
|
|
5847
|
+
}
|
|
5848
|
+
}
|
|
5849
|
+
|
|
5850
|
+
/**
|
|
5851
|
+
* Programs the rule table offers in its picker.
|
|
5852
|
+
*
|
|
5853
|
+
* Deliberately SOCKS-aware programs only: a rule other than these cannot be
|
|
5854
|
+
* proxied by injection (its only route is a 127.0.0.1 listener, which needs no
|
|
5855
|
+
* picker entry), so offering them would promise something we cannot deliver.
|
|
5856
|
+
*/
|
|
5857
|
+
const PROXY_PROGRAM_SUGGESTIONS = ['java', 'javaw', 'mvn', 'git', 'node', 'npm', 'curl', 'python', 'python3']
|
|
5858
|
+
|
|
5859
|
+
/** Distinct program names of the processes on THIS side of the OS boundary. */
|
|
5860
|
+
function localProgramNames() {
|
|
5861
|
+
const names = new Set()
|
|
5862
|
+
if (IS_WINDOWS) return names
|
|
5863
|
+
try {
|
|
5864
|
+
for (const entry of readdirSync('/proc')) {
|
|
5865
|
+
if (!/^\d+$/.test(entry)) continue
|
|
5866
|
+
try {
|
|
5867
|
+
const commandLine = readFileSync(`/proc/${entry}/cmdline`, 'utf8')
|
|
5868
|
+
const first = commandLine.split('\0')[0]
|
|
5869
|
+
if (first !== '') names.add(basename(first))
|
|
5870
|
+
} catch { /* the process exited between readdir and read */ }
|
|
5871
|
+
}
|
|
5872
|
+
} catch { /* no /proc: the suggestions still make the picker usable */ }
|
|
5873
|
+
return names
|
|
5874
|
+
}
|
|
5875
|
+
|
|
5876
|
+
/** Program names of the WINDOWS side, via PowerShell (interop may be off). */
|
|
5877
|
+
function windowsProgramNames() {
|
|
5878
|
+
// A cold PowerShell start is 3s here and worse under load: the old 4s budget made
|
|
5879
|
+
// the picker silently drop every Windows entry. Cache it and give it room.
|
|
5880
|
+
const cached = windowsProgramCache
|
|
5881
|
+
if (cached !== null && Date.now() - cached.at < WINDOWS_PROGRAM_TTL_MS) return Promise.resolve(new Set(cached.names))
|
|
5882
|
+
return new Promise((resolvePromise) => {
|
|
5883
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
5884
|
+
'Get-Process | Select-Object -ExpandProperty ProcessName -Unique'], { windowsHide: true })
|
|
5885
|
+
let stdout = ''
|
|
5886
|
+
let settled = false
|
|
5887
|
+
const done = (names) => { if (!settled) { settled = true; resolvePromise(names) } }
|
|
5888
|
+
child.stdout?.on('data', (chunk) => { if (stdout.length < 200000) stdout += chunk.toString('utf8') })
|
|
5889
|
+
child.on('error', () => done(new Set()))
|
|
5890
|
+
child.on('timeout', () => done(new Set()))
|
|
5891
|
+
child.on('close', () => {
|
|
5892
|
+
const names = new Set(stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== ''))
|
|
5893
|
+
if (names.size > 0) windowsProgramCache = { at: Date.now(), names: [...names] }
|
|
5894
|
+
done(names)
|
|
5895
|
+
})
|
|
5896
|
+
setTimeout(() => done(new Set()), TIMEOUT_WINDOWS_PROGRAMS_MS).unref?.()
|
|
5897
|
+
})
|
|
5898
|
+
}
|
|
5899
|
+
|
|
5900
|
+
/** Last successful Windows process list (the probe is too slow to repeat per open). */
|
|
5901
|
+
let windowsProgramCache = null
|
|
5902
|
+
|
|
5903
|
+
/** Drop the cached Windows process list (tests, or after a program was installed). */
|
|
5904
|
+
export function resetWindowsProgramCache() {
|
|
5905
|
+
windowsProgramCache = null
|
|
5906
|
+
}
|
|
5907
|
+
/** How long a successful Windows process list stays usable. */
|
|
5908
|
+
const WINDOWS_PROGRAM_TTL_MS = 20000
|
|
5909
|
+
/** Budget for one PowerShell process listing (cold start alone is ~3s). */
|
|
5910
|
+
const TIMEOUT_WINDOWS_PROGRAMS_MS = 12000
|
|
5911
|
+
|
|
5912
|
+
/** `GET` the program picker's candidates (this side + Windows when reachable). */
|
|
5913
|
+
/**
|
|
5914
|
+
* List one directory for the rules table's 「固定程序」 browser.
|
|
5915
|
+
*
|
|
5916
|
+
* A rule can point at an executable that is not running yet, so the panel needs
|
|
5917
|
+
* a way to pick an absolute path — by hand typing it is error-prone, and the
|
|
5918
|
+
* workspace tree only covers one root. Directories come first; files are limited
|
|
5919
|
+
* to things that can plausibly be programs (executable bit, or a known suffix),
|
|
5920
|
+
* so a build output directory does not bury the java.exe the user came for.
|
|
5921
|
+
* @param ctx - host context.
|
|
5922
|
+
* @param req - `?path=<dir>`; missing means the platform temp/home root.
|
|
5923
|
+
* @param res - JSON response.
|
|
5924
|
+
* @param options - host options.
|
|
5925
|
+
*/
|
|
5926
|
+
async function serveProxyBrowse(ctx, req, res, options) {
|
|
5927
|
+
try {
|
|
5928
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
5929
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
5930
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
5931
|
+
const clientCwd = url.searchParams.get('cwd') ?? ''
|
|
5932
|
+
// Two file systems can hold the same rule's program: the host's own (posix) and,
|
|
5933
|
+
// from WSL, the Windows one under /mnt. `side` says which spelling the UI uses.
|
|
5934
|
+
const side = url.searchParams.get('side') === 'windows' || (IS_WINDOWS && url.searchParams.get('side') !== 'local')
|
|
5935
|
+
? 'windows'
|
|
5936
|
+
: 'local'
|
|
5937
|
+
const requested = url.searchParams.get('path') ?? ''
|
|
5938
|
+
const windowsRoots = side === 'windows' ? windowsBrowseRoots() : []
|
|
5939
|
+
// Translate the UI's spelling into something readdir understands. Keeping the
|
|
5940
|
+
// original in `display` is what lets a click write back `D:\…` instead of `/mnt/d/…`.
|
|
5941
|
+
let target
|
|
5942
|
+
let display
|
|
5943
|
+
if (side === 'windows') {
|
|
5944
|
+
const asWindows = requested !== '' && /^[A-Za-z]:[\\/]/.test(requested)
|
|
5945
|
+
const asPosix = requested.startsWith('/mnt/')
|
|
5946
|
+
if (asWindows === true) {
|
|
5947
|
+
target = windowsToPosixPath(requested)
|
|
5948
|
+
display = requested.replace(/\//g, '\\').replace(/\\+$/, '') || requested
|
|
5949
|
+
} else if (asPosix === true) {
|
|
5950
|
+
target = requested
|
|
5951
|
+
display = posixToWindowsPath(requested)
|
|
5952
|
+
} else if (requested === '') {
|
|
5953
|
+
const first = windowsRoots[0]
|
|
5954
|
+
if (first === undefined) throw new TailError('bad-request', '这台机器上没有可浏览的 Windows 盘(/mnt/<盘> 不存在)', 400)
|
|
5955
|
+
target = windowsToPosixPath(first.path)
|
|
5956
|
+
display = first.path
|
|
5957
|
+
} else {
|
|
5958
|
+
throw new TailError('bad-request', `Windows 侧需要盘符路径(如 D:\\Program Files):${requested}`, 400)
|
|
5959
|
+
}
|
|
5960
|
+
} else {
|
|
5961
|
+
// Only the host side needs a session cwd; the Windows side is absolute by nature
|
|
5962
|
+
// and must keep working when the caller has no session (CLI, tests).
|
|
5963
|
+
const root = resolveCwd(ctx, sessionId, clientCwd)
|
|
5964
|
+
target = requested === '' ? root : resolve(root, expandHome(requested))
|
|
5965
|
+
display = target
|
|
5966
|
+
}
|
|
5967
|
+
if (target === '') throw new TailError('bad-request', `无法解析路径:${requested}`, 400)
|
|
5968
|
+
|
|
5969
|
+
let entries
|
|
5970
|
+
try {
|
|
5971
|
+
entries = await readdir(target, { withFileTypes: true })
|
|
5972
|
+
} catch (error) {
|
|
5973
|
+
throw new TailError('bad-request', `无法读取目录 ${display}:${error?.code ?? error}`, 400)
|
|
5974
|
+
}
|
|
5975
|
+
const dirs = []
|
|
5976
|
+
const files = []
|
|
5977
|
+
for (const entry of entries) {
|
|
5978
|
+
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name.startsWith('$')) continue
|
|
5979
|
+
const full = join(target, entry.name)
|
|
5980
|
+
const shown = side === 'windows' ? posixToWindowsPath(full) : full
|
|
5981
|
+
if (entry.isDirectory()) {
|
|
5982
|
+
dirs.push({ name: entry.name, path: shown })
|
|
5983
|
+
continue
|
|
5984
|
+
}
|
|
5985
|
+
if (!entry.isFile()) continue
|
|
5986
|
+
// On /mnt every Windows file carries the exec bit (drvfs), so the mode fallback
|
|
5987
|
+
// would list DLLs and logs; there only the suffix list is meaningful.
|
|
5988
|
+
const looksProgram = side === 'windows'
|
|
5989
|
+
? PROGRAM_SUFFIXES.some((suffix) => entry.name.toLowerCase().endsWith(suffix))
|
|
5990
|
+
: isProgramFile(full, entry.name)
|
|
5991
|
+
if (looksProgram) files.push({ name: entry.name, path: shown })
|
|
5992
|
+
}
|
|
5993
|
+
dirs.sort((a, b) => a.name.localeCompare(b.name))
|
|
5994
|
+
files.sort((a, b) => a.name.localeCompare(b.name))
|
|
5995
|
+
const parentTarget = dirname(target) === target ? null : dirname(target)
|
|
5996
|
+
writeJson(res, 200, {
|
|
5997
|
+
ok: true,
|
|
5998
|
+
side,
|
|
5999
|
+
path: display,
|
|
6000
|
+
parent: parentTarget === null ? null : (side === 'windows' ? posixToWindowsPath(parentTarget) : parentTarget),
|
|
6001
|
+
roots: side === 'windows' ? windowsRoots : browseRoots(),
|
|
6002
|
+
dirs: dirs.slice(0, 300),
|
|
6003
|
+
files: files.slice(0, 300),
|
|
6004
|
+
})
|
|
6005
|
+
} catch (error) {
|
|
6006
|
+
writeTailError(res, error)
|
|
6007
|
+
}
|
|
6008
|
+
}
|
|
6009
|
+
|
|
6010
|
+
/**
|
|
6011
|
+
* Quick-jump roots for the Windows side of the picker (opened from WSL via /mnt).
|
|
6012
|
+
* @returns {Array<{name: string, path: string}>} roots with WINDOWS paths.
|
|
6013
|
+
*/
|
|
6014
|
+
function windowsBrowseRoots() {
|
|
6015
|
+
const roots = []
|
|
6016
|
+
const seen = new Set()
|
|
6017
|
+
const push = (name, posix) => {
|
|
6018
|
+
if (existsSync(posix) !== true || seen.has(posix)) return
|
|
6019
|
+
seen.add(posix)
|
|
6020
|
+
roots.push({ name, path: posixToWindowsPath(posix) })
|
|
6021
|
+
}
|
|
6022
|
+
for (const letter of ['c', 'd', 'e', 'f']) push(`Windows ${letter.toUpperCase()}:`, `/mnt/${letter}`)
|
|
6023
|
+
for (const letter of ['c', 'd']) {
|
|
6024
|
+
push(`${letter.toUpperCase()}:\\Program Files`, `/mnt/${letter}/Program Files`)
|
|
6025
|
+
push(`${letter.toUpperCase()}:\\YonCode`, `/mnt/${letter}/Program Files/YonCode`)
|
|
6026
|
+
push(`${letter.toUpperCase()}:\\Git`, `/mnt/${letter}/Program Files/Git`)
|
|
6027
|
+
}
|
|
6028
|
+
return roots
|
|
6029
|
+
}
|
|
6030
|
+
|
|
6031
|
+
/** Names that look like a launchable program, for the browse listing. */
|
|
6032
|
+
function isProgramFile(fullPath, name) {
|
|
6033
|
+
const lower = name.toLowerCase()
|
|
6034
|
+
if (PROGRAM_SUFFIXES.some((suffix) => lower.endsWith(suffix))) return true
|
|
6035
|
+
try {
|
|
6036
|
+
// POSIX marks executables with a mode bit; Windows has no such bit and is
|
|
6037
|
+
// covered by the suffix list above.
|
|
6038
|
+
return (statSync(fullPath).mode & 0o111) !== 0
|
|
6039
|
+
} catch {
|
|
6040
|
+
return false
|
|
6041
|
+
}
|
|
6042
|
+
}
|
|
6043
|
+
|
|
6044
|
+
/** Suffixes the file browser always shows (plus anything with an exec bit). */
|
|
6045
|
+
const PROGRAM_SUFFIXES = ['.exe', '.cmd', '.bat', '.ps1', '.jar', '.sh', '.bin', '.mjs', '.cjs']
|
|
6046
|
+
|
|
6047
|
+
/** Quick-jump roots offered by the file browser. */
|
|
6048
|
+
function browseRoots() {
|
|
6049
|
+
// The tree starts at the two things a program path can live under, and nothing
|
|
6050
|
+
// else: the filesystem root (every path is reachable from it) and, on WSL, the
|
|
6051
|
+
// Windows disks. Workspace/home/temp shortcuts only pushed the real start down.
|
|
6052
|
+
const roots = []
|
|
6053
|
+
if (IS_WINDOWS) {
|
|
6054
|
+
for (const letter of ['C', 'D', 'E']) {
|
|
6055
|
+
if (existsSync(`${letter}:\\`) === true) roots.push({ name: `磁盘 ${letter}:`, path: `${letter}:\\` })
|
|
6056
|
+
}
|
|
6057
|
+
return roots
|
|
6058
|
+
}
|
|
6059
|
+
roots.push({ name: '根路径 /', path: '/' })
|
|
6060
|
+
for (const letter of ['c', 'd']) {
|
|
6061
|
+
if (existsSync(`/mnt/${letter}`) === true) roots.push({ name: `Windows ${letter.toUpperCase()}:`, path: `/mnt/${letter}` })
|
|
6062
|
+
}
|
|
6063
|
+
return roots
|
|
6064
|
+
}
|
|
6065
|
+
|
|
6066
|
+
async function serveProxyPrograms(ctx, req, res, options) {
|
|
6067
|
+
try {
|
|
6068
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
6069
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
6070
|
+
const side = engineSide()
|
|
6071
|
+
// On Windows the local side IS the Windows side; inside WSL both sides are
|
|
6072
|
+
// reachable (the picker must offer navicat.exe even though the engine runs in
|
|
6073
|
+
// the Linux side), so the Windows probe runs on either branch.
|
|
6074
|
+
// Only programs we can actually proxy are listed: injecting the tunnel means
|
|
6075
|
+
// setting a SOCKS address (env or JVM flag), and a program that has no SOCKS
|
|
6076
|
+
// client cannot be helped that way.
|
|
6077
|
+
const capable = (names) => names
|
|
6078
|
+
.filter((name) => isSocksCapableProgram(name))
|
|
6079
|
+
.map((name) => ({ name, side: engineSide() }))
|
|
6080
|
+
const local = IS_WINDOWS
|
|
6081
|
+
? capable([...await windowsProgramNames()].map((name) => (name.endsWith('.exe') ? name : `${name}.exe`)))
|
|
6082
|
+
.map((item) => ({ ...item, side: 'windows' }))
|
|
6083
|
+
: capable([...localProgramNames()])
|
|
6084
|
+
let remote = []
|
|
6085
|
+
if (!IS_WINDOWS) {
|
|
6086
|
+
const names = await windowsProgramNames()
|
|
6087
|
+
if (names.size > 0) {
|
|
6088
|
+
remote = capable([...names].map((name) => (name.endsWith('.exe') ? name : `${name}.exe`)))
|
|
6089
|
+
.map((item) => ({ ...item, side: 'windows' }))
|
|
6090
|
+
}
|
|
6091
|
+
}
|
|
6092
|
+
const suggested = PROXY_PROGRAM_SUGGESTIONS.map((name) => ({ name, side, suggested: true }))
|
|
6093
|
+
const seen = new Set()
|
|
6094
|
+
const programs = []
|
|
6095
|
+
for (const item of [...local, ...remote, ...suggested]) {
|
|
6096
|
+
const key = `${item.side}:${item.name.toLowerCase()}`
|
|
6097
|
+
if (seen.has(key)) continue
|
|
6098
|
+
seen.add(key)
|
|
6099
|
+
programs.push(item)
|
|
6100
|
+
}
|
|
6101
|
+
programs.sort((a, b) => Number(b.suggested === true) - Number(a.suggested === true) || a.name.localeCompare(b.name))
|
|
6102
|
+
writeJson(res, 200, {
|
|
6103
|
+
ok: true,
|
|
6104
|
+
side,
|
|
6105
|
+
// Why the list is short: a program without a SOCKS client can only use a
|
|
6106
|
+
// 127.0.0.1 listener, and those need no entry here.
|
|
6107
|
+
note: '只列出支持 SOCKS 的程序(java/git/node/curl 等);其它程序只能靠 127.0.0.1 同端口映射,无需在此选择。',
|
|
6108
|
+
programs: programs.slice(0, 400),
|
|
6109
|
+
})
|
|
6110
|
+
} catch (error) {
|
|
6111
|
+
writeTailError(res, error)
|
|
6112
|
+
}
|
|
6113
|
+
}
|
|
6114
|
+
|
|
5168
6115
|
async function serveDebug(ctx, req, res, options) {
|
|
5169
6116
|
try {
|
|
5170
6117
|
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
@@ -5346,6 +6293,80 @@ async function serveStart(ctx, req, res, options) {
|
|
|
5346
6293
|
* @param options - `{ stopGraceMs }`.
|
|
5347
6294
|
* @returns `{ alreadyRunning, program }`.
|
|
5348
6295
|
*/
|
|
6296
|
+
/**
|
|
6297
|
+
* Decide whether a program needs its dependencies installed before it can run.
|
|
6298
|
+
*
|
|
6299
|
+
* A freshly cloned frontend has no `node_modules`, and the failure it produces
|
|
6300
|
+
* (`cross-env: not found`, `vite: not found`) looks like a broken command rather
|
|
6301
|
+
* than a missing install. Installing up front — with the output going into the same
|
|
6302
|
+
* log the panel already tails — turns that into a visible, self-healing step.
|
|
6303
|
+
* @param {string} cwd - program working directory.
|
|
6304
|
+
* @returns {{pm: string, args: string[], dir: string}|null} plan, or null when the
|
|
6305
|
+
* directory has no package.json or already has dependencies.
|
|
6306
|
+
*/
|
|
6307
|
+
export function installPlanFor(cwd) {
|
|
6308
|
+
try {
|
|
6309
|
+
if (!existsSync(join(cwd, 'package.json'))) return null
|
|
6310
|
+
const modules = join(cwd, 'node_modules')
|
|
6311
|
+
if (existsSync(modules)) {
|
|
6312
|
+
const entries = readdirSync(modules)
|
|
6313
|
+
// An empty node_modules is what a killed install leaves behind.
|
|
6314
|
+
if (entries.length > 0) return null
|
|
6315
|
+
}
|
|
6316
|
+
const has = (name) => existsSync(join(cwd, name))
|
|
6317
|
+
const pm = has('pnpm-lock.yaml') ? 'pnpm' : (has('yarn.lock') ? 'yarn' : 'npm')
|
|
6318
|
+
const args = pm === 'npm' ? ['install', '--no-audit', '--no-fund'] : ['install']
|
|
6319
|
+
return { pm, args, dir: cwd }
|
|
6320
|
+
} catch {
|
|
6321
|
+
return null
|
|
6322
|
+
}
|
|
6323
|
+
}
|
|
6324
|
+
|
|
6325
|
+
/**
|
|
6326
|
+
* Run the install phase with its output appended to the program log.
|
|
6327
|
+
*
|
|
6328
|
+
* The proxy environment is stripped on purpose: npm's own traffic goes to a
|
|
6329
|
+
* registry (often a loopback mirror), and an injected ALL_PROXY would send that
|
|
6330
|
+
* through the tunnel where the allow list refuses it.
|
|
6331
|
+
* @param {object} plan - from {@link installPlanFor}.
|
|
6332
|
+
* @param {object} env - base environment.
|
|
6333
|
+
* @param {string} logPath - log the panel tails.
|
|
6334
|
+
* @param {number} timeoutMs - cap for a cold install.
|
|
6335
|
+
* @returns {Promise<{ok: boolean, ms: number, pm: string, error?: string}>} outcome.
|
|
6336
|
+
*/
|
|
6337
|
+
export function runInstallPhase(plan, env, logPath, timeoutMs = 1200000) {
|
|
6338
|
+
const clean = Object.assign({}, env)
|
|
6339
|
+
for (const key of Object.keys(clean)) {
|
|
6340
|
+
if (/^(ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|NO_PROXY|all_proxy|http_proxy|https_proxy|no_proxy)$/.test(key)) delete clean[key]
|
|
6341
|
+
}
|
|
6342
|
+
const fd = openSync(logPath, 'a')
|
|
6343
|
+
const started = Date.now()
|
|
6344
|
+
return new Promise((resolvePromise) => {
|
|
6345
|
+
const child = spawn(plan.pm, plan.args, {
|
|
6346
|
+
cwd: plan.dir, env: clean, stdio: ['ignore', fd, fd], shell: IS_WINDOWS, windowsHide: true,
|
|
6347
|
+
})
|
|
6348
|
+
let settled = false
|
|
6349
|
+
const done = (result) => {
|
|
6350
|
+
if (settled) return
|
|
6351
|
+
settled = true
|
|
6352
|
+
try { closeSync(fd) } catch { /* already closed */ }
|
|
6353
|
+
resolvePromise(result)
|
|
6354
|
+
}
|
|
6355
|
+
const timer = setTimeout(() => {
|
|
6356
|
+
try { child.kill('SIGKILL') } catch { /* gone already */ }
|
|
6357
|
+
done({ ok: false, ms: Date.now() - started, pm: plan.pm, error: `安装超时(${Math.round(timeoutMs / 1000)}s)` })
|
|
6358
|
+
}, timeoutMs)
|
|
6359
|
+
child.on('error', (error) => {
|
|
6360
|
+
clearTimeout(timer)
|
|
6361
|
+
done({ ok: false, ms: Date.now() - started, pm: plan.pm, error: isMissingExecutable(error) ? `本机没有安装 ${plan.pm}` : String(error?.message ?? error) })
|
|
6362
|
+
})
|
|
6363
|
+
child.on('close', (code) => {
|
|
6364
|
+
clearTimeout(timer)
|
|
6365
|
+
done(code === 0 ? { ok: true, ms: Date.now() - started, pm: plan.pm } : { ok: false, ms: Date.now() - started, pm: plan.pm, error: `${plan.pm} install exited with ${code}` })
|
|
6366
|
+
})
|
|
6367
|
+
})
|
|
6368
|
+
}
|
|
6369
|
+
|
|
5349
6370
|
export async function startProgram(cwd, logsDir, program, options) {
|
|
5350
6371
|
if (options?.debug === undefined) await debugSessions.detach(program.logPath)
|
|
5351
6372
|
if (program.kind === 'instance') {
|
|
@@ -5364,6 +6385,24 @@ export async function startProgram(cwd, logsDir, program, options) {
|
|
|
5364
6385
|
const childEnv = Object.assign({}, process.env, { DSH_LOG_DIR: logsDir }, {
|
|
5365
6386
|
DSH_STOP_GRACE_MS: String(clampBytes(graceMs, DEFAULT_STOP_GRACE_MS, MAX_STOP_GRACE_MS)),
|
|
5366
6387
|
})
|
|
6388
|
+
// A rule can name this program: inject the proxy at launch, so "配好规则再启动"
|
|
6389
|
+
// actually proxies it (Java reads JAVA_TOOL_OPTIONS, node/curl read ALL_PROXY).
|
|
6390
|
+
// Programs started outside this panel cannot be intercepted — they rely on the
|
|
6391
|
+
// 127.0.0.1 shadow listeners instead.
|
|
6392
|
+
Object.assign(childEnv, proxyEnvFor(program, cwd))
|
|
6393
|
+
// Dependencies first: a missing node_modules would otherwise surface as
|
|
6394
|
+
// "cross-env: not found" and look like the entry itself is broken.
|
|
6395
|
+
const installPlan = options?.skipInstall === true ? null : installPlanFor(cwd)
|
|
6396
|
+
if (installPlan !== null) {
|
|
6397
|
+
const header = `--- 初始化:${installPlan.pm} ${installPlan.args.join(' ')}(node_modules 缺失)---\n`
|
|
6398
|
+
await appendFile(program.logPath, header, 'utf8').catch(() => {})
|
|
6399
|
+
const init = await runInstallPhase(installPlan, childEnv, program.logPath, options?.installTimeoutMs)
|
|
6400
|
+
const summary = init.ok === true
|
|
6401
|
+
? `--- 初始化完成:${init.pm} install(${Math.round(init.ms / 1000)}s)---\n`
|
|
6402
|
+
: `--- 初始化失败:${init.pm} install(${init.error ?? '未知原因'}),见上方输出 ---\n`
|
|
6403
|
+
await appendFile(program.logPath, summary, 'utf8').catch(() => {})
|
|
6404
|
+
if (init.ok !== true) throw new TailError('init-failed', `依赖安装失败:${init.error ?? '未知原因'}(日志:${program.logPath})`, 502)
|
|
6405
|
+
}
|
|
5367
6406
|
let child
|
|
5368
6407
|
if (IS_WINDOWS) {
|
|
5369
6408
|
const selected = resolveWindowsRuntime(options?.runtime, options?.bashPath)
|
|
@@ -5418,6 +6457,67 @@ export async function startProgram(cwd, logsDir, program, options) {
|
|
|
5418
6457
|
}
|
|
5419
6458
|
}
|
|
5420
6459
|
|
|
6460
|
+
/**
|
|
6461
|
+
* Environment a started program needs to use the workspace proxy.
|
|
6462
|
+
*
|
|
6463
|
+
* Matches the program against the enabled rules: a rule that names a bare
|
|
6464
|
+
* program (`java`, `git`) matches any process with that basename, whatever its
|
|
6465
|
+
* path; a rule that names a path only matches that executable. The path is
|
|
6466
|
+
* therefore optional — it buys precision, not reach.
|
|
6467
|
+
* injection that fits that program. Returns `{}` when no rule matches or the
|
|
6468
|
+
* workspace has no upstream — a silent no-op rather than an error, because most
|
|
6469
|
+
* programs have no rule and must start exactly as before.
|
|
6470
|
+
* @param program - one row from {@link scanPrograms}.
|
|
6471
|
+
* @param cwd - workspace the program is launched from (the shared proxy config
|
|
6472
|
+
* only uses it to identify which rules belong to this workspace).
|
|
6473
|
+
* @returns environment overlay for the child process.
|
|
6474
|
+
*/
|
|
6475
|
+
function proxyEnvFor(program, cwd) {
|
|
6476
|
+
// A Windows-side redirector cannot see a process this side spawns, so only the
|
|
6477
|
+
// local hook may disable injection ("covered twice" was the old, wrong test).
|
|
6478
|
+
try {
|
|
6479
|
+
const config = readProxyConfig(cwd)
|
|
6480
|
+
if (config.socks.host === '' || config.socks.port === 0) return {}
|
|
6481
|
+
// ProxyBridge is the primary path when the LOCAL hook is up: it already
|
|
6482
|
+
// redirects this side's connections at the socket layer, so adding env/JVM
|
|
6483
|
+
// options on top would only stack two proxies. A Windows-side redirector does
|
|
6484
|
+
// NOT count — it hooks the Windows stack and cannot see a process this side
|
|
6485
|
+
// spawns, which is exactly the WSL + YonCode split.
|
|
6486
|
+
if (localRedirectorRunning()) return {}
|
|
6487
|
+
const names = new Set()
|
|
6488
|
+
const paths = new Set()
|
|
6489
|
+
for (const candidate of [program?.name, program?.command, program?.exe, program?.id]) {
|
|
6490
|
+
if (typeof candidate !== 'string' || candidate === '') continue
|
|
6491
|
+
names.add(programKey(candidate))
|
|
6492
|
+
if (candidate.includes('/') || candidate.includes('\\')) paths.add(candidate.replace(/\\/g, '/').toLowerCase())
|
|
6493
|
+
}
|
|
6494
|
+
const matchRule = (spec) => {
|
|
6495
|
+
if (typeof spec !== 'string' || spec === '') return false
|
|
6496
|
+
const isPath = spec.includes('/') || spec.includes('\\')
|
|
6497
|
+
if (!isPath) return names.has(programKey(spec))
|
|
6498
|
+
// A path rule is precise: it matches that executable only. When we do not
|
|
6499
|
+
// know the launched path, fall back to the basename so the rule is not
|
|
6500
|
+
// silently dead (the panel often launches by name, e.g. `java`).
|
|
6501
|
+
if (paths.size === 0) return names.has(programKey(spec))
|
|
6502
|
+
return paths.has(spec.replace(/\\/g, '/').toLowerCase())
|
|
6503
|
+
}
|
|
6504
|
+
const rule = config.rules.find((item) => item.enabled && matchRule(item.program))
|
|
6505
|
+
if (rule === undefined) return {}
|
|
6506
|
+
const injection = injectionFor(programKey(rule.program), config, { side: engineSide() })
|
|
6507
|
+
const env = Object.assign({}, injection?.env ?? {})
|
|
6508
|
+
const jvmArgs = Array.isArray(injection?.jvmArgs) ? injection.jvmArgs : []
|
|
6509
|
+
// Careful: an existing JAVA_TOOL_OPTIONS must be kept (it may carry the
|
|
6510
|
+
// user's own -Xmx); the proxy options are appended.
|
|
6511
|
+
if (jvmArgs.length > 0) {
|
|
6512
|
+
const previous = typeof process.env.JAVA_TOOL_OPTIONS === 'string' ? process.env.JAVA_TOOL_OPTIONS.trim() : ''
|
|
6513
|
+
env.JAVA_TOOL_OPTIONS = [previous, jvmArgs.join(' ')].filter((part) => part !== '').join(' ')
|
|
6514
|
+
}
|
|
6515
|
+
return env
|
|
6516
|
+
} catch {
|
|
6517
|
+
return {}
|
|
6518
|
+
}
|
|
6519
|
+
}
|
|
6520
|
+
|
|
5421
6521
|
/**
|
|
5422
6522
|
* Start one program in debug mode: stop it if needed, restart it with the JDWP
|
|
5423
6523
|
* agent on a free loopback port, wait for the port, then attach.
|
|
@@ -6112,6 +7212,29 @@ async function considerSpring(workspace, file, programs, launch) {
|
|
|
6112
7212
|
}
|
|
6113
7213
|
|
|
6114
7214
|
/** Record one frontend program when its manifest has a dev-ish script. */
|
|
7215
|
+
/**
|
|
7216
|
+
* YonBIP module manifest of a frontend directory (`module.xml` beside package.json).
|
|
7217
|
+
*
|
|
7218
|
+
* This is a yds/MDF convention: the deployed module name lives in `module.xml`, while
|
|
7219
|
+
* `package.json`'s `name` is often the *backend* domainKey — so a row named after the
|
|
7220
|
+
* package would read exactly like the java program's row. Only projects that ship a
|
|
7221
|
+
* module.xml are affected; a plain npm project keeps its package name.
|
|
7222
|
+
* @param dir - frontend project directory.
|
|
7223
|
+
* @returns `{ present, name }`; `name` is `''` when the manifest names nothing.
|
|
7224
|
+
*/
|
|
7225
|
+
async function moduleXmlManifest(dir) {
|
|
7226
|
+
const text = await readTextIfSmall(join(dir, 'module.xml'))
|
|
7227
|
+
if (text === undefined) return { present: false, name: '' }
|
|
7228
|
+
const match = /<module\b[^>]*\sname\s*=\s*"([^"]*)"/.exec(text)
|
|
7229
|
+
return { present: true, name: match === null ? '' : match[1].trim() }
|
|
7230
|
+
}
|
|
7231
|
+
|
|
7232
|
+
/** Row name for a frontend: module.xml → folder (yds), else package.json → folder. */
|
|
7233
|
+
function nameOfFrontend(manifest, manifestXml, dir) {
|
|
7234
|
+
if (manifestXml.present === true) return manifestXml.name !== '' ? manifestXml.name : basename(dir)
|
|
7235
|
+
return typeof manifest.name === 'string' && manifest.name !== '' ? manifest.name : basename(dir)
|
|
7236
|
+
}
|
|
7237
|
+
|
|
6115
7238
|
async function considerFrontend(workspace, file, programs) {
|
|
6116
7239
|
const dir = dirname(file)
|
|
6117
7240
|
const text = await readTextIfSmall(file)
|
|
@@ -6128,13 +7251,17 @@ async function considerFrontend(workspace, file, programs) {
|
|
|
6128
7251
|
if (scripts === undefined) return
|
|
6129
7252
|
const script = ['dev', 'start', 'serve'].find((key) => typeof scripts[key] === 'string' && scripts[key].trim() !== '')
|
|
6130
7253
|
if (script === undefined) return
|
|
7254
|
+
const manifestXml = await moduleXmlManifest(dir)
|
|
6131
7255
|
const relDir = relative(workspace, dir) || '.'
|
|
6132
7256
|
const id = `frontend:${relDir}#${script}`
|
|
6133
7257
|
if (programs.has(id)) return
|
|
6134
7258
|
programs.set(id, {
|
|
6135
7259
|
id,
|
|
6136
7260
|
kind: 'frontend',
|
|
6137
|
-
|
|
7261
|
+
// yds project (it has module.xml): name after the manifest, else the folder —
|
|
7262
|
+
// `package.json`'s name there is the domainKey and collides with the java row.
|
|
7263
|
+
// A plain npm project has no module.xml and keeps its package name.
|
|
7264
|
+
name: nameOfFrontend(manifest, manifestXml, dir),
|
|
6138
7265
|
project: projectOf(relDir, workspace),
|
|
6139
7266
|
dir,
|
|
6140
7267
|
relDir,
|
|
@@ -6729,7 +7856,12 @@ export function findConfigEntryIndex(entries, candidate, used) {
|
|
|
6729
7856
|
&& (entry.kind === undefined || entry.kind === candidate.kind))
|
|
6730
7857
|
if (byDir !== -1) return byDir
|
|
6731
7858
|
}
|
|
6732
|
-
|
|
7859
|
+
// Name is the last resort, and only within the same kind: two different kinds can
|
|
7860
|
+
// legitimately share a name (a yds project's package.json name equals its java
|
|
7861
|
+
// module), and matching across kinds made an update copy a launcher's startCommand
|
|
7862
|
+
// onto an unrelated frontend row — and then drop the launcher itself.
|
|
7863
|
+
return entries.findIndex((entry, at) => free(at) && entry.name === candidate.name
|
|
7864
|
+
&& (entry.kind === undefined || candidate.kind === undefined || entry.kind === candidate.kind))
|
|
6733
7865
|
}
|
|
6734
7866
|
|
|
6735
7867
|
/**
|
|
@@ -7226,7 +8358,14 @@ export function registerAgentTools(ctx, options) {
|
|
|
7226
8358
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
7227
8359
|
let programs = await scanPrograms(cwd, logsDir, args?.refresh === true)
|
|
7228
8360
|
if (args?.runningOnly === true) programs = programs.filter((program) => program.running?.alive === true)
|
|
7229
|
-
return jsonSafe({
|
|
8361
|
+
return jsonSafe({
|
|
8362
|
+
ok: true,
|
|
8363
|
+
root: cwd,
|
|
8364
|
+
dir: logsDir,
|
|
8365
|
+
programs: programRows(programs),
|
|
8366
|
+
// Only a real YMS workspace gets a hint; null keeps the payload clean.
|
|
8367
|
+
companion: detectCompanionPlugin(cwd),
|
|
8368
|
+
})
|
|
7230
8369
|
},
|
|
7231
8370
|
})
|
|
7232
8371
|
|
|
@@ -7754,13 +8893,19 @@ function describeRef(ref) {
|
|
|
7754
8893
|
/** Render one program list for the model. */
|
|
7755
8894
|
function renderProgramList(value) {
|
|
7756
8895
|
const programs = Array.isArray(value?.programs) ? value.programs : []
|
|
7757
|
-
|
|
8896
|
+
const companion = value?.companion
|
|
8897
|
+
// The hint is additive: the list itself (and the tool result) stays usable
|
|
8898
|
+
// when the companion plugin is not installed.
|
|
8899
|
+
const hint = companion !== undefined && companion !== null
|
|
8900
|
+
? `\nOptional companion plugin: ${companion.plugin} (detected ${companion.detected}) — ${companion.hint}`
|
|
8901
|
+
: ''
|
|
8902
|
+
if (programs.length === 0) return `No runnable programs under ${value?.root ?? '?'}.${hint}`
|
|
7758
8903
|
const lines = [`${programs.length} program(s) under ${value.root} (logs: ${value.dir}):`]
|
|
7759
8904
|
for (const program of programs) {
|
|
7760
8905
|
lines.push(`- ${program.running ? '[running]' : '[stopped]'} ${program.name} (${program.kind}) id=${program.id}`)
|
|
7761
8906
|
lines.push(` dir=${program.dir}${program.mainClass ? ` main=${program.mainClass}` : ''}${program.script ? ` script=${program.script}` : ''} log=${program.logPath}`)
|
|
7762
8907
|
}
|
|
7763
|
-
return lines.join('\n')
|
|
8908
|
+
return lines.join('\n') + hint
|
|
7764
8909
|
}
|
|
7765
8910
|
|
|
7766
8911
|
/** Render one start result for the model. */
|
|
@@ -7918,6 +9063,27 @@ function renderLogs(value) {
|
|
|
7918
9063
|
/** Test-only surface: the pure pieces, exercised without a live profile. */
|
|
7919
9064
|
export const __test = {
|
|
7920
9065
|
resolvePath,
|
|
9066
|
+
detectCompanionPlugin,
|
|
9067
|
+
renderProgramList,
|
|
9068
|
+
windowsProgramNames,
|
|
9069
|
+
resetWindowsProgramCache,
|
|
9070
|
+
// Proxy rules + engine (the dialog's three routes).
|
|
9071
|
+
PROXY_PATH,
|
|
9072
|
+
PROXY_ACTION_PATH,
|
|
9073
|
+
buildProfile,
|
|
9074
|
+
PROXY_PROGRAMS_PATH,
|
|
9075
|
+
PROXY_BROWSE_PATH,
|
|
9076
|
+
serveProxy,
|
|
9077
|
+
serveProxyAction,
|
|
9078
|
+
serveProxyPrograms,
|
|
9079
|
+
serveProxyBrowse,
|
|
9080
|
+
proxyEnvFor,
|
|
9081
|
+
proxyView,
|
|
9082
|
+
// Process-wide child-service lifecycle (exit hook + heartbeat + janitor), and the
|
|
9083
|
+
// adoption of an engine left behind by a previous dsh process.
|
|
9084
|
+
ensureLifecycle,
|
|
9085
|
+
adoptLeftoverEngine,
|
|
9086
|
+
decorateProxyRule,
|
|
7921
9087
|
// The bundled skill + its installer (idempotent, target-aware).
|
|
7922
9088
|
SKILL_NAME,
|
|
7923
9089
|
PKG_VERSION,
|