@asabot/core 0.2.0 → 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 +64 -2
- package/dist/core/bot-accounts.d.ts +2 -0
- package/dist/core/bot-accounts.js +7 -0
- package/dist/core/logger.js +4 -1
- package/dist/core/message/segment.js +3 -13
- package/dist/core/plugin/context.d.ts +15 -1
- package/dist/core/plugin/context.js +43 -3
- package/dist/core/plugin/credentials.d.ts +44 -0
- package/dist/core/plugin/credentials.js +45 -0
- package/dist/core/plugin/definition.d.ts +5 -0
- package/dist/core/plugin/icon.d.ts +2 -0
- package/dist/core/plugin/icon.js +14 -0
- package/dist/core/plugin/manager.d.ts +15 -3
- package/dist/core/plugin/manager.js +115 -34
- package/dist/core/plugin/packages.d.ts +4 -0
- package/dist/core/plugin/packages.js +39 -9
- package/dist/core/plugin/types.d.ts +24 -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 +88 -21
- package/dist/server/schemas.d.ts +13 -0
- package/dist/server/schemas.js +28 -0
- package/dist/server/views.d.ts +7 -0
- package/dist/server/views.js +3 -1
- package/docs/DEPLOY.md +22 -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-MEN1AImu.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-BAbj8e7E.css +0 -2
- package/web/dist/assets/index-CMuBy6y5.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)。
|
|
@@ -77,6 +79,8 @@ npm run dev
|
|
|
77
79
|
|
|
78
80
|
## 官方插件
|
|
79
81
|
|
|
82
|
+
`@asabot/plugin-ai` 为业务插件提供统一的对话、生图、语音合成和结构化决策服务。启用后,从「插件页面 → AI 管理」配置 API 渠道、模型、默认分配和白名单,查看来源、请求及用量。用法及本地构建见 [AI 插件文档](packages/plugin-ai/README.md)。
|
|
83
|
+
|
|
80
84
|
`@asabot/plugin-render` 将文本、Markdown 和 satori HTML 渲染为 PNG,也可通过配置 Chrome 或 Edge 使用网页截图。可在插件市场安装,或由超管发送 `/plugin install @asabot/plugin-render`。在插件中声明 `inject: ['render']` 后即可使用:
|
|
81
85
|
|
|
82
86
|
```ts
|
|
@@ -142,14 +146,26 @@ curl -X POST http://127.0.0.1:5140/api/v1/send \
|
|
|
142
146
|
"type": "module",
|
|
143
147
|
"keywords": ["asabot-plugin"],
|
|
144
148
|
"exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
|
|
145
|
-
"peerDependencies": { "@asabot/core": "^0.
|
|
149
|
+
"peerDependencies": { "@asabot/core": "^0.3.0" }
|
|
146
150
|
}
|
|
147
151
|
```
|
|
148
152
|
|
|
149
153
|
发布前将 TypeScript 编译成 JS 并附带 `.d.ts`,因为 Node 不会剥离 `node_modules` 中的 TypeScript。插件入口使用 `import { definePlugin } from '@asabot/core'`;运行时会连接当前框架实例。也可以运行 `npm create @asabot@latest -- --template plugin` 创建带构建和测试配置的插件项目。
|
|
150
154
|
|
|
155
|
+
要让插件市场和安装后的管理界面显示自定义图标,在 `package.json` 的 `keywords` 里加一条 `asabot-icon:` 声明,指向可公开访问的 HTTPS 图片(如 SVG 或 PNG):
|
|
156
|
+
|
|
157
|
+
```json
|
|
158
|
+
{
|
|
159
|
+
"keywords": ["asabot-plugin", "asabot-icon:https://assets.example.com/my-plugin.svg"]
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
两处使用同一条声明。没有声明、地址无效或图片加载失败时,面板显示默认的 `Package` 图标。
|
|
164
|
+
|
|
151
165
|
## 开发插件
|
|
152
166
|
|
|
167
|
+
面向插件作者的分步指南(插件功能、面板 UI、动效、测试与发布)见 [开发指南](docs/guide/README.md)。
|
|
168
|
+
|
|
153
169
|
### 最小插件
|
|
154
170
|
|
|
155
171
|
在 `plugins/hello.ts` 中编写:
|
|
@@ -170,6 +186,8 @@ export default definePlugin({
|
|
|
170
186
|
|
|
171
187
|
默认发现 `plugins/<name>.ts` 和 `plugins/<name>/index.ts`;文件默认导出 `definePlugin(...)` 的结果。顶层以 `_` 或 `.` 开头的文件和目录,以及 `*.test.*`、`*.spec.*`、`*.d.ts` 均被忽略。`name` 由小写英文字母、数字、`-` 和 `_` 组成且必须全局唯一,`core` 是保留名。插件可声明 `version`、`description`、`depends: ['其他插件名']` 和 zod 配置 schema;从 `@asabot/core` 导入 `z`。脚手架生成的 `plugins/hello.ts` 包含配置和命令示例。
|
|
172
188
|
|
|
189
|
+
文件插件可直接在 `definePlugin()` 中声明 `iconUrl: 'https://assets.example.com/my-plugin.svg'`。
|
|
190
|
+
|
|
173
191
|
### Context 一览
|
|
174
192
|
|
|
175
193
|
| API | 用途 |
|
|
@@ -188,11 +206,55 @@ export default definePlugin({
|
|
|
188
206
|
| `ctx.bot(selfId?)`、`ctx.bots` | 查找在线 Bot、列出 Bot;找不到在线 Bot 时 `ctx.bot()` 抛错 |
|
|
189
207
|
| `ctx.send`、`ctx.broadcast` | 向指定平台和会话主动发送或批量发送 |
|
|
190
208
|
| `ctx.beforeSend`、`ctx.interceptApi` | 处理出站消息或拦截 Bot API 调用 |
|
|
191
|
-
| `ctx.provide`、`ctx.inject`、`ctx.injectOptional` |
|
|
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 })` | 读取插件自己的凭据,并为自定义路由提供常用鉴权方式 |
|
|
192
212
|
| `ctx.dataDir`、`ctx.signal`、`ctx.onDispose(fn)` | 插件数据目录、卸载信号、自定义清理函数 |
|
|
193
213
|
|
|
194
214
|
观察者、命令、中间件、匹配器和定时任务随插件卸载自动回收。事件处理器应配合 `signal` 取消耗时操作;插件代码仍运行在主进程中。
|
|
195
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
|
+
|
|
196
258
|
### 插件面板页面
|
|
197
259
|
|
|
198
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;
|
package/dist/core/logger.js
CHANGED
|
@@ -94,7 +94,10 @@ class RotatingFile {
|
|
|
94
94
|
const { path, maxSize, maxFiles } = this.options;
|
|
95
95
|
if (!this.initialized) {
|
|
96
96
|
mkdirSync(dirname(path), { recursive: true });
|
|
97
|
-
|
|
97
|
+
const existing = statSync(path, { throwIfNoEntry: false });
|
|
98
|
+
if (existing && !existing.isFile())
|
|
99
|
+
throw new Error('Log path must point to a regular file');
|
|
100
|
+
this.size = existing?.size ?? 0;
|
|
98
101
|
this.initialized = true;
|
|
99
102
|
}
|
|
100
103
|
const length = Buffer.byteLength(chunk);
|
|
@@ -13,20 +13,10 @@ function mediaSource(source) {
|
|
|
13
13
|
if (/^(?:https?|base64|file):\/\//i.test(source)) {
|
|
14
14
|
return source;
|
|
15
15
|
}
|
|
16
|
-
if (isAbsolute(source)
|
|
17
|
-
if (process.platform !== 'win32' && win32.isAbsolute(source)) {
|
|
18
|
-
const normalized = source.replaceAll('\\', '/');
|
|
19
|
-
if (normalized.startsWith('//')) {
|
|
20
|
-
const [host, ...parts] = normalized.slice(2).split('/');
|
|
21
|
-
return `file://${host}/${parts.map(encodeURIComponent).join('/')}`;
|
|
22
|
-
}
|
|
23
|
-
return `file:///${normalized
|
|
24
|
-
.split('/')
|
|
25
|
-
.map((part, index) => (index === 0 ? part : encodeURIComponent(part)))
|
|
26
|
-
.join('/')}`;
|
|
27
|
-
}
|
|
16
|
+
if (isAbsolute(source) && !source.startsWith('//'))
|
|
28
17
|
return pathToFileURL(source).href;
|
|
29
|
-
|
|
18
|
+
if (win32.isAbsolute(source))
|
|
19
|
+
return pathToFileURL(source, { windows: true }).href;
|
|
30
20
|
if (/^\.\.?\//.test(source)) {
|
|
31
21
|
throw new TypeError('请使用 new URL(..., import.meta.url) 或绝对路径指定本地文件');
|
|
32
22
|
}
|
|
@@ -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 } 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
|
/** 按事件过滤的上下文,可继续注册处理器或叠加过滤条件。 */
|
|
@@ -34,9 +35,17 @@ export declare class Context<Config = undefined> {
|
|
|
34
35
|
private readonly tasks;
|
|
35
36
|
private readonly cleanups;
|
|
36
37
|
private readonly dependencies;
|
|
38
|
+
private readonly consumer;
|
|
37
39
|
private routeApp?;
|
|
38
40
|
private panelRouteApp?;
|
|
39
41
|
private disposed;
|
|
42
|
+
/** 读取当前插件的凭据,或用它们校验外部请求。 */
|
|
43
|
+
readonly credentials: PluginCredentials;
|
|
44
|
+
/** 查询插件目录;每次调用返回当前快照,包含停用或加载失败的插件。 */
|
|
45
|
+
readonly plugins: {
|
|
46
|
+
list: () => readonly PluginCatalogEntry[];
|
|
47
|
+
get: (name: string) => PluginCatalogEntry | undefined;
|
|
48
|
+
};
|
|
40
49
|
/** 注册插件面板页面、认证接口和实时事件;资源随插件卸载回收。 */
|
|
41
50
|
readonly panel: {
|
|
42
51
|
/** 注册一个静态面板页面,返回移除函数;同一插件重复注册页面时抛错。页面文件可以公开访问。 */
|
|
@@ -84,6 +93,11 @@ export declare class Context<Config = undefined> {
|
|
|
84
93
|
migrate(steps: string[]): void;
|
|
85
94
|
/** 按名称提供插件服务并返回撤销函数;同名服务已存在时抛错。 */
|
|
86
95
|
provide<K extends string>(name: K, service: K extends keyof Services ? Services[K] : unknown): Disposer;
|
|
96
|
+
/** 提供按使用方上下文创建的服务,服务可获取插件身份和卸载信号。 */
|
|
97
|
+
provideScoped<K extends string>(name: K, factory: (consumer: ServiceConsumer) => K extends keyof Services ? Services[K] : unknown): Disposer;
|
|
98
|
+
/** 列出声明依赖指定服务的已发现插件,包括未启用的插件。 */
|
|
99
|
+
serviceConsumers(name: string): string[];
|
|
100
|
+
private disposeService;
|
|
87
101
|
/** 获取已声明的必需服务;未声明或服务不可用时抛出 PluginError。 */
|
|
88
102
|
inject<K extends string>(name: K): K extends keyof Services ? Services[K] : unknown;
|
|
89
103
|
/** 获取已声明的可选服务;服务缺失返回 undefined,未声明时抛出 PluginError。 */
|
|
@@ -2,10 +2,12 @@ import { mkdirSync } from 'node:fs';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { Hono } from 'hono';
|
|
5
|
+
import { dispatchContext } from '../dispatch/trace.js';
|
|
5
6
|
import { NoBotOnlineError, PluginError } from '../errors.js';
|
|
6
7
|
import { Scheduler } from '../scheduler.js';
|
|
7
8
|
import { targetSchema } from '../target.js';
|
|
8
9
|
import { parseDuration } from '../utils/duration.js';
|
|
10
|
+
import { PluginCredentials } from './credentials.js';
|
|
9
11
|
import { serviceDependencies } from './definition.js';
|
|
10
12
|
import { pluginExecution } from './execution.js';
|
|
11
13
|
import { PersistentTasks } from './tasks.js';
|
|
@@ -22,9 +24,23 @@ export class Context {
|
|
|
22
24
|
tasks;
|
|
23
25
|
cleanups = [];
|
|
24
26
|
dependencies;
|
|
27
|
+
consumer;
|
|
25
28
|
routeApp;
|
|
26
29
|
panelRouteApp;
|
|
27
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
|
+
};
|
|
28
44
|
/** 注册插件面板页面、认证接口和实时事件;资源随插件卸载回收。 */
|
|
29
45
|
panel = {
|
|
30
46
|
/** 注册一个静态面板页面,返回移除函数;同一插件重复注册页面时抛错。页面文件可以公开访问。 */
|
|
@@ -64,10 +80,22 @@ export class Context {
|
|
|
64
80
|
this.owner = name;
|
|
65
81
|
this.value = config;
|
|
66
82
|
this.dependencies = serviceDependencies(dependencies);
|
|
83
|
+
this.consumer = Object.freeze({
|
|
84
|
+
plugin: name,
|
|
85
|
+
signal: this.controller.signal,
|
|
86
|
+
event() {
|
|
87
|
+
const current = dispatchContext.getStore();
|
|
88
|
+
if (current?.plugin !== name || !current.active.value)
|
|
89
|
+
return undefined;
|
|
90
|
+
const { eventId, platform, selfId } = current.trace;
|
|
91
|
+
return { eventId, platform, selfId };
|
|
92
|
+
},
|
|
93
|
+
});
|
|
67
94
|
this.childLogger = app.logger.child({ plugin: name });
|
|
68
95
|
this.scope = { owner: name, signal: this.controller.signal };
|
|
69
96
|
this.scheduler = new Scheduler(this.childLogger, this.controller.signal, app.config.timezone);
|
|
70
97
|
this.kv = app.storage.store(name, () => this.assertActive());
|
|
98
|
+
this.credentials = new PluginCredentials(app.storage.credentials, name, () => this.assertActive());
|
|
71
99
|
this.tasks = new PersistentTasks(app.tasks, name, this.controller.signal, () => this.assertActive());
|
|
72
100
|
}
|
|
73
101
|
/** 当前插件的唯一名称。 */
|
|
@@ -161,7 +189,19 @@ export class Context {
|
|
|
161
189
|
/** 按名称提供插件服务并返回撤销函数;同名服务已存在时抛错。 */
|
|
162
190
|
provide(name, service) {
|
|
163
191
|
this.assertActive();
|
|
164
|
-
|
|
192
|
+
return this.disposeService(this.app.plugins.provide(this.owner, name, service));
|
|
193
|
+
}
|
|
194
|
+
/** 提供按使用方上下文创建的服务,服务可获取插件身份和卸载信号。 */
|
|
195
|
+
provideScoped(name, factory) {
|
|
196
|
+
this.assertActive();
|
|
197
|
+
return this.disposeService(this.app.plugins.provideScoped(this.owner, name, factory));
|
|
198
|
+
}
|
|
199
|
+
/** 列出声明依赖指定服务的已发现插件,包括未启用的插件。 */
|
|
200
|
+
serviceConsumers(name) {
|
|
201
|
+
this.assertActive();
|
|
202
|
+
return this.app.plugins.serviceConsumers(name);
|
|
203
|
+
}
|
|
204
|
+
disposeService(dispose) {
|
|
165
205
|
this.controller.signal.addEventListener('abort', dispose, { once: true });
|
|
166
206
|
return () => {
|
|
167
207
|
this.controller.signal.removeEventListener('abort', dispose);
|
|
@@ -173,14 +213,14 @@ export class Context {
|
|
|
173
213
|
this.assertActive();
|
|
174
214
|
if (!this.dependencies.required.includes(name))
|
|
175
215
|
throw new PluginError(`插件 "${this.owner}" 未声明服务 ${name}`);
|
|
176
|
-
return this.app.plugins.inject(name);
|
|
216
|
+
return this.app.plugins.inject(name, this.consumer);
|
|
177
217
|
}
|
|
178
218
|
/** 获取已声明的可选服务;服务缺失返回 undefined,未声明时抛出 PluginError。 */
|
|
179
219
|
injectOptional(name) {
|
|
180
220
|
this.assertActive();
|
|
181
221
|
if (!this.dependencies.optional.includes(name))
|
|
182
222
|
throw new PluginError(`插件 "${this.owner}" 未声明可选服务 ${name}`);
|
|
183
|
-
return this.app.plugins.injectOptional(name);
|
|
223
|
+
return this.app.plugins.injectOptional(name, this.consumer);
|
|
184
224
|
}
|
|
185
225
|
on(name, listener) {
|
|
186
226
|
this.assertActive();
|
|
@@ -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
|
/** 全局唯一的插件名称。 */
|
|
@@ -9,6 +10,8 @@ export interface PluginDefinition<Schema extends z.ZodType | undefined = z.ZodTy
|
|
|
9
10
|
version?: string;
|
|
10
11
|
/** 插件说明,用于展示。 */
|
|
11
12
|
description?: string;
|
|
13
|
+
/** 内置和文件插件的 HTTPS 图标 URL;npm 插件在 keywords 中声明 asabot-icon:<URL>。 */
|
|
14
|
+
iconUrl?: string;
|
|
12
15
|
/** 安装时用于初始化「新机器人默认启用」;不声明时为 false。 */
|
|
13
16
|
defaultOnNewBots?: boolean;
|
|
14
17
|
/** 校验配置并推导 ctx.config 类型的 zod schema。 */
|
|
@@ -22,6 +25,8 @@ export interface PluginDefinition<Schema extends z.ZodType | undefined = z.ZodTy
|
|
|
22
25
|
};
|
|
23
26
|
/** 能力需求只用于兼容性提示,不阻止插件在机器人上启用。 */
|
|
24
27
|
capabilities?: CapabilityRequirements;
|
|
28
|
+
/** 可在面板管理的凭据用途,由插件决定如何鉴权。 */
|
|
29
|
+
credentials?: PluginCredentialGroups;
|
|
25
30
|
/** 插件启动入口;可以注册命令和其他资源。 */
|
|
26
31
|
setup(ctx: Context<Schema extends z.ZodType ? z.output<Schema> : undefined>): void | Promise<void>;
|
|
27
32
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function parsePluginIconUrl(value) {
|
|
2
|
+
if (typeof value !== 'string' || value.length > 2048)
|
|
3
|
+
return undefined;
|
|
4
|
+
const url = URL.parse(value);
|
|
5
|
+
if (url?.protocol === 'https:' && !url.username && !url.password)
|
|
6
|
+
return url.href;
|
|
7
|
+
}
|
|
8
|
+
export function pluginIconFromKeywords(keywords) {
|
|
9
|
+
if (!Array.isArray(keywords))
|
|
10
|
+
return undefined;
|
|
11
|
+
const prefix = 'asabot-icon:';
|
|
12
|
+
const keyword = keywords.find((value) => typeof value === 'string' && value.startsWith(prefix));
|
|
13
|
+
return parsePluginIconUrl(keyword?.slice(prefix.length));
|
|
14
|
+
}
|
|
@@ -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 } 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,9 +28,15 @@ 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
|
-
|
|
32
|
-
|
|
34
|
+
provideScoped(plugin: string, name: string, factory: (consumer: ServiceConsumer) => unknown): () => void;
|
|
35
|
+
serviceConsumers(name: string): string[];
|
|
36
|
+
private registerService;
|
|
37
|
+
inject(name: string, consumer?: ServiceConsumer): unknown;
|
|
38
|
+
injectOptional(name: string, consumer?: ServiceConsumer): unknown;
|
|
39
|
+
private serviceValue;
|
|
33
40
|
getConfig(name: string): unknown;
|
|
34
41
|
getGroupConfig(name: string, groupKey: string): Record<string, unknown> | undefined;
|
|
35
42
|
setGroupConfig(name: string, groupKey: string, override: Record<string, unknown> | null): void;
|
|
@@ -58,7 +65,11 @@ export declare class PluginManager {
|
|
|
58
65
|
upload(filename: string, content: string, overwrite?: boolean): Promise<PluginState>;
|
|
59
66
|
uninstall(name: string, purge?: boolean): Promise<void>;
|
|
60
67
|
packageInfo(name: string): import("./packages.ts").PackageInfo | undefined;
|
|
68
|
+
packageReadme(name: string): Promise<string | undefined>;
|
|
61
69
|
subscribePackageUpdates(subscriber: (state: PluginState) => void): () => void;
|
|
70
|
+
/** 发现、移除或重读插件定义;运行状态另由 plugin.state 通知。 */
|
|
71
|
+
subscribeListChanges(subscriber: () => void): () => void;
|
|
72
|
+
private publishListChange;
|
|
62
73
|
updateConfig(name: string, value: unknown): Promise<void>;
|
|
63
74
|
setDefaultOnNewBots(name: string, enabled: boolean): Promise<void>;
|
|
64
75
|
defaultsForNewBot(): string[];
|
|
@@ -76,6 +87,7 @@ export declare class PluginManager {
|
|
|
76
87
|
private persist;
|
|
77
88
|
private add;
|
|
78
89
|
private metadata;
|
|
90
|
+
private syncCredentialGroups;
|
|
79
91
|
private discover;
|
|
80
92
|
private isInside;
|
|
81
93
|
private ensureInside;
|