@zhin.js/core 1.0.45 → 1.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,390 @@
1
+ /**
2
+ * MessageFilterFeature — 消息过滤引擎
3
+ *
4
+ * 设计理念:
5
+ * 将过滤规则视为 Feature Item,与命令 (CommandFeature)、权限 (PermissionFeature) 同构,
6
+ * 遵循框架的 add/remove/extensions/toJSON 范式,支持插件级 CRUD 和生命周期自动回收。
7
+ *
8
+ * 核心特性:
9
+ * - 基于优先级的规则引擎(first-match-wins,类似防火墙规则)
10
+ * - 多维匹配:scope / adapter / bot / channel / sender
11
+ * - 支持精确匹配、通配符 `*`、正则 `/pattern/`
12
+ * - 通过 Dispatcher Guardrail 集成,在消息调度第一阶段拦截
13
+ * - 插件通过 `addFilterRule()` 动态注册规则,卸载时自动清理
14
+ */
15
+
16
+ import { Feature, FeatureJSON } from '../feature.js';
17
+ import { getPlugin } from '../plugin.js';
18
+ import type { Message, MessageType } from '../message.js';
19
+
20
+ // ============================================================================
21
+ // 类型定义
22
+ // ============================================================================
23
+
24
+ /** 过滤动作 */
25
+ export type FilterAction = 'allow' | 'deny';
26
+
27
+ /** 匹配模式:精确字符串 / 正则表达式 */
28
+ export type FilterPattern = string | RegExp;
29
+
30
+ /** 消息作用域 */
31
+ export type FilterScope = MessageType; // 'private' | 'group' | 'channel'
32
+
33
+ /**
34
+ * 过滤规则
35
+ *
36
+ * 每条规则描述一组匹配条件和对应的动作。
37
+ * 所有条件之间为 AND 关系(必须全部满足),每个条件内部的多个值为 OR 关系(满足任一即可)。
38
+ * 未设置的条件视为匹配所有。
39
+ *
40
+ * @example
41
+ * // 拒绝特定群的消息
42
+ * { name: 'block-spam', action: 'deny', scopes: ['group'], channels: ['123456'] }
43
+ *
44
+ * // 放行 VIP 用户(高优先级)
45
+ * { name: 'allow-vip', action: 'allow', priority: 100, senders: ['admin001'] }
46
+ *
47
+ * // 正则匹配:拒绝所有 test- 开头的频道
48
+ * { name: 'block-test', action: 'deny', scopes: ['channel'], channels: [/^test-/] }
49
+ */
50
+ export interface FilterRule {
51
+ /** 规则名称(唯一标识) */
52
+ name: string;
53
+ /** 规则描述 */
54
+ description?: string;
55
+ /** 过滤动作:allow 放行 / deny 拦截 */
56
+ action: FilterAction;
57
+ /** 优先级,数值越大越先匹配(默认 0) */
58
+ priority?: number;
59
+ /** 是否启用(默认 true) */
60
+ enabled?: boolean;
61
+ /** 匹配的消息作用域,未设置则匹配所有 */
62
+ scopes?: FilterScope[];
63
+ /** 匹配的适配器名称 */
64
+ adapters?: FilterPattern[];
65
+ /** 匹配的 Bot 名称 */
66
+ bots?: FilterPattern[];
67
+ /** 匹配的频道/群/会话 ID */
68
+ channels?: FilterPattern[];
69
+ /** 匹配的发送者 ID */
70
+ senders?: FilterPattern[];
71
+ }
72
+
73
+ /** 过滤检测结果 */
74
+ export interface FilterResult {
75
+ /** 是否允许处理 */
76
+ allowed: boolean;
77
+ /** 匹配到的规则名称(null 表示无规则匹配,走默认策略) */
78
+ matchedRule: string | null;
79
+ /** 结果原因 */
80
+ reason: string;
81
+ }
82
+
83
+ // ---- 配置类型 ----
84
+
85
+ /** 配置文件中的规则(pattern 均为 string,正则用 /pattern/ 表示) */
86
+ export interface FilterRuleConfig {
87
+ name: string;
88
+ description?: string;
89
+ action: FilterAction;
90
+ priority?: number;
91
+ enabled?: boolean;
92
+ scopes?: FilterScope[];
93
+ adapters?: string[];
94
+ bots?: string[];
95
+ channels?: string[];
96
+ senders?: string[];
97
+ }
98
+
99
+ /**
100
+ * 消息过滤配置
101
+ *
102
+ * ```yaml
103
+ * message_filter:
104
+ * default_policy: allow
105
+ * rules:
106
+ * - name: block-spam
107
+ * action: deny
108
+ * scopes: [group]
109
+ * channels: ['123456']
110
+ * - name: vip-pass
111
+ * action: allow
112
+ * priority: 100
113
+ * senders: ['admin001']
114
+ * ```
115
+ */
116
+ export interface MessageFilterConfig {
117
+ /** 默认策略:无规则匹配时的行为(默认 'allow') */
118
+ default_policy?: FilterAction;
119
+ /** 规则列表 */
120
+ rules?: FilterRuleConfig[];
121
+ }
122
+
123
+ // ============================================================================
124
+ // Plugin 扩展声明
125
+ // ============================================================================
126
+
127
+ export interface MessageFilterContextExtensions {
128
+ /** 添加过滤规则,返回 dispose 函数 */
129
+ addFilterRule(rule: FilterRule): () => void;
130
+ /** 检测消息是否应被处理 */
131
+ testFilter(message: Message<any>): FilterResult;
132
+ /** 设置默认过滤策略 */
133
+ setDefaultFilterPolicy(policy: FilterAction): void;
134
+ }
135
+
136
+ declare module '../plugin.js' {
137
+ namespace Plugin {
138
+ interface Extensions extends MessageFilterContextExtensions {}
139
+ interface Contexts {
140
+ 'message-filter': MessageFilterFeature;
141
+ }
142
+ }
143
+ }
144
+
145
+ // ============================================================================
146
+ // 规则工厂
147
+ // ============================================================================
148
+
149
+ export namespace FilterRules {
150
+ /** 创建拒绝规则 */
151
+ export function deny(name: string, conditions: Omit<FilterRule, 'name' | 'action'>): FilterRule {
152
+ return { ...conditions, name, action: 'deny' };
153
+ }
154
+
155
+ /** 创建放行规则 */
156
+ export function allow(name: string, conditions: Omit<FilterRule, 'name' | 'action'>): FilterRule {
157
+ return { ...conditions, name, action: 'allow' };
158
+ }
159
+
160
+ /**
161
+ * 创建黑名单规则组
162
+ * @returns 一条 deny 规则
163
+ */
164
+ export function blacklist(
165
+ scope: FilterScope,
166
+ ids: string[],
167
+ name?: string,
168
+ ): FilterRule {
169
+ return {
170
+ name: name ?? `${scope}-blacklist`,
171
+ action: 'deny',
172
+ scopes: [scope],
173
+ channels: ids,
174
+ };
175
+ }
176
+
177
+ /**
178
+ * 创建白名单规则组
179
+ * @returns [allow 规则, deny-catch-all 规则]
180
+ */
181
+ export function whitelist(
182
+ scope: FilterScope,
183
+ ids: string[],
184
+ name?: string,
185
+ ): [FilterRule, FilterRule] {
186
+ const baseName = name ?? `${scope}-whitelist`;
187
+ return [
188
+ { name: baseName, action: 'allow', scopes: [scope], channels: ids, priority: 1 },
189
+ { name: `${baseName}-deny-rest`, action: 'deny', scopes: [scope], priority: -100 },
190
+ ];
191
+ }
192
+ }
193
+
194
+ // ============================================================================
195
+ // Feature 实现
196
+ // ============================================================================
197
+
198
+ export class MessageFilterFeature extends Feature<FilterRule> {
199
+ readonly name = 'message-filter' as const;
200
+ readonly icon = 'Filter';
201
+ readonly desc = '消息过滤';
202
+
203
+ /** 按规则名称索引 */
204
+ readonly byName = new Map<string, FilterRule>();
205
+
206
+ #defaultPolicy: FilterAction = 'allow';
207
+ #sortedCache: FilterRule[] | null = null;
208
+
209
+ constructor(config?: MessageFilterConfig) {
210
+ super();
211
+ if (config) this.#loadConfig(config);
212
+ }
213
+
214
+ // ---- 公共 API ----
215
+
216
+ /** 默认策略 */
217
+ get defaultPolicy(): FilterAction { return this.#defaultPolicy; }
218
+ set defaultPolicy(policy: FilterAction) { this.#defaultPolicy = policy; }
219
+
220
+ /** 获取按优先级排序的启用规则列表(带缓存) */
221
+ get sortedRules(): FilterRule[] {
222
+ if (!this.#sortedCache) {
223
+ this.#sortedCache = [...this.items]
224
+ .filter(r => r.enabled !== false)
225
+ .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
226
+ }
227
+ return this.#sortedCache;
228
+ }
229
+
230
+ /** 按名称查询规则 */
231
+ getRule(name: string): FilterRule | undefined {
232
+ return this.byName.get(name);
233
+ }
234
+
235
+ /**
236
+ * 检测消息是否应该被处理
237
+ *
238
+ * 遍历按优先级排序的规则列表,返回第一个匹配的规则结果。
239
+ * 若无规则匹配,按默认策略决定。
240
+ */
241
+ test(message: Message<any>): FilterResult {
242
+ for (const rule of this.sortedRules) {
243
+ if (this.#matchRule(rule, message)) {
244
+ return {
245
+ allowed: rule.action === 'allow',
246
+ matchedRule: rule.name,
247
+ reason: `matched rule "${rule.name}" → ${rule.action}`,
248
+ };
249
+ }
250
+ }
251
+ return {
252
+ allowed: this.#defaultPolicy === 'allow',
253
+ matchedRule: null,
254
+ reason: `no rule matched → default policy: ${this.#defaultPolicy}`,
255
+ };
256
+ }
257
+
258
+ // ---- Feature 重写 ----
259
+
260
+ /** 添加规则,维护 byName 索引 */
261
+ add(rule: FilterRule, pluginName: string): () => void {
262
+ this.byName.set(rule.name, rule);
263
+ this.#sortedCache = null;
264
+ return super.add(rule, pluginName);
265
+ }
266
+
267
+ /** 移除规则,清理 byName 索引 */
268
+ remove(rule: FilterRule, pluginName?: string): boolean {
269
+ this.byName.delete(rule.name);
270
+ this.#sortedCache = null;
271
+ return super.remove(rule, pluginName);
272
+ }
273
+
274
+ /** 序列化为 JSON(供 Web 控制台展示) */
275
+ toJSON(pluginName?: string): FeatureJSON {
276
+ const list = pluginName ? this.getByPlugin(pluginName) : this.items;
277
+ return {
278
+ name: this.name,
279
+ icon: this.icon,
280
+ desc: this.desc,
281
+ count: list.length,
282
+ items: list.map(r => ({
283
+ name: r.name,
284
+ description: r.description,
285
+ action: r.action,
286
+ priority: r.priority ?? 0,
287
+ enabled: r.enabled !== false,
288
+ scopes: r.scopes,
289
+ adapters: r.adapters?.map(p => p instanceof RegExp ? p.source : p),
290
+ bots: r.bots?.map(p => p instanceof RegExp ? p.source : p),
291
+ channels: r.channels?.map(p => p instanceof RegExp ? p.source : p),
292
+ senders: r.senders?.map(p => p instanceof RegExp ? p.source : p),
293
+ })),
294
+ };
295
+ }
296
+
297
+ /** 插件扩展方法 */
298
+ get extensions() {
299
+ const feature = this;
300
+ return {
301
+ addFilterRule(rule: FilterRule) {
302
+ const plugin = getPlugin();
303
+ const dispose = feature.add(rule, plugin.name);
304
+ plugin.recordFeatureContribution(feature.name, rule.name);
305
+ plugin.onDispose(dispose);
306
+ return dispose;
307
+ },
308
+ testFilter(message: Message<any>) {
309
+ return feature.test(message);
310
+ },
311
+ setDefaultFilterPolicy(policy: FilterAction) {
312
+ feature.defaultPolicy = policy;
313
+ },
314
+ };
315
+ }
316
+
317
+ // ============================================================================
318
+ // 配置加载
319
+ // ============================================================================
320
+
321
+ #loadConfig(config: MessageFilterConfig): void {
322
+ if (config.default_policy) {
323
+ this.#defaultPolicy = config.default_policy;
324
+ }
325
+
326
+ if (config.rules) {
327
+ for (const rc of config.rules) {
328
+ this.add(this.#parseRuleConfig(rc), '__config__');
329
+ }
330
+ }
331
+ }
332
+
333
+ // ============================================================================
334
+ // 规则匹配
335
+ // ============================================================================
336
+
337
+ /** 解析配置中的规则字符串为 FilterPattern */
338
+ #parseRuleConfig(rc: FilterRuleConfig): FilterRule {
339
+ return {
340
+ name: rc.name,
341
+ description: rc.description,
342
+ action: rc.action,
343
+ priority: rc.priority,
344
+ enabled: rc.enabled,
345
+ scopes: rc.scopes,
346
+ adapters: rc.adapters?.map(p => this.#parsePattern(p)),
347
+ bots: rc.bots?.map(p => this.#parsePattern(p)),
348
+ channels: rc.channels?.map(p => this.#parsePattern(p)),
349
+ senders: rc.senders?.map(p => this.#parsePattern(p)),
350
+ };
351
+ }
352
+
353
+ /** 解析单个 pattern:"/regex/flags" → RegExp,其余为精确字符串 */
354
+ #parsePattern(pattern: string): FilterPattern {
355
+ const match = pattern.match(/^\/(.+)\/([gimsuy]*)$/);
356
+ if (match) {
357
+ return new RegExp(match[1], match[2]);
358
+ }
359
+ return pattern;
360
+ }
361
+
362
+ /** 检查规则是否匹配消息(所有条件 AND,条件内 OR) */
363
+ #matchRule(rule: FilterRule, message: Message<any>): boolean {
364
+ if (rule.scopes?.length && !rule.scopes.includes(message.$channel.type as FilterScope)) {
365
+ return false;
366
+ }
367
+ if (rule.adapters?.length && !this.#matchAny(rule.adapters, String(message.$adapter))) {
368
+ return false;
369
+ }
370
+ if (rule.bots?.length && !this.#matchAny(rule.bots, String(message.$bot))) {
371
+ return false;
372
+ }
373
+ if (rule.channels?.length && !this.#matchAny(rule.channels, message.$channel.id)) {
374
+ return false;
375
+ }
376
+ if (rule.senders?.length && !this.#matchAny(rule.senders, message.$sender.id)) {
377
+ return false;
378
+ }
379
+ return true;
380
+ }
381
+
382
+ /** 检查值是否与任一 pattern 匹配 */
383
+ #matchAny(patterns: FilterPattern[], value: string): boolean {
384
+ return patterns.some(p => {
385
+ if (p instanceof RegExp) return p.test(value);
386
+ if (p === '*') return true;
387
+ return p === value;
388
+ });
389
+ }
390
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ export * from './built/permission.js'
18
18
  export * from './built/adapter-process.js'
19
19
  export * from './built/component.js'
20
20
  export * from './built/database.js'
21
+ export * from './built/message-filter.js'
21
22
  // Tool Service (纯工具,无副作用)
22
23
  export * from './built/tool.js'
23
24
  // AI Trigger Service (纯工具,无副作用)