diff --git a/external_plugins/cc-browser-bridge/.zcode-plugin/plugin.json b/external_plugins/cc-browser-bridge/.zcode-plugin/plugin.json new file mode 100644 index 00000000..0662482c --- /dev/null +++ b/external_plugins/cc-browser-bridge/.zcode-plugin/plugin.json @@ -0,0 +1,31 @@ +{ + "name": "cc-browser-bridge", + "version": "0.6.0-rc.2", + "description": "Connect ZCode to your existing Chrome session for page reading, screenshots, and browser actions through a local MCP bridge.", + "description_i18n": { + "en": "Connect ZCode to your existing Chrome session for page reading, screenshots, and browser actions through a local MCP bridge.", + "zh-CN": "让 ZCode 通过本地 MCP 桥接连接日常 Chrome,保留登录态,读取网页、截图、点击和填写表单。" + }, + "author": { + "name": "lihytaihe-lang", + "url": "https://github.com/lihytaihe-lang" + }, + "license": "Apache-2.0", + "keywords": [ + "browser", + "chrome", + "mcp", + "automation", + "local-first" + ], + "mcpServers": { + "cc-browser": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/server/mcp-stdio.js" + ] + } + }, + "commands": "./commands" +} diff --git a/external_plugins/cc-browser-bridge/LICENSE b/external_plugins/cc-browser-bridge/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/external_plugins/cc-browser-bridge/LICENSE @@ -0,0 +1,202 @@ + + 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/external_plugins/cc-browser-bridge/NOTICE b/external_plugins/cc-browser-bridge/NOTICE new file mode 100644 index 00000000..4d8ba3ef --- /dev/null +++ b/external_plugins/cc-browser-bridge/NOTICE @@ -0,0 +1,5 @@ +Browser Bridge +Copyright 2026 lihytaihe-lang + +Original Browser Bridge source, documentation, and icons are licensed under Apache-2.0. +The bundled ws source remains under its MIT license; see THIRD_PARTY_NOTICES.md. diff --git a/external_plugins/cc-browser-bridge/README.md b/external_plugins/cc-browser-bridge/README.md new file mode 100644 index 00000000..1fa61ee7 --- /dev/null +++ b/external_plugins/cc-browser-bridge/README.md @@ -0,0 +1,55 @@ +# Browser Bridge + +[中文](README_CN.md) + +Browser Bridge connects ZCode to the Chrome session you already use. Its 15 MCP tools can list tabs, read page text, take screenshots, navigate, click, scroll, type, and run page JavaScript while keeping your existing sign-in state. Version **0.6.0-rc.2** is a community release candidate. + +## Requirements and installation + +- Node.js 18 or newer must be available as `node` on the client's PATH. +- Google Chrome 116 or newer. The extension uses Manifest V3. +- No separate model account, API key, paid service, or Chrome remote-debugging flag is required by the plugin. ZCode uses the model/provider configured by its user. + +1. Install and enable **Browser Bridge** in ZCode's plugin marketplace, then start a new session. If the submission is still under review, use a locally built marketplace from this repository instead of assuming it is publicly available. +2. On activation, the plugin prepares a loopback bridge and a stable extension folder. When the extension has not connected and the guide has never been shown, a setup page opens once. You can open it explicitly with `/cc-browser-setup`. +3. In Chrome, open `chrome://extensions`, enable **Developer mode**, and choose **Load unpacked**. Select the extension directory shown by the guide, normally `~/.browser-bridge/extension`. On Windows this is `%USERPROFILE%\.browser-bridge\extension`. On macOS, use Cmd+Shift+G in the file picker to paste the path; on Windows, use the address bar or Ctrl+L. +4. Wait for the extension's connected indicator. In ZCode, ask: **List the tabs in my Chrome browser.** A real tool response confirms the client-to-browser path. A connected setup page alone does not confirm the client call. + +The extension is supplied as source and is **not installed automatically** or listed by this submission in the Chrome Web Store. A successful guide opening is remembered separately from user completion. New sessions, elapsed time, and version changes do not reopen an already shown guide. An already connected extension also suppresses automatic opening. Failed opening attempts use bounded retry backoff. `/cc-browser-setup` always permits an explicit retry. + +## Examples and controls + +- “Read the current page and summarize it.” +- “Take a screenshot of the current tab.” +- “Fill this form, then wait for me to approve submission.” + +The extension popup shows connection status and lets you edit the bridge address or pause browser control. Pausing is never automatically reversed. Browser actions use your signed-in session and can change real websites; ask the agent to wait for your confirmation before submitting forms, sending messages, buying, or deleting. The plugin does not add an independent confirmation dialog to every action. + +The bridge follows the active browser tab; changing active tabs while a sequence is running can change its target. Keep the intended tab selected. Only one connected Chrome extension is supported per bridge instance. + +## Permissions, data flow, and side effects + +- **Chrome permissions:** `debugger`, `tabs`, `scripting`, `storage`, and ``. These enable page screenshots, tab inspection, DOM interaction, and script execution. Chrome may display its debugger banner. Browser-internal and otherwise restricted pages remain limited by Chrome. +- **Local processes:** MCP activation starts `server/mcp-stdio.js`. An auto-discovered `SessionStart` hook runs `hooks/session-start.js` to prewarm the same launcher. It reuses a healthy bridge and may start a detached Node bridge that remains alive after the client exits. On macOS/Windows, the first guide can open the system browser; explicit setup actions can open Chrome's extension manager or reveal the extension directory. No shell command or path is supplied by arbitrary web-page input. +- **Local writes:** by default, managed extension files, locks, completion/display state, and logs are written under `~/.browser-bridge/`. Standalone manual setup may also use a temporary guide-session file and `.onboard-state.json` inside the plugin directory. Chrome extension settings are stored with `chrome.storage`. Unmanaged files are preserved during extension synchronization; an unrecognized existing extension folder is rejected rather than overwritten. +- **Network:** default bridge traffic is loopback HTTP/WebSocket on `127.0.0.1:8765`; the guide binds loopback ports starting at `8791`. Chrome navigates to sites requested by the agent. There is no analytics endpoint, plugin cloud, runtime package download, or plugin-specific model/API request. The package includes the `ws` source dependency. ZCode may send tool results, including page text, tab metadata, screenshots, and evaluated JavaScript results, to the model/provider configured in the client. Explicitly setting `BRIDGE_URL` to another endpoint sends tool traffic to that endpoint; automatic local setup is disabled for remote/HTTPS endpoints. +- **Trust:** localhost access is not per-user authentication. Other trusted local processes may call the bridge. Host/Origin checks reject web-page callers and protect against DNS rebinding; they do not isolate untrusted local programs. Use this on a trusted workstation. Guide API calls additionally require a short-lived session token. +- **Credentials:** no website passwords or cookies are exported by a dedicated credential endpoint, but requested page content or JavaScript results can contain sensitive information. Choose the pages and actions you allow accordingly. + +To stop a bridge, identify the process using the PID and logs under `~/.browser-bridge/state/` and `logs/` and stop only that verified process. Disabling the plugin prevents future client activation; it does not terminate an already detached bridge automatically. + +## Configuration and troubleshooting + +`BROWSER_BRIDGE_HOME` changes the managed directory. `BRIDGE_PORT` or `BRIDGE_URL` selects a bridge endpoint; conflicting or invalid values fail explicitly. If using another local port, update the extension popup's WebSocket address to match. A port owned by another application is reported and the owner is not killed. + +If setup is interrupted, run `/cc-browser-setup`. If Node is missing, install Node.js and restart the client so it sees `node` on PATH. The plugin does not install a runtime. For browser control failures, check Chrome is running, the extension is enabled/connected, the intended tab is active, and control is not paused. + +## Validation scope + +Run `node --test tests/*.test.js` from this plugin directory. Package smoke checks use isolated homes/ports. Browser-opening regressions use a fake `open` command on macOS and are skipped on other platforms. + +Earlier macOS/ZCode/Chrome builds exercised the native guide and real browser tools. The current source includes the repeated-guide-opening fix and regression tests. Windows startup, packaging, and guide behavior have separate prior background checks. This release candidate's final native ZCode install/update/restart acceptance remains outstanding; it does not claim universal client or no-system-Node compatibility. Review the PR for exact current validation results. + +## License and provenance + +Browser Bridge source, documentation, and original icons: Apache-2.0, copyright 2026 lihytaihe-lang; see [LICENSE](LICENSE). The unmodified `ws` 8.22.0 source in `server/vendor/ws/` is MIT licensed, with its original license retained. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Google Chrome and ZCode are separate products governed by their own terms; this community plugin is not an official Google or Z.ai product. diff --git a/external_plugins/cc-browser-bridge/README_CN.md b/external_plugins/cc-browser-bridge/README_CN.md new file mode 100644 index 00000000..4b2965da --- /dev/null +++ b/external_plugins/cc-browser-bridge/README_CN.md @@ -0,0 +1,55 @@ +# Browser Bridge + +[English](README.md) + +Browser Bridge 让 ZCode 连接你日常使用的 Chrome,保留已有登录态。15 个 MCP 工具支持列出标签页、读取正文、截图、导航、点击、滚动、输入和执行网页 JavaScript。**0.6.0-rc.2 是社区测试候选版。** + +## 依赖与安装 + +- 客户端 PATH 中须有可运行的 `node`,要求 Node.js 18 或更新版本。 +- Google Chrome 116 或更新版本;扩展采用 Manifest V3。 +- 插件本身不要求另购模型账号、API Key、付费服务或打开 Chrome 远程调试端口。ZCode 使用用户在客户端配置的模型及服务商。 + +1. 在 ZCode 插件市场安装并启用 **Browser Bridge**,然后新建会话。如果投稿还在审核,请使用本仓库构建的本地市场,不要假定已经公开上架。 +2. 激活后自动准备本地桥接和稳定扩展目录。扩展未连接且引导从未展示时,打开一次安装引导。也可运行 `/cc-browser-setup` 主动打开。 +3. 在 Chrome 打开 `chrome://extensions`,开启**开发者模式**,点**加载已解压的扩展程序**,选择引导显示的目录,通常为 `~/.browser-bridge/extension`;Windows 对应 `%USERPROFILE%\.browser-bridge\extension`。macOS 在文件选择窗口按 Cmd+Shift+G 粘贴路径,Windows 使用地址栏或 Ctrl+L。 +4. 等待扩展显示已连接,然后回到 ZCode 说:**列出我当前 Chrome 中的标签页。** 收到真实工具结果才表示客户端到浏览器的链路通过;引导页显示已连接不代表客户端调用已经通过。 + +本投稿提供扩展源代码,**不会自动安装 Chrome 扩展,也不等于在 Chrome 网上应用店上架**。引导成功打开后单独记录“已展示”,与用户点“完成引导”分开。展示过的引导不因新会话、经过一段时间或升级再次弹出;扩展已经连接时也不自动打开。打开失败会按有界退避重试,`/cc-browser-setup` 始终允许主动重开。 + +## 使用示例与控制 + +- “读取当前网页并总结。” +- “截取当前标签页的画面。” +- “填写这个表单,提交前等我确认。” + +Chrome 扩展弹窗可查看连接状态、修改桥接地址和暂停浏览器控制。插件不会自动解除暂停。操作使用真实登录态,可能改变网站内容;涉及提交表单、发送消息、购买或删除,请要求 AI 等你确认。插件不会为每个操作额外添加独立确认对话框。 + +桥接跟随浏览器当前活动标签页;运行连续操作时切换活动页可能改变目标。请保持目标页选中。每个桥接实例同时只支持一份 Chrome 扩展连接。 + +## 权限、数据流与副作用 + +- **Chrome 权限:** `debugger`、`tabs`、`scripting`、`storage` 和 ``,用于截图、查看标签、DOM 操作和脚本执行。Chrome 可能显示正在调试的横幅。浏览器内部页和其他受限页面仍受 Chrome 限制。 +- **本地进程:** MCP 激活运行 `server/mcp-stdio.js`;自动发现的 `SessionStart` Hook 运行 `hooks/session-start.js`,预热同一启动层。健康桥接会复用,否则可能启动脱离客户端生命周期的 Node 后台桥接。macOS/Windows 首次引导可打开系统浏览器;用户明确触发的引导动作可打开 Chrome 扩展管理页或定位扩展目录。网页输入不能指定任意本机命令或路径。 +- **本地写入:** 默认在 `~/.browser-bridge/` 写入受管扩展、锁、展示/完成状态和日志。单独手动运行引导时,还可能写临时引导会话文件及插件目录中的 `.onboard-state.json`。扩展配置使用 `chrome.storage`。同步会保留未知文件,无法识别的已有扩展目录会拒绝接管。 +- **网络:** 默认只在 `127.0.0.1:8765` 传输 HTTP/WebSocket 桥接数据;引导使用从 `8791` 开始的回环端口。Chrome 按用户要求访问目标网站。插件没有统计上报、云服务、运行时依赖下载或专用模型/API 请求,包内带有 `ws` 源码依赖。ZCode 可能把网页正文、标签元数据、截图和 JavaScript 结果等工具输出发送给用户在客户端配置的模型/服务商。若明确设置远程 `BRIDGE_URL`,工具流量会发往该端点;远程/HTTPS 端点禁用自动本地准备。 +- **信任边界:** 回环访问不等于按用户身份认证,其他受信任本机进程也可调用桥接。Host/Origin 检查拒绝网页调用并防范 DNS 重绑定,不隔离恶意本地程序。请在受信任工作站使用。引导 API 还要求短期会话令牌。 +- **凭据:** 插件没有专门导出网站密码或 Cookie 的接口,但按要求读取的页面或 JavaScript 结果可能包含敏感信息,请按实际需要授权页面和操作。 + +需要停止桥接时,根据 `~/.browser-bridge/state/` 的 PID 与 `logs/` 日志核实归属,只停止确认过的桥接进程。禁用插件会阻止后续客户端激活,不会自动终止已脱离客户端的后台桥接。 + +## 配置与排障 + +`BROWSER_BRIDGE_HOME` 修改受管目录,`BRIDGE_PORT` 或 `BRIDGE_URL` 选择端点;冲突或非法值会明确报错。换本地端口时,扩展弹窗中的 WebSocket 地址也要一致。其他程序占用端口会明确报告,不会杀掉占用者。 + +引导中断可运行 `/cc-browser-setup`。缺少 Node 时先安装,再重启客户端使 PATH 生效;插件不安装运行时。控制失败请检查 Chrome 正在运行、扩展已启用并连接、目标页仍是活动标签,且没有暂停控制。 + +## 验证范围 + +在插件目录运行 `node --test tests/*.test.js`。包内冒烟测试使用隔离目录和端口;打开浏览器的回归使用 macOS 假 `open` 命令,在其他平台跳过。 + +此前 macOS/ZCode/Chrome 构建实际验证过原生引导和真实浏览器工具。当前源码包含重复弹引导修复和回归验证。Windows 启动、包装与引导另有此前后台检查。当前候选版的 ZCode 新装/更新/重启原生终验仍未完成,不宣称所有客户端兼容或无系统 Node 时开箱即用。当前具体检查结果见投稿 PR。 + +## 许可证与来源 + +Browser Bridge 源码、文档及原创图标采用 Apache-2.0,copyright 2026 lihytaihe-lang,见 [LICENSE](LICENSE)。`server/vendor/ws/` 是未修改的 `ws` 8.22.0 源码,遵循 MIT 并保留原许可证,见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。Google Chrome 和 ZCode 是独立产品,遵循其各自条款;本插件由社区维护,不代表 Google 或 Z.ai 官方产品。 diff --git a/external_plugins/cc-browser-bridge/THIRD_PARTY_NOTICES.md b/external_plugins/cc-browser-bridge/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..681dfdc9 --- /dev/null +++ b/external_plugins/cc-browser-bridge/THIRD_PARTY_NOTICES.md @@ -0,0 +1,13 @@ +# Third-party notices + +## ws 8.22.0 + +- Upstream: https://github.com/websockets/ws +- Distribution: https://registry.npmjs.org/ws/-/ws-8.22.0.tgz +- npm integrity: `sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==` +- Location: `server/vendor/ws/` +- License: MIT. The original copyright notices and license text are retained in `server/vendor/ws/LICENSE`. + +Files are copied without modification from the installed npm distribution pinned by `server/package-lock.json`. No native optional acceleration module is bundled or required. Browser Bridge's bridge imports this vendored copy directly, so installation and startup do not run npm or download a dependency. + +Browser Bridge's own source, documentation, and original icons are licensed separately under Apache-2.0. Chrome browser APIs are used at runtime; Chrome itself is not bundled. diff --git a/external_plugins/cc-browser-bridge/assets/icon.png b/external_plugins/cc-browser-bridge/assets/icon.png new file mode 100644 index 00000000..b66b5c52 Binary files /dev/null and b/external_plugins/cc-browser-bridge/assets/icon.png differ diff --git a/external_plugins/cc-browser-bridge/commands/cc-browser-setup.md b/external_plugins/cc-browser-bridge/commands/cc-browser-setup.md new file mode 100644 index 00000000..bb5ab0f3 --- /dev/null +++ b/external_plugins/cc-browser-bridge/commands/cc-browser-setup.md @@ -0,0 +1,22 @@ +--- +name: cc-browser-setup +description: Open or resume the Browser Bridge setup guide; 排障或主动重开 Chrome 连接引导。 +--- + +# Browser Bridge setup / 连接引导 + +Use this command when the user asks to set up Chrome or reopen the guide. Normal MCP activation and SessionStart prepare the bridge automatically. The guide opens automatically only when it has never been shown and the extension is not connected. Explicit reopening remains available after a successful opening or completion. + +Run the installed entry, resolving the actual plugin directory from the host's `ZCODE_PLUGIN_ROOT` variable or this command's installation location: + +```sh +node "${ZCODE_PLUGIN_ROOT}/server/onboard.js" --launch +``` + +The command opens a local guide and outputs its session URL. Do not send that URL/token to third parties or include it in public logs. If browser opening fails, let the user open the local URL privately. Missing Node must be reported; do not install software or modify client configuration without the user's instruction. + +Guide the user through Chrome's `chrome://extensions` → Developer mode → Load unpacked → the extension directory displayed by the guide. Loading requires the user's Chrome UI action. After connection, ask the user to try “List the tabs in my Chrome browser” / “列出我当前 Chrome 中的标签页” in ZCode. Do not claim client success from the guide's connected indicator alone. Do not read unrelated tabs while only troubleshooting setup. + +For disconnection, check the extension popup's connection and pause state, and ensure its bridge address matches `BRIDGE_PORT`/`BRIDGE_URL`. Never resume a pause automatically. Logs and state normally live under `~/.browser-bridge/`. Do not print page contents, browsing URLs, or session tokens into a public issue. + +浏览器引导成功展示过后不会随新会话重复打开。主动运行本命令始终可以重开。缺少 Node 时明确提示;加载 Chrome 扩展由用户完成。引导显示已连接后,仍需在 ZCode 真实调用一次工具才算客户端链路通过。 diff --git a/external_plugins/cc-browser-bridge/extension/background.js b/external_plugins/cc-browser-bridge/extension/background.js new file mode 100644 index 00000000..d532fd52 --- /dev/null +++ b/external_plugins/cc-browser-bridge/extension/background.js @@ -0,0 +1,913 @@ +// Claude API Browser Bridge — 扩展后台(MV3 Service Worker) +// 通过 WebSocket 连接本地桥接服务 (server/bridge.js),把工具调用翻译成 +// chrome.debugger (CDP) 与 chrome.scripting 操作,复刻原生 Claude in Chrome 的能力。 + +const DEFAULT_SERVER = "ws://127.0.0.1:8765/ws"; +const HEARTBEAT_MS = 20000; +const VERSION = "0.1.0"; + +let ws = null; +let connected = false; +let armed = true; // popup 里可暂停 +let serverUrl = DEFAULT_SERVER; +let reconnectTimer = null; +let heartbeatTimer = null; + +const attachedTabs = new Set(); // 已 attach debugger 的 tabId +const lastShot = new Map(); // tabId -> { scale }(截图像素 / CSS 像素) +let lastMouse = { x: 0, y: 0 }; // 最近一次鼠标位置(CSS 像素) + +// ---------- 小工具 ---------- +const cb = (fn, ...a) => + new Promise((resolve, reject) => { + fn(...a, (r) => { + const e = chrome.runtime.lastError; + if (e) reject(new Error(e.message)); + else resolve(r); + }); + }); + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +async function activeTab() { + const tabs = await cb(chrome.tabs.query, { active: true, lastFocusedWindow: true }); + if (!tabs || !tabs.length) throw new Error("找不到活动标签页"); + const t = tabs[0]; + if (/^(chrome|edge|about|devtools):/i.test(t.url || "") && !/^chrome:\/\/newtab/i.test(t.url)) { + // chrome:// 页面大部分操作受限,但截图可用,这里只对需要注入的操作在各自 handler 里报错 + } + return t; +} + +function pageRestricted(url) { + return /^chrome(-extension)?:\/\/(webstore|extensions)/i.test(url || "") || + /^(devtools|view-source):/i.test(url || ""); +} + +async function ensureAttached(tabId) { + if (attachedTabs.has(tabId)) return; + try { + await cb(chrome.debugger.attach, { tabId }, "1.3"); + } catch (e) { + if (!/already attached/i.test(String(e.message))) { + if (/Another debugger/i.test(String(e.message))) + throw new Error("该标签页已被其他调试器占用(可能开着 DevTools 或其他扩展),请关闭后重试"); + throw e; + } + } + attachedTabs.add(tabId); +} + +async function cdp(tabId, method, params = {}) { + await ensureAttached(tabId); + return cb(chrome.debugger.sendCommand, { tabId }, method, params); +} + +chrome.debugger.onDetach.addListener((source) => { + attachedTabs.delete(source.tabId); +}); + +// 截图过大时等比缩小(Claude 视觉推荐长边 ~1568,computer-use 惯例宽 ~1280) +// 返回值附带 srcW/srcH(解码出的原始位图尺寸),供调用方做比例校验 +async function shrinkBase64Png(b64, maxW, maxH) { + const blob = await (await fetch("data:image/png;base64," + b64)).blob(); + const bmp = await createImageBitmap(blob); + const w = bmp.width, h = bmp.height; + const scale = Math.min(maxW / w, maxH ? maxH / h : 1, 1); + if (scale >= 1) return { data: b64, width: w, height: h, srcW: w, srcH: h }; + const nw = Math.max(1, Math.round(w * scale)); + const nh = Math.max(1, Math.round(h * scale)); + const cnv = new OffscreenCanvas(nw, nh); + cnv.getContext("2d").drawImage(bmp, 0, 0, nw, nh); + const out = await cnv.convertToBlob({ type: "image/png" }); + const buf = new Uint8Array(await out.arrayBuffer()); + let bin = ""; + for (let i = 0; i < buf.length; i += 0x8000) + bin += String.fromCharCode.apply(null, buf.subarray(i, i + 0x8000)); + return { data: btoa(bin), width: nw, height: nh, srcW: w, srcH: h }; +} + +// 注入页面并在指定世界执行的自包含 agent:快照 / 按 ref 交互 / 读页面 +function pageAgent(args) { + // args: {mode:"snapshot"|"click"|"hover"|"type"|"select_option"|"read_page"|"scroll"|"metrics", + // ref:Number, text:String, value:String, clear:Bool, press_enter:Bool, + // direction:"up"|"down", amount:Number} + const MAX_NAME = 70; + const INTERACTIVE = [ + "a[href]", "button", "input", "select", "textarea", "summary", "label", + "[role]", '[contenteditable=""]', '[contenteditable="true"]', + "[onclick]", "[tabindex]", + "h1", "h2", "h3", "h4", "h5", "h6", + 'img[alt]:not([alt=""])', "video", "audio" + ].join(","); + const isVisible = (el) => { + const st = getComputedStyle(el); + if (st.display === "none" || st.visibility === "hidden" || st.opacity === "0") return false; + const r = el.getBoundingClientRect(); + return r.width >= 1 && r.height >= 1; + }; + // 稳定引用注册表:挂在 window 上(扩展隔离世界),跨多次注入调用存活; + // 页面导航/重载后随 document 销毁,旧 ref 自动全部失效。 + // ref 编号 = 文档 epoch × 2^20 + 本地索引: + // - 同一元素无论经历多少次 snapshot,ref 编号不变;新元素只能拿到新编号; + // - 元素被移除后其 ref 永久失效,不会重新绑定到别的元素; + // - epoch 为每个新文档(含 iframe 等独立 window)随机分配,跨文档/跨导航 + // 永不复用——旧文档的 ref 不可能命中新文档的元素(避免 ref=0 漂移)。 + const REG_KEY = "__ccBridgeRefRegistry"; + const REF_SPACE = 1 << 20; // 1048576:每文档本地索引空间 + const newEpoch = () => { + try { + if (typeof crypto !== "undefined" && crypto.getRandomValues) { + const u = new Uint32Array(1); + crypto.getRandomValues(u); + return (u[0] % 1073741823) + 1; // [1, 2^30) + } + } catch (e) {} + return Math.floor(Math.random() * 1073741823) + 1; + }; + const ensureReg = () => { + if (!window[REG_KEY] || !window[REG_KEY].els || !window[REG_KEY].byEl) + window[REG_KEY] = { epoch: newEpoch(), els: [], byEl: new WeakMap() }; + return window[REG_KEY]; + }; + const refOf = (reg, el) => { + let idx = reg.byEl.get(el); + if (idx === undefined) { + reg.els.push(el); + idx = reg.els.length - 1; + reg.byEl.set(el, idx); + } + return reg.epoch * REF_SPACE + idx; + }; + const resolveRef = (ref) => { + const reg = window[REG_KEY]; + const n = Number(ref); + if (!reg || !Array.isArray(reg.els)) + return { error: "页面还没有可用引用(可能已导航/重载),请先 browser_snapshot" }; + if (!Number.isInteger(n) || n < 0) + return { error: "ref 必须是 browser_snapshot 返回的编号" }; + const epoch = Math.floor(n / REF_SPACE); + const idx = n % REF_SPACE; + if (epoch !== reg.epoch) + return { error: "ref 来自其他页面/文档或已过期(ref 编号跨文档不通用),请重新 browser_snapshot" }; + if (idx >= reg.els.length) + return { error: "ref " + ref + " 不存在,请重新 browser_snapshot 获取最新 ref" }; + const el = reg.els[idx]; + if (!el || !el.isConnected) + return { error: "ref 指向的元素已从页面移除,请重新 browser_snapshot;该 ref 不会重新绑定到其他元素" }; + return { el }; + }; + const collect = () => { + const out = []; + const root = document.body || document.documentElement; + if (!root) return out; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT); + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + try { if (n.matches(INTERACTIVE) && isVisible(n)) out.push(n); } catch (e) {} + } + return out; + }; + const roleOf = (el) => { + const t = el.tagName.toLowerCase(); + const explicit = el.getAttribute("role"); + if (explicit) return explicit; + if (t === "a") return "link"; + if (t === "button") return "button"; + if (t === "select") return "combobox"; + if (t === "textarea") return "textbox"; + if (t === "summary") return "expand"; + if (t === "label") return "label"; + if (/^h[1-6]$/.test(t)) return "heading"; + if (t === "img") return "image"; + if (t === "video") return "video"; + if (t === "audio") return "audio"; + if (t === "input") { + const ty = (el.getAttribute("type") || "text").toLowerCase(); + if (ty === "button" || ty === "submit" || ty === "reset") return "button"; + if (ty === "checkbox") return "checkbox"; + if (ty === "radio") return "radio"; + if (ty === "range") return "slider"; + return "textbox"; + } + return el.hasAttribute("onclick") || el.getAttribute("tabindex") != null ? "clickable" : "text"; + }; + const clean = (s) => String(s == null ? "" : s).replace(/\s+/g, " ").trim().slice(0, MAX_NAME); + const nameOf = (el) => { + let n = clean(el.getAttribute("aria-label")) || clean(el.getAttribute("title")) || + clean(el.getAttribute("alt")) || clean(el.getAttribute("placeholder")); + if (!n) { + const t = el.tagName.toLowerCase(); + if (t === "input") { + const ty = (el.type || "").toLowerCase(); + if (ty === "button" || ty === "submit" || ty === "reset") n = clean(el.value); + else if ((ty === "checkbox" || ty === "radio") && el.labels && el.labels[0]) n = clean(el.labels[0].innerText); + } else if (t === "select") { + n = clean(el.selectedOptions && el.selectedOptions[0] && el.selectedOptions[0].text); + } else { + n = clean(el.innerText); + } + } + return n; + }; + + const mode = args.mode; + + if (mode === "metrics") { + return { + w: innerWidth, h: innerHeight, dpr: devicePixelRatio, + scrollX: scrollX, scrollY: scrollY, + docH: document.documentElement.scrollHeight, title: document.title, url: location.href + }; + } + + if (mode === "read_page") { + const text = (document.body ? document.body.innerText : "").replace(/\n{3,}/g, "\n\n"); + return { title: document.title, url: location.href, text: text.slice(0, 20000) }; + } + + if (mode === "snapshot") { + const reg = ensureReg(); + const els = collect(); + // 清理已脱离文档的引用槽(置 null,编号永不复用),防止内存长期滞留 + for (let i = 0; i < reg.els.length; i++) { + const e = reg.els[i]; + if (!e || !e.isConnected) { if (e) reg.byEl.delete(e); reg.els[i] = null; } + } + const lines = []; + for (let i = 0; i < els.length && i < 600; i++) { + const el = els[i]; + const ref = refOf(reg, el); + const t = el.tagName.toLowerCase(); + const r = el.getBoundingClientRect(); + let line = "[" + ref + "] " + roleOf(el) + " \"" + nameOf(el) + "\""; + if (t === "input" || t === "textarea") { + const ty = (el.type || "").toLowerCase(); + if (ty === "password") line += " value=••••"; + else if (el.value) line += " value=\"" + clean(el.value) + "\""; + if (el.checked) line += " [checked]"; + if (el.disabled) line += " [disabled]"; + } + if (t === "select") { + const opts = []; + for (let j = 0; j < el.options.length && opts.length < 6; j++) + opts.push(el.options[j].value + ":" + clean(el.options[j].text)); + line += " options=[" + opts.join(" | ") + "]"; + } + if (t === "a" && el.href) line += " href=\"" + String(el.href).slice(0, 90) + "\""; + line += " @(" + Math.round(r.x + scrollX) + "," + Math.round(r.y + scrollY) + " " + Math.round(r.width) + "x" + Math.round(r.height) + ")"; + lines.push(line); + } + return { count: els.length, title: document.title, url: location.href, snapshot: lines.join("\n") }; + } + + // ---- 需要 ref 的操作:从注册表解析,绝不按当次 collect 下标重绑 ---- + if (mode === "click" || mode === "hover") { + if (args.ref == null) return { error: "缺少 ref(来自 browser_snapshot)" }; + const rr = resolveRef(args.ref); + if (rr.error) return rr; + const el = rr.el; + el.scrollIntoView({ block: "center" }); + const r = el.getBoundingClientRect(); + const x = r.x + r.width / 2, y = r.y + r.height / 2; + const base = { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y, button: 0 }; + try { el.dispatchEvent(new PointerEvent("pointerover", base)); } catch (e) {} + el.dispatchEvent(new MouseEvent("mouseover", base)); + if (mode === "hover") return { ok: true, hovered: args.ref }; + el.dispatchEvent(new PointerEvent("pointerdown", base)); + el.dispatchEvent(new MouseEvent("mousedown", base)); + try { el.focus({ preventScroll: true }); } catch (e) {} + // 下面派发的 click 事件会触发浏览器默认激活行为(checkbox/radio 勾选、链接跳转等); + // 不再手动改 checked——手动改一次 + 默认行为一次会双重切换(真实 Chrome 已复现 + // 初始 false -> click -> false) + el.dispatchEvent(new PointerEvent("pointerup", base)); + el.dispatchEvent(new MouseEvent("mouseup", base)); + el.dispatchEvent(new MouseEvent("click", base)); + return { ok: true, clicked: args.ref, role: roleOf(el), name: nameOf(el) }; + } + + if (mode === "type") { + let target = null; + if (args.ref != null) { + const rr = resolveRef(args.ref); + if (rr.error) return rr; + target = rr.el; + } + if (!target) target = document.activeElement; + if (!target || target === document.body) + return { error: "没有可输入的目标:请提供 ref,或先点击输入框获得焦点" }; + if (target.disabled || target.readOnly) return { error: "目标元素是 disabled/readonly,无法输入" }; + target.focus(); + const t = target.tagName.toLowerCase(); + const ce = target.isContentEditable; + if (ce) { + if (args.clear !== false) { + const sel = window.getSelection(); + sel.selectAllChildren(target); + document.execCommand("delete"); + } + document.execCommand("insertText", false, args.text); + } else { + const proto = t === "textarea" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; + const setter = Object.getOwnPropertyDescriptor(proto, "value").set; + const keep = args.clear === false ? target.value : ""; + setter.call(target, keep + args.text); + target.dispatchEvent(new Event("input", { bubbles: true })); + target.dispatchEvent(new Event("change", { bubbles: true })); + } + if (args.press_enter) { + target.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", code: "Enter", keyCode: 13, which: 13, bubbles: true })); + const form = target.closest ? target.closest("form") : null; + if (form) { try { form.requestSubmit(); } catch (e) { try { form.submit(); } catch (e2) {} } } + } + return { ok: true, typed: args.text.length, value: ce ? "" : target.value }; + } + + if (mode === "select_option") { + if (args.ref == null) return { error: "缺少 ref(来自 browser_snapshot)" }; + const rr = resolveRef(args.ref); + if (rr.error) return rr; + const el = rr.el; + if (el.tagName.toLowerCase() !== "select") return { error: "ref " + args.ref + " 不是 + 暂停 AI 对浏览器的控制 + + + +
+ +
+ + +
+
+ +

角标 ● 表示已连接。被控制时 Chrome 顶部出现「正在调试」横幅属正常现象。

+ + + + diff --git a/external_plugins/cc-browser-bridge/extension/popup.js b/external_plugins/cc-browser-bridge/extension/popup.js new file mode 100644 index 00000000..16cf1ee8 --- /dev/null +++ b/external_plugins/cc-browser-bridge/extension/popup.js @@ -0,0 +1,114 @@ +// popup:连接状态(文字+颜色)、暂停开关、服务地址保存(URL 解析规范化;等后台真实回执,绝不未确认就报成功) +const $ = (id) => document.getElementById(id); +let timer = null; + +const EXT_VERSION = (chrome.runtime.getManifest && chrome.runtime.getManifest().version) || ""; + +// 状态文案:检测中 / 已连接(扩展版本取自 manifest,与后台握手版本区分)/ 已连接·已暂停 / 未连接(面向用户,不含内部文件名) +function statusView(st) { + if (!st) return { cls: "", dot: "", text: "检测中…" }; + const ver = EXT_VERSION ? ` · 扩展 v${EXT_VERSION}` : ""; + if (st.connected) { + if (st.armed === false) return { cls: "warn", dot: "warn", text: `已连接${ver} · 已暂停` }; + return { cls: "ok", dot: "on", text: `已连接${ver}` }; + } + return { + cls: "bad", dot: "", + text: "未连接:请打开 ZCode 等客户端建立会话,或重新运行一次连接引导;也可以检查下方服务地址是否正确。", + }; +} + +// 服务地址草稿保护(R3):输入框只被「首次成功状态」初始化一次,之后轮询绝不覆盖用户草稿 +// (包括清空后的空草稿);不依赖 value 是否为空判断初始化,而是跟踪用户是否输入过。 +// 保存成功且回执到达时没有新编辑,才回填规范化地址。 +let serverUrlReady = false; // 首次成功状态是否已消费初始化机会 +let editSeq = 0; // 用户每次输入自增;保存流程借此识别「保存期间是否有新编辑」 +$("serverUrl").addEventListener("input", () => { editSeq++; }); + +function refresh() { + chrome.runtime.sendMessage({ type: "status" }, (st) => { + if (chrome.runtime.lastError || !st) { + // 读取失败不得保留旧的「已连接」 + $("dot").className = "dot"; + const el = $("state"); + el.className = "v warn"; + el.textContent = "未能读取状态:请重新打开本弹窗。"; + return; + } + const v = statusView(st); + $("dot").className = "dot" + (v.dot ? " " + v.dot : ""); + const el = $("state"); + el.className = "v" + (v.cls ? " " + v.cls : ""); + el.textContent = v.text; + $("pause").checked = !st.armed; + if (!serverUrlReady) { + serverUrlReady = true; // 首次成功状态只消费一次;之后轮询不再改写输入框 + if (editSeq === 0) $("serverUrl").value = st.serverUrl; // 用户已开始输入(含已清空)则不覆盖 + } + }); +} + +function setHint(text, isErr) { + const el = $("hint"); + el.textContent = text; + el.classList.toggle("err", !!isErr); +} + +// URL 解析规范化:仅缺 /ws 时补;已有 /ws 不变(修复 /ws/ws);拒绝 http(s) 前缀伪装、凭据、坏端口; +// 保留合法 ws/wss 与 IPv6;空值报错。 +function normalizeUrl(raw) { + let s = String(raw || "").trim(); + if (!s) return { err: "地址不能为空。" }; + if (!/^wss?:\/\//i.test(s)) { + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) return { err: "地址无效:请使用 ws:// 或 wss:// 开头。" }; + s = "ws://" + s; + } + let u; + try { u = new URL(s); } catch (e) { return { err: "地址无效。" }; } + if (u.protocol !== "ws:" && u.protocol !== "wss:") return { err: "地址无效:仅支持 ws/wss。" }; + if (!u.hostname) return { err: "地址无效:缺少主机名。" }; + if (u.username || u.password) return { err: "地址无效:不支持在地址中携带凭据。" }; + let p = u.pathname.replace(/\/+$/, ""); + if (!/\/ws$/.test(p)) p += "/ws"; + return { url: u.protocol + "//" + u.host + p + u.search }; +} + +$("pause").addEventListener("change", (e) => { + chrome.runtime.sendMessage({ type: "arm", armed: !e.target.checked }); +}); + +$("save").addEventListener("click", () => { + const n = normalizeUrl($("serverUrl").value); + if (n.err) { setHint(n.err, true); return; } + const seq0 = editSeq; // 保存时刻的编辑序号:成功回填仅在没有新编辑时进行 + const btn = $("save"); + btn.disabled = true; // 保存期间防重复提交 + let settled = false; + const finish = (text, isErr) => { + if (settled) return; // 超时后迟到的回应一律忽略,不再改写提示 + settled = true; + clearTimeout(tooLate); + btn.disabled = false; + setHint(text, isErr); + }; + const tooLate = setTimeout(() => { + finish("保存未确认:扩展未在 2 秒内响应。请确认扩展已启用(角标有显示),或重新打开本弹窗再试。", true); + }, 2000); + try { + chrome.runtime.sendMessage({ type: "set_server", url: n.url }, (resp) => { + if (chrome.runtime.lastError) return finish("保存失败:" + chrome.runtime.lastError.message, true); + if (resp && resp.ok === true && resp.serverUrl) { + if (!settled && editSeq === seq0) $("serverUrl").value = resp.serverUrl; // 保存期间无新编辑:回填规范化值 + finish("已保存并开始重连:" + resp.serverUrl + "。角标变 ● 即连接成功。", false); + } else { + finish("保存失败:" + ((resp && resp.error) || "扩展返回未知结果,地址未更改。"), true); + } + }); + } catch (e) { + finish("保存失败:" + ((e && e.message) || e), true); + } +}); + +refresh(); +timer = setInterval(refresh, 1000); +window.addEventListener("unload", () => clearInterval(timer)); diff --git a/external_plugins/cc-browser-bridge/hooks/hooks.json b/external_plugins/cc-browser-bridge/hooks/hooks.json new file mode 100644 index 00000000..3f6cec76 --- /dev/null +++ b/external_plugins/cc-browser-bridge/hooks/hooks.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${ZCODE_PLUGIN_ROOT}/hooks/session-start.js\"", + "timeoutMs": 20000, + "statusMessage": "Browser Bridge:预热桥接服务(幂等;未预热时 MCP 激活也会自动准备)" + } + ] + } + ] + } +} diff --git a/external_plugins/cc-browser-bridge/hooks/session-start.js b/external_plugins/cc-browser-bridge/hooks/session-start.js new file mode 100644 index 00000000..2b2d2c64 --- /dev/null +++ b/external_plugins/cc-browser-bridge/hooks/session-start.js @@ -0,0 +1,81 @@ +#!/usr/bin/env node +// Browser Bridge · ZCode SessionStart 钩子(纯 Node、幂等、有界) +// --------------------------------------------------------------------------- +// 职责:会话建立时「预热」已验收的通用启动核心(<插件根>/server/launcher.js 的 ensureReady): +// 桥接服务幂等拉起/复用、扩展稳定副本同步、尚未展示且扩展未连接时打开一次图形引导(失败退避/并发去重)。 +// +// 与 MCP 主链的准确区别(重要,勿改语义): +// - MCP 启动才是主链:宿主激活 server/mcp-stdio.js 时(时机由宿主决定——有的宿主在新会话 +// 立即 initialize,有的延迟到首次工具调用),mcp-stdio 进程启动即自动执行同一 ensureReady。 +// - 本钩子只是优化:让支持 SessionStart 的宿主(如 ZCode)在用户发出第一条消息之前 +// 就完成准备。本包不假设所有宿主都会在新会话立刻初始化 MCP,也不假设宿主会运行钩子; +// 任一条链先到即完成准备,后到者幂等复用(跨进程锁 + 健康探测 + 完成标记)。 +// +// 约束: +// - stdout 恒为空(不污染宿主输出);诊断只写 stderr,且不输出引导 URL/token。 +// - 任何失败都不阻塞会话建立:始终以退出码 0 结束。 +// - 纯 Node:不依赖 Bash/Git Bash/WSL/Homebrew;不硬编码任何开发者路径。 +// - 插件根定位:优先宿主注入的 CLAUDE_PLUGIN_ROOT(须含 server/launcher.js), +// 无效或缺失时从本文件位置自定位(hooks/ 的上一级)。 +// 运行依赖:PATH 中的 node(与 plugin.json 的 mcpServers.command 一致);无系统 Node 的 +// 机器上钩子不生效但不报错阻塞,主链同样需要 node——该场景须真实客户端验证,见 workbuddy/README-ZH.md。 + +"use strict"; + +const fs = require("fs"); +const path = require("path"); + +const HARD_BUDGET_MS = 15000; // 预热自限时限(hooks.json timeoutMs 20000 内留出余量) + +function resolvePluginRoot() { + const self = path.resolve(__dirname, ".."); + const fromEnv = process.env.ZCODE_PLUGIN_ROOT || process.env.CLAUDE_PLUGIN_ROOT; + const envName = process.env.ZCODE_PLUGIN_ROOT ? "ZCODE_PLUGIN_ROOT" : "CLAUDE_PLUGIN_ROOT"; + if (fromEnv && path.isAbsolute(fromEnv)) { + const abs = path.resolve(fromEnv); + if (fs.existsSync(path.join(abs, "server", "launcher.js"))) { + return { root: abs, via: envName }; + } + process.stderr.write("[session-start] " + envName + " 无效(缺少 server/launcher.js),已回退自定位\n"); + } + return { root: self, via: "self" }; +} + +function summarize(r) { + if (!r || r.__timeout === true) return "timeout"; + const bridge = r.bridge ? (r.bridge.reused ? "reused" : "launched") : String(r.skipped || "none"); + const ext = r.ext ? ("updated:" + (r.ext.updated === true)) : "none"; + const onb = r.onboarding && r.onboarding.skipped ? ("skipped:" + r.onboarding.skipped) + : r.onboarding && r.onboarding.triggered ? "triggered" : "none"; + return "bridge=" + bridge + " ext=" + ext + " onboarding=" + onb; +} + +async function main() { + const { root, via } = resolvePluginRoot(); + const launcherPath = path.join(root, "server", "launcher.js"); + if (!fs.existsSync(launcherPath)) { + process.stderr.write("[session-start] 未找到启动核心 " + launcherPath + ",跳过预热(MCP 激活时会再次尝试)\n"); + return; + } + const launcher = require(launcherPath); + const guard = setTimeout(() => { + process.stderr.write("[session-start] 预热超过 " + HARD_BUDGET_MS + "ms,提前返回;后续由 MCP 主链接管\n"); + process.exit(0); // 后台进程均已 detached,安全退出 + }, HARD_BUDGET_MS); + let r; + try { + r = await launcher.ensureReady({ layoutRoot: root }); + } catch (e) { + clearTimeout(guard); + process.stderr.write("[session-start] 预热异常(不阻塞会话):" + (e && e.message || e) + "\n"); + return; + } + clearTimeout(guard); + process.stderr.write("[session-start] result rootVia=" + via + " " + summarize(r) + + (r && r.ok === false ? " reason=" + r.reason : "") + "\n"); +} + +main().catch((e) => { + process.stderr.write("[session-start] 未捕获异常(不阻塞会话):" + (e && e.message || e) + "\n"); + process.exit(0); +}); diff --git a/external_plugins/cc-browser-bridge/server/bridge.js b/external_plugins/cc-browser-bridge/server/bridge.js new file mode 100644 index 00000000..3ae2c2c8 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/bridge.js @@ -0,0 +1,360 @@ +// Claude API Browser Bridge — 本地桥接服务 +// 职责: +// 1. WebSocket 服务端:接收 Chrome 扩展长连接,转发工具命令/结果 +// 2. HTTP /tool:原生工具接口(自写脚本用) +// 3. HTTP /mcp:MCP streamable HTTP(Claude Code 等用,stateless 实现) +// 只监听 127.0.0.1,不暴露公网。 + +const http = require("http"); +const fs = require("fs"); +const path = require("path"); +const crypto = require("crypto"); +const { WebSocketServer } = require("./vendor/ws"); +const { TOOLS, planFor, shapeResult } = require("./tools"); + +const PORT = Number(process.env.PORT || 8765); +const HOST = "127.0.0.1"; +const EXT_TIMEOUT_MS = 60000; + +// ---------- 本机信任边界 ---------- +// HTTP/WS 端点只服务本机进程(curl、MCP 客户端、stdio 转发),这类客户端: +// - 不发送 Origin 头(浏览器才发);带上 Origin(含 "null")的一律视为网页来源,拒绝; +// - Host 是 127.0.0.1/localhost + 当前端口,防止 DNS 重绑定(外部域名解析到 127.0.0.1 后 +// 浏览器发的 Host 仍是该域名,不匹配即拒绝); +// - POST 正文只接受 application/json,拒绝 text/plain 等跨站简单请求可伪造的类型; +// - 不返回任何 CORS 授权头,浏览器页面即使能访问端口也读不到响应。 +// 需要放行额外本机 Host 时,用环境变量追加:BRIDGE_ALLOWED_HOSTS=foo.test:8765 +const ALLOWED_HOSTS = new Set( + [`127.0.0.1:${PORT}`, `localhost:${PORT}`, `[::1]:${PORT}`] + .concat(PORT === 80 ? ["127.0.0.1", "localhost", "[::1]"] : []) + .concat(String(process.env.BRIDGE_ALLOWED_HOSTS || "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)) +); + +function hostTrusted(req) { + return ALLOWED_HOSTS.has(String(req.headers.host || "").toLowerCase()); +} + +function originTrusted(req) { + const o = req.headers.origin; + // 本机非浏览器客户端(curl/Node/Python)不发 Origin;浏览器来源(含 "null")一律拒绝 + return o === undefined || String(o) === ""; +} + +function contentTypeJson(req) { + const ct = String(req.headers["content-type"] || "").trim(); + if (ct === "") return true; // 不带 Content-Type 的本机裸 POST 仍允许 + return /^application\/json\b/i.test(ct); +} + +function deny(res, status, msg) { + res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" }); + res.end(JSON.stringify({ ok: false, error: msg })); +} +const SERVER_INFO = { name: "cc-browser-bridge", version: "0.1.0" }; +const SUPPORTED_PROTOCOLS = ["2024-11-05", "2025-03-26", "2025-06-18"]; +const INSTRUCTIONS = + "通过这套工具可以查看和控制用户当前使用的 Chrome 浏览器(保留用户登录态)。" + + "推荐流程:browser_tabs list → browser_navigate → browser_snapshot(拿 ref)→ browser_click/browser_type;" + + "需要看视觉布局时用 browser_screenshot,其返回的截图坐标可直接用于 browser_click 的 x/y。"; + +// ---------- 扩展连接与命令路由 ---------- +let extWs = null; // 当前扩展连接(只支持一个) +const pending = new Map(); // id -> {resolve, reject, timer} + +function extConnected() { + return !!(extWs && extWs.readyState === 1); +} + +function extCall(tool, args) { + return new Promise((resolve, reject) => { + if (!extConnected()) { + reject(new Error("Chrome 扩展未连接:请确认 ① server/bridge.js 已在运行 ② Chrome 扩展已加载并启用 ③ 扩展图标角标显示 ●(未连接时点开扩展 popup 查看原因)")); + return; + } + const id = crypto.randomUUID(); + const timer = setTimeout(() => { + pending.delete(id); + reject(new Error("扩展执行超时(60s):" + tool)); + }, EXT_TIMEOUT_MS); + pending.set(id, { + resolve: (r) => { clearTimeout(timer); resolve(r); }, + reject: (e) => { clearTimeout(timer); reject(e); }, + }); + extWs.send(JSON.stringify({ id, tool, args: args || {} })); + }); +} + +function extDropPending(reason) { + for (const [, p] of pending) p.reject(new Error(reason)); + pending.clear(); +} + +function initWs(server) { + const wss = new WebSocketServer({ server, path: "/ws", host: HOST }); + wss.on("connection", (ws, req) => { + if (!hostTrusted(req)) { + ws.close(4003, "forbidden host"); + return; + } + const origin = String(req.headers.origin || ""); + // 只放行标准扩展来源 chrome-extension://<32位id>(不硬编码具体 id,未打包扩展也能连): + // 结构化校验排除网页(http/https/file 等)、空 Origin 和畸形值。 + // 注意这只是来源边界检查,不是扩展身份认证(本机任何扩展理论上都能连)。 + if (!/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) { + ws.close(4003, "forbidden origin"); + return; + } + if (extWs && extWs !== ws) { + // 新连接顶替旧连接(扩展重载场景);旧连接的在途命令不再可能有结果,直接拒绝让调用方重试 + try { extWs.close(4000, "replaced"); } catch (e) {} + extDropPending("扩展连接已被新连接替换,请重试"); + } + extWs = ws; + log("扩展已连接 origin=" + origin); + ws.on("message", (data) => { + let msg; + try { msg = JSON.parse(String(data)); } catch (e) { return; } + if (msg.type === "hello") { + log("扩展 hello version=" + msg.version); + return; + } + if (msg.type === "ping") { ws.send(JSON.stringify({ type: "pong" })); return; } + if (msg.type === "result" && msg.id && pending.has(msg.id)) { + const p = pending.get(msg.id); + pending.delete(msg.id); + if (msg.ok) p.resolve(msg.result); + else p.reject(new Error(String(msg.error || "扩展执行失败"))); + } + }); + ws.on("close", () => { + // 只有当前连接断开才清空在途命令;被替换的旧连接关闭时不得误伤新连接的 pending + if (extWs === ws) { + extWs = null; + extDropPending("扩展连接已断开,请检查 Chrome 扩展后重试"); + log("扩展已断开"); + } + }); + ws.on("error", () => {}); + }); +} + +// ---------- 工具分发 ---------- +async function dispatch(name, args) { + if (!TOOLS.some((t) => t.name === name)) + return { isError: true, content: [{ type: "text", text: "未知工具: " + name }] }; + + let plan; + try { plan = planFor(name, args); } + catch (e) { return { isError: true, content: [{ type: "text", text: String(e.message || e) }] }; } + + try { + if (plan.sleep != null) { + await new Promise((r) => setTimeout(r, plan.sleep)); + return { content: [{ type: "text", text: "已等待 " + plan.sleep + "ms" }] }; + } + const r = await extCall(plan.ext, plan.args); + return shapeResult(plan.ext, r); + } catch (e) { + return { isError: true, content: [{ type: "text", text: String(e.message || e) }] }; + } +} + +// ---------- HTTP ---------- +function readBody(req, limit = 5 * 1024 * 1024) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on("data", (c) => { + size += c.length; + if (size > limit) { reject(new Error("body too large")); req.destroy(); return; } + chunks.push(c); + }); + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + req.on("error", reject); + }); +} + +function sendJson(res, status, obj) { + const body = JSON.stringify(obj); + res.writeHead(status, { + "Content-Type": "application/json", + "Cache-Control": "no-store", + }); + res.end(body); +} + +const server = http.createServer(async (req, res) => { + const url = (req.url || "/").split("?")[0].replace(/\/{2,}/g, "/"); + + if (!hostTrusted(req)) { + deny(res, 403, "不可信的 Host(本服务仅限 127.0.0.1/localhost 本机调用,防 DNS 重绑定)"); + return; + } + if (!originTrusted(req)) { + deny(res, 403, "不可信的 Origin(本服务仅限本机进程调用,不接受网页来源)"); + return; + } + + if (req.method === "OPTIONS") { + // 预检同样先过了上面的 Host/Origin 检查;从不返回 Access-Control-Allow-Origin + // (本服务没有浏览器客户端,任何网页来源都读不到响应) + res.writeHead(204, { + "Access-Control-Allow-Methods": "GET, POST, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type", + "Cache-Control": "no-store", + }); + res.end(); + return; + } + + if (req.method === "GET" && (url === "/" || url === "/status")) { + sendJson(res, 200, { + ok: true, + service: SERVER_INFO, + extension_connected: extConnected(), + tools: TOOLS.map((t) => t.name), + }); + return; + } + + if (req.method === "POST" && url === "/tool") { + try { + if (!contentTypeJson(req)) { deny(res, 415, "Content-Type 必须是 application/json"); return; } + const body = JSON.parse(await readBody(req) || "{}"); + const name = body.tool || body.name; + const args = body.arguments || body.args || {}; + if (!name) { sendJson(res, 400, { ok: false, error: "缺少 tool 名称" }); return; } + const result = await dispatch(name, args); + sendJson(res, 200, { ok: !result.isError, result }); + } catch (e) { + sendJson(res, 400, { ok: false, error: String(e.message || e) }); + } + return; + } + + if (req.method === "POST" && url === "/mcp") { + try { + if (!contentTypeJson(req)) { deny(res, 415, "Content-Type 必须是 application/json"); return; } + const body = JSON.parse(await readBody(req) || "null"); + const out = await handleMcp(body, req); + if (out === null) { res.writeHead(202); res.end(); return; } // 通知:无需响应 + sendJson(res, 200, out); + } catch (e) { + sendJson(res, 200, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + (e.message || e) } }); + } + return; + } + + if (req.method === "GET" && url === "/crx/extension.crx") { + log("CRX 分发:Chrome 拉取 extension.crx(UA: " + String(req.headers["user-agent"] || "?").slice(0, 60) + ")"); + const f = path.join(CRX_DIR, "extension.crx"); + fs.readFile(f, (err, data) => { + if (err) { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("crx not packed"); return; } + res.writeHead(200, { "Content-Type": "application/x-chrome-extension", "Content-Length": data.length }); + res.end(data); + }); + return; + } + + if (req.method === "GET" && url === "/crx/updates.xml") { + log("CRX 分发:Chrome 拉取 updates.xml(UA: " + String(req.headers["user-agent"] || "?").slice(0, 60) + ")"); + if (!crxMeta) { res.writeHead(404); res.end("no crx meta"); return; } + const xml = + '\n' + + '\n' + + ' \n' + + ' \n' + + ' \n' + + '\n'; + res.writeHead(200, { "Content-Type": "application/xml" }); + res.end(xml); + return; + } + + if (url === "/mcp") { + res.writeHead(405, { "Content-Type": "application/json", "Allow": "POST, OPTIONS" }); + res.end(JSON.stringify({ error: "MCP over HTTP 仅支持 POST(streamable, stateless)" })); + return; + } + + sendJson(res, 404, { ok: false, error: "not found" }); +}); + +// ---------- MCP(最小 JSON-RPC 实现,stateless streamable HTTP) ---------- +async function handleMcp(body, req) { + if (Array.isArray(body)) { + const results = []; + for (const item of body) { + const r = await handleMcp(item, req); // 逐个处理(无批量工具并发场景) + if (r !== null) results.push(r); + } + return results.length ? results : null; + } + if (!body || typeof body !== "object" || body.jsonrpc !== "2.0") + return { jsonrpc: "2.0", id: body && body.id != null ? body.id : null, error: { code: -32600, message: "Invalid Request" } }; + + const { id, method, params } = body; + const isNotification = id === undefined || id === null; + const reply = (result) => (isNotification ? null : { jsonrpc: "2.0", id, result }); + const replyErr = (code, message) => + isNotification ? null : { jsonrpc: "2.0", id, error: { code, message } }; + + switch (method) { + case "initialize": { + const want = params && params.protocolVersion; + const protocolVersion = SUPPORTED_PROTOCOLS.includes(want) ? want : "2025-06-18"; + return reply({ + protocolVersion, + capabilities: { tools: { listChanged: false } }, + serverInfo: SERVER_INFO, + instructions: INSTRUCTIONS, + }); + } + case "notifications/initialized": + case "notifications/cancelled": + case "notifications/roots/list_changed": + return null; + case "ping": + return reply({}); + case "tools/list": + return reply({ tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) }); + case "tools/call": { + const name = params && params.name; + const args = (params && params.arguments) || {}; + if (!name) return replyErr(-32602, "params.name 必填"); + const result = await dispatch(name, args); + return reply(result); + } + case "resources/list": + return reply({ resources: [] }); + case "prompts/list": + return reply({ prompts: [] }); + default: + return replyErr(-32601, "Method not found: " + method); + } +} + +// ---------- CRX 分发(企业策略 ExtensionInstallForcelist 静默安装用) ---------- +const CRX_DIR = process.env.CRX_DIR || path.join(__dirname, "..", "crx"); +const crxMeta = (() => { + try { return JSON.parse(fs.readFileSync(path.join(CRX_DIR, "meta.json"), "utf8")); } + catch (e) { return null; } +})(); + +// ---------- 启动 ---------- +initWs(server); +server.listen(PORT, HOST, () => { + log(`桥接服务已启动: http://${HOST}:${PORT} (MCP: /mcp, 工具: /tool, 扩展: ws://${HOST}:${PORT}/ws)`); + log("等待 Chrome 扩展连接…"); +}); + +server.on("error", (e) => { + if (e.code === "EADDRINUSE") { + console.error(`端口 ${PORT} 已被占用:可能 bridge.js 已在运行,或修改 PORT 环境变量。`); + } else console.error(e); + process.exit(1); +}); + +function log(msg) { + console.log("[" + new Date().toLocaleTimeString() + "] " + msg); +} diff --git a/external_plugins/cc-browser-bridge/server/endpoint.js b/external_plugins/cc-browser-bridge/server/endpoint.js new file mode 100644 index 00000000..d9c2df10 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/endpoint.js @@ -0,0 +1,73 @@ +// 统一桥接端点解析(唯一实现;launcher / mcp-stdio / onboard 注入共用同一规范结果) +// 规则(R3 修复): +// - BRIDGE_PORT:必须是 1..65535 的十进制整数;非法即明确报错,绝不悄悄回退 8765 +// - BRIDGE_URL:用 URL 严格解析;协议仅 http/https;禁止凭据、查询、与非根路径 +// - 同时设置:远程/HTTPS URL 不能被本地端口覆盖、端口不一致 → 冲突报错; +// 本地 http 且端口一致(或 URL 未写端口)→ 合法,端口取 BRIDGE_PORT +// - manageable(可管理)仅指「本地回环 http 明文端点」:只有它允许拉起/接管本地桥接与引导; +// 远程端点与 HTTPS(含本地回环 https)端点只连接、绝不 spawn 任何本地服务 +// - 规范 url:可管理端点固定 http://127.0.0.1:(本地桥接绑定 127.0.0.1); +// 远程/HTTPS(含 https://localhost、[::1])保留原主机用于连接/TLS-SNI,IPv6 只保留一对括号 +"use strict"; + +const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "0.0.0.0"]); + +function bad(error) { + return { ok: false, error, manageable: false, local: false, secure: false, host: null, port: null, url: null }; +} + +function parseEndpoint(env = process.env) { + const rawUrl = env.BRIDGE_URL === undefined || env.BRIDGE_URL === null ? "" : String(env.BRIDGE_URL).trim(); + const rawPort = env.BRIDGE_PORT === undefined || env.BRIDGE_PORT === null ? "" : String(env.BRIDGE_PORT).trim(); + + let port = null; + if (rawPort !== "") { + if (!/^\d{1,5}$/.test(rawPort)) return bad("BRIDGE_PORT 非法:「" + rawPort + "」必须是 1..65535 的十进制整数(不会回退默认端口)"); + port = Number(rawPort); + if (port < 1 || port > 65535) return bad("BRIDGE_PORT 超出范围:「" + rawPort + "」必须是 1..65535 的整数(不会回退默认端口)"); + } + + if (rawUrl !== "") { + let u; + try { u = new URL(rawUrl); } catch (e) { return bad("BRIDGE_URL 无法解析:「" + rawUrl + "」(不会回退默认端口)"); } + const secure = u.protocol === "https:"; + if (u.protocol !== "http:" && u.protocol !== "https:") return bad("BRIDGE_URL 协议非法:" + u.protocol + "(仅支持 http/https)"); + if (u.username || u.password) return bad("BRIDGE_URL 不得携带用户名/密码凭据"); + if (u.pathname.replace(/\/+$/, "") !== "") return bad("BRIDGE_URL 不支持路径:「" + u.pathname + "」(桥接端点位于根路径)"); + if (u.search || u.hash) return bad("BRIDGE_URL 不支持查询串/片段:" + rawUrl); + // Node 的 URL.hostname 对 IPv6 含方括号(如 "[::1]"):先归一化去括号再匹配 localhost 集合 + const hostRaw = u.hostname.toLowerCase(); + const host = hostRaw.startsWith("[") && hostRaw.endsWith("]") ? hostRaw.slice(1, -1) : hostRaw; + let urlPort; + if (u.port !== "") { + if (!/^\d{1,5}$/.test(u.port)) return bad("BRIDGE_URL 端口非法:" + u.port); + urlPort = Number(u.port); + if (urlPort < 1 || urlPort > 65535) return bad("BRIDGE_URL 端口超出范围:" + u.port); + } else { + urlPort = secure ? 443 : 80; + } + const local = LOCAL_HOSTS.has(host); + if (port !== null) { + if (!local || secure) return bad("BRIDGE_URL 与 BRIDGE_PORT 冲突:远程/HTTPS 端点(" + u.protocol + "//" + u.hostname + ")不能由本地端口覆盖"); + if (u.port !== "" && urlPort !== port) return bad("BRIDGE_URL 与 BRIDGE_PORT 冲突:端口不一致(" + urlPort + " ≠ " + port + ")"); + urlPort = port; // URL 未写显式端口:按优先级 BRIDGE_PORT > BRIDGE_URL[:port] > 8765,由 BRIDGE_PORT 决定端口 + } + // IPv6 主机组装时只保留一对括号 + const hostPart = host.includes(":") ? "[" + host + "]" : host; + if (!local) { + // 远程端点:保留原主机(连接语义),只连接、不管理 + return { ok: true, manageable: false, local: false, secure, host, port: urlPort, url: (secure ? "https://" : "http://") + hostPart + ":" + urlPort }; + } + if (secure) { + // HTTPS(含回环):不可由本地明文 bridge 管理,但连接必须保留原主机(TLS/SNI) + return { ok: true, manageable: false, local: true, secure: true, host, port: urlPort, url: "https://" + hostPart + ":" + urlPort }; + } + // 可管理端点:规范化为 http://127.0.0.1:(本地桥接固定绑定 127.0.0.1) + return { ok: true, manageable: true, local: true, secure: false, host: "127.0.0.1", port: urlPort, url: "http://127.0.0.1:" + urlPort }; + } + + if (port !== null) return { ok: true, manageable: true, local: true, secure: false, host: "127.0.0.1", port, url: "http://127.0.0.1:" + port }; + return { ok: true, manageable: true, local: true, secure: false, host: "127.0.0.1", port: 8765, url: "http://127.0.0.1:8765" }; +} + +module.exports = { parseEndpoint, LOCAL_HOSTS }; diff --git a/external_plugins/cc-browser-bridge/server/fsutil.js b/external_plugins/cc-browser-bridge/server/fsutil.js new file mode 100644 index 00000000..0009d990 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/fsutil.js @@ -0,0 +1,61 @@ +// 受限文件系统工具(R4,针对 Windows 中文路径下 fs.rmSync 幽灵成功的实机证据): +// rmOwnedSync(target):删除「本组件自身创建」的目录/文件—— +// - 不跟随符号链接(lstat 判型;链接本身 unlink,绝不递归进目标,防逃逸) +// - 逐层 unlink + rmdir(Windows 实机验证可靠的原语组合,见 windows-fs-unicode.json) +// - 删除后必须验证不存在;瞬时失败/延迟短暂退避后重试;最终仍存在则抛错, +// 绝不吞掉删除失败后报告成功 +// - 仅用于明确拥有的路径(锁目录 / stage / backup / 自身会话文件),不做任何全局清理 +"use strict"; + +const fs = require("fs"); +const path = require("path"); + +const sleepSync = (ms) => { + try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } catch (e) {} +}; + +function removeOnce(target) { + let st; + try { st = fs.lstatSync(target); } catch (e) { + if (e.code === "ENOENT") return; + throw e; + } + if (st.isDirectory()) { + let names = []; + try { names = fs.readdirSync(target); } catch (e) { + if (e.code === "ENOENT") return; + throw e; + } + for (const name of names) removeOnce(path.join(target, name)); + try { fs.rmdirSync(target); } catch (e) { + if (e.code === "ENOENT") return; + throw e; + } + } else { + try { fs.unlinkSync(target); } catch (e) { + if (e.code === "ENOENT") return; + throw e; + } + } +} + +function rmOwnedSync(target, opts = {}) { + const attempts = Number(opts.attempts || 4); + let lastErr = null; + for (let i = 0; i < attempts; i++) { + try { removeOnce(target); } catch (e) { lastErr = e; } + let exists = true; + try { fs.lstatSync(target); } + catch (e) { + // 只有 ENOENT 才能证明「确实不存在」;其余错误(EACCES/EPERM 等)一律视为仍存在, + // 继续重试并最终抛错——绝不把验证失败当作删除成功(r4-final-finding) + if (e.code === "ENOENT") exists = false; + else if (!lastErr) lastErr = e; + } + if (!exists) return; // 验证通过:确实不存在了 + if (i < attempts - 1) sleepSync(25); // Windows/杀软延迟:短暂退避后重试 + } + throw new Error("删除自身目录/文件后仍存在(疑似文件系统延迟或占用):" + target + (lastErr ? "(最后错误:" + lastErr.message + ")" : "")); +} + +module.exports = { rmOwnedSync }; diff --git a/external_plugins/cc-browser-bridge/server/launcher.js b/external_plugins/cc-browser-bridge/server/launcher.js new file mode 100644 index 00000000..ebf80112 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/launcher.js @@ -0,0 +1,514 @@ +// Browser Bridge 通用启动层(阶段 A):任意本地 stdio MCP 宿主启动 mcp-stdio 时自动准备桥接与首次引导 +// 纯 Node:无 Bash/Homebrew 依赖;stdout 铁律为空(本模块从不写 stdout,诊断走 stderr/日志文件) +// ensureReady(单飞合并、有界预算): +// ① 端点统一解析(server/endpoint.js 唯一实现:BRIDGE_PORT/BRIDGE_URL 严格校验,非法即报错不回退; +// 远程/HTTPS 端点只连接、不拉起本地服务、不触发本地引导) +// ② 桥接幂等:健康则复用(绝不杀);端口被无关程序占用/响应停滞 → 明确报错(绝对时限+体积上限) +// ③ 扩展稳定副本(R3 事务化更新):源清单校验(manifest+必需文件+manifest 声明的 icons 全部必需, +// 缺任何必需源明确失败且不触发引导)→ 完整暂存候选(逐文件复制后哈希回读校验)→ 整目录原子交换; +// 交换失败恢复完整旧目录,禁止新旧混杂;未知文件保留;marker 输入验证(schema/白名单/哈希格式/ +// 路径不得逃逸/拒绝符号链接),非法 marker 拒绝接管且绝不按其清单删除任何文件; +// 清理仅限自身命名模式的 stage/old 临时目录;崩溃恢复(dest 缺失而 old 存在时先还原) +// ④ 完成标记迁移(旧安装根只读复制);首次引导按「共享 home + 桥接端点」去重(跨安装目录单次) +// 稳定目录(默认 ~/.browser-bridge,BROWSER_BRIDGE_HOME 可覆盖):extension/ state/ logs/ locks/ +// 布局:bridge/onboard 始终取自「本次运行的安装目录」(layoutRoot 指定或本文件所在 server 目录), +// 保证多客户端各自运行自己安装副本的代码,同时共享同一 home/端点的服务与会话 + +const http = require("http"); +const fs = require("fs"); +const path = require("path"); +const os = require("os"); +const crypto = require("crypto"); +const { spawn } = require("child_process"); +const onboard = require("./onboard"); +const endpoint = require("./endpoint"); +const { rmOwnedSync } = require("./fsutil"); + +const BRIDGE_WAIT_MS = 6000; +const LOCK_GRACE_MS = 10000; +const EXT_LOCK_WAIT_MS = 15000; +const EXT_REQUIRED = ["manifest.json", "background.js", "popup.html", "popup.js"]; +const EXT_WHITELIST = [ + "manifest.json", "background.js", "popup.html", "popup.js", + "icons/icon16.png", "icons/icon48.png", "icons/icon128.png", "icons/icon256.png", +]; +const MARKER_NAME = ".source-manifest.json"; + +const log = (...a) => { try { process.stderr.write("[launcher] " + a.join(" ") + "\n"); } catch (e) {} }; +const sha256File = (f) => { + const h = crypto.createHash("sha256"); + h.update(fs.readFileSync(f)); + return h.digest("hex"); +}; +const filesSig = (files) => Object.keys(files).sort().map((k) => k + ":" + files[k]).join("\n"); + +// ---------- 相对路径安全:无绝对路径、无 .. 逃逸 ---------- +function isSafeRel(rel) { + if (typeof rel !== "string" || rel === "" || rel.includes("\0")) return false; + if (path.isAbsolute(rel)) return false; + const norm = path.normalize(rel); + if (norm === "." || norm.startsWith("..")) return false; + return true; +} + +// ---------- 桥接健康探测:绝对时限 + 响应体积上限 + abort/error 全路径收敛 ---------- +// state: ours(本服务)/ foreign(有响应但不是本服务)/ stalled(监听存在但超时/超大/异常,视为占用)/ down(无监听) +function bridgeStatus(port, timeoutMs = 1200) { + return new Promise((resolve) => { + let done = false, size = 0, res = null, req = null; + const chunks = []; + const finish = (v) => { + if (done) return; + done = true; + clearTimeout(timer); + try { if (res) res.destroy(); } catch (e) {} + try { if (req) req.destroy(); } catch (e) {} + resolve(v); + }; + const timer = setTimeout(() => finish({ state: "stalled", reason: "deadline" }), timeoutMs); + try { + req = http.get({ host: "127.0.0.1", port, path: "/status" }, (r) => { + res = r; + res.on("data", (c) => { + size += c.length; + if (size > 65536) return finish({ state: "stalled", reason: "oversize" }); + chunks.push(c); + }); + res.on("end", () => { + try { + const j = JSON.parse(Buffer.concat(chunks).toString("utf8")); + const svc = j && j.service; + const name = svc && typeof svc === "object" ? svc.name : svc; + if (name === "cc-browser-bridge" && j.ok === true) return finish({ state: "ours", info: j }); + } catch (e) {} + finish({ state: "foreign" }); + }); + res.on("aborted", () => finish({ state: "stalled", reason: "aborted" })); + res.on("error", () => finish({ state: "stalled", reason: "response-error" })); + }); + req.on("error", () => finish({ state: "down" })); + } catch (e) { finish({ state: "down" }); } + }); +} +const notOurs = (st, port) => + st.state === "foreign" + ? "端口 " + port + " 已被其他程序占用(不是 Browser Bridge 桥接)。请释放该端口,或用 BRIDGE_PORT 指定其他端口后重启客户端。" + : "端口 " + port + " 有监听但响应异常/超时(可能被其他程序占用)。请检查该端口或改用 BRIDGE_PORT。"; + +// ---------- 原子锁(初始化宽限 + 死 pid 接管 + 所有权释放) ---------- +// 删除一律用 fsutil.rmOwnedSync:unlink+rmdir、不跟随符号链接、删除后验证, +// 失败可见(Windows 中文路径下 fs.rmSync 存在「返回成功但仍存在」的实机证据) +function lockStep(dir, ttlMs) { + const pidFile = path.join(dir, "pid.json"); + const take = () => { + try { fs.mkdirSync(dir); } catch (e) { return false; } + try { fs.writeFileSync(pidFile, JSON.stringify({ pid: process.pid, at: Date.now() })); } catch (e) {} + return true; + }; + if (take()) return "acquired"; + let info = null; + try { info = JSON.parse(fs.readFileSync(pidFile, "utf8")); } catch (e) {} + if (info && Number.isInteger(info.pid)) { + let alive = false; + try { process.kill(info.pid, 0); alive = true; } catch (e) {} + if (alive && Date.now() - (info.at || 0) < ttlMs) return "held"; + try { rmOwnedSync(dir); } catch (e) { return "busy"; } // 接管失败(删不掉)如实报告,不假装成功 + return take() ? "acquired" : "busy"; + } + let age = Infinity; + try { age = Date.now() - fs.statSync(dir).mtimeMs; } catch (e) {} + if (age < LOCK_GRACE_MS) return "held"; + try { rmOwnedSync(dir); } catch (e) { return "busy"; } + return take() ? "acquired" : "busy"; +} +function lockRelease(dir) { + try { + const info = JSON.parse(fs.readFileSync(path.join(dir, "pid.json"), "utf8")); + if (info.pid === process.pid) { + try { rmOwnedSync(dir); } + catch (e) { log("锁目录释放失败(他人将按陈旧锁接管重试):" + e.message); } + } + } catch (e) {} +} +async function lockAcquireWait(dir, ttlMs, waitMs) { + const deadline = Date.now() + waitMs; + for (;;) { + const r = lockStep(dir, ttlMs); + if (r === "acquired") return "acquired"; + if (Date.now() > deadline) return r; + await new Promise((r2) => setTimeout(r2, 120)); + } +} + +// ---------- 桥接幂等启动 ---------- +let launchCount = 0; +async function ensureBridge(o) { + const st = await bridgeStatus(o.port); + if (st.state === "ours") return { ok: true, reused: true }; + if (st.state !== "down") return { ok: false, reason: notOurs(st, o.port) }; + + fs.mkdirSync(path.join(o.home, "locks"), { recursive: true }); + const lockDir = path.join(o.home, "locks", "bridge-" + o.port + ".lock"); + const lock = await lockAcquireWait(lockDir, BRIDGE_WAIT_MS + LOCK_GRACE_MS, BRIDGE_WAIT_MS); + if (lock !== "acquired") { + const deadline = Date.now() + BRIDGE_WAIT_MS; // 他人正在启动:有界等待其就绪 + while (Date.now() < deadline) { + const s2 = await bridgeStatus(o.port); + if (s2.state === "ours") return { ok: true, reused: true }; + if (s2.state !== "down") return { ok: false, reason: notOurs(s2, o.port) }; + await new Promise((r) => setTimeout(r, 250)); + } + return { ok: false, reason: "等待其他进程启动桥接超时;日志见 " + path.join(o.home, "logs") }; + } + try { + const s2 = await bridgeStatus(o.port); + if (s2.state === "ours") return { ok: true, reused: true }; + if (s2.state !== "down") return { ok: false, reason: notOurs(s2, o.port) }; + + fs.mkdirSync(path.join(o.home, "logs"), { recursive: true }); + const logFile = path.join(o.home, "logs", "bridge-" + o.port + ".log"); + const fd = fs.openSync(logFile, "a"); + launchCount++; + const child = spawn(process.execPath, [o.bridgePath], { + cwd: path.dirname(o.bridgePath), + env: { ...process.env, PORT: String(o.port) }, + detached: true, stdio: ["ignore", fd, fd], + }); + child.unref(); + try { fs.closeSync(fd); } catch (e) {} + try { fs.writeFileSync(path.join(o.home, "state", "bridge-" + o.port + ".pid"), JSON.stringify({ pid: child.pid, at: Date.now() })); } catch (e) {} + + const deadline = Date.now() + BRIDGE_WAIT_MS; + for (;;) { + const s3 = await bridgeStatus(o.port); + if (s3.state === "ours") return { ok: true, pid: child.pid }; + if (s3.state !== "down") return { ok: false, reason: notOurs(s3, o.port) }; + if (Date.now() > deadline) return { ok: false, reason: "桥接启动超时(端口 " + o.port + ");日志 " + logFile }; + await new Promise((r) => setTimeout(r, 250)); + } + } finally { + lockRelease(lockDir); + } +} + +// ---------- 扩展稳定副本:源清单校验 / marker 输入验证 / 事务化整目录交换 ---------- +function declaredIcons(manifest) { + const out = new Set(); + const push = (v) => { + if (typeof v !== "string" || v === "") throw new Error("manifest 声明的 icon 路径非法:" + JSON.stringify(v)); + if (!isSafeRel(v)) throw new Error("manifest 声明的 icon 路径越界:" + v); + out.add(path.normalize(v).split(path.sep).join("/")); + }; + if (manifest.icons !== undefined) { + if (!manifest.icons || typeof manifest.icons !== "object" || Array.isArray(manifest.icons)) throw new Error("manifest.icons 结构非法"); + for (const k of Object.keys(manifest.icons)) push(manifest.icons[k]); + } + const act = manifest.action; + if (act && act.default_icon !== undefined) { + const di = act.default_icon; + if (typeof di === "string") push(di); + else if (di && typeof di === "object" && !Array.isArray(di)) for (const k of Object.keys(di)) push(di[k]); + else throw new Error("manifest.action.default_icon 结构非法"); + } + return out; +} + +// marker 是外部输入,必须完整验证后才能信任: +// schema / 版本格式 / files 至少包含全部 EXT_REQUIRED(空 files 或缺关键条目不认定受管)/ +// 白名单 / 哈希格式 / 路径逃逸 / 符号链接(含受管路径的父级目录,绝不跟随) +const MARKER_VERSION_RE = /^\d+\.\d+(\.\d+)?(-[0-9A-Za-z.]+)?$/; // 兼容 0.5.2 / 9.9.8 等真实历史版本 +function readMarker(destDir) { + const markerFile = path.join(destDir, MARKER_NAME); + let st; + try { st = fs.lstatSync(markerFile); } catch (e) { return { status: "none" }; } + if (st.isSymbolicLink()) return { status: "invalid", reason: "指纹标记是符号链接" }; + let m; + try { m = JSON.parse(fs.readFileSync(markerFile, "utf8")); } catch (e) { return { status: "invalid", reason: "指纹标记不是合法 JSON" }; } + if (!m || typeof m !== "object" || Array.isArray(m)) return { status: "invalid", reason: "指纹标记结构非法" }; + if (typeof m.version !== "string" || !MARKER_VERSION_RE.test(m.version)) return { status: "invalid", reason: "指纹标记 version 非法:" + JSON.stringify(m.version) }; + if (!m.files || typeof m.files !== "object" || Array.isArray(m.files)) return { status: "invalid", reason: "指纹标记缺少 files" }; + for (const req of EXT_REQUIRED) { + if (!(req in m.files)) return { status: "invalid", reason: "指纹标记 files 缺少必需受管条目:" + req }; + } + const destReal = path.resolve(destDir); + const files = {}; + for (const rel of Object.keys(m.files)) { + if (!isSafeRel(rel)) return { status: "invalid", reason: "受管文件路径越界:" + rel }; + if (!EXT_WHITELIST.includes(rel)) return { status: "invalid", reason: "受管文件不在合法白名单:" + rel }; + const h = m.files[rel]; + if (typeof h !== "string" || !/^[0-9a-f]{64}$/.test(h)) return { status: "invalid", reason: "受管文件哈希格式非法:" + rel }; + const f = path.resolve(destDir, rel); + if (!f.startsWith(destReal + path.sep)) return { status: "invalid", reason: "受管文件路径逃逸:" + rel }; + // 受管路径的每个父级目录(destDir 内部)必须是真实目录:符号链接一律拒绝,绝不跟随 + const segs = rel.split("/"); + let cur = destDir; + for (let i = 0; i < segs.length - 1; i++) { + cur = path.join(cur, segs[i]); + let pst = null; + try { pst = fs.lstatSync(cur); } catch (e) {} + if (pst && (pst.isSymbolicLink() || !pst.isDirectory())) return { status: "invalid", reason: "受管路径的父级不是真实目录(拒绝符号链接跟随):" + rel }; + } + let fst = null; + try { fst = fs.lstatSync(f); } catch (e) {} + if (fst && fst.isSymbolicLink()) return { status: "invalid", reason: "受管文件是符号链接:" + rel }; + files[rel] = h; + } + return { status: "valid", version: m.version, files }; +} + +// 把旧目录中的「未知文件」复制进暂存目录(R4 fail closed): +// - 任何读取/复制失败都必须让整次更新失败,完整保留旧目录——绝不吞错、绝不静默丢弃未知数据 +// - 符号链接不跟随、不读目标内容:以链接自身形式原样重建保留(安全保留,防逃逸) +// - 不使用宽泛的「*.tmp-数字」模式跳过用户未知文件(历史残留一律按未知数据保留) +// - 目录不可读/特殊文件(FIFO 等)→ 明确失败 +function copyUnknownInto(srcDir, stageDir, skip) { + const walk = (rel) => { + const abs = rel ? path.join(srcDir, rel) : srcDir; + let entries; + try { entries = fs.readdirSync(abs, { withFileTypes: true }); } + catch (e) { throw new Error("未知数据目录不可读:" + (rel || ".") + "(" + (e.message || e) + "),拒绝更新以保留旧目录"); } + for (const e of entries) { + const childRel = rel ? rel + "/" + e.name : e.name; + const childAbs = path.join(srcDir, childRel); + const target = path.join(stageDir, childRel); + let st; + try { st = fs.lstatSync(childAbs); } + catch (e2) { throw new Error("未知数据状态读取失败:" + childRel + "(" + (e2.message || e2) + "),拒绝更新以保留旧目录"); } + if (st.isSymbolicLink()) { + const linkTarget = fs.readlinkSync(childAbs); // 只读链接本身,绝不解析/跟随目标 + try { fs.symlinkSync(linkTarget, target); } + catch (e2) { throw new Error("未知符号链接保留失败:" + childRel + "(" + (e2.message || e2) + "),拒绝更新以保留旧目录"); } + continue; + } + if (st.isDirectory()) { + fs.mkdirSync(target, { recursive: true }); + walk(childRel); + continue; + } + if (!st.isFile()) throw new Error("未知条目不是常规文件/目录/符号链接:" + childRel + ",拒绝更新以保留旧目录"); + if (childRel === MARKER_NAME) continue; + if (skip.has(childRel)) continue; + try { fs.copyFileSync(childAbs, target); } + catch (e2) { throw new Error("未知文件复制失败:" + childRel + "(" + (e2.message || e2) + "),拒绝更新以保留旧目录"); } + } + }; + walk(""); +} + +// 崩溃恢复 + 只清理「自身命名模式」的交换临时目录(持锁期间无并发同步者) +function recoverSwapDirs(parent, base, destDir) { + let entries = []; + try { entries = fs.readdirSync(parent); } catch (e) { return; } + const pat = new RegExp("^\\." + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.(stage|old)-\\d+-\\d+$"); + let oldFound = null; + for (const n of entries) { + if (!pat.test(n)) continue; + if (n.includes(".old-")) oldFound = n; + else { try { rmOwnedSync(path.join(parent, n)); } catch (e) { log("残留 stage 清理失败(下次启动重试):" + e.message); } } + } + if (oldFound) { + // 上一进程死在「旧目录已让位、新目录未就位」之间:先完整还原旧目录再继续 + if (!fs.existsSync(destDir)) { + try { fs.renameSync(path.join(parent, oldFound), destDir); return; } catch (e) {} + } + try { rmOwnedSync(path.join(parent, oldFound)); } catch (e) { log("残留 old 备份清理失败(下次启动重试):" + e.message); } + } +} + +function syncExtensionTo(srcDir, destDir, opts = {}) { + // ---- 源清单校验(进入锁前;缺任何必需源——包括 manifest 声明的 icons——都明确失败,绝不 ok:skip)---- + if (!srcDir || typeof srcDir !== "string") return { ok: false, reason: "扩展源目录未提供(无法定位安装布局),保留现有副本" }; + let manifest; + try { manifest = JSON.parse(fs.readFileSync(path.join(srcDir, "manifest.json"), "utf8")); } + catch (e) { return { ok: false, reason: "扩展源缺少可解析的 manifest.json(" + (e.message || e) + "),保留现有副本" }; } + if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) return { ok: false, reason: "扩展源 manifest.json 结构非法,保留现有副本" }; + if (typeof manifest.version !== "string" || manifest.version === "") return { ok: false, reason: "扩展源 manifest.json 缺少有效 version,保留现有副本" }; + let declared; + try { declared = declaredIcons(manifest); } catch (e) { return { ok: false, reason: "扩展源 " + (e.message || e) + ",保留现有副本" }; } + const required = new Set(EXT_REQUIRED); + for (const ic of declared) required.add(ic); + for (const rel of required) { + let isFile = false; + try { isFile = fs.statSync(path.join(srcDir, rel)).isFile(); } catch (e) {} + if (!isFile) return { ok: false, reason: "扩展源缺少必需文件 " + rel + "(manifest 声明的 icons 同样必需),保留现有副本" }; + } + const cand = []; + for (const rel of EXT_WHITELIST) { + let isFile = false; + try { isFile = fs.statSync(path.join(srcDir, rel)).isFile(); } catch (e) {} + if (isFile) cand.push(rel); + } + cand.sort(); + const fp = { version: manifest.version, files: {} }; + for (const rel of cand) fp.files[rel] = sha256File(path.join(srcDir, rel)); + + const lockDir = destDir + ".sync.lock"; + return (async () => { + const lock = await lockAcquireWait(lockDir, EXT_LOCK_WAIT_MS, EXT_LOCK_WAIT_MS); + if (lock !== "acquired") return { ok: false, reason: "扩展目录同步忙(其他进程持有锁),本次跳过,下次启动重试" }; + try { + const parent = path.dirname(destDir); + const base = path.basename(destDir); + fs.mkdirSync(parent, { recursive: true }); + recoverSwapDirs(parent, base, destDir); + + const destExists = fs.existsSync(destDir); + let mk = { status: "none" }; + if (destExists) { + let dst = null; + try { dst = fs.lstatSync(destDir); } catch (e) {} + if (dst && dst.isSymbolicLink()) return { ok: false, reason: "目标目录是符号链接,拒绝接管:" + destDir }; + mk = readMarker(destDir); + if (mk.status === "none") return { ok: false, reason: "目标目录已存在且缺少本组件指纹标记,拒绝接管(保留未知数据):" + destDir }; + if (mk.status === "invalid") + return { ok: false, reason: "目标目录指纹标记非法/损坏(" + mk.reason + "),拒绝接管(保留未知数据,绝不按其清单删除任何文件):" + destDir }; + if (mk.version === fp.version && filesSig(mk.files) === filesSig(fp.files)) { + let intact = true; + for (const rel of Object.keys(fp.files)) { + const f = path.join(destDir, rel); + let actual = null; + try { actual = fs.readFileSync(f); } catch (e) {} + if (!actual || sha256File(f) !== fp.files[rel]) { intact = false; break; } + } + if (intact) return { ok: true, updated: false, dir: destDir }; + } + } + + // ---- 事务化更新:完整暂存(哈希回读校验)→ 整目录交换 → 失败恢复完整旧目录 ---- + const tag = process.pid + "-" + Date.now(); + const stage = path.join(parent, "." + base + ".stage-" + tag); + const backup = path.join(parent, "." + base + ".old-" + tag); + let swapped = false; + try { + fs.mkdirSync(stage); + for (const rel of cand) { + const target = path.join(stage, rel); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.copyFileSync(path.join(srcDir, rel), target); + if (sha256File(target) !== fp.files[rel]) throw new Error("暂存副本哈希校验失败:" + rel); + } + if (destExists) copyUnknownInto(destDir, stage, new Set([...Object.keys(mk.files), ...cand])); + fs.writeFileSync(path.join(stage, MARKER_NAME), JSON.stringify(fp, null, 2)); + if (destExists) fs.renameSync(destDir, backup); + try { + fs.renameSync(stage, destDir); + swapped = true; + } catch (e) { + if (destExists) fs.renameSync(backup, destDir); // 交换失败:完整恢复旧目录,禁止新旧混杂 + throw e; + } + let backupWarning = null; + if (destExists) { + try { rmOwnedSync(backup); } + catch (e) { backupWarning = "旧备份清理失败(下次启动自动重试):" + e.message; log(backupWarning); } + } + return backupWarning ? { ok: true, updated: true, dir: destDir, warning: backupWarning } : { ok: true, updated: true, dir: destDir }; + } catch (e) { + try { rmOwnedSync(stage); } catch (e2) {} // stage 为自身暂存目录;清理失败时它匹配自身命名模式,下次启动恢复清理 + if (!swapped && destExists && !fs.existsSync(destDir) && fs.existsSync(backup)) { + try { fs.renameSync(backup, destDir); } catch (e3) {} // 最后保险:任何路径下都不允许丢失旧目录 + } + return { ok: false, reason: "扩展副本更新失败(保留完整旧内容,下次启动重试):" + (e && e.message || e) }; + } + } finally { + lockRelease(lockDir); + } + })(); +} + +// ---------- 完成标记迁移(旧安装根 → 稳定目录;只读复制,不删旧) ---------- +function migrateStateTo(legacyFile, targetFile) { + try { + if (!fs.existsSync(legacyFile) || fs.existsSync(targetFile)) return false; + fs.mkdirSync(path.dirname(targetFile), { recursive: true }); + fs.copyFileSync(legacyFile, targetFile); + return true; + } catch (e) { return false; } +} + +// ---------- 首次引导触发(去重键 = 共享 home + 桥接端点,跨安装目录单次) ---------- +function onboardPreGate(stateFile) { + try { + const s = JSON.parse(fs.readFileSync(stateFile, "utf8")); + if (s && (s.completedAt || s.autoOpenedAt)) return false; + } catch (e) {} + return true; +} +function triggerOnboarding(o) { + const sessionFile = path.join(o.home, "state", "onboard-session-" + o.port + ".json"); + try { + fs.mkdirSync(path.join(o.home, "logs"), { recursive: true }); + const fd = fs.openSync(path.join(o.home, "logs", "onboard.log"), "a"); + const child = spawn(process.execPath, [o.onboardPath, "--auto"], { + cwd: path.dirname(o.onboardPath), + env: { + ...process.env, + ONBOARD_STATE_FILE: o.stateFile, + ONBOARD_SESSION_FILE: sessionFile, + ONBOARD_HOME: o.home, // 会话身份绑定共享 home(跨安装目录复用同一引导实例) + ONBOARD_EXT_DIR: o.extDir, + ONBOARD_BRIDGE_URL: "http://127.0.0.1:" + o.port, // 引导服务探测与桥接同端点(自定义端口一致) + }, + detached: true, stdio: ["ignore", fd, fd], + }); + child.on("error", (e) => { log("触发引导失败: " + e.message); }); + child.unref(); + try { fs.closeSync(fd); } catch (e) {} + return true; + } catch (e) { log("触发引导失败: " + e.message); return false; } +} + +// ---------- 总入口:单飞合并 ---------- +let inFlight = null; +function ensureReady(opts = {}) { + if (inFlight) return inFlight; + inFlight = runEnsure(opts).finally(() => { inFlight = null; }); + return inFlight; +} +async function runEnsure(opts) { + const ep = endpoint.parseEndpoint(opts.env || process.env); + if (!ep.ok) return { ok: false, stage: "endpoint", reason: ep.error, endpoint: ep }; + + const home = path.resolve(opts.home || process.env.BROWSER_BRIDGE_HOME || path.join(os.homedir(), ".browser-bridge")); + const port = Number(opts.port || ep.port); + // bridge/onboard 始终取自本次运行的安装目录(不同客户端副本各自运行自己的代码,仅共享 home/端点) + const serverDir = opts.layoutRoot ? path.join(opts.layoutRoot, "server") : __dirname; + const layout = onboard.resolveLayout(serverDir); + const o = { + home, port, layout, + bridgePath: path.join(serverDir, "bridge.js"), + onboardPath: path.join(serverDir, "onboard.js"), + extDir: path.join(home, "extension"), + stateFile: path.join(home, "state", "onboard-complete.json"), + }; + fs.mkdirSync(path.join(home, "state"), { recursive: true }); + + if (!ep.manageable) { + const why = ep.secure ? "HTTPS" : "远程"; + log("BRIDGE_URL=" + ep.url + " 为" + why + "端点:仅连接该地址,不启动/管理本地桥接,也不触发本地引导"); + return { ok: true, skipped: ep.secure ? "secure-bridge" : "remote-bridge", endpoint: ep, onboarding: { skipped: ep.secure ? "secure" : "remote" } }; + } + + const br = await ensureBridge(o); + if (!br.ok) return { ok: false, stage: "bridge", reason: br.reason, endpoint: ep }; + + const ext = await syncExtensionTo(layout.extDir, o.extDir, opts); + migrateStateTo(path.join(layout.root, ".onboard-state.json"), o.stateFile); + + if (!ext.ok) { + // 源损坏/同步失败:明确失败并保留旧版,绝不引导用户加载不完整目录(下次启动自动重试) + log(ext.reason); + return { ok: true, bridge: br, ext, onboarding: { skipped: "ext-sync-failed" }, endpoint: ep }; + } + + let onboarding = { skipped: "complete" }; + if (opts.noOnboarding !== true && onboardPreGate(o.stateFile)) { + onboarding = { triggered: triggerOnboarding(o) }; + } + return { ok: true, bridge: br, ext, onboarding, endpoint: ep }; +} + +module.exports = { + ensureReady, + _test: { bridgeStatus, ensureBridge, syncExtensionTo, migrateStateTo, onboardPreGate, parseEndpoint: endpoint.parseEndpoint, lockStep, launchCount: () => launchCount }, +}; diff --git a/external_plugins/cc-browser-bridge/server/mcp-stdio.js b/external_plugins/cc-browser-bridge/server/mcp-stdio.js new file mode 100644 index 00000000..7f2ee0ba --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/mcp-stdio.js @@ -0,0 +1,175 @@ +#!/usr/bin/env node +// Claude API Browser Bridge — MCP stdio 入口(Claude Desktop / 其他 stdio MCP 客户端用) +// 用法:node mcp-stdio.js (需 bridge.js 已在运行;地址可用 BRIDGE_URL 环境变量覆盖) +// 协议:按行分隔的 JSON-RPC 2.0(MCP stdio transport) + +const readline = require("readline"); +const { TOOLS } = require("./tools"); +const launcher = require("./launcher"); +const { parseEndpoint } = require("./endpoint"); + +// 统一端点(R3):与 launcher 使用同一 parseEndpoint 规范结果;只设 BRIDGE_PORT 时 MCP 实际 +// 请求地址与其完全一致;非法配置明确报错(不悄悄回退 8765);远程/HTTPS 端点只连接、不 spawn 本地 +const EP = parseEndpoint(process.env); +const BRIDGE_URL = EP.ok ? EP.url : "http://127.0.0.1:8765"; +const BODY_LIMIT_BYTES = Number(process.env.MCP_BODY_LIMIT_BYTES || 64 * 1024 * 1024); // 截图等大响应的合理上限 +const SERVER_INFO = { name: "cc-browser-bridge", version: "0.1.0" }; +const SUPPORTED_PROTOCOLS = ["2024-11-05", "2025-03-26", "2025-06-18"]; +const INSTRUCTIONS = + "通过这套工具可以查看和控制用户当前使用的 Chrome 浏览器(保留用户登录态)。" + + "推荐流程:browser_tabs list → browser_navigate → browser_snapshot(拿 ref)→ browser_click/browser_type;" + + "需要看视觉布局时用 browser_screenshot,其返回的截图坐标可直接用于 browser_click 的 x/y。"; + +function write(obj) { + process.stdout.write(JSON.stringify(obj) + "\n"); +} + +function err2stderr(e) { + process.stderr.write("[mcp-stdio] " + (e && e.message ? e.message : String(e)) + "\n"); +} + +// 阶段 A 通用启动层:进程启动即后台准备桥接/稳定目录/首次引导(不阻塞 MCP 握手;本模块 stdout 恒为纯协议) +const AUTO_ENSURE = process.env.BB_AUTO_ENSURE !== "0"; +if (!EP.ok) { + err2stderr(new Error("[endpoint] " + EP.error + ";工具调用将失败,请修正 BRIDGE_URL/BRIDGE_PORT 后重启客户端")); +} else if (AUTO_ENSURE) { + launcher.ensureReady() + .then((r) => { if (!r.ok) err2stderr("[launcher] " + r.reason); }) + .catch((e) => err2stderr("[launcher] " + (e.message || e))); +} + +// 有界响应读取:流式累积并检查体积上限(截图允许较大但仍必须有界),配合下面的绝对截止 +async function readBodyBounded(res) { + const reader = res.body.getReader(); + const chunks = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.length; + if (size > BODY_LIMIT_BYTES) { + try { await reader.cancel(); } catch (e) {} + throw new Error("桥接响应体积超过上限 " + BODY_LIMIT_BYTES + " 字节"); + } + chunks.push(Buffer.from(value)); + } + return Buffer.concat(chunks).toString("utf8"); +} + +async function callOnce(name, args) { + if (!EP.ok) throw new Error("桥接端点配置非法:" + EP.error); + const res = await fetch(EP.url + "/tool", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ tool: name, arguments: args }), + signal: AbortSignal.timeout(Number(process.env.MCP_CALL_TIMEOUT_MS || 10000)), // 绝对时限,防停滞响应 + }); + let text; + try { text = await readBodyBounded(res); } catch (e) { throw new Error("桥接响应读取失败(" + (e.message || e) + ")"); } + let body = null; + try { body = JSON.parse(text); } catch (e) {} + if (body === null) + throw new Error("桥接端口返回不可用响应(HTTP " + res.status + ")"); // 非 JSON(如端口被无关程序占用)→ 走启动层恢复路径 + if (!body.ok) + return { + isError: true, + content: [{ type: "text", text: (body.result && body.result.content && body.result.content[0] && body.result.content[0].text) || body.error || ("HTTP " + res.status) }], + }; + return body.result; +} + +async function callBridge(name, args) { + try { + return await callOnce(name, args); + } catch (e) { + if (!EP.ok) + return { isError: true, content: [{ type: "text", text: "桥接端点配置非法:" + EP.error }] }; + if (!AUTO_ENSURE || !EP.manageable) + return { + isError: true, + content: [{ + type: "text", + text: EP.manageable + ? "无法连接桥接服务 " + EP.url + ":请先运行 node bridge.js(" + (e.message || e) + ")" + : "无法连接桥接服务 " + EP.url + "(" + (EP.secure ? "HTTPS" : "远程") + "端点仅连接、不启动本地服务;" + (e.message || e) + ");请确认该端点可达", + }], + }; + // 有界等待通用启动层修复后重试一次;失败给出可理解原因(端口被占/启动超时/日志位置) + const r = await launcher.ensureReady(); + if (!r.ok) + return { isError: true, content: [{ type: "text", text: "桥接服务不可用:" + r.reason }] }; + try { + return await callOnce(name, args); + } catch (e2) { + return { + isError: true, + content: [{ type: "text", text: "无法连接桥接服务 " + EP.url + "(" + (e2.message || e2) + ");日志见 ~/.browser-bridge/logs/" }], + }; + } + } +} + +async function handleMessage(msg) { + const { id, method, params } = msg; + const isNotification = id === undefined || id === null; + const reply = (result) => { if (!isNotification) write({ jsonrpc: "2.0", id, result }); }; + const replyErr = (code, message) => { if (!isNotification) write({ jsonrpc: "2.0", id, error: { code, message } }); }; + + switch (method) { + case "initialize": { + const want = params && params.protocolVersion; + reply({ + protocolVersion: SUPPORTED_PROTOCOLS.includes(want) ? want : "2025-06-18", + capabilities: { tools: { listChanged: false } }, + serverInfo: SERVER_INFO, + instructions: INSTRUCTIONS, + }); + break; + } + case "notifications/initialized": + case "notifications/cancelled": + break; + case "ping": + reply({}); + break; + case "tools/list": + reply({ tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) }); + break; + case "tools/call": { + const name = params && params.name; + const args = (params && params.arguments) || {}; + if (!name) { replyErr(-32602, "params.name 必填"); break; } + try { reply(await callBridge(name, args)); } + catch (e) { replyErr(-32603, String(e.message || e)); } + break; + } + case "resources/list": + reply({ resources: [] }); + break; + case "prompts/list": + reply({ prompts: [] }); + break; + default: + replyErr(-32601, "Method not found: " + method); + } +} + +const rl = readline.createInterface({ input: process.stdin }); +let inFlight = 0; +rl.on("line", (line) => { + const s = line.trim(); + if (!s) return; + let msg; + try { msg = JSON.parse(s); } catch (e) { err2stderr(new Error("非 JSON 行已忽略")); return; } + inFlight++; + Promise.resolve(handleMessage(msg)) + .catch(err2stderr) + .finally(() => { inFlight--; }); +}); +// stdin 关闭后等在途请求完成再退出(fetch 会保持事件循环) +rl.on("close", () => { + const tryExit = () => (inFlight <= 0 ? process.exit(0) : setTimeout(tryExit, 50)); + tryExit(); +}); + +err2stderr("stdio MCP 入口已就绪,桥接地址: " + (EP.ok ? EP.url : "(无效配置:" + EP.error + ")")); diff --git a/external_plugins/cc-browser-bridge/server/onboard-state.js b/external_plugins/cc-browser-bridge/server/onboard-state.js new file mode 100644 index 00000000..a6e5ef5f --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/onboard-state.js @@ -0,0 +1,216 @@ +// cc-browser-bridge 引导页状态机(浏览器与 node --test 共用;无 DOM、无定时器依赖) +// 页面通过 createStateMachine(io) 注入渲染/请求能力;行为测试直接驱动 handle/poll/performDone。 +// 关键行为: +// - 每次状态迁移都由真实 /api/status 结果驱动;成功状态可被失败/断开撤回 +// - 暂停恢复、服务恢复(含未装扩展回到等待安装)、pass→fail 撤回均有明确迁移 +// - 轮询单飞(不堆叠)、旧响应丢弃、连续失联进入 offlineNet 并自动重试恢复 +// - /api/done 必须以 POST 成功才宣告完成,失败不假装已关闭 +(function (root, factory) { + if (typeof module === "object" && module.exports) module.exports = factory(); + else root.OnboardState = factory(); +})(typeof self !== "undefined" ? self : this, function () { + "use strict"; + + const TITLES = { + loading: ["正在检查连接状态", "确认桥接服务与 Chrome 扩展的当前状态,稍等…", 1], + start: ["为客户端连接 Chrome", "首次设置一次,以后直接在 ZCode 等客户端聊天中调用浏览器。", 1], + install: ["加载 Chrome 扩展", "只需完成下面的操作,加载后引导会自动继续。", 2], + checking: ["验证浏览器连接", "保留这个窗口,正在确认浏览器工具能否正常访问。", 3], + success: ["开始在客户端使用浏览器", "", 3], + offline: ["与 Chrome 的连接断开了", "请确认 Chrome 已打开且扩展处于启用状态,我们会持续检测。", 3], + paused: ["已连接,控制已暂停", "在 Chrome 中打开 Browser Bridge 扩展面板,关闭「暂停」开关后,点重新检测继续。", 3], + svcdown: ["本地桥接服务未运行", "引导需要桥接服务在客户端与 Chrome 扩展之间转发调用。", 2], + offlineNet: ["与引导服务的连接中断", "引导服务可能已退出或正在重启,正在自动重试;也可重跑 /cc-browser-setup 获取新页面。", 2], + expired: ["引导会话不可用", "页面令牌缺失或已过期(引导服务可能已重启)。请重新运行 /cc-browser-setup,或在 Finder 双击 setup.command。", 2], + done: ["引导完成", "可以关闭此页面,回到客户端继续聊天。", 3], + }; + const MISSES_TO_OFFLINE = 3; + + function createStateMachine(io) { + let state = "loading", prevStep = 1, reentryNote = false, deepPhase = false; + let ensureTried = false, doneSent = false, installSince = 0, slowShown = false; + let lastTabsKey = "", svcFrom = "", last = null; + let missCount = 0, inFlight = null, seq = 0, infoObj = null; + const sleep = io.sleep || ((ms) => new Promise((r) => setTimeout(r, ms))); + const isExpired = (e) => String((e && e.message) || e) === "expired"; + + function titlesFor(next) { + const conf = TITLES[next] || TITLES.loading; + let step = conf[2]; + if (next === "svcdown" || next === "offlineNet" || next === "expired") step = prevStep; + else prevStep = step; + const subtitle = next === "success" + ? (reentryNote ? "检测到 Chrome 扩展已连接,无需重复安装。" : "读取、点击、填写和截图,都从你的客户端聊天开始。") + : conf[1]; + return { title: conf[0], subtitle, step }; + } + + function setState(next) { + state = next; + if (next === "install") { installSince = Date.now(); slowShown = false; } + io.setTitles(titlesFor(next)); + io.render(next, { status: last, reentry: reentryNote }); + return next; + } + + function renderChecking(t) { + io.render("checking", { tabs: t, bridge: last && last.bridge, reentry: reentryNote }); + } + + function updateChecking(s) { + const t = s.tabs || { state: "pending" }; + const key = t.state + ":" + (t.paused ? "p" : "") + (t.count != null ? ":" + t.count : "") + ":" + (t.error || ""); + if (key !== lastTabsKey) { lastTabsKey = key; renderChecking(t); } + if (t.state === "pass") { deepPhase = true; setState("success"); } + else if (t.paused) setState("paused"); + } + + function updateInstallWait() { + if (!slowShown && Date.now() - installSince > 120000) { slowShown = true; io.installWaitSlow(); } + } + + function handle(s) { + last = s; + const b = s.bridge || {}; + if (!b.up) { + if (state !== "svcdown" && state !== "offlineNet" && state !== "expired") { + if (!ensureTried) { ensureTried = true; io.ensureBridge(); } + else { svcFrom = state; setState("svcdown"); } + } + return; + } + ensureTried = false; + const ext = !!b.extension_connected; + if (state === "loading" || state === "start") { + if (ext) { reentryNote = true; setState("checking"); updateChecking(s); } + else if (state === "loading") setState("start"); + return; + } + if (state === "install") { + if (ext) setState("checking"); + else updateInstallWait(); + return; + } + if (state === "checking") { + if (!ext) setState(deepPhase ? "offline" : "install"); + else updateChecking(s); + return; + } + if (state === "svcdown" || state === "offlineNet") { + if (ext) { setState("checking"); updateChecking(s); } + else if (deepPhase) setState("offline"); + else if (svcFrom === "install") setState("install"); + else setState("start"); + return; + } + if (state === "paused") { + if (!ext) setState("offline"); + else if (s.tabs && !s.tabs.paused) { setState("checking"); updateChecking(s); } + return; + } + if (state === "success") { + if (!ext) { reentryNote = false; setState("offline"); return; } + const t = s.tabs; + if (t && t.paused) { setState("paused"); return; } + if (t && t.state === "fail") { setState("checking"); updateChecking(s); return; } + return; + } + if (state === "offline") { + if (ext) { setState("checking"); updateChecking(s); } + return; + } + } + + async function pollOnce(fresh) { + if (doneSent || state === "expired") return { dropped: true }; + if (io.isHidden && io.isHidden()) return { skipped: true }; // 页面隐藏时停轮询,恢复可见补检 + const my = ++seq; + try { + const s = await io.request("/api/status" + (fresh ? "?fresh=1" : "")); + if (doneSent || my !== seq) return { dropped: true }; + missCount = 0; + // R2-2:info 曾失败(offlineNet 恢复路径)时必须重新取得,否则页面误判平台/目录为空 + if (!infoObj) { + try { + const j = await io.request("/api/info"); + if (j && j.ok) { infoObj = j; if (io.setInfo) io.setInfo(j); } + } catch (e) { + if (isExpired(e)) { setState("expired"); return { ok: false, error: "expired" }; } + } + } + if (state === "offlineNet") setState(svcFrom && svcFrom !== "offlineNet" ? svcFrom : "loading"); + handle(s); + return { ok: true }; + } catch (e) { + if (doneSent || my !== seq) return { dropped: true }; + if (isExpired(e)) { setState("expired"); return { ok: false, error: "expired" }; } + missCount++; + if (missCount >= MISSES_TO_OFFLINE && state !== "offlineNet" && state !== "expired") { + svcFrom = state; + setState("offlineNet"); + } + return { ok: false, error: String((e && e.message) || e) }; + } + } + + function poll(fresh) { + if (inFlight) return inFlight; + inFlight = pollOnce(fresh).finally(() => { inFlight = null; }); + return inFlight; + } + + async function start() { + setState("loading"); + for (let i = 0; i < 3; i++) { + try { + const j = await io.request("/api/info"); + if (j && j.ok) { infoObj = j; break; } + } catch (e) { + if (isExpired(e)) { setState("expired"); return; } + } + if (i < 2) await sleep(500); + } + if (!infoObj) { svcFrom = "loading"; setState("offlineNet"); return; } + if (io.setInfo) io.setInfo(infoObj); + await poll(true); + } + + async function prepare() { + try { + const r = await io.request("/api/prepare", { method: "POST", body: "{}" }); + const fails = [r.opened, r.revealed].filter((x) => x && !x.ok); + if (fails.length) { io.showPrepareError(fails.map((x) => x.reason).join(";")); return false; } + setState("install"); + return true; + } catch (e) { + if (isExpired(e)) { setState("expired"); return false; } + io.showPrepareError("请求失败:" + String((e && e.message) || e)); + return false; + } + } + + async function performDone() { + try { + const j = await io.request("/api/done", { method: "POST", body: "{}" }); + if (!j || j.ok !== true) throw new Error("bad response"); + doneSent = true; + setState("done"); + return true; + } catch (e) { + if (isExpired(e)) { setState("expired"); return false; } + io.notice("完成请求失败,引导服务可能仍在运行;可直接关闭本页,服务稍后会自动退出"); + return false; + } + } + + return { + get state() { return state; }, + get info() { return infoObj; }, + get doneSent() { return doneSent; }, + setState, handle, poll, start, prepare, performDone, + recheck() { lastTabsKey = ""; setState("checking"); poll(true); }, + }; + } + + return { createStateMachine, TITLES }; +}); diff --git a/external_plugins/cc-browser-bridge/server/onboard-ui.html b/external_plugins/cc-browser-bridge/server/onboard-ui.html new file mode 100644 index 00000000..2e1c1d06 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/onboard-ui.html @@ -0,0 +1,217 @@ + + + +连接 Chrome · 首次使用引导 + + +
Browser Bridge 免费插件
首次使用引导
+
让 AI 连接你正在使用的浏览器

为客户端连接 Chrome

首次设置一次,以后直接在 ZCode 等客户端聊天中调用浏览器。

1打开安装页面2加载 Chrome 扩展3验证与试用
+ + + diff --git a/external_plugins/cc-browser-bridge/server/onboard.js b/external_plugins/cc-browser-bridge/server/onboard.js new file mode 100644 index 00000000..cd23bd89 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/onboard.js @@ -0,0 +1,753 @@ +#!/usr/bin/env node +// cc-browser-bridge 首次连接引导:独立本机 HTTP 服务 + 启动器(随插件分发,无新增依赖) +// 服务模式:node onboard.js 监听 127.0.0.1,提供引导页与受控 API +// 启动器: node onboard.js --launch 复用/拉起服务并打开引导页(macOS open / Windows chrome.exe);stdout 只输出带令牌的 URL +// 自动模式:node onboard.js --auto 会话钩子用:未展示过且扩展未连接时打开一次(退避+并发去重,stdout 恒空) +// 安全边界(与 bridge.js 同风格,互相独立): +// - 只监听 127.0.0.1;Host 仅限 127.0.0.1/localhost/[::1]+端口(防 DNS 重绑定) +// - /api/* 拒绝一切网页 Origin,唯一例外是本服务自身 Origin(引导页同源 fetch) +// - 一次性会话令牌:crypto.randomBytes(24),timing-safe 比较;会话文件 0600 +// - 副作用仅三个固定动作:open_extensions / reveal_folder 由 platform-actions 平台适配层 +// 产出 spawn 固定参数数组(不经 shell、不接受客户端传入的路径/命令);win32 的 GUI 打开 +// (chrome.exe)按「spawn 确认已发起打开 + 有界观察」处理——绝不因浏览器主进程常驻而 kill; +// ensure_bridge 复用阶段 A 纯 Node 启动层(无 Bash/Git Bash/WSL 依赖,Windows 原生可运行) +// - 不代理 /tool /mcp,不提供通用命令执行;空闲 30 分钟或寿命 2 小时自动退出 + +const http = require("http"); +const fs = require("fs"); +const path = require("path"); +const crypto = require("crypto"); +const os = require("os"); +const { spawn } = require("child_process"); +const { rmOwnedSync } = require("./fsutil"); +const platformActions = require("./platform-actions"); +const endpoint = require("./endpoint"); + +const VERSION = "0.6.0-rc.2"; +const SERVICE = "cc-browser-onboard"; +const DEFAULT_PORT = Number(process.env.ONBOARD_PORT || 8791); +const PORT_SPAN = 10; +const BRIDGE_URL = (process.env.ONBOARD_BRIDGE_URL || "http://127.0.0.1:8765").replace(/\/+$/, ""); +const SHELL_DISABLED = process.env.ONBOARD_SHELL_DISABLED === "1"; +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const MAX_LIFE_MS = 2 * 60 * 60 * 1000; +const TABS_CACHE_MS = 5000; +// 桥接 home 默认与 launcher.ensureReady 同一规则:ONBOARD_HOME(launcher 注入)优先, +// 其次 BROWSER_BRIDGE_HOME,最后 ~/.browser-bridge;ensure_bridge 动作按此复用纯 Node 启动能力 +const bridgeHomeOf = () => + (HOME_SCOPE && String(HOME_SCOPE).trim()) || + (process.env.BROWSER_BRIDGE_HOME && String(process.env.BROWSER_BRIDGE_HOME).trim()) || + path.join(os.homedir(), ".browser-bridge"); + +// ---------- 布局自定位:插件目录(plugins/cc-browser-bridge/server)或项目仓库(server) ---------- +function resolveLayout(baseDir) { + const root = path.resolve(baseDir, ".."); + const pluginScript = path.join(root, "hooks", "start-bridge.sh"); + const repoScript = path.join(root, "plugins", "cc-browser-bridge", "hooks", "start-bridge.sh"); + if (fs.existsSync(path.join(root, ".zcode-plugin"))) + return { mode: "plugin", root, extDir: path.join(root, "extension"), + startBridge: null }; + if (fs.existsSync(repoScript)) + return { mode: "repo", root, extDir: path.join(root, "extension"), + startBridge: { cmd: "bash", args: [repoScript, path.join(root, "plugins", "cc-browser-bridge", "server"), path.join(root, "plugins", "cc-browser-bridge")] } }; + return { mode: "unknown", root, extDir: null, startBridge: null }; +} +const LAYOUT = resolveLayout(__dirname); +// 稳定扩展目录覆盖(阶段 A 通用启动层传入 ~/.browser-bridge/extension,升级后加载路径不变;不设置时沿用安装目录) +const EXT_DIR = process.env.ONBOARD_EXT_DIR || null; +const extDirOf = () => EXT_DIR || LAYOUT.extDir; +const UI_FILE = path.join(__dirname, "onboard-ui.html"); +const STATE_FILE = path.join(__dirname, "onboard-state.js"); + +// 会话身份(R3):launcher 注入 ONBOARD_SESSION_FILE(位于共享 home/state)+ ONBOARD_HOME 时, +// 会话按「共享 home + 桥接端点」去重——不同安装目录的客户端复用同一引导实例; +// 独立运行(未注入 home)时保持按「规范化安装根」隔离 +const ROOT_NORM = (() => { try { return fs.realpathSync(LAYOUT.root); } catch (e) { return LAYOUT.root; } })(); +const HOME_SCOPE = (process.env.ONBOARD_HOME && String(process.env.ONBOARD_HOME).trim()) || null; +function sessionFileFor(rootNorm) { + const h = crypto.createHash("sha256").update(String(rootNorm) + "|" + SERVICE).digest("hex").slice(0, 12); + return path.join(os.tmpdir(), "cc-onboard-" + h + ".json"); +} +const SESSION_FILE = process.env.ONBOARD_SESSION_FILE || sessionFileFor(ROOT_NORM); + +// ---------- 自动引导(--auto):完成状态 / 节流退避 / 并发去重 ---------- +// autoOpenedAt 只表示引导已展示,不代表用户完成引导或客户端验收通过。 +// 已完成/已展示不因版本变化重开;--launch 始终允许用户主动重开。 +const AUTO_STATE_FILE = process.env.ONBOARD_STATE_FILE || path.join(LAYOUT.root, ".onboard-state.json"); +const AUTO_ATTEMPT_FILE = SESSION_FILE + ".auto-attempt.json"; +const AUTO_LOCK_DIR = SESSION_FILE + ".auto.lock"; +const AUTO_BACKOFF_MS = [60 * 1000, 5 * 60 * 1000, 15 * 60 * 1000]; // 连续失败退避(封顶 15 分钟) +const AUTO_WAIT_MS = Number(process.env.ONBOARD_AUTO_WAIT_MS || 12000); +const AUTO_LOCK_TTL_MS = 120 * 1000; +const AUTO_INIT_GRACE_MS = 10 * 1000; // pid.json 未写出的初始化宽限:不得把并发者的新锁当陈旧互删 + +function readJsonFile(f) { try { return JSON.parse(fs.readFileSync(f, "utf8")); } catch (e) { return null; } } + +// 兼容旧版成功 attempt:以前只有十分钟节流,现在成功展示过就不再自动弹。 +function shouldAutoOpen(o) { + const s = o.state, a = o.attempt; + if (s && s.completedAt) return { open: false, reason: "completed" }; + if (s && s.autoOpenedAt) return { open: false, reason: "shown" }; + if (a && Number.isFinite(a.at)) { + if (a.failures === 0) return { open: false, reason: "shown" }; + const wait = AUTO_BACKOFF_MS[Math.min(a.failures, AUTO_BACKOFF_MS.length) - 1]; + if (o.now - a.at < wait) return { open: false, reason: "backoff" }; + } + return { open: true, reason: "first" }; +} + +function noteShown(at = Date.now()) { + const s = readJsonFile(AUTO_STATE_FILE) || {}; + if (s.autoOpenedAt || s.completedAt) return; + try { + fs.mkdirSync(path.dirname(AUTO_STATE_FILE), { recursive: true }); + fs.writeFileSync(AUTO_STATE_FILE, JSON.stringify({ autoOpenedAt: new Date(at).toISOString(), version: VERSION }, null, 2), { mode: 0o600, flag: "wx" }); + } catch (e) { + // 用户可能同时点完成:独占创建避免覆盖另一个进程刚写入的完成状态。 + if (e.code !== "EEXIST") console.error("引导展示记录写入失败: " + e.message); + } +} + +// 打开动作的并发去重:mkdir 原子锁。与 R2 服务锁同策略: +// - 初始化宽限:pid.json 未写出且锁龄 <10s 视为他人持有(并发启动不得互删新锁) +// - 接管仅限:持锁进程已死、或锁龄超 TTL 的滞留锁 +// - 所有权释放:只删除 pid.json 中是自己 pid 的锁,绝不删别人的 +let autoLockOwned = false; +function autoLockAcquire() { + const tryTake = () => { + try { fs.mkdirSync(AUTO_LOCK_DIR); } catch (e) { return false; } + try { fs.writeFileSync(path.join(AUTO_LOCK_DIR, "pid.json"), JSON.stringify({ pid: process.pid, at: Date.now() })); } catch (e) {} + autoLockOwned = true; + return true; + }; + if (tryTake()) return "acquired"; + const info = readJsonFile(path.join(AUTO_LOCK_DIR, "pid.json")); + if (info && Number.isInteger(info.pid)) { + if (pidAlive(info.pid) && Date.now() - (info.at || 0) < AUTO_LOCK_TTL_MS) return "held"; + try { rmOwnedSync(AUTO_LOCK_DIR); } catch (e) { return "busy"; } // 接管失败如实报告(不假装成功) + return tryTake() ? "acquired" : "busy"; + } + let age = Infinity; + try { age = Date.now() - fs.statSync(AUTO_LOCK_DIR).mtimeMs; } catch (e) {} + if (age < AUTO_INIT_GRACE_MS) return "held"; + try { rmOwnedSync(AUTO_LOCK_DIR); } catch (e) { return "busy"; } + return tryTake() ? "acquired" : "busy"; +} +function autoLockRelease() { + if (!autoLockOwned) return; + autoLockOwned = false; + const info = readJsonFile(path.join(AUTO_LOCK_DIR, "pid.json")); + if (info && info.pid === process.pid) { + try { rmOwnedSync(AUTO_LOCK_DIR); } + catch (e) { console.error("auto 锁释放失败(他人将按陈旧锁接管重试):" + e.message); } + } +} + +let completionNoted = false; +// 完成状态只能由用户在引导页明确点「完成引导」(POST /api/done)写入; +// 后台健康/连接探测(含只读 tabs 通过)不算用户引导完成,绝不写 completed +function markComplete() { + if (completionNoted) return; + completionNoted = true; + try { + fs.writeFileSync(AUTO_STATE_FILE, JSON.stringify({ completedAt: new Date().toISOString(), version: VERSION, updatedAt: new Date().toISOString() }, null, 2), { mode: 0o600 }); + } catch (e) { console.error("完成状态写入失败: " + e.message); } +} + +function writeAutoAttempt(failures) { + try { fs.writeFileSync(AUTO_ATTEMPT_FILE, JSON.stringify({ at: Date.now(), failures }, null, 2), { mode: 0o600 }); } catch (e) {} +} + +async function autoLaunch() { + const dbg = (...a) => { if (process.env.ONBOARD_AUTO_DEBUG === "1") console.error("[auto] " + a.join(" ")); }; + const decide = () => shouldAutoOpen({ state: readJsonFile(AUTO_STATE_FILE), attempt: readJsonFile(AUTO_ATTEMPT_FILE), version: VERSION, now: Date.now() }); + const pre = decide(); // 锁前预判只是快速路径 + if (!pre.open) { + // 把旧版成功 attempt 迁入持久状态,临时会话文件清理后仍不重复弹。 + if (pre.reason === "shown") noteShown((readJsonFile(AUTO_ATTEMPT_FILE) || {}).at); + dbg("skip:", pre.reason); return 0; + } + const lock = autoLockAcquire(); + if (lock !== "acquired") { dbg("skip: lock " + lock); return 0; } + try { + // 锁内必须重判:等锁期间前一个进程可能已完成打开并写了 attempt/状态, + // 用旧判定的排队者不得再打开(真实并发只允许一次打开动作) + const decision = decide(); + if (!decision.open) { dbg("skip after lock:", decision.reason); return 0; } + const bridge = await bridgeStatus(); + if (bridge.up && bridge.extension_connected) { dbg("skip: connected"); return 0; } + let url = await existingUrl(); + if (!url) { + const child = spawn(process.execPath, [__filename], { detached: true, stdio: ["ignore", "ignore", "ignore"], env: process.env }); + child.unref(); + url = await waitForExistingSession(AUTO_WAIT_MS); + } + if (!url) { + const prev = readJsonFile(AUTO_ATTEMPT_FILE); + writeAutoAttempt(((prev && prev.failures) || 0) + 1); + dbg("server not healthy"); + return 0; + } + const opened = await openUrl(url); + if (!opened || !opened.ok) { + // 打开失败必须可观测:记失败进入退避;绝不把失败当成功、绝不升级完成状态 + const prev = readJsonFile(AUTO_ATTEMPT_FILE); + writeAutoAttempt(((prev && prev.failures) || 0) + 1); + dbg("open failed:", (opened && opened.reason) || "unknown"); + return 0; + } + writeAutoAttempt(0); + noteShown(); + dbg("opened"); + return 0; + } finally { + autoLockRelease(); + } +} + +// ---------- 固定动作表(唯一的副作用入口;参数全部来自安装位置计算) ---------- +// open_extensions / reveal_folder:platform-actions 适配层按真实平台产出参数数组 +// macOS:open -a "Google Chrome" chrome://extensions/ 与 open -R <目录> +// Windows:标准位置查找 chrome.exe 后 --new-window 打开;explorer.exe <目录>(固定路径参数) +// ensure_bridge:复用阶段 A 纯 Node 启动层(见 ensureBridgeViaLauncher) +const ACTIONS = { + open_extensions: {}, + reveal_folder: {}, + ensure_bridge: {}, +}; + +// ---------- Windows GUI 进程寿命(阶段 B R2):spawn 确认「已发起打开」+ 有界观察,绝不因常驻 kill ---------- +// chrome.exe 打开 chrome://extensions/ 或引导页时有两种真实寿命:冷启动时该进程就是浏览器主进程 +// (长驻);已有实例时移交 URL 后很快退出 0。旧的「等 close + 15s SIGKILL」会把常驻当挂起: +// 误杀用户浏览器并谎报失败;openUrl 等 close 则无限挂起(--auto 永不返回)。 +// 语义(仅用于 gui:true 的动作):spawn error → 失败(无法创建进程);观察窗内退出 0 → 成功(移交); +// 观察窗内非零退出 → 失败(即时失败);观察窗结束仍存活 → 成功(已发起打开,绝不代表 Chrome 已连接)。 +// stdio 全 ignore + detached + 立即 unref:解除子进程/管道/父寿命引用(Windows 上仅 unref 不够, +// 父启动器退出会连带关闭 GUI 子进程),子进程不阻塞本进程事件循环也从不过继父寿命;从不调用 kill。 +const GUI_ACTION_WATCH_MS = 4000; // 按钮动作观察窗(远小于引导页 15s 请求截止,页面不会超时) +const GUI_OPENURL_WATCH_MS = 15000; // 自动/启动器打开 URL 的观察窗(有界;移交场景通常几百毫秒内即返回) +function spawnGuiBounded(cmd, args, watchMs) { + return new Promise((res) => { + let settled = false, timer = null; + let p; + try { + // Windows 实机证据(stage-b-gui-parent-exit-findings):仅 unref 不足以脱离父寿命—— + // 启动器退出时 GUI 子进程仍被连带关闭(Chrome 冷启动窗口随 --launch 返回而消失)。 + // Node 语义:Windows 上 detached:true 使子进程在父退出后继续运行;stdio 全 ignore + // 避免新控制台窗口并解除管道引用;unref 解除事件循环引用。三者组合=脱离父寿命且不阻塞本进程。 + p = spawn(cmd, args, { detached: true, stdio: ["ignore", "ignore", "ignore"] }); + } catch (e) { + // Windows 实机证据(stage-b-r2-windows-findings):spawn 对不可执行文件等会同步抛异常 + // (UNKNOWN/EINVAL)。executor 内的同步 throw 会把 Promise 变成 raw rejection, + // 调用边界一旦未处理即崩溃——这里与异步 error 事件一致返回结构化错误,本函数绝不 reject + return res({ ok: false, reason: "无法执行 " + cmd + ": " + (e && e.code ? e.code + " " : "") + (e && e.message || e) }); + } + try { p.unref(); } catch (e) {} + const finish = (v) => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + try { p.removeListener("exit", onExit); p.removeListener("error", onError); } catch (e) {} + res(v); + }; + const onExit = (code, signal) => { + if (code === 0) return finish({ ok: true, handedOff: true }); + finish({ ok: false, reason: "退出码 " + code + (signal ? "(信号 " + signal + ")" : "") + "(浏览器进程立即退出)" }); + }; + const onError = (e) => finish({ ok: false, reason: "无法执行 " + cmd + ": " + (e && e.message || e) }); + p.on("spawn", () => { + if (!(Number(watchMs) > 0)) return finish({ ok: true, launched: true }); + timer = setTimeout(() => finish({ ok: true, launched: true }), watchMs); // 仍存活=已发起打开;绝不 kill + }); + p.on("exit", onExit); + p.on("error", onError); + }); +} + +// Chrome 可执行文件(仅 Windows 需要显式查找;macOS 由 open -a 定位) +const chromePathOf = () => (process.platform === "win32" ? platformActions.findChromeWin() : null); + +// ensure_bridge 动作:惰性 require launcher,规避 launcher↔onboard 循环依赖 +// (launcher 顶层 require 本模块;运行期再取 launcher 时两边均已加载完成,也不会重复拉起: +// 复用 ensureReady 的健康检查/原子锁/幂等语义,且 noOnboarding 阻止引导自触发) +async function ensureBridgeViaLauncher() { + const ep = endpoint.parseEndpoint({ BRIDGE_URL }); + if (!ep.ok) return { ok: false, reason: "桥接端点配置非法:" + ep.error }; + if (!ep.manageable) + return { ok: false, reason: "桥接端点 " + ep.url + " 为远程/HTTPS 端点,引导不启动本地服务;请确认该端点可达" }; + const launcher = require("./launcher"); + const r = await launcher.ensureReady({ + home: bridgeHomeOf(), port: ep.port, layoutRoot: LAYOUT.root, + noOnboarding: true, env: process.env, + }); + if (!r.ok) return { ok: false, reason: r.reason }; // 端口被无关程序占用/启动超时等,如实报告 + return { ok: true, reused: !!(r.bridge && r.bridge.reused), home: bridgeHomeOf(), port: ep.port }; +} + +function runAction(name) { + if (name === "ensure_bridge") { + if (SHELL_DISABLED) + return Promise.resolve({ ok: false, reason: "本地打开/启动动作已被禁用(ONBOARD_SHELL_DISABLED=1)" }); + return ensureBridgeViaLauncher().catch((e) => ({ ok: false, reason: "启动桥接失败:" + (e && e.message || e) })); + } + return new Promise((res) => { + const def = ACTIONS[name]; + if (!def) return res({ ok: false, reason: "未知动作: " + name }); + if (SHELL_DISABLED) return res({ ok: false, reason: "本地打开/启动动作已被禁用(ONBOARD_SHELL_DISABLED=1)" }); + const ed = extDirOf(); + if (name === "reveal_folder" && (!ed || !fs.existsSync(ed))) + return res({ ok: false, reason: "扩展目录不存在: " + ed }); + let argv = null; + if (name === "open_extensions") { + const plan = platformActions.openExtensionsPlan(process.platform); + if (!plan) return res({ ok: false, reason: platformActions.UNSUPPORTED_REASON }); + if (plan.kind === "manual") + // Windows(R5):Chromium 拒绝 chrome:// 命令行导航——如实返回人工导航契约(非服务错误), + // 绝不发起只会得到空白新标签页的无效 Chrome 子进程 + return res({ ok: true, manualRequired: true, url: plan.url, reason: plan.reason }); + argv = [plan.cmd, ...plan.args]; // darwin:open 短命命令,退出码语义 + } else { + const built = platformActions.revealFolderArgs(process.platform, ed); + if (!built) return res({ ok: false, reason: platformActions.UNSUPPORTED_REASON }); + argv = [built.cmd, ...built.args]; + } + const p = spawn(argv[0], argv.slice(1), { stdio: ["ignore", "pipe", "pipe"] }); + let err = ""; + p.stdout.on("data", () => {}); + p.stderr.on("data", (d) => { err += String(d); }); + const timer = setTimeout(() => { try { p.kill("SIGKILL"); } catch (e) {} }, 15000); + p.on("error", (e) => { clearTimeout(timer); res({ ok: false, reason: "无法执行 " + argv[0] + ": " + e.message }); }); + p.on("close", (code) => { + clearTimeout(timer); + // explorer.exe 把打开请求移交给既有资源管理器进程后常以退出码 1 结束(即使成功打开窗口), + // 这是 Windows 既有行为;除该组合外,非零退出码一律如实视为失败 + const lenient = name === "reveal_folder" && process.platform === "win32" && code === 1; + if (code !== 0 && !lenient) + return res({ ok: false, reason: "退出码 " + code + (err.trim() ? ":" + err.trim().slice(0, 300) : "") }); + res({ ok: true }); + }); + }); +} + +// ---------- 与桥接的受控交互(本机进程身份:无 Origin 头,不触碰 bridge 安全边界) ---------- +// 有界响应:绝对截止(AbortSignal.timeout)+ 体积上限(超限即失败,绝不无限累积) +async function fetchJsonBounded(url, init, timeoutMs, maxBytes) { + const res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); + const reader = res.body.getReader(); + const chunks = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.length; + if (size > maxBytes) { try { await reader.cancel(); } catch (e) {} throw new Error("响应体积超过上限 " + maxBytes + " 字节"); } + chunks.push(Buffer.from(value)); + } + return { status: res.status, ok: res.ok, json: JSON.parse(Buffer.concat(chunks).toString("utf8")) }; +} + +async function bridgeStatus() { + try { + const r = await fetchJsonBounded(BRIDGE_URL + "/status", {}, 2000, 64 * 1024); + if (!r.ok) return { up: false }; + return { up: !!r.json.ok, extension_connected: !!r.json.extension_connected }; + } catch (e) { return { up: false }; } +} + +// 结构校验:绝不只看 ok 字符串;每个条目都要有有限数字 tab_id;结果只保留数量,不含标题/网址 +function validateTabsPayload(body) { + const text = body && body.result && Array.isArray(body.result.content) && body.result.content[0] && body.result.content[0].text; + if (!body || typeof body !== "object" || body.ok !== true) + return { state: "fail", error: String(text || (body && body.error) || "工具调用未成功"), paused: /已被暂停/.test(String(text || "")) }; + if (!text || body.result.content[0].type !== "text") + return { state: "fail", error: "返回结构缺少 text 内容", paused: false }; + let parsed; + try { parsed = JSON.parse(text); } catch (e) { return { state: "fail", error: "标签页结果不是合法 JSON", paused: false }; } + if (!parsed || !Array.isArray(parsed.tabs)) return { state: "fail", error: "返回结构中没有 tabs 数组", paused: false }; + for (const t of parsed.tabs) { + if (!t || typeof t !== "object" || !Number.isFinite(t.tab_id)) + return { state: "fail", error: "标签页条目缺少有效的数字型 tab_id", paused: false }; + } + return { state: "pass", count: parsed.tabs.length }; // 空数组是合法结构(count 0) +} + +async function bridgeTabs() { + let body = null; + try { + const r = await fetchJsonBounded(BRIDGE_URL + "/tool", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ tool: "browser_tabs", arguments: { action: "list" } }), + }, 12000, 8 * 1024 * 1024); + if (!r.ok) return { state: "fail", error: "桥接 HTTP " + r.status, paused: false }; // HTTP 错误即使正文像 ok 也判失败 + body = r.json; + } catch (e) { + return { state: "fail", error: "无法调用桥接 /tool:" + (e.message || e), paused: false }; + } + return validateTabsPayload(body); +} + +let tabsCache = { at: 0, val: { state: "skip" } }; +let tabsInFlight = null; +async function tabsChecked(fresh) { + if (!fresh && Date.now() - tabsCache.at < TABS_CACHE_MS) return tabsCache.val; + if (tabsInFlight) return tabsInFlight; + tabsInFlight = bridgeTabs().then((v) => { tabsCache = { at: Date.now(), val: v }; tabsInFlight = null; return v; }); + return tabsInFlight; +} + +async function statusPayload(fresh) { + const b = await bridgeStatus(); + if (!b.up || !b.extension_connected) { + tabsCache = { at: 0, val: { state: "skip" } }; // 扩展离线后缓存作废,重连即重查 + return { bridge: { ...b, url: BRIDGE_URL }, tabs: { state: "skip" } }; + } + // 注意:后台连接健康/只读验证通过不写完成状态——完成只能由用户在引导页点「完成引导」 + return { bridge: { ...b, url: BRIDGE_URL }, tabs: await tabsChecked(fresh) }; +} + +// ---------- 请求边界 ---------- +function hostOk(req, port) { + const h = String(req.headers.host || "").toLowerCase(); + return h === "127.0.0.1:" + port || h === "localhost:" + port || h === "[::1]:" + port; +} +function originOk(req, port) { + const o = req.headers.origin; + if (o === undefined || o === "") return true; // 本机进程(curl/测试)不发 Origin + return o === "http://127.0.0.1:" + port || o === "http://localhost:" + port; // 仅引导页自身 +} +function ctJson(req) { + const ct = String(req.headers["content-type"] || "").trim(); + if (ct === "") return true; + return /^application\/json\b/i.test(ct); +} +function readBody(req, limit = 64 * 1024) { + return new Promise((resolve, reject) => { + let size = 0; const chunks = []; + req.on("data", (c) => { size += c.length; if (size > limit) { reject(new Error("body too large")); req.destroy(); return; } chunks.push(c); }); + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + req.on("error", reject); + }); +} + +// ---------- HTTP 服务 ---------- +let TOKEN = null, PORT = 0, UI_HTML = null, STATE_JS = null; +let startedAt = 0, lastTouch = 0; + +function sendJson(res, status, obj) { + const body = JSON.stringify(obj); + res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" }); + res.end(body); +} +const deny = (res, msg) => sendJson(res, 403, { ok: false, error: msg }); + +async function handler(req, res) { + try { + const u = new URL(req.url, "http://127.0.0.1"); + const pathname = u.pathname.replace(/\/{2,}/g, "/"); + if (!hostOk(req, PORT)) return deny(res, "不可信的 Host(仅限 127.0.0.1/localhost 本机调用,防 DNS 重绑定)"); + + // /api/* 一律先拒绝网页来源(含 health;本机进程不发 Origin,不受影响) + if (pathname.startsWith("/api/") && !originOk(req, PORT)) + return deny(res, "不可信的 Origin(仅限本机进程与引导页自身)"); + + if (req.method === "OPTIONS") { + // 与 bridge 相同策略:过完 Host/Origin 检查;不返回任何 CORS 授权头(本服务唯一的浏览器客户端是同源引导页) + res.writeHead(204, { "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Cache-Control": "no-store" }); + return res.end(); + } + + if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) { + res.writeHead(200, { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "Content-Security-Policy": "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'", + }); + return res.end(UI_HTML); + } + + if (req.method === "GET" && pathname === "/onboard-state.js") { + res.writeHead(200, { + "Content-Type": "application/javascript; charset=utf-8", + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + }); + return res.end(STATE_JS); + } + + if (req.method === "GET" && pathname === "/api/health") + return sendJson(res, 200, { ok: true, service: SERVICE, version: VERSION }); + + if (!pathname.startsWith("/api/")) return sendJson(res, 404, { ok: false, error: "not found" }); + + if (!tokenOk(req, u)) return deny(res, "会话令牌缺失或无效"); + lastTouch = Date.now(); + + if (req.method === "GET" && pathname === "/api/info") { + // 真实平台/可用性:不把「Windows 平台」假设为已装 Chrome——chrome_found 每次如实探测; + // open_supported 只表示管理页可自动导航;Windows 需人工粘贴地址,文件夹动作另行报告。 + const ep = endpoint.parseEndpoint({ BRIDGE_URL }); + const chromePath = chromePathOf(); + const extOk = !!extDirOf() && fs.existsSync(extDirOf()); + return sendJson(res, 200, { + ok: true, platform: process.platform, + open_supported: process.platform === "darwin" && extOk, + manual_navigation: process.platform === "win32", + reveal_supported: (process.platform === "darwin" || process.platform === "win32") && extOk, + chrome_found: process.platform === "win32" ? !!chromePath : null, + chrome_path: chromePath, + ext_dir: extDirOf(), ext_dir_exists: extOk, + bridge_url: BRIDGE_URL, bridge_port: ep.ok ? ep.port : null, bridge_home: bridgeHomeOf(), + mode: LAYOUT.mode, + }); + } + + if (req.method === "GET" && pathname === "/api/status") + return sendJson(res, 200, { ok: true, ...(await statusPayload(u.searchParams.get("fresh") === "1")) }); + + if (req.method === "POST" && (pathname === "/api/prepare" || pathname === "/api/action" || pathname === "/api/done")) { + if (!ctJson(req)) return sendJson(res, 415, { ok: false, error: "Content-Type 必须是 application/json" }); + let parsed = {}; + try { const raw = await readBody(req); parsed = raw ? JSON.parse(raw) : {}; } + catch (e) { return sendJson(res, 400, { ok: false, error: "非法请求正文" }); } + if (pathname === "/api/done") { + markComplete(); + sendJson(res, 200, { ok: true }); + setTimeout(() => cleanupExit(0), 200); + return; + } + if (pathname === "/api/prepare") { + const opened = await runAction("open_extensions"); + const revealed = await runAction("reveal_folder"); + return sendJson(res, 200, { ok: !!(opened.ok && revealed.ok), opened, revealed }); + } + const name = String((parsed && parsed.action) || ""); + if (!ACTIONS[name]) + return sendJson(res, 400, { ok: false, error: "未知 action(允许: " + Object.keys(ACTIONS).join(", ") + ")" }); + return sendJson(res, 200, await runAction(name)); + } + + return sendJson(res, 404, { ok: false, error: "not found" }); + } catch (e) { + try { sendJson(res, 500, { ok: false, error: String(e && e.message || e) }); } catch (e2) {} + } +} + +function tokenOk(req, u) { + const m = /^Bearer ([0-9a-f]{16,128})$/.exec(String(req.headers.authorization || "")); + const given = String((m ? m[1] : u.searchParams.get("t")) || "").toLowerCase(); + if (!given) return false; + const a = Buffer.from(TOKEN), b = Buffer.from(given); + return a.length === b.length && crypto.timingSafeEqual(a, b); +} + +function writeSession(url) { + const data = JSON.stringify({ + service: SERVICE, version: VERSION, root: ROOT_NORM, home: HOME_SCOPE, bridge_url: BRIDGE_URL, + port: PORT, token: TOKEN, pid: process.pid, url, startedAt: Date.now(), + }); + try { + try { rmOwnedSync(SESSION_FILE); } catch (e) { /* 会话文件不存在或删除失败:写覆盖前尽力清理,写失败另有报错 */ } + fs.writeFileSync(SESSION_FILE, data, { mode: 0o600 }); + } catch (e) { console.error("会话文件写入失败: " + e.message); } +} +function cleanupExit(code) { + try { + const s = JSON.parse(fs.readFileSync(SESSION_FILE, "utf8")); + if (s.pid === process.pid) { try { rmOwnedSync(SESSION_FILE); } catch (e) { console.error("会话文件清理失败: " + e.message); } } + } catch (e) {} + try { + const info = JSON.parse(fs.readFileSync(path.join(LOCK_DIR, "pid.json"), "utf8")); + if (info.pid === process.pid) { try { rmOwnedSync(LOCK_DIR); } catch (e) { console.error("锁目录清理失败: " + e.message); } } + } catch (e) {} + process.exit(code); +} + +// ---------- 同安装根原子互斥(R2-1)---------- +// mkdir 的原子性保证多进程并发启动时只有一个能获取锁;锁内容为 pid.json。 +// 遗留锁处理:持锁进程已死 → 接管;空锁(启动中途崩溃)超过 10s → 接管; +// 超过强制接管时限(最大寿命+5min,防 pid 复用误判)→ 接管。 +const LOCK_DIR = SESSION_FILE + ".lock"; +const LOCK_STARTUP_GRACE_MS = 10000; +const LOCK_FORCE_TAKEOVER_MS = MAX_LIFE_MS + 5 * 60 * 1000; + +function pidAlive(pid) { try { process.kill(pid, 0); return true; } catch (e) { return false; } } +function readLockInfo() { + try { return JSON.parse(fs.readFileSync(path.join(LOCK_DIR, "pid.json"), "utf8")); } + catch (e) { return null; } +} +// 单步尝试:acquired=获得锁 / held=他人持有(进程存活)/ retry=已清理遗留锁可重试 / wait=他人刚建锁未写 pid +function lockStep() { + try { + fs.mkdirSync(LOCK_DIR); // 原子获取 + fs.writeFileSync(path.join(LOCK_DIR, "pid.json"), JSON.stringify({ pid: process.pid, startedAt: Date.now() })); + return "acquired"; + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + const info = readLockInfo(); + if (info && Number.isInteger(info.pid)) { + if (pidAlive(info.pid)) { + if (Date.now() - (info.startedAt || 0) > LOCK_FORCE_TAKEOVER_MS) { + try { rmOwnedSync(LOCK_DIR); } catch (e) { /* 接管失败:下一轮按同样规则重试 */ } + return "retry"; + } + return "held"; + } + try { rmOwnedSync(LOCK_DIR); } catch (e) { return "wait"; } + return "retry"; + } + try { + if (Date.now() - fs.statSync(LOCK_DIR).mtimeMs > LOCK_STARTUP_GRACE_MS) { + try { rmOwnedSync(LOCK_DIR); } catch (e) { return "wait"; } + return "retry"; + } + } catch (e) {} + return "wait"; +} +async function waitForExistingSession(ms) { + const deadline = Date.now() + ms; + while (Date.now() < deadline) { + const url = await existingUrl(); + if (url) return url; + await new Promise((r) => setTimeout(r, 300)); + } + return null; +} + +async function startServer() { + if (LAYOUT.mode === "unknown") { console.error("无法识别安装布局(既不是插件目录也不是项目仓库),退出"); process.exit(1); } + try { UI_HTML = fs.readFileSync(UI_FILE, "utf8"); } + catch (e) { console.error("缺少引导页面文件 " + UI_FILE + ": " + e.message); process.exit(1); } + try { STATE_JS = fs.readFileSync(STATE_FILE, "utf8"); } + catch (e) { console.error("缺少状态机文件 " + STATE_FILE + ": " + e.message); process.exit(1); } + + // 原子互斥(R2-1):并发启动时只有一个实例能获得锁;其余等待会话文件出现后复用退出 + const t0 = Date.now(); + for (;;) { + const r = lockStep(); + if (r === "acquired") break; + if (r === "held") { + const url = await waitForExistingSession(6000); + if (url) { console.error("[" + SERVICE + "] 本安装已有引导服务在运行: " + url + ",复用退出"); process.exit(0); } + // 会话迟迟未出现:持锁者可能刚死,回到锁竞争(下一轮将接管遗留锁) + } + if (Date.now() - t0 > 20000) { console.error("获取引导服务锁超时(锁目录: " + LOCK_DIR + "),可手动删除后重试"); process.exit(1); } + await new Promise((res) => setTimeout(res, r === "wait" ? 120 : 300)); + } + // 保险:获锁后再核对一次已有健康实例(如旧版本持会话未持锁),有则让位 + const existing = await existingUrl(); + if (existing) { + try { + const info = JSON.parse(fs.readFileSync(path.join(LOCK_DIR, "pid.json"), "utf8")); + if (info.pid === process.pid) { try { rmOwnedSync(LOCK_DIR); } catch (e) { console.error("锁目录清理失败: " + e.message); } } + } catch (e) {} + console.error("[" + SERVICE + "] 本安装已有引导服务在运行: " + existing + ",复用退出"); + process.exit(0); + } + + const server = http.createServer(handler); + for (let p = DEFAULT_PORT; p < DEFAULT_PORT + PORT_SPAN; p++) { + const ok = await new Promise((res) => { + const onError = () => res(false); + server.once("error", onError); + server.listen(p, "127.0.0.1", () => { server.removeListener("error", onError); res(true); }); + }); + if (ok) { PORT = p; break; } + } + if (!PORT) { console.error("端口 " + DEFAULT_PORT + "-" + (DEFAULT_PORT + PORT_SPAN - 1) + " 均被占用,无法启动引导服务"); process.exit(1); } + + TOKEN = crypto.randomBytes(24).toString("hex"); + startedAt = Date.now(); lastTouch = Date.now(); + const url = "http://127.0.0.1:" + PORT + "/?t=" + TOKEN; + writeSession(url); + console.error("[" + SERVICE + "] 引导服务已启动: " + url + "(布局: " + LAYOUT.mode + ",扩展目录: " + extDirOf() + ")"); + + process.on("SIGTERM", () => cleanupExit(0)); + process.on("SIGINT", () => cleanupExit(0)); + const idleTimer = setInterval(() => { + if (Date.now() - lastTouch > IDLE_TIMEOUT_MS || Date.now() - startedAt > MAX_LIFE_MS) cleanupExit(0); + }, 60000); + idleTimer.unref(); +} + +// ---------- 启动器:复用活着的引导服务,否则拉起,然后打开引导页 ---------- +// 会话复用身份(R3):ctx.HOME(launcher 注入的共享 home)优先——home 必须一致(无 home 字段的 +// 旧会话仅凭文件位置即在共享 home 内,允许迁移),安装根不再参与比较(跨安装目录复用正是目标); +// 未注入 HOME 的独立运行仍绑定安装根。其余校验保持:服务名/版本/桥接端点/端口/令牌/pid 存活/健康端点。 +// 返回的 URL 由已验证字段重建(127.0.0.1 + 校验过的端口与令牌),绝不采用会话文件里存储的 url 字符串 +async function existingUrlFrom(file, ctx) { + let s; + try { s = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { return null; } + if (!s || s.service !== ctx.SERVICE) return null; + if (s.version !== ctx.VERSION) return null; + if (ctx.HOME) { + if (s.home !== undefined && s.home !== ctx.HOME) return null; // 共享 home 不一致:不是本 home 的会话 + } else if (ctx.ROOT_NORM && s.root !== ctx.ROOT_NORM) return null; + if (s.bridge_url !== ctx.BRIDGE_URL) return null; + if (!Number.isInteger(s.port) || s.port < 1024 || s.port > 65535) return null; + if (!/^[0-9a-f]{48}$/.test(String(s.token || ""))) return null; + try { process.kill(s.pid, 0); } catch (e) { return null; } + const r = await fetch("http://127.0.0.1:" + s.port + "/api/health", { signal: AbortSignal.timeout(1200) }).catch(() => null); + if (!r || !r.ok) return null; + const b = await r.json().catch(() => null); + if (!b || b.service !== ctx.SERVICE || b.version !== ctx.VERSION) return null; + return "http://127.0.0.1:" + s.port + "/?t=" + s.token; +} +function existingUrl() { + return existingUrlFrom(SESSION_FILE, { SERVICE, VERSION, ROOT_NORM, HOME: HOME_SCOPE, BRIDGE_URL }); +} + +async function openUrl(url) { + if (SHELL_DISABLED) return { ok: false, reason: "已禁用(ONBOARD_SHELL_DISABLED=1)" }; + const built = platformActions.openUrlArgs(process.platform, url, chromePathOf()); + if (!built) { + return { + ok: false, + reason: process.platform === "win32" + ? platformActions.CHROME_MISSING_REASON + ";也可手动打开:" + url + : platformActions.UNSUPPORTED_REASON, + }; + } + if (built.gui) // Windows chrome.exe 打开引导页:有界观察(常驻即已发起打开),绝不无限等也绝不 kill + return spawnGuiBounded(built.cmd, built.args, GUI_OPENURL_WATCH_MS); + return new Promise((res) => { + const p = spawn(built.cmd, built.args, { stdio: ["ignore", "ignore", "pipe"] }); + let err = ""; + p.stderr.on("data", (d) => { err += String(d); }); + p.on("error", (e) => res({ ok: false, reason: "无法执行 " + built.cmd + ": " + e.message })); + p.on("close", (code) => { + if (code === 0) return res({ ok: true }); + res({ ok: false, reason: "退出码 " + code + (err.trim() ? ":" + err.trim().slice(0, 200) : "") }); + }); + }); +} + +async function launch() { + let url = await existingUrl(); + if (!url) { + const child = spawn(process.execPath, [__filename], { detached: true, stdio: ["ignore", "ignore", "ignore"] }); + child.unref(); + const deadline = Date.now() + 12000; + while (Date.now() < deadline) { + url = await existingUrl(); + if (url) break; + await new Promise((r) => setTimeout(r, 300)); + } + } + if (!url) { console.error("引导服务未能就绪(端口 " + DEFAULT_PORT + "-" + (DEFAULT_PORT + PORT_SPAN - 1) + " 可能被占用或启动失败),可重试"); return 1; } + const opened = await openUrl(url); + if (opened.ok) noteShown(); + if (!opened.ok) console.error("打开浏览器失败(" + opened.reason + ");请手动打开 " + url); + console.log(url); + return 0; +} + +if (require.main === module) { + if (process.argv.includes("--launch")) launch().then((c) => process.exit(c)); + else if (process.argv.includes("--auto")) autoLaunch().then((c) => process.exit(c)); + else startServer(); +} + +module.exports = { SERVICE, VERSION, ACTIONS, validateTabsPayload, resolveLayout, sessionFileFor, existingUrlFrom, shouldAutoOpen, spawnGuiBounded, _guiWatch: { action: GUI_ACTION_WATCH_MS, openUrl: GUI_OPENURL_WATCH_MS } }; diff --git a/external_plugins/cc-browser-bridge/server/package-lock.json b/external_plugins/cc-browser-bridge/server/package-lock.json new file mode 100644 index 00000000..40103aa8 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/package-lock.json @@ -0,0 +1,40 @@ +{ + "name": "cc-browser-bridge", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "cc-browser-bridge", + "version": "0.1.0", + "dependencies": { + "ws": "8.22.0" + }, + "engines": { + "node": ">=18" + }, + "license": "Apache-2.0" + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/external_plugins/cc-browser-bridge/server/package.json b/external_plugins/cc-browser-bridge/server/package.json new file mode 100644 index 00000000..dddd1c04 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/package.json @@ -0,0 +1,17 @@ +{ + "name": "cc-browser-bridge", + "version": "0.1.0", + "description": "Browser Bridge 本地桥接服务:把 MCP/HTTP 工具调用转发给 Chrome 扩展(插件标识 cc-browser-bridge)", + "main": "bridge.js", + "scripts": { + "start": "node bridge.js", + "mcp-stdio": "node mcp-stdio.js" + }, + "engines": { + "node": ">=18" + }, + "dependencies": { + "ws": "8.22.0" + }, + "license": "Apache-2.0" +} diff --git a/external_plugins/cc-browser-bridge/server/platform-actions.js b/external_plugins/cc-browser-bridge/server/platform-actions.js new file mode 100644 index 00000000..3da5c8d6 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/platform-actions.js @@ -0,0 +1,74 @@ +// 跨平台桌面动作适配层(阶段 B):macOS open / Windows 原生 chrome.exe + explorer.exe +// 纯参数构造:只产出 spawn(cmd, args) 的参数数组,绝不拼接 shell 命令、不经 shell 解释, +// 含中文、空格、&、引号的路径一律以独立参数原样传递(数组元素不转义、不拼接) +// gui 标记(R2/R4):win32 的 chrome.exe 打开 HTTP(S) 引导页 URL 是 GUI 进程,可能常驻(冷启动成为 +// 浏览器主进程)或移交既有实例后退出 0;调用方必须按「spawn 确认已发起打开 + 有界观察 + detached +// 脱离父寿命」处理,绝不因常驻而 kill。chrome:// 管理页地址在 Windows 被 Chromium 命令行拒绝 +// (R5),不再经由 chrome.exe 打开,改走 openExtensionsPlan 的人工导航计划。 +// mac 的 open 与 win32 的 explorer.exe 是短命命令(explorer 移交外壳后即退出),用退出码语义 +// 不支持的平台返回 null,由调用方给出可理解的手动指引(不假装成功) +// Windows Chrome 查找:标准系统安装位置(Program Files / Program Files (x86))+ 用户安装 +// (LOCALAPPDATA);ONBOARD_CHROME_PATH 显式覆盖时按覆盖值判定(不存在即视为未安装,不悄悄回退) +"use strict"; + +const fs = require("fs"); +const path = require("path"); + +const EXTENSIONS_URL = "chrome://extensions/"; +const UNSUPPORTED_REASON = "自动打开仅支持 macOS 与 Windows;请手动完成此步骤"; +const CHROME_MISSING_REASON = + "未在标准安装位置找到 Google Chrome(如已安装可将其放回默认位置)。" + + "请手动打开 chrome://extensions/ 并按引导页步骤加载扩展文件夹。"; + +// exists/isFile 均可注入:单元测试用假文件系统验证候选顺序与覆盖语义 +function findChromeWin(env = process.env, stat = (p) => { try { const s = fs.statSync(p); return s.isFile() ? p : null; } catch (e) { return null; } }) { + const override = env.ONBOARD_CHROME_PATH; + if (override !== undefined && override !== null && String(override).trim() !== "") { + return stat(String(override)); // 显式覆盖存在才可用;不存在即未安装(不回退扫描) + } + const cands = []; + if (env.ProgramFiles) cands.push(path.join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe")); + if (env["ProgramFiles(x86)"]) cands.push(path.join(env["ProgramFiles(x86)"], "Google", "Chrome", "Application", "chrome.exe")); + if (env.LOCALAPPDATA) cands.push(path.join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe")); + for (const c of cands) { const hit = stat(c); if (hit) return hit; } + return null; +} + +// 打开 chrome://extensions 管理页(R5:按平台真实能力返回计划,不假装能打开): +// darwin → {kind:"spawn"} open -a "Google Chrome" chrome://extensions/(LaunchServices 导航;open 短命命令) +// win32 → {kind:"manual"} Chromium 的 ValidateLaunchUrlWebUnsafe 不允许命令行打开 chrome:// 页面 +// (非 headless 时 chrome://extensions 不在许可表,实机只得到空白新标签页)。绝不再发起 +// 无效 Chrome 子进程:返回人工导航计划(固定地址由 UI 复制,用户在新标签页地址栏粘贴回车) +// 其他平台 → null(不支持) +const WIN_MANUAL_NAV_REASON = + "Chromium 安全限制:Windows 命令行无法直接打开 chrome:// 页面(只会得到空白新标签页)。" + + "请复制管理页地址,在 Chrome 新标签页地址栏粘贴并回车进入扩展管理页。"; +function openExtensionsPlan(platform) { + if (platform === "darwin") return { kind: "spawn", cmd: "open", args: ["-a", "Google Chrome", EXTENSIONS_URL] }; + if (platform === "win32") return { kind: "manual", url: EXTENSIONS_URL, reason: WIN_MANUAL_NAV_REASON }; + return null; +} + +// 定位扩展文件夹: +// darwin → open -R (Finder 中选中) +// win32 → explorer.exe (资源管理器打开该文件夹;固定路径参数,不拼接命令) +function revealFolderArgs(platform, dir) { + if (platform === "darwin") return { cmd: "open", args: ["-R", dir] }; + if (platform === "win32") return { cmd: "explorer.exe", args: [dir] }; + return null; +} + +// 打开引导页 URL(URL 只能来自本地实际引导服务,调用方负责生成): +// darwin → open (默认浏览器;open 为短命命令) +// win32 → --new-window (Chrome 缺失 → null,手动打开) +// 标记 gui:true(常驻主进程/移交退出 0 两种寿命;管理页另走人工导航) +function openUrlArgs(platform, url, chromePath) { + if (platform === "darwin") return { cmd: "open", args: [url] }; + if (platform === "win32") { + if (!chromePath) return null; + return { cmd: chromePath, args: ["--new-window", url], gui: true }; + } + return null; +} + +module.exports = { findChromeWin, openExtensionsPlan, revealFolderArgs, openUrlArgs, EXTENSIONS_URL, UNSUPPORTED_REASON, CHROME_MISSING_REASON, WIN_MANUAL_NAV_REASON }; diff --git a/external_plugins/cc-browser-bridge/server/tools.js b/external_plugins/cc-browser-bridge/server/tools.js new file mode 100644 index 00000000..acc65253 --- /dev/null +++ b/external_plugins/cc-browser-bridge/server/tools.js @@ -0,0 +1,346 @@ +// 工具注册表:MCP schema + 调用计划(纯函数,无 IO) +// planFor(name, args) 返回三种指令之一: +// { ext: tool, args } → 转发给 Chrome 扩展执行 +// { sleep: ms } → 桥接服务自己等待 +// { local: "..." } → 桥接服务直接回答(无扩展依赖) + +const obj = (properties, required) => ({ + type: "object", + properties, + additionalProperties: false, + ...(required && required.length ? { required } : {}), +}); +const S = { + ref: { type: "integer", description: "browser_snapshot 输出中的元素编号" }, + xy: { + type: "number", + description: "截图坐标系下的横/纵像素(来自最近一次 browser_screenshot)", + }, +}; + +const TOOLS = [ + { + name: "browser_screenshot", + description: + "截取当前标签页的截图(PNG)并返回给 Claude。推荐先用它看清页面再操作;" + + "坐标类操作(browser_click 的 x/y、browser_scroll 的 x/y)基于这张截图的像素。full_page=true 可截整页。", + inputSchema: obj({ + full_page: { type: "boolean", description: "是否截取整个页面(默认 false 只截可见区域)" }, + }), + }, + { + name: "browser_snapshot", + description: + "获取当前页面的可交互元素结构快照:链接/按钮/输入框/下拉/标题等,每项带 ref 编号、名称和位置。" + + "后续用 browser_click/browser_type 的 ref 参数精确定位元素,比坐标更快更稳。" + + "ref 绑定元素本身:同一文档内旧 ref 跨多次快照仍指向原元素(新元素拿新编号),元素被移除、页面导航或换文档后失效,需重新快照(ref 编号跨文档不复用)。", + inputSchema: obj({}), + }, + { + name: "browser_read_page", + description: "提取当前页面的纯文本内容(最多 2 万字符),适合读取文章/文档正文,比截图省 token。", + inputSchema: obj({}), + }, + { + name: "browser_click", + description: + "点击元素。优先用 ref(来自 browser_snapshot);否则用 x/y 截图坐标(需要先 browser_screenshot)。" + + "button 可选 left/right/middle,click_count=2 为双击。", + inputSchema: obj( + { + ref: S.ref, + x: S.xy, + y: { ...S.xy, description: "纵坐标像素" }, + button: { type: "string", enum: ["left", "right", "middle"], description: "默认 left" }, + click_count: { type: "integer", description: "默认 1;2=双击,3=三击" }, + }, + [] + ), + }, + { + name: "browser_type", + description: + "在输入框输入文本。ref 来自 browser_snapshot;不给 ref 则作用于当前焦点元素(同样支持 clear/press_enter)。" + + "默认先清空原内容(全选后删除,按平台自动选择 Meta/Control 组合键);press_enter=true 输入后按回车(在表单中会提交)。", + inputSchema: obj( + { + ref: S.ref, + text: { type: "string", description: "要输入的文本" }, + clear: { type: "boolean", description: "是否先清空(默认 true)" }, + press_enter: { type: "boolean", description: "输入后按回车(默认 false)" }, + }, + ["text"] + ), + }, + { + name: "browser_press_key", + description: "按键或组合键,例如 \"Enter\"、\"Escape\"、\"Tab\"、\"Control+a\"、\"Meta+c\"、\"ArrowDown\"。", + inputSchema: obj({ key: { type: "string" } }, ["key"]), + }, + { + name: "browser_hover", + description: "悬停到元素上(触发悬浮菜单等)。优先 ref,否则 x/y 截图坐标。", + inputSchema: obj({ ref: S.ref, x: S.xy, y: { ...S.xy, description: "纵坐标像素" } }), + }, + { + name: "browser_select_option", + description: "选择