feat: 新增拓展中心功能, 提供 关键词回复 去水印模板

This commit is contained in:
Wxw-Gu committed 2026-11-18 17:42:13 +08:00
1 parent aca103cb96
commit ebea992b10
85 files changed
+14750 -106

No files matched your search

+3
View File
@@ -31,3 +31,6 @@ task_plan.md
*libtmlicense*
debug-originals
/build/mac-staging/
# 去水印脚本
/examples/extensions/douyin-sender/scripts/douyin.py
+2
View File
@@ -50,6 +50,8 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
## 开发文档
- [开发、测试与构建](./development/overview.md)
- [克隆 TraceMemo 后开发自己的扩展](./extensions/clone-and-customize.md)
- [扩展 API 参考](./extensions/api-reference.md)
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
+187
View File
@@ -0,0 +1,187 @@
# 扩展 API 参考(v1)
## manifest.json
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `manifestVersion` | 是 | 固定 `1` |
| `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 |
| `name` | 是 | 展示名,≤ 64 字 |
| `version` | 是 | `x.y.z`(可带 prerelease) |
| `apiVersion` | 是 | 必须为 `1` |
| `minAppVersion` | 否 | 低于该版本拒绝安装 |
| `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) |
| `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 |
| `entrypoints.page` | 二选一 | 页面 HTML 相对路径 |
| `entrypoints.background` | 二选一 | 后台入口相对路径 |
| `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 |
| `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` |
| `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background |
路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名;
安装时还会用 realpath 复核入口仍在扩展目录内。
## 权限
| 权限 | 风险 | 能力 |
| --- | --- | --- |
| `messages.subscribe` | 高 | 接收 `message.received` |
| `messages.query` | 高 | `tm.messages.query` |
| `contacts.list` | 中 | 配置页读取群列表(`contacts.listGroups`),不含聊天内容 |
| `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` |
| `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` |
| `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video |
| `ai.chat` | 中 | `tm.ai.chat` |
| `storage` | 低 | `tm.storage.*` 与页面存储 |
| `automation.action` | 中 | `tm.automation.registerAction` |
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。
## 后台 API
### tm.extension
- `id: string`
- `dataDir: string`(扩展私有数据目录,媒体文件写这里才能通过发送校验)
- `permissions: string[]`(当前已授予)
### tm.events
- `on('message.received', handler): () => void`
- `off('message.received', handler): void`
事件字段见 `TraceMemoMessageEvent`:`eventId / accountId / conversationId / messageId /
senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
### tm.messages.query
```ts
await tm.messages.query({ conversationId, startTime?, endTime?, limit? })
// → { messages: [{ messageId, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }] }
```
- 时间参数是 **epoch 毫秒**;默认最近 24 小时。
- 单次窗口最多 7 天,`limit` 上限 200。
- 数据库未连接时抛 `DATABASE_NOT_READY`。
### tm.wechat.send
```ts
// 文本
await tm.wechat.send({ to, text, at?, dedupeKey? })
// 图片
await tm.wechat.send({ type: 'image', to, path: '/abs/path/cover.png', dedupeKey? })
// 视频(原生 Host 以 {toWxid, type:'video', msg:<路径>} 提交)
await tm.wechat.send({ type: 'video', to, path: '/abs/path/clip.mp4', dedupeKey? })
// → { actionId, status: 'sent' }
```
按顺序检查:权限 → 参数(文本 ≤ 2000 字)→ manifest 会话范围 → 频率
(同扩展 2 秒一条、每分钟 10 条)→ 本机发送能力 → 授权校验 → Gateway。
任何一步不通过都抛带错误码的异常,不会「静默丢弃」。
媒体路径额外约束:
- 必须是**绝对路径**的普通文件,realpath 后仍位于**扩展数据目录**或**系统临时目录**;
- 大小 1B–100MB;
- 图片扩展名:jpg/jpeg/png/gif/webp/bmp;视频扩展名:mp4/mov/m4v;
- 视频走 `type: 'video'`,不复用图片通道;发送失败不会降级成图片。
### tm.ai.chat
```ts
await tm.ai.chat([{ role: 'user', content: '...' }])
// → { text }
```
使用 TraceMemo 已配置的 AI Provider;扩展拿不到 API Key。
### tm.storage
```ts
await tm.storage.set('config', { ... })
await tm.storage.get('config')
await tm.storage.remove('config')
await tm.storage.list()
```
键:`[A-Za-z0-9._-]{1,64}`;单值 ≤ 256KB,总量 ≤ 1MB;只接受 JSON 值。
### tm.automation.registerAction
```ts
tm.automation.registerAction({ id, title, description?, inputSchema?, handler })
```
`id`:`[a-z0-9][a-z0-9._-]{1,63}`。`handler` 返回:
```ts
{ success: boolean, output?: object, reply?: { type: 'text', text, at? }, error?: string }
```
`inputSchema` 只支持 `object` + `string|number|boolean` 属性的浅校验;必填项缺失会直接拒绝。
执行超时默认 15 秒(宿主可配,最大 60 秒),超时返回 `ACTION_TIMEOUT`。
### tm.capabilities.get
返回只读快照:`enabled / permissions / platform / databaseReady / send{...} / ai{...}`。
### tm.log
`info / warn / error`,写入扩展日志(详情页可见,最多保留 200 条,单行 ≤ 500 字)。
## 页面桥
页面 → 宿主:
```ts
{ source: 'tracememo-extension-page', extensionId, requestId, method, params }
```
宿主 → 页面:
```ts
{ source: 'tracememo-extension-host', requestId, ok: true, result }
{ source: 'tracememo-extension-host', requestId, ok: false, error: { code, message } }
```
页面方法白名单:`storage.get|set|remove|list`、`capabilities.get`、`contacts.listGroups`、`extension.info`。
页面不能发送微信消息、不能查询消息、不能调用 AI。
## 错误码
| 码 | 含义 |
| --- | --- |
| `EXTENSION_NOT_FOUND` | 扩展不存在 / 已卸载 |
| `EXTENSION_DISABLED` | 扩展未启用 |
| `EXTENSION_INCOMPATIBLE` | apiVersion 或 minAppVersion 不满足 |
| `EXTENSION_INVALID_MANIFEST` | manifest 不合法 |
| `EXTENSION_INVALID_PATH` | 入口 / 资源路径越界 |
| `EXTENSION_HOST_UNAVAILABLE` | 后台进程未运行 |
| `PERMISSION_DENIED` | 未授予权限,或超出声明范围 |
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备(未绑定 / 未就绪) |
| `LICENSE_REQUIRED` | 无有效授权 |
| `DATABASE_NOT_READY` | 微信数据库未连接 |
| `SEND_NOT_SUPPORTED` | 当前平台或内容类型不支持 |
| `ACTION_TIMEOUT` | 处理超时 |
| `ACTION_FAILED` | 执行失败 |
| `RATE_LIMITED` | 触发频率限制 |
| `INVALID_REQUEST` | 参数非法 |
| `STORAGE_LIMIT_EXCEEDED` | 存储超限 |
## 自动化动作输入
规则里保存的静态 `input` 会与宿主注入字段合并,同名键以宿主为准:
```json
{
"url": "https://example.com/video",
"conversationId": "xxx@chatroom",
"isGroup": true,
"accountId": "wxid_self",
"message": { "eventId": "message:...", "text": "...", "mentionsMe": false }
}
```
+99
View File
@@ -0,0 +1,99 @@
# 扩展中心架构(v1)
## 目标
把用户二次开发从官方源码里剥离:扩展装在自己的目录、走稳定的 SDK、由宿主做权限与能力检查。
官方升级只替换应用本体,不触碰扩展目录与数据目录。
## 分层
```text
TraceMemo Core(Electron 主进程 / 渲染层)
│
ExtensionManager ─── ExtensionRegistry(启用状态 / 授权集合)
│ ExtensionInstaller(目录 / ZIP 安装,原子替换)
│ ExtensionLogStore(日志)
│ ExtensionActionRegistry(自动化动作)
│ ExtensionEventBus(消息事件分发)
│
ExtensionHost(每个扩展一个 Node 子进程)
│ require(background/index.js),注入 tm
│
tm.* ── 白名单 RPC ──▶ 宿主能力
├─ storage → extensions-data/<id>
├─ messages.query→ chat-service(有界窗口)
├─ wechat.send → ExtensionSendGateway → WechatActionGateway
├─ ai.chat → AIProviderService
└─ capabilities → 只读快照
```
关键边界:
- **主进程从不 `require` 扩展代码**;扩展只在子进程里加载。
- 扩展不 import 官方业务模块,只通过 JSON RPC 申请能力。
- 发送、消息读取、AI 调用全部复用既有服务,没有第二套监听或发送实现。
## 目录
```text
<userData>/
extensions/<id>/ 代码(manifest.json / ui / background)
extensions-data/<id>/ 扩展私有数据(storage.json)
extensions-state/ 宿主状态
registry.json 启用状态与已授予权限
logs/<id>.jsonl 运行日志(轮转一份 .1)
extensions-staging/ 安装临时目录(成功后原子改名)
```
三者分离的原因:
| 场景 | 结果 |
| --- | --- |
| 官方应用升级 | `userData` 不变,扩展与配置原样保留 |
| 扩展升级(同 id 新版本) | 只替换 `extensions/<id>`,`extensions-data` 不动 |
| 卸载并选择保留数据 | 删除代码目录,保留 `extensions-data` |
| 卸载并清除数据 | 同时删除数据目录与日志 |
## 生命周期
```text
install → 校验 manifest / 入口 → 临时目录 → 原子替换 → 登记(默认未启用)
enable → 授予 manifest 声明的权限 → 启动子进程 → activate 握手 → active
message → ExtensionEventBus 去重 → 按 subscriptions 过滤 → 投递给子进程
action → 自动化 runner → ExtensionHost.invokeAction → 返回 reply / output
disable → 停止子进程 → 撤销高风险权限(仅保留 storage)→ inactive
upgrade → 停进程 → 替换目录 → 保留 enabled 与授权 → 重启
```
崩溃处理:子进程异常退出时按 1s / 2s / 4s 退避重启,5 分钟内超过 3 次标记为
`crashed` 并停止自动重启,等用户手动停用再启用。
## 消息事件
- 事件来源只有 `MessageListenerService` 的规范化结果,不直连数据库。
- `eventId = message:<sha1(sessionId:localId)>`,同一条消息稳定不变。
- `mentionsMe` 来自 `source.atuserlist` ∩ 当前账号 username;拿不到自身身份时为 `false`。
- 分发前做 manifest 级过滤(消息类型 / 会话范围 / 是否 @我 / 是否包含自己)。
- 子进程侧有令牌桶(容量 100,按 60/秒补充);超出时丢弃并记一条 warn,
不让扩展拖慢主进程监听循环。
**已知降级**:旧 Native Runtime 的事件不带 `sessionId`,监听层只能回读「最近活跃会话」。
事件总线不掩盖这一点,自动化状态与扩展能力快照都按「降级」标记。
## 发送链路
```text
tm.wechat.send
→ ExtensionHost(权限检查)→ ExtensionSendGateway(权限 / 范围 / 频率 / 能力 / 授权校验)
→ WechatActionGateway.executeFromExtension(origin=extension, purpose=extension_send)
→ WechatSendGateway → Windows / macOS sender
```
自动化动作返回的 `reply` 走同一条 Gateway,但 purpose 是 `extension_action`,
幂等键由 `executionId` 派生。扩展无法传入 `origin` / `purpose` / `triggerType`。
## 与自动化的关系
- 扩展注册动作,自动化负责触发、过滤、冷却、幂等、执行日志。
- 自动化规则里的 `extensionAction` 只保存 `extensionId + actionId + 静态 input`;
卸载扩展后规则**保留**,执行时明确报 `EXTENSION_NOT_FOUND`,不会静默删除用户配置。
+170
View File
@@ -0,0 +1,170 @@
# 克隆 TraceMemo 后开发自己的扩展
本指南说明如何从 TraceMemo 示例开始,编写、安装和调试自己的扩展。扩展代码与 TraceMemo 主程序分开维护;通常只需要写一个扩展目录,不必改 TraceMemo 的业务源码。
本文适用于包含 Extension Center v1 的 TraceMemo 版本,扩展 API 版本为 `1`。较早的源码或安装包如果还没有左侧「扩展」入口,需要先使用包含 Extension Center 的分支或版本。
## 1. 克隆并启动 TraceMemo
先按项目开发文档准备 Node.js 与 pnpm,然后克隆源码、安装依赖并启动开发版:
```bash
git clone https://github.com/Wxw-Gu/TraceMemo.git
cd TraceMemo
pnpm install
pnpm dev
```
`pnpm dev` 启动的是 TraceMemo 开发版。扩展安装后会复制到应用的用户数据目录;修改源码目录里的文件不会自动同步到已安装副本,每次改完都要重新安装同一扩展目录。
## 2. 从示例创建扩展
建议先复制示例,再按功能删改文件:
```bash
cp -R examples/extensions/keyword-bot ../my-tracememo-extension
```
`keyword-bot` 带有规则、匹配与发送逻辑;如果只是做最小扩展,保留 `manifest.json`、`ui/` 与 `storage` 用法,删除 `lib/`、规则 UI 以及 `background` 里的匹配/发送代码即可。
目录通常如下:
```text
my-tracememo-extension/
manifest.json 扩展身份、入口和权限声明
background/index.js 可选;后台逻辑,运行于独立 Node 子进程
ui/ 可选;扩展页面,运行于 sandbox iframe
index.html
app.js
style.css
```
最小扩展只要求有一个页面或后台入口。可先从 `keyword-bot` 保留 `manifest.json`、页面桥与 `storage` 用法,再把 `manifest.json` 中的 `id`、`name`、`description`、`author` 改成自己的信息;`id` 是反向域名格式,例如 `com.example.my-helper`,必须唯一,不能使用 `com.tracememo.`、`tracememo.` 或 `tm.` 前缀。版本采用 `x.y.z` 格式。
示例中的页面脚本也有一个 `EXTENSION_ID` 常量,使用页面桥时要将它改成 manifest 中完全相同的 id。稳定 id 很重要:相同 id 的升级会保留该扩展的配置;换 id 则会被视为另一个扩展。
典型 manifest:
```json
{
"manifestVersion": 1,
"id": "com.example.my-helper",
"name": "我的扩展",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "我的 TraceMemo 扩展",
"permissions": ["storage"],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"contributions": {
"pages": [{ "id": "settings", "title": "设置" }]
}
}
```
`minAppVersion` 是最低应用版本,可按扩展实际依赖调整。入口路径必须是扩展目录内的安全相对路径;安装器会检查 manifest 和入口文件。
## 3. 编写后台逻辑
后台入口导出 `activate(tm)`。TraceMemo 会在扩展启用时启动独立 Node 子进程,并注入 `tm` API:
```js
module.exports = function activate(tm) {
tm.log.info(`扩展已启动:${tm.extension.id}`)
tm.events.on('message.received', async (event) => {
if (event.isSelf || !event.mentionsMe || !event.text) return
await tm.wechat.send({
to: event.conversationId,
text: '收到,我来处理。',
dedupeKey: event.eventId
})
})
}
```
上面这个例子需要在 manifest 中声明 `messages.subscribe`、`wechat.send.text`,并声明消息订阅范围:
```json
{
"permissions": ["messages.subscribe", "wechat.send.text", "storage"],
"subscriptions": {
"messageTypes": ["text"],
"conversationIds": [],
"requireMentionMe": true,
"includeSelf": false
}
}
```
按需申请权限,不要为了省事把所有权限都加上。高、中风险权限会在启用时要求用户确认;没有获得相应授权的 API 会返回权限错误。微信发送仍经过 TraceMemo 的权限、范围、频率、发送能力和授权校验。
可用 API 包括 `tm.events`、有界的 `tm.messages.query`、`tm.wechat.send`、`tm.ai.chat`、`tm.storage`、`tm.automation.registerAction`、`tm.capabilities.get` 和 `tm.log`。字段、限制与错误码见[扩展 API 参考](./api-reference.md)。仓库的 `packages/extension-sdk/index.d.ts` 只提供类型定义,不是运行时依赖;运行时的 `tm` 由 TraceMemo 注入。
## 4. 编写扩展页面
页面在 sandbox iframe 中运行,不能访问 `window.api`、Node 或 Electron。需要调用宿主白名单功能时,通过 `postMessage` 页面桥通信。可参考 `examples/extensions/keyword-bot/ui/app.js` 里的 `callHost()` 与消息处理,并更新其中的扩展 id。页面桥目前允许存储读写、能力查询、群列表查询(需 `contacts.list`)和扩展信息查询;页面不能直接读取聊天消息、调用 AI 或发送微信。
后台逻辑使用 `tm.storage`;页面则通过页面桥的 `storage.get` / `storage.set` 等方法访问同一扩展的私有存储。
## 5. 在 TraceMemo 中安装和调试
1. 在开发版或已支持扩展的 TraceMemo 中打开左侧「扩展」。
2. 选择「安装目录」,指向 `my-tracememo-extension`。也可以将扩展文件打成 ZIP;`manifest.json` 必须位于 ZIP 根目录,然后选择「安装 ZIP」。
3. 安装完成后,选中扩展并点「启用」。检查权限清单,只确认扩展功能确实需要的权限。
4. 有页面入口时点「打开页面」;检查配置是否读写正常。后台运行日志可在扩展详情页查看。
5. 修改源码后重新安装同一个目录,以更新已安装副本;如后台进程仍未刷新,再停用后重新启用。页面资源更新后重新打开或刷新扩展页面。
同一 `id` 重新安装会更新扩展代码并保留已授予权限、启用状态和扩展存储。卸载默认保留数据;需要清理时再明确选择删除数据。
## 6. 编写和运行测试
纯 JavaScript 扩展可用 Node 内置检查器与测试运行器,不需要把扩展依赖装进 TraceMemo:
```bash
node --check ../my-tracememo-extension/background/index.js
node --test ../my-tracememo-extension/tests/*.test.mjs
```
若扩展放在 TraceMemo 仓库的 `examples/extensions/` 下,也可以参照示例的测试命令,例如:
```bash
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
```
改动 TraceMemo 扩展宿主、SDK 契约或示例校验时,再运行对应的 TraceMemo 测试:
```bash
pnpm exec vitest run --config vitest.unit.config.ts tests/unit/extension-manifest.test.ts tests/unit/extension-installer.test.ts tests/unit/extension-host.test.ts
pnpm typecheck
```
## 7. 自动化动作
扩展可以在 manifest 中用 `contributions.automationActions` 声明动作,并申请 `automation.action`;后台通过 `tm.automation.registerAction()` 注册实现。动作返回的 `reply` 由 TraceMemo 宿主经统一 Gateway 发送,扩展不应自行绕过 Gateway。
当前版本可以在扩展详情页查看动作是否已注册;自动化规则编辑器尚未提供选择扩展动作的入口,因此目前不能通过界面把这些扩展动作配置到规则中。相关执行接口已在宿主侧实现,界面入口开放后再按产品文档配置。
## 8. 安全与发布前检查
扩展后台虽然运行在独立进程,但这**不是操作系统级沙箱**。它是任意 Node.js 代码,拥有运行 TraceMemo 用户的文件与网络权限。只安装自己编写或信任来源的扩展,不要把不可信扩展当成受隔离代码。
发布前至少确认:
- manifest id 唯一、版本递增、权限最小化,所有入口文件都在扩展目录内;
- 页面只使用受支持的 postMessage 白名单,不假设能访问 Electron API;
- 消息回调处理异常并使用稳定的 `dedupeKey`;
- 单元测试覆盖纯逻辑,人工验证安装、启用、停用、重装和配置保留;
- README 说明扩展行为、权限用途、外部依赖与可能发送的内容。
## 相关资料
- [扩展开发入门与 API 用法](./getting-started.md)
- [扩展 API 参考](./api-reference.md)
- [扩展中心架构](./architecture.md)
- [扩展安全模型](./security.md)
- [可安装示例](../../examples/extensions/README.md)
+141
View File
@@ -0,0 +1,141 @@
# 扩展开发入门
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页保留 API 用法速查。
## 1. 安装示例
1. 打开 TraceMemo,左侧一级导航点「扩展」。
2. 点「安装目录」,选择 `examples/extensions/keyword-bot`。
3. 列表里出现 **关键词回复机器人**,状态为「已停用」。
4. 点「启用」→「打开页面」;页面顶部的「启用机器人」默认关闭,打开后修改规则并保存。
5. 完全退出并重启 TraceMemo,配置仍在。
`examples/extensions/douyin-sender` 用同样的方式安装;它依赖本机 `python3`、Chrome 和抖音解析脚本,先看它自己的 README。
## 2. 最小扩展
```text
my-extension/
manifest.json
ui/index.html
background/index.js
```
`manifest.json`:
```json
{
"manifestVersion": 1,
"id": "com.example.my-extension",
"name": "我的扩展",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"permissions": ["storage"],
"entrypoints": { "page": "ui/index.html", "background": "background/index.js" },
"contributions": { "pages": [{ "id": "settings", "title": "设置" }] }
}
```
`background/index.js`:
```js
module.exports = function activate(tm) {
tm.log.info('我的扩展已启动')
}
```
`ui/index.html` 里不能直接用 `window.api`。页面通过 postMessage 与宿主通信:
```js
const requestId = `req-${Date.now()}`
parent.postMessage(
{
source: 'tracememo-extension-page',
extensionId: 'com.example.my-extension',
requestId,
method: 'storage.get',
params: { key: 'greeting' }
},
'*'
)
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== 'tracememo-extension-host' || data.requestId !== requestId) return
console.log(data.ok ? data.result : data.error)
})
```
页面可调用的方法只有:`storage.get` / `storage.set` / `storage.remove` / `storage.list` /
`capabilities.get` / `extension.info`。
## 3. 订阅消息
manifest 必须同时声明权限与订阅:
```json
{
"permissions": ["messages.subscribe"],
"subscriptions": {
"messageTypes": ["text"],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
}
}
```
```js
module.exports = function activate(tm) {
tm.events.on('message.received', async (event) => {
if (event.isSelf) return
if (!event.mentionsMe) return
await tm.wechat.send({
to: event.conversationId,
text: '收到',
dedupeKey: event.eventId
})
})
}
```
`dedupeKey` 建议直接用 `event.eventId`:同一条消息重复投递时,Gateway 会按审计记录短路。
## 4. 注册自动化动作
```js
tm.automation.registerAction({
id: 'douyin.process',
title: '抖音视频处理',
description: '处理指定视频链接',
inputSchema: {
type: 'object',
properties: { url: { type: 'string' } },
required: ['url']
},
async handler(input) {
return {
success: true,
output: { url: input.url },
reply: { type: 'text', text: '已收到链接' }
}
}
})
```
扩展中心会展示动作声明与运行时注册状态。当前自动化规则编辑器尚未提供扩展动作选择入口,因此暂时不能从界面配置该动作。宿主侧执行契约与输入结构见[扩展 API 参考](./api-reference.md#自动化动作输入)。
扩展动作返回的 `reply` 由宿主经 Gateway 发送;扩展本身不调用发送接口也能完成回复。
## 5. 开发与调试
- TraceMemo 会把扩展复制到用户数据目录;改完源码后先在扩展中心重新安装同一目录,更新已安装的文件。需要时再「停用 → 启用」重启后台进程。
- 页面资源更新后重新打开或刷新扩展页面。
- 日志在扩展详情页底部,`宿主` 表示生命周期与错误,`扩展` 表示 `tm.log.*` 写入的内容。
- 想看完整后台输出,可以在终端启动 `pnpm dev`,子进程 stderr 会进主进程日志。
## 6. 升级与保留
- 扩展升级只替换代码目录;`storage` 数据与启用状态保留。
- 官方 TraceMemo 升级不触碰 `extensions/`、`extensions-data/`、`extensions-state/`。
- 卸载默认保留数据(v1 界面只提供「保留数据」这一条路径;`keepData: false` 已在 IPC 中实现,界面暂未暴露)。
+86
View File
@@ -0,0 +1,86 @@
# 扩展安全模型(v1)
## 信任分级
| 类型 | 说明 | 本版支持 |
| --- | --- | --- |
| 声明式 UI 扩展 | 只有页面,使用白名单存储 / 能力查询 | 是 |
| 受信任本地代码扩展 | 后台是任意 Node 代码,可读写本机文件 | 是(安装即视为信任) |
**独立进程不等于强沙箱。** 后台子进程(`ELECTRON_RUN_AS_NODE`)拥有运行用户的全部
Node 能力,因此扩展作者可以读写本机文件、发起网络请求。本版不声称限制了这些——
它限制的是**TraceMemo 内部能力**:
- 拿不到数据库句柄、数据库密钥、授权凭据、Native Runtime 句柄;
- 不能直接调用原生发送接口(dylib / 底层端口);
- 不能 `require` 官方主进程模块;
- 不能伪造宿主可信元数据(`origin` / `purpose` / `triggerType` / 幂等键)。
## 进程与权限
```text
主进程 ── fork ──▶ 扩展子进程(每扩展一个)
│ 只注入 tm
▼
白名单 RPC(method + params)
│
宿主再次校验权限
```
两侧都检查权限:子进程提前失败给出明确错误码,宿主侧才是权威判定。
子进程崩溃 / 挂死不影响主进程:宿主有启动超时、调用超时、退避重启与熔断。
## 发送安全
```text
扩展声明「发什么」
↓
宿主填 origin=extension / purpose=extension_send / recipient 类型 / 幂等键
↓
ExtensionSendGateway:权限 → 会话范围 → 频率 → 本机能力 → 授权校验
↓
WechatActionGateway:用途白名单 + `extension_*` 必须来自 origin=extension
↓
WechatSendGateway:真实发送 + Send Log
```
- 扩展不能在请求里指定 `purpose`,因此无法借用 `manual_*` / `api_*` 等用途绕过白名单。
- 自动化草稿里的 `extensionAction` 只保存扩展 id、动作 id 与静态输入;
发送内容由扩展返回,发送动作由 runner 发起,幂等键由 `executionId` 派生。
- 授权只在主进程判定:macOS 读 Native license(要求 `authorized === true`),
Windows 探测 `/license/status` 只接受 `LICENSE_OK`。UI 上的 `ready` 不作为授权依据。
## 页面安全
- 自定义协议 `tm-extension://<id>/<path>`,每次请求 realpath 复核目录归属;
- iframe `sandbox="allow-scripts"`:无 same-origin、无 Node、无 preload、无 `window.api`;
- 响应头 CSP:`default-src 'self'`、`script-src 'self'`、`connect-src 'none'`、
`object-src 'none'`、`base-uri 'none'`、`form-action 'none'`;
- 页面只能调用 `storage.*` / `capabilities.get` / `contacts.listGroups` / `extension.info`;
`contacts.listGroups` 只返回群名称与会话 id,且要求 manifest 声明 `contacts.list`。
## 安装安全
ZIP 安装校验:
1. 包大小 ≤ 100MB、文件数 ≤ 2000、单文件 ≤ 20MB、解压总量 ≤ 50MB;
2. 条目路径规范化后判重(大小写不敏感),拒绝 `..`、绝对路径、盘符、保留名;
3. 拒绝 `SymbolicLink` 与非常规条目;
4. 先解压到 `extensions-staging`,校验 manifest 与入口存在后才原子改名;
5. 目标已存在时先改名备份,替换失败自动回滚。
目录安装同样拒绝符号链接与非普通文件,并遵守同样的体积 / 数量上限。
## 隐私
- 宿主日志只记录生命周期、错误摘要与数量,不写聊天正文、昵称、wxid、群名、路径;
- `message.received` 只在扩展声明 `messages.subscribe` 且用户启用后才投递;
- 扩展自己写 `tm.log.*` 的内容会落盘并展示,作者需自行遵守隐私约定;
- 扩展存储按 id 隔离,路径来自已校验的 id,不接受任意目录。
## 已知边界(v1 未解决)
- 后台代码的文件 / 网络权限未做系统级限制(无 seatbelt / AppContainer);
- 页面与后台共享 `storage`,因此页面能读到后台写入的任何配置;
- 没有签名校验与来源可信度分级,安装来源完全依赖用户选择;
- 事件投递是「至多一次」:进程重启或过载时可能丢事件,扩展需要用 `eventId` 自行幂等。
+2
View File
@@ -11,6 +11,8 @@ export default defineConfig({
rollupOptions: {
input: {
index: resolve('src/main/index.ts'),
/* 扩展后台宿主:由 `ExtensionHost` 以子进程方式 fork,不在主进程加载。 */
extensionHost: resolve('src/main/extensions/host-runtime.ts'),
reportTemplateTest: resolve('src/main/report-template-test-entry.ts'),
queryAgentPoc: resolve('src/main/query-agent-poc-entry.ts'),
voiceRecognitionWorker: resolve('src/main/voice-pipeline/voice-recognition-worker.ts'),
+9
View File
@@ -34,5 +34,14 @@ export default defineConfig(
...eslintPluginReactRefresh.configs.vite.rules
}
},
{
// 扩展示例是给第三方作者抄的 CommonJS,不是 TS 源码:
// 返回类型/require 规则在这里没有意义,强制它们只会让示例变成反例。
files: ['examples/**/*.{js,mjs}'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-require-imports': 'off'
}
},
eslintConfigPrettier
)
+37
View File
@@ -0,0 +1,37 @@
# 扩展示例
两个可直接安装的示例,用来验证扩展中心从安装到发送的完整链路。
| 目录 | 用途 | 申请权限 |
| --- | --- | --- |
| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` |
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
## 安装
TraceMemo → 左侧「扩展」→「安装目录」,选择对应目录即可。
安装后扩展默认**未启用**:
- `keyword-bot` 的 `enabled` 为 `false`,需要在配置页手动打开才会回复;
- `douyin-sender` 依赖本机的 `python3`、Chrome 和抖音解析脚本,安装前先看它自己的 README。
## 测试建议
- 关键词机器人默认监听全部群聊 + 私聊;想只对某个群生效,在「监听范围」里搜索并多选群聊。
- 冷却时间按「会话 + 规则」计算,避免同一句话连续刷屏。
- 扩展的发送走 `tm.wechat.send`,最终仍由 TraceMemo Gateway 做权限、授权校验、限流与审计。
## 开发
扩展目录里只需要 `manifest.json` 与入口文件:
```text
my-extension/
manifest.json
ui/index.html
background/index.js
```
`background/index.js` 导出 `activate(tm)`(或 `module.exports = { activate }`)。页面通过
`postMessage` 与宿主通信,协议见 `docs/extensions/api-reference.md`。
+143
View File
@@ -0,0 +1,143 @@
# 抖音视频搬运
被 @ 且消息里带抖音分享链接时,解析作品、下载视频,并发回原会话。
判定范围由扩展自己控制:只有**真正 @ 到当前登录账号**的文本消息才会进入流程
(`subscriptions.requireMentionMe: true`),普通消息直接忽略。
## 前置条件
- 本机有 `python3`(3.10 及以上)。
- 本机装了 Chrome:解析脚本用真实浏览器打开作品页、拦截页面自己发出的 `aweme/detail` 响应,
不自造签名。
- 解析脚本已存在于本机(默认 `scripts/douyin.py`,相对于扩展目录,也可在配置页指定自定义路径)。
- 首次运行时脚本会在 `~/Library/Caches/douyin-video/venv`(Windows 落在 `%LOCALAPPDATA%`)
自建 venv 并安装 `playwright` / `requests`,约 30 秒;之后复用,不再安装。
## 安装
TraceMemo → 左侧「扩展」→「安装目录」,选择本目录 `douyin-sender/`。
安装完成后:
1. 打开「抖音解析设置」页面,确认 Python 路径与脚本路径;
2. 打开总开关,保存;
3. 在「测试发送」里选目标群、粘贴抖音分享文案,点「测试发送」验证;
或在微信里 @ 自己发一条带抖音分享链接的文本消息。
扩展默认 `enabled: false`,安装后不会自动对外发送。
配置页的群列表来自本机通讯录,对应权限 `contacts.list`(只读群名与会话 id,不含聊天内容)。
升级同 id 的扩展会替换代码并保留配置;如果新版本**新增了权限**(例如从 image 换成 video),
升级后请「停用 → 启用」一次,让宿主按新 manifest 重新授权。
## 测试发送(配置页)
配置页底部有独立的「测试发送」:
1. 下拉选择目标群(列表来自 `contacts.listGroups`,需要 `contacts.list` 权限);
2. 粘贴抖音链接或整段分享文案(命令行脚本不需要手动截取 URL);
3. 点「测试发送」,页面会轮询进度,解析完成后把去水印视频发到该群;
4. 测试路径**不发回执**,避免测试时多一条消息;
5. 测试任务同样计入统计,进度显示在「当前任务」。
设置页可选使用「抖音 Cookie」面板粘贴并保存 Cookie header。宿主通过系统安全存储加密后保存在本机,页面只展示是否已配置,不会回显内容;测试发送与自动解析时在后台使用该 Cookie,未配置时也可回退读取本机 `douyin-cookie` 文件。
## 配置字段
| 字段 | 默认值 | 说明 |
| ----------------- | ------------------------ | ---------------------------------------------------------------------- |
| `enabled` | `false` | 总开关;关闭时任何消息都不处理 |
| `pythonPath` | `python3` | Python 可执行文件,支持 `~` |
| `scriptPath` | `scripts/douyin.py` | 解析脚本路径(默认相对于扩展目录,支持 `~` 与绝对路径) |
| `quality` | `720` | `''` 最高 / `1080` / `720` / `540`;其他值收敛到 `720` |
| `showUi` | `false` | 排障开关:显示浏览器窗口以观察最终页面;不保证改变平台响应 |
| 抖音 Cookie | 未配置 | 配置页输入后由 Electron `safeStorage` 加密保存 |
| `ackText` | `收到,正在解析,请稍候…`| 命中后先回复的文本;留空表示不回执 |
| `errorReply` | `true` | 失败时是否在原会话回一条简短说明 |
| `includeDirect` | `false` | 是否同时处理私聊 |
| `groups` | `[]` | 群白名单;空数组表示全部群 |
| `cooldownSeconds` | `60` | 按会话计的冷却,0–3600 |
| `maxFileMB` | `100` | 单文件上限,1–100,不能超过宿主 100 MB 硬限制 |
保存时写入 `configVersion: 1`;后台最多 1 秒内读到新配置(配置缓存 TTL 1000 ms)。
## 处理流程
1. `message.received` → 判定顺序:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
2. 命中后先回执(`ackText`,默认「收到,正在解析,请稍候…」;留空关闭),再进入解析。
3. `python3 <script> "<链接>" -o <dataDir>/downloads --wait 40 --download-timeout 90 --json --video-only --download`,单次打开作品页并完成解析、下载;图集只返回类型、不下载;进程总超时 420 秒,输出上限 8 MB,`cwd` 为扩展数据目录。
4. 从 JSON 结果中读取作品元数据与 `saved` 绝对路径;校验文件存在、是普通文件、未超过上限。
5. 若结果为图集,记为 `IMAGE_SET` 并按配置处理失败提示;若解析/下载失败,保留脚本返回的错误原因。
6. 发送视频,`dedupeKey = eventId + ':video'`(不再额外发送作品标题文本)。
7. 每个阶段都写 `progress` 快照并记一条日志;配置页每 2 秒刷新一次进度。
8. 无论成败写一条统计(成功/失败分别计数);失败只记阶段、错误码与去掉 URL / 路径的短原因。
9. 冷却只在**视频发送成功后**写入。
同一会话同时只跑一个任务;同一条消息重复投递时按 `会话 + 链接` 去重。启动时会清理
`<dataDir>/downloads`:只保留最近 20 个文件,并删除 7 天前的文件。
失败文案固定为三种,原因截断到 60 字且不含路径:
- `解析失败:<短原因>`
- `视频过大(<N>MB),已跳过`
- `暂不支持图集`
## 发送通道
视频走宿主的 **video 通道**:`tm.wechat.send({ type: 'video', to, path })`。
原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交,所以 `permissions` 里申请的是 `wechat.send.video`。
媒体文件必须落在扩展数据目录或系统临时目录内(宿主会用 `realpath` 复核),扩展名必须是
`mp4/mov/m4v`,大小 1 B–100 MB。所有发送仍要过 Gateway 的权限、
授权与限流:同一扩展 60 秒最多 10 条,两条之间至少 2 秒。
## 限制
- 只处理视频;图集(`type: 'image'`)不下载,按配置回「暂不支持图集」。
- 单个文件 ≤ 100 MB,超过不发送。
- 冷却按会话计,冷却期内同一会话的新链接会被忽略。
- 事件投递是「至多一次」:TraceMemo 未运行期间的消息不会补发。
- 脚本路径必须在本机真实存在;路径错误时错误文案会提示检查 Python 路径。
- 解析依赖抖音页面结构,脚本自身失效时扩展只能报「解析失败」。
## 排障:`页面已加载(NNNKB)但未发出 detail 请求`
这是浏览器打开了页面,但没有捕获到 `aweme/detail` 的作品数据。仅凭这一条错误不能判断作品已删除;页面也可能是作品壳、推荐页或平台验证状态。先看 `--debug` 现场中的页面标题、地址和截图。扩展不会并发启动第二次解析;测试发送失败时会在页面显示阶段、错误码和去掉 URL / 本地路径后的短原因。
仍需手动复试时:
1. 先等一会儿再尝试,避免同一作品短时间内重复请求;
2. 配置页勾选「显示浏览器窗口」后重新测试,观察最终停留页面;
3. 命令行单独验证时使用同一份脚本,避免与扩展并发运行:
```bash
python3 scripts/douyin.py \
"https://v.douyin.com/xxxxxx/" --json --wait 40 --show-ui
```
## 进度与统计
- 回执:命中后先发一条 `ackText`,默认「收到,正在解析,请稍候…」;留空则不回。
- 进度:存储键 `progress`,结构 `{stage,status,startedAt,updatedAt,awemeId,errorType,errorMessage}`。
配置页每 2 秒读取一次,显示「已接收 / 解析 / 下载 / 发送 / 补发文案 / 完成」,
失败时显示失败所在阶段与错误码。
- 统计:存储键 `stats`,结构 `{dateKey,todayTotal,todaySuccess,todayFailure,lastJobs[]}`;
失败也计数,`lastJobs` 保留最近 20 条(含阶段与错误码)。
- 页面顶部「统计」显示今日总计 / 成功 / 失败;表格展示最近 8 条。
## 隐私
- 分享链接会交给本机脚本,由脚本访问抖音页面;扩展本身不向任何第三方发请求。
- 下载的视频存放在扩展数据目录 `downloads/` 下,发送后不自动删除(按上面的规则轮转清理)。
- 统计只保存时间、作品 id、阶段、成败、错误码,**不含** URL、标题、作者、会话 id。
- 日志只写阶段与错误类型。
## 测试
```bash
node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
```
用例全部离线:不联网、不启动 python、不读写真实文件。
@@ -0,0 +1,766 @@
'use strict'
/**
* 抖音视频搬运 —— 后台入口。
*
* 链路:`message.received` → 纯函数判定 → 解析并下载脚本 →
* 经宿主 `wechat.send` 的 video 通道发回原会话。
*
* 这个文件跑在宿主的扩展子进程里,**只**用 `tm` 暴露的能力:
* 没有 socket、没有 dylib、没有直接读写微信数据目录。
*/
const os = require('node:os')
const path = require('node:path')
const fsSync = require('node:fs')
const fs = require('node:fs/promises')
const { execFile } = require('node:child_process')
const { promisify } = require('node:util')
const {
normalizeConfig,
extractDouyinUrl,
parseDownloadedResult,
shouldHandle,
isFileTooLarge
} = require('../lib/douyin')
const execFileAsync = promisify(execFile)
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
const PROGRESS_KEY = 'progress'
const TEST_RESULT_KEY = 'testResult'
const CONFIG_TTL_MS = 1000
/** 配置页「测试发送」的轮询间隔;页面只负责写请求、读结果。 */
/** 阶段名只用于展示与日志,不参与判断。 */
const STAGE_LABELS = {
accepted: '已接收',
resolve: '解析',
resolveDownload: '解析并下载',
download: '下载',
send: '发送',
caption: '补发文案',
done: '完成',
failed: '失败'
}
/** 脚本内部等待抖音接口的秒数,解析与下载共用。 */
const SCRIPT_WAIT_SECONDS = '40'
const DOWNLOAD_AND_RESOLVE_TIMEOUT_MS = 420_000
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
/** 宿主限制:同一扩展两次发送之间至少 2 秒,这里留 200ms 余量。 */
const SEND_GAP_MS = 2200
const KEEP_RECENT_FILES = 20
const MAX_FILE_AGE_MS = 7 * 24 * 60 * 60 * 1000
const MAX_JOB_HISTORY = 20
const COOLDOWN_MAP_LIMIT = 500
let tm = null
let cachedConfig = null
let cachedAt = 0
let cachedStats = null
let cachedProgress = null
/** 会话 → 冷却截止时间(epoch 毫秒)。 */
const cooldownUntil = new Map()
/** 正在处理的会话:同一会话同时只跑一个任务。 */
const activeConversations = new Set()
/** 正在处理的 `会话|链接`:避免同一条消息被重复投递时跑两遍。 */
const activeJobs = new Set()
function safeLog(level, message) {
try {
const writer = tm && tm.log && tm.log[level]
if (typeof writer === 'function') writer.call(tm.log, String(message))
} catch {
// 日志通道本身不可用时不能影响发送流程。
}
}
/** 错误类型化:日志只保留阶段与错误码,不写 URL、路径、标题。 */
function errorType(error) {
if (!error) return 'UNKNOWN'
if (error.killed || error.signal) return 'TIMEOUT'
// 数字退出码单独标成 EXIT_n,避免统计里只看到一个「2」。
if (typeof error.code === 'number') return `EXIT_${error.code}`
if (typeof error.code === 'string' && /^[A-Z0-9_]+$/.test(error.code)) return error.code
if (error.name === 'Error') return 'ERROR'
return String(error.name || 'ERROR')
}
/** 去掉换行、链接与路径,只留 ≤60 字的短原因。 */
function shortReason(input) {
let text = String(input === null || input === undefined ? '' : input)
.replace(/https?:\/\/\S+/gi, ' ')
.replace(/[\r\n\t]+/g, ' ')
.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s"'))]+)+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
text = text.replace(/^[::,,。;;-]+/, '').trim()
text = text.replace(/title=[^,,))]+/gi, 'title=已隐藏')
if (!text) return '未知原因'
return text.slice(0, 60)
}
function parseFailure(cause, type) {
return { ok: false, message: `解析失败:${shortReason(cause)}`, errorType: type || 'PARSE' }
}
function tooLargeMessage(sizeBytes) {
const megabytes = Math.max(1, Math.ceil(Number(sizeBytes) / (1024 * 1024)))
return `视频过大(${megabytes}MB),已跳过`
}
function expandHome(value) {
const raw = String(value || '').trim()
if (!raw) return ''
if (raw === '~') return os.homedir()
if (raw.startsWith('~/') || raw.startsWith('~' + path.sep)) {
return path.join(os.homedir(), raw.slice(2))
}
return raw
}
function downloadsDir() {
return path.join(tm.extension.dataDir, 'downloads')
}
async function loadConfig() {
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return cachedConfig
let stored = null
try {
stored = await tm.storage.get(CONFIG_KEY)
} catch (error) {
safeLog('warn', `读取配置失败:${errorType(error)}`)
}
cachedConfig = normalizeConfig(stored)
cachedAt = Date.now()
return cachedConfig
}
function dateKey(timestamp) {
const date = new Date(timestamp)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${date.getFullYear()}-${month}-${day}`
}
function normalizeStats(raw) {
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
const lastJobs = Array.isArray(input.lastJobs)
? input.lastJobs
.filter((job) => job && typeof job === 'object')
.slice(0, MAX_JOB_HISTORY)
.map((job) => ({
at: Number(job.at) || 0,
awemeId: String(job.awemeId || '').slice(0, 32),
ok: job.ok === true,
stage: String(job.stage || '').slice(0, 20),
errorType: String(job.errorType || '').slice(0, 24)
}))
: []
const total = Math.max(0, Math.trunc(Number(input.todayTotal ?? input.todayCount) || 0))
return {
dateKey: typeof input.dateKey === 'string' ? input.dateKey.slice(0, 10) : '',
todayTotal: total,
todaySuccess: Math.max(0, Math.trunc(Number(input.todaySuccess) || 0)),
todayFailure: Math.max(0, Math.trunc(Number(input.todayFailure) || 0)),
lastJobs
}
}
async function loadStats() {
if (cachedStats) return cachedStats
let stored = null
try {
stored = await tm.storage.get(STATS_KEY)
} catch (error) {
safeLog('warn', `读取统计失败:${errorType(error)}`)
}
cachedStats = normalizeStats(stored)
return cachedStats
}
/**
* 追加一条任务记录。
*
* 统计里只允许出现 awemeId / 时间 / 阶段 / 成败 / 错误类型;URL、标题、作者、
* 会话 id 都不写,避免把聊天内容沉淀成扩展数据。
*/
async function recordJob(job) {
const now = Date.now()
const current = await loadStats()
const key = dateKey(now)
const sameDay = current.dateKey === key
const next = {
dateKey: key,
todayTotal: (sameDay ? current.todayTotal : 0) + 1,
todaySuccess: (sameDay ? current.todaySuccess : 0) + (job.ok === true ? 1 : 0),
todayFailure: (sameDay ? current.todayFailure : 0) + (job.ok === true ? 0 : 1),
lastJobs: [
{
at: now,
awemeId: String(job.awemeId || '').slice(0, 32),
ok: job.ok === true,
stage: String(job.stage || '').slice(0, 20),
errorType: String(job.errorType || '').slice(0, 24)
},
...current.lastJobs
].slice(0, MAX_JOB_HISTORY)
}
cachedStats = next
try {
await tm.storage.set(STATS_KEY, next)
} catch (error) {
safeLog('warn', `写入统计失败:${errorType(error)}`)
}
}
/**
* 写「当前任务」快照,供配置页展示进度。
*
* 只保留一条最近任务:jobId 用事件 id(不可逆哈希),不含会话与正文。
* 写失败只 warn,不能因为展示层异常影响发送。
*/
async function setProgress(patch) {
const now = Date.now()
const next = {
...(cachedProgress || {}),
...patch,
updatedAt: now
}
if (!next.startedAt) next.startedAt = now
cachedProgress = next
const label = STAGE_LABELS[next.stage] || next.stage || ''
safeLog('info', `任务进度:${label}${next.awemeId ? `(${next.awemeId})` : ''}`)
try {
await tm.storage.set(PROGRESS_KEY, next)
} catch (error) {
safeLog('warn', `写入进度失败:${errorType(error)}`)
}
}
function markCooldown(conversationId, seconds) {
if (!conversationId || !(seconds > 0)) return
cooldownUntil.set(conversationId, Date.now() + seconds * 1000)
if (cooldownUntil.size > COOLDOWN_MAP_LIMIT) {
const now = Date.now()
for (const [key, until] of cooldownUntil) {
if (until <= now) cooldownUntil.delete(key)
}
}
}
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}
/**
* 在 Apple Silicon macOS 上,若宿主的默认 python3 是 x86_64(Rosetta 2),
* 直接启动会把 P_TRANSLATED 标志遗传给子进程 Google Chrome,导致抖音页面卡在加载中。
* 这里优先选用缓存 venv 的原生 Python,并通过 /usr/bin/arch -arm64 强制切换为原生 arm64。
*/
function resolvePythonInvocation(pythonPath, scriptPath, args) {
if (process.platform !== 'darwin') {
return { file: pythonPath, args: [scriptPath, ...args] }
}
let resolvedPython = pythonPath
if (pythonPath === 'python3') {
const venvPython = path.join(
os.homedir(),
'Library',
'Caches',
'douyin-video',
'venv',
'bin',
'python'
)
try {
if (fsSync.existsSync(venvPython)) resolvedPython = venvPython
} catch {
// 缓存 venv 不可读时退回配置里的 pythonPath。
}
}
try {
if (fsSync.existsSync('/usr/bin/arch')) {
return {
file: '/usr/bin/arch',
args: ['-arm64', resolvedPython, scriptPath, ...args]
}
}
} catch {
// 非标准系统环境缺少 /usr/bin/arch 时直接调用解释器。
}
return { file: resolvedPython, args: [scriptPath, ...args] }
}
/**
* 解析可用的抖音 Cookie:
* 1. 优先使用调用方显式传入的 cookieHeader(测试发送 / 测试下载);
* 2. 尝试向宿主读取已保存的 Cookie(若宿主暴露接口);
* 3. 回退读取扩展私有目录或桌面上的 `douyin-cookie` 文件(供 @我自己 自动回复链路使用)。
*/
async function resolveCookieHeader(explicitHeader) {
const direct = String(explicitHeader || '').trim()
if (direct) return direct
if (tm && tm.douyin && typeof tm.douyin.getCookie === 'function') {
try {
const fromHost = String((await tm.douyin.getCookie()) || '').trim()
if (fromHost) return fromHost
} catch {
// 宿主未提供或读取失败时继续尝试本地文件。
}
}
const candidates = [
path.join(tm.extension.dataDir, 'douyin-cookie.txt'),
path.join(os.homedir(), 'Desktop', 'douyin-cookie'),
path.join(os.homedir(), 'Desktop', 'douyin-cookie.txt')
]
for (const file of candidates) {
try {
const content = String(await fs.readFile(file, 'utf8')).trim()
if (content) return content
} catch {
// 文件不存在或无权限时跳过。
}
}
return ''
}
function resolveScriptPath(value) {
const expanded = expandHome(value)
if (!expanded) return path.resolve(__dirname, '..', 'scripts', 'douyin.py')
if (path.isAbsolute(expanded)) return expanded
return path.resolve(__dirname, '..', expanded)
}
/** 统一封装脚本调用:固定 cwd、超时、输出上限、UTF-8 与 macOS 原生 arm64 执行。 */
async function runPython(args, timeoutMs, config) {
// 首次启用时 dataDir 可能还没被创建;execFile 的 cwd 不存在会直接 ENOENT。
await fs.mkdir(tm.extension.dataDir, { recursive: true })
const pythonPath = expandHome(config.pythonPath)
const scriptPath = resolveScriptPath(config.scriptPath)
const invocation = resolvePythonInvocation(pythonPath, scriptPath, args)
return execFileAsync(invocation.file, invocation.args, {
cwd: tm.extension.dataDir,
timeout: timeoutMs,
maxBuffer: MAX_OUTPUT_BYTES,
env: {
...process.env,
PYTHONIOENCODING: 'utf-8',
PYTHONUNBUFFERED: '1',
DOUYIN_ARM64_READY: '1'
},
windowsHide: true
})
}
function describeExecError(error) {
if (!error) return '失败'
if (error.code === 'ENOENT') return '找不到 Python 可执行文件,请检查 Python 路径'
if (error.killed || error.signal) return '超时'
if (typeof error.code === 'number') return `脚本退出码 ${error.code}`
if (typeof error.code === 'string' && /^E[A-Z]+$/.test(error.code)) {
return `失败(${error.code})`
}
return '失败'
}
async function resolveAndDownloadVideo(url, config, options = {}) {
const dir = downloadsDir()
try {
await fs.mkdir(dir, { recursive: true })
} catch (error) {
return parseFailure('下载目录不可用(' + errorType(error) + ')', errorType(error))
}
const args = [
url,
'-o',
dir,
'--wait',
SCRIPT_WAIT_SECONDS,
'--download-timeout',
'90',
'--json',
'--debug',
'--video-only',
'--download'
]
if (config.quality) args.push('-q', config.quality)
if (config.showUi) args.push('--show-ui')
const cookieHeader = await resolveCookieHeader(options.cookieHeader)
let temporaryCookieFile = ''
let stdout = ''
try {
if (cookieHeader) {
await fs.mkdir(tm.extension.dataDir, { recursive: true })
temporaryCookieFile = path.join(
tm.extension.dataDir,
`.douyin-cookie-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`
)
await fs.writeFile(temporaryCookieFile, cookieHeader, { mode: 0o600, flag: 'wx' })
await fs.chmod(temporaryCookieFile, 0o600)
args.push('--cookie-file', temporaryCookieFile)
}
const result = await runPython(args, DOWNLOAD_AND_RESOLVE_TIMEOUT_MS, config)
stdout = String(result.stdout || '')
} catch (error) {
stdout = String((error && error.stdout) || '')
if (!stdout.trim()) {
return parseFailure(
temporaryCookieFile ? 'Cookie 文件不可用或解析超时' : describeExecError(error),
temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error)
)
}
} finally {
if (temporaryCookieFile) {
try {
await fs.unlink(temporaryCookieFile)
} catch {
// 解析结束后清除临时凭证文件。
}
}
}
const parsed = parseDownloadedResult(stdout)
if (!parsed) {
const failure = /✗\s*(?:失败[::])?\s*(.+)/.exec(stdout)
return parseFailure(failure ? failure[1] : '脚本输出无法识别', 'INVALID_OUTPUT')
}
if (!parsed.ok) return parseFailure(parsed.message, parsed.errorType)
let stat = null
try {
stat = await fs.stat(parsed.path)
} catch {
return parseFailure('下载文件不存在', 'MISSING_FILE')
}
if (!stat.isFile()) return parseFailure('下载结果不是文件', 'NOT_A_FILE')
if (isFileTooLarge(stat.size, config.maxFileMB)) {
return { ok: false, message: tooLargeMessage(stat.size), errorType: 'TOO_LARGE' }
}
return { ok: true, path: parsed.path, size: stat.size, meta: parsed.meta }
}
let lastSendAt = 0
async function waitSendSlot() {
const elapsed = Date.now() - lastSendAt
if (lastSendAt > 0 && elapsed < SEND_GAP_MS) {
await sleep(SEND_GAP_MS - elapsed)
}
lastSendAt = Date.now()
}
async function sendText(to, text, dedupeKey, stage) {
try {
await waitSendSlot()
await tm.wechat.send({ to, text, dedupeKey })
lastSendAt = Date.now()
return true
} catch (error) {
safeLog('warn', `未完成:阶段=${stage || 'text'} 错误=${errorType(error)}`)
return false
}
}
/** 发视频:走宿主 video 通道,`dedupeKey` 保证同一条消息只发一次。 */
async function sendVideo(event, filePath) {
try {
await waitSendSlot()
await tm.wechat.send({
type: 'video',
to: event.conversationId,
path: filePath,
dedupeKey: `${event.eventId}:video`
})
lastSendAt = Date.now()
return true
} catch (error) {
safeLog('warn', `未完成:阶段=send 错误=${errorType(error)}`)
return false
}
}
async function reportFailure(event, config, message) {
if (!config.errorReply) return
await sendText(event.conversationId, message, `${event.eventId}:error`, 'reply')
}
/**
* 一次完整任务。
*
* `stage` 记录失败发生的位置:`resolveDownload` / `send` / `done`。
* 进度快照与统计都会落盘;失败原因只保留错误类型,不写 URL / 路径 / 标题。
*/
async function processLink(event, config, url, options = {}) {
const jobId = event.eventId
let awemeId = ''
let stage = 'accepted'
let ok = false
let failureCode = ''
let failureMessage = ''
try {
stage = 'resolveDownload'
await setProgress({ jobId, awemeId, stage, status: 'running' })
const downloaded = await resolveAndDownloadVideo(url, config, options)
if (!downloaded.ok) {
failureCode = downloaded.errorType || 'DOWNLOAD_FAILED'
failureMessage = downloaded.message
return
}
const meta = downloaded.meta
awemeId = String(meta.aweme_id || '')
stage = 'send'
await setProgress({ jobId, awemeId, stage, status: 'running' })
const sent = await sendVideo(event, downloaded.path)
if (!sent) {
failureCode = 'SEND_FAILED'
failureMessage = '视频发送失败'
return
}
ok = true
stage = 'done'
// 冷却只在视频真正发出去之后才写入,失败不占用下一次机会。
markCooldown(event.conversationId, config.cooldownSeconds)
} catch (error) {
failureCode = errorType(error)
failureMessage = '处理异常'
safeLog('warn', `处理异常:阶段=${stage} 错误=${failureCode}`)
} finally {
if (ok) {
await setProgress({ jobId, awemeId, stage: 'done', status: 'done', errorType: '' })
} else {
if (failureMessage && options.replyOnFailure !== false) {
await reportFailure(event, config, failureMessage)
}
await setProgress({
jobId,
awemeId,
stage: stage === 'accepted' ? 'resolve' : stage,
status: 'failed',
errorType: failureCode || 'FAILED',
errorMessage: failureMessage ? shortReason(failureMessage) : ''
})
safeLog('warn', `未完成:阶段=${stage} 错误=${failureCode || 'FAILED'}`)
}
await recordJob({
awemeId,
ok,
stage: ok ? 'done' : stage,
errorType: ok ? '' : failureCode || 'FAILED'
})
}
}
async function handleEvent(event) {
try {
const config = await loadConfig()
const decision = shouldHandle(event, config, cooldownUntil, Date.now())
if (!decision.handle) return
const conversationId = event.conversationId
const jobKey = `${conversationId}|${decision.url}`
if (activeConversations.has(conversationId) || activeJobs.has(jobKey)) return
activeConversations.add(conversationId)
activeJobs.add(jobKey)
try {
await setProgress({
jobId: event.eventId,
stage: 'accepted',
status: 'running',
startedAt: Date.now(),
awemeId: '',
errorType: '',
errorMessage: ''
})
// 先回执再干活:解析/下载要十几秒,用户不该靠猜。
if (config.ackText) {
await sendText(conversationId, config.ackText, `${event.eventId}:ack`, 'ack')
}
await processLink(event, config, decision.url)
} finally {
activeConversations.delete(conversationId)
activeJobs.delete(jobKey)
}
} catch (error) {
safeLog('warn', `事件处理失败:${errorType(error)}`)
}
}
let lastTestRequestId = ''
let testInFlight = false
let pendingTestRequest = null
async function writeTestResult(result) {
try {
await tm.storage.set(TEST_RESULT_KEY, result)
} catch (error) {
safeLog('warn', `写入测试结果失败:${errorType(error)}`)
}
}
/**
* 配置页「测试发送」。
*
* 测试请求通过宿主一次性送达,不落入扩展持久化存储。
*/
async function pollTestRequest() {
if (testInFlight) return
const request = pendingTestRequest
pendingTestRequest = null
if (!request || typeof request !== 'object') return
const id = String(request.id || '').trim()
if (!id || id === lastTestRequestId) return
lastTestRequestId = id
const to = String(request.to || '').trim()
const text = String(request.text || '').trim()
if (!to || !text) {
await writeTestResult({
id,
status: 'failed',
message: '测试请求缺少群聊或链接',
at: Date.now()
})
return
}
if (activeConversations.has(to)) {
await writeTestResult({
id,
status: 'failed',
message: '该群正在执行其他任务,请稍后重试',
at: Date.now()
})
return
}
const url = extractDouyinUrl(text)
if (!url) {
await writeTestResult({ id, status: 'failed', message: '没有识别到抖音链接', at: Date.now() })
return
}
const config = await loadConfig()
const cookieHeader = request.cookieHeader ? String(request.cookieHeader) : ''
testInFlight = true
activeConversations.add(to)
try {
await writeTestResult({ id, status: 'running', message: '已开始解析…', at: Date.now() })
await setProgress({
jobId: `test:${id}`,
stage: 'accepted',
status: 'running',
startedAt: Date.now(),
awemeId: '',
errorType: '',
errorMessage: ''
})
// 测试路径不发回执:结果直接显示在配置页,视频发到目标群。
await processLink(
{
eventId: `test:${id}`,
conversationId: to,
isGroup: to.endsWith('@chatroom'),
isSelf: false,
type: 'text',
text,
mentionsMe: true
},
config,
url,
{ replyOnFailure: false, cookieHeader }
)
const progress = cachedProgress || {}
if (progress.status === 'done') {
await writeTestResult({
id,
status: 'done',
message: '测试发送完成:视频已发到该群',
at: Date.now()
})
} else {
const label = STAGE_LABELS[progress.stage] || progress.stage || '未知阶段'
await writeTestResult({
id,
status: 'failed',
message: `测试发送失败:${label}${progress.errorType ? `(${progress.errorType})` : ''}${progress.errorMessage ? `:${progress.errorMessage}` : ''}`,
at: Date.now()
})
}
} catch (error) {
await writeTestResult({
id,
status: 'failed',
message: `测试发送异常:${errorType(error)}`,
at: Date.now()
})
} finally {
activeConversations.delete(to)
testInFlight = false
}
}
/**
* 清理下载目录:只保留最近 20 个文件,并删除 7 天前的文件。
*
* 清理失败不影响发送能力,逐条 try/catch,最坏情况是目录继续变大。
*/
async function cleanupDownloads() {
const dir = downloadsDir()
let entries = []
try {
entries = await fs.readdir(dir, { withFileTypes: true })
} catch {
return
}
const files = []
for (const entry of entries) {
if (!entry.isFile()) continue
const full = path.join(dir, entry.name)
try {
const stat = await fs.stat(full)
files.push({ full, mtime: stat.mtimeMs })
} catch {
// 枚举期间被删除或无法访问,跳过即可。
}
}
files.sort((left, right) => right.mtime - left.mtime)
const now = Date.now()
for (let index = 0; index < files.length; index += 1) {
const fresh = now - files[index].mtime <= MAX_FILE_AGE_MS
if (index < KEEP_RECENT_FILES && fresh) continue
try {
await fs.unlink(files[index].full)
} catch {
// 单个文件删不掉就留着,下一次启动再试。
}
}
}
module.exports = function activate(api) {
tm = api
// 宿主对 handler 有 10 秒超时;脚本可能要跑几分钟,所以这里只排队不等待。
tm.events.on('message.received', (event) => {
void handleEvent(event)
})
void cleanupDownloads()
globalThis.__tmTestSend = async (request) => {
pendingTestRequest = request
await pollTestRequest()
return { accepted: true }
}
tm.log.info('抖音搬运已加载')
}
@@ -0,0 +1,354 @@
'use strict'
/**
* 抖音分享链接解析的纯函数层。
*
* 这一层不碰文件系统、不启子进程、不读时钟:所有输入都从参数进来,
* 所有输出都可序列化,便于在 `node:test` 里离线断言。
*
* 单位约定:
* - 时间一律 epoch 毫秒;
* - 文件大小一律字节,配置里的上限单位是 MB(1 MB = 1024 * 1024 B)。
*/
/** 宿主发送通道的硬上限:单个媒体文件 100 MB,配置不允许突破。 */
const HOST_MAX_FILE_MB = 100
/** 解析脚本的默认位置(相对于扩展目录,支持自定义绝对路径或 `~/`)。 */
const DEFAULT_SCRIPT_PATH = 'scripts/douyin.py'
/** 画质白名单;空串表示「最高」,不传 `-q` 给脚本。 */
const QUALITY_VALUES = ['', '1080', '720', '540']
const DEFAULT_CONFIG = {
configVersion: 1,
enabled: false,
pythonPath: 'python3',
scriptPath: DEFAULT_SCRIPT_PATH,
quality: '720',
/** 排障开关:显示浏览器窗口以观察实际页面状态。 */
showUi: false,
/** 命中后先回一句,避免用户不知道是否收到;空串表示不回复。 */
ackText: '收到,正在解析,请稍候…',
sendCaption: false,
captionTemplate: '{author}:{title}',
errorReply: true,
includeDirect: false,
groups: [],
cooldownSeconds: 60,
maxFileMB: HOST_MAX_FILE_MB
}
/** 分享链接只认这三种形态;短链的 id 是字母数字,长链只认数字作品 id。 */
const DOUYIN_URL_PATTERN =
/https?:\/\/(?:v\.douyin\.com\/[A-Za-z0-9_-]{1,64}|(?:www\.)?douyin\.com\/(?:video|note)\/\d{1,32})/i
/** 中文文案里链接后面常跟这些符号,属于分隔符不属于链接。 */
const TRAILING_PUNCTUATION = /[)\]}>,.;:!?'"`。,、;:!?…)】》〉」』”’]+$/
const CAPTION_MAX_LENGTH = 200
const GROUP_MAX_COUNT = 200
function clampInt(value, min, max, fallback) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return fallback
const rounded = Math.trunc(numeric)
if (rounded < min) return min
if (rounded > max) return max
return rounded
}
function normalizeQuality(value) {
if (value === null || value === undefined) return DEFAULT_CONFIG.quality
const text = String(value).trim()
// 数值型画质(720)与字符串画质('720')同义;`''` 表示最高。
if (text === '') return ''
return QUALITY_VALUES.includes(text) ? text : DEFAULT_CONFIG.quality
}
function normalizeGroups(value) {
const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\s,]+/) : []
const result = []
for (const item of list) {
const id = String(item === null || item === undefined ? '' : item).trim()
if (!id) continue
if (result.includes(id)) continue
result.push(id.slice(0, 128))
if (result.length >= GROUP_MAX_COUNT) break
}
return result
}
function normalizeText(value, fallback, maxLength) {
const text = typeof value === 'string' ? value.trim() : ''
return (text || fallback).slice(0, maxLength)
}
/**
* 把任意来源(存储、表单、旧版本)的配置收敛成可执行形态。
*
* 契约:**永不抛错**,字段缺失或非法时回落到默认值;返回对象永远是全新的,
* 调用方可以直接持有并修改,不会污染 `DEFAULT_CONFIG`。
*/
function normalizeConfig(raw) {
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
return {
configVersion: 1,
enabled: input.enabled === true,
pythonPath: normalizeText(input.pythonPath, DEFAULT_CONFIG.pythonPath, 512),
scriptPath: normalizeText(input.scriptPath, DEFAULT_SCRIPT_PATH, 512),
quality: normalizeQuality(input.quality),
showUi: input.showUi === true,
ackText:
input.ackText === undefined
? DEFAULT_CONFIG.ackText
: String(input.ackText).trim().slice(0, 200),
sendCaption: input.sendCaption === true,
captionTemplate: normalizeText(input.captionTemplate, DEFAULT_CONFIG.captionTemplate, 200),
errorReply: input.errorReply !== false,
includeDirect: input.includeDirect === true,
groups: normalizeGroups(input.groups),
cooldownSeconds: clampInt(input.cooldownSeconds, 0, 3600, DEFAULT_CONFIG.cooldownSeconds),
maxFileMB: clampInt(input.maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
}
}
/**
* 从一段文本里取第一个抖音分享链接。
*
* 输入可能是裸链接,也可能是「复制打开抖音…」整段文案;返回值已去掉尾随标点,
* 查询串与 fragment 一并丢弃(短链换长链由脚本完成,扩展不参与)。
*
* 返回 `null` 表示没有可识别的抖音作品链接;`javascript:` / `ftp:` / 非抖音域名
* 一律不匹配。
*/
function extractDouyinUrl(text) {
const source = typeof text === 'string' ? text : ''
if (!source) return null
const matched = DOUYIN_URL_PATTERN.exec(source)
if (!matched) return null
const cleaned = matched[0].replace(TRAILING_PUNCTUATION, '')
return cleaned || null
}
/** 从 `start` 处的 `[` 找到配对的 `]`,跳过字符串字面量与转义;失败返回 -1。 */
function findArrayEnd(text, start) {
let depth = 0
let inString = false
let escaped = false
for (let index = start; index < text.length; index += 1) {
const char = text[index]
if (inString) {
if (escaped) escaped = false
else if (char === '\\') escaped = true
else if (char === '"') inString = false
continue
}
if (char === '"') {
inString = true
continue
}
if (char === '[') {
depth += 1
continue
}
if (char === ']') {
depth -= 1
if (depth === 0) return index
if (depth < 0) return -1
}
}
return -1
}
function isResolveResultList(value) {
if (!Array.isArray(value) || value.length === 0) return false
return value.every(
(item) =>
item &&
typeof item === 'object' &&
typeof item.url === 'string' &&
typeof item.ok === 'boolean'
)
}
/**
* 从 stdout 中取第一个结构合法的结果数组。
*
* 按结构判定(非空数组、每项含 `url:string` 与 `ok:boolean`),跳过进度行里的
* `[1]` 与嵌套的 `quality_options`;空数组与非法 JSON 返回 `null`。
*/
function parseResolveJson(stdout) {
const text = typeof stdout === 'string' ? stdout : ''
if (!text) return null
for (let start = 0; start < text.length; start += 1) {
if (text[start] !== '[') continue
const end = findArrayEnd(text, start)
if (end < 0) continue
try {
const value = JSON.parse(text.slice(start, end + 1))
if (isResolveResultList(value)) return value
} catch {
// 这个 `[` 不是数组起点(可能在字符串里),继续向后找。
}
}
return null
}
/**
* 从下载输出里取最后一个 `✅` 后面的绝对路径。
*
* 脚本对视频打印 ` ✅ /abs/xxx.mp4`,对图集打印目录后面再跟一段「(N 个文件)」。
* 路径里可能含空格(作者名与标题),所以只按行首标记切分,不按空白切分。
*
* 返回 `null` 表示没有可用的绝对路径。
*/
function parseSavedPath(stdout) {
const text = typeof stdout === 'string' ? stdout : ''
if (!text) return null
const lines = text.split(/\r?\n/)
for (let index = lines.length - 1; index >= 0; index -= 1) {
const marker = lines[index].indexOf('✅')
if (marker < 0) continue
let rest = lines[index].slice(marker + 1).trim()
// 去掉尾部的「(N 个文件)」之类附注,它不属于路径。
rest = rest.replace(/\s*[((][^(())]*[))]\s*$/, '').trim()
if (!rest) continue
if (rest[0] !== '/') continue
return rest
}
return null
}
function parseDownloadedResult(stdout) {
const results = parseResolveJson(stdout)
const video = pickVideoResult(results)
if (video) {
const saved = Array.isArray(video.saved)
? video.saved.find((value) => typeof value === 'string' && value.startsWith('/'))
: null
if (saved) return { ok: true, meta: video, path: saved }
if (video.error) return { ok: false, message: video.error, errorType: 'DOWNLOAD_FAILED' }
return null
}
const image = results && results.find((item) => item && item.ok === true && item.type === 'image')
if (image) return { ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
const failure = results && results.find((item) => item && item.ok === false)
if (failure && failure.error) {
return {
ok: false,
message: failure.error,
errorType: failure.aweme_id ? 'DOWNLOAD_FAILED' : 'RESOLVE_FAILED'
}
}
return null
}
/**
* 按模板渲染文案。
*
* 已知变量 `{author}` / `{title}` / `{awemeId}` 会被替换;未知变量原样保留,
* 让用户能看见自己写错了什么。结果 trim 后截断到 200 字。
*/
function renderCaption(template, meta) {
const source = typeof template === 'string' ? template : ''
const data = meta && typeof meta === 'object' ? meta : {}
const values = {
author: data.author === null || data.author === undefined ? '' : String(data.author),
title: data.title === null || data.title === undefined ? '' : String(data.title),
awemeId: data.awemeId === null || data.awemeId === undefined ? '' : String(data.awemeId)
}
// 已知变量即使取不到值也替换成空串:正文里留下 `{author}` 会被当成程序缺陷。
const rendered = source.replace(/\{(author|title|awemeId)\}/g, (whole, name) => values[name])
return rendered.trim().slice(0, CAPTION_MAX_LENGTH)
}
function inScope(event, config) {
if (event.isGroup) {
return config.groups.length === 0 || config.groups.includes(event.conversationId)
}
return config.includeDirect === true
}
function readCooldown(cooldownUntil, conversationId) {
if (!cooldownUntil || !conversationId) return 0
const value =
typeof cooldownUntil.get === 'function'
? cooldownUntil.get(conversationId)
: cooldownUntil[conversationId]
const numeric = Number(value)
return Number.isFinite(numeric) && numeric > 0 ? numeric : 0
}
/**
* 判断一条事件是否该进入处理流程。
*
* 判定顺序固定:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
* `reason` 的取值集合固定为
* `disabled | self | type | mention | no_link | scope | cooldown | ok`。
*
* `url` 只要提取成功就会返回,即使后续被范围或冷却拦下,便于调用方写日志。
*/
function shouldHandle(event, config, cooldownUntil, now) {
const settings = normalizeConfig(config)
if (!settings.enabled) return { handle: false, url: null, reason: 'disabled' }
if (!event || typeof event !== 'object') return { handle: false, url: null, reason: 'no_link' }
if (event.isSelf) return { handle: false, url: null, reason: 'self' }
if (event.type !== 'text') return { handle: false, url: null, reason: 'type' }
if (!event.mentionsMe) return { handle: false, url: null, reason: 'mention' }
const url = extractDouyinUrl(event.text)
if (!url) return { handle: false, url: null, reason: 'no_link' }
if (!inScope(event, settings)) return { handle: false, url, reason: 'scope' }
const until = readCooldown(cooldownUntil, event.conversationId)
const timestamp = Number.isFinite(Number(now)) ? Number(now) : Date.now()
if (timestamp < until) return { handle: false, url, reason: 'cooldown' }
return { handle: true, url, reason: 'ok' }
}
/**
* 文件是否不该发送。
*
* 返回 true 的三种情况:超过配置上限、字节数非法、文件为空。
* 上限本身被收敛到 1–100 MB,宿主 100 MB 的硬限制不会被配置绕过。
*/
function isFileTooLarge(sizeBytes, maxFileMB) {
const limitMB = clampInt(maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
const size = Number(sizeBytes)
if (!Number.isFinite(size) || size <= 0) return true
return size > limitMB * 1024 * 1024
}
/**
* 从解析结果里挑第一条可下载的视频。
*
* 图集(`type === 'image'`)与失败项都不算;没有视频时返回 `null`,
* 由调用方决定回复「暂不支持图集」还是通用失败文案。
*/
function pickVideoResult(results) {
if (!Array.isArray(results)) return null
for (const item of results) {
if (!item || typeof item !== 'object') continue
if (item.ok !== true) continue
if (item.type !== 'video') continue
return item
}
return null
}
module.exports = {
DEFAULT_CONFIG,
normalizeConfig,
extractDouyinUrl,
parseResolveJson,
parseSavedPath,
parseDownloadedResult,
renderCaption,
shouldHandle,
isFileTooLarge,
pickVideoResult
}
@@ -0,0 +1,35 @@
{
"manifestVersion": 1,
"id": "com.example.douyin-sender",
"name": "抖音视频搬运",
"version": "1.0.3",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。",
"author": "TraceMemo Examples",
"permissions": [
"messages.subscribe",
"contacts.list",
"wechat.send.video",
"wechat.send.text",
"storage"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": ["text"],
"conversationIds": [],
"requireMentionMe": true,
"includeSelf": false
},
"contributions": {
"pages": [
{
"id": "settings",
"title": "抖音解析设置"
}
]
}
}
@@ -0,0 +1,412 @@
'use strict'
/**
* 纯函数层测试:不联网、不启动 python、不读真实文件。
* 运行:node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import douyin from '../lib/douyin.js'
const {
DEFAULT_CONFIG,
normalizeConfig,
extractDouyinUrl,
parseResolveJson,
parseSavedPath,
parseDownloadedResult,
renderCaption,
shouldHandle,
isFileTooLarge,
pickVideoResult
} = douyin
const SHORT_URL = 'https://v.douyin.com/fixture123'
const SHORT_TEXT_URL = 'https://v.douyin.com/fixture123/'
const VIDEO_URL = 'https://www.douyin.com/video/7300000000000000001'
const NOTE_URL = 'https://douyin.com/note/7300000000000000002'
function makeEvent(overrides = {}) {
return {
eventId: 'message:fixture-1',
accountId: 'wxid_fixture',
conversationId: 'fixture-room@chatroom',
messageId: 'local-1',
senderId: 'wxid_fixture',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text',
text: `@李四 ${SHORT_TEXT_URL}`,
mentionsMe: true,
timestamp: 0,
...overrides
}
}
function makeConfig(overrides = {}) {
return normalizeConfig({ enabled: true, ...overrides })
}
test('从裸短链里提取链接', () => {
assert.equal(extractDouyinUrl(SHORT_TEXT_URL), SHORT_URL)
})
test('从长链 video 里提取链接', () => {
assert.equal(extractDouyinUrl(VIDEO_URL), VIDEO_URL)
})
test('从 note 链接里提取链接', () => {
assert.equal(extractDouyinUrl(NOTE_URL), NOTE_URL)
})
test('从整段分享文案里提取链接', () => {
const text =
'7.89 复制打开抖音,看看【张三的作品】很有意思 https://v.douyin.com/fixture123/ 01/02 abc:/'
assert.equal(extractDouyinUrl(text), SHORT_URL)
})
test('去掉链接尾随的中文标点', () => {
assert.equal(extractDouyinUrl('看这个 https://v.douyin.com/fixture123/。'), SHORT_URL)
})
test('拒绝非抖音域名', () => {
assert.equal(extractDouyinUrl('https://example.com/video/7300000000000000001'), null)
assert.equal(extractDouyinUrl('https://douyin.com.evil.test/video/1'), null)
assert.equal(extractDouyinUrl('https://foo.douyin.com/video/1'), null)
})
test('拒绝 javascript: 与 ftp:', () => {
assert.equal(extractDouyinUrl('javascript://v.douyin.com/fixture123/'), null)
assert.equal(extractDouyinUrl('ftp://v.douyin.com/fixture123/'), null)
})
test('没有链接时返回 null', () => {
assert.equal(extractDouyinUrl('今天天气不错'), null)
assert.equal(extractDouyinUrl(''), null)
assert.equal(extractDouyinUrl(undefined), null)
})
test('JSON 前后有噪声也能解析出数组', () => {
const stdout = [
'共 1 个链接',
'▶ https://v.douyin.com/fixture123/',
' ✓ 解析成功:video | 张三 | 标题',
'',
'[{"url":"https://v.douyin.com/fixture123/","ok":true,"type":"video","aweme_id":"730"}]',
'',
'完成:1/1 成功'
].join('\n')
const parsed = parseResolveJson(stdout)
assert.ok(Array.isArray(parsed))
assert.equal(parsed.length, 1)
assert.equal(parsed[0].aweme_id, '730')
})
test('缩进的多行 JSON 数组按真实输出解析', () => {
const stdout = [
' ✓ 解析成功:video | 张三 | 标题',
'==================================================',
'完成:1/1 成功',
'[',
' {',
' "url": "https://v.douyin.com/fixture123/",',
' "ok": true,',
' "type": "video",',
' "quality_options": [',
' {"gear": "720p", "rank": 720}',
' ]',
' }',
']'
].join('\n')
const parsed = parseResolveJson(stdout)
assert.ok(Array.isArray(parsed))
assert.equal(parsed[0].quality_options[0].rank, 720)
})
test('非法 JSON 返回 null', () => {
assert.equal(parseResolveJson('不是 JSON'), null)
assert.equal(parseResolveJson('[{"ok":true,'), null)
assert.equal(parseResolveJson(''), null)
})
test('进度行里的方括号不会被误认为结果数组', () => {
const stdout = [
' [1] 跳过(无地址)',
' ✅ /tmp/fixture-folder (2 个文件)',
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","aweme_id":"730"}]'
].join('\n')
const parsed = parseResolveJson(stdout)
assert.ok(Array.isArray(parsed))
assert.equal(parsed.length, 1)
assert.equal(parsed[0].type, 'image')
})
test('空数组视为无效结果', () => {
assert.equal(parseResolveJson('[]'), null)
})
test('合法 JSON 但不是数组时返回 null', () => {
assert.equal(parseResolveJson('{"ok":true}'), null)
})
test('下载输出里能取到绝对路径', () => {
const stdout = [
' ✓ 解析成功:video | 张三 | 标题',
' 下载中 → 张三 - 标题 - 730.mp4',
' ✅ /tmp/fixture/downloads/张三 - 标题 - 730.mp4',
' 5.2MB | MP4'
].join('\n')
assert.equal(parseSavedPath(stdout), '/tmp/fixture/downloads/张三 - 标题 - 730.mp4')
})
test('多条 ✅ 时取最后一个', () => {
const stdout = [' ✅ /tmp/one.mp4', ' ✅ /tmp/two.mp4', ' 1.0MB | MP4'].join('\n')
assert.equal(parseSavedPath(stdout), '/tmp/two.mp4')
})
test('从 JSON 下载结果同时提取作品元数据和保存路径', () => {
const parsed = parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","aweme_id":"730","saved":["/tmp/fixture-video.mp4"]}]'
)
assert.deepEqual(parsed, {
ok: true,
meta: {
url: 'https://v.douyin.com/fixture123',
ok: true,
type: 'video',
aweme_id: '730',
saved: ['/tmp/fixture-video.mp4']
},
path: '/tmp/fixture-video.mp4'
})
assert.equal(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","saved":["relative.mp4"]}]'
),
null
)
})
test('JSON 下载失败保留脚本错误,图集保持不支持状态', () => {
assert.deepEqual(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":false,"error":"fixture platform error"}]'
),
{ ok: false, message: 'fixture platform error', errorType: 'RESOLVE_FAILED' }
)
assert.deepEqual(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","images":[]}]'
),
{ ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
)
})
test('下载阶段失败时标记为下载错误', () => {
assert.deepEqual(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":false,"aweme_id":"730","error":"fixture CDN timeout"}]'
),
{ ok: false, message: 'fixture CDN timeout', errorType: 'DOWNLOAD_FAILED' }
)
})
test('图集目录后面的附注被剥离', () => {
const stdout = [' ✅ /tmp/fixture-folder (5 个文件)'].join('\n')
assert.equal(parseSavedPath(stdout), '/tmp/fixture-folder')
})
test('没有 ✅ 行时返回 null', () => {
assert.equal(parseSavedPath(' ✗ 失败:超时\n完成:0/1 成功'), null)
assert.equal(parseSavedPath(''), null)
})
test('模板替换三个已知变量', () => {
const caption = renderCaption('{author}:{title}({awemeId})', {
author: '张三',
title: '测试标题',
awemeId: '730'
})
assert.equal(caption, '张三:测试标题(730)')
})
test('未知变量原样保留', () => {
const caption = renderCaption('{author} {unknownVar}', { author: '张三' })
assert.equal(caption, '张三 {unknownVar}')
})
test('超长文案截断到 200 字', () => {
const caption = renderCaption('{title}', { title: '字'.repeat(400) })
assert.equal(caption.length, 200)
})
test('默认配置符合约定', () => {
const config = normalizeConfig(undefined)
assert.equal(config.configVersion, 1)
assert.equal(config.enabled, false)
assert.equal(config.pythonPath, 'python3')
assert.equal(config.scriptPath, 'scripts/douyin.py')
assert.equal(config.quality, '720')
assert.equal(config.showUi, false)
assert.equal(config.sendCaption, false)
assert.equal(config.captionTemplate, '{author}:{title}')
assert.equal(config.errorReply, true)
assert.equal(config.includeDirect, false)
assert.deepEqual(config.groups, [])
assert.equal(config.cooldownSeconds, 60)
assert.equal(config.maxFileMB, 100)
})
test('常规配置不接纳 Cookie 凭证字段', () => {
const config = normalizeConfig({ cookie: 'must-not-persist', cookieFile: '/tmp/fixture-cookie' })
assert.equal(Object.hasOwn(config, 'cookie'), false)
assert.equal(Object.hasOwn(config, 'cookieFile'), false)
})
test('非法画质收敛到 720,空串表示最高', () => {
assert.equal(normalizeConfig({ quality: '4k' }).quality, '720')
assert.equal(normalizeConfig({ quality: '' }).quality, '')
assert.equal(normalizeConfig({ quality: '1080' }).quality, '1080')
})
test('数值型画质按字符串处理', () => {
assert.equal(normalizeConfig({ quality: 540 }).quality, '540')
})
test('showUi 只接受布尔 true', () => {
assert.equal(normalizeConfig({ showUi: true }).showUi, true)
assert.equal(normalizeConfig({ showUi: 'true' }).showUi, false)
assert.equal(normalizeConfig({ showUi: 1 }).showUi, false)
})
test('ackText 默认有回执,空串表示关闭', () => {
assert.match(normalizeConfig({}).ackText, /收到/)
assert.equal(normalizeConfig({ ackText: '' }).ackText, '')
assert.equal(normalizeConfig({ ackText: ' 好的 ' }).ackText, '好的')
assert.equal(normalizeConfig({ ackText: 'x'.repeat(300) }).ackText.length, 200)
})
test('冷却与文件上限被夹到合法区间', () => {
assert.equal(normalizeConfig({ cooldownSeconds: -10 }).cooldownSeconds, 0)
assert.equal(normalizeConfig({ cooldownSeconds: 999999 }).cooldownSeconds, 3600)
assert.equal(normalizeConfig({ maxFileMB: 0 }).maxFileMB, 1)
assert.equal(normalizeConfig({ maxFileMB: 500 }).maxFileMB, 100)
})
test('群 id 去空、去重并截断上限', () => {
const config = normalizeConfig({
groups: [' fixture-room@chatroom ', '', 'fixture-room@chatroom']
})
assert.deepEqual(config.groups, ['fixture-room@chatroom'])
})
test('总开关关闭时拒绝处理', () => {
const decision = shouldHandle(makeEvent(), makeConfig({ enabled: false }), new Map(), Date.now())
assert.deepEqual(decision, { handle: false, url: null, reason: 'disabled' })
})
test('自己发的消息拒绝处理', () => {
const decision = shouldHandle(makeEvent({ isSelf: true }), makeConfig(), new Map(), Date.now())
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'self')
})
test('非 text 消息拒绝处理', () => {
const decision = shouldHandle(makeEvent({ type: 'image' }), makeConfig(), new Map(), Date.now())
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'type')
})
test('没有真正 @ 我时拒绝处理', () => {
const decision = shouldHandle(
makeEvent({ mentionsMe: false }),
makeConfig(),
new Map(),
Date.now()
)
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'mention')
})
test('消息里没有链接时拒绝处理', () => {
const decision = shouldHandle(
makeEvent({ text: '@李四 今天天气不错' }),
makeConfig(),
new Map(),
Date.now()
)
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'no_link')
})
test('群不在白名单里时拒绝处理,但仍返回提取到的链接', () => {
const decision = shouldHandle(
makeEvent(),
makeConfig({ groups: ['other-room@chatroom'] }),
new Map(),
Date.now()
)
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'scope')
assert.equal(decision.url, SHORT_URL)
})
test('群在白名单里时允许处理', () => {
const decision = shouldHandle(
makeEvent(),
makeConfig({ groups: ['fixture-room@chatroom'] }),
new Map(),
Date.now()
)
assert.deepEqual(decision, { handle: true, url: SHORT_URL, reason: 'ok' })
})
test('私聊默认不处理,开启后处理', () => {
const direct = makeEvent({ isGroup: false, conversationId: 'wxid_fixture' })
assert.equal(shouldHandle(direct, makeConfig(), new Map(), Date.now()).reason, 'scope')
assert.equal(
shouldHandle(direct, makeConfig({ includeDirect: true }), new Map(), Date.now()).reason,
'ok'
)
})
test('冷却未过期时拒绝,过期后放行', () => {
const now = 1_767_225_600_000
const cooldown = new Map([['fixture-room@chatroom', now + 30_000]])
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now).reason, 'cooldown')
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now + 30_001).reason, 'ok')
})
test('图集不算视频', () => {
const results = [
{ url: SHORT_URL, ok: true, type: 'image', aweme_id: '730' },
{ url: VIDEO_URL, ok: true, type: 'video', aweme_id: '731' }
]
assert.equal(pickVideoResult(results).aweme_id, '731')
assert.equal(pickVideoResult([results[0]]), null)
})
test('跳过失败项并容忍非数组输入', () => {
assert.equal(pickVideoResult([{ ok: false, error: '超时' }]), null)
assert.equal(pickVideoResult(null), null)
assert.equal(pickVideoResult([]), null)
})
test('文件大小判定覆盖上限与非法值', () => {
assert.equal(isFileTooLarge(100 * 1024 * 1024, 100), false)
assert.equal(isFileTooLarge(100 * 1024 * 1024 + 1, 100), true)
assert.equal(isFileTooLarge(2 * 1024 * 1024, 1), true)
assert.equal(isFileTooLarge(0, 100), true)
assert.equal(isFileTooLarge(Number.NaN, 100), true)
assert.equal(isFileTooLarge(1, 100), false)
})
test('DEFAULT_CONFIG 不被 normalizeConfig 修改', () => {
const before = JSON.stringify(DEFAULT_CONFIG)
const config = normalizeConfig({ enabled: true, groups: ['fixture-room@chatroom'] })
config.groups.push('wxid_fixture')
assert.equal(JSON.stringify(DEFAULT_CONFIG), before)
})
+620
View File
@@ -0,0 +1,620 @@
'use strict'
/**
* 扩展页面桥。
*
* 页面只能通过宿主白名单能力与宿主通信,
* 没有发送能力,也没有 `require`。
*/
const EXTENSION_ID = 'com.example.douyin-sender'
const PAGE_SOURCE = 'tracememo-extension-page'
const HOST_SOURCE = 'tracememo-extension-host'
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
const PROGRESS_KEY = 'progress'
const TEST_RESULT_KEY = 'testResult'
const ALLOWED_METHODS = new Set([
'storage.get',
'storage.set',
'storage.remove',
'storage.list',
'capabilities.get',
'contacts.listGroups',
'test.send',
'douyin.cookie.get',
'douyin.cookie.set',
'douyin.cookie.clear',
'extension.info'
])
const DEFAULT_CONFIG = {
configVersion: 1,
enabled: false,
pythonPath: 'python3',
scriptPath: 'scripts/douyin.py',
quality: '720',
showUi: false,
ackText: '收到,正在解析,请稍候…',
sendCaption: false,
captionTemplate: '{author}:{title}',
errorReply: true,
includeDirect: false,
groups: [],
cooldownSeconds: 60,
maxFileMB: 100
}
const STAGE_LABELS = {
accepted: '已接收',
resolve: '解析',
resolveDownload: '解析并下载',
download: '下载',
send: '发送',
caption: '补发文案',
done: '完成',
failed: '失败'
}
const pending = new Map()
let sequence = 0
let config = clone(DEFAULT_CONFIG)
function clone(value) {
return JSON.parse(JSON.stringify(value))
}
function callHost(method, params) {
return new Promise((resolve, reject) => {
if (!ALLOWED_METHODS.has(method)) {
reject(new Error(`不支持的调用:${method}`))
return
}
const requestId = `req-${++sequence}`
pending.set(requestId, { resolve, reject })
window.parent.postMessage(
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
'*'
)
})
}
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== HOST_SOURCE) return
const entry = pending.get(data.requestId)
if (!entry) return
pending.delete(data.requestId)
if (data.ok) entry.resolve(data.result)
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
})
const status = document.getElementById('status')
const rows = document.getElementById('job-rows')
const todayTotal = document.getElementById('today-total')
const todaySuccess = document.getElementById('today-success')
const todayFailure = document.getElementById('today-failure')
const progressBadge = document.getElementById('progress-badge')
const progressStage = document.getElementById('progress-stage')
const progressTime = document.getElementById('progress-time')
const progressDetail = document.getElementById('progress-detail')
const testGroup = document.getElementById('test-group')
const testUrl = document.getElementById('test-url')
const cookieHeader = document.getElementById('cookie-header')
const cookieState = document.getElementById('cookie-state')
const testResult = document.getElementById('test-result')
const groupPicker = document.getElementById('group-picker')
const groupChips = document.getElementById('group-chips')
const groupSearch = document.getElementById('group-search')
const groupOptions = document.getElementById('group-options')
let allGroups = []
let selectedGroupIds = new Set()
let groupLoadError = ''
function setStatus(text, kind) {
status.textContent = text
status.dataset.kind = kind || ''
}
function clampInt(value, fallback, min, max) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return fallback
return Math.max(min, Math.min(Math.trunc(numeric), max))
}
function normalizeConfig(raw) {
const input = raw && typeof raw === 'object' ? raw : {}
const quality = ['', '1080', '720', '540'].includes(String(input.quality))
? String(input.quality)
: DEFAULT_CONFIG.quality
return {
configVersion: 1,
enabled: input.enabled === true,
pythonPath: String(input.pythonPath || DEFAULT_CONFIG.pythonPath).trim(),
scriptPath: String(input.scriptPath || DEFAULT_CONFIG.scriptPath).trim(),
quality,
showUi: input.showUi === true,
ackText:
input.ackText === undefined
? DEFAULT_CONFIG.ackText
: String(input.ackText).trim().slice(0, 200),
sendCaption: false,
captionTemplate: String(input.captionTemplate || DEFAULT_CONFIG.captionTemplate).slice(0, 200),
errorReply: input.errorReply !== false,
includeDirect: input.includeDirect === true,
groups: Array.isArray(input.groups)
? input.groups
.map((id) => String(id).trim())
.filter(Boolean)
.slice(0, 200)
: [],
cooldownSeconds: clampInt(input.cooldownSeconds, DEFAULT_CONFIG.cooldownSeconds, 0, 3600),
maxFileMB: clampInt(input.maxFileMB, DEFAULT_CONFIG.maxFileMB, 1, 100)
}
}
function syncForm() {
document.getElementById('enabled').checked = config.enabled === true
document.getElementById('python-path').value = config.pythonPath
document.getElementById('script-path').value = config.scriptPath
document.getElementById('quality').value = config.quality
document.getElementById('show-ui').checked = config.showUi === true
document.getElementById('ack-text').value = config.ackText
document.getElementById('error-reply').checked = config.errorReply === true
selectedGroupIds = new Set(config.groups)
renderGroupChips()
renderGroupOptions()
document.getElementById('include-direct').checked = config.includeDirect === true
document.getElementById('cooldown').value = String(config.cooldownSeconds)
document.getElementById('max-file-mb').value = String(config.maxFileMB)
}
function readForm() {
config.enabled = document.getElementById('enabled').checked
config.pythonPath = document.getElementById('python-path').value.trim()
config.scriptPath = document.getElementById('script-path').value.trim()
config.quality = document.getElementById('quality').value
config.showUi = document.getElementById('show-ui').checked
config.ackText = document.getElementById('ack-text').value.trim().slice(0, 200)
config.sendCaption = false
config.errorReply = document.getElementById('error-reply').checked
config.groups = [...selectedGroupIds].slice(0, 200)
config.includeDirect = document.getElementById('include-direct').checked
config.cooldownSeconds = clampInt(
document.getElementById('cooldown').value,
DEFAULT_CONFIG.cooldownSeconds,
0,
3600
)
config.maxFileMB = clampInt(
document.getElementById('max-file-mb').value,
DEFAULT_CONFIG.maxFileMB,
1,
100
)
config.configVersion = 1
}
function formatTime(value) {
const numeric = Number(value)
if (!Number.isFinite(numeric) || numeric <= 0) return '—'
const date = new Date(numeric)
const pad = (part) => String(part).padStart(2, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
function renderStats(raw) {
const stats = raw && typeof raw === 'object' ? raw : {}
const jobs = Array.isArray(stats.lastJobs) ? stats.lastJobs.slice(0, 8) : []
const total = Math.max(0, Math.trunc(Number(stats.todayTotal ?? stats.todayCount) || 0))
todayTotal.textContent = String(total)
todaySuccess.textContent = String(Math.max(0, Math.trunc(Number(stats.todaySuccess) || 0)))
todayFailure.textContent = String(Math.max(0, Math.trunc(Number(stats.todayFailure) || 0)))
rows.textContent = ''
if (!jobs.length) {
const row = document.createElement('tr')
const cell = document.createElement('td')
cell.colSpan = 5
cell.className = 'empty'
cell.textContent = '暂无记录'
row.append(cell)
rows.append(row)
return
}
for (const job of jobs) {
const row = document.createElement('tr')
const time = document.createElement('td')
time.textContent = formatTime(job && job.at)
const id = document.createElement('td')
id.className = 'mono'
id.textContent = (job && job.awemeId) || '—'
const stage = document.createElement('td')
stage.textContent = STAGE_LABELS[job && job.stage] || (job && job.stage) || '—'
const result = document.createElement('td')
const ok = job && job.ok === true
result.textContent = ok ? '成功' : '失败'
result.className = ok ? 'ok' : 'fail'
const error = document.createElement('td')
error.className = 'mono'
error.textContent = (job && job.errorType) || '—'
row.append(time, id, stage, result, error)
rows.append(row)
}
}
/** 进度:运行中显示阶段与已用时间;失败显示失败阶段与错误码。 */
function renderProgress(raw) {
const progress = raw && typeof raw === 'object' ? raw : null
if (!progress || !progress.stage) {
progressBadge.textContent = '空闲'
progressBadge.dataset.status = 'idle'
progressStage.textContent = '暂无任务'
progressTime.textContent = ''
progressDetail.textContent = '触发后这里会显示解析、下载、发送进行到哪一步。'
return
}
const status =
progress.status === 'failed' ? 'failed' : progress.status === 'done' ? 'done' : 'running'
progressBadge.textContent = status === 'failed' ? '失败' : status === 'done' ? '完成' : '进行中'
progressBadge.dataset.status = status
progressStage.textContent =
status === 'failed'
? `失败于:${STAGE_LABELS[progress.stage] || progress.stage}`
: status === 'done'
? '已完成'
: `正在${STAGE_LABELS[progress.stage] || progress.stage}`
const startedAt = Number(progress.startedAt)
// 运行中用当前时间计算,脚本卡住时秒数也会继续走,不会看起来停在 0s。
const updatedAt = status === 'running' ? Date.now() : Number(progress.updatedAt) || Date.now()
const elapsed =
Number.isFinite(startedAt) && startedAt > 0
? Math.max(0, Math.round((updatedAt - startedAt) / 1000))
: null
progressTime.textContent = elapsed === null ? '' : `· ${elapsed}s`
const parts = []
if (progress.awemeId) parts.push(`作品 ${progress.awemeId}`)
if (status === 'failed' && progress.errorType) parts.push(`错误 ${progress.errorType}`)
if (status === 'failed' && progress.errorMessage) parts.push(progress.errorMessage)
if (status === 'done') parts.push('视频已发送')
progressDetail.textContent = parts.join(' · ') || ''
}
async function loadStats() {
try {
const stored = await callHost('storage.get', { key: STATS_KEY })
renderStats(stored)
} catch (error) {
renderStats(null)
setStatus(`统计读取失败:${error.message}`, 'error')
}
}
async function loadProgress() {
try {
const stored = await callHost('storage.get', { key: PROGRESS_KEY })
renderProgress(stored)
} catch {
renderProgress(null)
}
}
let testPollTimer = null
let activeTestId = ''
function setTestResult(text, kind) {
testResult.textContent = text
testResult.dataset.kind = kind || ''
}
function groupDisplayName(group) {
if (!group) return ''
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
}
function emptyGroupOption(text) {
const empty = document.createElement('div')
empty.className = 'group-option-empty'
empty.textContent = text
return empty
}
function renderGroupChips() {
groupChips.textContent = ''
groupChips.hidden = selectedGroupIds.size === 0
for (const id of selectedGroupIds) {
const group = allGroups.find((item) => item.id === id)
const chip = document.createElement('span')
chip.className = 'group-chip'
const name = document.createElement('span')
name.textContent = group ? group.name || id : id
name.title = id
const remove = document.createElement('button')
remove.type = 'button'
remove.className = 'group-chip-remove'
remove.textContent = '×'
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
remove.addEventListener('click', (event) => {
event.stopPropagation()
selectedGroupIds.delete(id)
renderGroupChips()
renderGroupOptions()
})
chip.append(name, remove)
groupChips.append(chip)
}
}
function renderGroupOptions() {
if (groupOptions.hidden) return
const query = groupSearch.value.trim().toLowerCase()
groupOptions.textContent = ''
if (groupLoadError) {
groupOptions.append(emptyGroupOption(groupLoadError))
return
}
if (!allGroups.length) {
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
return
}
const matches = allGroups.filter((group) => {
if (!query) return true
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
})
if (!matches.length) {
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
return
}
for (const group of matches.slice(0, 200)) {
const option = document.createElement('label')
option.className = 'group-option'
const checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.checked = selectedGroupIds.has(group.id)
checkbox.addEventListener('change', () => {
if (checkbox.checked) selectedGroupIds.add(group.id)
else selectedGroupIds.delete(group.id)
renderGroupChips()
})
const text = document.createElement('span')
text.textContent = groupDisplayName(group)
option.append(checkbox, text)
groupOptions.append(option)
}
}
function openGroupOptions() {
groupOptions.hidden = false
renderGroupOptions()
}
function closeGroupOptions() {
groupOptions.hidden = true
groupSearch.value = ''
}
groupSearch.addEventListener('focus', openGroupOptions)
groupSearch.addEventListener('input', openGroupOptions)
groupSearch.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeGroupOptions()
groupSearch.blur()
}
})
document.addEventListener('click', (event) => {
if (!groupPicker.contains(event.target)) closeGroupOptions()
})
/** 群列表来自宿主通讯录;数据库未连接时给出明确空态,而不是假装有选项。 */
async function loadGroups() {
const current = testGroup.value
try {
const result = await callHost('contacts.listGroups', {})
allGroups = result && Array.isArray(result.groups) ? result.groups : []
groupLoadError = ''
testGroup.textContent = ''
if (!allGroups.length) {
const option = document.createElement('option')
option.value = ''
option.textContent = '未读取到群列表(请先连接微信数据库)'
testGroup.append(option)
renderGroupChips()
renderGroupOptions()
return
}
const placeholder = document.createElement('option')
placeholder.value = ''
placeholder.textContent = '请选择群聊'
testGroup.append(placeholder)
for (const group of allGroups) {
const option = document.createElement('option')
option.value = group.id
option.textContent = groupDisplayName(group)
testGroup.append(option)
}
const saved = await callHost('storage.get', { key: 'testGroup' }).catch(() => null)
const target = current || (typeof saved === 'string' ? saved : '')
if (target && allGroups.some((group) => group.id === target)) testGroup.value = target
} catch (error) {
allGroups = []
groupLoadError = `群列表读取失败:${error.message}`
testGroup.textContent = ''
const option = document.createElement('option')
option.value = ''
option.textContent = groupLoadError
testGroup.append(option)
}
renderGroupChips()
renderGroupOptions()
}
/** 轮询后台写入的测试结果;只认本次请求的 id,避免串台。 */
async function pollTestResult() {
if (!activeTestId) return
window.clearTimeout(testPollTimer)
try {
const result = await callHost('storage.get', { key: TEST_RESULT_KEY })
if (result && result.id === activeTestId) {
if (result.status === 'running') {
setTestResult(result.message || '处理中…', 'running')
} else if (result.status === 'done') {
setTestResult(result.message || '测试发送完成', 'ok')
activeTestId = ''
return
} else if (result.status === 'failed') {
setTestResult(result.message || '测试发送失败', 'error')
activeTestId = ''
return
}
}
} catch {
// 单次读取失败继续重试。
}
testPollTimer = window.setTimeout(() => {
void pollTestResult()
}, 1500)
}
async function loadConfig() {
const stored = await callHost('storage.get', { key: CONFIG_KEY })
config = normalizeConfig(stored)
syncForm()
}
async function loadCookieState() {
try {
const result = await callHost('douyin.cookie.get', {})
cookieState.textContent =
result && result.configured ? '已保存 Cookie(内容不可回显)' : '未配置'
} catch {
cookieState.textContent = '安全存储不可用,无法读取状态'
}
}
void loadCookieState()
async function checkCapabilities() {
try {
const snapshot = await callHost('capabilities.get', {})
const send = snapshot && snapshot.send ? snapshot.send : null
if (!send || !send.canSendVideo) {
setStatus('当前环境未就绪:视频发送通道不可用,配置仍可保存。', 'error')
return true
}
} catch {
// 能力查询失败不阻塞配置编辑。
}
return false
}
testGroup.addEventListener('change', () => {
void callHost('storage.set', { key: 'testGroup', value: testGroup.value }).catch(() => undefined)
})
document.getElementById('test-refresh').addEventListener('click', () => {
void loadGroups()
})
document.getElementById('test-send').addEventListener('click', async () => {
const to = testGroup.value
const text = testUrl.value.trim()
if (!to) {
setTestResult('请先选择目标群聊。', 'error')
return
}
if (!text) {
setTestResult('请粘贴抖音分享链接或整段分享文案。', 'error')
return
}
activeTestId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
setTestResult('已提交,等待后台开始解析…', 'running')
try {
const submitted = callHost('test.send', {
id: activeTestId,
to,
text,
at: Date.now()
})
void pollTestResult()
await submitted
} catch (error) {
activeTestId = ''
setTestResult(`提交失败:${error.message}`, 'error')
}
})
document.getElementById('cookie-save').addEventListener('click', async () => {
const value = cookieHeader.value.trim()
if (!value) {
setStatus('请先粘贴抖音 Cookie。', 'error')
return
}
try {
await callHost('douyin.cookie.set', { cookieHeader: value })
cookieHeader.value = ''
await loadCookieState()
setStatus('Cookie 已安全保存。', 'ok')
} catch (error) {
setStatus(`Cookie 保存失败:${error.message}`, 'error')
}
})
document.getElementById('cookie-clear').addEventListener('click', async () => {
try {
await callHost('douyin.cookie.clear', {})
cookieHeader.value = ''
await loadCookieState()
setStatus('Cookie 已清除。', 'ok')
} catch (error) {
setStatus(`Cookie 清除失败:${error.message}`, 'error')
}
})
document.getElementById('save').addEventListener('click', async () => {
readForm()
if (!config.pythonPath) {
setStatus('Python 可执行文件不能为空。', 'error')
return
}
if (!config.scriptPath) {
setStatus('解析脚本路径不能为空。', 'error')
return
}
if (!config.captionTemplate.trim() && config.sendCaption) {
setStatus('已开启标题文案,模板不能为空。', 'error')
return
}
try {
await callHost('storage.set', { key: CONFIG_KEY, value: config })
setStatus('配置已保存,后台 1 秒内生效', 'ok')
} catch (error) {
setStatus(`保存失败:${error.message}`, 'error')
}
})
document.getElementById('reload').addEventListener('click', async () => {
try {
await loadConfig()
await loadStats()
await loadProgress()
setStatus('已重新读取配置。', 'ok')
} catch (error) {
setStatus(`读取失败:${error.message}`, 'error')
}
})
async function boot() {
await loadConfig()
await Promise.all([loadStats(), loadProgress(), loadGroups()])
const blocked = await checkCapabilities()
if (!blocked) setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
// 页面打开期间轮询进度,任务跑到哪一步不用猜;统计低频刷新即可。
window.setInterval(() => {
void loadProgress()
}, 2000)
window.setInterval(() => {
void loadStats()
}, 6000)
}
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
@@ -0,0 +1,192 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>抖音视频搬运</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main class="page">
<header class="page-header">
<div>
<h1>抖音视频搬运</h1>
<p>
被 @ 且消息里带抖音分享链接时,解析视频并发回原会话。本页只写配置,发送全部由后台经
TraceMemo Gateway 完成。
</p>
</div>
<label class="switch">
<input id="enabled" type="checkbox" />
<span>启用</span>
</label>
</header>
<section class="panel">
<h2>运行环境</h2>
<label class="field">
<span>Python 可执行文件</span>
<input id="python-path" type="text" placeholder="python3" />
</label>
<label class="field">
<span>解析脚本路径(默认相对于扩展目录,支持 <code>~</code>,首次运行会在缓存目录创建 venv)</span>
<input
id="script-path"
type="text"
placeholder="scripts/douyin.py"
/>
</label>
<label class="field">
<span>画质</span>
<select id="quality">
<option value="">最高</option>
<option value="1080">1080</option>
<option value="720">720</option>
<option value="540">540</option>
</select>
</label>
<label class="check">
<input id="show-ui" type="checkbox" />
<span>显示浏览器窗口(排障用;可观察作品页实际停留状态,不保证改变平台响应)</span>
</label>
</section>
<section class="panel">
<h2>抖音 Cookie</h2>
<label class="field">
<span>Cookie(安全加密保存;仅本机使用)</span>
<input
id="cookie-header"
type="password"
autocomplete="new-password"
spellcheck="false"
placeholder="粘贴抖音 Cookie header"
/>
</label>
<p id="cookie-state" class="muted">未配置</p>
<div class="row">
<button id="cookie-save" type="button" class="primary">保存 Cookie</button>
<button id="cookie-clear" type="button" class="ghost">清除 Cookie</button>
</div>
</section>
<section class="panel">
<h2>回复与文案</h2>
<label class="field">
<span>触发后先回复一句(留空表示不回复)</span>
<input id="ack-text" type="text" maxlength="200" placeholder="收到,正在解析,请稍候…" />
</label>
<label class="check"
><input id="error-reply" type="checkbox" /><span
>失败时在原会话回一条简短说明</span
></label
>
</section>
<section class="panel">
<h2>监听范围</h2>
<div class="field">
<span>只处理这些群(可多选、可搜索;留空表示全部群)</span>
<div id="group-picker" class="group-picker">
<div id="group-chips" class="group-chips" hidden></div>
<input
id="group-search"
type="text"
placeholder="搜索群聊名称或 id…"
autocomplete="off"
/>
<div id="group-options" class="group-options" hidden></div>
</div>
</div>
<div class="row">
<label class="check"
><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label
>
</div>
<div class="grid-2">
<label class="field">
<span>冷却秒数(0–3600,按会话计)</span>
<input id="cooldown" type="number" min="0" max="3600" step="1" />
</label>
<label class="field">
<span>文件大小上限(MB,1–100)</span>
<input id="max-file-mb" type="number" min="1" max="100" step="1" />
</label>
</div>
</section>
<section class="panel">
<h2>测试发送</h2>
<label class="field">
<span>目标群聊</span>
<select id="test-group">
<option value="">加载中…</option>
</select>
</label>
<label class="field">
<span>抖音分享链接或整段分享文案</span>
<textarea
id="test-url"
rows="3"
placeholder="https://v.douyin.com/xxxxxx/ 复制打开抖音…"
></textarea>
</label>
<div class="row">
<button id="test-send" type="button" class="primary">测试发送</button>
<button id="test-refresh" type="button" class="ghost">刷新群列表</button>
</div>
<p id="test-result" class="status">
选择群聊、粘贴链接后点「测试发送」,解析完成后视频会直接发到该群。已保存的 Cookie
自动用于测试。
</p>
</section>
<section class="panel">
<div class="panel-header">
<h2>当前任务</h2>
<span id="progress-badge" class="badge">空闲</span>
</div>
<p class="progress-line">
<strong id="progress-stage">暂无任务</strong>
<span id="progress-time" class="muted"></span>
</p>
<p id="progress-detail" class="muted">触发后这里会显示解析、下载、发送进行到哪一步。</p>
</section>
<section class="panel">
<div class="panel-header">
<h2>统计</h2>
<span class="muted"
>今日 总计 <strong id="today-total">0</strong> · 成功
<strong id="today-success">0</strong> · 失败 <strong id="today-failure">0</strong></span
>
</div>
<table class="stats">
<thead>
<tr>
<th>时间</th>
<th>作品 ID</th>
<th>阶段</th>
<th>结果</th>
<th>错误</th>
</tr>
</thead>
<tbody id="job-rows">
<tr>
<td colspan="5" class="empty">暂无记录</td>
</tr>
</tbody>
</table>
</section>
<footer class="page-footer">
<div class="row">
<button id="save" type="button" class="primary">保存配置</button>
<button id="reload" type="button" class="ghost">重新读取</button>
</div>
<p id="status" class="status" role="status"></p>
</footer>
</main>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,387 @@
:root {
color-scheme: light dark;
--bg: #f6f8f7;
--card: #ffffff;
--text: #1c2622;
--muted: #6b7a73;
--border: #dfe6e2;
--brand: #247a63;
--danger: #b4472f;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161c19;
--card: #1e2622;
--text: #eef4f1;
--muted: #9aaba3;
--border: #33403a;
--brand: #4bb894;
--danger: #e0735a;
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
sans-serif;
}
.page {
max-width: 720px;
margin: 0 auto;
padding: 26px 22px 40px;
display: flex;
flex-direction: column;
gap: 16px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
h1 {
margin: 0;
font-size: 19px;
}
h2 {
margin: 0;
font-size: 13px;
font-weight: 700;
}
header p {
margin: 8px 0 0;
max-width: 52ch;
color: var(--muted);
font-size: 12px;
line-height: 19px;
}
.panel {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--card);
}
.panel-header {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
}
.field > span {
color: var(--muted);
font-size: 11px;
}
input[type='text'],
input[type='number'],
select,
textarea {
width: 100%;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
}
textarea {
resize: vertical;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
}
.row {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.check,
.switch {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--muted);
}
.switch {
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text);
}
button {
padding: 6px 11px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
cursor: pointer;
}
button.primary {
border-color: transparent;
background: var(--brand);
color: #fff;
}
button.ghost:hover {
border-color: var(--brand);
}
.page-footer {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.status {
min-height: 18px;
margin: 0;
color: var(--muted);
font-size: 12px;
}
.status[data-kind='ok'] {
color: var(--brand);
}
.status[data-kind='error'] {
color: var(--danger);
}
.muted {
color: var(--muted);
font-size: 12px;
}
.muted strong {
color: var(--text);
font-size: 13px;
}
.stats {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.stats th {
padding: 6px 8px;
border-bottom: 1px solid var(--border);
color: var(--muted);
font-size: 11px;
font-weight: 600;
text-align: left;
}
.stats td {
padding: 6px 8px;
border-bottom: 1px solid var(--border);
}
.stats tr:last-child td {
border-bottom: 0;
}
.stats td.empty {
color: var(--muted);
text-align: center;
}
.stats .mono {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
.stats .ok {
color: var(--brand);
}
.stats .fail {
color: var(--danger);
}
code {
padding: 1px 4px;
border-radius: 4px;
background: var(--bg);
font-size: 11px;
}
/* 当前任务:状态徽标 + 一行阶段 + 一行细节。 */
.badge {
padding: 2px 8px;
border-radius: 999px;
background: var(--bg);
color: var(--muted);
font-size: 11px;
font-weight: 600;
}
.badge[data-status='running'] {
background: color-mix(in srgb, var(--brand) 14%, transparent);
color: var(--brand);
}
.badge[data-status='done'] {
background: color-mix(in srgb, var(--brand) 14%, transparent);
color: var(--brand);
}
.badge[data-status='failed'] {
background: color-mix(in srgb, var(--danger) 14%, transparent);
color: var(--danger);
}
.progress-line {
display: flex;
align-items: baseline;
gap: 8px;
margin: 0;
font-size: 13px;
}
.progress-line .muted {
font-size: 11px;
}
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
.group-picker {
position: relative;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
padding: 6px;
}
.group-picker:focus-within {
border-color: var(--brand);
}
.group-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-bottom: 4px;
}
.group-chip {
display: inline-flex;
align-items: center;
gap: 2px;
max-width: 100%;
padding: 2px 4px 2px 8px;
border-radius: 6px;
background: var(--bg);
font-size: 11px;
}
.group-chip > span {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-chip-remove {
border: 0;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 14px;
line-height: 1;
padding: 0 4px;
}
.group-chip-remove:hover {
color: var(--danger);
}
.group-picker > input[type='text'] {
width: 100%;
border: 0;
outline: 0;
background: transparent;
color: var(--text);
padding: 4px 2px;
font: inherit;
font-size: 12px;
}
.group-options {
position: absolute;
z-index: 30;
left: 0;
right: 0;
top: calc(100% + 4px);
max-height: 220px;
overflow: auto;
padding: 4px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
.group-option {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 6px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
}
.group-option:hover {
background: var(--bg);
}
.group-option input {
margin: 0;
}
.group-option-empty {
padding: 8px 6px;
color: var(--muted);
font-size: 11px;
}
+116
View File
@@ -0,0 +1,116 @@
# 关键词回复机器人
监听微信文本消息,按规则表匹配关键词,命中后经 TraceMemo Gateway 回复。
两条入口共用同一份配置与同一套判定(`lib/matcher.js`):
- `message.received` 事件:扩展自己判断范围与冷却,再调用 `tm.wechat.send`;
- 自动化动作 `keyword.reply`:只返回回复文本,不发送,发送由宿主的自动化流程完成。
扩展本身不碰 socket、dylib 或 HTTP,所有发送都经过宿主 Gateway 的权限、授权校验、限流与审计。
## 目录
```text
keyword-bot/
manifest.json 权限、订阅、页面与自动化动作声明
background/index.js 事件编排、冷却表、命中统计
lib/matcher.js 纯函数:规范化 / 匹配 / 范围 / 模板 / 决策
ui/ 配置页(沙箱 iframe,只调用 storage.* / capabilities.get / extension.info)
tests/matcher.test.mjs
```
## 功能
- 规则支持三种匹配方式:`contains`(包含)、`exact`(完全匹配)、`prefix`(以…开头),均不区分大小写;
- 每条规则可单独启用/停用,并设置优先级与冷却;
- 监听范围可按群限定,可开关私聊,可要求真正 @ 我;
- 回复内容支持模板变量;
- 配置页展示今日命中数与最近 5 条命中结果。
## 配置字段
顶层:
| 字段 | 类型 | 默认 | 说明 |
| ------------------------ | -------- | ------- | ----------------------------------------- |
| `configVersion` | number | `2` | 保存时写入;v1(无此字段)读取时自动迁移 |
| `enabled` | boolean | `false` | 总开关。缺省关闭,避免安装后立即对外发送 |
| `rules` | array | `[]` | 规则表,见下 |
| `scope.groups` | string[] | `[]` | 群 id(`xxx@chatroom`);空数组表示全部群 |
| `scope.includeDirect` | boolean | `true` | 是否处理私聊 |
| `scope.requireMentionMe` | boolean | `false` | 是否只处理真正 @ 登录账号的消息 |
规则:
| 字段 | 类型 | 默认 | 约束 |
| ----------------- | ------- | ------------- | ------------------------------------------- |
| `id` | string | `rule-<序号>` | ≤ 64 字符;冷却键的一部分,尽量稳定 |
| `keyword` | string | `''` | ≤ 120 字符;启用中为空的规则会被丢弃 |
| `mode` | string | `contains` | `contains` / `exact` / `prefix` |
| `reply` | string | `''` | ≤ 2000 字符;启用中为空的规则会被丢弃 |
| `cooldownSeconds` | number | `0` | 0–3600,取整到秒 |
| `enabled` | boolean | `true` | v1 规则迁移后为 `true`;显式 `false` 才停用 |
| `priority` | number | `0` | 0–100 整数,越大越先匹配 |
配置页保存时只校验**启用中**的规则必须有 `keyword` 与 `reply`;停用的规则允许留空,方便先存草稿。
## 模板变量
| 变量 | 含义 |
| ----------- | -------------------------------------------------------------------------- |
| `{sender}` | 发送者昵称;为空时渲染为「你」。自动化动作路径没有发送者上下文,恒为「你」 |
| `{keyword}` | 命中的关键词(规则里的原文) |
| `{time}` | 当前本地时间 `HH:mm` |
未知变量(例如 `{group}`)原样保留,不会被静默删除。渲染结果 trim 后截断到 2000 字符。
## 优先级与冷却语义
- 只考虑 `enabled !== false` 的规则;按 `priority` 降序排列,同优先级保持规则在数组中的顺序;
- 取**第一个**命中的规则,一条消息最多回复一次(stopOnMatch),不会叠加多条回复;
- 冷却键是 `conversationId:ruleId`,即「同一会话 + 同一条规则」各自独立计时;
- 冷却只在**发送成功后**写入:发送失败不占用冷却,下一条命中会立刻重试;
- 冷却表只存在内存里,扩展进程重启后清空——宁可多回一条,也不跨重启误拦。
## 统计口径与隐私边界
存储键 `stats`,结构:
```json
{
"dateKey": "2026-11-12",
"todayCount": 3,
"lastHits": [{ "at": 0, "ruleId": "rule-1", "ok": true }]
}
```
- 每条命中记一条,**成功和失败都记**;`todayCount` 统计的是命中的次数(含发送失败);
- `lastHits` 最多保留 20 条,配置页只展示最近 5 条;`at` 是 epoch 毫秒;
- 跨日后读取会把 `todayCount` 归零,`lastHits` 作为滚动历史保留;
- 只记录规则 id、时间与发送结果,**不记录会话 id、消息正文、发送者昵称或群名**;
- 统计写入失败只打 warn 日志,不影响回复;
- 统计只覆盖事件自动回复,不包含自动化动作 `keyword.reply` 的调用。
## 测试
零依赖,Node 内置测试运行器,不安装任何包:
```bash
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
node --check examples/extensions/keyword-bot/lib/matcher.js
node --check examples/extensions/keyword-bot/background/index.js
node --check examples/extensions/keyword-bot/ui/app.js
```
用例覆盖:三种匹配方式、大小写、空关键词、禁用规则、优先级与稳定性、群范围与私聊开关、@ 要求、自己发的消息、冷却中/过期、模板替换与未知变量、超长截断、v1 迁移、非法规则丢弃、数值越界收敛、决策顺序。
`tests/matcher.test.mjs` 中的 fixture 全部为占位数据(`张三`、`李四`、`测试群`、`fixture-room@chatroom`、`wxid_fixture`)。
## 已知限制
- 不回复自己发送的消息(`isSelf` 直接跳过);
- 消息事件是「至多一次」投递:扩展进程重启的瞬间可能丢事件,没有补投队列;
- 不读取群名,因此没有 `{group}` 变量;需要按群定制时请拆成多条规则并配合「监听范围」;
- 配置缓存窗口为 1 秒,保存后最多 1 秒生效;
- 冷却表与配置缓存都在扩展后台进程内存中,进程重启即丢失。
@@ -0,0 +1,221 @@
/**
* 关键词回复机器人。
*
* 两条入口共用同一份配置与 `lib/matcher.js` 的同一套判定:
* 1. `message.received` 事件 → 自己判断范围 / 冷却 → `tm.wechat.send`;
* 2. 自动化动作 `keyword.reply` → 只返回回复内容,由宿主 Gateway 发送。
*
* 发送**永远**经过宿主:本文件里没有任何 socket、dylib 或 HTTP 调用。
* 匹配/规范化逻辑全部在 `lib/matcher.js`,本文件只负责编排与统计。
*/
const { normalizeConfig, pickRule, renderReply, shouldReply } = require('../lib/matcher.js')
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
/** 配置缓存窗口:配置页保存后最多 1 秒生效,避免每条消息都读一次 storage。 */
const CONFIG_TTL_MS = 1000
/** 最近命中记录上限;只保留规则 id、时间与结果,不保留任何会话内容。 */
const STATS_HISTORY_LIMIT = 20
/** 冷却表清理阈值:超过后剔除已过期项,避免长期运行无限增长。 */
const COOLDOWN_PRUNE_SIZE = 500
let tm = null
let cachedConfig = null
let cachedAt = 0
let cachedStats = null
const cooldownUntil = new Map()
/** 统计写入串行化:并发消息不互相覆盖 `stats` 快照。 */
let statsChain = Promise.resolve()
function loadConfig() {
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return Promise.resolve(cachedConfig)
return Promise.resolve(tm.storage.get(CONFIG_KEY))
.then((stored) => {
cachedConfig = normalizeConfig(stored)
cachedAt = Date.now()
return cachedConfig
})
.catch((error) => {
tm.log.warn(`读取配置失败,本次按未启用处理:${describeError(error)}`)
// 读失败也要缓存一小段时间,避免每条消息都打一次失败日志。
cachedConfig = normalizeConfig(null)
cachedAt = Date.now()
return cachedConfig
})
}
/** 本地时区的 `YYYY-MM-DD`,用于判定「今日」。 */
function statsDateKey(timestamp) {
const date = new Date(timestamp)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${date.getFullYear()}-${month}-${day}`
}
/** 本地时区的 `HH:mm`,模板变量 `{time}` 与统计展示共用。 */
function formatClock(timestamp) {
const date = new Date(timestamp)
const hour = String(date.getHours()).padStart(2, '0')
const minute = String(date.getMinutes()).padStart(2, '0')
return `${hour}:${minute}`
}
function emptyStats(timestamp) {
return { dateKey: statsDateKey(timestamp), todayCount: 0, lastHits: [] }
}
/**
* 规范化统计快照。
*
* 跨日后 `todayCount` 归零;`lastHits` 作为滚动历史保留(它记的是「最近命中」,
* 不是「今日命中」)。任何字段缺失或类型不对都退化为空值,统计损坏不能影响回复。
*/
function normalizeStats(raw, timestamp) {
const base = emptyStats(timestamp)
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base
const lastHits = Array.isArray(raw.lastHits)
? raw.lastHits
.filter((hit) => hit && typeof hit === 'object')
.map((hit) => ({
at: Number(hit.at),
ruleId: String(hit.ruleId == null ? '' : hit.ruleId).slice(0, 64),
ok: hit.ok === true
}))
.filter((hit) => Number.isFinite(hit.at) && hit.at > 0 && hit.ruleId)
.slice(-STATS_HISTORY_LIMIT)
: []
const sameDay = raw.dateKey === base.dateKey
const count = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
return { dateKey: base.dateKey, todayCount: count, lastHits }
}
function loadStats() {
if (cachedStats) return Promise.resolve(cachedStats)
return Promise.resolve(tm.storage.get(STATS_KEY))
.then((stored) => {
cachedStats = normalizeStats(stored, Date.now())
return cachedStats
})
.catch(() => {
cachedStats = emptyStats(Date.now())
return cachedStats
})
}
/**
* 追加一条命中记录并落库。
*
* 成功与失败都记;只写 `ruleId` / `at` / `ok`,绝不写会话 id、正文或昵称。
* 写失败只 warn:统计是旁路,不能因为 storage 异常把回复一起吞掉。
*/
function recordHit(ruleId, ok) {
statsChain = statsChain
.then(async () => {
const stats = await loadStats()
const now = Date.now()
const dateKey = statsDateKey(now)
if (stats.dateKey !== dateKey) {
stats.dateKey = dateKey
stats.todayCount = 0
}
stats.todayCount += 1
stats.lastHits = stats.lastHits
.concat({ at: now, ruleId: String(ruleId || '').slice(0, 64), ok: ok === true })
.slice(-STATS_HISTORY_LIMIT)
await tm.storage.set(STATS_KEY, stats)
})
.catch((error) => {
tm.log.warn(`命中统计写入失败:${describeError(error)}`)
})
return statsChain
}
/** 冷却只在真正发送成功后写入;发送失败不占冷却,下一条可以立刻重试。 */
function markCooldown(conversationId, rule, timestamp) {
const seconds = Number(rule.cooldownSeconds) || 0
cooldownUntil.set(`${conversationId}:${rule.id}`, timestamp + seconds * 1000)
if (cooldownUntil.size > COOLDOWN_PRUNE_SIZE) {
for (const [key, until] of cooldownUntil) {
if (until <= timestamp) cooldownUntil.delete(key)
}
}
}
function describeError(error) {
return error && error.message ? error.message : String(error)
}
async function onMessage(event) {
try {
const config = await loadConfig()
const now = Date.now()
const verdict = shouldReply(event, config, cooldownUntil, now)
if (!verdict.reply || !verdict.rule) return
const rule = verdict.rule
const text = renderReply(rule.reply, {
senderName: event.senderName,
keyword: rule.keyword,
time: formatClock(now)
})
try {
await tm.wechat.send({
to: event.conversationId,
text,
// 同一条微信消息在补投/重启后 eventId 不变,交给 Gateway 幂等短路。
dedupeKey: event.eventId
})
} catch (error) {
await recordHit(rule.id, false)
throw error
}
markCooldown(event.conversationId, rule, Date.now())
await recordHit(rule.id, true)
tm.log.info(`关键词命中,已发送回复(规则 ${rule.id})`)
} catch (error) {
tm.log.error(`自动回复失败:${describeError(error)}`)
}
}
module.exports = function activate(api) {
tm = api
tm.events.on('message.received', onMessage)
tm.automation.registerAction({
id: 'keyword.reply',
title: '关键词回复',
description: '按机器人配置匹配关键词并返回回复内容',
inputSchema: {
type: 'object',
properties: { text: { type: 'string' } },
required: ['text']
},
async handler(input) {
const config = await loadConfig()
if (!config.enabled) {
return { success: false, error: '机器人未启用' }
}
const rule = pickRule(input.text, config)
if (!rule) {
return { success: true, output: { matched: false } }
}
return {
success: true,
output: { matched: true, ruleId: rule.id },
// 动作路径没有发送者上下文,`{sender}` 会渲染成「你」。
reply: {
type: 'text',
text: renderReply(rule.reply, {
keyword: rule.keyword,
time: formatClock(Date.now())
})
}
}
}
})
tm.log.info('关键词回复机器人已加载')
}
@@ -0,0 +1,213 @@
'use strict'
/**
* 关键词回复的纯函数层:配置规范化、匹配、范围判定、模板渲染、决策。
*
* 契约:
* - 全部函数无副作用、不读写 storage、不打印日志,便于单测与后台进程复用;
* - 输入一律容忍 `undefined` / 错误类型,坏配置退化为「不回复」而不是抛错;
* - `enabled` 在任何一层都是硬开关:配置损坏时不能自动对外发送。
*/
/** 当前配置结构版本。v1 没有该字段,读取时按 v1 迁移。 */
const CONFIG_VERSION = 2
/** 与 UI、宿主动作输出保持一致的长度上限(字符)。 */
const MAX_RULE_ID_LENGTH = 64
const MAX_KEYWORD_LENGTH = 120
const MAX_REPLY_LENGTH = 2000
const MAX_GROUPS = 200
const MODES = new Set(['contains', 'exact', 'prefix'])
/**
* 把任意来源的配置规范化为 `configVersion: 2`。
*
* 启用中的空规则丢弃,停用的空规则保留为草稿;顶层 `enabled` 缺省 `false`,
* 配置缺失或损坏时宁可静默,也不能自动群发。
*
* @param {unknown} raw storage 里读出的原始值
*/
function normalizeConfig(raw) {
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
const sourceRules = Array.isArray(input.rules) ? input.rules : []
const rules = sourceRules
.filter((rule) => rule && typeof rule === 'object' && !Array.isArray(rule))
.map((rule, index) => ({
id: String(rule.id || `rule-${index + 1}`).slice(0, MAX_RULE_ID_LENGTH),
keyword: String(rule.keyword == null ? '' : rule.keyword).slice(0, MAX_KEYWORD_LENGTH),
mode: MODES.has(rule.mode) ? rule.mode : 'contains',
reply: String(rule.reply == null ? '' : rule.reply).slice(0, MAX_REPLY_LENGTH),
cooldownSeconds: clampNumber(rule.cooldownSeconds, 0, 3600),
// v1 规则没有该字段;只有显式 false 才算禁用。
enabled: rule.enabled !== false,
priority: clampNumber(rule.priority, 0, 100)
}))
.filter((rule) => rule.enabled === false || (rule.keyword.trim() && rule.reply.trim()))
const scope = input.scope && typeof input.scope === 'object' ? input.scope : {}
return {
configVersion: CONFIG_VERSION,
enabled: input.enabled === true,
rules,
scope: {
groups: Array.isArray(scope.groups)
? scope.groups
.map((id) => String(id == null ? '' : id).trim())
.filter(Boolean)
.slice(0, MAX_GROUPS)
: [],
includeDirect: scope.includeDirect !== false,
requireMentionMe: scope.requireMentionMe === true
}
}
}
/**
* 单条规则是否命中文本:大小写不敏感;`exact` / `prefix` 先 trim,
* `contains` 只 trim 关键词;空关键词恒为 false。
*
* @param {unknown} text 消息正文
* @param {{ keyword?: unknown, mode?: unknown }} rule
* @returns {boolean}
*/
function matchRule(text, rule) {
const keyword = String((rule && rule.keyword) == null ? '' : rule.keyword)
.trim()
.toLowerCase()
if (!keyword) return false
const haystack = String(text == null ? '' : text).toLowerCase()
const mode = rule && MODES.has(rule.mode) ? rule.mode : 'contains'
if (mode === 'exact') return haystack.trim() === keyword
if (mode === 'prefix') return haystack.trim().startsWith(keyword)
return haystack.includes(keyword)
}
/**
* 选出唯一命中的规则:`priority` 降序、同优先级保持数组顺序,取第一个命中。
*
* 这就是 stopOnMatch 语义:一条消息最多回复一次,命中即停。
* 禁用规则(`enabled === false`)不参与匹配。
*
* @param {unknown} text
* @param {object} config normalizeConfig 的产物
*/
function pickRule(text, config) {
const rules = config && Array.isArray(config.rules) ? config.rules : []
const candidates = rules
.map((rule, index) => ({ rule, index }))
.filter((item) => item.rule && item.rule.enabled !== false)
// 显式带下标排序,避免依赖引擎排序稳定性。
.sort((a, b) => (b.rule.priority || 0) - (a.rule.priority || 0) || a.index - b.index)
for (const item of candidates) {
if (matchRule(text, item.rule)) return item.rule
}
return null
}
/**
* 会话是否在生效范围内。
*
* - 群聊:`groups` 为空表示全部群;非空时必须包含 `event.conversationId`;
* - 私聊:只看 `includeDirect`。
*
* 范围在规则匹配之前判定:范围外的会话连匹配都不做,避免误触统计。
*/
function inScope(event, config) {
const scope = (config && config.scope) || {}
if (event && event.isGroup) {
const groups = Array.isArray(scope.groups) ? scope.groups : []
return groups.length === 0 || groups.includes(event.conversationId)
}
return scope.includeDirect !== false
}
/**
* 渲染回复模板。
*
* 支持 `{sender}`(发送者昵称,空则「你」)、`{keyword}`(命中关键词)、
* `{time}`(调用方给的本地时间字符串,缺省空串)。未知 `{xxx}` 原样保留,
* 方便用户在模板里写其它占位而不是被静默吃掉。结果 trim 后截断到 2000 字符。
*/
function renderReply(template, ctx) {
const source = String(template == null ? '' : template)
const context = ctx && typeof ctx === 'object' ? ctx : {}
const sender = String(context.senderName == null ? '' : context.senderName).trim() || '你'
const keyword = String(context.keyword == null ? '' : context.keyword)
const time = String(context.time == null ? '' : context.time)
const rendered = source.replace(/\{(sender|keyword|time)\}/g, (match, token) => {
if (token === 'sender') return sender
if (token === 'keyword') return keyword
if (token === 'time') return time
return match
})
return rendered.trim().slice(0, MAX_REPLY_LENGTH)
}
/**
* 综合决策:是否回复、用哪条规则、为什么。
*
* `reason` 取值固定,可直接用于日志/统计口径:
* `disabled` | `self` | `type` | `scope` | `mention` | `no_match` | `cooldown` | `ok`。
*
* 判断顺序固定为:总开关 → 自己发的 → 消息类型 → 会话范围 → @ 要求 → 规则匹配 → 冷却。
* 冷却键为 `conversationId:ruleId`,值为到期时间戳(epoch 毫秒),`now < until` 即冷却中。
* 冷却表允许是 `Map` 或普通对象,后台进程重启后自然清空(宁可多回一条,也不跨重启误拦)。
*
* @param {object} event 宿主的 message.received 事件
* @param {object} config normalizeConfig 的产物
* @param {Map<string, number>|Record<string, number>} [cooldownUntil]
* @param {number} [now] epoch 毫秒,缺省取当前时间
*/
function shouldReply(event, config, cooldownUntil, now) {
if (!config || config.enabled !== true) {
return { reply: false, rule: null, reason: 'disabled' }
}
if (!event || event.isSelf === true) {
return { reply: false, rule: null, reason: 'self' }
}
if (event.type !== 'text') {
return { reply: false, rule: null, reason: 'type' }
}
if (!inScope(event, config)) {
return { reply: false, rule: null, reason: 'scope' }
}
if (config.scope && config.scope.requireMentionMe === true && event.mentionsMe !== true) {
return { reply: false, rule: null, reason: 'mention' }
}
const rule = pickRule(event.text, config)
if (!rule) {
return { reply: false, rule: null, reason: 'no_match' }
}
const currentTime = Number.isFinite(now) ? now : Date.now()
const key = `${event.conversationId}:${rule.id}`
if (currentTime < readCooldown(cooldownUntil, key)) {
return { reply: false, rule: null, reason: 'cooldown' }
}
return { reply: true, rule, reason: 'ok' }
}
/** 冷却表读取:兼容 Map 与普通对象,缺失值按 0(永不冷却)。 */
function readCooldown(table, key) {
if (!table) return 0
const value = table instanceof Map ? table.get(key) : table[key]
const until = Number(value)
return Number.isFinite(until) ? until : 0
}
/** 收敛到 [min, max] 的整数;非数字 / NaN 一律当 0。 */
function clampNumber(value, min, max) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return 0
return Math.min(Math.max(Math.round(numeric), min), max)
}
module.exports = {
CONFIG_VERSION,
normalizeConfig,
matchRule,
pickRule,
inScope,
renderReply,
shouldReply
}
@@ -0,0 +1,42 @@
{
"manifestVersion": 1,
"id": "com.example.keyword-bot",
"name": "关键词回复机器人",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。",
"author": "TraceMemo Examples",
"permissions": [
"messages.subscribe",
"contacts.list",
"wechat.send.text",
"storage",
"automation.action"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": ["text"],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
},
"contributions": {
"pages": [
{
"id": "settings",
"title": "机器人配置"
}
],
"automationActions": [
{
"id": "keyword.reply",
"title": "关键词回复",
"description": "按机器人配置匹配关键词并返回回复内容"
}
]
}
}
@@ -0,0 +1,279 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import matcher from '../lib/matcher.js'
const { normalizeConfig, matchRule, pickRule, inScope, renderReply, shouldReply } = matcher
const GROUP_ID = 'fixture-room@chatroom'
const NOW = 1_700_000_000_000
/** 构造一份启用状态下的最小配置,参数按需覆盖。 */
function buildConfig(overrides = {}) {
return normalizeConfig({
enabled: true,
rules: [{ id: 'rule-1', keyword: '关键词', mode: 'contains', reply: '默认回复' }],
scope: { groups: [], includeDirect: true, requireMentionMe: false },
...overrides
})
}
/** 构造一条群聊文本消息事件。 */
function buildEvent(overrides = {}) {
return {
eventId: 'event-fixture-1',
accountId: 'account-fixture',
conversationId: GROUP_ID,
messageId: 'message-fixture-1',
senderId: 'wxid_fixture',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text',
text: '你好,关键词',
mentionsMe: false,
timestamp: NOW,
...overrides
}
}
test('exact 模式比较 trim 后的完整文本', () => {
const rule = { keyword: '关键词', mode: 'exact' }
assert.equal(matchRule(' 关键词 ', rule), true)
assert.equal(matchRule('你好,关键词', rule), false)
})
test('exact 模式不匹配大小写不同的关键词之外的差异', () => {
const rule = { keyword: 'Hello', mode: 'exact' }
assert.equal(matchRule('hello', rule), true)
assert.equal(matchRule('hello world', rule), false)
})
test('contains 模式匹配任意位置的子串', () => {
const rule = { keyword: '关键词', mode: 'contains' }
assert.equal(matchRule('前面的关键词后面', rule), true)
assert.equal(matchRule('完全无关', rule), false)
})
test('prefix 模式只匹配开头', () => {
const rule = { keyword: '你好', mode: 'prefix' }
assert.equal(matchRule(' 你好世界', rule), true)
assert.equal(matchRule('世界你好', rule), false)
})
test('匹配对大小写不敏感', () => {
assert.equal(matchRule('Say HELLO now', { keyword: 'hello', mode: 'contains' }), true)
assert.equal(matchRule('HELLO WORLD', { keyword: 'hello', mode: 'prefix' }), true)
})
test('空关键词在任何模式下都不命中', () => {
for (const mode of ['contains', 'exact', 'prefix']) {
assert.equal(matchRule('任意文本', { keyword: ' ', mode }), false)
assert.equal(matchRule('', { keyword: '', mode }), false)
}
})
test('pickRule 跳过禁用规则', () => {
const config = buildConfig({
rules: [
{ id: 'disabled', keyword: '关键词', reply: '不会发送', enabled: false },
{ id: 'active', keyword: '关键词', reply: '会发送' }
]
})
const rule = pickRule('关键词', config)
assert.equal(rule.id, 'active')
})
test('pickRule 按 priority 降序选择', () => {
const config = buildConfig({
rules: [
{ id: 'low', keyword: '关键词', reply: '低', priority: 10 },
{ id: 'high', keyword: '关键词', reply: '高', priority: 90 }
]
})
assert.equal(pickRule('关键词', config).id, 'high')
})
test('同优先级保持数组顺序(先定义先命中)', () => {
const config = buildConfig({
rules: [
{ id: 'first', keyword: '关键词', reply: '一', priority: 50 },
{ id: 'second', keyword: '关键词', reply: '二', priority: 50 }
]
})
assert.equal(pickRule('关键词', config).id, 'first')
})
test('同一条消息只返回一个规则(stopOnMatch)', () => {
const config = buildConfig({
rules: [
{ id: 'a', keyword: '关键词', reply: '一', priority: 1 },
{ id: 'b', keyword: '关键词', reply: '二', priority: 2 }
]
})
const rule = pickRule('关键词 关键词', config)
assert.equal(rule.id, 'b')
})
test('群范围命中指定群', () => {
const config = buildConfig({ scope: { groups: [GROUP_ID] } })
assert.equal(inScope(buildEvent(), config), true)
})
test('群范围排除未列出的群', () => {
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
assert.equal(inScope(buildEvent(), config), false)
})
test('groups 为空表示全部群聊', () => {
const config = buildConfig({ scope: { groups: [] } })
assert.equal(inScope(buildEvent(), config), true)
})
test('includeDirect 为 false 时不处理私聊', () => {
const closed = buildConfig({ scope: { groups: [], includeDirect: false } })
const open = buildConfig({ scope: { groups: [], includeDirect: true } })
const direct = buildEvent({ isGroup: false, conversationId: 'wxid_fixture' })
assert.equal(inScope(direct, closed), false)
assert.equal(inScope(direct, open), true)
})
test('requireMentionMe 只放行真正 @ 我的消息', () => {
const config = buildConfig({ scope: { groups: [], requireMentionMe: true } })
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'mention')
assert.equal(shouldReply(buildEvent({ mentionsMe: true }), config, new Map(), NOW).reason, 'ok')
})
test('自己发的消息不回复', () => {
const verdict = shouldReply(buildEvent({ isSelf: true }), buildConfig(), new Map(), NOW)
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'self' })
})
test('非文本消息不回复', () => {
const verdict = shouldReply(buildEvent({ type: 'image' }), buildConfig(), new Map(), NOW)
assert.equal(verdict.reason, 'type')
})
test('总开关关闭时不回复', () => {
const config = buildConfig({ enabled: false })
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'disabled')
assert.equal(shouldReply(buildEvent(), null, new Map(), NOW).reason, 'disabled')
})
test('没有命中规则时 reason 为 no_match', () => {
const verdict = shouldReply(buildEvent({ text: '无关内容' }), buildConfig(), new Map(), NOW)
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'no_match' })
})
test('冷却中不回复', () => {
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW + 30_000]])
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'cooldown' })
})
test('冷却过期后恢复回复', () => {
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW]])
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
assert.equal(verdict.reply, true)
assert.equal(verdict.reason, 'ok')
assert.equal(verdict.rule.id, 'rule-1')
})
test('冷却表也支持普通对象', () => {
const cooldown = { [`${GROUP_ID}:rule-1`]: NOW + 1 }
assert.equal(shouldReply(buildEvent(), buildConfig(), cooldown, NOW).reason, 'cooldown')
assert.equal(shouldReply(buildEvent(), buildConfig(), {}, NOW).reason, 'ok')
})
test('模板变量按上下文替换', () => {
const text = renderReply('{sender} 说了 {keyword},现在是 {time}', {
senderName: '张三',
keyword: '关键词',
time: '09:05'
})
assert.equal(text, '张三 说了 关键词,现在是 09:05')
})
test('发送者昵称为空时渲染为「你」', () => {
assert.equal(renderReply('{sender}', { senderName: ' ' }), '你')
assert.equal(renderReply('{sender}', {}), '你')
})
test('未知变量原样保留', () => {
const text = renderReply('{sender} 和 {group}', { senderName: '李四' })
assert.equal(text, '李四 和 {group}')
})
test('模板缺失的时间变量渲染为空串', () => {
assert.equal(renderReply('[{time}]', {}), '[]')
})
test('渲染结果 trim 后截断到 2000 字符', () => {
const input = ` ${'长'.repeat(2100)} `
const text = renderReply(input, {})
assert.equal(text.length, 2000)
assert.equal(text, '长'.repeat(2000))
})
test('v1 配置迁移补齐 enabled / priority 与 configVersion', () => {
const config = normalizeConfig({
enabled: true,
rules: [{ id: 'old', keyword: '关键词', mode: 'contains', reply: '旧规则' }],
scope: { groups: ['fixture-room@chatroom'] }
})
assert.equal(config.configVersion, 2)
assert.equal(config.rules.length, 1)
assert.equal(config.rules[0].enabled, true)
assert.equal(config.rules[0].priority, 0)
assert.equal(config.scope.includeDirect, true)
assert.equal(config.scope.requireMentionMe, false)
})
test('keyword 或 reply 为空的启用规则被丢弃,停用草稿保留', () => {
const config = normalizeConfig({
enabled: true,
rules: [
{ id: 'no-keyword', keyword: ' ', reply: '有回复' },
{ id: 'no-reply', keyword: '有词', reply: ' ' },
{ id: 'draft', keyword: '', reply: '', enabled: false },
{ id: 'ok', keyword: '有词', reply: '有回复' }
]
})
assert.deepEqual(
config.rules.map((rule) => rule.id),
['draft', 'ok']
)
})
test('非对象与缺失字段的配置退化为未启用空配置', () => {
for (const raw of [null, undefined, 'broken', 42, []]) {
const config = normalizeConfig(raw)
assert.equal(config.configVersion, 2)
assert.equal(config.enabled, false)
assert.deepEqual(config.rules, [])
assert.deepEqual(config.scope, { groups: [], includeDirect: true, requireMentionMe: false })
}
})
test('越界数值收敛到边界,非法值按 0', () => {
const config = normalizeConfig({
rules: [
{ id: 'clamp-high', keyword: '一', reply: '一', cooldownSeconds: 99_999, priority: 999 },
{ id: 'clamp-low', keyword: '二', reply: '二', cooldownSeconds: -5, priority: -5 },
{ id: 'nan', keyword: '三', reply: '三', cooldownSeconds: 'oops', priority: 'oops' }
]
})
assert.equal(config.rules[0].cooldownSeconds, 3600)
assert.equal(config.rules[0].priority, 100)
assert.equal(config.rules[1].cooldownSeconds, 0)
assert.equal(config.rules[1].priority, 0)
assert.equal(config.rules[2].cooldownSeconds, 0)
assert.equal(config.rules[2].priority, 0)
})
test('群范围过滤先于规则匹配,范围外不产生命中', () => {
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
const verdict = shouldReply(buildEvent(), config, new Map(), NOW)
assert.equal(verdict.reason, 'scope')
assert.equal(verdict.rule, null)
})
+495
View File
@@ -0,0 +1,495 @@
const EXTENSION_ID = 'com.example.keyword-bot'
const PAGE_SOURCE = 'tracememo-extension-page'
const HOST_SOURCE = 'tracememo-extension-host'
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
const CONFIG_VERSION = 2
const MAX_KEYWORD_LENGTH = 120
const MAX_REPLY_LENGTH = 2000
const STATS_PREVIEW = 5
const DEFAULT_CONFIG = {
configVersion: CONFIG_VERSION,
enabled: false,
rules: [
{
id: 'rule-1',
keyword: '你好',
mode: 'contains',
reply: '你好呀,{sender}!',
cooldownSeconds: 30,
enabled: true,
priority: 0
}
],
scope: { groups: [], includeDirect: true, requireMentionMe: false }
}
const pending = new Map()
let sequence = 0
let config = clone(DEFAULT_CONFIG)
function clone(value) {
return JSON.parse(JSON.stringify(value))
}
function callHost(method, params) {
return new Promise((resolve, reject) => {
const requestId = `req-${++sequence}`
pending.set(requestId, { resolve, reject })
window.parent.postMessage(
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
'*'
)
})
}
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== HOST_SOURCE) return
const entry = pending.get(data.requestId)
if (!entry) return
pending.delete(data.requestId)
if (data.ok) entry.resolve(data.result)
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
})
const rulesContainer = document.getElementById('rules')
const status = document.getElementById('status')
const statsSummary = document.getElementById('stats-summary')
const statsList = document.getElementById('stats-list')
const groupPicker = document.getElementById('group-picker')
const groupChips = document.getElementById('group-chips')
const groupSearch = document.getElementById('group-search')
const groupOptions = document.getElementById('group-options')
let allGroups = []
let selectedGroupIds = new Set()
let groupLoadError = ''
function groupDisplayName(group) {
if (!group) return ''
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
}
function renderGroupChips() {
groupChips.textContent = ''
groupChips.hidden = selectedGroupIds.size === 0
for (const id of selectedGroupIds) {
const group = allGroups.find((item) => item.id === id)
const chip = document.createElement('span')
chip.className = 'group-chip'
const name = document.createElement('span')
name.textContent = group ? group.name || id : id
name.title = id
const remove = document.createElement('button')
remove.type = 'button'
remove.className = 'group-chip-remove'
remove.textContent = '×'
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
remove.addEventListener('click', (event) => {
event.stopPropagation()
selectedGroupIds.delete(id)
renderGroupChips()
renderGroupOptions()
})
chip.append(name, remove)
groupChips.append(chip)
}
}
function renderGroupOptions() {
if (groupOptions.hidden) return
const query = groupSearch.value.trim().toLowerCase()
groupOptions.textContent = ''
if (groupLoadError) {
groupOptions.append(emptyGroupOption(groupLoadError))
return
}
if (!allGroups.length) {
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
return
}
const matches = allGroups.filter((group) => {
if (!query) return true
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
})
if (!matches.length) {
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
return
}
for (const group of matches.slice(0, 200)) {
const option = document.createElement('label')
option.className = 'group-option'
const checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.checked = selectedGroupIds.has(group.id)
checkbox.addEventListener('change', () => {
if (checkbox.checked) selectedGroupIds.add(group.id)
else selectedGroupIds.delete(group.id)
renderGroupChips()
})
const text = document.createElement('span')
text.textContent = groupDisplayName(group)
option.append(checkbox, text)
groupOptions.append(option)
}
}
function emptyGroupOption(text) {
const empty = document.createElement('div')
empty.className = 'group-option-empty'
empty.textContent = text
return empty
}
function openGroupOptions() {
groupOptions.hidden = false
renderGroupOptions()
}
function closeGroupOptions() {
groupOptions.hidden = true
groupSearch.value = ''
}
groupSearch.addEventListener('focus', openGroupOptions)
groupSearch.addEventListener('input', openGroupOptions)
groupSearch.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeGroupOptions()
groupSearch.blur()
}
})
document.addEventListener('click', (event) => {
if (!groupPicker.contains(event.target)) closeGroupOptions()
})
async function loadGroups() {
try {
const result = await callHost('contacts.listGroups', {})
allGroups = result && Array.isArray(result.groups) ? result.groups : []
groupLoadError = ''
} catch (error) {
allGroups = []
groupLoadError = `群列表读取失败:${error.message}`
}
renderGroupChips()
renderGroupOptions()
}
function setStatus(text, kind) {
status.textContent = text
status.dataset.kind = kind || ''
}
function clampInteger(value, min, max, fallback) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return fallback
return Math.min(Math.max(Math.round(numeric), min), max)
}
function newRuleId() {
return `rule-${Date.now().toString(36)}`
}
/**
* 页面侧的轻量规范化:只用于展示与回写,真正的判定在后台 lib/matcher.js。
* 缺字段一律补默认值,保证 v1 配置打开后能直接编辑。
*/
function normalizeRule(rule, index) {
const source = rule && typeof rule === 'object' ? rule : {}
return {
id: String(source.id || `rule-${index + 1}`).slice(0, 64),
keyword: String(source.keyword == null ? '' : source.keyword).slice(0, MAX_KEYWORD_LENGTH),
mode: ['contains', 'exact', 'prefix'].includes(source.mode) ? source.mode : 'contains',
reply: String(source.reply == null ? '' : source.reply).slice(0, MAX_REPLY_LENGTH),
cooldownSeconds: clampInteger(source.cooldownSeconds, 0, 3600, 0),
enabled: source.enabled !== false,
priority: clampInteger(source.priority, 0, 100, 0)
}
}
function normalizeStoredConfig(stored) {
if (!stored || typeof stored !== 'object') return clone(DEFAULT_CONFIG)
const scope = stored.scope && typeof stored.scope === 'object' ? stored.scope : {}
return {
configVersion: CONFIG_VERSION,
enabled: stored.enabled === true,
rules: Array.isArray(stored.rules)
? stored.rules.map(normalizeRule)
: clone(DEFAULT_CONFIG.rules),
scope: {
groups: Array.isArray(scope.groups)
? scope.groups.map((id) => String(id).trim()).filter(Boolean)
: [],
includeDirect: scope.includeDirect !== false,
requireMentionMe: scope.requireMentionMe === true
}
}
}
function field(label, control) {
const wrapper = document.createElement('label')
wrapper.className = 'field'
const caption = document.createElement('span')
caption.textContent = label
wrapper.append(caption, control)
return wrapper
}
function renderRules() {
rulesContainer.textContent = ''
config.rules.forEach((rule, index) => {
const card = document.createElement('article')
card.className = 'rule-card'
if (!rule.enabled) card.classList.add('is-disabled')
const head = document.createElement('div')
head.className = 'rule-head'
const title = document.createElement('strong')
title.textContent = `规则 ${index + 1}`
const toggle = document.createElement('label')
toggle.className = 'check'
const enabledInput = document.createElement('input')
enabledInput.type = 'checkbox'
enabledInput.checked = rule.enabled
enabledInput.addEventListener('change', () => {
rule.enabled = enabledInput.checked
card.classList.toggle('is-disabled', !rule.enabled)
})
const toggleText = document.createElement('span')
toggleText.textContent = '启用'
toggle.append(enabledInput, toggleText)
const remove = document.createElement('button')
remove.type = 'button'
remove.className = 'ghost danger'
remove.textContent = '删除'
remove.addEventListener('click', () => {
config.rules.splice(index, 1)
renderRules()
})
const headActions = document.createElement('div')
headActions.className = 'rule-head-actions'
headActions.append(toggle, remove)
head.append(title, headActions)
const keywordInput = document.createElement('input')
keywordInput.type = 'text'
keywordInput.maxLength = MAX_KEYWORD_LENGTH
keywordInput.value = rule.keyword
keywordInput.addEventListener('input', () => {
rule.keyword = keywordInput.value
})
const modeSelect = document.createElement('select')
;[
['contains', '包含'],
['exact', '完全匹配'],
['prefix', '以…开头']
].forEach(([value, label]) => {
const option = document.createElement('option')
option.value = value
option.textContent = label
option.selected = rule.mode === value
modeSelect.append(option)
})
modeSelect.addEventListener('change', () => {
rule.mode = modeSelect.value
})
const replyInput = document.createElement('textarea')
replyInput.rows = 2
replyInput.maxLength = MAX_REPLY_LENGTH
replyInput.value = rule.reply
replyInput.addEventListener('input', () => {
rule.reply = replyInput.value
})
const replyBlock = field('回复内容', replyInput)
const replyHint = document.createElement('p')
replyHint.className = 'hint'
replyHint.textContent =
'可用变量:{sender}(发送者)、{keyword}(命中词)、{time}(当前时间 HH:mm)'
replyBlock.append(replyHint)
const cooldownInput = document.createElement('input')
cooldownInput.type = 'number'
cooldownInput.min = '0'
cooldownInput.max = '3600'
cooldownInput.value = String(rule.cooldownSeconds)
cooldownInput.addEventListener('change', () => {
rule.cooldownSeconds = clampInteger(cooldownInput.value, 0, 3600, 0)
cooldownInput.value = String(rule.cooldownSeconds)
})
const priorityInput = document.createElement('input')
priorityInput.type = 'number'
priorityInput.min = '0'
priorityInput.max = '100'
priorityInput.step = '1'
priorityInput.value = String(rule.priority)
priorityInput.addEventListener('change', () => {
rule.priority = clampInteger(priorityInput.value, 0, 100, 0)
priorityInput.value = String(rule.priority)
})
const numberRow = document.createElement('div')
numberRow.className = 'field-row'
const cooldownField = field('冷却时间(秒)', cooldownInput)
const priorityField = field('优先级(0–100,越大越先匹配)', priorityInput)
numberRow.append(cooldownField, priorityField)
card.append(
head,
field('关键词', keywordInput),
field('匹配方式', modeSelect),
replyBlock,
numberRow
)
rulesContainer.append(card)
})
}
function syncForm() {
document.getElementById('enabled').checked = config.enabled === true
selectedGroupIds = new Set(config.scope.groups)
renderGroupChips()
renderGroupOptions()
document.getElementById('include-direct').checked = config.scope.includeDirect !== false
document.getElementById('require-mention').checked = config.scope.requireMentionMe === true
renderRules()
}
function readForm() {
config.enabled = document.getElementById('enabled').checked
config.scope.groups = [...selectedGroupIds].slice(0, 200)
config.scope.includeDirect = document.getElementById('include-direct').checked
config.scope.requireMentionMe = document.getElementById('require-mention').checked
}
function localDateKey(timestamp) {
const date = new Date(timestamp)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${date.getFullYear()}-${month}-${day}`
}
function formatClock(timestamp) {
const date = new Date(timestamp)
const hour = String(date.getHours()).padStart(2, '0')
const minute = String(date.getMinutes()).padStart(2, '0')
return `${hour}:${minute}`
}
/** 统计展示:只读 storage,不参与任何写入。 */
function renderStats(raw) {
statsList.textContent = ''
const now = Date.now()
const sameDay = raw && raw.dateKey === localDateKey(now)
const todayCount = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
const hits = raw && Array.isArray(raw.lastHits) ? raw.lastHits.filter((hit) => hit && hit.at) : []
if (!hits.length && todayCount === 0) {
statsSummary.textContent = '暂无命中记录'
return
}
statsSummary.textContent = `今日命中 ${todayCount} 次`
hits
.slice(-STATS_PREVIEW)
.reverse()
.forEach((hit) => {
const item = document.createElement('li')
item.className = 'stats-item'
const time = document.createElement('span')
time.textContent = formatClock(Number(hit.at))
const ruleId = document.createElement('code')
ruleId.textContent = String(hit.ruleId || '未知规则')
const result = document.createElement('span')
result.className = hit.ok === true ? 'stats-ok' : 'stats-fail'
result.textContent = hit.ok === true ? '成功' : '失败'
item.append(time, ruleId, result)
statsList.append(item)
})
}
async function loadStats() {
try {
const stored = await callHost('storage.get', { key: STATS_KEY })
renderStats(stored)
} catch (error) {
renderStats(null)
setStatus(`统计读取失败:${error.message}`, 'error')
}
}
document.getElementById('add-rule').addEventListener('click', () => {
config.rules.push({
id: newRuleId(),
keyword: '',
mode: 'contains',
reply: '',
cooldownSeconds: 30,
enabled: true,
priority: 0
})
renderRules()
})
document.getElementById('save').addEventListener('click', async () => {
readForm()
// 只有启用中的规则必须有内容:停用的草稿允许留空,方便先存后写。
const invalid = config.rules.find(
(rule) => rule.enabled && (!rule.keyword.trim() || !rule.reply.trim())
)
if (invalid) {
setStatus('启用中的规则都需要关键词和回复内容;也可以先取消启用再保存。', 'error')
return
}
const payload = {
configVersion: CONFIG_VERSION,
enabled: config.enabled === true,
rules: config.rules.map(normalizeRule),
scope: {
groups: config.scope.groups.slice(0, 200),
includeDirect: config.scope.includeDirect !== false,
requireMentionMe: config.scope.requireMentionMe === true
}
}
try {
await callHost('storage.set', { key: CONFIG_KEY, value: payload })
// 回写规范化结果但保留原对象引用:卡片上的输入事件仍在改这些对象。
payload.rules.forEach((rule, index) => Object.assign(config.rules[index], rule))
config.configVersion = CONFIG_VERSION
setStatus('配置已保存。后台进程会在下一次收到消息时生效。', 'ok')
loadStats()
} catch (error) {
setStatus(`保存失败:${error.message}`, 'error')
}
})
document.getElementById('reset').addEventListener('click', async () => {
config = clone(DEFAULT_CONFIG)
syncForm()
try {
await callHost('storage.set', { key: CONFIG_KEY, value: config })
setStatus('已恢复默认配置。', 'ok')
} catch (error) {
setStatus(`重置失败:${error.message}`, 'error')
}
})
document.getElementById('refresh-stats').addEventListener('click', () => {
loadStats()
})
async function boot() {
const stored = await callHost('storage.get', { key: CONFIG_KEY })
config = normalizeStoredConfig(stored)
syncForm()
await loadGroups()
setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
loadStats()
}
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
@@ -0,0 +1,71 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>关键词回复机器人</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main class="page">
<header class="page-header">
<div>
<h1>关键词回复机器人</h1>
<p>收到文本消息后按规则匹配,命中即经 TraceMemo Gateway 回复。本页只写配置,不直接发送。</p>
</div>
<label class="switch">
<input id="enabled" type="checkbox" />
<span>启用机器人</span>
</label>
</header>
<section class="panel">
<div class="panel-header">
<h2>关键词规则</h2>
<button id="add-rule" type="button" class="ghost">添加规则</button>
</div>
<div id="rules" class="rules"></div>
</section>
<section class="panel">
<h2>监听范围</h2>
<div class="field">
<span>只监听这些群聊(可多选、可搜索;留空表示全部群聊)</span>
<div id="group-picker" class="group-picker">
<div id="group-chips" class="group-chips" hidden></div>
<input
id="group-search"
type="text"
placeholder="搜索群聊名称或 id…"
autocomplete="off"
/>
<div id="group-options" class="group-options" hidden></div>
</div>
</div>
<div class="row">
<label class="check"><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label>
<label class="check"><input id="require-mention" type="checkbox" /><span>只处理真正 @ 我的消息</span></label>
</div>
</section>
<section class="panel">
<div class="panel-header">
<h2>运行统计</h2>
<button id="refresh-stats" type="button" class="ghost">刷新</button>
</div>
<p id="stats-summary" class="stats-summary">暂无命中记录</p>
<ul id="stats-list" class="stats-list"></ul>
<p class="hint">统计只记录规则编号、命中时间与发送结果,不含会话、昵称与消息正文。</p>
</section>
<footer class="page-footer">
<div class="row">
<button id="save" type="button" class="primary">保存配置</button>
<button id="reset" type="button" class="ghost">恢复默认</button>
</div>
<p id="status" class="status" role="status"></p>
</footer>
</main>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,384 @@
:root {
color-scheme: light dark;
--bg: #f6f8f7;
--card: #ffffff;
--text: #1c2622;
--muted: #6b7a73;
--border: #dfe6e2;
--brand: #247a63;
--danger: #b4472f;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161c19;
--card: #1e2622;
--text: #eef4f1;
--muted: #9aaba3;
--border: #33403a;
--brand: #4bb894;
--danger: #e0735a;
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
sans-serif;
}
.page {
max-width: 720px;
margin: 0 auto;
padding: 26px 22px 40px;
display: flex;
flex-direction: column;
gap: 16px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
h1 {
margin: 0;
font-size: 19px;
}
h2 {
margin: 0;
font-size: 13px;
font-weight: 700;
}
header p {
margin: 8px 0 0;
max-width: 52ch;
color: var(--muted);
font-size: 12px;
line-height: 19px;
}
.panel {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--card);
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.rules {
display: flex;
flex-direction: column;
gap: 12px;
}
.rule-card {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 10px;
}
.rule-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: 12px;
}
.rule-head-actions {
display: flex;
align-items: center;
gap: 10px;
}
.rule-card.is-disabled {
border-style: dashed;
}
.rule-card.is-disabled .field,
.rule-card.is-disabled .field-row {
opacity: 0.55;
}
.field-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
}
.hint {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 16px;
}
.stats-summary {
margin: 0;
color: var(--text);
font-size: 12px;
}
.stats-list {
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.stats-item {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 12px;
}
.stats-ok {
color: var(--brand);
}
.stats-fail {
color: var(--danger);
}
@media (max-width: 480px) {
.field-row {
grid-template-columns: minmax(0, 1fr);
}
}
.field > span {
color: var(--muted);
font-size: 11px;
}
input[type='text'],
input[type='number'],
select,
textarea {
width: 100%;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
}
textarea {
resize: vertical;
}
.row {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.check,
.switch {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--muted);
}
.switch {
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text);
}
button {
padding: 6px 11px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
cursor: pointer;
}
button.primary {
border-color: transparent;
background: var(--brand);
color: #fff;
}
button.ghost:hover {
border-color: var(--brand);
}
button.danger {
color: var(--danger);
}
.page-footer {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.status {
min-height: 18px;
margin: 0;
color: var(--muted);
font-size: 12px;
}
.status[data-kind='ok'] {
color: var(--brand);
}
.status[data-kind='error'] {
color: var(--danger);
}
code {
padding: 1px 4px;
border-radius: 4px;
background: var(--bg);
font-size: 11px;
}
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
.group-picker {
position: relative;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
padding: 6px;
}
.group-picker:focus-within {
border-color: var(--brand);
}
.group-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-bottom: 4px;
}
.group-chip {
display: inline-flex;
align-items: center;
gap: 2px;
max-width: 100%;
padding: 2px 4px 2px 8px;
border-radius: 6px;
background: var(--bg);
font-size: 11px;
}
.group-chip > span {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-chip-remove {
border: 0;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 14px;
line-height: 1;
padding: 0 4px;
}
.group-chip-remove:hover {
color: var(--danger);
}
.group-picker > input[type='text'] {
width: 100%;
border: 0;
outline: 0;
background: transparent;
color: var(--text);
padding: 4px 2px;
font: inherit;
font-size: 12px;
}
.group-options {
position: absolute;
z-index: 30;
left: 0;
right: 0;
top: calc(100% + 4px);
max-height: 220px;
overflow: auto;
padding: 4px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
.group-option {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 6px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
}
.group-option:hover {
background: var(--bg);
}
.group-option input {
margin: 0;
}
.group-option-empty {
padding: 8px 6px;
color: var(--muted);
font-size: 11px;
}
+27
View File
@@ -0,0 +1,27 @@
# @tracememo/extension-sdk
TraceMemo 扩展 SDK v1 的**类型定义**。运行期不需要安装或打包这个包:宿主在扩展后台进程里注入全局 `tm`。
## 用法
把 `index.d.ts` 复制进扩展仓库(或作为 devDependency),然后:
```ts
import type { TraceMemoApi } from './extension-sdk'
module.exports = function activate(tm: TraceMemoApi): void {
tm.events.on('message.received', async (event) => {
if (event.isSelf || event.type !== 'text') return
if (!event.text?.includes('你好')) return
await tm.wechat.send({ to: event.conversationId, text: '你好呀!', dedupeKey: event.eventId })
})
}
```
## 约定
- 所有能力都要在 `manifest.json` 里声明权限;未声明的调用返回 `PERMISSION_DENIED`。
- 后台是**独立 Node 子进程**,不是强沙箱:安装即表示信任该扩展代码。
- 页面运行在 `sandbox="allow-scripts"` 的 iframe 里,只能通过 postMessage 调用
`storage.*` / `capabilities.get` / `extension.info`,不能发送微信消息。
- 发送永远经过宿主 Gateway:权限、授权校验、限流、审计与幂等都在宿主侧执行。
+188
View File
@@ -0,0 +1,188 @@
/**
* TraceMemo 扩展 SDK v1 —— 仅类型定义。
*
* 运行期没有这个包:宿主在后台子进程里注入全局 `tm`,扩展入口只需要
* `module.exports = function activate(tm: TraceMemoApi) {}`。
* 把本文件放进扩展仓库即可获得补全与类型检查。
*/
export type ExtensionMessageType =
| 'text'
| 'image'
| 'voice'
| 'video'
| 'sticker'
| 'file'
| 'link'
| 'system'
| 'other'
export interface TraceMemoMessageEvent {
/** 同一条微信消息稳定不变:`message:<sha1(sessionId:localId)>`。 */
eventId: string
accountId: string
conversationId: string
messageId: string
senderId?: string
senderName?: string
isGroup: boolean
isSelf: boolean
type: ExtensionMessageType
text?: string
/** 真正 @ 到当前登录账号,不是正文里的 `@昵称`。 */
mentionsMe: boolean
/** epoch 毫秒。 */
timestamp: number
}
export interface TraceMemoQueriedMessage {
messageId: string
conversationId: string
senderId?: string
senderName?: string
isSelf: boolean
type: string
text?: string
/** epoch 毫秒。 */
timestamp: number
}
export interface TraceMemoSendTextRequest {
/** 缺省为 text。 */
type?: 'text'
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
to: string
text: string
at?: Record<string, string>
/** 相同键的重复请求会被 Gateway 审计短路。 */
dedupeKey?: string
}
/**
* 图片发送。
*/
export interface TraceMemoSendImageRequest {
type: 'image'
to: string
path: string
dedupeKey?: string
}
/**
* 视频发送。原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。
* 路径必须位于扩展数据目录或系统临时目录。
*/
export interface TraceMemoSendVideoRequest {
type: 'video'
to: string
path: string
dedupeKey?: string
}
export type TraceMemoSendRequest =
| TraceMemoSendTextRequest
| TraceMemoSendImageRequest
| TraceMemoSendVideoRequest
export interface TraceMemoAutomationActionDefinition {
id: string
title: string
description?: string
inputSchema?: {
type: 'object'
properties?: Record<string, { type?: 'string' | 'number' | 'boolean'; description?: string }>
required?: string[]
}
handler: (input: Record<string, unknown>) => unknown | Promise<unknown>
}
export interface TraceMemoAutomationActionOutput {
success: boolean
output?: Record<string, unknown>
/** 宿主经 Gateway 发回原会话;扩展自己不发消息。 */
reply?: { type: 'text'; text: string; at?: Record<string, string> }
error?: string
}
export interface TraceMemoCapabilities {
extensionId: string
enabled: boolean
permissions: string[]
platform: string
databaseReady: boolean
send: {
supported: boolean
ready: boolean
canSendText: boolean
canSendImage: boolean
canSendVideo: boolean
licensed: boolean
message: string
}
ai: { configured: boolean; modelName: string }
}
export interface TraceMemoApi {
extension: {
readonly id: string
/** 扩展私有数据目录;下载与生成的文件应放在这里。 */
readonly dataDir: string
readonly permissions: string[]
}
events: {
on(
name: 'message.received',
handler: (event: TraceMemoMessageEvent) => void | Promise<void>
): () => void
off(
name: 'message.received',
handler: (event: TraceMemoMessageEvent) => void | Promise<void>
): void
}
messages: {
query(request: {
conversationId: string
/** epoch 毫秒;默认最近 24 小时。 */
startTime?: number
/** epoch 毫秒;默认现在。 */
endTime?: number
limit?: number
}): Promise<{ messages: TraceMemoQueriedMessage[] }>
}
wechat: {
send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }>
}
ai: {
chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }>
}
storage: {
get(key: string): Promise<unknown>
set(key: string, value: unknown): Promise<void>
remove(key: string): Promise<boolean>
list(): Promise<Array<{ key: string; value: unknown }>>
}
automation: {
registerAction(definition: TraceMemoAutomationActionDefinition): void
}
capabilities: {
get(): Promise<TraceMemoCapabilities>
}
log: {
info(message: unknown): void
warn(message: unknown): void
error(message: unknown): void
}
}
/**
* 后台入口签名。
*
* ```js
* module.exports = function activate(tm) { ... }
* ```
*/
export type TraceMemoActivate = (tm: TraceMemoApi) => void | Promise<void>
declare global {
var tm: TraceMemoApi
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "@tracememo/extension-sdk",
"version": "1.0.0",
"private": true,
"description": "TraceMemo 扩展 SDK 的类型定义(v1)。运行期由宿主注入 tm 对象,无需打包进扩展。",
"types": "index.d.ts",
"files": ["index.d.ts", "README.md"],
"license": "MIT"
}
@@ -0,0 +1,134 @@
import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest'
import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types'
export interface RegisteredExtensionAction {
extensionId: string
extensionName: string
actionId: string
title: string
description?: string
/** 后台进程是否真的注册了这个动作。 */
registered: boolean
/** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */
declared: boolean
}
/**
* 扩展贡献的自动化动作注册表。
*
* 两个来源刻意分开记:
* - `declared`:manifest 里写了什么 —— 用于在规则编辑器里展示「这个扩展提供了哪些动作」;
* - `registered`:后台进程运行期真正注册了什么 —— 只有它能被执行。
*
* 二者不一致时**不猜**:动作在界面上显示为不可用,规则执行时明确报错。
*/
export class ExtensionActionRegistry {
private readonly registered = new Map<
string,
Map<string, { title: string; description?: string }>
>()
private readonly declared = new Map<
string,
{ name: string; actions: ExtensionAutomationActionContribution[] }
>()
private readonly names = new Map<string, string>()
setDeclared(
extensionId: string,
extensionName: string,
actions: ExtensionAutomationActionContribution[]
): void {
this.names.set(extensionId, extensionName)
this.declared.set(extensionId, { name: extensionName, actions: [...actions] })
}
setRegistered(
extensionId: string,
extensionName: string,
actions: Array<{ id: string; title: string; description?: string }>
): void {
this.names.set(extensionId, extensionName)
this.registered.set(
extensionId,
new Map(
actions.map((action) => [
action.id,
{
title: action.title,
...(action.description ? { description: action.description } : {})
}
])
)
)
}
remove(extensionId: string): void {
this.registered.delete(extensionId)
this.declared.delete(extensionId)
this.names.delete(extensionId)
}
removeRuntime(extensionId: string): void {
this.registered.delete(extensionId)
}
isRegistered(extensionId: string, actionId: string): boolean {
return this.registered.get(extensionId)?.has(actionId) === true
}
get(extensionId: string, actionId: string): RegisteredExtensionAction | undefined {
const declaredAction = this.declared
.get(extensionId)
?.actions.find((action) => action.id === actionId)
const runtime = this.registered.get(extensionId)?.get(actionId)
if (!declaredAction && !runtime) return undefined
return {
extensionId,
extensionName: this.names.get(extensionId) || extensionId,
actionId,
title: runtime?.title || declaredAction?.title || actionId,
...(runtime?.description || declaredAction?.description
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime),
declared: Boolean(declaredAction)
}
}
list(): RegisteredExtensionAction[] {
const result: RegisteredExtensionAction[] = []
const extensionIds = new Set([...this.declared.keys(), ...this.registered.keys()])
for (const extensionId of extensionIds) {
const declaredActions = this.declared.get(extensionId)?.actions ?? []
const runtimeActions = this.registered.get(extensionId) ?? new Map()
const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()])
for (const actionId of ids) {
const action = this.get(extensionId, actionId)
if (action) result.push(action)
}
}
return result.sort((left, right) => {
if (left.extensionName !== right.extensionName)
return left.extensionName.localeCompare(right.extensionName)
return left.title.localeCompare(right.title)
})
}
summariesFor(extensionId: string): ExtensionAutomationActionSummary[] {
const declaredActions = this.declared.get(extensionId)?.actions ?? []
const runtimeActions = this.registered.get(extensionId) ?? new Map()
const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()])
return Array.from(ids).map((actionId) => {
const declaredAction = declaredActions.find((action) => action.id === actionId)
const runtime = runtimeActions.get(actionId)
return {
id: actionId,
title: runtime?.title || declaredAction?.title || actionId,
...(runtime?.description || declaredAction?.description
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime)
}
})
}
}
@@ -0,0 +1,45 @@
import { ExtensionError } from '../../shared/extensions/errors'
import { hasExtensionPermission } from '../../shared/extensions/permissions'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import { getExtensionManager, hasExtensionManager } from './extension-service'
export interface ExtensionActionContext {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
/**
* 自动化 → 扩展动作的桥。
*
* 输入里的 `conversationId` / `accountId` / `message` 是**宿主注入的运行时上下文**,
* 与用户在规则里配置的静态 `input` 合并;同名键以宿主值为准,扩展不能靠配置
* 伪造一个假的会话或账号。
*/
export async function invokeExtensionAction(
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: ExtensionActionContext
): Promise<ExtensionAutomationActionOutput> {
if (!hasExtensionManager()) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展系统尚未初始化')
}
const runtimeInput: Record<string, unknown> = {
...input,
conversationId: context.conversationId,
isGroup: context.isGroup,
accountId: context.accountId,
...(context.message ? { message: context.message } : {})
}
return getExtensionManager().invokeAutomationAction(extensionId, actionId, runtimeInput)
}
export function canExtensionSendText(extensionId: string): boolean {
if (!hasExtensionManager()) return false
const extension = getExtensionManager().get(extensionId)
if (!extension?.enabled) return false
return hasExtensionPermission(extension.grantedPermissions, 'wechat.send.text')
}
@@ -0,0 +1,74 @@
import { mapLicenseStatus, probeLicenseStatus } from '../services/msg-insert-capability-service'
import { macWechatRuntimeManager } from '../services/mac-wechat-runtime-manager'
export interface ExtensionEntitlementResult {
ok: boolean
message: string
source: 'mac_license' | 'hook_license' | 'unsupported'
}
export interface ExtensionEntitlementDependencies {
platform?: NodeJS.Platform
getMacLicense?: () => Promise<{ authorized: boolean; message?: string }>
probeLicense?: () => Promise<{ ok: boolean; status?: string }>
}
/**
* 扩展发送的 授权校验。
*
* 只在主进程可信边界调用,且**不接受渲染层 / 扩展传入的任何布尔值**:
* - macOS:读 Native Runtime 的 license 状态,要求 `authorized === true`;
* - Windows:探测本机 Hook 的 `/license/status`,只接受 `LICENSE_OK`。
*
* 与「发送能力 ready」是两件事:能力 ready 只说明本机装好了 Runtime,
* 不代表授权有效。
*/
export async function checkExtensionSendEntitlement(
dependencies: ExtensionEntitlementDependencies = {}
): Promise<ExtensionEntitlementResult> {
const platform = dependencies.platform ?? process.platform
if (platform === 'darwin') {
try {
const status = dependencies.getMacLicense
? await dependencies.getMacLicense()
: await macWechatRuntimeManager.getMacLicenseStatus()
if (status.authorized) {
return { ok: true, message: '授权有效', source: 'mac_license' }
}
return {
ok: false,
message: status.message || '需要有效授权才能由扩展发送消息',
source: 'mac_license'
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '无法确认授权状态',
source: 'mac_license'
}
}
}
if (platform === 'win32') {
try {
const probe = dependencies.probeLicense
? await dependencies.probeLicense()
: await probeLicenseStatus()
if (!probe.ok) {
return { ok: false, message: '无法确认授权状态', source: 'hook_license' }
}
const mapped = mapLicenseStatus(probe.status)
return {
ok: mapped.entitlement === 'valid',
message: mapped.message,
source: 'hook_license'
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '无法确认授权状态',
source: 'hook_license'
}
}
}
return { ok: false, message: '当前平台不支持微信发送', source: 'unsupported' }
}
+135
View File
@@ -0,0 +1,135 @@
import { createHash } from 'node:crypto'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import {
buildExtensionMessageEvent,
EXTENSION_EVENT_PROTOCOL_VERSION,
shouldDeliverExtensionEvent,
type ExtensionMessageEvent
} from '../../shared/extensions/events'
import type { ExtensionSubscriptions } from '../../shared/extensions/manifest'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
const DEDUPE_TTL_MS = 10 * 60 * 1000
const DEDUPE_MAX_ENTRIES = 5_000
export interface ExtensionEventSubscriber {
extensionId: string
subscriptions: ExtensionSubscriptions | undefined
deliver: (envelope: ExtensionEventEnvelope) => boolean
}
export interface ExtensionEventBusDependencies {
listSubscribers: () => ExtensionEventSubscriber[]
getAccountId: () => string
getSelfUsernames: () => string[]
now?: () => number
onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void
}
export interface ExtensionEventBusStats {
received: number
deduped: number
delivered: number
dropped: number
}
/**
* 把 MessageListener 的规范化消息分发给扩展。
*
* 去重键 `sessionId:localId`,扩展侧独立保留一层,避免进程重启后补投重复;
* 旧 Runtime 只能回读最近活跃会话,能力诊断会如实标记降级。
*/
export class ExtensionEventBus {
private readonly seen = new Map<string, number>()
private readonly now: () => number
private accountId = ''
private counters: ExtensionEventBusStats = { received: 0, deduped: 0, delivered: 0, dropped: 0 }
constructor(private readonly dependencies: ExtensionEventBusDependencies) {
this.now = dependencies.now ?? (() => Date.now())
}
/** 切换账号时清空去重表:旧账号的 localId 不能在新账号下命中。 */
setAccountId(accountId: string): void {
const next = String(accountId || '').trim()
if (next === this.accountId) return
this.accountId = next
this.seen.clear()
}
stats(): ExtensionEventBusStats {
return { ...this.counters }
}
/** 入口**绝不抛**:它挂在 MessageListener 的投递循环上。 */
handleMessage(message: NormalizedIncomingMessage): void {
try {
this.counters.received += 1
const eventId = buildEventId(message.sessionId, message.localId)
if (!this.markSeen(eventId)) {
this.counters.deduped += 1
return
}
const selfUsernames = new Set(this.dependencies.getSelfUsernames())
const event = buildExtensionMessageEvent({
eventId,
accountId: this.accountId,
conversationId: message.sessionId,
messageId: message.serverId || message.localId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
isGroup: message.isGroup,
isSelf: message.isSelf,
messageType: message.messageType,
...(message.content !== undefined ? { content: message.content } : {}),
// 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。
mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)),
createTimeSeconds: message.createTime
})
const envelope: ExtensionEventEnvelope = {
version: EXTENSION_EVENT_PROTOCOL_VERSION,
kind: 'message.received',
event
}
for (const subscriber of this.dependencies.listSubscribers()) {
if (!shouldDeliverExtensionEvent(subscriber.subscriptions, event)) continue
if (subscriber.deliver(envelope)) {
this.counters.delivered += 1
this.dependencies.onDelivered?.(subscriber.extensionId, event)
} else {
this.counters.dropped += 1
}
}
} catch (error) {
console.warn(
`[ExtensionEventBus] dispatch failed: ${error instanceof Error ? error.message : String(error)}`
)
}
}
private markSeen(eventId: string): boolean {
const now = this.now()
if (this.seen.has(eventId)) return false
this.seen.set(eventId, now)
if (this.seen.size > DEDUPE_MAX_ENTRIES) {
for (const [key, at] of this.seen) {
if (now - at > DEDUPE_TTL_MS) this.seen.delete(key)
}
if (this.seen.size > DEDUPE_MAX_ENTRIES) {
const overflow = this.seen.size - DEDUPE_MAX_ENTRIES
let removed = 0
for (const key of this.seen.keys()) {
this.seen.delete(key)
removed += 1
if (removed >= overflow) break
}
}
}
return true
}
}
export function buildEventId(sessionId: string, localId: string): string {
const digest = createHash('sha1').update(`${sessionId}\u0001${localId}`).digest('hex')
return `message:${digest}`
}
+677
View File
@@ -0,0 +1,677 @@
import { fork, type ChildProcess } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
import {
sortPermissionsByRisk,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
type ExtensionHostCall,
type ExtensionHostCallMethod,
type ExtensionHostInboundMessage,
type ExtensionHostOutboundMessage,
type ExtensionMessagesQueryRequest,
type ExtensionQueriedMessage,
type ExtensionSendImageRequest,
type ExtensionSendTextRequest,
type ExtensionSendTextResult,
type ExtensionSendVideoRequest
} from '../../shared/extensions/rpc'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
import type { ExtensionStorage } from './extension-storage'
const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000
const DEFAULT_ACTION_TIMEOUT_MS = 15_000
const MAX_RESTARTS = 3
const RESTART_WINDOW_MS = 5 * 60 * 1000
const RESTART_BASE_DELAY_MS = 1_000
const EVENT_BUCKET_CAPACITY = 100
const EVENT_REFILL_PER_SECOND = 60
export interface ExtensionHostChild {
send(message: unknown): void
kill(): void
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
once?(event: 'exit', listener: () => void): void
readonly pid?: number
}
export interface ExtensionHostSpawnOptions {
extensionId: string
extensionDir: string
}
export interface ExtensionHostDependencies {
extensionId: string
extensionDir: string
/** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */
dataDir: string
permissions: ExtensionPermission[]
storage: ExtensionStorage
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
onLog?: (level: 'info' | 'warn' | 'error', message: string) => void
onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void
onActionsChanged?: () => void
queryMessages?: (
extensionId: string,
request: ExtensionMessagesQueryRequest
) => Promise<ExtensionQueriedMessage[]>
sendText?: (
extensionId: string,
request: ExtensionSendTextRequest
) => Promise<ExtensionSendTextResult>
sendImage?: (
extensionId: string,
request: ExtensionSendImageRequest
) => Promise<ExtensionSendTextResult>
sendVideo?: (
extensionId: string,
request: ExtensionSendVideoRequest
) => Promise<ExtensionSendTextResult>
aiChat?: (
extensionId: string,
messages: Array<{ role: string; content: string }>
) => Promise<{ text: string }>
capabilities?: (extensionId: string) => Promise<ExtensionCapabilitySnapshot>
now?: () => number
activateTimeoutMs?: number
actionTimeoutMs?: number
}
interface PendingAction {
resolve: (value: ExtensionAutomationActionOutput) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
interface RegisteredAction {
id: string
title: string
description?: string
}
interface ActivationWaiter {
resolve: () => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
child: ExtensionHostChild
}
/**
* 单个扩展的后台进程。
*
* **隔离边界**:每个扩展一个独立 Node 子进程,`require` 只发生在那里面;
* 主进程从不 `require` 扩展代码。子进程拿不到 Electron API、数据库句柄、
* 授权凭据或原生发送通道 —— 它只能通过本类转发的白名单 RPC 申请能力。
*
* ⚠️ 独立进程不等于强沙箱:后台仍是任意 Node 代码,安装时按「受信任本地开发者扩展」处理。
*/
export class ExtensionHost {
private readonly dependencies: ExtensionHostDependencies
private readonly storage: ExtensionStorage
private readonly now: () => number
private child: ExtensionHostChild | null = null
private state: ExtensionRuntimeSnapshot
private stopping = false
private activation: Promise<void> | null = null
private activationWaiter: ActivationWaiter | null = null
private restartTimer: ReturnType<typeof setTimeout> | null = null
private readonly pendingActions = new Map<string, PendingAction>()
private readonly testHandlers = new Map<
string,
{
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
>()
private readonly actions = new Map<string, RegisteredAction>()
private eventTokens = EVENT_BUCKET_CAPACITY
private eventTokensAt: number
private droppedEvents = 0
private mutedDropLog = false
private restartTimestamps: number[] = []
constructor(dependencies: ExtensionHostDependencies) {
this.dependencies = dependencies
this.storage = dependencies.storage
this.now = dependencies.now ?? (() => Date.now())
this.eventTokensAt = this.now()
this.state = { state: 'inactive', since: this.now(), restarts: 0 }
}
snapshot(): ExtensionRuntimeSnapshot {
return { ...this.state }
}
registeredActions(): RegisteredAction[] {
return Array.from(this.actions.values()).map((action) => ({ ...action }))
}
async testSend(params: Record<string, unknown>): Promise<unknown> {
return this.runTestMessage('test-send', params)
}
private async runTestMessage(
type: 'test-send',
params: Record<string, unknown>
): Promise<unknown> {
if (this.state.state !== 'active' || !this.child) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
}
const requestId = randomUUID()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.testHandlers.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT'))
}, 450_000)
this.testHandlers.set(requestId, { resolve, reject, timer })
try {
this.child?.send({
type,
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
params
})
} catch (error) {
clearTimeout(timer)
this.testHandlers.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
/** 启动并等待 `activate` 握手完成。重复调用复用同一次启动。 */
async start(): Promise<void> {
if (this.state.state === 'active') return
if (this.activation) return this.activation
this.stopping = false
this.activation = this.doStart().finally(() => {
this.activation = null
})
return this.activation
}
async stop(): Promise<void> {
this.stopping = true
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
}
const child = this.child
this.child = null
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.actions.clear()
this.setState('inactive')
if (!child) return
try {
child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION })
} catch {
// 进程可能已经断开;kill 兜底。
}
await new Promise<void>((resolve) => {
const timer = setTimeout(() => {
try {
child.kill()
} catch {
// ignore
}
resolve()
}, 1_500)
child.once?.('exit', () => {
clearTimeout(timer)
resolve()
})
})
}
/**
* 投递消息事件。
*
* 令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志,
* 也不能让主进程的监听回调被拖垮。
*/
deliverEvent(envelope: ExtensionEventEnvelope): boolean {
if (this.state.state !== 'active' || !this.child) return false
this.refillTokens()
if (this.eventTokens < 1) {
this.droppedEvents += 1
if (!this.mutedDropLog && this.droppedEvents % 100 === 1) {
this.dependencies.onLog?.('warn', '消息事件超过扩展处理上限,部分事件已丢弃')
this.mutedDropLog = true
setTimeout(() => {
this.mutedDropLog = false
}, 10_000)
}
return false
}
this.eventTokens -= 1
try {
this.child.send({ type: 'event', version: EXTENSION_HOST_PROTOCOL_VERSION, envelope })
return true
} catch {
return false
}
}
/** 调用扩展注册的自动化动作。超时由宿主强制结束,扩展无法自行取消。 */
async invokeAction(
actionId: string,
input: Record<string, unknown>,
timeoutMs = this.dependencies.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS
): Promise<ExtensionAutomationActionOutput> {
if (this.state.state !== 'active' || !this.child) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
}
if (!this.actions.has(actionId)) {
throw new ExtensionError('ACTION_FAILED', `扩展没有注册动作 ${actionId}`)
}
const requestId = randomUUID()
return new Promise<ExtensionAutomationActionOutput>((resolve, reject) => {
const timer = setTimeout(
() => {
this.pendingActions.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT'))
},
Math.max(1_000, Math.min(timeoutMs, 60_000))
)
this.pendingActions.set(requestId, { resolve, reject, timer })
try {
this.child?.send({
type: 'invoke-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
actionId,
input,
timeoutMs
})
} catch (error) {
clearTimeout(timer)
this.pendingActions.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
private async doStart(): Promise<void> {
this.setState('starting')
this.actions.clear()
let child: ExtensionHostChild
try {
child = this.dependencies.spawn({
extensionId: this.dependencies.extensionId,
extensionDir: this.dependencies.extensionDir
})
} catch (error) {
this.setState('error', error instanceof Error ? error.message : '扩展进程启动失败')
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程启动失败')
}
this.child = child
this.wire(child)
try {
await this.activateChild(child)
this.setState('active')
this.dependencies.onLog?.('info', '扩展后台已启动')
} catch (error) {
this.dependencies.onLog?.(
'error',
`扩展启动失败:${error instanceof Error ? error.message : String(error)}`
)
// 先摘掉引用再 kill:否则 exit 回调会被当成「运行期崩溃」并触发重启。
if (this.child === child) this.child = null
try {
child.kill()
} catch {
// ignore
}
this.setState('error', error instanceof Error ? error.message : '扩展启动失败')
throw error instanceof Error
? error
: new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展启动失败')
}
}
/** 发 `activate` 并等待 `activated`。握手结果由 `handleMessage` 统一结算。 */
private activateChild(child: ExtensionHostChild): Promise<void> {
const timeoutMs = this.dependencies.activateTimeoutMs ?? DEFAULT_ACTIVATE_TIMEOUT_MS
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => {
this.settleActivation(new ExtensionError('ACTION_TIMEOUT', '扩展启动超时'))
},
Math.max(2_000, timeoutMs)
)
this.activationWaiter = { resolve, reject, timer, child }
try {
child.send({
type: 'activate',
version: EXTENSION_HOST_PROTOCOL_VERSION,
extensionId: this.dependencies.extensionId,
extensionDir: this.dependencies.extensionDir,
dataDir: this.dependencies.dataDir,
apiVersion: EXTENSION_API_VERSION,
permissions: sortPermissionsByRisk(this.dependencies.permissions)
})
} catch (error) {
this.settleActivation(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '无法向扩展进程发送激活指令'
)
)
}
})
}
private settleActivation(error?: Error): void {
const waiter = this.activationWaiter
if (!waiter) return
this.activationWaiter = null
clearTimeout(waiter.timer)
if (error) waiter.reject(error)
else waiter.resolve()
}
private wire(child: ExtensionHostChild): void {
child.on('message', (message) => this.handleMessage(message))
child.on('error', (error) => {
this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`)
})
child.on('exit', (code) => this.handleExit(child, code))
}
private handleExit(child: ExtensionHostChild, code: number | null): void {
if (this.child !== child) return
this.child = null
this.actions.clear()
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
this.failPendingActions(
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
)
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
if (this.stopping) {
this.setState('inactive')
return
}
const timestamp = this.now()
this.restartTimestamps = this.restartTimestamps.filter(
(item) => timestamp - item < RESTART_WINDOW_MS
)
if (this.restartTimestamps.length >= MAX_RESTARTS) {
this.dependencies.onLog?.('error', '扩展连续异常退出,已停止自动重启')
this.setState('crashed', '扩展连续异常退出,已停止自动重启')
return
}
this.restartTimestamps.push(timestamp)
this.setState('starting', '扩展进程异常退出,正在重启')
const delay = RESTART_BASE_DELAY_MS * 2 ** (this.restartTimestamps.length - 1)
this.restartTimer = setTimeout(() => {
this.restartTimer = null
this.state = { ...this.state, restarts: this.state.restarts + 1, since: this.now() }
void this.start().catch(() => undefined)
}, delay)
}
private handleMessage(raw: unknown): void {
if (!raw || typeof raw !== 'object') return
const message = raw as ExtensionHostOutboundMessage & { version?: number }
if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return
switch (message.type) {
case 'activated':
this.settleActivation(
message.ok
? undefined
: new ExtensionError('ACTION_FAILED', message.error?.message || '扩展激活失败')
)
return
case 'call':
void this.handleCall(message)
return
case 'register-action': {
const action = message.action
if (!action || typeof action.id !== 'string') return
this.actions.set(action.id, {
id: action.id,
title: String(action.title || action.id).slice(0, 60),
...(action.description ? { description: String(action.description).slice(0, 200) } : {})
})
this.dependencies.onActionsChanged?.()
return
}
case 'log':
this.dependencies.onLog?.(message.level, message.message)
return
case 'action-result': {
const pending = this.pendingActions.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.pendingActions.delete(message.requestId)
if (message.ok && message.output) {
pending.resolve(message.output)
} else {
pending.reject(
new ExtensionError(
'ACTION_FAILED',
message.error?.message || message.output?.error || '扩展动作执行失败'
)
)
}
return
}
case 'test-result': {
const pending = this.testHandlers.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.testHandlers.delete(message.requestId)
if (message.ok) pending.resolve(message.result)
else
pending.reject(
new ExtensionError(message.error?.code || 'ACTION_FAILED', message.error?.message)
)
return
}
}
}
private async handleCall(message: ExtensionHostCall): Promise<void> {
try {
const result = await this.executeCall(message.method, message.params)
this.send({
type: 'call-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: message.callId,
ok: true,
result
})
} catch (error) {
this.send({
type: 'call-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: message.callId,
ok: false,
error: toExtensionErrorPayload(error)
})
}
}
private async executeCall(
method: ExtensionHostCallMethod,
params: Record<string, unknown>
): Promise<unknown> {
const extensionId = this.dependencies.extensionId
switch (method) {
case 'storage.get':
this.requirePermission('storage')
return this.storage.get(extensionId, params.key)
case 'storage.set':
this.requirePermission('storage')
this.storage.set(extensionId, params.key, params.value)
return { ok: true }
case 'storage.remove':
this.requirePermission('storage')
return { removed: this.storage.remove(extensionId, params.key) }
case 'storage.list':
this.requirePermission('storage')
return { entries: this.storage.list(extensionId) }
case 'messages.query': {
this.requirePermission('messages.query')
if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return {
messages: await this.dependencies.queryMessages(
extensionId,
params as unknown as ExtensionMessagesQueryRequest
)
}
}
case 'wechat.send.text': {
this.requirePermission('wechat.send.text')
if (!this.dependencies.sendText) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendText(
extensionId,
params as unknown as ExtensionSendTextRequest
)
}
case 'wechat.send.image': {
this.requirePermission('wechat.send.image')
if (!this.dependencies.sendImage) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendImage(
extensionId,
params as unknown as ExtensionSendImageRequest
)
}
case 'wechat.send.video': {
this.requirePermission('wechat.send.video')
if (!this.dependencies.sendVideo) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendVideo(
extensionId,
params as unknown as ExtensionSendVideoRequest
)
}
case 'ai.chat': {
this.requirePermission('ai.chat')
if (!this.dependencies.aiChat) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
const messages = Array.isArray(params.messages) ? params.messages : []
const normalized = messages
.filter((item): item is { role: string; content: string } =>
Boolean(item && typeof item === 'object')
)
.slice(0, 40)
.map((item) => ({
role: String((item as { role?: unknown }).role || 'user'),
content: String((item as { content?: unknown }).content || '').slice(0, 20_000)
}))
return this.dependencies.aiChat(extensionId, normalized)
}
case 'capabilities.get':
if (!this.dependencies.capabilities) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.capabilities(extensionId)
default:
throw new ExtensionError('INVALID_REQUEST', `未知方法:${String(method)}`)
}
}
private requirePermission(permission: ExtensionPermission): void {
if (!this.dependencies.permissions.includes(permission)) {
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
}
}
private send(message: ExtensionHostInboundMessage): void {
try {
this.child?.send(message)
} catch {
// 进程已退出:pending 会由 handleExit 统一失败。
}
}
private failPendingActions(error: Error): void {
for (const [requestId, pending] of this.pendingActions) {
clearTimeout(pending.timer)
this.pendingActions.delete(requestId)
pending.reject(error)
}
}
private failPendingTests(error: Error): void {
for (const [requestId, pending] of this.testHandlers) {
clearTimeout(pending.timer)
this.testHandlers.delete(requestId)
pending.reject(error)
}
}
private refillTokens(): void {
const now = this.now()
const elapsed = Math.max(0, now - this.eventTokensAt)
if (elapsed <= 0) return
this.eventTokens = Math.min(
EVENT_BUCKET_CAPACITY,
this.eventTokens + (elapsed / 1000) * EVENT_REFILL_PER_SECOND
)
this.eventTokensAt = now
}
private setState(next: ExtensionRuntimeSnapshot['state'], lastError?: string): void {
this.state = {
state: next,
since: this.now(),
restarts: this.state.restarts,
...(lastError ? { lastError } : {})
}
this.dependencies.onStateChange?.(this.snapshot())
}
}
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
export function forkExtensionHost(
scriptPath: string
): (options: ExtensionHostSpawnOptions) => ExtensionHostChild {
return (options) => {
const child: ChildProcess = fork(scriptPath, [], {
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
serialization: 'advanced',
env: {
...process.env,
ELECTRON_RUN_AS_NODE: '1',
TM_EXTENSION_ID: options.extensionId,
TM_EXTENSION_DIR: options.extensionDir
}
})
return {
send: (message) => {
if (!child.connected) throw new Error('扩展进程未连接')
child.send(message as object)
},
kill: () => child.kill(),
on: (event, listener) => {
if (event === 'message') child.on('message', listener as (message: unknown) => void)
else if (event === 'exit') child.on('exit', listener as (code: number | null) => void)
else child.on('error', listener as (error: Error) => void)
},
once: (event, listener) => {
child.once(event, listener)
},
...(child.pid ? { pid: child.pid } : {})
}
}
}
+390
View File
@@ -0,0 +1,390 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { Open } from 'unzipper'
import { ExtensionError } from '../../shared/extensions/errors'
import {
isSafeRelativeEntryPath,
parseExtensionManifest,
type ExtensionManifest
} from '../../shared/extensions/manifest'
import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry'
import { isPathInside, type ExtensionPaths } from './extension-paths'
const MAX_FILES = 2_000
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
const MAX_FILE_BYTES = 20 * 1024 * 1024
const MAX_PACKAGE_BYTES = 100 * 1024 * 1024
export interface InstallOptions {
/** 应用版本,用于 `minAppVersion` 兼容检查。 */
appVersion: string
source?: 'directory' | 'package'
}
export interface InstallOutcome {
manifest: ExtensionManifest
installPath: string
previousVersion?: string
upgraded: boolean
}
export interface ExtensionInstallerDependencies {
paths: ExtensionPaths
registry: ExtensionRegistry
now?: () => number
}
interface TreeEntry {
relativePath: string
type: 'file' | 'directory'
size: number
}
/**
* 扩展安装 / 升级 / 卸载。
*
* 写入顺序固定为「临时目录 → 校验 → 原子改名」:任何一步失败都不会留下
* 半装目录;升级失败时旧版本仍在原位。
*/
export class ExtensionInstaller {
private readonly paths: ExtensionPaths
private readonly registry: ExtensionRegistry
private readonly now: () => number
constructor(dependencies: ExtensionInstallerDependencies) {
this.paths = dependencies.paths
this.registry = dependencies.registry
this.now = dependencies.now ?? (() => Date.now())
}
async installFromDirectory(sourceDir: string, options: InstallOptions): Promise<InstallOutcome> {
const root = path.resolve(sourceDir)
const stat = await fs.stat(root).catch(() => null)
if (!stat || !stat.isDirectory()) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的路径不是目录')
}
const manifest = await this.readManifest(root, options.appVersion)
const entries = await this.collectTree(root)
this.assertEntrypointsPresent(entries, manifest)
const staging = this.paths.stagingPath('dir')
await fs.mkdir(staging, { recursive: true })
try {
await copyTree(root, staging, entries)
return await this.finalize(staging, manifest, options.source ?? 'directory')
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
}
async installFromPackage(packagePath: string, options: InstallOptions): Promise<InstallOutcome> {
const stat = await fs.stat(packagePath).catch(() => null)
if (!stat || !stat.isFile()) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的扩展包不存在')
}
if (stat.size > MAX_PACKAGE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包超过大小限制')
}
const archive = await Open.file(packagePath)
if (!archive.files.length || archive.files.length > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包文件数量不合法')
}
const seen = new Set<string>()
let declaredTotal = 0
const entries: Array<{
relativePath: string
directory: boolean
size: number
entry: (typeof archive.files)[number]
}> = []
for (const entry of archive.files) {
const normalized = normalizeZipPath(entry.path)
const collisionKey = normalized.toLowerCase()
if (seen.has(collisionKey)) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内路径重复:${normalized}`)
}
seen.add(collisionKey)
if (entry.type !== 'File' && entry.type !== 'Directory') {
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
`扩展包条目类型不受支持:${normalized}`
)
}
const directory = entry.type === 'Directory'
const size = Number(entry.uncompressedSize || 0)
if (!directory && size > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内文件过大:${normalized}`)
}
declaredTotal += size
if (declaredTotal > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包解压后体积超过限制')
}
entries.push({ relativePath: normalized, directory, size, entry })
}
const manifestFile = entries.find(
(item) => item.relativePath === 'manifest.json' && !item.directory
)
if (!manifestFile)
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展包缺少 manifest.json')
const manifest = this.parseManifestText(
(await manifestFile.entry.buffer()).toString('utf8'),
options.appVersion
)
this.assertEntrypointsPresent(
entries.map((item) => ({
relativePath: item.relativePath,
type: item.directory ? 'directory' : 'file',
size: item.size
})),
manifest
)
const staging = this.paths.stagingPath('zip')
await fs.mkdir(staging, { recursive: true })
try {
let actualTotal = 0
for (const item of entries) {
const destination = path.resolve(staging, item.relativePath)
if (!isPathInside(staging, destination)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包条目越界:${item.relativePath}`)
}
if (item.directory) {
await fs.mkdir(destination, { recursive: true })
continue
}
await fs.mkdir(path.dirname(destination), { recursive: true })
const chunks: Buffer[] = []
for await (const chunk of item.entry.stream()) {
const buffer = Buffer.from(chunk as Uint8Array)
actualTotal += buffer.length
if (actualTotal > MAX_TOTAL_BYTES || buffer.length > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包实际解压体积超过限制')
}
chunks.push(buffer)
}
await fs.writeFile(destination, Buffer.concat(chunks))
const fileStat = await fs.lstat(destination)
if (!fileStat.isFile()) {
throw new ExtensionError(
'EXTENSION_INVALID_PATH',
`扩展包条目不是普通文件:${item.relativePath}`
)
}
}
return await this.finalize(staging, manifest, 'package')
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
}
/**
* 卸载扩展。
*
* `keepData` 为 true 时**只**删除代码目录,用户配置保留在
* `extensions-data/<id>`,同名扩展重新安装后能读回。
*/
async uninstall(extensionId: string, options: { keepData: boolean }): Promise<void> {
const target = this.paths.installDir(extensionId)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
const trash = `${target}.removed-${this.now()}`
const exists = await fs
.stat(target)
.then(() => true)
.catch(() => false)
if (exists) {
await fs.rename(target, trash)
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
}
if (!options.keepData) {
await fs
.rm(this.paths.extensionDataDir(extensionId), { recursive: true, force: true })
.catch(() => undefined)
}
this.registry.remove(extensionId)
}
private async readManifest(root: string, appVersion: string): Promise<ExtensionManifest> {
const manifestPath = path.join(root, 'manifest.json')
const text = await fs.readFile(manifestPath, 'utf8').catch(() => '')
if (!text) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展目录缺少 manifest.json')
return this.parseManifestText(text, appVersion)
}
private parseManifestText(text: string, appVersion: string): ExtensionManifest {
const result = parseExtensionManifestJsonWithDetail(text, appVersion)
if (!result.ok || !result.manifest) {
throw new ExtensionError(
result.code === 'EXTENSION_INCOMPATIBLE'
? 'EXTENSION_INCOMPATIBLE'
: 'EXTENSION_INVALID_MANIFEST',
result.message || '扩展 manifest 不合法'
)
}
return result.manifest
}
private assertEntrypointsPresent(entries: TreeEntry[], manifest: ExtensionManifest): void {
const files = new Set(
entries.filter((entry) => entry.type === 'file').map((entry) => entry.relativePath)
)
for (const [key, value] of Object.entries(manifest.entrypoints)) {
if (!value) continue
if (!files.has(value)) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`entrypoints.${key} 指向的文件不存在:${value}`
)
}
}
for (const page of manifest.contributions.pages) {
const entry = page.entry || manifest.entrypoints.page
if (!entry || !files.has(entry)) {
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', `页面 ${page.id} 的入口文件不存在`)
}
}
}
private async collectTree(root: string): Promise<TreeEntry[]> {
const entries: TreeEntry[] = []
let total = 0
const walk = async (directory: string, prefix: string): Promise<void> => {
const items = await fs.readdir(directory, { withFileTypes: true })
for (const item of items) {
const relativePath = prefix ? `${prefix}/${item.name}` : item.name
if (!isSafeRelativeEntryPath(relativePath)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`)
}
const absolute = path.join(directory, item.name)
const stat = await fs.lstat(absolute)
if (stat.isSymbolicLink()) {
throw new ExtensionError(
'EXTENSION_INVALID_PATH',
`扩展目录不能包含符号链接:${relativePath}`
)
}
if (stat.isDirectory()) {
entries.push({ relativePath, type: 'directory', size: 0 })
await walk(absolute, relativePath)
continue
}
if (!stat.isFile()) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `不支持的文件类型:${relativePath}`)
}
if (stat.size > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `文件过大:${relativePath}`)
}
total += stat.size
if (total > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展体积超过限制')
}
entries.push({ relativePath, type: 'file', size: stat.size })
if (entries.length > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展文件数量超过限制')
}
}
}
await walk(root, '')
return entries
}
/** 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 */
private async finalize(
staging: string,
manifest: ExtensionManifest,
source: 'directory' | 'package'
): Promise<InstallOutcome> {
const target = this.paths.installDir(manifest.id)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
await fs.mkdir(this.paths.extensionsDir, { recursive: true })
const existingRecord = this.registry.get(manifest.id)
const backup = `${target}.backup-${this.now()}`
const targetExists = await fs
.stat(target)
.then(() => true)
.catch(() => false)
if (targetExists) await fs.rename(target, backup)
try {
await fs.rename(staging, target)
} catch (error) {
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error ? error.message : '安装目录替换失败'
)
}
if (targetExists) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
const timestamp = this.now()
const record: ExtensionRegistryRecord = {
id: manifest.id,
version: manifest.version,
apiVersion: manifest.apiVersion,
// 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。
enabled: existingRecord?.enabled ?? false,
grantedPermissions: existingRecord?.grantedPermissions ?? [],
installedAt: existingRecord?.installedAt ?? timestamp,
updatedAt: timestamp,
source
}
this.registry.upsert(record)
return {
manifest,
installPath: target,
...(existingRecord ? { previousVersion: existingRecord.version } : {}),
upgraded: Boolean(existingRecord)
}
}
}
function normalizeZipPath(value: string): string {
const normalized = String(value || '')
.replace(/\\/g, '/')
.replace(/\/+$/, '')
if (!isSafeRelativeEntryPath(normalized)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包内路径不合法:${value}`)
}
return normalized
}
async function copyTree(root: string, destination: string, entries: TreeEntry[]): Promise<void> {
for (const entry of entries) {
const from = path.join(root, entry.relativePath)
const to = path.resolve(destination, entry.relativePath)
if (!isPathInside(destination, to)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `复制路径越界:${entry.relativePath}`)
}
if (entry.type === 'directory') {
await fs.mkdir(to, { recursive: true })
continue
}
await fs.mkdir(path.dirname(to), { recursive: true })
await fs.copyFile(from, to)
}
}
/**
* 与 shared 的 `parseExtensionManifestJson` 同构,但把「兼容性」与「格式」区分开,
* 好让安装界面给出可操作的提示(升级 TraceMemo vs 修 manifest)。
*/
function parseExtensionManifestJsonWithDetail(
text: string,
appVersion: string
): ReturnType<typeof parseExtensionManifest> {
let value: unknown
try {
value = JSON.parse(text)
} catch {
return { ok: false, code: 'EXTENSION_INVALID_MANIFEST', message: 'manifest.json 不是合法 JSON' }
}
return parseExtensionManifest(value, { appVersion })
}
+195
View File
@@ -0,0 +1,195 @@
import fs from 'fs-extra'
import path from 'node:path'
import { BrowserWindow, dialog, ipcMain, shell } from 'electron'
import { EXTENSION_IPC } from '../../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
InstalledExtension
} from '../../shared/extensions/types'
import type { ExtensionManager } from './extension-manager'
import type { ExtensionPaths } from './extension-paths'
export interface ExtensionIpcOptions {
/** 懒取:扩展系统在窗口创建之后才完成初始化。 */
getManager: () => ExtensionManager
paths: ExtensionPaths
/** 扩展页面 IPC 的调用方必须是主窗口;其它 webContents 一律拒绝。 */
isTrustedSender: (senderId: number) => boolean
}
/**
* 注册扩展中心的 IPC。
*
* 所有入参都在这一层收敛类型与长度:渲染层与扩展页面都是「不可信输入」,
* 不能把未校验的对象直接交给 manager。
*/
export function registerExtensionIpc(options: ExtensionIpcOptions): void {
const { paths } = options
const manager = (): ExtensionManager => options.getManager()
const guard = <Args extends unknown[], Result>(
handler: (...args: Args) => Promise<Result> | Result
): ((
event: Electron.IpcMainInvokeEvent,
...args: Args
) => Promise<Result | { success: false; error: { code: string; message: string } }>) => {
return async (event, ...args) => {
if (!options.isTrustedSender(event.sender.id)) {
return { success: false, error: { code: 'PERMISSION_DENIED', message: '不受信任的调用方' } }
}
try {
return await handler(...args)
} catch (error) {
return {
success: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '扩展操作失败'
}
}
}
}
}
ipcMain.handle(
EXTENSION_IPC.list,
guard((): InstalledExtension[] => manager().list())
)
ipcMain.handle(
EXTENSION_IPC.detail,
guard((extensionId: unknown): InstalledExtension | null =>
manager().get(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.pickDirectory,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const result = window
? await dialog.showOpenDialog(window, { properties: ['openDirectory'] })
: await dialog.showOpenDialog({ properties: ['openDirectory'] })
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.pickPackage,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const options: Electron.OpenDialogOptions = {
properties: ['openFile'],
filters: [
{ name: 'TraceMemo 扩展包', extensions: ['zip', 'tmext'] },
{ name: '全部文件', extensions: ['*'] }
]
}
const result = window
? await dialog.showOpenDialog(window, options)
: await dialog.showOpenDialog(options)
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.installDirectory,
guard(
(directory: unknown): Promise<ExtensionInstallResult> =>
manager().installFromDirectory(requirePath(directory))
)
)
ipcMain.handle(
EXTENSION_IPC.installPackage,
guard(
(packagePath: unknown): Promise<ExtensionInstallResult> =>
manager().installFromPackage(requirePath(packagePath))
)
)
ipcMain.handle(
EXTENSION_IPC.setEnabled,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; enabled?: unknown }
return manager().setEnabled(requireId(input.id), input.enabled === true)
})
)
ipcMain.handle(
EXTENSION_IPC.uninstall,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; keepData?: unknown }
return manager().uninstall(requireId(input.id), input.keepData !== false)
})
)
ipcMain.handle(
EXTENSION_IPC.logs,
guard((payload: unknown): ExtensionLogEntry[] => {
const input = (payload ?? {}) as { id?: unknown; limit?: unknown }
const limit = Number(input.limit)
return manager().getLogs(requireId(input.id), Number.isFinite(limit) ? limit : 100)
})
)
ipcMain.handle(
EXTENSION_IPC.clearLogs,
guard((extensionId: unknown): { success: true } => {
manager().clearLogs(requireId(extensionId))
return { success: true }
})
)
ipcMain.handle(
EXTENSION_IPC.pageUrl,
guard((payload: unknown): ExtensionPageDescriptor => {
const input = (payload ?? {}) as { id?: unknown; pageId?: unknown }
const pageId =
typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined
return manager().pageUrl(requireId(input.id), pageId)
})
)
ipcMain.handle(
EXTENSION_IPC.pageRequest,
guard((payload: unknown): Promise<ExtensionPageResponse> => {
const request = (payload ?? {}) as Partial<ExtensionPageRequest>
const extensionId = requireId(request.extensionId)
const method = String(request.method || '')
const params =
request.params && typeof request.params === 'object' && !Array.isArray(request.params)
? (request.params as Record<string, unknown>)
: {}
return manager().pageRequest(extensionId, method, params)
})
)
ipcMain.handle(
EXTENSION_IPC.openDataDir,
guard(async (extensionId: unknown): Promise<{ success: boolean; error?: string }> => {
const id = requireId(extensionId)
const directory = paths.extensionDataDir(id)
fs.ensureDirSync(directory)
const error = await shell.openPath(directory)
return error ? { success: false, error } : { success: true }
})
)
}
function requireId(value: unknown): string {
const id = String(value || '').trim()
if (!/^[a-z0-9.-]{3,128}$/.test(id)) throw new Error('扩展 id 不合法')
return id
}
function requirePath(value: unknown): string {
const target = String(value || '').trim()
if (!target || target.length > 4_096) throw new Error('路径不合法')
if (!path.isAbsolute(target)) throw new Error('必须使用绝对路径')
return target
}
+125
View File
@@ -0,0 +1,125 @@
import fs from 'fs-extra'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import type { ExtensionLogEntry } from '../../shared/extensions/types'
const MAX_ENTRIES_PER_EXTENSION = 200
const MAX_MESSAGE_LENGTH = 500
const MAX_FILE_BYTES = 256 * 1024
/**
* 扩展日志:内存环形缓冲 + 磁盘 JSONL(超过上限时轮转一份 `.1`)。
*
* 隐私边界:宿主只记录**生命周期与错误摘要**,不写聊天正文。
* 扩展主动写入的内容会原样落盘并展示给用户,作者必须自己遵守隐私约定。
*/
export class ExtensionLogStore {
private readonly logsDir: string
private readonly memory = new Map<string, ExtensionLogEntry[]>()
private readonly loaded = new Set<string>()
constructor(logsDir: string) {
this.logsDir = logsDir
}
append(
extensionId: string,
level: ExtensionLogEntry['level'],
source: ExtensionLogEntry['source'],
message: string
): ExtensionLogEntry {
this.ensureLoaded(extensionId)
const entry: ExtensionLogEntry = {
id: randomUUID(),
at: Date.now(),
level,
source,
message: sanitizeMessage(message)
}
const list = this.memory.get(extensionId) ?? []
list.push(entry)
if (list.length > MAX_ENTRIES_PER_EXTENSION)
list.splice(0, list.length - MAX_ENTRIES_PER_EXTENSION)
this.memory.set(extensionId, list)
this.appendToDisk(extensionId, entry)
return entry
}
list(extensionId: string, limit = MAX_ENTRIES_PER_EXTENSION): ExtensionLogEntry[] {
this.ensureLoaded(extensionId)
const list = this.memory.get(extensionId) ?? []
return list.slice(-Math.max(1, Math.min(limit, MAX_ENTRIES_PER_EXTENSION))).reverse()
}
clear(extensionId: string): void {
this.memory.set(extensionId, [])
this.loaded.add(extensionId)
fs.removeSync(this.filePath(extensionId))
fs.removeSync(`${this.filePath(extensionId)}.1`)
}
remove(extensionId: string): void {
this.memory.delete(extensionId)
this.loaded.delete(extensionId)
fs.removeSync(this.filePath(extensionId))
fs.removeSync(`${this.filePath(extensionId)}.1`)
}
private filePath(extensionId: string): string {
return path.join(this.logsDir, `${extensionId}.jsonl`)
}
private ensureLoaded(extensionId: string): void {
if (this.loaded.has(extensionId)) return
this.loaded.add(extensionId)
try {
const text = fs.readFileSync(this.filePath(extensionId), 'utf8')
const lines = text.split('\n').filter(Boolean).slice(-MAX_ENTRIES_PER_EXTENSION)
const entries: ExtensionLogEntry[] = []
for (const line of lines) {
try {
const raw = JSON.parse(line) as Partial<ExtensionLogEntry>
if (!raw || typeof raw !== 'object') continue
if (typeof raw.message !== 'string') continue
entries.push({
id: String(raw.id || randomUUID()),
at: Number(raw.at) || 0,
level: raw.level === 'warn' || raw.level === 'error' ? raw.level : 'info',
source: raw.source === 'extension' ? 'extension' : 'core',
message: sanitizeMessage(raw.message)
})
} catch {
// 单行损坏不影响其余日志。
}
}
this.memory.set(extensionId, entries)
} catch {
this.memory.set(extensionId, [])
}
}
private appendToDisk(extensionId: string, entry: ExtensionLogEntry): void {
try {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
const size = fs.statSync(filePath, { throwIfNoEntry: false })?.size ?? 0
if (size > MAX_FILE_BYTES) fs.moveSync(filePath, `${filePath}.1`, { overwrite: true })
fs.appendFileSync(filePath, `${JSON.stringify(entry)}\n`, 'utf8')
} catch {
// 日志写不进去不能影响扩展运行。
}
}
}
// eslint-disable-next-line no-control-regex -- 终端 ANSI 序列与控制字符要在落盘前剥掉
const ANSI_PATTERN = /\u001b\[[0-9;]*m/g
// eslint-disable-next-line no-control-regex -- 同上:日志里不允许出现不可见控制字符
const CONTROL_PATTERN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g
function sanitizeMessage(value: unknown): string {
const text = String(value ?? '')
.replace(ANSI_PATTERN, '')
.replace(CONTROL_PATTERN, '')
.trim()
return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text
}
+761
View File
@@ -0,0 +1,761 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { safeStorage } from 'electron'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import {
autoGrantedPermissions,
hasExtensionPermission,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import {
checkExtensionCompatibility,
parseExtensionManifest,
type ExtensionManifest
} from '../../shared/extensions/manifest'
import type {
ExtensionCapabilitySnapshot,
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageMethod,
ExtensionPageResponse,
InstalledExtension
} from '../../shared/extensions/types'
import type {
ExtensionAutomationActionOutput,
ExtensionMessagesQueryRequest,
ExtensionQueriedMessage,
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
import { ExtensionActionRegistry } from './extension-action-registry'
import { ExtensionEventBus } from './extension-event-bus'
import type { ExtensionEntitlementResult } from './extension-entitlement'
import {
ExtensionHost,
forkExtensionHost,
type ExtensionHostChild,
type ExtensionHostSpawnOptions
} from './extension-host'
import { ExtensionInstaller } from './extension-installer'
import { ExtensionLogStore } from './extension-log'
import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry'
import { ExtensionSendGateway } from './extension-send-gateway'
import { ExtensionStorage } from './extension-storage'
import type { ExtensionPaths } from './extension-paths'
export interface ExtensionManagerDependencies {
paths: ExtensionPaths
appVersion: string
platform?: NodeJS.Platform
spawn?: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
getCapability: () => Promise<PersonalWechatSendCapability>
checkEntitlement: () => Promise<ExtensionEntitlementResult>
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
queryMessages: (request: ExtensionMessagesQueryRequest) => Promise<ExtensionQueriedMessage[]>
/** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */
listGroups: () => Promise<Array<{ id: string; name: string }>>
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
getAccountId: () => string
getSelfUsernames: () => string[]
isDatabaseReady: () => boolean
now?: () => number
onChange?: (
extensionId: string,
reason: 'installed' | 'enabled' | 'disabled' | 'uninstalled' | 'runtime' | 'actions'
) => void
}
const PAGE_METHODS: ExtensionPageMethod[] = [
'storage.get',
'storage.set',
'storage.remove',
'storage.list',
'capabilities.get',
'contacts.listGroups',
'test.send',
'douyin.cookie.get',
'douyin.cookie.set',
'douyin.cookie.clear',
'extension.info'
]
/**
* 扩展系统的编排层。
*
* 职责边界:
* - **只做编排**:清单读取、安装、启停、进程托管、事件分发、能力转发;
* - 不实现消息监听(复用 `MessageListenerService`)、不实现发送(复用
* `WechatActionGateway`)、不实现自动化规则存储(复用 `AutomationRuleStore`)。
*
* 所有扩展代码都在 `ExtensionHost` 的子进程里运行;本类不 `require` 任何扩展文件。
*/
export class ExtensionManager {
private readonly dependencies: ExtensionManagerDependencies
private readonly paths: ExtensionPaths
private readonly registry: ExtensionRegistry
private readonly installer: ExtensionInstaller
private readonly storage: ExtensionStorage
private readonly logs: ExtensionLogStore
private readonly actions = new ExtensionActionRegistry()
private readonly sendGateway: ExtensionSendGateway
private readonly hosts = new Map<string, ExtensionHost>()
private readonly manifests = new Map<string, ExtensionManifest | null>()
private readonly eventBus: ExtensionEventBus
private readonly now: () => number
private initialized = false
constructor(dependencies: ExtensionManagerDependencies) {
this.dependencies = dependencies
this.paths = dependencies.paths
this.now = dependencies.now ?? (() => Date.now())
this.registry = new ExtensionRegistry({ registryFile: this.paths.registryFile, now: this.now })
this.installer = new ExtensionInstaller({
paths: this.paths,
registry: this.registry,
now: this.now
})
this.storage = new ExtensionStorage({ dataRoot: this.paths.dataDir })
this.logs = new ExtensionLogStore(this.paths.logsDir)
this.sendGateway = new ExtensionSendGateway({
getCapability: dependencies.getCapability,
checkEntitlement: dependencies.checkEntitlement,
executeAction: dependencies.executeAction,
getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId),
now: this.now
})
this.eventBus = new ExtensionEventBus({
listSubscribers: () => this.listEventSubscribers(),
getAccountId: dependencies.getAccountId,
getSelfUsernames: dependencies.getSelfUsernames,
now: this.now
})
}
/** 建立目录、加载状态、拉起已启用的扩展。单个扩展失败不影响其他扩展。 */
async initialize(): Promise<void> {
if (this.initialized) return
this.initialized = true
for (const directory of [
this.paths.extensionsDir,
this.paths.dataDir,
this.paths.stateDir,
this.paths.logsDir,
this.paths.stagingDir
]) {
fs.ensureDirSync(directory)
}
this.eventBus.setAccountId(this.dependencies.getAccountId())
for (const record of this.registry.list()) {
const manifest = this.readManifest(record.id)
if (!manifest) {
this.logs.append(record.id, 'error', 'core', '扩展文件缺失或 manifest 无法读取')
continue
}
this.syncDeclared(record.id, manifest)
if (!record.enabled) continue
const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
if (!compatibility.compatible) {
this.logs.append(record.id, 'error', 'core', compatibility.reason || '扩展不兼容')
continue
}
try {
await this.startHost(record.id, manifest)
} catch (error) {
this.logs.append(
record.id,
'error',
'core',
`扩展启动失败:${error instanceof Error ? error.message : String(error)}`
)
}
}
}
list(): InstalledExtension[] {
return this.registry
.list()
.map((record) => this.toInstalled(record))
.sort((left, right) => left.name.localeCompare(right.name))
}
get(extensionId: string): InstalledExtension | null {
const record = this.registry.get(extensionId)
if (!record) return null
return this.toInstalled(record)
}
getLogs(extensionId: string, limit = 100): ExtensionLogEntry[] {
return this.logs.list(extensionId, limit)
}
clearLogs(extensionId: string): void {
this.logs.clear(extensionId)
}
async installFromDirectory(directory: string): Promise<ExtensionInstallResult> {
return this.install(() =>
this.installer.installFromDirectory(directory, { appVersion: this.dependencies.appVersion })
)
}
async installFromPackage(packagePath: string): Promise<ExtensionInstallResult> {
return this.install(() =>
this.installer.installFromPackage(packagePath, {
appVersion: this.dependencies.appVersion,
source: 'package'
})
)
}
async setEnabled(extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
const manifest = this.readManifest(extensionId)
if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失'))
if (!enabled) {
await this.stopHost(extensionId)
this.registry.setEnabled(extensionId, false)
this.registry.setGrantedPermissions(extensionId, autoGrantedPermissions(manifest.permissions))
this.dependencies.onChange?.(extensionId, 'disabled')
return { success: true }
}
const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
if (!compatibility.compatible) {
return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', compatibility.reason))
}
this.registry.setEnabled(extensionId, true)
this.registry.setGrantedPermissions(extensionId, manifest.permissions)
this.syncDeclared(extensionId, manifest)
if (manifest.entrypoints.background) {
try {
await this.startHost(extensionId, manifest)
} catch {
// 启用状态保留:运行状态会显示为「错误」,用户可以查看日志后重新启用。
}
}
this.dependencies.onChange?.(extensionId, 'enabled')
return { success: true }
}
async uninstall(extensionId: string, keepData: boolean): Promise<ExtensionOperationResult> {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
await this.stopHost(extensionId)
this.actions.remove(extensionId)
this.manifests.delete(extensionId)
try {
await this.installer.uninstall(extensionId, { keepData })
} catch (error) {
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
}
if (!keepData) this.logs.remove(extensionId)
this.dependencies.onChange?.(extensionId, 'uninstalled')
return { success: true }
}
/** 页面地址。停用的扩展也允许打开自己的配置页(否则用户无法先配置再启用)。 */
pageUrl(extensionId: string, pageId?: string): ExtensionPageDescriptor {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
const manifest = this.readManifest(extensionId)
if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')
const page = pageId
? manifest.contributions.pages.find((item) => item.id === pageId)
: manifest.contributions.pages[0]
const entry = page?.entry || manifest.entrypoints.page
if (!entry) throw new ExtensionError('EXTENSION_NOT_FOUND', '扩展没有可打开的页面')
return {
extensionId,
pageId: page?.id || 'main',
title: page?.title || manifest.name,
url: `tm-extension://${extensionId}/${entry}`
}
}
/**
* 扩展页面可调用的能力。
*
* 页面**没有**发送 / 查询 / AI 权限:那些能力只从后台进程按权限申请。
* 页面与后台共享同一个 `storage` 命名空间,所以配置页保存的内容后台能直接读到。
*/
async pageRequest(
extensionId: string,
method: string,
params: Record<string, unknown> = {}
): Promise<ExtensionPageResponse> {
try {
if (!PAGE_METHODS.includes(method as ExtensionPageMethod)) {
throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`)
}
if (method.startsWith('douyin.cookie.') && extensionId !== 'com.example.douyin-sender') {
throw new ExtensionError('PERMISSION_DENIED', 'Cookie 能力不适用于此扩展')
}
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
const manifest = this.readManifest(extensionId)
if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')
if (!manifest.permissions.includes('storage') && method.startsWith('storage.')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 storage 权限')
}
if (method === 'contacts.listGroups' && !manifest.permissions.includes('contacts.list')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 contacts.list 权限')
}
switch (method as ExtensionPageMethod) {
case 'storage.get':
return { ok: true, result: this.storage.get(extensionId, params.key) }
case 'storage.set':
this.storage.set(extensionId, params.key, params.value)
return { ok: true, result: { ok: true } }
case 'storage.remove':
return { ok: true, result: { removed: this.storage.remove(extensionId, params.key) } }
case 'storage.list':
return { ok: true, result: { entries: this.storage.list(extensionId) } }
case 'capabilities.get':
return { ok: true, result: await this.buildCapabilitySnapshot(extensionId) }
case 'contacts.listGroups': {
const groups = await this.dependencies.listGroups()
return {
ok: true,
result: {
groups: groups
.filter((group) => group && group.id)
.map((group) => ({ id: group.id, name: group.name || group.id }))
.slice(0, 2_000)
}
}
}
case 'test.send': {
if (extensionId !== 'com.example.douyin-sender') {
throw new ExtensionError('PERMISSION_DENIED', '测试能力不适用于此扩展')
}
const host = this.hosts.get(extensionId)
if (!host) throw new ExtensionError('EXTENSION_DISABLED')
const cookieHeader = String(params.cookieHeader || '') || this.readDouyinCookie()
try {
return { ok: true, result: await host.testSend({ ...params, cookieHeader }) }
} finally {
params.cookieHeader = ''
}
}
case 'douyin.cookie.get':
return { ok: true, result: { configured: Boolean(this.readDouyinCookie()) } }
case 'douyin.cookie.set': {
const value = String(params.cookieHeader || '').trim()
if (!value) throw new ExtensionError('INVALID_REQUEST', 'Cookie 不能为空')
if (!safeStorage.isEncryptionAvailable())
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '系统安全存储不可用')
fs.writeFileSync(
path.join(this.paths.userData, 'douyin-cookie.bin'),
safeStorage.encryptString(value),
{ mode: 0o600 }
)
fs.chmodSync(path.join(this.paths.userData, 'douyin-cookie.bin'), 0o600)
this.syncDouyinCookieToExtensionData(value)
return { ok: true, result: { configured: true } }
}
case 'douyin.cookie.clear':
this.clearDouyinCookie()
return { ok: true, result: { configured: false } }
case 'extension.info':
return {
ok: true,
result: {
id: manifest.id,
name: manifest.name,
version: manifest.version,
enabled: record.enabled
}
}
default:
throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`)
}
} catch (error) {
return { ok: false, error: toExtensionErrorPayload(error) }
}
}
handleMessage(message: NormalizedIncomingMessage): void {
this.eventBus.setAccountId(this.dependencies.getAccountId())
this.eventBus.handleMessage(message)
}
private syncDouyinCookieToExtensionData(value: string): void {
try {
const dataDir = this.paths.extensionDataDir('com.example.douyin-sender')
fs.ensureDirSync(dataDir)
const target = path.join(dataDir, 'douyin-cookie.txt')
fs.writeFileSync(target, value, { mode: 0o600 })
fs.chmodSync(target, 0o600)
} catch {
// 扩展数据目录同步失败不影响加密主存储。
}
}
private readDouyinCookie(): string {
const file = path.join(this.paths.userData, 'douyin-cookie.bin')
if (fs.existsSync(file) && safeStorage.isEncryptionAvailable()) {
try {
const decrypted = safeStorage.decryptString(fs.readFileSync(file)).trim()
if (decrypted) {
this.syncDouyinCookieToExtensionData(decrypted)
return decrypted
}
} catch {
// 加密文件损坏或不可解密时继续尝试桌面 Cookie 文件。
}
}
const desktopCookie = path.join(os.homedir(), 'Desktop', 'douyin-cookie')
if (fs.existsSync(desktopCookie)) {
try {
return fs.readFileSync(desktopCookie, 'utf8').trim()
} catch {
return ''
}
}
return ''
}
private clearDouyinCookie(): void {
try {
fs.removeSync(path.join(this.paths.userData, 'douyin-cookie.bin'))
fs.removeSync(
path.join(this.paths.extensionDataDir('com.example.douyin-sender'), 'douyin-cookie.txt')
)
} catch {
throw new ExtensionError('INVALID_REQUEST', '无法清除抖音 Cookie')
}
}
setAccountId(accountId: string): void {
this.eventBus.setAccountId(accountId)
}
/** 自动化动作执行入口。由 `AutomationActionRunner` 调用。 */
async invokeAutomationAction(
extensionId: string,
actionId: string,
input: Record<string, unknown>,
timeoutMs?: number
): Promise<ExtensionAutomationActionOutput> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 automation.action 权限')
}
const host = this.hosts.get(extensionId)
if (!host) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
if (!this.actions.isRegistered(extensionId, actionId)) {
throw new ExtensionError('ACTION_FAILED', '扩展没有注册该动作')
}
return host.invokeAction(actionId, input, timeoutMs)
}
getActions(): ReturnType<ExtensionActionRegistry['list']> {
return this.actions.list()
}
async dispose(): Promise<void> {
const ids = Array.from(this.hosts.keys())
await Promise.all(ids.map((id) => this.stopHost(id)))
}
private async install(
run: () => Promise<{ manifest: ExtensionManifest; upgraded: boolean; previousVersion?: string }>
): Promise<ExtensionInstallResult> {
let outcome: Awaited<ReturnType<typeof run>>
try {
outcome = await run()
} catch (error) {
return { success: false, error: toExtensionErrorPayload(error) }
}
const { manifest } = outcome
const wasEnabled = this.registry.get(manifest.id)?.enabled === true
if (wasEnabled) await this.stopHost(manifest.id)
this.manifests.delete(manifest.id)
this.manifests.set(manifest.id, manifest)
this.syncDeclared(manifest.id, manifest)
// 新安装只自动授予低风险权限;升级保留用户已经授予的集合。
if (!outcome.upgraded) {
this.registry.setGrantedPermissions(manifest.id, autoGrantedPermissions(manifest.permissions))
}
this.logs.append(
manifest.id,
'info',
'core',
outcome.upgraded
? `扩展已更新:${outcome.previousVersion ?? '?'} → ${manifest.version}`
: `扩展已安装:${manifest.version}`
)
this.dependencies.onChange?.(manifest.id, 'installed')
if (wasEnabled && manifest.entrypoints.background) {
await this.startHost(manifest.id, manifest).catch(() => undefined)
}
const installed = this.get(manifest.id)
return { success: true, ...(installed ? { extension: installed } : {}) }
}
private async startHost(extensionId: string, manifest: ExtensionManifest): Promise<void> {
if (!manifest.entrypoints.background) return
await this.stopHost(extensionId)
const host = new ExtensionHost({
extensionId,
extensionDir: this.paths.installDir(extensionId),
dataDir: this.paths.extensionDataDir(extensionId),
permissions: this.registry.get(extensionId)?.grantedPermissions ?? [],
storage: this.storage,
spawn: this.dependencies.spawn ?? this.defaultSpawn(),
onLog: (level, message) => {
this.logs.append(extensionId, level, 'core', message)
if (level === 'error') this.dependencies.onChange?.(extensionId, 'runtime')
},
onStateChange: () => this.dependencies.onChange?.(extensionId, 'runtime'),
onActionsChanged: () => {
this.syncRegisteredActions(extensionId, manifest.name)
this.dependencies.onChange?.(extensionId, 'actions')
},
queryMessages: (id, request) => this.queryMessages(id, request),
sendText: (id, request) => this.sendText(id, request),
sendImage: (id, request) => this.sendImage(id, request),
sendVideo: (id, request) => this.sendVideo(id, request),
aiChat: (_id, messages) => this.dependencies.aiChat(messages),
capabilities: (id) => this.buildCapabilitySnapshot(id)
})
this.hosts.set(extensionId, host)
await host.start()
}
private async stopHost(extensionId: string): Promise<void> {
const host = this.hosts.get(extensionId)
if (!host) return
this.hosts.delete(extensionId)
await host.stop()
this.actions.removeRuntime(extensionId)
}
private defaultSpawn(): (options: ExtensionHostSpawnOptions) => ExtensionHostChild {
// electron-vite 把主进程入口输出到 out/main,扩展宿主脚本与它同级。
return forkExtensionHost(path.join(__dirname, 'extensionHost.js'))
}
private syncDeclared(extensionId: string, manifest: ExtensionManifest): void {
this.actions.setDeclared(extensionId, manifest.name, manifest.contributions.automationActions)
}
private syncRegisteredActions(extensionId: string, extensionName: string): void {
const host = this.hosts.get(extensionId)
this.actions.setRegistered(extensionId, extensionName, host?.registeredActions() ?? [])
}
private listEventSubscribers(): Array<{
extensionId: string
subscriptions: ExtensionManifest['subscriptions']
deliver: (
envelope: Parameters<ExtensionEventBus['handleMessage']>[0] extends never
? never
: import('../../shared/extensions/events').ExtensionEventEnvelope
) => boolean
}> {
const subscribers: Array<{
extensionId: string
subscriptions: ExtensionManifest['subscriptions']
deliver: (
envelope: import('../../shared/extensions/events').ExtensionEventEnvelope
) => boolean
}> = []
for (const [extensionId, host] of this.hosts) {
const record = this.registry.get(extensionId)
const manifest = this.manifests.get(extensionId)
if (!record?.enabled || !manifest) continue
if (!hasExtensionPermission(record.grantedPermissions, 'messages.subscribe')) continue
if (host.snapshot().state !== 'active') continue
subscribers.push({
extensionId,
subscriptions: manifest.subscriptions,
deliver: (envelope) => host.deliverEvent(envelope)
})
}
return subscribers
}
private async queryMessages(
extensionId: string,
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
if (!this.dependencies.isDatabaseReady()) {
throw new ExtensionError('DATABASE_NOT_READY')
}
const conversationId = String(request?.conversationId || '').trim()
if (!conversationId || conversationId.length > 128) {
throw new ExtensionError('INVALID_REQUEST', '会话 id 不合法')
}
const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 200))
const startTime = Number.isFinite(Number(request?.startTime))
? Number(request.startTime)
: Date.now() - 24 * 60 * 60 * 1000
const endTime = Number.isFinite(Number(request?.endTime)) ? Number(request.endTime) : Date.now()
if (endTime <= startTime) throw new ExtensionError('INVALID_REQUEST', '时间范围不合法')
if (endTime - startTime > 7 * 24 * 60 * 60 * 1000) {
throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 7 天')
}
const record = this.registry.get(extensionId)
if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED')
return this.dependencies.queryMessages({
conversationId,
startTime,
endTime,
limit
})
}
private async sendText(
extensionId: string,
request: ExtensionSendTextRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendText(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async sendImage(
extensionId: string,
request: ExtensionSendImageRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendImage(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async sendVideo(
extensionId: string,
request: ExtensionSendVideoRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendVideo(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async buildCapabilitySnapshot(extensionId: string): Promise<ExtensionCapabilitySnapshot> {
const record = this.registry.get(extensionId)
const granted = record?.grantedPermissions ?? []
const capability = await this.dependencies.getCapability().catch(() => null)
let licensed = false
if (hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text')) {
const entitlement = await this.dependencies.checkEntitlement().catch(() => null)
licensed = entitlement?.ok === true
}
return {
extensionId,
enabled: record?.enabled === true,
permissions: [...granted],
platform: this.dependencies.platform ?? process.platform,
databaseReady: this.dependencies.isDatabaseReady(),
send: {
supported: Boolean(capability?.supported),
ready: Boolean(capability?.ready),
canSendText: Boolean(capability?.capabilities?.text),
canSendImage: Boolean(capability?.capabilities?.image),
canSendVideo: Boolean(capability?.capabilities?.video),
licensed,
message: capability?.message || '暂时无法获知微信发送能力'
},
ai: {
configured: false,
modelName: ''
}
}
}
private toInstalled(record: ExtensionRegistryRecord): InstalledExtension {
const manifest = this.readManifest(record.id)
const compatibility = manifest
? checkExtensionCompatibility(manifest, this.dependencies.appVersion)
: { compatible: false, code: 'manifest' as const, reason: '扩展文件缺失或 manifest 无法读取' }
const host = this.hosts.get(record.id)
const runtime = host
? host.snapshot()
: {
state: record.enabled ? ('active' as const) : ('inactive' as const),
since: record.updatedAt,
restarts: 0
}
return {
id: record.id,
name: manifest?.name || record.id,
version: manifest?.version || record.version,
apiVersion: manifest?.apiVersion || record.apiVersion,
...(manifest?.minAppVersion ? { minAppVersion: manifest.minAppVersion } : {}),
...(manifest?.description ? { description: manifest.description } : {}),
...(manifest?.author ? { author: manifest.author } : {}),
enabled: record.enabled,
installedAt: record.installedAt,
updatedAt: record.updatedAt,
compatibility,
permissions: manifest?.permissions ?? [],
grantedPermissions: record.grantedPermissions,
runtime,
pages: (manifest?.contributions.pages ?? []).map((page) => ({
id: page.id,
title: page.title
})),
automationActions: this.actions.summariesFor(record.id),
filesPresent: Boolean(manifest)
}
}
private readManifest(extensionId: string): ExtensionManifest | null {
if (this.manifests.has(extensionId)) return this.manifests.get(extensionId) ?? null
const file = path.join(this.paths.installDir(extensionId), 'manifest.json')
let manifest: ExtensionManifest | null = null
try {
const parsed = parseExtensionManifest(fs.readJsonSync(file) as unknown)
manifest = parsed.ok ? (parsed.manifest ?? null) : null
} catch {
manifest = null
}
this.manifests.set(extensionId, manifest)
return manifest
}
}
function failure(error: unknown): ExtensionOperationResult {
const payload = toExtensionErrorPayload(error)
return { success: false, error: payload }
}
+65
View File
@@ -0,0 +1,65 @@
import path from 'node:path'
import { app } from 'electron'
/**
* 扩展相关目录的唯一解析器。
*
* **所有扩展文件都在 `userData` 下**,与安装目录 / `app.asar` / 源码树完全分离:
* 官方升级只替换应用本体,不会碰这三个目录。Windows 与 macOS 的差异由
* `app.getPath('userData')` 吸收,调用方不假设任何绝对路径。
*
* ```text
* <userData>/extensions/<id>/ 扩展代码(manifest + ui + background)
* <userData>/extensions-data/<id>/ 扩展私有数据(配置、缓存)
* <userData>/extensions-state/ 宿主状态(registry、日志)
* <userData>/extensions-staging/ 安装临时目录(成功后原子改名,不留半装状态)
* ```
*/
export interface ExtensionPaths {
userData: string
extensionsDir: string
dataDir: string
stateDir: string
stagingDir: string
registryFile: string
logsDir: string
installDir: (extensionId: string) => string
extensionDataDir: (extensionId: string) => string
logFile: (extensionId: string) => string
stagingPath: (prefix: string) => string
}
export function createExtensionPaths(userData: string): ExtensionPaths {
const extensionsDir = path.join(userData, 'extensions')
const dataDir = path.join(userData, 'extensions-data')
const stateDir = path.join(userData, 'extensions-state')
const stagingDir = path.join(userData, 'extensions-staging')
const logsDir = path.join(stateDir, 'logs')
return {
userData,
extensionsDir,
dataDir,
stateDir,
stagingDir,
registryFile: path.join(stateDir, 'registry.json'),
logsDir,
installDir: (extensionId) => path.join(extensionsDir, extensionId),
extensionDataDir: (extensionId) => path.join(dataDir, extensionId),
logFile: (extensionId) => path.join(logsDir, `${extensionId}.jsonl`),
stagingPath: (prefix) => path.join(stagingDir, `${prefix}-${Date.now().toString(36)}`)
}
}
let cached: ExtensionPaths | null = null
/** 懒解析:`app.getPath` 必须在 app ready 之后才可靠。 */
export function getExtensionPaths(): ExtensionPaths {
if (!cached) cached = createExtensionPaths(app.getPath('userData'))
return cached
}
/** 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 */
export function isPathInside(parent: string, child: string): boolean {
const relative = path.relative(path.resolve(parent), path.resolve(child))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
+101
View File
@@ -0,0 +1,101 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { protocol } from 'electron'
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside, type ExtensionPaths } from './extension-paths'
export const EXTENSION_SCHEME = 'tm-extension'
const MIME_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.wasm': 'application/wasm'
}
/**
* 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在
* 扩展目录内;响应带严格 CSP(无外链、无内联脚本、无网络)。
*
* `registerSchemesAsPrivileged` 必须在 app ready 前调用。
*/
export function registerExtensionScheme(): void {
protocol.registerSchemesAsPrivileged([
{
scheme: EXTENSION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
stream: true
}
}
])
}
export function installExtensionProtocolHandler(paths: ExtensionPaths): void {
protocol.handle(EXTENSION_SCHEME, async (request) => {
try {
const url = new URL(request.url)
const extensionId = url.hostname.toLowerCase()
if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return notFound()
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '')
if (!isSafeRelativeEntryPath(relative)) return notFound()
const root = paths.installDir(extensionId)
const resolved = path.resolve(root, relative)
if (!isPathInside(root, resolved)) return notFound()
const realRoot = await fs.realpath(root).catch(() => null)
const realFile = await fs.realpath(resolved).catch(() => null)
if (!realRoot || !realFile) return notFound()
if (!isPathInside(realRoot, realFile)) return notFound()
const stat = await fs.stat(realFile)
if (!stat.isFile() || stat.size > 20 * 1024 * 1024) return notFound()
const body = await fs.readFile(realFile)
const contentType =
MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream'
return new Response(body, {
status: 200,
headers: {
'Content-Type': contentType,
'Content-Security-Policy': [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"font-src 'self' data:",
"connect-src 'none'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'"
].join('; '),
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-store'
}
})
} catch {
return notFound()
}
})
}
function notFound(): Response {
return new Response('Not found', {
status: 404,
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
})
}
+155
View File
@@ -0,0 +1,155 @@
import fs from 'fs-extra'
import path from 'node:path'
import {
normalizeExtensionPermissions,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
/**
* 宿主侧的扩展安装状态。
*
* **manifest 不是状态的一部分**:它以扩展目录里的 `manifest.json` 为准,
* 升级扩展只替换目录、不动这里的启用状态与权限授予。
*/
export interface ExtensionRegistryRecord {
id: string
version: string
apiVersion: string
enabled: boolean
grantedPermissions: ExtensionPermission[]
installedAt: number
updatedAt: number
source: 'directory' | 'package'
}
interface RegistryFile {
version: number
extensions: ExtensionRegistryRecord[]
}
const REGISTRY_VERSION = 1
function normalizeRecord(value: unknown): ExtensionRegistryRecord | null {
if (!value || typeof value !== 'object') return null
const raw = value as Partial<ExtensionRegistryRecord>
const id = String(raw.id || '').trim()
if (!id) return null
const installedAt = Number(raw.installedAt) || 0
return {
id,
version: String(raw.version || '0.0.0'),
apiVersion: String(raw.apiVersion || EXTENSION_API_VERSION),
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
enabled: raw.enabled === true,
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
installedAt,
updatedAt: Number(raw.updatedAt) || installedAt,
source: raw.source === 'package' ? 'package' : 'directory'
}
}
export interface ExtensionRegistryDependencies {
registryFile: string
now?: () => number
}
export class ExtensionRegistry {
private readonly registryFile: string
private readonly now: () => number
private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] }
private loaded = false
constructor(dependencies: ExtensionRegistryDependencies) {
this.registryFile = dependencies.registryFile
this.now = dependencies.now ?? (() => Date.now())
}
list(): ExtensionRegistryRecord[] {
this.ensureLoaded()
return this.state.extensions.map((record) => ({
...record,
grantedPermissions: [...record.grantedPermissions]
}))
}
get(id: string): ExtensionRegistryRecord | undefined {
const key = String(id || '').trim()
if (!key) return undefined
return this.list().find((record) => record.id === key)
}
upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord {
this.ensureLoaded()
const exists = this.state.extensions.some((item) => item.id === record.id)
const next = exists
? this.state.extensions.map((item) => (item.id === record.id ? record : item))
: [...this.state.extensions, record]
this.commit(next)
return { ...record, grantedPermissions: [...record.grantedPermissions] }
}
remove(id: string): boolean {
this.ensureLoaded()
const next = this.state.extensions.filter((item) => item.id !== id)
if (next.length === this.state.extensions.length) return false
this.commit(next)
return true
}
setEnabled(id: string, enabled: boolean): ExtensionRegistryRecord | undefined {
const current = this.get(id)
if (!current) return undefined
return this.upsert({ ...current, enabled, updatedAt: this.now() })
}
setGrantedPermissions(
id: string,
permissions: ExtensionPermission[]
): ExtensionRegistryRecord | undefined {
const current = this.get(id)
if (!current) return undefined
return this.upsert({
...current,
grantedPermissions: normalizeExtensionPermissions(permissions),
updatedAt: this.now()
})
}
private ensureLoaded(): void {
if (this.loaded) return
this.loaded = true
try {
const raw = fs.readJsonSync(this.registryFile) as unknown
if (!raw || typeof raw !== 'object') return
const list = (raw as { extensions?: unknown }).extensions
if (!Array.isArray(list)) return
this.state = {
version: REGISTRY_VERSION,
extensions: list
.map((item) => normalizeRecord(item))
.filter((item): item is ExtensionRegistryRecord => item !== null)
}
} catch {
// 文件不存在 / 损坏都按「没有装过扩展」处理,不阻塞应用启动。
}
}
private commit(extensions: ExtensionRegistryRecord[]): void {
const previous = this.state
this.state = { version: REGISTRY_VERSION, extensions }
try {
this.persist()
} catch (error) {
this.state = previous
throw error
}
}
private persist(): void {
fs.ensureDirSync(path.dirname(this.registryFile))
const temporary = `${this.registryFile}.tmp`
fs.writeJsonSync(temporary, this.state, { spaces: 2 })
fs.moveSync(temporary, this.registryFile, { overwrite: true })
}
}
@@ -0,0 +1,358 @@
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import {
hasExtensionPermission,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import type {
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { ExtensionEntitlementResult } from './extension-entitlement'
import { isPathInside } from './extension-paths'
const MAX_TEXT_LENGTH = 2_000
const MAX_RECIPIENT_LENGTH = 128
const MAX_MEDIA_BYTES = 100 * 1024 * 1024
const SEND_INTERVAL_MS = 2_000
const SEND_WINDOW_MS = 60_000
const SEND_WINDOW_LIMIT = 10
/** 原生发送端把视频按 `type: 'video'` 提交,这里只放行常见容器。 */
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'])
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v'])
export interface ExtensionSendContext {
extensionId: string
permissions: ExtensionPermission[]
/** manifest 声明的会话范围;空数组表示不限制。 */
conversationScope: string[]
}
export interface ExtensionSendGatewayDependencies {
getCapability: () => Promise<PersonalWechatSendCapability>
checkEntitlement: () => Promise<ExtensionEntitlementResult>
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
/** 扩展数据目录;媒体文件只允许从这里或系统临时目录发送。 */
getExtensionDataRoot?: (extensionId: string) => string
now?: () => number
}
/**
* 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。
*
* origin、purpose、triggerType、幂等键全部由宿主填写,扩展只描述
* 「发给谁、发什么」。
*/
export class ExtensionSendGateway {
private readonly getCapability: () => Promise<PersonalWechatSendCapability>
private readonly checkEntitlement: () => Promise<ExtensionEntitlementResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly getExtensionDataRoot: (extensionId: string) => string
private readonly now: () => number
private readonly sendHistory = new Map<string, number[]>()
constructor(dependencies: ExtensionSendGatewayDependencies) {
this.getCapability = dependencies.getCapability
this.checkEntitlement = dependencies.checkEntitlement
this.executeAction = dependencies.executeAction
this.getExtensionDataRoot = dependencies.getExtensionDataRoot ?? (() => '')
this.now = dependencies.now ?? (() => Date.now())
}
async sendText(
context: ExtensionSendContext,
request: ExtensionSendTextRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.text')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.text 权限')
}
const to = String(request?.to || '').trim()
const text = String(request?.text || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (!text || text.length > MAX_TEXT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '发送内容不能为空且不能超过 2000 字')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const at = normalizeAt(request?.at, to)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.text) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '个人微信发送能力尚未就绪'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'text', text, ...(at ? { at } : {}) },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/**
* 发送图片。
*
* 文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件,
* 否则扩展就能借 TraceMemo 把本机任意文件发出去。
*/
async sendImage(
context: ExtensionSendContext,
request: ExtensionSendImageRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.image')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.image 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const mediaPath = assertSendableMediaPath(
request?.path,
this.getExtensionDataRoot(context.extensionId),
IMAGE_EXTENSIONS
)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.image) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '个人微信发送能力尚未就绪'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'image', path: mediaPath },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/**
* 发送视频。
*
* 与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。
* 文件边界与图片相同(扩展数据目录 / 临时目录、普通文件、≤ 100MB)。
*/
async sendVideo(
context: ExtensionSendContext,
request: ExtensionSendVideoRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.video')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.video 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const mediaPath = assertSendableMediaPath(
request?.path,
this.getExtensionDataRoot(context.extensionId),
VIDEO_EXTENSIONS
)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.video) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '当前微信发送能力不支持视频'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'video', path: mediaPath },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/** 令牌窗口:同一扩展 60 秒内最多 10 条,且两条之间至少 2 秒。 */
private assertRateLimit(extensionId: string): void {
const now = this.now()
const history = (this.sendHistory.get(extensionId) ?? []).filter(
(timestamp) => now - timestamp < SEND_WINDOW_MS
)
const last = history[history.length - 1]
if (last !== undefined && now - last < SEND_INTERVAL_MS) {
throw new ExtensionError('RATE_LIMITED', '发送过于频繁,请稍后再试')
}
if (history.length >= SEND_WINDOW_LIMIT) {
throw new ExtensionError('RATE_LIMITED', '已达到每分钟发送上限')
}
history.push(now)
this.sendHistory.set(extensionId, history)
}
}
/**
* 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件。
*
* 用 realpath 复核,符号链接跳到目录外同样会被拒绝;这一层不能省,
* 否则 `wechat.send.image` 就等价于「读取并外发任意本机文件」。
*/
function assertSendableMediaPath(value: unknown, dataRoot: string, allowed: Set<string>): string {
const raw = String(value ?? '').trim()
if (!raw || raw.length > 4_096) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径不合法')
}
if (!path.isAbsolute(raw)) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是绝对路径')
}
let realPath: string
try {
realPath = fs.realpathSync(raw)
} catch {
throw new ExtensionError('INVALID_REQUEST', '媒体文件不存在')
}
const stat = fs.statSync(realPath)
if (!stat.isFile()) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是普通文件')
}
if (stat.size <= 0 || stat.size > MAX_MEDIA_BYTES) {
throw new ExtensionError('INVALID_REQUEST', '媒体文件为空或超过 100MB')
}
const extension = path.extname(realPath).toLowerCase()
if (!allowed.has(extension)) {
throw new ExtensionError('SEND_NOT_SUPPORTED', `不支持发送 ${extension || '无扩展名'} 文件`)
}
const roots = [dataRoot, os.tmpdir()]
.filter(Boolean)
.map((root) => {
try {
return fs.realpathSync(root)
} catch {
return ''
}
})
.filter(Boolean)
if (!roots.some((root) => isPathInside(root, realPath))) {
throw new ExtensionError('PERMISSION_DENIED', '只能发送扩展数据目录或临时目录中的文件')
}
return realPath
}
function normalizeAt(value: unknown, recipientId: string): Record<string, string> | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
if (!recipientId.endsWith('@chatroom')) return undefined
const entries = Object.entries(value as Record<string, unknown>)
if (!entries.length || entries.length > 50) return undefined
const result: Record<string, string> = {}
for (const [wxid, name] of entries) {
const key = String(wxid).trim()
if (!key || typeof name !== 'string' || !name.trim()) continue
result[key] = name.trim()
}
return Object.keys(result).length ? result : undefined
}
/** 扩展提供的去重键只作为后缀,前缀固定,避免与官方自动化幂等键串台。 */
export function extensionIdempotencyKey(extensionId: string, dedupeKey: string): string {
const digest = createHash('sha1')
.update(`${extensionId}\u0001${String(dedupeKey).trim()}`)
.digest('hex')
return `extension:${extensionId}:${digest}`
}
function mapGatewayError(
code: string | undefined
): 'CAPABILITY_UNAVAILABLE' | 'PERMISSION_DENIED' | 'ACTION_FAILED' | 'INVALID_REQUEST' {
switch (code) {
case 'SEND_CAPABILITY_UNAVAILABLE':
case 'SEND_NOT_READY':
return 'CAPABILITY_UNAVAILABLE'
case 'ACTION_NOT_ALLOWED':
case 'RECIPIENT_SCOPE_VIOLATION':
return 'PERMISSION_DENIED'
case 'INVALID_REQUEST':
case 'INVALID_RECIPIENT':
return 'INVALID_REQUEST'
default:
return 'ACTION_FAILED'
}
}
+128
View File
@@ -0,0 +1,128 @@
import { AIProviderService } from '../services/ai-provider-service'
import {
getChatDb,
getSelfAccountInfo,
isReady,
listContacts,
listMessagesAsync,
resolveMd5
} from '../services/chat-service'
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
import { wechatActionGateway } from '../services/wechat-action-gateway'
import { ExtensionError } from '../../shared/extensions/errors'
import type {
ExtensionMessagesQueryRequest,
ExtensionQueriedMessage
} from '../../shared/extensions/rpc'
import { checkExtensionSendEntitlement } from './extension-entitlement'
import { ExtensionManager } from './extension-manager'
import { getExtensionPaths } from './extension-paths'
let manager: ExtensionManager | null = null
export interface ExtensionSystemOptions {
appVersion: string
onChange: (extensionId: string, reason: string) => void
}
/**
* 扩展系统的主进程接线。
*
* 这里只做依赖注入:所有能力都来自既有服务,扩展系统自己不实现第二套
* 消息监听、发送通道或 AI Provider。
*/
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
if (manager) return
manager = new ExtensionManager({
paths: getExtensionPaths(),
appVersion: options.appVersion,
getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(),
checkEntitlement: () => checkExtensionSendEntitlement(),
executeAction: (request) => wechatActionGateway.execute(request),
queryMessages: queryConversationMessages,
listGroups: async () => {
try {
return listContacts()
.filter((contact) => contact.type === 'group')
.map((contact) => ({
id: contact.m_nsUsrName,
name: contact.m_nsNickName || contact.m_nsUsrName
}))
} catch {
return []
}
},
aiChat: chatWithConfiguredProvider,
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
getSelfUsernames: () => {
try {
return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean)
} catch {
return []
}
},
isDatabaseReady: () => {
try {
return isReady()
} catch {
return false
}
},
onChange: (extensionId, reason) => options.onChange(extensionId, reason)
})
await manager.initialize()
}
export function getExtensionManager(): ExtensionManager {
if (!manager) throw new Error('扩展系统尚未初始化')
return manager
}
export function hasExtensionManager(): boolean {
return manager !== null
}
export async function disposeExtensionSystem(): Promise<void> {
const current = manager
manager = null
if (current) await current.dispose()
}
async function queryConversationMessages(
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
const contact = resolveMd5(request.conversationId)
if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接')
const messages = await listMessagesAsync(
contact.md5,
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
Math.floor((request.endTime ?? Date.now()) / 1000),
{ limit: request.limit ?? 50 },
'',
'unknown'
)
return messages.map((message) => ({
messageId: message.serverId || String(message.localId ?? message.id),
conversationId: request.conversationId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.name ? { senderName: message.name } : {}),
isSelf: message.isSender === true,
type: message.type,
...(message.type === 'text' ? { text: message.content } : {}),
timestamp: Math.round((message.createTime ?? 0) * 1000)
}))
}
async function chatWithConfiguredProvider(
messages: Array<{ role: string; content: string }>
): Promise<{ text: string }> {
const result = await new AIProviderService().chat(messages)
if (!result.success) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 调用失败')
}
return { text: result.data || '' }
}
export function extensionManagerForTests(value: ExtensionManager | null): void {
manager = value
}
+142
View File
@@ -0,0 +1,142 @@
import fs from 'fs-extra'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
const STORAGE_FILE = 'storage.json'
const STORAGE_VERSION = 1
const MAX_KEY_LENGTH = 64
const MAX_VALUE_BYTES = 256 * 1024
const MAX_TOTAL_BYTES = 1024 * 1024
const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/
interface StorageFile {
version: number
values: Record<string, unknown>
}
export interface ExtensionStorageDependencies {
/** 通常是 `<userData>/extensions-data`。 */
dataRoot: string
maxTotalBytes?: number
maxValueBytes?: number
}
/**
* 扩展私有的键值存储。
*
* 边界:
* - 每个扩展一个独立目录,键空间互不可见;
* - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**;
* - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。
*/
export class ExtensionStorage {
private readonly dataRoot: string
private readonly maxTotalBytes: number
private readonly maxValueBytes: number
constructor(dependencies: ExtensionStorageDependencies) {
this.dataRoot = dependencies.dataRoot
this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES
this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES
}
filePath(extensionId: string): string {
return path.join(this.dataRoot, extensionId, STORAGE_FILE)
}
directory(extensionId: string): string {
return path.join(this.dataRoot, extensionId)
}
get(extensionId: string, key: unknown): unknown {
const name = assertKey(key)
const values = this.read(extensionId).values
return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined
}
set(extensionId: string, key: unknown, value: unknown): void {
const name = assertKey(key)
const serialized = serializeValue(value)
if (Buffer.byteLength(serialized, 'utf8') > this.maxValueBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限')
}
const file = this.read(extensionId)
file.values[name] = JSON.parse(serialized)
this.assertTotalSize(file)
this.write(extensionId, file)
}
remove(extensionId: string, key: unknown): boolean {
const name = assertKey(key)
const file = this.read(extensionId)
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
delete file.values[name]
this.write(extensionId, file)
return true
}
list(extensionId: string): Array<{ key: string; value: unknown }> {
const values = this.read(extensionId).values
return Object.keys(values).map((key) => ({ key, value: clone(values[key]) }))
}
clear(extensionId: string): void {
this.write(extensionId, { version: STORAGE_VERSION, values: {} })
}
private read(extensionId: string): StorageFile {
const filePath = this.filePath(extensionId)
try {
const raw = fs.readJsonSync(filePath) as unknown
if (!raw || typeof raw !== 'object') return { version: STORAGE_VERSION, values: {} }
const values = (raw as { values?: unknown }).values
if (!values || typeof values !== 'object' || Array.isArray(values)) {
return { version: STORAGE_VERSION, values: {} }
}
return { version: STORAGE_VERSION, values: values as Record<string, unknown> }
} catch {
return { version: STORAGE_VERSION, values: {} }
}
}
private write(extensionId: string, file: StorageFile): void {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
const temporary = `${filePath}.tmp`
fs.writeJsonSync(temporary, file, { spaces: 2 })
fs.moveSync(temporary, filePath, { overwrite: true })
}
private assertTotalSize(file: StorageFile): void {
const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8')
if (bytes > this.maxTotalBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '扩展存储总量超出上限')
}
}
}
function assertKey(value: unknown): string {
if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '存储键必须是字符串')
const key = value.trim()
if (!KEY_PATTERN.test(key)) {
throw new ExtensionError('INVALID_REQUEST', '存储键只能包含字母、数字、点、下划线与短横线')
}
if (key.length > MAX_KEY_LENGTH) throw new ExtensionError('INVALID_REQUEST', '存储键过长')
return key
}
function serializeValue(value: unknown): string {
if (value === undefined) throw new ExtensionError('INVALID_REQUEST', '不能存储 undefined')
try {
const serialized = JSON.stringify(value)
if (serialized === undefined) throw new Error('unsupported')
return serialized
} catch {
throw new ExtensionError('INVALID_REQUEST', '存储值必须可序列化为 JSON')
}
}
function clone<T>(value: T): T {
if (value === null || typeof value !== 'object') return value
return JSON.parse(JSON.stringify(value)) as T
}
+545
View File
@@ -0,0 +1,545 @@
/**
* 扩展后台进程入口。
*
* 这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、
* 把请求转成白名单 RPC。任何 `require` 都只发生在这里,主进程永远不会加载
* 第三方扩展代码。
*
* 与主进程的协议见 `src/shared/extensions/rpc.ts`。
*/
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
type ExtensionHostActivate,
type ExtensionHostCall,
type ExtensionHostCallResult,
type ExtensionHostEvent,
type ExtensionHostInboundMessage,
type ExtensionHostInvokeAction,
type ExtensionHostTestSend,
type ExtensionHostOutboundMessage,
type ExtensionHostRegisterAction
} from '../../shared/extensions/rpc'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
type MessageHandler = (event: ExtensionMessageEvent) => void | Promise<void>
interface RegisteredActionDefinition {
id: string
title: string
description?: string
inputSchema?: Record<string, unknown>
handler: (input: Record<string, unknown>) => unknown
}
interface PendingCall {
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
const pendingCalls = new Map<string, PendingCall>()
const eventHandlers = new Set<MessageHandler>()
const actions = new Map<string, RegisteredActionDefinition>()
let permissions: string[] = []
let activated = false
let extensionDir = ''
let extensionDataDir = ''
let extensionId = process.env.TM_EXTENSION_ID || ''
function post(message: ExtensionHostOutboundMessage): void {
if (typeof process.send !== 'function') return
try {
process.send(message)
} catch {
// 父进程已断开;子进程会在 shutdown 或退出时结束。
}
}
function sendLog(level: 'info' | 'warn' | 'error', message: string): void {
post({ type: 'log', version: EXTENSION_HOST_PROTOCOL_VERSION, level, message })
}
function requirePermission(permission: string): void {
if (!permissions.includes(permission)) {
const error = new Error(`扩展没有 ${permission} 权限`)
;(error as Error & { code?: string }).code = 'PERMISSION_DENIED'
throw error
}
}
/** 白名单 RPC:扩展只能申请这些能力,且每次都要过权限检查。 */
function callHost(
method: ExtensionHostCall['method'],
params: Record<string, unknown>,
timeoutMs = 8_000
): Promise<unknown> {
if (!activated) return Promise.reject(new Error('扩展尚未激活'))
const callId = randomUUID()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingCalls.delete(callId)
reject(Object.assign(new Error('宿主调用超时'), { code: 'ACTION_TIMEOUT' }))
}, timeoutMs)
pendingCalls.set(callId, { resolve, reject, timer })
post({ type: 'call', version: EXTENSION_HOST_PROTOCOL_VERSION, callId, method, params })
})
}
const tm = {
extension: {
get id(): string {
return extensionId
},
/** 扩展私有数据目录;下载/生成的媒体应放在这里。 */
get dataDir(): string {
return extensionDataDir
},
get permissions(): string[] {
return [...permissions]
}
},
events: {
on(name: 'message.received', handler: MessageHandler): () => void {
if (name !== 'message.received' || typeof handler !== 'function') return () => undefined
eventHandlers.add(handler)
return () => eventHandlers.delete(handler)
},
off(name: 'message.received', handler: MessageHandler): void {
if (name !== 'message.received') return
eventHandlers.delete(handler)
}
},
messages: {
async query(request: {
conversationId: string
startTime?: number
endTime?: number
limit?: number
}): Promise<{ messages: unknown[] }> {
requirePermission('messages.query')
const result = (await callHost('messages.query', { ...request })) as { messages: unknown[] }
return result
}
},
wechat: {
/**
* 发送文本、图片或视频。
*
* 兼容旧调用:不传 `type` 视为 `text`。视频走独立的 video 通道,
* 原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。
*/
async send(request: {
type?: 'text' | 'image' | 'video'
to: string
text?: string
path?: string
at?: Record<string, string>
dedupeKey?: string
}) {
const type =
request && (request.type === 'image' || request.type === 'video') ? request.type : 'text'
if (type === 'image' || type === 'video') {
requirePermission(type === 'video' ? 'wechat.send.video' : 'wechat.send.image')
return (await callHost(
type === 'video' ? 'wechat.send.video' : 'wechat.send.image',
{
to: request.to,
path: request.path,
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
180_000
)) as {
actionId: string
status: 'sent'
}
}
requirePermission('wechat.send.text')
return (await callHost(
'wechat.send.text',
{
to: request.to,
text: request.text,
...(request.at ? { at: request.at } : {}),
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
20_000
)) as {
actionId: string
status: 'sent'
}
}
},
ai: {
async chat(messages: Array<{ role: string; content: string }>) {
requirePermission('ai.chat')
return (await callHost('ai.chat', { messages }, 60_000)) as { text: string }
}
},
storage: {
async get(key: string): Promise<unknown> {
requirePermission('storage')
return callHost('storage.get', { key })
},
async set(key: string, value: unknown): Promise<void> {
requirePermission('storage')
await callHost('storage.set', { key, value })
},
async remove(key: string): Promise<boolean> {
requirePermission('storage')
const result = (await callHost('storage.remove', { key })) as { removed?: boolean }
return result.removed === true
},
async list(): Promise<Array<{ key: string; value: unknown }>> {
requirePermission('storage')
const result = (await callHost('storage.list', {})) as {
entries?: Array<{ key: string; value: unknown }>
}
return result.entries ?? []
}
},
automation: {
registerAction(definition: {
id: string
title: string
description?: string
inputSchema?: Record<string, unknown>
handler: (input: Record<string, unknown>) => unknown
}): void {
requirePermission('automation.action')
const id = String(definition?.id || '').trim()
if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(id)) throw new Error('动作 id 不合法')
if (typeof definition.handler !== 'function') throw new Error('动作必须提供 handler')
const title = String(definition.title || id)
.trim()
.slice(0, 60)
if (!title) throw new Error('动作 title 不能为空')
actions.set(id, {
id,
title,
...(definition.description
? { description: String(definition.description).slice(0, 200) }
: {}),
...(definition.inputSchema ? { inputSchema: definition.inputSchema } : {}),
handler: definition.handler
})
const message: ExtensionHostRegisterAction = {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: {
id,
title,
...(definition.description
? { description: String(definition.description).slice(0, 200) }
: {}),
hasInputSchema: Boolean(definition.inputSchema)
}
}
post(message)
}
},
capabilities: {
async get(): Promise<unknown> {
return callHost('capabilities.get', {})
}
},
log: {
info(message: unknown): void {
sendLog('info', String(message ?? ''))
},
warn(message: unknown): void {
sendLog('warn', String(message ?? ''))
},
error(message: unknown): void {
sendLog('error', String(message ?? ''))
}
}
}
/** 入口文件必须真实位于扩展目录内;符号链接与越界路径都会被拒绝。 */
function resolveBackgroundEntry(dir: string): string | null {
const manifestPath = path.join(dir, 'manifest.json')
let manifest: { entrypoints?: { background?: unknown } }
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as typeof manifest
} catch {
return null
}
const relative = String(manifest.entrypoints?.background || '')
if (!relative) return null
const resolved = path.resolve(dir, relative)
try {
const realDir = fs.realpathSync(dir)
const realEntry = fs.realpathSync(resolved)
const inside = path.relative(realDir, realEntry)
if (!inside || inside.startsWith('..') || path.isAbsolute(inside)) return null
return realEntry
} catch {
return null
}
}
function pickExportedActivator(loaded: unknown): ((api: typeof tm) => unknown) | null {
if (typeof loaded === 'function') return loaded as (api: typeof tm) => unknown
if (loaded && typeof loaded === 'object') {
const candidate = (loaded as { activate?: unknown }).activate
if (typeof candidate === 'function') return candidate as (api: typeof tm) => unknown
}
return null
}
async function activate(message: ExtensionHostActivate): Promise<void> {
extensionId = message.extensionId
extensionDir = message.extensionDir
extensionDataDir = message.dataDir
permissions = Array.isArray(message.permissions) ? message.permissions : []
const entry = resolveBackgroundEntry(extensionDir)
if (!entry) {
post({
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: false,
error: { code: 'EXTENSION_INVALID_PATH', message: '后台入口文件不合法或不存在' }
})
return
}
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const loaded = require(entry) as unknown
const activator = pickExportedActivator(loaded)
if (activator) await activator(tm)
activated = true
post({ type: 'activated', version: EXTENSION_HOST_PROTOCOL_VERSION, ok: true })
} catch (error) {
activated = false
post({
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 300) : '扩展激活失败'
}
})
}
}
async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
if (!activated) return
for (const handler of eventHandlers) {
try {
await withTimeout(Promise.resolve(handler(message.envelope.event)), 10_000)
} catch (error) {
sendLog('error', `消息处理失败:${error instanceof Error ? error.message : String(error)}`)
}
}
}
function validateActionInput(
schema: Record<string, unknown> | undefined,
input: Record<string, unknown>
): void {
if (!schema) return
const required = Array.isArray(schema.required) ? schema.required : []
for (const key of required) {
if (typeof key === 'string' && !(key in input)) {
throw new Error(`缺少必填参数:${key}`)
}
}
const properties = schema.properties
if (!properties || typeof properties !== 'object') return
for (const [key, definition] of Object.entries(properties as Record<string, unknown>)) {
if (!(key in input)) continue
const type = (definition as { type?: unknown })?.type
const value = input[key]
if (type === 'string' && typeof value !== 'string') throw new Error(`参数 ${key} 必须是字符串`)
if (type === 'number' && typeof value !== 'number') throw new Error(`参数 ${key} 必须是数字`)
if (type === 'boolean' && typeof value !== 'boolean')
throw new Error(`参数 ${key} 必须是布尔值`)
}
}
async function invokeAction(message: ExtensionHostInvokeAction): Promise<void> {
const definition = actions.get(message.actionId)
if (!definition) {
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: `动作不存在:${message.actionId}` }
})
return
}
try {
validateActionInput(definition.inputSchema, message.input)
const raw = await withTimeout(
Promise.resolve(definition.handler(message.input)),
Math.max(1_000, Math.min(message.timeoutMs - 500, 60_000))
)
const output = normalizeActionOutput(raw)
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: output.success,
output,
...(output.success
? {}
: {
error: { code: 'ACTION_FAILED' as const, message: output.error || '扩展动作返回失败' }
})
})
} catch (error) {
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code:
error instanceof Error && /超时/.test(error.message) ? 'ACTION_TIMEOUT' : 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 300) : '扩展动作执行失败'
}
})
}
}
function normalizeActionOutput(raw: unknown): ExtensionAutomationActionOutput {
if (!raw || typeof raw !== 'object') {
return { success: false, error: '动作必须返回对象' }
}
const value = raw as Partial<ExtensionAutomationActionOutput>
const reply = value.reply
const hasReply =
reply && reply.type === 'text' && typeof reply.text === 'string' && reply.text.trim().length > 0
return {
success: value.success !== false,
...(value.output && typeof value.output === 'object' ? { output: value.output } : {}),
...(hasReply
? {
reply: {
type: 'text' as const,
text: reply!.text.trim().slice(0, 2_000),
...(reply!.at && typeof reply!.at === 'object' ? { at: reply!.at } : {})
}
}
: {}),
...(typeof value.error === 'string' && value.error.trim()
? { error: value.error.trim().slice(0, 300) }
: {})
}
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('扩展处理超时')), timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
}
)
})
}
process.on('message', (raw: unknown) => {
if (!raw || typeof raw !== 'object') return
const message = raw as ExtensionHostInboundMessage
if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return
switch (message.type) {
case 'activate':
void activate(message)
return
case 'event':
void dispatchEvent(message)
return
case 'invoke-action':
void invokeAction(message)
return
case 'test-send':
if (extensionId !== 'com.example.douyin-sender') return
void dispatchTestSend(message)
return
case 'call-result': {
const result = message as ExtensionHostCallResult
const pending = pendingCalls.get(result.callId)
if (!pending) return
clearTimeout(pending.timer)
pendingCalls.delete(result.callId)
if (result.ok) {
pending.resolve(result.result)
} else {
pending.reject(
Object.assign(new Error(result.error?.message || '宿主调用失败'), {
code: result.error?.code || 'ACTION_FAILED'
})
)
}
return
}
case 'shutdown':
process.exit(0)
}
})
async function dispatchTestSend(message: ExtensionHostTestSend): Promise<void> {
const handler = (
globalThis as typeof globalThis & {
__tmTestSend?: (params: Record<string, unknown>) => Promise<unknown>
}
).__tmTestSend
if (!handler) {
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: '测试处理器不可用' }
})
return
}
try {
const result = await handler(message.params)
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: true,
result
})
} catch (error) {
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '测试任务失败'
}
})
}
}
process.on('uncaughtException', (error) => {
sendLog('error', `未捕获异常:${error.message}`)
process.exit(1)
})
process.on('unhandledRejection', (reason) => {
sendLog(
'warn',
`未处理的 Promise 拒绝:${reason instanceof Error ? reason.message : String(reason)}`
)
})
// 让宿主知道进程已就绪,可以发 activate。必须在监听器之后发送。
post({ type: 'ready', version: EXTENSION_HOST_PROTOCOL_VERSION })
+57 -5
View File
@@ -141,6 +141,16 @@ import {
leaveNotificationContactDisplayName
} from './services/leave-notification-target'
import { MessageListenerService } from './services/message-listener-service'
import { EXTENSION_IPC } from '../shared/extensions/ipc'
import { installExtensionProtocolHandler, registerExtensionScheme } from './extensions/extension-protocol'
import { registerExtensionIpc } from './extensions/extension-ipc'
import { getExtensionPaths } from './extensions/extension-paths'
import {
disposeExtensionSystem,
getExtensionManager,
hasExtensionManager,
initExtensionSystem
} from './extensions/extension-service'
import { automationRuleStore } from './services/automation-rule-store'
import { automationExecutionLogService } from './services/automation-execution-log-service'
import { initAutomationService, getAutomationService } from './services/automation-service'
@@ -1079,8 +1089,10 @@ function createWindow(): void {
// Electron 初始化完成并准备创建浏览器窗口后,将调用此方法
// 某些 API 只能在此事件发生后使用
app.whenReady().then(async () => {
if (isLegacyMigrationHelper) {
/* 扩展页面走自定义协议;scheme 必须在 app ready 之前登记为特权协议。 */
registerExtensionScheme()
app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
try {
runLegacySafeStorageHelper()
app.exit(0)
@@ -1442,7 +1454,24 @@ app.whenReady().then(async () => {
// Create the renderer before native WCDB bootstrap so startup progress is visible immediately.
await reportTemplateService.recover()
registerReportTemplateIpc()
installExtensionProtocolHandler(getExtensionPaths())
registerExtensionIpc({
getManager: getExtensionManager,
paths: getExtensionPaths(),
isTrustedSender: (senderId) =>
BrowserWindow.getAllWindows().some((window) => window.webContents.id === senderId)
})
createWindow()
void initExtensionSystem({
appVersion: app.getVersion(),
onChange: (extensionId, reason) => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(EXTENSION_IPC.changed, { extensionId, reason })
}
}
}
})
wcdbBootstrapPromise = bootstrapWcdbNativeAsync().then(() => {
console.log('[WCDB4] async bootstrap complete')
})
@@ -1706,6 +1735,21 @@ app.whenReady().then(async () => {
}`
)
}
/*
* 扩展事件分发:与 Automation 并行、互不影响。
* 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。
*/
if (hasExtensionManager()) {
try {
getExtensionManager().handleMessage(message)
} catch (error) {
console.warn(
`[Extension] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
}
}
})
const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false })
configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled)
@@ -1884,7 +1928,7 @@ app.whenReady().then(async () => {
// 排查「消息到底发没发出去」时恰好缺的就是那份证据。
// 普通手动发送保持 triggerType=user;带 postfixText 的日报图片由 Gateway 编排成
// 两个 automation action,以复用同一条 3s 队列,并严格在图片 sent 后才发后置词。
if (request.type === 'text' || request.type === 'image') {
if (request.type === 'text' || request.type === 'image' || request.type === 'video') {
const to = String(request.to || '').trim()
const recipient = {
type:
@@ -1912,7 +1956,12 @@ app.whenReady().then(async () => {
}
const action = await wechatActionGateway.execute({
origin: 'user_manual',
purpose: request.type === 'text' ? 'manual_text' : 'manual_image',
purpose:
request.type === 'text'
? 'manual_text'
: request.type === 'video'
? 'manual_video'
: 'manual_image',
triggerType: 'user',
recipient,
content:
@@ -1922,7 +1971,9 @@ app.whenReady().then(async () => {
text: String(request.text || ''),
...(request.at ? { at: request.at } : {})
}
: { type: 'image', path: String(request.filePath || '') }
: request.type === 'video'
? { type: 'video', path: String(request.filePath || '') }
: { type: 'image', path: String(request.filePath || '') }
})
// 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。
return toPersonalWechatSendResult(action, await currentPersonalWechatSenderStatus())
@@ -3674,6 +3725,7 @@ app.on('before-quit', (event) => {
agentHubService.stop()
scheduledReportService.stop()
groupExitMonitorService.stop()
await disposeExtensionSystem().catch(() => undefined)
flushBootstrapCacheWritesSync()
const [, nativeCallsDrained] = await Promise.all([
apiServer.stop().catch(() => undefined),
+182 -26
View File
@@ -19,8 +19,21 @@ import {
renderLeaveNotificationText,
type GroupMemberExitedEvent
} from '../../shared/group-exit-event'
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { SaveGeneratedReportRequest, SaveGeneratedReportResult } from '../../shared/report-history'
import type {
WechatActionContent,
WechatActionRequest,
WechatActionResult
} from '../../shared/wechat-action'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import {
canExtensionSendText,
invokeExtensionAction
} from '../extensions/extension-automation-bridge'
import type {
SaveGeneratedReportRequest,
SaveGeneratedReportResult
} from '../../shared/report-history'
import {
generateAgentGroupReport,
type AgentGroupReportRequest,
@@ -45,6 +58,21 @@ import type { AutomationTargetResolution } from './automation-wechat-target'
/** 一步执行完毕后,后续步骤的处置方式。 */
const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send']
/**
* 配了扩展动作时的步骤顺序。
*
* 只有规则真的配了扩展动作才把这一步加进来:给每条日报都渲染一条
* 「执行扩展动作 已跳过」是纯噪声,用户会以为规则配错了。
*/
const EXTENSION_STEP_ORDER: AutomationStepKey[] = [
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
]
/** 退群通知的步骤顺序(与消息型规则**不共用**)。 */
const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
'exit_received',
@@ -74,6 +102,7 @@ const SCHEDULED_REPORT_STEP_ORDER: AutomationStepKey[] = [
*/
const SKIPPED_AFTER_REPLY_FAILURE = '前置步骤失败(回复确认未成功),本次不再继续。'
const SKIPPED_AFTER_REPORT_FAILURE = '前置步骤失败(日报未生成),没有图片可发送。'
const SKIPPED_AFTER_EXTENSION_FAILURE = '前置步骤失败(扩展动作未成功),本次不再继续。'
/**
* 定时日报「生成 / 落库」失败时,后续步骤的 `skipReason`。
@@ -102,6 +131,8 @@ export interface AutomationRunInput {
sourceDisplayName: string
/** 群消息触发者;仅内置日报确认回复会使用它构造 @。 */
triggerSender?: { wxid: string; displayName: string }
/** 触发本次执行的消息(扩展动作的运行时上下文)。 */
message?: ExtensionMessageEvent
}
export interface AutomationRunResult {
@@ -185,6 +216,22 @@ export interface ScheduledReportRunResult {
export interface AutomationActionRunnerDependencies {
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
/**
* 扩展动作调用。默认走 `ExtensionManager`;单测注入假实现即可绕开子进程。
*/
invokeExtensionAction?: (
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
) => Promise<ExtensionAutomationActionOutput>
/** 扩展是否具备发送文本的权限。默认读扩展中心授予集合。 */
canExtensionSendText?: (extensionId: string) => boolean
now?: () => number
/** 延迟实现。默认真 sleep;单测注入即时 resolve 的假实现,避免真的等 2 秒。 */
delay?: (ms: number) => Promise<void>
@@ -246,7 +293,9 @@ function actionErrorMessage(code: string | undefined, fallback: string | undefin
}
export class AutomationActionRunner {
private readonly generateReport: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
private readonly generateReport: (
request: AgentGroupReportRequest
) => Promise<AgentGroupReportResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly now: () => number
private readonly delay: (ms: number) => Promise<void>
@@ -257,21 +306,31 @@ export class AutomationActionRunner {
AutomationActionRunnerDependencies['resolveReportContact']
>
private readonly getContactAvatars: (usernames: string[]) => Promise<Record<string, string>>
private readonly invokeExtensionAction: NonNullable<
AutomationActionRunnerDependencies['invokeExtensionAction']
>
private readonly canExtensionSendText: (extensionId: string) => boolean
constructor(dependencies: AutomationActionRunnerDependencies = {}) {
this.generateReport = dependencies.generateReport ?? generateAgentGroupReport
this.executeAction = dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.executeAction =
dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.now = dependencies.now ?? (() => Date.now())
this.delay =
dependencies.delay ??
((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
dependencies.delay ?? ((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
this.saveGeneratedReport = dependencies.saveGeneratedReport ?? saveGeneratedReport
this.resolveReportContact = dependencies.resolveReportContact ?? ((raw) => resolveMd5(raw))
this.getContactAvatars = dependencies.getContactAvatars ?? ((ids) => getContactAvatars(ids))
this.invokeExtensionAction =
dependencies.invokeExtensionAction ??
((id, actionId, input, context) => invokeExtensionAction(id, actionId, input, context))
this.canExtensionSendText = dependencies.canExtensionSendText ?? canExtensionSendText
}
async run(input: AutomationRunInput): Promise<AutomationRunResult> {
const steps = STEP_ORDER.map((key) => createStep(key))
const extensionAction = findAction(input.rule, 'extensionAction')
const order = extensionAction ? EXTENSION_STEP_ORDER : STEP_ORDER
const steps = order.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -282,25 +341,77 @@ export class AutomationActionRunner {
const reportAction = findAction(input.rule, 'generateReport')
const sendAction = findAction(input.rule, 'sendReportImage')
// ---- 步骤 3:回复确认 ----
// ---- 步骤 3:扩展动作 ----
//
// 回复等待:规则一命中就秒回,看起来就是个机器人(消息刚到、回复就到)。
// 等待时长是**规则自己的一项执行参数**(`rule.replyDelaySeconds`,在
// 「编辑自动化 → 3 · 触发后执行」里配),所以不同规则可以不一样。
//
// 等待刻意放在 `reply` 步骤计时**之外** —— `reply.durationMs` 只应该反映发送本身,
// 否则用户看到「回复确认 2000ms」会误以为是发送慢。
// 已经命中就不再回头重判规则:等待窗口里规则被停用/删掉也不中断本次执行,
// 与 cooldown、同消息幂等的口径一致(都是「命中那一刻」的快照)。
if (replyAction) {
// 扩展动作先跑,它产出的 `reply` 会成为下一步「回复确认」的内容。
// 扩展本身**不发送**:内容交回宿主,由宿主在权限与授权都通过后经 Gateway 发出。
let extensionOutput: ExtensionAutomationActionOutput | undefined
if (extensionAction) {
const extensionStep = stepAt('extension_action')
extensionStep.status = 'running'
extensionStep.startedAt = this.now()
try {
extensionOutput = await this.invokeExtensionAction(
String(extensionAction.extensionId || ''),
String(extensionAction.actionId || ''),
extensionAction.input ?? {},
{
conversationId: input.conversationId,
isGroup: input.isGroup,
accountId: input.message?.accountId ?? '',
...(input.message ? { message: input.message } : {})
}
)
} catch (error) {
markFailed(
extensionStep,
this.now(),
error instanceof Error ? error.message : '扩展动作执行失败'
)
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (!extensionOutput || extensionOutput.success === false) {
markFailed(extensionStep, this.now(), extensionOutput?.error || '扩展动作返回失败')
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (extensionOutput.reply) extensionStep.detail = '已生成回复内容'
markSuccess(extensionStep, this.now())
}
const extensionReply = extensionOutput?.reply
// 步骤 4:回复确认。
// 命中即视为快照:等待窗口内规则被停用/删除也不中断本次执行。
// 等待时长来自 rule.replyDelaySeconds,且不计入 reply.durationMs。
const willReply = Boolean(extensionReply) || Boolean(replyAction)
if (willReply) {
// 用共享的归一化函数,而不是 `Number(...) || 0`:旧版 rules.json 里没有这个字段,
// 那应该按**默认 2 秒**处理(否则「默认 2 秒」要等用户手动进编辑页才会生效)。
const replyDelayMs = normalizeReplyDelaySeconds(input.rule.replyDelaySeconds) * 1_000
if (replyDelayMs > 0) await this.delay(replyDelayMs)
}
if (!replyAction) {
if (!willReply) {
markSkipped(stepAt('reply'))
} else if (extensionReply) {
const replyStep = stepAt('reply')
const extensionId = String(extensionAction?.extensionId || '')
if (!this.canExtensionSendText(extensionId)) {
markFailed(replyStep, this.now(), '扩展没有 wechat.send.text 权限,回复未发送')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
replyStep.status = 'running'
replyStep.startedAt = this.now()
const sent = await this.sendExtensionReply(input, extensionId, extensionReply)
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
} else {
const replyStep = stepAt('reply')
replyStep.status = 'running'
@@ -316,12 +427,12 @@ export class AutomationActionRunner {
: undefined
const sent = await this.sendThroughGateway(input, 'reply', {
type: 'text',
text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT,
text: replyAction?.text?.trim() || DEFAULT_REPLY_TEXT,
...(confirmationAt ? { at: confirmationAt } : {})
})
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
@@ -346,7 +457,7 @@ export class AutomationActionRunner {
}
if (!result.success || !result.pngPath) {
markFailed(reportStep, this.now(), result.error || '日报生成失败')
markRemainingSkipped(steps, 'report', SKIPPED_AFTER_REPORT_FAILURE)
markRemainingSkipped(steps, order, 'report', SKIPPED_AFTER_REPORT_FAILURE)
return { steps, status: 'failed', errorSummary: reportStep.error }
}
pngPath = result.pngPath
@@ -395,6 +506,43 @@ export class AutomationActionRunner {
return { steps, status: 'success', pngPath }
}
/**
* 发送扩展产出的回复。
*
* 内容来自扩展,**发送动作来自宿主**:`origin` / `purpose` / 幂等键都在这里填,
* 扩展返回的只是「想说什么」。所以扩展无法借这条链路绕过发送策略。
*/
private async sendExtensionReply(
input: AutomationRunInput,
extensionId: string,
reply: NonNullable<ExtensionAutomationActionOutput['reply']>
): Promise<{ ok: boolean; error?: string }> {
try {
const result = await this.executeAction({
idempotencyKey: `extension_action:${input.executionId}`,
origin: 'extension',
purpose: 'extension_action',
triggerType: 'automation',
executionId: input.executionId,
recipient: {
type: input.isGroup ? 'group' : 'contact',
id: input.conversationId,
name: input.sourceDisplayName
},
content: {
type: 'text',
text: reply.text,
...(reply.at ? { at: reply.at } : {})
},
metadata: { extensionId }
})
if (result.status === 'sent') return { ok: true }
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 把「@我生成日报」产出的日报写进**日报历史**。
*
@@ -522,7 +670,9 @@ export class AutomationActionRunner {
generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊',
contactAvatar,
source: 'scheduled',
dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel(input.config.report.range),
dateRange:
generated.reportMetadata?.dateRange ||
scheduledReportRangeLabel(input.config.report.range),
reportDate: generated.reportMetadata?.reportDate,
messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0,
generatedAt: new Date(this.now()).toISOString(),
@@ -674,7 +824,9 @@ export class AutomationActionRunner {
* 与 `run()` 的差别:没有动作链、没有回复等待、没有 cooldown
* (退群是低频事件,且**不能被时间窗合并** —— 两个成员先后退出就是两条通知)。
*/
async runLeaveNotification(input: LeaveNotificationRunInput): Promise<LeaveNotificationRunResult> {
async runLeaveNotification(
input: LeaveNotificationRunInput
): Promise<LeaveNotificationRunResult> {
const steps = LEAVE_NOTIFICATION_STEP_ORDER.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -792,18 +944,22 @@ export class AutomationActionRunner {
}
}
function findAction(rule: AutomationRule, type: AutomationAction['type']): AutomationAction | undefined {
function findAction(
rule: AutomationRule,
type: AutomationAction['type']
): AutomationAction | undefined {
return rule.actions.find((action) => action.type === type && action.enabled)
}
/** 把 `after` 之后的步骤全部标成 `skipped`(前一步挂了,后面的不许再动)。 */
function markRemainingSkipped(
steps: AutomationStep[],
order: AutomationStepKey[],
after: AutomationStepKey,
skipReason?: string
): void {
const from = STEP_ORDER.indexOf(after) + 1
for (const key of STEP_ORDER.slice(from)) {
const from = order.indexOf(after) + 1
for (const key of order.slice(from)) {
const step = steps.find((item) => item.key === key)
if (step) markSkipped(step, skipReason)
}
+31 -18
View File
@@ -1,8 +1,5 @@
import { createHash, randomUUID } from 'node:crypto'
import {
matchAutomationRule,
type AutomationMatchInput
} from '../../shared/automation-matcher'
import { matchAutomationRule, type AutomationMatchInput } from '../../shared/automation-matcher'
import {
AUTOMATION_SEND_PURPOSE,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
@@ -14,6 +11,8 @@ import {
type ScheduledRuleRunOutcome
} from '../../shared/automation'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { buildExtensionMessageEvent } from '../../shared/extensions/events'
import { buildEventId } from '../extensions/extension-event-bus'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { Wcdb4Client } from '../wcdb4-client'
import type { NormalizedIncomingMessage } from './message-listener-service'
@@ -28,18 +27,12 @@ import {
scheduledReportSourceDisplayName
} from './scheduled-report-target'
import type { AutomationTargetContact } from './automation-wechat-target'
import {
automationRuleStore,
type AutomationRuleStore
} from './automation-rule-store'
import { automationRuleStore, type AutomationRuleStore } from './automation-rule-store'
import {
automationExecutionLogService,
type AutomationExecutionLogService
} from './automation-execution-log-service'
import {
automationActionRunner,
type AutomationActionRunner
} from './automation-action-runner'
import { automationActionRunner, type AutomationActionRunner } from './automation-action-runner'
/**
* AutomationService —— Automation v1 的编排层。
*
@@ -137,9 +130,7 @@ export function leaveNotificationIdempotencyKey(eventId: string): string {
* 「立即执行」会因为幂等而被静默吞掉。
*/
export function scheduledReportExecutionId(ruleId: string, slot: string): string {
return createHash('sha1')
.update(`scheduled_report\u0001${ruleId}\u0001${slot}`)
.digest('hex')
return createHash('sha1').update(`scheduled_report\u0001${ruleId}\u0001${slot}`).digest('hex')
}
/** 定时日报一次执行的结果(定义在 shared 层,便于 IPC / 渲染层共用)。 */
@@ -291,7 +282,7 @@ export class AutomationService {
const sourceDisplayName = this.resolveDisplayName(message)
try {
await this.execute(rule, message, sourceDisplayName)
await this.execute(rule, message, sourceDisplayName, selfUsernames)
} finally {
// 无论 success / failed / 抛异常都要解除 in-flight。
// 漏掉这一步会让这条规则在这个会话里**永久锁死**。
@@ -660,7 +651,10 @@ export class AutomationService {
return true
}
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ id: string; name: string }> {
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{
id: string
name: string
}> {
try {
return listContacts()
.filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom'))
@@ -683,7 +677,8 @@ export class AutomationService {
private async execute(
rule: AutomationRule,
message: NormalizedIncomingMessage,
sourceDisplayName: string
sourceDisplayName: string,
selfUsernames: string[]
): Promise<void> {
const executionId = randomUUID()
const startedAt = this.now()
@@ -727,6 +722,24 @@ export class AutomationService {
displayName: message.senderNickname
}
}
: {}),
...(rule.actions.some((action) => action.type === 'extensionAction' && action.enabled)
? {
message: buildExtensionMessageEvent({
eventId: buildEventId(message.sessionId, message.localId),
accountId: String(getSelfAccountInfo()?.wxid || ''),
conversationId: message.sessionId,
messageId: message.serverId || message.localId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
isGroup: message.isGroup,
isSelf: message.isSelf,
messageType: message.messageType,
...(message.content !== undefined ? { content: message.content } : {}),
mentionsMe: message.mentionTargets.some((target) => selfUsernames.includes(target)),
createTimeSeconds: message.createTime
})
}
: {})
})
} catch (error) {
+16 -19
View File
@@ -112,9 +112,7 @@ export function formatMacWechatHostStartupFailure(code: number | null, diagnosti
const lines = diagnostic.trim().split('\n').filter(Boolean)
const detail = lines[lines.length - 1]
if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}`
return code === null
? '发送运行时在启动过程中退出'
: `发送运行时启动失败(进程退出码 ${code})`
return code === null ? '发送运行时在启动过程中退出' : `发送运行时启动失败(进程退出码 ${code})`
}
export function resolveMacWechatSendMechanism(
@@ -201,6 +199,12 @@ export function deriveMacWechatSenderStatus({
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
/*
* 视频复用图片的媒体通道(Host 的 `/SendMsg` type=video)。
* Runtime manifest 不单独声明 video 能力,因此以图片通道是否可用作为判据;
* 真正的发送结果仍以 Host 返回为准,不在 UI 层假装支持。
*/
const canSendVideo = bindingReady && binding?.canSendImage === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -224,10 +228,11 @@ export function deriveMacWechatSenderStatus({
imageHookInstalled: identityMatches && (binding?.canSendImage ?? false),
imageHookReady: identityMatches && (binding?.canSendImage ?? false),
messageListenerReady: scriptLoaded,
canSend: canSendText || canSendImage || canSendVoice,
canSend: canSendText || canSendImage || canSendVoice || canSendVideo,
canSendText,
canSendImage,
canSendVoice,
canSendVideo,
message,
error: state === 'error' ? message : undefined
}
@@ -349,9 +354,7 @@ export class MacWechatRuntimeManager {
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
* online" and "WeChat bound" stay two independent states.
*/
ensureStarted(
options: { allowManualRestart?: boolean } = {}
): Promise<MacWechatRuntimeSnapshot> {
ensureStarted(options: { allowManualRestart?: boolean } = {}): Promise<MacWechatRuntimeSnapshot> {
if (this.startInFlight) return this.startInFlight
const startPromise = this.ensureStartedOnce(options)
@@ -367,9 +370,9 @@ export class MacWechatRuntimeManager {
return startPromise
}
protected async ensureStartedOnce(
options: { allowManualRestart?: boolean }
): Promise<MacWechatRuntimeSnapshot> {
protected async ensureStartedOnce(options: {
allowManualRestart?: boolean
}): Promise<MacWechatRuntimeSnapshot> {
if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot()
if (options.allowManualRestart) this.manuallyStopped = false
if (isMacNativeRuntimeUnavailable()) {
@@ -481,19 +484,13 @@ export class MacWechatRuntimeManager {
}
try {
if (!app.isPackaged) {
execFileSync('/usr/bin/codesign', [
'--force',
'--sign',
'-',
'--timestamp=none',
hostPath
])
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', '--timestamp=none', hostPath])
}
execFileSync('/usr/bin/codesign', ['--verify', '--strict', hostPath])
} catch (error) {
this.lifecycle = 'stopped'
this.lastError = '无法验证发送 Host 签名:' +
(error instanceof Error ? error.message : String(error))
this.lastError =
'无法验证发送 Host 签名:' + (error instanceof Error ? error.message : String(error))
appLogger.write({
level: 'error',
scope: 'mac-wechat-runtime',
+43 -3
View File
@@ -137,14 +137,39 @@ export function extractMentionTargets(source: string | undefined): string[] {
if (!match) return []
const inner = match[1].trim()
const unwrapped = inner.replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, '').trim()
return unwrapped ? [unwrapped] : []
if (!unwrapped) return []
return unwrapped
.split(',')
.map((item) => item.trim())
.filter(Boolean)
}
/** 把 WCDB 的 `source` 列(zstd 压缩的 Buffer)还原成 XML 文本。 */
/** 把 WCDB 的 `source` 列(明文 XML 字符串或 zstd 压缩的 Buffer)还原成 XML 文本。 */
export function decodeSourcePayload(value: unknown): string | undefined {
if (typeof value === 'string') {
const trimmed = value.trim()
if (!trimmed) return undefined
if (
trimmed.length >= 8 &&
trimmed.length % 2 === 0 &&
/^28b52ffd[0-9a-f]+$/i.test(trimmed)
) {
try {
return Buffer.from(zstdDecompress(Buffer.from(trimmed, 'hex'))).toString('utf8')
} catch {
return undefined
}
}
return trimmed
}
let buffer: Buffer | null = null
if (Buffer.isBuffer(value)) {
buffer = value
} else if (value instanceof Uint8Array) {
buffer = Buffer.from(value)
} else if (Array.isArray(value)) {
buffer = Buffer.from(value)
} else {
const candidate = value as { type?: string; data?: unknown } | null
if (candidate?.type === 'Buffer' && Array.isArray(candidate.data)) {
@@ -193,6 +218,7 @@ export class MessageListenerService {
private readonly pendingSessions = new Set<string>()
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
private readbackInFlight = false
private pendingReadback = false
private disposed = false
private readonly coalesceMs: number
@@ -282,8 +308,13 @@ export class MessageListenerService {
* - **legacy(protocol v1,旧 runtime)**:只能退回「最近活跃会话」`getSessions()[0]`。
*/
private async readback(): Promise<void> {
if (this.disposed || this.readbackInFlight) return
if (this.disposed) return
if (this.readbackInFlight) {
this.pendingReadback = true
return
}
this.readbackInFlight = true
this.pendingReadback = false
const startedAt = Date.now()
const preciseSessions = Array.from(this.pendingSessions)
@@ -321,6 +352,15 @@ export class MessageListenerService {
)
} finally {
this.readbackInFlight = false
if (!this.disposed && (this.pendingReadback || this.pendingSessions.size > 0)) {
this.pendingReadback = false
if (!this.coalesceTimer) {
this.coalesceTimer = setTimeout(() => {
this.coalesceTimer = null
void this.readback()
}, this.coalesceMs)
}
}
}
}
@@ -37,7 +37,8 @@ export class PersonalWechatCapabilityService {
const capabilities = {
text: Boolean(senderStatus.canSendText),
image: Boolean(senderStatus.canSendImage),
voice: Boolean(senderStatus.canSendVoice)
voice: Boolean(senderStatus.canSendVoice),
video: Boolean(senderStatus.canSendVideo)
}
const status = this.mapState(senderStatus)
const ready = status === 'ready'
+166 -13
View File
@@ -23,7 +23,10 @@ import type {
import { loadSettings } from './settings-store'
import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder'
import { appLogger } from '../app-logger'
import { accountDirectoryBelongsToIdentity, readLocalAccountIdentity } from './local-account-identity'
import {
accountDirectoryBelongsToIdentity,
readLocalAccountIdentity
} from './local-account-identity'
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
const execFileAsync = promisify(execFile)
@@ -31,6 +34,8 @@ const WINDOWS_LOOPBACK_HOST = '127.0.0.1'
const REQUEST_TIMEOUT_MS = 20_000
const MAX_IMAGE_BYTES = 20 * 1024 * 1024
const MAX_VOICE_BYTES = 20 * 1024 * 1024
/** 视频与扩展发送通道的上限保持一致。 */
const MAX_VIDEO_BYTES = 100 * 1024 * 1024
// 语音编码由 native runtime 内的 SILK 实现完成,不再是外部编码器进程。
const VOICE_ENCODER_NAME = 'silk'
const VOICE_ENCODER_VERSION = 'tm-wechat-native'
@@ -327,6 +332,73 @@ function stageMacWechatImageForMessageSourceSend(
return stagedPath
}
const MAC_VIDEO_STAGE_PREFIX = 'tm-video-'
const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000
/**
* macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`
* 只能读取 `~/Library/Containers/com.tencent.xinWeChat/Data/...` 容器内路径,
* 直接传 `~/Library/Application Support/TraceMemo/...` 会触发 `VIDEO_PREPARATION_FAILED:0`。
* 因此发送前需将容器外视频暂存到微信容器的 `Documents` 目录。
*/
export function stageMacWechatVideoForSend(
filePath: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { stagedPath: string; cleanup: () => void } {
const normalized = String(filePath || '').trim()
const containerDataRoot = dirname(dirname(wechatFilesRoot))
if (
containerDataRoot.includes('com.tencent.xinWeChat') &&
normalized.startsWith(`${containerDataRoot}${sep}`)
) {
return { stagedPath: normalized, cleanup: () => {} }
}
const documentsDir = dirname(wechatFilesRoot)
const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot
mkdirSync(stageDir, { recursive: true })
// 顺手清理超过 10 分钟的历史暂存视频,防止异常退出残留。
const now = Date.now()
try {
for (const entry of readdirSync(stageDir)) {
if (!entry.startsWith(MAC_VIDEO_STAGE_PREFIX)) continue
const candidate = join(stageDir, entry)
try {
if (now - statSync(candidate).mtimeMs > MAC_VIDEO_STAGE_RETENTION_MS) {
unlinkSync(candidate)
}
} catch {
// Best-effort stale file cleanup.
}
}
} catch {
// Ignore directory listing errors.
}
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.mp4'
const stagedPath = join(
stageDir,
`${MAC_VIDEO_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}`
)
copyFileSync(normalized, stagedPath)
return {
stagedPath,
cleanup: () => {
const timer = setTimeout(() => {
try {
unlinkSync(stagedPath)
} catch {
// Best-effort delayed cleanup after WeChat finishes asynchronous video upload.
}
}, 120_000)
timer.unref?.()
}
}
}
/** Locate the current account's temporary image directory consumed by the image send path. */
export function findWechatImagePath(
root = WECHAT_FILES_ROOT,
@@ -443,6 +515,12 @@ export function buildWindowsWechatRequest(
body: { toWxid: target, type: 'image', msg: String(request.filePath || '').trim() }
}
}
if (request.type === 'video') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'video', msg: String(request.filePath || '').trim() }
}
}
const fromId = String(request.fromId || '').trim()
const filePath = String(options.filePath || request.filePath || '').trim()
@@ -609,6 +687,7 @@ export class PersonalWechatSendService {
if (request.type === 'text') return this.sendMacText(request)
if (request.type === 'image') return this.sendMacImage(request)
if (request.type === 'voice') return this.sendMacVoice(request)
if (request.type === 'video') return this.sendMacVideo(request)
}
return {
success: false,
@@ -772,11 +851,78 @@ export class PersonalWechatSendService {
signal: AbortSignal.timeout(timeoutMs)
}).catch(() => null)
if (response === null || !response.ok) return null
return (await response.json().catch(() => null)) as {
code: number
ok: boolean
message: string
} | null
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null
if (!payload) return null
/*
* 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`,
* `/SendMsg` 兼容层可能返回 `{status:true}` 或 Windows 风格的 `{ret:0}`。
* 这里统一收敛,避免「实际已发送、界面报失败」。
*/
const explicitFailure = payload.ok === false || payload.status === false
const ok =
!explicitFailure &&
(payload.ok === true || payload.status === true || payload.ret === 0 || payload.code === 0)
return {
code: Number(payload.code ?? payload.ret ?? (ok ? 0 : 1)),
ok,
message: String(payload.message ?? payload.msg ?? '')
}
}
/**
* macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。
*
* 微信运行在 App Sandbox 容器中,注入的 `libtmwechat.dylib` 在微信进程内执行,
* 只能访问微信沙盒容器目录(`~/Library/Containers/com.tencent.xinWeChat/Data/...`)。
* 因此先将容器外视频暂存到微信容器 `Documents` 目录,再调用 `/SendMsg`。
*/
private async sendMacVideo(
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
): Promise<PersonalWechatSendResult> {
await macWechatRuntimeManager.ensureStarted()
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!status.canSendVideo) {
return {
success: false,
status,
error: status.message || '当前微信发送组件不支持视频,请升级后重试'
}
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) {
return { success: false, status, error: '请选择有效的视频文件' }
}
const size = statSync(filePath).size
if (size <= 0 || size > MAX_VIDEO_BYTES) {
return { success: false, status, error: '视频必须小于 100 MB' }
}
let staged: { stagedPath: string; cleanup: () => void } | null = null
try {
staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot)
} catch (error) {
const latest = await macWechatRuntimeManager.buildSenderStatus()
return {
success: false,
status: latest,
error: error instanceof Error ? error.message : '无法将视频暂存到微信沙盒目录'
}
}
try {
const result = await this.postMacHost(
'/SendMsg',
{ toWxid: request.to, type: 'video', msg: staged.stagedPath },
180_000
)
const latest = await macWechatRuntimeManager.buildSenderStatus()
if (!result?.ok) {
return { success: false, status: latest, error: result?.message || '视频发送失败' }
}
return { success: true, status: latest }
} finally {
staged.cleanup()
}
}
private async sendMacImage(
@@ -974,21 +1120,24 @@ export class PersonalWechatSendService {
request = { ...request, to, text }
} else {
const filePath = String(request.filePath || '').trim()
const label = request.type === 'voice' ? '语音' : request.type === 'video' ? '视频' : '图片'
const limit =
request.type === 'voice'
? MAX_VOICE_BYTES
: request.type === 'video'
? MAX_VIDEO_BYTES
: MAX_IMAGE_BYTES
if (!filePath || !existsSync(filePath)) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件`
}
return { success: false, status, error: `请选择有效的${label}文件` }
}
const size = statSync(filePath).size
if (size <= 0 || size > (request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES)) {
if (size <= 0 || size > limit) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB`
error: `${label}必须小于 ${Math.round(limit / (1024 * 1024))} MB`
}
}
request = { ...request, to, filePath }
@@ -1019,6 +1168,10 @@ export class PersonalWechatSendService {
filePath: preparedImage.filePath
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
} else if (request.type === 'video') {
// 视频不复制到临时目录:原生 Host 直接按绝对路径读取。
const windowsRequest = buildWindowsWechatRequest(request)
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000)
} else if (request.type === 'voice') {
const fromId = String(request.fromId || '').trim()
if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音')
+76 -6
View File
@@ -39,7 +39,15 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
// purpose,各自有幂等位 —— 少这一条会被 evaluateWechatActionPolicy 拦下。
'automation_scheduled_report_postfix',
'manual_report_image',
'manual_report_postfix'
'manual_report_postfix',
/*
* 扩展来源的两个用途。
*
* 扩展不能自己决定 purpose:`ExtensionSendGateway` 与自动化 runner 分别填这两个值,
* 且 `evaluateWechatActionPolicy` 要求 `origin === 'extension'`,两边同时成立才放行。
*/
'extension_send',
'extension_action'
])
export interface ReportImageSequenceRequest {
@@ -137,6 +145,46 @@ export class WechatActionGateway {
return this.loadAuditState().records.map((record) => ({ ...record }))
}
/**
* 扩展来源的发送入口。
*
* 与 `execute()` 的区别只有一个:`origin` / `purpose` / `metadata.extensionId`
* 由这里按宿主规则填,扩展侧传不进来。其余检查(能力、审计、幂等、
* 自动化发送节流)与普通发送完全一致。
*/
async executeFromExtension(input: {
extensionId: string
purpose: 'extension_send' | 'extension_action'
recipient: WechatActionRequest['recipient']
content: WechatActionContent
idempotencyKey?: string
executionId?: string
}): Promise<WechatActionResult> {
const extensionId = String(input.extensionId || '').trim()
const startedAt = this.deps.now().toISOString()
if (!extensionId) {
return {
actionId: randomUUID(),
status: 'blocked',
decision: 'block',
errorCode: 'INVALID_REQUEST',
reason: '扩展发送缺少扩展标识',
startedAt,
finishedAt: startedAt
}
}
return this.execute({
...(input.idempotencyKey ? { idempotencyKey: String(input.idempotencyKey) } : {}),
...(input.executionId ? { executionId: String(input.executionId) } : {}),
origin: 'extension',
purpose: input.purpose,
triggerType: 'automation',
recipient: input.recipient,
content: input.content,
metadata: { extensionId }
})
}
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
const normalized = normalizeActionRequest(request)
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
@@ -256,9 +304,10 @@ export class WechatActionGateway {
const queued = this.automationSendTail.then(async () => {
const now = this.deps.now().getTime()
const remaining = this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
const remaining =
this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
if (remaining > 0) await this.deps.wait(remaining)
this.lastAutomationSendStartedAt = this.deps.now().getTime()
return this.deps.send(sendRequest)
@@ -393,14 +442,20 @@ export class WechatActionGateway {
!request.content ||
(request.content.type !== 'text' &&
request.content.type !== 'image' &&
request.content.type !== 'video' &&
request.content.type !== 'voice')
) {
return
}
const state = this.loadAuditState()
const extensionId =
request.metadata && typeof request.metadata.extensionId === 'string'
? request.metadata.extensionId.trim().slice(0, 128)
: ''
const record: WechatActionAuditRecord = {
actionId: result.actionId,
...(idempotencyKey ? { idempotencyKey } : {}),
...(extensionId ? { extensionId } : {}),
origin: request.origin,
purpose: request.purpose,
triggerType: request.triggerType,
@@ -465,6 +520,18 @@ export function evaluateWechatActionPolicy(request: WechatActionRequest): Policy
reason: `自动化动作不允许执行 purpose=${request.purpose}`
}
}
/*
* 扩展用途必须来自扩展来源。少了这一条,任何能构造 `WechatActionRequest` 的
* 内部调用都可以用 `extension_send` 绕过自动化用途白名单。
*/
if (String(request.purpose).startsWith('extension_') && request.origin !== 'extension') {
return {
decision: 'block',
source: 'deterministic',
reasonCode: 'ACTION_NOT_ALLOWED',
reason: '扩展发送用途只能用于扩展来源的请求'
}
}
return { decision: 'allow', source: 'deterministic' }
}
@@ -526,7 +593,7 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu
content: { type: 'text', text, ...(at ? { at } : {}) }
} as WechatActionRequest
}
if (contentType !== 'image' && contentType !== 'voice') return null
if (contentType !== 'image' && contentType !== 'video' && contentType !== 'voice') return null
const filePath = String((content as { path?: unknown }).path || '').trim()
if (!filePath) return null
return {
@@ -585,6 +652,9 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech
if (request.content.type === 'image') {
return { ...base, type: 'image', filePath: request.content.path }
}
if (request.content.type === 'video') {
return { ...base, type: 'video', filePath: request.content.path }
}
const metadata = request.metadata && typeof request.metadata === 'object' ? request.metadata : {}
const fromId = typeof metadata.fromId === 'string' ? metadata.fromId.trim() : ''
const durationMs =
@@ -638,7 +708,7 @@ function contentAudit(
}
function contentTypeLabel(type: WechatActionContent['type']): string {
return type === 'text' ? '文字' : type === 'image' ? '图片' : '语音'
return type === 'text' ? '文字' : type === 'image' ? '图片' : type === 'video' ? '视频' : '语音'
}
function normalizeAuditRecords(values: unknown[]): WechatActionAuditRecord[] {
+22 -2
View File
@@ -1442,8 +1442,16 @@ export class Wcdb4Client {
// cannot silently stop at a shard boundary.
let tableMessages: Wcdb4Message[] = []
const cursorSatisfiesLimit = maxRows !== undefined && cursorMessages.length >= maxRows
const cursorMissingSource =
cursorMessages.length > 0 &&
cursorMessages.some(
(msg) => !msg.raw || !Object.prototype.hasOwnProperty.call(msg.raw, 'source')
)
let tableScanExecuted = false
if (!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) {
if (
(!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) ||
(Boolean(endTime) && cursorMissingSource)
) {
tableScanExecuted = true
tableMessages = await this.getMessagesByTableScanAsync(
username,
@@ -2411,7 +2419,19 @@ export class Wcdb4Client {
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: `${message.msgCreateTime}:${message.msgContent}`
const key = recoveredRow ? `recovered:${identity}` : identity
merged.set(key, message)
const existing = merged.get(key)
if (existing?.raw && message.raw) {
merged.set(key, {
...existing,
...message,
raw: {
...existing.raw,
...message.raw
}
})
} else {
merged.set(key, message)
}
}
const messages = Array.from(merged.values()).sort(
(left, right) =>
+36
View File
@@ -1,5 +1,17 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import { Contact, Message, MessagesAroundResult } from '../shared/types'
import type {
ExtensionChangedEvent,
ExtensionPageRequest
} from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageResponse,
InstalledExtension
} from '../shared/extensions/types'
import {
GroupReportExportRequest,
GroupReportExportResult,
@@ -817,6 +829,30 @@ declare global {
onAgentHubConversationsCleared: (callback: () => void) => () => void
onAgentHubStatus: (callback: (status: AgentHubStatus) => void) => () => void
onAgentHubLog: (callback: (entry: AgentHubLogEntry) => void) => () => void
/* 扩展中心 */
listExtensions: () => Promise<InstalledExtension[]>
getExtension: (extensionId: string) => Promise<InstalledExtension | null>
pickExtensionDirectory: () => Promise<string | null>
pickExtensionPackage: () => Promise<string | null>
installExtensionFromDirectory: (directory: string) => Promise<ExtensionInstallResult>
installExtensionFromPackage: (packagePath: string) => Promise<ExtensionInstallResult>
setExtensionEnabled: (
extensionId: string,
enabled: boolean
) => Promise<ExtensionOperationResult>
uninstallExtension: (
extensionId: string,
keepData?: boolean
) => Promise<ExtensionOperationResult>
getExtensionLogs: (extensionId: string, limit?: number) => Promise<ExtensionLogEntry[]>
clearExtensionLogs: (extensionId: string) => Promise<{ success: true }>
getExtensionPageUrl: (
extensionId: string,
pageId?: string
) => Promise<ExtensionPageDescriptor>
extensionPageRequest: (request: ExtensionPageRequest) => Promise<ExtensionPageResponse>
openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }>
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void
}
}
}
+40
View File
@@ -131,6 +131,16 @@ import type {
SaveTextToSpeechSettingsRequest,
SynthesizeTextToSpeechRequest
} from '../shared/text-to-speech'
import type { ExtensionChangedEvent } from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
InstalledExtension
} from '../shared/extensions/types'
// 渲染器的自定义 API
const api = {
@@ -265,6 +275,36 @@ const api = {
enabled: boolean
): Promise<MsgInsertApplyResult> =>
ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }),
listExtensions: (): Promise<InstalledExtension[]> => ipcRenderer.invoke('extension:list'),
getExtension: (extensionId: string): Promise<InstalledExtension | null> =>
ipcRenderer.invoke('extension:get', extensionId),
pickExtensionDirectory: (): Promise<string | null> =>
ipcRenderer.invoke('extension:pickDirectory'),
pickExtensionPackage: (): Promise<string | null> => ipcRenderer.invoke('extension:pickPackage'),
installExtensionFromDirectory: (directory: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installDirectory', directory),
installExtensionFromPackage: (packagePath: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installPackage', packagePath),
setExtensionEnabled: (extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }),
uninstallExtension: (extensionId: string, keepData = true): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }),
getExtensionLogs: (extensionId: string, limit?: number): Promise<ExtensionLogEntry[]> =>
ipcRenderer.invoke('extension:getLogs', { id: extensionId, limit }),
clearExtensionLogs: (extensionId: string): Promise<{ success: true }> =>
ipcRenderer.invoke('extension:clearLogs', extensionId),
getExtensionPageUrl: (extensionId: string, pageId?: string): Promise<ExtensionPageDescriptor> =>
ipcRenderer.invoke('extension:getPageUrl', { id: extensionId, pageId }),
extensionPageRequest: (request: ExtensionPageRequest): Promise<ExtensionPageResponse> =>
ipcRenderer.invoke('extension:pageRequest', request),
openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke('extension:openDataDir', extensionId),
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => {
const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void =>
callback(payload)
ipcRenderer.on('extension:changed', listener)
return () => ipcRenderer.removeListener('extension:changed', listener)
},
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => {
const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void =>
callback(state)
+1 -1
View File
@@ -7,7 +7,7 @@
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:;"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:; frame-src tm-extension:;"
/>
</head>
+3
View File
@@ -46,6 +46,7 @@ import { Button, useToast } from './components/ui'
import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt'
import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace'
import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace'
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
import {
buildContactSearchIndex,
@@ -2139,6 +2140,8 @@ function App(): React.ReactElement {
)
case 'agent-hub':
return <AgentHubWorkspace selfInfo={selfInfo} />
case 'extensions':
return <ExtensionWorkspace />
case 'api':
return (
<ApiWorkspace
@@ -46,6 +46,15 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
<path d="m16.5 9 3 3-3 3" />
</svg>
)
case 'extensions':
// 拼图:扩展是「往现有能力上加一块」,与自动化的闪电区分开。
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M9.5 4.5h5v2a1.5 1.5 0 1 0 3 0v-2h1.5v15h-15v-15H5.5v2a1.5 1.5 0 1 1-3 0v-2H5" />
<path d="M8.5 12h7" />
<path d="M8.5 16h4.5" />
</svg>
)
case 'export':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
@@ -5,6 +5,7 @@ export type AppPage =
| 'exit-monitor'
| 'automation'
| 'agent-hub'
| 'extensions'
| 'export'
| 'api'
| 'settings'
@@ -20,6 +21,7 @@ export const PRIMARY_NAV_ITEMS: NavigationItem[] = [
{ id: 'report', label: '日报' },
{ id: 'exit-monitor', label: '退群监控' },
{ id: 'automation', label: '自动化' },
{ id: 'extensions', label: '扩展' },
{ id: 'agent-hub', label: 'Agent' },
{ id: 'export', label: '导出' },
{ id: 'api', label: 'API' },
@@ -0,0 +1,122 @@
import * as React from 'react'
import {
EXTENSION_PAGE_HOST_SOURCE,
isExtensionPageBridgeRequest
} from '../../../../shared/extensions/ipc'
import type {
ExtensionPageDescriptor,
ExtensionPageMethod
} from '../../../../shared/extensions/types'
import { Button } from '../../components/ui'
interface ExtensionPageHostProps {
descriptor: ExtensionPageDescriptor
onBack: () => void
}
/**
* 扩展页面容器。
*
* 页面在 `sandbox="allow-scripts"` 的 iframe 里运行:没有 Node、没有 preload、
* 没有 `window.api`,与官方渲染层不同源。它与宿主的唯一通道是 postMessage,
* 由本组件转成受白名单约束的 `extensionPageRequest`。
*/
export function ExtensionPageHost({
descriptor,
onBack
}: ExtensionPageHostProps): React.ReactElement {
const frameRef = React.useRef<HTMLIFrameElement | null>(null)
const [loaded, setLoaded] = React.useState(false)
const [slow, setSlow] = React.useState(false)
const [reloadKey, setReloadKey] = React.useState(0)
React.useEffect(() => {
const timer = window.setTimeout(() => setSlow(true), 8_000)
return () => window.clearTimeout(timer)
}, [reloadKey])
React.useEffect(() => {
const onMessage = (event: MessageEvent): void => {
const frame = frameRef.current
if (!frame || event.source !== frame.contentWindow) return
if (!isExtensionPageBridgeRequest(event.data)) return
const request = event.data
if (request.extensionId !== descriptor.extensionId) return
void window.api
.extensionPageRequest({
extensionId: descriptor.extensionId,
method: request.method as ExtensionPageMethod,
params: request.params ?? {}
})
.then((response) => {
frame.contentWindow?.postMessage(
{
source: EXTENSION_PAGE_HOST_SOURCE,
requestId: request.requestId,
ok: response.ok,
...(response.ok ? { result: response.result } : { error: response.error })
},
'*'
)
})
.catch((error) => {
frame.contentWindow?.postMessage(
{
source: EXTENSION_PAGE_HOST_SOURCE,
requestId: request.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '调用失败'
}
},
'*'
)
})
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [descriptor.extensionId])
React.useEffect(() => {
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') onBack()
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [onBack])
return (
<div className="extension-page-host">
<header className="extension-page-host-header">
<Button size="sm" variant="ghost" onClick={onBack}>
← 返回扩展中心
</Button>
<div className="extension-page-host-title">
<strong>{descriptor.title}</strong>
<span>{descriptor.extensionId}</span>
</div>
<Button size="sm" variant="ghost" onClick={() => setReloadKey((value) => value + 1)}>
重新加载
</Button>
</header>
<div className="extension-page-host-body">
{!loaded && (
<div className="extension-page-host-loading">
<p>{slow ? '页面尚未响应。扩展页面必须通过 tm.* 与宿主通信。' : '正在加载扩展页面…'}</p>
</div>
)}
<iframe
key={reloadKey}
ref={frameRef}
className="extension-page-frame"
title={descriptor.title}
src={descriptor.url}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
onLoad={() => setLoaded(true)}
/>
</div>
</div>
)
}
@@ -0,0 +1,494 @@
import * as React from 'react'
import {
EXTENSION_PERMISSION_INFO,
sortPermissionsByRisk,
type ExtensionPermission
} from '../../../../shared/extensions/permissions'
import type {
ExtensionLogEntry,
ExtensionPageDescriptor,
InstalledExtension
} from '../../../../shared/extensions/types'
import { Button, Spinner, useToast } from '../../components/ui'
import { ExtensionPageHost } from './ExtensionPageHost'
const STATUS_LABELS: Record<InstalledExtension['runtime']['state'], string> = {
inactive: '未运行',
starting: '启动中',
active: '运行中',
error: '运行错误',
crashed: '已停止'
}
function formatTimestamp(value: number): string {
if (!value) return '—'
return new Date(value).toLocaleString('zh-CN', { hour12: false })
}
function statusTone(extension: InstalledExtension): 'success' | 'warning' | 'danger' | 'muted' {
if (!extension.enabled) return 'muted'
if (extension.runtime.state === 'active') return 'success'
if (extension.runtime.state === 'crashed' || extension.runtime.state === 'error') return 'danger'
return 'warning'
}
export function ExtensionWorkspace(): React.ReactElement {
const { toast } = useToast()
const [extensions, setExtensions] = React.useState<InstalledExtension[]>([])
const [selectedId, setSelectedId] = React.useState<string | null>(null)
const [logs, setLogs] = React.useState<ExtensionLogEntry[]>([])
const [busy, setBusy] = React.useState(false)
const [page, setPage] = React.useState<ExtensionPageDescriptor | null>(null)
const [pendingEnable, setPendingEnable] = React.useState<InstalledExtension | null>(null)
const [pendingUninstall, setPendingUninstall] = React.useState<string | null>(null)
const refresh = React.useCallback(async (): Promise<void> => {
const list = await window.api.listExtensions()
setExtensions(list)
setSelectedId((current) => {
if (current && list.some((item) => item.id === current)) return current
return list[0]?.id ?? null
})
}, [])
React.useEffect(() => {
void refresh().catch(() => undefined)
const unsubscribe = window.api.onExtensionChanged(() => {
void refresh().catch(() => undefined)
})
return unsubscribe
}, [refresh])
const selected = React.useMemo(
() => extensions.find((item) => item.id === selectedId) ?? null,
[extensions, selectedId]
)
const selectedIdForLogs = selected?.id
const selectedRuntimeState = selected?.runtime.state
const selectedUpdatedAt = selected?.updatedAt
React.useEffect(() => {
if (!selectedIdForLogs) {
setLogs([])
return
}
let disposed = false
void window.api
.getExtensionLogs(selectedIdForLogs, 60)
.then((entries) => {
if (!disposed) setLogs(entries)
})
.catch(() => undefined)
return () => {
disposed = true
}
}, [selectedIdForLogs, selectedRuntimeState, selectedUpdatedAt])
const run = async <T,>(action: () => Promise<T>, successMessage?: string): Promise<T | null> => {
setBusy(true)
try {
return await action()
} catch (error) {
toast({
title: '操作失败',
description: error instanceof Error ? error.message : String(error),
variant: 'destructive'
})
return null
} finally {
setBusy(false)
if (successMessage) toast({ title: successMessage, variant: 'success' })
}
}
const installFrom = async (kind: 'directory' | 'package'): Promise<void> => {
const target =
kind === 'directory'
? await window.api.pickExtensionDirectory()
: await window.api.pickExtensionPackage()
if (!target) return
setBusy(true)
try {
const result =
kind === 'directory'
? await window.api.installExtensionFromDirectory(target)
: await window.api.installExtensionFromPackage(target)
if (!result.success) {
toast({
title: '安装失败',
description: result.error?.message || '扩展安装失败',
variant: 'destructive'
})
return
}
await refresh()
if (result.extension) setSelectedId(result.extension.id)
toast({
title: '扩展已安装',
description: `${result.extension?.name || ''} ${result.extension?.version || ''}`.trim(),
variant: 'success'
})
} finally {
setBusy(false)
}
}
const requestEnable = (extension: InstalledExtension): void => {
const risky = extension.permissions.filter(
(permission) => EXTENSION_PERMISSION_INFO[permission].risk !== 'low'
)
if (risky.length > 0) {
setPendingEnable(extension)
return
}
void toggleEnabled(extension, true)
}
const toggleEnabled = async (extension: InstalledExtension, enabled: boolean): Promise<void> => {
setPendingEnable(null)
const result = await run(() => window.api.setExtensionEnabled(extension.id, enabled))
if (result?.success) {
toast({
title: enabled ? '扩展已启用' : '扩展已停用',
description: extension.name,
variant: 'success'
})
await refresh()
} else if (result && !result.success) {
toast({
title: enabled ? '启用失败' : '停用失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const confirmUninstall = async (extension: InstalledExtension): Promise<void> => {
setPendingUninstall(null)
const result = await run(() => window.api.uninstallExtension(extension.id, true))
if (result?.success) {
toast({ title: '扩展已卸载', description: '扩展数据已保留', variant: 'success' })
await refresh()
} else if (result && !result.success) {
toast({
title: '卸载失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
if (page) {
return (
<ExtensionPageHost
descriptor={page}
onBack={() => {
setPage(null)
void refresh().catch(() => undefined)
}}
/>
)
}
return (
<div className="extension-workspace">
<aside className="extension-sidebar">
<header className="extension-sidebar-header">
<div>
<h2>扩展</h2>
<p>把二次开发从官方源码里剥离出来</p>
</div>
<span className="extension-count">{extensions.length}</span>
</header>
<div className="extension-install-row">
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => void installFrom('directory')}
>
安装目录
</Button>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => void installFrom('package')}
>
安装 ZIP
</Button>
</div>
<div className="extension-list" role="listbox" aria-label="已安装扩展">
{extensions.length === 0 ? (
<p className="extension-empty">
还没有安装扩展。可以在 <code>examples/extensions</code> 下找到两个可直接安装的示例。
</p>
) : (
extensions.map((extension) => (
<button
key={extension.id}
type="button"
role="option"
aria-selected={extension.id === selectedId}
className={`extension-list-item ${extension.id === selectedId ? 'is-active' : ''}`}
onClick={() => setSelectedId(extension.id)}
>
<span
className={`extension-status-dot tone-${statusTone(extension)}`}
aria-hidden
/>
<span className="extension-list-main">
<span className="extension-list-name">{extension.name}</span>
<span className="extension-list-meta">
v{extension.version} ·{' '}
{extension.enabled ? STATUS_LABELS[extension.runtime.state] : '已停用'}
</span>
</span>
</button>
))
)}
</div>
</aside>
<section className="extension-detail" aria-label="扩展详情">
{!selected ? (
<div className="extension-detail-empty">
<h3>选择左侧的扩展</h3>
<p>安装后在这里查看权限、页面、自动化动作与执行日志。</p>
</div>
) : (
<>
<header className="extension-detail-header">
<div>
<div className="extension-detail-title">
<h3>{selected.name}</h3>
<span className="extension-version">v{selected.version}</span>
<span className={`extension-badge tone-${statusTone(selected)}`}>
{selected.enabled ? STATUS_LABELS[selected.runtime.state] : '已停用'}
</span>
</div>
<p className="extension-detail-description">
{selected.description || '该扩展没有提供描述。'}
</p>
<p className="extension-detail-id">{selected.id}</p>
{!selected.compatibility.compatible && (
<p className="extension-incompatible">
{selected.compatibility.reason || '扩展与当前版本不兼容'}
</p>
)}
{selected.runtime.lastError && (
<p className="extension-runtime-error">{selected.runtime.lastError}</p>
)}
</div>
<div className="extension-detail-actions">
<Button
size="sm"
variant={selected.enabled ? 'outline' : 'default'}
disabled={busy || !selected.compatibility.compatible}
onClick={() =>
selected.enabled ? void toggleEnabled(selected, false) : requestEnable(selected)
}
>
{selected.enabled ? '停用' : '启用'}
</Button>
{selected.pages.length > 0 && (
<Button
size="sm"
variant="secondary"
onClick={() => {
void window.api
.getExtensionPageUrl(selected.id, selected.pages[0]?.id)
.then(setPage)
.catch(() => undefined)
}}
>
打开页面
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => void window.api.openExtensionDataDir(selected.id)}
>
数据目录
</Button>
</div>
</header>
<div className="extension-detail-grid">
<section className="extension-card">
<h4>页面</h4>
{selected.pages.length === 0 ? (
<p className="extension-muted">该扩展没有注册页面。</p>
) : (
<ul className="extension-page-list">
{selected.pages.map((item) => (
<li key={item.id}>
<span>{item.title}</span>
<Button
size="sm"
variant="link"
onClick={() => {
void window.api
.getExtensionPageUrl(selected.id, item.id)
.then(setPage)
.catch(() => undefined)
}}
>
打开
</Button>
</li>
))}
</ul>
)}
</section>
<section className="extension-card">
<h4>权限</h4>
{selected.permissions.length === 0 ? (
<p className="extension-muted">未申请任何权限。</p>
) : (
<ul className="extension-permission-list">
{sortPermissionsByRisk(selected.permissions).map((permission) => (
<li key={permission}>
<div>
<span className="extension-permission-label">
{EXTENSION_PERMISSION_INFO[permission].label}
</span>
<span
className={`extension-permission-risk risk-${EXTENSION_PERMISSION_INFO[permission].risk}`}
>
{EXTENSION_PERMISSION_INFO[permission].risk === 'high'
? '高'
: EXTENSION_PERMISSION_INFO[permission].risk === 'medium'
? '中'
: '低'}
</span>
</div>
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
<span
className={`extension-grant ${selected.grantedPermissions.includes(permission) ? 'is-granted' : ''}`}
>
{selected.grantedPermissions.includes(permission) ? '已授予' : '未授予'}
</span>
</li>
))}
</ul>
)}
</section>
<section className="extension-card extension-card-wide">
<h4>自动化动作</h4>
{selected.automationActions.length === 0 ? (
<p className="extension-muted">该扩展没有注册自动化动作。</p>
) : (
<ul className="extension-action-list">
{selected.automationActions.map((action) => (
<li key={action.id}>
<span>{action.title}</span>
<span
className={`extension-grant ${action.registered ? 'is-granted' : ''}`}
>
{action.registered ? '已注册' : '未注册'}
</span>
</li>
))}
</ul>
)}
</section>
<section className="extension-card extension-card-wide">
<div className="extension-card-header">
<h4>运行日志</h4>
<Button
size="sm"
variant="ghost"
onClick={() => {
void window.api.clearExtensionLogs(selected.id).then(() => setLogs([]))
}}
>
清空
</Button>
</div>
{logs.length === 0 ? (
<p className="extension-muted">暂无日志。</p>
) : (
<ul className="extension-log-list">
{logs.map((entry) => (
<li key={entry.id} className={`log-${entry.level}`}>
<span className="extension-log-time">{formatTimestamp(entry.at)}</span>
<span className="extension-log-source">
{entry.source === 'extension' ? '扩展' : '宿主'}
</span>
<span className="extension-log-message">{entry.message}</span>
</li>
))}
</ul>
)}
</section>
</div>
<footer className="extension-detail-footer">
<span>安装于 {formatTimestamp(selected.installedAt)}</span>
{pendingUninstall === selected.id ? (
<span className="extension-uninstall-confirm">
卸载后扩展代码会被移除,配置与数据默认保留。
<Button
size="sm"
variant="destructive"
onClick={() => void confirmUninstall(selected)}
>
确认卸载
</Button>
<Button size="sm" variant="ghost" onClick={() => setPendingUninstall(null)}>
取消
</Button>
</span>
) : (
<Button size="sm" variant="ghost" onClick={() => setPendingUninstall(selected.id)}>
卸载
</Button>
)}
</footer>
</>
)}
</section>
{pendingEnable && (
<div className="extension-modal-backdrop" role="dialog" aria-modal="true">
<div className="extension-modal">
<h3>启用「{pendingEnable.name}」</h3>
<p>该扩展会获得以下权限。扩展代码在独立进程中运行,但仍属于受信任的本地代码。</p>
<ul className="extension-permission-list">
{sortPermissionsByRisk(pendingEnable.permissions).map(
(permission: ExtensionPermission) => (
<li key={permission}>
<div>
<span className="extension-permission-label">
{EXTENSION_PERMISSION_INFO[permission].label}
</span>
</div>
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
</li>
)
)}
</ul>
<div className="extension-modal-actions">
<Button variant="ghost" onClick={() => setPendingEnable(null)}>
取消
</Button>
<Button onClick={() => void toggleEnabled(pendingEnable, true)}>确认启用</Button>
</div>
</div>
</div>
)}
{busy && (
<div className="extension-busy" aria-live="polite">
<Spinner />
</div>
)}
</div>
)
}
+597
View File
@@ -0,0 +1,597 @@
/* 扩展中心:左侧扩展列表 + 右侧详情 / 扩展页面容器。 */
.extension-workspace {
box-sizing: border-box;
display: grid;
grid-template-columns: 288px minmax(0, 1fr);
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
background: var(--wxex-bg-main);
color: var(--wxex-text-primary);
font-family: var(--wxex-font);
}
.extension-sidebar {
display: flex;
flex-direction: column;
min-height: 0;
gap: 12px;
padding: 24px 16px 16px;
border-right: 1px solid var(--wxex-border);
background: var(--wxex-bg-sidebar);
}
.extension-sidebar-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 0 4px;
h2 {
margin: 0;
font-size: 18px;
line-height: 24px;
font-weight: 700;
}
p {
margin: 4px 0 0;
color: var(--wxex-text-muted);
font-size: 12px;
line-height: 18px;
}
}
.extension-count {
min-width: 24px;
height: 22px;
padding: 0 7px;
border-radius: 999px;
background: var(--wxex-brand-soft);
color: var(--wxex-brand);
font-size: 12px;
font-weight: 600;
line-height: 22px;
text-align: center;
}
.extension-install-row {
display: flex;
gap: 8px;
padding: 0 4px;
}
.extension-list {
display: flex;
flex-direction: column;
gap: 4px;
min-height: 0;
overflow: auto;
padding: 2px 0 8px;
}
.extension-list-item {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 10px 10px;
border: 1px solid transparent;
border-radius: var(--wxex-radius-md);
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
&:hover {
background: var(--wxex-brand-soft);
}
&.is-active {
border-color: var(--wxex-border);
background: var(--wxex-bg-elevated);
box-shadow: var(--wxex-shadow-popover);
}
}
.extension-status-dot {
flex: 0 0 auto;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--wxex-text-muted);
&.tone-success {
background: var(--wxex-success);
}
&.tone-warning {
background: var(--wxex-warning);
}
&.tone-danger {
background: var(--wxex-danger);
}
}
.extension-list-main {
display: flex;
flex-direction: column;
min-width: 0;
}
.extension-list-name {
font-size: 13px;
font-weight: 600;
line-height: 18px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.extension-list-meta {
color: var(--wxex-text-muted);
font-size: 11px;
line-height: 16px;
}
.extension-empty {
margin: 8px 4px;
color: var(--wxex-text-muted);
font-size: 12px;
line-height: 19px;
}
.extension-detail {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
overflow: auto;
padding: 28px clamp(20px, 3vw, 40px) 32px;
gap: 18px;
}
.extension-detail-empty {
margin: auto;
max-width: 42ch;
text-align: center;
color: var(--wxex-text-muted);
h3 {
margin: 0 0 8px;
color: var(--wxex-text-primary);
font-size: 16px;
}
p {
margin: 0;
font-size: 13px;
line-height: 20px;
}
}
.extension-detail-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
flex-wrap: wrap;
}
.extension-detail-title {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
h3 {
margin: 0;
font-size: 22px;
line-height: 30px;
font-weight: 700;
}
}
.extension-version {
color: var(--wxex-text-muted);
font-size: 12px;
}
.extension-badge {
padding: 2px 8px;
border-radius: 999px;
background: var(--wxex-bg-sidebar);
color: var(--wxex-text-secondary);
font-size: 11px;
font-weight: 600;
line-height: 18px;
&.tone-success {
background: color-mix(in srgb, var(--wxex-success) 14%, transparent);
color: var(--wxex-success);
}
&.tone-warning {
background: color-mix(in srgb, var(--wxex-warning) 16%, transparent);
color: var(--wxex-warning);
}
&.tone-danger {
background: color-mix(in srgb, var(--wxex-danger) 14%, transparent);
color: var(--wxex-danger);
}
}
.extension-detail-description {
margin: 8px 0 0;
max-width: 72ch;
color: var(--wxex-text-secondary);
font-size: 13px;
line-height: 20px;
}
.extension-detail-id {
margin: 6px 0 0;
color: var(--wxex-text-muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
.extension-incompatible,
.extension-runtime-error {
margin: 8px 0 0;
padding: 6px 10px;
border-radius: var(--wxex-radius-sm);
background: color-mix(in srgb, var(--wxex-danger) 10%, transparent);
color: var(--wxex-danger);
font-size: 12px;
line-height: 18px;
}
.extension-detail-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding-top: 4px;
}
.extension-detail-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.extension-card {
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
padding: 16px 18px;
border: 1px solid var(--wxex-border);
border-radius: var(--wxex-radius-lg);
background: var(--wxex-bg-elevated);
h4 {
margin: 0;
font-size: 13px;
font-weight: 700;
}
}
.extension-card-wide {
grid-column: 1 / -1;
}
.extension-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.extension-muted {
margin: 0;
color: var(--wxex-text-muted);
font-size: 12px;
line-height: 19px;
}
.extension-hint {
margin: 0;
color: var(--wxex-text-muted);
font-size: 11px;
line-height: 17px;
}
.extension-page-list,
.extension-action-list {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: 13px;
}
}
.extension-permission-list {
display: flex;
flex-direction: column;
gap: 12px;
margin: 0;
padding: 0;
list-style: none;
li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 10px;
padding-bottom: 10px;
border-bottom: 1px solid var(--wxex-border);
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
> div {
flex: 1 1 auto;
min-width: 0;
}
> .extension-grant {
margin-left: auto;
}
}
p {
flex: 0 0 100%;
order: 3;
margin: 0;
color: var(--wxex-text-muted);
font-size: 11px;
line-height: 17px;
}
}
.extension-permission-label {
font-size: 13px;
font-weight: 600;
}
.extension-permission-risk {
margin-left: 6px;
padding: 0 5px;
border-radius: 4px;
font-size: 10px;
font-weight: 600;
line-height: 16px;
&.risk-high {
background: color-mix(in srgb, var(--wxex-danger) 14%, transparent);
color: var(--wxex-danger);
}
&.risk-medium {
background: color-mix(in srgb, var(--wxex-warning) 16%, transparent);
color: var(--wxex-warning);
}
&.risk-low {
background: var(--wxex-bg-sidebar);
color: var(--wxex-text-muted);
}
}
.extension-grant {
align-self: flex-start;
padding: 1px 7px;
border-radius: 999px;
background: var(--wxex-bg-sidebar);
color: var(--wxex-text-muted);
font-size: 10px;
line-height: 16px;
white-space: nowrap;
&.is-granted {
background: color-mix(in srgb, var(--wxex-success) 12%, transparent);
color: var(--wxex-success);
}
}
.extension-log-list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 0;
padding: 0;
max-height: 320px;
overflow: auto;
list-style: none;
li {
display: grid;
grid-template-columns: 132px 40px minmax(0, 1fr);
gap: 10px;
align-items: baseline;
padding: 4px 6px;
border-radius: var(--wxex-radius-sm);
font-size: 12px;
line-height: 18px;
&.log-warn {
background: color-mix(in srgb, var(--wxex-warning) 8%, transparent);
}
&.log-error {
background: color-mix(in srgb, var(--wxex-danger) 8%, transparent);
color: var(--wxex-danger);
}
}
}
.extension-log-time {
color: var(--wxex-text-muted);
font-variant-numeric: tabular-nums;
font-size: 11px;
}
.extension-log-source {
color: var(--wxex-text-muted);
font-size: 11px;
}
.extension-log-message {
min-width: 0;
overflow-wrap: anywhere;
}
.extension-detail-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
padding-top: 6px;
color: var(--wxex-text-muted);
font-size: 11px;
}
.extension-uninstall-confirm {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
color: var(--wxex-danger);
}
.extension-modal-backdrop {
position: fixed;
inset: 0;
z-index: 60;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(15, 20, 18, 0.42);
}
.extension-modal {
width: min(520px, 100%);
max-height: 80vh;
overflow: auto;
padding: 22px 24px;
border-radius: var(--wxex-radius-lg);
background: var(--wxex-bg-elevated);
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.24);
h3 {
margin: 0 0 6px;
font-size: 16px;
}
> p {
margin: 0 0 14px;
color: var(--wxex-text-secondary);
font-size: 12px;
line-height: 19px;
}
}
.extension-modal-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 18px;
}
.extension-busy {
position: fixed;
inset: 0;
z-index: 70;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--wxex-bg-main) 55%, transparent);
}
/* 扩展页面容器:iframe 铺满,头部保留返回入口。 */
.extension-page-host {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
background: var(--wxex-bg-main);
}
.extension-page-host-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 10px 16px;
border-bottom: 1px solid var(--wxex-border);
}
.extension-page-host-title {
display: flex;
flex-direction: column;
align-items: center;
line-height: 16px;
span {
color: var(--wxex-text-muted);
font-size: 10px;
}
}
.extension-page-host-body {
position: relative;
flex: 1;
min-height: 0;
background: var(--wxex-bg-elevated);
}
.extension-page-frame {
width: 100%;
height: 100%;
border: 0;
background: var(--wxex-bg-elevated);
}
.extension-page-host-loading {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
color: var(--wxex-text-muted);
font-size: 12px;
text-align: center;
}
@media (max-width: 1080px) {
.extension-workspace {
grid-template-columns: 232px minmax(0, 1fr);
}
.extension-detail-grid {
grid-template-columns: minmax(0, 1fr);
}
}
+1
View File
@@ -21,4 +21,5 @@
@use './group-member-stats';
@use './local-index';
@use './automation';
@use './extensions';
@use './theme';
+50 -12
View File
@@ -6,10 +6,7 @@
*/
import { normalizeGroupExitNotificationTemplate } from './group-exit-monitor'
import {
isSelectableReportTemplateId,
type SelectableReportTemplateId
} from './report-templates'
import { isSelectableReportTemplateId, type SelectableReportTemplateId } from './report-templates'
import type {
ScheduledReportMemberNameMode,
ScheduledReportMessageType,
@@ -321,9 +318,7 @@ export function calculateNextRunAt(scheduleTime: string, from: Date = new Date()
}
/** 收敛定时日报配置:未知值一律回落到安全默认,绝不落一条跑不起来的规则。 */
export function normalizeScheduledReportConfig(
input: unknown
): ScheduledReportAutomationConfig {
export function normalizeScheduledReportConfig(input: unknown): ScheduledReportAutomationConfig {
const raw = (input ?? {}) as Partial<ScheduledReportAutomationConfig>
const scheduleRaw = (raw.schedule ?? {}) as Partial<ScheduledReportAutomationConfig['schedule']>
const reportRaw = (raw.report ?? {}) as Partial<ScheduledReportAutomationConfig['report']>
@@ -421,13 +416,23 @@ export interface AutomationConditions {
}
/** 执行动作类型。顺序由 `actions` 数组顺序决定。 */
export type AutomationActionType = 'replyText' | 'generateReport' | 'sendReportImage'
export type AutomationActionType =
| 'replyText'
| 'generateReport'
| 'sendReportImage'
| 'extensionAction'
export interface AutomationAction {
type: AutomationActionType
enabled: boolean
/** `replyText` 的文案。 */
text?: string
/** `extensionAction`:提供动作的扩展 id。 */
extensionId?: string
/** `extensionAction`:扩展内注册的动作 id。 */
actionId?: string
/** `extensionAction`:用户配置的静态输入(JSON 对象)。 */
input?: Record<string, unknown>
}
export interface AutomationRule {
@@ -483,6 +488,7 @@ export type AutomationStepStatus = 'pending' | 'running' | 'success' | 'failed'
export type AutomationStepKey =
| 'received'
| 'matched'
| 'extension_action'
| 'reply'
| 'report'
| 'send'
@@ -771,6 +777,7 @@ export const LEAVE_NOTIFICATION_RULE_NAME = '退群通知'
export const AUTOMATION_STEP_LABELS: Record<AutomationStepKey, string> = {
received: '收到消息',
matched: '规则匹配',
extension_action: '执行扩展动作',
reply: '回复确认',
report: '生成日报',
send: '发送日报图片',
@@ -998,7 +1005,8 @@ export function describeRuleActions(rule: AutomationRule): string {
const labels: Record<AutomationActionType, string> = {
replyText: '回复确认',
generateReport: '生成日报',
sendReportImage: '发送图片'
sendReportImage: '发送图片',
extensionAction: '执行扩展动作'
}
const enabled = rule.actions.filter((action) => action.enabled)
return enabled.length ? enabled.map((action) => labels[action.type]).join(' → ') : '无动作'
@@ -1152,6 +1160,29 @@ export function createDefaultScheduledReportRule(
}
}
/** 扩展动作静态输入的体积上限(序列化后字符数)。 */
export const EXTENSION_ACTION_INPUT_MAX_CHARS = 4_000
/**
* 收敛扩展动作的静态输入。
*
* 只接受 JSON 对象:数组 / 字符串会让「输入」变成不可预期的形状,
* 扩展作者无法在 `inputSchema` 里表达;超限直接丢弃而不是截断,
* 截断后的 JSON 可能语义完全不同。
*/
export function normalizeExtensionActionInput(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
try {
const text = JSON.stringify(value)
if (!text || text.length > EXTENSION_ACTION_INPUT_MAX_CHARS) return undefined
const parsed = JSON.parse(text) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
return parsed as Record<string, unknown>
} catch {
return undefined
}
}
/** 归一化用户提交的草稿:把未知值收敛成合法值,避免脏数据落盘。 */
export function normalizeRuleDraft(
input: unknown,
@@ -1177,13 +1208,19 @@ export function normalizeRuleDraft(
.map((action) => ({
type: action.type,
enabled: action.enabled !== false,
...(typeof action.text === 'string' ? { text: action.text } : {})
...(typeof action.text === 'string' ? { text: action.text } : {}),
...(typeof action.extensionId === 'string' ? { extensionId: action.extensionId.trim() } : {}),
...(typeof action.actionId === 'string' ? { actionId: action.actionId.trim() } : {}),
...(normalizeExtensionActionInput(action.input)
? { input: normalizeExtensionActionInput(action.input) }
: {})
}))
.filter(
(action) =>
action.type === 'replyText' ||
action.type === 'generateReport' ||
action.type === 'sendReportImage'
action.type === 'sendReportImage' ||
(action.type === 'extensionAction' && Boolean(action.extensionId && action.actionId))
)
const cooldown = Number(raw.cooldownSeconds)
const base = {
@@ -1243,7 +1280,8 @@ export function normalizeLeaveNotificationConfig(input: unknown): LeaveNotificat
...(effectiveType === 'contact' ? { contactId } : {})
},
template: normalizeLeaveNotificationTemplate(raw.template),
notifyScope: raw.notifyScope === 'selected' ? 'selected' : LEAVE_NOTIFICATION_DEFAULT_NOTIFY_SCOPE,
notifyScope:
raw.notifyScope === 'selected' ? 'selected' : LEAVE_NOTIFICATION_DEFAULT_NOTIFY_SCOPE,
notifyRoomIds: normalizeLeaveNotificationRoomIds(raw.notifyRoomIds),
// 用户手动保存一次即视为已确认目标,清除迁移提示。
...(raw.targetNeedsReview === true ? { targetNeedsReview: true } : {})
+98
View File
@@ -0,0 +1,98 @@
/**
* 扩展系统的稳定错误码。
*
* 调用方(UI / 扩展 SDK / 自动化 runner)只依赖这里的 `code`,
* 不解析 `message` —— 文案会改,错误码不会。
*/
export const EXTENSION_ERROR_CODES = [
'EXTENSION_NOT_FOUND',
'EXTENSION_DISABLED',
'EXTENSION_INCOMPATIBLE',
'EXTENSION_ALREADY_INSTALLED',
'EXTENSION_INSTALL_FAILED',
'EXTENSION_INVALID_MANIFEST',
'EXTENSION_INVALID_PATH',
'EXTENSION_HOST_UNAVAILABLE',
'PERMISSION_DENIED',
'CAPABILITY_UNAVAILABLE',
'LICENSE_REQUIRED',
'DATABASE_NOT_READY',
'SEND_NOT_SUPPORTED',
'ACTION_TIMEOUT',
'ACTION_FAILED',
'RATE_LIMITED',
'INVALID_REQUEST',
'STORAGE_LIMIT_EXCEEDED'
] as const
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
EXTENSION_NOT_FOUND: '找不到该扩展',
EXTENSION_DISABLED: '扩展当前未启用',
EXTENSION_INCOMPATIBLE: '扩展与当前 TraceMemo 版本不兼容',
EXTENSION_ALREADY_INSTALLED: '已安装同名扩展',
EXTENSION_INSTALL_FAILED: '扩展安装失败',
EXTENSION_INVALID_MANIFEST: '扩展 manifest 不合法',
EXTENSION_INVALID_PATH: '扩展资源路径不合法',
EXTENSION_HOST_UNAVAILABLE: '扩展后台进程不可用',
PERMISSION_DENIED: '扩展没有该权限',
CAPABILITY_UNAVAILABLE: '当前环境不具备该能力',
LICENSE_REQUIRED: '需要有效授权',
DATABASE_NOT_READY: '微信数据库尚未连接',
SEND_NOT_SUPPORTED: '当前发送能力不支持该消息类型',
ACTION_TIMEOUT: '扩展处理超时',
ACTION_FAILED: '扩展执行失败',
RATE_LIMITED: '触发频率限制,请稍后再试',
INVALID_REQUEST: '请求格式不合法',
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限'
}
export interface ExtensionErrorPayload {
code: ExtensionErrorCode
message: string
/** 可选的机器可读细节;**不允许**放聊天正文、文件路径、wxid。 */
detail?: string
}
export class ExtensionError extends Error {
readonly code: ExtensionErrorCode
constructor(code: ExtensionErrorCode, message?: string, options?: { cause?: unknown }) {
super(message || EXTENSION_ERROR_MESSAGES[code], options)
this.name = 'ExtensionError'
this.code = code
}
}
export function extensionError(code: ExtensionErrorCode, message?: string): ExtensionError {
return new ExtensionError(code, message)
}
export function isExtensionErrorCode(value: unknown): value is ExtensionErrorCode {
return typeof value === 'string' && (EXTENSION_ERROR_CODES as readonly string[]).includes(value)
}
/** 任意异常 → 可跨进程传输的错误载荷。未知异常一律落到 `ACTION_FAILED`。 */
export function toExtensionErrorPayload(error: unknown): ExtensionErrorPayload {
if (error instanceof ExtensionError) {
return { code: error.code, message: error.message }
}
if (error && typeof error === 'object') {
const candidate = error as { code?: unknown; message?: unknown }
if (isExtensionErrorCode(candidate.code)) {
return {
code: candidate.code,
message:
typeof candidate.message === 'string'
? candidate.message
: EXTENSION_ERROR_MESSAGES[candidate.code]
}
}
if (typeof candidate.message === 'string' && candidate.message.trim()) {
return { code: 'ACTION_FAILED', message: candidate.message.trim() }
}
}
return { code: 'ACTION_FAILED', message: EXTENSION_ERROR_MESSAGES.ACTION_FAILED }
}
+123
View File
@@ -0,0 +1,123 @@
import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
/**
* 投递给扩展的规范化消息事件。
*
* **字段契约**
* - `timestamp` 是 **epoch 毫秒**(MessageListener 内部是 epoch 秒,换算只在主进程做一次)。
* - `eventId` 对同一条微信消息稳定:`message:<sha1(sessionId:localId)>`,
* 扩展重启、后台补投都拿到同一个值,可直接用于幂等。
* - `text` 只在可安全还原为纯文本时出现;图片 / 语音 / 视频等不带正文。
*/
export interface ExtensionMessageEvent {
eventId: string
accountId: string
conversationId: string
messageId: string
senderId?: string
senderName?: string
isGroup: boolean
isSelf: boolean
type: ExtensionMessageType
text?: string
/** 真正 @ 到当前登录账号(来自 `atuserlist` ∩ 自身 username),不是正文里的 `@昵称`。 */
mentionsMe: boolean
timestamp: number
}
/** 事件协议版本。未来的持久化队列 / 可靠投递必须保持向后兼容。 */
export const EXTENSION_EVENT_PROTOCOL_VERSION = 1
export interface ExtensionEventEnvelope {
version: number
kind: 'message.received'
event: ExtensionMessageEvent
}
/**
* 微信 `local_type` / `messageType` → 扩展侧消息类型。
*
* 未列出的类型归到 `other`:扩展宁可收到一个明确的 `other`,
* 也不要因为宿主新增类型而静默收不到事件。
*/
export function mapWechatMessageType(messageType: number): ExtensionMessageType {
switch (Number(messageType)) {
case 1:
return 'text'
case 3:
return 'image'
case 34:
return 'voice'
case 43:
return 'video'
case 47:
return 'sticker'
case 49:
return 'link'
case 10000:
case 10002:
return 'system'
default:
return 'other'
}
}
export interface BuildExtensionMessageEventInput {
eventId: string
accountId: string
conversationId: string
messageId: string
senderId?: string
senderName?: string
isGroup: boolean
isSelf: boolean
messageType: number
content?: string
mentionsMe: boolean
/** epoch 秒,与 MessageListener 同口径。 */
createTimeSeconds: number
}
export function buildExtensionMessageEvent(
input: BuildExtensionMessageEventInput
): ExtensionMessageEvent {
const type = mapWechatMessageType(input.messageType)
const text = type === 'text' ? String(input.content ?? '') : ''
return {
eventId: input.eventId,
accountId: input.accountId,
conversationId: input.conversationId,
messageId: input.messageId,
...(input.senderId ? { senderId: input.senderId } : {}),
...(input.senderName ? { senderName: input.senderName } : {}),
isGroup: input.isGroup,
isSelf: input.isSelf,
type,
...(text ? { text } : {}),
mentionsMe: input.mentionsMe,
timestamp: Math.round(input.createTimeSeconds * 1000)
}
}
/**
* manifest 级订阅过滤。
*
* 这一层只做「扩展作者声明过的粗筛」;用户级的开关是扩展的启用状态与权限授予,
* 不在事件总线里再做第二套真相。
*/
export function shouldDeliverExtensionEvent(
subscriptions: ExtensionSubscriptions | undefined,
event: ExtensionMessageEvent
): boolean {
if (!subscriptions) return false
if (!subscriptions.includeSelf && event.isSelf) return false
if (subscriptions.requireMentionMe && !event.mentionsMe) return false
if (!subscriptions.messageTypes.includes(event.type)) return false
if (
subscriptions.conversationIds.length > 0 &&
!subscriptions.conversationIds.includes(event.conversationId)
) {
return false
}
return true
}
+62
View File
@@ -0,0 +1,62 @@
import type { ExtensionErrorPayload } from './errors'
/** 扩展中心 IPC 通道。渲染层只依赖这些常量,不手写通道字符串。 */
export const EXTENSION_IPC = {
list: 'extension:list',
detail: 'extension:get',
installDirectory: 'extension:installDirectory',
installPackage: 'extension:installPackage',
pickDirectory: 'extension:pickDirectory',
pickPackage: 'extension:pickPackage',
setEnabled: 'extension:setEnabled',
uninstall: 'extension:uninstall',
logs: 'extension:getLogs',
clearLogs: 'extension:clearLogs',
pageUrl: 'extension:getPageUrl',
pageRequest: 'extension:pageRequest',
openDataDir: 'extension:openDataDir',
changed: 'extension:changed'
} as const
export type ExtensionChangeReason =
| 'installed'
| 'enabled'
| 'disabled'
| 'uninstalled'
| 'runtime'
| 'actions'
export interface ExtensionChangedEvent {
extensionId: string
reason: ExtensionChangeReason
}
export const EXTENSION_PAGE_MESSAGE_SOURCE = 'tracememo-extension-page'
export const EXTENSION_PAGE_HOST_SOURCE = 'tracememo-extension-host'
export interface ExtensionPageBridgeRequest {
source: typeof EXTENSION_PAGE_MESSAGE_SOURCE
extensionId: string
requestId: string
method: string
params?: Record<string, unknown>
}
export interface ExtensionPageBridgeResponse {
source: typeof EXTENSION_PAGE_HOST_SOURCE
requestId: string
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export function isExtensionPageBridgeRequest(value: unknown): value is ExtensionPageBridgeRequest {
if (!value || typeof value !== 'object') return false
const candidate = value as Partial<ExtensionPageBridgeRequest>
return (
candidate.source === EXTENSION_PAGE_MESSAGE_SOURCE &&
typeof candidate.extensionId === 'string' &&
typeof candidate.requestId === 'string' &&
typeof candidate.method === 'string'
)
}
+419
View File
@@ -0,0 +1,419 @@
import {
EXTENSION_PERMISSIONS,
normalizeExtensionPermissions,
type ExtensionPermission
} from './permissions'
/**
* 扩展 manifest v1。
*
* 校验策略:**未知值一律拒绝而不是静默丢弃**。一个拼错的权限名如果被悄悄忽略,
* 扩展会在运行期以 `PERMISSION_DENIED` 失败,而作者看到的是「manifest 合法」。
*/
export const EXTENSION_MANIFEST_VERSION = 1
/** 宿主实现的扩展 API 主版本。扩展的 `apiVersion` 主版本必须与它相同。 */
export const EXTENSION_API_VERSION = '1'
/** 低于该版本的 TraceMemo 不允许安装本 SDK 产出的扩展。 */
export const EXTENSION_MIN_APP_VERSION = '2.6.0'
export type ExtensionMessageType =
| 'text'
| 'image'
| 'voice'
| 'video'
| 'sticker'
| 'file'
| 'link'
| 'system'
| 'other'
export const EXTENSION_MESSAGE_TYPES: readonly ExtensionMessageType[] = [
'text',
'image',
'voice',
'video',
'sticker',
'file',
'link',
'system',
'other'
]
export interface ExtensionPageContribution {
id: string
title: string
/** 相对扩展根目录的 HTML 路径;缺省用 `entrypoints.page`。 */
entry?: string
}
export interface ExtensionAutomationActionContribution {
id: string
title: string
description?: string
}
export interface ExtensionSubscriptions {
messageTypes: ExtensionMessageType[]
/** 空数组 = 不按会话过滤。非空时只投递这些会话。 */
conversationIds: string[]
requireMentionMe: boolean
/** 默认 false:扩展默认收不到自己发出的消息。 */
includeSelf: boolean
}
export interface ExtensionManifest {
manifestVersion: number
id: string
name: string
version: string
apiVersion: string
minAppVersion?: string
description?: string
author?: string
homepage?: string
permissions: ExtensionPermission[]
entrypoints: {
page?: string
background?: string
}
subscriptions?: ExtensionSubscriptions
contributions: {
pages: ExtensionPageContribution[]
automationActions: ExtensionAutomationActionContribution[]
}
}
export interface ExtensionCompatibility {
compatible: boolean
code?: 'api_version' | 'app_version' | 'manifest'
reason?: string
}
export interface ManifestParseResult {
ok: boolean
manifest?: ExtensionManifest
code?: 'EXTENSION_INVALID_MANIFEST' | 'EXTENSION_INCOMPATIBLE'
message?: string
}
const EXTENSION_ID_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
const RESERVED_ID_PREFIXES = ['com.tracememo.', 'tracememo.', 'tm.']
const SEMVER_PATTERN = /^(\d{1,4})\.(\d{1,4})\.(\d{1,4})(?:-[0-9A-Za-z.-]{1,40})?$/
const PAGE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/
const ACTION_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{1,63}$/
const MAX_PAGES = 20
const MAX_AUTOMATION_ACTIONS = 20
const MAX_NAME_LENGTH = 64
const MAX_DESCRIPTION_LENGTH = 500
const MAX_CONVERSATION_SCOPE = 200
export function isValidExtensionId(value: unknown): value is string {
if (typeof value !== 'string') return false
const id = value.trim()
if (id.length < 3 || id.length > 128) return false
if (!EXTENSION_ID_PATTERN.test(id)) return false
return !RESERVED_ID_PREFIXES.some((prefix) => id.startsWith(prefix))
}
export function isValidExtensionVersion(value: unknown): value is string {
return typeof value === 'string' && SEMVER_PATTERN.test(value.trim())
}
/**
* 纯数字比较,忽略 prerelease。
*
* `minAppVersion` 的语义是「最低可运行版本」,把 `2.6.0-beta.1` 判成低于 `2.6.0`
* 会让预发布构建无法安装明示支持的扩展;宁可放行,也不误伤。
*/
export function compareSemver(left: string, right: string): number | null {
const a = SEMVER_PATTERN.exec(String(left || '').trim())
const b = SEMVER_PATTERN.exec(String(right || '').trim())
if (!a || !b) return null
for (let index = 1; index <= 3; index += 1) {
const delta = Number(a[index]) - Number(b[index])
if (delta !== 0) return delta > 0 ? 1 : -1
}
return 0
}
export function isApiVersionCompatible(
apiVersion: unknown,
hostApiVersion = EXTENSION_API_VERSION
): boolean {
const declared = String(apiVersion ?? '').trim()
if (!/^\d+$/.test(declared)) return false
return declared === String(hostApiVersion).trim()
}
export function checkExtensionCompatibility(
input: { apiVersion?: unknown; minAppVersion?: unknown },
appVersion: string
): ExtensionCompatibility {
if (!isApiVersionCompatible(input.apiVersion)) {
return {
compatible: false,
code: 'api_version',
reason: `扩展 API 版本 ${String(input.apiVersion ?? '')} 与当前 TraceMemo 不兼容`
}
}
const minAppVersion = String(input.minAppVersion ?? '').trim()
if (!minAppVersion) return { compatible: true }
if (!isValidExtensionVersion(minAppVersion)) {
return { compatible: false, code: 'manifest', reason: 'minAppVersion 不是合法版本号' }
}
const compared = compareSemver(appVersion, minAppVersion)
if (compared === null) return { compatible: true }
if (compared < 0) {
return {
compatible: false,
code: 'app_version',
reason: `需要 TraceMemo ${minAppVersion} 或更高版本(当前 ${appVersion})`
}
}
return { compatible: true }
}
/**
* 相对路径安全检查(纯字符串层)。
*
* 只做语法判断;**真实路径是否仍在扩展目录内必须由主进程用 realpath 再验一次** ——
* 符号链接可以绕过任何纯字符串检查。
*/
export function isSafeRelativeEntryPath(value: unknown): value is string {
if (typeof value !== 'string') return false
const raw = value.trim().replace(/\\/g, '/')
if (!raw || raw.length > 240) return false
if (raw.includes('\0')) return false
if (raw.startsWith('/') || raw.startsWith('//')) return false
if (/^[A-Za-z]:/.test(raw)) return false
const segments = raw.split('/')
if (segments.length > 10) return false
for (const segment of segments) {
if (!segment || segment === '.' || segment === '..') return false
if (segment.length > 64) return false
if (!/^[A-Za-z0-9._@+\- ]+$/.test(segment)) return false
if (/[. ]$/.test(segment)) return false
// Windows 对 `con.txt` 与 `con` 一视同仁,保留名按「点前的主干」判断。
if (/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(segment)) return false
}
return true
}
function asTrimmedString(value: unknown, maxLength: number): string {
if (typeof value !== 'string') return ''
return value.trim().slice(0, maxLength)
}
function parseMessageTypes(input: unknown): ExtensionMessageType[] {
if (!Array.isArray(input)) return ['text']
const result: ExtensionMessageType[] = []
for (const value of input) {
if (typeof value !== 'string') return []
if (!EXTENSION_MESSAGE_TYPES.includes(value as ExtensionMessageType)) return []
const typed = value as ExtensionMessageType
if (!result.includes(typed)) result.push(typed)
}
return result.length ? result : ['text']
}
function parseSubscriptions(input: unknown): ExtensionSubscriptions | null {
if (input === undefined) return null
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
const raw = input as Record<string, unknown>
const messageTypes = parseMessageTypes(raw.messageTypes)
if (!messageTypes.length) return null
const conversationIds: string[] = []
if (raw.conversationIds !== undefined) {
if (!Array.isArray(raw.conversationIds)) return null
if (raw.conversationIds.length > MAX_CONVERSATION_SCOPE) return null
for (const value of raw.conversationIds) {
if (typeof value !== 'string') return null
const id = value.trim()
if (!id || id.length > 128) return null
if (!conversationIds.includes(id)) conversationIds.push(id)
}
}
return {
messageTypes,
conversationIds,
requireMentionMe: raw.requireMentionMe === true,
includeSelf: raw.includeSelf === true
}
}
function parsePages(input: unknown): ExtensionPageContribution[] | null {
if (input === undefined) return []
if (!Array.isArray(input) || input.length > MAX_PAGES) return null
const pages: ExtensionPageContribution[] = []
for (const value of input) {
if (!value || typeof value !== 'object') return null
const raw = value as Record<string, unknown>
const id = asTrimmedString(raw.id, 32)
const title = asTrimmedString(raw.title, 40)
if (!PAGE_ID_PATTERN.test(id) || !title) return null
if (pages.some((page) => page.id === id)) return null
if (raw.entry !== undefined) {
if (!isSafeRelativeEntryPath(raw.entry)) return null
pages.push({ id, title, entry: raw.entry })
} else {
pages.push({ id, title })
}
}
return pages
}
function parseAutomationActions(input: unknown): ExtensionAutomationActionContribution[] | null {
if (input === undefined) return []
if (!Array.isArray(input) || input.length > MAX_AUTOMATION_ACTIONS) return null
const actions: ExtensionAutomationActionContribution[] = []
for (const value of input) {
if (!value || typeof value !== 'object') return null
const raw = value as Record<string, unknown>
const id = asTrimmedString(raw.id, 64)
const title = asTrimmedString(raw.title, 60)
if (!ACTION_ID_PATTERN.test(id) || !title) return null
if (actions.some((action) => action.id === id)) return null
const description = asTrimmedString(raw.description, 200)
actions.push({ id, title, ...(description ? { description } : {}) })
}
return actions
}
function fail(
message: string,
code: ManifestParseResult['code'] = 'EXTENSION_INVALID_MANIFEST'
): ManifestParseResult {
return { ok: false, code, message }
}
/** 解析并收敛 manifest。失败时返回**具体**原因,供安装界面直接展示。 */
export function parseExtensionManifest(
input: unknown,
options: { appVersion?: string } = {}
): ManifestParseResult {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
return fail('manifest 必须是 JSON 对象')
}
const raw = input as Record<string, unknown>
if (Number(raw.manifestVersion) !== EXTENSION_MANIFEST_VERSION) {
return fail(`manifestVersion 必须是 ${EXTENSION_MANIFEST_VERSION}`)
}
if (!isValidExtensionId(raw.id)) {
return fail('id 必须是反向域名形式(如 com.example.hello),且不能使用 TraceMemo 保留前缀')
}
const name = asTrimmedString(raw.name, MAX_NAME_LENGTH)
if (!name) return fail('name 不能为空')
if (!isValidExtensionVersion(raw.version)) return fail('version 必须是 x.y.z 形式')
if (!isApiVersionCompatible(raw.apiVersion)) {
return fail('apiVersion 与当前 TraceMemo 扩展 API 不兼容', 'EXTENSION_INCOMPATIBLE')
}
if (raw.minAppVersion !== undefined && !isValidExtensionVersion(raw.minAppVersion)) {
return fail('minAppVersion 必须是 x.y.z 形式')
}
if (!Array.isArray(raw.permissions)) return fail('permissions 必须是数组')
for (const permission of raw.permissions) {
if (
typeof permission !== 'string' ||
!(EXTENSION_PERMISSIONS as readonly string[]).includes(permission)
) {
return fail(`未知权限:${String(permission)}`)
}
}
const permissions = normalizeExtensionPermissions(raw.permissions)
const entrypointsRaw = raw.entrypoints
if (!entrypointsRaw || typeof entrypointsRaw !== 'object' || Array.isArray(entrypointsRaw)) {
return fail('entrypoints 必须是对象')
}
const entryRaw = entrypointsRaw as Record<string, unknown>
const entrypoints: ExtensionManifest['entrypoints'] = {}
if (entryRaw.page !== undefined) {
if (!isSafeRelativeEntryPath(entryRaw.page)) return fail('entrypoints.page 不是安全的相对路径')
entrypoints.page = entryRaw.page
}
if (entryRaw.background !== undefined) {
if (!isSafeRelativeEntryPath(entryRaw.background)) {
return fail('entrypoints.background 不是安全的相对路径')
}
entrypoints.background = entryRaw.background
}
const subscriptions = parseSubscriptions(raw.subscriptions)
if (raw.subscriptions !== undefined && subscriptions === null) {
return fail('subscriptions 字段不合法(messageTypes 必须是已知消息类型)')
}
const contributionsRaw = raw.contributions
if (
contributionsRaw !== undefined &&
(typeof contributionsRaw !== 'object' || Array.isArray(contributionsRaw))
) {
return fail('contributions 必须是对象')
}
const contributionsObject = (contributionsRaw ?? {}) as Record<string, unknown>
const pages = parsePages(contributionsObject.pages)
if (pages === null) return fail('contributions.pages 不合法')
const automationActions = parseAutomationActions(contributionsObject.automationActions)
if (automationActions === null) return fail('contributions.automationActions 不合法')
if (pages.length > 0 && !entrypoints.page) {
return fail('注册了页面但缺少 entrypoints.page')
}
if ((subscriptions !== null || automationActions.length > 0) && !entrypoints.background) {
return fail('声明了消息订阅或自动化动作,必须提供 entrypoints.background')
}
if (!entrypoints.page && !entrypoints.background) {
return fail('至少需要 entrypoints.page 或 entrypoints.background')
}
if (permissions.includes('messages.subscribe') && !subscriptions) {
return fail('申请 messages.subscribe 时必须声明 subscriptions')
}
const description = asTrimmedString(raw.description, MAX_DESCRIPTION_LENGTH)
const author = asTrimmedString(raw.author, 80)
const homepage = asTrimmedString(raw.homepage, 200)
const minAppVersion = asTrimmedString(raw.minAppVersion, 20)
const manifest: ExtensionManifest = {
manifestVersion: EXTENSION_MANIFEST_VERSION,
id: raw.id.trim(),
name,
version: String(raw.version).trim(),
apiVersion: String(raw.apiVersion).trim(),
...(minAppVersion ? { minAppVersion } : {}),
...(description ? { description } : {}),
...(author ? { author } : {}),
...(homepage && /^https?:\/\//.test(homepage) ? { homepage } : {}),
permissions,
entrypoints,
...(subscriptions ? { subscriptions } : {}),
contributions: { pages, automationActions }
}
if (options.appVersion) {
const compatibility = checkExtensionCompatibility(manifest, options.appVersion)
if (!compatibility.compatible) {
return fail(compatibility.reason || '扩展与当前版本不兼容', 'EXTENSION_INCOMPATIBLE')
}
}
return { ok: true, manifest }
}
/** 解析 manifest JSON 文本。JSON 语法错误与 schema 错误分开报,便于作者定位。 */
export function parseExtensionManifestJson(
text: string,
options: { appVersion?: string } = {}
): ManifestParseResult {
let value: unknown
try {
value = JSON.parse(text)
} catch {
return fail('manifest.json 不是合法 JSON')
}
return parseExtensionManifest(value, options)
}
+127
View File
@@ -0,0 +1,127 @@
/**
* 扩展权限目录。
*
* 权限是**宿主授予**的,不是扩展自己声称的:manifest 里只声明「需要什么」,
* 真正生效的是 registry 里 `grantedPermissions` 与当前启用状态的交集。
*/
export const EXTENSION_PERMISSIONS = [
'messages.subscribe',
'messages.query',
'contacts.list',
'wechat.send.text',
'wechat.send.image',
'wechat.send.video',
'ai.chat',
'storage',
'automation.action'
] as const
export type ExtensionPermission = (typeof EXTENSION_PERMISSIONS)[number]
export type ExtensionPermissionRisk = 'low' | 'medium' | 'high'
export interface ExtensionPermissionInfo {
label: string
description: string
risk: ExtensionPermissionRisk
}
export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPermissionInfo> = {
'messages.subscribe': {
label: '接收新消息事件',
description:
'在 TraceMemo 监听运行期间接收新消息的规范化字段(会话、发送者、消息类型、正文)。',
risk: 'high'
},
'messages.query': {
label: '读取指定会话消息',
description: '按会话与时间窗口读取有上限的历史消息,不能遍历全部会话。',
risk: 'high'
},
'contacts.list': {
label: '读取群列表',
description: '读取本机通讯录中的群名称与会话 id,用于配置页选择发送目标;不包含聊天内容。',
risk: 'medium'
},
'wechat.send.text': {
label: '发送微信文本',
description: '经 TraceMemo 官方 Gateway 发送文本;仍需有效授权、本机发送能力与发送频率限制。',
risk: 'high'
},
'wechat.send.image': {
label: '发送微信图片',
description:
'经 TraceMemo 官方 Gateway 发送图片;只能使用扩展数据目录或临时目录中的文件,仍需有效授权与发送能力。',
risk: 'high'
},
'wechat.send.video': {
label: '发送微信视频',
description:
'经 TraceMemo 官方 Gateway 发送视频文件;原生 Host 以 video 类型提交,单文件不超过 100MB,仍需有效授权与发送能力。',
risk: 'high'
},
'ai.chat': {
label: '调用 AI 模型',
description: '使用 TraceMemo 已配置的 AI Provider 发起对话;扩展拿不到 API Key 明文。',
risk: 'medium'
},
storage: {
label: '扩展私有存储',
description: '读写本扩展独立的数据目录,不会接触其他扩展或官方数据。',
risk: 'low'
},
'automation.action': {
label: '注册自动化动作',
description: '向 TraceMemo 自动化中心注册动作,由用户在规则里选择后才会执行。',
risk: 'medium'
}
}
export function isExtensionPermission(value: unknown): value is ExtensionPermission {
return typeof value === 'string' && (EXTENSION_PERMISSIONS as readonly string[]).includes(value)
}
/** 去重、去空白、丢弃未知值。**未知权限在 manifest 校验阶段就会被拒绝**,这里只做收敛。 */
export function normalizeExtensionPermissions(input: unknown): ExtensionPermission[] {
if (!Array.isArray(input)) return []
const result: ExtensionPermission[] = []
for (const value of input) {
if (!isExtensionPermission(value)) continue
if (result.includes(value)) continue
result.push(value)
}
return result
}
export function hasExtensionPermission(
granted: readonly ExtensionPermission[] | undefined,
permission: ExtensionPermission
): boolean {
return Array.isArray(granted) && granted.includes(permission)
}
/** 界面按风险从高到低展示;同风险保持目录顺序。 */
export function sortPermissionsByRisk(
permissions: readonly ExtensionPermission[]
): ExtensionPermission[] {
const weight: Record<ExtensionPermissionRisk, number> = { high: 0, medium: 1, low: 2 }
return [...permissions].sort((left, right) => {
const delta =
weight[EXTENSION_PERMISSION_INFO[left].risk] - weight[EXTENSION_PERMISSION_INFO[right].risk]
if (delta !== 0) return delta
return EXTENSION_PERMISSIONS.indexOf(left) - EXTENSION_PERMISSIONS.indexOf(right)
})
}
/**
* 安装时自动授予的权限子集:只有低风险项。
*
* 高 / 中风险权限必须由用户在「启用扩展」时确认 —— 安装本身不应等于同意
* 读取消息或发送微信。
*/
export function autoGrantedPermissions(
permissions: readonly ExtensionPermission[]
): ExtensionPermission[] {
return permissions.filter((permission) => EXTENSION_PERMISSION_INFO[permission].risk === 'low')
}
+219
View File
@@ -0,0 +1,219 @@
import type { ExtensionEventEnvelope } from './events'
import type { ExtensionErrorPayload } from './errors'
/**
* 主进程 ↔ 扩展后台进程的私有协议。
*
* 只有主进程能构造 `invoke-action` / `event` / `call-result`;
* 扩展进程只能发 `call` / `register-action` / `log` / `action-result`。
* 任何「宿主可信元数据」(extensionId、origin、purpose、幂等键)都**由主进程填**,
* 不接受扩展侧传入。
*/
export const EXTENSION_HOST_PROTOCOL_VERSION = 1
export type ExtensionHostCallMethod =
| 'storage.get'
| 'storage.set'
| 'storage.remove'
| 'storage.list'
| 'messages.query'
| 'wechat.send.text'
| 'wechat.send.image'
| 'wechat.send.video'
| 'ai.chat'
| 'capabilities.get'
export interface ExtensionHostReady {
type: 'ready'
version: number
}
export interface ExtensionHostActivate {
type: 'activate'
version: number
extensionId: string
extensionDir: string
/** 扩展私有数据目录(`extensions-data/<id>`);媒体文件应落在这里。 */
dataDir: string
apiVersion: string
permissions: string[]
}
export interface ExtensionHostActivated {
type: 'activated'
version: number
ok: boolean
error?: ExtensionErrorPayload
}
export interface ExtensionHostShutdown {
type: 'shutdown'
version: number
}
export interface ExtensionHostCall {
type: 'call'
version: number
callId: string
method: ExtensionHostCallMethod
params: Record<string, unknown>
}
export interface ExtensionHostCallResult {
type: 'call-result'
version: number
callId: string
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export interface ExtensionHostEvent {
type: 'event'
version: number
envelope: ExtensionEventEnvelope
}
export interface ExtensionHostRegisterAction {
type: 'register-action'
version: number
action: {
id: string
title: string
description?: string
hasInputSchema: boolean
}
}
export interface ExtensionHostInvokeAction {
type: 'invoke-action'
version: number
requestId: string
actionId: string
input: Record<string, unknown>
timeoutMs: number
}
export interface ExtensionHostActionResult {
type: 'action-result'
version: number
requestId: string
ok: boolean
output?: ExtensionAutomationActionOutput
error?: ExtensionErrorPayload
}
export interface ExtensionHostTestSend {
type: 'test-send'
version: number
requestId: string
params: Record<string, unknown>
}
export interface ExtensionHostTestResult {
type: 'test-result'
version: number
requestId: string
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export interface ExtensionHostLog {
type: 'log'
version: number
level: 'info' | 'warn' | 'error'
message: string
}
export type ExtensionHostOutboundMessage =
| ExtensionHostReady
| ExtensionHostActivated
| ExtensionHostCall
| ExtensionHostRegisterAction
| ExtensionHostLog
| ExtensionHostActionResult
| ExtensionHostTestResult
export type ExtensionHostInboundMessage =
| ExtensionHostActivate
| ExtensionHostShutdown
| ExtensionHostCallResult
| ExtensionHostEvent
| ExtensionHostInvokeAction
| ExtensionHostTestSend
| ExtensionHostTestResult
/**
* 自动化动作的返回值。
*
* `reply` 是扩展**声明想发什么**,不是发送指令:真正的发送由宿主在
* 权限、授权校验、发送能力全部通过后经 `WechatActionGateway` 完成。
*/
export interface ExtensionAutomationActionOutput {
success: boolean
output?: Record<string, unknown>
reply?: {
type: 'text'
text: string
/** 群聊里要 @ 的 wxid → 显示名;仅 `wechat.send.text` 被授予时生效。 */
at?: Record<string, string>
}
/** 失败原因(用户可见的短句)。 */
error?: string
}
export interface ExtensionMessagesQueryRequest {
conversationId: string
/** epoch **毫秒**。 */
startTime?: number
/** epoch **毫秒**。 */
endTime?: number
limit?: number
}
export interface ExtensionQueriedMessage {
messageId: string
conversationId: string
senderId?: string
senderName?: string
isSelf: boolean
type: string
text?: string
/** epoch 毫秒。 */
timestamp: number
}
export interface ExtensionSendTextRequest {
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
to: string
text: string
at?: Record<string, string>
/** 扩展自定义去重键;相同键的重复请求会被 Gateway 审计短路。 */
dedupeKey?: string
}
/**
* 图片发送。
*
* 图片与视频是两条独立通道:视频必须显式用 `type: 'video'`,
* 由原生 Host 的 `/SendMsg` 以 video 类型提交。
*/
export interface ExtensionSendImageRequest {
to: string
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
path: string
dedupeKey?: string
}
export interface ExtensionSendVideoRequest {
to: string
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
path: string
dedupeKey?: string
}
export interface ExtensionSendTextResult {
actionId: string
status: 'sent'
}
+124
View File
@@ -0,0 +1,124 @@
import type { ExtensionCompatibility } from './manifest'
import type { ExtensionPermission } from './permissions'
import type { ExtensionErrorPayload } from './errors'
/** 扩展后台进程状态。`crashed` 表示连续崩溃后已停止自动重启,等用户手动处理。 */
export type ExtensionRuntimeState = 'inactive' | 'starting' | 'active' | 'error' | 'crashed'
export interface ExtensionRuntimeSnapshot {
state: ExtensionRuntimeState
since: number
restarts: number
/** 面向用户的一句话;**不含**路径、wxid、聊天正文。 */
lastError?: string
}
export interface ExtensionAutomationActionSummary {
/** 扩展内唯一 id(manifest 声明)。 */
id: string
title: string
description?: string
/** 宿主运行期是否真的注册成功(后台进程未启动时为 false)。 */
registered: boolean
}
export interface InstalledExtension {
id: string
name: string
version: string
apiVersion: string
minAppVersion?: string
description?: string
author?: string
enabled: boolean
installedAt: number
updatedAt: number
compatibility: ExtensionCompatibility
permissions: ExtensionPermission[]
grantedPermissions: ExtensionPermission[]
runtime: ExtensionRuntimeSnapshot
pages: Array<{ id: string; title: string }>
automationActions: ExtensionAutomationActionSummary[]
/** 扩展目录是否仍然存在;false 时 UI 必须显示为「文件缺失」而不是可启动。 */
filesPresent: boolean
}
export interface ExtensionLogEntry {
id: string
at: number
level: 'info' | 'warn' | 'error'
/** 来源:宿主自身事件,或扩展代码主动写入的日志。 */
source: 'core' | 'extension'
message: string
}
export interface ExtensionInstallResult {
success: boolean
extension?: InstalledExtension
error?: ExtensionErrorPayload
}
export interface ExtensionOperationResult {
success: boolean
error?: ExtensionErrorPayload
}
export interface ExtensionPageDescriptor {
extensionId: string
pageId: string
title: string
url: string
}
/** 渲染层可调用的页面侧能力白名单;扩展页面拿不到发送 / AI / 查询权限。 */
export type ExtensionPageMethod =
| 'storage.get'
| 'storage.set'
| 'storage.remove'
| 'storage.list'
| 'capabilities.get'
| 'contacts.listGroups'
| 'test.send'
| 'douyin.cookie.get'
| 'douyin.cookie.set'
| 'douyin.cookie.clear'
| 'extension.info'
export interface ExtensionPageRequest {
extensionId: string
method: ExtensionPageMethod
params?: Record<string, unknown>
}
export interface ExtensionPageResponse {
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export interface ExtensionCapabilitySnapshot {
extensionId: string
enabled: boolean
permissions: ExtensionPermission[]
platform: NodeJS.Platform
databaseReady: boolean
send: {
supported: boolean
ready: boolean
canSendText: boolean
/** 图片与视频是两条独立通道。 */
canSendImage: boolean
canSendVideo: boolean
/** 仅 `wechat.send.text` 被授予时才有意义。 */
licensed: boolean
message: string
}
ai: {
configured: boolean
modelName: string
}
}
export interface ExtensionQuitBehavior {
keepData: boolean
}
+16
View File
@@ -39,6 +39,8 @@ export interface PersonalWechatSenderStatus {
canSendText: boolean
canSendImage: boolean
canSendVoice: boolean
/** 视频与图片共用媒体通道;旧 runtime 不报告该字段。 */
canSendVideo?: boolean
message: string
error?: string
}
@@ -60,6 +62,8 @@ export interface PersonalWechatSendCapability {
text: boolean
image: boolean
voice: boolean
/** 图片/视频共用媒体通道;未报告的旧 runtime 视为 false。 */
video?: boolean
}
senderStatus: PersonalWechatSenderStatus
message: string
@@ -93,10 +97,22 @@ export interface PersonalWechatSendVoiceRequest extends PersonalWechatSendBaseRe
durationMs?: number
}
/**
* 视频发送。
*
* 原生 Host 走 `POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`;
* `filePath` 必须是本机可访问的普通文件。
*/
export interface PersonalWechatSendVideoRequest extends PersonalWechatSendBaseRequest {
type: 'video'
filePath: string
}
export type PersonalWechatSendRequest =
| PersonalWechatSendTextRequest
| PersonalWechatSendImageRequest
| PersonalWechatSendVoiceRequest
| PersonalWechatSendVideoRequest
/** Renderer 请求发送刚刚生成的 TTS 语音;Action 元数据由主进程补齐。 */
export interface PersonalWechatGeneratedTtsVoiceRequest {
+3
View File
@@ -74,6 +74,7 @@ export interface WechatActionRecipient {
export type WechatActionContent =
| { type: 'text'; text: string; at?: Record<string, string> }
| { type: 'image'; path: string }
| { type: 'video'; path: string }
| { type: 'voice'; path: string }
export interface WechatActionRequest {
@@ -127,6 +128,8 @@ export interface PolicyDecision {
export interface WechatActionAuditRecord {
actionId: string
idempotencyKey?: string
/** 扩展来源时为扩展 id;其他来源省略。 */
extensionId?: string
origin: WechatActionOrigin
purpose: WechatActionPurpose
triggerType: WechatActionTriggerType
@@ -0,0 +1,272 @@
import fs from 'fs-extra'
import path from 'node:path'
import { describe, expect, it, vi } from 'vitest'
const root = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs')
// eslint-disable-next-line @typescript-eslint/no-require-imports
const os = require('node:os') as typeof import('node:os')
// eslint-disable-next-line @typescript-eslint/no-require-imports
const path = require('node:path') as typeof import('node:path')
return fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-automation-'))
})
vi.mock('electron', () => ({
app: { getPath: () => root },
safeStorage: {
isEncryptionAvailable: () => false,
encryptString: (value: string) => Buffer.from(value, 'utf8'),
decryptString: (value: Buffer) => value.toString('utf8')
},
BrowserWindow: { getAllWindows: () => [] }
}))
import {
createDefaultDailyReportRule,
describeRuleActions,
normalizeRuleDraft,
type AutomationRule
} from '../../src/shared/automation'
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
import { AutomationActionRunner } from '../../src/main/services/automation-action-runner'
import { AutomationRuleStore } from '../../src/main/services/automation-rule-store'
const sent: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
function extensionRule(): AutomationRule {
return {
...createDefaultDailyReportRule(0),
id: 'rule-with-extension',
name: '关键词回复',
conditions: {
requireMentionMe: false,
keyword: '你好',
keywordMatchMode: 'contains',
conversationIds: [],
ignoreSelf: true
},
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
}
]
}
}
function runner(dependencies: {
reply?: { type: 'text'; text: string }
canSend?: boolean
fail?: boolean
}): {
instance: AutomationActionRunner
executeAction: ReturnType<
typeof vi.fn<(request: WechatActionRequest) => Promise<WechatActionResult>>
>
} {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sent
})
const instance = new AutomationActionRunner({
executeAction,
invokeExtensionAction: async () => {
if (dependencies.fail) throw new Error('扩展崩溃')
return {
success: true,
output: { matched: true },
...(dependencies.reply ? { reply: dependencies.reply } : {})
}
},
canExtensionSendText: () => dependencies.canSend !== false,
delay: async () => undefined,
now: () => 1_000
})
return { instance, executeAction }
}
const message = {
eventId: 'message:1',
accountId: 'wxid_self',
conversationId: 'fixture-room@chatroom',
messageId: '9001',
senderId: 'wxid_peer',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text' as const,
text: '你好',
mentionsMe: false,
timestamp: 1_700_000_000_000
}
describe('extension automation action', () => {
it('扩展返回 reply 后由宿主经 Gateway 发送', async () => {
const { instance, executeAction } = runner({ reply: { type: 'text', text: '你好呀!' } })
const result = await instance.run({
executionId: 'exec-1',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('success')
expect(result.steps.map((step) => step.key)).toEqual([
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
])
expect(executeAction).toHaveBeenCalledTimes(1)
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_action')
expect(request.triggerType).toBe('automation')
expect(request.idempotencyKey).toBe('extension_action:exec-1')
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture-room@chatroom' })
expect(request.content).toEqual({ type: 'text', text: '你好呀!' })
expect((request.metadata as { extensionId: string }).extensionId).toBe(
'com.example.keyword-bot'
)
})
it('扩展没有发送权限时拒绝发送,且不调用 Gateway', async () => {
const { instance, executeAction } = runner({
reply: { type: 'text', text: '你好呀!' },
canSend: false
})
const result = await instance.run({
executionId: 'exec-2',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('failed')
expect(result.errorSummary).toContain('wechat.send.text')
expect(executeAction).not.toHaveBeenCalled()
const reply = result.steps.find((step) => step.key === 'reply')
expect(reply?.status).toBe('failed')
})
it('扩展动作失败时后续步骤全部跳过', async () => {
const { instance, executeAction } = runner({ fail: true })
const result = await instance.run({
executionId: 'exec-3',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('failed')
expect(result.steps.find((step) => step.key === 'extension_action')?.status).toBe('failed')
expect(result.steps.filter((step) => step.status === 'skipped')).toHaveLength(3)
expect(executeAction).not.toHaveBeenCalled()
})
it('未配置扩展动作时步骤列表保持原样', async () => {
const { instance } = runner({})
const rule: AutomationRule = {
...createDefaultDailyReportRule(0),
actions: [{ type: 'replyText', enabled: true, text: '收到' }]
}
const result = await instance.run({
executionId: 'exec-4',
rule,
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.steps.map((step) => step.key)).toEqual([
'received',
'matched',
'reply',
'report',
'send'
])
})
})
describe('extension action persistence', () => {
it('规则保存后仍保留扩展动作,缺少扩展/动作 id 的草稿会被丢弃', () => {
const store = new AutomationRuleStore({ userDataPath: () => path.join(root, 'rules') })
const created = store.createRule({
name: '扩展规则',
enabled: true,
ruleType: 'daily_report',
scope: 'group',
conditions: { keyword: '你好', keywordMatchMode: 'contains' },
cooldownSeconds: 30,
replyDelaySeconds: 0,
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
},
{ type: 'extensionAction', enabled: true }
]
})
expect(created.actions).toHaveLength(1)
expect(created.actions[0]).toMatchObject({
type: 'extensionAction',
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
})
const reloaded = new AutomationRuleStore({
userDataPath: () => path.join(root, 'rules')
}).getRule(created.id)
expect(reloaded?.actions[0].extensionId).toBe('com.example.keyword-bot')
expect(describeRuleActions(reloaded!)).toBe('执行扩展动作')
})
it('input 只接受 JSON 对象,超限丢弃', () => {
const normalized = normalizeRuleDraft({
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
input: { url: 'https://example.com', nested: { ok: true } }
}
]
})
expect(normalized.actions[0].input).toEqual({
url: 'https://example.com',
nested: { ok: true }
})
const tooBig = normalizeRuleDraft({
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
input: { blob: 'x'.repeat(5_000) }
}
]
})
expect(tooBig.actions[0].input).toBeUndefined()
})
})
process.on('exit', () => {
fs.removeSync(root)
})
@@ -0,0 +1,328 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionResult } from '../../src/shared/wechat-action'
const MANIFEST = {
manifestVersion: 1,
id: 'com.example.fixture-bot',
name: 'Fixture Bot',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['messages.subscribe', 'wechat.send.text', 'storage', 'automation.action', 'contacts.list'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
subscriptions: {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false
},
contributions: {
pages: [{ id: 'settings', title: '配置' }],
automationActions: [{ id: 'keyword.reply', title: '关键词回复' }]
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: false },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const sentResult: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() => {
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
this.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
})
}
if (payload.type === 'invoke-action') {
queueMicrotask(() =>
this.emit('message', {
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
output: { success: true, reply: { type: 'text', text: '你好呀!' } }
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
events(): Array<Record<string, unknown>> {
return this.sent.filter((message) => message.type === 'event')
}
}
const roots: string[] = []
let userData: string
function createSourceExtension(): string {
const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-src-'))
roots.push(parent)
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), MANIFEST)
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>fixture</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports = () => {}')
return source
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
executeAction: ReturnType<typeof vi.fn>
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const executeAction = vi.fn(async () => sentResult)
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction,
queryMessages: async () => [],
listGroups: async () => [{ id: 'fixture-room@chatroom', name: '测试群' }],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children, executeAction }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-manager-'))
roots.push(userData)
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension lifecycle', () => {
it('安装 → 页面读写配置 → 启用 → 事件 → 动作 → 发送 → 停用 → 卸载', async () => {
const { manager, paths, children, executeAction } = createManager()
await manager.initialize()
const source = createSourceExtension()
const installed = await manager.installFromDirectory(source)
expect(installed.success).toBe(true)
expect(installed.extension?.enabled).toBe(false)
// 安装只自动授予低风险权限。
expect(installed.extension?.grantedPermissions).toEqual(['storage'])
const page = manager.pageUrl('com.example.fixture-bot')
expect(page.url).toBe('tm-extension://com.example.fixture-bot/ui/index.html')
const saved = await manager.pageRequest('com.example.fixture-bot', 'storage.set', {
key: 'greeting',
value: '你好'
})
expect(saved.ok).toBe(true)
expect(
(await manager.pageRequest('com.example.fixture-bot', 'storage.get', { key: 'greeting' }))
.result
).toBe('你好')
// 页面不能发送微信消息。
expect((await manager.pageRequest('com.example.fixture-bot', 'wechat.send.text', {})).ok).toBe(
false
)
// 页面可以读取群列表(manifest 已声明 contacts.list)。
const groups = await manager.pageRequest('com.example.fixture-bot', 'contacts.listGroups', {})
expect(groups.ok).toBe(true)
expect(groups.result).toEqual({
groups: [{ id: 'fixture-room@chatroom', name: '测试群' }]
})
const enabled = await manager.setEnabled('com.example.fixture-bot', true)
expect(enabled.success).toBe(true)
await tick()
const child = children[0]
expect(manager.get('com.example.fixture-bot')?.runtime.state).toBe('active')
expect(manager.get('com.example.fixture-bot')?.automationActions[0]).toMatchObject({
id: 'keyword.reply',
registered: true
})
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1001',
serverId: '9001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
senderId: 'wxid_peer',
senderNickname: '张三',
content: '@我 你好',
isGroup: true,
mentionTargets: ['wxid_self']
})
const event = child.events()[0]
expect(event).toBeTruthy()
const envelope = event.envelope as { event: { mentionsMe: boolean; text: string } }
expect(envelope.event.mentionsMe).toBe(true)
expect(envelope.event.text).toBe('@我 你好')
// 同一条消息重复投递不会再分发。
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
content: '@我 你好',
isGroup: true,
mentionTargets: ['wxid_self']
})
expect(child.events()).toHaveLength(1)
const output = await manager.invokeAutomationAction(
'com.example.fixture-bot',
'keyword.reply',
{ text: '你好' }
)
expect(output.reply).toEqual({ type: 'text', text: '你好呀!' })
// 后台主动发送:宿主填 origin/purpose,扩展只描述收件人与内容。
child.emit('message', {
type: 'call',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: 'call-1',
method: 'wechat.send.text',
params: { to: 'fixture-room@chatroom', text: '你好呀!' }
})
await tick()
const callResult = child.sent.find(
(message) => message.type === 'call-result' && message.callId === 'call-1'
)
expect(callResult?.ok).toBe(true)
expect(executeAction).toHaveBeenCalledTimes(1)
expect(executeAction.mock.calls[0][0]).toMatchObject({
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: 'group', id: 'fixture-room@chatroom' },
content: { type: 'text', text: '你好呀!' }
})
const disabled = await manager.setEnabled('com.example.fixture-bot', false)
expect(disabled.success).toBe(true)
expect(manager.get('com.example.fixture-bot')?.grantedPermissions).toEqual(['storage'])
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1002',
createTime: 1_700_000_100,
messageType: 1,
isSelf: false,
content: '还在吗',
isGroup: true,
mentionTargets: []
})
expect(child.events()).toHaveLength(1)
const removed = await manager.uninstall('com.example.fixture-bot', true)
expect(removed.success).toBe(true)
expect(fs.existsSync(paths.installDir('com.example.fixture-bot'))).toBe(false)
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture-bot'))).toBe(true)
expect(manager.list()).toEqual([])
})
it('不兼容的扩展安装被拒绝', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSourceExtension()
fs.writeJsonSync(path.join(source, 'manifest.json'), { ...MANIFEST, minAppVersion: '9.9.0' })
const result = await manager.installFromDirectory(source)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('停用状态下页面仍可打开与保存配置', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSourceExtension()
await manager.installFromDirectory(source)
const page = manager.pageUrl('com.example.fixture-bot', 'settings')
expect(page.pageId).toBe('settings')
const result = await manager.pageRequest('com.example.fixture-bot', 'storage.set', {
key: 'draft',
value: 1
})
expect(result.ok).toBe(true)
})
})
+177
View File
@@ -0,0 +1,177 @@
import { describe, expect, it } from 'vitest'
import { ExtensionEventBus } from '../../src/main/extensions/extension-event-bus'
import type { ExtensionEventEnvelope } from '../../src/shared/extensions/events'
import type { ExtensionSubscriptions } from '../../src/shared/extensions/manifest'
import type { NormalizedIncomingMessage } from '../../src/main/services/message-listener-service'
function message(overrides: Partial<NormalizedIncomingMessage> = {}): NormalizedIncomingMessage {
return {
sessionId: 'fixture-room@chatroom',
localId: '1001',
serverId: '9001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
senderId: 'wxid_peer',
senderNickname: '张三',
content: '你好',
isGroup: true,
mentionTargets: [],
...overrides
}
}
function subscriptions(overrides: Partial<ExtensionSubscriptions> = {}): ExtensionSubscriptions {
return {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false,
...overrides
}
}
describe('extension event bus', () => {
it('为同一条消息生成稳定 eventId,并做跨扩展去重', () => {
const first: ExtensionEventEnvelope[] = []
const second: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (first.push(e), true)
},
{
extensionId: 'com.example.b',
subscriptions: subscriptions(),
deliver: (e) => (second.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message())
bus.handleMessage(message())
expect(first).toHaveLength(1)
expect(second).toHaveLength(1)
expect(first[0].event.eventId).toMatch(/^message:[0-9a-f]{40}$/)
expect(bus.stats().deduped).toBe(1)
})
it('按消息类型与会话范围过滤', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions({
messageTypes: ['text'],
conversationIds: ['other@chatroom']
}),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message())
bus.handleMessage(message({ localId: '1002', messageType: 3 }))
expect(delivered).toHaveLength(0)
})
it('mentionsMe 只认真实 atuserlist 与自身 username 的交集', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message({ content: '@someone 你好', mentionTargets: ['wxid_other'] }))
bus.handleMessage(
message({ localId: '1002', content: '@张三 你好', mentionTargets: ['wxid_self'] })
)
expect(delivered[0].event.mentionsMe).toBe(false)
expect(delivered[1].event.mentionsMe).toBe(true)
})
it('拿不到自身身份时绝不猜测 @我', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => '',
getSelfUsernames: () => []
})
bus.handleMessage(message({ mentionTargets: ['wxid_fixture'] }))
expect(delivered[0].event.mentionsMe).toBe(false)
})
it('默认不投递自己发送的消息', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message({ isSelf: true }))
expect(delivered).toHaveLength(0)
})
it('账号切换后旧账号相同 localId 的消息会重新投递', () => {
const delivered: ExtensionEventEnvelope[] = []
const accountId = 'wxid_a'
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => accountId,
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message())
bus.setAccountId('wxid_b')
bus.handleMessage(message())
expect(delivered).toHaveLength(2)
expect(delivered[1].event.accountId).toBe('wxid_b')
})
it('扩展投递失败计入 dropped,不影响其它订阅者', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{ extensionId: 'com.example.a', subscriptions: subscriptions(), deliver: () => false },
{
extensionId: 'com.example.b',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => []
})
bus.handleMessage(message())
expect(delivered).toHaveLength(1)
expect(bus.stats().dropped).toBe(1)
})
})
+46
View File
@@ -0,0 +1,46 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { parseExtensionManifest } from '../../src/shared/extensions/manifest'
const EXAMPLES_ROOT = path.resolve(process.cwd(), 'examples/extensions')
function exampleDirectories(): string[] {
return fs
.readdirSync(EXAMPLES_ROOT, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort()
}
/**
* 示例扩展是文档的一部分:manifest 失配或入口文件缺失时必须在这里失败,
* 而不是等用户点「安装目录」才看到错误。
*/
describe('example extensions', () => {
it('每个示例都有合法 manifest 与真实入口文件', () => {
const directories = exampleDirectories()
expect(directories.length).toBeGreaterThanOrEqual(2)
for (const directory of directories) {
const root = path.join(EXAMPLES_ROOT, directory)
const manifestPath = path.join(root, 'manifest.json')
expect(fs.existsSync(manifestPath), `${directory} 缺少 manifest.json`).toBe(true)
const parsed = parseExtensionManifest(
JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown,
{ appVersion: '2.6.0' }
)
expect(parsed.ok, `${directory}: ${parsed.message || ''}`).toBe(true)
const manifest = parsed.manifest
if (!manifest) throw new Error(`${directory} manifest 未解析`)
for (const [key, entry] of Object.entries(manifest.entrypoints)) {
if (!entry) continue
expect(fs.existsSync(path.join(root, entry)), `${directory} 缺少 ${key}: ${entry}`).toBe(true)
}
for (const page of manifest.contributions.pages) {
const entry = page.entry || manifest.entrypoints.page
expect(Boolean(entry), `${directory} 页面 ${page.id} 缺少入口`).toBe(true)
if (entry) expect(fs.existsSync(path.join(root, entry))).toBe(true)
}
}
})
})
+230
View File
@@ -0,0 +1,230 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import {
ExtensionHost,
type ExtensionHostChild,
type ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
readonly listeners = new Map<string, Listener[]>()
killed = false
autoActivate = true
activationOk = true
actionOutput: unknown = { success: true, output: { matched: true } }
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() => {
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: this.activationOk,
...(this.activationOk ? {} : { error: { code: 'ACTION_FAILED', message: 'boom' } })
})
})
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
if (payload.type === 'invoke-action') {
queueMicrotask(() => {
this.emit('message', {
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
output: this.actionOutput
})
})
}
}
kill(): void {
this.killed = true
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const roots: string[] = []
function storage(): ExtensionStorage {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-host-'))
roots.push(root)
return new ExtensionStorage({ dataRoot: root })
}
function createHost(overrides: Partial<ConstructorParameters<typeof ExtensionHost>[0]> = {}): {
host: ExtensionHost
child: FakeChild
spawn: ReturnType<typeof vi.fn>
} {
const child = new FakeChild()
const spawn = vi.fn((options: ExtensionHostSpawnOptions) => {
void options
return child
})
const host = new ExtensionHost({
extensionId: 'com.example.keyword-bot',
extensionDir: '/tmp/fixture-extension',
dataDir: '/tmp/fixture-extension-data',
permissions: ['storage', 'wechat.send.text'],
storage: storage(),
spawn,
...overrides
})
return { host, child, spawn }
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
vi.useRealTimers()
})
describe('extension host', () => {
it('激活握手后进入 active,并把权限传给子进程', async () => {
const { host, child } = createHost()
await host.start()
expect(host.snapshot().state).toBe('active')
const activate = child.sent.find((message) => message.type === 'activate')
expect(activate?.extensionId).toBe('com.example.keyword-bot')
expect(activate?.permissions).toEqual(['wechat.send.text', 'storage'])
})
it('后台注册的动作会被记录,未注册的动作拒绝调用', async () => {
const { host, child } = createHost()
await host.start()
await expect(host.invokeAction('keyword.reply', {})).rejects.toMatchObject({
code: 'ACTION_FAILED'
})
child.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
expect(host.registeredActions()).toEqual([{ id: 'keyword.reply', title: '关键词回复' }])
})
it('动作调用走 invoke-action 并回传输出', async () => {
const { host, child } = createHost()
await host.start()
child.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
const result = await host.invokeAction('keyword.reply', { text: '你好' })
expect(result).toMatchObject({ success: true, output: { matched: true } })
expect(child.sent.some((message) => message.type === 'invoke-action')).toBe(true)
})
it('激活失败时 start 拒绝,状态为 error', async () => {
const { host, child } = createHost()
child.activationOk = false
await expect(host.start()).rejects.toMatchObject({ code: 'ACTION_FAILED' })
expect(host.snapshot().state).toBe('error')
})
it('未激活时不投递事件,激活后按 envelope 投递', async () => {
const { host } = createHost()
expect(host.deliverEvent({ version: 1, kind: 'message.received', event: {} as never })).toBe(
false
)
await host.start()
expect(
host.deliverEvent({
version: 1,
kind: 'message.received',
event: {
eventId: 'message:1',
accountId: 'wxid_self',
conversationId: 'fixture@chatroom',
messageId: '1',
isGroup: true,
isSelf: false,
type: 'text',
mentionsMe: false,
timestamp: 1
}
})
).toBe(true)
})
it('停止时发送 shutdown 并回到 inactive', async () => {
const { host, child } = createHost()
await host.start()
await host.stop()
expect(child.sent.some((message) => message.type === 'shutdown')).toBe(true)
expect(host.snapshot().state).toBe('inactive')
})
it('异常退出后按退避重启,超过次数标记 crashed', async () => {
vi.useFakeTimers()
const children: FakeChild[] = []
const spawn = vi.fn((options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
})
const host = new ExtensionHost({
extensionId: 'com.example.keyword-bot',
extensionDir: '/tmp/fixture-extension',
dataDir: '/tmp/fixture-extension-data',
permissions: [],
storage: storage(),
spawn,
now: () => Date.now()
})
await host.start()
for (let attempt = 0; attempt < 3; attempt += 1) {
children[children.length - 1].emit('exit', 1, null)
await vi.advanceTimersByTimeAsync(10_000)
}
children[children.length - 1].emit('exit', 1, null)
await vi.advanceTimersByTimeAsync(10_000)
expect(host.snapshot().state).toBe('crashed')
})
it('子进程请求的能力在未授权时被拒绝', async () => {
const { host, child } = createHost({ permissions: [] })
await host.start()
child.emit('message', {
type: 'call',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: 'call-1',
method: 'storage.get',
params: { key: 'x' }
})
await new Promise((resolve) => setTimeout(resolve, 0))
const result = child.sent.find((message) => message.type === 'call-result')
expect(result?.ok).toBe(false)
expect((result?.error as { code: string }).code).toBe('PERMISSION_DENIED')
})
})
+242
View File
@@ -0,0 +1,242 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
import { ExtensionInstaller } from '../../src/main/extensions/extension-installer'
const MANIFEST = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
manifestVersion: 1,
id: 'com.example.fixture',
name: 'Fixture',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
contributions: { pages: [{ id: 'settings', title: '设置' }] },
...overrides
})
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-installer-'))
roots.push(root)
return root
}
function createExtensionSource(root: string, overrides: Record<string, unknown> = {}): string {
const parent = fs.mkdtempSync(path.join(root, 'source-'))
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), MANIFEST(overrides))
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>fixture</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports = function(){}')
return source
}
function setup(): {
paths: ReturnType<typeof createExtensionPaths>
registry: ExtensionRegistry
installer: ExtensionInstaller
} {
const root = tempRoot()
const paths = createExtensionPaths(root)
const registry = new ExtensionRegistry({ registryFile: paths.registryFile })
const installer = new ExtensionInstaller({ paths, registry })
return { paths, registry, installer }
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension installer', () => {
it('安装目录后登记为未启用,代码位于 extensions/<id>', async () => {
const { paths, registry, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
const outcome = await installer.installFromDirectory(source, { appVersion: '2.6.0' })
expect(outcome.upgraded).toBe(false)
expect(fs.existsSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json'))).toBe(
true
)
const record = registry.get('com.example.fixture')
expect(record?.enabled).toBe(false)
expect(record?.grantedPermissions).toEqual([])
})
it('升级保留启用状态与授权,不改动数据目录', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setEnabled('com.example.fixture', true)
registry.setGrantedPermissions('com.example.fixture', ['storage', 'messages.subscribe'])
fs.ensureDirSync(paths.extensionDataDir('com.example.fixture'))
fs.writeJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'), {
version: 1,
values: { greeting: '保留我' }
})
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
expect(outcome.upgraded).toBe(true)
expect(outcome.previousVersion).toBe('1.0.0')
const record = registry.get('com.example.fixture')
expect(record?.version).toBe('1.2.0')
expect(record?.enabled).toBe(true)
expect(record?.grantedPermissions).toEqual(['storage', 'messages.subscribe'])
expect(
fs.readJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'))
.values.greeting
).toBe('保留我')
})
it('卸载默认保留数据,选择清除时一并删除', async () => {
const { paths, registry, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
await installer.installFromDirectory(source, { appVersion: '2.6.0' })
fs.ensureDirSync(paths.extensionDataDir('com.example.fixture'))
fs.writeFileSync(path.join(paths.extensionDataDir('com.example.fixture'), 'keep.txt'), 'x')
await installer.uninstall('com.example.fixture', { keepData: true })
expect(fs.existsSync(paths.installDir('com.example.fixture'))).toBe(false)
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture'))).toBe(true)
expect(registry.get('com.example.fixture')).toBeUndefined()
await installer.uninstall('com.example.fixture', { keepData: false })
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture'))).toBe(false)
})
it('拒绝符号链接,且不留下半装目录', async () => {
const { paths, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
fs.symlinkSync('/etc/hosts', path.join(source, 'ui', 'link.html'))
await expect(
installer.installFromDirectory(source, { appVersion: '2.6.0' })
).rejects.toMatchObject({
code: 'EXTENSION_INVALID_PATH'
})
expect(fs.existsSync(paths.installDir('com.example.fixture'))).toBe(false)
expect(fs.existsSync(paths.stagingDir) ? fs.readdirSync(paths.stagingDir) : []).toEqual([])
})
it('入口文件缺失时拒绝安装', async () => {
const { installer } = setup()
const root = tempRoot()
const source = createExtensionSource(root)
fs.removeSync(path.join(source, 'background', 'index.js'))
await expect(
installer.installFromDirectory(source, { appVersion: '2.6.0' })
).rejects.toMatchObject({
code: 'EXTENSION_INVALID_MANIFEST'
})
})
it('ZIP 条目穿越时拒绝,且不会写到扩展目录之外', async () => {
const { paths, installer } = setup()
const zipPath = path.join(tempRoot(), 'evil.zip')
fs.writeFileSync(
zipPath,
buildZip([
{ name: 'manifest.json', data: JSON.stringify(MANIFEST()) },
{ name: 'ui/index.html', data: '<!doctype html>' },
{ name: 'background/index.js', data: 'module.exports=()=>{}' },
{ name: '../escaped.txt', data: 'escaped' }
])
)
await expect(
installer.installFromPackage(zipPath, { appVersion: '2.6.0' })
).rejects.toMatchObject({
code: 'EXTENSION_INVALID_PATH'
})
expect(fs.existsSync(path.join(paths.userData, 'escaped.txt'))).toBe(false)
expect(fs.existsSync(paths.installDir('com.example.fixture'))).toBe(false)
})
it('合法 ZIP 可安装', async () => {
const { paths, installer } = setup()
const zipPath = path.join(tempRoot(), 'fixture.zip')
fs.writeFileSync(
zipPath,
buildZip([
{ name: 'manifest.json', data: JSON.stringify(MANIFEST()) },
{ name: 'ui/index.html', data: '<!doctype html>' },
{ name: 'background/index.js', data: 'module.exports=()=>{}' }
])
)
const outcome = await installer.installFromPackage(zipPath, { appVersion: '2.6.0' })
expect(outcome.manifest.id).toBe('com.example.fixture')
expect(
fs.existsSync(path.join(paths.installDir('com.example.fixture'), 'ui', 'index.html'))
).toBe(true)
})
})
/* 最小 ZIP 写入器:只支持 stored(无压缩)条目,用于构造非法路径样本。 */
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let index = 0; index < 256; index += 1) {
let value = index
for (let bit = 0; bit < 8; bit += 1) {
value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1
}
table[index] = value >>> 0
}
return table
})()
function crc32(buffer: Buffer): number {
let crc = 0xffffffff
for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)
return (crc ^ 0xffffffff) >>> 0
}
function buildZip(entries: Array<{ name: string; data: string }>): Buffer {
const locals: Buffer[] = []
const centrals: Buffer[] = []
let offset = 0
for (const entry of entries) {
const name = Buffer.from(entry.name, 'utf8')
const data = Buffer.from(entry.data, 'utf8')
const crc = crc32(data)
const local = Buffer.alloc(30)
local.writeUInt32LE(0x04034b50, 0)
local.writeUInt16LE(20, 4)
local.writeUInt16LE(0, 6)
local.writeUInt16LE(0, 8)
local.writeUInt32LE(crc, 14)
local.writeUInt32LE(data.length, 18)
local.writeUInt32LE(data.length, 22)
local.writeUInt16LE(name.length, 26)
local.writeUInt16LE(0, 28)
locals.push(local, name, data)
const central = Buffer.alloc(46)
central.writeUInt32LE(0x02014b50, 0)
central.writeUInt16LE(20, 4)
central.writeUInt16LE(20, 6)
central.writeUInt32LE(crc, 16)
central.writeUInt32LE(data.length, 20)
central.writeUInt32LE(data.length, 24)
central.writeUInt16LE(name.length, 28)
central.writeUInt32LE(offset, 42)
centrals.push(central, name)
offset += local.length + name.length + data.length
}
const centralBuffer = Buffer.concat(centrals)
const end = Buffer.alloc(22)
end.writeUInt32LE(0x06054b50, 0)
end.writeUInt16LE(entries.length, 8)
end.writeUInt16LE(entries.length, 10)
end.writeUInt32LE(centralBuffer.length, 12)
end.writeUInt32LE(offset, 16)
return Buffer.concat([...locals, centralBuffer, end])
}
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest'
import {
checkExtensionCompatibility,
compareSemver,
isSafeRelativeEntryPath,
isValidExtensionId,
parseExtensionManifest,
parseExtensionManifestJson
} from '../../src/shared/extensions/manifest'
const base = {
manifestVersion: 1,
id: 'com.example.fixture-bot',
name: 'Fixture Bot',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
contributions: { pages: [{ id: 'settings', title: '设置' }] }
}
describe('extension manifest', () => {
it('接受合法的反向域名 id 并补齐默认值', () => {
const result = parseExtensionManifest(base)
expect(result.ok).toBe(true)
expect(result.manifest?.id).toBe('com.example.fixture-bot')
expect(result.manifest?.permissions).toEqual(['storage'])
expect(result.manifest?.contributions.automationActions).toEqual([])
})
it('拒绝保留前缀与大写 id', () => {
expect(isValidExtensionId('com.tracememo.reader')).toBe(false)
expect(isValidExtensionId('com.Example.Hello')).toBe(false)
expect(isValidExtensionId('hello')).toBe(false)
expect(isValidExtensionId('com.example.ok')).toBe(true)
})
it('拒绝未知权限,而不是静默丢弃', () => {
const result = parseExtensionManifest({ ...base, permissions: ['storage', 'fs.read'] })
expect(result.ok).toBe(false)
expect(result.message).toContain('未知权限')
})
it('拒绝与宿主不兼容的 apiVersion', () => {
const result = parseExtensionManifest({ ...base, apiVersion: '2' })
expect(result.ok).toBe(false)
expect(result.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('minAppVersion 高于当前版本时拒绝安装', () => {
const result = parseExtensionManifest(
{ ...base, minAppVersion: '2.7.0' },
{ appVersion: '2.6.0' }
)
expect(result.ok).toBe(false)
expect(result.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('声明消息订阅但没有 background 时拒绝', () => {
const result = parseExtensionManifest({
...base,
entrypoints: { page: 'ui/index.html' },
permissions: ['messages.subscribe'],
subscriptions: { messageTypes: ['text'], conversationIds: [] }
})
expect(result.ok).toBe(false)
expect(result.message).toContain('entrypoints.background')
})
it('拒绝目录穿越的入口路径', () => {
const result = parseExtensionManifest({
...base,
entrypoints: { page: '../../etc/passwd' }
})
expect(result.ok).toBe(false)
expect(result.message).toContain('entrypoints.page')
})
it('入口路径检查覆盖穿越、盘符、保留名与反斜杠', () => {
expect(isSafeRelativeEntryPath('ui/index.html')).toBe(true)
expect(isSafeRelativeEntryPath('../evil.html')).toBe(false)
expect(isSafeRelativeEntryPath('/etc/passwd')).toBe(false)
expect(isSafeRelativeEntryPath('C:/Windows/system32')).toBe(false)
expect(isSafeRelativeEntryPath('ui\\index.html')).toBe(true)
expect(isSafeRelativeEntryPath('ui/con.txt')).toBe(false)
expect(isSafeRelativeEntryPath('ui//index.html')).toBe(false)
})
it('页面 id 与动作 id 不合法时拒绝', () => {
expect(
parseExtensionManifest({
...base,
contributions: { pages: [{ id: 'Bad Page', title: 'x' }] }
}).ok
).toBe(false)
expect(
parseExtensionManifest({
...base,
contributions: { automationActions: [{ id: 'UPPER', title: 'x' }] }
}).ok
).toBe(false)
})
it('JSON 语法错误与 schema 错误分开报', () => {
expect(parseExtensionManifestJson('{').message).toContain('JSON')
expect(parseExtensionManifestJson('[]').message).toContain('manifest')
})
it('semver 比较忽略 prerelease 且不误伤预发布构建', () => {
expect(compareSemver('2.6.0', '2.5.9')).toBe(1)
expect(compareSemver('2.6.0-beta.1', '2.6.0')).toBe(0)
expect(compareSemver('bad', '2.6.0')).toBeNull()
expect(
checkExtensionCompatibility({ apiVersion: '1', minAppVersion: '2.6.0' }, '2.6.0-rc.1')
).toEqual({
compatible: true
})
})
})
+338
View File
@@ -0,0 +1,338 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ExtensionSendGateway } from '../../src/main/extensions/extension-send-gateway'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
const readyCapability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: false, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const sentResult: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
function gateway(
overrides: {
capability?: PersonalWechatSendCapability
entitlement?: {
ok: boolean
message: string
source: 'mac_license' | 'hook_license' | 'unsupported'
}
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
dataRoot?: string
now?: () => number
} = {}
): {
instance: ExtensionSendGateway
executeAction: ReturnType<
typeof vi.fn<(request: WechatActionRequest) => Promise<WechatActionResult>>
>
} {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
if (overrides.executeAction) return overrides.executeAction(request)
return sentResult
})
const instance = new ExtensionSendGateway({
getCapability: async () => overrides.capability ?? readyCapability,
checkEntitlement: async () =>
overrides.entitlement ?? { ok: true, message: '授权有效', source: 'mac_license' },
executeAction: executeAction as never,
...(overrides.dataRoot ? { getExtensionDataRoot: () => overrides.dataRoot as string } : {}),
now: overrides.now ?? (() => 1_000_000)
})
return { instance, executeAction }
}
const context = {
extensionId: 'com.example.keyword-bot',
permissions: ['wechat.send.text' as const],
conversationScope: [] as string[]
}
describe('extension send gateway', () => {
it('缺少权限时拒绝,且不触碰 Gateway', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({ executeAction })
await expect(
instance.sendText({ ...context, permissions: [] }, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
expect(executeAction).not.toHaveBeenCalled()
})
it('目标超出扩展声明的会话范围时拒绝', async () => {
const { instance } = gateway()
await expect(
instance.sendText(
{ ...context, conversationScope: ['allowed@chatroom'] },
{ to: 'other@chatroom', text: 'hi' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('发送能力未就绪时返回 CAPABILITY_UNAVAILABLE', async () => {
const { instance } = gateway({
capability: { ...readyCapability, ready: false, message: '请先绑定个人微信' }
})
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
it('没有有效授权时返回 LICENSE_REQUIRED', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({
entitlement: { ok: false, message: '需要有效授权', source: 'mac_license' },
executeAction
})
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'LICENSE_REQUIRED' })
expect(executeAction).not.toHaveBeenCalled()
})
it('成功时由宿主填写 origin / purpose / 幂等键', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({ executeAction })
const result = await instance.sendText(context, {
to: 'fixture@chatroom',
text: '你好',
dedupeKey: 'event-1'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
const request = executeAction.mock.calls[0][0] as unknown as Record<string, unknown>
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_send')
expect(request.triggerType).toBe('automation')
expect((request.metadata as { extensionId: string }).extensionId).toBe(context.extensionId)
expect(String(request.idempotencyKey)).toMatch(/^extension:com\.example\.keyword-bot:/)
expect((request.recipient as { type: string }).type).toBe('group')
})
it('两条之间至少 2 秒,超限返回 RATE_LIMITED', async () => {
let now = 1_000_000
const { instance } = gateway({ now: () => now })
await instance.sendText(context, { to: 'fixture@chatroom', text: 'one' })
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'two' })
).rejects.toMatchObject({ code: 'RATE_LIMITED' })
now += 2_001
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'three' })
).resolves.toEqual({
actionId: 'action-1',
status: 'sent'
})
})
it('网关失败时把底层错误码映射成扩展错误码', async () => {
const { instance } = gateway({
executeAction: async () => ({
actionId: 'action-2',
status: 'failed',
decision: 'allow',
errorCode: 'SEND_NOT_READY',
reason: '未绑定',
startedAt: '',
finishedAt: ''
})
})
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
it('非群聊忽略 at 参数,文本长度超限直接拒绝', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({ executeAction })
await instance.sendText(context, {
to: 'wxid_peer',
text: 'hi',
at: { wxid_peer: '张三' }
})
expect(executeAction).toHaveBeenCalledTimes(1)
const request = executeAction.mock.calls[0][0] as { content: { at?: unknown } }
expect(request.content.at).toBeUndefined()
await expect(
instance.sendText(context, { to: 'wxid_peer', text: 'x'.repeat(2_001) })
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
})
})
describe('extension send gateway / image', () => {
const cleanup: string[] = []
function tempDir(prefix: string): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
cleanup.push(root)
return root
}
afterEach(() => {
for (const root of cleanup.splice(0)) fs.rmSync(root, { recursive: true, force: true })
})
const imageContext = {
extensionId: 'com.example.douyin',
permissions: ['wechat.send.image' as const],
conversationScope: [] as string[]
}
it('缺少 wechat.send.image 权限时拒绝', async () => {
const { instance } = gateway({ dataRoot: tempDir('tm-ext-data-') })
await expect(
instance.sendImage(
{ ...imageContext, permissions: [] },
{ to: 'fixture@chatroom', path: '/tmp/a.mp4' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('只能发送扩展数据目录或临时目录内的文件', async () => {
const dataRoot = tempDir('tm-ext-data-')
// 刻意放在仓库工作目录下:它既不在扩展数据目录,也不在系统临时目录。
const outside = fs.mkdtempSync(path.join(process.cwd(), '.tm-ext-outside-'))
cleanup.push(outside)
const file = path.join(outside, 'cover.png')
fs.writeFileSync(file, Buffer.from('fixture'))
const { instance, executeAction } = gateway({ dataRoot })
await expect(
instance.sendImage(imageContext, { to: 'fixture@chatroom', path: file })
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
expect(executeAction).not.toHaveBeenCalled()
})
it('图片按 image 类型提交,路径取 realpath', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'cover.png')
fs.writeFileSync(file, Buffer.from('fixture-image'))
const { instance, executeAction } = gateway({ dataRoot })
const result = await instance.sendImage(imageContext, {
to: 'fixture@chatroom',
path: file,
dedupeKey: 'message:fixture'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_send')
expect(request.content).toEqual({ type: 'image', path: fs.realpathSync(file) })
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture@chatroom' })
expect(String(request.idempotencyKey)).toMatch(/^extension:com\.example\.douyin:/)
})
it('拒绝非图片/视频扩展名与不存在的路径', async () => {
const dataRoot = tempDir('tm-ext-data-')
const textFile = path.join(dataRoot, 'note.txt')
fs.writeFileSync(textFile, Buffer.from('fixture'))
const { instance } = gateway({ dataRoot })
await expect(
instance.sendImage(imageContext, { to: 'fixture@chatroom', path: textFile })
).rejects.toMatchObject({ code: 'SEND_NOT_SUPPORTED' })
await expect(
instance.sendImage(imageContext, {
to: 'fixture@chatroom',
path: path.join(dataRoot, 'missing.mp4')
})
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
})
})
describe('extension send gateway / video', () => {
const cleanup: string[] = []
function tempDir(prefix: string): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
cleanup.push(root)
return root
}
afterEach(() => {
for (const root of cleanup.splice(0)) fs.rmSync(root, { recursive: true, force: true })
})
const videoContext = {
extensionId: 'com.example.douyin',
permissions: ['wechat.send.video' as const],
conversationScope: [] as string[]
}
it('缺 wechat.send.video 权限时拒绝', async () => {
const { instance } = gateway({ dataRoot: tempDir('tm-ext-data-') })
await expect(
instance.sendVideo(
{ ...videoContext, permissions: [] },
{ to: 'fixture@chatroom', path: '/tmp/a.mp4' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('视频按 video 类型提交,不复用 image 通道', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'clip.mp4')
fs.writeFileSync(file, Buffer.from('fixture-video'))
const { instance, executeAction } = gateway({ dataRoot })
const result = await instance.sendVideo(videoContext, {
to: 'fixture@chatroom',
path: file,
dedupeKey: 'message:fixture:video'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_send')
expect(request.content).toEqual({ type: 'video', path: fs.realpathSync(file) })
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture@chatroom' })
expect(String(request.idempotencyKey)).toMatch(/^extension:com\.example\.douyin:/)
})
it('视频通道拒绝图片扩展名', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'cover.png')
fs.writeFileSync(file, Buffer.from('fixture-image'))
const { instance } = gateway({ dataRoot })
await expect(
instance.sendVideo(videoContext, { to: 'fixture@chatroom', path: file })
).rejects.toMatchObject({ code: 'SEND_NOT_SUPPORTED' })
})
it('本机能力没有视频时返回 CAPABILITY_UNAVAILABLE', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'clip.mp4')
fs.writeFileSync(file, Buffer.from('fixture-video'))
const { instance } = gateway({
dataRoot,
capability: {
...readyCapability,
capabilities: { text: true, image: true, voice: false, video: false }
}
})
await expect(
instance.sendVideo(videoContext, { to: 'fixture@chatroom', path: file })
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
})
+111
View File
@@ -0,0 +1,111 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createExtensionPaths, isPathInside } from '../../src/main/extensions/extension-paths'
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
import { ExtensionLogStore } from '../../src/main/extensions/extension-log'
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-state-'))
roots.push(root)
return root
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension paths', () => {
it('三段目录彼此分离且都在 userData 下', () => {
const paths = createExtensionPaths('/tmp/user-data')
expect(paths.extensionsDir).toBe(path.join('/tmp/user-data', 'extensions'))
expect(paths.extensionDataDir('com.example.a')).toBe(
path.join('/tmp/user-data', 'extensions-data', 'com.example.a')
)
expect(paths.registryFile).toBe(
path.join('/tmp/user-data', 'extensions-state', 'registry.json')
)
expect(isPathInside(paths.extensionsDir, path.join(paths.extensionsDir, 'a'))).toBe(true)
expect(isPathInside(paths.extensionsDir, 'a/../../etc')).toBe(false)
})
})
describe('extension registry', () => {
it('持久化启用状态与授权,重启后仍可读', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const first = new ExtensionRegistry({ registryFile })
first.upsert({
id: 'com.example.a',
version: '1.0.0',
apiVersion: '1',
enabled: true,
grantedPermissions: ['storage', 'messages.subscribe'],
installedAt: 1,
updatedAt: 2,
source: 'directory'
})
const second = new ExtensionRegistry({ registryFile })
const record = second.get('com.example.a')
expect(record?.enabled).toBe(true)
expect(record?.grantedPermissions).toEqual(['storage', 'messages.subscribe'])
})
it('文件损坏时按未安装处理,不抛异常', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
fs.ensureDirSync(root)
fs.writeFileSync(registryFile, '{broken', 'utf8')
const registry = new ExtensionRegistry({ registryFile })
expect(registry.list()).toEqual([])
})
})
describe('extension storage', () => {
it('按扩展隔离键空间并支持删除', () => {
const root = tempRoot()
const storage = new ExtensionStorage({ dataRoot: root })
storage.set('com.example.a', 'greeting', '你好')
storage.set('com.example.b', 'greeting', 'hello')
expect(storage.get('com.example.a', 'greeting')).toBe('你好')
expect(storage.get('com.example.b', 'greeting')).toBe('hello')
expect(storage.remove('com.example.a', 'greeting')).toBe(true)
expect(storage.get('com.example.a', 'greeting')).toBeUndefined()
})
it('拒绝非法键与不可序列化的值', () => {
const storage = new ExtensionStorage({ dataRoot: tempRoot() })
expect(() => storage.set('com.example.a', '../escape', 1)).toThrowError(/存储键/)
expect(() => storage.set('com.example.a', 'fn', () => undefined)).toThrowError(/JSON/)
})
it('单值超限时拒绝而不是截断', () => {
const storage = new ExtensionStorage({ dataRoot: tempRoot(), maxValueBytes: 32 })
expect(() => storage.set('com.example.a', 'big', 'x'.repeat(64))).toThrowError(/上限/)
})
})
describe('extension log store', () => {
it('落盘后可被新的实例读回,并按数量截断', () => {
const root = tempRoot()
const first = new ExtensionLogStore(root)
for (let index = 0; index < 5; index += 1) {
first.append('com.example.a', 'info', 'extension', `line-${index}`)
}
const second = new ExtensionLogStore(root)
const entries = second.list('com.example.a', 10)
expect(entries).toHaveLength(5)
expect(entries[0].message).toBe('line-4')
})
it('清洗控制字符并截断超长日志', () => {
const store = new ExtensionLogStore(tempRoot())
const entry = store.append('com.example.a', 'warn', 'extension', `a\u0000b${'x'.repeat(800)}`)
expect(entry.message).not.toContain('\u0000')
expect(entry.message.length).toBeLessThanOrEqual(501)
})
})
@@ -103,6 +103,11 @@ describe('mention parser(纯函数)', () => {
// 若实现里写了 `startsWith('wxid_')` 过滤,这条会变成 []
expect(extractMentionTargets(source)).toEqual(['SELF_USER'])
})
it('多人 @(逗号分隔)能够拆分为独立 username 列表', () => {
const source = '<msgsource><atuserlist><![CDATA[,OTHER_USER,SELF_USER]]></atuserlist></msgsource>'
expect(extractMentionTargets(source)).toEqual(['OTHER_USER', 'SELF_USER'])
})
})
describe('decodeSourcePayload', () => {
@@ -121,8 +126,14 @@ describe('decodeSourcePayload', () => {
expect(decodeSourcePayload(jsonForm)).toBe(xml)
})
it('TEXT 列直接返回明文 XML 字符串时原样保留', () => {
const xml = '<msgsource><atuserlist>SELF_USER</atuserlist></msgsource>'
expect(decodeSourcePayload(xml)).toBe(xml)
})
it('空值 / 非 zstd 内容安全返回', () => {
expect(decodeSourcePayload(undefined)).toBeUndefined()
expect(decodeSourcePayload('')).toBeUndefined()
expect(decodeSourcePayload(Buffer.alloc(0))).toBeUndefined()
expect(decodeSourcePayload(Buffer.from('plain text'))).toBe('plain text')
})
@@ -418,6 +418,20 @@ describe('Windows request', () => {
})
})
it('builds the unified video request with type=video', () => {
expect(
buildWindowsWechatRequest({
to: 'room@chatroom',
type: 'video',
filePath: '/tmp/tm-test.mp4',
isGroup: true
})
).toEqual({
endpoint: '/SendMsg',
body: { toWxid: 'room@chatroom', type: 'video', msg: '/tmp/tm-test.mp4' }
})
})
it('builds the unified voice request with sender wxid and duration', () => {
expect(
buildWindowsWechatRequest(