From 8c982d7c781cdb66cecf5d9842b95058ca464fcd Mon Sep 17 00:00:00 2001 From: harris Date: Tue, 1 Dec 2026 18:17:59 -0800 Subject: [PATCH] =?UTF-8?q?Add=20plugin=20VPS=20=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E4=B8=8E=E8=BF=90=E7=BB=B4=E7=AE=A1=E5=AE=B6=20v0.1.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add plugin 图片工具箱 v3.0.1 - Update plugin Live Markdown v0.1.1 - Update plugin 图片批处理 v0.1.4 - Merge pull request #776 from MoruTeaven/plugin/image-toolbox-ztools - Merge pull request #777 from TheLastSheep/plugin/live-markdown - Update plugin 大古截图 v1.3.0 - Add plugin 大古快传 v1.0.0 - Update plugin Todos待办 v1.4.0 - Merge pull request #779 from beierweiwei/plugin/dagu-ocr - Merge pull request #778 from TheLastSheep/plugin/image-batch-studio - release: 1.0.3 新增服务器配置导出并完善更新日志 - chore: 从插件仓库移除 dbx 源码 - Merge pull request #780 from beierweiwei/plugin/dagu-transfer - Merge pull request #782 from lhlucky0410/plugin/ssh-batch-exec - Merge pull request #781 from Code-Agitator/plugin/todos - Add plugin 快速密码填充 v0.0.1 - feat: initial release of win-context-menu v1.0.0 - Merge pull request #783 from GIWTO/plugin/ztools-quick-pwd - Merge pull request #784 from Pizalo/plugin/win-context-menu - feat: he-calendar:升级至1.6.0 - Merge branch 'main' of https://github.com/felanny/ZTools-plugins - Merge pull request #785 from felanny/main - feat: 新增OSS插件 - feat: 重构vibe-coding - fix(vibe-coding): sync release version to 0.1.5 - feat: ai复刻悬浮便签 - feat: 更新悬浮便签版本号 - Update plugin 快速密码填充 v0.0.2 - Add plugin 二维码转链接 v1.0.0 - feat: AI复刻易翻翻译 - Merge pull request #786 from GIWTO/plugin/ztools-quick-pwd - Update plugin jet plugin v1.2.3 - Merge pull request #788 from leqq00/plugin/jet-plugin - Merge pull request #787 from wanger1913/plugin/qr-to-link - feat(vps-manager): 新增 VPS 代理与运维管家插件 v0.1.0 --- plugins/vps-manager/.gitignore | 5 + plugins/vps-manager/CHANGELOG.md | 12 + plugins/vps-manager/README.md | 50 + plugins/vps-manager/docs/MCP.md | 32 + plugins/vps-manager/index.html | 12 + plugins/vps-manager/logo.svg | 20 + plugins/vps-manager/package-lock.json | 2412 +++++++++++++++++ plugins/vps-manager/package.json | 39 + plugins/vps-manager/plugin.json | 440 +++ plugins/vps-manager/preload/clash-api.cjs | 191 ++ plugins/vps-manager/preload/config-store.cjs | 941 +++++++ .../vps-manager/preload/deploy-templates.cjs | 650 +++++ .../vps-manager/preload/embedded-proxy.cjs | 1396 ++++++++++ plugins/vps-manager/preload/http-client.cjs | 395 +++ plugins/vps-manager/preload/ip-check.cjs | 741 +++++ plugins/vps-manager/preload/mcp-tools.cjs | 929 +++++++ plugins/vps-manager/preload/native-core.cjs | 483 ++++ plugins/vps-manager/preload/package-lock.json | 121 + plugins/vps-manager/preload/package.json | 10 + plugins/vps-manager/preload/services.cjs | 106 + plugins/vps-manager/preload/ssh-client.cjs | 1611 +++++++++++ plugins/vps-manager/preload/system-proxy.cjs | 347 +++ .../scripts/ensure-preload-deps.mjs | 26 + plugins/vps-manager/scripts/prepare-dist.mjs | 69 + plugins/vps-manager/scripts/verify-dist.mjs | 91 + .../vps-manager/skills/vps-manager/SKILL.md | 43 + .../vps-manager/references/ip-diagnostics.md | 17 + .../vps-manager/references/proxy-routing.md | 20 + .../vps-manager/references/safe-deploy.md | 20 + .../skills/vps-manager/references/vps-ops.md | 19 + plugins/vps-manager/src/App.tsx | 856 ++++++ .../src/components/ConfirmDialog.tsx | 94 + .../src/components/DeployDrawer.tsx | 642 +++++ .../src/components/EndpointModal.tsx | 90 + .../src/components/IpCheckPanel.tsx | 775 ++++++ .../src/components/McpSkillsModal.tsx | 190 ++ .../src/components/ProxyHomePanel.tsx | 1809 +++++++++++++ .../vps-manager/src/components/QrCodeBox.tsx | 72 + .../vps-manager/src/components/RulesPanel.tsx | 1419 ++++++++++ .../vps-manager/src/components/RulesTable.tsx | 252 ++ .../src/components/ServerOpsDrawer.tsx | 475 ++++ .../src/components/ServersPanel.tsx | 413 +++ .../src/components/VpsProfileModal.tsx | 510 ++++ plugins/vps-manager/src/lib/format.ts | 209 ++ plugins/vps-manager/src/lib/storage.ts | 97 + .../vps-manager/src/lib/usePreservedScroll.ts | 34 + plugins/vps-manager/src/main.tsx | 10 + plugins/vps-manager/src/styles.css | 1931 +++++++++++++ plugins/vps-manager/src/types.ts | 556 ++++ plugins/vps-manager/src/ztools.d.ts | 37 + .../tests/preload/preload.test.cjs | 1679 ++++++++++++ plugins/vps-manager/tests/unit/format.test.ts | 99 + plugins/vps-manager/tsconfig.json | 20 + plugins/vps-manager/vite.config.ts | 22 + 54 files changed, 23539 insertions(+) create mode 100644 plugins/vps-manager/.gitignore create mode 100644 plugins/vps-manager/CHANGELOG.md create mode 100644 plugins/vps-manager/README.md create mode 100644 plugins/vps-manager/docs/MCP.md create mode 100644 plugins/vps-manager/index.html create mode 100644 plugins/vps-manager/logo.svg create mode 100644 plugins/vps-manager/package-lock.json create mode 100644 plugins/vps-manager/package.json create mode 100644 plugins/vps-manager/plugin.json create mode 100644 plugins/vps-manager/preload/clash-api.cjs create mode 100644 plugins/vps-manager/preload/config-store.cjs create mode 100644 plugins/vps-manager/preload/deploy-templates.cjs create mode 100644 plugins/vps-manager/preload/embedded-proxy.cjs create mode 100644 plugins/vps-manager/preload/http-client.cjs create mode 100644 plugins/vps-manager/preload/ip-check.cjs create mode 100644 plugins/vps-manager/preload/mcp-tools.cjs create mode 100644 plugins/vps-manager/preload/native-core.cjs create mode 100644 plugins/vps-manager/preload/package-lock.json create mode 100644 plugins/vps-manager/preload/package.json create mode 100644 plugins/vps-manager/preload/services.cjs create mode 100644 plugins/vps-manager/preload/ssh-client.cjs create mode 100644 plugins/vps-manager/preload/system-proxy.cjs create mode 100644 plugins/vps-manager/scripts/ensure-preload-deps.mjs create mode 100644 plugins/vps-manager/scripts/prepare-dist.mjs create mode 100644 plugins/vps-manager/scripts/verify-dist.mjs create mode 100644 plugins/vps-manager/skills/vps-manager/SKILL.md create mode 100644 plugins/vps-manager/skills/vps-manager/references/ip-diagnostics.md create mode 100644 plugins/vps-manager/skills/vps-manager/references/proxy-routing.md create mode 100644 plugins/vps-manager/skills/vps-manager/references/safe-deploy.md create mode 100644 plugins/vps-manager/skills/vps-manager/references/vps-ops.md create mode 100644 plugins/vps-manager/src/App.tsx create mode 100644 plugins/vps-manager/src/components/ConfirmDialog.tsx create mode 100644 plugins/vps-manager/src/components/DeployDrawer.tsx create mode 100644 plugins/vps-manager/src/components/EndpointModal.tsx create mode 100644 plugins/vps-manager/src/components/IpCheckPanel.tsx create mode 100644 plugins/vps-manager/src/components/McpSkillsModal.tsx create mode 100644 plugins/vps-manager/src/components/ProxyHomePanel.tsx create mode 100644 plugins/vps-manager/src/components/QrCodeBox.tsx create mode 100644 plugins/vps-manager/src/components/RulesPanel.tsx create mode 100644 plugins/vps-manager/src/components/RulesTable.tsx create mode 100644 plugins/vps-manager/src/components/ServerOpsDrawer.tsx create mode 100644 plugins/vps-manager/src/components/ServersPanel.tsx create mode 100644 plugins/vps-manager/src/components/VpsProfileModal.tsx create mode 100644 plugins/vps-manager/src/lib/format.ts create mode 100644 plugins/vps-manager/src/lib/storage.ts create mode 100644 plugins/vps-manager/src/lib/usePreservedScroll.ts create mode 100644 plugins/vps-manager/src/main.tsx create mode 100644 plugins/vps-manager/src/styles.css create mode 100644 plugins/vps-manager/src/types.ts create mode 100644 plugins/vps-manager/src/ztools.d.ts create mode 100644 plugins/vps-manager/tests/preload/preload.test.cjs create mode 100644 plugins/vps-manager/tests/unit/format.test.ts create mode 100644 plugins/vps-manager/tsconfig.json create mode 100644 plugins/vps-manager/vite.config.ts diff --git a/plugins/vps-manager/.gitignore b/plugins/vps-manager/.gitignore new file mode 100644 index 000000000..0793b5bb2 --- /dev/null +++ b/plugins/vps-manager/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +preload/node_modules/ +*.zpx +.DS_Store diff --git a/plugins/vps-manager/CHANGELOG.md b/plugins/vps-manager/CHANGELOG.md new file mode 100644 index 000000000..28a897506 --- /dev/null +++ b/plugins/vps-manager/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +## 0.1.0 - 2026-12-01 + +### Added +- 新增 VPS 运维台与操作安全门禁:支持密码、SSH Key、本地 `~/.ssh` 自动扫描与 `~/.ssh/config` 导入,提供 1s 实时资源监控、systemd 代理服务启停与日志查看,以及针对所有修改服务器操作(部署、写入配置、服务控制、Shell 执行、远端控制器修改)的强制二次确认弹窗。 +- 新增内置零依赖一键代理与智能无感切换:不依赖本机外部代理客户端与固定 `7890` 端口,支持 macOS / Windows / Linux 三端系统代理自动接管与退出清理;支持 SSH 隧道与原生高速协议(VLESS / Hysteria2 / SS)测速自动无感切换,并自动将服务端 `sing-box` / `Xray` / `MATCH,DIRECT` 配置适配为客户端安全分流。 +- 新增一键代理部署中心:支持在 Debian / Ubuntu / CentOS / Alpine VPS 部署 `sing-box`(VLESS+Vision+Reality / Hysteria2)、`Xray-core`、`Mihomo`、`Hysteria2` 与 `Shadowsocks-rust`,部署后自动生成 Shadowrocket 分享链接、二维码与 Clash/Mihomo YAML 配置。 +- 新增真实服务器分流分组与规则编排:按服务器现有真实 `proxy-groups` 与规则动态渲染分组卡片与筛选(无服务部署时回退标准模板),支持本地文件、VPS SFTP、订阅链接及非 YAML 原始 JSON 配置编辑。 +- 新增多维度 IP 纯净度与分流检测:提供出口 IP / IPv4 / IPv6 双栈探测、归属地与 ASN 风险评估、Claude AI 与流媒体解锁矩阵、国内/海外双出口分流对比及 DNS / WebRTC 泄露自查。 +- 新增内置 MCP Tools 与 Agent Skills 能力中心:暴露 12 个 `vps_*` 工具(所有写操作均强制 `confirm + confirmHost` 两步确认并自动脱敏凭据),内置 5 份可随时加载的运维与诊断 Skill 文档。 +- 优化交互与多页面体验:全量支持一级 Tab 与子 Tab 状态保活、滚动位置记忆、切回静默刷新、丝滑入场动效及单入口按钮精简。 diff --git a/plugins/vps-manager/README.md b/plugins/vps-manager/README.md new file mode 100644 index 000000000..17ce9baca --- /dev/null +++ b/plugins/vps-manager/README.md @@ -0,0 +1,50 @@ +# VPS 代理与运维管家 (`vps-manager`) + +面向开发者与运维人员的 ZTools 跨平台(macOS / Windows / Linux)VPS 管理与代理编排插件,集成了 **SSH 服务器运维**、**零依赖内置一键代理与智能通道切换**、**一键部署代理服务端 & Shadowrocket/Clash 导出**、**真实服务器分流编排**、**多维度 IP 纯净度检测** 以及 **内置 MCP Tools & Agent Skills**。 + +## 核心功能 + +1. **VPS 运维台与强制二次确认** + - 多服务器档案管理(支持密码、私钥文本或本地 `~/.ssh` 私钥自动扫描,以及 `~/.ssh/config` 主机导入与一键 SSH 端口转发隧道)。 + - 实时系统监控:OS / 内核、运行时长、CPU 核心与使用率、内存 / Swap、磁盘、网卡实时 RX/TX 速率、监听端口与常见代理服务状态。 + - `systemd` 服务管理:一键启停/重启 `sing-box`、`xray`、`mihomo`、`hysteria-server`、`shadowsocks-rust` 并查看 `journalctl` 最近日志。 + - **安全门禁**:所有修改远端服务器配置、文件、服务状态或执行命令行操作前均强制弹出二次确认对话框。 + +2. **内置零依赖一键代理 & 智能无感切换** + - 不依赖本机额外运行 `7890` 客户端,开启即自动分配空闲本地端口提供 HTTP / HTTPS / SOCKS5 混合代理,并自动接管 macOS / Windows / Linux 系统代理(关闭或退出插件自动还原)。 + - 支持 **纯 SSH 通道**、**原生高速协议(VLESS / Hysteria2 / SS)** 及 **智能切换**(SSH 高延迟或连续受阻时自动无感切换至原生协议)。 + - 自动将服务端 `sing-box` / `Xray` / `MATCH,DIRECT` 规则适配为客户端分流(「国内与局域网直连、海外走 VPS」),防止海外流量漏回本地网关。 + +3. **一键部署代理服务端 + Shadowrocket / Clash 导出** + - 支持一键在 Debian / Ubuntu / CentOS / Alpine VPS 上安装配置 `sing-box`、`Xray-core`、`Mihomo (Clash Meta)`、`Hysteria 2` 与 `Shadowsocks-rust`。 + - 自动生成 UUID、Reality x25519 密钥对与随机密码,支持部署前脚本与服务端配置预览。 + - 部署后立即生成 **Shadowrocket 分享链接与二维码** 与 **Clash / Mihomo YAML 配置**,并自动绑定原生高速节点。 + +4. **真实服务器分流分组与规则编排 + Clash 控制** + - 自动同步并按服务器真实 `proxy-groups` 与规则动态构建分组开关(服务器未部署代理时才回退预设模板),支持可视化规则增删改查、批量策略切换与原始 JSON 源码编辑。 + - 外部 Clash 控制器模式支持直连或经 SSH 隧道连接 REST API,控制运行模式、策略组节点切换、并发测速、活跃连接与实时规则。 + +5. **多维度 IP 纯净度与分流检测** + - 支持「本机代理」「本机直连」「VPS 出口实测」「查指定 IP」四模式独立结果保留。 + - 检查真实出口 IPv4 / IPv6、ASN 机房/住宅归属、Claude AI 信任评分、ChatGPT / Gemini / Netflix / YouTube 等解锁状态、国内直连与代理分流对比,以及 DNS / WebRTC 泄露自查。 + +6. **内置 MCP Tools & Agent Skills** + - 内置 12 个 `vps_*` MCP 工具,外部 Agent 调用远端修改类工具时强制经过 `confirm + confirmHost` 二次确认与凭据脱敏保护;插件内附 5 份系统化 Agent Skill 文档。 + +## 开发与构建 + +```bash +# 安装前端开发依赖与 preload 运行时依赖 +npm install +npm run ensure:preload + +# 开发模式 +npm run dev + +# 类型检查与完整测试(Preload + Unit) +npm run typecheck +npm test + +# 构建并校验 dist/ 发布产物(含 5MB 体积门禁) +npm run build +``` diff --git a/plugins/vps-manager/docs/MCP.md b/plugins/vps-manager/docs/MCP.md new file mode 100644 index 000000000..d8686a2d0 --- /dev/null +++ b/plugins/vps-manager/docs/MCP.md @@ -0,0 +1,32 @@ +# VPS 代理与运维管家 — 内置 MCP Tools & Skills 使用说明 + +本插件原生内置 **ZTools HTTP MCP Tools** 与 **Agent Skill(`skills/vps-manager/`)**,支持在 ZTools AI / 外部编码 Agent(Claude Code、Codex、Cursor、Antigravity 等)中直接调用服务器运维、代理调控、分流编排与 IP 诊断能力。 + +## 启用方法(ZTools 3.0+) + +1. 在 ZTools 中安装或加载本插件(开发加载根目录 `plugin.json`,打包加载 `dist/plugin.json`)。 +2. 打开 **ZTools 设置 → MCP 服务** 并启用内置 HTTP MCP Server,复制服务地址(endpoint)与 API Key(使用 `Authorization: Bearer `)。 +3. 外部 MCP 客户端执行 `tools/list` 后即可看到以插件为前缀的 12 个工具(例如 `vps_manager_vps_list_servers`)。 +4. 插件右上角点击 **`MCP / Skills`** 按钮可随时查看全部工具状态、权限级别与内置 Skill 文档内容。 + +## 内置工具列表 + +### 只读 / 诊断类工具 +- `vps_list_servers`:列出已保存 VPS(密码/私钥全脱敏)、SSH 隧道与本机 `~/.ssh/config` 主机。 +- `vps_get_metrics`:采集 VPS CPU、内存、磁盘、网速、BBR、端口与代理 systemd 服务状态。 +- `vps_discover_proxy`:扫描服务器上已有代理内核、配置文件路径、端口及分流规则摘要。 +- `clash_get_status`:查看 Clash / Mihomo 控制器运行模式、端口、策略组与当前节点。 +- `clash_test_delay`:对指定代理或策略组并发测速。 +- `ip_check`:执行多维度 IP 纯净度、Claude AI 信任评分、流媒体解锁、网站真实分流与 DNS 泄露检测。 +- `vps_load_skill`:读取插件内置 `SKILL.md` 及场景操作指南。 + +### 修改类工具(强制两步二次确认) +- `vps_manage_service`:`start` / `stop` / `restart` 必须传 `confirm: true` 且 `confirmHost` 等于目标 VPS 主机地址,否则仅返回确认预览。 +- `vps_deploy_proxy`:`execute: false` 仅生成预览;`execute: true` 必须同时携带 `confirm: true` 与 `confirmHost`。 +- `vps_exec_command`:执行 SSH Shell 命令前必须先预览并由用户在对话中明确确认,再携带 `confirm: true` 与 `confirmHost` 调用。 +- `clash_switch_proxy`:本地回环控制可直接执行;涉及 SSH 隧道或非回环远端服务器控制器时强制要求 `confirm: true` 与 `confirmHost`。 +- `vps_sync_rules`:`preview` 为只读;`add_rule` / `remove_rule` / `push_yaml` 必须携带 `confirm: true` 与 `confirmHost`,并在远端自动备份 `.bak` 后重载服务。 + +## 使用内置 Skills + +可将插件目录下的 `skills/vps-manager` 软链或复制到你的 Agent Skills 目录(例如 `~/.agents/skills/vps-manager`),或在对话中直接调用 MCP 工具 `vps_load_skill({ skill: "overview" })` 读取完整工作流与安全协议。 diff --git a/plugins/vps-manager/index.html b/plugins/vps-manager/index.html new file mode 100644 index 000000000..606d23534 --- /dev/null +++ b/plugins/vps-manager/index.html @@ -0,0 +1,12 @@ + + + + + + VPS 代理与运维管家 + + +
+ + + diff --git a/plugins/vps-manager/logo.svg b/plugins/vps-manager/logo.svg new file mode 100644 index 000000000..088a02be4 --- /dev/null +++ b/plugins/vps-manager/logo.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/vps-manager/package-lock.json b/plugins/vps-manager/package-lock.json new file mode 100644 index 000000000..de220632a --- /dev/null +++ b/plugins/vps-manager/package-lock.json @@ -0,0 +1,2412 @@ +{ + "name": "ztools-vps-manager", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ztools-vps-manager", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "lucide-react": "^0.511.0", + "qrcode": "^1.5.4", + "react": "^19.1.0", + "react-dom": "^19.1.0" + }, + "devDependencies": { + "@types/node": "^22.15.0", + "@types/qrcode": "^1.5.5", + "@types/react": "^19.1.0", + "@types/react-dom": "^19.1.0", + "@vitejs/plugin-react": "^4.4.1", + "@ztools-center/ztools-api-types": "^1.0.1", + "typescript": "^5.8.3", + "vite": "^6.3.5", + "vitest": "^3.1.3" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.15", + "@babel/types": "^7.29.15", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.15", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.15" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.15", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.15", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.15", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.8.tgz", + "integrity": "sha512-7l9FdeCGjhmMTVePgndK4t9u5tLR+VuTTMoyc0PscqZDdYjS07ZsQ0vQYsWsODu/ZZYPG7WVJwbUZ77n1hVT+w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.8.tgz", + "integrity": "sha512-kXkkIiJujBjArHwEToz99BQqIqibn4xdV6SjsoaxuZzvLUCVEzoHQ1Lp62m7xOhpLRpWpCtxL2ZUy/ADKuz9/g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.8.tgz", + "integrity": "sha512-KYoBygnHs3zUOLR0z7SaqhMnUrSF9pbuTOJT/uHK3PrgCXdv/xaMubZD8jCpg6NTo46deasLgZRq38xFTyu8uw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.8", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.8.tgz", + "integrity": "sha512-XMX5ybuOmkwiM13KJtsBxakZ69pyaR9thRYU2fMejhaB0VuzLMIkIc+9TBsu2rv34eEf6XaSMOaLOyEgHGWHTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.8.tgz", + "integrity": "sha512-WuBXScWJDaqPJKwVrotUe1sM9DHWMN937C23RClt0MVHVt7A1rBy285ZfZTLccPEVMxmGJMt2jvdHMOI33lrKA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.8.tgz", + "integrity": "sha512-kegwGqP3rMenEMaKo8OzMBb5WvLW2h2jrQ3iKuYptTTF8C/yuxz+hinjBPrtYuIPLJDwxHc/hv2e4u5pmrqo9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.8.tgz", + "integrity": "sha512-Qct0oLM1zGNbvqs1udQnuchg+Q9uHbkMcQqCfs3M7foNn7HvEkUypfFn9o5fklimUI5OF3A2nMknd4/vrEyeVg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.8.tgz", + "integrity": "sha512-xTH5vD+lW/5MU3kL/Op8RSSG/O9fxUQZuJcSBmmBeYem9uXYvCq6PDHx/oDSNeyLD/p4pGujG2PVI0R8MjAhSw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.8.tgz", + "integrity": "sha512-lPPStmynSHvwWpSrAsuemPFB+EWFObXjwz44EK4Hph47U6SBAk1Kehq5MkI7i8EYVjrXddaAV7YkJH8mX8QSZQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.8.tgz", + "integrity": "sha512-kZkvIYAihM6l6M+giSUHayDDf/JL+TYR5bYWiAX7/jUFWvMkMmysA4GV2F0HOsXQNEyctW3x1xLjww1GqW7Q1w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.8.tgz", + "integrity": "sha512-XZKLEIY977OJr6zUtK6nlQcLXme34c8HqVp3+WmKQxKVN6Nj+b9qE3ZHWIDHXznHJsGl2AsaMOgB0GL0fkZGUg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.8.tgz", + "integrity": "sha512-+sN+Fj6F9suk8SkL6boIfXDmj9iJwSKPCTeCy8/pfTOHuzNX+duhTb9uyj6154oVK8Odl5zgL4DXRZzXjsRKcw==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.8.tgz", + "integrity": "sha512-EBCu3uDFaGwSodUl+XR8yubvVFUkSo6QK9YAIOV1vljqntzTF2/mXLM6utgLaSGf/8oM+qEe8Ai0Jd4+tyMoIQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.8.tgz", + "integrity": "sha512-hRC0jWdsLBckCijx2wiUfk7zW1SqEW47yMsCNoDGmQfoqq0AjW+9UYZqxg3LTmG76PyHNdNGBSuspB3CqrhGIA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.8.tgz", + "integrity": "sha512-OZKrTRWyGnLITUTipbeXDdtb2dxQPyFk/Fbw9qER8pIvd2Ja9hHELkY0Fv5p9yYYkimqtzVhApKKXGv0cWGQGw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.8.tgz", + "integrity": "sha512-HmhSRSQ+dOeOntPfmYux4rCpOQLtsGbcGLQu4nm8ig3tuVqe/bKfDHorg36LKAqYq4X/nwFr79ImtaFHHsn4ug==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.8.tgz", + "integrity": "sha512-wk1Ci1hsMREaBELoKPSnzRAh1oUULI+8kfb2F5vVmTD2IcfR9AKMskCusizZhIAvojOtPZihPj4OdKy6ifZwhQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.8.tgz", + "integrity": "sha512-mDufoUJ6fnKZnCyjV3sGEDvXQQkM6j1UmINHheGX4Emau3TZWJzX3sCVmbzkNB+W2G84BiFQdDCcF09lv0i0VA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.8.tgz", + "integrity": "sha512-7EGVL9rYRYQZe3UC8JQzfBN9rxk484Rfs4u/yGWumTYKUdJt6tmdP+0Y3qHvAvzJCQ+JQM5rSqZbVyrJARlGpA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.8.tgz", + "integrity": "sha512-Umklz+QSGwKWQVlVrsMJrwFx1oNRYHgrxSGiZM8pJCMpzWnMDMinDhPILf0BvRXfA1QOArsDcs+AE7Jd6dQxvA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.8.tgz", + "integrity": "sha512-BlRp6uzQDK5rczAdaXQ8dlSIRFRlkDRBqpb8GGtv8iwZxQdOjoigdFU5t5dcxpnpU0caMoT9mH27MyAl4dWwKw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.8.tgz", + "integrity": "sha512-Sc8Mkf/fVfcV0hBJNDRIM82BjS4kJn2Of0jP8dgQ+TodquxtCZ/5D6FgSsY3uN5IBmNi8Zrb/OHd60IEYKaw+Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.8.tgz", + "integrity": "sha512-XPTFXclN+I+Cfu3ONWDsw+uvgSZjTJa1B2u2EvtdKlSdgNU6mrOZdgeaMkvN+2T2KPTEXn6fnRY8IODlRg3/Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.8.tgz", + "integrity": "sha512-63dWiHgvpWcienfdr465lT3SIn4u3535vbDfaLKhSn0F2KJ06bbcUsewDGJZUPZCbJ67qESrPDhb85UnWdb5ew==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.8.tgz", + "integrity": "sha512-/W1LBsMeQAdiCuH3Z2gkRspl3mlxL+butknhq4vXjmxO45vuT08BqhehxDoE4YS+m6s9lhpq6M9/PjTEAg8PYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.11", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.7", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/react": { + "version": "19.3.3", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@ztools-center/ztools-api-types": { + "version": "1.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.40", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.6", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001828", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "5.3.3", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.4", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.495", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "0.511.0", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.66", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pngjs": { + "version": "5.0.0", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/postcss": { + "version": "8.5.34", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.4" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/qrcode": { + "version": "1.5.4", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/react": { + "version": "19.3.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/rollup": { + "version": "4.68.8", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.8", + "@rollup/rollup-android-arm64": "4.68.8", + "@rollup/rollup-android-x64": "4.68.8", + "@rollup/rollup-darwin-arm64": "4.68.8", + "@rollup/rollup-darwin-x64": "4.68.8", + "@rollup/rollup-freebsd-arm64": "4.68.8", + "@rollup/rollup-freebsd-x64": "4.68.8", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.8", + "@rollup/rollup-linux-arm-musleabihf": "4.68.8", + "@rollup/rollup-linux-arm64-gnu": "4.68.8", + "@rollup/rollup-linux-arm64-musl": "4.68.8", + "@rollup/rollup-linux-loong64-gnu": "4.68.8", + "@rollup/rollup-linux-loong64-musl": "4.68.8", + "@rollup/rollup-linux-ppc64-gnu": "4.68.8", + "@rollup/rollup-linux-ppc64-musl": "4.68.8", + "@rollup/rollup-linux-riscv64-gnu": "4.68.8", + "@rollup/rollup-linux-riscv64-musl": "4.68.8", + "@rollup/rollup-linux-s390x-gnu": "4.68.8", + "@rollup/rollup-linux-x64-gnu": "4.68.8", + "@rollup/rollup-linux-x64-musl": "4.68.8", + "@rollup/rollup-openbsd-x64": "4.68.8", + "@rollup/rollup-openharmony-arm64": "4.68.8", + "@rollup/rollup-win32-arm64-msvc": "4.68.8", + "@rollup/rollup-win32-ia32-msvc": "4.68.8", + "@rollup/rollup-win32-x64-gnu": "4.68.8", + "@rollup/rollup-win32-x64-msvc": "4.68.8", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.2", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/siginfo": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/strip-literal/node_modules/js-tokens": { + "version": "9.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.4.0", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.6", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "license": "ISC" + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "license": "ISC" + }, + "node_modules/yallist": { + "version": "3.1.1", + "dev": true, + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/plugins/vps-manager/package.json b/plugins/vps-manager/package.json new file mode 100644 index 000000000..7caba4d09 --- /dev/null +++ b/plugins/vps-manager/package.json @@ -0,0 +1,39 @@ +{ + "name": "ztools-vps-manager", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "VPS operations, one-click proxy deployment (sing-box / Xray / Mihomo / Hysteria2 / SS), Shadowrocket/Clash export, and Clash/Mihomo node & rule controller for ZTools.", + "license": "MIT", + "scripts": { + "dev": "vite --host 127.0.0.1 --port 5195", + "ensure:preload": "node scripts/ensure-preload-deps.mjs", + "typecheck": "tsc --noEmit", + "test": "npm run test:preload && npm run test:unit", + "test:preload": "npm run ensure:preload && node --test tests/preload/*.test.cjs", + "test:unit": "vitest run tests/unit", + "build": "npm run ensure:preload && npm run typecheck && npm test && vite build && node scripts/prepare-dist.mjs && npm run verify:dist", + "verify:dist": "node scripts/verify-dist.mjs", + "preview": "vite preview --host 127.0.0.1 --port 4195" + }, + "dependencies": { + "lucide-react": "^0.511.0", + "qrcode": "^1.5.4", + "react": "^19.1.0", + "react-dom": "^19.1.0" + }, + "devDependencies": { + "@types/node": "^22.15.0", + "@types/qrcode": "^1.5.5", + "@types/react": "^19.1.0", + "@types/react-dom": "^19.1.0", + "@vitejs/plugin-react": "^4.4.1", + "@ztools-center/ztools-api-types": "^1.0.1", + "typescript": "^5.8.3", + "vite": "^6.3.5", + "vitest": "^3.1.3" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/plugins/vps-manager/plugin.json b/plugins/vps-manager/plugin.json new file mode 100644 index 000000000..d37db065f --- /dev/null +++ b/plugins/vps-manager/plugin.json @@ -0,0 +1,440 @@ +{ + "$schema": "node_modules/@ztools-center/ztools-api-types/resource/ztools.schema.json", + "name": "vps-manager", + "title": "VPS 代理与运维管家", + "description": "SSH 管理 VPS 服务器,一键部署 sing-box / Xray / Mihomo / Hysteria2 / Shadowsocks,生成 Shadowrocket 分享链接与二维码,支持 Clash/Mihomo 节点切换、测速与分流规则编辑,内置 MCP Tools 与 Agent Skills。", + "author": "harris", + "version": "0.1.0", + "main": "dist/index.html", + "preload": "preload/services.cjs", + "logo": "logo.svg", + "categories": ["network"], + "platform": ["darwin", "win32", "linux"], + "pluginSetting": { + "single": true, + "height": 760, + "backgroundRunning": true + }, + "features": [ + { + "code": "vps-manager", + "explain": "打开 VPS 代理与运维管家(服务器监控、SSH 运维、代理一键部署)", + "icon": "logo.svg", + "cmds": [ + "vps", + "VPS 管理", + "服务器管理", + "一键部署代理", + "SSH 运维" + ] + }, + { + "code": "proxy-controller", + "explain": "Clash / Mihomo 节点切换、延迟测速与代理模式控制", + "icon": "logo.svg", + "cmds": [ + "clash", + "mihomo", + "切换节点", + "代理切换", + "节点测速" + ] + }, + { + "code": "deploy-proxy", + "explain": "在 VPS 一键部署代理服务端并生成 Shadowrocket 二维码与 Clash 配置", + "icon": "logo.svg", + "cmds": [ + "shadowrocket", + "部署 clash", + "部署 sing-box", + "部署 xray", + "小火箭" + ] + }, + { + "code": "rule-editor", + "explain": "编辑本地或远端 Clash / Mihomo 分流规则与订阅配置", + "icon": "logo.svg", + "cmds": [ + "代理规则", + "分流规则", + "Clash 规则", + "规则编辑器" + ] + }, + { + "code": "ip-check", + "explain": "多维度 IP 查询、纯净度评分、Claude / AI / 流媒体解锁、网站分流与 WebRTC/DNS 泄露检测", + "icon": "logo.svg", + "cmds": [ + "ip检测", + "ip查询", + "纯净度检测", + "分流测试", + "claude检测" + ] + } + ], + "tools": { + "vps_list_servers": { + "title": "列出 VPS 服务器与隧道", + "description": "只读列出已保存的 VPS 服务器档案(自动脱敏密码与私钥)、活跃 SSH 隧道以及可选本机 ~/.ssh/config 主机。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "includeLocalSsh": { + "type": "boolean", + "description": "是否同时读取本机 ~/.ssh/config 中的主机列表" + } + } + } + }, + "vps_get_metrics": { + "title": "采集 VPS 运维监控", + "description": "只读采集目标 VPS 的 CPU、内存、磁盘、网速、BBR、监听端口和 systemd 代理服务状态。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "server": { + "type": "string", + "description": "服务器名称、ID 或主机 IP;留空默认使用当前选中或第一台 VPS" + }, + "light": { + "type": "boolean", + "description": "轻量采集模式(跳过端口和 BBR 探测)" + } + } + } + }, + "vps_discover_proxy": { + "title": "扫描服务器已有代理配置", + "description": "只读扫描目标 VPS 上已安装或运行中的代理内核、配置文件路径、端口、节点数与前 50 条分流规则摘要。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "server": { + "type": "string", + "description": "服务器名称、ID 或主机 IP;留空默认当前选中 VPS" + }, + "configPath": { + "type": "string", + "description": "指定要读取的远端配置文件路径" + } + } + } + }, + "vps_manage_service": { + "title": "控制 VPS 代理服务", + "description": "status/logs 为只读;start/stop/restart 修改远端 systemd 服务状态,强制要求先返回预览并在用户明确同意后传 confirm=true 与 confirmHost。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "server": { + "type": "string", + "description": "目标服务器名称、ID 或 IP" + }, + "serviceName": { + "type": "string", + "description": "服务名,例如 sing-box、xray、mihomo、clash、hysteria-server、ssserver" + }, + "action": { + "type": "string", + "enum": ["status", "logs", "start", "stop", "restart"], + "description": "操作类型" + }, + "confirm": { + "type": "boolean", + "description": "仅用户二次确认后设为 true(start/stop/restart 必填)" + }, + "confirmHost": { + "type": "string", + "description": "必须精确等于目标 VPS 的 host(IP 或域名)" + } + }, + "required": ["serviceName", "action"] + } + }, + "vps_deploy_proxy": { + "title": "一键部署代理服务", + "description": "生成代理部署配置、Shadowrocket URI 与 Clash YAML;仅当 execute=true 且同时传入 confirm=true 与匹配 confirmHost 时才通过 SSH 真实写入服务器。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "server": { + "type": "string", + "description": "目标 VPS 名称、ID 或主机 IP" + }, + "protocol": { + "type": "string", + "enum": ["singbox-reality", "xray-reality", "hysteria2", "mihomo-node", "ss-rust"], + "description": "部署协议" + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "description": "服务端监听端口" + }, + "host": { + "type": "string", + "description": "客户端连接地址(默认同 VPS host)" + }, + "sni": { + "type": "string", + "description": "TLS/Reality 伪装域名" + }, + "nodeName": { + "type": "string", + "description": "导出的节点名称" + }, + "ssMethod": { + "type": "string", + "enum": ["2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm"], + "description": "Shadowsocks 2022 加密套件" + }, + "openFirewall": { + "type": "boolean", + "description": "是否放行防火墙端口(默认 true)" + }, + "exposeController": { + "type": "boolean", + "description": "是否对外暴露 Mihomo Controller(默认 false)" + }, + "execute": { + "type": "boolean", + "description": "false 仅预览生成配置;true 时执行 SSH 部署(须配合 confirm/confirmHost)" + }, + "confirm": { + "type": "boolean", + "description": "execute=true 时必须为 true" + }, + "confirmHost": { + "type": "string", + "description": "必须精确等于目标 VPS 的 host" + } + }, + "required": ["protocol"] + } + }, + "vps_exec_command": { + "title": "SSH 执行运维命令", + "description": "在目标 VPS 上执行 Shell 命令。始终强制两步二次确认:未传 confirm=true 与匹配 confirmHost 时仅返回待确认命令预览。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "server": { + "type": "string", + "description": "目标服务器名称、ID 或 IP" + }, + "command": { + "type": "string", + "minLength": 1, + "description": "拟执行的远端 Shell 命令" + }, + "timeoutMs": { + "type": "integer", + "minimum": 1000, + "maximum": 180000 + }, + "confirm": { + "type": "boolean", + "description": "仅用户二次确认后设为 true" + }, + "confirmHost": { + "type": "string", + "description": "必须精确等于目标 VPS 的 host" + } + }, + "required": ["command"] + } + }, + "clash_get_status": { + "title": "获取 Clash / Mihomo 状态", + "description": "只读查询本地或远端 Clash 控制器的版本、运行模式、策略组与当前选中节点。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "endpoint": { + "type": "string", + "description": "控制器端点名称、ID 或 URL(例如 http://127.0.0.1:9090);留空默认当前选中控制器" + }, + "includeRules": { + "type": "boolean", + "description": "是否附带前 40 条运行规则样本" + }, + "includeConnections": { + "type": "boolean", + "description": "是否附带活跃连接数与总流量汇总" + } + } + } + }, + "clash_switch_proxy": { + "title": "切换 Clash 节点或模式", + "description": "切换 Clash 运行模式、策略组节点或重载配置;涉及远端或 SSH 隧道控制器时强制要求 confirm=true 与 confirmHost。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "endpoint": { + "type": "string", + "description": "控制器端点名称、ID 或 URL" + }, + "action": { + "type": "string", + "enum": ["set_mode", "select_proxy", "reload"], + "description": "操作类型" + }, + "mode": { + "type": "string", + "enum": ["direct", "rule", "global"], + "description": "action=set_mode 时必填" + }, + "groupName": { + "type": "string", + "description": "策略组名称(action=select_proxy 时必填)" + }, + "proxyName": { + "type": "string", + "description": "目标节点名称(action=select_proxy 时必填)" + }, + "configPath": { + "type": "string", + "description": "可选重载配置文件路径" + }, + "confirm": { + "type": "boolean", + "description": "远端或隧道控制器修改时必填 true" + }, + "confirmHost": { + "type": "string", + "description": "远端控制器主机名或名称" + } + }, + "required": ["action"] + } + }, + "clash_test_delay": { + "title": "代理节点延迟测速", + "description": "只读测试指定代理节点或策略组下全部节点的延迟并返回按耗时升序结果。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "endpoint": { + "type": "string", + "description": "控制器端点名称、ID 或 URL" + }, + "proxyName": { + "type": "string", + "description": "单个节点名称;若不填则测整个策略组" + }, + "groupName": { + "type": "string", + "description": "策略组名称;默认测第一个非内置策略组" + }, + "testUrl": { + "type": "string", + "description": "测速 URL(默认 gstatic generate_204)" + }, + "timeout": { + "type": "integer", + "minimum": 500, + "maximum": 15000 + } + } + } + }, + "vps_sync_rules": { + "title": "预览或同步远端分流规则", + "description": "preview 只读预览;add_rule/remove_rule/push_yaml 会修改服务器配置文件并重启/重载服务,强制要求先预览确认并传 confirm=true 与 confirmHost。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "server": { + "type": "string", + "description": "目标 VPS 名称、ID 或 IP" + }, + "action": { + "type": "string", + "enum": ["preview", "add_rule", "remove_rule", "push_yaml"], + "description": "操作类型" + }, + "remotePath": { + "type": "string", + "description": "远端配置文件路径(留空则自动识别)" + }, + "rule": { + "type": "string", + "description": "add_rule 或 remove_rule 时传入的规则文本,如 DOMAIN-SUFFIX,openai.com,🤖 AI 服务" + }, + "yamlText": { + "type": "string", + "description": "push_yaml 时传入的完整 YAML 文本" + }, + "confirm": { + "type": "boolean", + "description": "写操作确认标志,必须为 true 才实际写入服务器" + }, + "confirmHost": { + "type": "string", + "description": "必须精确等于目标 VPS 的 host" + } + }, + "required": ["action"] + } + }, + "ip_check": { + "title": "IP 纯净度与分流检测", + "description": "只读执行多维度 IP 检测(本机代理/本机直连/VPS 出口/指定 IP):归属地 ASN、Claude 风险评分、流媒体解锁、网站真实分流及 DNS 泄露排查。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "mode": { + "type": "string", + "enum": ["proxy", "direct", "vps", "custom-ip"], + "description": "检测模式" + }, + "proxyUrl": { + "type": "string", + "description": "mode=proxy 时的本地代理地址,默认 http://127.0.0.1:7890" + }, + "server": { + "type": "string", + "description": "mode=vps 时的目标 VPS 名称、ID 或 IP" + }, + "customIp": { + "type": "string", + "description": "mode=custom-ip 时的目标 IPv4 或 IPv6 地址" + } + }, + "required": ["mode"] + } + }, + "vps_load_skill": { + "title": "读取内置 Skill 指南", + "description": "只读加载本插件内置的 Agent Skill (SKILL.md) 及操作规范手册(vps-ops / proxy-routing / safe-deploy / ip-diagnostics)。", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "skill": { + "type": "string", + "enum": ["overview", "vps-ops", "proxy-routing", "safe-deploy", "ip-diagnostics"], + "description": "要加载的指南章节(默认 overview)" + } + } + } + } + } +} diff --git a/plugins/vps-manager/preload/clash-api.cjs b/plugins/vps-manager/preload/clash-api.cjs new file mode 100644 index 000000000..e578a15fe --- /dev/null +++ b/plugins/vps-manager/preload/clash-api.cjs @@ -0,0 +1,191 @@ +const httpClient = require('./http-client.cjs') + +function normalizeBaseUrl(rawUrl) { + const input = String(rawUrl || '').trim().replace(/\/+$/, '') + if (!input) { + throw new Error('Clash/Mihomo Controller 地址不能为空') + } + const withScheme = /^https?:\/\//i.test(input) ? input : `http://${input}` + const parsed = new URL(withScheme) + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new Error('仅支持 http:// 或 https:// 协议的 Controller 地址') + } + return parsed.origin +} + +async function requestJson(endpoint, method, apiPath, body, timeoutMs = 8000) { + const baseUrl = normalizeBaseUrl(endpoint?.baseUrl) + const secret = String(endpoint?.secret || '').trim() + const headers = { + Accept: 'application/json' + } + if (secret) { + headers.Authorization = `Bearer ${secret}` + } + if (body !== undefined) { + headers['Content-Type'] = 'application/json' + } + + let res + try { + res = await httpClient.request(`${baseUrl}${apiPath}`, { + method, + headers, + body: body !== undefined ? JSON.stringify(body) : undefined, + timeoutMs + }) + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + if (msg.includes('端口未监听')) { + throw new Error(`无法连接到代理控制器 (${baseUrl}):端口未监听,请启动本机 Clash/Mihomo 或通过「服务器 → SSH 隧道」转发远端控制器`) + } + throw new Error(msg) + } + + if (res.status === 204) { + return { ok: true } + } + + const text = res.text || '' + let parsed = null + if (text) { + try { + parsed = JSON.parse(text) + } catch { + parsed = text + } + } + + if (!res.ok) { + const detail = (parsed && typeof parsed === 'object' && parsed.message) || text || res.statusText + throw new Error(`Controller API (${res.status}): ${detail}`) + } + + return parsed +} + +async function getOverview(endpoint) { + const [version, configs, proxies] = await Promise.all([ + requestJson(endpoint, 'GET', '/version').catch(() => ({ version: 'unknown' })), + requestJson(endpoint, 'GET', '/configs'), + requestJson(endpoint, 'GET', '/proxies') + ]) + return { + version, + configs, + proxies: proxies?.proxies || {} + } +} + +async function patchConfigs(endpoint, patch) { + return requestJson(endpoint, 'PATCH', '/configs', patch) +} + +async function reloadConfig(endpoint, configPath = '') { + const payload = configPath ? { path: String(configPath) } : { path: '' } + return requestJson(endpoint, 'PUT', '/configs?force=true', payload, 15000) +} + +async function selectProxy(endpoint, groupName, proxyName) { + const g = encodeURIComponent(String(groupName || '')) + return requestJson(endpoint, 'PUT', `/proxies/${g}`, { name: String(proxyName || '') }) +} + +async function testProxyDelay(endpoint, proxyName, testUrl = 'https://www.gstatic.com/generate_204', timeout = 5000) { + const name = encodeURIComponent(String(proxyName || '')) + const urlParam = encodeURIComponent(testUrl) + return requestJson( + endpoint, + 'GET', + `/proxies/${name}/delay?timeout=${Number(timeout) || 5000}&url=${urlParam}`, + undefined, + (Number(timeout) || 5000) + 2000 + ) +} + +async function testGroupDelay(endpoint, proxyNames, testUrl = 'https://www.gstatic.com/generate_204', timeout = 5000) { + const list = Array.isArray(proxyNames) ? proxyNames : [] + const results = {} + const concurrency = 5 + let index = 0 + + async function worker() { + while (index < list.length) { + const current = list[index++] + try { + const res = await testProxyDelay(endpoint, current, testUrl, timeout) + results[current] = { delay: res.delay ?? null, ok: true } + } catch (err) { + results[current] = { delay: null, ok: false, error: err.message } + } + } + } + + const workers = Array.from({ length: Math.min(concurrency, list.length) }, () => worker()) + await Promise.all(workers) + return results +} + +async function getRules(endpoint) { + const data = await requestJson(endpoint, 'GET', '/rules') + return data?.rules || [] +} + +async function getConnections(endpoint) { + return requestJson(endpoint, 'GET', '/connections') +} + +async function closeConnection(endpoint, connectionId) { + return requestJson(endpoint, 'DELETE', `/connections/${encodeURIComponent(String(connectionId || ''))}`) +} + +async function closeAllConnections(endpoint) { + return requestJson(endpoint, 'DELETE', '/connections') +} + +async function probeLocalControllers(ports = [9090, 9097, 53000, 9091]) { + const found = [] + await Promise.all( + ports.map(async (port) => { + const baseUrl = `http://127.0.0.1:${port}` + try { + const res = await httpClient.request(`${baseUrl}/version`, { timeoutMs: 900 }) + if (res.status === 200 || res.status === 401) { + let version = 'unknown' + if (res.status === 200 && res.text) { + try { + const json = JSON.parse(res.text) + version = json.version || 'detected' + } catch { + version = 'detected' + } + } + found.push({ + baseUrl, + port, + requiresSecret: res.status === 401, + version + }) + } + } catch { + // not listening + } + }) + ) + return found.sort((a, b) => a.port - b.port) +} + +module.exports = { + normalizeBaseUrl, + getOverview, + patchConfigs, + reloadConfig, + selectProxy, + testProxyDelay, + testGroupDelay, + getRules, + getConnections, + closeConnection, + closeAllConnections, + probeLocalControllers +} diff --git a/plugins/vps-manager/preload/config-store.cjs b/plugins/vps-manager/preload/config-store.cjs new file mode 100644 index 000000000..71e85cbaa --- /dev/null +++ b/plugins/vps-manager/preload/config-store.cjs @@ -0,0 +1,941 @@ +const fs = require('node:fs') +const path = require('node:path') +const os = require('node:os') +const yaml = require('js-yaml') +const httpClient = require('./http-client.cjs') + +const MAX_YAML_BYTES = 10 * 1024 * 1024 +const YAML_EXT_RE = /\.(ya?ml)$/i +const DISABLED_RULE_TOKEN_PREFIX = '__VPS_MGR_DISABLED_RULE_' + +const RULE_PRESETS = [ + { + id: 'ai', + name: 'AI 服务分流 (OpenAI / Claude / Gemini)', + rules: [ + 'DOMAIN-SUFFIX,openai.com', + 'DOMAIN-SUFFIX,chatgpt.com', + 'DOMAIN-SUFFIX,oaistatic.com', + 'DOMAIN-SUFFIX,oaiusercontent.com', + 'DOMAIN-SUFFIX,anthropic.com', + 'DOMAIN-SUFFIX,claude.ai', + 'DOMAIN-SUFFIX,generativelanguage.googleapis.com', + 'DOMAIN-SUFFIX,perplexity.ai' + ] + }, + { + id: 'streaming', + name: '流媒体分流 (YouTube / Netflix / Spotify)', + rules: [ + 'DOMAIN-SUFFIX,youtube.com', + 'DOMAIN-SUFFIX,googlevideo.com', + 'DOMAIN-SUFFIX,ytimg.com', + 'DOMAIN-SUFFIX,netflix.com', + 'DOMAIN-SUFFIX,nflxvideo.net', + 'DOMAIN-SUFFIX,spotify.com', + 'DOMAIN-SUFFIX,disneyplus.com' + ] + }, + { + id: 'dev', + name: '开发者生态 (GitHub / Docker / npm)', + rules: [ + 'DOMAIN-SUFFIX,github.com', + 'DOMAIN-SUFFIX,githubusercontent.com', + 'DOMAIN-SUFFIX,githubassets.com', + 'DOMAIN-SUFFIX,docker.io', + 'DOMAIN-SUFFIX,npmjs.org', + 'DOMAIN-SUFFIX,huggingface.co' + ] + }, + { + id: 'direct-cn', + name: '国内与局域网直连', + rules: [ + 'DOMAIN-SUFFIX,cn', + 'DOMAIN-SUFFIX,qq.com', + 'DOMAIN-SUFFIX,weixin.qq.com', + 'DOMAIN-SUFFIX,taobao.com', + 'DOMAIN-SUFFIX,jd.com', + 'DOMAIN-SUFFIX,bilibili.com', + 'GEOIP,LAN,DIRECT,no-resolve', + 'GEOIP,CN,DIRECT,no-resolve' + ] + } +] + +function parseRuleLine(rawLine, index = 0) { + const trimmed = String(rawLine || '').trim() + const enabled = !trimmed.startsWith('#') + const clean = enabled ? trimmed : trimmed.replace(/^#+\s*/, '') + const parts = clean.split(',').map((p) => p.trim()) + const type = (parts[0] || 'DOMAIN-SUFFIX').toUpperCase() + + if (type === 'MATCH' || type === 'FINAL') { + return { + id: `rule-${index}`, + type, + value: '', + policy: parts[1] || 'DIRECT', + noResolve: false, + enabled, + raw: trimmed + } + } + + return { + id: `rule-${index}`, + type, + value: parts[1] || '', + policy: parts[2] || 'DIRECT', + noResolve: parts.slice(3).some((p) => p.toLowerCase() === 'no-resolve'), + enabled, + raw: trimmed + } +} + +function formatRuleLine(rule) { + const type = String(rule.type || 'DOMAIN-SUFFIX').trim().toUpperCase() + const policy = String(rule.policy || 'DIRECT').trim() + const value = String(rule.value || '').trim() + + let line + if (type === 'MATCH' || type === 'FINAL') { + line = `${type},${policy}` + } else { + const parts = [type, value, policy] + if (rule.noResolve) parts.push('no-resolve') + line = parts.join(',') + } + + return rule.enabled === false ? `# ${line}` : line +} + +function extractRulesFromYamlBlock(yamlText) { + const lines = String(yamlText || '').split(/\r?\n/) + const extracted = [] + let inRulesBlock = false + + for (const line of lines) { + if (!inRulesBlock) { + if (/^rules\s*:\s*(?:#.*)?$/.test(line)) { + inRulesBlock = true + } + continue + } + + if (!line.trim()) continue + if (/^[^\s#]/.test(line)) break + + const commentedItem = /^\s*#\s*-\s*(.+)$/.exec(line) + if (commentedItem) { + const inner = commentedItem[1].trim() + if (inner) { + let ruleStr = inner + try { + const loaded = yaml.load(`- ${inner}`) + if (Array.isArray(loaded) && typeof loaded[0] === 'string') { + ruleStr = loaded[0] + } + } catch { + // keep inner string + } + extracted.push(parseRuleLine(`# ${ruleStr}`, extracted.length)) + } + continue + } + + const activeItem = /^\s*-\s*(.+)$/.exec(line) + if (activeItem) { + const inner = activeItem[1].trim() + let ruleStr = inner + try { + const loaded = yaml.load(`- ${inner}`) + if (Array.isArray(loaded) && typeof loaded[0] === 'string') { + ruleStr = loaded[0] + } + } catch { + // keep inner string + } + extracted.push(parseRuleLine(ruleStr, extracted.length)) + } + } + + return extracted +} + +function parseClashYaml(yamlText) { + const doc = yaml.load(String(yamlText || '')) + if (!doc || typeof doc !== 'object' || Array.isArray(doc)) { + throw new Error('YAML 配置无效:根节点必须是对象') + } + + const proxies = Array.isArray(doc.proxies) ? doc.proxies : [] + const proxyGroups = Array.isArray(doc['proxy-groups']) ? doc['proxy-groups'] : [] + const rawRules = Array.isArray(doc.rules) ? doc.rules : [] + const blockRules = extractRulesFromYamlBlock(yamlText) + const parsedRules = + blockRules.length >= rawRules.length ? blockRules : rawRules.map((line, i) => parseRuleLine(line, i)) + + return { + doc, + proxies, + proxyGroups, + rules: rawRules, + parsedRules, + general: { + port: doc.port ?? doc['mixed-port'] ?? 7890, + mode: doc.mode || 'rule', + allowLan: Boolean(doc['allow-lan']), + externalController: doc['external-controller'] || '', + secret: doc.secret || '' + } + } +} + +function serializeClashYaml(doc) { + return yaml.dump(doc, { lineWidth: 120, noRefs: true }) +} + +function updateRulesInYaml(yamlText, ruleItems) { + const doc = yaml.load(String(yamlText || '')) || {} + if (typeof doc !== 'object' || Array.isArray(doc)) { + throw new Error('YAML 配置无效') + } + + const items = Array.isArray(ruleItems) ? ruleItems : [] + const disabledTokenMap = new Map() + + doc.rules = items.map((item, idx) => { + if (item && item.enabled === false) { + const token = `${DISABLED_RULE_TOKEN_PREFIX}${idx}__` + disabledTokenMap.set(token, formatRuleLine({ ...item, enabled: true })) + return token + } + return formatRuleLine(item) + }) + + let dumped = serializeClashYaml(doc) + if (disabledTokenMap.size > 0) { + dumped = dumped.replace( + /^([ \t]*)-\s*['"]?(__VPS_MGR_DISABLED_RULE_\d+__)['"]?\s*$/gm, + (match, indent, token) => { + const ruleStr = disabledTokenMap.get(token) + return ruleStr ? `${indent}# - ${ruleStr}` : match + } + ) + } + + return dumped +} + +function decodeBase64Safe(input) { + const norm = String(input || '').trim().replace(/-/g, '+').replace(/_/g, '/') + const pad = norm.length % 4 === 0 ? norm : norm + '='.repeat(4 - (norm.length % 4)) + return Buffer.from(pad, 'base64').toString('utf8') +} + +function safeDecodeURIComponent(value) { + try { + return decodeURIComponent(String(value || '')) + } catch { + return String(value || '') + } +} + +function parseValidPort(rawPort, fallback) { + const port = Number(rawPort ?? fallback) + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`分享链接端口无效: ${rawPort}`) + } + return port +} + +function parseShareUri(rawUri) { + const uri = String(rawUri || '').trim() + if (!uri) throw new Error('分享链接不能为空') + + if (uri.startsWith('vmess://')) { + const payload = JSON.parse(decodeBase64Safe(uri.slice(8))) + if (!payload.add || !payload.id) { + throw new Error('vmess 链接缺少服务器或 UUID') + } + return { + name: payload.ps || `${payload.add}:${payload.port}`, + type: 'vmess', + server: payload.add, + port: parseValidPort(payload.port, 443), + uuid: payload.id, + alterId: Number(payload.aid || 0), + cipher: payload.scy || 'auto', + udp: true, + tls: payload.tls === 'tls', + servername: payload.sni || payload.host || undefined, + network: payload.net || 'tcp', + ...(payload.net === 'ws' + ? { + 'ws-opts': { + path: payload.path || '/', + headers: payload.host ? { Host: payload.host } : undefined + } + } + : {}) + } + } + + if (uri.startsWith('vless://')) { + const url = new URL(uri) + const params = url.searchParams + const port = parseValidPort(url.port || 443, 443) + const name = safeDecodeURIComponent(url.hash.replace(/^#/, '')) || `${url.hostname}:${port}` + const proxy = { + name, + type: 'vless', + server: url.hostname, + port, + uuid: safeDecodeURIComponent(url.username), + network: params.get('type') || 'tcp', + udp: true + } + const sec = params.get('security') + if (sec === 'tls' || sec === 'reality') { + proxy.tls = true + if (params.get('sni')) proxy.servername = params.get('sni') + if (params.get('fp')) proxy['client-fingerprint'] = params.get('fp') + } + if (params.get('flow')) proxy.flow = params.get('flow') + if (sec === 'reality') { + proxy['reality-opts'] = { + 'public-key': params.get('pbk') || '', + 'short-id': params.get('sid') || '' + } + } + if (proxy.network === 'ws') { + proxy['ws-opts'] = { + path: params.get('path') || '/', + headers: params.get('host') ? { Host: params.get('host') } : undefined + } + } + return proxy + } + + if (uri.startsWith('trojan://')) { + const url = new URL(uri) + const params = url.searchParams + const port = parseValidPort(url.port || 443, 443) + return { + name: safeDecodeURIComponent(url.hash.replace(/^#/, '')) || `${url.hostname}:${port}`, + type: 'trojan', + server: url.hostname, + port, + password: safeDecodeURIComponent(url.username), + sni: params.get('sni') || undefined, + 'skip-cert-verify': params.get('allowInsecure') === '1', + udp: true + } + } + + if (uri.startsWith('hysteria2://') || uri.startsWith('hy2://')) { + const normUri = uri.replace(/^hy2:\/\//, 'hysteria2://') + const url = new URL(normUri) + const params = url.searchParams + const port = parseValidPort(url.port || 443, 443) + return { + name: safeDecodeURIComponent(url.hash.replace(/^#/, '')) || `${url.hostname}:${port}`, + type: 'hysteria2', + server: url.hostname, + port, + password: safeDecodeURIComponent(url.username), + sni: params.get('sni') || undefined, + 'skip-cert-verify': params.get('insecure') === '1' + } + } + + if (uri.startsWith('ss://')) { + const hashIdx = uri.indexOf('#') + const tag = hashIdx >= 0 ? safeDecodeURIComponent(uri.slice(hashIdx + 1)) : '' + const beforeHash = hashIdx >= 0 ? uri.slice(5, hashIdx) : uri.slice(5) + const queryIdx = beforeHash.indexOf('?') + const mainPart = queryIdx >= 0 ? beforeHash.slice(0, queryIdx) : beforeHash + + let method = '' + let password = '' + let server = '' + let port = 8388 + + if (mainPart.includes('@')) { + const atIdx = mainPart.lastIndexOf('@') + const userInfo = mainPart.slice(0, atIdx) + const hostPort = mainPart.slice(atIdx + 1) + const decoded = userInfo.includes(':') ? safeDecodeURIComponent(userInfo) : decodeBase64Safe(userInfo) + const sep = decoded.indexOf(':') + if (sep <= 0) throw new Error('ss:// 链接凭据格式无效') + method = decoded.slice(0, sep) + password = decoded.slice(sep + 1) + const hpUrl = new URL(`http://${hostPort}`) + server = hpUrl.hostname + port = parseValidPort(hpUrl.port || 8388, 8388) + } else { + const decoded = decodeBase64Safe(mainPart) + const atIdx = decoded.lastIndexOf('@') + if (atIdx <= 0) throw new Error('ss:// 链接格式无效') + const userInfo = decoded.slice(0, atIdx) + const hostPort = decoded.slice(atIdx + 1) + const sep = userInfo.indexOf(':') + if (sep <= 0) throw new Error('ss:// 链接凭据格式无效') + method = userInfo.slice(0, sep) + password = userInfo.slice(sep + 1) + const hpUrl = new URL(`http://${hostPort}`) + server = hpUrl.hostname + port = parseValidPort(hpUrl.port || 8388, 8388) + } + + if (!server) throw new Error('ss:// 链接缺少服务器地址') + + return { + name: tag || `${server}:${port}`, + type: 'ss', + server, + port, + cipher: method, + password, + udp: true + } + } + + throw new Error('暂不支持的分享链接协议(支持 vless / vmess / trojan / hysteria2 / ss)') +} + +function addProxyToYaml(yamlText, proxyObj) { + const doc = yaml.load(String(yamlText || '')) || {} + if (typeof doc !== 'object' || Array.isArray(doc)) { + throw new Error('YAML 配置无效') + } + doc.proxies = Array.isArray(doc.proxies) ? doc.proxies : [] + const existingIdx = doc.proxies.findIndex((p) => p && p.name === proxyObj.name) + if (existingIdx >= 0) { + doc.proxies[existingIdx] = proxyObj + } else { + doc.proxies.push(proxyObj) + } + + if (Array.isArray(doc['proxy-groups'])) { + for (const group of doc['proxy-groups']) { + if (group && Array.isArray(group.proxies) && !group.proxies.includes(proxyObj.name)) { + if (group.type === 'select' || group.type === 'url-test' || group.type === 'fallback') { + group.proxies.push(proxyObj.name) + } + } + } + } + + return serializeClashYaml(doc) +} + +async function fetchSubscription(subUrl) { + const url = String(subUrl || '').trim() + if (!/^https?:\/\//i.test(url)) { + throw new Error('订阅地址必须以 http:// 或 https:// 开头') + } + + const res = await httpClient.request(url, { + method: 'GET', + headers: { 'User-Agent': 'clash-verge/v2.0.0' }, + timeoutMs: 15000, + maxBytes: MAX_YAML_BYTES + }) + if (!res.ok) { + throw new Error(`订阅拉取失败: HTTP ${res.status}`) + } + + const rawText = res.text || '' + try { + const parsed = parseClashYaml(rawText) + if (parsed.proxies.length > 0 || parsed.proxyGroups.length > 0) { + return { + sourceType: 'clash-yaml', + yamlText: rawText, + proxiesCount: parsed.proxies.length, + rulesCount: parsed.rules.length + } + } + } catch { + // try base64 URI list + } + + const decoded = decodeBase64Safe(rawText) + const lines = decoded.split(/\r?\n/).map((l) => l.trim()).filter(Boolean) + const proxies = [] + for (const line of lines) { + try { + proxies.push(parseShareUri(line)) + } catch { + // skip unsupported line + } + } + if (proxies.length === 0) { + throw new Error('未能从订阅中解析出有效 Clash YAML 或代理节点') + } + + const names = proxies.map((p) => p.name) + const generatedDoc = { + 'mixed-port': 7890, + mode: 'rule', + 'external-controller': '127.0.0.1:9090', + proxies, + 'proxy-groups': [ + { name: '🚀 节点选择', type: 'select', proxies: ['⚡ 自动测速', ...names, 'DIRECT'] }, + { name: '⚡ 自动测速', type: 'url-test', proxies: names, url: 'https://www.gstatic.com/generate_204', interval: 300 } + ], + rules: [ + 'GEOIP,LAN,DIRECT,no-resolve', + 'GEOIP,CN,DIRECT,no-resolve', + 'MATCH,🚀 节点选择' + ] + } + + return { + sourceType: 'base64-uris', + yamlText: serializeClashYaml(generatedDoc), + proxiesCount: proxies.length, + rulesCount: generatedDoc.rules.length + } +} + +function validateLocalYamlPath(filePath) { + const raw = String(filePath || '').trim() + if (!raw || raw.includes('\0')) { + throw new Error('本地文件路径无效') + } + const target = path.resolve(raw) + if (!YAML_EXT_RE.test(target)) { + throw new Error('安全限制:仅允许读写 .yaml 或 .yml 配置文件') + } + return target +} + +function readLocalFile(filePath) { + const target = validateLocalYamlPath(filePath) + if (!fs.existsSync(target)) { + throw new Error(`本地文件不存在: ${target}`) + } + const stat = fs.statSync(target) + if (!stat.isFile()) { + throw new Error(`目标路径不是普通文件: ${target}`) + } + if (stat.size > MAX_YAML_BYTES) { + throw new Error('文件过大,超过 10MB 限制') + } + return fs.readFileSync(target, 'utf8') +} + +function writeLocalFile(filePath, content) { + const target = validateLocalYamlPath(filePath) + const text = String(content ?? '') + if (Buffer.byteLength(text, 'utf8') > MAX_YAML_BYTES) { + throw new Error('写入内容过大,超过 10MB 限制') + } + fs.mkdirSync(path.dirname(target), { recursive: true }) + fs.writeFileSync(target, text, 'utf8') + return { ok: true, filePath: target } +} + +function discoverLocalConfigs() { + const home = os.homedir() + const candidates = [ + path.join(home, '.config', 'mihomo', 'config.yaml'), + path.join(home, '.config', 'clash', 'config.yaml'), + path.join(home, 'Library', 'Application Support', 'io.github.clash-verge-rev.clash-verge-rev', 'clash-verge.yaml'), + path.join(home, '.config', 'clash-verge', 'clash-verge.yaml') + ] + for (const envRoot of [process.env.APPDATA, process.env.LOCALAPPDATA]) { + if (!envRoot) continue + candidates.push( + path.join(envRoot, 'io.github.clash-verge-rev.clash-verge-rev', 'clash-verge.yaml'), + path.join(envRoot, 'clash-verge', 'clash-verge.yaml'), + path.join(envRoot, 'mihomo', 'config.yaml'), + path.join(envRoot, 'clash', 'config.yaml') + ) + } + return Array.from(new Set(candidates)).filter((p) => fs.existsSync(p)) +} + +function parseControllerAddr(rawAddr) { + const raw = String(rawAddr || '').trim() + if (!raw) return { host: '', port: 0 } + const idx = raw.lastIndexOf(':') + if (idx === -1) return { host: raw, port: 0 } + const host = raw.slice(0, idx) || '127.0.0.1' + const port = Number(raw.slice(idx + 1)) + return { + host, + port: Number.isInteger(port) && port > 0 && port <= 65535 ? port : 0 + } +} + +function mapOutboundToPolicy(outbound, fallback = 'PROXY') { + const raw = String(outbound || '').trim() + if (!raw) return fallback + const lower = raw.toLowerCase() + if (lower === 'direct' || lower === 'freedom') return 'DIRECT' + if (lower === 'block' || lower === 'blackhole' || lower === 'reject') return 'REJECT' + return raw +} + +function stripJsonComments(input) { + let out = '' + let inString = false + let escape = false + for (let i = 0; i < input.length; i++) { + const ch = input[i] + const next = input[i + 1] + if (inString) { + out += ch + if (escape) { + escape = false + } else if (ch === '\\') { + escape = true + } else if (ch === '"') { + inString = false + } + continue + } + if (ch === '"') { + inString = true + out += ch + continue + } + if (ch === '/' && next === '/') { + while (i < input.length && input[i] !== '\n') i++ + out += '\n' + continue + } + if (ch === '/' && next === '*') { + i += 2 + while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i++ + i++ + continue + } + out += ch + } + return out +} + +function parseJsonSafe(rawText) { + const trimmed = String(rawText || '').trim() + if (!trimmed || (!trimmed.startsWith('{') && !trimmed.startsWith('['))) return null + try { + return JSON.parse(trimmed) + } catch { + try { + return JSON.parse(stripJsonComments(trimmed)) + } catch { + return null + } + } +} + +function convertSingBoxToResult(serviceName, configPath, rawContent, json) { + const outbounds = Array.isArray(json.outbounds) ? json.outbounds : [] + const inbounds = Array.isArray(json.inbounds) ? json.inbounds : [] + const route = json.route && typeof json.route === 'object' ? json.route : {} + const finalOutbound = mapOutboundToPolicy(route.final || 'direct', 'DIRECT') + const clashApi = json.experimental?.clash_api || {} + const ctrl = parseControllerAddr(clashApi.external_controller || '') + + let mixedPort = 7890 + for (const ib of inbounds) { + if (ib && typeof ib === 'object' && (ib.type === 'mixed' || ib.type === 'socks' || ib.type === 'http') && ib.listen_port) { + mixedPort = Number(ib.listen_port) || mixedPort + break + } + } + + const ruleLines = [] + const toArray = (v) => (Array.isArray(v) ? v : v !== undefined && v !== null ? [v] : []) + + for (const rule of Array.isArray(route.rules) ? route.rules : []) { + if (!rule || typeof rule !== 'object') continue + const policy = mapOutboundToPolicy( + rule.action === 'reject' ? 'REJECT' : rule.outbound || (rule.action === 'hijack-dns' ? 'DIRECT' : ''), + finalOutbound + ) + for (const d of toArray(rule.domain_suffix)) ruleLines.push(`DOMAIN-SUFFIX,${d},${policy}`) + for (const d of toArray(rule.domain)) ruleLines.push(`DOMAIN,${d},${policy}`) + for (const d of toArray(rule.domain_keyword)) ruleLines.push(`DOMAIN-KEYWORD,${d},${policy}`) + for (const cidr of toArray(rule.ip_cidr)) ruleLines.push(`IP-CIDR,${cidr},${policy},no-resolve`) + for (const g of toArray(rule.geoip)) ruleLines.push(`GEOIP,${String(g).toUpperCase()},${policy},no-resolve`) + for (const gs of toArray(rule.geosite)) ruleLines.push(`GEOSITE,${gs},${policy}`) + for (const rs of toArray(rule.rule_set)) ruleLines.push(`RULE-SET,${rs},${policy}`) + for (const p of toArray(rule.port)) ruleLines.push(`DST-PORT,${p},${policy}`) + for (const proc of toArray(rule.process_name)) ruleLines.push(`PROCESS-NAME,${proc},${policy}`) + if (rule.ip_is_private) ruleLines.push(`GEOIP,LAN,${policy},no-resolve`) + } + ruleLines.push(`MATCH,${finalOutbound}`) + + const customOutbounds = outbounds + .filter((o) => o && typeof o === 'object' && o.tag && !['direct', 'block', 'dns'].includes(String(o.type || '').toLowerCase())) + .map((o) => ({ + name: String(o.tag), + type: String(o.type || 'custom'), + server: o.server || '-', + port: Number(o.server_port) || 443 + })) + + const groupNames = Array.from( + new Set([ + ...customOutbounds.map((o) => o.name), + ...ruleLines + .map((line) => line.split(',')[2]) + .filter((p) => p && p !== 'DIRECT' && p !== 'REJECT') + ]) + ) + + const outboundTypeMap = new Map(customOutbounds.map((o) => [o.name, o.type])) + + const doc = { + 'mixed-port': mixedPort, + mode: 'rule', + ...(ctrl.port ? { 'external-controller': clashApi.external_controller } : {}), + ...(clashApi.secret ? { secret: clashApi.secret } : {}), + proxies: customOutbounds, + 'proxy-groups': (groupNames.length > 0 ? groupNames : ['PROXY']).map((name) => ({ + name, + type: outboundTypeMap.get(name) || 'select', + proxies: ['DIRECT'] + })), + rules: ruleLines + } + + return { + found: true, + primaryService: serviceName || 'sing-box', + configPath: configPath || '', + format: 'sing-box-json', + writableAsYaml: false, + yamlText: serializeClashYaml(doc), + rawContent, + proxiesCount: customOutbounds.length, + rulesCount: ruleLines.length, + proxyGroupsCount: doc['proxy-groups'].length, + controllerHost: ctrl.host, + controllerPort: ctrl.port, + controllerSecret: String(clashApi.secret || ''), + mixedPort, + mode: 'rule' + } +} + +function convertXrayToResult(serviceName, configPath, rawContent, json) { + const outbounds = Array.isArray(json.outbounds) ? json.outbounds : [] + const inbounds = Array.isArray(json.inbounds) ? json.inbounds : [] + const routing = json.routing && typeof json.routing === 'object' ? json.routing : {} + + let mixedPort = 7890 + for (const ib of inbounds) { + if (ib && typeof ib === 'object' && (ib.protocol === 'socks' || ib.protocol === 'http') && ib.port) { + mixedPort = Number(ib.port) || mixedPort + break + } + } + + const ruleLines = [] + for (const rule of Array.isArray(routing.rules) ? routing.rules : []) { + if (!rule || typeof rule !== 'object') continue + const policy = mapOutboundToPolicy(rule.outboundTag || rule.balancerTag, 'PROXY') + for (const d of Array.isArray(rule.domain) ? rule.domain : []) { + const s = String(d || '').trim() + if (!s) continue + if (s.startsWith('geosite:')) ruleLines.push(`GEOSITE,${s.slice(8)},${policy}`) + else if (s.startsWith('full:')) ruleLines.push(`DOMAIN,${s.slice(5)},${policy}`) + else if (s.startsWith('domain:')) ruleLines.push(`DOMAIN-SUFFIX,${s.slice(7)},${policy}`) + else if (s.startsWith('keyword:')) ruleLines.push(`DOMAIN-KEYWORD,${s.slice(8)},${policy}`) + else if (s.startsWith('regexp:')) ruleLines.push(`DOMAIN-KEYWORD,${s.slice(7)},${policy}`) + else ruleLines.push(`DOMAIN-SUFFIX,${s},${policy}`) + } + for (const ip of Array.isArray(rule.ip) ? rule.ip : []) { + const s = String(ip || '').trim() + if (!s) continue + if (s.startsWith('geoip:')) { + const cc = s.slice(6).toUpperCase() + ruleLines.push(`GEOIP,${cc === 'PRIVATE' ? 'LAN' : cc},${policy},no-resolve`) + } else { + ruleLines.push(`IP-CIDR,${s.includes('/') ? s : `${s}/32`},${policy},no-resolve`) + } + } + if (rule.port !== undefined) { + ruleLines.push(`DST-PORT,${rule.port},${policy}`) + } + } + const defaultOutbound = mapOutboundToPolicy(outbounds[0]?.tag, 'DIRECT') + ruleLines.push(`MATCH,${defaultOutbound}`) + + const customOutbounds = outbounds + .filter((o) => o && typeof o === 'object' && !['freedom', 'blackhole'].includes(String(o.protocol || '').toLowerCase())) + .map((o, idx) => ({ + name: String(o.tag || `${o.protocol || 'outbound'}-${idx + 1}`), + type: String(o.protocol || 'xray'), + server: o.settings?.vnext?.[0]?.address || o.settings?.servers?.[0]?.address || '-', + port: Number(o.settings?.vnext?.[0]?.port || o.settings?.servers?.[0]?.port) || 443 + })) + + const groupNames = Array.from( + new Set([ + ...customOutbounds.map((o) => o.name), + ...ruleLines + .map((line) => line.split(',')[2]) + .filter((p) => p && p !== 'DIRECT' && p !== 'REJECT') + ]) + ) + + const xrayOutboundTypeMap = new Map(customOutbounds.map((o) => [o.name, o.type])) + + const doc = { + 'mixed-port': mixedPort, + mode: 'rule', + proxies: customOutbounds, + 'proxy-groups': (groupNames.length > 0 ? groupNames : ['PROXY']).map((name) => ({ + name, + type: xrayOutboundTypeMap.get(name) || 'select', + proxies: ['DIRECT'] + })), + rules: ruleLines + } + + return { + found: true, + primaryService: serviceName || 'xray', + configPath: configPath || '', + format: 'xray-json', + writableAsYaml: false, + yamlText: serializeClashYaml(doc), + rawContent, + proxiesCount: customOutbounds.length, + rulesCount: ruleLines.length, + proxyGroupsCount: doc['proxy-groups'].length, + controllerHost: '', + controllerPort: 0, + controllerSecret: '', + mixedPort, + mode: 'rule' + } +} + +function parseRemoteProxyConfig({ serviceName = '', configPath = '', rawContent = '' }) { + const raw = String(rawContent || '') + const trimmed = raw.trim() + if (!trimmed) { + return { + found: Boolean(serviceName), + primaryService: serviceName, + configPath, + format: 'other', + writableAsYaml: false, + yamlText: '', + rawContent: raw, + proxiesCount: 0, + rulesCount: 0, + proxyGroupsCount: 0, + controllerHost: '', + controllerPort: 0, + controllerSecret: '', + mixedPort: 0, + mode: '' + } + } + + const json = parseJsonSafe(trimmed) + if (json && typeof json === 'object' && !Array.isArray(json)) { + const looksSingBox = + serviceName === 'sing-box' || + Boolean(json.route) || + Boolean(json.experimental?.clash_api) || + (Array.isArray(json.inbounds) && json.inbounds.some((i) => i && i.listen_port !== undefined)) || + (Array.isArray(json.outbounds) && json.outbounds.some((o) => o && (o.server_port !== undefined || o.type === 'direct'))) + if (looksSingBox && !json.routing) { + return convertSingBoxToResult(serviceName || 'sing-box', configPath, raw, json) + } + + const looksXray = + serviceName === 'xray' || + serviceName === 'v2ray' || + Boolean(json.routing) || + /xray|v2ray|x-ui/i.test(configPath || '') || + (Array.isArray(json.outbounds) && Array.isArray(json.inbounds)) + if (looksXray) { + return convertXrayToResult(serviceName || 'xray', configPath, raw, json) + } + } + + const isClashService = ['mihomo', 'clash', 'clash-meta'].includes(serviceName) || /\.ya?ml$/i.test(configPath || '') + if (isClashService || (!trimmed.startsWith('{') && (/^rules:/m.test(raw) || /^proxies:/m.test(raw) || /^external-controller:/m.test(raw)))) { + try { + const loaded = yaml.load(raw) + if (loaded && typeof loaded === 'object' && !Array.isArray(loaded)) { + const hasClashKeys = + Array.isArray(loaded.proxies) || + Array.isArray(loaded['proxy-groups']) || + Array.isArray(loaded.rules) || + loaded['external-controller'] !== undefined || + loaded['mixed-port'] !== undefined + if (hasClashKeys && !loaded.listen && !loaded.auth) { + const parsed = parseClashYaml(raw) + const ctrl = parseControllerAddr(parsed.general.externalController) + return { + found: true, + primaryService: serviceName || 'mihomo', + configPath, + format: 'clash-yaml', + writableAsYaml: true, + yamlText: raw, + rawContent: raw, + proxiesCount: parsed.proxies.length, + rulesCount: parsed.parsedRules.length, + proxyGroupsCount: parsed.proxyGroups.length, + controllerHost: ctrl.host, + controllerPort: ctrl.port, + controllerSecret: parsed.general.secret || '', + mixedPort: parsed.general.port || 7890, + mode: parsed.general.mode || 'rule' + } + } + } + } catch { + // fall through as generic non-clash config + } + } + + return { + found: true, + primaryService: serviceName || 'proxy', + configPath, + format: 'other', + writableAsYaml: false, + yamlText: '', + rawContent: raw, + proxiesCount: 0, + rulesCount: 0, + proxyGroupsCount: 0, + controllerHost: '', + controllerPort: 0, + controllerSecret: '', + mixedPort: 0, + mode: '' + } +} + +module.exports = { + RULE_PRESETS, + parseRuleLine, + formatRuleLine, + parseClashYaml, + serializeClashYaml, + updateRulesInYaml, + parseShareUri, + addProxyToYaml, + parseRemoteProxyConfig, + fetchSubscription, + readLocalFile, + writeLocalFile, + discoverLocalConfigs +} diff --git a/plugins/vps-manager/preload/deploy-templates.cjs b/plugins/vps-manager/preload/deploy-templates.cjs new file mode 100644 index 000000000..d37b1d642 --- /dev/null +++ b/plugins/vps-manager/preload/deploy-templates.cjs @@ -0,0 +1,650 @@ +const crypto = require('node:crypto') +const yaml = require('js-yaml') + +const SNI_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ +const UNSAFE_HOST_RE = /[\s\r\n\0'"`$\\;|&<>()]/ + +function shellQuote(value) { + return `'${String(value ?? '').replace(/'/g, `'\\''`)}'` +} + +function validatePort(port) { + const n = Number(port) + if (!Number.isInteger(n) || n < 1 || n > 65535) { + throw new Error(`无效端口号: ${port}(必须为 1-65535 的整数)`) + } + return n +} + +function validateHost(host) { + const clean = String(host || '').trim() + if (!clean || clean.length > 253 || UNSAFE_HOST_RE.test(clean)) { + throw new Error(`无效的节点地址 (host): ${host}`) + } + return clean +} + +function validateSni(sni) { + const clean = String(sni || '').trim() + if (!clean || clean.length > 253 || !SNI_RE.test(clean)) { + throw new Error(`非法的伪装域名 (SNI): ${sni}`) + } + return clean +} + +function generateUuid() { + return crypto.randomUUID() +} + +function generateRandomPassword(bytes = 16) { + return crypto.randomBytes(bytes).toString('base64') +} + +function generateSs2022Key(method = '2022-blake3-aes-128-gcm') { + const byteLen = String(method).includes('256') ? 32 : 16 + return crypto.randomBytes(byteLen).toString('base64') +} + +function generateShortId() { + return crypto.randomBytes(4).toString('hex') +} + +function generateRealityKeypair() { + const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519') + const pubJwk = publicKey.export({ format: 'jwk' }) + const privJwk = privateKey.export({ format: 'jwk' }) + return { + publicKey: pubJwk.x, + privateKey: privJwk.d + } +} + +function generateSecrets(protocol, options = {}) { + const ssMethod = String(options.ssMethod || '2022-blake3-aes-128-gcm').trim() + const password = + protocol === 'ss-rust' && ssMethod.startsWith('2022-') + ? generateSs2022Key(ssMethod) + : generateRandomPassword(16) + + const secrets = { + uuid: generateUuid(), + password, + shortId: generateShortId(), + controllerSecret: crypto.randomBytes(12).toString('hex'), + realityPrivateKey: '', + realityPublicKey: '' + } + + if (protocol === 'singbox-reality' || protocol === 'xray-reality') { + const kp = generateRealityKeypair() + secrets.realityPrivateKey = kp.privateKey + secrets.realityPublicKey = kp.publicKey + } + + return secrets +} + +function defaultClashRules() { + return [ + 'DOMAIN-SUFFIX,openai.com,🤖 AI 服务', + 'DOMAIN-SUFFIX,chatgpt.com,🤖 AI 服务', + 'DOMAIN-SUFFIX,anthropic.com,🤖 AI 服务', + 'DOMAIN-SUFFIX,claude.ai,🤖 AI 服务', + 'DOMAIN-SUFFIX,generativelanguage.googleapis.com,🤖 AI 服务', + 'DOMAIN-SUFFIX,github.com,🚀 节点选择', + 'DOMAIN-SUFFIX,githubusercontent.com,🚀 节点选择', + 'DOMAIN-SUFFIX,google.com,🚀 节点选择', + 'DOMAIN-SUFFIX,youtube.com,🎬 流媒体', + 'DOMAIN-SUFFIX,netflix.com,🎬 流媒体', + 'DOMAIN-SUFFIX,cn,DIRECT', + 'DOMAIN-SUFFIX,baidu.com,DIRECT', + 'DOMAIN-SUFFIX,qq.com,DIRECT', + 'DOMAIN-SUFFIX,alicdn.com,DIRECT', + 'GEOIP,LAN,DIRECT,no-resolve', + 'GEOIP,CN,DIRECT,no-resolve', + 'MATCH,🚀 节点选择' + ] +} + +function buildClashConfigYaml(proxyObj, options = {}) { + const controllerPort = validatePort(options.controllerPort ?? 9090) + const controllerSecret = options.controllerSecret || '' + const mixedPort = validatePort(options.mixedPort ?? 7890) + const proxyName = proxyObj.name + + const doc = { + 'mixed-port': mixedPort, + 'allow-lan': false, + mode: 'rule', + 'log-level': 'info', + 'external-controller': `127.0.0.1:${controllerPort}`, + ...(controllerSecret ? { secret: controllerSecret } : {}), + dns: { + enable: true, + 'enhanced-mode': 'fake-ip', + 'fake-ip-range': '198.18.0.1/16', + nameserver: ['223.5.5.5', '119.29.29.29'], + fallback: ['1.1.1.1', '8.8.8.8'] + }, + proxies: [proxyObj], + 'proxy-groups': [ + { + name: '🚀 节点选择', + type: 'select', + proxies: ['⚡ 自动测速', proxyName, 'DIRECT'] + }, + { + name: '⚡ 自动测速', + type: 'url-test', + proxies: [proxyName], + url: 'https://www.gstatic.com/generate_204', + interval: 300 + }, + { + name: '🤖 AI 服务', + type: 'select', + proxies: ['🚀 节点选择', proxyName] + }, + { + name: '🎬 流媒体', + type: 'select', + proxies: ['🚀 节点选择', proxyName, 'DIRECT'] + } + ], + rules: defaultClashRules() + } + + return yaml.dump(doc, { lineWidth: 120, noRefs: true }) +} + +function writeFileBase64Snippet(remotePath, content) { + const b64 = Buffer.from(String(content ?? ''), 'utf8').toString('base64') + return `echo ${shellQuote(b64)} | base64 -d > ${shellQuote(remotePath)}` +} + +function systemdUnitScript(name, description, binaryName, binaryFallback, argsStr) { + return `BIN_PATH=$(command -v ${binaryName} || echo ${shellQuote(binaryFallback)}) +if [ ! -x "$BIN_PATH" ]; then + echo "Binary not found or not executable: $BIN_PATH" >&2 + exit 1 +fi +cat < /etc/systemd/system/${name}.service +[Unit] +Description=${description} +After=network.target nss-lookup.target + +[Service] +Type=simple +User=root +ExecStart=\${BIN_PATH} ${argsStr} +Restart=on-failure +RestartSec=5s +LimitNOFILE=1048576 + +[Install] +WantedBy=multi-user.target +EOF +systemctl daemon-reload +systemctl enable ${name} +systemctl restart ${name}` +} + +function firewallSnippet(port, protos = ['tcp']) { + const safePort = validatePort(port) + const validProtos = protos.filter((p) => p === 'tcp' || p === 'udp') + if (validProtos.length === 0) return '' + + const ufwLines = validProtos.map((proto) => ` ufw allow ${safePort}/${proto} || true`).join('\n') + const fwLines = validProtos + .map((proto) => ` firewall-cmd --permanent --add-port=${safePort}/${proto} || true`) + .join('\n') + + return `if command -v ufw >/dev/null 2>&1 && ufw status | grep -q "Status: active"; then +${ufwLines} +elif command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then +${fwLines} + firewall-cmd --reload || true +fi` +} + +function buildRealityClientArtifacts(ctx) { + const { host, port, uuid, sni, nodeName, realityPublicKey, shortId, tagEncoded } = ctx + const shadowrocketUri = `vless://${uuid}@${host}:${port}?encryption=none&flow=xtls-rprx-vision&security=reality&sni=${encodeURIComponent(sni)}&fp=chrome&pbk=${encodeURIComponent(realityPublicKey)}&sid=${encodeURIComponent(shortId)}&type=tcp#${tagEncoded}` + const clashProxy = { + name: nodeName, + type: 'vless', + server: host, + port, + uuid, + network: 'tcp', + tls: true, + udp: true, + flow: 'xtls-rprx-vision', + servername: sni, + 'client-fingerprint': 'chrome', + 'reality-opts': { + 'public-key': realityPublicKey, + 'short-id': shortId + } + } + + return { + shadowrocketUri, + clashProxy, + clashConfigYaml: buildClashConfigYaml(clashProxy), + clientMeta: { host, port, uuid, sni, publicKey: realityPublicKey, shortId } + } +} + +function buildSingboxReality(ctx) { + const { port, uuid, sni, realityPrivateKey, fwCmd } = ctx + const serverConfigObj = { + log: { level: 'info', timestamp: true }, + inbounds: [ + { + type: 'vless', + tag: 'vless-reality-in', + listen: '::', + listen_port: port, + users: [{ uuid, flow: 'xtls-rprx-vision' }], + tls: { + enabled: true, + server_name: sni, + reality: { + enabled: true, + handshake: { server: sni, server_port: 443 }, + private_key: realityPrivateKey, + short_id: [ctx.shortId] + } + } + } + ], + outbounds: [ + { type: 'direct', tag: 'direct' }, + { type: 'block', tag: 'block' } + ] + } + const serverConfig = JSON.stringify(serverConfigObj, null, 2) + const installScript = `#!/usr/bin/env bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +ARCH=$(uname -m) +case "$ARCH" in + x86_64|amd64) SB_ARCH="amd64" ;; + aarch64|arm64) SB_ARCH="arm64" ;; + *) echo "Unsupported arch: $ARCH"; exit 1 ;; +esac + +if ! command -v sing-box >/dev/null 2>&1; then + if command -v apt-get >/dev/null 2>&1; then apt-get update -y && apt-get install -y curl tar jq; fi + if command -v dnf >/dev/null 2>&1; then dnf install -y curl tar jq; elif command -v yum >/dev/null 2>&1; then yum install -y curl tar jq; fi + VER=$(curl -fsSL https://api.github.com/repos/SagerNet/sing-box/releases/latest | grep -oE '"tag_name":\\s*"v[^"]+"' | head -n1 | cut -d'"' -f4 | sed 's/^v//' || true) + VER=\${VER:-1.10.7} + TMP=$(mktemp -d) + curl -fsSL "https://github.com/SagerNet/sing-box/releases/download/v\${VER}/sing-box-\${VER}-linux-\${SB_ARCH}.tar.gz" -o "$TMP/sb.tar.gz" + tar -xzf "$TMP/sb.tar.gz" -C "$TMP" + install -m 755 "$TMP/sing-box-\${VER}-linux-\${SB_ARCH}/sing-box" /usr/local/bin/sing-box + rm -rf "$TMP" +fi + +mkdir -p /etc/sing-box +${writeFileBase64Snippet('/etc/sing-box/config.json', serverConfig)} + +BIN_SB=$(command -v sing-box || echo /usr/local/bin/sing-box) +"$BIN_SB" check -c /etc/sing-box/config.json +${systemdUnitScript('sing-box', 'sing-box service', 'sing-box', '/usr/local/bin/sing-box', 'run -c /etc/sing-box/config.json')} +${fwCmd} +systemctl is-active sing-box` + + return { + protocol: 'singbox-reality', + serviceName: 'sing-box', + configPath: '/etc/sing-box/config.json', + serverConfig, + installScript, + ...buildRealityClientArtifacts(ctx) + } +} + +function buildXrayReality(ctx) { + const { port, uuid, sni, realityPrivateKey, shortId, fwCmd } = ctx + const serverConfigObj = { + log: { loglevel: 'warning' }, + inbounds: [ + { + port, + protocol: 'vless', + settings: { + clients: [{ id: uuid, flow: 'xtls-rprx-vision' }], + decryption: 'none' + }, + streamSettings: { + network: 'tcp', + security: 'reality', + realitySettings: { + dest: `${sni}:443`, + serverNames: [sni], + privateKey: realityPrivateKey, + shortIds: [shortId] + } + }, + sniffing: { enabled: true, destOverride: ['http', 'tls', 'quic'] } + } + ], + outbounds: [{ protocol: 'freedom', tag: 'direct' }] + } + const serverConfig = JSON.stringify(serverConfigObj, null, 2) + const installScript = `#!/usr/bin/env bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +if ! command -v xray >/dev/null 2>&1 && [ ! -x /usr/local/bin/xray ]; then + if command -v apt-get >/dev/null 2>&1; then apt-get update -y && apt-get install -y curl unzip; fi + bash -c "$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install +fi +mkdir -p /usr/local/etc/xray +${writeFileBase64Snippet('/usr/local/etc/xray/config.json', serverConfig)} +${systemdUnitScript('xray', 'Xray Service', 'xray', '/usr/local/bin/xray', 'run -config /usr/local/etc/xray/config.json')} +${fwCmd} +systemctl is-active xray` + + return { + protocol: 'xray-reality', + serviceName: 'xray', + configPath: '/usr/local/etc/xray/config.json', + serverConfig, + installScript, + ...buildRealityClientArtifacts(ctx) + } +} + +function buildHysteria2(ctx) { + const { host, port, sni, nodeName, password, tagEncoded, fwCmd } = ctx + const hyPassword = password.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 24) || 'hy2secret123' + const serverConfigObj = { + listen: `:${port}`, + tls: { + cert: '/etc/hysteria/server.crt', + key: '/etc/hysteria/server.key' + }, + auth: { + type: 'password', + password: hyPassword + }, + masquerade: { + type: 'proxy', + proxy: { + url: `https://${sni}`, + rewriteHost: true + } + } + } + const serverConfig = yaml.dump(serverConfigObj, { lineWidth: 120, noRefs: true }) + const installScript = `#!/usr/bin/env bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +if ! command -v hysteria >/dev/null 2>&1 && [ ! -x /usr/local/bin/hysteria ]; then + if command -v apt-get >/dev/null 2>&1; then apt-get update -y && apt-get install -y curl openssl; fi + bash <(curl -fsSL https://get.hy2.sh/) +fi +mkdir -p /etc/hysteria +if [ ! -f /etc/hysteria/server.crt ] || [ ! -f /etc/hysteria/server.key ]; then + openssl req -x509 -nodes -newkey ec:<(openssl ecparam -name prime256v1) -keyout /etc/hysteria/server.key -out /etc/hysteria/server.crt -subj ${shellQuote(`/CN=${sni}`)} -days 3650 +fi +${writeFileBase64Snippet('/etc/hysteria/config.yaml', serverConfig)} +${systemdUnitScript('hysteria-server', 'Hysteria 2 Service', 'hysteria', '/usr/local/bin/hysteria', 'server --config /etc/hysteria/config.yaml')} +${fwCmd} +systemctl is-active hysteria-server` + + const shadowrocketUri = `hysteria2://${encodeURIComponent(hyPassword)}@${host}:${port}?insecure=1&sni=${encodeURIComponent(sni)}#${tagEncoded}` + const clashProxy = { + name: nodeName, + type: 'hysteria2', + server: host, + port, + password: hyPassword, + sni, + 'skip-cert-verify': true + } + + return { + protocol: 'hysteria2', + serviceName: 'hysteria-server', + configPath: '/etc/hysteria/config.yaml', + serverConfig, + installScript, + shadowrocketUri, + clashProxy, + clashConfigYaml: buildClashConfigYaml(clashProxy), + clientMeta: { host, port, password: hyPassword, sni } + } +} + +function buildMihomoNode(ctx) { + const { host, port, nodeName, password, controllerSecret, tagEncoded, exposeController, fwCmd } = ctx + const controllerBind = exposeController ? '0.0.0.0:9090' : '127.0.0.1:9090' + const proxyPass = password.replace(/[^a-zA-Z0-9]/g, '').slice(0, 20) || 'MihomoPass2026' + const serverObj = { + 'mixed-port': 7890, + 'bind-address': '127.0.0.1', + 'allow-lan': false, + mode: 'rule', + 'log-level': 'info', + 'external-controller': controllerBind, + secret: controllerSecret, + listeners: [ + { + name: 'ss-in', + type: 'shadowsocks', + port, + listen: '0.0.0.0', + cipher: 'aes-256-gcm', + password: proxyPass, + udp: true + } + ], + proxies: [], + 'proxy-groups': [{ name: 'PROXY', type: 'select', proxies: ['DIRECT'] }], + rules: ['MATCH,DIRECT'] + } + const serverConfig = yaml.dump(serverObj, { lineWidth: 120, noRefs: true }) + const installScript = `#!/usr/bin/env bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +ARCH=$(uname -m) +case "$ARCH" in + x86_64|amd64) MH_ARCH="amd64" ;; + aarch64|arm64) MH_ARCH="arm64" ;; + *) echo "Unsupported arch: $ARCH"; exit 1 ;; +esac +if ! command -v mihomo >/dev/null 2>&1; then + if command -v apt-get >/dev/null 2>&1; then apt-get update -y && apt-get install -y curl gzip; fi + VER=$(curl -fsSL https://api.github.com/repos/MetaCubeX/mihomo/releases/latest | grep -oE '"tag_name":\\s*"v[^"]+"' | head -n1 | cut -d'"' -f4 || true) + VER=\${VER:-v1.19.1} + curl -fsSL "https://github.com/MetaCubeX/mihomo/releases/download/\${VER}/mihomo-linux-\${MH_ARCH}-\${VER}.gz" -o /tmp/mihomo.gz + gzip -dc /tmp/mihomo.gz > /usr/local/bin/mihomo + chmod +x /usr/local/bin/mihomo + rm -f /tmp/mihomo.gz +fi +mkdir -p /etc/mihomo +${writeFileBase64Snippet('/etc/mihomo/config.yaml', serverConfig)} +${systemdUnitScript('mihomo', 'Mihomo (Clash Meta) Service', 'mihomo', '/usr/local/bin/mihomo', '-d /etc/mihomo')} +${fwCmd} +systemctl is-active mihomo` + + const ssUserinfo = Buffer.from(`aes-256-gcm:${proxyPass}`).toString('base64') + const shadowrocketUri = `ss://${ssUserinfo}@${host}:${port}#${tagEncoded}` + const clashProxy = { + name: nodeName, + type: 'ss', + server: host, + port, + cipher: 'aes-256-gcm', + password: proxyPass, + udp: true + } + + return { + protocol: 'mihomo-node', + serviceName: 'mihomo', + configPath: '/etc/mihomo/config.yaml', + serverConfig, + installScript, + shadowrocketUri, + clashProxy, + clashConfigYaml: buildClashConfigYaml(clashProxy, { + controllerPort: 9090, + controllerSecret + }), + clientMeta: { host, port, cipher: 'aes-256-gcm', password: proxyPass, controllerBind, controllerSecret } + } +} + +function buildShadowsocksRust(ctx) { + const { host, port, nodeName, password, ssMethod, tagEncoded, fwCmd } = ctx + let ssPassword + if (ssMethod.startsWith('2022-')) { + const expectedBytes = ssMethod.includes('256') ? 32 : 16 + if (password) { + const decodedLen = Buffer.from(password, 'base64').length + if (decodedLen !== expectedBytes) { + throw new Error( + `${ssMethod} 需要 ${expectedBytes} 字节 Base64 密钥(当前解码为 ${decodedLen} 字节),请点击「重新生成密钥」` + ) + } + ssPassword = password + } else { + ssPassword = generateSs2022Key(ssMethod) + } + } else { + ssPassword = password.replace(/[^a-zA-Z0-9]/g, '').slice(0, 24) || 'SsPass2026' + } + + const serverConfigObj = { + server: '0.0.0.0', + server_port: port, + password: ssPassword, + method: ssMethod, + mode: 'tcp_and_udp', + timeout: 300 + } + const serverConfig = JSON.stringify(serverConfigObj, null, 2) + const installScript = `#!/usr/bin/env bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +ARCH=$(uname -m) +case "$ARCH" in + x86_64|amd64) SS_ARCH="x86_64-unknown-linux-gnu" ;; + aarch64|arm64) SS_ARCH="aarch64-unknown-linux-gnu" ;; + *) echo "Unsupported arch: $ARCH"; exit 1 ;; +esac +if ! command -v ssserver >/dev/null 2>&1; then + if command -v apt-get >/dev/null 2>&1; then apt-get update -y && apt-get install -y curl xz-utils; fi + VER=$(curl -fsSL https://api.github.com/repos/shadowsocks/shadowsocks-rust/releases/latest | grep -oE '"tag_name":\\s*"v[^"]+"' | head -n1 | cut -d'"' -f4 || true) + VER=\${VER:-v1.21.2} + TMP=$(mktemp -d) + curl -fsSL "https://github.com/shadowsocks/shadowsocks-rust/releases/download/\${VER}/shadowsocks-\${VER}.\${SS_ARCH}.tar.xz" -o "$TMP/ss.tar.xz" + tar -xJf "$TMP/ss.tar.xz" -C "$TMP" + install -m 755 "$TMP/ssserver" /usr/local/bin/ssserver + rm -rf "$TMP" +fi +mkdir -p /etc/shadowsocks-rust +${writeFileBase64Snippet('/etc/shadowsocks-rust/config.json', serverConfig)} +${systemdUnitScript('shadowsocks-rust', 'Shadowsocks-rust Service', 'ssserver', '/usr/local/bin/ssserver', '-c /etc/shadowsocks-rust/config.json')} +${fwCmd} +systemctl is-active shadowsocks-rust` + + const ssUserinfo = Buffer.from(`${ssMethod}:${ssPassword}`).toString('base64') + const shadowrocketUri = `ss://${ssUserinfo}@${host}:${port}#${tagEncoded}` + const clashProxy = { + name: nodeName, + type: 'ss', + server: host, + port, + cipher: ssMethod, + password: ssPassword, + udp: true + } + + return { + protocol: 'ss-rust', + serviceName: 'shadowsocks-rust', + configPath: '/etc/shadowsocks-rust/config.json', + serverConfig, + installScript, + shadowrocketUri, + clashProxy, + clashConfigYaml: buildClashConfigYaml(clashProxy), + clientMeta: { host, port, method: ssMethod, password: ssPassword } + } +} + +const PROTOCOL_BUILDERS = { + 'singbox-reality': { protos: ['tcp'], defaultPort: 443, build: buildSingboxReality }, + 'xray-reality': { protos: ['tcp'], defaultPort: 443, build: buildXrayReality }, + hysteria2: { protos: ['udp'], defaultPort: 8443, build: buildHysteria2 }, + 'mihomo-node': { protos: ['tcp', 'udp'], defaultPort: 8388, build: buildMihomoNode }, + 'ss-rust': { protos: ['tcp', 'udp'], defaultPort: 8388, build: buildShadowsocksRust } +} + +function buildDeploymentBundle(rawParams = {}) { + const protocol = rawParams.protocol || 'singbox-reality' + const entry = PROTOCOL_BUILDERS[protocol] + if (!entry) { + throw new Error(`不支持的部署协议: ${protocol}`) + } + + const host = validateHost(rawParams.host || '127.0.0.1') + const port = validatePort(rawParams.port ?? entry.defaultPort) + const sni = validateSni(rawParams.sni || 'www.apple.com') + const nodeName = String(rawParams.nodeName || `${host}-${protocol}`).trim() || `${host}-${protocol}` + const uuid = String(rawParams.uuid || generateUuid()).trim() + const ssMethod = String(rawParams.ssMethod || '2022-blake3-aes-128-gcm').trim() + const password = String(rawParams.password ?? '').trim() + const shortId = String(rawParams.shortId || generateShortId()).trim() + const controllerSecret = String(rawParams.controllerSecret || crypto.randomBytes(12).toString('hex')).trim() + const openFirewall = rawParams.openFirewall !== false + + let realityPrivateKey = String(rawParams.realityPrivateKey || '').trim() + let realityPublicKey = String(rawParams.realityPublicKey || '').trim() + if ((protocol === 'singbox-reality' || protocol === 'xray-reality') && (!realityPrivateKey || !realityPublicKey)) { + const kp = generateRealityKeypair() + realityPrivateKey = kp.privateKey + realityPublicKey = kp.publicKey + } + + const tagEncoded = encodeURIComponent(nodeName) + const fwCmd = openFirewall ? firewallSnippet(port, entry.protos) : '' + + return entry.build({ + protocol, + host, + port, + sni, + nodeName, + uuid, + password: password || (protocol === 'ss-rust' ? '' : generateRandomPassword(16)), + shortId, + realityPrivateKey, + realityPublicKey, + controllerSecret, + ssMethod, + tagEncoded, + exposeController: Boolean(rawParams.exposeController), + fwCmd + }) +} + +module.exports = { + validatePort, + validateHost, + validateSni, + generateUuid, + generateRandomPassword, + generateSs2022Key, + generateShortId, + generateRealityKeypair, + generateSecrets, + defaultClashRules, + buildClashConfigYaml, + buildDeploymentBundle +} diff --git a/plugins/vps-manager/preload/embedded-proxy.cjs b/plugins/vps-manager/preload/embedded-proxy.cjs new file mode 100644 index 000000000..fbec3552d --- /dev/null +++ b/plugins/vps-manager/preload/embedded-proxy.cjs @@ -0,0 +1,1396 @@ +const net = require('node:net') +const { Client } = require('ssh2') +const sshClient = require('./ssh-client.cjs') +const configStore = require('./config-store.cjs') +const systemProxy = require('./system-proxy.cjs') +const httpClient = require('./http-client.cjs') +const { createNativeCoreManager } = require('./native-core.cjs') + +const MAX_HEADER_BYTES = 16 * 1024 +const HANDSHAKE_TIMEOUT_MS = 10000 +const DIAL_TIMEOUT_MS = 12000 +const DEFAULT_SSH_SLOW_MS = 450 +const MONITOR_INTERVAL_MS = 25000 + +const CN_DOMAIN_HINTS = [ + 'baidu.com', + 'qq.com', + 'weixin.qq.com', + 'wechat.com', + 'taobao.com', + 'tmall.com', + 'jd.com', + 'bilibili.com', + 'hdslb.com', + 'aliyun.com', + 'alicdn.com', + '163.com', + '126.com', + 'weibo.com', + 'zhihu.com', + 'douyin.com', + 'bytedance.com', + 'meituan.com', + 'alipay.com', + 'feishu.cn', + 'dingtalk.com', + 'xiaohongshu.com', + 'mi.com', + 'xiaomi.com', + 'huawei.com', + 'ipip.net', + 'cip.cc', + 'ip.cn', + 'ip138.com', + 'douban.com', + 'csdn.net', + 'gitee.com', + 'juejin.cn', + '1688.com', + 'pinduoduo.com', + 'iqiyi.com', + 'youku.com', + 'kuaishou.com', + 'netease.com', + 'sohu.com', + 'ctrip.com', + 'amap.com', + 'baidubce.com', + 'gtimg.com', + 'bdstatic.com' +] + +function normalizeHost(host) { + return String(host || '') + .trim() + .toLowerCase() + .replace(/^\[|\]$/g, '') + .replace(/\.$/, '') +} + +function isLoopbackHost(host) { + const h = normalizeHost(host) + if (!h) return true + if (h === 'localhost' || h === '::1' || h === '0:0:0:0:0:0:0:1' || h.endsWith('.local')) { + return true + } + return /^127\./.test(h) +} + +function isPrivateOrLoopbackHost(host) { + const h = normalizeHost(host) + if (isLoopbackHost(h)) return true + if ( + /^10\./.test(h) || + /^192\.168\./.test(h) || + /^172\.(1[6-9]|2\d|3[01])\./.test(h) || + /^169\.254\./.test(h) || + /^fe80:/i.test(h) || + /^fc00:/i.test(h) || + /^fd[0-9a-f]{2}:/i.test(h) + ) { + return true + } + return false +} + +function ipv4ToInt(ip) { + const parts = String(ip || '').trim().split('.') + if (parts.length !== 4) return null + let num = 0 + for (const part of parts) { + if (!/^\d+$/.test(part)) return null + const octet = Number(part) + if (octet < 0 || octet > 255) return null + num = ((num << 8) | octet) >>> 0 + } + return num +} + +function matchIpv4Cidr(ip, cidr) { + const [netStr, prefixStr] = String(cidr || '').split('/') + const ipNum = ipv4ToInt(ip) + const netNum = ipv4ToInt(netStr) + if (ipNum === null || netNum === null) return false + const prefix = prefixStr === undefined ? 32 : Number(prefixStr) + if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false + if (prefix === 0) return true + const mask = (~((1 << (32 - prefix)) - 1)) >>> 0 + return (ipNum & mask) === (netNum & mask) +} + +function isCnHost(host) { + const h = normalizeHost(host) + if (!h) return false + if (h === 'cn' || h.endsWith('.cn')) return true + return CN_DOMAIN_HINTS.some((domain) => h === domain || h.endsWith(`.${domain}`)) +} + +function policyToAction(policy) { + const raw = String(policy || '').trim() + const upper = raw.toUpperCase() + if (!raw || upper === 'DIRECT' || raw.includes('直连')) { + return 'DIRECT' + } + if (upper === 'REJECT' || upper === 'BLOCK' || raw.includes('拦截') || raw.includes('广告')) { + return 'REJECT' + } + return 'PROXY' +} + +function compileLocalRoutingRules(yamlText, options = {}) { + const raw = String(yamlText || '').trim() + if (!raw) { + return { rules: [], adapted: false, adaptReason: '' } + } + try { + const parsed = configStore.parseClashYaml(raw) + const rawRules = (parsed.parsedRules || []) + .filter((r) => r && r.enabled) + .map((r) => { + const type = String(r.type || 'DOMAIN-SUFFIX').toUpperCase() + const value = String(r.value || '').trim() + const policy = String(r.policy || 'DIRECT').trim() || 'DIRECT' + return { + type, + value, + valueLower: value.toLowerCase(), + policy, + action: policyToAction(policy), + raw: `${type}${value ? `,${value}` : ''},${policy}` + } + }) + + const sourceKind = String(options.sourceKind || '').toLowerCase() + const sourceFormat = String(options.sourceFormat || '').toLowerCase() + + // Server-side sing-box / Xray JSON rules describe outbound routing on the VPS itself + // (where `direct` means VPS WAN egress and geoip:cn -> block is anti-abuse). + // Running them verbatim on the user's laptop would leak all traffic directly via the local/soft-router gateway. + if (sourceFormat === 'sing-box-json' || sourceFormat === 'xray-json') { + const preservedRejects = rawRules.filter( + (r) => ['DOMAIN', 'DOMAIN-SUFFIX', 'DOMAIN-KEYWORD'].includes(r.type) && r.action === 'REJECT' + ) + const adaptedRules = [ + ...preservedRejects, + { + type: 'GEOIP', + value: 'LAN', + valueLower: 'lan', + policy: 'DIRECT', + action: 'DIRECT', + raw: 'GEOIP,LAN,DIRECT (客户端适配)' + }, + { + type: 'GEOIP', + value: 'CN', + valueLower: 'cn', + policy: 'DIRECT', + action: 'DIRECT', + raw: 'GEOIP,CN,DIRECT (客户端适配)' + }, + { + type: 'MATCH', + value: '', + valueLower: '', + policy: 'PROXY', + action: 'PROXY', + raw: 'MATCH,PROXY (客户端适配)' + } + ] + return { + rules: adaptedRules, + adapted: true, + adaptReason: + '检测到服务端 sing-box / Xray 配置,已自动适配为「国内/局域网直连,海外走 VPS」客户端分流(避免流量漏回本机/软路由)' + } + } + + const filteredRules = + sourceKind === 'vps' + ? rawRules.filter((r) => { + if (r.action !== 'REJECT') return true + if (r.type === 'GEOIP' && (r.value.toUpperCase() === 'CN' || r.value.toUpperCase() === 'LAN' || r.value.toUpperCase() === 'PRIVATE')) { + return false + } + if (r.type === 'GEOSITE' && (r.valueLower === 'cn' || r.valueLower === 'geolocation-cn')) { + return false + } + return true + }) + : rawRules + + const hasDirectCatchAll = filteredRules.some( + (r) => (r.type === 'MATCH' || r.type === 'FINAL') && r.action === 'DIRECT' + ) + + if (hasDirectCatchAll) { + const hasExplicitCnDirect = filteredRules.some( + (r) => + ((r.type === 'GEOIP' && r.value.toUpperCase() === 'CN') || + (r.type === 'GEOSITE' && (r.valueLower === 'cn' || r.valueLower === 'geolocation-cn'))) && + r.action === 'DIRECT' + ) + + const rewrittenRules = [] + let insertedCn = false + for (const r of filteredRules) { + const isCatchAll = r.type === 'MATCH' || r.type === 'FINAL' + if (isCatchAll && !hasExplicitCnDirect && !insertedCn) { + rewrittenRules.push({ + type: 'GEOIP', + value: 'CN', + valueLower: 'cn', + policy: 'DIRECT', + action: 'DIRECT', + raw: 'GEOIP,CN,DIRECT (客户端适配)' + }) + insertedCn = true + } + if (isCatchAll && r.action === 'DIRECT') { + rewrittenRules.push({ + ...r, + policy: 'PROXY', + action: 'PROXY', + raw: 'MATCH,PROXY (已适配本地分流)' + }) + } else { + rewrittenRules.push(r) + } + } + + return { + rules: rewrittenRules, + adapted: true, + adaptReason: + sourceKind === 'vps' + ? '检测到服务器侧默认直连规则 (MATCH,DIRECT),已自动转为「国内直连、海外走 VPS」避免漏回本机/软路由' + : '检测到规则末尾为默认直连 (MATCH,DIRECT),内置引擎已自动转为「国内直连、海外走 VPS」避免海外流量漏回本机/软路由' + } + } + + return { + rules: filteredRules, + adapted: false, + adaptReason: '' + } + } catch { + return { rules: [], adapted: false, adaptReason: '' } + } +} + +function compileRulesFromYaml(yamlText, options = {}) { + return compileLocalRoutingRules(yamlText, options).rules +} + +function matchDstPort(port, ruleValue) { + const portNum = Number(port) + if (!Number.isInteger(portNum) || portNum <= 0) return false + for (const token of String(ruleValue || '').split(/[\/,]/)) { + const clean = token.trim() + if (!clean) continue + if (clean.includes('-')) { + const [startStr, endStr] = clean.split('-') + const start = Number(startStr) + const end = Number(endStr) + if (Number.isInteger(start) && Number.isInteger(end) && portNum >= start && portNum <= end) { + return true + } + } else if (Number(clean) === portNum) { + return true + } + } + return false +} + +function matchRoutingRule(host, port, mode = 'rule', compiledRules = []) { + const cleanHost = normalizeHost(host) + const cleanMode = String(mode || 'rule').toLowerCase() + + if (isLoopbackHost(cleanHost)) { + return { action: 'DIRECT', policy: 'DIRECT', rule: 'BUILTIN:LOOPBACK' } + } + if (cleanMode === 'direct') { + return { action: 'DIRECT', policy: 'DIRECT', rule: 'MODE:DIRECT' } + } + if (cleanMode === 'global') { + return { action: 'PROXY', policy: 'GLOBAL', rule: 'MODE:GLOBAL' } + } + + if (isPrivateOrLoopbackHost(cleanHost)) { + return { action: 'DIRECT', policy: 'DIRECT', rule: 'BUILTIN:LAN' } + } + + for (const rule of compiledRules || []) { + let matched = false + switch (rule.type) { + case 'DOMAIN': + matched = cleanHost === rule.valueLower + break + case 'DOMAIN-SUFFIX': + matched = cleanHost === rule.valueLower || cleanHost.endsWith(`.${rule.valueLower}`) + break + case 'DOMAIN-KEYWORD': + matched = Boolean(rule.valueLower) && cleanHost.includes(rule.valueLower) + break + case 'DST-PORT': + matched = matchDstPort(port, rule.value) + break + case 'IP-CIDR': + matched = net.isIPv4(cleanHost) && matchIpv4Cidr(cleanHost, rule.value) + break + case 'GEOIP': { + const cc = rule.value.toUpperCase() + if (cc === 'LAN' || cc === 'PRIVATE') matched = isPrivateOrLoopbackHost(cleanHost) + else if (cc === 'CN') matched = isCnHost(cleanHost) + break + } + case 'GEOSITE': { + const gs = rule.valueLower + if (gs === 'cn' || gs === 'geolocation-cn') matched = isCnHost(cleanHost) + break + } + case 'MATCH': + case 'FINAL': + matched = true + break + default: + break + } + + if (matched) { + return { + action: rule.action, + policy: rule.policy, + rule: rule.raw + } + } + } + + if (isCnHost(cleanHost)) { + return { action: 'DIRECT', policy: 'DIRECT', rule: 'FALLBACK:CN' } + } + return { action: 'PROXY', policy: 'PROXY', rule: 'FALLBACK:PROXY' } +} + +function parseAuthority(rawTarget, defaultPort = 443) { + const target = String(rawTarget || '').trim() + if (target.startsWith('[')) { + const closeIdx = target.indexOf(']') + if (closeIdx > 1) { + const host = target.slice(1, closeIdx) + const rest = target.slice(closeIdx + 1) + const port = rest.startsWith(':') ? Number(rest.slice(1)) || defaultPort : defaultPort + return { host, port } + } + } + const lastColon = target.lastIndexOf(':') + if (lastColon > 0 && target.indexOf(':') === lastColon) { + const host = target.slice(0, lastColon) + const port = Number(target.slice(lastColon + 1)) || defaultPort + return { host, port } + } + return { host: target, port: defaultPort } +} + +function formatIpv6(buf) { + const groups = [] + for (let i = 0; i < 16; i += 2) { + groups.push(buf.readUInt16BE(i).toString(16)) + } + return groups.join(':') +} + +function createSocketReader(socket, firstChunk) { + let buffer = Buffer.isBuffer(firstChunk) ? firstChunk : Buffer.from(firstChunk) + let ended = false + let failureErr = null + let pendingWaiter = null + + const notifyWaiter = () => { + if (!pendingWaiter) return + const { minBytes, resolve, reject, timer } = pendingWaiter + if (failureErr) { + pendingWaiter = null + clearTimeout(timer) + reject(failureErr) + return + } + if (buffer.length >= minBytes) { + pendingWaiter = null + clearTimeout(timer) + resolve() + return + } + if (ended) { + pendingWaiter = null + clearTimeout(timer) + reject(new Error('客户端提前关闭连接')) + } + } + + const onData = (chunk) => { + buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]) + notifyWaiter() + } + const onEnd = () => { + ended = true + notifyWaiter() + } + const onError = (err) => { + failureErr = err + notifyWaiter() + } + + socket.on('data', onData) + socket.on('end', onEnd) + socket.on('error', onError) + + return { + async readExact(n) { + if (buffer.length < n) { + if (failureErr) throw failureErr + if (ended) throw new Error('连接已关闭,读取握手数据不足') + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pendingWaiter = null + reject(new Error('代理握手超时')) + }, HANDSHAKE_TIMEOUT_MS) + pendingWaiter = { minBytes: n, resolve, reject, timer } + }) + } + const out = buffer.subarray(0, n) + buffer = buffer.subarray(n) + return out + }, + async readUntilDelimiter(delimiterBuf, maxBytes = MAX_HEADER_BYTES) { + while (true) { + const idx = buffer.indexOf(delimiterBuf) + if (idx >= 0) { + const head = buffer.subarray(0, idx) + buffer = buffer.subarray(idx + delimiterBuf.length) + return head + } + if (buffer.length > maxBytes) { + throw new Error('HTTP 代理请求头过大') + } + if (failureErr) throw failureErr + if (ended) throw new Error('HTTP 请求头不完整') + const targetLen = buffer.length + 1 + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pendingWaiter = null + reject(new Error('HTTP 请求头接收超时')) + }, HANDSHAKE_TIMEOUT_MS) + pendingWaiter = { minBytes: targetLen, resolve, reject, timer } + }) + } + }, + detach() { + if (pendingWaiter) { + clearTimeout(pendingWaiter.timer) + pendingWaiter = null + } + socket.removeListener('data', onData) + socket.removeListener('end', onEnd) + socket.removeListener('error', onError) + const rest = buffer + buffer = Buffer.alloc(0) + return rest + } + } +} + +function createEmbeddedProxyController(deps = {}) { + const sysProxyApi = deps.systemProxy || systemProxy + const buildConfigFn = deps.buildConnectConfig || sshClient.buildConnectConfig + const ClientCtor = deps.Client || Client + const nativeCore = deps.nativeCore || createNativeCoreManager() + const sshSlowThresholdMs = Number(deps.sshSlowThresholdMs) > 0 ? Number(deps.sshSlowThresholdMs) : DEFAULT_SSH_SLOW_MS + const customProbeFn = typeof deps.probeTransport === 'function' ? deps.probeTransport : null + + let server = null + let boundPort = 0 + let running = false + let mode = 'rule' + let profile = null + let compiledRules = [] + let ruleAdapted = false + let ruleAdaptReason = '' + let customUpstreamDialer = null + let sshConn = null + let sshConnectingPromise = null + let managedSystemProxy = false + let systemProxyWarning = '' + let lastError = '' + let startedAt = '' + let uploadTotal = 0 + let downloadTotal = 0 + let nextConnId = 1 + + let transportPolicy = 'auto' + let activeTransport = 'ssh' + let nativeProxyNode = null + let sshLatencyMs = null + let nativeLatencyMs = null + let switchReason = '' + let sshFailStreak = 0 + let nativeFailStreak = 0 + let switchPromise = null + let monitorTimer = null + + const activeConnections = new Map() + + function getStatus() { + const coreStatus = nativeCore.getStatus() + const currentPort = running ? boundPort : 0 + return { + running, + mode, + port: currentPort, + host: '127.0.0.1', + profileId: profile?.id || '', + profileName: profile?.name || '', + profileHost: profile?.host || '', + rulesCount: compiledRules.length, + ruleAdapted, + ruleAdaptReason, + activeConnections: activeConnections.size, + uploadTotal, + downloadTotal, + managedSystemProxy, + systemProxyWarning, + lastError, + startedAt, + transportPolicy, + activeTransport, + nativeCoreState: coreStatus.state, + nativeNodeName: String(nativeProxyNode?.name || coreStatus.activeNodeName || ''), + nativeProtocol: String(nativeProxyNode?.type || coreStatus.activeProtocol || ''), + sshLatencyMs, + nativeLatencyMs, + switchReason, + fallbackEnv: sysProxyApi.buildProxyEnvSnippet + ? sysProxyApi.buildProxyEnvSnippet('127.0.0.1', currentPort || 7890, process.platform) + : '' + } + } + + function getConnections() { + return Array.from(activeConnections.values()).map((c) => ({ + id: c.id, + host: c.host, + port: c.port, + protocol: c.protocol, + action: c.action, + policy: c.policy, + rule: c.rule, + upload: c.upload, + download: c.download, + startedAt: c.startedAt + })) + } + + function closeConnection(id) { + const entry = activeConnections.get(String(id || '')) + if (!entry) return false + try { + entry.clientSocket.destroy() + } catch {} + try { + entry.upstreamSocket?.destroy() + } catch {} + activeConnections.delete(entry.id) + return true + } + + function closeAllConnections() { + let closed = 0 + for (const id of Array.from(activeConnections.keys())) { + if (closeConnection(id)) closed++ + } + return closed + } + + async function ensureSshReady() { + if (customUpstreamDialer) return null + if (!profile) throw new Error('未选择代理目标 VPS 服务器') + if (sshConn && sshConn._vpsMgrReady) { + return sshConn + } + if (sshConnectingPromise) { + return sshConnectingPromise + } + + const connectConfig = buildConfigFn(profile) + sshConnectingPromise = new Promise((resolve, reject) => { + const conn = new ClientCtor() + let settled = false + + const timer = setTimeout(() => { + if (settled) return + settled = true + sshConnectingPromise = null + try { + conn.end() + } catch {} + reject(new Error(`SSH 内置代理连接超时 (${connectConfig.host}:${connectConfig.port})`)) + }, 15000) + + conn.on('ready', () => { + if (settled) return + settled = true + clearTimeout(timer) + conn._vpsMgrReady = true + sshConn = conn + sshConnectingPromise = null + resolve(conn) + }) + + conn.on('error', (err) => { + conn._vpsMgrReady = false + lastError = err.message + if (!settled) { + settled = true + clearTimeout(timer) + sshConnectingPromise = null + reject(new Error(`SSH 内置代理连接失败 (${connectConfig.host}:${connectConfig.port}): ${err.message}`)) + } else if (sshConn === conn) { + sshConn = null + } + }) + + conn.on('close', () => { + conn._vpsMgrReady = false + if (sshConn === conn) sshConn = null + if (!settled) { + settled = true + clearTimeout(timer) + sshConnectingPromise = null + reject(new Error(`SSH 内置代理连接已关闭 (${connectConfig.host}:${connectConfig.port})`)) + } + }) + + conn.connect({ + ...connectConfig, + keepaliveInterval: 15000, + keepaliveCountMax: 3 + }) + }) + + return sshConnectingPromise + } + + async function dialViaSsh(dstHost, dstPort) { + if (customUpstreamDialer) { + return customUpstreamDialer(dstHost, dstPort) + } + + const conn = await ensureSshReady() + return new Promise((resolve, reject) => { + let settled = false + const timer = setTimeout(() => { + if (settled) return + settled = true + reject(new Error(`SSH 转发超时 (${dstHost}:${dstPort})`)) + }, DIAL_TIMEOUT_MS) + + conn.forwardOut('127.0.0.1', 0, dstHost, dstPort, (err, stream) => { + if (settled) { + if (stream) { + try { + stream.destroy() + } catch {} + } + return + } + settled = true + clearTimeout(timer) + if (err) { + reject(err) + return + } + resolve(stream) + }) + }) + } + + async function switchToNative(reason = '') { + if (!nativeProxyNode) { + throw new Error('当前 VPS 尚未绑定原生高速节点(VLESS / Hysteria2 / SS),请先一键部署或粘贴分享链接') + } + if (switchPromise) return switchPromise + + switchPromise = (async () => { + try { + const proxyUrlForDownload = running && boundPort > 0 ? `http://127.0.0.1:${boundPort}` : '' + await nativeCore.start({ + proxyObj: nativeProxyNode, + proxyUrlForDownload + }) + activeTransport = 'native' + nativeFailStreak = 0 + switchReason = reason || '已切换至原生高速协议' + return getStatus() + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + lastError = msg + switchReason = `原生高速通道启用失败 (${msg}),保持 SSH 通道` + activeTransport = 'ssh' + throw err + } finally { + switchPromise = null + } + })() + + return switchPromise + } + + async function dialUpstream(action, dstHost, dstPort) { + if (action === 'DIRECT') { + return new Promise((resolve, reject) => { + const sock = net.createConnection({ host: dstHost, port: dstPort }) + let settled = false + const timer = setTimeout(() => { + if (settled) return + settled = true + sock.destroy() + reject(new Error(`直连超时 (${dstHost}:${dstPort})`)) + }, DIAL_TIMEOUT_MS) + + sock.once('connect', () => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(sock) + }) + sock.once('error', (err) => { + if (settled) return + settled = true + clearTimeout(timer) + reject(err) + }) + }) + } + + if (activeTransport === 'native' && nativeCore.getStatus().running) { + try { + const stream = await nativeCore.dialViaHttpConnect(dstHost, dstPort, DIAL_TIMEOUT_MS) + nativeFailStreak = 0 + return stream + } catch (err) { + nativeFailStreak += 1 + if (nativeFailStreak >= 2 && (profile?.host || customUpstreamDialer)) { + activeTransport = 'ssh' + switchReason = '原生高速通道异常,已无感切回 SSH 通道' + } + if (profile?.host || customUpstreamDialer) { + return dialViaSsh(dstHost, dstPort) + } + throw err + } + } + + try { + const stream = await dialViaSsh(dstHost, dstPort) + sshFailStreak = 0 + return stream + } catch (err) { + sshFailStreak += 1 + if (transportPolicy === 'auto' && sshFailStreak >= 2 && nativeProxyNode && !switchPromise) { + void switchToNative('SSH 通道连续受阻,已自动切换原生高速协议').catch(() => {}) + } + throw err + } + } + + function bridgeSockets(meta, clientSocket, upstreamSocket, leftover) { + const id = String(nextConnId++) + const entry = { + id, + host: meta.host, + port: meta.port, + protocol: meta.protocol, + action: meta.action, + policy: meta.policy, + rule: meta.rule, + upload: 0, + download: 0, + startedAt: new Date().toISOString(), + clientSocket, + upstreamSocket + } + activeConnections.set(id, entry) + + let closed = false + const cleanup = () => { + if (closed) return + closed = true + activeConnections.delete(id) + if (!clientSocket.destroyed) { + try { + clientSocket.destroy() + } catch {} + } + if (!upstreamSocket.destroyed) { + try { + upstreamSocket.destroy() + } catch {} + } + } + + clientSocket.on('data', (chunk) => { + uploadTotal += chunk.length + entry.upload += chunk.length + if (!upstreamSocket.destroyed) { + upstreamSocket.write(chunk) + } + }) + upstreamSocket.on('data', (chunk) => { + downloadTotal += chunk.length + entry.download += chunk.length + if (!clientSocket.destroyed) { + clientSocket.write(chunk) + } + }) + + clientSocket.on('end', () => { + try { + upstreamSocket.end() + } catch {} + }) + upstreamSocket.on('end', () => { + try { + clientSocket.end() + } catch {} + }) + + clientSocket.on('error', cleanup) + upstreamSocket.on('error', cleanup) + clientSocket.on('close', cleanup) + upstreamSocket.on('close', cleanup) + + if (leftover && leftover.length > 0 && !upstreamSocket.destroyed) { + uploadTotal += leftover.length + entry.upload += leftover.length + upstreamSocket.write(leftover) + } + } + + async function handleSocks5Client(clientSocket, firstChunk) { + const reader = createSocketReader(clientSocket, firstChunk) + try { + const greetingHead = await reader.readExact(2) + const nmethods = greetingHead[1] + if (nmethods > 0) await reader.readExact(nmethods) + clientSocket.write(Buffer.from([0x05, 0x00])) + + const reqHead = await reader.readExact(4) + const ver = reqHead[0] + const cmd = reqHead[1] + const atyp = reqHead[3] + if (ver !== 0x05 || cmd !== 0x01) { + reader.detach() + clientSocket.end(Buffer.from([0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0])) + return + } + + let dstHost = '' + if (atyp === 0x01) { + const addr = await reader.readExact(4) + dstHost = `${addr[0]}.${addr[1]}.${addr[2]}.${addr[3]}` + } else if (atyp === 0x03) { + const lenBuf = await reader.readExact(1) + const hostBuf = await reader.readExact(lenBuf[0]) + dstHost = hostBuf.toString('utf8') + } else if (atyp === 0x04) { + const addr6 = await reader.readExact(16) + dstHost = formatIpv6(addr6) + } else { + reader.detach() + clientSocket.end(Buffer.from([0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0])) + return + } + + const portBuf = await reader.readExact(2) + const dstPort = portBuf.readUInt16BE(0) + const leftover = reader.detach() + + const match = matchRoutingRule(dstHost, dstPort, mode, compiledRules) + if (match.action === 'REJECT') { + clientSocket.end(Buffer.from([0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0])) + return + } + + const upstream = await dialUpstream(match.action, dstHost, dstPort) + if (clientSocket.destroyed) { + upstream.destroy() + return + } + + clientSocket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0])) + bridgeSockets( + { + host: dstHost, + port: dstPort, + protocol: 'SOCKS5', + ...match + }, + clientSocket, + upstream, + leftover + ) + } catch { + reader.detach() + if (!clientSocket.destroyed) { + try { + clientSocket.end(Buffer.from([0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0])) + } catch {} + clientSocket.destroy() + } + } + } + + async function handleHttpClient(clientSocket, firstChunk) { + const reader = createSocketReader(clientSocket, firstChunk) + try { + const headBuf = await reader.readUntilDelimiter(Buffer.from('\r\n\r\n')) + const leftover = reader.detach() + const headText = headBuf.toString('utf8') + const lines = headText.split('\r\n') + const reqLine = lines[0] || '' + const matchReq = /^([A-Z]+)\s+(\S+)\s+(HTTP\/\d\.\d)$/i.exec(reqLine.trim()) + if (!matchReq) { + clientSocket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n') + return + } + + const method = matchReq[1].toUpperCase() + const target = matchReq[2] + const httpVer = matchReq[3] + + if (method === 'CONNECT') { + const { host, port } = parseAuthority(target, 443) + const match = matchRoutingRule(host, port, mode, compiledRules) + if (match.action === 'REJECT') { + clientSocket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n') + return + } + const upstream = await dialUpstream(match.action, host, port) + if (clientSocket.destroyed) { + upstream.destroy() + return + } + clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n') + bridgeSockets( + { + host, + port, + protocol: 'HTTPS', + ...match + }, + clientSocket, + upstream, + leftover + ) + return + } + + // Plain HTTP proxy request + let hostHeader = '' + const filteredHeaders = [] + for (let i = 1; i < lines.length; i++) { + const line = lines[i] + if (!line) continue + const colonIdx = line.indexOf(':') + if (colonIdx <= 0) continue + const key = line.slice(0, colonIdx).trim() + const lowerKey = key.toLowerCase() + if (lowerKey === 'host') hostHeader = line.slice(colonIdx + 1).trim() + if (lowerKey === 'proxy-connection' || lowerKey === 'connection') continue + filteredHeaders.push(`${key}: ${line.slice(colonIdx + 1).trim()}`) + } + + const parsedUrl = /^https?:\/\//i.test(target) + ? new URL(target) + : new URL(`http://${hostHeader || 'localhost'}${target.startsWith('/') ? target : `/${target}`}`) + + const dstHost = parsedUrl.hostname + const dstPort = Number(parsedUrl.port) || (parsedUrl.protocol === 'https:' ? 443 : 80) + const match = matchRoutingRule(dstHost, dstPort, mode, compiledRules) + if (match.action === 'REJECT') { + clientSocket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n') + return + } + + const upstream = await dialUpstream(match.action, dstHost, dstPort) + if (clientSocket.destroyed) { + upstream.destroy() + return + } + + const originPath = `${parsedUrl.pathname}${parsedUrl.search}` + if (!hostHeader) { + filteredHeaders.unshift(`Host: ${parsedUrl.host}`) + } + filteredHeaders.push('Connection: close') + const rewrittenHead = `${method} ${originPath} ${httpVer}\r\n${filteredHeaders.join('\r\n')}\r\n\r\n` + const combinedInitial = Buffer.concat([Buffer.from(rewrittenHead, 'utf8'), leftover]) + + bridgeSockets( + { + host: dstHost, + port: dstPort, + protocol: 'HTTP', + ...match + }, + clientSocket, + upstream, + combinedInitial + ) + } catch (err) { + reader.detach() + lastError = err instanceof Error ? err.message : String(err) + if (!clientSocket.destroyed) { + try { + clientSocket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n') + } catch {} + clientSocket.destroy() + } + } + } + + function handleIncomingSocket(clientSocket) { + clientSocket.on('error', () => { + // suppress uncaught client reset errors + }) + clientSocket.once('data', (firstChunk) => { + if (!running || !firstChunk || firstChunk.length === 0) { + clientSocket.destroy() + return + } + if (firstChunk[0] === 0x05) { + void handleSocks5Client(clientSocket, firstChunk) + } else { + void handleHttpClient(clientSocket, firstChunk) + } + }) + } + + function restoreSystemProxyBestEffort() { + if (!managedSystemProxy) return + managedSystemProxy = false + try { + sysProxyApi.setSystemProxy({ enabled: false }) + } catch { + // ignore cleanup failures on shutdown + } + } + + async function probeLatencyFor(targetTransport) { + if (customProbeFn) { + return customProbeFn({ + transport: targetTransport, + port: boundPort, + nativePort: nativeCore.getStatus().port, + profile + }) + } + const targetPort = targetTransport === 'native' ? nativeCore.getStatus().port : boundPort + if (!targetPort) throw new Error('探测端口未就绪') + const started = Date.now() + const res = await httpClient.request('https://www.cloudflare.com/cdn-cgi/trace', { + timeoutMs: 4000, + proxyUrl: `http://127.0.0.1:${targetPort}` + }) + if (!res.ok) throw new Error(`HTTP ${res.status}`) + return Math.max(1, Date.now() - started) + } + + async function evaluateAndOptimizeTransport() { + if (!running || mode === 'direct') return getStatus() + + if (activeTransport === 'ssh') { + try { + const ms = await probeLatencyFor('ssh') + sshLatencyMs = ms + sshFailStreak = 0 + if (transportPolicy === 'auto' && nativeProxyNode && ms > sshSlowThresholdMs) { + await switchToNative(`检测到 SSH 延迟较高 (${ms}ms > ${sshSlowThresholdMs}ms),已自动无感切换至原生高速协议`) + try { + nativeLatencyMs = await probeLatencyFor('native') + } catch {} + } + } catch (err) { + sshFailStreak += 1 + if (transportPolicy === 'auto' && nativeProxyNode) { + await switchToNative(`SSH 通道受限 (${err instanceof Error ? err.message : '不可用'}),已自动无感切换至原生高速协议`) + } + } + return getStatus() + } + + try { + const ms = await probeLatencyFor('native') + nativeLatencyMs = ms + nativeFailStreak = 0 + } catch { + nativeFailStreak += 1 + if (nativeFailStreak >= 2 && (profile?.host || customUpstreamDialer)) { + activeTransport = 'ssh' + switchReason = '原生高速通道连续探测失败,已自动无感切回 SSH 通道' + } + } + return getStatus() + } + + function clearMonitorTimer() { + if (monitorTimer) { + clearInterval(monitorTimer) + monitorTimer = null + } + } + + function stopSync() { + clearMonitorTimer() + running = false + boundPort = 0 + startedAt = '' + activeTransport = 'ssh' + ruleAdapted = false + ruleAdaptReason = '' + switchPromise = null + restoreSystemProxyBestEffort() + closeAllConnections() + nativeCore.stopSync() + if (server) { + try { + server.close() + } catch {} + server = null + } + if (sshConn) { + try { + sshConn._vpsMgrReady = false + sshConn.end() + } catch {} + sshConn = null + } + sshConnectingPromise = null + customUpstreamDialer = null + return getStatus() + } + + async function stop() { + clearMonitorTimer() + running = false + boundPort = 0 + startedAt = '' + activeTransport = 'ssh' + ruleAdapted = false + ruleAdaptReason = '' + switchPromise = null + restoreSystemProxyBestEffort() + closeAllConnections() + await nativeCore.stop() + + const closingServer = server + server = null + if (closingServer) { + await new Promise((resolve) => { + try { + closingServer.close(() => resolve()) + } catch { + resolve() + } + }) + } + + if (sshConn) { + try { + sshConn._vpsMgrReady = false + sshConn.end() + } catch {} + sshConn = null + } + sshConnectingPromise = null + customUpstreamDialer = null + return getStatus() + } + + async function start(options = {}) { + await stop() + + profile = options.profile || null + mode = ['direct', 'rule', 'global'].includes(options.mode) ? options.mode : 'rule' + transportPolicy = ['auto', 'native', 'ssh'].includes(options.transportPolicy) ? options.transportPolicy : 'auto' + nativeProxyNode = options.nativeProxyNode || profile?.nativeProxyNode || null + const compiledRes = compileLocalRoutingRules(options.yamlText || '', { + sourceKind: options.sourceKind, + sourceFormat: options.sourceFormat + }) + compiledRules = compiledRes.rules + ruleAdapted = compiledRes.adapted + ruleAdaptReason = compiledRes.adaptReason + customUpstreamDialer = typeof options.upstreamDialer === 'function' ? options.upstreamDialer : null + systemProxyWarning = '' + lastError = '' + switchReason = '' + sshLatencyMs = null + nativeLatencyMs = null + sshFailStreak = 0 + nativeFailStreak = 0 + uploadTotal = 0 + downloadTotal = 0 + activeTransport = 'ssh' + + const wantImmediateNative = transportPolicy === 'native' && nativeProxyNode + if (!customUpstreamDialer) { + if (!profile || !profile.host) { + if (!wantImmediateNative) { + throw new Error('请先添加并选择一台 VPS 服务器作为代理出口') + } + } else { + await ensureSshReady() + } + } + + const listenPort = Number.isInteger(Number(options.port)) && Number(options.port) > 0 ? Number(options.port) : 0 + const srv = net.createServer(handleIncomingSocket) + + try { + await new Promise((resolve, reject) => { + srv.once('error', reject) + srv.listen(listenPort, '127.0.0.1', () => { + srv.removeListener('error', reject) + resolve() + }) + }) + } catch (err) { + await stop() + throw new Error(`内置本地代理启动失败: ${err instanceof Error ? err.message : String(err)}`) + } + + server = srv + boundPort = srv.address().port + running = true + startedAt = new Date().toISOString() + + if (options.enableSystemProxy !== false) { + try { + sysProxyApi.setSystemProxy({ + enabled: true, + host: '127.0.0.1', + port: boundPort + }) + managedSystemProxy = true + } catch (err) { + managedSystemProxy = false + systemProxyWarning = err instanceof Error ? err.message : String(err) + } + } + + if (wantImmediateNative) { + const cached = nativeCore.findLocalBinary ? nativeCore.findLocalBinary() : nativeCore.getStatus().binaryCached + if (cached) { + try { + await switchToNative('已启用原生高速协议通道') + } catch { + // stay on SSH fallback cleanly + } + } else { + switchReason = '已先通过 SSH 启动上网,正在后台拉取原生高速内核并无感升级…' + void switchToNative('原生高速内核就绪,已自动无感切换').catch(() => {}) + } + } + + if (!deps.disableMonitorTimer) { + monitorTimer = setInterval(() => { + if (running && transportPolicy === 'auto' && nativeProxyNode) { + void evaluateAndOptimizeTransport().catch(() => {}) + } + }, MONITOR_INTERVAL_MS) + if (typeof monitorTimer.unref === 'function') monitorTimer.unref() + } + + return getStatus() + } + + function setMode(nextMode) { + if (!['direct', 'rule', 'global'].includes(nextMode)) { + throw new Error(`不支持的运行模式: ${nextMode}`) + } + mode = nextMode + return getStatus() + } + + async function setTransportPolicy(nextPolicy) { + if (!['auto', 'native', 'ssh'].includes(nextPolicy)) { + throw new Error(`不支持的通道策略: ${nextPolicy}`) + } + transportPolicy = nextPolicy + if (!running) { + return getStatus() + } + if (nextPolicy === 'ssh') { + activeTransport = 'ssh' + switchReason = '已手动切换为纯 SSH 通道' + await nativeCore.stop() + return getStatus() + } + if (nextPolicy === 'native') { + await switchToNative('已切换至原生高速协议通道') + return getStatus() + } + switchReason = '已开启智能通道切换(SSH 慢速时自动无感升级至原生协议)' + return evaluateAndOptimizeTransport() + } + + function setNativeNode(proxyObj) { + nativeProxyNode = proxyObj && typeof proxyObj === 'object' ? proxyObj : null + if (running && nativeProxyNode && transportPolicy === 'native') { + void switchToNative('已更新原生高速节点并切换').catch(() => {}) + } + return getStatus() + } + + function updateRules(yamlText, options = {}) { + const compiledRes = compileLocalRoutingRules(yamlText || '', { + sourceKind: options.sourceKind, + sourceFormat: options.sourceFormat + }) + compiledRules = compiledRes.rules + ruleAdapted = compiledRes.adapted + ruleAdaptReason = compiledRes.adaptReason + return getStatus() + } + + return { + start, + stop, + stopSync, + setMode, + setTransportPolicy, + setNativeNode, + triggerSmartSwitch: evaluateAndOptimizeTransport, + updateRules, + getStatus, + getConnections, + closeConnection, + closeAllConnections + } +} + +const defaultController = createEmbeddedProxyController() + +module.exports = { + CN_DOMAIN_HINTS, + isLoopbackHost, + isPrivateOrLoopbackHost, + matchIpv4Cidr, + compileLocalRoutingRules, + compileRulesFromYaml, + matchRoutingRule, + createEmbeddedProxyController, + defaultController +} diff --git a/plugins/vps-manager/preload/http-client.cjs b/plugins/vps-manager/preload/http-client.cjs new file mode 100644 index 000000000..d653c7a1f --- /dev/null +++ b/plugins/vps-manager/preload/http-client.cjs @@ -0,0 +1,395 @@ +const http = require('node:http') +const https = require('node:https') +const net = require('node:net') +const tls = require('node:tls') + +const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]) + +function formatNetworkError(err, rawUrl, timeoutMs = 8000) { + let origin = String(rawUrl || '') + let hostname = origin + try { + const parsed = new URL(origin) + origin = parsed.origin + hostname = parsed.hostname + } catch { + // keep raw string + } + + const code = err && (err.code || err.cause?.code) + if (code === 'ECONNREFUSED') { + return `无法连接到 ${origin}(端口未监听或服务未启动)` + } + if (code === 'ETIMEDOUT' || code === 'UND_ERR_CONNECT_TIMEOUT' || err?.name === 'AbortError') { + return `请求超时 (${Math.max(1, Math.round(timeoutMs / 1000))}s): ${origin}` + } + if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') { + return `域名解析失败: ${hostname}` + } + if (code === 'ECONNRESET' || code === 'EPIPE' || code === 'ERR_STREAM_PREMATURE_CLOSE') { + return `连接被远端重置: ${origin}` + } + if (code === 'EHOSTUNREACH' || code === 'ENETUNREACH') { + return `目标地址不可达: ${origin}` + } + if (code === 'DEPTH_ZERO_SELF_SIGNED_CERT' || code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' || code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + return `TLS 证书校验失败: ${origin} (${code})` + } + const message = err instanceof Error ? err.message : String(err || '未知网络错误') + if (/failed to fetch|fetch failed/i.test(message)) { + return `无法连接到 ${origin}(请确认目标服务已启动且网络可达)` + } + return `${origin}: ${message}` +} + +function wrapNetworkError(err, rawUrl, timeoutMs) { + const wrapped = new Error(formatNetworkError(err, rawUrl, timeoutMs)) + if (err && (err.code || err.cause?.code)) { + wrapped.code = err.code || err.cause?.code + } + return wrapped +} + +function openHttpProxyTunnel(proxyUrlObj, targetHost, targetPort, timeoutMs, originalUrl) { + return new Promise((resolve, reject) => { + const proxyHeaders = { + Host: `${targetHost}:${targetPort}` + } + if (proxyUrlObj.username || proxyUrlObj.password) { + const auth = Buffer.from( + `${decodeURIComponent(proxyUrlObj.username)}:${decodeURIComponent(proxyUrlObj.password)}` + ).toString('base64') + proxyHeaders['Proxy-Authorization'] = `Basic ${auth}` + } + + let settled = false + let activeTlsSocket = null + const fail = (err) => { + if (settled) return + settled = true + if (activeTlsSocket && !activeTlsSocket.destroyed) { + try { + activeTlsSocket.destroy() + } catch {} + } + reject(err) + } + + const connectReq = http.request({ + hostname: proxyUrlObj.hostname, + port: proxyUrlObj.port || 80, + method: 'CONNECT', + path: `${targetHost}:${targetPort}`, + headers: proxyHeaders, + agent: false, + timeout: timeoutMs + }) + + connectReq.setTimeout(timeoutMs, () => { + const timeoutErr = new Error(`代理连接超时 (${Math.max(1, Math.round(timeoutMs / 1000))}s): ${proxyUrlObj.origin}`) + timeoutErr.code = 'ETIMEDOUT' + connectReq.destroy(timeoutErr) + }) + + connectReq.on('response', (res) => { + res.resume() + fail(new Error(`HTTP 代理拒绝 CONNECT (${res.statusCode || 0}): ${originalUrl}`)) + }) + + connectReq.on('connect', (res, socket, head) => { + if (settled) { + socket.destroy() + return + } + if (res.statusCode !== 200) { + socket.destroy() + fail(new Error(`HTTP 代理 CONNECT 失败 (${res.statusCode}): ${originalUrl}`)) + return + } + if (head && head.length > 0) { + socket.unshift(head) + } + + const tlsOptions = { socket } + if (!net.isIP(targetHost)) { + tlsOptions.servername = targetHost + } + const tlsSocket = tls.connect(tlsOptions) + activeTlsSocket = tlsSocket + + const onTlsError = (err) => { + fail(wrapNetworkError(err, originalUrl, timeoutMs)) + } + const onTlsTimeout = () => { + const timeoutErr = new Error(`代理 TLS 握手超时 (${Math.max(1, Math.round(timeoutMs / 1000))}s): ${originalUrl}`) + timeoutErr.code = 'ETIMEDOUT' + fail(timeoutErr) + } + + tlsSocket.once('error', onTlsError) + tlsSocket.setTimeout(timeoutMs, onTlsTimeout) + tlsSocket.once('secureConnect', () => { + if (settled) { + tlsSocket.destroy() + return + } + settled = true + tlsSocket.removeListener('error', onTlsError) + tlsSocket.removeListener('timeout', onTlsTimeout) + tlsSocket.setTimeout(0) + resolve(tlsSocket) + }) + }) + + connectReq.on('error', (err) => { + fail(wrapNetworkError(err, proxyUrlObj.href, timeoutMs)) + }) + + connectReq.end() + }) +} + +async function requestOnce(urlObj, options, timeoutMs, maxBytes) { + let proxyUrlObj = null + if (options.proxyUrl) { + try { + proxyUrlObj = new URL(String(options.proxyUrl).trim()) + } catch { + throw new Error(`无效代理地址: ${options.proxyUrl}`) + } + } + + const targetPort = Number(urlObj.port) || (urlObj.protocol === 'https:' ? 443 : 80) + let tunneledSocket = null + if (proxyUrlObj && urlObj.protocol === 'https:') { + tunneledSocket = await openHttpProxyTunnel(proxyUrlObj, urlObj.hostname, targetPort, timeoutMs, urlObj.href) + } + + const truncateAtMaxBytes = Boolean(options.truncateAtMaxBytes) + let tunnelAgent = null + if (tunneledSocket) { + tunnelAgent = new https.Agent({ keepAlive: false }) + tunnelAgent.createConnection = () => tunneledSocket + } + + return new Promise((resolve, reject) => { + const useHttpDirectViaProxy = Boolean(proxyUrlObj && urlObj.protocol === 'http:') + const client = useHttpDirectViaProxy ? http : urlObj.protocol === 'https:' ? https : http + const headers = { ...(options.headers || {}) } + if (tunnelAgent && !headers.Connection && !headers.connection) { + headers.Connection = 'close' + } + if (useHttpDirectViaProxy) { + headers.Host = urlObj.host + if (proxyUrlObj.username || proxyUrlObj.password) { + const auth = Buffer.from( + `${decodeURIComponent(proxyUrlObj.username)}:${decodeURIComponent(proxyUrlObj.password)}` + ).toString('base64') + headers['Proxy-Authorization'] = `Basic ${auth}` + } + } + + let bodyBuf = null + if (options.body !== undefined && options.body !== null) { + bodyBuf = Buffer.isBuffer(options.body) ? options.body : Buffer.from(String(options.body), 'utf8') + if (!headers['Content-Length'] && !headers['content-length']) { + headers['Content-Length'] = String(bodyBuf.length) + } + } + + let settled = false + const cleanupTunnel = () => { + if (tunnelAgent) { + try { + tunnelAgent.destroy() + } catch {} + } + if (tunneledSocket && !tunneledSocket.destroyed) { + try { + tunneledSocket.destroy() + } catch {} + } + } + const finishErr = (err) => { + if (settled) return + settled = true + cleanupTunnel() + reject(err) + } + + const reqOptions = useHttpDirectViaProxy + ? { + protocol: 'http:', + hostname: proxyUrlObj.hostname, + port: proxyUrlObj.port || 80, + path: urlObj.href, + method: options.method || 'GET', + headers, + agent: false, + timeout: timeoutMs + } + : { + protocol: urlObj.protocol, + hostname: urlObj.hostname, + port: targetPort, + path: `${urlObj.pathname}${urlObj.search}`, + method: options.method || 'GET', + headers, + timeout: timeoutMs, + ...(tunnelAgent ? { agent: tunnelAgent } : {}) + } + + const req = client.request( + reqOptions, + (res) => { + const chunks = [] + let totalBytes = 0 + + res.on('data', (chunk) => { + if (settled) return + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + if (totalBytes + buf.length > maxBytes) { + if (truncateAtMaxBytes) { + const remain = Math.max(0, maxBytes - totalBytes) + if (remain > 0) chunks.push(buf.subarray(0, remain)) + settled = true + req.destroy() + cleanupTunnel() + const bufOut = Buffer.concat(chunks) + resolve({ + status: res.statusCode || 0, + statusText: res.statusMessage || '', + headers: res.headers || {}, + bodyBuffer: bufOut, + bodyText: bufOut.toString('utf8') + }) + return + } + req.destroy() + finishErr(new Error(`响应体过大,超过 ${Math.max(1, Math.round(maxBytes / 1024 / 1024))}MB 限制`)) + return + } + totalBytes += buf.length + chunks.push(buf) + }) + + res.on('end', () => { + if (settled) return + settled = true + cleanupTunnel() + const bufOut = Buffer.concat(chunks) + resolve({ + status: res.statusCode || 0, + statusText: res.statusMessage || '', + headers: res.headers || {}, + bodyBuffer: bufOut, + bodyText: bufOut.toString('utf8') + }) + }) + + res.on('error', (err) => { + finishErr(wrapNetworkError(err, urlObj.href, timeoutMs)) + }) + } + ) + + req.setTimeout(timeoutMs, () => { + const timeoutErr = new Error(`请求超时 (${Math.max(1, Math.round(timeoutMs / 1000))}s): ${urlObj.origin}`) + timeoutErr.code = 'ETIMEDOUT' + req.destroy(timeoutErr) + }) + + req.on('error', (err) => { + finishErr(wrapNetworkError(err, urlObj.href, timeoutMs)) + }) + + if (bodyBuf) { + req.write(bodyBuf) + } + req.end() + }) +} + +async function requestCore(rawUrl, options = {}) { + const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 8000 + const maxBytes = Number(options.maxBytes) > 0 ? Number(options.maxBytes) : 10 * 1024 * 1024 + const maxRedirects = Number.isInteger(options.maxRedirects) ? options.maxRedirects : 5 + const proxyUrl = options.proxyUrl ? String(options.proxyUrl).trim() : '' + + let currentUrl = new URL(String(rawUrl || '').trim()) + if (currentUrl.protocol !== 'http:' && currentUrl.protocol !== 'https:') { + throw new Error(`仅支持 http:// 或 https:// 协议: ${currentUrl.protocol}`) + } + + let method = String(options.method || 'GET').toUpperCase() + let body = options.body + const baseHeaders = { ...(options.headers || {}) } + + const truncateAtMaxBytes = Boolean(options.truncateAtMaxBytes) + + for (let hop = 0; hop <= maxRedirects; hop++) { + const res = await requestOnce( + currentUrl, + { method, headers: baseHeaders, body, proxyUrl, truncateAtMaxBytes }, + timeoutMs, + maxBytes + ) + const location = res.headers.location + if (REDIRECT_STATUS_CODES.has(res.status) && location && hop < maxRedirects) { + currentUrl = new URL(Array.isArray(location) ? location[0] : location, currentUrl) + if (currentUrl.protocol !== 'http:' && currentUrl.protocol !== 'https:') { + throw new Error(`重定向协议不受支持: ${currentUrl.protocol}`) + } + if (res.status === 301 || res.status === 302 || res.status === 303) { + method = 'GET' + body = undefined + delete baseHeaders['Content-Type'] + delete baseHeaders['content-type'] + delete baseHeaders['Content-Length'] + delete baseHeaders['content-length'] + } + continue + } + return { + ok: res.status >= 200 && res.status < 300, + status: res.status, + statusText: res.statusText, + headers: res.headers, + buffer: res.bodyBuffer, + text: res.bodyText, + url: currentUrl.href + } + } + + throw new Error(`重定向次数过多 (>${maxRedirects})`) +} + +async function request(rawUrl, options = {}) { + const res = await requestCore(rawUrl, options) + return { + ok: res.ok, + status: res.status, + statusText: res.statusText, + headers: res.headers, + text: res.text, + url: res.url + } +} + +async function requestBuffer(rawUrl, options = {}) { + const res = await requestCore(rawUrl, options) + return { + ok: res.ok, + status: res.status, + statusText: res.statusText, + headers: res.headers, + buffer: res.buffer, + url: res.url + } +} + +module.exports = { + request, + requestBuffer, + formatNetworkError +} diff --git a/plugins/vps-manager/preload/ip-check.cjs b/plugins/vps-manager/preload/ip-check.cjs new file mode 100644 index 000000000..3d283b15a --- /dev/null +++ b/plugins/vps-manager/preload/ip-check.cjs @@ -0,0 +1,741 @@ +const dns = require('node:dns') +const net = require('node:net') +const httpClient = require('./http-client.cjs') +const sshClient = require('./ssh-client.cjs') + +const DATACENTER_KEYWORDS = [ + 'amazon', 'aws', 'google', 'gcp', 'azure', 'microsoft', 'digitalocean', 'vultr', + 'linode', 'akamai', 'ovh', 'hetzner', 'oracle', 'alibaba', 'aliyun', 'tencent', + 'choopa', 'contabo', 'ionos', 'scaleway', 'cloudflare', 'm247', 'datacamp', + 'cdn77', 'cogent', 'tzulo', 'leaseweb', 'hostinger', 'racknerd', + 'bandwagon', 'it7', 'dmit', 'misaka', 'xtom', 'gcore', 'zenlayer' +] + +const RESIDENTIAL_KEYWORDS = [ + 'comcast', 'verizon', 'at&t', 'spectrum', 'charter', 'cox', 'ntt', 'kddi', + 'softbank', 'docomo', 'chunghwa', 'hinet', 'sonet', 'telstra', 'singtel', + 'starhub', 'telefonica', 'deutsche telekom', 'orange', 'vodafone', 'british telecom', + 'chinanet', 'chinamobile', 'china unicom', 'broadband', 'fiber', 'cable', 'residential' +] + +const SERVICE_PROBES = [ + { id: 'claude', name: 'Claude AI', category: 'ai', url: 'https://claude.ai' }, + { id: 'chatgpt', name: 'ChatGPT', category: 'ai', url: 'https://chatgpt.com' }, + { id: 'gemini', name: 'Google Gemini', category: 'ai', url: 'https://gemini.google.com' }, + { id: 'netflix', name: 'Netflix', category: 'stream', url: 'https://www.netflix.com/title/81280792' }, + { id: 'youtube', name: 'YouTube', category: 'stream', url: 'https://www.youtube.com' }, + { id: 'disney', name: 'Disney+', category: 'stream', url: 'https://www.disneyplus.com' }, + { id: 'tiktok', name: 'TikTok', category: 'stream', url: 'https://www.tiktok.com' }, + { id: 'github', name: 'GitHub', category: 'dev', url: 'https://github.com' }, + { id: 'discord', name: 'Discord', category: 'social', url: 'https://discord.com' }, + { id: 'telegram', name: 'Telegram API', category: 'social', url: 'https://api.telegram.org', apiEndpoint: true } +] + +const SPLIT_SITES = [ + { id: 'baidu', name: '百度 Baidu', group: '国内直连', url: 'https://www.baidu.com', direct: true }, + { id: 'bilibili', name: '哔哩哔哩', group: '国内直连', url: 'https://www.bilibili.com', direct: true }, + { id: 'taobao', name: '淘宝 Taobao', group: '国内直连', url: 'https://www.taobao.com', direct: true }, + { id: 'qq', name: '腾讯网 QQ', group: '国内直连', url: 'https://www.qq.com', direct: true }, + { id: 'cloudflare', name: 'Cloudflare', group: '海外常用', url: 'https://www.cloudflare.com' }, + { id: 'google', name: 'Google', group: '海外常用', url: 'https://www.google.com/generate_204' }, + { id: 'openai-api', name: 'OpenAI API', group: 'AI 服务', url: 'https://api.openai.com', apiEndpoint: true }, + { id: 'anthropic-api', name: 'Anthropic API', group: 'AI 服务', url: 'https://api.anthropic.com', apiEndpoint: true }, + { id: 'npmjs', name: 'npm Registry', group: '开发生态', url: 'https://registry.npmjs.org' }, + { id: 'docker', name: 'Docker Hub', group: '开发生态', url: 'https://hub.docker.com' }, + { id: 'spotify', name: 'Spotify', group: '流媒体', url: 'https://open.spotify.com' }, + { id: 'twitch', name: 'Twitch', group: '流媒体', url: 'https://www.twitch.tv' } +] + +function parseCloudflareTrace(rawText) { + const result = { + ip: '', + loc: '', + colo: '', + warp: '', + tls: '', + http: '' + } + for (const line of String(rawText || '').split(/\r?\n/)) { + const idx = line.indexOf('=') + if (idx <= 0) continue + const key = line.slice(0, idx).trim() + const val = line.slice(idx + 1).trim() + if (key in result) { + result[key] = val + } + } + return result +} + +function checkTcpReachable(host, port, timeoutMs = 2000) { + return new Promise((resolve, reject) => { + const socket = net.createConnection({ host, port }) + let settled = false + + const cleanup = () => { + socket.removeAllListeners() + if (!socket.destroyed) socket.destroy() + } + + socket.setTimeout(timeoutMs, () => { + if (settled) return + settled = true + cleanup() + reject(new Error(`本地代理 ${host}:${port} 连接超时,请确认代理客户端已启动并检查 HTTP 端口`)) + }) + + socket.once('connect', () => { + if (settled) return + settled = true + cleanup() + resolve(true) + }) + + socket.once('error', () => { + if (settled) return + settled = true + cleanup() + reject(new Error(`本地代理 ${host}:${port} 未监听或无法连接,请确认代理客户端已启动并检查 HTTP 端口`)) + }) + }) +} + +function evaluateIpRisk(geo = {}, claudeProbe = null) { + if (!geo || (!geo.ip && !geo.isp && !geo.org && !geo.as)) { + return { + score: 0, + level: 'unknown', + ipType: '未知', + isNative: null, + claudeScore: 0, + claudeAdvice: '未获取到出口 IP,无法评估纯净度与 Claude 风险', + reasons: ['未能获取到有效出口 IP,请检查网络或代理连通性'] + } + } + + let score = 82 + const reasons = [] + + const orgText = `${geo.isp || ''} ${geo.org || ''} ${geo.as || ''} ${geo.asname || ''}`.toLowerCase() + const isDatacenter = Boolean(geo.hosting) || DATACENTER_KEYWORDS.some((kw) => orgText.includes(kw)) + const isMobile = Boolean(geo.mobile) + const isProxy = Boolean(geo.proxy) + const looksResidential = !isDatacenter && !isProxy && RESIDENTIAL_KEYWORDS.some((kw) => orgText.includes(kw)) + + let ipType = '宽带 / 普通网络' + if (isProxy) { + ipType = '代理 / VPN 出口' + } else if (isMobile) { + ipType = '移动蜂窝网络' + } else if (isDatacenter) { + ipType = '数据中心 / 机房 IP' + } else if (looksResidential) { + ipType = '原生住宅宽带' + } + + if (isDatacenter) { + score -= 30 + reasons.push('ASN / 组织被识别为云计算或机房托管网络(风控敏感度较高)') + } else if (looksResidential) { + score += 10 + reasons.push('运营商属于常规家庭/商业宽带网段,IP 信任度高') + } + + if (isMobile) { + score += 6 + reasons.push('移动运营商 IP 段,常规业务风控放行率高') + } + + if (isProxy) { + score -= 22 + reasons.push('公共数据库存在代理 / VPN / 中继标签') + } + + if (geo.riskFieldsAvailable === false) { + reasons.push('当前归属地数据源缺少机房/代理风控标记,评分仅供参考') + } else if (!isDatacenter && !isProxy && !geo.org?.includes('Anycast')) { + reasons.push('未命中高危代理黑名单或典型匿名中继网段') + } + + let claudeScore = score + let claudeAdvice = '可正常访问,建议保持固定出口 IP' + if (claudeProbe) { + if (claudeProbe.status === 'blocked' || claudeProbe.status === 'fail') { + claudeScore = Math.max(12, score - 25) + claudeAdvice = '当前出口触发拦截或不可达,不建议主力登录 Claude 账号' + reasons.push(`Claude 连通性探测异常 (${claudeProbe.detail || claudeProbe.status})`) + } else if (claudeProbe.status === 'warn') { + claudeScore = Math.max(45, score - 6) + claudeAdvice = '探测触发 Cloudflare 人机验证(非直接封禁),建议在浏览器中实际验证访问' + reasons.push(`Claude 探测遇到人机验证 (${claudeProbe.detail})`) + } else if (isDatacenter) { + claudeScore = Math.max(38, Math.min(72, score + 4)) + claudeAdvice = 'Claude 页面可达,但机房 IP 建议搭配固定节点、开启二次验证并避免高频切换' + } else { + claudeScore = Math.min(98, score + 6) + claudeAdvice = 'Claude 可达且 IP 类型温和,适合长期稳定使用' + } + } + + score = Math.max(5, Math.min(99, Math.round(score))) + claudeScore = Math.max(5, Math.min(99, Math.round(claudeScore))) + + let level = 'good' + if (score >= 80) level = 'excellent' + else if (score >= 60) level = 'good' + else if (score >= 40) level = 'medium' + else level = 'high-risk' + + const isNative = isDatacenter ? false : looksResidential || isMobile ? true : null + + return { + score, + level, + ipType, + isNative, + claudeScore, + claudeAdvice, + reasons + } +} + +async function fetchJsonSafe(url, options = {}) { + const res = await httpClient.request(url, { + timeoutMs: options.timeoutMs || 5000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/126.0.0.0 Safari/537.36', + ...(options.headers || {}) + }, + proxyUrl: options.proxyUrl + }) + if (!res.ok) { + throw new Error(`HTTP ${res.status}`) + } + return JSON.parse(res.text) +} + +async function lookupGeoIp(ip, proxyUrl = '') { + const target = String(ip || '').trim() + if (!net.isIP(target)) return null + + const ipApiUrl = `http://ip-api.com/json/${encodeURIComponent(target)}?fields=status,message,country,countryCode,regionName,city,isp,org,as,asname,mobile,proxy,hosting,query&lang=zh-CN` + const proxyAttempts = proxyUrl ? [proxyUrl, ''] : [''] + + for (const attemptProxy of proxyAttempts) { + try { + const data = await fetchJsonSafe(ipApiUrl, { timeoutMs: 4500, proxyUrl: attemptProxy }) + if (data && data.status === 'success') { + return { + ip: data.query || target, + country: data.country || '', + countryCode: data.countryCode || '', + region: data.regionName || '', + city: data.city || '', + isp: data.isp || '', + org: data.org || '', + as: data.as || '', + asname: data.asname || '', + mobile: Boolean(data.mobile), + proxy: Boolean(data.proxy), + hosting: Boolean(data.hosting), + riskFieldsAvailable: true + } + } + } catch { + // try next attempt or fallback + } + } + + try { + const fallback = await fetchJsonSafe(`https://ipwho.is/${encodeURIComponent(target)}`, { + timeoutMs: 4500, + proxyUrl + }) + if (fallback && fallback.success !== false) { + return { + ip: fallback.ip || target, + country: fallback.country || '', + countryCode: fallback.country_code || '', + region: fallback.region || '', + city: fallback.city || '', + isp: fallback.connection?.isp || '', + org: fallback.connection?.org || '', + as: fallback.connection?.asn ? `AS${fallback.connection.asn}` : '', + asname: fallback.connection?.domain || '', + mobile: false, + proxy: false, + hosting: false, + riskFieldsAvailable: false + } + } + } catch { + // ignore fallback failure + } + + return { + ip: target, + country: '', + countryCode: '', + region: '', + city: '', + isp: '', + org: '', + as: '', + asname: '', + mobile: false, + proxy: false, + hosting: false, + riskFieldsAvailable: false + } +} + +function classifyProbeResult(item, { status = 0, headers = {}, text = '', latencyMs = 0, url = '' } = {}) { + const cfMitigated = String(headers['cf-mitigated'] || '').toLowerCase() + const isCfChallenge = + (status === 403 || status === 503) && + (cfMitigated.includes('challenge') || /just a moment|challenge-platform|cf-browser-verification/i.test(text)) + + if (item.id === 'netflix') { + if (status === 200) { + return { ...item, status: 'ok', badgeText: '全解锁', httpCode: status, latencyMs, detail: '全解锁 (非自制剧可用)' } + } + if (status === 404) { + return { ...item, status: 'warn', badgeText: '仅自制剧', httpCode: status, latencyMs, detail: '仅自制剧 (Originals)' } + } + if (status === 403) { + return { ...item, status: 'blocked', badgeText: '受限', httpCode: status, latencyMs, detail: '受限 / 拒绝访问' } + } + if (status === 301 || status === 302) { + return { ...item, status: 'warn', badgeText: '重定向', httpCode: status, latencyMs, detail: `HTTP ${status} · 未完成地区跳转` } + } + } + + if (item.id === 'gemini') { + if (/\/faq\b/i.test(url) || /isn'?t supported|not available in your country|region.*not.*supported/i.test(text)) { + return { ...item, status: 'blocked', badgeText: '地区受限', httpCode: status, latencyMs, detail: 'Gemini 当前地区不支持' } + } + } + + if (item.id === 'claude' || item.id === 'chatgpt') { + if (/app-unavailable|unsupported_country|not available in your (region|country)/i.test(text)) { + return { ...item, status: 'blocked', badgeText: '地区受限', httpCode: status, latencyMs, detail: '当前出口地区不支持' } + } + if (isCfChallenge) { + return { ...item, status: 'warn', badgeText: '需验证', httpCode: status, latencyMs, detail: `HTTP ${status} · Cloudflare 人机验证` } + } + } + + if (item.apiEndpoint) { + if (isCfChallenge) { + return { ...item, status: 'warn', badgeText: '需验证', httpCode: status, latencyMs, detail: `HTTP ${status} · Cloudflare 人机验证` } + } + if ((status >= 200 && status < 400) || status === 401 || status === 404 || status === 405) { + return { ...item, status: 'ok', badgeText: '可达', httpCode: status, latencyMs, detail: `HTTP ${status} · API 节点可达` } + } + } + + if (isCfChallenge) { + return { ...item, status: 'warn', badgeText: '需验证', httpCode: status, latencyMs, detail: `HTTP ${status} · Cloudflare 人机验证` } + } + if (status >= 200 && status < 400) { + return { ...item, status: 'ok', badgeText: '可用', httpCode: status, latencyMs, detail: `HTTP ${status} · 可用` } + } + if (status === 403 || status === 429) { + return { ...item, status: 'blocked', badgeText: '拦截', httpCode: status, latencyMs, detail: `HTTP ${status} · 风控/拦截` } + } + if (status === 0) { + return { ...item, status: 'fail', badgeText: '失败', httpCode: 0, latencyMs, detail: '不可达/超时' } + } + return { ...item, status: 'warn', badgeText: `HTTP ${status}`, httpCode: status, latencyMs, detail: `HTTP ${status}` } +} + +async function probeTarget(item, proxyUrl = '') { + const started = Date.now() + try { + const res = await httpClient.request(item.url, { + method: 'GET', + timeoutMs: 5000, + maxBytes: 64 * 1024, + truncateAtMaxBytes: true, + maxRedirects: 3, + proxyUrl, + headers: { + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/126.0.0.0 Safari/537.36', + Accept: 'text/html,application/json;q=0.9,*/*;q=0.8' + } + }) + const latencyMs = Date.now() - started + return classifyProbeResult(item, { + status: res.status, + headers: res.headers, + text: res.text, + latencyMs, + url: res.url + }) + } catch (err) { + const latencyMs = Date.now() - started + const msg = err instanceof Error ? err.message : String(err) + return { + ...item, + status: 'fail', + badgeText: /超时/.test(msg) ? '超时' : '失败', + httpCode: 0, + latencyMs, + detail: /超时/.test(msg) ? '请求超时' : '不可达' + } + } +} + +async function runDnsLeakCheck() { + const systemServers = dns.getServers() + const testDomains = ['openai.com', 'claude.ai', 'github.com', 'baidu.com'] + const records = await Promise.all( + testDomains.map(async (domain) => { + try { + const looked = await dns.promises.lookup(domain, { all: true, family: 4 }) + const ips = Array.from(new Set(looked.map((entry) => entry.address).filter(Boolean))).slice(0, 3) + if (ips.length > 0) { + return { domain, ips, ok: true } + } + } catch { + // fallback to resolve4 + } + try { + const ips = await dns.promises.resolve4(domain) + return { domain, ips: ips.slice(0, 3), ok: true } + } catch (err) { + return { domain, ips: [], ok: false, error: err instanceof Error ? err.message : String(err) } + } + }) + ) + + const hasFakeIp = records.some((r) => r.ips.some((ip) => /^198\.1[89]\./.test(ip))) + const usesLocalDns = systemServers.some( + (s) => s === '127.0.0.1' || s === '198.18.0.2' || s.startsWith('192.168.') || s.startsWith('10.') + ) + + let verdict = '常规 DNS 解析' + if (hasFakeIp) { + verdict = '已接管 Fake-IP (198.18.x.x),无海外 DNS 泄露风险' + } else if (systemServers.some((s) => ['1.1.1.1', '8.8.8.8', '9.9.9.9'].includes(s))) { + verdict = '使用公共海外 DNS(常规 UDP 53,非 DoH/DoT 加密)' + } else if (usesLocalDns) { + verdict = '使用本地/网关 DNS,建议在代理客户端开启 DNS 接管或 Fake-IP' + } + + return { + servers: systemServers, + hasFakeIp, + verdict, + records + } +} + +async function mapWithConcurrency(items, concurrency, worker) { + const list = Array.isArray(items) ? items : [] + const limit = Math.max(1, Number(concurrency) || 5) + const results = new Array(list.length) + let nextIdx = 0 + + async function runWorker() { + while (nextIdx < list.length) { + const idx = nextIdx++ + results[idx] = await worker(list[idx], idx) + } + } + + const workers = Array.from({ length: Math.min(limit, list.length) }, () => runWorker()) + await Promise.all(workers) + return results +} + +async function probeExitIp(proxyUrl = '') { + const [traceRes, v4Res, v6Res] = await Promise.allSettled([ + httpClient.request('https://www.cloudflare.com/cdn-cgi/trace', { timeoutMs: 7000, proxyUrl }), + fetchJsonSafe('https://api.ipify.org?format=json', { timeoutMs: 7000, proxyUrl }), + fetchJsonSafe('https://api64.ipify.org?format=json', { timeoutMs: 5000, proxyUrl }) + ]) + + const trace = + traceRes.status === 'fulfilled' && traceRes.value.ok + ? parseCloudflareTrace(traceRes.value.text) + : { ip: '', loc: '', colo: '', warp: '', tls: '', http: '' } + + const v4Ip = v4Res.status === 'fulfilled' ? String(v4Res.value?.ip || '') : '' + const v6Candidate = v6Res.status === 'fulfilled' ? String(v6Res.value?.ip || '') : '' + const ipv6 = net.isIPv6(v6Candidate) ? v6Candidate : net.isIPv6(trace.ip) ? trace.ip : '' + const ipv4 = net.isIPv4(v4Ip) ? v4Ip : net.isIPv4(trace.ip) ? trace.ip : '' + + return { + primaryIp: ipv4 || trace.ip || ipv6 || '', + ipv4, + ipv6, + trace + } +} + +async function probeDomesticDirectIp(proxyUrl = '') { + try { + const res = await fetchJsonSafe('https://myip.ipip.net/json', { timeoutMs: 3500, proxyUrl }) + if (res?.data?.ip) { + return { + ip: res.data.ip, + location: Array.isArray(res.data.location) ? res.data.location.filter(Boolean).join(' ') : '' + } + } + } catch { + // ignore + } + try { + const res = await fetchJsonSafe('http://ip-api.com/json/?fields=status,country,regionName,city,isp,query&lang=zh-CN', { + timeoutMs: 3500, + proxyUrl + }) + if (res?.status === 'success') { + return { + ip: res.query || '', + location: [res.country, res.regionName, res.city, res.isp].filter(Boolean).join(' ') + } + } + } catch { + // ignore + } + return null +} + +function buildVpsProbeScript() { + const probeCommands = SERVICE_PROBES.map( + (item) => `( + out=$(curl -sS -L --max-redirs 3 -m 5 -D "$TMPD/${item.id}.hdr" -o /dev/null -w "%{http_code}|%{time_total}|%{url_effective}" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/126.0.0.0 Safari/537.36" "${item.url}" 2>/dev/null || echo "000|0|") + cf=0 + if grep -qi '^cf-mitigated:[[:space:]]*challenge' "$TMPD/${item.id}.hdr" 2>/dev/null; then cf=1; fi + printf '%s|%s|%s\\n' "${item.id}" "$out" "$cf" > "$TMPD/p_${item.id}" +) &` + ).join('\n') + + return `TMPD=$(mktemp -d 2>/dev/null || echo "/tmp/vps_ipchk_$$") +mkdir -p "$TMPD" +trap 'rm -rf "$TMPD"' EXIT + +(curl -4fsSL --max-time 4 https://api.ipify.org 2>/dev/null || hostname -I 2>/dev/null | awk '{print $1}') > "$TMPD/v4" & +(curl -6fsSL --max-time 3 https://api64.ipify.org 2>/dev/null || true) > "$TMPD/v6" & +(curl -fsSL --max-time 4 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null || true) > "$TMPD/trace" & +${probeCommands} +wait + +echo "__IP_V4__" +cat "$TMPD/v4" 2>/dev/null || true +echo "" +echo "__IP_V6__" +cat "$TMPD/v6" 2>/dev/null || true +echo "" +echo "__IP_CF_TRACE__" +cat "$TMPD/trace" 2>/dev/null || true +echo "" +echo "__IP_PROBES__" +cat "$TMPD"/p_* 2>/dev/null || true +` +} + +async function runVpsRemoteCheck(vpsProfile) { + const script = buildVpsProbeScript() + const execRes = await sshClient.execCommand(vpsProfile, `sh -c ${sshClient.shellQuote(script)}`, { + timeoutMs: 25000 + }) + + const sections = {} + let key = null + for (const line of String(execRes.stdout || '').split('\n')) { + const m = /^__([A-Z0-9_]+)__$/.exec(line.trim()) + if (m) { + key = m[1] + sections[key] = [] + } else if (key) { + sections[key].push(line) + } + } + + const ipv4Raw = (sections.IP_V4 || []).join('').trim() + const ipv6Raw = (sections.IP_V6 || []).join('').trim() + const trace = parseCloudflareTrace((sections.IP_CF_TRACE || []).join('\n')) + let ipv4 = net.isIPv4(ipv4Raw) ? ipv4Raw : net.isIPv4(trace.ip) ? trace.ip : '' + let ipv6 = net.isIPv6(ipv6Raw) ? ipv6Raw : net.isIPv6(trace.ip) ? trace.ip : '' + + let primaryIp = ipv4 || trace.ip || ipv6 || '' + if (!primaryIp && vpsProfile.host) { + if (net.isIP(vpsProfile.host)) { + primaryIp = vpsProfile.host + } else { + try { + const looked = await dns.promises.lookup(vpsProfile.host, { family: 4 }) + primaryIp = looked.address || '' + } catch { + try { + const lookedAny = await dns.promises.lookup(vpsProfile.host) + primaryIp = lookedAny.address || '' + } catch { + primaryIp = '' + } + } + } + if (net.isIPv4(primaryIp) && !ipv4) ipv4 = primaryIp + if (net.isIPv6(primaryIp) && !ipv6) ipv6 = primaryIp + } + + const probeMap = {} + for (const line of sections.IP_PROBES || []) { + const parts = line.trim().split('|') + const id = parts[0] + if (!id) continue + const code = Number(parts[1]) || 0 + const latencyMs = Math.round((parseFloat(parts[2] || '0') || 0) * 1000) + const cfChallenge = parts[parts.length - 1] === '1' + const effectiveUrl = parts.slice(3, -1).join('|') + probeMap[id] = { code, latencyMs, cfChallenge, effectiveUrl } + } + + const services = SERVICE_PROBES.map((item) => { + const p = probeMap[item.id] || { code: 0, latencyMs: 0, cfChallenge: false, effectiveUrl: '' } + return classifyProbeResult(item, { + status: p.code, + headers: p.cfChallenge ? { 'cf-mitigated': 'challenge' } : {}, + text: '', + latencyMs: p.latencyMs, + url: p.effectiveUrl + }) + }) + + const geo = primaryIp ? await lookupGeoIp(primaryIp) : null + const risk = evaluateIpRisk(geo || {}, services.find((s) => s.id === 'claude')) + + return { + checkedAt: new Date().toISOString(), + mode: 'vps', + exit: { + primaryIp, + ipv4, + ipv6, + trace, + geo + }, + domestic: null, + risk, + services, + splitTests: [], + dnsLeak: null + } +} + +function buildDomesticSummary(mode, domesticDirect, domesticViaProxy, exitPrimaryIp) { + if (!domesticDirect && !domesticViaProxy) return null + const directIp = domesticDirect?.ip || '' + const viaProxyIp = mode === 'proxy' ? domesticViaProxy?.ip || '' : '' + + let splitStatus = 'unknown' + if (mode === 'proxy' && viaProxyIp) { + if (directIp && viaProxyIp === directIp && viaProxyIp !== exitPrimaryIp) { + splitStatus = 'direct-ok' + } else if (exitPrimaryIp && viaProxyIp === exitPrimaryIp && viaProxyIp !== directIp) { + splitStatus = 'proxied' + } else if (directIp && exitPrimaryIp && directIp === exitPrimaryIp) { + splitStatus = 'same-exit' + } + } else if (directIp && exitPrimaryIp) { + splitStatus = directIp !== exitPrimaryIp ? 'direct-ok' : 'same-exit' + } + + return { + ip: directIp || viaProxyIp, + location: domesticDirect?.location || domesticViaProxy?.location || '', + viaProxyIp: viaProxyIp || undefined, + splitStatus + } +} + +async function runFullIpCheck(options = {}) { + const mode = options.mode || 'direct' + if (mode === 'vps' && options.vpsProfile) { + return runVpsRemoteCheck(options.vpsProfile) + } + + if (mode === 'custom-ip') { + const targetIp = String(options.customIp || '').trim() + if (!net.isIP(targetIp)) { + throw new Error('请输入合法的 IPv4 或 IPv6 地址') + } + const geo = await lookupGeoIp(targetIp) + const risk = evaluateIpRisk(geo || {}, null) + return { + checkedAt: new Date().toISOString(), + mode, + exit: { + primaryIp: targetIp, + ipv4: net.isIPv4(targetIp) ? targetIp : '', + ipv6: net.isIPv6(targetIp) ? targetIp : '', + trace: { ip: targetIp, loc: geo?.countryCode || '', colo: '', warp: '', tls: '', http: '' }, + geo + }, + domestic: null, + risk, + services: [], + splitTests: [], + dnsLeak: null + } + } + + let proxyUrl = '' + if (mode === 'proxy') { + proxyUrl = String(options.proxyUrl || '').trim() + let parsedProxy + try { + parsedProxy = new URL(proxyUrl) + } catch { + throw new Error('请输入有效的本地 HTTP 代理地址') + } + if (parsedProxy.protocol !== 'http:' && parsedProxy.protocol !== 'https:') { + throw new Error(`仅支持 HTTP/HTTPS 代理端口检测,当前为 ${parsedProxy.protocol}`) + } + const portNum = Number(parsedProxy.port) || (parsedProxy.protocol === 'https:' ? 443 : 80) + await checkTcpReachable(parsedProxy.hostname, portNum, 2000) + } + + const [exitProbe, domesticDirect, domesticViaProxy, dnsLeak] = await Promise.all([ + probeExitIp(proxyUrl), + probeDomesticDirectIp(''), + mode === 'proxy' ? probeDomesticDirectIp(proxyUrl) : Promise.resolve(null), + runDnsLeakCheck() + ]) + + const [geo, services, splitTests] = await Promise.all([ + exitProbe.primaryIp ? lookupGeoIp(exitProbe.primaryIp, proxyUrl) : Promise.resolve(null), + mapWithConcurrency(SERVICE_PROBES, 5, (item) => probeTarget(item, proxyUrl)), + mapWithConcurrency(SPLIT_SITES, 5, (item) => probeTarget(item, proxyUrl)) + ]) + + const risk = evaluateIpRisk(geo || {}, exitProbe.primaryIp ? services.find((s) => s.id === 'claude') : null) + const domestic = buildDomesticSummary(mode, domesticDirect, domesticViaProxy, exitProbe.primaryIp) + + return { + checkedAt: new Date().toISOString(), + mode, + proxyUrl, + exit: { + ...exitProbe, + geo + }, + domestic, + risk, + services, + splitTests, + dnsLeak + } +} + +module.exports = { + parseCloudflareTrace, + evaluateIpRisk, + classifyProbeResult, + buildVpsProbeScript, + lookupGeoIp, + runFullIpCheck +} diff --git a/plugins/vps-manager/preload/mcp-tools.cjs b/plugins/vps-manager/preload/mcp-tools.cjs new file mode 100644 index 000000000..71f366259 --- /dev/null +++ b/plugins/vps-manager/preload/mcp-tools.cjs @@ -0,0 +1,929 @@ +const fs = require('node:fs') +const path = require('node:path') +const sshClient = require('./ssh-client.cjs') +const deployTemplates = require('./deploy-templates.cjs') +const clashApi = require('./clash-api.cjs') +const configStore = require('./config-store.cjs') +const ipCheck = require('./ip-check.cjs') + +const STORAGE_KEYS = { + vpsProfiles: 'vps_manager_profiles_v1', + clashEndpoints: 'vps_manager_clash_endpoints_v1', + selectedVpsId: 'vps_manager_selected_vps_v1', + selectedEndpointId: 'vps_manager_selected_endpoint_v1' +} + +const DEFAULT_LOCAL_ENDPOINT = { + id: 'local-default', + name: '本地 Clash / Mihomo', + baseUrl: 'http://127.0.0.1:9090', + secret: '' +} + +const TOOL_NAMES = Object.freeze({ + listServers: 'vps_list_servers', + getMetrics: 'vps_get_metrics', + discoverProxy: 'vps_discover_proxy', + manageService: 'vps_manage_service', + deployProxy: 'vps_deploy_proxy', + execCommand: 'vps_exec_command', + clashGetStatus: 'clash_get_status', + clashSwitchProxy: 'clash_switch_proxy', + clashTestDelay: 'clash_test_delay', + vpsSyncRules: 'vps_sync_rules', + ipCheck: 'ip_check', + loadSkill: 'vps_load_skill' +}) + +const TOOL_DEFINITIONS = Object.freeze([ + { + name: TOOL_NAMES.listServers, + title: '列出 VPS 服务器与隧道', + description: '只读列出插件已保存的 VPS 服务器档案(自动脱敏密码与私钥)、活跃 SSH 隧道,以及可选本机 ~/.ssh/config 主机。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.getMetrics, + title: '采集 VPS 运维监控', + description: '只读采集目标 VPS 的 CPU、内存、磁盘、网速、BBR、监听端口和代理 systemd 服务状态。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.discoverProxy, + title: '扫描服务器已有代理配置', + description: '只读探测目标 VPS 上运行的代理服务、配置文件路径、端口、节点数及前 50 条分流规则摘要。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.clashGetStatus, + title: '获取 Clash / Mihomo 状态', + description: '只读查询本地或远端 Clash 控制器版本、运行模式、策略组与当前选中节点(可选规则/连接摘要)。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.clashTestDelay, + title: '代理节点延迟测速', + description: '只读测试单个代理节点或整个策略组的延迟并返回排序结果。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.ipCheck, + title: 'IP 纯净度与分流检测', + description: '只读执行多维度 IP 检测(proxy / direct / vps / custom-ip):Claude 风险评分、流媒体解锁、网站真实分流与 DNS 泄露排查。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.loadSkill, + title: '读取内置 Skill 指南', + description: '只读加载本插件内置 vps-manager Skill 的 SKILL.md 主规范或指定场景参考手册。', + mutating: false, + requiresConfirmation: false + }, + { + name: TOOL_NAMES.manageService, + title: '控制 VPS 代理服务', + description: 'status/logs 为只读;start/stop/restart 修改远端 systemd 服务状态,强制要求先预览确认并传 confirm=true 与 confirmHost。', + mutating: true, + requiresConfirmation: true + }, + { + name: TOOL_NAMES.deployProxy, + title: '一键部署代理服务', + description: '生成部署配置、Shadowrocket URI 与 Clash YAML;仅当 execute=true 且携带 confirm=true 与 confirmHost 时才通过 SSH 部署到服务器。', + mutating: true, + requiresConfirmation: true + }, + { + name: TOOL_NAMES.execCommand, + title: 'SSH 执行运维命令', + description: '在指定 VPS 上执行 Shell 命令。始终强制两步二次确认:未传 confirm=true 与匹配 confirmHost 时仅返回命令确认预览。', + mutating: true, + requiresConfirmation: true + }, + { + name: TOOL_NAMES.clashSwitchProxy, + title: '切换 Clash 节点或模式', + description: '切换运行模式、策略组出站节点或重载配置。本地回环可直接执行;远端或 SSH 隧道控制器强制要求 confirm=true 与 confirmHost。', + mutating: true, + requiresConfirmation: true + }, + { + name: TOOL_NAMES.vpsSyncRules, + title: '预览或同步远端分流规则', + description: 'preview 为只读预览;add_rule/remove_rule/push_yaml 会修改服务器配置文件(自动 .bak 备份),强制要求 confirm=true 与 confirmHost。', + mutating: true, + requiresConfirmation: true + } +]) + +const SKILLS_DIR = path.resolve(__dirname, '..', 'skills', 'vps-manager') + +const SKILL_FILES = Object.freeze([ + { + id: 'overview', + title: '主技能总览 (SKILL.md)', + description: '工具列表、强制两步二次确认规范与场景路由', + relativePath: 'SKILL.md' + }, + { + id: 'vps-ops', + title: 'SSH 运维与服务控制', + description: '系统指标采集、systemd 服务启停与 SSH 命令二次确认流程', + relativePath: 'references/vps-ops.md' + }, + { + id: 'proxy-routing', + title: '代理切换与分流同步', + description: 'Clash 控制器切换、延迟测速与远端规则配置安全同步', + relativePath: 'references/proxy-routing.md' + }, + { + id: 'safe-deploy', + title: '五协议安全部署', + description: 'sing-box / Xray / Hysteria2 / Mihomo / SS-2022 预览与部署流程', + relativePath: 'references/safe-deploy.md' + }, + { + id: 'ip-diagnostics', + title: 'IP 纯净度与泄露诊断', + description: '四模式检测、Claude 风险评估、流媒体与真分流结果解读', + relativePath: 'references/ip-diagnostics.md' + } +]) + +const VALID_PROTOCOLS = new Set(['singbox-reality', 'xray-reality', 'hysteria2', 'mihomo-node', 'ss-rust']) +const registeredHosts = new WeakSet() + +function parseEndpointHost(baseUrl) { + const raw = String(baseUrl || '').trim() + if (!raw) return '' + try { + const parsed = new URL(raw.includes('://') ? raw : `http://${raw}`) + return parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '') + } catch { + return '' + } +} + +function isRemoteEndpointUrl(baseUrl, endpointObj = null) { + if (endpointObj && endpointObj.tunnelId) return true + const host = parseEndpointHost(baseUrl) + if (!host) return false + return host !== '127.0.0.1' && host !== 'localhost' && host !== '::1' +} + +function sanitizeProfile(profile) { + if (!profile || typeof profile !== 'object') return null + return { + id: String(profile.id || ''), + name: String(profile.name || profile.host || ''), + host: String(profile.host || ''), + port: Number(profile.port) || 22, + username: String(profile.username || 'root'), + authType: profile.authType === 'key' ? 'key' : 'password', + privateKeyPath: profile.privateKeyPath || '', + notes: profile.notes || '', + clashConfigPath: profile.clashConfigPath || '', + clashControllerPort: Number(profile.clashControllerPort) || 9090, + hasCredentials: Boolean(profile.password || profile.privateKey || profile.privateKeyPath) + } +} + +function readDbStorageJson(hostApi, key, fallback) { + try { + const db = hostApi?.dbStorage + if (!db || typeof db.getItem !== 'function') return fallback + const raw = db.getItem(key) + if (raw === null || raw === undefined) return fallback + if (typeof raw === 'string') return JSON.parse(raw) + return raw + } catch { + return fallback + } +} + +function loadSkillDocument(skillId = 'overview') { + const cleanId = String(skillId || 'overview').trim() || 'overview' + const meta = SKILL_FILES.find((item) => item.id === cleanId) + if (!meta) { + throw new Error(`未知内置 Skill: ${cleanId},可用值: ${SKILL_FILES.map((s) => s.id).join(', ')}`) + } + const fullPath = path.resolve(SKILLS_DIR, meta.relativePath) + const relCheck = path.relative(SKILLS_DIR, fullPath) + if (relCheck.startsWith('..') || path.isAbsolute(relCheck)) { + throw new Error('非法的 Skill 文件路径') + } + const content = fs.readFileSync(fullPath, 'utf8') + return { + ...meta, + fullPath, + content + } +} + +function createDefaultBridge() { + return { + ssh: { + collectMetrics: (profile, options) => sshClient.collectSystemMetrics(profile, options), + discoverRemoteProxy: (profile, options) => sshClient.discoverRemoteProxy(profile, options), + manageService: (profile, serviceName, action) => sshClient.manageService(profile, serviceName, action), + execCommand: (profile, command, options) => sshClient.execCommand(profile, command, options), + readRemoteFile: (profile, remotePath) => sshClient.readRemoteFile(profile, remotePath), + writeRemoteFile: (profile, remotePath, content, options) => + sshClient.writeRemoteFile(profile, remotePath, content, options), + listTunnels: () => sshClient.listTunnels(), + discoverSshConfigHosts: () => sshClient.discoverSshConfigHosts() + }, + deploy: { + generateSecrets: (protocol, options) => deployTemplates.generateSecrets(protocol, options), + buildBundle: (params) => deployTemplates.buildDeploymentBundle(params), + executeDeploy: async (profile, params) => { + const bundle = deployTemplates.buildDeploymentBundle(params) + const encodedScript = Buffer.from(bundle.installScript, 'utf8').toString('base64') + const cmd = `echo ${sshClient.shellQuote(encodedScript)} | base64 -d | (if [ "$(id -u)" -eq 0 ]; then bash; else sudo bash; fi)` + const execRes = await sshClient.execCommand(profile, cmd, { timeoutMs: 180000 }) + return { ...bundle, execRes } + } + }, + clash: { + getOverview: (ep) => clashApi.getOverview(ep), + patchConfigs: (ep, patch) => clashApi.patchConfigs(ep, patch), + reloadConfig: (ep, configPath) => clashApi.reloadConfig(ep, configPath), + selectProxy: (ep, groupName, proxyName) => clashApi.selectProxy(ep, groupName, proxyName), + testProxyDelay: (ep, proxyName, testUrl, timeout) => clashApi.testProxyDelay(ep, proxyName, testUrl, timeout), + testGroupDelay: (ep, proxyNames, testUrl, timeout) => clashApi.testGroupDelay(ep, proxyNames, testUrl, timeout), + getRules: (ep) => clashApi.getRules(ep), + getConnections: (ep) => clashApi.getConnections(ep) + }, + config: { + parseYaml: (yamlText) => configStore.parseClashYaml(yamlText), + updateRulesInYaml: (yamlText, ruleItems) => configStore.updateRulesInYaml(yamlText, ruleItems) + }, + ipCheck: { + runCheck: (options) => ipCheck.runFullIpCheck(options) + } + } +} + +function createMcpService(options = {}) { + const hostProvider = typeof options.getHost === 'function' ? options.getHost : () => (typeof window !== 'undefined' ? window.ztools : null) + const bridge = options.bridge || createDefaultBridge() + + const runtimeContext = { + profiles: Array.isArray(options.initialProfiles) ? options.initialProfiles : null, + endpoints: Array.isArray(options.initialEndpoints) ? options.initialEndpoints : null, + selectedVpsId: options.initialSelectedVpsId || '', + selectedEndpointId: options.initialSelectedEndpointId || '' + } + + function syncContext(ctx = {}) { + if (Array.isArray(ctx.profiles)) runtimeContext.profiles = ctx.profiles + if (Array.isArray(ctx.endpoints)) runtimeContext.endpoints = ctx.endpoints + if (typeof ctx.selectedVpsId === 'string') runtimeContext.selectedVpsId = ctx.selectedVpsId + if (typeof ctx.selectedEndpointId === 'string') runtimeContext.selectedEndpointId = ctx.selectedEndpointId + return true + } + + function getProfiles() { + if (runtimeContext.profiles && runtimeContext.profiles.length > 0) { + return runtimeContext.profiles + } + const stored = readDbStorageJson(hostProvider(), STORAGE_KEYS.vpsProfiles, []) + return Array.isArray(stored) ? stored : [] + } + + function getSelectedVpsId() { + if (runtimeContext.selectedVpsId) return runtimeContext.selectedVpsId + return String(readDbStorageJson(hostProvider(), STORAGE_KEYS.selectedVpsId, '') || '') + } + + function getEndpoints() { + if (runtimeContext.endpoints && runtimeContext.endpoints.length > 0) { + return runtimeContext.endpoints + } + const stored = readDbStorageJson(hostProvider(), STORAGE_KEYS.clashEndpoints, []) + if (Array.isArray(stored) && stored.length > 0) return stored + return [{ ...DEFAULT_LOCAL_ENDPOINT }] + } + + function getSelectedEndpointId() { + if (runtimeContext.selectedEndpointId) return runtimeContext.selectedEndpointId + return String(readDbStorageJson(hostProvider(), STORAGE_KEYS.selectedEndpointId, DEFAULT_LOCAL_ENDPOINT.id) || DEFAULT_LOCAL_ENDPOINT.id) + } + + function resolveServer(serverRef) { + const profiles = getProfiles() + if (profiles.length === 0) { + throw new Error('尚未在插件中添加任何 VPS 服务器,请先在「服务器」界面添加并保存配置') + } + if (!serverRef || !String(serverRef).trim()) { + const selectedId = getSelectedVpsId() + return profiles.find((p) => p.id === selectedId) || profiles[0] + } + const q = String(serverRef).trim().toLowerCase() + const matched = + profiles.find((p) => String(p.id || '').toLowerCase() === q) || + profiles.find((p) => String(p.name || '').toLowerCase() === q) || + profiles.find((p) => String(p.host || '').toLowerCase() === q) + if (!matched) { + throw new Error(`未找到匹配的 VPS 服务器 "${serverRef}",请先调用 vps_list_servers 查看可用服务器`) + } + return matched + } + + function resolveEndpoint(endpointRef) { + const endpoints = getEndpoints() + const ref = String(endpointRef || '').trim() + if (!ref) { + const selectedId = getSelectedEndpointId() + return endpoints.find((e) => e.id === selectedId) || endpoints[0] + } + if (/^https?:\/\//i.test(ref) || /^[a-zA-Z0-9.-]+:\d+$/.test(ref)) { + const normalized = clashApi.normalizeBaseUrl(ref) + return endpoints.find((e) => clashApi.normalizeBaseUrl(e.baseUrl) === normalized) || { + id: 'adhoc', + name: ref, + baseUrl: normalized, + secret: '' + } + } + const q = ref.toLowerCase() + return ( + endpoints.find((e) => String(e.id || '').toLowerCase() === q) || + endpoints.find((e) => String(e.name || '').toLowerCase() === q) || + endpoints.find((e) => String(e.baseUrl || '').toLowerCase().includes(q)) || + (() => { + throw new Error(`未找到匹配的 Clash 控制器端点: ${endpointRef}`) + })() + ) + } + + function isConfirmedForHost(params, expectedHosts) { + if (!params || params.confirm !== true) return false + const actual = String(params.confirmHost || '').trim().toLowerCase() + if (!actual) return false + return expectedHosts.some((h) => h && String(h).trim().toLowerCase() === actual) + } + + const handlers = { + async [TOOL_NAMES.listServers](params = {}) { + const profiles = getProfiles().map(sanitizeProfile).filter(Boolean) + const tunnels = bridge.ssh.listTunnels ? bridge.ssh.listTunnels() : [] + const includeLocalSsh = Boolean(params.includeLocalSsh) + const localSshHosts = + includeLocalSsh && bridge.ssh.discoverSshConfigHosts ? bridge.ssh.discoverSshConfigHosts() : undefined + + return { + ok: true, + selectedVpsId: getSelectedVpsId(), + servers: profiles, + tunnels, + ...(localSshHosts ? { localSshHosts } : {}) + } + }, + + async [TOOL_NAMES.getMetrics](params = {}) { + const profile = resolveServer(params.server) + const metrics = await bridge.ssh.collectMetrics(profile, { light: Boolean(params.light) }) + return { + ok: true, + server: sanitizeProfile(profile), + metrics + } + }, + + async [TOOL_NAMES.discoverProxy](params = {}) { + const profile = resolveServer(params.server) + const discovery = await bridge.ssh.discoverRemoteProxy(profile, { + configPath: params.configPath ? String(params.configPath) : undefined + }) + + let rulesPreview = [] + if (discovery.yamlText && bridge.config?.parseYaml) { + try { + const parsed = bridge.config.parseYaml(discovery.yamlText) + rulesPreview = (parsed.parsedRules || []).slice(0, 50).map((r) => ({ + type: r.type, + value: r.value, + policy: r.policy, + enabled: r.enabled + })) + } catch { + rulesPreview = [] + } + } + + return { + ok: true, + server: sanitizeProfile(profile), + found: discovery.found, + primaryService: discovery.primaryService, + configPath: discovery.configPath, + format: discovery.format, + writableAsYaml: discovery.writableAsYaml, + proxiesCount: discovery.proxiesCount, + rulesCount: discovery.rulesCount, + proxyGroupsCount: discovery.proxyGroupsCount, + controllerHost: discovery.controllerHost, + controllerPort: discovery.controllerPort, + mixedPort: discovery.mixedPort, + mode: discovery.mode, + services: discovery.services, + candidates: discovery.candidates || [], + rulesPreview + } + }, + + async [TOOL_NAMES.manageService](params = {}) { + const profile = resolveServer(params.server) + const serviceName = sshClient.validateServiceName(params.serviceName) + const action = String(params.action || '').trim().toLowerCase() + if (!['status', 'logs', 'start', 'stop', 'restart'].includes(action)) { + throw new Error(`不支持的服务操作: ${action}`) + } + + const isMutating = action !== 'status' && action !== 'logs' + if (isMutating && !isConfirmedForHost(params, [profile.host])) { + const impact = + action === 'stop' + ? `停止 ${serviceName} 会立即中断该 VPS 上的代理流量转发` + : action === 'restart' + ? `重启 ${serviceName} 会短暂中断当前活跃代理连接` + : `将启动 ${serviceName} systemd 服务并开放对应代理端口` + return { + ok: true, + requiresConfirmation: true, + dryRun: true, + target: `${profile.name} (${profile.username}@${profile.host}:${profile.port})`, + confirmHost: profile.host, + serviceName, + action, + commandPreview: `systemctl ${action} ${serviceName}`, + impact, + nextStep: `请向用户确认后,重新调用 vps_manage_service 并传入 confirm: true, confirmHost: "${profile.host}"` + } + } + + const execRes = await bridge.ssh.manageService(profile, serviceName, action) + return { + ok: true, + requiresConfirmation: false, + dryRun: false, + server: sanitizeProfile(profile), + serviceName, + action, + code: execRes.code, + stdout: execRes.stdout, + stderr: execRes.stderr + } + }, + + async [TOOL_NAMES.deployProxy](params = {}) { + const protocol = String(params.protocol || '').trim() + if (!VALID_PROTOCOLS.has(protocol)) { + throw new Error(`不支持的部署协议: ${protocol}`) + } + + const profile = params.server || params.execute ? resolveServer(params.server) : null + const host = String(params.host || profile?.host || '198.51.100.10').trim() + const secrets = bridge.deploy.generateSecrets(protocol, { ssMethod: params.ssMethod }) + const defaultPort = protocol === 'hysteria2' ? 8443 : protocol === 'mihomo-node' || protocol === 'ss-rust' ? 8388 : 443 + const port = Number(params.port) || defaultPort + + const deployParams = { + protocol, + host, + port, + sni: params.sni || 'www.apple.com', + nodeName: params.nodeName || `${profile?.name || host}-${protocol}`, + openFirewall: params.openFirewall !== false, + exposeController: Boolean(params.exposeController), + ssMethod: params.ssMethod || '2022-blake3-aes-128-gcm', + ...secrets + } + + const bundle = bridge.deploy.buildBundle(deployParams) + const execute = Boolean(params.execute) + + if (!execute || !profile || !isConfirmedForHost(params, [profile.host])) { + return { + ok: true, + requiresConfirmation: execute, + dryRun: true, + target: profile ? `${profile.name} (${profile.username}@${profile.host}:${profile.port})` : host, + confirmHost: profile?.host || host, + protocol, + port, + serviceName: bundle.serviceName, + openFirewall: deployParams.openFirewall, + exposeController: deployParams.exposeController, + shadowrocketUri: bundle.shadowrocketUri, + clashMetaProxy: bundle.clashMetaProxy, + instructions: bundle.instructions, + impact: execute + ? `将在远端服务器安装并覆写 ${bundle.serviceName} 配置与 systemd 单元,且${ + deployParams.openFirewall ? `放行 ${port} 端口` : '保持现有防火墙' + }` + : '当前仅生成配置预览,未对服务器做任何更改', + nextStep: execute && profile + ? `请向用户确认后,重新调用 vps_deploy_proxy 并传入 execute: true, confirm: true, confirmHost: "${profile.host}"` + : '若要真实部署到 VPS,请确认参数后传入 execute: true, confirm: true 与对应的 confirmHost' + } + } + + const execOut = await bridge.deploy.executeDeploy(profile, deployParams) + return { + ok: true, + requiresConfirmation: false, + dryRun: false, + server: sanitizeProfile(profile), + serviceName: execOut.serviceName, + shadowrocketUri: execOut.shadowrocketUri, + clashMetaProxy: execOut.clashMetaProxy, + code: execOut.execRes?.code, + stdout: execOut.execRes?.stdout, + stderr: execOut.execRes?.stderr + } + }, + + async [TOOL_NAMES.execCommand](params = {}) { + const profile = resolveServer(params.server) + const command = String(params.command || '').trim() + if (!command) { + throw new Error('请输入要执行的 Shell 命令 (command)') + } + + if (!isConfirmedForHost(params, [profile.host])) { + return { + ok: true, + requiresConfirmation: true, + dryRun: true, + target: `${profile.name} (${profile.username}@${profile.host}:${profile.port})`, + confirmHost: profile.host, + commandPreview: command, + warning: '远端 Shell 命令可能修改系统配置、文件或运行中进程,必须经用户明确确认后才可执行。', + nextStep: `请向用户展示以上命令并确认后,重新调用 vps_exec_command 并传入 confirm: true, confirmHost: "${profile.host}"` + } + } + + const timeoutMs = Number(params.timeoutMs) > 0 ? Number(params.timeoutMs) : 45000 + const execRes = await bridge.ssh.execCommand(profile, command, { timeoutMs }) + return { + ok: true, + requiresConfirmation: false, + dryRun: false, + server: sanitizeProfile(profile), + command, + code: execRes.code, + stdout: execRes.stdout, + stderr: execRes.stderr + } + }, + + async [TOOL_NAMES.clashGetStatus](params = {}) { + const endpoint = resolveEndpoint(params.endpoint) + const overview = await bridge.clash.getOverview(endpoint) + const groups = Object.values(overview.proxies || {}) + .filter((g) => Array.isArray(g.all) && g.all.length > 0) + .map((g) => ({ + name: g.name, + type: g.type, + now: g.now || '', + optionsCount: g.all.length, + options: g.all.slice(0, 30) + })) + + const result = { + ok: true, + endpoint: { + id: endpoint.id, + name: endpoint.name, + baseUrl: endpoint.baseUrl, + remote: isRemoteEndpointUrl(endpoint.baseUrl, endpoint) + }, + version: overview.version, + configs: overview.configs, + groups + } + + if (params.includeRules) { + const rules = await bridge.clash.getRules(endpoint) + result.rulesCount = rules.length + result.rulesSample = rules.slice(0, 40) + } + if (params.includeConnections) { + const conns = await bridge.clash.getConnections(endpoint) + result.connectionsSummary = { + count: (conns.connections || []).length, + downloadTotal: conns.downloadTotal || 0, + uploadTotal: conns.uploadTotal || 0 + } + } + return result + }, + + async [TOOL_NAMES.clashSwitchProxy](params = {}) { + const endpoint = resolveEndpoint(params.endpoint) + const action = String(params.action || '').trim() + if (!['set_mode', 'select_proxy', 'reload'].includes(action)) { + throw new Error(`不支持的 Clash 动作: ${action}`) + } + + if (action === 'set_mode' && !['direct', 'rule', 'global'].includes(String(params.mode || ''))) { + throw new Error('action="set_mode" 时必须提供 mode: "direct" | "rule" | "global"') + } + if (action === 'select_proxy' && (!params.groupName || !params.proxyName)) { + throw new Error('action="select_proxy" 时必须提供 groupName 与 proxyName') + } + + const remote = isRemoteEndpointUrl(endpoint.baseUrl, endpoint) + const endpointHost = parseEndpointHost(endpoint.baseUrl) + if (remote && !isConfirmedForHost(params, [endpointHost, endpoint.name])) { + const expectedHost = endpoint.tunnelId ? endpoint.name || endpointHost : endpointHost + return { + ok: true, + requiresConfirmation: true, + dryRun: true, + target: `${endpoint.name} (${endpoint.baseUrl})`, + confirmHost: expectedHost, + action, + details: { + mode: params.mode, + groupName: params.groupName, + proxyName: params.proxyName + }, + impact: '目标控制器位于远端服务器或 SSH 隧道,修改将直接影响服务器端转发策略或连接。', + nextStep: `请向用户确认后,重新调用 clash_switch_proxy 并传入 confirm: true, confirmHost: "${expectedHost}"` + } + } + + if (action === 'set_mode') { + await bridge.clash.patchConfigs(endpoint, { mode: params.mode }) + } else if (action === 'select_proxy') { + await bridge.clash.selectProxy(endpoint, String(params.groupName), String(params.proxyName)) + } else { + await bridge.clash.reloadConfig(endpoint, params.configPath ? String(params.configPath) : undefined) + } + + return { + ok: true, + requiresConfirmation: false, + dryRun: false, + endpoint: { id: endpoint.id, name: endpoint.name, baseUrl: endpoint.baseUrl, remote }, + action + } + }, + + async [TOOL_NAMES.clashTestDelay](params = {}) { + const endpoint = resolveEndpoint(params.endpoint) + const testUrl = params.testUrl ? String(params.testUrl) : undefined + const timeout = Number(params.timeout) > 0 ? Number(params.timeout) : 4500 + + if (params.proxyName) { + const res = await bridge.clash.testProxyDelay(endpoint, String(params.proxyName), testUrl, timeout) + return { + ok: true, + endpoint: endpoint.baseUrl, + proxyName: String(params.proxyName), + delay: typeof res.delay === 'number' ? res.delay : null + } + } + + const overview = await bridge.clash.getOverview(endpoint) + const groupName = String(params.groupName || '').trim() + const group = groupName + ? overview.proxies?.[groupName] + : Object.values(overview.proxies || {}).find((g) => Array.isArray(g.all) && g.all.length > 0) + + if (!group || !Array.isArray(group.all)) { + throw new Error(`未找到可测速的策略组${groupName ? `: ${groupName}` : ''}`) + } + + const candidates = group.all.filter((n) => !['DIRECT', 'REJECT', 'PASS'].includes(n)) + const results = await bridge.clash.testGroupDelay(endpoint, candidates, testUrl, timeout) + const sorted = Object.entries(results) + .map(([name, info]) => ({ name, delay: info.delay ?? null, ok: Boolean(info.ok), error: info.error })) + .sort((a, b) => (a.delay || 999999) - (b.delay || 999999)) + + return { + ok: true, + endpoint: endpoint.baseUrl, + groupName: group.name, + results: sorted + } + }, + + async [TOOL_NAMES.vpsSyncRules](params = {}) { + const profile = resolveServer(params.server) + const action = String(params.action || 'preview').trim() + if (!['preview', 'add_rule', 'remove_rule', 'push_yaml'].includes(action)) { + throw new Error(`不支持的规则操作: ${action}`) + } + + const discovery = await bridge.ssh.discoverRemoteProxy(profile, { + configPath: params.remotePath ? String(params.remotePath) : undefined + }) + const targetPath = String(params.remotePath || discovery.configPath || profile.clashConfigPath || '').trim() + if (!targetPath) { + throw new Error('未能识别远端配置文件路径,请显式传入 remotePath') + } + + if (action === 'preview') { + const parsed = discovery.yamlText ? bridge.config.parseYaml(discovery.yamlText) : null + return { + ok: true, + dryRun: true, + server: sanitizeProfile(profile), + remotePath: targetPath, + format: discovery.format, + writableAsYaml: discovery.writableAsYaml, + rulesCount: parsed ? parsed.parsedRules.length : discovery.rulesCount, + rulesSample: parsed ? parsed.parsedRules.slice(0, 50) : [] + } + } + + if (discovery.found && discovery.writableAsYaml === false && action !== 'push_yaml') { + throw new Error(`远端配置格式为 ${discovery.format},不支持直接按 Clash YAML 增删规则`) + } + + let nextYaml = '' + let changeSummary = '' + if (action === 'push_yaml') { + nextYaml = String(params.yamlText || '') + if (!nextYaml.trim()) throw new Error('action="push_yaml" 时必须提供非空 yamlText') + const parsedCheck = bridge.config.parseYaml(nextYaml) + changeSummary = `整份替换远端 YAML 配置(共 ${parsedCheck.parsedRules.length} 条规则)` + } else { + const rawBaseYaml = discovery.rawContent || discovery.yamlText || (await bridge.ssh.readRemoteFile(profile, targetPath)) + const parsed = bridge.config.parseYaml(rawBaseYaml) + const ruleLine = String(params.rule || '').trim() + if (!ruleLine) throw new Error(`${action} 必须提供 rule 参数`) + + const currentRules = [...parsed.parsedRules] + if (action === 'add_rule') { + const parsedRule = configStore.parseRuleLine(ruleLine) + if (!parsedRule) throw new Error(`无法解析规则: ${ruleLine}`) + const matchIdx = currentRules.findIndex((r) => r.type === 'MATCH' || r.type === 'FINAL') + if (matchIdx >= 0 && parsedRule.type !== 'MATCH') { + currentRules.splice(matchIdx, 0, parsedRule) + } else { + currentRules.unshift(parsedRule) + } + nextYaml = bridge.config.updateRulesInYaml(rawBaseYaml, currentRules) + changeSummary = `新增分流规则: ${configStore.formatRuleLine(parsedRule)}` + } else { + const needle = ruleLine.toLowerCase() + const remaining = currentRules.filter( + (r) => + configStore.formatRuleLine(r).toLowerCase() !== needle && + String(r.value || '').toLowerCase() !== needle + ) + const removedCount = currentRules.length - remaining.length + if (removedCount === 0) { + throw new Error(`未在配置中找到匹配规则: ${ruleLine}`) + } + nextYaml = bridge.config.updateRulesInYaml(rawBaseYaml, remaining) + changeSummary = `移除 ${removedCount} 条匹配 "${ruleLine}" 的规则` + } + } + + if (!isConfirmedForHost(params, [profile.host])) { + const previewParsed = bridge.config.parseYaml(nextYaml) + return { + ok: true, + requiresConfirmation: true, + dryRun: true, + target: `${profile.name} (${profile.username}@${profile.host}:${profile.port})`, + confirmHost: profile.host, + remotePath: targetPath, + action, + changeSummary, + totalRulesAfter: previewParsed.parsedRules.length, + backupNotice: '写入前将在远端自动创建 .bak 备份并重启/重载服务', + nextStep: `请向用户确认以上变更后,重新调用 vps_sync_rules 并传入 confirm: true, confirmHost: "${profile.host}"` + } + } + + await bridge.ssh.writeRemoteFile(profile, targetPath, nextYaml, { backup: true }) + const svcName = discovery.primaryService + let serviceRestarted = false + if (svcName) { + try { + await bridge.ssh.manageService(profile, svcName, 'restart') + serviceRestarted = true + } catch { + serviceRestarted = false + } + } + + return { + ok: true, + requiresConfirmation: false, + dryRun: false, + server: sanitizeProfile(profile), + remotePath: targetPath, + changeSummary, + serviceRestarted + } + }, + + async [TOOL_NAMES.ipCheck](params = {}) { + const mode = String(params.mode || 'proxy').trim() + if (!['proxy', 'direct', 'vps', 'custom-ip'].includes(mode)) { + throw new Error(`不支持的检测模式: ${mode}`) + } + const vpsProfile = mode === 'vps' ? resolveServer(params.server) : undefined + const res = await bridge.ipCheck.runCheck({ + mode, + proxyUrl: mode === 'proxy' ? String(params.proxyUrl || 'http://127.0.0.1:7890').trim() : '', + customIp: params.customIp ? String(params.customIp).trim() : '', + vpsProfile + }) + return { ok: true, ...res } + }, + + async [TOOL_NAMES.loadSkill](params = {}) { + const doc = loadSkillDocument(params.skill || 'overview') + return { + ok: true, + skillsDir: SKILLS_DIR, + availableSkills: SKILL_FILES, + skill: doc + } + } + } + + function getStatus(hostOverride) { + const hostApi = hostOverride || hostProvider() + const supportsRegisterTool = Boolean(hostApi && typeof hostApi.registerTool === 'function') + const registered = Boolean(hostApi && registeredHosts.has(hostApi)) + return { + registered, + registeredCount: registered ? TOOL_DEFINITIONS.length : 0, + supportsRegisterTool, + skillsDir: SKILLS_DIR, + tools: TOOL_DEFINITIONS, + skills: SKILL_FILES + } + } + + async function invokeTool(name, params = {}) { + const fn = handlers[name] + if (typeof fn !== 'function') { + throw new Error(`未知 MCP 工具: ${name}`) + } + return fn(params) + } + + return { + TOOL_NAMES, + TOOL_DEFINITIONS, + SKILL_FILES, + handlers, + syncContext, + getStatus, + listTools: () => TOOL_DEFINITIONS, + listSkills: () => SKILL_FILES, + loadSkill: (skillId) => loadSkillDocument(skillId), + invokeTool + } +} + +function registerTools(target, bridge) { + const ztools = target?.ztools + if (!ztools || typeof ztools.registerTool !== 'function') return false + if (registeredHosts.has(ztools)) return false + + const mcpService = createMcpService({ + getHost: () => ztools, + bridge + }) + + for (const def of TOOL_DEFINITIONS) { + const handler = mcpService.handlers[def.name] + if (typeof handler === 'function') { + ztools.registerTool.call(ztools, def.name, (input) => handler(input || {})) + } + } + + registeredHosts.add(ztools) + return mcpService +} + +module.exports = { + TOOL_NAMES, + TOOL_DEFINITIONS, + SKILL_FILES, + SKILLS_DIR, + isRemoteEndpointUrl, + sanitizeProfile, + loadSkillDocument, + createMcpService, + registerTools +} diff --git a/plugins/vps-manager/preload/native-core.cjs b/plugins/vps-manager/preload/native-core.cjs new file mode 100644 index 000000000..2ce17d143 --- /dev/null +++ b/plugins/vps-manager/preload/native-core.cjs @@ -0,0 +1,483 @@ +const { spawn } = require('node:child_process') +const fs = require('node:fs') +const net = require('node:net') +const os = require('node:os') +const path = require('node:path') +const zlib = require('node:zlib') +const yaml = require('js-yaml') +const httpClient = require('./http-client.cjs') + +const DEFAULT_MIHOMO_VERSION = 'v1.19.2' +const DEFAULT_BIN_DIR = path.join(os.homedir(), '.vps-manager', 'bin') +const DEFAULT_RUNTIME_DIR = path.join(os.homedir(), '.vps-manager', 'runtime') + +function resolveMihomoAsset(platform = process.platform, arch = process.arch, version = DEFAULT_MIHOMO_VERSION) { + const cleanVer = String(version || DEFAULT_MIHOMO_VERSION).trim() + const ver = cleanVer.startsWith('v') ? cleanVer : `v${cleanVer}` + const archMap = { + x64: 'amd64', + amd64: 'amd64', + arm64: 'arm64', + aarch64: 'arm64' + } + const mihomoArch = archMap[String(arch || '').toLowerCase()] + if (!mihomoArch) { + throw new Error(`暂不支持当前 CPU 架构自动下载原生内核: ${arch}`) + } + + let osToken = '' + let archiveType = 'gz' + let binaryName = 'mihomo' + if (platform === 'darwin') { + osToken = 'darwin' + } else if (platform === 'linux') { + osToken = 'linux' + } else if (platform === 'win32') { + osToken = 'windows' + archiveType = 'zip' + binaryName = 'mihomo.exe' + } else { + throw new Error(`暂不支持当前操作系统自动下载原生内核: ${platform}`) + } + + const filename = `mihomo-${osToken}-${mihomoArch}-${ver}.${archiveType}` + const url = `https://github.com/MetaCubeX/mihomo/releases/download/${encodeURIComponent(ver)}/${filename}` + return { + platform, + arch, + version: ver, + archiveType, + binaryName, + filename, + url + } +} + +function extractGzipBuffer(gzBuffer) { + return zlib.gunzipSync(Buffer.isBuffer(gzBuffer) ? gzBuffer : Buffer.from(gzBuffer)) +} + +function extractFirstExeFromZipBuffer(zipBuffer) { + const buf = Buffer.isBuffer(zipBuffer) ? zipBuffer : Buffer.from(zipBuffer) + const minEocdSize = 22 + if (buf.length < minEocdSize) { + throw new Error('无效的 ZIP 压缩包(文件过小)') + } + + let eocdOffset = -1 + const minSearch = Math.max(0, buf.length - 65557) + for (let i = buf.length - minEocdSize; i >= minSearch; i--) { + if (buf.readUInt32LE(i) === 0x06054b50) { + eocdOffset = i + break + } + } + if (eocdOffset < 0) { + throw new Error('无效的 ZIP 压缩包(缺少 EOCD 头)') + } + + const totalEntries = buf.readUInt16LE(eocdOffset + 10) + const cdOffset = buf.readUInt32LE(eocdOffset + 16) + if (cdOffset >= buf.length) { + throw new Error('ZIP 中央目录偏移越界') + } + + const candidates = [] + let ptr = cdOffset + for (let idx = 0; idx < totalEntries && ptr + 46 <= buf.length; idx++) { + if (buf.readUInt32LE(ptr) !== 0x02014b50) break + const compressionMethod = buf.readUInt16LE(ptr + 10) + const compressedSize = buf.readUInt32LE(ptr + 20) + const uncompressedSize = buf.readUInt32LE(ptr + 24) + const fileNameLen = buf.readUInt16LE(ptr + 28) + const extraLen = buf.readUInt16LE(ptr + 30) + const commentLen = buf.readUInt16LE(ptr + 32) + const localHeaderOffset = buf.readUInt32LE(ptr + 42) + const name = buf.subarray(ptr + 46, ptr + 46 + fileNameLen).toString('utf8') + ptr += 46 + fileNameLen + extraLen + commentLen + + if (!name || name.endsWith('/')) continue + candidates.push({ + name, + compressionMethod, + compressedSize, + uncompressedSize, + localHeaderOffset + }) + } + + const target = + candidates.find((c) => /mihomo.*\.exe$/i.test(path.basename(c.name))) || + candidates.find((c) => /\.exe$/i.test(c.name)) || + candidates.sort((a, b) => b.uncompressedSize - a.uncompressedSize)[0] + + if (!target) { + throw new Error('ZIP 压缩包中未找到可执行文件') + } + + const lh = target.localHeaderOffset + if (lh + 30 > buf.length || buf.readUInt32LE(lh) !== 0x04034b50) { + throw new Error('ZIP 本地文件头损坏') + } + const lhNameLen = buf.readUInt16LE(lh + 26) + const lhExtraLen = buf.readUInt16LE(lh + 28) + const dataStart = lh + 30 + lhNameLen + lhExtraLen + const dataEnd = dataStart + target.compressedSize + if (dataEnd > buf.length) { + throw new Error('ZIP 条目数据越界') + } + + const compressedData = buf.subarray(dataStart, dataEnd) + if (target.compressionMethod === 0) { + return { name: path.basename(target.name), data: Buffer.from(compressedData) } + } + if (target.compressionMethod === 8) { + return { name: path.basename(target.name), data: zlib.inflateRawSync(compressedData) } + } + throw new Error(`不支持的 ZIP 压缩算法: ${target.compressionMethod}`) +} + +function findLocalBinary(options = {}) { + const binDir = options.binDir || DEFAULT_BIN_DIR + const platform = options.platform || process.platform + const names = platform === 'win32' ? ['mihomo.exe', 'clash-meta.exe'] : ['mihomo', 'clash-meta'] + + for (const name of names) { + const cachedPath = path.join(binDir, name) + if (fs.existsSync(cachedPath)) { + return cachedPath + } + } + + const pathEnv = String(process.env.PATH || '') + for (const dir of pathEnv.split(path.delimiter).filter(Boolean)) { + for (const name of names) { + const candidate = path.join(dir, name) + try { + if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { + return candidate + } + } catch { + // ignore permission/stat error + } + } + } + return null +} + +async function resolveLatestReleaseTag(proxyUrl = '') { + const attempts = proxyUrl ? [proxyUrl, ''] : [''] + for (const p of attempts) { + try { + const res = await httpClient.request('https://api.github.com/repos/MetaCubeX/mihomo/releases/latest', { + timeoutMs: 6000, + proxyUrl: p, + headers: { + 'User-Agent': 'vps-manager-ztools/0.1', + Accept: 'application/vnd.github+json' + } + }) + if (res.ok) { + const json = JSON.parse(res.text) + if (json && json.tag_name) return String(json.tag_name) + } + } catch { + // try next + } + } + return DEFAULT_MIHOMO_VERSION +} + +function allocateFreeLoopbackPort() { + return new Promise((resolve, reject) => { + const srv = net.createServer() + srv.once('error', reject) + srv.listen(0, '127.0.0.1', () => { + const port = srv.address().port + srv.close((err) => (err ? reject(err) : resolve(port))) + }) + }) +} + +function waitForPortListening(host, port, timeoutMs = 6000) { + const started = Date.now() + return new Promise((resolve, reject) => { + const attempt = () => { + const sock = net.createConnection({ host, port }) + sock.once('connect', () => { + sock.destroy() + resolve(true) + }) + sock.once('error', () => { + sock.destroy() + if (Date.now() - started >= timeoutMs) { + reject(new Error(`原生内核启动超时 (${host}:${port})`)) + return + } + setTimeout(attempt, 120) + }) + } + attempt() + }) +} + +function dialViaHttpConnect(proxyPort, dstHost, dstPort, timeoutMs = 10000) { + return new Promise((resolve, reject) => { + const sock = net.createConnection({ host: '127.0.0.1', port: proxyPort }) + let settled = false + let buf = Buffer.alloc(0) + + const timer = setTimeout(() => { + if (settled) return + settled = true + sock.destroy() + reject(new Error(`原生内核通道连接超时 (${dstHost}:${dstPort})`)) + }, timeoutMs) + + const fail = (err) => { + if (settled) return + settled = true + clearTimeout(timer) + sock.destroy() + reject(err) + } + + sock.once('error', fail) + sock.once('connect', () => { + const authority = String(dstHost).includes(':') && !String(dstHost).startsWith('[') + ? `[${dstHost}]:${dstPort}` + : `${dstHost}:${dstPort}` + sock.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\nConnection: close\r\n\r\n`) + }) + + const onData = (chunk) => { + buf = Buffer.concat([buf, chunk]) + const idx = buf.indexOf(Buffer.from('\r\n\r\n')) + if (idx < 0) { + if (buf.length > 8192) fail(new Error('原生内核响应头异常')) + return + } + const headLine = buf.subarray(0, idx).toString('utf8').split('\r\n')[0] || '' + const rest = buf.subarray(idx + 4) + sock.removeListener('data', onData) + if (!/^HTTP\/\d\.\d\s+200\b/i.test(headLine)) { + fail(new Error(`原生内核 CONNECT 失败: ${headLine}`)) + return + } + settled = true + clearTimeout(timer) + if (rest.length > 0) { + sock.unshift(rest) + } + resolve(sock) + } + + sock.on('data', onData) + }) +} + +function createNativeCoreManager(options = {}) { + const binDir = options.binDir || DEFAULT_BIN_DIR + const runtimeDir = options.runtimeDir || DEFAULT_RUNTIME_DIR + const platform = options.platform || process.platform + const arch = options.arch || process.arch + const downloadFn = options.downloadBuffer || ((url, opts) => httpClient.requestBuffer(url, opts)) + + let state = 'idle' + let proc = null + let listenPort = 0 + let binaryPath = findLocalBinary({ binDir, platform }) + let lastError = '' + let activeNodeName = '' + let activeProtocol = '' + let ensurePromise = null + + function getStatus() { + return { + state, + running: Boolean(proc && listenPort > 0 && state === 'running'), + port: state === 'running' ? listenPort : 0, + binaryPath: binaryPath || '', + binaryCached: Boolean(binaryPath && fs.existsSync(binaryPath)), + activeNodeName, + activeProtocol, + lastError + } + } + + async function ensureBinary(opts = {}) { + const existing = findLocalBinary({ binDir, platform }) + if (existing) { + binaryPath = existing + return existing + } + if (ensurePromise) return ensurePromise + + ensurePromise = (async () => { + state = 'downloading' + lastError = '' + try { + const tag = await resolveLatestReleaseTag(opts.proxyUrl || '') + const asset = resolveMihomoAsset(platform, arch, tag) + const proxyAttempts = opts.proxyUrl ? [opts.proxyUrl, ''] : [''] + let res = null + let lastDlErr = null + for (const p of proxyAttempts) { + try { + res = await downloadFn(asset.url, { + proxyUrl: p, + timeoutMs: 45000, + maxBytes: 60 * 1024 * 1024, + maxRedirects: 6 + }) + if (res && res.ok && res.buffer && res.buffer.length > 1024) { + break + } + } catch (err) { + lastDlErr = err + } + } + if (!res || !res.ok || !res.buffer) { + throw lastDlErr || new Error(`下载原生内核失败 (${asset.filename})`) + } + + const extractedBuf = + asset.archiveType === 'zip' + ? extractFirstExeFromZipBuffer(res.buffer).data + : extractGzipBuffer(res.buffer) + + fs.mkdirSync(binDir, { recursive: true }) + const destPath = path.join(binDir, asset.binaryName) + const tmpPath = `${destPath}.tmp-${process.pid}` + fs.writeFileSync(tmpPath, extractedBuf) + if (platform !== 'win32') { + fs.chmodSync(tmpPath, 0o755) + } + fs.renameSync(tmpPath, destPath) + binaryPath = destPath + return destPath + } catch (err) { + state = 'error' + lastError = err instanceof Error ? err.message : String(err) + throw err + } finally { + ensurePromise = null + } + })() + + return ensurePromise + } + + function stopSync() { + if (proc) { + try { + proc.kill('SIGTERM') + } catch {} + proc = null + } + listenPort = 0 + activeNodeName = '' + activeProtocol = '' + if (state !== 'error') state = 'idle' + return getStatus() + } + + async function stop() { + return stopSync() + } + + async function start({ proxyObj, proxyUrlForDownload = '' } = {}) { + if (!proxyObj || !proxyObj.name || !proxyObj.type) { + throw new Error('缺少原生代理节点配置 (proxyObj)') + } + stopSync() + lastError = '' + + const bin = await ensureBinary({ proxyUrl: proxyUrlForDownload }) + const port = await allocateFreeLoopbackPort() + fs.mkdirSync(runtimeDir, { recursive: true }) + const cfgPath = path.join(runtimeDir, 'native-core.yaml') + + const runtimeDoc = { + 'mixed-port': port, + 'bind-address': '127.0.0.1', + 'allow-lan': false, + mode: 'global', + 'log-level': 'silent', + proxies: [proxyObj], + 'proxy-groups': [ + { + name: 'GLOBAL', + type: 'select', + proxies: [proxyObj.name] + } + ], + rules: [`MATCH,${proxyObj.name}`] + } + + fs.writeFileSync(cfgPath, yaml.dump(runtimeDoc, { lineWidth: -1 }), { encoding: 'utf8', mode: 0o600 }) + + const child = spawn(bin, ['-f', cfgPath, '-d', runtimeDir], { + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'] + }) + + let stderrBuf = '' + child.stderr?.on('data', (chunk) => { + if (stderrBuf.length < 4096) stderrBuf += String(chunk) + }) + + child.once('exit', (code) => { + if (proc === child) { + proc = null + listenPort = 0 + if (state === 'running') { + state = 'error' + lastError = `原生内核意外退出 (${code ?? 0})${stderrBuf ? `: ${stderrBuf.trim()}` : ''}` + } + } + }) + + proc = child + try { + await waitForPortListening('127.0.0.1', port, 6500) + listenPort = port + activeNodeName = String(proxyObj.name || '') + activeProtocol = String(proxyObj.type || '') + state = 'running' + return getStatus() + } catch (err) { + stopSync() + state = 'error' + lastError = err instanceof Error ? err.message : String(err) + throw err + } + } + + return { + resolveMihomoAsset, + findLocalBinary: () => findLocalBinary({ binDir, platform }), + ensureBinary, + start, + stop, + stopSync, + getStatus, + dialViaHttpConnect: (dstHost, dstPort, timeoutMs) => { + if (!proc || listenPort <= 0 || state !== 'running') { + return Promise.reject(new Error('原生内核未运行')) + } + return dialViaHttpConnect(listenPort, dstHost, dstPort, timeoutMs) + } + } +} + +module.exports = { + DEFAULT_MIHOMO_VERSION, + DEFAULT_BIN_DIR, + resolveMihomoAsset, + extractGzipBuffer, + extractFirstExeFromZipBuffer, + findLocalBinary, + dialViaHttpConnect, + createNativeCoreManager +} diff --git a/plugins/vps-manager/preload/package-lock.json b/plugins/vps-manager/preload/package-lock.json new file mode 100644 index 000000000..3b6fff227 --- /dev/null +++ b/plugins/vps-manager/preload/package-lock.json @@ -0,0 +1,121 @@ +{ + "name": "vps-manager-preload", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "vps-manager-preload", + "version": "0.1.0", + "dependencies": { + "js-yaml": "^4.1.0", + "ssh2": "^1.16.0" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "license": "BSD-3-Clause", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "node_modules/buildcheck": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz", + "integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==", + "optional": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/cpu-features": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz", + "integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==", + "hasInstallScript": true, + "optional": true, + "dependencies": { + "buildcheck": "~0.0.6", + "nan": "^2.19.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/nan": { + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz", + "integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==", + "license": "MIT", + "optional": true + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/ssh2": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz", + "integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==", + "hasInstallScript": true, + "dependencies": { + "asn1": "^0.2.6", + "bcrypt-pbkdf": "^1.0.2" + }, + "engines": { + "node": ">=10.16.0" + }, + "optionalDependencies": { + "cpu-features": "~0.0.10", + "nan": "^2.23.0" + } + }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", + "license": "Unlicense" + } + } +} diff --git a/plugins/vps-manager/preload/package.json b/plugins/vps-manager/preload/package.json new file mode 100644 index 000000000..dc39e3355 --- /dev/null +++ b/plugins/vps-manager/preload/package.json @@ -0,0 +1,10 @@ +{ + "name": "vps-manager-preload", + "version": "0.1.0", + "private": true, + "type": "commonjs", + "dependencies": { + "js-yaml": "^4.1.0", + "ssh2": "^1.16.0" + } +} diff --git a/plugins/vps-manager/preload/services.cjs b/plugins/vps-manager/preload/services.cjs new file mode 100644 index 000000000..57135c86c --- /dev/null +++ b/plugins/vps-manager/preload/services.cjs @@ -0,0 +1,106 @@ +const sshClient = require('./ssh-client.cjs') +const deployTemplates = require('./deploy-templates.cjs') +const clashApi = require('./clash-api.cjs') +const configStore = require('./config-store.cjs') +const systemProxy = require('./system-proxy.cjs') +const ipCheck = require('./ip-check.cjs') +const embeddedProxy = require('./embedded-proxy.cjs') +const mcpTools = require('./mcp-tools.cjs') + +window.addEventListener('beforeunload', () => { + embeddedProxy.defaultController.stopSync() + sshClient.closeAllTunnels() + sshClient.closeAllSessions() +}) + +window.vpsManager = { + ssh: { + testConnection: (profile) => sshClient.testSshConnection(profile), + execCommand: (profile, command, options) => sshClient.execCommand(profile, command, options), + collectMetrics: (profile, options) => sshClient.collectSystemMetrics(profile, options), + discoverRemoteProxy: (profile, options) => sshClient.discoverRemoteProxy(profile, options), + closeSession: (profile) => sshClient.closeSession(profile), + manageService: (profile, serviceName, action) => sshClient.manageService(profile, serviceName, action), + readRemoteFile: (profile, remotePath) => sshClient.readRemoteFile(profile, remotePath), + writeRemoteFile: (profile, remotePath, content, options) => sshClient.writeRemoteFile(profile, remotePath, content, options), + openTunnel: (profile, options) => sshClient.openTunnel(profile, options), + closeTunnel: (tunnelId) => sshClient.closeTunnel(tunnelId), + listTunnels: () => sshClient.listTunnels(), + discoverLocalKeys: () => sshClient.discoverLocalSshKeys(), + discoverSshConfigHosts: () => sshClient.discoverSshConfigHosts() + }, + deploy: { + generateSecrets: (protocol, options) => deployTemplates.generateSecrets(protocol, options), + buildBundle: (params) => deployTemplates.buildDeploymentBundle(params), + executeDeploy: async (profile, params) => { + const bundle = deployTemplates.buildDeploymentBundle(params) + const encodedScript = Buffer.from(bundle.installScript, 'utf8').toString('base64') + const cmd = `echo ${sshClient.shellQuote(encodedScript)} | base64 -d | (if [ "$(id -u)" -eq 0 ]; then bash; else sudo bash; fi)` + const execRes = await sshClient.execCommand(profile, cmd, { timeoutMs: 180000 }) + return { + ...bundle, + execRes + } + } + }, + clash: { + probeLocal: () => clashApi.probeLocalControllers(), + getOverview: (endpoint) => clashApi.getOverview(endpoint), + patchConfigs: (endpoint, patch) => clashApi.patchConfigs(endpoint, patch), + reloadConfig: (endpoint, configPath) => clashApi.reloadConfig(endpoint, configPath), + selectProxy: (endpoint, groupName, proxyName) => clashApi.selectProxy(endpoint, groupName, proxyName), + testProxyDelay: (endpoint, proxyName, testUrl, timeout) => + clashApi.testProxyDelay(endpoint, proxyName, testUrl, timeout), + testGroupDelay: (endpoint, proxyNames, testUrl, timeout) => + clashApi.testGroupDelay(endpoint, proxyNames, testUrl, timeout), + getRules: (endpoint) => clashApi.getRules(endpoint), + getConnections: (endpoint) => clashApi.getConnections(endpoint), + closeConnection: (endpoint, id) => clashApi.closeConnection(endpoint, id), + closeAllConnections: (endpoint) => clashApi.closeAllConnections(endpoint) + }, + config: { + getRulePresets: () => configStore.RULE_PRESETS, + parseYaml: (yamlText) => configStore.parseClashYaml(yamlText), + updateRulesInYaml: (yamlText, ruleItems) => configStore.updateRulesInYaml(yamlText, ruleItems), + parseShareUri: (uri) => configStore.parseShareUri(uri), + addProxyToYaml: (yamlText, proxyObj) => configStore.addProxyToYaml(yamlText, proxyObj), + fetchSubscription: (url) => configStore.fetchSubscription(url), + readLocalFile: (filePath) => configStore.readLocalFile(filePath), + writeLocalFile: (filePath, content) => configStore.writeLocalFile(filePath, content), + discoverLocalConfigs: () => configStore.discoverLocalConfigs() + }, + proxy: { + getSystemProxy: () => systemProxy.getSystemProxy(), + setSystemProxy: (options) => systemProxy.setSystemProxy(options), + getProxyEnvSnippet: (host, port) => systemProxy.buildProxyEnvSnippet(host, port) + }, + ipCheck: { + runCheck: (options) => ipCheck.runFullIpCheck(options), + lookupIp: (ip) => ipCheck.lookupGeoIp(ip) + }, + embeddedProxy: { + start: (options) => embeddedProxy.defaultController.start(options), + stop: () => embeddedProxy.defaultController.stop(), + getStatus: () => embeddedProxy.defaultController.getStatus(), + setMode: (mode) => embeddedProxy.defaultController.setMode(mode), + setTransportPolicy: (policy) => embeddedProxy.defaultController.setTransportPolicy(policy), + setNativeNode: (proxyObj) => embeddedProxy.defaultController.setNativeNode(proxyObj), + triggerSmartSwitch: () => embeddedProxy.defaultController.triggerSmartSwitch(), + updateRules: (yamlText, options) => embeddedProxy.defaultController.updateRules(yamlText, options), + getConnections: () => embeddedProxy.defaultController.getConnections(), + closeConnection: (id) => embeddedProxy.defaultController.closeConnection(id), + closeAllConnections: () => embeddedProxy.defaultController.closeAllConnections() + } +} + +const mcpService = mcpTools.registerTools(window, window.vpsManager) || mcpTools.createMcpService({ bridge: window.vpsManager }) +window.vpsManager.mcp = { + getStatus: () => mcpService.getStatus(), + listTools: () => mcpService.listTools(), + listSkills: () => mcpService.listSkills(), + loadSkill: (skillId) => mcpService.loadSkill(skillId), + syncContext: (ctx) => mcpService.syncContext(ctx), + invokeTool: (name, params) => mcpService.invokeTool(name, params) +} + +console.log('[vps-manager] preload ready') diff --git a/plugins/vps-manager/preload/ssh-client.cjs b/plugins/vps-manager/preload/ssh-client.cjs new file mode 100644 index 000000000..55e0514f6 --- /dev/null +++ b/plugins/vps-manager/preload/ssh-client.cjs @@ -0,0 +1,1611 @@ +const fs = require('node:fs') +const net = require('node:net') +const os = require('node:os') +const path = require('node:path') +const crypto = require('node:crypto') +const { Client, utils: sshUtils } = require('ssh2') +const configStore = require('./config-store.cjs') + +const ALLOWED_SERVICE_RE = /^[a-zA-Z0-9._@-]{1,64}$/ +const MAX_OUTPUT_BYTES = 2 * 1024 * 1024 +const MAX_KEY_FILE_BYTES = 64 * 1024 +const SESSION_IDLE_MS = 120 * 1000 +const PREFERRED_KEY_ORDER = ['id_ed25519', 'id_ecdsa', 'id_rsa', 'id_dsa'] +const IGNORED_SSH_FILES = new Set(['config', 'known_hosts', 'known_hosts.old', 'authorized_keys', 'environment', 'rc']) +const activeTunnels = new Map() +const pooledSessions = new Map() +const metricsCache = new Map() + +function shellQuote(value) { + return `'${String(value ?? '').replace(/'/g, `'\\''`)}'` +} + +function expandHomePath(rawPath) { + const input = String(rawPath || '').trim() + if (!input) return '' + if (input === '~') return os.homedir() + if (input.startsWith('~/') || input.startsWith('~\\')) { + return path.join(os.homedir(), input.slice(2)) + } + return input +} + +function validateServiceName(name) { + const clean = String(name || '').trim() + if (!ALLOWED_SERVICE_RE.test(clean)) { + throw new Error(`非法的服务名: ${clean}`) + } + return clean +} + +function normalizePort(port, fallback = 22) { + const n = Number(port ?? fallback) + if (!Number.isInteger(n) || n < 1 || n > 65535) { + throw new Error(`无效端口号: ${port}`) + } + return n +} + +function isEncryptedKeyText(rawText) { + const text = String(rawText || '') + if (/-----BEGIN ENCRYPTED PRIVATE KEY-----/.test(text) || /Proc-Type:\s*4,ENCRYPTED/i.test(text)) { + return true + } + const parsed = sshUtils.parseKey(text) + if (parsed instanceof Error && /passphrase|encrypted/i.test(parsed.message)) { + return true + } + return false +} + +function tryConvertPkcs8Pem(pemText, passphrase) { + try { + const keyObj = crypto.createPrivateKey({ + key: pemText, + format: 'pem', + ...(passphrase ? { passphrase } : {}) + }) + if (keyObj.asymmetricKeyType === 'rsa') { + return keyObj.export({ type: 'pkcs1', format: 'pem' }) + } + if (keyObj.asymmetricKeyType === 'ec') { + return keyObj.export({ type: 'sec1', format: 'pem' }) + } + return null + } catch (err) { + const msg = err && err.message ? err.message : '' + if (/passphrase|decrypt|bad password|wrong tag|EVP_DecryptFinal|bad decrypt/i.test(msg)) { + throw new Error('该私钥已加密,请输入正确的私钥口令 (Passphrase)') + } + return null + } +} + +function normalizeAndValidatePrivateKey(rawKey, passphrase = '', sourceLabel = '私钥') { + let normalized = String(rawKey || '') + .replace(/^\uFEFF/, '') + .replace(/\r\n/g, '\n') + .replace(/\r/g, '\n') + .trim() + + if (!normalized) { + throw new Error(`${sourceLabel}内容为空`) + } + + if (!normalized.includes('\n') && normalized.includes('\\n')) { + normalized = normalized.replace(/\\n/g, '\n').trim() + } + + if (/^PuTTY-User-Key-File/i.test(normalized)) { + throw new Error('暂不支持 PuTTY (.ppk) 格式,请先转换为 OpenSSH/PEM 私钥') + } + + if ( + /^(ssh-rsa|ssh-dss|ssh-ed25519|ecdsa-sha2-|sk-ssh-)/i.test(normalized) || + /-----BEGIN (?:PUBLIC KEY|SSH2 PUBLIC KEY)-----/.test(normalized) + ) { + throw new Error('检测到公钥内容,请使用对应的私钥文件(不含 .pub 后缀,以 -----BEGIN ... PRIVATE KEY----- 开头)') + } + + let finalPem = normalized + let clearPassphrase = false + const cleanPass = passphrase ? String(passphrase) : undefined + + let parsed = sshUtils.parseKey(finalPem, cleanPass) + if ( + parsed instanceof Error && + /-----BEGIN (?:ENCRYPTED )?PRIVATE KEY-----/.test(finalPem) && + /Unsupported key format/i.test(parsed.message) + ) { + const converted = tryConvertPkcs8Pem(finalPem, cleanPass) + if (converted) { + finalPem = converted + clearPassphrase = true + parsed = sshUtils.parseKey(finalPem) + } + } + + if (parsed instanceof Error) { + if (/passphrase|encrypted|decrypt/i.test(parsed.message)) { + throw new Error('该私钥已加密,请输入正确的私钥口令 (Passphrase)') + } + throw new Error(`私钥格式无效 (${sourceLabel}): ${parsed.message}`) + } + + const keyObj = Array.isArray(parsed) ? parsed[0] : parsed + if (!keyObj || typeof keyObj.getPrivatePEM !== 'function' || keyObj.getPrivatePEM() === null) { + throw new Error('私钥内容无效:检测到仅包含公钥,请选择不含 .pub 后缀的私钥文件') + } + + return { + privateKey: finalPem, + clearPassphrase, + keyType: keyObj.type || 'private-key' + } +} + +function formatKeyTypeLabel(rawType, text) { + if (/ed25519/i.test(rawType || '') || /ed25519/i.test(text || '')) return 'ED25519' + if (/ecdsa|ec/i.test(rawType || '') || /EC PRIVATE KEY/.test(text || '')) return 'ECDSA' + if (/rsa/i.test(rawType || '') || /RSA PRIVATE KEY/.test(text || '')) return 'RSA' + if (/dsa/i.test(rawType || '')) return 'DSA' + return 'SSH' +} + +function discoverLocalSshKeys(sshDirOverride) { + const sshDir = sshDirOverride ? expandHomePath(sshDirOverride) : path.join(os.homedir(), '.ssh') + if (!sshDir || !fs.existsSync(sshDir)) return [] + + let entries = [] + try { + entries = fs.readdirSync(sshDir, { withFileTypes: true }) + } catch { + return [] + } + + const found = [] + for (const entry of entries) { + if (!entry.isFile()) continue + const name = entry.name + if ( + name.startsWith('.') || + name.endsWith('.pub') || + name.endsWith('.sock') || + name.endsWith('.log') || + IGNORED_SSH_FILES.has(name) || + name.startsWith('known_hosts') || + name.startsWith('authorized_keys') || + name.startsWith('config.') + ) { + continue + } + + const fullPath = path.join(sshDir, name) + let stat + try { + stat = fs.statSync(fullPath) + } catch { + continue + } + if (!stat.isFile() || stat.size === 0 || stat.size > MAX_KEY_FILE_BYTES) continue + + let content = '' + try { + content = fs.readFileSync(fullPath, 'utf8') + } catch { + continue + } + + if (!/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/.test(content)) continue + + const encrypted = isEncryptedKeyText(content) + let keyType = '' + if (!encrypted) { + const parsed = sshUtils.parseKey(content) + if (parsed instanceof Error) { + if (/-----BEGIN PRIVATE KEY-----/.test(content)) { + const converted = tryConvertPkcs8Pem(content, undefined) + if (!converted) continue + const reparsed = sshUtils.parseKey(converted) + const obj = Array.isArray(reparsed) ? reparsed[0] : reparsed + if (!obj || obj.getPrivatePEM() === null) continue + keyType = obj.type || '' + } else { + continue + } + } else { + const obj = Array.isArray(parsed) ? parsed[0] : parsed + if (!obj || obj.getPrivatePEM() === null) continue + keyType = obj.type || '' + } + } + + const defaultSshDir = path.join(os.homedir(), '.ssh') + const displayPath = sshDir === defaultSshDir ? `~/.ssh/${name}` : fullPath + + found.push({ + path: fullPath, + displayPath, + name, + keyType: formatKeyTypeLabel(keyType, content), + encrypted + }) + } + + found.sort((a, b) => { + const idxA = PREFERRED_KEY_ORDER.indexOf(a.name) + const idxB = PREFERRED_KEY_ORDER.indexOf(b.name) + if (idxA !== -1 && idxB !== -1) return idxA - idxB + if (idxA !== -1) return -1 + if (idxB !== -1) return 1 + return a.name.localeCompare(b.name) + }) + + return found +} + +function parseSshConfigText(configText) { + const hosts = [] + let current = null + + const flush = () => { + if (!current || !current.aliases.length) return + for (const alias of current.aliases) { + if (!alias || /[*?!]/.test(alias)) continue + hosts.push({ + alias, + host: current.hostName || alias, + port: current.port || 22, + username: current.user || 'root', + ...(current.identityFile ? { identityFile: current.identityFile } : {}) + }) + } + } + + for (const rawLine of String(configText || '').split(/\r?\n/)) { + const trimmed = rawLine.trim() + if (!trimmed || trimmed.startsWith('#')) continue + const match = /^([A-Za-z][A-Za-z0-9]*)\s*(?:=|\s+)\s*(.+)$/.exec(trimmed) + if (!match) continue + + const keyword = match[1].toLowerCase() + const rawValue = match[2].replace(/\s+#.*$/, '').trim() + + if (keyword === 'host') { + flush() + current = { + aliases: rawValue.split(/\s+/).filter(Boolean), + hostName: '', + port: 22, + user: '', + identityFile: '' + } + continue + } + + if (!current) continue + if (keyword === 'hostname') { + current.hostName = rawValue + } else if (keyword === 'user') { + current.user = rawValue + } else if (keyword === 'port') { + const p = Number(rawValue) + if (Number.isInteger(p) && p >= 1 && p <= 65535) current.port = p + } else if (keyword === 'identityfile' && !current.identityFile) { + current.identityFile = rawValue.replace(/^["']|["']$/g, '') + } + } + + flush() + return hosts +} + +function discoverSshConfigHosts(sshDirOverride) { + const sshDir = sshDirOverride ? expandHomePath(sshDirOverride) : path.join(os.homedir(), '.ssh') + const configPath = path.join(sshDir, 'config') + if (!fs.existsSync(configPath)) return [] + try { + const text = fs.readFileSync(configPath, 'utf8') + return parseSshConfigText(text) + } catch { + return [] + } +} + +function buildConnectConfig(profile) { + if (!profile || typeof profile !== 'object') { + throw new Error('缺少 VPS 连接配置') + } + const host = String(profile.host || '').trim() + const username = String(profile.username || 'root').trim() + if (!host) throw new Error('VPS 地址 (host) 不能为空') + if (!username) throw new Error('SSH 用户名不能为空') + + const config = { + host, + port: normalizePort(profile.port, 22), + username, + readyTimeout: Number(profile.timeoutMs) || 15000, + keepaliveInterval: 10000 + } + + const authType = profile.authType || (profile.privateKey || profile.privateKeyPath ? 'key' : 'password') + if (authType === 'key') { + let rawKeyContent = '' + let sourceLabel = '私钥内容' + + const pasted = String(profile.privateKey || '').trim() + const pathInput = String(profile.privateKeyPath || '').trim() + + if (pasted) { + // Handle accidental paste of a file path into the key content textarea + if (!pasted.includes('\n') && !pasted.includes('-----BEGIN')) { + const maybePath = expandHomePath(pasted) + if (fs.existsSync(maybePath) && fs.statSync(maybePath).isFile()) { + rawKeyContent = fs.readFileSync(maybePath, 'utf8') + sourceLabel = maybePath + } else { + rawKeyContent = pasted + } + } else { + rawKeyContent = pasted + } + } else if (pathInput) { + let keyPath = expandHomePath(pathInput) + if (keyPath.endsWith('.pub')) { + const paired = keyPath.slice(0, -4) + if (fs.existsSync(paired)) { + keyPath = paired + } else { + throw new Error(`选择了公钥文件 (${keyPath}),请改为不含 .pub 后缀的私钥文件`) + } + } + if (!fs.existsSync(keyPath)) { + throw new Error(`私钥文件不存在: ${keyPath}`) + } + rawKeyContent = fs.readFileSync(keyPath, 'utf8') + sourceLabel = keyPath + } else { + const discovered = discoverLocalSshKeys() + if (discovered.length === 0) { + throw new Error('未在本地 ~/.ssh 目录检测到可用私钥,请手动选择私钥文件或粘贴私钥内容') + } + rawKeyContent = fs.readFileSync(discovered[0].path, 'utf8') + sourceLabel = discovered[0].displayPath + } + + const validated = normalizeAndValidatePrivateKey(rawKeyContent, profile.passphrase, sourceLabel) + config.privateKey = validated.privateKey + if (profile.passphrase && !validated.clearPassphrase) { + config.passphrase = String(profile.passphrase) + } + } else { + if (!profile.password && profile.password !== '') { + throw new Error('请输入 SSH 登录密码') + } + config.password = String(profile.password) + } + + return config +} + +function getProfileSessionKey(config) { + return crypto + .createHash('sha256') + .update( + JSON.stringify([ + config.host, + config.port, + config.username, + config.privateKey || '', + config.password || '', + config.passphrase || '' + ]) + ) + .digest('hex') + .slice(0, 24) +} + +function destroyPooledSession(sessionKey) { + const entry = pooledSessions.get(sessionKey) + if (!entry) return + if (entry.idleTimer) { + clearTimeout(entry.idleTimer) + entry.idleTimer = null + } + pooledSessions.delete(sessionKey) + try { + entry.conn?.end?.() + } catch { + // ignore + } +} + +function touchPooledSession(sessionKey, entry) { + if (entry.idleTimer) clearTimeout(entry.idleTimer) + entry.idleTimer = setTimeout(() => { + if (pooledSessions.get(sessionKey) === entry) { + destroyPooledSession(sessionKey) + } + }, SESSION_IDLE_MS) + if (typeof entry.idleTimer.unref === 'function') { + entry.idleTimer.unref() + } +} + +async function getPooledConnection(profile) { + const config = buildConnectConfig(profile) + const sessionKey = getProfileSessionKey(config) + const existing = pooledSessions.get(sessionKey) + + if (existing) { + if (existing.ready && existing.conn) { + touchPooledSession(sessionKey, existing) + return { conn: existing.conn, sessionKey, config } + } + if (existing.connectingPromise) { + const conn = await existing.connectingPromise + touchPooledSession(sessionKey, existing) + return { conn, sessionKey, config } + } + } + + const entry = { + conn: null, + ready: false, + idleTimer: null, + connectingPromise: null + } + pooledSessions.set(sessionKey, entry) + + entry.connectingPromise = new Promise((resolve, reject) => { + const conn = new Client() + let settled = false + + conn.on('ready', () => { + if (settled) return + settled = true + entry.conn = conn + entry.ready = true + entry.connectingPromise = null + touchPooledSession(sessionKey, entry) + resolve(conn) + }) + + conn.on('error', (err) => { + if (!settled) { + settled = true + pooledSessions.delete(sessionKey) + reject(new Error(`SSH 连接失败 (${config.host}:${config.port}): ${err.message}`)) + } else if (pooledSessions.get(sessionKey) === entry) { + destroyPooledSession(sessionKey) + } + }) + + conn.on('close', () => { + if (pooledSessions.get(sessionKey) === entry) { + destroyPooledSession(sessionKey) + } + if (!settled) { + settled = true + reject(new Error(`SSH 连接被关闭 (${config.host}:${config.port})`)) + } + }) + + conn.connect(config) + }) + + const conn = await entry.connectingPromise + return { conn, sessionKey, config } +} + +function closeSession(profile) { + if (!profile || !profile.host) return false + try { + const config = buildConnectConfig(profile) + const sessionKey = getProfileSessionKey(config) + const existed = pooledSessions.has(sessionKey) + destroyPooledSession(sessionKey) + metricsCache.delete(sessionKey) + return existed + } catch { + return false + } +} + +function closeAllSessions() { + for (const key of Array.from(pooledSessions.keys())) { + destroyPooledSession(key) + } + metricsCache.clear() +} + +function withSshConnection(profile, taskFn) { + const config = buildConnectConfig(profile) + return new Promise((resolve, reject) => { + const conn = new Client() + let settled = false + + const finish = (err, res) => { + if (settled) return + settled = true + try { + conn.end() + } catch { + // ignore cleanup error + } + if (err) reject(err) + else resolve(res) + } + + conn.on('ready', async () => { + try { + const result = await taskFn(conn) + finish(null, result) + } catch (err) { + finish(err) + } + }) + + conn.on('error', (err) => { + finish(new Error(`SSH 连接失败 (${config.host}:${config.port}): ${err.message}`)) + }) + + conn.connect(config) + }) +} + +function runExecOnConn(conn, command, timeoutMs = 30000) { + return new Promise((resolve, reject) => { + let stdout = '' + let stderr = '' + let stdoutBytes = 0 + let stderrBytes = 0 + let stdoutTruncated = false + let stderrTruncated = false + let finished = false + let activeStream = null + + const timer = setTimeout(() => { + if (!finished) { + finished = true + try { + activeStream?.close?.() + } catch {} + try { + activeStream?.destroy?.() + } catch {} + reject(new Error(`远端命令执行超时 (${Math.round(timeoutMs / 1000)}s)`)) + } + }, timeoutMs) + + conn.exec(command, (err, stream) => { + if (err) { + clearTimeout(timer) + if (!finished) { + finished = true + reject(err) + } + return + } + if (finished) { + try { + stream.close() + } catch {} + return + } + activeStream = stream + + stream.on('close', (code) => { + clearTimeout(timer) + if (!finished) { + finished = true + resolve({ + code: typeof code === 'number' ? code : 0, + stdout, + stderr + }) + } + }) + + stream.on('data', (chunk) => { + if (finished || stdoutTruncated) return + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8') + if (stdoutBytes + buf.length > MAX_OUTPUT_BYTES) { + const remain = Math.max(0, MAX_OUTPUT_BYTES - stdoutBytes) + if (remain > 0) stdout += buf.subarray(0, remain).toString('utf8') + stdout += '\n[输出已截断,超过 2MB 上限]' + stdoutTruncated = true + return + } + stdoutBytes += buf.length + stdout += buf.toString('utf8') + }) + + stream.stderr.on('data', (chunk) => { + if (finished || stderrTruncated) return + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8') + if (stderrBytes + buf.length > MAX_OUTPUT_BYTES) { + const remain = Math.max(0, MAX_OUTPUT_BYTES - stderrBytes) + if (remain > 0) stderr += buf.subarray(0, remain).toString('utf8') + stderr += '\n[错误输出已截断,超过 2MB 上限]' + stderrTruncated = true + return + } + stderrBytes += buf.length + stderr += buf.toString('utf8') + }) + }) + }) +} + +async function withPooledSsh(profile, taskFn) { + const { conn, sessionKey } = await getPooledConnection(profile) + try { + return await taskFn(conn) + } catch (err) { + const msg = err && err.message ? err.message : '' + if (/Channel open failure|Not connected|ECONNRESET|write after end/i.test(msg)) { + destroyPooledSession(sessionKey) + const fresh = await getPooledConnection(profile) + return taskFn(fresh.conn) + } + throw err + } +} + +async function execCommand(profile, command, options = {}) { + const cmd = String(command || '').trim() + if (!cmd) throw new Error('执行命令不能为空') + const timeoutMs = Number(options.timeoutMs) || 30000 + return withPooledSsh(profile, (conn) => runExecOnConn(conn, cmd, timeoutMs)) +} + +async function testSshConnection(profile) { + const startedAt = Date.now() + const res = await execCommand( + profile, + 'uname -srm && (grep -m1 PRETTY_NAME /etc/os-release 2>/dev/null || echo "Linux")', + { timeoutMs: 15000 } + ) + const latencyMs = Date.now() - startedAt + const lines = res.stdout.trim().split('\n') + return { + ok: res.code === 0, + latencyMs, + kernel: lines[0] || '', + os: (lines[1] || '').replace(/^PRETTY_NAME=["']?|["']?$/g, '') + } +} + +function parseCpuTotalsLine(line) { + const nums = String(line || '').trim().split(/\s+/).slice(1).map(Number) + const idle = (nums[3] || 0) + (nums[4] || 0) + const total = nums.reduce((s, v) => s + (v || 0), 0) + return { total, idle } +} + +function parseMetricsOutput(raw, prevSnapshot = null) { + const sections = {} + let currentKey = null + for (const line of String(raw || '').split('\n')) { + const match = /^__SEC_([A-Z0-9_]+)__$/.exec(line.trim()) + if (match) { + currentKey = match[1] + sections[currentKey] = [] + } else if (currentKey) { + sections[currentKey].push(line) + } + } + + const getText = (key) => (sections[key] || []).join('\n').trim() + + // CPU usage from two /proc/stat snapshots or from single snapshot + prevSnapshot + let cpuUsage = prevSnapshot && typeof prevSnapshot.cpuUsage === 'number' ? prevSnapshot.cpuUsage : 0 + let cpuTotals = null + const cpuLines = (sections.CPU_STAT || []).map((l) => l.trim()).filter((l) => l.startsWith('cpu ')) + if (cpuLines.length >= 2) { + const a = parseCpuTotalsLine(cpuLines[0]) + const b = parseCpuTotalsLine(cpuLines[1]) + cpuTotals = b + const diffTotal = b.total - a.total + const diffIdle = b.idle - a.idle + if (diffTotal > 0) { + cpuUsage = Math.max(0, Math.min(100, Number((((diffTotal - diffIdle) / diffTotal) * 100).toFixed(1)))) + } + } else if (cpuLines.length === 1) { + const current = parseCpuTotalsLine(cpuLines[0]) + cpuTotals = current + if (prevSnapshot?.cpuTotals) { + const diffTotal = current.total - prevSnapshot.cpuTotals.total + const diffIdle = current.idle - prevSnapshot.cpuTotals.idle + if (diffTotal > 0) { + cpuUsage = Math.max(0, Math.min(100, Number((((diffTotal - diffIdle) / diffTotal) * 100).toFixed(1)))) + } + } + } + + // Meminfo + const memMap = {} + for (const line of sections.MEM || []) { + const m = /^([A-Za-z0-9_()]+):\s+(\d+)/.exec(line.trim()) + if (m) memMap[m[1]] = Number(m[2]) + } + const memTotalMb = Math.round((memMap.MemTotal || 0) / 1024) + const memAvailMb = Math.round((memMap.MemAvailable ?? memMap.MemFree ?? 0) / 1024) + const memUsedMb = Math.max(0, memTotalMb - memAvailMb) + const swapTotalMb = Math.round((memMap.SwapTotal || 0) / 1024) + const swapFreeMb = Math.round((memMap.SwapFree || 0) / 1024) + + // Disk df -Pm / + let diskTotalMb = 0 + let diskUsedMb = 0 + let diskAvailMb = 0 + let diskPercent = 0 + const dfLines = (sections.DISK || []).map((l) => l.trim()).filter(Boolean) + if (dfLines.length >= 2) { + const parts = dfLines[1].split(/\s+/) + diskTotalMb = Number(parts[1]) || 0 + diskUsedMb = Number(parts[2]) || 0 + diskAvailMb = Number(parts[3]) || 0 + diskPercent = parseInt(parts[4] || '0', 10) || 0 + } + + // Network RX/TX + let rxBytes = 0 + let txBytes = 0 + const interfaces = [] + for (const line of sections.NET || []) { + const m = /^\s*([a-zA-Z0-9._-]+):\s*(.+)$/.exec(line) + if (!m || m[1] === 'lo') continue + const nums = m[2].trim().split(/\s+/).map(Number) + const rx = nums[0] || 0 + const tx = nums[8] || 0 + rxBytes += rx + txBytes += tx + interfaces.push({ name: m[1], rxBytes: rx, txBytes: tx }) + } + + let rxSpeedBps = 0 + let txSpeedBps = 0 + if (prevSnapshot && typeof prevSnapshot.rxBytes === 'number' && typeof prevSnapshot.timestamp === 'number') { + const elapsedSec = Math.max(0.2, (Date.now() - prevSnapshot.timestamp) / 1000) + const rxDiff = rxBytes - prevSnapshot.rxBytes + const txDiff = txBytes - prevSnapshot.txBytes + rxSpeedBps = rxDiff >= 0 ? Math.round(rxDiff / elapsedSec) : 0 + txSpeedBps = txDiff >= 0 ? Math.round(txDiff / elapsedSec) : 0 + } + + // Services (require 3 fields, ignore stray status tokens like "inactive") + const INVALID_SVC_NAMES = new Set(['inactive', 'active', 'failed', 'activating', 'deactivating', 'unknown']) + const servicesMap = new Map() + for (const line of sections.SERVICES || []) { + const parts = line.trim().split('|') + if (parts.length < 3) continue + const name = parts[0].trim() + const rawStatus = (parts[1] || '').trim() + const installedFlag = (parts[2] || '').trim() + if (!name || INVALID_SVC_NAMES.has(name) || servicesMap.has(name)) continue + const isActive = rawStatus === 'active' + servicesMap.set(name, { + name, + active: isActive, + status: rawStatus || 'inactive', + installed: isActive || installedFlag === '1' + }) + } + const services = Array.from(servicesMap.values()).sort((a, b) => { + if (a.active !== b.active) return a.active ? -1 : 1 + if (a.installed !== b.installed) return a.installed ? -1 : 1 + return 0 + }) + + // Ports + const ports = (sections.PORTS || []) + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith('Netid') && !l.startsWith('Proto')) + .slice(0, 30) + + const osRaw = getText('OS') + const osMatch = /PRETTY_NAME=["']?([^"'\n]+)["']?/.exec(osRaw) + + return { + collectedAt: new Date().toISOString(), + hostname: getText('HOSTNAME'), + os: osMatch ? osMatch[1] : osRaw || 'Linux', + kernel: getText('KERNEL'), + arch: getText('ARCH'), + uptimeSeconds: Math.floor(parseFloat(getText('UPTIME').split(/\s+/)[0] || '0')), + loadAvg: getText('LOAD').split(/\s+/).slice(0, 3).join(' '), + cpuCores: parseInt(getText('CORES') || '1', 10) || 1, + cpuModel: getText('CPU_MODEL'), + cpuUsage, + cpuTotals, + memTotalMb, + memUsedMb, + memAvailMb, + swapTotalMb, + swapUsedMb: Math.max(0, swapTotalMb - swapFreeMb), + diskTotalMb, + diskUsedMb, + diskAvailMb, + diskPercent, + rxBytes, + txBytes, + rxSpeedBps, + txSpeedBps, + interfaces, + bbr: getText('BBR'), + publicIp: getText('PUBLIC_IP'), + services, + ports + } +} + +function buildMetricsProbeScript(useLight = false) { + const servicesList = 'sing-box xray v2ray mihomo clash hysteria-server shadowsocks-rust ssserver' + const serviceProbeSnippet = ` +PS_LIST=$(ps -eo args 2>/dev/null) +echo "__SEC_SERVICES__" +for s in ${servicesList}; do + st=$(systemctl is-active "$s" 2>/dev/null | head -n1) + [ -z "$st" ] && st="inactive" + inst=0 + if [ "$st" = "active" ] || command -v "$s" >/dev/null 2>&1 || [ -f "/etc/systemd/system/$s.service" ] || [ -f "/lib/systemd/system/$s.service" ]; then + inst=1 + fi + if [ "$st" != "active" ]; then + if [ "$s" = "xray" ]; then + if printf '%s\\n' "$PS_LIST" | grep -E "(^|/)(xray|xray-linux[^ ]*)( |$)" | grep -v grep >/dev/null 2>&1; then + st="active" + inst=1 + fi + elif printf '%s\\n' "$PS_LIST" | grep -E "(^|/)$s( |$)" | grep -v grep >/dev/null 2>&1; then + st="active" + inst=1 + fi + fi + echo "$s|$st|$inst" +done +` + + if (useLight) { + return ` +echo "__SEC_UPTIME__" +cat /proc/uptime 2>/dev/null || echo 0 +echo "__SEC_LOAD__" +cat /proc/loadavg 2>/dev/null || uptime +echo "__SEC_CPU_STAT__" +grep '^cpu ' /proc/stat 2>/dev/null +echo "__SEC_MEM__" +cat /proc/meminfo 2>/dev/null +echo "__SEC_DISK__" +df -Pm / 2>/dev/null +echo "__SEC_NET__" +cat /proc/net/dev 2>/dev/null +${serviceProbeSnippet} +` + } + + return ` +echo "__SEC_HOSTNAME__" +hostname 2>/dev/null || echo unknown +echo "__SEC_OS__" +grep -m1 PRETTY_NAME /etc/os-release 2>/dev/null || uname -s +echo "__SEC_KERNEL__" +uname -r +echo "__SEC_ARCH__" +uname -m +echo "__SEC_UPTIME__" +cat /proc/uptime 2>/dev/null || echo 0 +echo "__SEC_LOAD__" +cat /proc/loadavg 2>/dev/null || uptime +echo "__SEC_CORES__" +nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo 2>/dev/null || echo 1 +echo "__SEC_CPU_MODEL__" +awk -F: '/model name|Model/{print $2; exit}' /proc/cpuinfo 2>/dev/null | sed 's/^ *//' +echo "__SEC_CPU_STAT__" +grep '^cpu ' /proc/stat 2>/dev/null +sleep 0.25 +grep '^cpu ' /proc/stat 2>/dev/null +echo "__SEC_MEM__" +cat /proc/meminfo 2>/dev/null +echo "__SEC_DISK__" +df -Pm / 2>/dev/null +echo "__SEC_NET__" +cat /proc/net/dev 2>/dev/null +echo "__SEC_BBR__" +sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo unknown +echo "__SEC_PUBLIC_IP__" +(curl -4fsSL --max-time 2 https://api.ipify.org 2>/dev/null || hostname -I 2>/dev/null | awk '{print $1}') +${serviceProbeSnippet} +echo "__SEC_PORTS__" +ss -tulnp 2>/dev/null | head -n 30 || netstat -tulnp 2>/dev/null | head -n 30 +` +} + +async function collectSystemMetrics(profile, options = {}) { + const config = buildConnectConfig(profile) + const sessionKey = getProfileSessionKey(config) + const cached = metricsCache.get(sessionKey) || { + staticInfo: null, + prevCpuTotals: null, + prevCpuUsage: 0, + prevRxBytes: null, + prevTxBytes: null, + prevTimestamp: null, + tickCount: 0 + } + + const useLight = + Boolean(options.light) && + Boolean(cached.staticInfo) && + cached.tickCount > 0 && + cached.tickCount % 15 !== 0 + + const probeScript = buildMetricsProbeScript(useLight) + + const res = await execCommand(profile, `sh -c ${shellQuote(probeScript)}`, { + timeoutMs: useLight ? 10000 : 20000 + }) + + const prevSnapshot = + cached.prevTimestamp !== null + ? { + cpuTotals: cached.prevCpuTotals, + cpuUsage: cached.prevCpuUsage, + rxBytes: cached.prevRxBytes, + txBytes: cached.prevTxBytes, + timestamp: cached.prevTimestamp + } + : null + + const parsed = parseMetricsOutput(res.stdout, prevSnapshot) + const merged = useLight + ? { + ...parsed, + hostname: cached.staticInfo.hostname, + os: cached.staticInfo.os, + kernel: cached.staticInfo.kernel, + arch: cached.staticInfo.arch, + cpuCores: cached.staticInfo.cpuCores, + cpuModel: cached.staticInfo.cpuModel, + bbr: cached.staticInfo.bbr, + publicIp: cached.staticInfo.publicIp, + ports: cached.staticInfo.ports + } + : parsed + + if (!useLight) { + cached.staticInfo = { + hostname: merged.hostname, + os: merged.os, + kernel: merged.kernel, + arch: merged.arch, + cpuCores: merged.cpuCores, + cpuModel: merged.cpuModel, + bbr: merged.bbr, + publicIp: merged.publicIp, + ports: merged.ports + } + } + + cached.prevCpuTotals = merged.cpuTotals + cached.prevCpuUsage = merged.cpuUsage + cached.prevRxBytes = merged.rxBytes + cached.prevTxBytes = merged.txBytes + cached.prevTimestamp = Date.now() + cached.tickCount += 1 + metricsCache.set(sessionKey, cached) + + return merged +} + +function parseDiscoveryOutput(raw) { + const sections = {} + let currentKey = null + for (const line of String(raw || '').split('\n')) { + const match = /^__DISC_([A-Z0-9_]+)__$/.exec(line.trim()) + if (match) { + currentKey = match[1] + sections[currentKey] = [] + } else if (currentKey) { + sections[currentKey].push(line) + } + } + + const getText = (key) => (sections[key] || []).join('\n').trim() + const services = [] + for (const line of sections.SERVICES || []) { + const parts = line.trim().split('|') + if (parts.length < 3) continue + const [name, activeFlag, installedFlag, configPath] = parts + if (!name) continue + services.push({ + name, + active: activeFlag === '1', + installed: installedFlag === '1', + configPath: configPath || '' + }) + } + + const primaryService = getText('PRIMARY_SERVICE') + const configPath = getText('CONFIG_PATH') + const b64 = getText('CONFIG_B64').replace(/\s+/g, '') + let rawContent = '' + if (b64) { + try { + rawContent = Buffer.from(b64, 'base64').toString('utf8') + } catch { + rawContent = '' + } + } + + if (!primaryService && !rawContent && !services.some((s) => s.active || s.installed)) { + return { + found: false, + services, + primaryService: '', + configPath: '', + format: 'other', + writableAsYaml: false, + yamlText: '', + rawContent: '', + proxiesCount: 0, + rulesCount: 0, + proxyGroupsCount: 0, + controllerHost: '', + controllerPort: 0, + controllerSecret: '', + mixedPort: 0, + mode: '' + } + } + + const parsed = configStore.parseRemoteProxyConfig({ + serviceName: primaryService || services.find((s) => s.active || s.installed)?.name || '', + configPath, + rawContent + }) + + return { + ...parsed, + found: true, + services + } +} + +function buildDiscoveryProbeScript() { + return ` +echo "__DISC_PS__" +ps -eo args 2>/dev/null | grep -Ei 'mihomo|clash|sing-box|xray|v2ray|hysteria|shadowsocks|ssserver|ss-server|trojan|tuic|snell|x-ui|3x-ui|s-ui|marzban|naive|gost|realm|v2raya|dae' | grep -v grep | head -n 60 +echo "__DISC_SYSTEMD__" +UNITS="mihomo clash clash-meta sing-box xray v2ray hysteria-server hysteria shadowsocks-rust ssserver x-ui 3x-ui s-ui trojan-go tuic snell" +RUNNING_UNITS=$(systemctl list-units --type=service --state=running --no-legend 2>/dev/null | awk '{print $1}' | sed 's/\\.service$//' | grep -Ei 'mihomo|clash|sing-box|xray|v2ray|hysteria|shadowsocks|ssserver|trojan|tuic|snell|x-ui|marzban' || true) +ALL_UNITS=$(printf '%s\n%s\n' $UNITS $RUNNING_UNITS | awk 'NF && !seen[$0]++') +for u in $ALL_UNITS; do + st=$(systemctl is-active "$u" 2>/dev/null | head -n1) + [ -z "$st" ] && st="inactive" + inst=0 + if [ "$st" = "active" ] || command -v "$u" >/dev/null 2>&1 || [ -f "/etc/systemd/system/$u.service" ] || [ -f "/lib/systemd/system/$u.service" ]; then + inst=1 + fi + exec_line="" + if [ "$inst" = "1" ]; then + exec_line=$(systemctl cat "$u" 2>/dev/null | grep -m1 '^ExecStart=' | sed 's/^ExecStart=//' | tr '\\r\\n' ' ') + fi + echo "$u|$st|$inst|$exec_line" +done +echo "__DISC_FILES__" +for d in /etc/mihomo /etc/clash /etc/clash-meta /opt/clash /opt/mihomo /etc/sing-box /usr/local/etc/sing-box /etc/xray /usr/local/etc/xray /etc/v2ray /usr/local/etc/v2ray /usr/local/x-ui/bin /etc/x-ui /var/lib/marzban /etc/hysteria /etc/shadowsocks-rust /etc/shadowsocks /etc/shadowsocks-libev /etc/trojan-go /etc/tuic /etc/snell "$HOME/.config/mihomo" "$HOME/.config/clash" /root/.config/mihomo /root/.config/clash /root/sing-box /root/xray /root/hysteria; do + if [ -d "$d" ]; then + find "$d" -maxdepth 2 -type f \\( -name '*.yaml' -o -name '*.yml' -o -name '*.json' -o -name '*.conf' \\) 2>/dev/null + fi +done | awk 'NF && !seen[$0]++' | head -n 80 +` +} + +function inferServiceFromText(text) { + const s = String(text || '').toLowerCase() + if (/mihomo|clash-meta|clash\.meta/.test(s)) return 'mihomo' + if (/clash/.test(s)) return 'clash' + if (/sing-box/.test(s)) return 'sing-box' + if (/xray|x-ui|3x-ui/.test(s)) return 'xray' + if (/v2ray/.test(s)) return 'v2ray' + if (/hysteria/.test(s)) return 'hysteria-server' + if (/shadowsocks-rust|ssserver|ss-rust/.test(s)) return 'shadowsocks-rust' + if (/shadowsocks|ss-server/.test(s)) return 'ssserver' + if (/trojan/.test(s)) return 'trojan' + if (/tuic/.test(s)) return 'tuic' + if (/snell/.test(s)) return 'snell' + if (/marzban/.test(s)) return 'sing-box' + return '' +} + +function getServiceWeight(serviceName) { + switch (serviceName) { + case 'mihomo': + case 'clash': + case 'clash-meta': + return 5 + case 'sing-box': + return 4 + case 'xray': + case 'v2ray': + return 3 + case 'hysteria-server': + case 'shadowsocks-rust': + return 2 + default: + return 1 + } +} + +function stripOuterQuotes(val) { + const trimmed = String(val || '').trim() + if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) { + return trimmed.slice(1, -1) + } + return trimmed +} + +function extractConfigPathFromCmdline(cmdline, serviceHint = '') { + const line = String(cmdline || '').trim() + if (!line) return { configPath: '', isDir: false } + + const dirMatch = /(?:^|\s)(?:-d|--config-dir|-C|--confdir|-confdir)(?:=|\s+)("[^"]+"|'[^']+'|\S+)/.exec(line) + const fileMatch = /(?:^|\s)(?:--config|-config|-c|-f)(?:=|\s+)("[^"]+"|'[^']+'|\S+)/.exec(line) + + if (fileMatch) { + const rawPath = stripOuterQuotes(fileMatch[1]) + if (rawPath && rawPath !== 'stdin' && rawPath !== '-') { + return { configPath: rawPath, isDir: false } + } + } + if (dirMatch) { + const rawDir = stripOuterQuotes(dirMatch[1]).replace(/\/+$/, '') + if (rawDir) { + if (/(?:^|\s)(?:-C|--confdir|-confdir)/.test(dirMatch[0])) { + return { configPath: rawDir, isDir: true } + } + if (serviceHint === 'mihomo' || serviceHint === 'clash' || /mihomo|clash/.test(line)) { + return { configPath: `${rawDir}/config.yaml`, isDir: false } + } + return { configPath: `${rawDir}/config.json`, isDir: false } + } + } + return { configPath: '', isDir: false } +} + +function extractDiscoveryCandidates(probeStdout) { + const sections = {} + let currentKey = null + for (const line of String(probeStdout || '').split('\n')) { + const match = /^__DISC_([A-Z0-9_]+)__$/.exec(line.trim()) + if (match) { + currentKey = match[1] + sections[currentKey] = [] + } else if (currentKey) { + sections[currentKey].push(line) + } + } + + const psLines = (sections.PS || []).map((l) => l.trim()).filter(Boolean) + const systemdLines = (sections.SYSTEMD || []).map((l) => l.trim()).filter(Boolean) + const filePaths = (sections.FILES || []).map((l) => l.trim()).filter(Boolean) + + const fileSet = new Set(filePaths) + const servicesMap = new Map() + const candidateMap = new Map() + + const addCandidate = (serviceName, configPath, score, active, isDir = false) => { + if (!configPath) return + const key = configPath + const existing = candidateMap.get(key) + if (!existing || score > existing.score) { + candidateMap.set(key, { + serviceName: serviceName || inferServiceFromText(configPath) || 'proxy', + configPath, + score, + active: Boolean(active), + isDir: Boolean(isDir) + }) + } + } + + const upsertService = (name, patch) => { + if (!name) return + const prev = servicesMap.get(name) || { name, active: false, installed: false, configPath: '' } + servicesMap.set(name, { + name, + active: prev.active || Boolean(patch.active), + installed: prev.installed || Boolean(patch.installed) || Boolean(patch.active), + configPath: prev.configPath || patch.configPath || '' + }) + } + + for (const line of psLines) { + const svc = inferServiceFromText(line) + if (!svc) continue + const extracted = extractConfigPathFromCmdline(line, svc) + let resolvedPath = extracted.configPath + if (!resolvedPath && !extracted.isDir) { + const matchedFile = filePaths.find((fp) => inferServiceFromText(fp) === svc) + if (matchedFile) resolvedPath = matchedFile + } + upsertService(svc, { active: true, installed: true, configPath: resolvedPath }) + if (resolvedPath) { + const baseScore = extracted.configPath ? 140 : 100 + addCandidate(svc, resolvedPath, baseScore + getServiceWeight(svc), true, extracted.isDir) + } + } + + for (const line of systemdLines) { + const firstSep = line.indexOf('|') + const secondSep = line.indexOf('|', firstSep + 1) + const thirdSep = line.indexOf('|', secondSep + 1) + if (firstSep === -1 || secondSep === -1) continue + const unit = line.slice(0, firstSep).trim() + const state = line.slice(firstSep + 1, secondSep).trim() + const instFlag = thirdSep === -1 ? line.slice(secondSep + 1).trim() : line.slice(secondSep + 1, thirdSep).trim() + const execStart = thirdSep === -1 ? '' : line.slice(thirdSep + 1).trim() + const canonicalSvc = inferServiceFromText(unit) || unit + const isActive = state === 'active' + const isInstalled = isActive || instFlag === '1' + const extracted = extractConfigPathFromCmdline(execStart, canonicalSvc) + let resolvedPath = extracted.configPath + if (!resolvedPath && isInstalled) { + const matchedFile = filePaths.find((fp) => inferServiceFromText(fp) === canonicalSvc) + if (matchedFile) resolvedPath = matchedFile + } + upsertService(canonicalSvc, { active: isActive, installed: isInstalled, configPath: resolvedPath }) + if (resolvedPath) { + const baseScore = isActive ? (extracted.configPath ? 120 : 100) : isInstalled ? 60 : 30 + addCandidate(canonicalSvc, resolvedPath, baseScore + getServiceWeight(canonicalSvc), isActive, extracted.isDir) + } + } + + for (const fp of filePaths) { + const svc = inferServiceFromText(fp) || 'proxy' + const svcEntry = servicesMap.get(svc) + if (svc && (!svcEntry || !svcEntry.configPath)) { + upsertService(svc, { installed: true, configPath: fp }) + } + addCandidate(svc, fp, (svcEntry?.active ? 90 : 35) + getServiceWeight(svc), Boolean(svcEntry?.active), false) + } + + // If a -d config.yaml resolved path does not appear in __DISC_FILES__, prefer existing files when equal + const candidates = Array.from(candidateMap.values()).sort((a, b) => { + const aExists = fileSet.has(a.configPath) ? 1 : 0 + const bExists = fileSet.has(b.configPath) ? 1 : 0 + if (b.score !== a.score) return b.score - a.score + return bExists - aExists + }) + + const services = Array.from(servicesMap.values()).sort((a, b) => { + if (a.active !== b.active) return a.active ? -1 : 1 + if (a.installed !== b.installed) return a.installed ? -1 : 1 + return getServiceWeight(b.name) - getServiceWeight(a.name) + }) + + const primary = candidates[0] || (() => { + const activeSvc = services.find((s) => s.active || s.installed) + return activeSvc ? { serviceName: activeSvc.name, configPath: activeSvc.configPath || '', isDir: false, active: activeSvc.active } : null + })() + + return { + services, + candidates: candidates.map(({ serviceName, configPath, active, isDir }) => ({ + serviceName, + configPath, + active, + isDir + })), + primary + } +} + +async function readRemoteConfigWithFallback(profile, targetPath, isDir = false) { + const cleanPath = String(targetPath || '').trim() + if (!cleanPath) return '' + + if (!isDir) { + try { + const content = await readRemoteFile(profile, cleanPath) + if (content && content.trim()) return content + } catch { + // fall through to sudo/shell fallback + } + } + + const readScript = ` +TARGET=${shellQuote(cleanPath)} +read_file_cmd() { + if [ -r "$1" ]; then + head -c 524288 "$1" 2>/dev/null + elif command -v sudo >/dev/null 2>&1; then + sudo -n head -c 524288 "$1" 2>/dev/null || true + fi +} +if [ -d "$TARGET" ]; then + if [ -f "$TARGET/config.json" ]; then + read_file_cmd "$TARGET/config.json" | base64 | tr -d '\n' + elif [ -f "$TARGET/config.yaml" ]; then + read_file_cmd "$TARGET/config.yaml" | base64 | tr -d '\n' + else + first_f=$(find "$TARGET" -maxdepth 1 -type f \\( -name '*.json' -o -name '*.yaml' -o -name '*.yml' \\) 2>/dev/null | sort | head -n1) + [ -n "$first_f" ] && read_file_cmd "$first_f" | base64 | tr -d '\n' + fi +elif [ -f "$TARGET" ]; then + read_file_cmd "$TARGET" | base64 | tr -d '\n' +fi +` + const res = await execCommand(profile, `sh -c ${shellQuote(readScript)}`, { timeoutMs: 15000 }) + const b64 = String(res.stdout || '').replace(/\s+/g, '') + if (!b64) return '' + try { + return Buffer.from(b64, 'base64').toString('utf8') + } catch { + return '' + } +} + +async function discoverRemoteProxy(profile, options = {}) { + const probeScript = buildDiscoveryProbeScript() + const probeRes = await execCommand(profile, `sh -c ${shellQuote(probeScript)}`, { timeoutMs: 20000 }) + const extracted = extractDiscoveryCandidates(probeRes.stdout) + + const requestedPath = String(options.configPath || '').trim() + const chosenCandidate = + (requestedPath && extracted.candidates.find((c) => c.configPath === requestedPath)) || + (requestedPath ? { serviceName: inferServiceFromText(requestedPath) || extracted.primary?.serviceName || 'proxy', configPath: requestedPath, isDir: false } : extracted.primary) + + if (!chosenCandidate && extracted.services.length === 0) { + return { + found: false, + services: [], + candidates: [], + primaryService: '', + configPath: '', + format: 'other', + writableAsYaml: false, + yamlText: '', + rawContent: '', + proxiesCount: 0, + rulesCount: 0, + proxyGroupsCount: 0, + controllerHost: '', + controllerPort: 0, + controllerSecret: '', + mixedPort: 0, + mode: '' + } + } + + const targetPath = chosenCandidate?.configPath || '' + let rawContent = '' + if (targetPath) { + rawContent = await readRemoteConfigWithFallback(profile, targetPath, Boolean(chosenCandidate?.isDir)) + } + + const parsed = configStore.parseRemoteProxyConfig({ + serviceName: chosenCandidate?.serviceName || extracted.services[0]?.name || 'proxy', + configPath: targetPath, + rawContent + }) + + return { + ...parsed, + found: true, + services: extracted.services, + candidates: extracted.candidates + } +} + +async function manageService(profile, serviceName, action) { + const safeName = validateServiceName(serviceName) + const allowedActions = ['start', 'stop', 'restart', 'status', 'enable', 'disable', 'logs'] + if (!allowedActions.includes(action)) { + throw new Error(`不支持的服务操作: ${action}`) + } + + let cmd + if (action === 'logs') { + cmd = `journalctl -u ${shellQuote(safeName)} -n 120 --no-pager 2>&1` + } else if (action === 'status') { + cmd = `systemctl status ${shellQuote(safeName)} --no-pager -l 2>&1` + } else { + cmd = `if [ "$(id -u)" -eq 0 ]; then systemctl ${action} ${shellQuote(safeName)}; else sudo systemctl ${action} ${shellQuote(safeName)}; fi && systemctl is-active ${shellQuote(safeName)} || true` + } + + return execCommand(profile, cmd, { timeoutMs: 20000 }) +} + +async function readRemoteFile(profile, remotePath) { + const target = String(remotePath || '').trim() + if (!target) throw new Error('远端文件路径不能为空') + + return withPooledSsh(profile, (conn) => { + return new Promise((resolve, reject) => { + conn.sftp((err, sftp) => { + if (err) return reject(err) + sftp.readFile(target, 'utf8', (readErr, data) => { + if (readErr) { + return reject(new Error(`读取远端文件失败 (${target}): ${readErr.message}`)) + } + resolve(String(data)) + }) + }) + }) + }) +} + +async function writeRemoteFile(profile, remotePath, content, options = {}) { + const target = String(remotePath || '').trim() + if (!target) throw new Error('远端文件路径不能为空') + + if (options?.backup) { + const bakPath = `${target}.bak` + try { + await execCommand( + profile, + `[ -f ${shellQuote(target)} ] && cp -p ${shellQuote(target)} ${shellQuote(bakPath)} || true`, + { timeoutMs: 8000 } + ) + } catch { + // ignore backup failure if file doesn't exist + } + } + + return withPooledSsh(profile, (conn) => { + return new Promise((resolve, reject) => { + conn.sftp((err, sftp) => { + if (err) return reject(err) + sftp.writeFile(target, String(content ?? ''), 'utf8', (writeErr) => { + if (writeErr) { + return reject(new Error(`写入远端文件失败 (${target}): ${writeErr.message}`)) + } + resolve({ ok: true, remotePath: target }) + }) + }) + }) + }) +} + +function openTunnel(profile, options = {}) { + const connectConfig = buildConnectConfig(profile) + const remoteHost = String(options.remoteHost || '127.0.0.1').trim() + const remotePort = normalizePort(options.remotePort || 9090) + const requestedLocalPort = options.localPort ? normalizePort(options.localPort) : 0 + + return new Promise((resolve, reject) => { + const conn = new Client() + let server = null + let settled = false + + const fail = (err) => { + if (settled) return + settled = true + try { + server?.close() + } catch {} + try { + conn.end() + } catch {} + reject(err) + } + + conn.on('ready', () => { + server = net.createServer((sock) => { + conn.forwardOut( + sock.remoteAddress || '127.0.0.1', + sock.remotePort || 0, + remoteHost, + remotePort, + (err, stream) => { + if (err) { + sock.destroy() + return + } + sock.pipe(stream).pipe(sock) + sock.on('error', () => stream.end()) + stream.on('error', () => sock.destroy()) + } + ) + }) + + server.on('error', (err) => { + fail(new Error(`本地隧道端口监听失败: ${err.message}`)) + }) + + server.listen(requestedLocalPort, '127.0.0.1', () => { + const addr = server.address() + const localPort = typeof addr === 'object' && addr ? addr.port : requestedLocalPort + const tunnelId = crypto.randomUUID() + const info = { + tunnelId, + profileId: profile.id || '', + profileName: profile.name || connectConfig.host, + host: connectConfig.host, + localHost: '127.0.0.1', + localPort, + remoteHost, + remotePort, + createdAt: new Date().toISOString() + } + activeTunnels.set(tunnelId, { info, conn, server }) + settled = true + resolve(info) + }) + }) + + conn.on('close', () => { + for (const [id, entry] of activeTunnels.entries()) { + if (entry.conn === conn) { + try { + entry.server.close() + } catch {} + activeTunnels.delete(id) + } + } + }) + + conn.on('error', (err) => { + fail(new Error(`SSH 隧道建立失败: ${err.message}`)) + }) + + conn.connect(connectConfig) + }) +} + +function closeTunnel(tunnelId) { + const entry = activeTunnels.get(tunnelId) + if (!entry) return false + try { + entry.server.close() + } catch {} + try { + entry.conn.end() + } catch {} + activeTunnels.delete(tunnelId) + return true +} + +function listTunnels() { + return Array.from(activeTunnels.values()).map((entry) => entry.info) +} + +function closeAllTunnels() { + for (const id of Array.from(activeTunnels.keys())) { + closeTunnel(id) + } +} + +module.exports = { + shellQuote, + expandHomePath, + validateServiceName, + normalizeAndValidatePrivateKey, + discoverLocalSshKeys, + parseSshConfigText, + discoverSshConfigHosts, + buildConnectConfig, + buildMetricsProbeScript, + buildDiscoveryProbeScript, + extractDiscoveryCandidates, + execCommand, + testSshConnection, + collectSystemMetrics, + parseMetricsOutput, + discoverRemoteProxy, + parseDiscoveryOutput, + closeSession, + closeAllSessions, + manageService, + readRemoteFile, + writeRemoteFile, + openTunnel, + closeTunnel, + listTunnels, + closeAllTunnels +} diff --git a/plugins/vps-manager/preload/system-proxy.cjs b/plugins/vps-manager/preload/system-proxy.cjs new file mode 100644 index 000000000..85d3939d7 --- /dev/null +++ b/plugins/vps-manager/preload/system-proxy.cjs @@ -0,0 +1,347 @@ +const { execFileSync } = require('node:child_process') + +const HOST_RE = /^[a-zA-Z0-9._:-]{1,253}$/ +const MAC_BYPASS_DOMAINS = ['localhost', '127.0.0.1', '*.local', '192.168.0.0/16', '10.0.0.0/8'] + +function validateProxyTarget(host = '127.0.0.1', port = 7890) { + const cleanHost = String(host || '').trim() + if (!cleanHost || !HOST_RE.test(cleanHost)) { + throw new Error(`无效代理地址: ${host}`) + } + const cleanPort = Number(port) + if (!Number.isInteger(cleanPort) || cleanPort < 1 || cleanPort > 65535) { + throw new Error(`无效代理端口: ${port}`) + } + return { host: cleanHost, port: cleanPort } +} + +function buildProxyEnvSnippet(host = '127.0.0.1', port = 7890, platform = process.platform) { + const clean = validateProxyTarget(host, port) + if (platform === 'win32') { + return `$env:HTTP_PROXY="http://${clean.host}:${clean.port}"; $env:HTTPS_PROXY="http://${clean.host}:${clean.port}"; $env:ALL_PROXY="socks5://${clean.host}:${clean.port}"` + } + return `export http_proxy=http://${clean.host}:${clean.port} https_proxy=http://${clean.host}:${clean.port} all_proxy=socks5://${clean.host}:${clean.port}` +} + +function parseMacServiceFromHardwarePorts(hwOutput, iface) { + const targetIface = String(iface || '').trim() + if (!targetIface) return null + const blocks = String(hwOutput || '').split(/\r?\n\r?\n/) + for (const block of blocks) { + const portMatch = /^Hardware Port:\s*(.+)$/m.exec(block) + const devMatch = /^Device:\s*(\S+)$/m.exec(block) + if (portMatch && devMatch && devMatch[1] === targetIface) { + return portMatch[1].trim() + } + } + return null +} + +function parseMacWebProxyOutput(output) { + const text = String(output || '') + const enabledMatch = /^Enabled:\s*(Yes|No)/im.exec(text) + const serverMatch = /^Server:\s*(.*)$/im.exec(text) + const portMatch = /^Port:\s*(\d+)/im.exec(text) + return { + enabled: Boolean(enabledMatch && enabledMatch[1].toLowerCase() === 'yes'), + host: (serverMatch && serverMatch[1].trim()) || '127.0.0.1', + port: (portMatch && Number(portMatch[1])) || 7890 + } +} + +function parseWindowsProxyServer(rawServer) { + const text = String(rawServer || '').trim() + if (!text) return { host: '127.0.0.1', port: 7890 } + const firstSegment = text.includes(';') ? text.split(';')[0] : text + const cleaned = firstSegment.replace(/^[a-zA-Z]+=/, '').trim() + const idx = cleaned.lastIndexOf(':') + if (idx > 0) { + const h = cleaned.slice(0, idx).replace(/^\[|\]$/g, '').trim() || '127.0.0.1' + const p = Number(cleaned.slice(idx + 1)) + return { + host: h, + port: Number.isInteger(p) && p > 0 && p <= 65535 ? p : 7890 + } + } + return { host: cleaned || '127.0.0.1', port: 7890 } +} + +function execCmd(bin, args, timeout = 5000) { + return execFileSync(bin, args, { + encoding: 'utf8', + timeout, + windowsHide: true + }).trim() +} + +function detectMacPrimaryService() { + try { + const routeOut = execCmd('route', ['-n', 'get', 'default']) + const ifaceMatch = /interface:\s*(\S+)/.exec(routeOut) + if (ifaceMatch) { + const hwOut = execCmd('networksetup', ['-listallhardwareports']) + const svc = parseMacServiceFromHardwarePorts(hwOut, ifaceMatch[1]) + if (svc) return svc + } + } catch { + // fallback below + } + + const servicesOut = execCmd('networksetup', ['-listallnetworkservices']) + const services = servicesOut + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith('An asterisk') && !l.startsWith('*')) + + const preferred = services.find((s) => /wi-fi|ethernet|lan|thunderbolt/i.test(s)) + const chosen = preferred || services[0] + if (!chosen) { + throw new Error('未检测到可用的 macOS 网络服务') + } + return chosen +} + +function getMacSystemProxy() { + const service = detectMacPrimaryService() + const webOut = execCmd('networksetup', ['-getwebproxy', service]) + const parsed = parseMacWebProxyOutput(webOut) + let secureEnabled = false + let socksEnabled = false + try { + secureEnabled = parseMacWebProxyOutput(execCmd('networksetup', ['-getsecurewebproxy', service])).enabled + } catch {} + try { + socksEnabled = parseMacWebProxyOutput(execCmd('networksetup', ['-getsocksfirewallproxy', service])).enabled + } catch {} + + return { + supported: true, + platform: 'darwin', + enabled: parsed.enabled || secureEnabled || socksEnabled, + host: parsed.host || '127.0.0.1', + port: parsed.port || 7890, + service + } +} + +function setMacSystemProxy(enabled, host, port) { + const service = detectMacPrimaryService() + if (enabled) { + const portStr = String(port) + execCmd('networksetup', ['-setwebproxy', service, host, portStr]) + execCmd('networksetup', ['-setsecurewebproxy', service, host, portStr]) + execCmd('networksetup', ['-setsocksfirewallproxy', service, host, portStr]) + execCmd('networksetup', ['-setproxybypassdomains', service, ...MAC_BYPASS_DOMAINS]) + } else { + execCmd('networksetup', ['-setwebproxystate', service, 'off']) + execCmd('networksetup', ['-setsecurewebproxystate', service, 'off']) + execCmd('networksetup', ['-setsocksfirewallproxystate', service, 'off']) + } + return getMacSystemProxy() +} + +const WIN_REG_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings' + +function notifyWindowsInternetSettingsChanged() { + try { + const script = + 'Add-Type -Namespace WinINet -Name Native -MemberDefinition \'[DllImport("wininet.dll", SetLastError=true)] public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);\'; [WinINet.Native]::InternetSetOption([IntPtr]::Zero, 39, [IntPtr]::Zero, 0) | Out-Null; [WinINet.Native]::InternetSetOption([IntPtr]::Zero, 37, [IntPtr]::Zero, 0) | Out-Null' + execCmd('powershell', ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script], 4000) + } catch { + // non-fatal if PowerShell policy blocks inline Add-Type + } +} + +function getWindowsSystemProxy() { + const out = execCmd('reg', ['query', WIN_REG_KEY]) + const enableMatch = /ProxyEnable\s+REG_DWORD\s+0x([0-9a-fA-F]+)/i.exec(out) + const serverMatch = /ProxyServer\s+REG_SZ\s+([^\r\n]+)/i.exec(out) + const enabled = Boolean(enableMatch && parseInt(enableMatch[1], 16) === 1) + const parsed = serverMatch ? parseWindowsProxyServer(serverMatch[1]) : { host: '127.0.0.1', port: 7890 } + return { + supported: true, + platform: 'win32', + enabled, + host: parsed.host, + port: parsed.port, + service: 'Windows Internet Settings' + } +} + +function setWindowsSystemProxy(enabled, host, port) { + if (enabled) { + execCmd('reg', ['add', WIN_REG_KEY, '/v', 'ProxyEnable', '/t', 'REG_DWORD', '/d', '1', '/f']) + execCmd('reg', ['add', WIN_REG_KEY, '/v', 'ProxyServer', '/t', 'REG_SZ', '/d', `${host}:${port}`, '/f']) + execCmd('reg', [ + 'add', + WIN_REG_KEY, + '/v', + 'ProxyOverride', + '/t', + 'REG_SZ', + '/d', + 'localhost;127.*;10.*;192.168.*;', + '/f' + ]) + } else { + execCmd('reg', ['add', WIN_REG_KEY, '/v', 'ProxyEnable', '/t', 'REG_DWORD', '/d', '0', '/f']) + } + notifyWindowsInternetSettingsChanged() + return getWindowsSystemProxy() +} + +function findKdeTools() { + for (const ver of ['6', '5']) { + try { + execCmd(`kreadconfig${ver}`, ['--help'], 1500) + return { read: `kreadconfig${ver}`, write: `kwriteconfig${ver}` } + } catch { + // try next KDE version + } + } + return null +} + +function getLinuxSystemProxy() { + try { + const modeRaw = execCmd('gsettings', ['get', 'org.gnome.system.proxy', 'mode']).replace(/'/g, '') + let host = '127.0.0.1' + let port = 7890 + try { + host = execCmd('gsettings', ['get', 'org.gnome.system.proxy.http', 'host']).replace(/'/g, '') || host + const p = Number(execCmd('gsettings', ['get', 'org.gnome.system.proxy.http', 'port'])) + if (Number.isInteger(p) && p > 0) port = p + } catch {} + return { + supported: true, + platform: 'linux', + enabled: modeRaw === 'manual', + host, + port, + service: 'GNOME Proxy' + } + } catch { + // fallback to KDE + } + + const kde = findKdeTools() + if (kde) { + let proxyType = '0' + let host = '127.0.0.1' + let port = 7890 + try { + proxyType = execCmd(kde.read, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'ProxyType']) + const rawHttp = execCmd(kde.read, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'httpProxy']) + const match = /https?:\/\/([^:\s]+):(\d+)/i.exec(rawHttp) + if (match) { + host = match[1] + port = Number(match[2]) || port + } + } catch {} + return { + supported: true, + platform: 'linux', + enabled: proxyType === '1', + host, + port, + service: 'KDE Plasma Proxy' + } + } + + return { + supported: false, + platform: 'linux', + enabled: false, + host: '127.0.0.1', + port: 7890, + service: 'Linux (环境变量模式)', + fallbackEnv: buildProxyEnvSnippet('127.0.0.1', 7890, 'linux'), + error: '当前 Linux 桌面未检测到 GNOME/KDE 代理接口,可使用终端环境变量命令或应用内代理端口' + } +} + +function setLinuxSystemProxy(enabled, host, port) { + try { + execCmd('gsettings', ['get', 'org.gnome.system.proxy', 'mode']) + if (enabled) { + const portStr = String(port) + execCmd('gsettings', ['set', 'org.gnome.system.proxy.http', 'host', host]) + execCmd('gsettings', ['set', 'org.gnome.system.proxy.http', 'port', portStr]) + execCmd('gsettings', ['set', 'org.gnome.system.proxy.https', 'host', host]) + execCmd('gsettings', ['set', 'org.gnome.system.proxy.https', 'port', portStr]) + execCmd('gsettings', ['set', 'org.gnome.system.proxy.socks', 'host', host]) + execCmd('gsettings', ['set', 'org.gnome.system.proxy.socks', 'port', portStr]) + execCmd('gsettings', ['set', 'org.gnome.system.proxy', 'mode', 'manual']) + } else { + execCmd('gsettings', ['set', 'org.gnome.system.proxy', 'mode', 'none']) + } + return getLinuxSystemProxy() + } catch { + // fallback to KDE + } + + const kde = findKdeTools() + if (kde) { + if (enabled) { + execCmd(kde.write, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'ProxyType', '1']) + execCmd(kde.write, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'httpProxy', `http://${host}:${port}`]) + execCmd(kde.write, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'httpsProxy', `http://${host}:${port}`]) + execCmd(kde.write, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'socksProxy', `socks://${host}:${port}`]) + execCmd(kde.write, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'NoProxyFor', 'localhost,127.0.0.1,10.0.0.0/8,192.168.0.0/16']) + } else { + execCmd(kde.write, ['--file', 'kioslaverc', '--group', 'Proxy Settings', '--key', 'ProxyType', '0']) + } + try { + execCmd('dbus-send', ['--type=signal', '/KIO/Scheduler', 'org.kde.KIO.Scheduler.reparseSlaveConfiguration', 'string:']) + } catch {} + return getLinuxSystemProxy() + } + + throw new Error(`未检测到 GNOME/KDE 系统代理接口;请直接在终端执行: ${buildProxyEnvSnippet(host, port, 'linux')}`) +} + +function getSystemProxy() { + try { + if (process.platform === 'darwin') return getMacSystemProxy() + if (process.platform === 'win32') return getWindowsSystemProxy() + if (process.platform === 'linux') return getLinuxSystemProxy() + return { + supported: false, + platform: process.platform, + enabled: false, + host: '127.0.0.1', + port: 7890, + fallbackEnv: buildProxyEnvSnippet('127.0.0.1', 7890, process.platform), + error: `暂不支持当前系统: ${process.platform}` + } + } catch (err) { + return { + supported: false, + platform: process.platform, + enabled: false, + host: '127.0.0.1', + port: 7890, + fallbackEnv: buildProxyEnvSnippet('127.0.0.1', 7890, process.platform), + error: err instanceof Error ? err.message : String(err) + } + } +} + +function setSystemProxy(options = {}) { + const enabled = Boolean(options.enabled) + const { host, port } = validateProxyTarget(options.host || '127.0.0.1', options.port || 7890) + if (process.platform === 'darwin') return setMacSystemProxy(enabled, host, port) + if (process.platform === 'win32') return setWindowsSystemProxy(enabled, host, port) + if (process.platform === 'linux') return setLinuxSystemProxy(enabled, host, port) + throw new Error(`暂不支持自动切换系统代理的平台: ${process.platform}`) +} + +module.exports = { + validateProxyTarget, + buildProxyEnvSnippet, + parseMacServiceFromHardwarePorts, + parseMacWebProxyOutput, + parseWindowsProxyServer, + getSystemProxy, + setSystemProxy +} diff --git a/plugins/vps-manager/scripts/ensure-preload-deps.mjs b/plugins/vps-manager/scripts/ensure-preload-deps.mjs new file mode 100644 index 000000000..5645ac488 --- /dev/null +++ b/plugins/vps-manager/scripts/ensure-preload-deps.mjs @@ -0,0 +1,26 @@ +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const preloadDir = path.join(root, "preload"); +const requiredModules = [ + path.join(preloadDir, "node_modules", "ssh2", "package.json"), + path.join(preloadDir, "node_modules", "js-yaml", "package.json") +]; + +const hasAllDeps = requiredModules.every((filePath) => fs.existsSync(filePath)); +if (!hasAllDeps) { + const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; + const hasLockfile = fs.existsSync(path.join(preloadDir, "package-lock.json")); + const args = hasLockfile + ? ["ci", "--omit=dev", "--omit=optional", "--no-audit", "--no-fund"] + : ["install", "--omit=dev", "--omit=optional", "--no-audit", "--no-fund"]; + console.log(`[ensure:preload] installing preload runtime dependencies via npm ${args[0]}...`); + execFileSync(npmCommand, args, { + cwd: preloadDir, + stdio: "inherit", + shell: process.platform === "win32" + }); +} diff --git a/plugins/vps-manager/scripts/prepare-dist.mjs b/plugins/vps-manager/scripts/prepare-dist.mjs new file mode 100644 index 000000000..0f35c677c --- /dev/null +++ b/plugins/vps-manager/scripts/prepare-dist.mjs @@ -0,0 +1,69 @@ +import { execFileSync } from "node:child_process"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const dist = path.join(root, "dist"); +const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; + +// 1. Rewrite dist/index.html so file:// loads without ES module CORS failures in Electron WebContentsView +const indexHtmlPath = path.join(dist, "index.html"); +let indexHtml = await fs.readFile(indexHtmlPath, "utf8"); +indexHtml = indexHtml + .replace(/<\/script>/g, '') + .replace(/<\/script>/g, '') + .replace(//g, '') + .replace(/\scrossorigin(?:="[^"]*")?/g, ""); +await fs.writeFile(indexHtmlPath, indexHtml, "utf8"); + +// 2. Ensure dist/assets/*.js are IIFE-wrapped for classic