@asabot/core 0.2.1 → 0.3.0
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.
- package/README.md +49 -1
- package/dist/core/bot-accounts.d.ts +2 -0
- package/dist/core/bot-accounts.js +7 -0
- package/dist/core/plugin/context.d.ts +9 -1
- package/dist/core/plugin/context.js +15 -0
- package/dist/core/plugin/credentials.d.ts +44 -0
- package/dist/core/plugin/credentials.js +45 -0
- package/dist/core/plugin/definition.d.ts +3 -0
- package/dist/core/plugin/manager.d.ts +8 -1
- package/dist/core/plugin/manager.js +73 -23
- package/dist/core/plugin/types.d.ts +13 -0
- package/dist/core/storage/credentials.d.ts +25 -0
- package/dist/core/storage/credentials.js +139 -0
- package/dist/core/storage/index.d.ts +2 -0
- package/dist/core/storage/index.js +10 -0
- package/dist/index.d.ts +2 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +87 -21
- package/dist/server/schemas.d.ts +13 -0
- package/dist/server/schemas.js +28 -0
- package/dist/server/views.d.ts +5 -0
- package/dist/server/views.js +3 -1
- package/package.json +1 -1
- package/web/dist/assets/index-C3RsfNwC.js +51 -0
- package/web/dist/assets/index-Dz7T5hDM.css +2 -0
- package/web/dist/assets/{markdown-CIohfKSa.js → markdown-HrgPSKyp.js} +4 -4
- package/web/dist/assets/plugin-credentials-CuMBPnPO.js +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-ogXTSYEt.css +0 -2
- package/web/dist/assets/index-r9XycpMd.js +0 -51
package/README.md
CHANGED
|
@@ -55,6 +55,8 @@ npm run dev
|
|
|
55
55
|
|
|
56
56
|
框架会记住已识别的机器人账号。断线、停用连接或重启后,可以继续从「机器人」进入该账号,修改管理员、插件开关和配置。详情会显示最近上线时间;发送消息和刷新群列表需要机器人在线。删除连接或换号会解除原有的连接关联,账号和设置仍会保留。
|
|
57
57
|
|
|
58
|
+
在「机器人 → 选择机器人 → 设置」可保存面板别名,便于区分同一平台的多个账号。清空并保存后,面板恢复显示平台昵称或机器人 ID。别名只影响 AsaBot 面板上的显示名称。
|
|
59
|
+
|
|
58
60
|
## 开发和加载适配器
|
|
59
61
|
|
|
60
62
|
内置适配器在 `src/adapters/<平台>/` 独立实现,在 [内置注册表](src/adapters/index.ts) 加一项;公开平台能力时可增加 npm 子路径。第三方适配器可以独立开发成 ESM npm 包,不需要修改框架。通过 `@asabot/core` 导入 `defineAdapter` 和类型,默认导出适配器定义,声明 `id`、`platform`、名称、版本、连接方式、能力、配置 schema 以及 `create(config, host)`。驱动实现 `start()`、`stop()` 和 `reconfigure(config)`;框架在调用前校验配置,每条连接分别创建实例。见 [AdapterHost 契约](src/core/adapter.ts)。
|
|
@@ -144,7 +146,7 @@ curl -X POST http://127.0.0.1:5140/api/v1/send \
|
|
|
144
146
|
"type": "module",
|
|
145
147
|
"keywords": ["asabot-plugin"],
|
|
146
148
|
"exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
|
|
147
|
-
"peerDependencies": { "@asabot/core": "^0.
|
|
149
|
+
"peerDependencies": { "@asabot/core": "^0.3.0" }
|
|
148
150
|
}
|
|
149
151
|
```
|
|
150
152
|
|
|
@@ -162,6 +164,8 @@ curl -X POST http://127.0.0.1:5140/api/v1/send \
|
|
|
162
164
|
|
|
163
165
|
## 开发插件
|
|
164
166
|
|
|
167
|
+
面向插件作者的分步指南(插件功能、面板 UI、动效、测试与发布)见 [开发指南](docs/guide/README.md)。
|
|
168
|
+
|
|
165
169
|
### 最小插件
|
|
166
170
|
|
|
167
171
|
在 `plugins/hello.ts` 中编写:
|
|
@@ -203,10 +207,54 @@ export default definePlugin({
|
|
|
203
207
|
| `ctx.send`、`ctx.broadcast` | 向指定平台和会话主动发送或批量发送 |
|
|
204
208
|
| `ctx.beforeSend`、`ctx.interceptApi` | 处理出站消息或拦截 Bot API 调用 |
|
|
205
209
|
| `ctx.provide`、`ctx.provideScoped`、`ctx.inject`、`ctx.injectOptional` | 提供共享或按调用方绑定的服务,或注入已声明的服务 |
|
|
210
|
+
| `ctx.plugins.list()`、`ctx.plugins.get(name)` | 查询已发现插件的只读目录快照 |
|
|
211
|
+
| `ctx.credentials.list()`、`readAll({ group })`、`match(value, { group })`、`bearer(request, { group })` | 读取插件自己的凭据,并为自定义路由提供常用鉴权方式 |
|
|
206
212
|
| `ctx.dataDir`、`ctx.signal`、`ctx.onDispose(fn)` | 插件数据目录、卸载信号、自定义清理函数 |
|
|
207
213
|
|
|
208
214
|
观察者、命令、中间件、匹配器和定时任务随插件卸载自动回收。事件处理器应配合 `signal` 取消耗时操作;插件代码仍运行在主进程中。
|
|
209
215
|
|
|
216
|
+
### 选择其他插件
|
|
217
|
+
|
|
218
|
+
`ctx.plugins.list()` 和 `ctx.plugins.get(name)` 可以查询插件的名称、版本、描述、来源、状态以及提供和依赖的服务。目录包含停用和加载失败的插件;`provides` 只包含当前已注册的服务。`get` 在插件不存在时返回 `undefined`。
|
|
219
|
+
|
|
220
|
+
配置里的字符串可以在面板中显示为插件选择框。例如,只列出声明使用 `ai` 服务的插件:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
const config = z.object({
|
|
224
|
+
plugin: z.string().meta({
|
|
225
|
+
title: '使用 AI 的插件',
|
|
226
|
+
'x-asabot-options': { source: 'plugins', consumes: 'ai' },
|
|
227
|
+
}).optional(),
|
|
228
|
+
})
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
省略 `consumes` 会列出所有已发现的插件。必需和可选服务依赖都能匹配。全局、机器人和群组配置保存的都是插件名;所选插件卸载后,原值仍保留并标记为不可用。运行时可以用 `ctx.plugins.get(name)` 判断它是否仍在目录中。
|
|
232
|
+
|
|
233
|
+
### 插件凭据
|
|
234
|
+
|
|
235
|
+
插件可通过 `credentials` 声明用途;每个用途提供稳定的 ID、面板显示标题和可选说明。面板可以按用途生成或导入多个凭据,也可以查看和撤销。框架生成的值是 32 字节随机值的 base64url 编码;导入值和密文都不写入普通日志,插件凭据使用 AES-GCM 加密后存入 SQLite,主密钥保存于 `data/plugin-credentials.key`。备份插件凭据时,必须同时保留这个主密钥;带有凭据密文但缺少密钥或密钥损坏的数据库不能解密凭据,也不能继续添加新凭据。
|
|
236
|
+
|
|
237
|
+
验证策略由插件自身的路由决定。下面的 Bearer 示例与面板共用 HTTP 服务,访问路径为 `POST /plugins/incoming-hook/notify`:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
export default definePlugin({
|
|
241
|
+
name: 'incoming-hook',
|
|
242
|
+
credentials: { webhook: { title: 'Webhook' } },
|
|
243
|
+
setup(ctx) {
|
|
244
|
+
ctx.route((app) => app.post('/notify', async (c) => {
|
|
245
|
+
if (!ctx.credentials.bearer(c.req.raw, { group: 'webhook' }))
|
|
246
|
+
return c.json({ error: 'Invalid credential' }, 401)
|
|
247
|
+
// 已验证;在此解析并处理请求。
|
|
248
|
+
return c.body(null, 204)
|
|
249
|
+
}))
|
|
250
|
+
},
|
|
251
|
+
})
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
`ctx.credentials.list()` 只返回当前插件有效凭据的元数据。`ctx.credentials.readAll({ group })` 返回指定用途的有效原值,适用于 HMAC;`match` 做安全值比较,`bearer` 解析标准 Bearer 请求头。这些方法都按插件名隔离。移除用途不会自动删除凭据:框架会停用它们,让面板能显示并撤销;`/plugin uninstall` 默认保留凭据,清除插件数据时一并删除。插件运行在宿主进程中;该密钥保护的是数据库和面板默认返回值,不隔离可信插件代码。
|
|
255
|
+
|
|
256
|
+
完整的 `release-notifier` 部署密钥与 GitHub HMAC 验签示例见 [`plugins/_examples/release-notifier.ts`](plugins/_examples/release-notifier.ts)。
|
|
257
|
+
|
|
210
258
|
### 插件面板页面
|
|
211
259
|
|
|
212
260
|
插件可通过 `ctx.panel.page` 声明一个页面目录,通过 `ctx.panel.route` 注册数据接口。页面文件通过 `/plugin-pages/<插件名>/` 公开访问,不要在静态文件中存放敏感数据;需要鉴权的数据通过 `panel.route` 提供。面板启用时,这些接口位于 `/api/panel/ext/<插件名>/`,需要登录,修改请求也遵循面板的 CSRF 校验。
|
|
@@ -3,6 +3,7 @@ import { type Bot, type BotCapabilities } from './bot.ts';
|
|
|
3
3
|
import { type BotIdentity } from './identity.ts';
|
|
4
4
|
import type { Storage } from './storage/index.ts';
|
|
5
5
|
export interface BotAccount extends BotIdentity {
|
|
6
|
+
alias?: string;
|
|
6
7
|
nickname?: string;
|
|
7
8
|
avatar?: string;
|
|
8
9
|
capabilities?: BotCapabilities;
|
|
@@ -22,6 +23,7 @@ export declare class BotAccounts {
|
|
|
22
23
|
constructor(storage: Storage);
|
|
23
24
|
get(bot: BotIdentity): BotAccount | undefined;
|
|
24
25
|
list(): BotAccount[];
|
|
26
|
+
setAlias(bot: BotIdentity, alias: string | null): boolean;
|
|
25
27
|
record(bot: Bot, info?: BotInfo, lastOnlineAt?: number): void;
|
|
26
28
|
bind(bot: Bot, binding?: BotBinding): void;
|
|
27
29
|
pruneBindings(bindings: ReadonlyMap<string, BotBinding>): void;
|
|
@@ -22,6 +22,7 @@ function account(row) {
|
|
|
22
22
|
return {
|
|
23
23
|
platform,
|
|
24
24
|
selfId,
|
|
25
|
+
alias: row.alias === null ? undefined : String(row.alias),
|
|
25
26
|
nickname: row.nickname === null ? undefined : String(row.nickname),
|
|
26
27
|
avatar: row.avatar === null ? undefined : String(row.avatar),
|
|
27
28
|
capabilities: row.capabilities === null ? undefined : capabilitySchema.parse(JSON.parse(String(row.capabilities))),
|
|
@@ -43,6 +44,12 @@ export class BotAccounts {
|
|
|
43
44
|
list() {
|
|
44
45
|
return this.storage.db.prepare('SELECT * FROM bot_accounts ORDER BY bot_key').all().map(account);
|
|
45
46
|
}
|
|
47
|
+
setAlias(bot, alias) {
|
|
48
|
+
const result = this.storage.db
|
|
49
|
+
.prepare('UPDATE bot_accounts SET alias = ? WHERE bot_key = ?')
|
|
50
|
+
.run(alias, botKey(bot));
|
|
51
|
+
return Number(result.changes) > 0;
|
|
52
|
+
}
|
|
46
53
|
record(bot, info, lastOnlineAt) {
|
|
47
54
|
if (bot.platform === 'virtual')
|
|
48
55
|
return;
|
|
@@ -14,9 +14,10 @@ import type { Sendable } from '../message/index.ts';
|
|
|
14
14
|
import type { KVStore } from '../storage/index.ts';
|
|
15
15
|
import { type Target } from '../target.ts';
|
|
16
16
|
import { type Duration } from '../utils/duration.ts';
|
|
17
|
+
import { PluginCredentials } from './credentials.ts';
|
|
17
18
|
import { type PluginDefinition } from './definition.ts';
|
|
18
19
|
import { type TaskHandle, type TaskHandler, type TaskRegistrationOptions } from './tasks.ts';
|
|
19
|
-
import type { PanelPageOptions, PluginStateEvent, ServiceConsumer } from './types.ts';
|
|
20
|
+
import type { PanelPageOptions, PluginCatalogEntry, PluginStateEvent, ServiceConsumer } from './types.ts';
|
|
20
21
|
type Listener = (event: AnyEvent | PluginStateEvent, signal: AbortSignal) => unknown | Promise<unknown>;
|
|
21
22
|
type Cleanup = () => void | Promise<void>;
|
|
22
23
|
/** 按事件过滤的上下文,可继续注册处理器或叠加过滤条件。 */
|
|
@@ -38,6 +39,13 @@ export declare class Context<Config = undefined> {
|
|
|
38
39
|
private routeApp?;
|
|
39
40
|
private panelRouteApp?;
|
|
40
41
|
private disposed;
|
|
42
|
+
/** 读取当前插件的凭据,或用它们校验外部请求。 */
|
|
43
|
+
readonly credentials: PluginCredentials;
|
|
44
|
+
/** 查询插件目录;每次调用返回当前快照,包含停用或加载失败的插件。 */
|
|
45
|
+
readonly plugins: {
|
|
46
|
+
list: () => readonly PluginCatalogEntry[];
|
|
47
|
+
get: (name: string) => PluginCatalogEntry | undefined;
|
|
48
|
+
};
|
|
41
49
|
/** 注册插件面板页面、认证接口和实时事件;资源随插件卸载回收。 */
|
|
42
50
|
readonly panel: {
|
|
43
51
|
/** 注册一个静态面板页面,返回移除函数;同一插件重复注册页面时抛错。页面文件可以公开访问。 */
|
|
@@ -7,6 +7,7 @@ import { NoBotOnlineError, PluginError } from '../errors.js';
|
|
|
7
7
|
import { Scheduler } from '../scheduler.js';
|
|
8
8
|
import { targetSchema } from '../target.js';
|
|
9
9
|
import { parseDuration } from '../utils/duration.js';
|
|
10
|
+
import { PluginCredentials } from './credentials.js';
|
|
10
11
|
import { serviceDependencies } from './definition.js';
|
|
11
12
|
import { pluginExecution } from './execution.js';
|
|
12
13
|
import { PersistentTasks } from './tasks.js';
|
|
@@ -27,6 +28,19 @@ export class Context {
|
|
|
27
28
|
routeApp;
|
|
28
29
|
panelRouteApp;
|
|
29
30
|
disposed = false;
|
|
31
|
+
/** 读取当前插件的凭据,或用它们校验外部请求。 */
|
|
32
|
+
credentials;
|
|
33
|
+
/** 查询插件目录;每次调用返回当前快照,包含停用或加载失败的插件。 */
|
|
34
|
+
plugins = {
|
|
35
|
+
list: () => {
|
|
36
|
+
this.assertActive();
|
|
37
|
+
return this.app.plugins.listCatalog();
|
|
38
|
+
},
|
|
39
|
+
get: (name) => {
|
|
40
|
+
this.assertActive();
|
|
41
|
+
return this.app.plugins.getCatalogEntry(name);
|
|
42
|
+
},
|
|
43
|
+
};
|
|
30
44
|
/** 注册插件面板页面、认证接口和实时事件;资源随插件卸载回收。 */
|
|
31
45
|
panel = {
|
|
32
46
|
/** 注册一个静态面板页面,返回移除函数;同一插件重复注册页面时抛错。页面文件可以公开访问。 */
|
|
@@ -81,6 +95,7 @@ export class Context {
|
|
|
81
95
|
this.scope = { owner: name, signal: this.controller.signal };
|
|
82
96
|
this.scheduler = new Scheduler(this.childLogger, this.controller.signal, app.config.timezone);
|
|
83
97
|
this.kv = app.storage.store(name, () => this.assertActive());
|
|
98
|
+
this.credentials = new PluginCredentials(app.storage.credentials, name, () => this.assertActive());
|
|
84
99
|
this.tasks = new PersistentTasks(app.tasks, name, this.controller.signal, () => this.assertActive());
|
|
85
100
|
}
|
|
86
101
|
/** 当前插件的唯一名称。 */
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { CredentialStore } from '../storage/credentials.ts';
|
|
3
|
+
export declare const credentialGroupId: z.ZodString;
|
|
4
|
+
export declare const credentialGroupsSchema: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
5
|
+
title: z.ZodString;
|
|
6
|
+
description: z.ZodOptional<z.ZodString>;
|
|
7
|
+
}, z.core.$strict>>;
|
|
8
|
+
/** 插件声明的凭据用途,以稳定的用途 ID 为键。 */
|
|
9
|
+
export type PluginCredentialGroups = z.input<typeof credentialGroupsSchema>;
|
|
10
|
+
export interface PluginCredentialGroup {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly title: string;
|
|
13
|
+
readonly description?: string;
|
|
14
|
+
}
|
|
15
|
+
/** 单条凭据的元数据。 */
|
|
16
|
+
export interface PluginCredentialInfo {
|
|
17
|
+
readonly id: string;
|
|
18
|
+
readonly group: string;
|
|
19
|
+
readonly label: string;
|
|
20
|
+
readonly createdAt: number;
|
|
21
|
+
readonly active: boolean;
|
|
22
|
+
}
|
|
23
|
+
/** 含原值的凭据,仅用于插件自己的验签或鉴权。 */
|
|
24
|
+
export interface PluginCredentialValue extends PluginCredentialInfo {
|
|
25
|
+
readonly value: string;
|
|
26
|
+
}
|
|
27
|
+
export interface PluginCredentialFilter {
|
|
28
|
+
group: string;
|
|
29
|
+
}
|
|
30
|
+
/** 由框架绑定到当前插件的凭据查询与鉴权工具。 */
|
|
31
|
+
export declare class PluginCredentials {
|
|
32
|
+
private readonly store;
|
|
33
|
+
private readonly owner;
|
|
34
|
+
private readonly assertActive;
|
|
35
|
+
constructor(store: CredentialStore, owner: string, assertActive: () => void);
|
|
36
|
+
/** 列出当前插件的有效凭据元数据,可按用途筛选。 */
|
|
37
|
+
list(filter?: PluginCredentialFilter): readonly PluginCredentialInfo[];
|
|
38
|
+
/** 读取指定用途的有效凭据原值,用于 HMAC 等需要原值的场景。 */
|
|
39
|
+
readAll({ group }: PluginCredentialFilter): readonly PluginCredentialValue[];
|
|
40
|
+
/** 安全比较原值;匹配时返回元数据,否则返回 undefined。 */
|
|
41
|
+
match(value: string | undefined | null, filter: PluginCredentialFilter): PluginCredentialInfo | undefined;
|
|
42
|
+
/** 解析 Authorization: Bearer … 后匹配;由插件决定失败时的 HTTP 响应。 */
|
|
43
|
+
bearer(request: Request, filter: PluginCredentialFilter): PluginCredentialInfo | undefined;
|
|
44
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { constantTimeEqual } from '../utils/security.js';
|
|
3
|
+
export const credentialGroupId = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/);
|
|
4
|
+
export const credentialGroupsSchema = z.record(credentialGroupId, z.strictObject({
|
|
5
|
+
title: z.string().trim().min(1).max(100),
|
|
6
|
+
description: z.string().trim().min(1).max(500).optional(),
|
|
7
|
+
}));
|
|
8
|
+
/** 由框架绑定到当前插件的凭据查询与鉴权工具。 */
|
|
9
|
+
export class PluginCredentials {
|
|
10
|
+
store;
|
|
11
|
+
owner;
|
|
12
|
+
assertActive;
|
|
13
|
+
constructor(store, owner, assertActive) {
|
|
14
|
+
this.store = store;
|
|
15
|
+
this.owner = owner;
|
|
16
|
+
this.assertActive = assertActive;
|
|
17
|
+
}
|
|
18
|
+
/** 列出当前插件的有效凭据元数据,可按用途筛选。 */
|
|
19
|
+
list(filter) {
|
|
20
|
+
this.assertActive();
|
|
21
|
+
return this.store.list(this.owner, { group: filter?.group, activeOnly: true });
|
|
22
|
+
}
|
|
23
|
+
/** 读取指定用途的有效凭据原值,用于 HMAC 等需要原值的场景。 */
|
|
24
|
+
readAll({ group }) {
|
|
25
|
+
this.assertActive();
|
|
26
|
+
return this.store.readAll(this.owner, group);
|
|
27
|
+
}
|
|
28
|
+
/** 安全比较原值;匹配时返回元数据,否则返回 undefined。 */
|
|
29
|
+
match(value, filter) {
|
|
30
|
+
this.assertActive();
|
|
31
|
+
if (!value)
|
|
32
|
+
return undefined;
|
|
33
|
+
let matched;
|
|
34
|
+
for (const { value: secret, ...info } of this.store.readAll(this.owner, filter.group)) {
|
|
35
|
+
if (constantTimeEqual(value, secret))
|
|
36
|
+
matched = info;
|
|
37
|
+
}
|
|
38
|
+
return matched;
|
|
39
|
+
}
|
|
40
|
+
/** 解析 Authorization: Bearer … 后匹配;由插件决定失败时的 HTTP 响应。 */
|
|
41
|
+
bearer(request, filter) {
|
|
42
|
+
const token = /^Bearer[ \t]+([a-z\d._~+/-]+=*)$/i.exec(request.headers.get('Authorization') ?? '')?.[1];
|
|
43
|
+
return this.match(token, filter);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { z } from 'zod';
|
|
2
2
|
import type { CapabilityRequirements } from '../capabilities.ts';
|
|
3
3
|
import type { Context } from './context.ts';
|
|
4
|
+
import type { PluginCredentialGroups } from './credentials.ts';
|
|
4
5
|
/** 插件名称、可选配置 schema、依赖及 setup 入口的定义。 */
|
|
5
6
|
export interface PluginDefinition<Schema extends z.ZodType | undefined = z.ZodType | undefined> {
|
|
6
7
|
/** 全局唯一的插件名称。 */
|
|
@@ -24,6 +25,8 @@ export interface PluginDefinition<Schema extends z.ZodType | undefined = z.ZodTy
|
|
|
24
25
|
};
|
|
25
26
|
/** 能力需求只用于兼容性提示,不阻止插件在机器人上启用。 */
|
|
26
27
|
capabilities?: CapabilityRequirements;
|
|
28
|
+
/** 可在面板管理的凭据用途,由插件决定如何鉴权。 */
|
|
29
|
+
credentials?: PluginCredentialGroups;
|
|
27
30
|
/** 插件启动入口;可以注册命令和其他资源。 */
|
|
28
31
|
setup(ctx: Context<Schema extends z.ZodType ? z.output<Schema> : undefined>): void | Promise<void>;
|
|
29
32
|
}
|
|
@@ -2,7 +2,7 @@ import type { App } from '../app.ts';
|
|
|
2
2
|
import { type BotIdentity } from '../identity.ts';
|
|
3
3
|
import { type PluginDefinition } from './definition.ts';
|
|
4
4
|
import { type PackageOptions, PackageService } from './packages.ts';
|
|
5
|
-
import type { PluginState, ServiceConsumer } from './types.ts';
|
|
5
|
+
import type { PluginCatalogEntry, PluginState, ServiceConsumer } from './types.ts';
|
|
6
6
|
/** 管理插件注册、依赖协调、启停、重载和服务。 */
|
|
7
7
|
export declare class PluginManager {
|
|
8
8
|
private readonly app;
|
|
@@ -17,6 +17,7 @@ export declare class PluginManager {
|
|
|
17
17
|
private readonly uninstalling;
|
|
18
18
|
private readonly watchers;
|
|
19
19
|
private readonly packageUpdateSubscribers;
|
|
20
|
+
private readonly listSubscribers;
|
|
20
21
|
private readonly timers;
|
|
21
22
|
private readonly groupConfigCache;
|
|
22
23
|
private releaseRoots?;
|
|
@@ -27,6 +28,8 @@ export declare class PluginManager {
|
|
|
27
28
|
register(definition: PluginDefinition): void;
|
|
28
29
|
list(): PluginState[];
|
|
29
30
|
get(name: string): PluginState | undefined;
|
|
31
|
+
listCatalog(): readonly PluginCatalogEntry[];
|
|
32
|
+
getCatalogEntry(name: string): PluginCatalogEntry | undefined;
|
|
30
33
|
provide(plugin: string, name: string, value: unknown): () => void;
|
|
31
34
|
provideScoped(plugin: string, name: string, factory: (consumer: ServiceConsumer) => unknown): () => void;
|
|
32
35
|
serviceConsumers(name: string): string[];
|
|
@@ -64,6 +67,9 @@ export declare class PluginManager {
|
|
|
64
67
|
packageInfo(name: string): import("./packages.ts").PackageInfo | undefined;
|
|
65
68
|
packageReadme(name: string): Promise<string | undefined>;
|
|
66
69
|
subscribePackageUpdates(subscriber: (state: PluginState) => void): () => void;
|
|
70
|
+
/** 发现、移除或重读插件定义;运行状态另由 plugin.state 通知。 */
|
|
71
|
+
subscribeListChanges(subscriber: () => void): () => void;
|
|
72
|
+
private publishListChange;
|
|
67
73
|
updateConfig(name: string, value: unknown): Promise<void>;
|
|
68
74
|
setDefaultOnNewBots(name: string, enabled: boolean): Promise<void>;
|
|
69
75
|
defaultsForNewBot(): string[];
|
|
@@ -81,6 +87,7 @@ export declare class PluginManager {
|
|
|
81
87
|
private persist;
|
|
82
88
|
private add;
|
|
83
89
|
private metadata;
|
|
90
|
+
private syncCredentialGroups;
|
|
84
91
|
private discover;
|
|
85
92
|
private isInside;
|
|
86
93
|
private ensureInside;
|
|
@@ -10,6 +10,7 @@ import { PluginConfigError, PluginError } from '../errors.js';
|
|
|
10
10
|
import { groupIdentity } from '../identity.js';
|
|
11
11
|
import { mergeConfig } from '../utils/merge.js';
|
|
12
12
|
import { Context } from './context.js';
|
|
13
|
+
import { credentialGroupsSchema } from './credentials.js';
|
|
13
14
|
import { serviceDependencies } from './definition.js';
|
|
14
15
|
import { pluginExecution } from './execution.js';
|
|
15
16
|
import { parsePluginIconUrl, pluginIconFromKeywords } from './icon.js';
|
|
@@ -22,6 +23,18 @@ function errorMessage(error) {
|
|
|
22
23
|
function ignoredEntry(name) {
|
|
23
24
|
return name.startsWith('_') || name.startsWith('.') || /\.(?:test|spec)\.|\.d\.ts$/.test(name);
|
|
24
25
|
}
|
|
26
|
+
function catalogEntry({ state, manifest }) {
|
|
27
|
+
return {
|
|
28
|
+
name: state.name,
|
|
29
|
+
version: state.version ?? manifest?.version,
|
|
30
|
+
description: state.description ?? manifest?.description,
|
|
31
|
+
source: state.source,
|
|
32
|
+
state: state.state,
|
|
33
|
+
enabled: state.enabled,
|
|
34
|
+
provides: [...state.provides],
|
|
35
|
+
inject: state.inject.map((service) => ({ ...service })),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
25
38
|
function validateDefinition(value) {
|
|
26
39
|
if (typeof value !== 'object' ||
|
|
27
40
|
value === null ||
|
|
@@ -57,6 +70,10 @@ function validateDefinition(value) {
|
|
|
57
70
|
value.capabilities !== undefined &&
|
|
58
71
|
!requirementsSchema.safeParse(value.capabilities).success)
|
|
59
72
|
throw new PluginError(`Invalid capability requirements for plugin "${value.name}"`);
|
|
73
|
+
if ('credentials' in value &&
|
|
74
|
+
value.credentials !== undefined &&
|
|
75
|
+
!credentialGroupsSchema.safeParse(value.credentials).success)
|
|
76
|
+
throw new PluginError(`Invalid credential groups for plugin "${value.name}"`);
|
|
60
77
|
return value;
|
|
61
78
|
}
|
|
62
79
|
/** 管理插件注册、依赖协调、启停、重载和服务。 */
|
|
@@ -73,6 +90,7 @@ export class PluginManager {
|
|
|
73
90
|
uninstalling = new Set();
|
|
74
91
|
watchers = [];
|
|
75
92
|
packageUpdateSubscribers = new Set();
|
|
93
|
+
listSubscribers = new Set();
|
|
76
94
|
timers = new Map();
|
|
77
95
|
groupConfigCache = new Map();
|
|
78
96
|
releaseRoots;
|
|
@@ -122,6 +140,13 @@ export class PluginManager {
|
|
|
122
140
|
const state = this.entries.get(name)?.state;
|
|
123
141
|
return state && { ...state };
|
|
124
142
|
}
|
|
143
|
+
listCatalog() {
|
|
144
|
+
return [...this.entries.values()].map(catalogEntry);
|
|
145
|
+
}
|
|
146
|
+
getCatalogEntry(name) {
|
|
147
|
+
const entry = this.entries.get(name);
|
|
148
|
+
return entry && catalogEntry(entry);
|
|
149
|
+
}
|
|
125
150
|
provide(plugin, name, value) {
|
|
126
151
|
return this.registerService(name, { plugin, kind: 'shared', value });
|
|
127
152
|
}
|
|
@@ -287,9 +312,11 @@ export class PluginManager {
|
|
|
287
312
|
this.started = true;
|
|
288
313
|
await this.packages.init();
|
|
289
314
|
this.releaseRoots = registerPluginRoots([...this.dirs, this.packages.dir]);
|
|
290
|
-
for (const
|
|
291
|
-
if (definition)
|
|
292
|
-
|
|
315
|
+
for (const entry of this.entries.values()) {
|
|
316
|
+
if (!entry.definition)
|
|
317
|
+
continue;
|
|
318
|
+
await this.initializeDefaultOnNewBots(entry.definition);
|
|
319
|
+
this.syncCredentialGroups(entry);
|
|
293
320
|
}
|
|
294
321
|
for (const dir of this.dirs)
|
|
295
322
|
await this.discover(dir);
|
|
@@ -475,9 +502,11 @@ export class PluginManager {
|
|
|
475
502
|
catch (error) {
|
|
476
503
|
await this.unload(old);
|
|
477
504
|
old.definition = undefined;
|
|
505
|
+
old.state.credentialGroups = undefined;
|
|
478
506
|
old.failure = 'import';
|
|
479
507
|
this.setState(old, 'failed', errorMessage(error));
|
|
480
508
|
await this.reconcile();
|
|
509
|
+
this.publishListChange();
|
|
481
510
|
}
|
|
482
511
|
}
|
|
483
512
|
else
|
|
@@ -521,6 +550,7 @@ export class PluginManager {
|
|
|
521
550
|
this.entries.set(name, entry);
|
|
522
551
|
this.files.set(path, entry);
|
|
523
552
|
await this.reconcile();
|
|
553
|
+
this.publishListChange();
|
|
524
554
|
throw error;
|
|
525
555
|
}
|
|
526
556
|
if (purge)
|
|
@@ -542,6 +572,21 @@ export class PluginManager {
|
|
|
542
572
|
this.packageUpdateSubscribers.add(subscriber);
|
|
543
573
|
return () => this.packageUpdateSubscribers.delete(subscriber);
|
|
544
574
|
}
|
|
575
|
+
/** 发现、移除或重读插件定义;运行状态另由 plugin.state 通知。 */
|
|
576
|
+
subscribeListChanges(subscriber) {
|
|
577
|
+
this.listSubscribers.add(subscriber);
|
|
578
|
+
return () => this.listSubscribers.delete(subscriber);
|
|
579
|
+
}
|
|
580
|
+
publishListChange() {
|
|
581
|
+
for (const subscriber of this.listSubscribers) {
|
|
582
|
+
try {
|
|
583
|
+
subscriber();
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
this.app.logger.error({ err: error }, 'Plugin list subscriber failed');
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
545
590
|
updateConfig(name, value) {
|
|
546
591
|
return this.serial(async () => {
|
|
547
592
|
const entry = this.requireAvailable(name);
|
|
@@ -648,8 +693,11 @@ export class PluginManager {
|
|
|
648
693
|
entry.state.error = `Duplicate plugin name "${name}"`;
|
|
649
694
|
this.duplicates.push(entry);
|
|
650
695
|
}
|
|
651
|
-
else
|
|
696
|
+
else {
|
|
697
|
+
if (this.started)
|
|
698
|
+
this.syncCredentialGroups(entry);
|
|
652
699
|
this.entries.set(name, entry);
|
|
700
|
+
}
|
|
653
701
|
if (path)
|
|
654
702
|
this.files.set(path, entry);
|
|
655
703
|
return entry;
|
|
@@ -665,6 +713,9 @@ export class PluginManager {
|
|
|
665
713
|
? pluginIconFromKeywords(entry.manifest.keywords)
|
|
666
714
|
: parsePluginIconUrl(definition.iconUrl);
|
|
667
715
|
entry.state.depends = definition.depends;
|
|
716
|
+
entry.state.credentialGroups =
|
|
717
|
+
definition.credentials &&
|
|
718
|
+
Object.entries(definition.credentials).map(([id, { title, description }]) => Object.freeze({ id, title: title.trim(), description: description?.trim() }));
|
|
668
719
|
const dependencies = serviceDependencies(definition.inject);
|
|
669
720
|
entry.state.inject = [
|
|
670
721
|
...dependencies.required.map((name) => ({ name, optional: false })),
|
|
@@ -674,6 +725,9 @@ export class PluginManager {
|
|
|
674
725
|
? z.toJSONSchema(definition.config, { unrepresentable: 'any' })
|
|
675
726
|
: undefined;
|
|
676
727
|
}
|
|
728
|
+
syncCredentialGroups(entry) {
|
|
729
|
+
this.app.storage.credentials.retireMissingGroups(entry.state.name, entry.state.credentialGroups?.map(({ id }) => id) ?? []);
|
|
730
|
+
}
|
|
677
731
|
async discover(dir) {
|
|
678
732
|
let names;
|
|
679
733
|
try {
|
|
@@ -787,6 +841,7 @@ export class PluginManager {
|
|
|
787
841
|
this.files.delete(entry.state.path);
|
|
788
842
|
entry.release?.();
|
|
789
843
|
}
|
|
844
|
+
this.publishListChange();
|
|
790
845
|
}
|
|
791
846
|
async rescanFiles() {
|
|
792
847
|
const previous = new Set(this.files.keys());
|
|
@@ -809,10 +864,13 @@ export class PluginManager {
|
|
|
809
864
|
for (const dir of this.dirs)
|
|
810
865
|
await this.discover(dir);
|
|
811
866
|
await this.reconcile();
|
|
867
|
+
const added = [...this.files]
|
|
868
|
+
.filter(([path, entry]) => !previous.has(path) && entry.state.source === 'file')
|
|
869
|
+
.map(([, entry]) => entry.state.name);
|
|
870
|
+
if (added.length)
|
|
871
|
+
this.publishListChange();
|
|
812
872
|
return {
|
|
813
|
-
added
|
|
814
|
-
.filter(([path, entry]) => !previous.has(path) && entry.state.source === 'file')
|
|
815
|
-
.map(([, entry]) => entry.state.name),
|
|
873
|
+
added,
|
|
816
874
|
removed: missing.map((entry) => entry.state.name),
|
|
817
875
|
};
|
|
818
876
|
}
|
|
@@ -919,6 +977,8 @@ export class PluginManager {
|
|
|
919
977
|
throw new ManagementError(409, 'Plugin changed during package installation');
|
|
920
978
|
const entry = await this.addPackage(installed, previous);
|
|
921
979
|
await this.reconcile();
|
|
980
|
+
if (!previous)
|
|
981
|
+
this.publishListChange();
|
|
922
982
|
return { ...entry.state };
|
|
923
983
|
});
|
|
924
984
|
}
|
|
@@ -1246,7 +1306,9 @@ export class PluginManager {
|
|
|
1246
1306
|
entry.release?.();
|
|
1247
1307
|
entry.release = release;
|
|
1248
1308
|
this.metadata(entry);
|
|
1309
|
+
this.syncCredentialGroups(entry);
|
|
1249
1310
|
await this.reconcile();
|
|
1311
|
+
this.publishListChange();
|
|
1250
1312
|
}
|
|
1251
1313
|
async handleChange(dir, path) {
|
|
1252
1314
|
const removed = [];
|
|
@@ -1264,22 +1326,8 @@ export class PluginManager {
|
|
|
1264
1326
|
removed.push(entry);
|
|
1265
1327
|
}
|
|
1266
1328
|
}
|
|
1267
|
-
if (removed.length
|
|
1268
|
-
|
|
1269
|
-
for (const entry of removed)
|
|
1270
|
-
entry.state.enabled = false;
|
|
1271
|
-
await this.reconcile();
|
|
1272
|
-
for (const entry of removed) {
|
|
1273
|
-
if (this.entries.get(entry.state.name) === entry)
|
|
1274
|
-
this.entries.delete(entry.state.name);
|
|
1275
|
-
const duplicate = this.duplicates.indexOf(entry);
|
|
1276
|
-
if (duplicate !== -1)
|
|
1277
|
-
this.duplicates.splice(duplicate, 1);
|
|
1278
|
-
if (entry.state.path)
|
|
1279
|
-
this.files.delete(entry.state.path);
|
|
1280
|
-
entry.release?.();
|
|
1281
|
-
}
|
|
1282
|
-
}
|
|
1329
|
+
if (removed.length)
|
|
1330
|
+
await this.removeEntries(removed);
|
|
1283
1331
|
const previous = new Set(this.files.keys());
|
|
1284
1332
|
await this.discover(dir);
|
|
1285
1333
|
const affected = [...this.entries.values()].filter((entry) => entry.state.path &&
|
|
@@ -1294,6 +1342,8 @@ export class PluginManager {
|
|
|
1294
1342
|
}
|
|
1295
1343
|
}
|
|
1296
1344
|
await this.reconcile();
|
|
1345
|
+
if (this.files.size !== previous.size)
|
|
1346
|
+
this.publishListChange();
|
|
1297
1347
|
}
|
|
1298
1348
|
setState(entry, state, error) {
|
|
1299
1349
|
if (entry.state.state === state && entry.state.error === error)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Bot } from '../bot.ts';
|
|
2
2
|
import type { CapabilityRequirements } from '../capabilities.ts';
|
|
3
3
|
import type { BaseEvent } from '../event/index.ts';
|
|
4
|
+
import type { PluginCredentialGroup } from './credentials.ts';
|
|
4
5
|
/** 插件面板页面的标题、图标、静态目录和可选入口文件。 */
|
|
5
6
|
export interface PanelPageOptions {
|
|
6
7
|
title: string;
|
|
@@ -43,6 +44,18 @@ export interface PluginState {
|
|
|
43
44
|
}[];
|
|
44
45
|
configSchema?: Record<string, unknown>;
|
|
45
46
|
capabilities?: CapabilityRequirements;
|
|
47
|
+
credentialGroups?: readonly PluginCredentialGroup[];
|
|
48
|
+
}
|
|
49
|
+
/** 已发现插件的公开目录条目,不包含路径、配置和错误详情。 */
|
|
50
|
+
export interface PluginCatalogEntry {
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly version?: string;
|
|
53
|
+
readonly description?: string;
|
|
54
|
+
readonly source: PluginState['source'];
|
|
55
|
+
readonly state: PluginState['state'];
|
|
56
|
+
readonly enabled: boolean;
|
|
57
|
+
readonly provides: readonly string[];
|
|
58
|
+
readonly inject: readonly Readonly<PluginState['inject'][number]>[];
|
|
46
59
|
}
|
|
47
60
|
/** 插件状态变化事件;机器人可能尚未上线,bot 因而可缺省。 */
|
|
48
61
|
export interface PluginStateEvent extends Omit<BaseEvent, 'bot'> {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { PluginError } from '../errors.ts';
|
|
3
|
+
import type { PluginCredentialInfo, PluginCredentialValue } from '../plugin/credentials.ts';
|
|
4
|
+
export declare class CredentialUnavailableError extends PluginError {
|
|
5
|
+
constructor(cause?: unknown);
|
|
6
|
+
}
|
|
7
|
+
export declare class DuplicateCredentialError extends PluginError {
|
|
8
|
+
constructor();
|
|
9
|
+
}
|
|
10
|
+
export declare class CredentialStore {
|
|
11
|
+
private readonly database;
|
|
12
|
+
private readonly keyFile;
|
|
13
|
+
constructor(database: () => DatabaseSync, dataDir: string);
|
|
14
|
+
has(plugin: string): boolean;
|
|
15
|
+
list(plugin: string, { group, activeOnly }?: {
|
|
16
|
+
group?: string;
|
|
17
|
+
activeOnly?: boolean;
|
|
18
|
+
}): PluginCredentialInfo[];
|
|
19
|
+
read(plugin: string, id: string): string | undefined;
|
|
20
|
+
readAll(plugin: string, group: string): PluginCredentialValue[];
|
|
21
|
+
create(plugin: string, group: string, label: string, value?: string): PluginCredentialInfo;
|
|
22
|
+
revoke(plugin: string, id: string): boolean;
|
|
23
|
+
retireMissingGroups(plugin: string, groups: string[]): void;
|
|
24
|
+
private readKey;
|
|
25
|
+
}
|