Add room-scoped Matrix plugins and bilingual configuration commands
This commit is contained in:
1 parent
061bfbd12a
commit
f4f30c3b5c
75 files changed
+2559
-1975
No files matched your search
@@ -1,10 +1,15 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
coverage-integration
|
||||
data
|
||||
*.db
|
||||
*.db-journal
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
|
||||
+1
-9
@@ -1,12 +1,4 @@
|
||||
# 数据库连接(SQLite 起步)
|
||||
DATABASE_URL="file:./dev.db"
|
||||
|
||||
# 配置文件路径
|
||||
BOT_CONFIG_PATH="./config/bots.yaml"
|
||||
|
||||
# dry-run = true 时不真正登录 Matrix,仅装配并打印路由表,便于本地/CI 启动验证
|
||||
DRY_RUN=true
|
||||
|
||||
# Matrix 账号密码(由 config/bots.yaml 里 env(XXX) 引用)
|
||||
MAIN_PW="replace-me"
|
||||
CHECKIN_PW="replace-me"
|
||||
BOT_PASSWORD="replace-me"
|
||||
@@ -1,9 +1,14 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
coverage-integration
|
||||
*.db
|
||||
*.db-journal
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# 实际配置(含账号密码),不进版本库;从 config/bots.example.yaml 复制后填写
|
||||
config/bots.yaml
|
||||
|
||||
+6
-6
@@ -1,6 +1,4 @@
|
||||
# 使用 debian(glibc)而非 alpine(musl):原生加密模块
|
||||
# @matrix-org/matrix-sdk-crypto-nodejs 在 arm64 上只提供 gnu(glibc)预编译,
|
||||
# 不支持 arm64-musl;debian 同时覆盖 x64/arm64,适配 Apple Silicon 上的 Docker。
|
||||
# Use glibc for compatibility with the native encryption and database engines.
|
||||
FROM node:22-slim AS build
|
||||
WORKDIR /app
|
||||
# openssl: Prisma 引擎;ca-certificates: postinstall 从 github 下载加密二进制。
|
||||
@@ -8,7 +6,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-cert
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
COPY src ./src
|
||||
COPY prisma ./prisma
|
||||
COPY tsconfig*.json nest-cli.json ./
|
||||
RUN npm run prisma:generate && npm run build
|
||||
|
||||
FROM node:22-slim AS runtime
|
||||
@@ -22,9 +22,9 @@ COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/node_modules/.prisma ./node_modules/.prisma
|
||||
COPY --from=build /app/node_modules/@prisma ./node_modules/@prisma
|
||||
COPY prisma ./prisma
|
||||
COPY config ./config
|
||||
COPY config/bots.example.yaml ./config/bots.example.yaml
|
||||
COPY docker-entrypoint.sh ./
|
||||
RUN chmod +x docker-entrypoint.sh
|
||||
# 数据目录(运行时由 compose 把宿主 ./data 挂载到此;含 SQLite 与加密 store)。
|
||||
RUN mkdir -p /app/data
|
||||
RUN mkdir -p /app/data /app/plugins
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
# Matrix plugin bot
|
||||
|
||||
[中文](README.md)
|
||||
|
||||
A NestJS / TypeScript host for room-scoped Matrix plugins. The host owns account sessions, encryption, command routing, permissions, localization, scheduling and storage. Installed plugins can be enabled or disabled from a managed room without restarting the host.
|
||||
|
||||
Built-in plugins:
|
||||
|
||||
- `checkin` / `签到`: calendar-day check-ins, read-only reports and optional inactive-member cleanup.
|
||||
- `room-manager` / `成员管理` / `权限同步`: independent business roles, optional Matrix power mapping and membership reconciliation.
|
||||
|
||||
## Commands
|
||||
|
||||
Commands accept `!`, `!` or `/`. Some Matrix clients intercept slash commands; use `!` when a slash command is not sent as a room message. English command words are case-insensitive. Chinese aliases and English aliases invoke the same handlers. Replies use the room's configured language; administrators can change it with `!language en` or `!语言 中文`.
|
||||
|
||||
**The ASCII `!` and fullwidth `!` prefixes are interchangeable** for both English and Chinese commands. Send any one command in a row for the same result.
|
||||
|
||||
| Action | ASCII + English | Fullwidth + English | ASCII + Chinese | Fullwidth + Chinese |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Check in | `!checkin` | `!checkin` | `!签到` | `!签到` |
|
||||
| View your record | `!list` | `!list` | `!查询` | `!查询` |
|
||||
| Show help | `!help` | `!help` | `!帮助` | `!帮助` |
|
||||
|
||||
`签到` and `帮助` also work as standalone messages. Queries require a prefix.
|
||||
|
||||
### Host commands
|
||||
|
||||
| English | 中文 | Permission |
|
||||
| --- | --- | --- |
|
||||
| `!help` | `!帮助` or `帮助` | Everyone; help lists commands currently available |
|
||||
| `!ping` | `!在线` | Everyone |
|
||||
| `!echo <text>` | `!复述 <文本>` | Everyone |
|
||||
| `!plugin list` / `!plugin status` | `!插件 列表` / `!插件 状态` | Everyone; error detail is admin-only |
|
||||
| `!plugin enable <name>` | `!插件 启用 <名称>` | Administrator |
|
||||
| `!plugin disable <name>` | `!插件 停用 <名称>` / `!插件 禁用 <名称>` | Administrator |
|
||||
| `!language zh-CN` / `!language en` | `!语言 中文` / `!语言 英文` | Administrator |
|
||||
| `!audit` | `!操作记录` | Administrator; latest 10 of up to 200 retained entries per room |
|
||||
|
||||
An administrator is a user in the room's `admins` list or with a native Matrix power level at least `adminPowerLevel` (default 100). Lookup failures deny access. Business roles do not grant administrator privileges.
|
||||
|
||||
Administrators can inspect the current room ID, language, timezone and report settings with `/config` or `!config`. `!config language en` applies immediately. `!config reports off` applies the next time the check-in plugin starts.
|
||||
|
||||
If a domainless room ID was configured with an extra server suffix, send `!config` in the actual room, then `!config bind`. Recovery requires a unique candidate, a sender listed in `admins` with sufficient native room power, and bot membership in the actual room but not the configured room. The database stores the correction for the next service start and keeps the original data scope. The command requires a readable message and cannot restore missing encryption keys.
|
||||
|
||||
### Check-in commands
|
||||
|
||||
| English | 中文 | Effect |
|
||||
| --- | --- | --- |
|
||||
| `!checkin` | `!签到` or `签到` | Check in once per local calendar date |
|
||||
| `!list` | `!查询` | Read own summary |
|
||||
| `!list <userId>` / `!list all` | `!查询 <用户ID>` / `!查询 全部` | Other users and all records require administrator access |
|
||||
| `!list [userId\|all] --raw` | `!查询 [用户ID\|全部] --原始` | Administrator; JSON summary |
|
||||
| `!report daily [YYYY-MM-DD]` | `!日报 [YYYY-MM-DD]` | Administrator; read-only report |
|
||||
| `!report monthly [YYYY-MM]` | `!月报 [YYYY-MM]` | Administrator; read-only report |
|
||||
| `!cleanup preview` | `!清理 预览` | Administrator; preview candidates |
|
||||
| `!cleanup confirm <token>` | `!清理 确认 <确认码>` | Administrator; execute the previewed candidates after revalidation |
|
||||
|
||||
Check-ins are unique by account, room, user and calendar date. Day boundaries use the room's explicit `timeZone` (default `Asia/Shanghai`), independently of report scheduling. Reports never clear records. Levels use the total number of known check-ins: Bronze 1–7, Silver 8–14, Gold 15–29, Platinum 30–44, Diamond 45+.
|
||||
|
||||
Scheduled daily reports cover the preceding calendar date at 03:00; monthly reports cover the preceding month at 00:05 on the first day. The plugin checks due periods once per minute. Checkpoints survive restarts; after downtime it sends the latest due report with a catch-up notice rather than flooding the room with every missed report. Historical dates remain queryable. Initial activation establishes a checkpoint without sending old reports. Sending and checkpointing are not a distributed transaction: a crash between them can duplicate a notification, but cannot duplicate check-ins or reset counts.
|
||||
|
||||
Daily reports compare historical check-ins with **current** membership, not a historical membership snapshot. Legacy migration preserves only the history actually available in the old schema; see [upgrade notes](docs/UPGRADE.md).
|
||||
|
||||
`cleanupEnabled` permits explicit preview/confirmation. `autoCleanup` additionally permits automatic daily cleanup after 03:00. Both default to false. Automatic cleanup is not run in the enable hook; the next scheduled check may run it if it is explicitly enabled and due. Members with no known check-in, members who checked in today, listed exemptions and administrators are excluded. Permission read failures skip the member. Cleanup removes members from the current control room and never deletes their check-in history.
|
||||
|
||||
### Membership commands
|
||||
|
||||
| English | 中文 | Effect |
|
||||
| --- | --- | --- |
|
||||
| `!access status` | `!成员管理 状态` | Show mode and automatic action switches |
|
||||
| `!role set <userId> core\|member\|restricted` | `!身份 设置 <用户ID> 核心\|普通\|受限` | Preview an independent business-role change |
|
||||
| `!access preview [userId]` / `!access reconcile [userId]` | `!成员管理 预览 [用户ID]` / `!成员管理 核对 [用户ID]` | Preview reconciliation |
|
||||
| `!access confirm <token>` | `!成员管理 确认 <确认码>` | Apply a preview after rechecking current state |
|
||||
|
||||
All membership commands require administrator access. Confirmations are bound to the initiating administrator, room and plugin; expire after five minutes; are single-use; and are invalidated when the plugin is re-enabled. A new preview replaces that administrator's previous preview for the same operation.
|
||||
|
||||
| Business role | Intended membership |
|
||||
| --- | --- |
|
||||
| `core` / 核心 | Invite to work rooms 1 and 2; remove from lost room |
|
||||
| `member` / 普通 | Remove from work room 1; invite to work room 2; remove from lost room |
|
||||
| `restricted` / 受限 | Remove from work rooms 1 and 2; invite to lost room |
|
||||
|
||||
Invitations require acceptance by recipients. The bot needs suitable native permissions in each target room. Automatic membership changes are disabled by default. `syncOnJoin`, `syncOnLeave` and `autoReconcile` are independent switches; `autoReconcile` checks current state on enable and every 15 minutes. Previously observed members can be checked after a missed leave when leave synchronization is enabled. Members never observed by this version cannot be inferred from missing history.
|
||||
|
||||
The default `business` mode keeps business roles separate from Matrix moderation powers. Optional `matrix` mode maps powers to membership: `>= levelA` is core, `levelB <= power < levelA` is member, `<= levelC` is restricted. Intermediate values between C and B only remove from the lost room. `syncPowerChanges` is available only in matrix mode. Changing power in the control room still changes the user's native Matrix rights; use business mode when only group access should change.
|
||||
|
||||
`autoCleanup` does not control this plugin. Turning off inactive-member cleanup does not disable separately enabled leave or power synchronization.
|
||||
|
||||
The old `!reset`, `!test ...` and `!level ...` commands return a retirement notice and perform no reset, cleanup or rank mutation.
|
||||
|
||||
## Configuration and deployment
|
||||
|
||||
Copy `.env.example` to `.env` and `config/bots.example.yaml` to `config/bots.yaml`, then supply the deployment's account credentials and room IDs. The configuration accepts multiple accounts and rooms. A room remains managed even when all of its business plugins are disabled. Configure the bot as a member of each control and target room before enabling the relevant features.
|
||||
|
||||
Runtime enable/disable choices and reply language are stored in the database and take precedence over initial configuration defaults after restart. Plugin-specific configuration, room permissions and timezones remain server configuration; changes take effect after restart. Commands do not install packages, accept code or modify server files.
|
||||
|
||||
The following starts the real service when `DRY_RUN=false`:
|
||||
|
||||
```sh
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
For a local installation, install dependencies, generate Prisma's client, initialize a dedicated database and build the application before starting it. `.env` is consumed by Docker Compose; direct Node/Nest startup requires exporting the corresponding environment variables. `DRY_RUN=true` suppresses Matrix transport calls but still initializes storage, migrates legacy data and starts scheduled tasks; use the isolated tests below for validation without touching runtime state.
|
||||
|
||||
Persistent data:
|
||||
|
||||
- `./data`: application SQLite database and plugin states.
|
||||
- `matrix-crypto` volume: Matrix sessions, device credentials and encryption state.
|
||||
- `./config`: read-only runtime configuration mount.
|
||||
- `./plugins`: read-only mount for optional trusted external plugins.
|
||||
|
||||
Back up application storage and encryption/session storage together before upgrading. Keep a single active process per account/database deployment: per-room execution queues and single-use confirmations are coordinated within one process. Daily record uniqueness is additionally enforced by the database, but multiple replicas of the same scheduler are not supported.
|
||||
|
||||
## Development and verification
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run prisma:generate
|
||||
npm run typecheck
|
||||
npm run build
|
||||
npm run test:all
|
||||
```
|
||||
|
||||
Tests use fake Matrix transports, blocked network APIs and unique temporary SQLite databases. Runtime configuration files are unavailable to tests. Prisma CLI test subprocesses use `RUST_LOG=info` to avoid the Prisma 5.22 error-parser issue with missing SQLite files under `RUST_LOG=warn`. Test cleanup tolerates initialization failure.
|
||||
|
||||
See [plugin development](docs/PLUGINS.md) for the API and a complete external plugin example. New trusted modules require a service restart to be discovered; enabling/disabling already installed plugins does not. Hot replacement of module code and sandboxing untrusted third-party code are not provided.
|
||||
@@ -1,144 +1,155 @@
|
||||
# daily-bot-nest
|
||||
# Matrix 插件机器人
|
||||
|
||||
多房间 Matrix 机器人平台(NestJS 重构版)。每个房间机器人是一个**自包含的功能模块**,
|
||||
可**共享账号**或使用**独立 Matrix 账号**;新增机器人只需加一个目录,核心代码不动。
|
||||
[English](README.en.md)
|
||||
|
||||
## 架构
|
||||
基于 NestJS / TypeScript 的多账号、多房间插件平台。核心统一处理 Matrix 登录、加密、消息分发、权限、中英文命令、定时任务和存储。已安装插件可以在群内启停,不需要重启机器人。
|
||||
|
||||
```
|
||||
src/
|
||||
├─ config/ 加载 + 校验 bots.yaml(zod),支持 env(VAR) 引用
|
||||
├─ core/
|
||||
│ ├─ matrix/ SessionManager(账号去重) + MatrixSession(归一化事件 + 出站)
|
||||
│ ├─ bot/ RoomBot 契约 / BotContext / BotRegistry(DiscoveryService 自动发现)
|
||||
│ │ Dispatcher(按 account:roomId 路由) / BotPlatform(总装配)
|
||||
│ ├─ command/ 命令解析(! 前缀,移植自 Rust 版)
|
||||
│ ├─ scheduler/ cron 注册
|
||||
│ └─ db/ Prisma + BotStore(按 bot 名隔离的 KV)
|
||||
└─ bots/
|
||||
└─ checkin/ 示例:签到 bot(命令 + 日报定时)
|
||||
内置插件:
|
||||
|
||||
- **签到 `checkin`**:按业务日期签到、查询统计、可选的长期未签到成员清理。
|
||||
- **成员管理 `room-manager`**:独立业务身份、可选的 Matrix 权限映射及跨群成员同步。
|
||||
|
||||
## 管理与使用
|
||||
|
||||
所有命令支持 `!`、`!` 和 `/` 前缀。部分 Matrix 客户端会拦截斜杠命令,遇到这种情况使用 `!`。英文命令不区分大小写,中英文别名执行同一个处理函数。默认回复中文,可由管理员用 `!语言 英文` 切换;配置及语言设置按房间隔离。
|
||||
|
||||
**英文半角 `!` 和中文全角 `!` 可以互换**,与命令使用中文还是英文无关。每行四种写法效果相同,任选一条发送即可。
|
||||
|
||||
| 操作 | 半角 + 中文 | 全角 + 中文 | 半角 + 英文 | 全角 + 英文 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 签到 | `!签到` | `!签到` | `!checkin` | `!checkin` |
|
||||
| 查自己的签到记录 | `!查询` | `!查询` | `!list` | `!list` |
|
||||
| 查看帮助 | `!帮助` | `!帮助` | `!help` | `!help` |
|
||||
|
||||
单独发送 `签到` 或 `帮助` 也可以。查询请带前缀。
|
||||
|
||||
管理员指房间 `admins` 名单中的用户,或原生 Matrix 权限分达到 `adminPowerLevel` 的用户(默认 100)。读取权限失败时拒绝管理操作。业务身份不会赋予 Matrix 管理权限。
|
||||
|
||||
### 平台命令
|
||||
|
||||
| 中文 | English | 权限与效果 |
|
||||
| --- | --- | --- |
|
||||
| `!帮助` 或 `帮助` | `!help` | 显示当前已启用功能中有权使用的命令 |
|
||||
| `!在线` | `!ping` | 回复 pong |
|
||||
| `!复述 <文本>` | `!echo <text>` | 复述文本 |
|
||||
| `!插件 列表` / `!插件 状态` | `!plugin list` / `!plugin status` | 查看插件状态;错误详情仅管理员可见 |
|
||||
| `!插件 启用 <名称>` | `!plugin enable <name>` | 管理员;启用当前房间的插件 |
|
||||
| `!插件 停用 <名称>` / `!插件 禁用 <名称>` | `!plugin disable <name>` | 管理员;停止插件并保留数据 |
|
||||
| `!语言 中文` / `!语言 英文` | `!language zh-CN` / `!language en` | 管理员;保存房间回复语言 |
|
||||
| `!操作记录` | `!audit` | 管理员;查看最近 10 条操作,房间最多保留 200 条 |
|
||||
|
||||
插件名称可用 `签到` / `checkin`、`成员管理` / `权限同步` / `room-manager`。即使所有业务插件均停用,平台管理命令仍然可用。
|
||||
|
||||
管理员可用 `/config`(`!配置`)查看当前房间 ID、语言、时区和报表设置。`!配置 语言 英文` 立即生效;`!配置 报表 关` 在签到插件下次启动时生效。
|
||||
|
||||
如果配置给一个无域名的房间 ID 误加了 `:域名`,可在实际房间发送 `!配置` 查看提示,再发 `!配置 绑定`。仅限配置 `admins` 名单内且达到该房间管理权限阈值的人。机器人必须已加入该房间,没有加入旧 ID 对应的房间,且候选房间必须唯一。绑定保存到数据库,保留原配置和数据范围,服务下次启动时使用正确的 ID。此命令需要机器人能够读到消息;缺失的历史解密密钥需要单独处理。
|
||||
|
||||
### 签到命令
|
||||
|
||||
| 中文 | English | 权限与效果 |
|
||||
| --- | --- | --- |
|
||||
| `签到` 或 `!签到` | `!checkin` | 普通成员;当日签到 |
|
||||
| `!查询` | `!list` | 普通成员;查询自己的签到摘要 |
|
||||
| `!查询 <用户ID>` / `!查询 全部` | `!list <userId>` / `!list all` | 查询其他人或全部记录需要管理员权限 |
|
||||
| `!查询 [用户ID] --原始` | `!list [userId] --raw` | 管理员;返回 JSON 摘要,也可指定全部 / all |
|
||||
| `!日报 [YYYY-MM-DD]` | `!report daily [YYYY-MM-DD]` | 管理员;只读查询,不重置、不踢人 |
|
||||
| `!月报 [YYYY-MM]` | `!report monthly [YYYY-MM]` | 管理员;只读查询,不清零 |
|
||||
| `!清理 预览` | `!cleanup preview` | 管理员;预览长期未签到候选人 |
|
||||
| `!清理 确认 <确认码>` | `!cleanup confirm <token>` | 管理员;重新校验后执行预览过的名单 |
|
||||
|
||||
签到按“账号、房间、用户、业务日期”唯一记录。业务日期以配置的 `timeZone` 为准,默认北京时间;午夜即可开始新一天签到,不依赖日报执行。重复发送、切换中英文或重复查询报表都不会增加次数。
|
||||
|
||||
等级按累计已知签到次数计算:青铜 1–7、白银 8–14、黄金 15–29、铂金 30–44、钻石 45 次及以上。它只用于展示,不决定群权限。旧数据缺少完整历史时不会虚构累计次数,详见升级说明。
|
||||
|
||||
自动日报在配置时区的每天 03:00 统计前一天,月报在每月 1 日 00:05 统计上月。插件每分钟检查一次到期任务,并保存发送进度。停机后补发最新一期及补发范围说明,不连续刷出所有漏发报表;历史日期仍可查询。首次启用只建立进度,不补发此前报表。
|
||||
|
||||
报表不删除签到记录。日报的成员名单依据**当前群成员**,不是历史成员快照。发送消息与保存进度并非原子操作,若进程在两者之间退出,恢复后可能重复发送通知,但不会重复记签到或清零统计。
|
||||
|
||||
### 成员管理命令
|
||||
|
||||
以下命令均要求管理员权限。
|
||||
|
||||
| 中文 | English | 效果 |
|
||||
| --- | --- | --- |
|
||||
| `!成员管理 状态` | `!access status` | 查看模式与各项自动操作开关 |
|
||||
| `!身份 设置 <用户ID> 核心/普通/受限` | `!role set <userId> core/member/restricted` | 预览业务身份变更;角色参数只填写其中一个值 |
|
||||
| `!成员管理 预览 [用户ID]` / `!成员管理 核对 [用户ID]` | `!access preview [userId]` / `!access reconcile [userId]` | 预览状态差异,不执行成员操作 |
|
||||
| `!成员管理 确认 <确认码>` | `!access confirm <token>` | 重新校验后执行预览中的操作 |
|
||||
|
||||
默认采用独立业务身份,不通过提升原生权限来分配工作群:
|
||||
|
||||
| 身份 | 目标成员状态 |
|
||||
| --- | --- |
|
||||
| 核心 / core | 邀请进入工作群 1、2,从失联群移出 |
|
||||
| 普通 / member | 从工作群 1 移出,邀请进入工作群 2,从失联群移出 |
|
||||
| 受限 / restricted | 从工作群 1、2 移出,邀请进入失联群 |
|
||||
|
||||
邀请仍需成员接受。机器人需要在目标群中具备相应权限。机器人自身不会被清理或同步;原生管理员不会被成员同步移除。
|
||||
|
||||
确认码只对发起预览的管理员、当前房间和当前插件有效,五分钟后过期且只能使用一次。新的同类预览替换旧预览,重新启用插件会使旧确认码失效。执行前会检查成员状态、权限和预览是否仍适用,不会把新出现的操作加入原预览名单。
|
||||
|
||||
## 自动操作开关
|
||||
|
||||
所有成员变更自动化默认关闭,各开关互相独立。
|
||||
|
||||
| 配置 | 作用 |
|
||||
| --- | --- |
|
||||
| `checkin.cleanupEnabled` | 允许通过预览和确认进行未签到清理 |
|
||||
| `checkin.autoCleanup` | 额外允许每天 03:00 后自动清理;必须同时开启 cleanupEnabled |
|
||||
| `room-manager.syncOnJoin` | 加入管理群时按规则同步 |
|
||||
| `room-manager.syncOnLeave` | 离开管理群时移出工作群并邀请进入失联群 |
|
||||
| `room-manager.syncPowerChanges` | 按原生权限变化同步;仅 matrix 模式可用 |
|
||||
| `room-manager.autoReconcile` | 启用时及每 15 分钟按当前状态重新核对 |
|
||||
|
||||
自动清理不会在签到插件的启用钩子中执行;如果明确开启了自动清理且任务到期,后续定时检查可能执行它。豁免名单、管理员、机器人自身、当天已签到和从未有过已知签到记录的成员不会成为清理对象。权限读取失败会跳过并记录。
|
||||
|
||||
成员管理的自动核对可以补偿已观察到成员的漏处理事件;与离群联动共同开启时,也能处理停机期间这些成员的离群。没有被当前版本观察过的历史成员无法凭空恢复。**关闭签到清理不会关闭成员管理的离群或权限联动。**
|
||||
|
||||
可选 `mode: matrix` 使用原生权限映射:分数达到 A 为核心,B 至 A 之间为普通,达到或低于 C 为受限;C 与 B 之间只从失联群移出。必须满足 `levelA > levelB > levelC`。改变原生权限仍会影响该用户在控制群的管理能力;只想改变工作群准入时使用默认 business 模式。
|
||||
|
||||
旧 `!reset`、`!test ...`、`!level ...` 仅回复停用说明,不再重置数据、清理成员或手动修改签到等级。
|
||||
|
||||
## 部署配置
|
||||
|
||||
复制 `.env.example` 为 `.env`,复制 `config/bots.example.yaml` 为 `config/bots.yaml`,填写部署使用的账号及房间信息。机器人应事先加入管理群和所需目标群。配置支持多个账号、多个房间;每个插件实例的数据按账号和房间隔离。
|
||||
|
||||
运行时保存的插件启停状态和回复语言优先于配置中的初始默认值。插件规则、管理员名单、房间及时间设置仍由服务器配置管理,修改后重启生效。聊天命令不会下载安装代码,也不会修改服务器文件。
|
||||
|
||||
以下命令会启动服务,`DRY_RUN=false` 时连接真实 Matrix:
|
||||
|
||||
```sh
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
### 设计要点
|
||||
- **账号可共享/独立**:bot 在配置里声明 `account`。多个 bot 同 account ⇒ 只建一个
|
||||
client(共享);不同 account ⇒ 独立身份。由 `SessionManager` 去重。
|
||||
- **路由**:消息归一化后带 `{account, roomId}`,`Dispatcher` 用 `account:roomId`
|
||||
查 `BotRegistry` 找到对应 bot,调其钩子。
|
||||
- **隔离**:每个 bot 通过 `BotContext.db` 拿到按自身名字 scope 的 `BotStore`,数据互不串。
|
||||
- **可测试**:bot 只依赖 `BotContext` 接口,单测 mock 即可,无需真连 Matrix。
|
||||
- **可扩展**:新增 bot = 新建 `bots/xxx/`,类上加 `@RegisterBot()`,在 `AppModule` import 其 module。
|
||||
本地直接使用 Node/Nest 启动时,需要先安装依赖、生成 Prisma 客户端、初始化专用数据库并构建,同时将所需变量导出到进程环境。`.env` 由 Docker Compose 读取;直接启动应用不会自动把该文件全部导入环境。
|
||||
|
||||
## 快速开始(本地)
|
||||
`DRY_RUN=true` 只抑制 Matrix 传输,仍会初始化数据库、运行旧数据迁移并注册定时任务。验证代码请使用下面的隔离测试,不要把 dry-run 当作完全只读检查。
|
||||
|
||||
```bash
|
||||
cp .env.example .env # 配置 DATABASE_URL / DRY_RUN / 各账号密码
|
||||
cp config/bots.example.yaml config/bots.yaml # 复制配置模板,填写真实房间 ID 与账号
|
||||
npm install
|
||||
持久化内容包括:
|
||||
|
||||
- `./data`:应用数据库、插件数据和启停状态。
|
||||
- `matrix-crypto` 卷:Matrix 登录会话、设备凭据及加密状态。
|
||||
- `./config`:只读挂载的运行配置。
|
||||
- `./plugins`:只读挂载的外部插件目录。
|
||||
|
||||
升级前应一致备份应用数据及会话加密数据。每套账号及数据库部署只运行一个活动进程;每个房间的命令、事件、定时任务和插件启停在进程内串行协调。数据库额外保证每日签到唯一,但暂不支持多个副本共同执行同一套定时任务及确认操作。
|
||||
|
||||
## 测试与扩展
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run prisma:generate
|
||||
npm run prisma:push # 初始化数据库表
|
||||
npm test # 跑单元测试
|
||||
npm run test:integration # 跑集成测试(使用临时 SQLite,自动清理)
|
||||
DRY_RUN=true npm run start # 不连 Matrix 的装配验证(打印路由表)
|
||||
npm run typecheck
|
||||
npm run build
|
||||
npm run test:all
|
||||
```
|
||||
|
||||
> **注意**:`config/bots.yaml` 包含真实凭据,已加入 `.gitignore` 不会被提交。
|
||||
> 首次克隆后必须先从 `bots.example.yaml` 复制并填写,否则启动时会报错提示。
|
||||
测试使用模拟 Matrix、被拦截的网络接口及独立临时 SQLite 数据库,不读取运行配置。测试中的 Prisma CLI 子进程固定使用 `RUST_LOG=info`,绕过 Prisma 5.22 在 `warn` 日志级别下解析新建数据库错误的问题。初始化失败时清理步骤也不会继续访问未创建的数据库对象。
|
||||
|
||||
真实运行:把 `.env` 里 `DRY_RUN` 设为 false,并填好 `config/bots.yaml` 的房间与各账号密码。
|
||||
新插件无需修改应用模块、消息分发或会话管理代码。放入已配置目录并重启发现后,就能通过插件命令启用。已安装插件的启停无需重启;插件代码热替换和不可信代码沙箱暂未提供。
|
||||
|
||||
## Docker 部署
|
||||
- [升级与旧数据迁移](docs/UPGRADE.md)
|
||||
- [插件 API 与开发说明](docs/PLUGINS.md)
|
||||
- [可运行的外部插件示例](examples/greeting.plugin.js)
|
||||
|
||||
```bash
|
||||
cp .env.example .env # 填好各账号密码与 DRY_RUN;DATABASE_URL 由 compose 覆盖
|
||||
cp config/bots.example.yaml config/bots.yaml # 复制模板后填写真实房间 ID 与账号
|
||||
# 编辑 config/bots.yaml,填入真实房间 ID 与 homeServer 等信息
|
||||
|
||||
docker compose up -d --build # 构建并后台启动
|
||||
docker compose logs -f # 看日志
|
||||
```
|
||||
|
||||
- 启动时 `docker-entrypoint.sh` 会自动 `prisma db push` 建表(幂等)。
|
||||
- SQLite 数据落在与 `docker-compose.yml` 同级的 **`./data/` 本地目录**(bind mount 到
|
||||
`/app/data`),容器重建不丢数据。该目录已在 `.gitignore`/`.dockerignore` 中排除
|
||||
(仅保留 `.gitkeep` 占位),不会被提交或打进镜像。
|
||||
- `config/` 以只读方式挂载;改完配置 `docker compose restart` 即生效。
|
||||
- `DRY_RUN` 现由 `.env` 控制(不再被 compose 写死)。真实运行设 `DRY_RUN=false`。
|
||||
- 切 Postgres:改 `prisma/schema.prisma` 的 provider 为 `postgresql`,
|
||||
并把 compose 里 `DATABASE_URL` 指向 Postgres 连接串即可。
|
||||
|
||||
## 排错
|
||||
|
||||
**容器反复重启 / 日志不断打印登录**
|
||||
根因通常是 **Matrix 用户名或密码错误**:登录返回 `M_FORBIDDEN [403]`,进程退出,
|
||||
被 compose `restart: on-failure` 拉起后再次失败,形成循环。处理:
|
||||
- 核对 `.env` 的账号密码、`config/bots.yaml` 的 `userId` / `homeServer`;
|
||||
- 程序已对凭据类错误延迟 30 秒再退出,以避免高频登录被 homeserver 限流/封禁;
|
||||
- 本地仅想验证装配,可在 `.env` 设 `DRY_RUN=true` 跳过真实登录。
|
||||
|
||||
## 控制方式
|
||||
- **配置**:`config/bots.yaml` 决定哪些 bot、用什么账号、管哪些房间。改后重启生效。
|
||||
- **房间内命令**:管理员直接在 Matrix 房间发 `!` 命令。
|
||||
- 无需前端;REST 管理 API 为将来预留(当前未实现)。
|
||||
|
||||
## 签到 bot 命令
|
||||
|
||||
| 命令 | 说明 |
|
||||
|---|---|
|
||||
| `!checkin` 或 直接发「签到」 | 今日签到(全角「!签到」也可) |
|
||||
| `!list <用户ID\|all> [--raw]` | 查询签到状态,`--raw` 输出 JSON |
|
||||
| `!reset` | 重置所有人当日签到状态 **🔒 管理员** |
|
||||
| `!test daily\|monthly` | 手动触发日报/月报(运维测试用)**🔒 管理员** |
|
||||
| `!echo <文本>` / `!ping` / `!help` | 杂项 |
|
||||
|
||||
签到等级(青铜 / 白银 / 黄金 / 铂金 / 钻石)将根据用户的累计签到次数纯自动升级,仅作趣味展示。
|
||||
|
||||
> **🔒 管理员权限与免死特权**:
|
||||
> `reset` / `test` 等管理命令仅 **房间内 power level ≥ `adminPowerLevel`(默认 100)** 或在 `config.admins` 白名单中的用户可调用。
|
||||
> 同时,**只要用户的原生权限分达到了管理员级别,就会在每天凌晨的清理逻辑中被自动“免死”**(即使长期不签到也不会被踢)。
|
||||
> 所有权限调整请直接在 Element 客户端的「房间设置 → 权限」里通过原生 UI 操作,无需手动输入命令。
|
||||
|
||||
### 定时任务
|
||||
- **每日 03:00**:生成签到日报(按今日未签到 / ≥7 / ≥14 / ≥30 天 / 从未签到分桶),
|
||||
发到 `mainRoom`;若 `autoKick: true`,踢出未签到 ≥ `kickDays` 天的用户
|
||||
(尊重 `whitelist` 与超级管理),然后重置当日签到。
|
||||
- **每月 1 日 00:05**:生成月度签到排行,发到 `mainRoom`,重置月度计数。
|
||||
|
||||
### checkin 配置项(`config/bots.yaml` 的 `config`)
|
||||
| 字段 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `mainRoom` | 第一个房间 | 日报/月报发送的房间 |
|
||||
| `kickDays` | 30 | 自动踢人的未签到天数阈值 |
|
||||
| `autoKick` | false | 是否在日报后自动踢人 |
|
||||
| `whitelist` | [] | 永不踢出的用户列表 |
|
||||
| `adminPowerLevel` | 100 | 房间内 power level ≥ 此值即视为管理员(100=管理员、50=版主) |
|
||||
| `admins` | [] | 额外管理员白名单(power level 之外的补充,可留空) |
|
||||
|
||||
## 权限同步机器人 (Room Manager)
|
||||
|
||||
该机器人不靠命令驱动,而是**监听 Matrix 原生的权限分(Power Level)变化以及人员离开事件**。
|
||||
1. **权限联动**:管理员只需在客户端(如 Element)的签到房间设置里,点开用户头像修改权限等级,机器人就会自动将该用户跨群调配到不同的工作房或小黑屋中。
|
||||
2. **踢出联动**:如果某个用户主动退出了签到房,或者因为长期不打卡被签到机器人踢出了签到房,该机器人也会立即将其视为“失去大本营身份”,自动将其从所有工作房踢出,并丢进失联房。
|
||||
|
||||
| 原生权限分 | 内部级别 | 默认自动执行的操作 |
|
||||
|---|---|---|
|
||||
| `≥ levelA` | 最高权限 (如版主 50) | 邀请进**工作房1**,邀请进**工作房2** |
|
||||
| `== levelB`| 中等权限 (如默认 0) | 从**工作房1**踢出,邀请进**工作房2** |
|
||||
| `≤ levelC` | 最低权限 (如受限 -1) | 从**工作房1、2**踢出,邀请进**失联房** |
|
||||
|
||||
### room-manager 配置项(`config/bots.yaml` 的 `config`)
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `workRoom1` | 高级工作群 ID(最高权限才能进) |
|
||||
| `workRoom2` | 普通工作群 ID(中高权限能进) |
|
||||
| `lostRoom` | 失联小黑屋 ID(最低权限进入) |
|
||||
| `levelA` | 最高权限的分数阈值,默认为 `50` |
|
||||
| `levelB` | 中等权限的分数,默认为 `0` |
|
||||
| `levelC` | 最低权限的分数阈值,默认为 `-1` |
|
||||
|
||||
> **注意**:`room-manager` 机器人的 `rooms` 数组中,应当**只填写**“签到/管理房”的 ID。机器人只会在这个房间里当“保安”监听原生权限变化,然后往外执行踢/拉操作。
|
||||
|
||||
## 新增一个机器人(例:notify)
|
||||
1. 新建 `src/bots/notify/notify.bot.ts`,`implements RoomBot`,类上加 `@RegisterBot()`。
|
||||
2. 新建 `notify.module.ts`,`providers: [NotifyBot]`。
|
||||
3. `AppModule` 的 imports 里加 `NotifyModule`。
|
||||
4. `config/bots.yaml` 增加一条 `{ name: notify, account: main, rooms: [...] }`。
|
||||
目前内置签到和成员管理,RSS 订阅可在此接口上独立扩展,尚未内置 RSS 拉取和解析功能。
|
||||
+40
-54
@@ -1,59 +1,45 @@
|
||||
# 账号:每个唯一账号只会登录一次并复用一个 client。
|
||||
# 多个 bot 引用同一 account ⇒ 共享账号;引用不同 account ⇒ 独立身份。
|
||||
#
|
||||
# homeServer 填账号域名即可(如 https://matrix.org),程序会自动通过
|
||||
# /.well-known/matrix/client 发现真实 API 地址。
|
||||
# 也可直接填真实 API 地址跳过发现。
|
||||
#
|
||||
# 密码用 env(VAR_NAME) 引用环境变量,避免明文密码入版本库。
|
||||
# 在 .env 文件中设置对应的环境变量(参见 .env.example)。
|
||||
accounts:
|
||||
main:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@mybot:example.com"
|
||||
password: "env(MAIN_PW)"
|
||||
checkin:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@checkin:example.com"
|
||||
password: "env(CHECKIN_PW)"
|
||||
homeServer: "https://matrix.example.org"
|
||||
userId: "@bot:example.org"
|
||||
password: "env(BOT_PASSWORD)"
|
||||
|
||||
# 每个 bot 是一个独立功能模块,声明用哪个账号、管哪些房间、私有配置。
|
||||
bots:
|
||||
- name: checkin
|
||||
account: checkin
|
||||
rooms:
|
||||
- "!yourRoomId:example.com" # 替换为真实 Matrix 房间 ID(以 ! 开头)
|
||||
config:
|
||||
mainRoom: "!yourRoomId:example.com" # 日报/月报发送的目标房间(默认取 rooms[0])
|
||||
kickDays: 30 # 未签到超过多少天触发自动踢人
|
||||
autoKick: false # true 时每日日报后自动踢出长期未签到用户
|
||||
adminPowerLevel: 100 # 房间内 power level ≥ 此值视为管理员(100=管理员、50=版主)
|
||||
admins: [] # 额外管理员白名单(power level 之外的补充,可留空)
|
||||
# - "@admin:example.com"
|
||||
whitelist: [] # 额外的免踢白名单(注意:权限分 >= adminPowerLevel 的人已自动免死,无需填在此处。这里只填低权限但免踢的特权用户,比如机器人或老板账号)
|
||||
# - "@vip:example.com"
|
||||
# Only server-installed, trusted modules are loaded from these directories.
|
||||
pluginDirectories:
|
||||
- "./plugins"
|
||||
|
||||
# 示例:共享 main 账号的另一个 bot(实现后取消注释并启用)
|
||||
# - name: notify
|
||||
# account: main
|
||||
# rooms:
|
||||
# - "!anotherRoom:example.com"
|
||||
rooms:
|
||||
- account: main
|
||||
roomId: "!control:example.org"
|
||||
locale: zh-CN
|
||||
timeZone: Asia/Shanghai
|
||||
adminPowerLevel: 100
|
||||
admins: []
|
||||
plugins:
|
||||
checkin:
|
||||
enabled: true
|
||||
config:
|
||||
reportsEnabled: true
|
||||
cleanupEnabled: false
|
||||
autoCleanup: false
|
||||
kickDays: 30
|
||||
whitelist: []
|
||||
room-manager:
|
||||
enabled: false
|
||||
config:
|
||||
workRoom1: "!work1:example.org"
|
||||
workRoom2: "!work2:example.org"
|
||||
lostRoom: "!lost:example.org"
|
||||
mode: business
|
||||
syncPowerChanges: false
|
||||
syncOnJoin: false
|
||||
syncOnLeave: false
|
||||
autoReconcile: false
|
||||
levelA: 50
|
||||
levelB: 0
|
||||
levelC: -1
|
||||
|
||||
# =======================================================
|
||||
# 原生权限联动保安 (room-manager)
|
||||
# =======================================================
|
||||
# 该机器人不靠命令驱动,而是监听 Matrix 原生权限(Power Level)。
|
||||
# 管理员在客户端(Element)直接改成员权限,机器人会自动拉/踢人。
|
||||
- name: room-manager
|
||||
account: main
|
||||
rooms:
|
||||
- "!checkinRoomId:example.com" # 【务必】只填签到/管理房的ID!作为控制中枢。
|
||||
config:
|
||||
workRoom1: "!workRoom1Id:example.com" # 工作房 A (核心群)
|
||||
workRoom2: "!workRoom2Id:example.com" # 工作房 B (普通群)
|
||||
lostRoom: "!lostRoomId:example.com" # 失联房 (小黑屋)
|
||||
|
||||
# 分数映射 (对应 Element 客户端里的权限设定)
|
||||
levelA: 50 # 最高权限(如版主50):进工作房1 + 进工作房2
|
||||
levelB: 0 # 中等权限(如默认0) :踢出工作房1 + 保留在工作房2
|
||||
levelC: -1 # 最低权限(如受限-1):踢出工作房1、2 + 丢进失联房
|
||||
# For an existing v1 database, explicitly assign the shared check-in data.
|
||||
# legacyCheckinTarget:
|
||||
# account: main
|
||||
# roomId: "!control:example.org"
|
||||
+3
-3
@@ -8,16 +8,16 @@ services:
|
||||
environment:
|
||||
# SQLite 落到挂载卷,保证容器重建后数据不丢。
|
||||
DATABASE_URL: "file:/app/data/prod.db"
|
||||
TZ: "Asia/Shanghai"
|
||||
# DRY_RUN 由 .env 控制(true=本地不连 Matrix 仅装配验证)。
|
||||
volumes:
|
||||
# 业务数据(Prisma 的 prod.db):宿主 ./data <-> 容器 /app/data,方便直接查看。
|
||||
- ./data:/app/data
|
||||
# E2EE 加密状态 + 登录凭据:用 Docker 命名卷,跑在 Linux ext4 上。
|
||||
# 不能用 macOS bind mount —— Rust 加密内核的 SQLite 在 virtiofs/gRPC-FUSE
|
||||
# 文件虚拟化下会损坏(database disk image is malformed),导致解密失败。
|
||||
# Keep encryption state and session credentials in a persistent named volume.
|
||||
- matrix-crypto:/app/data/matrix
|
||||
# 配置热改:改完重启容器即可生效。
|
||||
- ./config:/app/config:ro
|
||||
- ./plugins:/app/plugins:ro
|
||||
|
||||
volumes:
|
||||
# 命名卷:加密会话与设备密钥持久化于此,容器重建/重启不丢,device 固定不再重新验证。
|
||||
|
||||
@@ -4,7 +4,7 @@ set -e
|
||||
# 启动前确保数据库表已就绪(SQLite/Postgres 均适用)。
|
||||
# 幂等:已存在则无操作。
|
||||
echo "[entrypoint] syncing database schema..."
|
||||
npx prisma db push --skip-generate
|
||||
RUST_LOG=info node node_modules/prisma/build/index.js db push --skip-generate
|
||||
|
||||
echo "[entrypoint] starting daily-bot-nest..."
|
||||
exec node dist/main.js
|
||||
@@ -0,0 +1,45 @@
|
||||
# Plugin API v1
|
||||
|
||||
## Loading
|
||||
|
||||
Built-in plugin files are discovered recursively under the compiled `dist/plugins` directory. External directories are listed in `pluginDirectories`. Entry files end in `.plugin.js` and export a default manifest via CommonJS (`exports.default = ...`). TypeScript built-ins use `.plugin.ts` during development and compile to JavaScript. External TypeScript plugins must be compiled first. External dependencies should be packaged alongside the plugin or installed by the server operator.
|
||||
|
||||
A manifest declares:
|
||||
|
||||
- `apiVersion: 1`, a unique lowercase `id`, a `version`, optional name aliases and bilingual `description`.
|
||||
- `validate(config)`, returning validated configuration or throwing an error.
|
||||
- Optional `allowedRooms(config)`, declaring additional target rooms for membership actions and reads.
|
||||
- `create(context, config)`, returning an instance with a command list and optional `start`, `stop`, `onMember` and `onPowerLevel` hooks.
|
||||
|
||||
Duplicate plugin IDs/name aliases and incompatible manifests reject discovery. Command alias collisions reject that plugin's activation before its start hook runs. A failed activation cancels registered jobs and leaves the host's management commands available. Installed plugins with missing required configuration appear as failed until configuration is corrected and activation is retried.
|
||||
|
||||
Plugins are trusted code running in the host process. Context room checks and abort signals prevent accidental use outside declared scopes, but are not a security sandbox. Only operators install files; chat commands cannot fetch packages or execute uploaded code.
|
||||
|
||||
## Context
|
||||
|
||||
The public interfaces live in `src/core/plugin/types.ts`. The context provides:
|
||||
|
||||
- `account`, `botUserId`, `roomId`, `locale`, `timeZone`, `adminPowerLevel`, `signal`, `now()`.
|
||||
- `t({ 'zh-CN': ..., en: ... }, values)` for shared interpolation and language selection.
|
||||
- `db.get/set/create/remove/entries`, already isolated to the account/room/plugin instance. `create` is atomic and returns false for an existing key.
|
||||
- `send(text)` and `reply(message, text)` to the current room.
|
||||
- `members(roomId?)`, `power(userId)`, `isAdmin(userId)`; lookup failures propagate from members/power while administrative checks deny on failure.
|
||||
- `kick(roomId, userId, reason)` and `invite(roomId, userId)` to declared rooms.
|
||||
- `schedule(name, cron, callback)` using the room timezone. The host serializes callbacks with commands, lifecycle changes and events.
|
||||
- `audit(action, actor, details)` for room-scoped administrative history.
|
||||
|
||||
Use `context.schedule` instead of unmanaged timers. Disable waits behind already running room work, unregisters scheduled callbacks, aborts the instance signal, calls `stop` and retains data. Async work started outside host callbacks must observe the abort signal and release its resources in `stop`. A stalled plugin can stall its room; plugins should use bounded I/O and cancellation. A process shutdown additionally prevents new transport operations while queues drain.
|
||||
|
||||
Use `context.t` and declarative command aliases instead of branching on language in handlers. `context.locale` is a live getter so an enabled plugin sees language changes immediately.
|
||||
|
||||
## Commands
|
||||
|
||||
Each command declares `id`, `paths`, optional exact `bare` aliases, optional `admin: true`, localized `description` and `usage`, and `run(invocation)`.
|
||||
|
||||
The host matches the longest registered command path, normalizes command words and fullwidth prefixes, preserves quoted arguments and recognizes `--raw` / `--原始`. The handler receives `{ message, args, raw }`. Prefix-free aliases must match the entire message, preventing ordinary conversation from accidentally executing a command. The host handles the primary administrator check, help generation and errors. Plugins should also validate arguments and recheck permissions immediately before delayed or confirmed mutations.
|
||||
|
||||
## Complete example
|
||||
|
||||
Copy `examples/greeting.plugin.js` into an external directory listed in configuration. After restarting to discover the file, use `!plugin enable greeting` or `!插件 启用 问候`. Then `!greet World` and `!问候 世界` invoke the same handler. `!language en` changes the response language without reinstalling the plugin. No changes to the application module, dispatcher or session manager are needed.
|
||||
|
||||
A future RSS plugin can use the same API to register subscription commands, persist subscriptions/deduplication keys and schedule polling. Feed retrieval and parsing belong inside that plugin. The host does not currently include an RSS feed parser or subscription implementation.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Upgrade from static modules
|
||||
|
||||
## Behavior changes
|
||||
|
||||
- `rooms` replaces static bot-module registration. The host discovers plugin manifests automatically.
|
||||
- A room's plugin state and reply language persist. After the first activation, stored choices override configuration defaults.
|
||||
- Check-in day boundaries are local midnight in the configured timezone. Reports no longer reset daily or monthly data.
|
||||
- Manual report queries are read-only. Legacy reset, test and manual-level commands no longer execute their previous behavior.
|
||||
- Other-user, all-user and raw check-in queries require administrator access.
|
||||
- Cleanup requires `cleanupEnabled`; automatic cleanup additionally requires `autoCleanup`. The legacy `autoKick` field is not carried forward as authorization for the new cleanup workflow.
|
||||
- Membership management defaults to independent business roles. All automatic membership switches default to false. To retain native power mapping, explicitly choose `mode: matrix` and the required synchronization switches.
|
||||
- Native administrators are exempt from membership removals. Failed permission lookups do not authorize removals.
|
||||
- Startup does not announce each plugin. Re-enabling a plugin may deliver due report notifications, and explicitly enabled membership reconciliation can run on enable.
|
||||
- Old command events preceding the current Matrix session process are ignored to avoid replaying administrative actions. Optional reconciliation works from current membership state.
|
||||
|
||||
## Configuration
|
||||
|
||||
Use the example `rooms` format for new deployments. The legacy `bots` format is normalized into one plugin instance per account/room, but it should be replaced during upgrade. Do not mix `rooms` and `bots` in one file. Reports are local to each plugin instance; the old `mainRoom` aggregation setting is no longer used.
|
||||
|
||||
For a legacy `checkin` bot bound to exactly one account and one room, the migration target is inferred. When shared records previously covered multiple rooms, select exactly one destination explicitly:
|
||||
|
||||
```yaml
|
||||
legacyCheckinTarget:
|
||||
account: main
|
||||
roomId: "!control:example.org"
|
||||
```
|
||||
|
||||
The destination must exist in `rooms` and have a configured `checkin` plugin. New room configurations using an old database also need this target. Migration refuses an ambiguous destination, an already populated destination without a migration marker, malformed source records or reassignment after a completed migration.
|
||||
|
||||
## Data conversion
|
||||
|
||||
The old table used `checkin` as a shared storage scope. Version 2 scopes records by account, room and plugin. Migration copies records and writes its completion marker in one transaction; it leaves the original rows intact.
|
||||
|
||||
The legacy schema contains the current monthly count and last check-in timestamp, not a complete daily or lifetime history. Migration preserves the known monthly count as a baseline and the last check-in date as a non-counting daily record. This prevents double counting or a second check-in on that date. Earlier daily dates and earlier monthly totals cannot be reconstructed. The displayed cumulative total is therefore the known baseline plus new records, not an invented lifetime total. Legacy levels are recalculated from that known total. Source data remains available for an explicit future reconciliation if additional history is available.
|
||||
|
||||
Take a consistent backup before the first upgraded startup. A code rollback alone does not copy new v2 activity back into legacy records; restore a compatible backup or explicitly reconcile subsequent activity. Migration runs during service initialization, before Matrix sessions start.
|
||||
@@ -0,0 +1,23 @@
|
||||
const description = { 'zh-CN': '问候示例', en: 'Greeting example' };
|
||||
exports.default = {
|
||||
apiVersion: 1,
|
||||
id: 'greeting',
|
||||
aliases: ['问候'],
|
||||
version: '1.0.0',
|
||||
description,
|
||||
validate(config) { return config; },
|
||||
create(ctx) {
|
||||
return {
|
||||
commands: [{
|
||||
id: 'greeting.send',
|
||||
paths: [['greet'], ['问候']],
|
||||
description,
|
||||
usage: { 'zh-CN': '!问候 <名字>', en: '!greet <name>' },
|
||||
async run({ message, args }) {
|
||||
await ctx.reply(message, ctx.t({ 'zh-CN': '你好,{name}!', en: 'Hello, {name}!' },
|
||||
{ name: args.join(' ') || 'World' }));
|
||||
},
|
||||
}],
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -4,11 +4,12 @@ module.exports = {
|
||||
rootDir: 'src',
|
||||
testRegex: '\\.integration\\.spec\\.ts$',
|
||||
transform: {
|
||||
'^.+\\.(t|j)s$': 'ts-jest',
|
||||
'^.+\\.ts$': 'ts-jest',
|
||||
},
|
||||
collectCoverageFrom: ['**/*.(t|j)s'],
|
||||
coverageDirectory: '../coverage-integration',
|
||||
testEnvironment: 'node',
|
||||
setupFilesAfterEnv: ['<rootDir>/test/no-network.ts'],
|
||||
// 集成测试串行执行,避免多个测试同时写同一个 SQLite 文件
|
||||
maxWorkers: 1,
|
||||
};
|
||||
+2
-1
@@ -3,6 +3,7 @@
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
"deleteOutDir": true,
|
||||
"tsConfigPath": "tsconfig.build.json"
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -12,7 +12,9 @@
|
||||
"test": "jest",
|
||||
"test:integration": "jest --config jest.integration.config.js",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:push": "prisma db push"
|
||||
"prisma:push": "prisma db push",
|
||||
"typecheck": "tsc --noEmit --incremental false",
|
||||
"test:all": "npm test -- --runInBand && npm run test:integration"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^10.4.4",
|
||||
@@ -50,12 +52,15 @@
|
||||
"rootDir": "src",
|
||||
"testRegex": "(?<!\\.integration)\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
"^.+\\.ts$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
"testEnvironment": "node",
|
||||
"setupFilesAfterEnv": [
|
||||
"<rootDir>/test/no-network.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -4,5 +4,6 @@
|
||||
!.gitignore
|
||||
!cross-sign/
|
||||
!cross-sign/**
|
||||
!test-network-guard.cjs
|
||||
# 但 cross-sign 下的依赖仍不提交。
|
||||
cross-sign/node_modules/
|
||||
@@ -29,11 +29,11 @@ node ./cross-sign.mjs
|
||||
|
||||
然后按提示**交互式粘贴**即可(无需任何环境变量 / 配置文件):
|
||||
|
||||
1. 账号域名或 API 地址(回车用默认 `tchncs.de`)
|
||||
2. 账号 user id(回车用默认 `@eskimapro:tchncs.de`)
|
||||
1. 输入账号域名或 API 地址
|
||||
2. 输入完整的 Matrix 用户 ID,例如 `@bot:example.org`
|
||||
3. 账号密码 —— **粘贴时不回显**
|
||||
4. 安全密钥(base58,如 `EsTc ...`)—— 不回显;直接回车则改填安全短语
|
||||
5. 要签名的设备 ID(回车用默认 `ZHEAJZJMDZ`;留空则签名名下所有未验证设备)
|
||||
5. 输入要签名的设备 ID。留空后还需输入 `ALL` 才会签名所有未验证设备。
|
||||
|
||||
跑一次即可,之后无需再跑(除非 bot 重新登录产生了新设备)。
|
||||
|
||||
|
||||
@@ -60,8 +60,10 @@ let TARGET_DEVICE_ID = '';
|
||||
async function main() {
|
||||
console.log('=== bot 设备 cross-signing 工具 ===\n');
|
||||
|
||||
const homeserverInput = await ask('账号域名或 API 地址', 'tchncs.de');
|
||||
const userId = await ask('账号 user id', '@eskimapro:tchncs.de');
|
||||
const homeserverInput = await ask('账号域名或 API 地址');
|
||||
if (!homeserverInput) fail('必须输入账号域名或 API 地址。');
|
||||
const userId = await ask('账号 user id');
|
||||
if (!userId) fail('必须输入账号 ID。');
|
||||
PASSWORD = await askSecret('账号密码(粘贴,不回显)');
|
||||
if (!PASSWORD) fail('必须输入密码。');
|
||||
|
||||
@@ -80,10 +82,10 @@ async function main() {
|
||||
if (!SECURITY_PHRASE) fail('安全密钥和安全短语必须至少提供一个。');
|
||||
}
|
||||
|
||||
TARGET_DEVICE_ID = await ask(
|
||||
'要签名的设备 ID(留空=签名名下所有未验证设备)',
|
||||
'ZHEAJZJMDZ',
|
||||
);
|
||||
TARGET_DEVICE_ID = await ask('要签名的设备 ID');
|
||||
if (!TARGET_DEVICE_ID && await ask('签名所有未验证设备?输入 ALL 确认') !== 'ALL') {
|
||||
fail('未选择签名目标。');
|
||||
}
|
||||
|
||||
// 1) 解析真实 API 地址(支持裸域名 well-known 发现)
|
||||
const baseUrl = await resolveBaseUrl(homeserverInput);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
const blocked = () => { throw new Error('Network access is disabled in test subprocesses'); };
|
||||
require('node:http').request = blocked;
|
||||
require('node:http').get = blocked;
|
||||
require('node:https').request = blocked;
|
||||
require('node:https').get = blocked;
|
||||
require('node:net').Socket.prototype.connect = blocked;
|
||||
require('node:tls').connect = blocked;
|
||||
global.fetch = blocked;
|
||||
const fs = require('node:fs');
|
||||
const exists = fs.existsSync.bind(fs);
|
||||
const read = fs.readFileSync.bind(fs);
|
||||
const privateConfiguration = path => typeof path === 'string' &&
|
||||
(/(^|\/)\.env(?:\..*)?$/.test(path) || /(^|\/)config\/bots\.yaml$/.test(path));
|
||||
fs.existsSync = path => privateConfiguration(path) ? false : exists(path);
|
||||
fs.readFileSync = (path, ...args) => {
|
||||
if (privateConfiguration(path)) throw new Error('Runtime configuration is unavailable in tests');
|
||||
return read(path, ...args);
|
||||
};
|
||||
@@ -3,8 +3,6 @@ import { ConfigModule } from './config/config.module';
|
||||
import { DbModule } from './core/db/db.module';
|
||||
import { MatrixModule } from './core/matrix/matrix.module';
|
||||
import { BotModule } from './core/bot/bot.module';
|
||||
import { CheckinModule } from './bots/checkin/checkin.module';
|
||||
import { RoomManagerModule } from './bots/room-manager/room-manager.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -12,9 +10,6 @@ import { RoomManagerModule } from './bots/room-manager/room-manager.module';
|
||||
DbModule,
|
||||
MatrixModule,
|
||||
BotModule,
|
||||
// —— 在此注册各房间机器人 feature module ——
|
||||
CheckinModule,
|
||||
RoomManagerModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -1,372 +0,0 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { RegisterBot } from '../../core/bot/register-bot.decorator';
|
||||
import { BotContext, RoomBot } from '../../core/bot/room-bot.interface';
|
||||
import {
|
||||
CronSpec,
|
||||
InboundMessage,
|
||||
ParsedCommand,
|
||||
} from '../../core/command/types';
|
||||
import {
|
||||
analyzeUnchecked,
|
||||
buildDailyReport,
|
||||
computeKickTargets,
|
||||
} from './report';
|
||||
import {
|
||||
applyCheckin,
|
||||
levelChoices,
|
||||
levelLabel,
|
||||
newUserState,
|
||||
parseLevel,
|
||||
resetDaily,
|
||||
resetMonthly,
|
||||
UserState,
|
||||
} from './user-state';
|
||||
|
||||
interface CheckinConfig {
|
||||
mainRoom?: string;
|
||||
kickDays: number;
|
||||
autoKick: boolean;
|
||||
whitelist: string[];
|
||||
admins: string[];
|
||||
adminPowerLevel: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签到机器人:完整移植 Rust daily_bot 的签到/等级/日报/踢人/月统计。
|
||||
*
|
||||
* 命令(! 前缀):
|
||||
* !ping
|
||||
* !checkin
|
||||
* !list <用户ID|all>
|
||||
* !reset 重置所有用户当日签到
|
||||
* !level set <用户ID> <等级>
|
||||
* !level raise <用户ID>
|
||||
* !level super <用户ID>
|
||||
* !level clear <用户ID>
|
||||
* 定时:
|
||||
* 每日 03:00 日报 + 可选自动踢人 + 重置当日
|
||||
* 每月 1 日 00:05 月度统计 + 重置月度计数
|
||||
*/
|
||||
@RegisterBot()
|
||||
@Injectable()
|
||||
export class CheckinBot implements RoomBot {
|
||||
readonly name = 'checkin';
|
||||
readonly account: string;
|
||||
readonly rooms: string[];
|
||||
private readonly logger = new Logger('CheckinBot');
|
||||
private readonly cfg: CheckinConfig;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
const entry = config.bots.find((b) => b.name === 'checkin');
|
||||
if (!entry) {
|
||||
throw new Error('config 中缺少 name=checkin 的 bot 配置');
|
||||
}
|
||||
this.account = entry.account;
|
||||
this.rooms = entry.rooms;
|
||||
const c = entry.config;
|
||||
this.cfg = {
|
||||
mainRoom: (c.mainRoom as string) ?? entry.rooms[0],
|
||||
kickDays: (c.kickDays as number) ?? 30,
|
||||
autoKick: (c.autoKick as boolean) ?? false,
|
||||
whitelist: (c.whitelist as string[]) ?? [],
|
||||
admins: (c.admins as string[]) ?? [],
|
||||
adminPowerLevel: (c.adminPowerLevel as number) ?? 100,
|
||||
};
|
||||
this.logger.log(
|
||||
`管理员判定:房间 power level ≥ ${this.cfg.adminPowerLevel}` +
|
||||
(this.cfg.admins.length > 0
|
||||
? ` 或 config.admins 白名单(${this.cfg.admins.length} 人)`
|
||||
: ''),
|
||||
);
|
||||
}
|
||||
|
||||
/** 管理员鉴权:房间内 power level ≥ 阈值,或在 config.admins 白名单中。 */
|
||||
private async isAdmin(
|
||||
roomId: string,
|
||||
userId: string,
|
||||
ctx: BotContext,
|
||||
): Promise<boolean> {
|
||||
if (this.cfg.admins.includes(userId)) return true;
|
||||
const power = await ctx.getPowerLevel(roomId, userId);
|
||||
return power >= this.cfg.adminPowerLevel;
|
||||
}
|
||||
|
||||
/** 校验调用者是否管理员,非管理员回拒绝并返回 false。 */
|
||||
private async requireAdmin(
|
||||
cmd: ParsedCommand,
|
||||
ctx: BotContext,
|
||||
): Promise<boolean> {
|
||||
if (await this.isAdmin(cmd.raw.roomId, cmd.raw.userId, ctx)) return true;
|
||||
await ctx.reply(cmd.raw, '⛔ 无权限:该命令仅管理员可用');
|
||||
this.logger.warn(
|
||||
`拒绝越权命令 !${cmd.command} 来自 ${cmd.raw.userId}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 平台登录完成后,向主房间发送一条上线通知,便于确认收发正常。 */
|
||||
async onReady(ctx: BotContext): Promise<void> {
|
||||
const room = this.cfg.mainRoom ?? this.rooms[0];
|
||||
if (!room) return;
|
||||
const time = new Date().toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
await ctx.send(room, `✅ 签到机器人已启动(${time})。发送 !help 查看命令。`);
|
||||
this.logger.log(`已发送上线通知到 ${room}`);
|
||||
}
|
||||
|
||||
/** 中文「签到」无需前缀也可触发(对应 Rust support_chinese_command)。 */
|
||||
async onMessage(msg: InboundMessage, ctx: BotContext): Promise<void> {
|
||||
const text = msg.text.trim();
|
||||
if (text === '签到') {
|
||||
await this.handleCheckin(msg, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
async onCommand(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
switch (cmd.command) {
|
||||
case 'ping':
|
||||
await ctx.reply(cmd.raw, 'pong');
|
||||
break;
|
||||
case 'help':
|
||||
await ctx.reply(cmd.raw, this.helpText());
|
||||
break;
|
||||
case 'echo':
|
||||
await ctx.reply(cmd.raw, cmd.args.join(' ') || '(空)');
|
||||
break;
|
||||
case 'checkin':
|
||||
case '签到':
|
||||
await this.handleCheckin(cmd.raw, ctx);
|
||||
break;
|
||||
case 'list':
|
||||
await this.handleList(cmd, ctx);
|
||||
break;
|
||||
case 'reset':
|
||||
if (!(await this.requireAdmin(cmd, ctx))) break;
|
||||
await this.handleReset(cmd.raw, ctx);
|
||||
break;
|
||||
case 'test':
|
||||
if (!(await this.requireAdmin(cmd, ctx))) break;
|
||||
await this.handleTest(cmd, ctx);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
registerCrons(ctx: BotContext): CronSpec[] {
|
||||
return [
|
||||
{
|
||||
name: 'daily-report',
|
||||
cron: '0 0 3 * * *',
|
||||
run: () => this.dailyReport(ctx),
|
||||
},
|
||||
{
|
||||
name: 'monthly-report',
|
||||
cron: '0 5 0 1 * *',
|
||||
run: () => this.monthlyReport(ctx),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// ——— 命令处理 ———
|
||||
|
||||
private async handleCheckin(
|
||||
raw: InboundMessage,
|
||||
ctx: BotContext,
|
||||
): Promise<void> {
|
||||
const existing = await ctx.db.get<UserState>(raw.userId);
|
||||
if (existing?.isCheckinToday) {
|
||||
await ctx.reply(raw, '您今天已签到过了,请勿重复签到');
|
||||
return;
|
||||
}
|
||||
const state = applyCheckin(existing ?? newUserState());
|
||||
await ctx.db.set(raw.userId, state);
|
||||
await ctx.reply(
|
||||
raw,
|
||||
`${raw.userId} 签到成功 ✅ 本月第 ${state.checkinTimesInMonth} 次,当前等级 ${levelLabel(state.level)}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async handleList(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
const target = cmd.args[0];
|
||||
const raw = cmd.options.raw !== undefined;
|
||||
if (!target) {
|
||||
await ctx.reply(cmd.raw, '用法: !list <用户ID|all> [--raw]');
|
||||
return;
|
||||
}
|
||||
if (target === 'all') {
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
if (raw) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
entries.length ? JSON.stringify(entries, null, 2) : '暂无签到记录',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const text = entries.length
|
||||
? entries
|
||||
.map(
|
||||
([uid, s]) =>
|
||||
`${uid}: ${s.isCheckinToday ? '已签到' : '未签到'} 等级=${levelLabel(s.level)} 本月=${s.checkinTimesInMonth}次`,
|
||||
)
|
||||
.join('\n')
|
||||
: '暂无签到记录';
|
||||
await ctx.reply(cmd.raw, text);
|
||||
return;
|
||||
}
|
||||
const state = await ctx.db.get<UserState>(target);
|
||||
if (raw) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
state ? JSON.stringify(state, null, 2) : `${target} 尚未签到过`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
state
|
||||
? `${target}: ${state.isCheckinToday ? '已签到' : '未签到'} 等级=${levelLabel(state.level)} 本月=${state.checkinTimesInMonth}次`
|
||||
: `${target} 尚未签到过`,
|
||||
);
|
||||
}
|
||||
|
||||
private helpText(): string {
|
||||
return [
|
||||
'签到机器人命令列表:',
|
||||
'!checkin / 签到 — 今日签到',
|
||||
'!list <用户ID|all> [--raw] — 查询签到状态',
|
||||
'!reset — 重置所有人当日签到(管理员)',
|
||||
'!test daily|monthly — 手动触发日报/月报(管理员)',
|
||||
'!echo <文本> / !ping / !help',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** 手动触发定时任务,便于运维测试(对应 Rust `!test daily_report`)。 */
|
||||
private async handleTest(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
const project = cmd.args[0];
|
||||
if (!project) {
|
||||
await ctx.reply(cmd.raw, '用法: !test <daily|monthly>');
|
||||
return;
|
||||
}
|
||||
switch (project) {
|
||||
case 'daily':
|
||||
case 'daily_report':
|
||||
await ctx.reply(cmd.raw, '开始执行日报测试…');
|
||||
await this.dailyReport(ctx);
|
||||
await ctx.reply(cmd.raw, '日报测试完成 ✅');
|
||||
break;
|
||||
case 'monthly':
|
||||
case 'monthly_report':
|
||||
await ctx.reply(cmd.raw, '开始执行月报测试…');
|
||||
await this.monthlyReport(ctx);
|
||||
await ctx.reply(cmd.raw, '月报测试完成 ✅');
|
||||
break;
|
||||
default:
|
||||
await ctx.reply(cmd.raw, `未知测试项目: ${project}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleReset(
|
||||
raw: InboundMessage,
|
||||
ctx: BotContext,
|
||||
): Promise<void> {
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
for (const [uid, s] of entries) {
|
||||
if (s.isCheckinToday) {
|
||||
await ctx.db.set(uid, resetDaily(s));
|
||||
}
|
||||
}
|
||||
await ctx.reply(raw, '已重置所有用户的当日签到状态');
|
||||
}
|
||||
|
||||
// ——— 定时任务 ———
|
||||
|
||||
private async dailyReport(ctx: BotContext): Promise<void> {
|
||||
const room = this.cfg.mainRoom ?? this.rooms[0];
|
||||
if (!room) return;
|
||||
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
const states = new Map(entries);
|
||||
// 已签到人数(对应 Rust 的 checked_nums)。
|
||||
const checkedNums = entries.filter(
|
||||
([, s]) => s.isCheckinToday,
|
||||
).length;
|
||||
|
||||
const members = await ctx.getJoinedMembers(room);
|
||||
const allUserNums =
|
||||
members.length > 0 ? members.length : await ctx.getMemberCount(room);
|
||||
const rows = analyzeUnchecked(members, states);
|
||||
|
||||
const date = new Date().toLocaleDateString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
const text = buildDailyReport({ date, checkedNums, allUserNums, rows });
|
||||
await ctx.send(room, text);
|
||||
|
||||
if (this.cfg.autoKick) {
|
||||
let targets = computeKickTargets(
|
||||
rows,
|
||||
this.cfg.kickDays,
|
||||
this.cfg.whitelist,
|
||||
);
|
||||
|
||||
// 原生权限豁免:如果用户的 Power Level 达到管理员级别,自动免死
|
||||
const finalTargets: string[] = [];
|
||||
for (const userId of targets) {
|
||||
try {
|
||||
const power = await ctx.getPowerLevel(room, userId);
|
||||
if (power >= this.cfg.adminPowerLevel) {
|
||||
this.logger.log(`用户 ${userId} 未签到超期,但权限分(${power})足够,豁免踢出`);
|
||||
continue;
|
||||
}
|
||||
finalTargets.push(userId);
|
||||
} catch (err) {
|
||||
this.logger.error(`获取用户 ${userId} 权限分失败,加入踢出名单`, err);
|
||||
finalTargets.push(userId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const userId of finalTargets) {
|
||||
await ctx.kick(room, userId, `超过 ${this.cfg.kickDays} 天未签到`);
|
||||
this.logger.log(`已踢出 ${userId}`);
|
||||
}
|
||||
if (finalTargets.length > 0) {
|
||||
await ctx.send(room, `已踢出 ${finalTargets.length} 名长期未签到用户`);
|
||||
}
|
||||
}
|
||||
|
||||
// 重置当日签到标记。
|
||||
for (const [uid, s] of entries) {
|
||||
if (s.isCheckinToday) {
|
||||
await ctx.db.set(uid, resetDaily(s));
|
||||
}
|
||||
}
|
||||
this.logger.log(`日报完成: checked=${checkedNums} total=${allUserNums}`);
|
||||
}
|
||||
|
||||
private async monthlyReport(ctx: BotContext): Promise<void> {
|
||||
const room = this.cfg.mainRoom ?? this.rooms[0];
|
||||
if (!room) return;
|
||||
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
const ranked = entries
|
||||
.sort((a, b) => b[1].checkinTimesInMonth - a[1].checkinTimesInMonth);
|
||||
|
||||
const date = new Date().toLocaleDateString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
const lines = ranked.map(
|
||||
([uid, s], i) => `${i + 1}. ${uid} — ${s.checkinTimesInMonth} 次 (${levelLabel(s.level)})`,
|
||||
);
|
||||
const text = `# ${date} 月度签到统计\n${lines.join('\n') || '暂无数据'}`;
|
||||
await ctx.send(room, text);
|
||||
|
||||
// 重置月度计数。
|
||||
for (const [uid, s] of entries) {
|
||||
await ctx.db.set(uid, resetMonthly(s));
|
||||
}
|
||||
this.logger.log(`月报完成: users=${entries.length}`);
|
||||
}
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, unlinkSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { PrismaService } from '../../core/db/prisma.service';
|
||||
import { BotStore } from '../../core/db/bot-store';
|
||||
import { BotContext } from '../../core/bot/room-bot.interface';
|
||||
import { InboundMessage, ParsedCommand } from '../../core/command/types';
|
||||
import { parseCommand } from '../../core/command/command-parser';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
import { UserState } from './user-state';
|
||||
|
||||
const PROJECT_ROOT = resolve(__dirname, '../../..');
|
||||
const TEST_DB_FILE = resolve(PROJECT_ROOT, 'test-checkin-integration.db');
|
||||
const TEST_DB_URL = `file:${TEST_DB_FILE}`;
|
||||
|
||||
function cleanDb(): void {
|
||||
for (const suffix of ['', '-journal', '-wal', '-shm']) {
|
||||
const f = TEST_DB_FILE + suffix;
|
||||
if (existsSync(f)) unlinkSync(f);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- test doubles ----------
|
||||
|
||||
/** BotContext backed by a real BotStore (wraps real Prisma). */
|
||||
class RealStoreContext implements BotContext {
|
||||
readonly account = 'checkin';
|
||||
readonly sent: string[] = [];
|
||||
readonly kicked: Array<{ roomId: string; userId: string; reason?: string }> =
|
||||
[];
|
||||
readonly invited: Array<{ roomId: string; userId: string }> = [];
|
||||
members: string[] = [];
|
||||
powerLevels: Record<string, number> = {};
|
||||
|
||||
constructor(public readonly db: BotStore) {}
|
||||
|
||||
async invite(roomId: string, userId: string): Promise<void> {
|
||||
this.invited.push({ roomId, userId });
|
||||
}
|
||||
|
||||
async send(_roomId: string, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async reply(_msg: InboundMessage, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
this.kicked.push({ roomId, userId, reason });
|
||||
}
|
||||
async getMemberCount(): Promise<number> {
|
||||
return this.members.length || 10;
|
||||
}
|
||||
async getJoinedMembers(): Promise<string[]> {
|
||||
return this.members;
|
||||
}
|
||||
async getPowerLevel(_roomId: string, userId: string): Promise<number> {
|
||||
return this.powerLevels[userId] ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
let prismaService: PrismaService;
|
||||
|
||||
function makeBot(): CheckinBot {
|
||||
const fakeConfig = {
|
||||
bots: [
|
||||
{
|
||||
name: 'checkin',
|
||||
account: 'checkin',
|
||||
rooms: ['!room:hs'],
|
||||
config: { mainRoom: '!room:hs', admins: ['@admin:hs'] },
|
||||
},
|
||||
],
|
||||
} as never;
|
||||
return new CheckinBot(fakeConfig);
|
||||
}
|
||||
|
||||
function makeCtx(): RealStoreContext {
|
||||
return new RealStoreContext(new BotStore(prismaService, 'checkin'));
|
||||
}
|
||||
|
||||
function msg(text: string, userId = '@alice:hs'): InboundMessage {
|
||||
return {
|
||||
eventId: 'e1',
|
||||
account: 'checkin',
|
||||
roomId: '!room:hs',
|
||||
userId,
|
||||
text,
|
||||
timestampMs: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
function cmd(text: string, userId = '@alice:hs'): ParsedCommand {
|
||||
return parseCommand(msg(text, userId), text);
|
||||
}
|
||||
|
||||
// ---------- lifecycle ----------
|
||||
|
||||
beforeAll(async () => {
|
||||
cleanDb();
|
||||
execSync('npx prisma db push --skip-generate', {
|
||||
cwd: PROJECT_ROOT,
|
||||
env: { ...process.env, DATABASE_URL: TEST_DB_URL },
|
||||
stdio: 'pipe',
|
||||
});
|
||||
process.env.DATABASE_URL = TEST_DB_URL;
|
||||
prismaService = new PrismaService();
|
||||
await prismaService.onModuleInit();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prismaService.onModuleDestroy();
|
||||
cleanDb();
|
||||
delete process.env.DATABASE_URL;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await prismaService.botState.deleteMany();
|
||||
});
|
||||
|
||||
// ---------- tests ----------
|
||||
|
||||
describe('CheckinBot + real BotStore (integration)', () => {
|
||||
describe('checkin command persists state to SQLite', () => {
|
||||
it('writes isCheckinToday=true and increments monthly count', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state).not.toBeNull();
|
||||
expect(state!.isCheckinToday).toBe(true);
|
||||
expect(state!.checkinTimesInMonth).toBe(1);
|
||||
expect(ctx.sent[0]).toContain('签到成功');
|
||||
});
|
||||
|
||||
it('prevents duplicate checkin and persists only one record', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin'), ctx);
|
||||
await bot.onCommand(cmd('checkin'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.checkinTimesInMonth).toBe(1); // not incremented twice
|
||||
expect(ctx.sent[1]).toContain('已签到过');
|
||||
});
|
||||
|
||||
it('state is readable across multiple BotStore instances (same DB)', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx1 = makeCtx();
|
||||
await bot.onCommand(cmd('checkin'), ctx1);
|
||||
|
||||
// Simulate reading from a fresh context (same prismaService → same DB).
|
||||
const ctx2 = makeCtx();
|
||||
const state = await ctx2.db.get<UserState>('@alice:hs');
|
||||
expect(state!.isCheckinToday).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('!reset clears isCheckinToday in the database', () => {
|
||||
it('resets all checked-in users', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
await bot.onCommand(cmd('checkin', '@bob:hs'), ctx);
|
||||
|
||||
ctx.sent.length = 0;
|
||||
await bot.onCommand(cmd('reset', '@admin:hs'), ctx);
|
||||
|
||||
const alice = await ctx.db.get<UserState>('@alice:hs');
|
||||
const bob = await ctx.db.get<UserState>('@bob:hs');
|
||||
expect(alice!.isCheckinToday).toBe(false);
|
||||
expect(bob!.isCheckinToday).toBe(false);
|
||||
expect(ctx.sent[0]).toContain('已重置');
|
||||
});
|
||||
|
||||
it('reset is admin-only — non-admin gets rejected and DB is unchanged', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('reset', '@alice:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.isCheckinToday).toBe(true); // unchanged
|
||||
});
|
||||
});
|
||||
|
||||
describe('!level commands persist level changes to SQLite', () => {
|
||||
it('!level set persists the new level', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('level set @bob:hs 黄金', '@admin:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@bob:hs');
|
||||
expect(state!.level).toBe('Gold');
|
||||
});
|
||||
|
||||
it('!level raise increments the stored level', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
// After one checkin, applyCheckin sets level to Bronze (t=1, t<=7).
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('level raise @alice:hs', '@admin:hs'), ctx);
|
||||
|
||||
// Bronze -> Silver is the expected raise.
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Silver');
|
||||
});
|
||||
|
||||
it('!level super grants Super level', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@admin:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Super');
|
||||
});
|
||||
|
||||
it('!level clear resets level to Bronze', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@admin:hs'), ctx);
|
||||
await bot.onCommand(cmd('level clear @alice:hs', '@admin:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Bronze');
|
||||
});
|
||||
});
|
||||
|
||||
describe('!list reads from real DB', () => {
|
||||
it('lists all users stored in DB', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
await bot.onCommand(cmd('checkin', '@bob:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('list all'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('@alice:hs');
|
||||
expect(ctx.sent[0]).toContain('@bob:hs');
|
||||
});
|
||||
|
||||
it('lists a specific user', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('list @alice:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('@alice:hs');
|
||||
expect(ctx.sent[0]).toContain('已签到');
|
||||
});
|
||||
|
||||
it('returns "尚未签到" for a user not in DB', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('list @nobody:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('尚未签到');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Chinese text trigger onMessage()', () => {
|
||||
it('signs in when message text is exactly "签到"', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onMessage(msg('签到', '@alice:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.isCheckinToday).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores other Chinese messages', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onMessage(msg('你好', '@alice:hs'), ctx);
|
||||
|
||||
expect(ctx.sent).toHaveLength(0);
|
||||
expect(await ctx.db.get('@alice:hs')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin authorization via power level reads correct value', () => {
|
||||
it('allows power-level-100 user to use admin commands', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
ctx.powerLevels['@mod:hs'] = 100;
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@mod:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Super');
|
||||
});
|
||||
|
||||
it('denies power-level-50 user from admin commands', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
ctx.powerLevels['@halfmod:hs'] = 50;
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@halfmod:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
expect(await ctx.db.get('@alice:hs')).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
|
||||
/**
|
||||
* 签到 bot 模块。新增 bot 时照此模式新建一个目录与模块,
|
||||
* 在 AppModule 里 import 即可,核心代码无需改动。
|
||||
*/
|
||||
@Module({
|
||||
providers: [CheckinBot],
|
||||
})
|
||||
export class CheckinModule {}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { BotContext } from '../../core/bot/room-bot.interface';
|
||||
import { InboundMessage } from '../../core/command/types';
|
||||
import { parseCommand } from '../../core/command/command-parser';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
import { UserState } from './user-state';
|
||||
|
||||
/** 内存版 BotContext,用于纯逻辑单测,无需连接 Matrix。 */
|
||||
class FakeContext implements BotContext {
|
||||
readonly account = 'checkin';
|
||||
readonly sent: string[] = [];
|
||||
private readonly store = new Map<string, unknown>();
|
||||
|
||||
readonly db = {
|
||||
get: async <T>(key: string) => (this.store.get(key) ?? null) as T | null,
|
||||
set: async <T>(key: string, value: T) => {
|
||||
this.store.set(key, value);
|
||||
},
|
||||
remove: async (key: string) => {
|
||||
this.store.delete(key);
|
||||
},
|
||||
entries: async <T>() =>
|
||||
[...this.store.entries()] as Array<[string, T]>,
|
||||
} as unknown as BotContext['db'];
|
||||
|
||||
async send(_roomId: string, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async reply(_msg: InboundMessage, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async kick(): Promise<void> {}
|
||||
async invite(): Promise<void> {}
|
||||
async getMemberCount(): Promise<number> {
|
||||
return 10;
|
||||
}
|
||||
members: string[] = [];
|
||||
async getJoinedMembers(): Promise<string[]> {
|
||||
return this.members;
|
||||
}
|
||||
powerLevels: Record<string, number> = {};
|
||||
async getPowerLevel(_roomId: string, userId: string): Promise<number> {
|
||||
return this.powerLevels[userId] ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
function buildBot(): CheckinBot {
|
||||
const fakeConfig = {
|
||||
bots: [
|
||||
{
|
||||
name: 'checkin',
|
||||
account: 'checkin',
|
||||
rooms: ['!room:hs'],
|
||||
config: { mainRoom: '!room:hs', admins: ['@admin:hs'] },
|
||||
},
|
||||
],
|
||||
} as never;
|
||||
return new CheckinBot(fakeConfig);
|
||||
}
|
||||
|
||||
function msg(text: string, userId = '@alice:hs'): InboundMessage {
|
||||
return {
|
||||
eventId: 'e1',
|
||||
account: 'checkin',
|
||||
roomId: '!room:hs',
|
||||
userId,
|
||||
text,
|
||||
timestampMs: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('CheckinBot', () => {
|
||||
it('binds account and rooms from config', () => {
|
||||
const bot = buildBot();
|
||||
expect(bot.name).toBe('checkin');
|
||||
expect(bot.account).toBe('checkin');
|
||||
expect(bot.rooms).toEqual(['!room:hs']);
|
||||
});
|
||||
|
||||
it('records a check-in and prevents duplicates', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state?.isCheckinToday).toBe(true);
|
||||
expect(state?.checkinTimesInMonth).toBe(1);
|
||||
expect(ctx.sent[0]).toContain('签到成功');
|
||||
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
expect(ctx.sent[1]).toContain('已签到过');
|
||||
});
|
||||
|
||||
it('lists all users', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(parseCommand(msg('list all'), 'list all'), ctx);
|
||||
expect(ctx.sent[0]).toContain('@alice:hs');
|
||||
});
|
||||
|
||||
it('registers daily and monthly crons', () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
const crons = bot.registerCrons(ctx);
|
||||
expect(crons).toHaveLength(2);
|
||||
expect(crons[0].cron).toBe('0 0 3 * * *');
|
||||
expect(crons[1].cron).toBe('0 5 0 1 * *');
|
||||
});
|
||||
|
||||
it('denies privileged commands from non-admins', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// reset 受限。
|
||||
await bot.onCommand(parseCommand(msg('reset', '@alice:hs'), 'reset'), ctx);
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
});
|
||||
|
||||
it('allows privileged commands from room admins via power level', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// @mod 不在 config.admins,但房间 power level=100,应视为管理员。
|
||||
ctx.powerLevels['@mod:hs'] = 100;
|
||||
await bot.onCommand(parseCommand(msg('reset', '@mod:hs'), 'reset'), ctx);
|
||||
expect(ctx.sent[0]).toContain('重置');
|
||||
});
|
||||
|
||||
it('denies privileged commands when power level below threshold', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// @mod power level=50(版主),低于阈值 100,应被拒绝。
|
||||
ctx.powerLevels['@mod:hs'] = 50;
|
||||
await bot.onCommand(parseCommand(msg('reset', '@mod:hs'), 'reset'), ctx);
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
});
|
||||
|
||||
it('shows Chinese level on check-in', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
expect(ctx.sent[0]).toContain('青铜');
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import {
|
||||
analyzeUnchecked,
|
||||
buildDailyReport,
|
||||
computeKickTargets,
|
||||
} from './report';
|
||||
import { newUserState, UserState } from './user-state';
|
||||
|
||||
function state(partial: Partial<UserState>): UserState {
|
||||
return { ...newUserState(), ...partial };
|
||||
}
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const NOW = 1_000 * DAY; // 固定 now,便于天数计算
|
||||
|
||||
describe('report', () => {
|
||||
it('analyzes unchecked members, skipping checked-in', () => {
|
||||
const states = new Map<string, UserState>([
|
||||
['@a:hs', state({ isCheckinToday: true, checkinUnixMs: NOW })],
|
||||
['@b:hs', state({ checkinUnixMs: NOW - 10 * DAY })],
|
||||
]);
|
||||
// @c:hs 不在 DB ⇒ 从未签到
|
||||
const rows = analyzeUnchecked(
|
||||
['@a:hs', '@b:hs', '@c:hs'],
|
||||
states,
|
||||
NOW,
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ userId: '@b:hs', days: 10 },
|
||||
{ userId: '@c:hs', days: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('builds a markdown report with buckets', () => {
|
||||
const rows = [
|
||||
{ userId: '@b:hs', days: 10 },
|
||||
{ userId: '@d:hs', days: 31 },
|
||||
{ userId: '@c:hs', days: null },
|
||||
];
|
||||
const text = buildDailyReport({
|
||||
date: '2026/6/3',
|
||||
checkedNums: 5,
|
||||
allUserNums: 8,
|
||||
rows,
|
||||
});
|
||||
expect(text).toContain('签到率:63%');
|
||||
expect(text).toContain('未签到人数:3');
|
||||
expect(text).toContain('## 超过7天未签到用户\n@b:hs ,\n@d:hs');
|
||||
expect(text).toContain('## 超过30天未签到用户\n@d:hs');
|
||||
expect(text).toContain('## 从未签到用户\n@c:hs');
|
||||
});
|
||||
|
||||
it('computes kick targets respecting whitelist and never-checked', () => {
|
||||
const rows = [
|
||||
{ userId: '@b:hs', days: 10 },
|
||||
{ userId: '@d:hs', days: 31 },
|
||||
{ userId: '@e:hs', days: 40 },
|
||||
{ userId: '@c:hs', days: null },
|
||||
];
|
||||
const targets = computeKickTargets(rows, 30, ['@e:hs']);
|
||||
expect(targets).toEqual(['@d:hs']); // e 在白名单, c 从未签到不踢, b 未达阈值
|
||||
});
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
import { isSuper, uncheckedDays, UserState } from './user-state';
|
||||
|
||||
export interface UncheckedRow {
|
||||
userId: string;
|
||||
/** null = 从未签到。 */
|
||||
days: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析主房间成员的未签到情况:
|
||||
* - 已今日签到的跳过
|
||||
* - Super 用户跳过(对应 Rust super_filter)
|
||||
* - 不在 DB 里的成员记为「从未签到」(days=null)
|
||||
*/
|
||||
export function analyzeUnchecked(
|
||||
memberIds: string[],
|
||||
states: Map<string, UserState>,
|
||||
now = Date.now(),
|
||||
): UncheckedRow[] {
|
||||
const rows: UncheckedRow[] = [];
|
||||
for (const userId of memberIds) {
|
||||
const state = states.get(userId);
|
||||
if (!state) {
|
||||
rows.push({ userId, days: null });
|
||||
continue;
|
||||
}
|
||||
if (state.isCheckinToday) continue;
|
||||
if (isSuper(state)) continue;
|
||||
rows.push({ userId, days: uncheckedDays(state, now) });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function bucket(rows: UncheckedRow[], minDays: number): string[] {
|
||||
return rows
|
||||
.filter((r) => r.days !== null && r.days >= minDays)
|
||||
.map((r) => r.userId);
|
||||
}
|
||||
|
||||
/** 生成 Markdown 日报(移植自 Rust daily_statistics_and_report)。 */
|
||||
export function buildDailyReport(params: {
|
||||
date: string;
|
||||
checkedNums: number;
|
||||
allUserNums: number;
|
||||
rows: UncheckedRow[];
|
||||
}): string {
|
||||
const { date, checkedNums, allUserNums, rows } = params;
|
||||
const uncheckedNums = Math.max(allUserNums - checkedNums, 0);
|
||||
const checkinRate =
|
||||
allUserNums > 0 ? Math.round((checkedNums / allUserNums) * 100) : 0;
|
||||
|
||||
const today = rows.map((r) => r.userId).join(' ,\n');
|
||||
const join = (ids: string[]) => ids.join(' ,\n');
|
||||
|
||||
return `# ${date}签到统计报告
|
||||
- 今日签到人数:${checkedNums}
|
||||
- 全部人数:${allUserNums}
|
||||
- 未签到人数:${uncheckedNums}
|
||||
- 签到率:${checkinRate}%
|
||||
|
||||
## 今日未签到用户
|
||||
${today}
|
||||
|
||||
## 超过7天未签到用户
|
||||
${join(bucket(rows, 7))}
|
||||
|
||||
## 超过14天未签到用户
|
||||
${join(bucket(rows, 14))}
|
||||
|
||||
## 超过30天未签到用户
|
||||
${join(bucket(rows, 30))}
|
||||
|
||||
## 从未签到用户
|
||||
${join(rows.filter((r) => r.days === null).map((r) => r.userId))}
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算应被踢出的用户:未签到天数 >= kickDays,且不在白名单。
|
||||
* 「从未签到」(days=null)不计入(无法判断时长,保守不踢)。
|
||||
*/
|
||||
export function computeKickTargets(
|
||||
rows: UncheckedRow[],
|
||||
kickDays: number,
|
||||
whitelist: string[] = [],
|
||||
): string[] {
|
||||
const wl = new Set(whitelist);
|
||||
return rows
|
||||
.filter((r) => r.days !== null && r.days >= kickDays)
|
||||
.map((r) => r.userId)
|
||||
.filter((id) => !wl.has(id));
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
export type UserLevel =
|
||||
| 'Bronze'
|
||||
| 'Silver'
|
||||
| 'Gold'
|
||||
| 'Platinum'
|
||||
| 'Diamond';
|
||||
|
||||
/** 签到等级升序(已移除手工赋予的 Super)。 */
|
||||
export const LEVELS_ASC: UserLevel[] = [
|
||||
'Bronze',
|
||||
'Silver',
|
||||
'Gold',
|
||||
'Platinum',
|
||||
'Diamond',
|
||||
];
|
||||
|
||||
export const VALID_LEVELS: UserLevel[] = [...LEVELS_ASC];
|
||||
|
||||
/** 等级的中文显示名(内部仍用英文 key,只在展示层转中文)。 */
|
||||
export const LEVEL_LABELS: Record<UserLevel, string> = {
|
||||
Bronze: '青铜',
|
||||
Silver: '白银',
|
||||
Gold: '黄金',
|
||||
Platinum: '铂金',
|
||||
Diamond: '钻石',
|
||||
};
|
||||
|
||||
/** 中文 → 英文 key 的反查表,供命令输入解析。 */
|
||||
const LABEL_TO_LEVEL: Record<string, UserLevel> = Object.fromEntries(
|
||||
Object.entries(LEVEL_LABELS).map(([k, v]) => [v, k as UserLevel]),
|
||||
) as Record<string, UserLevel>;
|
||||
|
||||
/** 等级的中文显示名。 */
|
||||
export function levelLabel(level: UserLevel): string {
|
||||
return LEVEL_LABELS[level];
|
||||
}
|
||||
|
||||
/** 可选等级的中文列表,用于帮助文案。 */
|
||||
export function levelChoices(): string {
|
||||
return VALID_LEVELS.map((l) => LEVEL_LABELS[l]).join('/');
|
||||
}
|
||||
|
||||
/** 解析等级,兼容中文(青铜)与英文(bronze/Bronze)。 */
|
||||
export function parseLevel(s: string): UserLevel | null {
|
||||
const trimmed = s.trim();
|
||||
if (LABEL_TO_LEVEL[trimmed]) return LABEL_TO_LEVEL[trimmed];
|
||||
const normalized = trimmed.charAt(0).toUpperCase() + trimmed.slice(1).toLowerCase();
|
||||
return VALID_LEVELS.includes(normalized as UserLevel)
|
||||
? (normalized as UserLevel)
|
||||
: null;
|
||||
}
|
||||
|
||||
export interface UserState {
|
||||
isCheckinToday: boolean;
|
||||
level: UserLevel;
|
||||
checkinUnixMs: number;
|
||||
checkinTimesInMonth: number;
|
||||
checkinDays: number[];
|
||||
}
|
||||
|
||||
export function newUserState(): UserState {
|
||||
return {
|
||||
isCheckinToday: false,
|
||||
level: 'Silver',
|
||||
checkinUnixMs: 0,
|
||||
checkinTimesInMonth: 0,
|
||||
checkinDays: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function isSuper(state: UserState): boolean {
|
||||
return false; // 已废弃,通过原生权限判断
|
||||
}
|
||||
|
||||
/** 执行一次签到,更新状态与等级(移植自 Rust UserState::checkin)。 */
|
||||
export function applyCheckin(state: UserState, now = new Date()): UserState {
|
||||
const next: UserState = { ...state, checkinDays: [...state.checkinDays] };
|
||||
next.isCheckinToday = true;
|
||||
next.checkinUnixMs = now.getTime();
|
||||
next.checkinTimesInMonth += 1;
|
||||
const day = now.getUTCDate();
|
||||
if (!next.checkinDays.includes(day)) {
|
||||
next.checkinDays.push(day);
|
||||
}
|
||||
const t = next.checkinTimesInMonth;
|
||||
if (t <= 7) next.level = 'Bronze';
|
||||
else if (t <= 14) next.level = 'Silver';
|
||||
else if (t <= 29) next.level = 'Gold';
|
||||
else if (t <= 44) next.level = 'Platinum';
|
||||
else next.level = 'Diamond';
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 重置当日签到标记。 */
|
||||
export function resetDaily(state: UserState): UserState {
|
||||
return { ...state, isCheckinToday: false };
|
||||
}
|
||||
|
||||
/** 重置月度统计(每月初调用)。 */
|
||||
export function resetMonthly(state: UserState): UserState {
|
||||
return { ...state, checkinTimesInMonth: 0, checkinDays: [] };
|
||||
}
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
/**
|
||||
* 距上次签到的整天数。从未签到(checkinUnixMs=0)返回 null。
|
||||
* 注:Rust 原版此计算有 bug,这里实现的是其本意(now - lastCheckin)。
|
||||
*/
|
||||
export function uncheckedDays(
|
||||
state: UserState,
|
||||
now = Date.now(),
|
||||
): number | null {
|
||||
if (!state.checkinUnixMs) return null;
|
||||
return Math.floor((now - state.checkinUnixMs) / MS_PER_DAY);
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { RegisterBot } from '../../core/bot/register-bot.decorator';
|
||||
import { BotContext, RoomBot } from '../../core/bot/room-bot.interface';
|
||||
import { MemberEvent, PowerLevelEvent } from '../../core/command/types';
|
||||
|
||||
interface RoomManagerConfig {
|
||||
workRoom1: string;
|
||||
workRoom2: string;
|
||||
lostRoom: string;
|
||||
levelA: number;
|
||||
levelB: number;
|
||||
levelC: number;
|
||||
}
|
||||
|
||||
@RegisterBot()
|
||||
@Injectable()
|
||||
export class RoomManagerBot implements RoomBot {
|
||||
readonly name = 'room-manager';
|
||||
readonly account: string;
|
||||
readonly rooms: string[];
|
||||
private readonly logger = new Logger('RoomManagerBot');
|
||||
private readonly cfg: RoomManagerConfig;
|
||||
|
||||
// 用一个简单的内存锁防止重复执行(权限变更会发全量 users,只抓取差异比较好,
|
||||
// 为了简便,这里每次直接同步成员权限状态)
|
||||
constructor(config: ConfigService) {
|
||||
const entry = config.bots.find((b) => b.name === this.name);
|
||||
if (!entry) {
|
||||
throw new Error(`config 中缺少 name=${this.name} 的 bot 配置`);
|
||||
}
|
||||
this.account = entry.account;
|
||||
this.rooms = entry.rooms;
|
||||
const c = entry.config || {};
|
||||
this.cfg = {
|
||||
workRoom1: c.workRoom1 as string,
|
||||
workRoom2: c.workRoom2 as string,
|
||||
lostRoom: c.lostRoom as string,
|
||||
levelA: (c.levelA as number) ?? 50,
|
||||
levelB: (c.levelB as number) ?? 0,
|
||||
levelC: (c.levelC as number) ?? -1,
|
||||
};
|
||||
}
|
||||
|
||||
async onReady(ctx: BotContext): Promise<void> {
|
||||
const mainRoom = this.rooms[0];
|
||||
if (!mainRoom) return;
|
||||
const time = new Date().toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
await ctx.send(mainRoom, `✅ 权限同步保安已上线(${time})。正在监听本房间原生权限变更...`);
|
||||
this.logger.log(`已发送权限管理上线通知到 ${mainRoom}`);
|
||||
}
|
||||
|
||||
async onPowerLevel(ev: PowerLevelEvent, ctx: BotContext): Promise<void> {
|
||||
const { workRoom1, workRoom2, lostRoom, levelA, levelB, levelC } = this.cfg;
|
||||
if (!workRoom1 || !workRoom2 || !lostRoom) {
|
||||
this.logger.warn('未配置完整的目标房间(workRoom1, workRoom2, lostRoom),跳过权限同步');
|
||||
return;
|
||||
}
|
||||
|
||||
const { users, prevUsers, defaultPower } = ev;
|
||||
const changedUsers = new Set<string>();
|
||||
|
||||
// 收集所有在新列表或旧列表中出现过的用户
|
||||
for (const userId of Object.keys(users)) changedUsers.add(userId);
|
||||
for (const userId of Object.keys(prevUsers)) changedUsers.add(userId);
|
||||
|
||||
for (const userId of changedUsers) {
|
||||
try {
|
||||
const oldPower = prevUsers[userId] ?? defaultPower;
|
||||
const newPower = users[userId] ?? defaultPower;
|
||||
|
||||
// 如果该用户的分数根本没变,跳过
|
||||
if (oldPower === newPower) continue;
|
||||
|
||||
let targetState = '';
|
||||
const actions: Array<{ action: 'kick' | 'invite'; roomName: string; roomId: string; reason?: string }> = [];
|
||||
|
||||
if (newPower >= levelA) {
|
||||
targetState = `A级(高级) [${newPower}分]`;
|
||||
actions.push({ action: 'invite', roomName: '工作房1', roomId: workRoom1 });
|
||||
actions.push({ action: 'invite', roomName: '工作房2', roomId: workRoom2 });
|
||||
actions.push({ action: 'kick', roomName: '失联房', roomId: lostRoom, reason: '恢复工作权限' });
|
||||
} else if (newPower >= levelB) {
|
||||
targetState = `B级(普通) [${newPower}分]`;
|
||||
actions.push({ action: 'kick', roomName: '工作房1', roomId: workRoom1, reason: '权限不足' });
|
||||
actions.push({ action: 'invite', roomName: '工作房2', roomId: workRoom2 });
|
||||
actions.push({ action: 'kick', roomName: '失联房', roomId: lostRoom, reason: '恢复工作权限' });
|
||||
} else if (newPower > levelC) {
|
||||
// 在 levelC 和 levelB 之间的分数(比如 -1 到 0 之间的分数),除了踢出失联房,什么都不做
|
||||
targetState = `中间状态 [${newPower}分]`;
|
||||
actions.push({ action: 'kick', roomName: '失联房', roomId: lostRoom, reason: '脱离受限状态' });
|
||||
} else {
|
||||
// newPower <= levelC
|
||||
targetState = `C级(失联) [${newPower}分]`;
|
||||
actions.push({ action: 'kick', roomName: '工作房1', roomId: workRoom1, reason: '打入冷宫' });
|
||||
actions.push({ action: 'kick', roomName: '工作房2', roomId: workRoom2, reason: '打入冷宫' });
|
||||
actions.push({ action: 'invite', roomName: '失联房', roomId: lostRoom });
|
||||
}
|
||||
|
||||
await this.executeActions(ctx, ev.roomId, userId, targetState, actions, '👮 权限同步');
|
||||
} catch (err) {
|
||||
this.logger.error(`处理用户 ${userId} 权限异常: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onMemberLeave(ev: MemberEvent, ctx: BotContext): Promise<void> {
|
||||
const { workRoom1, workRoom2, lostRoom } = this.cfg;
|
||||
if (!workRoom1 || !workRoom2 || !lostRoom) return;
|
||||
|
||||
const actions: Array<{ action: 'kick' | 'invite'; roomName: string; roomId: string; reason?: string }> = [
|
||||
{ action: 'kick', roomName: '工作房1', roomId: workRoom1, reason: '离开大本营' },
|
||||
{ action: 'kick', roomName: '工作房2', roomId: workRoom2, reason: '离开大本营' },
|
||||
{ action: 'invite', roomName: '失联房', roomId: lostRoom },
|
||||
];
|
||||
|
||||
await this.executeActions(ctx, ev.roomId, ev.userId, '离群(失联)', actions, '🚪 离群联动');
|
||||
}
|
||||
|
||||
private async executeActions(
|
||||
ctx: BotContext,
|
||||
controlRoomId: string,
|
||||
userId: string,
|
||||
targetState: string,
|
||||
actions: Array<{ action: 'kick' | 'invite'; roomName: string; roomId: string; reason?: string }>,
|
||||
title: string,
|
||||
): Promise<void> {
|
||||
const logs: string[] = [];
|
||||
let hasActualChanges = false;
|
||||
|
||||
for (const req of actions) {
|
||||
try {
|
||||
if (req.action === 'kick') {
|
||||
await ctx.kick(req.roomId, userId, req.reason);
|
||||
logs.push(`${req.roomName}: 移出成功`);
|
||||
hasActualChanges = true;
|
||||
} else {
|
||||
await ctx.invite(req.roomId, userId);
|
||||
logs.push(`${req.roomName}: 拉入成功`);
|
||||
hasActualChanges = true;
|
||||
}
|
||||
} catch (err: any) {
|
||||
const msg = err.message || '';
|
||||
if (req.action === 'kick' && msg.includes('not in the room')) {
|
||||
// 本来就不在,无需处理,不产生噪音
|
||||
} else if (req.action === 'invite' && msg.includes('already in the room')) {
|
||||
// 本来就在,无需处理,不产生噪音
|
||||
} else {
|
||||
// 真正的意外失败
|
||||
logs.push(`${req.roomName}: ${req.action === 'kick' ? '移出' : '拉入'}失败 (${msg})`);
|
||||
hasActualChanges = true; // 把失败当作一种状态变化汇报给群里
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 只有在真正踢了人、拉了人,或者遇到意外报错时,才在群里打字播报
|
||||
if (hasActualChanges && logs.length > 0) {
|
||||
const msg = `${title}: 将 ${userId} 设为 ${targetState}\n` + logs.map(l => `- ${l}`).join('\n');
|
||||
await ctx.send(controlRoomId, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RoomManagerBot } from './room-manager.bot';
|
||||
|
||||
@Module({
|
||||
providers: [RoomManagerBot],
|
||||
})
|
||||
export class RoomManagerModule {}
|
||||
@@ -40,7 +40,7 @@ export class ConfigService {
|
||||
const resolved = this.resolveEnvRefs(parsed);
|
||||
this.config = rootConfigSchema.parse(resolved);
|
||||
this.logger.log(
|
||||
`已加载配置: ${Object.keys(this.config.accounts).length} 个账号, ${this.config.bots.length} 个 bot`,
|
||||
`已加载配置: ${Object.keys(this.config.accounts).length} 个账号, ${this.config.rooms.length} 个管理房间`,
|
||||
);
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { rootConfigSchema } from './schema';
|
||||
const accounts = { test: { userId: '@bot:example.org', password: 'fixture', homeServer: 'https://example.org' } };
|
||||
const room = { account: 'test', roomId: '!room:example.org' };
|
||||
describe('room configuration', () => {
|
||||
it('supports empty plugin sets, explicit timezone and language', () => {
|
||||
const config = rootConfigSchema.parse({ accounts, rooms: [room] });
|
||||
expect(config.rooms[0]).toMatchObject({ locale: 'zh-CN', timeZone: 'Asia/Shanghai', plugins: {} });
|
||||
});
|
||||
it('rejects duplicate routes, unknown accounts and invalid timezones', () => {
|
||||
expect(() => rootConfigSchema.parse({ accounts, rooms: [room, room] })).toThrow();
|
||||
expect(() => rootConfigSchema.parse({ accounts, rooms: [{ ...room, account: 'missing' }] })).toThrow();
|
||||
expect(() => rootConfigSchema.parse({ accounts, rooms: [{ ...room, timeZone: 'Invalid/Zone' }] })).toThrow();
|
||||
});
|
||||
it('normalizes a single legacy room and infers an unambiguous migration target', () => {
|
||||
const config = rootConfigSchema.parse({ accounts, bots: [{ name: 'checkin', account: 'test', rooms: [room.roomId], config: {} }] });
|
||||
expect(config.legacyCheckinTarget).toEqual(room);
|
||||
expect(config.rooms[0].plugins.checkin.enabled).toBe(true);
|
||||
});
|
||||
it('does not guess where shared legacy multi-room data belongs', () => {
|
||||
const config = rootConfigSchema.parse({ accounts, bots: [{ name: 'checkin', account: 'test', rooms: [room.roomId, '!other:example.org'] }] });
|
||||
expect(config.legacyCheckinTarget).toBeUndefined();
|
||||
});
|
||||
it('rejects mixed old and new room configuration', () => {
|
||||
expect(() => rootConfigSchema.parse({ accounts, rooms: [room], bots: [{ name: 'checkin', account: 'test', rooms: [room.roomId] }] })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves domainless room IDs in managed rooms, legacy bindings and migration targets', () => {
|
||||
const id = '!' + 'A'.repeat(43);
|
||||
const target = { account: 'test', roomId: id };
|
||||
const modern = rootConfigSchema.parse({ accounts, rooms: [target], legacyCheckinTarget: target });
|
||||
expect(modern.rooms[0].roomId).toBe(id);
|
||||
expect(modern.legacyCheckinTarget).toEqual(target);
|
||||
const legacy = rootConfigSchema.parse({ accounts, bots: [{ name: 'checkin', account: 'test', rooms: [id] }] });
|
||||
expect(legacy.rooms[0].roomId).toBe(id);
|
||||
expect(() => rootConfigSchema.parse({ accounts, rooms: [{ ...target, roomId: '!short' }] })).toThrow();
|
||||
});
|
||||
+59
-2
@@ -1,5 +1,8 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Preserve the exact server-supplied ID for routing, including domainless v12 IDs.
|
||||
export const matrixRoomId = z.string().regex(/^!(?:[A-Za-z0-9_-]{43}|[^\s:]+:[^\s]+)$/, 'Invalid roomId');
|
||||
|
||||
const accountSchema = z.object({
|
||||
homeServer: z.string().url(),
|
||||
userId: z.string().regex(/^@.+:.+$/, 'userId 必须是 @user:server 形式'),
|
||||
@@ -9,15 +12,69 @@ const accountSchema = z.object({
|
||||
const botSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
account: z.string().min(1),
|
||||
rooms: z.array(z.string().regex(/^!.+:.+$/, 'roomId 必须是 !id:server 形式')).min(1),
|
||||
rooms: z.array(matrixRoomId).min(1),
|
||||
config: z.record(z.any()).default({}),
|
||||
});
|
||||
|
||||
export const roomSchema = z.object({
|
||||
account: z.string().min(1),
|
||||
roomId: matrixRoomId,
|
||||
locale: z.enum(['zh-CN', 'en']).default('zh-CN'),
|
||||
timeZone: z.string().default('Asia/Shanghai').refine((value) => {
|
||||
try { new Intl.DateTimeFormat('en', { timeZone: value }); return true; }
|
||||
catch { return false; }
|
||||
}, 'Invalid timeZone'),
|
||||
adminPowerLevel: z.number().int().min(1).default(100),
|
||||
admins: z.array(z.string().regex(/^@.+:.+$/)).default([]),
|
||||
plugins: z.record(z.object({
|
||||
enabled: z.boolean().default(false), config: z.record(z.unknown()).default({}),
|
||||
})).default({}),
|
||||
});
|
||||
export const rootConfigSchema = z.object({
|
||||
accounts: z.record(accountSchema),
|
||||
bots: z.array(botSchema),
|
||||
rooms: z.array(roomSchema).default([]),
|
||||
bots: z.array(botSchema).default([]),
|
||||
pluginDirectories: z.array(z.string().min(1)).default([]),
|
||||
legacyCheckinTarget: z.object({ account: z.string(), roomId: matrixRoomId }).optional(),
|
||||
}).transform((config, ctx) => {
|
||||
if (config.rooms.length && config.bots.length) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Use rooms or legacy bots, not both' });
|
||||
return z.NEVER;
|
||||
}
|
||||
const rooms = [...config.rooms];
|
||||
for (const bot of config.bots) {
|
||||
for (const roomId of bot.rooms) {
|
||||
let room = rooms.find((r) => r.account === bot.account && r.roomId === roomId);
|
||||
if (!room) {
|
||||
room = roomSchema.parse({ account: bot.account, roomId,
|
||||
adminPowerLevel: bot.config.adminPowerLevel, admins: bot.config.admins });
|
||||
rooms.push(room);
|
||||
}
|
||||
if (room.plugins[bot.name]) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate plugin in legacy room' });
|
||||
return z.NEVER;
|
||||
}
|
||||
const { mainRoom, adminPowerLevel, admins, ...options } = bot.config;
|
||||
room.plugins[bot.name] = { enabled: true, config: options };
|
||||
}
|
||||
}
|
||||
const keys = new Set<string>();
|
||||
for (const room of rooms) {
|
||||
const key = JSON.stringify([room.account, room.roomId]);
|
||||
if (!config.accounts[room.account] || keys.has(key)) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unknown account or duplicate room' });
|
||||
return z.NEVER;
|
||||
}
|
||||
keys.add(key);
|
||||
}
|
||||
if (!rooms.length) ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'At least one managed room is required' });
|
||||
const legacy = config.bots.filter((b) => b.name === 'checkin');
|
||||
const inferred = legacy.length === 1 && legacy[0].rooms.length === 1
|
||||
? { account: legacy[0].account, roomId: legacy[0].rooms[0] } : undefined;
|
||||
return { ...config, rooms, legacyCheckinTarget: config.legacyCheckinTarget ?? inferred };
|
||||
});
|
||||
|
||||
export type AccountConfig = z.infer<typeof accountSchema>;
|
||||
export type BotConfig = z.infer<typeof botSchema>;
|
||||
export type RootConfig = z.infer<typeof rootConfigSchema>;
|
||||
export type RoomConfig = z.infer<typeof roomSchema>;
|
||||
@@ -1,44 +0,0 @@
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import { InboundMessage } from '../command/types';
|
||||
import { MatrixTransport } from '../matrix/types';
|
||||
import { BotContext } from './room-bot.interface';
|
||||
|
||||
/** BotContext 的默认实现:把出站调用委托给该 bot 账号的 MatrixSession。 */
|
||||
export class DefaultBotContext implements BotContext {
|
||||
constructor(
|
||||
private readonly transport: MatrixTransport,
|
||||
public readonly db: BotStore,
|
||||
) {}
|
||||
|
||||
get account(): string {
|
||||
return this.transport.account;
|
||||
}
|
||||
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string> {
|
||||
return this.transport.send(roomId, text, replyToEventId);
|
||||
}
|
||||
|
||||
reply(msg: InboundMessage, text: string): Promise<string> {
|
||||
return this.transport.send(msg.roomId, text, msg.eventId);
|
||||
}
|
||||
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
return this.transport.kick(roomId, userId, reason);
|
||||
}
|
||||
|
||||
invite(roomId: string, userId: string): Promise<void> {
|
||||
return this.transport.invite(roomId, userId);
|
||||
}
|
||||
|
||||
getMemberCount(roomId: string): Promise<number> {
|
||||
return this.transport.getMemberCount(roomId);
|
||||
}
|
||||
|
||||
getJoinedMembers(roomId: string): Promise<string[]> {
|
||||
return this.transport.getJoinedMembers(roomId);
|
||||
}
|
||||
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number> {
|
||||
return this.transport.getPowerLevel(roomId, userId);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +1,23 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnApplicationBootstrap,
|
||||
OnApplicationShutdown,
|
||||
} from '@nestjs/common';
|
||||
import { Injectable, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { SessionManager } from '../matrix/session-manager.service';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
import { PluginManager } from '../plugin/plugin-manager.service';
|
||||
import { Dispatcher } from './dispatcher.service';
|
||||
import { SchedulerService } from '../scheduler/scheduler.service';
|
||||
|
||||
/**
|
||||
* 平台总装配:
|
||||
* 1. 为每个唯一账号创建会话(共享账号自动去重),sink 指向 Dispatcher
|
||||
* 2. 构建 bot 路由表与 context
|
||||
* 3. 注册各 bot 的定时任务
|
||||
* 4. 启动所有会话(dry-run 下不真正连接)
|
||||
*/
|
||||
@Injectable()
|
||||
export class BotPlatformService
|
||||
implements OnApplicationBootstrap, OnApplicationShutdown
|
||||
{
|
||||
private readonly logger = new Logger(BotPlatformService.name);
|
||||
|
||||
constructor(
|
||||
private readonly registry: BotRegistry,
|
||||
private readonly sessions: SessionManager,
|
||||
private readonly dispatcher: Dispatcher,
|
||||
private readonly scheduler: SchedulerService,
|
||||
) {}
|
||||
|
||||
export class BotPlatformService implements OnApplicationBootstrap, OnApplicationShutdown {
|
||||
constructor(private readonly config: ConfigService, private readonly sessions: SessionManager,
|
||||
private readonly plugins: PluginManager, private readonly dispatcher: Dispatcher) {}
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
for (const account of this.registry.accounts) {
|
||||
for (const account of new Set(this.config.all.rooms.map((room) => room.account))) {
|
||||
this.sessions.ensureSession(account, this.dispatcher);
|
||||
}
|
||||
|
||||
this.registry.build();
|
||||
|
||||
for (const { bot, ctx } of this.registry.registered) {
|
||||
const specs = bot.registerCrons?.(ctx) ?? [];
|
||||
for (const spec of specs) {
|
||||
this.scheduler.register(bot.name, spec);
|
||||
}
|
||||
}
|
||||
|
||||
await this.plugins.initialize();
|
||||
await this.sessions.startAll();
|
||||
|
||||
this.logger.log(
|
||||
`平台已启动: ${this.registry.all.length} 个 bot, ${this.registry.accounts.length} 个账号`,
|
||||
);
|
||||
for (const bot of this.registry.all) {
|
||||
this.logger.log(
|
||||
` • ${bot.name} [account=${bot.account}] rooms=${bot.rooms.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 所有会话已登录,触发各 bot 的就绪钩子(如发送上线通知)。
|
||||
for (const { bot, ctx } of this.registry.registered) {
|
||||
if (!bot.onReady) continue;
|
||||
try {
|
||||
await bot.onReady(ctx);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} onReady 执行失败: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
await this.plugins.start();
|
||||
}
|
||||
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await this.plugins.stop();
|
||||
await this.sessions.stopAll();
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DiscoveryService } from '@nestjs/core';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import { SessionManager } from '../matrix/session-manager.service';
|
||||
import { DefaultBotContext } from './bot-context';
|
||||
import { IS_ROOM_BOT } from './register-bot.decorator';
|
||||
import { BotContext, RoomBot } from './room-bot.interface';
|
||||
|
||||
interface RegisteredBot {
|
||||
bot: RoomBot;
|
||||
ctx: BotContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 维护路由表:`${account}:${roomId}` → bot(s)。
|
||||
* 通过 DiscoveryService 自动发现所有被 @RegisterBot() 标记的 provider,
|
||||
* 这样新增 bot 只需在 feature module 里 provide,无需改动核心。
|
||||
*/
|
||||
@Injectable()
|
||||
export class BotRegistry {
|
||||
private bots: RoomBot[] = [];
|
||||
private discovered = false;
|
||||
private readonly byRoute = new Map<string, RegisteredBot[]>();
|
||||
private readonly byName = new Map<string, RegisteredBot>();
|
||||
|
||||
constructor(
|
||||
private readonly discovery: DiscoveryService,
|
||||
private readonly sessions: SessionManager,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
private discover(): void {
|
||||
if (this.discovered) return;
|
||||
this.bots = this.discovery
|
||||
.getProviders()
|
||||
.filter((w) => w.metatype && w.instance)
|
||||
.filter(
|
||||
(w) => Reflect.getMetadata(IS_ROOM_BOT, w.metatype as object) === true,
|
||||
)
|
||||
.map((w) => w.instance as RoomBot);
|
||||
this.discovered = true;
|
||||
}
|
||||
|
||||
/** 为每个 bot 建好 context 并填充路由表。须在 session 创建后调用。 */
|
||||
build(): void {
|
||||
this.discover();
|
||||
for (const bot of this.bots) {
|
||||
const session = this.sessions.get(bot.account);
|
||||
if (!session) {
|
||||
throw new Error(`bot ${bot.name} 引用了未初始化的账号 ${bot.account}`);
|
||||
}
|
||||
const ctx = new DefaultBotContext(
|
||||
session,
|
||||
new BotStore(this.prisma, bot.name),
|
||||
);
|
||||
const reg: RegisteredBot = { bot, ctx };
|
||||
this.byName.set(bot.name, reg);
|
||||
for (const roomId of bot.rooms) {
|
||||
const key = routeKey(bot.account, roomId);
|
||||
const list = this.byRoute.get(key) ?? [];
|
||||
list.push(reg);
|
||||
this.byRoute.set(key, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get all(): RoomBot[] {
|
||||
this.discover();
|
||||
return this.bots;
|
||||
}
|
||||
|
||||
/** 涉及的所有账号集合(供 SessionManager 去重创建)。 */
|
||||
get accounts(): string[] {
|
||||
this.discover();
|
||||
return [...new Set(this.bots.map((b) => b.account))];
|
||||
}
|
||||
|
||||
resolve(account: string, roomId: string): RegisteredBot[] {
|
||||
return this.byRoute.get(routeKey(account, roomId)) ?? [];
|
||||
}
|
||||
|
||||
getByName(name: string): RegisteredBot | undefined {
|
||||
return this.byName.get(name);
|
||||
}
|
||||
|
||||
get registered(): RegisteredBot[] {
|
||||
return [...this.byName.values()];
|
||||
}
|
||||
}
|
||||
|
||||
export function routeKey(account: string, roomId: string): string {
|
||||
return `${account}:${roomId}`;
|
||||
}
|
||||
@@ -1,18 +1,7 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { DiscoveryModule } from '@nestjs/core';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
import { Dispatcher } from './dispatcher.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BotPlatformService } from './bot-platform.service';
|
||||
import { SchedulerService } from '../scheduler/scheduler.service';
|
||||
import { Dispatcher } from './dispatcher.service';
|
||||
import { PluginManager } from '../plugin/plugin-manager.service';
|
||||
|
||||
/**
|
||||
* 核心 bot 平台模块。具体 bot 由各自的 feature module 通过
|
||||
* @RegisterBot() 标记并 provide,本模块用 DiscoveryService 自动发现。
|
||||
*/
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [DiscoveryModule],
|
||||
providers: [BotRegistry, Dispatcher, BotPlatformService, SchedulerService],
|
||||
exports: [BotRegistry, Dispatcher, BotPlatformService, SchedulerService],
|
||||
})
|
||||
@Module({ providers: [PluginManager, Dispatcher, BotPlatformService] })
|
||||
export class BotModule {}
|
||||
@@ -1,81 +1,22 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types';
|
||||
import { CommandError, parseCommand } from '../command/command-parser';
|
||||
import { MatrixEventSink } from '../matrix/types';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
import { PluginManager } from '../plugin/plugin-manager.service';
|
||||
|
||||
/** 命令前缀。非此前缀的消息只走 onMessage,不解析为命令。 */
|
||||
const COMMAND_PREFIX = '!';
|
||||
|
||||
/**
|
||||
* 把归一化事件按 (account, roomId) 路由到对应 bot 的钩子。
|
||||
* 实现 MatrixEventSink,注册进每个 MatrixSession。
|
||||
*/
|
||||
@Injectable()
|
||||
export class Dispatcher implements MatrixEventSink {
|
||||
private readonly logger = new Logger(Dispatcher.name);
|
||||
|
||||
constructor(private readonly registry: BotRegistry) {}
|
||||
|
||||
async onMessage(msg: InboundMessage): Promise<void> {
|
||||
const targets = this.registry.resolve(msg.account, msg.roomId);
|
||||
if (targets.length === 0) return;
|
||||
|
||||
// 通用归一化:全角叹号→半角、换行→空格,便于中文输入触发命令。
|
||||
const text = msg.text.replace(/!/g, '!').replace(/[\r\n]+/g, ' ').trim();
|
||||
const commandText = text.startsWith(COMMAND_PREFIX)
|
||||
? text.slice(COMMAND_PREFIX.length)
|
||||
: undefined;
|
||||
|
||||
for (const { bot, ctx } of targets) {
|
||||
try {
|
||||
if (bot.onMessage) {
|
||||
await bot.onMessage(msg, ctx);
|
||||
}
|
||||
if (commandText !== undefined && bot.onCommand) {
|
||||
const cmd = parseCommand(msg, commandText);
|
||||
await bot.onCommand(cmd, ctx);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof CommandError) {
|
||||
this.logger.debug(`命令解析失败 (${bot.name}): ${err.message}`);
|
||||
} else {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} 处理消息失败 (room=${msg.roomId}): ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
constructor(private readonly plugins: PluginManager) {}
|
||||
async onMessage(message: InboundMessage): Promise<void> {
|
||||
try { await this.plugins.onMessage(message); }
|
||||
catch { this.logger.error('Message processing failed'); }
|
||||
}
|
||||
|
||||
async onMember(ev: MemberEvent): Promise<void> {
|
||||
const targets = this.registry.resolve(ev.account, ev.roomId);
|
||||
for (const { bot, ctx } of targets) {
|
||||
try {
|
||||
if (ev.membership === 'join' && bot.onMemberJoin) {
|
||||
await bot.onMemberJoin(ev, ctx);
|
||||
} else if (ev.membership === 'leave' && bot.onMemberLeave) {
|
||||
await bot.onMemberLeave(ev, ctx);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} 处理成员事件失败: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
async onMember(event: MemberEvent): Promise<void> {
|
||||
try { await this.plugins.onEvent(event); }
|
||||
catch { this.logger.error('Member event processing failed'); }
|
||||
}
|
||||
|
||||
async onPowerLevel(ev: PowerLevelEvent): Promise<void> {
|
||||
const targets = this.registry.resolve(ev.account, ev.roomId);
|
||||
for (const { bot, ctx } of targets) {
|
||||
if (!bot.onPowerLevel) continue;
|
||||
try {
|
||||
await bot.onPowerLevel(ev, ctx);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} 处理权限变更事件失败: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
async onPowerLevel(event: PowerLevelEvent): Promise<void> {
|
||||
try { await this.plugins.onEvent(event); }
|
||||
catch { this.logger.error('Power event processing failed'); }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
/** 标记一个 provider 为 RoomBot,供 BotRegistry 通过 DiscoveryService 发现。 */
|
||||
export const IS_ROOM_BOT = 'daily-bot:is-room-bot';
|
||||
|
||||
export const RegisterBot = (): ClassDecorator => SetMetadata(IS_ROOM_BOT, true);
|
||||
@@ -1,47 +0,0 @@
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import {
|
||||
CronSpec,
|
||||
InboundMessage,
|
||||
MemberEvent,
|
||||
ParsedCommand,
|
||||
PowerLevelEvent,
|
||||
} from '../command/types';
|
||||
|
||||
/**
|
||||
* 注入给每个 bot 的运行时上下文:出站能力 + 已隔离的存储。
|
||||
* bot 永远不直接碰 matrix client,便于单测(mock 本接口即可)。
|
||||
*/
|
||||
export interface BotContext {
|
||||
readonly account: string;
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string>;
|
||||
reply(msg: InboundMessage, text: string): Promise<string>;
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void>;
|
||||
invite(roomId: string, userId: string): Promise<void>;
|
||||
getMemberCount(roomId: string): Promise<number>;
|
||||
getJoinedMembers(roomId: string): Promise<string[]>;
|
||||
/** 读取用户在房间内的 power level,用于按房间权限判断管理员(读不到返回 0)。 */
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number>;
|
||||
readonly db: BotStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个房间机器人实现的契约。一个 bot = 一个独立功能模块。
|
||||
* 所有钩子均可选,bot 只实现自己关心的事件。
|
||||
*/
|
||||
export interface RoomBot {
|
||||
/** 唯一名字,同时作为 DB scope。 */
|
||||
readonly name: string;
|
||||
/** 使用哪个账号(对应 config.accounts 的 key)。 */
|
||||
readonly account: string;
|
||||
/** 管理哪些房间。 */
|
||||
readonly rooms: string[];
|
||||
|
||||
/** 平台完成所有会话登录后调用一次,适合发送上线通知、做初始化等。 */
|
||||
onReady?(ctx: BotContext): Promise<void>;
|
||||
onMessage?(msg: InboundMessage, ctx: BotContext): Promise<void>;
|
||||
onCommand?(cmd: ParsedCommand, ctx: BotContext): Promise<void>;
|
||||
onMemberJoin?(ev: MemberEvent, ctx: BotContext): Promise<void>;
|
||||
onMemberLeave?(ev: MemberEvent, ctx: BotContext): Promise<void>;
|
||||
onPowerLevel?(ev: PowerLevelEvent, ctx: BotContext): Promise<void>;
|
||||
registerCrons?(ctx: BotContext): CronSpec[];
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Command, CommandRouter } from './command-router';
|
||||
import { message } from '../../test/fakes';
|
||||
const command: Command = { id: 'checkin', paths: [['checkin'], ['签到']], bare: ['签到'],
|
||||
description: { 'zh-CN': '签到', en: 'check in' }, usage: { 'zh-CN': '!签到', en: '!checkin' }, run: async () => undefined };
|
||||
|
||||
describe('shared command aliases', () => {
|
||||
it.each(['签到', '!签到', '!签到', '/签到', '/checkin', '!CHECKIN', '!checkin'])('%s resolves to the same command', (text) => {
|
||||
expect(new CommandRouter([command]).match(message(text))?.command.id).toBe('checkin');
|
||||
});
|
||||
it('does not parse normal conversation as commands', () => {
|
||||
expect(new CommandRouter([command]).match(message('今天已经签到了吗'))).toBeUndefined();
|
||||
expect(new CommandRouter([command]).match(message('checkin'))).toBeUndefined();
|
||||
});
|
||||
it('matches longest registered paths and preserves quoted arguments', () => {
|
||||
const nested = { ...command, id: 'query', paths: [['签到', '查询']], bare: [] };
|
||||
const result = new CommandRouter([command, nested]).match(message('!签到 查询 "value with spaces" --原始'))!;
|
||||
expect(result.command.id).toBe('query');
|
||||
expect(result.invocation).toMatchObject({ args: ['value with spaces'], raw: true });
|
||||
});
|
||||
it('rejects alias collisions instead of dispatching multiple handlers', () => {
|
||||
expect(() => new CommandRouter([command, { ...command, id: 'other' }])).toThrow('Duplicate');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { InboundMessage } from './types';
|
||||
import { tokenize } from './command-parser';
|
||||
import { Text } from '../i18n/i18n';
|
||||
|
||||
export interface Invocation { message: InboundMessage; args: string[]; raw: boolean; }
|
||||
export interface Command {
|
||||
id: string;
|
||||
paths: string[][];
|
||||
bare?: string[];
|
||||
admin?: boolean;
|
||||
description: Text;
|
||||
usage: Text;
|
||||
run(invocation: Invocation): Promise<void>;
|
||||
}
|
||||
const normalize = (s: string) => s.normalize('NFKC').toLowerCase();
|
||||
|
||||
/** A single alias registry serves every plugin, including multi-word commands. */
|
||||
export class CommandRouter {
|
||||
private readonly commands = new Map<string, Command>();
|
||||
private readonly bare = new Map<string, Command>();
|
||||
constructor(readonly definitions: Command[]) {
|
||||
for (const command of definitions) {
|
||||
for (const path of command.paths) {
|
||||
if (!path.length || path.some((p) => !p || /\s/.test(p))) throw new Error('Invalid command path');
|
||||
const key = path.map(normalize).join(' ');
|
||||
if (this.commands.has(key)) throw new Error(`Duplicate command: ${key}`);
|
||||
this.commands.set(key, command);
|
||||
}
|
||||
for (const alias of command.bare ?? []) {
|
||||
const key = normalize(alias);
|
||||
if (this.bare.has(key)) throw new Error(`Duplicate bare command: ${key}`);
|
||||
this.bare.set(key, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
match(message: InboundMessage): { command: Command; invocation: Invocation } | undefined {
|
||||
const text = message.text.trim();
|
||||
const bare = this.bare.get(normalize(text));
|
||||
if (bare) return { command: bare, invocation: { message, args: [], raw: false } };
|
||||
if (!/^[!!//]/.test(text)) return undefined;
|
||||
const tokens = tokenize(text.slice(1));
|
||||
for (let length = tokens.length; length > 0; length--) {
|
||||
const command = this.commands.get(tokens.slice(0, length).map(normalize).join(' '));
|
||||
if (!command) continue;
|
||||
const args = tokens.slice(length);
|
||||
const raw = args.some((a) => ['--raw', '--原始'].includes(normalize(a)));
|
||||
return { command, invocation: { message, raw,
|
||||
args: args.filter((a) => !['--raw', '--原始'].includes(normalize(a))) } };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,11 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, unlinkSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { PrismaService } from './prisma.service';
|
||||
import { BotStore } from './bot-store';
|
||||
|
||||
const PROJECT_ROOT = resolve(__dirname, '../../..');
|
||||
const TEST_DB_FILE = resolve(PROJECT_ROOT, 'test-botstore-integration.db');
|
||||
const TEST_DB_URL = `file:${TEST_DB_FILE}`;
|
||||
|
||||
function cleanDb(): void {
|
||||
for (const suffix of ['', '-journal', '-wal', '-shm']) {
|
||||
const f = TEST_DB_FILE + suffix;
|
||||
if (existsSync(f)) unlinkSync(f);
|
||||
}
|
||||
}
|
||||
|
||||
import { testDatabase } from '../../test/database';
|
||||
let database: Awaited<ReturnType<typeof testDatabase>> | undefined;
|
||||
let prismaService: PrismaService;
|
||||
|
||||
beforeAll(async () => {
|
||||
cleanDb();
|
||||
execSync('npx prisma db push --skip-generate', {
|
||||
cwd: PROJECT_ROOT,
|
||||
env: { ...process.env, DATABASE_URL: TEST_DB_URL },
|
||||
stdio: 'pipe',
|
||||
});
|
||||
process.env.DATABASE_URL = TEST_DB_URL;
|
||||
// PrismaService reads DATABASE_URL at construction time via PrismaClient.
|
||||
prismaService = new PrismaService();
|
||||
await prismaService.onModuleInit();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prismaService.onModuleDestroy();
|
||||
cleanDb();
|
||||
delete process.env.DATABASE_URL;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean all rows between tests to ensure isolation.
|
||||
await prismaService.botState.deleteMany();
|
||||
});
|
||||
beforeAll(async () => { database = await testDatabase(); prismaService = database.prisma; });
|
||||
afterAll(async () => { await database?.close(); });
|
||||
afterEach(async () => { await database?.prisma.botState.deleteMany(); });
|
||||
|
||||
describe('BotStore (integration with real SQLite)', () => {
|
||||
it('returns null for a key that has never been set', async () => {
|
||||
|
||||
@@ -27,9 +27,17 @@ export class BotStore {
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.prisma.botState
|
||||
.delete({ where: { botName_key: { botName: this.botName, key } } })
|
||||
.catch(() => undefined);
|
||||
await this.prisma.botState.deleteMany({ where: { botName: this.botName, key } });
|
||||
}
|
||||
|
||||
async create<T>(key: string, value: T): Promise<boolean> {
|
||||
try {
|
||||
await this.prisma.botState.create({ data: { botName: this.botName, key, valueJson: JSON.stringify(value) } });
|
||||
return true;
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code === 'P2002') return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async entries<T = unknown>(): Promise<Array<[string, T]>> {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
export type Locale = 'zh-CN' | 'en';
|
||||
export type Text = Record<Locale, string>;
|
||||
export type Messages = Record<string, Text>;
|
||||
|
||||
export function translate(text: Text, locale: Locale, values: Record<string, unknown> = {}): string {
|
||||
return text[locale].replace(/\{(\w+)\}/g, (_, key: string) => String(values[key] ?? `{${key}}`));
|
||||
}
|
||||
|
||||
export function choice<T extends string>(value: string | undefined, choices: Record<T, readonly string[]>): T | undefined {
|
||||
const normalized = value?.normalize('NFKC').toLowerCase();
|
||||
return (Object.keys(choices) as T[]).find((key) =>
|
||||
[key, ...choices[key]].some((alias) => alias.toLowerCase() === normalized));
|
||||
}
|
||||
|
||||
export const common = {
|
||||
denied: { 'zh-CN': '无权限:此操作仅管理员可用。', en: 'Permission denied: administrators only.' },
|
||||
failed: { 'zh-CN': '操作未完成,请查看插件状态或联系维护人员。', en: 'Operation failed. Check plugin status or contact maintenance.' },
|
||||
unknown: { 'zh-CN': '未知命令,请发送 !帮助。', en: 'Unknown command. Send !help.' },
|
||||
usage: { 'zh-CN': '用法:{usage}', en: 'Usage: {usage}' },
|
||||
expired: { 'zh-CN': '确认码无效、已使用或已过期,请重新预览。', en: 'Invalid, used or expired confirmation. Preview again.' },
|
||||
empty: { 'zh-CN': '暂无记录。', en: 'No records.' },
|
||||
preview: { 'zh-CN': '预览(尚未执行):\n{details}\n5 分钟内由同一管理员发送:{command}', en: 'Preview (not executed):\n{details}\nThe same administrator can confirm within 5 minutes: {command}' },
|
||||
done: { 'zh-CN': '执行结果:\n{details}', en: 'Results:\n{details}' },
|
||||
removed: { 'zh-CN': '旧的重置、测试和手动等级命令已停用。请使用 !日报、!月报 或 !清理 预览。', en: 'Legacy reset, test and manual level commands are retired. Use !report daily, !report monthly or !cleanup preview.' },
|
||||
} satisfies Messages;
|
||||
@@ -0,0 +1,37 @@
|
||||
jest.mock('matrix-bot-sdk', () => ({}));
|
||||
jest.mock('@matrix-org/matrix-sdk-crypto-nodejs', () => ({}));
|
||||
import { MatrixSession } from './matrix-session';
|
||||
import { MatrixEventSink } from './types';
|
||||
|
||||
describe('Matrix transport failure semantics without connecting', () => {
|
||||
const config = { userId: '@bot:example.org', password: 'fixture', homeServer: 'https://example.org' };
|
||||
const sink: MatrixEventSink = { onMessage: jest.fn(), onMember: jest.fn(), onPowerLevel: jest.fn() };
|
||||
it('rejects mutations and permission reads before the session is ready', async () => {
|
||||
const session = new MatrixSession('test', config, sink, false);
|
||||
await expect(session.send('!room:example.org', 'text')).rejects.toThrow('not ready');
|
||||
await expect(session.kick('!room:example.org', '@member:example.org')).rejects.toThrow('not ready');
|
||||
await expect(session.getPowerLevel('!room:example.org', '@member:example.org')).rejects.toThrow('not ready');
|
||||
});
|
||||
it('propagates lookup failures rather than granting an apparent low permission level', async () => {
|
||||
const session = new MatrixSession('test', config, sink, false);
|
||||
Object.assign(session, { client: {
|
||||
getRoomStateEvent: async () => { throw new Error('Unavailable'); },
|
||||
getJoinedRoomMembers: async () => { throw new Error('Unavailable'); },
|
||||
} });
|
||||
await expect(session.getPowerLevel('!room:example.org', '@member:example.org')).rejects.toThrow('Unavailable');
|
||||
await expect(session.getJoinedMembers('!room:example.org')).rejects.toThrow('Unavailable');
|
||||
});
|
||||
it('filters replayed commands and self messages before dispatch', () => {
|
||||
const handlers = new Map<string, (...args: any[]) => void>();
|
||||
const session = new MatrixSession('test', config, sink, false);
|
||||
(session as any).registerHandlers({ on: (name: string, fn: (...args: any[]) => void) => handlers.set(name, fn) });
|
||||
const onMessage = handlers.get('room.message')!;
|
||||
jest.mocked(sink.onMessage).mockClear();
|
||||
const event = { event_id: '$event', sender: '@member:example.org', content: { msgtype: 'm.text', body: '!plugin enable checkin' }, origin_server_ts: 1 };
|
||||
onMessage('!room:example.org', event);
|
||||
onMessage('!room:example.org', { ...event, sender: config.userId, origin_server_ts: Date.now() + 10 });
|
||||
expect(sink.onMessage).not.toHaveBeenCalled();
|
||||
onMessage('!room:example.org', { ...event, origin_server_ts: Date.now() + 10 });
|
||||
expect(sink.onMessage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -37,9 +37,12 @@ export class MatrixSession implements MatrixTransport {
|
||||
private client?: MatrixClient;
|
||||
private selfUserId?: string;
|
||||
private started = false;
|
||||
private readonly acceptEventsAfter = Date.now();
|
||||
/** 记录 bot 自己刚发出的 event_id,sync 回流时跳过,避免回应自己(支持与用户同账号自测)。 */
|
||||
private readonly recentSentEventIds = new Set<string>();
|
||||
|
||||
get userId(): string { return this.selfUserId ?? this.cfg.userId; }
|
||||
|
||||
constructor(
|
||||
public readonly account: string,
|
||||
private readonly cfg: AccountConfig,
|
||||
@@ -107,6 +110,12 @@ export class MatrixSession implements MatrixTransport {
|
||||
);
|
||||
}
|
||||
|
||||
async getJoinedRooms(): Promise<string[]> {
|
||||
if (this.dryRun) return [];
|
||||
if (!this.client) throw new Error('Matrix session is not ready');
|
||||
return this.client.getJoinedRooms();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.client?.stop();
|
||||
}
|
||||
@@ -147,7 +156,7 @@ export class MatrixSession implements MatrixTransport {
|
||||
/**
|
||||
* 用密码登录一次,拿到 accessToken/baseUrl/deviceId 落盘,返回长期使用的 client。
|
||||
* matrix-bot-sdk 的 MatrixAuth 会自行做 .well-known 发现并返回正确的
|
||||
* homeserverUrl(裸域名 tchncs.de → matrix.tchncs.de),无需手动发现。
|
||||
* homeserverUrl(裸域名 example.org → matrix.example.org),无需手动发现。
|
||||
*/
|
||||
private async loginAndBuild(
|
||||
accDir: string,
|
||||
@@ -183,8 +192,8 @@ export class MatrixSession implements MatrixTransport {
|
||||
*/
|
||||
private async passwordLoginWithRetry(): Promise<MatrixClient> {
|
||||
// MatrixAuth 不会自动做服务器发现,它直接拿传入地址打 /login。
|
||||
// 必须先用 .well-known 把账号域名(https://tchncs.de)解析成真实 API 域名
|
||||
// (https://matrix.tchncs.de),否则会打到裸域名的落地页入口被限流(429)。
|
||||
// 必须先用 .well-known 把账号域名(https://example.org)解析成真实 API 域名
|
||||
// (https://matrix.example.org),否则会打到裸域名的落地页入口被限流(429)。
|
||||
const baseUrl = await this.discoverBaseUrl(this.cfg.homeServer);
|
||||
const auth = new MatrixAuth(baseUrl);
|
||||
const maxWaitMs = 10 * 60_000; // 单次等待上限 10 分钟,避免异常超长阻塞。
|
||||
@@ -222,7 +231,7 @@ export class MatrixSession implements MatrixTransport {
|
||||
|
||||
/**
|
||||
* 通过 /.well-known/matrix/client 自动发现真实的 homeserver API 地址。
|
||||
* 例如账号域名 https://tchncs.de 会被解析为 https://matrix.tchncs.de。
|
||||
* 例如账号域名 https://example.org 会被解析为 https://matrix.example.org。
|
||||
* 这是 Matrix 标准的服务器发现机制(Element 等客户端均如此)。
|
||||
* 若配置里已经是真实 API 地址,发现通常返回同值;发现失败则回退原值。
|
||||
*/
|
||||
@@ -309,10 +318,11 @@ export class MatrixSession implements MatrixTransport {
|
||||
text: string,
|
||||
replyToEventId?: string,
|
||||
): Promise<string> {
|
||||
if (this.dryRun || !this.client) {
|
||||
if (this.dryRun) {
|
||||
this.logger.log(`[dry-run] send → ${roomId}: ${text}`);
|
||||
return 'dry-run-event-id';
|
||||
}
|
||||
if (!this.client) throw new Error('Matrix session is not ready');
|
||||
const content: Record<string, unknown> = { msgtype: 'm.text', body: text };
|
||||
if (replyToEventId) {
|
||||
content['m.relates_to'] = {
|
||||
@@ -336,54 +346,48 @@ export class MatrixSession implements MatrixTransport {
|
||||
}
|
||||
|
||||
async kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
if (this.dryRun || !this.client) {
|
||||
if (this.dryRun) {
|
||||
this.logger.log(
|
||||
`[dry-run] kick ${userId} from ${roomId} (${reason ?? ''})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!this.client) throw new Error('Matrix session is not ready');
|
||||
await this.client.kickUser(userId, roomId, reason);
|
||||
}
|
||||
|
||||
async invite(roomId: string, userId: string): Promise<void> {
|
||||
if (this.dryRun || !this.client) {
|
||||
if (this.dryRun) {
|
||||
this.logger.log(`[dry-run] invite ${userId} to ${roomId}`);
|
||||
return;
|
||||
}
|
||||
if (!this.client) throw new Error('Matrix session is not ready');
|
||||
await this.client.inviteUser(userId, roomId);
|
||||
}
|
||||
|
||||
async getMemberCount(roomId: string): Promise<number> {
|
||||
if (this.dryRun || !this.client) return 0;
|
||||
const members = await this.client
|
||||
.getJoinedRoomMembers(roomId)
|
||||
.catch(() => []);
|
||||
return members.length;
|
||||
return (await this.getJoinedMembers(roomId)).length;
|
||||
}
|
||||
|
||||
async getJoinedMembers(roomId: string): Promise<string[]> {
|
||||
if (this.dryRun || !this.client) return [];
|
||||
return this.client.getJoinedRoomMembers(roomId).catch(() => []);
|
||||
if (this.dryRun) return [];
|
||||
if (!this.client) throw new Error('Matrix session is not ready');
|
||||
return this.client.getJoinedRoomMembers(roomId);
|
||||
}
|
||||
|
||||
/** 读取用户在房间内的 power level:取 m.room.power_levels 的 users[userId],回落 users_default。 */
|
||||
async getPowerLevel(roomId: string, userId: string): Promise<number> {
|
||||
if (this.dryRun || !this.client) return 0;
|
||||
try {
|
||||
if (this.dryRun) return 0;
|
||||
if (!this.client) throw new Error('Matrix session is not ready');
|
||||
const pl = (await this.client.getRoomStateEvent(
|
||||
roomId,
|
||||
'm.room.power_levels',
|
||||
'',
|
||||
)) as { users?: Record<string, number>; users_default?: number };
|
||||
const users = pl?.users ?? {};
|
||||
if (typeof users[userId] === 'number') return users[userId];
|
||||
return typeof pl?.users_default === 'number' ? pl.users_default : 0;
|
||||
} catch (err) {
|
||||
this.logger.debug?.(
|
||||
`读取 ${roomId} power_levels 失败: ${(err as Error).message}`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
const value = users[userId] ?? pl?.users_default ?? 0;
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error('Invalid power level');
|
||||
return value;
|
||||
}
|
||||
|
||||
private registerHandlers(client: MatrixClient): void {
|
||||
@@ -391,6 +395,8 @@ export class MatrixSession implements MatrixTransport {
|
||||
client.on('room.message', (roomId: string, event: Record<string, any>) => {
|
||||
const sender = event['sender'] as string | undefined;
|
||||
const eventId = event['event_id'] as string | undefined;
|
||||
if (sender === this.cfg.userId || sender === this.selfUserId) return;
|
||||
if (typeof event['origin_server_ts'] !== 'number' || event['origin_server_ts'] < this.acceptEventsAfter) return;
|
||||
// 去重:仅跳过 bot 自己刚发出的消息,用户同账号发的命令仍会处理。
|
||||
if (eventId && this.recentSentEventIds.has(eventId)) {
|
||||
this.recentSentEventIds.delete(eventId);
|
||||
@@ -415,6 +421,7 @@ export class MatrixSession implements MatrixTransport {
|
||||
|
||||
// room.event:所有房间事件;在此筛成员变更及权限变更。
|
||||
client.on('room.event', (roomId: string, event: Record<string, any>) => {
|
||||
if (typeof event['origin_server_ts'] !== 'number' || event['origin_server_ts'] < this.acceptEventsAfter) return;
|
||||
const type = event['type'];
|
||||
const content = (event['content'] ?? {}) as Record<string, unknown>;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { recoveryRooms } from '../plugin/room-binding';
|
||||
import { MatrixSession } from './matrix-session';
|
||||
import { MatrixEventSink } from './types';
|
||||
|
||||
@@ -23,11 +24,12 @@ export class SessionManager {
|
||||
const accCfg = this.config.getAccount(account);
|
||||
// 聚合所有使用该账号的 bot 关注的房间(去重),限制 sync 范围。
|
||||
const watchRoomIds = [
|
||||
...new Set(
|
||||
this.config.bots
|
||||
.filter((b) => b.account === account)
|
||||
.flatMap((b) => b.rooms),
|
||||
),
|
||||
...new Set([
|
||||
...this.config.all.rooms
|
||||
.filter((room) => room.account === account)
|
||||
.map((room) => room.roomId),
|
||||
...recoveryRooms(this.config.all.rooms, account).keys(),
|
||||
]),
|
||||
];
|
||||
const session = new MatrixSession(
|
||||
account,
|
||||
|
||||
@@ -3,12 +3,13 @@ import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types';
|
||||
/** bot 与 Matrix 交互的统一出站能力(BotContext 内部依赖它)。 */
|
||||
export interface MatrixTransport {
|
||||
readonly account: string;
|
||||
readonly userId: string;
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string>;
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void>;
|
||||
invite(roomId: string, userId: string): Promise<void>;
|
||||
getMemberCount(roomId: string): Promise<number>;
|
||||
getJoinedMembers(roomId: string): Promise<string[]>;
|
||||
/** 读取用户在房间内的 power level(读不到或无权限时返回 0)。 */
|
||||
/** Permission lookups reject on failure; callers must not treat errors as level zero. */
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export function localDate(date: Date, timeZone: string): string {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(date);
|
||||
const get = (type: string) => parts.find((p) => p.type === type)!.value;
|
||||
return `${get('year')}-${get('month')}-${get('day')}`;
|
||||
}
|
||||
export function localMinutes(date: Date, timeZone: string): number {
|
||||
const parts = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(date);
|
||||
return Number(parts.find((p) => p.type === 'hour')!.value) * 60 + Number(parts.find((p) => p.type === 'minute')!.value);
|
||||
}
|
||||
export function shiftDate(date: string, days: number): string {
|
||||
const value = new Date(`${date}T12:00:00Z`);
|
||||
value.setUTCDate(value.getUTCDate() + days);
|
||||
return value.toISOString().slice(0, 10);
|
||||
}
|
||||
export function validDate(value: string): boolean {
|
||||
return /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
||||
}
|
||||
export function previousMonth(date: string): string { return shiftDate(`${date.slice(0, 7)}-01`, -1).slice(0, 7); }
|
||||
@@ -0,0 +1,38 @@
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { loadPlugins } from './catalog';
|
||||
import { RoomRuntime } from './room-runtime';
|
||||
import { roomSchema } from '../../config/schema';
|
||||
import { FakeTransport, FakeScheduler, memoryStores, message } from '../../test/fakes';
|
||||
|
||||
describe('plugin discovery', () => {
|
||||
it('discovers built-in plugins without a registration list', () => {
|
||||
expect(loadPlugins([resolve(__dirname, '../../plugins')]).map((p) => p.id)).toEqual(['checkin', 'room-manager']);
|
||||
});
|
||||
it('loads a new server-installed module without changing core imports', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'bot-plugin-'));
|
||||
try {
|
||||
writeFileSync(join(dir, 'sample.plugin.js'), `exports.default = { apiVersion: 1, id: 'sample', version: '1', description: { 'zh-CN': '示例', en: 'Example' }, validate: c => c, create: () => ({ commands: [] }) };`);
|
||||
expect(loadPlugins([dir]).map((p) => p.id)).toEqual(['sample']);
|
||||
expect(() => loadPlugins([dir, dir])).toThrow('Duplicate');
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
it('rejects incompatible API versions', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'bot-plugin-'));
|
||||
try {
|
||||
writeFileSync(join(dir, 'bad.plugin.js'), `exports.default = { apiVersion: 2, id: 'bad' };`);
|
||||
expect(() => loadPlugins([dir])).toThrow('Invalid plugin');
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
it('runs the external example with the unchanged host and bilingual commands', async () => {
|
||||
const transport = new FakeTransport();
|
||||
const runtime = new RoomRuntime(roomSchema.parse({ account: 'test', roomId: '!control:example.org' }),
|
||||
loadPlugins([resolve(__dirname, '../../../examples')]), transport, memoryStores(), new FakeScheduler());
|
||||
await runtime.start(); await runtime.message(message('!插件 启用 问候', '@admin:example.org'));
|
||||
await runtime.message(message('!问候 世界')); expect(transport.sent.at(-1)?.text).toBe('你好,世界!');
|
||||
await runtime.message(message('!language en', '@admin:example.org'));
|
||||
await runtime.message(message('!greet World')); expect(transport.sent.at(-1)?.text).toBe('Hello, World!');
|
||||
await runtime.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { PluginDefinition } from './types';
|
||||
|
||||
/** Loads trusted server-installed modules. Chat commands never download or evaluate code. */
|
||||
export function loadPlugins(directories: string[]): PluginDefinition[] {
|
||||
const definitions: PluginDefinition[] = [];
|
||||
const aliases = new Set<string>();
|
||||
const visit = (directory: string) => {
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const file = join(directory, entry.name);
|
||||
if (entry.isDirectory()) { visit(file); continue; }
|
||||
if (!/\.plugin\.(js|ts)$/.test(entry.name) || entry.name.endsWith('.d.ts')) continue;
|
||||
const definition = require(file).default as PluginDefinition;
|
||||
if (definition?.apiVersion !== 1 || !/^[a-z][a-z0-9-]*$/.test(definition.id) ||
|
||||
typeof definition.version !== 'string' || typeof definition.create !== 'function' ||
|
||||
typeof definition.validate !== 'function' || !definition.description?.en || !definition.description?.['zh-CN']) {
|
||||
throw new Error(`Invalid plugin manifest: ${entry.name}`);
|
||||
}
|
||||
for (const alias of [definition.id, ...(definition.aliases ?? [])]) {
|
||||
const key = alias.normalize('NFKC').toLowerCase();
|
||||
if (aliases.has(key)) throw new Error(`Duplicate plugin alias: ${alias}`);
|
||||
aliases.add(key);
|
||||
}
|
||||
definitions.push(definition);
|
||||
}
|
||||
};
|
||||
directories.forEach(visit);
|
||||
return definitions;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { PluginContext } from './types';
|
||||
|
||||
interface Pending<T> { actor: string; expires: number; payload: T; }
|
||||
export class Confirmations<T> {
|
||||
constructor(private readonly ctx: PluginContext, private readonly kind: string) {}
|
||||
async preview(actor: string, payload: T): Promise<string> {
|
||||
const token = randomBytes(8).toString('hex');
|
||||
// One plan per actor and operation bounds storage and invalidates older plans.
|
||||
await this.ctx.db.set(`pending:${this.kind}:${actor}`, {
|
||||
actor, token, expires: this.ctx.now().getTime() + 300_000, payload,
|
||||
});
|
||||
return token;
|
||||
}
|
||||
async consume(actor: string, token: string): Promise<T | undefined> {
|
||||
const key = `pending:${this.kind}:${actor}`;
|
||||
const plan = await this.ctx.db.get<Pending<T> & { token: string }>(key);
|
||||
if (!plan || plan.token !== token || plan.expires <= this.ctx.now().getTime()) return undefined;
|
||||
await this.ctx.db.remove(key);
|
||||
return plan.payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { RootConfig } from '../../config/schema';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { localDate } from './calendar';
|
||||
import { pluginScope } from './room-runtime';
|
||||
|
||||
/** Copies the legacy scope atomically. Source rows are retained for rollback. */
|
||||
export async function migrateCheckin(prisma: PrismaService, config: RootConfig): Promise<void> {
|
||||
const source = await prisma.botState.findMany({ where: { botName: 'checkin' } });
|
||||
if (!source.length) return;
|
||||
const target = config.legacyCheckinTarget;
|
||||
const room = target && config.rooms.find((r) => r.account === target.account && r.roomId === target.roomId);
|
||||
if (!target || !room || !room.plugins.checkin) {
|
||||
throw new Error('Legacy check-in data requires an explicit legacyCheckinTarget with a configured checkin plugin');
|
||||
}
|
||||
const scope = pluginScope(target.account, target.roomId, 'checkin');
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const marker = await tx.botState.findUnique({ where: { botName_key: { botName: '$migrations', key: 'checkin-v2' } } });
|
||||
if (marker) {
|
||||
if (JSON.parse(marker.valueJson).scope !== scope) throw new Error('Legacy check-in data was already assigned to another room');
|
||||
return;
|
||||
}
|
||||
if (await tx.botState.count({ where: { botName: scope } })) throw new Error('Migration target already contains data; explicit reconciliation is required');
|
||||
for (const row of source) {
|
||||
if (!/^@.+:.+$/.test(row.key)) throw new Error('Unexpected legacy check-in key');
|
||||
const old = JSON.parse(row.valueJson) as { checkinTimesInMonth?: number; checkinUnixMs?: number };
|
||||
const count = old.checkinTimesInMonth ?? 0, lastAt = old.checkinUnixMs ?? 0;
|
||||
if (!Number.isInteger(count) || count < 0 || !Number.isFinite(lastAt) || lastAt < 0 || (count > 0 && !lastAt)) {
|
||||
throw new Error('Invalid legacy check-in record');
|
||||
}
|
||||
const date = lastAt ? localDate(new Date(lastAt), room.timeZone) : '';
|
||||
await tx.botState.create({ data: { botName: scope, key: `legacy:${row.key}`,
|
||||
valueJson: JSON.stringify({ userId: row.key, count, month: date.slice(0, 7), lastAt }) } });
|
||||
if (date) await tx.botState.create({ data: { botName: scope, key: `day:${JSON.stringify([row.key, date])}`,
|
||||
valueJson: JSON.stringify({ userId: row.key, date, at: lastAt, counted: false }) } });
|
||||
}
|
||||
await tx.botState.create({ data: { botName: '$migrations', key: 'checkin-v2', valueJson: JSON.stringify({ scope, records: source.length }) } });
|
||||
}, { timeout: 30_000 });
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import { SessionManager } from '../matrix/session-manager.service';
|
||||
import { loadPlugins } from './catalog';
|
||||
import { RoomConfig } from '../../config/schema';
|
||||
import { bindingKey, recoveryRooms, recoverBinding } from './room-binding';
|
||||
import { RoomRuntime } from './room-runtime';
|
||||
import { PluginScheduler } from './scheduler';
|
||||
import { migrateCheckin } from './migrate-checkin';
|
||||
import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types';
|
||||
|
||||
@Injectable()
|
||||
export class PluginManager {
|
||||
private readonly logger = new Logger(PluginManager.name);
|
||||
private readonly rooms = new Map<string, RoomRuntime>();
|
||||
private readonly candidates = new Map<string, RoomConfig>();
|
||||
private get bindings() { return new BotStore(this.prisma, '$room-bindings'); }
|
||||
constructor(private readonly config: ConfigService, private readonly prisma: PrismaService, private readonly sessions: SessionManager) {}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
const definitions = loadPlugins([resolve(__dirname, '../../plugins'), ...this.config.all.pluginDirectories.map((p) => resolve(p))]);
|
||||
await migrateCheckin(this.prisma, this.config.all);
|
||||
for (const account of new Set(this.config.all.rooms.map((room) => room.account))) {
|
||||
for (const [id, room] of recoveryRooms(this.config.all.rooms, account)) {
|
||||
this.candidates.set(JSON.stringify([account, id]), room);
|
||||
}
|
||||
}
|
||||
for (const room of this.config.all.rooms) {
|
||||
const session = this.sessions.get(room.account);
|
||||
if (!session) throw new Error('Missing account session');
|
||||
const saved = await this.bindings.get<{ id: string }>(bindingKey(room));
|
||||
if (saved && this.candidates.get(JSON.stringify([room.account, saved.id])) !== room) {
|
||||
throw new Error('Room binding conflicts with configured rooms or recovery policy');
|
||||
}
|
||||
const effective = { ...room, roomId: saved?.id ?? room.roomId };
|
||||
this.rooms.set(JSON.stringify([room.account, effective.roomId]), new RoomRuntime(effective, definitions,
|
||||
session, (scope) => new BotStore(this.prisma, scope), new PluginScheduler(), undefined, room.roomId));
|
||||
}
|
||||
}
|
||||
async start(): Promise<void> {
|
||||
for (const runtime of this.rooms.values()) {
|
||||
await runtime.start();
|
||||
for (const state of runtime.status()) if (state.state === 'failed') this.logger.error(`Plugin failed to start: ${state.id}`);
|
||||
}
|
||||
}
|
||||
async stop(): Promise<void> {
|
||||
for (const runtime of this.rooms.values()) await runtime.stop();
|
||||
}
|
||||
async onMessage(msg: InboundMessage): Promise<void> {
|
||||
const key = JSON.stringify([msg.account, msg.roomId]);
|
||||
const runtime = this.rooms.get(key);
|
||||
if (runtime) return runtime.message(msg);
|
||||
const candidate = this.candidates.get(key);
|
||||
const session = this.sessions.get(msg.account);
|
||||
if (candidate && session) await recoverBinding(candidate, msg, this.bindings, session);
|
||||
}
|
||||
async onEvent(event: MemberEvent | PowerLevelEvent): Promise<void> {
|
||||
await this.rooms.get(JSON.stringify([event.account, event.roomId]))?.event(event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { roomSchema } from '../../config/schema';
|
||||
import { memoryStores, message } from '../../test/fakes';
|
||||
import { recoverBinding, bindingKey, recoveryRooms } from './room-binding';
|
||||
|
||||
const id = '!' + 'A'.repeat(43);
|
||||
const admin = '@admin:example.org';
|
||||
const room = roomSchema.parse({ account: 'test', admins: [admin], roomId: id + ':example.org' });
|
||||
const msg = message('/config bind', admin, id);
|
||||
function fixture() {
|
||||
return { store: memoryStores()('bindings'), transport: { getJoinedRooms: jest.fn(async () => [id]),
|
||||
getPowerLevel: jest.fn(async () => 100), send: jest.fn(async () => '$event') } };
|
||||
}
|
||||
it('shows the recovery command before binding the event room and recording its actor', async () => {
|
||||
const { store, transport } = fixture();
|
||||
await recoverBinding(room, { ...msg, text: '!配置' }, store, transport);
|
||||
expect(await store.get(bindingKey(room))).toBeNull();
|
||||
expect(transport.send.mock.calls[0]).toContain(id);
|
||||
await recoverBinding(room, msg, store, transport);
|
||||
expect(await store.get(bindingKey(room))).toEqual({ id, actor: admin });
|
||||
});
|
||||
it('refuses unlisted senders, insufficient power and ambiguous joined rooms', async () => {
|
||||
const { transport, store } = fixture();
|
||||
await recoverBinding(room, { ...msg, userId: '@other:example.org' }, store, transport);
|
||||
transport.getPowerLevel.mockResolvedValueOnce(50);
|
||||
await recoverBinding(room, msg, store, transport);
|
||||
transport.getJoinedRooms.mockResolvedValueOnce([room.roomId, id]);
|
||||
await recoverBinding(room, msg, store, transport);
|
||||
await recoverBinding(room, { ...msg, text: '/config bind !other:example.org' }, store, transport);
|
||||
expect(await store.entries()).toEqual([]);
|
||||
expect(transport.send).not.toHaveBeenCalled();
|
||||
});
|
||||
it('excludes overlapping candidates and explicit routes from recovery', () => {
|
||||
expect(recoveryRooms([room], 'test').get(id)).toBe(room);
|
||||
expect(recoveryRooms([room, { ...room, roomId: id }], 'test').size).toBe(0);
|
||||
expect(recoveryRooms([room, { ...room, roomId: id + ':other.example.org' }], 'test').size).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { RoomConfig } from '../../config/schema';
|
||||
import { InboundMessage } from '../command/types';
|
||||
import { translate } from '../i18n/i18n';
|
||||
import { Store } from './types';
|
||||
|
||||
// Handle the specific migration mistake without widening synchronization to all joined rooms.
|
||||
export function recoveryId(room: RoomConfig): string | undefined {
|
||||
if (!room.admins.length) return undefined;
|
||||
return /^(![A-Za-z0-9_-]{43}):/.exec(room.roomId)?.[1];
|
||||
}
|
||||
|
||||
export function recoveryRooms(rooms: RoomConfig[], account: string): Map<string, RoomConfig> {
|
||||
const withinAccount = rooms.filter((room) => room.account === account);
|
||||
const candidates = new Map<string, RoomConfig>();
|
||||
for (const room of withinAccount) {
|
||||
const id = recoveryId(room);
|
||||
if (!id || withinAccount.some((other) => other !== room && (other.roomId === id || other.roomId.startsWith(`${id}:`)))) continue;
|
||||
candidates.set(id, room);
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
export interface BindingTransport {
|
||||
getJoinedRooms(): Promise<string[]>;
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number>;
|
||||
send(roomId: string, text: string, eventId?: string): Promise<string>;
|
||||
}
|
||||
export const bindingKey = (room: RoomConfig) => JSON.stringify([room.account, room.roomId]);
|
||||
export async function recoverBinding(room: RoomConfig, msg: InboundMessage, store: Store, transport: BindingTransport): Promise<void> {
|
||||
if (room.account !== msg.account || recoveryId(room) !== msg.roomId || !room.admins.includes(msg.userId)) return;
|
||||
const match = /^[!!//](?:config|配置)(?:\s+(bind|绑定))?$/iu.exec(msg.text.trim());
|
||||
if (!match) return;
|
||||
const joined = await transport.getJoinedRooms();
|
||||
if (!joined.includes(msg.roomId) || joined.includes(room.roomId)) return;
|
||||
if (!(await transport.getPowerLevel(msg.roomId, msg.userId) >= room.adminPowerLevel)) return;
|
||||
if (match[1]) {
|
||||
await store.set(bindingKey(room), { id: msg.roomId, actor: msg.userId });
|
||||
await transport.send(msg.roomId, translate({ 'zh-CN': '已保存此房间 ID,服务下次启动时生效。', en: 'Room ID saved. It takes effect at the next service start.' }, room.locale), msg.eventId);
|
||||
} else {
|
||||
await transport.send(msg.roomId, translate({ 'zh-CN': '当前房间 {id} 与配置不一致。发送 !配置 绑定 保存当前房间,重启后生效。', en: 'Current room {id} differs from configuration. Send !config bind to use this room at the next start.' }, room.locale, { id: msg.roomId }), msg.eventId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { roomSchema } from '../../config/schema';
|
||||
import checkin from '../../plugins/checkin/checkin.plugin';
|
||||
import { FakeScheduler, FakeTransport, memoryStores, message } from '../../test/fakes';
|
||||
import { PluginContext, PluginDefinition } from './types';
|
||||
import { RoomRuntime, pluginScope } from './room-runtime';
|
||||
|
||||
const admin = '@admin:example.org';
|
||||
function setup(definitions: PluginDefinition[] = [checkin]) {
|
||||
const store = memoryStores(), transport = new FakeTransport(), scheduler = new FakeScheduler();
|
||||
const config = roomSchema.parse({ account: 'test', roomId: '!control:example.org' });
|
||||
const runtime = new RoomRuntime(config, definitions, transport, store, scheduler);
|
||||
return { runtime, config, transport, scheduler, store };
|
||||
}
|
||||
const stub = (create: PluginDefinition['create']): PluginDefinition => ({
|
||||
apiVersion: 1, id: 'sample', aliases: ['示例'], version: '1', description: { 'zh-CN': '示例', en: 'sample' }, validate: (c) => c, create,
|
||||
});
|
||||
|
||||
describe('room plugin lifecycle', () => {
|
||||
it.each(['!', '!'])('supports %s with Chinese and English host and plugin commands', async (prefix) => {
|
||||
const { runtime, transport } = setup();
|
||||
await runtime.start();
|
||||
await runtime.message(message(`${prefix}插件 启用 签到`, admin));
|
||||
expect(runtime.status()[0].state).toBe('enabled');
|
||||
await runtime.message(message(`${prefix}checkin`));
|
||||
expect(transport.sent.at(-1)?.text).toContain('签到成功');
|
||||
await runtime.message(message(`${prefix}签到`));
|
||||
expect(transport.sent.at(-1)?.text).toContain('已签到');
|
||||
for (const query of ['查询', 'list']) {
|
||||
await runtime.message(message(`${prefix}${query}`));
|
||||
expect(transport.sent.at(-1)?.text).toContain('本月 1 次');
|
||||
}
|
||||
for (const help of ['帮助', 'help']) {
|
||||
await runtime.message(message(`${prefix}${help}`));
|
||||
expect(transport.sent.at(-1)?.text).toContain('今日签到');
|
||||
}
|
||||
await runtime.message(message(`${prefix}plugin disable checkin`, admin));
|
||||
expect(runtime.status()[0].state).toBe('disabled');
|
||||
await runtime.stop();
|
||||
});
|
||||
it('keeps management commands available with all plugins disabled', async () => {
|
||||
const { runtime, transport } = setup(); await runtime.start();
|
||||
await runtime.message(message('/plugin list'));
|
||||
expect(transport.sent.at(-1)?.text).toContain('已停用');
|
||||
await runtime.message(message('/plugin enable checkin', admin));
|
||||
await runtime.message(message('签到'));
|
||||
expect(transport.sent.at(-1)?.text).toContain('签到成功');
|
||||
await runtime.stop();
|
||||
});
|
||||
it('rejects non-admin lifecycle commands and failed permission reads', async () => {
|
||||
const { runtime, transport } = setup(); await runtime.start();
|
||||
await runtime.message(message('!插件 启用 签到')); expect(runtime.status()[0].state).toBe('disabled');
|
||||
transport.powerFailures.add(admin);
|
||||
await runtime.message(message('!plugin enable checkin', admin));
|
||||
expect(runtime.status()[0].state).toBe('disabled'); expect(transport.sent.at(-1)?.text).toContain('无权限');
|
||||
});
|
||||
it('stops jobs, preserves data, restores disabled state and keeps bilingual aliases', async () => {
|
||||
const { runtime, config, store, transport, scheduler } = setup(); await runtime.start();
|
||||
await runtime.message(message('!插件 启用 签到', admin)); await runtime.message(message('/checkin'));
|
||||
expect(scheduler.jobs.size).toBe(1); expect(scheduler.zones).toEqual(['Asia/Shanghai']);
|
||||
await runtime.message(message('!plugin disable checkin', admin)); expect(scheduler.jobs.size).toBe(0);
|
||||
await runtime.message(message('!checkin')); expect(transport.sent.at(-1)?.text).toContain('未知');
|
||||
await runtime.stop();
|
||||
const restarted = new RoomRuntime(config, [checkin], transport, store, scheduler); await restarted.start();
|
||||
expect(restarted.status()[0].state).toBe('disabled');
|
||||
await restarted.message(message('!插件 启用 checkin', admin)); await restarted.message(message('签到'));
|
||||
expect(transport.sent.at(-1)?.text).toContain('已签到'); await restarted.stop();
|
||||
});
|
||||
it('persists reply language and shares all command handlers across languages', async () => {
|
||||
const { runtime, config, store, transport, scheduler } = setup(); await runtime.start();
|
||||
await runtime.message(message('!语言 英文', admin)); await runtime.message(message('!插件 启用 签到', admin));
|
||||
await runtime.message(message('签到')); expect(transport.sent.at(-1)?.text).toContain('Checked in'); await runtime.stop();
|
||||
const restarted = new RoomRuntime(config, [checkin], transport, store, scheduler); await restarted.start();
|
||||
await restarted.message(message('!帮助', admin)); expect(transport.sent.at(-1)?.text).toContain('Enable a plugin'); await restarted.stop();
|
||||
});
|
||||
it('isolates records by account and room and ignores messages outside its route', async () => {
|
||||
const { runtime, config, store, transport, scheduler } = setup(); await runtime.start();
|
||||
const otherConfig = { ...config, roomId: '!other:example.org' };
|
||||
const other = new RoomRuntime(otherConfig, [checkin], transport, store, scheduler); await other.start();
|
||||
await runtime.message(message('!plugin enable checkin', admin)); await runtime.message(message('签到'));
|
||||
await other.message(message('!plugin enable checkin', admin, otherConfig.roomId)); await other.message(message('签到', undefined, otherConfig.roomId));
|
||||
expect(transport.sent.at(-1)?.text).toContain('签到成功');
|
||||
const count = transport.sent.length; await runtime.message(message('!ping', admin, otherConfig.roomId)); expect(transport.sent).toHaveLength(count);
|
||||
expect(pluginScope('another', config.roomId, 'checkin')).not.toBe(pluginScope('test', config.roomId, 'checkin'));
|
||||
await runtime.stop(); await other.stop();
|
||||
});
|
||||
it('never executes retired reset/test/level commands', async () => {
|
||||
const { runtime, transport, store, config } = setup(); await runtime.start(); await runtime.message(message('!plugin enable checkin', admin));
|
||||
await runtime.message(message('签到'));
|
||||
const scope = store(pluginScope('test', config.roomId, 'checkin')); const before = await scope.entries();
|
||||
for (const text of ['!reset', '!test daily', '!test monthly', '!level super @member:example.org']) await runtime.message(message(text, admin));
|
||||
expect(await scope.entries()).toEqual(before); expect(transport.kicks).toHaveLength(0); await runtime.stop();
|
||||
});
|
||||
it('rolls back jobs after failed start and leaves core commands usable', async () => {
|
||||
const broken = stub((ctx) => ({ commands: [], start: async () => { ctx.schedule('job', '* * * * * *', async () => undefined); throw new Error('broken'); } }));
|
||||
const { runtime, scheduler, transport } = setup([broken]); await runtime.start();
|
||||
await runtime.message(message('!plugin enable sample', admin)); expect(scheduler.jobs.size).toBe(0); expect(runtime.status()[0].state).toBe('failed');
|
||||
await runtime.message(message('!ping')); expect(transport.sent.at(-1)?.text).toBe('pong');
|
||||
});
|
||||
it('rejects command collisions before running start hooks', async () => {
|
||||
const start = jest.fn();
|
||||
const duplicate = stub(() => ({ start, commands: [{ id: 'bad', paths: [['ping']], description: { 'zh-CN': '重复', en: 'duplicate' },
|
||||
usage: { 'zh-CN': '!ping', en: '!ping' }, run: async () => undefined }] }));
|
||||
const { runtime } = setup([duplicate]); await runtime.start(); await runtime.message(message('!plugin enable sample', admin));
|
||||
expect(start).not.toHaveBeenCalled(); expect(runtime.status()[0].state).toBe('failed');
|
||||
});
|
||||
it('serializes events with disable and revokes stale plugin capabilities', async () => {
|
||||
let context!: PluginContext; let release!: () => void; let entered!: () => void;
|
||||
const enteredPromise = new Promise<void>((resolve) => { entered = resolve; });
|
||||
const blocked = new Promise<void>((resolve) => { release = resolve; });
|
||||
const plugin = stub((ctx) => { context = ctx; return { commands: [], onMember: async () => { entered(); await blocked; await ctx.send('completed'); } }; });
|
||||
const { runtime, transport } = setup([plugin]); await runtime.start(); await runtime.message(message('!plugin enable sample', admin));
|
||||
const event = runtime.event({ account: 'test', roomId: '!control:example.org', userId: '@member:example.org', membership: 'join' });
|
||||
await enteredPromise;
|
||||
const disable = runtime.message(message('!plugin disable sample', admin));
|
||||
release(); await event; await disable;
|
||||
expect(transport.sent.some((s) => s.text === 'completed')).toBe(true);
|
||||
await expect(context.send('late')).rejects.toThrow('stopped');
|
||||
await expect(context.db.set('late', true)).rejects.toThrow('stopped');
|
||||
});
|
||||
it('enforces additional-room capabilities and protects its own account', async () => {
|
||||
let context!: PluginContext;
|
||||
const sample = stub((ctx) => { context = ctx; return { commands: [] }; });
|
||||
const { runtime, transport } = setup([sample]); await runtime.start(); await runtime.message(message('!plugin enable sample', admin));
|
||||
await expect(context.kick('!outside:example.org', '@member:example.org', 'test')).rejects.toThrow('scope');
|
||||
await expect(context.kick(context.roomId, transport.userId, 'test')).rejects.toThrow('own account');
|
||||
await expect(context.invite(context.roomId, transport.userId)).rejects.toThrow('own account');
|
||||
expect(transport.kicks).toHaveLength(0); expect(transport.invites).toHaveLength(0); await runtime.stop();
|
||||
});
|
||||
it('coalesces overlapping scheduled ticks instead of queuing duplicate work', async () => {
|
||||
let release!: () => void; let enter!: () => void;
|
||||
const ready = new Promise<void>((resolve) => { enter = resolve; });
|
||||
const blocked = new Promise<void>((resolve) => { release = resolve; });
|
||||
const run = jest.fn(async () => { enter(); await blocked; });
|
||||
const sample = stub((ctx) => ({ commands: [], start: async () => { ctx.schedule('slow', '* * * * * *', run); } }));
|
||||
const { runtime, scheduler } = setup([sample]); await runtime.start(); await runtime.message(message('!plugin enable sample', admin));
|
||||
const first = scheduler.tick(); await ready; await scheduler.tick(); release(); await first;
|
||||
expect(run).toHaveBeenCalledTimes(1); await runtime.stop();
|
||||
});
|
||||
});
|
||||
|
||||
it('restricts config changes to administrators and restores report preferences after restart', async () => {
|
||||
const validate = jest.fn((options: Record<string, unknown>) => options);
|
||||
const def = { ...stub(() => ({ commands: [] })), id: 'checkin', validate };
|
||||
const { runtime, transport, config, store, scheduler } = setup([def]);
|
||||
await runtime.start();
|
||||
await runtime.message(message('/config reports off'));
|
||||
expect(transport.sent.at(-1)?.text).toContain('无权限');
|
||||
await runtime.message(message('!配置 报表 关', admin));
|
||||
await runtime.message(message('/config language en', admin));
|
||||
await runtime.stop();
|
||||
const restarted = new RoomRuntime(config, [def], transport, store, scheduler);
|
||||
await restarted.start();
|
||||
await restarted.message(message('/config', admin));
|
||||
expect(transport.sent.at(-1)?.text).toContain(`Current room ${config.roomId}`);
|
||||
await restarted.message(message('/plugin enable checkin', admin));
|
||||
expect(validate).toHaveBeenCalledWith({ reportsEnabled: false });
|
||||
await restarted.stop();
|
||||
});
|
||||
@@ -0,0 +1,323 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { ZodError } from 'zod';
|
||||
import { RoomConfig } from '../../config/schema';
|
||||
import { Command, CommandRouter, Invocation } from '../command/command-router';
|
||||
import { CommandError } from '../command/command-parser';
|
||||
import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types';
|
||||
import { choice, common, Locale, Text, translate } from '../i18n/i18n';
|
||||
import { MatrixTransport } from '../matrix/types';
|
||||
import { Plugin, PluginContext, PluginDefinition, Store } from './types';
|
||||
import { SerialQueue } from './serial-queue';
|
||||
import { Scheduler } from './scheduler';
|
||||
|
||||
interface Instance {
|
||||
definition: PluginDefinition; plugin?: Plugin; state: 'disabled' | 'enabled' | 'failed';
|
||||
lastError?: Text; controller: AbortController; disposers: Array<() => void>;
|
||||
}
|
||||
export const pluginScope = (account: string, room: string, id: string) => JSON.stringify(['plugin-v2', account, room, id]);
|
||||
const texts = {
|
||||
help: { 'zh-CN': '帮助', en: 'Help' },
|
||||
ping: { 'zh-CN': '检查响应', en: 'Check responsiveness' },
|
||||
echo: { 'zh-CN': '复述文本', en: 'Echo text' },
|
||||
list: { 'zh-CN': '列出插件和运行状态', en: 'List plugins and runtime status' },
|
||||
enable: { 'zh-CN': '启用当前房间的插件', en: 'Enable a plugin in this room' },
|
||||
disable: { 'zh-CN': '停用当前房间的插件,保留数据', en: 'Disable a plugin in this room, retaining data' },
|
||||
language: { 'zh-CN': '设置房间回复语言', en: 'Set room reply language' },
|
||||
audit: { 'zh-CN': '查看最近管理操作', en: 'View recent administrative actions' },
|
||||
changed: { 'zh-CN': '{plugin}:{state}', en: '{plugin}: {state}' },
|
||||
unknownPlugin: { 'zh-CN': '未安装该插件,请先查看 !插件 列表。', en: 'Plugin not installed. See !plugin list.' },
|
||||
languageSet: { 'zh-CN': '回复语言已设为中文。', en: 'Reply language set to English.' },
|
||||
enabled: { 'zh-CN': '已启用', en: 'enabled' },
|
||||
disabled: { 'zh-CN': '已停用', en: 'disabled' },
|
||||
failed: { 'zh-CN': '启动失败', en: 'failed to start' },
|
||||
lastError: { 'zh-CN': '最近错误:{error}', en: 'Last error: {error}' },
|
||||
} satisfies Record<string, Text>;
|
||||
|
||||
export class RoomRuntime {
|
||||
private readonly logger = new Logger(RoomRuntime.name);
|
||||
private readonly queue = new SerialQueue();
|
||||
private readonly instances = new Map<string, Instance>();
|
||||
private readonly system: Store;
|
||||
private locale: Locale;
|
||||
private ready = false;
|
||||
private stopped = false;
|
||||
private readonly coreController = new AbortController();
|
||||
|
||||
constructor(readonly config: RoomConfig, private readonly definitions: PluginDefinition[],
|
||||
private readonly transport: MatrixTransport, private readonly store: (scope: string) => Store,
|
||||
private readonly scheduler: Scheduler, private readonly now: () => Date = () => new Date(),
|
||||
private readonly storageRoomId = config.roomId) {
|
||||
this.locale = config.locale;
|
||||
this.system = store(pluginScope(config.account, storageRoomId, '$system'));
|
||||
for (const definition of definitions) this.instances.set(definition.id,
|
||||
{ definition, state: 'disabled', controller: new AbortController(), disposers: [] });
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
await this.queue.run(async () => {
|
||||
const savedLocale = await this.system.get<string>('locale');
|
||||
this.locale = savedLocale === 'en' || savedLocale === 'zh-CN' ? savedLocale : this.config.locale;
|
||||
for (const id of Object.keys(this.config.plugins)) {
|
||||
if (!this.instances.has(id)) throw new Error(`Configured plugin is not installed: ${id}`);
|
||||
}
|
||||
for (const [id] of this.instances) {
|
||||
const saved = await this.system.get<boolean>(`enabled:${id}`);
|
||||
if (saved ?? this.config.plugins[id]?.enabled ?? false) {
|
||||
try { await this.enable(id); } catch { /* Failed plugins remain visible and can be retried. */ }
|
||||
}
|
||||
}
|
||||
this.ready = true;
|
||||
});
|
||||
}
|
||||
|
||||
status() {
|
||||
return [...this.instances].map(([id, i]) => ({ id, state: i.state, lastError: i.lastError, version: i.definition.version }));
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopped = true;
|
||||
await this.queue.run(async () => {
|
||||
this.ready = false;
|
||||
for (const instance of this.instances.values()) {
|
||||
try { await this.dispose(instance); }
|
||||
catch { await this.audit('plugin.stop.failed', 'system', { plugin: instance.definition.id }); }
|
||||
}
|
||||
this.coreController.abort();
|
||||
});
|
||||
}
|
||||
|
||||
private async dispose(instance: Instance): Promise<void> {
|
||||
instance.controller.abort();
|
||||
instance.disposers.splice(0).forEach((dispose) => dispose());
|
||||
try { await instance.plugin?.stop?.(); }
|
||||
finally { instance.plugin = undefined; instance.state = 'disabled'; }
|
||||
}
|
||||
|
||||
private async enable(id: string): Promise<void> {
|
||||
const instance = this.instances.get(id)!;
|
||||
if (instance.state === 'enabled') return;
|
||||
instance.controller = new AbortController();
|
||||
const configured = this.config.plugins[id]?.config ?? {};
|
||||
const reportOverride = id === 'checkin' ? await this.system.get<boolean>('config:reports') : null;
|
||||
const configuration = reportOverride === null ? configured : { ...configured, reportsEnabled: reportOverride };
|
||||
try {
|
||||
const parsed = instance.definition.validate(configuration);
|
||||
const context = this.context(id, instance, instance.definition.allowedRooms?.(parsed));
|
||||
for (const [key] of await context.db.entries()) if (key.startsWith('pending:')) await context.db.remove(key);
|
||||
instance.plugin = instance.definition.create(context, parsed);
|
||||
// Validate aliases before starting any jobs or initialization hooks.
|
||||
new CommandRouter([...this.commands(), ...instance.plugin.commands]);
|
||||
instance.state = 'enabled';
|
||||
await instance.plugin.start?.();
|
||||
await this.system.set(`enabled:${id}`, true);
|
||||
instance.lastError = undefined;
|
||||
} catch (error) {
|
||||
await this.dispose(instance).catch(() => undefined);
|
||||
instance.state = 'failed';
|
||||
const fields = error instanceof ZodError ? error.issues.map((issue) => issue.path.join('.') || 'config').join(', ') : '';
|
||||
instance.lastError = fields
|
||||
? { 'zh-CN': `配置项无效:${fields}`, en: `Invalid configuration fields: ${fields}` }
|
||||
: { 'zh-CN': '插件初始化失败,请检查配置或命令冲突。', en: 'Plugin initialization failed; check configuration or command collisions.' };
|
||||
this.logger.error(`Plugin initialization failed: ${id}${fields ? ` (${fields})` : ''}`);
|
||||
await this.audit('plugin.enable.failed', 'system', { plugin: id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async disable(id: string): Promise<void> {
|
||||
// Persist intent first, so a failed stop hook cannot re-enable the plugin on restart.
|
||||
await this.system.set(`enabled:${id}`, false);
|
||||
await this.dispose(this.instances.get(id)!);
|
||||
}
|
||||
|
||||
private async isAdmin(userId: string): Promise<boolean> {
|
||||
if (this.config.admins.includes(userId)) return true;
|
||||
try { return await this.transport.getPowerLevel(this.config.roomId, userId) >= this.config.adminPowerLevel; }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private async audit(action: string, actor: string, details: Record<string, unknown>): Promise<void> {
|
||||
await this.system.set(`audit:${this.now().toISOString()}:${randomUUID()}`, { at: this.now().toISOString(), action, actor, details });
|
||||
const entries = (await this.system.entries()).filter(([key]) => key.startsWith('audit:')).sort(([a], [b]) => b.localeCompare(a));
|
||||
for (const [key] of entries.slice(200)) await this.system.remove(key);
|
||||
}
|
||||
|
||||
private context(id: string, instance?: Instance, additionalRooms: string[] = []): PluginContext {
|
||||
const runtime = this;
|
||||
const allowed = new Set([this.config.roomId, ...additionalRooms]);
|
||||
const signal = (instance?.controller ?? this.coreController).signal;
|
||||
const check = (roomId = this.config.roomId) => {
|
||||
if (signal.aborted || this.stopped) throw new Error('Plugin stopped');
|
||||
if (!allowed.has(roomId)) throw new Error('Room outside plugin scope');
|
||||
};
|
||||
const storage = this.store(pluginScope(this.config.account, this.storageRoomId, id));
|
||||
const scopedStore: Store = {
|
||||
get: async (key) => { check(); return storage.get(key); },
|
||||
set: async (key, value) => { check(); await storage.set(key, value); },
|
||||
create: async (key, value) => { check(); return storage.create(key, value); },
|
||||
remove: async (key) => { check(); await storage.remove(key); },
|
||||
entries: async () => { check(); return storage.entries(); },
|
||||
};
|
||||
return {
|
||||
account: this.config.account, botUserId: this.transport.userId, roomId: this.config.roomId, timeZone: this.config.timeZone, adminPowerLevel: this.config.adminPowerLevel,
|
||||
get locale() { return runtime.locale; }, signal,
|
||||
db: scopedStore, now: this.now,
|
||||
t: (text, values) => translate(text, this.locale, values),
|
||||
send: async (text) => { check(); return this.transport.send(this.config.roomId, text); },
|
||||
reply: async (msg, text) => {
|
||||
check();
|
||||
if (msg.account !== this.config.account || msg.roomId !== this.config.roomId) throw new Error('Reply outside plugin scope');
|
||||
return this.transport.send(this.config.roomId, text, msg.eventId);
|
||||
},
|
||||
isAdmin: async (userId) => { check(); return this.isAdmin(userId); },
|
||||
members: async (roomId = this.config.roomId) => { check(roomId); return this.transport.getJoinedMembers(roomId); },
|
||||
power: async (userId) => { check(); return this.transport.getPowerLevel(this.config.roomId, userId); },
|
||||
kick: async (roomId, userId, reason) => {
|
||||
check(roomId); if (userId === this.transport.userId) throw new Error('Cannot remove own account');
|
||||
await this.transport.kick(roomId, userId, reason);
|
||||
},
|
||||
invite: async (roomId, userId) => {
|
||||
check(roomId); if (userId === this.transport.userId) throw new Error('Cannot invite own account');
|
||||
await this.transport.invite(roomId, userId);
|
||||
},
|
||||
schedule: (name, cron, run) => {
|
||||
if (!instance) throw new Error('Missing plugin instance');
|
||||
check();
|
||||
let pending = false;
|
||||
const dispose = this.scheduler.register(cron, this.config.timeZone, async () => {
|
||||
if (pending) return;
|
||||
pending = true;
|
||||
try {
|
||||
await this.queue.run(async () => {
|
||||
if (!this.ready || this.stopped || instance.state !== 'enabled' || signal.aborted) return;
|
||||
try { await run(); } catch {
|
||||
instance.lastError = { 'zh-CN': `定时任务失败:${name}`, en: `Scheduled task failed: ${name}` };
|
||||
await this.audit('plugin.task.failed', 'system', { plugin: id, task: name });
|
||||
}
|
||||
});
|
||||
} finally { pending = false; }
|
||||
});
|
||||
instance.disposers.push(dispose);
|
||||
},
|
||||
audit: async (action, actor, details) => { check(); await this.audit(action, actor, { ...details, plugin: id }); },
|
||||
};
|
||||
}
|
||||
|
||||
private coreCommands(): Command[] {
|
||||
const ctx = this.context('$core');
|
||||
const reply = async (inv: Invocation, text: string) => { await ctx.reply(inv.message, text); };
|
||||
const usage = (inv: Invocation, id: string) => reply(inv, ctx.t(common.usage, {
|
||||
usage: ctx.t(this.coreCommands().find((command) => command.id === id)!.usage),
|
||||
}));
|
||||
const toggle = (enabled: boolean) => async (inv: Invocation) => {
|
||||
if (inv.args.length !== 1) return usage(inv, enabled ? 'plugin.enable' : 'plugin.disable');
|
||||
const name = inv.args[0].normalize('NFKC').toLowerCase();
|
||||
const definition = this.definitions.find((d) => [d.id, ...(d.aliases ?? [])].some((a) => a.toLowerCase() === name));
|
||||
if (!definition) return reply(inv, ctx.t(texts.unknownPlugin));
|
||||
await this.audit(enabled ? 'plugin.enable.requested' : 'plugin.disable.requested', inv.message.userId, { plugin: definition.id });
|
||||
if (enabled) await this.enable(definition.id); else await this.disable(definition.id);
|
||||
await reply(inv, ctx.t(texts.changed, { plugin: definition.id, state: ctx.t(enabled ? texts.enabled : texts.disabled) }));
|
||||
};
|
||||
return [
|
||||
{ id: 'config', paths: [['config'], ['配置']], admin: true,
|
||||
description: { 'zh-CN': '查看当前房间配置', en: 'Show current room settings' },
|
||||
usage: { 'zh-CN': '!配置', en: '!config' }, run: async (inv) => {
|
||||
const reports = await this.system.get<boolean>('config:reports') ?? this.config.plugins.checkin?.config.reportsEnabled ?? true;
|
||||
await reply(inv, ctx.t({
|
||||
'zh-CN': '当前房间 {room}\n语言 {locale},时区 {zone},自动报表 {reports}(下次启用签到时使用)\n!配置 语言 中文|英文\n!配置 报表 开|关',
|
||||
en: 'Current room {room}\nLanguage {locale}, timezone {zone}, scheduled reports {reports} (at next check-in activation)\n!config language zh-CN|en\n!config reports on|off',
|
||||
}, { room: ctx.roomId, locale: ctx.locale, zone: ctx.timeZone, reports: ctx.t(reports ? texts.enabled : texts.disabled) }));
|
||||
} },
|
||||
{ id: 'config.bind', paths: [['config', 'bind'], ['配置', '绑定']], admin: true,
|
||||
description: { 'zh-CN': '核对当前房间绑定', en: 'Check current room binding' },
|
||||
usage: { 'zh-CN': '!配置 绑定', en: '!config bind' }, run: async (inv) => {
|
||||
await reply(inv, ctx.t({ 'zh-CN': '当前房间 {room} 已绑定。', en: 'Room {room} is already bound.' }, { room: ctx.roomId }));
|
||||
} },
|
||||
{ id: 'config.reports', paths: [['config', 'reports'], ['配置', '报表']], admin: true,
|
||||
description: { 'zh-CN': '设置签到定时报表', en: 'Configure scheduled check-in reports' },
|
||||
usage: { 'zh-CN': '!配置 报表 开|关', en: '!config reports on|off' }, run: async (inv) => {
|
||||
const state = choice(inv.args[0], { on: ['开'], off: ['关'] });
|
||||
if (!state || inv.args.length !== 1) return usage(inv, 'config.reports');
|
||||
await this.system.set('config:reports', state === 'on');
|
||||
await this.audit('config.reports', inv.message.userId, { state });
|
||||
await reply(inv, ctx.t({ 'zh-CN': '已保存,签到插件下次启动时生效。', en: 'Saved for the next check-in plugin start.' }));
|
||||
} },
|
||||
{ id: 'help', paths: [['help'], ['帮助']], bare: ['帮助'], description: texts.help,
|
||||
usage: { 'zh-CN': '!帮助', en: '!help' }, run: async (inv) => {
|
||||
const admin = await this.isAdmin(inv.message.userId);
|
||||
await reply(inv, this.commands().filter((c) => !c.admin || admin).map((c) =>
|
||||
`${ctx.t(c.usage)} — ${ctx.t(c.description)}`).join('\n'));
|
||||
} },
|
||||
{ id: 'ping', paths: [['ping'], ['在线']], description: texts.ping, usage: { 'zh-CN': '!在线', en: '!ping' }, run: (inv) => reply(inv, 'pong') },
|
||||
{ id: 'echo', paths: [['echo'], ['复述']], description: texts.echo, usage: { 'zh-CN': '!复述 <文本>', en: '!echo <text>' }, run: (inv) => reply(inv, inv.args.join(' ') || '…') },
|
||||
{ id: 'plugin.list', paths: [['plugin', 'list'], ['插件', '列表'], ['plugin', 'status'], ['插件', '状态']], description: texts.list,
|
||||
usage: { 'zh-CN': '!插件 列表', en: '!plugin list' }, run: async (inv) => {
|
||||
const admin = await this.isAdmin(inv.message.userId);
|
||||
await reply(inv, this.status().map((s) => `${s.id} ${s.version}: ${ctx.t(texts[s.state])}${admin && s.lastError ? `\n${ctx.t(texts.lastError, { error: ctx.t(s.lastError) })}` : ''}`).join('\n'));
|
||||
} },
|
||||
{ id: 'plugin.enable', paths: [['plugin', 'enable'], ['插件', '启用'], ['plugin', '启用'], ['插件', 'enable']], admin: true,
|
||||
description: texts.enable, usage: { 'zh-CN': '!插件 启用 <名称>', en: '!plugin enable <name>' }, run: toggle(true) },
|
||||
{ id: 'plugin.disable', paths: [['plugin', 'disable'], ['插件', '停用'], ['插件', '禁用'], ['plugin', '停用'], ['插件', 'disable']], admin: true,
|
||||
description: texts.disable, usage: { 'zh-CN': '!插件 停用 <名称>', en: '!plugin disable <name>' }, run: toggle(false) },
|
||||
{ id: 'language', paths: [['language'], ['语言'], ['config', 'language'], ['配置', '语言']], admin: true, description: texts.language,
|
||||
usage: { 'zh-CN': '!语言 中文|英文', en: '!language zh-CN|en' }, run: async (inv) => {
|
||||
const locale = choice(inv.args[0], { 'zh-CN': ['中文', 'zh'], en: ['英文', 'english'] });
|
||||
if (!locale || inv.args.length !== 1) return usage(inv, 'language');
|
||||
await this.system.set('locale', locale); this.locale = locale;
|
||||
await this.audit('language.set', inv.message.userId, { locale });
|
||||
await reply(inv, ctx.t(texts.languageSet));
|
||||
} },
|
||||
{ id: 'audit', paths: [['audit'], ['操作记录']], admin: true, description: texts.audit,
|
||||
usage: { 'zh-CN': '!操作记录', en: '!audit' }, run: async (inv) => {
|
||||
const rows = (await this.system.entries()).filter(([key]) => key.startsWith('audit:')).sort(([a], [b]) => b.localeCompare(a)).slice(0, 10);
|
||||
await reply(inv, rows.length ? rows.map(([, row]) => JSON.stringify(row)).join('\n') : ctx.t(common.empty));
|
||||
} },
|
||||
{ id: 'retired', paths: [['reset'], ['test'], ['level'], ['重置']], description: common.removed,
|
||||
usage: { 'zh-CN': '旧命令已停用', en: 'Legacy commands retired' }, run: (inv) => reply(inv, ctx.t(common.removed)) },
|
||||
];
|
||||
}
|
||||
|
||||
private commands(): Command[] {
|
||||
return [...this.coreCommands(), ...[...this.instances.values()].filter((i) => i.state === 'enabled').flatMap((i) => i.plugin?.commands ?? [])];
|
||||
}
|
||||
|
||||
async message(message: InboundMessage): Promise<void> {
|
||||
if (!this.ready || this.stopped || message.account !== this.config.account || message.roomId !== this.config.roomId) return;
|
||||
await this.queue.run(async () => {
|
||||
if (this.stopped) return;
|
||||
const ctx = this.context('$core');
|
||||
try {
|
||||
const matched = new CommandRouter(this.commands()).match(message);
|
||||
if (!matched) {
|
||||
if (/^[!!//]/.test(message.text.trim())) await ctx.reply(message, ctx.t(common.unknown));
|
||||
return;
|
||||
}
|
||||
if (matched.command.admin && !await this.isAdmin(message.userId)) {
|
||||
await ctx.reply(message, ctx.t(common.denied)); return;
|
||||
}
|
||||
await matched.command.run(matched.invocation);
|
||||
} catch (error) {
|
||||
await this.audit('command.failed', message.userId, { kind: error instanceof CommandError ? 'syntax' : 'execution' });
|
||||
await ctx.reply(message, ctx.t(common.failed)).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async event(event: MemberEvent | PowerLevelEvent): Promise<void> {
|
||||
if (!this.ready || this.stopped || event.account !== this.config.account || event.roomId !== this.config.roomId) return;
|
||||
await this.queue.run(async () => {
|
||||
if (this.stopped) return;
|
||||
for (const [id, instance] of this.instances) {
|
||||
if (instance.state !== 'enabled') continue;
|
||||
try {
|
||||
if ('membership' in event) await instance.plugin?.onMember?.(event);
|
||||
else await instance.plugin?.onPowerLevel?.(event);
|
||||
} catch {
|
||||
instance.lastError = { 'zh-CN': '事件处理失败', en: 'Event handler failed' };
|
||||
await this.audit('plugin.event.failed', 'system', { plugin: id });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { CronJob } from 'cron';
|
||||
|
||||
export interface Scheduler {
|
||||
register(cron: string, timeZone: string, run: () => Promise<void>): () => void;
|
||||
}
|
||||
export class PluginScheduler implements Scheduler {
|
||||
register(cron: string, timeZone: string, run: () => Promise<void>): () => void {
|
||||
const job = new CronJob(cron, () => { void run().catch(() => undefined); }, null, true, timeZone);
|
||||
return () => job.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export class SerialQueue {
|
||||
private tail: Promise<unknown> = Promise.resolve();
|
||||
run<T>(task: () => Promise<T>): Promise<T> {
|
||||
const result = this.tail.then(task);
|
||||
this.tail = result.catch(() => undefined);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Command } from '../command/command-router';
|
||||
import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types';
|
||||
import { Locale, Text } from '../i18n/i18n';
|
||||
|
||||
export interface Store {
|
||||
get<T>(key: string): Promise<T | null>;
|
||||
set<T>(key: string, value: T): Promise<void>;
|
||||
create<T>(key: string, value: T): Promise<boolean>;
|
||||
remove(key: string): Promise<void>;
|
||||
entries<T>(): Promise<Array<[string, T]>>;
|
||||
}
|
||||
export interface PluginContext {
|
||||
readonly account: string;
|
||||
readonly botUserId: string;
|
||||
readonly roomId: string;
|
||||
readonly timeZone: string;
|
||||
readonly adminPowerLevel: number;
|
||||
readonly locale: Locale;
|
||||
readonly signal: AbortSignal;
|
||||
readonly db: Store;
|
||||
now(): Date;
|
||||
t(text: Text, values?: Record<string, unknown>): string;
|
||||
send(text: string): Promise<string>;
|
||||
reply(message: InboundMessage, text: string): Promise<string>;
|
||||
isAdmin(userId: string): Promise<boolean>;
|
||||
members(roomId?: string): Promise<string[]>;
|
||||
power(userId: string): Promise<number>;
|
||||
kick(roomId: string, userId: string, reason: string): Promise<void>;
|
||||
invite(roomId: string, userId: string): Promise<void>;
|
||||
schedule(name: string, cron: string, run: () => Promise<void>): void;
|
||||
audit(action: string, actor: string, details: Record<string, unknown>): Promise<void>;
|
||||
}
|
||||
export interface Plugin {
|
||||
commands: Command[];
|
||||
start?(): Promise<void>;
|
||||
stop?(): Promise<void>;
|
||||
onMember?(event: MemberEvent): Promise<void>;
|
||||
onPowerLevel?(event: PowerLevelEvent): Promise<void>;
|
||||
}
|
||||
export interface PluginDefinition {
|
||||
apiVersion: 1;
|
||||
id: string;
|
||||
aliases?: string[];
|
||||
version: string;
|
||||
description: Text;
|
||||
validate(config: Record<string, unknown>): Record<string, unknown>;
|
||||
allowedRooms?(config: Record<string, unknown>): string[];
|
||||
create(context: PluginContext, config: Record<string, unknown>): Plugin;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import { CronJob } from 'cron';
|
||||
import { CronSpec } from '../command/types';
|
||||
|
||||
/**
|
||||
* 简单的 cron 注册器,封装 cron 库。
|
||||
* bot 通过 registerCrons() 返回 CronSpec,由平台批量注册到此处。
|
||||
*/
|
||||
@Injectable()
|
||||
export class SchedulerService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(SchedulerService.name);
|
||||
private readonly jobs: CronJob[] = [];
|
||||
|
||||
register(botName: string, spec: CronSpec): void {
|
||||
const job = new CronJob(spec.cron, () => {
|
||||
void this.runSafely(botName, spec);
|
||||
});
|
||||
job.start();
|
||||
this.jobs.push(job);
|
||||
this.logger.log(
|
||||
`已注册定时任务 [${botName}] ${spec.name ?? ''} cron="${spec.cron}"`,
|
||||
);
|
||||
}
|
||||
|
||||
private async runSafely(botName: string, spec: CronSpec): Promise<void> {
|
||||
try {
|
||||
await spec.run();
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`定时任务失败 [${botName}] ${spec.name ?? ''}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
for (const job of this.jobs) {
|
||||
job.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { testDatabase } from '../../test/database';
|
||||
import { FakeContext, message } from '../../test/fakes';
|
||||
import { BotStore } from '../../core/db/bot-store';
|
||||
import { pluginScope } from '../../core/plugin/room-runtime';
|
||||
import { CheckinPlugin, checkinConfig } from './checkin.plugin';
|
||||
import { CommandRouter } from '../../core/command/command-router';
|
||||
import { migrateCheckin } from '../../core/plugin/migrate-checkin';
|
||||
import { rootConfigSchema } from '../../config/schema';
|
||||
|
||||
let database: Awaited<ReturnType<typeof testDatabase>> | undefined;
|
||||
beforeAll(async () => { database = await testDatabase(); });
|
||||
afterAll(async () => { await database?.close(); });
|
||||
afterEach(async () => { await database?.prisma.botState.deleteMany(); });
|
||||
const roomId = '!control:example.org';
|
||||
const user = '@member:example.org';
|
||||
const config = () => rootConfigSchema.parse({ accounts: { test: { userId: '@bot:example.org', password: 'fixture', homeServer: 'https://example.org' } },
|
||||
rooms: [{ account: 'test', roomId, plugins: { checkin: { enabled: true } } }], legacyCheckinTarget: { account: 'test', roomId } });
|
||||
function plugin(room = roomId, account = 'test') {
|
||||
const ctx = new FakeContext(new BotStore(database!.prisma, pluginScope(account, room, 'checkin')));
|
||||
const bot = new CheckinPlugin(ctx, checkinConfig.parse({}));
|
||||
const router = new CommandRouter(bot.commands);
|
||||
return { ctx, bot, run: async (text: string, actor = user) => {
|
||||
const match = router.match(message(text, actor))!; await match.command.run(match.invocation);
|
||||
} };
|
||||
}
|
||||
|
||||
describe('check-in with isolated SQLite', () => {
|
||||
it('enforces unique user/date records across concurrent plugin instances', async () => {
|
||||
const a = plugin(), b = plugin();
|
||||
await Promise.all([a.run('签到'), b.run('!checkin'), a.run('!签到')]);
|
||||
expect(await a.bot.records()).toHaveLength(1);
|
||||
expect((await b.bot.stats()).get(user)?.total).toBe(1);
|
||||
});
|
||||
it('keeps room and account data separate in the same database', async () => {
|
||||
const a = plugin(), b = plugin('!second:example.org'), c = plugin(roomId, 'second-account');
|
||||
await a.run('签到'); await b.run('签到');
|
||||
expect((await a.bot.stats()).get(user)?.total).toBe(1);
|
||||
expect((await b.bot.stats()).get(user)?.total).toBe(1);
|
||||
expect((await c.bot.stats()).size).toBe(0);
|
||||
});
|
||||
it('uses native room permissions for administration instead of removed level commands', async () => {
|
||||
const a = plugin(); await a.run('签到');
|
||||
await a.run('!查询 全部', '@member:example.org'); expect(a.ctx.transport.sent.at(-1)?.text).toContain('无权限');
|
||||
await a.run('!查询 全部 --原始', '@admin:example.org'); expect(JSON.parse(a.ctx.transport.sent.at(-1)!.text)[0].total).toBe(1);
|
||||
});
|
||||
it('migrates legacy data once, preserves source and avoids counting today twice', async () => {
|
||||
const legacy = new BotStore(database!.prisma, 'checkin');
|
||||
await legacy.set(user, { checkinTimesInMonth: 8, checkinUnixMs: Date.parse('2026-01-15T01:00:00Z'), isCheckinToday: true });
|
||||
await migrateCheckin(database!.prisma, config()); await migrateCheckin(database!.prisma, config());
|
||||
const a = plugin(); await a.run('签到');
|
||||
expect((await a.bot.stats()).get(user)).toMatchObject({ total: 8, month: 8, today: true });
|
||||
expect(await legacy.get(user)).not.toBeNull();
|
||||
a.ctx.date = new Date('2026-02-01T01:00:00Z'); await a.run('签到');
|
||||
expect((await a.bot.stats()).get(user)).toMatchObject({ total: 9, month: 1 });
|
||||
});
|
||||
it('refuses ambiguous targets, existing destination data and reassignment', async () => {
|
||||
const legacy = new BotStore(database!.prisma, 'checkin');
|
||||
await legacy.set(user, { checkinTimesInMonth: 1, checkinUnixMs: Date.parse('2026-01-15T01:00:00Z') });
|
||||
await expect(migrateCheckin(database!.prisma, { ...config(), legacyCheckinTarget: undefined })).rejects.toThrow('explicit');
|
||||
const a = plugin(); await a.run('签到');
|
||||
await expect(migrateCheckin(database!.prisma, config())).rejects.toThrow('already contains');
|
||||
await database!.prisma.botState.deleteMany({ where: { botName: pluginScope('test', roomId, 'checkin') } });
|
||||
await migrateCheckin(database!.prisma, config());
|
||||
const other = config(); other.rooms[0].roomId = '!second:example.org'; other.legacyCheckinTarget!.roomId = '!second:example.org';
|
||||
await expect(migrateCheckin(database!.prisma, other)).rejects.toThrow('another room');
|
||||
});
|
||||
it('rolls back the whole migration when a legacy record is invalid', async () => {
|
||||
const legacy = new BotStore(database!.prisma, 'checkin');
|
||||
await legacy.set(user, { checkinTimesInMonth: 1, checkinUnixMs: Date.parse('2026-01-15T01:00:00Z') });
|
||||
await legacy.set('@invalid:example.org', { checkinTimesInMonth: -1 });
|
||||
await expect(migrateCheckin(database!.prisma, config())).rejects.toThrow('Invalid');
|
||||
expect(await database!.prisma.botState.count({ where: { botName: pluginScope('test', roomId, 'checkin') } })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
import { z } from 'zod';
|
||||
import { Command, Invocation } from '../../core/command/command-router';
|
||||
import { common, choice, Text } from '../../core/i18n/i18n';
|
||||
import { Plugin, PluginContext, PluginDefinition } from '../../core/plugin/types';
|
||||
import { Confirmations } from '../../core/plugin/confirmation';
|
||||
import { localDate, localMinutes, previousMonth, shiftDate, validDate } from '../../core/plugin/calendar';
|
||||
import { messages as m } from './messages';
|
||||
|
||||
export const checkinConfig = z.object({
|
||||
reportsEnabled: z.boolean().default(true),
|
||||
cleanupEnabled: z.boolean().default(false),
|
||||
autoCleanup: z.boolean().default(false),
|
||||
kickDays: z.number().int().min(1).default(30),
|
||||
whitelist: z.array(z.string().regex(/^@.+:.+$/)).default([]),
|
||||
}).refine((c) => !c.autoCleanup || c.cleanupEnabled, 'autoCleanup requires cleanupEnabled');
|
||||
type Config = z.infer<typeof checkinConfig>;
|
||||
export interface CheckinRecord { userId: string; date: string; at: number; counted?: boolean; }
|
||||
export interface LegacyBaseline { userId: string; count: number; month: string; lastAt: number; }
|
||||
interface Stats { userId: string; total: number; month: number; today: boolean; lastAt: number; }
|
||||
interface Periods { daily: string; monthly: string; cleanup: string; }
|
||||
const levels: Array<[number, Text]> = [
|
||||
[7, { 'zh-CN': '青铜', en: 'Bronze' }], [14, { 'zh-CN': '白银', en: 'Silver' }],
|
||||
[29, { 'zh-CN': '黄金', en: 'Gold' }], [44, { 'zh-CN': '铂金', en: 'Platinum' }],
|
||||
[Infinity, { 'zh-CN': '钻石', en: 'Diamond' }],
|
||||
];
|
||||
export const recordKey = (userId: string, date: string) => `day:${JSON.stringify([userId, date])}`;
|
||||
|
||||
export class CheckinPlugin implements Plugin {
|
||||
readonly commands: Command[];
|
||||
private readonly plans: Confirmations<string[]>;
|
||||
constructor(private readonly ctx: PluginContext, private readonly config: Config) {
|
||||
this.plans = new Confirmations(ctx, 'cleanup');
|
||||
this.commands = [
|
||||
{ id: 'checkin', paths: [['checkin'], ['签到']], bare: ['签到'], description: m.checkin,
|
||||
usage: { 'zh-CN': '!签到', en: '!checkin' }, run: (inv) => this.checkin(inv) },
|
||||
{ id: 'checkin.list', paths: [['list'], ['查询'], ['签到', '查询']], description: m.list,
|
||||
usage: { 'zh-CN': '!查询 [用户ID|全部] [--原始]', en: '!list [userId|all] [--raw]' }, run: (inv) => this.list(inv) },
|
||||
{ id: 'checkin.daily', paths: [['report', 'daily'], ['日报'], ['统计', '日报']], description: m.daily, admin: true,
|
||||
usage: { 'zh-CN': '!日报 [YYYY-MM-DD]', en: '!report daily [YYYY-MM-DD]' }, run: (inv) => this.daily(inv) },
|
||||
{ id: 'checkin.monthly', paths: [['report', 'monthly'], ['月报'], ['统计', '月报']], description: m.monthly, admin: true,
|
||||
usage: { 'zh-CN': '!月报 [YYYY-MM]', en: '!report monthly [YYYY-MM]' }, run: (inv) => this.monthly(inv) },
|
||||
{ id: 'checkin.cleanup.preview', paths: [['cleanup', 'preview'], ['清理', '预览']], description: m.cleanupPreview, admin: true,
|
||||
usage: { 'zh-CN': '!清理 预览', en: '!cleanup preview' }, run: (inv) => this.preview(inv) },
|
||||
{ id: 'checkin.cleanup.confirm', paths: [['cleanup', 'confirm'], ['清理', '确认']], description: m.cleanupConfirm, admin: true,
|
||||
usage: { 'zh-CN': '!清理 确认 <确认码>', en: '!cleanup confirm <token>' }, run: (inv) => this.confirm(inv) },
|
||||
];
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
await this.settle(false);
|
||||
this.ctx.schedule('period-reports', '0 * * * * *', () => this.settle(true));
|
||||
}
|
||||
|
||||
private today(): string { return localDate(this.ctx.now(), this.ctx.timeZone); }
|
||||
private async reply(inv: Invocation, text: string): Promise<void> { await this.ctx.reply(inv.message, text); }
|
||||
private usage(inv: Invocation, id: string): Promise<void> {
|
||||
return this.reply(inv, this.ctx.t(common.usage, { usage: this.ctx.t(this.commands.find((command) => command.id === id)!.usage) }));
|
||||
}
|
||||
private async admin(inv: Invocation): Promise<boolean> {
|
||||
if (await this.ctx.isAdmin(inv.message.userId)) return true;
|
||||
await this.reply(inv, this.ctx.t(common.denied)); return false;
|
||||
}
|
||||
|
||||
async records(): Promise<CheckinRecord[]> {
|
||||
return (await this.ctx.db.entries<CheckinRecord>()).filter(([key]) => key.startsWith('day:')).map(([, value]) => value);
|
||||
}
|
||||
async stats(month = this.today().slice(0, 7)): Promise<Map<string, Stats>> {
|
||||
const result = new Map<string, Stats>();
|
||||
const get = (id: string) => {
|
||||
if (!result.has(id)) result.set(id, { userId: id, total: 0, month: 0, today: false, lastAt: 0 });
|
||||
return result.get(id)!;
|
||||
};
|
||||
const baselines = (await this.ctx.db.entries<LegacyBaseline>()).filter(([key]) => key.startsWith('legacy:'));
|
||||
for (const [, base] of baselines) {
|
||||
const stat = get(base.userId);
|
||||
stat.total += base.count; stat.month += base.month === month ? base.count : 0;
|
||||
stat.lastAt = Math.max(stat.lastAt, base.lastAt);
|
||||
}
|
||||
for (const record of await this.records()) {
|
||||
const stat = get(record.userId);
|
||||
if (record.counted !== false) {
|
||||
stat.total++; if (record.date.startsWith(month)) stat.month++;
|
||||
}
|
||||
stat.today ||= record.date === this.today();
|
||||
stat.lastAt = Math.max(stat.lastAt, record.at);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private level(total: number): string { return this.ctx.t(levels.find(([max]) => total <= max)![1]); }
|
||||
private async checkin(inv: Invocation): Promise<void> {
|
||||
if (inv.args.length) return this.usage(inv, 'checkin');
|
||||
const date = this.today();
|
||||
const record = { userId: inv.message.userId, date, at: this.ctx.now().getTime() };
|
||||
const inserted = await this.ctx.db.create(recordKey(record.userId, date), record);
|
||||
if (!inserted) return this.reply(inv, this.ctx.t(m.duplicate, { date }));
|
||||
const stat = (await this.stats()).get(record.userId)!;
|
||||
await this.reply(inv, this.ctx.t(m.checked, { date, month: stat.month, total: stat.total, level: this.level(stat.total) }));
|
||||
}
|
||||
|
||||
private async list(inv: Invocation): Promise<void> {
|
||||
const target = inv.args[0] ?? inv.message.userId;
|
||||
const all = choice(target, { all: ['全部', '所有'] }) === 'all';
|
||||
if ((all || target !== inv.message.userId || inv.raw) && !await this.admin(inv)) return;
|
||||
if (inv.args.length > 1 || (!all && !/^@.+:.+$/.test(target))) {
|
||||
return this.usage(inv, 'checkin.list');
|
||||
}
|
||||
const stats = await this.stats();
|
||||
const rows = all ? [...stats.values()] : [stats.get(target)].filter((s): s is Stats => !!s);
|
||||
await this.reply(inv, !rows.length ? this.ctx.t(common.empty) : inv.raw ? JSON.stringify(rows, null, 2) :
|
||||
rows.map((stat) => this.ctx.t(m.row, { user: stat.userId, today: this.ctx.t(stat.today ? m.yes : m.no),
|
||||
month: stat.month, total: stat.total, level: this.level(stat.total) })).join('\n'));
|
||||
}
|
||||
|
||||
async dailyText(date: string): Promise<string> {
|
||||
const members = await this.ctx.members();
|
||||
const users = new Set((await this.records()).filter((r) => r.date === date).map((r) => r.userId));
|
||||
return this.ctx.t(m.reportDay, { date, count: users.size, members: members.length,
|
||||
missing: members.filter((id) => !users.has(id)).join('\n') || '—' });
|
||||
}
|
||||
async monthlyText(month: string): Promise<string> {
|
||||
const rows = [...(await this.stats(month)).values()].filter((s) => s.month > 0).sort((a, b) => b.month - a.month || a.userId.localeCompare(b.userId));
|
||||
return this.ctx.t(m.reportMonth, { month, rows: rows.map((s, index) => `${index + 1}. ${s.userId}: ${s.month}`).join('\n') || this.ctx.t(common.empty) });
|
||||
}
|
||||
private async daily(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
const date = inv.args[0] ?? this.today();
|
||||
if (inv.args.length > 1 || !validDate(date)) return this.usage(inv, 'checkin.daily');
|
||||
await this.reply(inv, await this.dailyText(date));
|
||||
}
|
||||
private async monthly(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
const month = inv.args[0] ?? this.today().slice(0, 7);
|
||||
if (inv.args.length > 1 || !validDate(`${month}-01`)) return this.usage(inv, 'checkin.monthly');
|
||||
await this.reply(inv, await this.monthlyText(month));
|
||||
}
|
||||
|
||||
async cleanupCandidates(): Promise<{ users: string[]; skipped: string[] }> {
|
||||
const members = await this.ctx.members();
|
||||
const stats = await this.stats();
|
||||
const users: string[] = [], skipped: string[] = [];
|
||||
for (const user of members) {
|
||||
if (user === this.ctx.botUserId) continue;
|
||||
const stat = stats.get(user);
|
||||
if (!stat?.lastAt || stat.today || this.config.whitelist.includes(user) ||
|
||||
this.ctx.now().getTime() - stat.lastAt < this.config.kickDays * 86_400_000) continue;
|
||||
try {
|
||||
// Read explicitly: a failed lookup must never be interpreted as a low power level.
|
||||
const power = await this.ctx.power(user);
|
||||
if (power >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(user)) continue;
|
||||
users.push(user);
|
||||
} catch { skipped.push(user); }
|
||||
}
|
||||
return { users, skipped };
|
||||
}
|
||||
private async preview(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
if (!this.config.cleanupEnabled) return this.reply(inv, this.ctx.t(m.disabled));
|
||||
if (inv.args.length) return this.usage(inv, 'checkin.cleanup.preview');
|
||||
const plan = await this.cleanupCandidates();
|
||||
const token = await this.plans.preview(inv.message.userId, plan.users);
|
||||
await this.reply(inv, this.ctx.t(common.preview, {
|
||||
details: [...plan.users, ...plan.skipped.map((user) => this.ctx.t(m.skipped, { user }))].join('\n') || this.ctx.t(common.empty),
|
||||
command: `!cleanup confirm ${token} / !清理 确认 ${token}`,
|
||||
}));
|
||||
}
|
||||
private async confirm(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
if (!this.config.cleanupEnabled) return this.reply(inv, this.ctx.t(m.disabled));
|
||||
const users = inv.args.length === 1 ? await this.plans.consume(inv.message.userId, inv.args[0]) : undefined;
|
||||
if (!users) return this.reply(inv, this.ctx.t(common.expired));
|
||||
await this.reply(inv, this.ctx.t(common.done, { details: await this.executeCleanup(users, inv.message.userId) }));
|
||||
}
|
||||
private async executeCleanup(planned: string[], actor: string): Promise<string> {
|
||||
const current = await this.cleanupCandidates();
|
||||
const results: string[] = [];
|
||||
for (const user of planned) {
|
||||
if (!current.users.includes(user)) { results.push(this.ctx.t(m.changed, { user })); continue; }
|
||||
try {
|
||||
// Recheck privilege immediately before each individual mutation.
|
||||
if (await this.ctx.power(user) >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(user)) {
|
||||
results.push(this.ctx.t(m.changed, { user })); continue;
|
||||
}
|
||||
await this.ctx.audit('cleanup.kick.requested', actor, { user });
|
||||
await this.ctx.kick(this.ctx.roomId, user, this.ctx.t(m.kickReason, { days: this.config.kickDays }));
|
||||
await this.ctx.audit('cleanup.kick.completed', actor, { user });
|
||||
results.push(this.ctx.t(m.kicked, { user }));
|
||||
} catch {
|
||||
await this.ctx.audit('cleanup.kick.failed', actor, { user });
|
||||
results.push(this.ctx.t(m.kickFailed, { user }));
|
||||
}
|
||||
}
|
||||
return results.join('\n') || this.ctx.t(common.empty);
|
||||
}
|
||||
|
||||
async settle(allowCleanup: boolean): Promise<void> {
|
||||
const date = this.today(), minutes = localMinutes(this.ctx.now(), this.ctx.timeZone);
|
||||
const daily = shiftDate(date, minutes >= 180 ? -1 : -2);
|
||||
const monthly = date.endsWith('-01') && minutes < 5 ? previousMonth(`${previousMonth(date)}-01`) : previousMonth(date);
|
||||
const saved = await this.ctx.db.get<Periods>('periods');
|
||||
if (!saved) { await this.ctx.db.set('periods', { daily, monthly, cleanup: date }); return; }
|
||||
if (saved.daily < daily) {
|
||||
if (this.config.reportsEnabled) {
|
||||
const prefix = shiftDate(saved.daily, 1) < daily ? this.ctx.t(m.catchup, { from: shiftDate(saved.daily, 1), to: daily }) + '\n' : '';
|
||||
await this.ctx.send(prefix + await this.dailyText(daily));
|
||||
}
|
||||
saved.daily = daily;
|
||||
await this.ctx.db.set('periods', saved);
|
||||
}
|
||||
if (saved.monthly < monthly) {
|
||||
if (this.config.reportsEnabled) await this.ctx.send(this.ctx.t(m.catchup, { from: saved.monthly, to: monthly }) + '\n' + await this.monthlyText(monthly));
|
||||
saved.monthly = monthly;
|
||||
await this.ctx.db.set('periods', saved);
|
||||
}
|
||||
if (allowCleanup && this.config.autoCleanup && saved.cleanup < date && minutes >= 180) {
|
||||
// Automatic cleanup is separate from reporting and never runs in the enable hook.
|
||||
const plan = await this.cleanupCandidates();
|
||||
const results: string[] = [];
|
||||
if (plan.users.length) results.push(await this.executeCleanup(plan.users, 'scheduler'));
|
||||
if (plan.skipped.length) {
|
||||
await this.ctx.audit('cleanup.lookup.failed', 'scheduler', { users: plan.skipped });
|
||||
results.push(...plan.skipped.map((user) => this.ctx.t(m.skipped, { user })));
|
||||
}
|
||||
if (results.length) await this.ctx.send(results.join('\n'));
|
||||
saved.cleanup = date;
|
||||
await this.ctx.db.set('periods', saved);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
apiVersion: 1, id: 'checkin', aliases: ['签到'], version: '2.0.0', description: m.description,
|
||||
validate: (config) => checkinConfig.parse(config),
|
||||
create: (ctx, config) => new CheckinPlugin(ctx, checkinConfig.parse(config)),
|
||||
} satisfies PluginDefinition;
|
||||
@@ -0,0 +1,133 @@
|
||||
import definition, { CheckinPlugin, checkinConfig, recordKey } from './checkin.plugin';
|
||||
import { CommandRouter } from '../../core/command/command-router';
|
||||
import { FakeContext, message } from '../../test/fakes';
|
||||
|
||||
function setup(config: Record<string, unknown> = {}) {
|
||||
const ctx = new FakeContext();
|
||||
const plugin = new CheckinPlugin(ctx, checkinConfig.parse(config));
|
||||
const router = new CommandRouter(plugin.commands);
|
||||
const run = async (text: string, user = '@member:example.org') => {
|
||||
const match = router.match(message(text, user));
|
||||
if (!match) throw new Error('Missing command');
|
||||
await match.command.run(match.invocation);
|
||||
};
|
||||
return { ctx, plugin, run };
|
||||
}
|
||||
const admin = '@admin:example.org', member = '@member:example.org';
|
||||
const last = (ctx: FakeContext) => ctx.transport.sent.at(-1)!.text;
|
||||
|
||||
describe('date-based check-in plugin', () => {
|
||||
it('Chinese and English commands share the atomic daily record', async () => {
|
||||
const { ctx, plugin, run } = setup();
|
||||
await Promise.all([run('签到'), run('/checkin'), run('!签到')]);
|
||||
expect((await plugin.records())).toHaveLength(1);
|
||||
expect((await plugin.stats()).get(member)).toMatchObject({ total: 1, month: 1, today: true });
|
||||
expect(ctx.transport.sent.filter((s) => s.text.includes('签到成功'))).toHaveLength(1);
|
||||
});
|
||||
it('starts a new day at midnight in the configured timezone without a report/reset', async () => {
|
||||
const { ctx, plugin, run } = setup();
|
||||
ctx.date = new Date('2026-01-15T15:59:59Z'); await run('!checkin');
|
||||
ctx.date = new Date('2026-01-15T16:00:00Z'); await run('!checkin');
|
||||
expect((await plugin.records()).map((r) => r.date)).toEqual(['2026-01-15', '2026-01-16']);
|
||||
expect((await plugin.stats()).get(member)?.total).toBe(2);
|
||||
});
|
||||
it('monthly and daily reports preserve all records and counters', async () => {
|
||||
const { ctx, run } = setup(); await run('!checkin');
|
||||
const before = await ctx.db.entries();
|
||||
await run('!日报', admin); await run('!report monthly', admin); await run('!月报', admin);
|
||||
expect(await ctx.db.entries()).toEqual(before);
|
||||
});
|
||||
it('uses lifetime known records for levels across month boundaries', async () => {
|
||||
const { ctx, plugin, run } = setup();
|
||||
for (let day = 0; day < 45; day++) {
|
||||
ctx.date = new Date(Date.UTC(2026, 0, 1 + day, 2)); await run('!签到');
|
||||
}
|
||||
expect((await plugin.stats()).get(member)).toMatchObject({ total: 45, month: 14 });
|
||||
expect(last(ctx)).toContain('钻石');
|
||||
});
|
||||
it('allows own summary but restricts all, other users and raw data', async () => {
|
||||
const { ctx, run } = setup(); await run('签到'); await run('!查询');
|
||||
expect(last(ctx)).toContain(member);
|
||||
for (const query of ['!list all', '!查询 全部', '!list @other:example.org', '!list --raw']) {
|
||||
await run(query); expect(last(ctx)).toContain('无权限');
|
||||
}
|
||||
await run('!查询 全部 --原始', admin); expect(JSON.parse(last(ctx))[0].total).toBe(1);
|
||||
});
|
||||
it('supports English replies through the same resources', async () => {
|
||||
const { ctx, run } = setup(); ctx.locale = 'en'; await run('签到');
|
||||
expect(last(ctx)).toContain('Checked in'); await run('!签到'); expect(last(ctx)).toContain('Already');
|
||||
});
|
||||
it('rejects invalid dates and prevents monthly report access by members', async () => {
|
||||
const { ctx, run } = setup(); await run('!日报 2026-02-30', admin); expect(last(ctx)).toContain('用法:!日报');
|
||||
await run('!月报'); expect(last(ctx)).toContain('无权限');
|
||||
});
|
||||
it('catches up reports once without deleting history or executing cleanup on enable', async () => {
|
||||
const { ctx, plugin, run } = setup({ cleanupEnabled: true, autoCleanup: true });
|
||||
await run('!checkin'); await plugin.start();
|
||||
ctx.date = new Date('2026-03-03T02:00:00Z');
|
||||
await plugin.settle(false);
|
||||
const count = ctx.transport.sent.length;
|
||||
expect(ctx.transport.kicks).toHaveLength(0);
|
||||
expect(last(ctx)).toContain('2026-02');
|
||||
await plugin.settle(false); expect(ctx.transport.sent).toHaveLength(count);
|
||||
expect((await plugin.stats('2026-01')).get(member)?.month).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanup previews and confirmation', () => {
|
||||
async function inactive(config: Record<string, unknown> = {}) {
|
||||
const result = setup({ cleanupEnabled: true, ...config });
|
||||
await result.run('签到'); result.ctx.date = new Date('2026-03-01T02:00:00Z');
|
||||
return result;
|
||||
}
|
||||
const token = (ctx: FakeContext) => /cleanup confirm ([a-f0-9]+)/.exec(last(ctx))![1];
|
||||
it('is disabled by default', async () => {
|
||||
const { ctx, run } = setup(); await run('!清理 预览', admin);
|
||||
expect(last(ctx)).toContain('未启用'); expect(ctx.transport.kicks).toHaveLength(0);
|
||||
});
|
||||
it('previews without kicking; requires the same administrator and consumes the token', async () => {
|
||||
const { ctx, run } = await inactive();
|
||||
await run('!清理 预览', admin); const code = token(ctx);
|
||||
expect(ctx.transport.kicks).toHaveLength(0);
|
||||
ctx.transport.powers.set('@second:example.org', 100);
|
||||
await run(`!cleanup confirm ${code}`, '@second:example.org'); expect(ctx.transport.kicks).toHaveLength(0);
|
||||
await run(`!清理 确认 ${code}`, admin); expect(ctx.transport.kicks).toHaveLength(1);
|
||||
await run(`!cleanup confirm ${code}`, admin); expect(last(ctx)).toContain('无效');
|
||||
});
|
||||
it('rechecks check-in and privileges at confirmation', async () => {
|
||||
const { ctx, run } = await inactive();
|
||||
await run('!cleanup preview', admin); const code = token(ctx);
|
||||
await run('签到'); await run(`!cleanup confirm ${code}`, admin);
|
||||
expect(ctx.transport.kicks).toHaveLength(0);
|
||||
});
|
||||
it('expires previews and refuses a demoted administrator', async () => {
|
||||
const { ctx, run } = await inactive(); await run('!cleanup preview', admin); const code = token(ctx);
|
||||
ctx.transport.powers.set(admin, 0); await run(`!cleanup confirm ${code}`, admin);
|
||||
expect(last(ctx)).toContain('无权限');
|
||||
ctx.transport.powers.set(admin, 100); ctx.date = new Date(ctx.date.getTime() + 300_001);
|
||||
await run(`!cleanup confirm ${code}`, admin); expect(last(ctx)).toContain('过期');
|
||||
expect(ctx.transport.kicks).toHaveLength(0);
|
||||
});
|
||||
it('skips permission lookup failures, protected users and never-checked members', async () => {
|
||||
const { ctx, plugin } = await inactive();
|
||||
ctx.transport.powerFailures.add(member);
|
||||
ctx.transport.memberMap.set(ctx.roomId, [member, '@new:example.org']);
|
||||
expect(await plugin.cleanupCandidates()).toEqual({ users: [], skipped: [member] });
|
||||
ctx.transport.powerFailures.clear(); ctx.transport.powers.set(member, 100);
|
||||
expect((await plugin.cleanupCandidates()).users).toEqual([]);
|
||||
});
|
||||
it('does not turn a failed member lookup into an empty successful report', async () => {
|
||||
const { ctx, plugin } = setup(); ctx.transport.memberFailures.add(ctx.roomId);
|
||||
await expect(plugin.dailyText('2026-01-15')).rejects.toThrow('Unavailable');
|
||||
});
|
||||
it('validates automation prerequisites', () => {
|
||||
expect(() => definition.validate({ autoCleanup: true })).toThrow();
|
||||
expect(recordKey(member, '2026-01-15')).not.toBe(recordKey('@other:example.org', '2026-01-15'));
|
||||
});
|
||||
it('never includes its own account in cleanup candidates', async () => {
|
||||
const { ctx, plugin, run } = setup({ cleanupEnabled: true });
|
||||
await run('签到', ctx.botUserId); ctx.date = new Date('2026-03-01T02:00:00Z');
|
||||
ctx.transport.memberMap.set(ctx.roomId, [ctx.botUserId]);
|
||||
expect(await plugin.cleanupCandidates()).toEqual({ users: [], skipped: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Messages } from '../../core/i18n/i18n';
|
||||
export const messages = {
|
||||
description: { 'zh-CN': '按日期签到、统计与成员清理', en: 'Daily check-in, reports and membership cleanup' },
|
||||
checkin: { 'zh-CN': '今日签到', en: 'Check in for today' },
|
||||
list: { 'zh-CN': '查询签到;他人、全部和原始数据仅管理员可查', en: 'Check-in records; others, all and raw data require admin access' },
|
||||
daily: { 'zh-CN': '查询日报,不修改数据', en: 'Read daily report without changing data' },
|
||||
monthly: { 'zh-CN': '查询月报,不修改数据', en: 'Read monthly report without changing data' },
|
||||
cleanupPreview: { 'zh-CN': '预览长期未签到清理名单', en: 'Preview inactive-member cleanup' },
|
||||
cleanupConfirm: { 'zh-CN': '执行已预览的清理名单', en: 'Execute a previously previewed cleanup' },
|
||||
checked: { 'zh-CN': '{date} 签到成功。本月 {month} 次,累计已知记录 {total} 次,等级:{level}。', en: 'Checked in for {date}. This month: {month}; known total: {total}; level: {level}.' },
|
||||
duplicate: { 'zh-CN': '{date} 已签到,无需重复。', en: 'Already checked in for {date}.' },
|
||||
row: { 'zh-CN': '{user}:今日 {today},本月 {month} 次,累计已知记录 {total} 次,等级 {level}', en: '{user}: today {today}, month {month}, known total {total}, level {level}' },
|
||||
yes: { 'zh-CN': '已签到', en: 'checked in' },
|
||||
no: { 'zh-CN': '未签到', en: 'not checked in' },
|
||||
reportDay: { 'zh-CN': '{date} 日报\n已签到 {count} 人;当前群成员 {members} 人。\n按当前成员核对,未找到当日记录:\n{missing}', en: 'Daily report {date}\nChecked in: {count}; current members: {members}.\nCurrent members without a record for this date:\n{missing}' },
|
||||
reportMonth: { 'zh-CN': '{month} 月报\n{rows}', en: 'Monthly report {month}\n{rows}' },
|
||||
skipped: { 'zh-CN': '{user}:权限读取失败,已跳过', en: '{user}: permission lookup failed; skipped' },
|
||||
kickReason: { 'zh-CN': '连续至少 {days} 天未签到', en: 'No check-in for at least {days} days' },
|
||||
kicked: { 'zh-CN': '{user}:已移出', en: '{user}: removed' },
|
||||
kickFailed: { 'zh-CN': '{user}:移出失败,待人工复核', en: '{user}: removal failed; review required' },
|
||||
changed: { 'zh-CN': '{user}:状态已变化,已跳过', en: '{user}: eligibility changed; skipped' },
|
||||
disabled: { 'zh-CN': '成员清理未启用。请由维护人员配置 cleanupEnabled。', en: 'Membership cleanup is disabled. Configure cleanupEnabled first.' },
|
||||
catchup: { 'zh-CN': '补发统计:{from} 至 {to} 期间的最新一期;完整历史仍可按日期查询。', en: 'Catch-up: latest report for the interval {from} through {to}. Full history remains available by date.' },
|
||||
} satisfies Messages;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Messages } from '../../core/i18n/i18n';
|
||||
export const messages = {
|
||||
description: { 'zh-CN': '业务身份与跨房间成员管理', en: 'Business roles and cross-room membership management' },
|
||||
status: { 'zh-CN': '查看成员管理模式和自动操作开关', en: 'Show membership mode and automation switches' },
|
||||
role: { 'zh-CN': '预览业务身份调整', en: 'Preview a business-role change' },
|
||||
preview: { 'zh-CN': '预览成员状态核对结果', en: 'Preview membership reconciliation' },
|
||||
confirm: { 'zh-CN': '确认已预览的成员操作', en: 'Confirm previewed membership actions' },
|
||||
mode: { 'zh-CN': '模式:{mode}\n权限变更同步:{power}\n入群同步:{join}\n离群联动:{leave}\n定时核对:{reconcile}', en: 'Mode: {mode}\nPower-change sync: {power}\nJoin sync: {join}\nLeave sync: {leave}\nPeriodic reconciliation: {reconcile}' },
|
||||
business: { 'zh-CN': '独立业务身份', en: 'independent business roles' },
|
||||
matrix: { 'zh-CN': 'Matrix 权限映射', en: 'Matrix power-level mapping' },
|
||||
on: { 'zh-CN': '开启', en: 'on' },
|
||||
off: { 'zh-CN': '关闭', en: 'off' },
|
||||
wrongMode: { 'zh-CN': '当前采用 Matrix 权限映射;业务身份命令仅在 business 模式可用。', en: 'Matrix mapping is active. Business-role commands require business mode.' },
|
||||
core: { 'zh-CN': '核心成员', en: 'core member' },
|
||||
member: { 'zh-CN': '普通成员', en: 'member' },
|
||||
restricted: { 'zh-CN': '受限成员', en: 'restricted member' },
|
||||
intermediate: { 'zh-CN': '中间权限', en: 'intermediate power' },
|
||||
invite: { 'zh-CN': '发送邀请', en: 'send invitation' },
|
||||
kick: { 'zh-CN': '移出', en: 'remove' },
|
||||
roleChange: { 'zh-CN': '{user} → {role}', en: '{user} → {role}' },
|
||||
failed: { 'zh-CN': '{user}:读取失败或操作失败,待复核', en: '{user}: lookup or operation failed; review required' },
|
||||
skipped: { 'zh-CN': '{user}:状态变化、管理员豁免或不在管理群,已跳过', en: '{user}: changed state, administrator exemption or not in control room; skipped' },
|
||||
action: { 'zh-CN': '{user}:{action} {room}', en: '{user}: {action} {room}' },
|
||||
reason: { 'zh-CN': '按已配置的成员管理规则同步', en: 'Reconciled according to configured membership policy' },
|
||||
} satisfies Messages;
|
||||
@@ -0,0 +1,212 @@
|
||||
import { z } from 'zod';
|
||||
import { Command, Invocation } from '../../core/command/command-router';
|
||||
import { MemberEvent, PowerLevelEvent } from '../../core/command/types';
|
||||
import { choice, common } from '../../core/i18n/i18n';
|
||||
import { Confirmations } from '../../core/plugin/confirmation';
|
||||
import { Plugin, PluginContext, PluginDefinition } from '../../core/plugin/types';
|
||||
import { messages as m } from './messages';
|
||||
|
||||
import { matrixRoomId } from '../../config/schema';
|
||||
export const roomManagerConfig = z.object({
|
||||
workRoom1: matrixRoomId, workRoom2: matrixRoomId, lostRoom: matrixRoomId,
|
||||
mode: z.enum(['business', 'matrix']).default('business'),
|
||||
levelA: z.number().int().default(50), levelB: z.number().int().default(0), levelC: z.number().int().default(-1),
|
||||
syncPowerChanges: z.boolean().default(false),
|
||||
syncOnJoin: z.boolean().default(false), syncOnLeave: z.boolean().default(false),
|
||||
autoReconcile: z.boolean().default(false),
|
||||
}).refine((c) => c.levelA > c.levelB && c.levelB > c.levelC, 'Require levelA > levelB > levelC')
|
||||
.refine((c) => new Set([c.workRoom1, c.workRoom2, c.lostRoom]).size === 3, 'Target rooms must be distinct')
|
||||
.refine((c) => !c.syncPowerChanges || c.mode === 'matrix', 'syncPowerChanges requires matrix mode');
|
||||
type Config = z.infer<typeof roomManagerConfig>;
|
||||
type Role = 'core' | 'member' | 'restricted' | 'intermediate';
|
||||
type Action = { user: string; room: string; type: 'invite' | 'kick' };
|
||||
type PlanRow = { user: string; role: Role; previous: Role | null; member: boolean; actions: Action[] };
|
||||
type Plan = { rows: PlanRow[]; assign: boolean };
|
||||
|
||||
export class RoomManagerPlugin implements Plugin {
|
||||
readonly commands: Command[];
|
||||
private readonly plans: Confirmations<Plan>;
|
||||
constructor(private readonly ctx: PluginContext, private readonly config: Config) {
|
||||
if ([config.workRoom1, config.workRoom2, config.lostRoom].includes(ctx.roomId)) throw new Error('Control room must differ from target rooms');
|
||||
this.plans = new Confirmations(ctx, 'membership');
|
||||
this.commands = [
|
||||
{ id: 'access.status', paths: [['access', 'status'], ['成员管理', '状态']], admin: true, description: m.status,
|
||||
usage: { 'zh-CN': '!成员管理 状态', en: '!access status' }, run: async (inv) => {
|
||||
await this.reply(inv, ctx.t(m.mode, { mode: ctx.t(m[config.mode]), power: ctx.t(config.syncPowerChanges ? m.on : m.off),
|
||||
join: ctx.t(config.syncOnJoin ? m.on : m.off), leave: ctx.t(config.syncOnLeave ? m.on : m.off), reconcile: ctx.t(config.autoReconcile ? m.on : m.off) }));
|
||||
} },
|
||||
{ id: 'role.set', paths: [['role', 'set'], ['身份', '设置']], admin: true, description: m.role,
|
||||
usage: { 'zh-CN': '!身份 设置 <用户ID> 核心|普通|受限', en: '!role set <userId> core|member|restricted' }, run: (inv) => this.rolePreview(inv) },
|
||||
{ id: 'access.preview', paths: [['access', 'preview'], ['access', 'reconcile'], ['成员管理', '预览'], ['成员管理', '核对']], admin: true, description: m.preview,
|
||||
usage: { 'zh-CN': '!成员管理 预览 [用户ID]', en: '!access preview [userId]' }, run: (inv) => this.preview(inv) },
|
||||
{ id: 'access.confirm', paths: [['access', 'confirm'], ['成员管理', '确认']], admin: true, description: m.confirm,
|
||||
usage: { 'zh-CN': '!成员管理 确认 <确认码>', en: '!access confirm <token>' }, run: (inv) => this.confirm(inv) },
|
||||
];
|
||||
}
|
||||
async start(): Promise<void> {
|
||||
if (this.config.autoReconcile) {
|
||||
this.ctx.schedule('membership-reconciliation', '0 */15 * * * *', () => this.reconcile());
|
||||
await this.reconcile();
|
||||
}
|
||||
}
|
||||
private async reply(inv: Invocation, text: string): Promise<void> { await this.ctx.reply(inv.message, text); }
|
||||
private usage(inv: Invocation, id: string): Promise<void> {
|
||||
return this.reply(inv, this.ctx.t(common.usage, { usage: this.ctx.t(this.commands.find((command) => command.id === id)!.usage) }));
|
||||
}
|
||||
private async admin(inv: Invocation): Promise<boolean> {
|
||||
if (await this.ctx.isAdmin(inv.message.userId)) return true;
|
||||
await this.reply(inv, this.ctx.t(common.denied)); return false;
|
||||
}
|
||||
private mapPower(power: number): Role {
|
||||
if (power >= this.config.levelA) return 'core';
|
||||
if (power >= this.config.levelB) return 'member';
|
||||
return power > this.config.levelC ? 'intermediate' : 'restricted';
|
||||
}
|
||||
private async desired(user: string, isMember: boolean): Promise<Role | undefined> {
|
||||
if (!isMember) return this.config.syncOnLeave ? 'restricted' : undefined;
|
||||
return this.config.mode === 'matrix' ? this.mapPower(await this.ctx.power(user)) :
|
||||
await this.ctx.db.get<Role>(`role:${user}`) ?? 'member';
|
||||
}
|
||||
private operations(user: string, role: Role): Action[] {
|
||||
const { workRoom1: first, workRoom2: second, lostRoom: lost } = this.config;
|
||||
const table: Record<Role, Array<[string, 'invite' | 'kick']>> = {
|
||||
core: [[first, 'invite'], [second, 'invite'], [lost, 'kick']],
|
||||
member: [[first, 'kick'], [second, 'invite'], [lost, 'kick']],
|
||||
restricted: [[first, 'kick'], [second, 'kick'], [lost, 'invite']],
|
||||
intermediate: [[lost, 'kick']],
|
||||
};
|
||||
return table[role].map(([room, type]) => ({ user, room, type }));
|
||||
}
|
||||
private async row(user: string, members: string[], override?: Role): Promise<PlanRow | undefined> {
|
||||
if (user === this.ctx.botUserId) return undefined;
|
||||
const member = members.includes(user);
|
||||
if (override && !member && override !== 'restricted') return undefined;
|
||||
const role = override ?? await this.desired(user, member);
|
||||
if (!role) return undefined;
|
||||
const previous = await this.ctx.db.get<Role>(`role:${user}`);
|
||||
const power = await this.ctx.power(user);
|
||||
const admin = power >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(user);
|
||||
const actions: Action[] = [];
|
||||
for (const action of this.operations(user, role)) {
|
||||
if (action.type === 'kick' && admin) continue;
|
||||
const joined = (await this.ctx.members(action.room)).includes(user);
|
||||
if (action.type === 'kick' ? joined : !joined) actions.push(action);
|
||||
}
|
||||
return { user, role, previous, member, actions };
|
||||
}
|
||||
private async collect(user?: string, role?: Role): Promise<{ rows: PlanRow[]; notes: string[] }> {
|
||||
const members = await this.ctx.members();
|
||||
const known = (await this.ctx.db.entries()).filter(([key]) => key.startsWith('role:') || key.startsWith('seen:')).map(([key]) => key.slice(5));
|
||||
const users = user ? [user] : [...new Set([...members, ...known])].filter((id) => id !== this.ctx.botUserId);
|
||||
const rows: PlanRow[] = [], notes: string[] = [];
|
||||
for (const id of users) {
|
||||
try {
|
||||
const row = await this.row(id, members, role);
|
||||
if (row) rows.push(row); else if (user) notes.push(this.ctx.t(m.skipped, { user: id }));
|
||||
} catch { notes.push(this.ctx.t(m.failed, { user: id })); }
|
||||
}
|
||||
return { rows, notes };
|
||||
}
|
||||
private async showPlan(inv: Invocation, role?: Role): Promise<void> {
|
||||
const result = await this.collect(inv.args[0], role);
|
||||
const token = await this.plans.preview(inv.message.userId, { rows: result.rows, assign: !!role });
|
||||
const lines = result.rows.flatMap((row) => [
|
||||
...(role ? [this.ctx.t(m.roleChange, { user: row.user, role: this.ctx.t(m[row.role]) })] : []),
|
||||
...row.actions.map((a) => this.describe(a)),
|
||||
]);
|
||||
await this.reply(inv, this.ctx.t(common.preview, { details: [...lines, ...result.notes].join('\n') || this.ctx.t(common.empty),
|
||||
command: `!access confirm ${token} / !成员管理 确认 ${token}` }));
|
||||
}
|
||||
private async rolePreview(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
if (this.config.mode !== 'business') return this.reply(inv, this.ctx.t(m.wrongMode));
|
||||
const role = choice(inv.args[1], { core: ['核心', '核心成员'], member: ['普通', '普通成员'], restricted: ['受限', '受限成员'] });
|
||||
if (inv.args.length !== 2 || !/^@.+:.+$/.test(inv.args[0]) || !role) {
|
||||
return this.usage(inv, 'role.set');
|
||||
}
|
||||
await this.showPlan(inv, role);
|
||||
}
|
||||
private async preview(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
if (inv.args.length > 1 || (inv.args[0] && !/^@.+:.+$/.test(inv.args[0]))) {
|
||||
return this.usage(inv, 'access.preview');
|
||||
}
|
||||
await this.showPlan(inv);
|
||||
}
|
||||
private describe(action: Action): string {
|
||||
return this.ctx.t(m.action, { user: action.user, action: this.ctx.t(m[action.type]), room: action.room });
|
||||
}
|
||||
private async execute(plan: Plan, actor: string): Promise<string[]> {
|
||||
const result: string[] = [];
|
||||
for (const row of plan.rows) {
|
||||
try {
|
||||
const members = await this.ctx.members();
|
||||
const previous = await this.ctx.db.get<Role>(`role:${row.user}`);
|
||||
const desired = plan.assign ? row.role : await this.desired(row.user, members.includes(row.user));
|
||||
if (previous !== row.previous || members.includes(row.user) !== row.member || desired !== row.role) {
|
||||
result.push(this.ctx.t(m.skipped, { user: row.user })); continue;
|
||||
}
|
||||
if (plan.assign) {
|
||||
await this.ctx.audit('role.set', actor, { user: row.user, role: row.role });
|
||||
await this.ctx.db.set(`role:${row.user}`, row.role);
|
||||
result.push(this.ctx.t(m.roleChange, { user: row.user, role: this.ctx.t(m[row.role]) }));
|
||||
}
|
||||
if (row.member) await this.ctx.db.set(`seen:${row.user}`, true);
|
||||
// Execute only actions shown in the preview, never add new targets at confirmation.
|
||||
for (const action of row.actions) {
|
||||
try {
|
||||
const stillMember = (await this.ctx.members()).includes(row.user);
|
||||
if (stillMember !== row.member || (!plan.assign && await this.desired(row.user, stillMember) !== row.role)) {
|
||||
result.push(this.ctx.t(m.skipped, { user: row.user })); break;
|
||||
}
|
||||
const joined = (await this.ctx.members(action.room)).includes(action.user);
|
||||
if (action.type === 'kick' ? !joined : joined) continue;
|
||||
const power = await this.ctx.power(action.user);
|
||||
if (action.type === 'kick' && (power >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(action.user))) {
|
||||
result.push(this.ctx.t(m.skipped, { user: action.user })); continue;
|
||||
}
|
||||
await this.ctx.audit(`membership.${action.type}.requested`, actor, { user: action.user, room: action.room });
|
||||
if (action.type === 'kick') await this.ctx.kick(action.room, action.user, this.ctx.t(m.reason));
|
||||
else await this.ctx.invite(action.room, action.user);
|
||||
await this.ctx.audit(`membership.${action.type}.completed`, actor, { user: action.user, room: action.room });
|
||||
result.push(this.describe(action));
|
||||
} catch {
|
||||
await this.ctx.audit(`membership.${action.type}.failed`, actor, { user: action.user, room: action.room });
|
||||
result.push(this.ctx.t(m.failed, { user: action.user }));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
await this.ctx.audit('membership.lookup.failed', actor, { user: row.user });
|
||||
result.push(this.ctx.t(m.failed, { user: row.user }));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private async confirm(inv: Invocation): Promise<void> {
|
||||
if (!await this.admin(inv)) return;
|
||||
const plan = inv.args.length === 1 ? await this.plans.consume(inv.message.userId, inv.args[0]) : undefined;
|
||||
if (!plan) return this.reply(inv, this.ctx.t(common.expired));
|
||||
const result = await this.execute(plan, inv.message.userId);
|
||||
await this.reply(inv, this.ctx.t(common.done, { details: result.join('\n') || this.ctx.t(common.empty) }));
|
||||
}
|
||||
private async reconcile(user?: string): Promise<void> {
|
||||
const { rows, notes } = await this.collect(user);
|
||||
const result = await this.execute({ rows, assign: false }, 'scheduler');
|
||||
if (result.length || notes.length) await this.ctx.send(this.ctx.t(common.done, { details: [...result, ...notes].join('\n') }));
|
||||
}
|
||||
async onMember(event: MemberEvent): Promise<void> {
|
||||
if ((event.membership === 'join' && this.config.syncOnJoin) ||
|
||||
(event.membership === 'leave' && this.config.syncOnLeave)) await this.reconcile(event.userId);
|
||||
}
|
||||
async onPowerLevel(_event: PowerLevelEvent): Promise<void> {
|
||||
// Reconcile current state, including users_default changes omitted by a users-only diff.
|
||||
if (this.config.syncPowerChanges) await this.reconcile();
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
apiVersion: 1, id: 'room-manager', aliases: ['成员管理', '权限同步'], version: '2.0.0', description: m.description,
|
||||
validate: (config) => roomManagerConfig.parse(config),
|
||||
allowedRooms: (config) => { const c = roomManagerConfig.parse(config); return [c.workRoom1, c.workRoom2, c.lostRoom]; },
|
||||
create: (ctx, config) => new RoomManagerPlugin(ctx, roomManagerConfig.parse(config)),
|
||||
} satisfies PluginDefinition;
|
||||
@@ -0,0 +1,88 @@
|
||||
import { CommandRouter } from '../../core/command/command-router';
|
||||
import { FakeContext, message } from '../../test/fakes';
|
||||
import definition, { RoomManagerPlugin, roomManagerConfig } from './room-manager.plugin';
|
||||
|
||||
const admin = '@admin:example.org', member = '@member:example.org';
|
||||
const config = { workRoom1: '!work1:example.org', workRoom2: '!work2:example.org', lostRoom: '!lost:example.org' };
|
||||
function setup(extra: Record<string, unknown> = {}) {
|
||||
const ctx = new FakeContext(), plugin = new RoomManagerPlugin(ctx, roomManagerConfig.parse({ ...config, ...extra }));
|
||||
const router = new CommandRouter(plugin.commands);
|
||||
const run = async (text: string, user = admin) => {
|
||||
const match = router.match(message(text, user))!; await match.command.run(match.invocation);
|
||||
};
|
||||
return { ctx, plugin, run };
|
||||
}
|
||||
const last = (ctx: FakeContext) => ctx.transport.sent.at(-1)!.text;
|
||||
const token = (ctx: FakeContext) => /access confirm ([a-f0-9]+)/.exec(last(ctx))![1];
|
||||
|
||||
describe('membership plugin', () => {
|
||||
it('defaults to business roles with every automatic mutation switch off', async () => {
|
||||
const { ctx, plugin } = setup(); await plugin.start();
|
||||
await plugin.onMember({ ...message(''), membership: 'leave' });
|
||||
await plugin.onMember({ ...message(''), membership: 'join' });
|
||||
await plugin.onPowerLevel({ account: ctx.account, roomId: ctx.roomId, users: { [member]: -1 }, prevUsers: {}, defaultPower: 0 });
|
||||
expect(ctx.scheduler.jobs.size).toBe(0); expect(ctx.transport.kicks).toHaveLength(0); expect(ctx.transport.invites).toHaveLength(0);
|
||||
});
|
||||
it('business roles do not grant native Matrix management power and require confirmation', async () => {
|
||||
const { ctx, run } = setup(); await run(`!身份 设置 ${member} 核心`); const code = token(ctx);
|
||||
expect(await ctx.db.get(`role:${member}`)).toBeNull(); expect(ctx.transport.invites).toHaveLength(0);
|
||||
await run(`!access confirm ${code}`);
|
||||
expect(await ctx.db.get(`role:${member}`)).toBe('core'); expect(ctx.transport.powers.get(member)).toBeUndefined();
|
||||
expect(ctx.transport.invites.map((i) => i.room)).toEqual([config.workRoom1, config.workRoom2]);
|
||||
});
|
||||
it('requires the previewing administrator and expires tokens', async () => {
|
||||
const { ctx, run } = setup(); await run(`!role set ${member} restricted`); const code = token(ctx);
|
||||
ctx.transport.powers.set('@other-admin:example.org', 100);
|
||||
await run(`!access confirm ${code}`, '@other-admin:example.org'); expect(last(ctx)).toContain('无效');
|
||||
ctx.date = new Date(ctx.date.getTime() + 300_001);
|
||||
await run(`!access confirm ${code}`); expect(last(ctx)).toContain('过期'); expect(ctx.transport.invites).toHaveLength(0);
|
||||
});
|
||||
it('does not apply a stale preview if the member leaves the control room', async () => {
|
||||
const { ctx, run } = setup(); await run(`!role set ${member} core`); const code = token(ctx);
|
||||
ctx.transport.memberMap.set(ctx.roomId, []);
|
||||
await run(`!access confirm ${code}`); expect(ctx.transport.invites).toHaveLength(0); expect(await ctx.db.get(`role:${member}`)).toBeNull();
|
||||
});
|
||||
it('preview and reconciliation never mutate membership until confirmed', async () => {
|
||||
const { ctx, run } = setup(); ctx.transport.memberMap.set(config.workRoom1, [member]);
|
||||
await run('!access reconcile'); const code = token(ctx);
|
||||
expect(ctx.transport.kicks).toHaveLength(0);
|
||||
await run(`!成员管理 确认 ${code}`); expect(ctx.transport.kicks).toEqual([{ room: config.workRoom1, user: member }]);
|
||||
});
|
||||
it('skips unreadable privileges and newly promoted administrators at execution', async () => {
|
||||
const { ctx, run } = setup(); ctx.transport.memberMap.set(config.workRoom1, [member]);
|
||||
await run('!access preview'); const code = token(ctx);
|
||||
ctx.transport.powerFailures.add(member); await run(`!access confirm ${code}`);
|
||||
expect(ctx.transport.kicks).toHaveLength(0); expect(ctx.transport.invites).toHaveLength(0);
|
||||
});
|
||||
it('maps intermediate integer power levels using the configured ranges', async () => {
|
||||
const { ctx, run } = setup({ mode: 'matrix' }); ctx.transport.powers.set(member, 25);
|
||||
ctx.transport.memberMap.set(config.workRoom1, [member]);
|
||||
await run('!access preview'); const code = token(ctx); await run(`!access confirm ${code}`);
|
||||
expect(ctx.transport.kicks).toEqual([{ room: config.workRoom1, user: member }]);
|
||||
expect(ctx.transport.invites).toEqual([{ room: config.workRoom2, user: member }]);
|
||||
});
|
||||
it('reconciles members affected by users_default changes when explicitly enabled', async () => {
|
||||
const { ctx, plugin } = setup({ mode: 'matrix', syncPowerChanges: true });
|
||||
ctx.transport.powers.set(member, -1); ctx.transport.memberMap.set(config.workRoom1, [member]);
|
||||
await plugin.onPowerLevel({ account: ctx.account, roomId: ctx.roomId, users: {}, prevUsers: {}, defaultPower: -1 });
|
||||
expect(ctx.transport.kicks).toHaveLength(1); expect(ctx.transport.invites).toContainEqual({ room: config.lostRoom, user: member });
|
||||
});
|
||||
it('can recover a missed leave for previously observed members when both switches are enabled', async () => {
|
||||
const { ctx, plugin } = setup({ syncOnLeave: true, autoReconcile: true });
|
||||
await plugin.start(); ctx.transport.memberMap.set(ctx.roomId, []); ctx.transport.memberMap.set(config.workRoom2, [member]);
|
||||
await ctx.scheduler.tick(); expect(ctx.transport.kicks).toContainEqual({ room: config.workRoom2, user: member });
|
||||
});
|
||||
it('validates distinct rooms, threshold ordering and mode-dependent switches', () => {
|
||||
expect(() => definition.validate({ ...config, workRoom2: config.workRoom1 })).toThrow();
|
||||
expect(() => definition.validate({ ...config, levelA: 0 })).toThrow();
|
||||
expect(() => definition.validate({ ...config, syncPowerChanges: true })).toThrow();
|
||||
});
|
||||
it('never reconciles its own account or emits no-op periodic notifications', async () => {
|
||||
const { ctx, plugin } = setup({ autoReconcile: true });
|
||||
ctx.transport.memberMap.set(ctx.roomId, [ctx.botUserId]);
|
||||
ctx.transport.memberMap.set(config.workRoom1, [ctx.botUserId]);
|
||||
await plugin.start(); await ctx.scheduler.tick();
|
||||
expect(ctx.transport.kicks).toHaveLength(0); expect(ctx.transport.invites).toHaveLength(0);
|
||||
expect(ctx.transport.sent).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { PrismaService } from '../core/db/prisma.service';
|
||||
|
||||
export async function testDatabase(): Promise<{ prisma: PrismaService; close(): Promise<void> }> {
|
||||
const directory = mkdtempSync(join(tmpdir(), 'bot-test-'));
|
||||
const url = `file:${join(directory, 'test.db')}`;
|
||||
const root = resolve(__dirname, '../..');
|
||||
let prisma: PrismaService | undefined;
|
||||
try {
|
||||
execFileSync(process.execPath, [require.resolve('prisma'), 'db', 'push', '--skip-generate', '--schema', resolve(root, 'prisma/schema.prisma')], {
|
||||
cwd: directory,
|
||||
env: { ...process.env, DATABASE_URL: url, RUST_LOG: 'info', CHECKPOINT_DISABLE: '1', PRISMA_HIDE_UPDATE_MESSAGE: '1',
|
||||
NODE_OPTIONS: `--require=${JSON.stringify(resolve(root, 'scripts/test-network-guard.cjs'))}` },
|
||||
stdio: 'pipe', timeout: 30_000,
|
||||
});
|
||||
prisma = new PrismaService({ datasources: { db: { url } } });
|
||||
await prisma.onModuleInit();
|
||||
const client = prisma;
|
||||
return { prisma: client, close: async () => {
|
||||
try { await client.onModuleDestroy(); } finally { rmSync(directory, { recursive: true, force: true }); }
|
||||
} };
|
||||
} catch (error) {
|
||||
await prisma?.onModuleDestroy().catch(() => undefined);
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { InboundMessage } from '../core/command/types';
|
||||
import { translate, Locale } from '../core/i18n/i18n';
|
||||
import { PluginContext, Store } from '../core/plugin/types';
|
||||
import { MatrixTransport } from '../core/matrix/types';
|
||||
import { Scheduler } from '../core/plugin/scheduler';
|
||||
|
||||
export class MemoryStore implements Store {
|
||||
private readonly data = new Map<string, unknown>();
|
||||
async get<T>(key: string): Promise<T | null> { return this.data.has(key) ? structuredClone(this.data.get(key)) as T : null; }
|
||||
async set<T>(key: string, value: T): Promise<void> { this.data.set(key, structuredClone(value)); }
|
||||
async create<T>(key: string, value: T): Promise<boolean> {
|
||||
if (this.data.has(key)) return false;
|
||||
this.data.set(key, structuredClone(value)); return true;
|
||||
}
|
||||
async remove(key: string): Promise<void> { this.data.delete(key); }
|
||||
async entries<T>(): Promise<Array<[string, T]>> { return structuredClone([...this.data]) as Array<[string, T]>; }
|
||||
}
|
||||
export function memoryStores(): (scope: string) => MemoryStore {
|
||||
const stores = new Map<string, MemoryStore>();
|
||||
return (scope) => { if (!stores.has(scope)) stores.set(scope, new MemoryStore()); return stores.get(scope)!; };
|
||||
}
|
||||
export class FakeScheduler implements Scheduler {
|
||||
readonly jobs = new Set<() => Promise<void>>();
|
||||
readonly zones: string[] = [];
|
||||
register(_cron: string, timeZone: string, run: () => Promise<void>): () => void {
|
||||
this.jobs.add(run); this.zones.push(timeZone); return () => { this.jobs.delete(run); };
|
||||
}
|
||||
async tick(): Promise<void> { for (const job of [...this.jobs]) await job(); }
|
||||
}
|
||||
export class FakeTransport implements MatrixTransport {
|
||||
readonly account = 'test';
|
||||
readonly userId = '@bot:example.org';
|
||||
readonly sent: Array<{ room: string; text: string }> = [];
|
||||
readonly kicks: Array<{ room: string; user: string }> = [];
|
||||
readonly invites: Array<{ room: string; user: string }> = [];
|
||||
readonly memberMap = new Map<string, string[]>([['!control:example.org', ['@member:example.org']]]);
|
||||
readonly powers = new Map<string, number>([['@admin:example.org', 100]]);
|
||||
readonly powerFailures = new Set<string>();
|
||||
readonly memberFailures = new Set<string>();
|
||||
async send(room: string, text: string): Promise<string> { this.sent.push({ room, text }); return 'event'; }
|
||||
async kick(room: string, user: string): Promise<void> {
|
||||
this.kicks.push({ room, user }); this.memberMap.set(room, (this.memberMap.get(room) ?? []).filter((id) => id !== user));
|
||||
}
|
||||
async invite(room: string, user: string): Promise<void> { this.invites.push({ room, user }); }
|
||||
async getJoinedMembers(room: string): Promise<string[]> {
|
||||
if (this.memberFailures.has(room)) throw new Error('Unavailable');
|
||||
return [...(this.memberMap.get(room) ?? [])];
|
||||
}
|
||||
async getMemberCount(room: string): Promise<number> { return (await this.getJoinedMembers(room)).length; }
|
||||
async getPowerLevel(_room: string, user: string): Promise<number> {
|
||||
if (this.powerFailures.has(user)) throw new Error('Unavailable');
|
||||
return this.powers.get(user) ?? 0;
|
||||
}
|
||||
}
|
||||
export class FakeContext implements PluginContext {
|
||||
readonly account = 'test';
|
||||
readonly botUserId = '@bot:example.org';
|
||||
readonly roomId = '!control:example.org';
|
||||
readonly timeZone = 'Asia/Shanghai';
|
||||
readonly adminPowerLevel = 100;
|
||||
locale: Locale = 'zh-CN';
|
||||
readonly controller = new AbortController();
|
||||
readonly signal = this.controller.signal;
|
||||
readonly scheduler = new FakeScheduler();
|
||||
readonly transport = new FakeTransport();
|
||||
readonly audits: Array<{ action: string; actor: string; details: Record<string, unknown> }> = [];
|
||||
date = new Date('2026-01-15T02:00:00Z');
|
||||
constructor(readonly db: Store = new MemoryStore()) {}
|
||||
now = (): Date => new Date(this.date);
|
||||
t: PluginContext['t'] = (text, values) => translate(text, this.locale, values);
|
||||
send = (text: string) => this.transport.send(this.roomId, text);
|
||||
reply = (_message: InboundMessage, text: string) => this.send(text);
|
||||
isAdmin = async (user: string) => {
|
||||
try { return await this.power(user) >= this.adminPowerLevel; } catch { return false; }
|
||||
};
|
||||
members = (room = this.roomId) => this.transport.getJoinedMembers(room);
|
||||
power = (user: string) => this.transport.getPowerLevel(this.roomId, user);
|
||||
kick = (room: string, user: string, _reason: string) => this.transport.kick(room, user);
|
||||
invite = (room: string, user: string) => this.transport.invite(room, user);
|
||||
schedule = (_name: string, cron: string, run: () => Promise<void>) => { this.scheduler.register(cron, this.timeZone, run); };
|
||||
audit: PluginContext['audit'] = async (action, actor, details) => { this.audits.push({ action, actor, details }); };
|
||||
}
|
||||
export function message(text: string, userId = '@member:example.org', roomId = '!control:example.org'): InboundMessage {
|
||||
return { text, userId, roomId, account: 'test', eventId: '$test', timestampMs: Date.parse('2026-01-15T02:00:00Z') };
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Tests use injected transports. Any accidental network call fails immediately.
|
||||
import { Logger } from '@nestjs/common';
|
||||
Logger.overrideLogger(false);
|
||||
const blocked = () => { throw new Error('Network access is disabled in tests'); };
|
||||
jest.spyOn(require('node:http'), 'request').mockImplementation(blocked);
|
||||
jest.spyOn(require('node:http'), 'get').mockImplementation(blocked);
|
||||
jest.spyOn(require('node:https'), 'request').mockImplementation(blocked);
|
||||
jest.spyOn(require('node:https'), 'get').mockImplementation(blocked);
|
||||
jest.spyOn(require('node:net').Socket.prototype, 'connect').mockImplementation(blocked);
|
||||
jest.spyOn(require('node:tls'), 'connect').mockImplementation(blocked);
|
||||
global.fetch = jest.fn(blocked);
|
||||
|
||||
const fs = require('node:fs');
|
||||
const exists = fs.existsSync.bind(fs);
|
||||
const read = fs.readFileSync.bind(fs);
|
||||
const privateConfiguration = (path: unknown) => typeof path === 'string' &&
|
||||
(/(^|\/)\.env(?:\..*)?$/.test(path) || /(^|\/)config\/bots\.yaml$/.test(path));
|
||||
jest.spyOn(fs, 'existsSync').mockImplementation((path: unknown) => privateConfiguration(path) ? false : exists(path));
|
||||
jest.spyOn(fs, 'readFileSync').mockImplementation((path: unknown, ...args: unknown[]) => {
|
||||
if (privateConfiguration(path)) throw new Error('Runtime configuration is unavailable in tests');
|
||||
return read(path, ...args);
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "dist", "src/test", "**/*.spec.ts"]
|
||||
}
|
||||
+1
-1
@@ -21,7 +21,7 @@
|
||||
"paths": {
|
||||
"@core/*": ["src/core/*"],
|
||||
"@config/*": ["src/config/*"],
|
||||
"@bots/*": ["src/bots/*"]
|
||||
"@plugins/*": ["src/plugins/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
|
||||
Reference in new issue
Block a user