A local-first multi-agent app development platform, built on PenguinHarness
feat(plugins): 新增 web-vscode:把浏览器版 VS Code 一次装成能用的样子
lmliheng4ceb8e069d10
diff --git a/README.md b/README.mdindex 44d8c5d3..b43bfd3a 100644--- a/README.md+++ b/README.md@@ -97,7 +97,7 @@ optimise its own Skills:| Category | Plugins || --- | --- || Office Productivity | `data-analysis`, `use-firecrawl`, `use-offerdao`, `browser-automation`, `use-bento-slides`, `use-lieflat-charts`, `use-wps-office`, `use-seedance`, `use-seedream`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |-| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram`, `gpu-model-serving` |+| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram`, `gpu-model-serving`, `web-vscode` || AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` || Agent Company | `agent-company` |diff --git a/README.zh.md b/README.zh.mdindex d6ea2010..71a0e58c 100644--- a/README.zh.md+++ b/README.zh.md@@ -83,7 +83,7 @@ Adelie 运行在你的电脑或服务器上,自动串联 Agent 应用的创建| 分类 | 插件 || ----------- | ------------------------------------------------------------------------------- || 办公效率 | `data-analysis`、`use-firecrawl`、`use-offerdao`、`browser-automation`、`use-bento-slides`、`use-lieflat-charts`、`use-wps-office`、`use-seedance`、`use-seedream`、`humanizer`、`goal`、`continual-learning`、`csu-mail`、`lesson-video`、`requirements-box` |-| 软件开发 | `software-development`、`use-claude-code`、`wechat-miniprogram`、`gpu-model-serving` |+| 软件开发 | `software-development`、`use-claude-code`、`wechat-miniprogram`、`gpu-model-serving`、`web-vscode` || AI 应用开发 | `agent-development`、`model-development`、`skill-porting`、`agent-tuning` || Agent 公司 | `agent-company` |diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex be6ff7fa..85dee883 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -48,6 +48,7 @@"@adelie/use-wps-office": "workspace:*","@adelie/use-claude-code": "workspace:*","@adelie/wechat-miniprogram": "workspace:*",+ "@adelie/web-vscode": "workspace:*","@prismshadow/agenthub": "^0.4.15","@adelie/core": "workspace:*","@adelie/server": "workspace:*",diff --git a/packages/core/package.json b/packages/core/package.jsonindex 01fd9a2c..e6629b36 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -81,6 +81,7 @@"@adelie/use-wps-office": "workspace:*","@adelie/use-claude-code": "workspace:*","@adelie/wechat-miniprogram": "workspace:*",+ "@adelie/web-vscode": "workspace:*","@prismshadow/agenthub": "^0.4.15","arktype": "^2.2.3","smol-toml": "^1.3.0",diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.tsindex 86df0600..e01f22de 100644--- a/packages/core/test/plugins.test.ts+++ b/packages/core/test/plugins.test.ts@@ -65,7 +65,7 @@ describe("loadLibraryPlugins", () => {it("loads every plugin directory sorted by name, each with a date-sequence version and a category", () => {const plugins = loadLibraryPlugins();expect(plugins.map((p) => p.name)).toEqual([...plugins.map((p) => p.name)].sort());- expect(plugins.length).toBe(24);+ expect(plugins.length).toBe(25);for (const plugin of plugins) {expect(plugin.version, plugin.name).toMatch(PLUGIN_VERSION_PATTERN);expect(diff --git a/packages/desktop/package.json b/packages/desktop/package.jsonindex 21dc7207..fa99e2bb 100644--- a/packages/desktop/package.json+++ b/packages/desktop/package.json@@ -39,7 +39,8 @@"@adelie/use-seedream": "workspace:*","@adelie/use-wps-office": "workspace:*","@adelie/use-claude-code": "workspace:*",- "@adelie/wechat-miniprogram": "workspace:*"+ "@adelie/wechat-miniprogram": "workspace:*",+ "@adelie/web-vscode": "workspace:*"},"devDependencies": {"@adelie/cli": "workspace:*",diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.mdindex d78a6eb5..9e87ec64 100644--- a/packages/docs/content/skills.en.md+++ b/packages/docs/content/skills.en.md@@ -236,6 +236,7 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu| | `use-claude-code` | Run Claude Code on a remote host over SSH: a persistent expect session, headless `-p` with the stdin fix, a tmux-driven interactive TUI and multi-turn continuity (not preinstalled: install from the library when needed) || | `wechat-miniprogram` | Take a WeChat mini-program from code to published on a headless Linux server: QR login to mp.weixin.qq.com, switching from a public account to the mini-program backend, the AppID and upload key, IP whitelisting, upload with miniprogram-ci, a verified preview QR, the mandatory user-privacy policy, review and release (not preinstalled) || | `gpu-model-serving` | Stand up an OpenAI-compatible LLM endpoint on a rented or owned GPU box: pick the instance and where the weights live, take an already-quantized checkpoint, build the pip CUDA toolchain, start `serve.sh` detached, then verify with SGLang's speculative decoding, prefix caching and tool calling on — with the traps that cost the first attempt written down as symptom, cause and fix (not preinstalled: install from the library when needed) |+| | `web-vscode` | Stand up VS Code in the browser on a server and make it actually usable: code-server bound to loopback, an HTTPS reverse proxy that terminates TLS and passes WebSockets through, the site certificate signed by a local CA, the certificate-trust steps for Windows / macOS / iOS / Android, and the three checks that decide it is done — secure context, service worker, a notebook rendered as cells. It also records the traps that read as "the install is broken": a self-signed certificate clicked through in the browser still cannot run webviews, restricted mode opens a `.ipynb` as JSON, and 6665–6669 are blocked ports (not preinstalled) || AI App Development | `agent-development` | Agent development on Adelie, with four Skills: `penguin-sdk` (build agent/AI/RAG apps on the SDK, or connect a program to an agent over the Agent API; it asks which way first), `unified-llm-api` (call model APIs through `@prismshadow/agenthub`), `penguin-config` (manage model keys, defaults and Vault secrets) and `penguin-orchestration` (drive agents, Sessions, costs and schedules from a shell) || | `model-development` | Model development on your own hardware, with three Skills: `llamafactory` (fine-tune), `ollama` (run local models) and `vllm` (serve behind an OpenAI-compatible endpoint) || | `skill-porting` | Port Skills from external sources (plugin marketplaces, skills.sh registries, GitHub repos or local folders) into the agent after review and normalization |diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.mdindex a998e0d8..5dc94b11 100644--- a/packages/docs/content/skills.zh.md+++ b/packages/docs/content/skills.zh.md@@ -236,6 +236,7 @@ Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和| | `use-claude-code` | 通过 SSH 在远程主机上运行 Claude Code:持久 expect 会话、带 stdin 修复的无头 `-p` 模式、tmux 驱动的交互式 TUI,以及多轮连续性(不预装:需要时从插件库安装) || | `wechat-miniprogram` | 在无桌面的 Linux 服务器上把微信小程序从代码做到发布:扫码登录 mp.weixin.qq.com、从公众号后台切到小程序后台、取 AppID 与上传密钥、加 IP 白名单、用 miniprogram-ci 上传、交付校验过的预览码、填写必填的用户隐私保护指引、提交审核与发布(不预装) || | `gpu-model-serving` | 在租用或自有的 GPU 机器上立起一个 OpenAI 兼容的模型服务:选实例与权重落盘的位置、直接取已量化好的 checkpoint、搭好 pip 装的 CUDA 工具链、把 `serve.sh` 以 detached 方式拉起,最后按 SGLang 开投机解码、前缀缓存与 tool calling 的状态逐项验证;第一次部署会踩的坑按「现象 → 原因 → 修法」写进参考文档(不预装:需要时从插件库安装) |+| | `web-vscode` | 把 VS Code 装到服务器上、做成浏览器里真正能用的版本:code-server 只监听回环,HTTPS 反代终结 TLS 并直通 WebSocket,站点证书由本机自签的 CA 签发;附 Windows / macOS / iOS / Android 的证书信任步骤,以及三项验收(安全上下文、Service Worker、notebook 渲染成单元格)。也记下那些让人以为「装坏了」的坑——点「继续前往」的自签证书救不了 webview、受限模式会把 `.ipynb` 打开成 JSON、6665–6669 是浏览器的危险端口(不预装:需要时从插件库安装) || AI 应用开发 | `agent-development` | Adelie 上的 Agent 开发,包含四个 Skill:`penguin-sdk`(基于 SDK 构建 Agent/AI/RAG 应用,或经 Agent API 把程序接入 Agent;动手前先问用哪种方式)、`unified-llm-api`(通过 `@prismshadow/agenthub` 调用模型 API)、`penguin-config`(管理模型密钥、默认值和 Vault 机密)和 `penguin-orchestration`(在 shell 里驱动 Agent、Session、成本和定时任务) || | `model-development` | 在自己的硬件上做模型开发,包含三个 Skill:`llamafactory`(微调)、`ollama`(运行本地模型)和 `vllm`(在 OpenAI 兼容端点后面提供服务) || | `skill-porting` | 把外部来源(插件市场、skills.sh 注册表、GitHub 仓库或本地文件夹)的 Skill 经审查和规范化后移植到 Agent |diff --git a/plugins/README.md b/plugins/README.mdindex 9f7d9665..c8537415 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -9,7 +9,7 @@ Included plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins| Category | Plugins || --- | --- || Office Productivity | `data-analysis`, `use-firecrawl`, `use-offerdao`, `browser-automation`, `use-bento-slides`, `use-lieflat-charts`, `use-wps-office`, `use-seedance`, `use-seedream`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |-| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram`, `gpu-model-serving` |+| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram`, `gpu-model-serving`, `web-vscode` || AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` || Agent Company | `agent-company` |diff --git a/plugins/web-vscode/LICENSE b/plugins/web-vscode/LICENSEnew file mode 100644index 00000000..261eeb9e--- /dev/null+++ b/plugins/web-vscode/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/plugins/web-vscode/icon.svg b/plugins/web-vscode/icon.svgnew file mode 100644index 00000000..092061e4--- /dev/null+++ b/plugins/web-vscode/icon.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Web VS Code">+ <rect x="4" y="12" width="56" height="40" rx="5" fill="#2f6fed"/>+ <path d="M26 22 14 32l12 10z" fill="#eaf1ff"/>+ <path d="M34 44 50 22" fill="none" stroke="#eaf1ff" stroke-width="4" stroke-linecap="round"/>+ <circle cx="50" cy="47" r="9" fill="#0b3ea8"/>+ <path d="M45.5 47h9M50 42.5v9" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round"/>+</svg>diff --git a/plugins/web-vscode/package.json b/plugins/web-vscode/package.jsonnew file mode 100644index 00000000..d9cd790f--- /dev/null+++ b/plugins/web-vscode/package.json@@ -0,0 +1,24 @@+{+ "name": "@adelie/web-vscode",+ "version": "0.6.4",+ "description": "Stand up VS Code in the browser on a server and make it actually usable: code-server behind an HTTPS reverse proxy with a local certificate authority, verified end to end, with the certificate-trust steps for Windows, macOS, iOS and Android.",+ "license": "Apache-2.0",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/lmliheng/Adelie.git",+ "directory": "plugins/web-vscode"+ },+ "keywords": [+ "adelie-plugin",+ "penguin-harness"+ ],+ "files": [+ "plugin.json",+ "icon.svg",+ "skills",+ "LICENSE"+ ],+ "publishConfig": {+ "access": "public"+ }+}diff --git a/plugins/web-vscode/plugin.json b/plugins/web-vscode/plugin.jsonnew file mode 100644index 00000000..65822e01--- /dev/null+++ b/plugins/web-vscode/plugin.json@@ -0,0 +1,9 @@+{+ "description": "Stand up VS Code in the browser on a server and make it actually usable: code-server, an HTTPS reverse proxy with its own certificate authority, the certificate-trust steps for Windows, macOS, iOS and Android, and the checks that decide the install is done — including why a self-signed certificate clicked through in the browser still cannot run webviews.",+ "description_zh": "把 VS Code 装到服务器上做成能用的浏览器版本:code-server + 自带证书机构的 HTTPS 反向代理,配上 Windows/macOS/iOS/Android 的证书信任步骤,以及验收必须跑的三项检查——包括为什么「点继续前往」的自签证书仍然跑不了 webview。",+ "short_description": "VS Code in the browser: code-server, HTTPS proxy, trusted certificate, verified.",+ "short_description_zh": "浏览器版 VS Code:code-server + HTTPS 反代 + 证书信任 + 端到端验收。",+ "version": "2026.11.06.1",+ "category": "software-development",+ "preinstall": false+}diff --git a/plugins/web-vscode/skills/web-vscode/SKILL.md b/plugins/web-vscode/skills/web-vscode/SKILL.mdnew file mode 100644index 00000000..92b418cc--- /dev/null+++ b/plugins/web-vscode/skills/web-vscode/SKILL.md@@ -0,0 +1,129 @@+---+name: web-vscode+description: Stand up VS Code in the browser on a Linux server and make it actually usable — code-server bound to loopback, an HTTPS reverse proxy with its own certificate authority, the certificate-trust steps for Windows/macOS/iOS/Android, and the three checks that decide the install is done. Use whenever the task is to install, fix or verify a web VS Code (code-server) on a server, or when a browser shows the workbench but files, notebooks or webviews will not open.+---++# 浏览器版 VS Code(code-server + HTTPS 反代 + 本地证书机构)++`npm i -g code-server` 只装上了引擎。真正让人能用起来的是另外三件事,缺一个就会出现+「能登录、能看见文件树,但文件打不开」这种半死状态:++1. **必须是 HTTPS**。明文的 `http://<IP>:端口` 不是安全上下文,浏览器禁用 `crypto.subtle`,+ VS Code 的 webview 与 notebook 起不来。+2. **证书必须真的被设备信任**。浏览器对证书无效的源一律拒绝注册 Service Worker,所以+ 在警告页点「继续前往」也没用——webview 照样报 `Could not register service worker`。+3. **端口不能落在 Chrome 的危险段**(6665–6669),否则浏览器连请求都不发,直接+ `ERR_UNSAFE_PORT`。++这个插件把三件事一次做完:code-server 只听回环,反代在另一个端口终结 TLS,站点证书由+本机自签的 CA 签发,CA 可以下载后装进任何设备。++## Before you start++如果消息只是点名这个插件(比如「用 web-vscode」)而没有具体的事,先问清楚要做哪一件:+**装一台新的**、**修一台已经装坏的**、还是**只想知道现在为什么打不开**。有具体目标时先跑+`node scripts/install.mjs status`,它会告诉你安装目录、两个单元的状态、证书指纹和健康检查,+比从头猜快得多。++动手前的三个前提,缺哪个先问用户而不是自己造:++- 这台机器是不是 Linux + systemd,能不能拿到 root(拿不到就只能 `--no-systemd`,而且没有开机自启);+- 用户从哪台设备访问(Windows / macOS / iPhone / Android),装根证书的步骤完全不同;+- 中间有没有反向代理或防火墙。**公网 80 / 443 被云厂商封掉的机器,签不了 Let's Encrypt**,+ 只能用本机 CA 这条路。++## 这套东西由什么组成++| 部分 | 位置 | 说明 |+| --- | --- | --- |+| code-server | `127.0.0.1:6666` | 只监听回环;口令与 `disable-workspace-trust` 在 `<prefix>/config.yaml`(0600) |+| 反代 | `0.0.0.0:6766` | `https.createServer` + 同端口双协议:TLS 终结、WebSocket 直通、明文 301 跳 HTTPS |+| 证书 | `<prefix>/tls/{ca.crt,ca.key,cert.pem,key.pem}` | CA 十年,站点证书 825 天,SAN 是探测到的每个 IPv4 + `127.0.0.1` + `localhost` |+| 服务单元 | `web-vscode.service`、`web-vscode-proxy.service` | 一起 enable,反代 `After=web-vscode.service` |+| 默认前缀 | `/opt/web-vscode` | `--prefix` 可改 |++反代还提供两条固定路径:`/-/healthz`(自检用,返回 JSON)和 `/ca.crt`(根证书下载,+证书还没被信任时也能下)。++## 装++```bash+node scripts/install.mjs install # 默认 /opt/web-vscode,6666 → 6766+node scripts/install.mjs install --tls-port 8443 --workspace /srv/code+node scripts/install.mjs install --dry-run # 只打印将要做什么+```++装完脚本会自己等 `/-/healthz` 通过,并打印地址、口令、根证书路径。`code-server` 不在 PATH 里+时会 `npm install -g code-server`,国内机器加 `--npm-registry https://registry.npmmirror.com`。++想用真证书(有域名、能签 Let's Encrypt)时,不必让脚本管:把证书放到+`<prefix>/tls/cert.pem` 和 `key.pem`,不带 `--force` 重跑一次 install,脚本会沿用已有证书。++## 验(三项都要过)++```bash+# 1) 反代活着+curl -k https://127.0.0.1:6766/-/healthz++# 2) 证书链真的对(不跳过校验)+curl --cacert /opt/web-vscode/tls/ca.crt -o /dev/null -w '%{http_code}\n' https://<IP>:6766/login++# 3) 浏览器里:安全上下文 + Service Worker + 一个 notebook+```++第 3 项在浏览器控制台里跑,三条都成立才算装好:++```js+isSecureContext; // true+navigator.serviceWorker.controller !== null; // true(首屏之后刷新一次再问)+(await navigator.serviceWorker.getRegistration())?.active?.state; // "activated"+```++然后打开一个 `.ipynb`:**渲染成单元格**才算过。如果标签页里是一屏 JSON 文本+(`"cell_type": "code"`),是「受限模式」没关——`disable-workspace-trust` 没生效。++没有浏览器可用时,用无头 Chromium 也能验:把 `<prefix>/tls/ca.crt` 导入 NSS+(`certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n web-vscode -i ca.crt`),不带+`--ignore-certificate-errors` 启动,数 `.cell-list-container .cell` 的个数。+**用 `--ignore-certificate-errors` 验出来的成功不算数**:它模拟不了「证书未信任时+Service Worker 被拒」,而这正是要排除的失败。++## 让设备信任证书++先把 `https://<IP>:6766/ca.crt` 下载下来(这一步会先弹警告,点一次「继续前往」,文件能下,+但 webview 仍然不可用——所以才有下一步)。++- **Windows**:双击 `.crt` → 安装证书 → 本地计算机 → 将所有的证书放入下列存储 →+ 浏览 → **受信任的根证书颁发机构** → 完成。或者管理员命令行+ `certutil -addstore -f Root web-vscode-ca.crt`。+- **macOS**:双击导入「钥匙串访问」→ 系统钥匙串 → 找到 `Web VS Code Local CA` →+ 显示简介 → 信任 → 使用此证书时**始终信任**。+- **iPhone / iPad**:Safari 下载 → 设置 → 已下载描述文件 → 安装;装完**必须**再去+ 设置 → 通用 → 关于本机 → 证书信任设置,把开关打开。少这一步等于没装。+- **Android**:设置 → 安全 → 加密与凭据 → 安装证书 → CA 证书。++装完**把浏览器全部退出再打开**(Chrome 会把「证书有问题」的决定缓存到进程退出),+再访问就会是干净的 HTTPS,notebook 直接能开。++## 出事时看哪里++症状 → 原因 → 处理,见 [reference/pitfalls.md](reference/pitfalls.md)。最短版:++- `ERR_UNSAFE_PORT`:端口在 6665–6669,换端口。+- `Could not register service worker ... An SSL certificate error occurred`:证书没被信任。+- 打开 `.ipynb` 满屏 JSON:受限模式,检查 `disable-workspace-trust: true`。+- 能登录但不显示文件:`crypto.subtle` 不可用,你用的是明文 HTTP。++## 卸载++```bash+node scripts/install.mjs uninstall # 停服务、删单元,文件留着+node scripts/install.mjs uninstall --purge # 连 /opt/web-vscode 一起删+```++code-server 本体不会被卸(可能还有别的用途),要删自己 `npm rm -g code-server`。++## 参考资料++- [reference/pitfalls.md](reference/pitfalls.md):每个坑的症状、原因、判断命令。+- [reference/verify.md](reference/verify.md):验收清单与每种输出的合格判据。diff --git a/plugins/web-vscode/skills/web-vscode/reference/pitfalls.md b/plugins/web-vscode/skills/web-vscode/reference/pitfalls.mdnew file mode 100644index 00000000..2cd81ea7--- /dev/null+++ b/plugins/web-vscode/skills/web-vscode/reference/pitfalls.md@@ -0,0 +1,91 @@+# 坑:症状 → 原因 → 判断++每一条都是真事,按「你先看到什么」查。++## 1. 浏览器直接 `ERR_UNSAFE_PORT`,请求根本没发出去++**原因**:Chrome / Edge 把 6665–6669 列为危险端口(IRC 遗留),6666 正好在里面。+服务端日志一条记录都没有就是证据。++**判断**:`journalctl -k | grep 'UFW BLOCK' | grep DPT=6666` 没有输出,而 `ss -tlnp | grep 6666`+明明在监听——包压根没到。++**处理**:对外端口换到 6766(或任何不在黑名单里的)。这也是反代默认 6766 的原因。++## 2. `Could not register service worker: ... An SSL certificate error occurred when fetching the script`++**原因**:浏览器对**证书无效的源**一律拒绝注册 Service Worker,用户在警告页点+「高级 → 继续前往」只影响页面导航,不影响 SW 注册。而 VS Code 的 webview 和 notebook 都跑在+webview 的 SW 上,所以必然起不来。++**判断**:控制台里搜 `service worker`;`https://<IP>:<port>/ca.crt` 能下、但页面上+`navigator.serviceWorker.controller` 是 `null`。++**处理**:把 `<prefix>/tls/ca.crt` 装进设备的受信任根(iOS 还要单独打开「证书信任设置」)。+装完**退出浏览器进程**重开。别指望换浏览器能绕过——Safari、Firefox 一样拒绝。++## 3. 能用,但 `.ipynb` 打开的是一屏 JSON 文本++**原因**:工作区处于「受限模式」(Restricted Mode),Jupyter 扩展不激活,`.ipynb` 按纯文本+JSON 打开。1.9 MB 的 notebook 在编辑器里滚 JSON,看起来就像卡死。++**判断**:标签页底部有「受限模式」徽标;正文里能看到 `"cell_type": "code"`。++**处理**:`<prefix>/config.yaml` 里加 `disable-workspace-trust: true`,重启。+新版本的 code-server 也认 `--disable-workspace-trust`。装完记得真的开一个 notebook 确认+渲染成单元格,而不是只看到文件树。++## 4. 能登录、文件树正常,但文件点开是空白++**原因**:`crypto.subtle` 不可用——你走的是明文 HTTP,不是安全上下文。++**判断**:控制台报 `'crypto.subtle' is not available so webviews will not work`;+`isSecureContext` 为 `false`。++**处理**:用反代的 HTTPS 端口,不要用 code-server 的明文端口。除非走 SSH 隧道开+`http://localhost:<port>`——localhost 天然是安全上下文。++## 5. 签不了真证书:`Connection reset by peer` / `reader size limit exceeded`++**原因**:机器面对的公网 80 / 443 被云厂商封了(没有备案的国内 IP 很常见)。Let's Encrypt 的+HTTP-01 要从外网连回来的 80 端口,TLS-ALPN-01 要 443,两条都过不去。certbot standalone+也不支持 tls-alpn。++**判断**:`curl http://<IP>/.well-known/acme-challenge/<file>` 从外部节点测是 reset 或超时,+而同一台机器换个高端口(如 6766)从多国节点都在——说明封的是端口,不是机器。+`check-host.net` 的 `check-tcp` / `check-http` 免 key,可以直接从多个国家测。++**处理**:本机 CA + 设备信任,或者让用户给一个能配 DNS 的域名(DNS-01 不需要 80/443)。+nip.io / sslip.io 这类通配解析域名要先确认解析到的是本机 IP,再试一次。++## 6. 用 Cloudflare 快速隧道绕过证书,工作台能开、notebook 永远空白++**原因**:快速隧道(`cloudflared tunnel --url`)证书是真的、零警告,但实测两件事:+冷启动每个请求约 2 秒,而且 **webview 的 iframe 根本不生成**,扩展宿主还常报+`The remote extension host took longer than 60s to send its ready message`。++**判断**:`document.querySelectorAll('iframe')` 里只有 worker 那个,没有+`.../webview/browser/pre/index.html`;`.cell-list-container .cell` 数量恒为 0。++**处理**:别把它当入口,只当「临时看一眼文件树」。要零警告又稳定,只能真证书或本机 CA。++## 7. 装完 `status` 说健康检查失败++**排查顺序**:++1. `systemctl status web-vscode-proxy` —— 进程在不在,`server.js` 里的端口与证书路径对不对;+2. `ss -tlnp | grep <tls-port>` —— 端口有没有被别的进程占了;+3. `journalctl -u web-vscode` —— code-server 有没有起来(口令文件权限、`--config` 路径);+4. `curl -k https://127.0.0.1:<tls-port>/-/healthz` —— 反代本身活着就会返回 `{"ok":true}`,+ 活着但 `login` 502,说明是 code-server 那一段断了。++## 8. 证书明明装了,Chrome 还是报 `NET::ERR_CERT_AUTHORITY_INVALID`++**原因**:装到了「当前用户」而不是「本地计算机」,或者装完没有重启浏览器进程(Chrome 把证书+决定缓存在进程里,标签页刷新不管用)。++**判断**:`chrome://settings/certificates` → 「受信任的根证书颁发机构」里找+`Web VS Code Local CA`。找不到就是没装进去。++**处理**:按 SKILL.md 的步骤重装一次,然后**完全退出 Chrome**(任务管理器里没有 chrome.exe)+再打开。diff --git a/plugins/web-vscode/skills/web-vscode/reference/verify.md b/plugins/web-vscode/skills/web-vscode/reference/verify.mdnew file mode 100644index 00000000..da0066b2--- /dev/null+++ b/plugins/web-vscode/skills/web-vscode/reference/verify.md@@ -0,0 +1,65 @@+# 验收:每条命令的合格输出是什么++装完不等于能用。按顺序跑完这四项,前三项在服务器上,第四项必须真的开一个 notebook。++## 1. 反代活着++```bash+curl -sk https://127.0.0.1:6766/-/healthz+```++合格:`{"ok":true,"target":"127.0.0.1:6666","uptime":...}`。+返回 502 说明反代在、code-server 不在;连不上说明反代没起来(看+`journalctl -u web-vscode-proxy`)。++## 2. 证书链真的对(不要 `-k`)++```bash+curl --cacert /opt/web-vscode/tls/ca.crt -o /dev/null -w '%{http_code}\n' https://<公网IP>:6766/login+```++合格:`200`。报 `unable to get local issuer certificate` 说明站点证书不是这张 CA 签的+(`--force` 重装一次);报 `no alternative certificate subject name matches` 说明 SAN 里没有+这个 IP(安装时 `--ip <addr>` 补上)。++## 3. 页面真的是安全上下文++浏览器控制台,或者无头 Chromium:++```js+isSecureContext; // true+navigator.serviceWorker.controller !== null; // true(首屏后刷新一次)+(await navigator.serviceWorker.getRegistration())?.active?.state; // "activated"+```++合格:三条都对。任何一条不对,webview 一定失败,先修这里再看别的。++## 4. notebook 真的渲染成单元格++打开任意 `.ipynb`,合格是**看到单元格**(markdown 渲染、代码块带行号)。++无头 Chromium 的写法(把 CA 导入 NSS,**不要**用 `--ignore-certificate-errors`):++```bash+apt-get install -y libnss3-tools+certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "web-vscode" -i /opt/web-vscode/tls/ca.crt+```++```js+// 登录 → 等 .monaco-workbench → 双击文件树里的 notebook → 等 30s+document.querySelectorAll('.cell-list-container .cell, .notebook-editor .cell-editor-part').length+```++合格:大于 0(一个 12 单元格的 notebook 应返回 12)。+为 0 时先看 `document.querySelectorAll('iframe')` 里有没有 `webview/browser/pre/index.html`:+没有就是 Service Worker 没注册(回到第 3 项)。++**为什么不能用 `--ignore-certificate-errors` 验收**:它让浏览器接受任何证书,于是+「证书未信任 → SW 被拒」这条真实失败路径被跳过,测出来的成功在用户设备上不成立。++## 别忘了这两个端口++- code-server 的端口**只监听 127.0.0.1**:`ss -tlnp | grep <port>` 应该是 `127.0.0.1:<port>`,+ 不是 `0.0.0.0`。如果看到 `0.0.0.0`,说明有人手工启动过 code-server,把它停掉。+- 对外只放行反代端口:`ufw status | grep <tls-port>`。**不要**把 code-server 端口也放行——+ 明文入口既不能用 webview,还是唯一的弱口令面。diff --git a/plugins/web-vscode/skills/web-vscode/scripts/install.mjs b/plugins/web-vscode/skills/web-vscode/scripts/install.mjsnew file mode 100644index 00000000..48ac8bd7--- /dev/null+++ b/plugins/web-vscode/skills/web-vscode/scripts/install.mjs@@ -0,0 +1,584 @@+#!/usr/bin/env node+/**+ * web-vscode —— 把 VS Code 装到服务器上,并给出一个浏览器真正能用的入口。+ *+ * node install.mjs install # code-server + HTTPS 反代 + 本地证书机构+ * node install.mjs status # 现在是什么状态,链路上哪一段不通+ * node install.mjs uninstall # 停服务、删单元;--purge 连文件一起删+ * node install.mjs ca # 根证书在哪、指纹是什么+ *+ * 为什么不是一个 `npm i -g code-server` 就完事:+ * * 明文的 http://<IP>:端口 不是安全上下文,浏览器禁用 crypto.subtle,+ * VS Code 的 webview 与 notebook 直接报错,文件看起来「打不开」;+ * * Chrome/Edge 把 6665–6669 列为危险端口,6666 连请求都发不出去(ERR_UNSAFE_PORT);+ * * 浏览器对证书无效的源一律拒绝注册 Service Worker,点「继续前往」也救不了 webview,+ * 所以证书必须真的被设备信任。+ * 这个脚本把这三件事一次性处理掉:code-server 只监听回环,反代在另一个端口终结 TLS,+ * 证书由本机自己签的 CA 签发,CA 可以下载后装进设备。+ *+ * 用法与选项见 `node install.mjs help`。+ */+import { execFileSync } from "node:child_process";+import { randomBytes } from "node:crypto";+import fs from "node:fs";+import https from "node:https";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const PROXY_TEMPLATE = path.join(HERE, "proxy-server.js");++const SERVICE_CODE = "web-vscode.service";+const SERVICE_PROXY = "web-vscode-proxy.service";++const DEFAULTS = {+ prefix: "/opt/web-vscode",+ port: 6666,+ tlsPort: 6766,+ workspace: null,+};++let step = 0;+const info = (msg) => console.log(` ${msg}`);+const ok = (msg) => console.log(`✓ ${msg}`);+const warn = (msg) => console.log(`! ${msg}`);+const fail = (msg) => {+ throw new Error(msg);+};++function parseArgv(argv) {+ const opts = { _: [] };+ const alias = { t: "--tls-port", p: "--port" };+ for (let i = 0; i < argv.length; i++) {+ let a = argv[i];+ if (alias[a]) a = alias[a];+ if (a === "--help" || a === "-h") {+ opts.help = true;+ continue;+ }+ if (a.startsWith("--")) {+ const [rawKey, inline] = a.slice(2).split("=");+ const key = rawKey.replace(/-([a-z])/g, (_, c) => c.toUpperCase());+ if (inline !== undefined) {+ opts[key] = inline;+ } else if (argv[i + 1] && !argv[i + 1].startsWith("-")) {+ opts[key] = argv[++i];+ } else {+ opts[key] = true;+ }+ continue;+ }+ opts._.push(a);+ }+ return opts;+}++const HELP = `web-vscode —— 浏览器版 VS Code 的安装器++ node install.mjs install [选项] 安装并启动(默认 /opt/web-vscode)+ node install.mjs status 查看服务、端口、证书与健康检查+ node install.mjs uninstall [--purge] 停止并移除服务单元;--purge 连目录一起删+ node install.mjs ca [--export <文件>] 打印根证书路径/指纹,可导出后拷到设备++install 选项+ --prefix <dir> 安装目录(默认 /opt/web-vscode)+ --port <n> code-server 端口,只监听 127.0.0.1(默认 6666)+ --tls-port <n> 对外 HTTPS 端口(默认 6766;别用 6665–6669,Chrome 会拦)+ --password <str> 登录口令(默认随机生成并写在 config.yaml)+ --ip <addr> 追加证书 SAN,可重复或逗号分隔;默认自动探测本机 IPv4+ --workspace <dir> code-server 打开的目录(默认当前用户 home)+ --no-systemd 不起 systemd 单元,改成后台进程(无 systemd 或无 root 时用)+ --npm-registry <url> 装 code-server 时使用的 npm 源(国内可用 npmmirror)+ --dry-run 只打印将要做什么+ --force 重新生成证书与配置(已存在的真证书默认保留)+`;++function sh(cmd, args, opts = {}) {+ // stdio: 'ignore' 时 execFileSync 返回 null,所以统一兜一层+ const out = execFileSync(cmd, args, { encoding: "utf8", ...opts });+ return (out ?? "").toString().trim();+}++function trySh(cmd, args, opts = {}) {+ try {+ return sh(cmd, args, opts);+ } catch {+ return null;+ }+}++const which = (bin) => trySh("which", [bin]);+const isRoot = () => typeof process.getuid === "function" && process.getuid() === 0;++function writeFile(file, content, mode) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ if (mode) fs.chmodSync(file, mode);+}++function localIPv4() {+ const out = [];+ for (const entries of Object.values(os.networkInterfaces())) {+ for (const e of entries ?? []) {+ if (e.family === "IPv4" && !e.internal) out.push(e.address);+ }+ }+ return out;+}++function certFingerprint(file) {+ const out = trySh("openssl", ["x509", "-in", file, "-noout", "-fingerprint", "-sha256"]);+ return out ? out.split("=")[1] : null;+}++// ---------------------------------------------------------------- certificates++function createCertificates(tlsDir, ips, { force }) {+ fs.mkdirSync(tlsDir, { recursive: true });+ const ca = path.join(tlsDir, "ca.crt");+ const caKey = path.join(tlsDir, "ca.key");+ const cert = path.join(tlsDir, "cert.pem");+ const key = path.join(tlsDir, "key.pem");++ const haveLeaf = fs.existsSync(cert) && fs.existsSync(key);+ if (haveLeaf && !force) {+ if (!fs.existsSync(ca)) fail(`${cert} 存在但缺少 ${ca}:要么补上 CA,要么 --force 重新生成`);+ return { ca, cert, key, generated: false };+ }++ if (!which("openssl")) fail("缺少 openssl:apt-get install -y openssl");++ const san = [...new Set(["127.0.0.1", ...ips])].map((ip) => `IP:${ip}`).concat("DNS:localhost");+ if (!fs.existsSync(ca) || force) {+ sh("openssl", ["genrsa", "-out", caKey, "2048"], { stdio: "ignore" });+ sh(+ "openssl",+ [+ "req",+ "-x509",+ "-new",+ "-nodes",+ "-key",+ caKey,+ "-sha256",+ "-days",+ "3650",+ "-out",+ ca,+ "-subj",+ "/CN=Web VS Code Local CA/O=web-vscode",+ "-addext",+ "basicConstraints=critical,CA:TRUE",+ "-addext",+ "keyUsage=critical,keyCertSign,cRLSign",+ ],+ { stdio: "ignore" },+ );+ fs.chmodSync(caKey, 0o600);+ }++ const csr = path.join(tlsDir, "leaf.csr");+ const ext = path.join(tlsDir, "leaf.ext");+ writeFile(+ ext,+ [+ "basicConstraints=CA:FALSE",+ "keyUsage=critical,digitalSignature,keyEncipherment",+ "extendedKeyUsage=serverAuth",+ `subjectAltName=${san.join(",")}`,+ "",+ ].join("\n"),+ );+ sh(+ "openssl",+ [+ "req",+ "-new",+ "-nodes",+ "-newkey",+ "rsa:2048",+ "-keyout",+ key,+ "-out",+ csr,+ "-subj",+ `/CN=${ips[0] ?? "127.0.0.1"}`,+ ],+ { stdio: "ignore" },+ );+ sh(+ "openssl",+ [+ "x509",+ "-req",+ "-in",+ csr,+ "-CA",+ ca,+ "-CAkey",+ caKey,+ "-CAcreateserial",+ "-days",+ "825",+ "-sha256",+ "-extfile",+ ext,+ "-out",+ cert,+ ],+ { stdio: "ignore" },+ );+ fs.rmSync(csr, { force: true });+ fs.rmSync(ext, { force: true });+ fs.chmodSync(key, 0o600);+ return { ca, cert, key, generated: true };+}++// ---------------------------------------------------------------- install++function unitCodeServer(prefix, port, workspace) {+ const bin = which("code-server") ?? "/usr/local/bin/code-server";+ return `[Unit]+Description=Web VS Code (code-server on 127.0.0.1:${port})+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+ExecStart=${bin} --config ${path.join(prefix, "config.yaml")} ${workspace}+Restart=always+RestartSec=3+Environment=HOME=${os.homedir()}++[Install]+WantedBy=multi-user.target+`;+}++function unitProxy(prefix, tlsPort) {+ return `[Unit]+Description=Web VS Code HTTPS front door (:${tlsPort} -> 127.0.0.1)+After=network-online.target ${SERVICE_CODE}+Wants=network-online.target++[Service]+Type=simple+ExecStart=${process.execPath} ${path.join(prefix, "proxy", "server.js")}+Restart=always+RestartSec=3++[Install]+WantedBy=multi-user.target+`;+}++function healthCheck(tlsPort, timeoutMs = 60_000) {+ const deadline = Date.now() + timeoutMs;+ return new Promise((resolve) => {+ const probe = () => {+ const req = https.get(+ {+ host: "127.0.0.1",+ port: tlsPort,+ path: "/-/healthz",+ rejectUnauthorized: false,+ timeout: 3000,+ },+ (res) => {+ res.resume();+ if (res.statusCode === 200) return resolve(true);+ retry();+ },+ );+ req.on("error", retry);+ req.on("timeout", () => {+ req.destroy();+ retry();+ });+ function retry() {+ if (Date.now() > deadline) return resolve(false);+ setTimeout(probe, 1000);+ }+ };+ probe();+ });+}++async function install(opts) {+ const prefix = path.resolve(opts.prefix || DEFAULTS.prefix);+ const port = Number(opts.port || DEFAULTS.port);+ const tlsPort = Number(opts.tlsPort || DEFAULTS.tlsPort);+ const workspace = path.resolve(opts.workspace || os.homedir());+ const useSystemd = !opts.noSystemd;+ const dry = Boolean(opts.dryRun);+ const force = Boolean(opts.force);++ if (process.platform !== "linux")+ fail(`这个安装器只处理 Linux + systemd;当前是 ${process.platform}`);+ if (!Number.isInteger(port) || port < 1 || port > 65535) fail(`--port 不合法:${opts.port}`);+ if (!Number.isInteger(tlsPort) || tlsPort < 1 || tlsPort > 65535)+ fail(`--tls-port 不合法:${opts.tlsPort}`);+ if (port === tlsPort) fail("--port 与 --tls-port 不能相同");+ if (useSystemd && !isRoot()) fail("起 systemd 单元需要 root;或者加 --no-systemd 用后台进程");+ if (tlsPort >= 6665 && tlsPort <= 6669)+ warn(`${tlsPort} 落在 Chrome 的危险端口段 6665–6669,浏览器会 ERR_UNSAFE_PORT`);++ console.log(`\nweb-vscode 安装到 ${prefix}(code-server :${port} → HTTPS :${tlsPort})\n`);++ const steps = [];+ const planned = (msg) => (dry ? info(`将执行:${msg}`) : (steps.push(msg), ok(msg)));++ // 1. code-server+ let bin = which("code-server");+ if (bin) {+ ok(`code-server 已安装:${bin}`);+ } else {+ const registry = opts.npmRegistry ? ["--registry", String(opts.npmRegistry)] : [];+ planned(`npm install -g code-server ${registry.join(" ")}`);+ if (!dry) {+ execFileSync("npm", ["install", "-g", "code-server", ...registry], { stdio: "inherit" });+ bin = which("code-server");+ if (!bin) fail("npm 装完仍找不到 code-server,请检查 npm 全局 bin 是否在 PATH 里");+ }+ }++ // 2. 目录 + 配置+ const tlsDir = path.join(prefix, "tls");+ const password = opts.password ? String(opts.password) : randomBytes(9).toString("hex");+ if (!dry) {+ fs.mkdirSync(path.join(prefix, "proxy"), { recursive: true });+ fs.mkdirSync(path.join(prefix, "logs"), { recursive: true });+ fs.mkdirSync(path.join(prefix, "run"), { recursive: true });+ writeFile(+ path.join(prefix, "config.yaml"),+ [+ `bind-addr: 127.0.0.1:${port}`,+ "auth: password",+ `password: ${password}`,+ "cert: false",+ "disable-telemetry: true",+ // 受限模式下 Jupyter 不会激活,.ipynb 只会被当成 JSON 文本打开+ "disable-workspace-trust: true",+ "disable-update-check: true",+ "",+ ].join("\n"),+ 0o600,+ );+ ok(`配置写入 ${path.join(prefix, "config.yaml")}(0600)`);+ } else {+ info(`将写入 ${path.join(prefix, "config.yaml")}(口令、只监听 127.0.0.1:${port})`);+ }++ // 3. 证书+ const ips = (Array.isArray(opts.ip) ? opts.ip : opts.ip ? String(opts.ip).split(",") : [])+ .map((s) => s.trim())+ .filter(Boolean);+ const allIps = [...new Set([...ips, ...localIPv4()])].filter((ip) =>+ /^\d+\.\d+\.\d+\.\d+$/.test(ip),+ );+ let certs = { ca: path.join(tlsDir, "ca.crt"), generated: false };+ if (dry) {+ info(`将生成根 CA + 站点证书,SAN: ${[...new Set(["127.0.0.1", ...allIps])].join(", ")}`);+ } else {+ certs = createCertificates(tlsDir, allIps, { force });+ ok(+ certs.generated+ ? `证书已生成:根 CA ${certs.ca},站点证书 SAN ${[...new Set(["127.0.0.1", ...allIps])].join(", ")}`+ : `沿用已有证书 ${certs.cert}(--force 可重新生成)`,+ );+ }++ // 4. 反代+ if (dry) {+ info(`将写入 ${path.join(prefix, "proxy", "server.js")}`);+ } else {+ const template = fs.readFileSync(PROXY_TEMPLATE, "utf8");+ writeFile(+ path.join(prefix, "proxy", "server.js"),+ template+ .replaceAll("__LISTEN_PORT__", String(tlsPort))+ .replaceAll("__TARGET_PORT__", String(port))+ .replaceAll("__TLS_DIR__", JSON.stringify(tlsDir)),+ 0o644,+ );+ ok(`反代写入 ${path.join(prefix, "proxy", "server.js")}`);+ }++ // 5. 起服务+ if (useSystemd) {+ if (dry) {+ info(`将写入 /etc/systemd/system/${SERVICE_CODE} 与 ${SERVICE_PROXY},并 enable --now`);+ } else {+ const unitDir = "/etc/systemd/system";+ writeFile(path.join(unitDir, SERVICE_CODE), unitCodeServer(prefix, port, workspace), 0o644);+ writeFile(path.join(unitDir, SERVICE_PROXY), unitProxy(prefix, tlsPort), 0o644);+ sh("systemctl", ["daemon-reload"]);+ sh("systemctl", ["enable", "--now", SERVICE_CODE, SERVICE_PROXY]);+ ok(`systemd 单元已启用:${SERVICE_CODE} ${SERVICE_PROXY}`);+ }+ } else {+ const runner = path.join(prefix, "run");+ const logs = path.join(prefix, "logs");+ if (dry) {+ info(`将在后台启动 code-server 与 node proxy/server.js,日志在 ${logs}`);+ } else {+ const { spawn } = await import("node:child_process");+ const start = (name, cmd, args) => {+ const out = fs.openSync(path.join(logs, `${name}.log`), "a");+ const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out] });+ child.unref();+ writeFile(path.join(runner, `${name}.pid`), `${child.pid}\n`);+ return child.pid;+ };+ const pidCode = start("code-server", "code-server", [+ "--config",+ path.join(prefix, "config.yaml"),+ workspace,+ ]);+ await new Promise((r) => setTimeout(r, 1500));+ const pidProxy = start("proxy", process.execPath, [path.join(prefix, "proxy", "server.js")]);+ ok(`后台进程已启动:code-server pid ${pidCode},proxy pid ${pidProxy}`);+ }+ }++ // 6. 防火墙+ if (!dry && isRoot()) {+ const ufw = trySh("ufw", ["status"]);+ if (ufw && /Status:\s*active/i.test(ufw)) {+ sh("ufw", ["allow", `${tlsPort}/tcp`]);+ ok(`ufw 已放行 ${tlsPort}/tcp`);+ }+ }++ // 7. 自检+ if (!dry) {+ const healthy = await healthCheck(tlsPort);+ if (healthy) {+ ok(`自检通过:https://127.0.0.1:${tlsPort}/-/healthz`);+ } else {+ warn(`反代在 60 秒内没有响应,看日志:journalctl -u ${SERVICE_PROXY}(或 ${prefix}/logs)`);+ process.exitCode = 1;+ }+ }++ const hosts = [...new Set([...allIps, "127.0.0.1"])];+ console.log(`\n完成。\n`);+ for (const h of hosts) console.log(` 地址 https://${h}:${tlsPort}/`);+ console.log(` 口令 ${dry ? "(随机生成)" : password}`);+ console.log(` 根证书 ${path.join(tlsDir, "ca.crt")}`);+ console.log(+ ` 下载 https://${hosts[0]}:${tlsPort}/ca.crt(先点一次「继续前往」才下得下来)`,+ );+ console.log(`\n下一步:把根证书装进要访问的设备,否则 webview 与 notebook 一定起不来——`);+ console.log(` 浏览器对证书无效的源一律拒绝注册 Service Worker,点「继续前往」不算数。`);+ console.log(` 装法见 skills/web-vscode/reference/pitfalls.md,或跑 node install.mjs ca。\n`);+}++// ---------------------------------------------------------------- status / ca / uninstall++async function status(opts) {+ const prefix = path.resolve(opts.prefix || DEFAULTS.prefix);+ const configFile = path.join(prefix, "config.yaml");+ const config = fs.existsSync(configFile) ? fs.readFileSync(configFile, "utf8") : "";+ const port = /bind-addr:\s*127\.0\.0\.1:(\d+)/.exec(config)?.[1];+ const tlsPort = (() => {+ const p = path.join(prefix, "proxy", "server.js");+ if (!fs.existsSync(p)) return null;+ return /const LISTEN_PORT = (\d+)/.exec(fs.readFileSync(p, "utf8"))?.[1];+ })();++ console.log(`安装目录 ${fs.existsSync(prefix) ? prefix : "(不存在)"}`);+ if (port) console.log(`code-server 127.0.0.1:${port}`);+ if (tlsPort) console.log(`HTTPS :${tlsPort}`);+ for (const unit of [SERVICE_CODE, SERVICE_PROXY]) {+ const state = trySh("systemctl", ["is-active", unit]) ?? "not-found";+ console.log(`${unit} ${state}`);+ }+ const ca = path.join(prefix, "tls", "ca.crt");+ if (fs.existsSync(ca)) {+ console.log(`根证书 ${ca}`);+ console.log(`指纹 ${certFingerprint(ca)}`);+ }+ if (tlsPort) {+ const healthy = await healthCheck(Number(tlsPort), 4000);+ console.log(`健康检查 ${healthy ? "通过" : "失败"}`);+ }+}++function ca(opts) {+ const prefix = path.resolve(opts.prefix || DEFAULTS.prefix);+ const file = path.join(prefix, "tls", "ca.crt");+ if (!fs.existsSync(file)) fail(`找不到 ${file}`);+ if (opts.export) {+ fs.copyFileSync(file, path.resolve(String(opts.export)));+ ok(`已导出到 ${path.resolve(String(opts.export))}`);+ }+ console.log(`路径 ${file}`);+ console.log(`指纹 ${certFingerprint(file)}`);+ const tlsPort = (() => {+ const p = path.join(prefix, "proxy", "server.js");+ return fs.existsSync(p)+ ? /const LISTEN_PORT = (\d+)/.exec(fs.readFileSync(p, "utf8"))?.[1]+ : null;+ })();+ if (tlsPort) console.log(`下载 https://<本机IP>:${tlsPort}/ca.crt`);+}++function uninstall(opts) {+ const prefix = path.resolve(opts.prefix || DEFAULTS.prefix);+ for (const unit of [SERVICE_PROXY, SERVICE_CODE]) {+ if (trySh("systemctl", ["is-enabled", unit]) !== null) {+ trySh("systemctl", ["disable", "--now", unit]);+ fs.rmSync(`/etc/systemd/system/${unit}`, { force: true });+ ok(`已停止并删除 ${unit}`);+ }+ }+ trySh("systemctl", ["daemon-reload"]);+ const runDir = path.join(prefix, "run");+ if (fs.existsSync(runDir)) {+ for (const f of fs.readdirSync(runDir).filter((f) => f.endsWith(".pid"))) {+ const pid = Number(fs.readFileSync(path.join(runDir, f), "utf8").trim());+ if (pid) {+ try {+ process.kill(pid, "SIGTERM");+ ok(`已结束 pid ${pid}(${f})`);+ } catch {+ warn(`pid ${pid} 已经不在了`);+ }+ }+ }+ }+ if (opts.purge) {+ fs.rmSync(prefix, { recursive: true, force: true });+ ok(`已删除 ${prefix}`);+ } else {+ info(`文件保留在 ${prefix},要一起删就加 --purge`);+ }+}++// ---------------------------------------------------------------- main++const opts = parseArgv(process.argv.slice(2));+const command = opts._[0] ?? "help";++try {+ if (opts.help || command === "help") {+ console.log(HELP);+ } else if (command === "install") {+ await install(opts);+ } else if (command === "status") {+ await status(opts);+ } else if (command === "ca") {+ ca(opts);+ } else if (command === "uninstall") {+ uninstall(opts);+ } else {+ console.error(`未知命令 ${command}\n`);+ console.log(HELP);+ process.exit(2);+ }+} catch (e) {+ console.error(`\n✗ ${e instanceof Error ? e.message : String(e)}\n`);+ process.exit(1);+}diff --git a/plugins/web-vscode/skills/web-vscode/scripts/proxy-server.js b/plugins/web-vscode/skills/web-vscode/scripts/proxy-server.jsnew file mode 100644index 00000000..6bae7b9b--- /dev/null+++ b/plugins/web-vscode/skills/web-vscode/scripts/proxy-server.js@@ -0,0 +1,148 @@+// <prefix>/proxy/server.js —— 由 @adelie/web-vscode 安装器生成,可自由修改,重装会覆盖。+//+// 一个端口同时承担两件事:+// * TLS 终结并反代到本机 code-server(含 WebSocket 升级,终端/扩展宿主/文件监听都靠它);+// * 明文请求一律 301 跳到 HTTPS —— 明文是「不安全上下文」,浏览器的 crypto.subtle 会被禁用,+// VS Code 的 webview 与 notebook 直接起不来。+//+// 占位符由安装器替换:__LISTEN_PORT__ __TARGET_PORT__ __TLS_DIR__+const fs = require("node:fs");+const net = require("node:net");+const http = require("node:http");+const https = require("node:https");+const path = require("node:path");++const LISTEN_PORT = __LISTEN_PORT__;+const TARGET_HOST = "127.0.0.1";+const TARGET_PORT = __TARGET_PORT__;+const TLS_DIR = __TLS_DIR__;++const log = (msg) => console.log(`${new Date().toISOString()} ${msg}`);++function sendCa(res) {+ fs.readFile(path.join(TLS_DIR, "ca.crt"), (err, data) => {+ if (err) {+ res.writeHead(404, { "Content-Type": "text/plain" });+ res.end("ca.crt not found");+ return;+ }+ res.writeHead(200, {+ "Content-Type": "application/x-x509-ca-cert",+ "Content-Disposition": 'attachment; filename="web-vscode-ca.crt"',+ "Content-Length": data.length,+ });+ res.end(data);+ });+}++function handleRequest(req, res) {+ const started = Date.now();+ const from = (req.socket.remoteAddress || "").replace("::ffff:", "");+ const url = req.url.split("?")[0];++ res.on("finish", () => {+ const ms = Date.now() - started;+ // 静态资源只在慢或出错时记一行,否则日志会被几百个 chunk 淹没+ const isAsset = url.startsWith("/static/") || url.startsWith("/stable-");+ if (!isAsset || res.statusCode >= 400 || ms > 5000)+ log(`${from} ${req.method} ${url} -> ${res.statusCode} ${ms}ms`);+ });++ // 根证书:证书还没被信任时也要能下载,所以这条路不需要可信任的 TLS+ if (url === "/ca.crt" || url === "/ca.cer") {+ sendCa(res);+ return;+ }+ if (url === "/-/healthz") {+ const body = JSON.stringify({+ ok: true,+ target: `${TARGET_HOST}:${TARGET_PORT}`,+ uptime: process.uptime(),+ });+ res.writeHead(200, {+ "Content-Type": "application/json",+ "Content-Length": Buffer.byteLength(body),+ });+ res.end(body);+ return;+ }++ const proxyReq = http.request(+ {+ host: TARGET_HOST,+ port: TARGET_PORT,+ method: req.method,+ path: req.url,+ headers: { ...req.headers, "x-forwarded-proto": "https" },+ },+ (proxyRes) => {+ res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);+ proxyRes.pipe(res);+ },+ );+ proxyReq.on("error", (e) => {+ log(`${from} ${req.method} ${url} 上游错误: ${e.code || e.message}`);+ if (!res.headersSent) res.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" });+ res.end(`bad gateway: code-server(127.0.0.1:${TARGET_PORT}) is not responding\n`);+ });+ req.pipe(proxyReq);+}++// WebSocket 升级:把握手原样转给上游,之后两条流直接对接+function handleUpgrade(req, socket, head) {+ const from = (socket.remoteAddress || "").replace("::ffff:", "");+ log(`${from} ws ${req.url.split("?")[0]}`);+ const upstream = net.connect(TARGET_PORT, TARGET_HOST, () => {+ const lines = [`${req.method} ${req.url} HTTP/1.1`];+ for (const [k, v] of Object.entries(req.headers)) lines.push(`${k}: ${v}`);+ upstream.write(`${lines.join("\r\n")}\r\n\r\n`);+ if (head && head.length) upstream.write(head);+ socket.pipe(upstream);+ upstream.pipe(socket);+ });+ upstream.on("error", (e) => {+ log(`${from} ws 上游错误 ${e.code || e.message}`);+ socket.destroy();+ });+ socket.on("error", () => upstream.destroy());+}++const tlsServer = https.createServer(+ {+ key: fs.readFileSync(path.join(TLS_DIR, "key.pem")),+ cert: fs.readFileSync(path.join(TLS_DIR, "cert.pem")),+ },+ handleRequest,+);+tlsServer.on("upgrade", handleUpgrade);+tlsServer.on("tlsClientError", () => {}); // 扫描器/明文误连不打日志++const plainServer = http.createServer((req, res) => {+ const url = req.url.split("?")[0];+ if (url === "/ca.crt" || url === "/ca.cer") {+ sendCa(res);+ return;+ }+ const host = (req.headers.host || "localhost").replace(/:\d+$/, "");+ log(`${req.socket.remoteAddress} plain ${url} -> 301`);+ res.writeHead(301, { Location: `https://${host}:${LISTEN_PORT}${req.url}` });+ res.end(`use https://${host}:${LISTEN_PORT}${req.url}\n`);+});++// 同端口双协议:TLS 握手的第一个字节是 0x16,其余当明文+net+ .createServer((socket) => {+ socket.once("data", (buf) => {+ socket.pause();+ socket.unshift(buf);+ if (buf[0] === 0x16) tlsServer.emit("connection", socket);+ else plainServer.emit("connection", socket);+ process.nextTick(() => socket.resume());+ });+ socket.on("error", () => socket.destroy());+ })+ .listen(LISTEN_PORT, "0.0.0.0", () => {+ log(+ `https://0.0.0.0:${LISTEN_PORT} -> http://${TARGET_HOST}:${TARGET_PORT}(明文 301 跳 HTTPS,WebSocket 直通)`,+ );+ });diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 026d2941..2b6d9b35 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -138,6 +138,9 @@ importers:'@adelie/use-wps-office':specifier: workspace:*version: link:../../plugins/use-wps-office+ '@adelie/web-vscode':+ specifier: workspace:*+ version: link:../../plugins/web-vscode'@adelie/wechat-miniprogram':specifier: workspace:*version: link:../../plugins/wechat-miniprogram@@ -247,6 +250,9 @@ importers:'@adelie/use-wps-office':specifier: workspace:*version: link:../../plugins/use-wps-office+ '@adelie/web-vscode':+ specifier: workspace:*+ version: link:../../plugins/web-vscode'@adelie/wechat-miniprogram':specifier: workspace:*version: link:../../plugins/wechat-miniprogram@@ -362,6 +368,9 @@ importers:'@adelie/use-wps-office':specifier: workspace:*version: link:../../plugins/use-wps-office+ '@adelie/web-vscode':+ specifier: workspace:*+ version: link:../../plugins/web-vscode'@adelie/wechat-miniprogram':specifier: workspace:*version: link:../../plugins/wechat-miniprogram@@ -864,6 +873,8 @@ importers:plugins/use-wps-office: {}+ plugins/web-vscode: {}+plugins/wechat-miniprogram: {}packages:@@ -957,6 +968,9 @@ packages:'@adelie/use-wps-office@file:plugins/use-wps-office':resolution: {directory: plugins/use-wps-office, type: directory}+ '@adelie/web-vscode@file:plugins/web-vscode':+ resolution: {directory: plugins/web-vscode, type: directory}+'@adelie/wechat-miniprogram@file:plugins/wechat-miniprogram':resolution: {directory: plugins/wechat-miniprogram, type: directory}@@ -4996,6 +5010,7 @@ snapshots:'@adelie/use-seedance': file:plugins/use-seedance'@adelie/use-seedream': file:plugins/use-seedream'@adelie/use-wps-office': file:plugins/use-wps-office+ '@adelie/web-vscode': file:plugins/web-vscode'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram'@modelcontextprotocol/client': 2.0.0'@prismshadow/agenthub': 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])@@ -5039,6 +5054,7 @@ snapshots:'@adelie/use-seedance': file:plugins/use-seedance'@adelie/use-seedream': file:plugins/use-seedream'@adelie/use-wps-office': file:plugins/use-wps-office+ '@adelie/web-vscode': file:plugins/web-vscode'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram'@modelcontextprotocol/client': 2.0.0'@prismshadow/agenthub': 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])@@ -5078,6 +5094,7 @@ snapshots:'@adelie/use-seedance': file:plugins/use-seedance'@adelie/use-seedream': file:plugins/use-seedream'@adelie/use-wps-office': file:plugins/use-wps-office+ '@adelie/web-vscode': file:plugins/web-vscode'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram'@modelcontextprotocol/client': 2.0.0'@prismshadow/agenthub': 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])([email protected])@@ -5195,6 +5212,8 @@ snapshots:'@adelie/use-wps-office@file:plugins/use-wps-office': {}+ '@adelie/web-vscode@file:plugins/web-vscode': {}+'@adelie/wechat-miniprogram@file:plugins/wechat-miniprogram': {}'@ampproject/[email protected]':