init
This commit is contained in:
commit
440f572834
53 files changed
+12776
No files matched your search
@@ -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>;
|
||||
Reference in new issue
Block a user