init
This commit is contained in:
commit
440f572834
53 files changed
+12776
No files matched your search
@@ -0,0 +1,12 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
data
|
||||
*.db
|
||||
*.db-journal
|
||||
.env
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
# 实际配置含密码,不打进镜像;运行时由 compose volume 挂载
|
||||
config/bots.yaml
|
||||
@@ -0,0 +1,12 @@
|
||||
# 数据库连接(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"
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
*.db
|
||||
*.db-journal
|
||||
.env
|
||||
|
||||
# 实际配置(含账号密码),不进版本库;从 config/bots.example.yaml 复制后填写
|
||||
config/bots.yaml
|
||||
|
||||
# 本地运行数据目录(SQLite 等),只保留占位文件
|
||||
/data/*
|
||||
!/data/.gitkeep
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# 使用 debian(glibc)而非 alpine(musl):原生加密模块
|
||||
# @matrix-org/matrix-sdk-crypto-nodejs 在 arm64 上只提供 gnu(glibc)预编译,
|
||||
# 不支持 arm64-musl;debian 同时覆盖 x64/arm64,适配 Apple Silicon 上的 Docker。
|
||||
FROM node:22-slim AS build
|
||||
WORKDIR /app
|
||||
# openssl: Prisma 引擎;ca-certificates: postinstall 从 github 下载加密二进制。
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run prisma:generate && npm run build
|
||||
|
||||
FROM node:22-slim AS runtime
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
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 docker-entrypoint.sh ./
|
||||
RUN chmod +x docker-entrypoint.sh
|
||||
# 数据目录(运行时由 compose 把宿主 ./data 挂载到此;含 SQLite 与加密 store)。
|
||||
RUN mkdir -p /app/data
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,124 @@
|
||||
# daily-bot-nest
|
||||
|
||||
多房间 Matrix 机器人平台(NestJS 重构版)。每个房间机器人是一个**自包含的功能模块**,
|
||||
可**共享账号**或使用**独立 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(命令 + 日报定时)
|
||||
```
|
||||
|
||||
### 设计要点
|
||||
- **账号可共享/独立**: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。
|
||||
|
||||
## 快速开始(本地)
|
||||
|
||||
```bash
|
||||
cp .env.example .env # 配置 DATABASE_URL / DRY_RUN / 各账号密码
|
||||
cp config/bots.example.yaml config/bots.yaml # 复制配置模板,填写真实房间 ID 与账号
|
||||
npm install
|
||||
npm run prisma:generate
|
||||
npm run prisma:push # 初始化数据库表
|
||||
npm test # 跑单元测试
|
||||
npm run test:integration # 跑集成测试(使用临时 SQLite,自动清理)
|
||||
DRY_RUN=true npm run start # 不连 Matrix 的装配验证(打印路由表)
|
||||
```
|
||||
|
||||
> **注意**:`config/bots.yaml` 包含真实凭据,已加入 `.gitignore` 不会被提交。
|
||||
> 首次克隆后必须先从 `bots.example.yaml` 复制并填写,否则启动时会报错提示。
|
||||
|
||||
真实运行:把 `.env` 里 `DRY_RUN` 设为 false,并填好 `config/bots.yaml` 的房间与各账号密码。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
```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 |
|
||||
| `!level set <用户ID> <等级>` | 设置等级(等级支持中文「黄金」或英文 `gold`)**🔒 管理员** |
|
||||
| `!level raise <用户ID>` | 提升一级 **🔒 管理员** |
|
||||
| `!level super <用户ID>` | 赋予超级管理(免统计/免踢)**🔒 管理员** |
|
||||
| `!level clear <用户ID>` | 清除等级为青铜 **🔒 管理员** |
|
||||
| `!reset` | 重置所有人当日签到状态 **🔒 管理员** |
|
||||
| `!test daily\|monthly` | 手动触发日报/月报(运维测试用)**🔒 管理员** |
|
||||
| `!echo <文本>` / `!ping` / `!help` | 杂项 |
|
||||
|
||||
等级:超级管理 / 青铜 / 白银 / 黄金 / 铂金 / 钻石(内部存英文 key,仅展示转中文)。
|
||||
|
||||
> **🔒 管理员命令权限**:`level` / `reset` / `test` 仅 **房间内 power level ≥ `adminPowerLevel`(默认 100)**
|
||||
> 或在 `config.admins` 白名单中的用户可调用,其他人发送会被拒绝。这是信任根 —— DB 里的「超级管理」
|
||||
> 等级只表示免统计/免踢,**不等于**命令权限。power level 在 Element 的「房间设置 → 权限」里给成员调整
|
||||
> (100=管理员、50=版主);`admins` 留空即纯按 power level 判定,无需写死名单。
|
||||
|
||||
### 定时任务
|
||||
- **每日 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 之外的补充,可留空) |
|
||||
|
||||
## 新增一个机器人(例: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: [...] }`。
|
||||
@@ -0,0 +1,40 @@
|
||||
# 账号:每个唯一账号只会登录一次并复用一个 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)"
|
||||
|
||||
# 每个 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: [] # 永不踢出的用户(Super 等级也永不踢)
|
||||
# - "@vip:example.com"
|
||||
|
||||
# 示例:共享 main 账号的另一个 bot(实现后取消注释并启用)
|
||||
# - name: notify
|
||||
# account: main
|
||||
# rooms:
|
||||
# - "!anotherRoom:example.com"
|
||||
Whitespace-only changes.
@@ -0,0 +1,24 @@
|
||||
services:
|
||||
daily-bot:
|
||||
build: .
|
||||
container_name: daily-bot-nest
|
||||
# 仅在异常退出(非 0)时重启。凭据错误会延迟退出以节流,避免无限高频重登。
|
||||
restart: on-failure
|
||||
env_file: .env
|
||||
environment:
|
||||
# SQLite 落到挂载卷,保证容器重建后数据不丢。
|
||||
DATABASE_URL: "file:/app/data/prod.db"
|
||||
# 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),导致解密失败。
|
||||
- matrix-crypto:/app/data/matrix
|
||||
# 配置热改:改完重启容器即可生效。
|
||||
- ./config:/app/config:ro
|
||||
|
||||
volumes:
|
||||
# 命名卷:加密会话与设备密钥持久化于此,容器重建/重启不丢,device 固定不再重新验证。
|
||||
matrix-crypto:
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# 启动前确保数据库表已就绪(SQLite/Postgres 均适用)。
|
||||
# 幂等:已存在则无操作。
|
||||
echo "[entrypoint] syncing database schema..."
|
||||
npx prisma db push --skip-generate
|
||||
|
||||
echo "[entrypoint] starting daily-bot-nest..."
|
||||
exec node dist/main.js
|
||||
@@ -0,0 +1,14 @@
|
||||
/** @type {import('jest').Config} */
|
||||
module.exports = {
|
||||
moduleFileExtensions: ['js', 'json', 'ts'],
|
||||
rootDir: 'src',
|
||||
testRegex: '\\.integration\\.spec\\.ts$',
|
||||
transform: {
|
||||
'^.+\\.(t|j)s$': 'ts-jest',
|
||||
},
|
||||
collectCoverageFrom: ['**/*.(t|j)s'],
|
||||
coverageDirectory: '../coverage-integration',
|
||||
testEnvironment: 'node',
|
||||
// 集成测试串行执行,避免多个测试同时写同一个 SQLite 文件
|
||||
maxWorkers: 1,
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
Generated
+8978
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "daily-bot-nest",
|
||||
"version": "0.1.0",
|
||||
"description": "Multi-room Matrix bot platform built with NestJS",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:prod": "node dist/main.js",
|
||||
"lint": "eslint \"src/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:integration": "jest --config jest.integration.config.js",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:push": "prisma db push"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^10.4.4",
|
||||
"@nestjs/core": "^10.4.4",
|
||||
"@nestjs/platform-express": "^10.4.4",
|
||||
"@nestjs/schedule": "^4.1.1",
|
||||
"@prisma/client": "^5.20.0",
|
||||
"cron": "^3.1.7",
|
||||
"js-yaml": "^4.1.0",
|
||||
"matrix-bot-sdk": "^0.8.0",
|
||||
"prisma": "^5.20.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.4.5",
|
||||
"@nestjs/schematics": "^10.1.4",
|
||||
"@nestjs/testing": "^10.4.4",
|
||||
"@types/jest": "^29.5.13",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^22.7.4",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.6.2"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": "(?<!\\.integration)\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
// 用 docker compose 在目标机本地构建,native 即正确目标,无需多架构。
|
||||
binaryTargets = ["native"]
|
||||
}
|
||||
|
||||
datasource db {
|
||||
// 起步用 SQLite,零运维。切换 Postgres 只需改 provider + url。
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
/// 通用 KV 状态表,对应 Rust 版 Sled 的 `scope:id` 模式。
|
||||
/// botName 充当 scope,实现各 bot 数据隔离。
|
||||
model BotState {
|
||||
botName String
|
||||
key String
|
||||
valueJson String
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@id([botName, key])
|
||||
@@map("bot_state")
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# scripts/ 下默认忽略一切(read-history 等会含解密后的私密数据/导出目录,
|
||||
# 以及未来新增的临时脚本),只放行 cross-sign 的源码。
|
||||
*
|
||||
!.gitignore
|
||||
!cross-sign/
|
||||
!cross-sign/**
|
||||
# 但 cross-sign 下的依赖仍不提交。
|
||||
cross-sign/node_modules/
|
||||
@@ -0,0 +1,43 @@
|
||||
# cross-sign 一次性工具
|
||||
|
||||
给 bot 设备做 **cross-signing(交叉签名)**,让它在 Element 设备列表里显示为
|
||||
「已验证」(绿盾),并触发你的其它设备自动向 bot 分享房间密钥(从而能解部分旧消息)。
|
||||
|
||||
## 为什么需要它
|
||||
|
||||
bot 主程序用的是 `matrix-bot-sdk`,其底层加密内核
|
||||
(`@matrix-org/[email protected]`)**不支持设备验证 / cross-signing**,
|
||||
所以你在 Element 里点「验证」会一直卡在「等待对方接受」。
|
||||
|
||||
本工具改用官方 **`matrix-js-sdk`**(支持完整验证)临时登录一次,从你的
|
||||
Secret Storage(4S)取出 cross-signing 私钥,直接给目标设备签名 —— 等价于
|
||||
Element 里 SAS 对暗号成功后的那一步。签完立即登出并删除这个临时设备。
|
||||
**bot 运行时完全不受影响。**
|
||||
|
||||
## 前提
|
||||
|
||||
你的 Matrix 账号必须**已设置过 cross-signing + 安全密钥(Security Key)或安全短语**
|
||||
(Element → 设置 → 安全与隐私 → 加密)。
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
cd scripts/cross-sign
|
||||
npm install # 首次需要
|
||||
node ./cross-sign.mjs
|
||||
```
|
||||
|
||||
然后按提示**交互式粘贴**即可(无需任何环境变量 / 配置文件):
|
||||
|
||||
1. 账号域名或 API 地址(回车用默认 `tchncs.de`)
|
||||
2. 账号 user id(回车用默认 `@eskimapro:tchncs.de`)
|
||||
3. 账号密码 —— **粘贴时不回显**
|
||||
4. 安全密钥(base58,如 `EsTc ...`)—— 不回显;直接回车则改填安全短语
|
||||
5. 要签名的设备 ID(回车用默认 `ZHEAJZJMDZ`;留空则签名名下所有未验证设备)
|
||||
|
||||
跑一次即可,之后无需再跑(除非 bot 重新登录产生了新设备)。
|
||||
|
||||
## 注意
|
||||
|
||||
- 密码、恢复密钥/短语只在本机脚本内使用,不会上传任何第三方;输入时不回显。
|
||||
- 过程中会**短暂**出现一个名为 `cross-sign-temp (可删)` 的临时设备,脚本结束会自动删除。
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* 一次性交互脚本:用你的「恢复密钥 / 安全短语」给 bot 设备做 cross-signing。
|
||||
*
|
||||
* 背景:bot 跑的 matrix-bot-sdk(底层 crypto 0.4.0)不支持设备验证,
|
||||
* 所以在 Element 里点「验证」会一直卡住。本脚本用官方 matrix-js-sdk
|
||||
* 临时登录一次,从你的 Secret Storage(4S)取出 cross-signing 私钥,
|
||||
* 直接给目标设备签名(等价于 Element 里 SAS 验证成功后的那一步),
|
||||
* 签完立刻登出这个临时设备。bot 运行时完全不动。
|
||||
*
|
||||
* 用法:node ./cross-sign.mjs 然后按提示粘贴即可。
|
||||
*/
|
||||
import { createClient, AutoDiscovery } from 'matrix-js-sdk';
|
||||
import { decodeRecoveryKey } from 'matrix-js-sdk/lib/crypto-api/recovery-key.js';
|
||||
import { pbkdf2 } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { stdin, stdout } from 'node:process';
|
||||
|
||||
const pbkdf2Async = promisify(pbkdf2);
|
||||
|
||||
function fail(msg) {
|
||||
console.error(`❌ ${msg}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** 普通提问;支持默认值(直接回车采用) */
|
||||
function ask(question, def) {
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
const suffix = def ? ` [${def}]` : '';
|
||||
return new Promise((resolve) => {
|
||||
rl.question(`${question}${suffix}: `, (ans) => {
|
||||
rl.close();
|
||||
resolve((ans.trim() || def || '').trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** 隐藏输入(粘贴时不回显),用于密码 / 恢复密钥 */
|
||||
function askSecret(question) {
|
||||
return new Promise((resolve) => {
|
||||
// 先把提示语打印出来(可见),再静音后续按键回显
|
||||
stdout.write(`${question}: `);
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
rl._writeToOutput = function (str) {
|
||||
// 仅放行换行,其余按键不回显
|
||||
if (str.includes('\n')) rl.output.write('\n');
|
||||
};
|
||||
rl.question('', (ans) => {
|
||||
rl.close();
|
||||
resolve(ans.trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let RECOVERY_KEY = '';
|
||||
let SECURITY_PHRASE = '';
|
||||
let PASSWORD = '';
|
||||
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');
|
||||
PASSWORD = await askSecret('账号密码(粘贴,不回显)');
|
||||
if (!PASSWORD) fail('必须输入密码。');
|
||||
|
||||
console.log(
|
||||
'\n签名需要你的「安全密钥」或「安全短语」二选一。安全密钥优先,直接回车切到安全短语。',
|
||||
);
|
||||
RECOVERY_KEY = await askSecret('安全密钥(base58,如 EsTc...;不回显)');
|
||||
if (RECOVERY_KEY) {
|
||||
try {
|
||||
decodeRecoveryKey(RECOVERY_KEY.replace(/\s+/g, ''));
|
||||
} catch {
|
||||
fail('安全密钥格式不对(应是 EsTx... 的 base58,4 字符一组共 12 组)。');
|
||||
}
|
||||
} else {
|
||||
SECURITY_PHRASE = await askSecret('安全短语(不回显)');
|
||||
if (!SECURITY_PHRASE) fail('安全密钥和安全短语必须至少提供一个。');
|
||||
}
|
||||
|
||||
TARGET_DEVICE_ID = await ask(
|
||||
'要签名的设备 ID(留空=签名名下所有未验证设备)',
|
||||
'ZHEAJZJMDZ',
|
||||
);
|
||||
|
||||
// 1) 解析真实 API 地址(支持裸域名 well-known 发现)
|
||||
const baseUrl = await resolveBaseUrl(homeserverInput);
|
||||
console.log(`\n🔗 homeserver API: ${baseUrl}`);
|
||||
|
||||
// 2) 临时登录(产生一个临时设备,结束后登出删除)
|
||||
const loginClient = createClient({ baseUrl });
|
||||
console.log('🔑 临时登录中...');
|
||||
const login = await loginClient.login('m.login.password', {
|
||||
identifier: { type: 'm.id.user', user: userId },
|
||||
password: PASSWORD,
|
||||
initial_device_display_name: 'cross-sign-temp (可删)',
|
||||
});
|
||||
const accessToken = login.access_token;
|
||||
const deviceId = login.device_id;
|
||||
const realUserId = login.user_id;
|
||||
console.log(`✅ 临时设备已登录: ${deviceId}`);
|
||||
|
||||
// 3) 构建带 crypto 的 client,提供 secret storage 取钥回调
|
||||
const client = createClient({
|
||||
baseUrl,
|
||||
accessToken,
|
||||
userId: realUserId,
|
||||
deviceId,
|
||||
cryptoCallbacks: { getSecretStorageKey },
|
||||
});
|
||||
|
||||
let signedOk = false;
|
||||
try {
|
||||
await client.initRustCrypto({ useIndexedDB: false });
|
||||
const crypto = client.getCrypto();
|
||||
if (!crypto) fail('crypto 初始化失败。');
|
||||
|
||||
console.log('🔄 启动同步(拉取设备列表 / secret storage)...');
|
||||
await client.startClient({ initialSyncLimit: 1 });
|
||||
await waitForSync(client);
|
||||
|
||||
// 4) 从 4S 导入 cross-signing 私钥(不重置已有密钥)
|
||||
console.log('📥 从 Secret Storage 导入 cross-signing 私钥...');
|
||||
await crypto.bootstrapCrossSigning({
|
||||
authUploadDeviceSigningKeys: async (makeRequest) => {
|
||||
await makeRequest({
|
||||
type: 'm.login.password',
|
||||
identifier: { type: 'm.id.user', user: realUserId },
|
||||
password: PASSWORD,
|
||||
});
|
||||
},
|
||||
});
|
||||
if (!(await crypto.isCrossSigningReady())) {
|
||||
fail(
|
||||
'cross-signing 未就绪——恢复密钥/短语可能不对,或账号未设置过 cross-signing。',
|
||||
);
|
||||
}
|
||||
console.log('✅ cross-signing 私钥就绪。');
|
||||
|
||||
// 5) 确定要签名的设备
|
||||
const targets = await resolveTargets(crypto, realUserId, deviceId);
|
||||
if (targets.length === 0) {
|
||||
console.log('ℹ️ 没有需要签名的设备(可能都已验证)。');
|
||||
}
|
||||
for (const dev of targets) {
|
||||
console.log(`✍️ 签名设备 ${dev} ...`);
|
||||
await crypto.crossSignDevice(dev);
|
||||
const st = await crypto.getDeviceVerificationStatus(realUserId, dev);
|
||||
console.log(` → crossSigningVerified=${st?.crossSigningVerified ?? '?'}`);
|
||||
}
|
||||
signedOk = true;
|
||||
} finally {
|
||||
// 6) 清理:登出临时设备(删除它),停止 client
|
||||
try {
|
||||
client.stopClient();
|
||||
} catch {}
|
||||
try {
|
||||
console.log('🧹 登出并删除临时设备...');
|
||||
await client.logout(true);
|
||||
console.log('✅ 临时设备已删除。');
|
||||
} catch (e) {
|
||||
console.warn('⚠️ 登出临时设备失败(可手动在 Element 删除):', e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (signedOk) {
|
||||
console.log('\n🎉 完成!刷新 Element 设备列表即可看到目标设备已验证(绿盾)。');
|
||||
}
|
||||
process.exit(signedOk ? 0 : 1);
|
||||
}
|
||||
|
||||
/** secret storage 取钥回调:用恢复密钥或安全短语派生 4S 密钥 */
|
||||
async function getSecretStorageKey({ keys }) {
|
||||
const keyId = Object.keys(keys)[0];
|
||||
const info = keys[keyId];
|
||||
let privateKey;
|
||||
if (RECOVERY_KEY) {
|
||||
privateKey = decodeRecoveryKey(RECOVERY_KEY.replace(/\s+/g, ''));
|
||||
} else {
|
||||
const pp = info?.passphrase;
|
||||
if (!pp?.salt || !pp?.iterations) {
|
||||
fail('该账号的 4S 没有 passphrase 信息,请改用安全密钥。');
|
||||
}
|
||||
privateKey = new Uint8Array(
|
||||
await pbkdf2Async(SECURITY_PHRASE, pp.salt, pp.iterations, 32, 'sha512'),
|
||||
);
|
||||
}
|
||||
return [keyId, privateKey];
|
||||
}
|
||||
|
||||
/** 决定签名目标:指定了 TARGET_DEVICE_ID 就只签它;否则签名所有未交叉验证的自有设备(除临时设备) */
|
||||
async function resolveTargets(crypto, userId, tempDeviceId) {
|
||||
if (TARGET_DEVICE_ID) return [TARGET_DEVICE_ID];
|
||||
const map = await crypto.getUserDeviceInfo([userId], true);
|
||||
const devices = map.get(userId);
|
||||
const out = [];
|
||||
if (!devices) return out;
|
||||
for (const devId of devices.keys()) {
|
||||
if (devId === tempDeviceId) continue;
|
||||
const st = await crypto.getDeviceVerificationStatus(userId, devId);
|
||||
if (!st?.crossSigningVerified) out.push(devId);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** well-known 发现:裸域名 → 真实 API 地址 */
|
||||
async function resolveBaseUrl(input) {
|
||||
if (/^https?:\/\//.test(input)) return input.replace(/\/$/, '');
|
||||
const res = await AutoDiscovery.findClientConfig(input);
|
||||
const url = res?.['m.homeserver']?.base_url;
|
||||
if (!url) fail(`无法从 ${input} 发现 homeserver,请直接填完整 API 地址。`);
|
||||
return url.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
/** 等待首次同步完成 */
|
||||
function waitForSync(client) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const to = setTimeout(() => reject(new Error('同步超时(60s)')), 60_000);
|
||||
client.once('sync', function handler(state) {
|
||||
if (state === 'PREPARED') {
|
||||
clearTimeout(to);
|
||||
resolve();
|
||||
} else if (state === 'ERROR') {
|
||||
clearTimeout(to);
|
||||
reject(new Error('同步出错'));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('💥 出错:', e);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
+216
@@ -0,0 +1,216 @@
|
||||
{
|
||||
"name": "cross-sign-tool",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cross-sign-tool",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"matrix-js-sdk": "^34.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.29.7.tgz",
|
||||
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@matrix-org/matrix-sdk-crypto-wasm": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/@matrix-org/matrix-sdk-crypto-wasm/-/matrix-sdk-crypto-wasm-9.1.0.tgz",
|
||||
"integrity": "sha512-CtPoNcoRW6ehwxpRQAksG3tR+NJ7k4DV02nMFYTDwQtie1V4R8OTY77BjEIs97NOblhtS26jU8m1lWsOBEz0Og==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@matrix-org/olm": {
|
||||
"version": "3.2.15",
|
||||
"resolved": "https://registry.npmmirror.com/@matrix-org/olm/-/olm-3.2.15.tgz",
|
||||
"integrity": "sha512-S7lOrndAK9/8qOtaTq/WhttJC/o4GAzdfK0MUPpo8ApzsJEC0QjtwrkC3KBXdFP1cD1MXi/mlKR7aaoVMKgs6Q==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@types/events": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/@types/events/-/events-3.0.3.tgz",
|
||||
"integrity": "sha512-trOc4AAUThEz9hapPtSd7wf5tiQKvTtu5b371UxXdTuqzIh0ArcRspRP0i0Viu+LXstIQ1z96t1nsPxT9ol01g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/retry": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmmirror.com/@types/retry/-/retry-0.12.0.tgz",
|
||||
"integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/another-json": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/another-json/-/another-json-0.2.0.tgz",
|
||||
"integrity": "sha512-/Ndrl68UQLhnCdsAzEXLMFuOR546o2qbYRqCglaNHbjXrwG1ayTcdwr3zkSGOGtGXDyR5X9nCFfnyG2AFJIsqg==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/base-x": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/base-x/-/base-x-5.0.1.tgz",
|
||||
"integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bs58": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/bs58/-/bs58-6.0.0.tgz",
|
||||
"integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base-x": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmmirror.com/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/events": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmmirror.com/events/-/events-3.3.0.tgz",
|
||||
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.8.x"
|
||||
}
|
||||
},
|
||||
"node_modules/jwt-decode": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/jwt-decode/-/jwt-decode-4.0.0.tgz",
|
||||
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/loglevel": {
|
||||
"version": "1.9.2",
|
||||
"resolved": "https://registry.npmmirror.com/loglevel/-/loglevel-1.9.2.tgz",
|
||||
"integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "tidelift",
|
||||
"url": "https://tidelift.com/funding/github/npm/loglevel"
|
||||
}
|
||||
},
|
||||
"node_modules/matrix-events-sdk": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/matrix-events-sdk/-/matrix-events-sdk-0.0.1.tgz",
|
||||
"integrity": "sha512-1QEOsXO+bhyCroIe2/A5OwaxHvBm7EsSQ46DEDn8RBIfQwN5HWBpFvyWWR4QY0KHPPnnJdI99wgRiAl7Ad5qaA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/matrix-js-sdk": {
|
||||
"version": "34.13.0",
|
||||
"resolved": "https://registry.npmmirror.com/matrix-js-sdk/-/matrix-js-sdk-34.13.0.tgz",
|
||||
"integrity": "sha512-AAU8ZdCawca+7ucQfdcC3LA85OtCTV7QeqcjvKt/ZZhU3xL9VoawuoRQ+4R6H8KZnqyJmT4j7bdeC0jG4qcqLg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@matrix-org/matrix-sdk-crypto-wasm": "^9.0.0",
|
||||
"@matrix-org/olm": "3.2.15",
|
||||
"another-json": "^0.2.0",
|
||||
"bs58": "^6.0.0",
|
||||
"content-type": "^1.0.4",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"loglevel": "^1.7.1",
|
||||
"matrix-events-sdk": "0.0.1",
|
||||
"matrix-widget-api": "^1.10.0",
|
||||
"oidc-client-ts": "^3.0.1",
|
||||
"p-retry": "4",
|
||||
"sdp-transform": "^2.14.1",
|
||||
"unhomoglyph": "^1.0.6",
|
||||
"uuid": "11"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/matrix-widget-api": {
|
||||
"version": "1.17.0",
|
||||
"resolved": "https://registry.npmmirror.com/matrix-widget-api/-/matrix-widget-api-1.17.0.tgz",
|
||||
"integrity": "sha512-5FHoo3iEP3Bdlv5jsYPWOqj+pGdFQNLWnJLiB0V7Ygne7bb+Gsj3ibyFyHWC6BVw+Z+tSW4ljHpO17I9TwStwQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@types/events": "^3.0.0",
|
||||
"events": "^3.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/oidc-client-ts": {
|
||||
"version": "3.5.0",
|
||||
"resolved": "https://registry.npmmirror.com/oidc-client-ts/-/oidc-client-ts-3.5.0.tgz",
|
||||
"integrity": "sha512-l2q8l9CTCTOlbX+AnK4p3M+4CEpKpyQhle6blQkdFhm0IsBqsxm15bYaSa11G7pWdsYr6epdsRZxJpCyCRbT8A==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"jwt-decode": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/p-retry": {
|
||||
"version": "4.6.2",
|
||||
"resolved": "https://registry.npmmirror.com/p-retry/-/p-retry-4.6.2.tgz",
|
||||
"integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/retry": "0.12.0",
|
||||
"retry": "^0.13.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/retry": {
|
||||
"version": "0.13.1",
|
||||
"resolved": "https://registry.npmmirror.com/retry/-/retry-0.13.1.tgz",
|
||||
"integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/sdp-transform": {
|
||||
"version": "2.15.0",
|
||||
"resolved": "https://registry.npmmirror.com/sdp-transform/-/sdp-transform-2.15.0.tgz",
|
||||
"integrity": "sha512-KrOH82c/W+GYQ0LHqtr3caRpM3ITglq3ljGUIb8LTki7ByacJZ9z+piSGiwZDsRyhQbYBOBJgr2k6X4BZXi3Kw==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"sdp-verify": "checker.js"
|
||||
}
|
||||
},
|
||||
"node_modules/unhomoglyph": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmmirror.com/unhomoglyph/-/unhomoglyph-1.0.6.tgz",
|
||||
"integrity": "sha512-7uvcWI3hWshSADBu4JpnyYbTVc7YlhF5GDW/oPD5AxIxl34k4wXR3WDkPnzLxkN32LiTCTKMQLtKVZiwki3zGg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "11.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/uuid/-/uuid-11.1.1.tgz",
|
||||
"integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "dist/esm/bin/uuid"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "cross-sign-tool",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"description": "一次性脚本:用恢复密钥给 bot 设备做 cross-signing(变已验证)。",
|
||||
"dependencies": {
|
||||
"matrix-js-sdk": "^34.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
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';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
DbModule,
|
||||
MatrixModule,
|
||||
BotModule,
|
||||
// —— 在此注册各房间机器人 feature module ——
|
||||
CheckinModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,415 @@
|
||||
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,
|
||||
clearLevel,
|
||||
levelChoices,
|
||||
levelLabel,
|
||||
newUserState,
|
||||
parseLevel,
|
||||
raiseLevel,
|
||||
resetDaily,
|
||||
resetMonthly,
|
||||
setLevel,
|
||||
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 'level':
|
||||
if (!(await this.requireAdmin(cmd, ctx))) break;
|
||||
await this.handleLevel(cmd, 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] — 查询签到状态',
|
||||
'!level set <用户ID> <等级> — 设置等级(管理员)',
|
||||
'!level raise <用户ID> — 提升一级(管理员)',
|
||||
'!level super <用户ID> — 赋予超级管理(管理员)',
|
||||
'!level clear <用户ID> — 清除等级(管理员)',
|
||||
'!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 handleLevel(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
const [action, userId, levelArg] = cmd.args;
|
||||
if (!action) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
'用法: !level set|raise|super|clear <用户ID> [等级]',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!userId) {
|
||||
await ctx.reply(cmd.raw, '请提供用户ID,例如: !level super @user:hs');
|
||||
return;
|
||||
}
|
||||
|
||||
const current = (await ctx.db.get<UserState>(userId)) ?? newUserState();
|
||||
switch (action) {
|
||||
case 'set': {
|
||||
const level = levelArg ? parseLevel(levelArg) : null;
|
||||
if (!level) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
`无效的等级。可选: ${levelChoices()}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ctx.db.set(userId, setLevel(current, level));
|
||||
await ctx.reply(cmd.raw, `已设置用户 ${userId} 的等级为 ${levelLabel(level)}`);
|
||||
break;
|
||||
}
|
||||
case 'raise': {
|
||||
const next = raiseLevel(current);
|
||||
await ctx.db.set(userId, next);
|
||||
await ctx.reply(cmd.raw, `已提升用户 ${userId} 的等级为 ${levelLabel(next.level)}`);
|
||||
break;
|
||||
}
|
||||
case 'super':
|
||||
await ctx.db.set(userId, setLevel(current, 'Super'));
|
||||
await ctx.reply(cmd.raw, `已赋予用户 ${userId} 超级权限`);
|
||||
break;
|
||||
case 'clear':
|
||||
await ctx.db.set(userId, clearLevel(current));
|
||||
await ctx.reply(cmd.raw, `已清除用户 ${userId} 的等级为${levelLabel('Bronze')}`);
|
||||
break;
|
||||
default:
|
||||
await ctx.reply(cmd.raw, `未知的 level 操作: ${action}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ——— 定时任务 ———
|
||||
|
||||
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);
|
||||
// 已签到且非 Super 的人数(对应 Rust 的 checked_nums)。
|
||||
const checkedNums = entries.filter(
|
||||
([, s]) => s.isCheckinToday && s.level !== 'Super',
|
||||
).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) {
|
||||
const targets = computeKickTargets(
|
||||
rows,
|
||||
this.cfg.kickDays,
|
||||
this.cfg.whitelist,
|
||||
);
|
||||
for (const userId of targets) {
|
||||
await ctx.kick(room, userId, `超过 ${this.cfg.kickDays} 天未签到`);
|
||||
this.logger.log(`已踢出 ${userId}`);
|
||||
}
|
||||
if (targets.length > 0) {
|
||||
await ctx.send(room, `已踢出 ${targets.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
|
||||
.filter(([, s]) => s.level !== 'Super')
|
||||
.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}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
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 }> =
|
||||
[];
|
||||
members: string[] = [];
|
||||
powerLevels: Record<string, number> = {};
|
||||
|
||||
constructor(public readonly db: BotStore) {}
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
|
||||
/**
|
||||
* 签到 bot 模块。新增 bot 时照此模式新建一个目录与模块,
|
||||
* 在 AppModule 里 import 即可,核心代码无需改动。
|
||||
*/
|
||||
@Module({
|
||||
providers: [CheckinBot],
|
||||
})
|
||||
export class CheckinModule {}
|
||||
@@ -0,0 +1,178 @@
|
||||
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 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('sets level via Chinese name and displays Chinese label', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
await bot.onCommand(
|
||||
parseCommand(
|
||||
msg('level set @bob:hs 黄金', '@admin:hs'),
|
||||
'level set @bob:hs 黄金',
|
||||
),
|
||||
ctx,
|
||||
);
|
||||
expect(ctx.sent[0]).toContain('黄金');
|
||||
const state = await ctx.db.get<UserState>('@bob:hs');
|
||||
expect(state?.level).toBe('Gold');
|
||||
});
|
||||
|
||||
it('denies privileged commands from non-admins', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// @alice 非管理员,试图把自己设为超管应被拒绝。
|
||||
await bot.onCommand(
|
||||
parseCommand(
|
||||
msg('level super @alice:hs', '@alice:hs'),
|
||||
'level super @alice:hs',
|
||||
),
|
||||
ctx,
|
||||
);
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
expect(await ctx.db.get<UserState>('@alice:hs')).toBeNull();
|
||||
|
||||
// reset / test 同样受限。
|
||||
await bot.onCommand(parseCommand(msg('reset', '@alice:hs'), 'reset'), ctx);
|
||||
expect(ctx.sent[1]).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('level set @bob:hs 黄金', '@mod:hs'),
|
||||
'level set @bob:hs 黄金',
|
||||
),
|
||||
ctx,
|
||||
);
|
||||
expect(ctx.sent[0]).toContain('黄金');
|
||||
expect((await ctx.db.get<UserState>('@bob:hs'))?.level).toBe('Gold');
|
||||
});
|
||||
|
||||
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('青铜');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
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 and super', () => {
|
||||
const states = new Map<string, UserState>([
|
||||
['@a:hs', state({ isCheckinToday: true, checkinUnixMs: NOW })],
|
||||
['@b:hs', state({ checkinUnixMs: NOW - 10 * DAY })],
|
||||
['@s:hs', state({ level: 'Super', checkinUnixMs: NOW - 50 * DAY })],
|
||||
]);
|
||||
// @c:hs 不在 DB ⇒ 从未签到
|
||||
const rows = analyzeUnchecked(
|
||||
['@a:hs', '@b:hs', '@s: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 未达阈值
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
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));
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
export type UserLevel =
|
||||
| 'Super'
|
||||
| 'Bronze'
|
||||
| 'Silver'
|
||||
| 'Gold'
|
||||
| 'Platinum'
|
||||
| 'Diamond';
|
||||
|
||||
/** 非 Super 的等级升序,用于 raise 逻辑。 */
|
||||
export const LEVELS_ASC: UserLevel[] = [
|
||||
'Bronze',
|
||||
'Silver',
|
||||
'Gold',
|
||||
'Platinum',
|
||||
'Diamond',
|
||||
];
|
||||
|
||||
export const VALID_LEVELS: UserLevel[] = ['Super', ...LEVELS_ASC];
|
||||
|
||||
/** 等级的中文显示名(内部仍用英文 key,只在展示层转中文)。 */
|
||||
export const LEVEL_LABELS: Record<UserLevel, string> = {
|
||||
Super: '超级管理',
|
||||
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 state.level === 'Super';
|
||||
}
|
||||
|
||||
/** 执行一次签到,更新状态与等级(移植自 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);
|
||||
}
|
||||
if (next.level === 'Super') {
|
||||
return next;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** 升一级(移植自 Rust raise_level):Super 与 Diamond 不变。 */
|
||||
export function raiseLevel(state: UserState): UserState {
|
||||
if (state.level === 'Super') return state;
|
||||
const idx = LEVELS_ASC.indexOf(state.level);
|
||||
const nextIdx = Math.min(idx + 1, LEVELS_ASC.length - 1);
|
||||
return { ...state, level: LEVELS_ASC[nextIdx] };
|
||||
}
|
||||
|
||||
export function setLevel(state: UserState, level: UserLevel): UserState {
|
||||
return { ...state, level };
|
||||
}
|
||||
|
||||
/** 清空等级为 Bronze(移植自 Rust clean_user_level)。 */
|
||||
export function clearLevel(state: UserState): UserState {
|
||||
return { ...state, level: 'Bronze' };
|
||||
}
|
||||
|
||||
/** 重置当日签到标记。 */
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { ConfigService } from './config.service';
|
||||
|
||||
const FIXTURE_PATH = resolve(__dirname, '../test/fixtures/bots.test.yaml');
|
||||
const MISSING_PATH = resolve(__dirname, '../test/fixtures/nonexistent.yaml');
|
||||
|
||||
function makeService(configPath: string): ConfigService {
|
||||
process.env.BOT_CONFIG_PATH = configPath;
|
||||
return new ConfigService();
|
||||
}
|
||||
|
||||
describe('ConfigService (integration)', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.BOT_CONFIG_PATH;
|
||||
delete process.env.TEST_ACCOUNT_PW;
|
||||
});
|
||||
|
||||
it('loads and validates a well-formed config file', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
const cfg = svc.all;
|
||||
|
||||
expect(Object.keys(cfg.accounts)).toEqual(
|
||||
expect.arrayContaining(['main', 'checkin']),
|
||||
);
|
||||
expect(cfg.bots).toHaveLength(1);
|
||||
expect(cfg.bots[0].name).toBe('checkin');
|
||||
expect(cfg.bots[0].rooms).toEqual(['!testroom:example.com']);
|
||||
});
|
||||
|
||||
it('exposes bots and getAccount helpers', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
|
||||
expect(svc.bots[0].account).toBe('checkin');
|
||||
|
||||
const acc = svc.getAccount('main');
|
||||
expect(acc.homeServer).toBe('https://matrix.example.com');
|
||||
expect(acc.userId).toBe('@testbot:example.com');
|
||||
});
|
||||
|
||||
it('throws a user-friendly error when config file does not exist', () => {
|
||||
const svc = makeService(MISSING_PATH);
|
||||
expect(() => svc.all).toThrow(/配置文件不存在/);
|
||||
expect(() => svc.all).toThrow(/bots.example.yaml/);
|
||||
});
|
||||
|
||||
it('resolves env() references from environment variables', () => {
|
||||
// Write a temp config that uses env() ref, then verify it resolves.
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.envref.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@bot:example.com"
|
||||
password: "env(TEST_ACCOUNT_PW)"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
process.env.TEST_ACCOUNT_PW = 'secret-from-env';
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
const acc = svc.getAccount('bot');
|
||||
expect(acc.password).toBe('secret-from-env');
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('throws when an env() referenced variable is not set', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.envmissing.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@bot:example.com"
|
||||
password: "env(MISSING_ENV_VAR_XYZ)"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
delete process.env.MISSING_ENV_VAR_XYZ;
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow(/MISSING_ENV_VAR_XYZ/);
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects config with an invalid homeServer URL', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.badurl.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "not-a-url"
|
||||
userId: "@bot:example.com"
|
||||
password: "secret"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow();
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects config with malformed userId', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.baduser.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "not-a-matrix-id"
|
||||
password: "secret"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow(/userId/);
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects config where bot room IDs are malformed', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.badroom.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@bot:example.com"
|
||||
password: "secret"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "not-a-room-id"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow(/roomId/);
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('caches the parsed config on subsequent accesses', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
const first = svc.all;
|
||||
const second = svc.all;
|
||||
expect(first).toBe(second); // same object reference
|
||||
});
|
||||
|
||||
it('reports isDryRun based on DRY_RUN env var', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
|
||||
process.env.DRY_RUN = 'true';
|
||||
expect(svc.isDryRun).toBe(true);
|
||||
|
||||
process.env.DRY_RUN = 'false';
|
||||
expect(svc.isDryRun).toBe(false);
|
||||
|
||||
delete process.env.DRY_RUN;
|
||||
expect(svc.isDryRun).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { ConfigService } from './config.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [ConfigService],
|
||||
exports: [ConfigService],
|
||||
})
|
||||
export class ConfigModule {}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import * as yaml from 'js-yaml';
|
||||
import {
|
||||
AccountConfig,
|
||||
BotConfig,
|
||||
RootConfig,
|
||||
rootConfigSchema,
|
||||
} from './schema';
|
||||
|
||||
/**
|
||||
* 加载并校验 bots.yaml。
|
||||
* 支持把配置里的 "env(VAR_NAME)" 解析为对应环境变量值,避免明文密码入库。
|
||||
* 采用惰性加载,确保即使在其它 provider 构造期被读取也已就绪。
|
||||
*/
|
||||
@Injectable()
|
||||
export class ConfigService {
|
||||
private readonly logger = new Logger(ConfigService.name);
|
||||
private config?: RootConfig;
|
||||
|
||||
private ensureLoaded(): RootConfig {
|
||||
if (this.config) return this.config;
|
||||
const path = resolve(process.env.BOT_CONFIG_PATH ?? './config/bots.yaml');
|
||||
let raw: string;
|
||||
try {
|
||||
raw = readFileSync(path, 'utf8');
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
throw new Error(
|
||||
`配置文件不存在: ${path}\n` +
|
||||
`请复制示例文件并填写配置:\n` +
|
||||
` cp config/bots.example.yaml config/bots.yaml\n` +
|
||||
`然后根据注释修改真实账号、房间等信息。`,
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const parsed = yaml.load(raw);
|
||||
const resolved = this.resolveEnvRefs(parsed);
|
||||
this.config = rootConfigSchema.parse(resolved);
|
||||
this.logger.log(
|
||||
`已加载配置: ${Object.keys(this.config.accounts).length} 个账号, ${this.config.bots.length} 个 bot`,
|
||||
);
|
||||
return this.config;
|
||||
}
|
||||
|
||||
get all(): RootConfig {
|
||||
return this.ensureLoaded();
|
||||
}
|
||||
|
||||
get bots(): BotConfig[] {
|
||||
return this.ensureLoaded().bots;
|
||||
}
|
||||
|
||||
getAccount(name: string): AccountConfig {
|
||||
const acc = this.ensureLoaded().accounts[name];
|
||||
if (!acc) {
|
||||
throw new Error(`未找到账号配置: ${name}`);
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
get isDryRun(): boolean {
|
||||
return (process.env.DRY_RUN ?? 'false').toLowerCase() === 'true';
|
||||
}
|
||||
|
||||
/** 递归把字符串里的 env(VAR) 替换为 process.env.VAR。 */
|
||||
private resolveEnvRefs(value: unknown): unknown {
|
||||
if (typeof value === 'string') {
|
||||
const match = value.match(/^env\((.+)\)$/);
|
||||
if (match) {
|
||||
const envVal = process.env[match[1]];
|
||||
if (envVal === undefined) {
|
||||
throw new Error(`配置引用了未设置的环境变量: ${match[1]}`);
|
||||
}
|
||||
return envVal;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v) => this.resolveEnvRefs(v));
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([k, v]) => [k, this.resolveEnvRefs(v)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const accountSchema = z.object({
|
||||
homeServer: z.string().url(),
|
||||
userId: z.string().regex(/^@.+:.+$/, 'userId 必须是 @user:server 形式'),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
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),
|
||||
config: z.record(z.any()).default({}),
|
||||
});
|
||||
|
||||
export const rootConfigSchema = z.object({
|
||||
accounts: z.record(accountSchema),
|
||||
bots: z.array(botSchema),
|
||||
});
|
||||
|
||||
export type AccountConfig = z.infer<typeof accountSchema>;
|
||||
export type BotConfig = z.infer<typeof botSchema>;
|
||||
export type RootConfig = z.infer<typeof rootConfigSchema>;
|
||||
@@ -0,0 +1,40 @@
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnApplicationBootstrap,
|
||||
OnApplicationShutdown,
|
||||
} from '@nestjs/common';
|
||||
import { SessionManager } from '../matrix/session-manager.service';
|
||||
import { BotRegistry } from './bot-registry.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,
|
||||
) {}
|
||||
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
for (const account of this.registry.accounts) {
|
||||
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.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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await this.sessions.stopAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
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}`;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { DiscoveryModule } from '@nestjs/core';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
import { Dispatcher } from './dispatcher.service';
|
||||
import { BotPlatformService } from './bot-platform.service';
|
||||
import { SchedulerService } from '../scheduler/scheduler.service';
|
||||
|
||||
/**
|
||||
* 核心 bot 平台模块。具体 bot 由各自的 feature module 通过
|
||||
* @RegisterBot() 标记并 provide,本模块用 DiscoveryService 自动发现。
|
||||
*/
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [DiscoveryModule],
|
||||
providers: [BotRegistry, Dispatcher, BotPlatformService, SchedulerService],
|
||||
exports: [BotRegistry, Dispatcher, BotPlatformService, SchedulerService],
|
||||
})
|
||||
export class BotModule {}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InboundMessage, MemberEvent } from '../command/types';
|
||||
import { CommandError, parseCommand } from '../command/command-parser';
|
||||
import { MatrixEventSink } from '../matrix/types';
|
||||
import { BotRegistry } from './bot-registry.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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onMember(ev: MemberEvent): Promise<void> {
|
||||
if (ev.membership !== 'join') return;
|
||||
const targets = this.registry.resolve(ev.account, ev.roomId);
|
||||
for (const { bot, ctx } of targets) {
|
||||
if (!bot.onMemberJoin) continue;
|
||||
try {
|
||||
await bot.onMemberJoin(ev, ctx);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} 处理成员事件失败: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
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);
|
||||
@@ -0,0 +1,43 @@
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import {
|
||||
CronSpec,
|
||||
InboundMessage,
|
||||
MemberEvent,
|
||||
ParsedCommand,
|
||||
} 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>;
|
||||
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>;
|
||||
registerCrons?(ctx: BotContext): CronSpec[];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { parseCommand, tokenize, CommandError } from './command-parser';
|
||||
import { InboundMessage } from './types';
|
||||
|
||||
const raw: InboundMessage = {
|
||||
eventId: 'e',
|
||||
account: 'a',
|
||||
roomId: '!r:hs',
|
||||
userId: '@u:hs',
|
||||
text: '',
|
||||
timestampMs: 0,
|
||||
};
|
||||
|
||||
describe('command-parser', () => {
|
||||
it('parses command and positional args', () => {
|
||||
const ast = parseCommand(raw, 'deploy service-a region-cn');
|
||||
expect(ast.command).toBe('deploy');
|
||||
expect(ast.args).toEqual(['service-a', 'region-cn']);
|
||||
expect(ast.options).toEqual({});
|
||||
});
|
||||
|
||||
it('parses --key=value and --key value', () => {
|
||||
const ast = parseCommand(raw, 'deploy --env=prod --region cn');
|
||||
expect(ast.options.env).toBe('prod');
|
||||
expect(ast.options.region).toBe('cn');
|
||||
});
|
||||
|
||||
it('treats trailing flag as true', () => {
|
||||
const ast = parseCommand(raw, 'sync --dry-run --limit=10 --verbose');
|
||||
expect(ast.options['dry-run']).toBe('true');
|
||||
expect(ast.options.limit).toBe('10');
|
||||
expect(ast.options.verbose).toBe('true');
|
||||
});
|
||||
|
||||
it('handles quotes', () => {
|
||||
expect(tokenize('send "hello world" \'to room\'')).toEqual([
|
||||
'send',
|
||||
'hello world',
|
||||
'to room',
|
||||
]);
|
||||
});
|
||||
|
||||
it('throws on unterminated quote', () => {
|
||||
expect(() => tokenize('cmd "oops')).toThrow(CommandError);
|
||||
});
|
||||
|
||||
it('throws on empty command', () => {
|
||||
expect(() => parseCommand(raw, ' ')).toThrow(CommandError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { InboundMessage, ParsedCommand } from './types';
|
||||
|
||||
export class CommandError extends Error {}
|
||||
|
||||
/**
|
||||
* 命令解析器,移植自 Rust 版 command_parser:
|
||||
* - 支持单/双引号、双引号内反斜杠转义
|
||||
* - --key=value / --key value / --flag(无值则为 "true")
|
||||
* 第一个 token 为命令名,其余为位置参数。
|
||||
*/
|
||||
export function tokenize(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let buf = '';
|
||||
let inSingle = false;
|
||||
let inDouble = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
if (ch === "'" && !inDouble) {
|
||||
inSingle = !inSingle;
|
||||
} else if (ch === '"' && !inSingle) {
|
||||
inDouble = !inDouble;
|
||||
} else if (ch === '\\' && inDouble) {
|
||||
const next = input[i + 1];
|
||||
if (next === undefined) {
|
||||
throw new CommandError('dangling escape');
|
||||
}
|
||||
buf += next;
|
||||
i++;
|
||||
} else if (/\s/.test(ch) && !inSingle && !inDouble) {
|
||||
if (buf.length > 0) {
|
||||
tokens.push(buf);
|
||||
buf = '';
|
||||
}
|
||||
} else {
|
||||
buf += ch;
|
||||
}
|
||||
}
|
||||
|
||||
if (inSingle || inDouble) {
|
||||
throw new CommandError('unterminated quote');
|
||||
}
|
||||
if (buf.length > 0) {
|
||||
tokens.push(buf);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parseCommand(raw: InboundMessage, text: string): ParsedCommand {
|
||||
const tokens = tokenize(text);
|
||||
if (tokens.length === 0) {
|
||||
throw new CommandError('empty command');
|
||||
}
|
||||
|
||||
const command = tokens[0];
|
||||
const args: string[] = [];
|
||||
const options: Record<string, string> = {};
|
||||
|
||||
let i = 1;
|
||||
while (i < tokens.length) {
|
||||
const token = tokens[i];
|
||||
if (token.startsWith('--')) {
|
||||
const body = token.slice(2);
|
||||
if (body.length === 0) {
|
||||
throw new CommandError('invalid option: --');
|
||||
}
|
||||
const eq = body.indexOf('=');
|
||||
if (eq >= 0) {
|
||||
const key = body.slice(0, eq);
|
||||
if (key.length === 0) {
|
||||
throw new CommandError(`invalid option key in '--${body}'`);
|
||||
}
|
||||
options[key] = body.slice(eq + 1);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const next = tokens[i + 1];
|
||||
if (next !== undefined && !next.startsWith('-')) {
|
||||
options[body] = next;
|
||||
i += 2;
|
||||
} else {
|
||||
options[body] = 'true';
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
args.push(token);
|
||||
i++;
|
||||
}
|
||||
|
||||
return { raw, command, args, options };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/** 归一化的入站消息(与底层 Matrix 事件解耦,便于测试与将来接入其它 IM)。 */
|
||||
export interface InboundMessage {
|
||||
eventId: string;
|
||||
account: string;
|
||||
roomId: string;
|
||||
userId: string;
|
||||
text: string;
|
||||
timestampMs: number;
|
||||
}
|
||||
|
||||
/** 成员加入/离开等事件。 */
|
||||
export interface MemberEvent {
|
||||
account: string;
|
||||
roomId: string;
|
||||
userId: string;
|
||||
membership: 'join' | 'leave' | 'invite' | 'ban';
|
||||
}
|
||||
|
||||
/** 解析后的命令。 */
|
||||
export interface ParsedCommand {
|
||||
raw: InboundMessage;
|
||||
command: string;
|
||||
args: string[];
|
||||
options: Record<string, string>;
|
||||
}
|
||||
|
||||
/** bot 注册的定时任务。 */
|
||||
export interface CronSpec {
|
||||
/** 标准 5/6 段 cron 表达式。 */
|
||||
cron: string;
|
||||
run: () => Promise<void>;
|
||||
name?: string;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
describe('BotStore (integration with real SQLite)', () => {
|
||||
it('returns null for a key that has never been set', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
expect(await store.get('missing')).toBeNull();
|
||||
});
|
||||
|
||||
it('persists and retrieves a value with set/get round-trip', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
const data = { foo: 'bar', num: 42 };
|
||||
await store.set('mykey', data);
|
||||
expect(await store.get('mykey')).toEqual(data);
|
||||
});
|
||||
|
||||
it('overwrites an existing value on set', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('key', { v: 1 });
|
||||
await store.set('key', { v: 2 });
|
||||
expect(await store.get<{ v: number }>('key')).toEqual({ v: 2 });
|
||||
});
|
||||
|
||||
it('removes an existing entry', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('todelete', 'value');
|
||||
await store.remove('todelete');
|
||||
expect(await store.get('todelete')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not throw when removing a non-existent key', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await expect(store.remove('ghost')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns an empty array from entries() when no keys exist', async () => {
|
||||
const store = new BotStore(prismaService, 'emptybot');
|
||||
expect(await store.entries()).toEqual([]);
|
||||
});
|
||||
|
||||
it('entries() returns all key-value pairs for the bot scope', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('a', 1);
|
||||
await store.set('b', 2);
|
||||
await store.set('c', 3);
|
||||
const entries = await store.entries<number>();
|
||||
expect(entries).toHaveLength(3);
|
||||
expect(entries).toEqual(
|
||||
expect.arrayContaining([
|
||||
['a', 1],
|
||||
['b', 2],
|
||||
['c', 3],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('isolates data between different bot scopes', async () => {
|
||||
const storeA = new BotStore(prismaService, 'botA');
|
||||
const storeB = new BotStore(prismaService, 'botB');
|
||||
|
||||
await storeA.set('shared-key', 'from-A');
|
||||
await storeB.set('shared-key', 'from-B');
|
||||
|
||||
expect(await storeA.get('shared-key')).toBe('from-A');
|
||||
expect(await storeB.get('shared-key')).toBe('from-B');
|
||||
|
||||
const entriesA = await storeA.entries<string>();
|
||||
const entriesB = await storeB.entries<string>();
|
||||
expect(entriesA).toHaveLength(1);
|
||||
expect(entriesB).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('persists complex nested objects', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
const complex = {
|
||||
isCheckinToday: true,
|
||||
level: 'Gold',
|
||||
checkinUnixMs: 1717000000000,
|
||||
checkinTimesInMonth: 15,
|
||||
checkinDays: [1, 3, 5, 7],
|
||||
};
|
||||
await store.set('@user:hs', complex);
|
||||
expect(await store.get('@user:hs')).toEqual(complex);
|
||||
});
|
||||
|
||||
it('handles multiple distinct keys in the same bot scope', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('user1', { count: 1 });
|
||||
await store.set('user2', { count: 2 });
|
||||
|
||||
expect(await store.get<{ count: number }>('user1')).toEqual({ count: 1 });
|
||||
expect(await store.get<{ count: number }>('user2')).toEqual({ count: 2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
/**
|
||||
* 按 botName 隔离的 KV 存储,对应 Rust 版 DailyBotStore 的 `scope:id` 语义。
|
||||
* 每个 bot 通过 BotContext.db 拿到一个已绑定自身 name 的实例,互不串数据。
|
||||
*/
|
||||
export class BotStore {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly botName: string,
|
||||
) {}
|
||||
|
||||
async get<T = unknown>(key: string): Promise<T | null> {
|
||||
const row = await this.prisma.botState.findUnique({
|
||||
where: { botName_key: { botName: this.botName, key } },
|
||||
});
|
||||
return row ? (JSON.parse(row.valueJson) as T) : null;
|
||||
}
|
||||
|
||||
async set<T = unknown>(key: string, value: T): Promise<void> {
|
||||
const valueJson = JSON.stringify(value);
|
||||
await this.prisma.botState.upsert({
|
||||
where: { botName_key: { botName: this.botName, key } },
|
||||
create: { botName: this.botName, key, valueJson },
|
||||
update: { valueJson },
|
||||
});
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.prisma.botState
|
||||
.delete({ where: { botName_key: { botName: this.botName, key } } })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
async entries<T = unknown>(): Promise<Array<[string, T]>> {
|
||||
const rows = await this.prisma.botState.findMany({
|
||||
where: { botName: this.botName },
|
||||
});
|
||||
return rows.map((r) => [r.key, JSON.parse(r.valueJson) as T]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class DbModule {}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import {
|
||||
MatrixAuth,
|
||||
MatrixClient,
|
||||
RustSdkCryptoStorageProvider,
|
||||
SimpleFsStorageProvider,
|
||||
} from 'matrix-bot-sdk';
|
||||
import { StoreType } from '@matrix-org/matrix-sdk-crypto-nodejs';
|
||||
import { AccountConfig } from '../../config/schema';
|
||||
import { InboundMessage, MemberEvent } from '../command/types';
|
||||
import { MatrixEventSink, MatrixTransport } from './types';
|
||||
|
||||
interface PersistedCreds {
|
||||
accessToken: string;
|
||||
userId: string;
|
||||
deviceId?: string;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 包装一个 matrix-bot-sdk client = 一个 Matrix 账号会话。
|
||||
* 负责:登录、sync、把底层事件归一化后交给 sink;并提供出站能力。
|
||||
*
|
||||
* 端到端加密(E2EE):使用 matrix-bot-sdk + @matrix-org/matrix-sdk-crypto-nodejs
|
||||
* 的原生 Rust 加密内核,加密状态持久化到 SQLite(每账号一个目录),
|
||||
* 加密房收发的消息会被自动加/解密。
|
||||
*
|
||||
* 登录策略:首次用密码登录拿 accessToken/deviceId 并落盘,之后复用,
|
||||
* 避免每次启动都重新登录(产生新设备、触发限流、丢失加密会话)。
|
||||
*
|
||||
* dryRun=true 时不连接网络,send/kick 仅记日志,便于本地/CI 启动验证。
|
||||
*/
|
||||
export class MatrixSession implements MatrixTransport {
|
||||
private readonly logger: Logger;
|
||||
private client?: MatrixClient;
|
||||
private selfUserId?: string;
|
||||
private started = false;
|
||||
/** 记录 bot 自己刚发出的 event_id,sync 回流时跳过,避免回应自己(支持与用户同账号自测)。 */
|
||||
private readonly recentSentEventIds = new Set<string>();
|
||||
|
||||
constructor(
|
||||
public readonly account: string,
|
||||
private readonly cfg: AccountConfig,
|
||||
private readonly sink: MatrixEventSink,
|
||||
private readonly dryRun: boolean,
|
||||
// 只同步这些房间(各 bot 关注房间的并集)。为空则同步全部(不推荐:
|
||||
// 账号若加入大量加密房,初始 sync 会拉取并尝试解密海量历史 → 内存暴涨被 OOM)。
|
||||
private readonly watchRoomIds: string[] = [],
|
||||
) {
|
||||
this.logger = new Logger(`MatrixSession:${account}`);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.started) return;
|
||||
this.started = true;
|
||||
|
||||
if (this.dryRun) {
|
||||
this.logger.warn(
|
||||
`[dry-run] 跳过登录,账号 ${this.cfg.userId} 不会真正连接`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const accDir = this.accountDir();
|
||||
fs.mkdirSync(accDir, { recursive: true });
|
||||
|
||||
const storage = new SimpleFsStorageProvider(path.join(accDir, 'state.json'));
|
||||
const crypto = new RustSdkCryptoStorageProvider(
|
||||
path.join(accDir, 'crypto'),
|
||||
StoreType.Sqlite,
|
||||
);
|
||||
|
||||
let client = await this.buildClient(accDir, storage, crypto);
|
||||
this.registerHandlers(client);
|
||||
|
||||
const syncFilter = this.buildSyncFilter();
|
||||
|
||||
try {
|
||||
await client.start(syncFilter);
|
||||
} catch (err) {
|
||||
// accessToken 失效(如服务端登出该设备):清除凭据与加密状态后重登一次。
|
||||
if (this.isTokenError(err)) {
|
||||
this.logger.warn(
|
||||
`账号 ${this.cfg.userId} 的 accessToken 已失效,清除本地凭据后重新登录。`,
|
||||
);
|
||||
this.clearCreds(accDir);
|
||||
client = await this.loginAndBuild(accDir, storage, crypto);
|
||||
this.registerHandlers(client);
|
||||
await client.start(syncFilter);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
this.client = client;
|
||||
this.selfUserId = await client.getUserId();
|
||||
const whoami = await client.getWhoAmI().catch(() => undefined);
|
||||
this.logger.log(
|
||||
`账号 ${this.selfUserId} 已登录并开始 sync` +
|
||||
(whoami?.device_id ? `(device=${whoami.device_id})` : '') +
|
||||
`,E2EE=${client.crypto ? '已启用' : '未启用'}` +
|
||||
(this.watchRoomIds.length
|
||||
? `,仅同步 ${this.watchRoomIds.length} 个房间`
|
||||
: ',同步全部房间'),
|
||||
);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.client?.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 sync filter:用房间白名单把同步范围限制在各 bot 关注的房间,
|
||||
* 避免账号加入的其它(尤其大型加密)房间被拉取、解密历史而耗尽内存。
|
||||
* to-device / account_data 不过滤,保证 E2EE 密钥分发正常。
|
||||
* 返回 undefined 表示不限制(同步全部房间)。
|
||||
*/
|
||||
private buildSyncFilter(): Record<string, unknown> | undefined {
|
||||
if (!this.watchRoomIds.length) return undefined;
|
||||
return {
|
||||
room: {
|
||||
rooms: this.watchRoomIds,
|
||||
timeline: { limit: 20, lazy_load_members: true },
|
||||
state: { lazy_load_members: true },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 client:优先复用落盘的 accessToken;无则用密码登录一次并落盘。
|
||||
*/
|
||||
private async buildClient(
|
||||
accDir: string,
|
||||
storage: SimpleFsStorageProvider,
|
||||
crypto: RustSdkCryptoStorageProvider,
|
||||
): Promise<MatrixClient> {
|
||||
const creds = this.readCreds(accDir);
|
||||
if (creds?.accessToken && creds.baseUrl) {
|
||||
this.logger.log(`复用已保存的登录凭据(${creds.userId})`);
|
||||
return new MatrixClient(creds.baseUrl, creds.accessToken, storage, crypto);
|
||||
}
|
||||
return this.loginAndBuild(accDir, storage, crypto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用密码登录一次,拿到 accessToken/baseUrl/deviceId 落盘,返回长期使用的 client。
|
||||
* matrix-bot-sdk 的 MatrixAuth 会自行做 .well-known 发现并返回正确的
|
||||
* homeserverUrl(裸域名 tchncs.de → matrix.tchncs.de),无需手动发现。
|
||||
*/
|
||||
private async loginAndBuild(
|
||||
accDir: string,
|
||||
storage: SimpleFsStorageProvider,
|
||||
crypto: RustSdkCryptoStorageProvider,
|
||||
): Promise<MatrixClient> {
|
||||
const loggedIn = await this.passwordLoginWithRetry();
|
||||
|
||||
const baseUrl = loggedIn.homeserverUrl;
|
||||
const accessToken = loggedIn.accessToken;
|
||||
const userId = await loggedIn.getUserId();
|
||||
const whoami = await loggedIn.getWhoAmI().catch(() => undefined);
|
||||
|
||||
this.logger.log(`账号 ${userId} 密码登录成功,凭据已保存,后续复用`);
|
||||
|
||||
this.writeCreds(accDir, {
|
||||
accessToken,
|
||||
userId,
|
||||
deviceId: whoami?.device_id,
|
||||
baseUrl,
|
||||
});
|
||||
|
||||
// 复用已注册事件/加密状态的 storage、crypto,生成长期使用的 client。
|
||||
return new MatrixClient(baseUrl, accessToken, storage, crypto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码登录,带 429 限流处理:
|
||||
* 登录被限流时,读 retry_after_ms 在【进程内】等待后重试,而非抛错退出。
|
||||
* 关键原因:若让进程崩溃退出,容器(restart: on-failure)会立刻重启并再次登录,
|
||||
* 每次新登录都会刷新/延长服务端的登录限流窗口,陷入"反复登录→反复限流"的死循环。
|
||||
* 进程内等待则只占用一次登录配额,等窗口过去即可成功,随后凭据落盘不再登录。
|
||||
*/
|
||||
private async passwordLoginWithRetry(): Promise<MatrixClient> {
|
||||
// MatrixAuth 不会自动做服务器发现,它直接拿传入地址打 /login。
|
||||
// 必须先用 .well-known 把账号域名(https://tchncs.de)解析成真实 API 域名
|
||||
// (https://matrix.tchncs.de),否则会打到裸域名的落地页入口被限流(429)。
|
||||
const baseUrl = await this.discoverBaseUrl(this.cfg.homeServer);
|
||||
const auth = new MatrixAuth(baseUrl);
|
||||
const maxWaitMs = 10 * 60_000; // 单次等待上限 10 分钟,避免异常超长阻塞。
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
return await auth.passwordLogin(
|
||||
this.cfg.userId,
|
||||
this.cfg.password,
|
||||
'🤖 签到机器人 (daily-bot-nest)',
|
||||
);
|
||||
} catch (err) {
|
||||
const e = err as {
|
||||
errcode?: string;
|
||||
statusCode?: number;
|
||||
retryAfterMs?: number;
|
||||
};
|
||||
const isRateLimited =
|
||||
e?.errcode === 'M_LIMIT_EXCEEDED' || e?.statusCode === 429;
|
||||
if (!isRateLimited) throw err;
|
||||
|
||||
const waitMs = Math.min(
|
||||
Math.max((e.retryAfterMs ?? 30_000) + 1_000, 5_000),
|
||||
maxWaitMs,
|
||||
);
|
||||
this.logger.warn(
|
||||
`账号 ${this.cfg.userId} 登录被限流(429),${Math.ceil(
|
||||
waitMs / 1000,
|
||||
)} 秒后在进程内重试(第 ${attempt} 次)。` +
|
||||
' 不退出进程,避免容器重启反复登录刷新限流窗口。',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 /.well-known/matrix/client 自动发现真实的 homeserver API 地址。
|
||||
* 例如账号域名 https://tchncs.de 会被解析为 https://matrix.tchncs.de。
|
||||
* 这是 Matrix 标准的服务器发现机制(Element 等客户端均如此)。
|
||||
* 若配置里已经是真实 API 地址,发现通常返回同值;发现失败则回退原值。
|
||||
*/
|
||||
private async discoverBaseUrl(configured: string): Promise<string> {
|
||||
const trimmed = configured.replace(/\/$/, '');
|
||||
try {
|
||||
const res = await fetch(`${trimmed}/.well-known/matrix/client`, {
|
||||
method: 'GET',
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = (await res.json()) as {
|
||||
'm.homeserver'?: { base_url?: string };
|
||||
};
|
||||
const baseUrl = data['m.homeserver']?.base_url?.replace(/\/$/, '');
|
||||
if (baseUrl) {
|
||||
if (baseUrl !== trimmed) {
|
||||
this.logger.log(
|
||||
`服务器发现: ${configured} → ${baseUrl}(来自 .well-known)`,
|
||||
);
|
||||
}
|
||||
return baseUrl;
|
||||
}
|
||||
}
|
||||
this.logger.warn(
|
||||
`服务器发现未返回有效地址(HTTP ${res.status}),回退使用 ${configured}`,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`服务器发现失败,回退使用 ${configured}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private accountDir(): string {
|
||||
const base = process.env.DATA_DIR ?? './data';
|
||||
return path.resolve(base, 'matrix', this.account);
|
||||
}
|
||||
|
||||
private credsPath(accDir: string): string {
|
||||
return path.join(accDir, 'creds.json');
|
||||
}
|
||||
|
||||
private readCreds(accDir: string): PersistedCreds | undefined {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.credsPath(accDir), 'utf8');
|
||||
return JSON.parse(raw) as PersistedCreds;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private writeCreds(accDir: string, creds: PersistedCreds): void {
|
||||
fs.writeFileSync(this.credsPath(accDir), JSON.stringify(creds, null, 2), {
|
||||
mode: 0o600,
|
||||
});
|
||||
}
|
||||
|
||||
private clearCreds(accDir: string): void {
|
||||
try {
|
||||
fs.rmSync(this.credsPath(accDir), { force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// 旧 device 已失效,其加密会话不可再用,清空加密 store 让新设备重新建立。
|
||||
try {
|
||||
fs.rmSync(path.join(accDir, 'crypto'), { recursive: true, force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
private isTokenError(err: unknown): boolean {
|
||||
const e = err as { errcode?: string; statusCode?: number };
|
||||
return (
|
||||
e?.errcode === 'M_UNKNOWN_TOKEN' ||
|
||||
e?.errcode === 'M_MISSING_TOKEN' ||
|
||||
e?.statusCode === 401
|
||||
);
|
||||
}
|
||||
|
||||
async send(
|
||||
roomId: string,
|
||||
text: string,
|
||||
replyToEventId?: string,
|
||||
): Promise<string> {
|
||||
if (this.dryRun || !this.client) {
|
||||
this.logger.log(`[dry-run] send → ${roomId}: ${text}`);
|
||||
return 'dry-run-event-id';
|
||||
}
|
||||
const content: Record<string, unknown> = { msgtype: 'm.text', body: text };
|
||||
if (replyToEventId) {
|
||||
content['m.relates_to'] = {
|
||||
'm.in_reply_to': { event_id: replyToEventId },
|
||||
};
|
||||
}
|
||||
// 加密房间下 sendMessage 会自动加密;返回 event_id。
|
||||
const eventId = await this.client.sendMessage(roomId, content);
|
||||
this.rememberSent(eventId);
|
||||
return eventId;
|
||||
}
|
||||
|
||||
/** 登记 bot 自己发出的 event_id,用于在 sync 回流时去重(有界,防内存泄漏)。 */
|
||||
private rememberSent(eventId?: string): void {
|
||||
if (!eventId) return;
|
||||
this.recentSentEventIds.add(eventId);
|
||||
if (this.recentSentEventIds.size > 500) {
|
||||
const oldest = this.recentSentEventIds.values().next().value;
|
||||
if (oldest) this.recentSentEventIds.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
async kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
if (this.dryRun || !this.client) {
|
||||
this.logger.log(
|
||||
`[dry-run] kick ${userId} from ${roomId} (${reason ?? ''})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await this.client.kickUser(userId, roomId, reason);
|
||||
}
|
||||
|
||||
async getMemberCount(roomId: string): Promise<number> {
|
||||
if (this.dryRun || !this.client) return 0;
|
||||
const members = await this.client
|
||||
.getJoinedRoomMembers(roomId)
|
||||
.catch(() => []);
|
||||
return members.length;
|
||||
}
|
||||
|
||||
async getJoinedMembers(roomId: string): Promise<string[]> {
|
||||
if (this.dryRun || !this.client) return [];
|
||||
return this.client.getJoinedRoomMembers(roomId).catch(() => []);
|
||||
}
|
||||
|
||||
/** 读取用户在房间内的 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 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
private registerHandlers(client: MatrixClient): void {
|
||||
// room.message:已自动解密的房间消息(明文与加密房统一在此回调)。
|
||||
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;
|
||||
// 去重:仅跳过 bot 自己刚发出的消息,用户同账号发的命令仍会处理。
|
||||
if (eventId && this.recentSentEventIds.has(eventId)) {
|
||||
this.recentSentEventIds.delete(eventId);
|
||||
return;
|
||||
}
|
||||
const content = (event['content'] ?? {}) as Record<string, unknown>;
|
||||
this.logger.debug?.(
|
||||
`收到消息 room=${roomId} from=${sender} type=${content['msgtype']}: ${String(content['body'] ?? '').slice(0, 60)}`,
|
||||
);
|
||||
if (content['msgtype'] !== 'm.text') return;
|
||||
|
||||
const msg: InboundMessage = {
|
||||
eventId: (event['event_id'] as string) ?? '',
|
||||
account: this.account,
|
||||
roomId,
|
||||
userId: sender ?? '',
|
||||
text: (content['body'] as string) ?? '',
|
||||
timestampMs: (event['origin_server_ts'] as number) ?? Date.now(),
|
||||
};
|
||||
void this.sink.onMessage(msg);
|
||||
});
|
||||
|
||||
// room.event:所有房间事件;在此筛成员变更。
|
||||
client.on('room.event', (roomId: string, event: Record<string, any>) => {
|
||||
if (event['type'] !== 'm.room.member') return;
|
||||
const content = (event['content'] ?? {}) as Record<string, unknown>;
|
||||
const ev: MemberEvent = {
|
||||
account: this.account,
|
||||
roomId,
|
||||
userId: (event['state_key'] as string) ?? '',
|
||||
membership: content['membership'] as MemberEvent['membership'],
|
||||
};
|
||||
void this.sink.onMember(ev);
|
||||
});
|
||||
|
||||
// 解密失败:最常见是历史消息(bot 加入前的消息,发送方不会共享旧密钥)
|
||||
// 或密钥尚未送达,属正常现象,降为 debug 避免刷屏;库损坏等异常另行排查。
|
||||
client.on(
|
||||
'room.failed_decryption',
|
||||
(roomId: string, event: Record<string, any>, e: Error) => {
|
||||
this.logger.debug(
|
||||
`房间 ${roomId} 事件 ${event?.['event_id']} 解密失败: ${e?.message}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { SessionManager } from './session-manager.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [SessionManager],
|
||||
exports: [SessionManager],
|
||||
})
|
||||
export class MatrixModule {}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { MatrixSession } from './matrix-session';
|
||||
import { MatrixEventSink } from './types';
|
||||
|
||||
/**
|
||||
* 管理所有 Matrix 账号会话。
|
||||
* 多个 bot 引用同一 account ⇒ 只建一个 MatrixSession(共享账号);
|
||||
* 引用不同 account ⇒ 各自独立会话(独立身份)。
|
||||
*/
|
||||
@Injectable()
|
||||
export class SessionManager {
|
||||
private readonly logger = new Logger(SessionManager.name);
|
||||
private readonly sessions = new Map<string, MatrixSession>();
|
||||
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
|
||||
/** 按需创建并缓存某账号的会话(去重)。 */
|
||||
ensureSession(account: string, sink: MatrixEventSink): MatrixSession {
|
||||
const existing = this.sessions.get(account);
|
||||
if (existing) return existing;
|
||||
|
||||
const accCfg = this.config.getAccount(account);
|
||||
// 聚合所有使用该账号的 bot 关注的房间(去重),限制 sync 范围。
|
||||
const watchRoomIds = [
|
||||
...new Set(
|
||||
this.config.bots
|
||||
.filter((b) => b.account === account)
|
||||
.flatMap((b) => b.rooms),
|
||||
),
|
||||
];
|
||||
const session = new MatrixSession(
|
||||
account,
|
||||
accCfg,
|
||||
sink,
|
||||
this.config.isDryRun,
|
||||
watchRoomIds,
|
||||
);
|
||||
this.sessions.set(account, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
get(account: string): MatrixSession | undefined {
|
||||
return this.sessions.get(account);
|
||||
}
|
||||
|
||||
async startAll(): Promise<void> {
|
||||
for (const [account, session] of this.sessions) {
|
||||
this.logger.log(`启动会话: ${account}`);
|
||||
await session.start();
|
||||
}
|
||||
}
|
||||
|
||||
async stopAll(): Promise<void> {
|
||||
for (const session of this.sessions.values()) {
|
||||
await session.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { InboundMessage, MemberEvent } from '../command/types';
|
||||
|
||||
/** bot 与 Matrix 交互的统一出站能力(BotContext 内部依赖它)。 */
|
||||
export interface MatrixTransport {
|
||||
readonly account: string;
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string>;
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void>;
|
||||
getMemberCount(roomId: string): Promise<number>;
|
||||
getJoinedMembers(roomId: string): Promise<string[]>;
|
||||
/** 读取用户在房间内的 power level(读不到或无权限时返回 0)。 */
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number>;
|
||||
}
|
||||
|
||||
/** 归一化事件回调,由 SessionManager 注册,转交 Dispatcher。 */
|
||||
export interface MatrixEventSink {
|
||||
onMessage(msg: InboundMessage): Promise<void>;
|
||||
onMember(ev: MemberEvent): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import 'reflect-metadata';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { LogLevel, LogService } from 'matrix-bot-sdk';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
// 静音 matrix-bot-sdk 的 debug/info 噪音,只保留 warn/error。
|
||||
// 可用 MATRIX_LOG_LEVEL 覆盖(trace/debug/info/warn/error)。
|
||||
LogService.setLevel(
|
||||
LogLevel.fromString(process.env.MATRIX_LOG_LEVEL ?? 'WARN', LogLevel.WARN),
|
||||
);
|
||||
LogService.muteModule('Metrics');
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.createApplicationContext(AppModule, {
|
||||
abortOnError: true,
|
||||
});
|
||||
app.enableShutdownHooks();
|
||||
Logger.log('daily-bot-nest 已启动。Ctrl+C 退出。', 'Bootstrap');
|
||||
}
|
||||
|
||||
bootstrap().catch((err) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('启动失败:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
accounts:
|
||||
main:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@testbot:example.com"
|
||||
password: "test-password-main"
|
||||
checkin:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@checkin-test:example.com"
|
||||
password: "test-password-checkin"
|
||||
|
||||
bots:
|
||||
- name: checkin
|
||||
account: checkin
|
||||
rooms:
|
||||
- "!testroom:example.com"
|
||||
config:
|
||||
mainRoom: "!testroom:example.com"
|
||||
kickDays: 30
|
||||
autoKick: false
|
||||
adminPowerLevel: 100
|
||||
admins: []
|
||||
whitelist: []
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"paths": {
|
||||
"@core/*": ["src/core/*"],
|
||||
"@config/*": ["src/config/*"],
|
||||
"@bots/*": ["src/bots/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Reference in new issue
Block a user