This commit is contained in:
eskima committed 2026-06-04 15:45:20 +08:00
commit 440f572834
53 files changed
+12776

No files matched your search

+40
View File
@@ -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);
}
}
+73
View File
@@ -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();
}
}
+94
View File
@@ -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}`;
}
+18
View File
@@ -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 {}
+65
View File
@@ -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}`,
);
}
}
}
}
+6
View File
@@ -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);
+43
View File
@@ -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[];
}
+49
View File
@@ -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);
});
});
+92
View File
@@ -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 };
}
+33
View File
@@ -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;
}
+134
View File
@@ -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 });
});
});
+41
View File
@@ -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]);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Global()
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class DbModule {}
+16
View File
@@ -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();
}
}
+432
View File
@@ -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}`,
);
},
);
}
}
+9
View File
@@ -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();
}
}
}
+18
View File
@@ -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>;
}
+40
View File
@@ -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();
}
}
}