@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
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { PluginError } from '../errors.js';
|
|
5
|
+
import { constantTimeEqual } from '../utils/security.js';
|
|
6
|
+
export class CredentialUnavailableError extends PluginError {
|
|
7
|
+
constructor(cause) {
|
|
8
|
+
super('无法解密插件凭据,请检查凭据主密钥和数据库备份', { cause });
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export class DuplicateCredentialError extends PluginError {
|
|
12
|
+
constructor() {
|
|
13
|
+
super('这个用途下已存在相同的凭据');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const metadata = 'id, purpose, label, created_at, retired';
|
|
17
|
+
const nonceSize = 12;
|
|
18
|
+
const tagSize = 16;
|
|
19
|
+
function credentialInfo(row) {
|
|
20
|
+
return {
|
|
21
|
+
id: String(row.id),
|
|
22
|
+
group: String(row.purpose),
|
|
23
|
+
label: String(row.label),
|
|
24
|
+
createdAt: Number(row.created_at),
|
|
25
|
+
active: row.retired === 0,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
const aad = (plugin, group, id) => Buffer.from(JSON.stringify([plugin, group, id]));
|
|
29
|
+
function decrypt(row, key) {
|
|
30
|
+
try {
|
|
31
|
+
if (!(row.ciphertext instanceof Uint8Array))
|
|
32
|
+
throw new TypeError('Expected encrypted credential bytes');
|
|
33
|
+
const bytes = row.ciphertext;
|
|
34
|
+
const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, nonceSize), {
|
|
35
|
+
authTagLength: tagSize,
|
|
36
|
+
});
|
|
37
|
+
decipher.setAAD(aad(String(row.plugin), String(row.purpose), String(row.id)));
|
|
38
|
+
decipher.setAuthTag(bytes.subarray(nonceSize, nonceSize + tagSize));
|
|
39
|
+
return Buffer.concat([decipher.update(bytes.subarray(nonceSize + tagSize)), decipher.final()]).toString('utf8');
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
throw new CredentialUnavailableError(error);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export class CredentialStore {
|
|
46
|
+
database;
|
|
47
|
+
keyFile;
|
|
48
|
+
constructor(database, dataDir) {
|
|
49
|
+
this.database = database;
|
|
50
|
+
this.keyFile = join(dataDir, 'plugin-credentials.key');
|
|
51
|
+
}
|
|
52
|
+
has(plugin) {
|
|
53
|
+
return (this.database().prepare('SELECT 1 FROM plugin_credentials WHERE plugin = ? LIMIT 1').get(plugin) !==
|
|
54
|
+
undefined);
|
|
55
|
+
}
|
|
56
|
+
list(plugin, { group, activeOnly = false } = {}) {
|
|
57
|
+
return this.database()
|
|
58
|
+
.prepare(`SELECT ${metadata} FROM plugin_credentials WHERE plugin = ?${group === undefined ? '' : ' AND purpose = ?'}${activeOnly ? ' AND retired = 0' : ''} ORDER BY created_at DESC, id`)
|
|
59
|
+
.all(plugin, ...(group === undefined ? [] : [group]))
|
|
60
|
+
.map(credentialInfo);
|
|
61
|
+
}
|
|
62
|
+
read(plugin, id) {
|
|
63
|
+
const row = this.database()
|
|
64
|
+
.prepare('SELECT * FROM plugin_credentials WHERE plugin = ? AND id = ?')
|
|
65
|
+
.get(plugin, id);
|
|
66
|
+
return row && decrypt(row, this.readKey(false));
|
|
67
|
+
}
|
|
68
|
+
readAll(plugin, group) {
|
|
69
|
+
const rows = this.database()
|
|
70
|
+
.prepare('SELECT * FROM plugin_credentials WHERE plugin = ? AND purpose = ? AND retired = 0 ORDER BY created_at DESC, id')
|
|
71
|
+
.all(plugin, group);
|
|
72
|
+
if (!rows.length)
|
|
73
|
+
return [];
|
|
74
|
+
const key = this.readKey(false);
|
|
75
|
+
return rows.map((row) => ({ ...credentialInfo(row), value: decrypt(row, key) }));
|
|
76
|
+
}
|
|
77
|
+
create(plugin, group, label, value = randomBytes(32).toString('base64url')) {
|
|
78
|
+
const db = this.database();
|
|
79
|
+
db.exec('BEGIN IMMEDIATE');
|
|
80
|
+
try {
|
|
81
|
+
const existing = db.prepare('SELECT * FROM plugin_credentials LIMIT 1').get();
|
|
82
|
+
const key = this.readKey(existing === undefined);
|
|
83
|
+
// A replaced key may still have the right size. Authenticate existing ciphertext before accepting it.
|
|
84
|
+
if (existing)
|
|
85
|
+
decrypt(existing, key);
|
|
86
|
+
for (const row of db
|
|
87
|
+
.prepare('SELECT * FROM plugin_credentials WHERE plugin = ? AND purpose = ?')
|
|
88
|
+
.iterate(plugin, group)) {
|
|
89
|
+
if (constantTimeEqual(value, decrypt(row, key)))
|
|
90
|
+
throw new DuplicateCredentialError();
|
|
91
|
+
}
|
|
92
|
+
const id = randomUUID();
|
|
93
|
+
const createdAt = Date.now();
|
|
94
|
+
const nonce = randomBytes(nonceSize);
|
|
95
|
+
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
96
|
+
cipher.setAAD(aad(plugin, group, id));
|
|
97
|
+
const bytes = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
|
98
|
+
const ciphertext = Buffer.concat([nonce, cipher.getAuthTag(), bytes]);
|
|
99
|
+
db.prepare('INSERT INTO plugin_credentials (id, plugin, purpose, label, created_at, ciphertext) VALUES (?, ?, ?, ?, ?, ?)').run(id, plugin, group, label, createdAt, ciphertext);
|
|
100
|
+
db.exec('COMMIT');
|
|
101
|
+
return { id, group, label, createdAt, active: true };
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
db.exec('ROLLBACK');
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
revoke(plugin, id) {
|
|
109
|
+
return (this.database().prepare('DELETE FROM plugin_credentials WHERE plugin = ? AND id = ?').run(plugin, id)
|
|
110
|
+
.changes !== 0);
|
|
111
|
+
}
|
|
112
|
+
retireMissingGroups(plugin, groups) {
|
|
113
|
+
this.database()
|
|
114
|
+
.prepare('UPDATE plugin_credentials SET retired = 1 WHERE plugin = ? AND retired = 0 AND purpose NOT IN (SELECT value FROM json_each(?))')
|
|
115
|
+
.run(plugin, JSON.stringify(groups));
|
|
116
|
+
}
|
|
117
|
+
readKey(allowCreate) {
|
|
118
|
+
try {
|
|
119
|
+
const key = readFileSync(this.keyFile);
|
|
120
|
+
if (key.length !== 32)
|
|
121
|
+
throw new CredentialUnavailableError();
|
|
122
|
+
return key;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (error instanceof CredentialUnavailableError)
|
|
126
|
+
throw error;
|
|
127
|
+
if (!allowCreate || error.code !== 'ENOENT')
|
|
128
|
+
throw new CredentialUnavailableError(error);
|
|
129
|
+
try {
|
|
130
|
+
writeFileSync(this.keyFile, randomBytes(32), { flag: 'wx', mode: 0o600 });
|
|
131
|
+
}
|
|
132
|
+
catch (writeError) {
|
|
133
|
+
if (writeError.code !== 'EEXIST')
|
|
134
|
+
throw new CredentialUnavailableError(writeError);
|
|
135
|
+
}
|
|
136
|
+
return this.readKey(false);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DatabaseSync } from 'node:sqlite';
|
|
2
2
|
import type { Logger } from 'pino';
|
|
3
3
|
import type { DispatchEvent } from '../dispatch/types.ts';
|
|
4
|
+
import { CredentialStore } from './credentials.ts';
|
|
4
5
|
/** 访问控制列表类型:黑名单或白名单。 */
|
|
5
6
|
export type AccessList = 'block' | 'allow';
|
|
6
7
|
/** 访问控制对象类型:用户或群。 */
|
|
@@ -27,6 +28,7 @@ export declare class Storage {
|
|
|
27
28
|
private readonly groups;
|
|
28
29
|
private readonly commandGroups;
|
|
29
30
|
private readonly accessEntries;
|
|
31
|
+
readonly credentials: CredentialStore;
|
|
30
32
|
readonly access: {
|
|
31
33
|
add: (list: AccessList, subject: AccessSubject, key: string) => void;
|
|
32
34
|
remove: (list: AccessList, subject: AccessSubject, key: string) => void;
|
|
@@ -2,6 +2,7 @@ import { mkdirSync } from 'node:fs';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { DatabaseSync } from 'node:sqlite';
|
|
4
4
|
import { parseDuration } from '../utils/duration.js';
|
|
5
|
+
import { CredentialStore } from './credentials.js';
|
|
5
6
|
const coreMigrations = [
|
|
6
7
|
`CREATE TABLE kv (plugin TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, expires_at INTEGER,
|
|
7
8
|
PRIMARY KEY (plugin, key));
|
|
@@ -57,6 +58,12 @@ const coreMigrations = [
|
|
|
57
58
|
SELECT bot_key FROM bot_plugin_defaults WHERE json_extract(bot_key, '$[0]') <> 'virtual';`,
|
|
58
59
|
`ALTER TABLE tasks ADD COLUMN delivery_failure TEXT;
|
|
59
60
|
ALTER TABLE task_attempts ADD COLUMN delivery_failure TEXT;`,
|
|
61
|
+
`CREATE TABLE plugin_credentials (
|
|
62
|
+
id TEXT PRIMARY KEY, plugin TEXT NOT NULL, purpose TEXT NOT NULL, label TEXT NOT NULL,
|
|
63
|
+
created_at INTEGER NOT NULL, ciphertext BLOB NOT NULL, retired INTEGER NOT NULL DEFAULT 0
|
|
64
|
+
);
|
|
65
|
+
CREATE INDEX plugin_credentials_purpose ON plugin_credentials(plugin, purpose, retired);`,
|
|
66
|
+
'ALTER TABLE bot_accounts ADD COLUMN alias TEXT;',
|
|
60
67
|
];
|
|
61
68
|
/** SQLite 存储及插件状态、迁移和访问控制管理器。 */
|
|
62
69
|
export class Storage {
|
|
@@ -67,10 +74,12 @@ export class Storage {
|
|
|
67
74
|
groups = new Map();
|
|
68
75
|
commandGroups = new Map();
|
|
69
76
|
accessEntries = new Map();
|
|
77
|
+
credentials;
|
|
70
78
|
access;
|
|
71
79
|
constructor(dataDir, logger) {
|
|
72
80
|
this.dataDir = dataDir;
|
|
73
81
|
this.logger = logger;
|
|
82
|
+
this.credentials = new CredentialStore(() => this.db, dataDir);
|
|
74
83
|
this.access = {
|
|
75
84
|
add: (list, subject, key) => {
|
|
76
85
|
this.db.prepare('INSERT OR IGNORE INTO access_list VALUES (?, ?, ?)').run(list, subject, key);
|
|
@@ -285,6 +294,7 @@ export class Storage {
|
|
|
285
294
|
'plugin_group_state',
|
|
286
295
|
'plugin_group_config',
|
|
287
296
|
'plugin_bot_policy',
|
|
297
|
+
'plugin_credentials',
|
|
288
298
|
'task_attempts',
|
|
289
299
|
'tasks',
|
|
290
300
|
]) {
|
package/dist/index.d.ts
CHANGED
|
@@ -37,11 +37,12 @@ export { isSegment, normalizeSendable, plainText, seg, } from './core/message/in
|
|
|
37
37
|
export type { Permission, Rule } from './core/permission.ts';
|
|
38
38
|
export { perm } from './core/permission.ts';
|
|
39
39
|
export { Context, type FilteredContext } from './core/plugin/context.ts';
|
|
40
|
+
export type { PluginCredentialFilter, PluginCredentialGroup, PluginCredentialGroups, PluginCredentialInfo, PluginCredentials, PluginCredentialValue, } from './core/plugin/credentials.ts';
|
|
40
41
|
export { definePlugin, type PluginDefinition } from './core/plugin/definition.ts';
|
|
41
42
|
export { PluginManager } from './core/plugin/manager.ts';
|
|
42
43
|
export type { TaskAttempt, TaskHandle, TaskHandler, TaskOptions, TaskOutcome, TaskPolicy, TaskQuery, TaskRecord, TaskRegistrationOptions, TaskState, } from './core/plugin/tasks.ts';
|
|
43
44
|
export { TaskConflictError } from './core/plugin/tasks.ts';
|
|
44
|
-
export type { PanelPageOptions, PluginState, PluginStateEvent, ServiceConsumer } from './core/plugin/types.ts';
|
|
45
|
+
export type { PanelPageOptions, PluginCatalogEntry, PluginState, PluginStateEvent, ServiceConsumer, } from './core/plugin/types.ts';
|
|
45
46
|
export type { CooldownScope } from './core/ratelimit.ts';
|
|
46
47
|
export { type AccessEntry, type AccessList, type AccessSubject, KVStore, Storage, } from './core/storage/index.ts';
|
|
47
48
|
export { formatTarget, parseTarget, type Target, targetSchema } from './core/target.ts';
|
package/dist/server/index.d.ts
CHANGED
package/dist/server/index.js
CHANGED
|
@@ -19,6 +19,7 @@ import { getRecentLogs, subscribeLogs } from '../core/logger.js';
|
|
|
19
19
|
import { plainText } from '../core/message/index.js';
|
|
20
20
|
import { TaskConflictError, taskStates } from '../core/plugin/tasks.js';
|
|
21
21
|
import { ManagementError } from '../core/plugin/upload.js';
|
|
22
|
+
import { CredentialUnavailableError, DuplicateCredentialError } from '../core/storage/credentials.js';
|
|
22
23
|
import { redactText, redactValue } from '../core/utils/redact.js';
|
|
23
24
|
import { constantTimeEqual } from '../core/utils/security.js';
|
|
24
25
|
import { PanelAuth } from './auth.js';
|
|
@@ -26,7 +27,7 @@ import { ConnectionSetups, connectionSetupInput, verificationInput } from './con
|
|
|
26
27
|
import { Groups } from './groups.js';
|
|
27
28
|
import { Playground } from './playground.js';
|
|
28
29
|
import { isPluginPageName, pluginPageFile, unsafePluginPageUrl } from './plugin-pages.js';
|
|
29
|
-
import { accessSchema, packageInstallSchema, packageNameSchema, packageUninstallSchema, playgroundEventSchema, playgroundSchema, purgeSchema, sendSchema, uploadSchema, } from './schemas.js';
|
|
30
|
+
import { accessSchema, botAliasSchema, packageInstallSchema, packageNameSchema, packageUninstallSchema, playgroundEventSchema, playgroundSchema, pluginCredentialInput, purgeSchema, sendSchema, uploadSchema, } from './schemas.js';
|
|
30
31
|
import { ConnectionSetupError, connectionSetupSaveInput, SettingsService, SettingsValidationError, SetupCodeError, settingsInput, setupInput, } from './settings.js';
|
|
31
32
|
import { botPluginView, commandView, overview, panelBot, panelBots, pluginView } from './views.js';
|
|
32
33
|
const deliveryStatus = {
|
|
@@ -56,6 +57,12 @@ function failure(c, error) {
|
|
|
56
57
|
error: { code: error.code, message: error.message, ...(error.issues ? { issues: error.issues } : {}) },
|
|
57
58
|
}, error.status);
|
|
58
59
|
}
|
|
60
|
+
function requestWithUrl(request, url) {
|
|
61
|
+
// Hono's lightweight Request cannot be passed directly as RequestInit.
|
|
62
|
+
const { method, headers, body, signal } = request;
|
|
63
|
+
const init = { method, headers, body, signal, duplex: 'half' };
|
|
64
|
+
return new Request(url, init);
|
|
65
|
+
}
|
|
59
66
|
function issuePath(path) {
|
|
60
67
|
return (path.reduce((value, part) => typeof part === 'number' ? `${value}[${part}]` : value ? `${value}.${String(part)}` : String(part), '') || '<root>');
|
|
61
68
|
}
|
|
@@ -83,14 +90,14 @@ function configSecrets(value, key = '') {
|
|
|
83
90
|
}
|
|
84
91
|
return [];
|
|
85
92
|
}
|
|
86
|
-
async function body(c, schema, maxBytes) {
|
|
93
|
+
async function body(c, schema, maxBytes, tooLargeMessage = 'Request exceeds 2 MB') {
|
|
87
94
|
let value;
|
|
88
95
|
try {
|
|
89
96
|
if (maxBytes === undefined)
|
|
90
97
|
value = await c.req.json();
|
|
91
98
|
else {
|
|
92
99
|
if (Number(c.req.header('content-length') ?? 0) > maxBytes)
|
|
93
|
-
throw new HttpError(400, 'BAD_REQUEST',
|
|
100
|
+
throw new HttpError(400, 'BAD_REQUEST', tooLargeMessage);
|
|
94
101
|
const reader = c.req.raw.body?.getReader();
|
|
95
102
|
if (!reader)
|
|
96
103
|
throw new HttpError(400, 'BAD_REQUEST', 'Invalid JSON');
|
|
@@ -103,7 +110,7 @@ async function body(c, schema, maxBytes) {
|
|
|
103
110
|
size += part.value.length;
|
|
104
111
|
if (size > maxBytes) {
|
|
105
112
|
await reader.cancel();
|
|
106
|
-
throw new HttpError(400, 'BAD_REQUEST',
|
|
113
|
+
throw new HttpError(400, 'BAD_REQUEST', tooLargeMessage);
|
|
107
114
|
}
|
|
108
115
|
chunks.push(part.value);
|
|
109
116
|
}
|
|
@@ -295,6 +302,10 @@ export class HttpServer {
|
|
|
295
302
|
return failure(c, new HttpError(400, 'BAD_REQUEST', error.message));
|
|
296
303
|
if (error instanceof SetupCodeError)
|
|
297
304
|
return failure(c, new HttpError(401, 'UNAUTHORIZED', 'Invalid setup code'));
|
|
305
|
+
if (error instanceof CredentialUnavailableError)
|
|
306
|
+
return failure(c, new HttpError(503, 'CREDENTIAL_UNAVAILABLE', error.message));
|
|
307
|
+
if (error instanceof DuplicateCredentialError)
|
|
308
|
+
return failure(c, new HttpError(409, 'CONFLICT', error.message));
|
|
298
309
|
if (error instanceof ManagementError)
|
|
299
310
|
return failure(c, new HttpError(error.status, error.status === 409 ? 'CONFLICT' : error.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', error.message));
|
|
300
311
|
this.app.logger.error({ err: error, method: c.req.method, path: c.req.path }, 'HTTP request failed');
|
|
@@ -317,7 +328,7 @@ export class HttpServer {
|
|
|
317
328
|
throw new HttpError(404, 'NOT_FOUND', 'Plugin route not found');
|
|
318
329
|
const url = new URL(c.req.url);
|
|
319
330
|
url.pathname = url.pathname.replace(/^\/plugins\/[^/]+/, '') || '/';
|
|
320
|
-
return app.fetch(
|
|
331
|
+
return app.fetch(requestWithUrl(c.req.raw, url));
|
|
321
332
|
};
|
|
322
333
|
routes.all('/plugins/:name', forwardPlugin);
|
|
323
334
|
routes.all('/plugins/:name/*', forwardPlugin);
|
|
@@ -485,7 +496,7 @@ export class HttpServer {
|
|
|
485
496
|
throw new HttpError(404, 'NOT_FOUND', 'Plugin route not found');
|
|
486
497
|
const url = new URL(c.req.url);
|
|
487
498
|
url.pathname = url.pathname.replace(/^\/api\/panel\/ext\/[^/]+/, '') || '/';
|
|
488
|
-
return app.fetch(
|
|
499
|
+
return app.fetch(requestWithUrl(c.req.raw, url));
|
|
489
500
|
};
|
|
490
501
|
panel.all('/ext/:name', forwardPanelPlugin);
|
|
491
502
|
panel.all('/ext/:name/*', forwardPanelPlugin);
|
|
@@ -548,6 +559,17 @@ export class HttpServer {
|
|
|
548
559
|
plugins: this.app.plugins.list().map((plugin) => botPluginView(this.app, bot, plugin.name)),
|
|
549
560
|
});
|
|
550
561
|
});
|
|
562
|
+
panel.put('/bots/:platform/:selfId/alias', async (c) => {
|
|
563
|
+
const platform = c.req.param('platform');
|
|
564
|
+
const selfId = c.req.param('selfId');
|
|
565
|
+
const { alias } = await body(c, botAliasSchema, 4096, '别名请求过长');
|
|
566
|
+
if (!this.app.botAccounts.setAlias({ platform, selfId }, alias))
|
|
567
|
+
throw new HttpError(404, 'NOT_FOUND', 'Bot account not found');
|
|
568
|
+
const bot = requireBot(platform, selfId);
|
|
569
|
+
for (const [client, cookie] of this.clientSessions)
|
|
570
|
+
this.pushFrame(client, cookie, { type: 'bot', bot });
|
|
571
|
+
return c.json(bot);
|
|
572
|
+
});
|
|
551
573
|
panel.put('/bots/:platform/:selfId/admins', async (c) => {
|
|
552
574
|
const bot = requireBot(c.req.param('platform'), c.req.param('selfId'));
|
|
553
575
|
const { admins } = await body(c, z.object({ admins: z.array(z.string().trim().min(1)).max(100) }).strict());
|
|
@@ -634,8 +656,49 @@ export class HttpServer {
|
|
|
634
656
|
})));
|
|
635
657
|
});
|
|
636
658
|
panel.post('/send', async (c) => c.json(await this.send(await body(c, sendSchema))));
|
|
659
|
+
panel.get('/plugin-catalog', (c) => c.json(this.app.plugins.listCatalog()));
|
|
637
660
|
panel.get('/plugins', (c) => c.json(this.app.plugins.list().map((plugin) => pluginView(this.app, plugin))));
|
|
638
661
|
panel.get('/plugins/:name/readme', async (c) => c.json({ readme: await this.app.plugins.packageReadme(c.req.param('name')) }));
|
|
662
|
+
const credentials = this.app.storage.credentials;
|
|
663
|
+
panel.get('/plugins/:name/credentials', (c) => {
|
|
664
|
+
const name = c.req.param('name');
|
|
665
|
+
const plugin = this.requirePlugin(name);
|
|
666
|
+
const groups = plugin.credentialGroups ?? [];
|
|
667
|
+
const declared = new Set(groups.map(({ id }) => id));
|
|
668
|
+
c.header('Cache-Control', 'no-store');
|
|
669
|
+
return c.json({
|
|
670
|
+
groups,
|
|
671
|
+
items: credentials
|
|
672
|
+
.list(name)
|
|
673
|
+
.map((item) => ({ ...item, active: item.active && declared.has(item.group) })),
|
|
674
|
+
});
|
|
675
|
+
});
|
|
676
|
+
panel.post('/plugins/:name/credentials', async (c) => {
|
|
677
|
+
const name = c.req.param('name');
|
|
678
|
+
const input = await body(c, pluginCredentialInput, 32 * 1024, 'Request body is too large');
|
|
679
|
+
const plugin = this.requirePlugin(name);
|
|
680
|
+
if (!plugin.credentialGroups?.some(({ id }) => id === input.group))
|
|
681
|
+
throw new HttpError(400, 'BAD_REQUEST', '插件没有声明这个凭据用途');
|
|
682
|
+
const created = credentials.create(name, input.group, input.label, input.mode === 'import' ? input.value : undefined);
|
|
683
|
+
c.header('Cache-Control', 'no-store');
|
|
684
|
+
return c.json(created, 201);
|
|
685
|
+
});
|
|
686
|
+
panel.post('/plugins/:name/credentials/:id/reveal', (c) => {
|
|
687
|
+
const name = c.req.param('name');
|
|
688
|
+
this.requirePlugin(name);
|
|
689
|
+
c.header('Cache-Control', 'no-store');
|
|
690
|
+
const value = credentials.read(name, c.req.param('id'));
|
|
691
|
+
if (value === undefined)
|
|
692
|
+
throw new HttpError(404, 'NOT_FOUND', '凭据不存在或已撤销');
|
|
693
|
+
return c.json({ value });
|
|
694
|
+
});
|
|
695
|
+
panel.delete('/plugins/:name/credentials/:id', (c) => {
|
|
696
|
+
const name = c.req.param('name');
|
|
697
|
+
this.requirePlugin(name);
|
|
698
|
+
if (!credentials.revoke(name, c.req.param('id')))
|
|
699
|
+
throw new HttpError(404, 'NOT_FOUND', '凭据不存在或已撤销');
|
|
700
|
+
return c.body(null, 204);
|
|
701
|
+
});
|
|
639
702
|
panel.post('/plugins/rescan', async (c) => {
|
|
640
703
|
const result = await this.app.plugins.rescan();
|
|
641
704
|
return c.json({
|
|
@@ -869,27 +932,29 @@ export class HttpServer {
|
|
|
869
932
|
send(input) {
|
|
870
933
|
return this.app.send(input.target, input.message);
|
|
871
934
|
}
|
|
935
|
+
pushFrame(client, cookie, frame) {
|
|
936
|
+
if (client.readyState !== WebSocket.OPEN)
|
|
937
|
+
return;
|
|
938
|
+
if (!this.auth.authenticated(cookie)) {
|
|
939
|
+
client.close(1008, 'Session expired');
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
try {
|
|
943
|
+
client.send(JSON.stringify(frame));
|
|
944
|
+
}
|
|
945
|
+
catch (error) {
|
|
946
|
+
client.terminate();
|
|
947
|
+
this.app.logger.warn({ err: error }, 'Panel WebSocket send failed');
|
|
948
|
+
}
|
|
949
|
+
}
|
|
872
950
|
connect(client, cookie) {
|
|
873
951
|
this.clientSessions.set(client, cookie);
|
|
874
|
-
const push = (frame) =>
|
|
875
|
-
if (client.readyState !== WebSocket.OPEN)
|
|
876
|
-
return;
|
|
877
|
-
if (!this.auth.authenticated(cookie)) {
|
|
878
|
-
client.close(1008, 'Session expired');
|
|
879
|
-
return;
|
|
880
|
-
}
|
|
881
|
-
try {
|
|
882
|
-
client.send(JSON.stringify(frame));
|
|
883
|
-
}
|
|
884
|
-
catch (error) {
|
|
885
|
-
client.terminate();
|
|
886
|
-
this.app.logger.warn({ err: error }, 'Panel WebSocket send failed');
|
|
887
|
-
}
|
|
888
|
-
};
|
|
952
|
+
const push = (frame) => this.pushFrame(client, cookie, frame);
|
|
889
953
|
push({ type: 'hello', overview: overview(this.app) });
|
|
890
954
|
const unsubscribeLogs = subscribeLogs((record) => push({ type: 'log', record }));
|
|
891
955
|
const unsubscribePackages = this.app.plugins.packages.subscribe((operation) => push({ type: 'package', operation: this.packageOperation(operation) }));
|
|
892
956
|
const unsubscribePackageUpdates = this.app.plugins.subscribePackageUpdates((plugin) => push({ type: 'plugin', plugin: pluginView(this.app, plugin) }));
|
|
957
|
+
const unsubscribePluginList = this.app.plugins.subscribeListChanges(() => push({ type: 'plugins-changed' }));
|
|
893
958
|
const unsubscribeEvents = this.app.subscribeDispatch((event) => {
|
|
894
959
|
const frame = this.eventFrame(event);
|
|
895
960
|
if (frame)
|
|
@@ -928,6 +993,7 @@ export class HttpServer {
|
|
|
928
993
|
unsubscribeLogs();
|
|
929
994
|
unsubscribePackages();
|
|
930
995
|
unsubscribePackageUpdates();
|
|
996
|
+
unsubscribePluginList();
|
|
931
997
|
unsubscribeEvents();
|
|
932
998
|
unsubscribePanelEvents();
|
|
933
999
|
unsubscribeTasks();
|
package/dist/server/schemas.d.ts
CHANGED
|
@@ -18,6 +18,16 @@ export declare const sendSchema: z.ZodObject<{
|
|
|
18
18
|
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
19
19
|
}, z.core.$strip>>]>;
|
|
20
20
|
}, z.core.$strict>;
|
|
21
|
+
export declare const pluginCredentialInput: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
22
|
+
group: z.ZodString;
|
|
23
|
+
label: z.ZodString;
|
|
24
|
+
mode: z.ZodLiteral<"generate">;
|
|
25
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
26
|
+
group: z.ZodString;
|
|
27
|
+
label: z.ZodString;
|
|
28
|
+
mode: z.ZodLiteral<"import">;
|
|
29
|
+
value: z.ZodString;
|
|
30
|
+
}, z.core.$strip>], "mode">;
|
|
21
31
|
export declare const playgroundSchema: z.ZodObject<{
|
|
22
32
|
text: z.ZodOptional<z.ZodString>;
|
|
23
33
|
message: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
@@ -101,6 +111,9 @@ export declare const uploadSchema: z.ZodObject<{
|
|
|
101
111
|
export declare const purgeSchema: z.ZodObject<{
|
|
102
112
|
purge: z.ZodBoolean;
|
|
103
113
|
}, z.core.$strip>;
|
|
114
|
+
export declare const botAliasSchema: z.ZodObject<{
|
|
115
|
+
alias: z.ZodNullable<z.ZodString>;
|
|
116
|
+
}, z.core.$strict>;
|
|
104
117
|
export declare const packageInstallSchema: z.ZodObject<{
|
|
105
118
|
name: z.ZodString;
|
|
106
119
|
version: z.ZodOptional<z.ZodString>;
|
package/dist/server/schemas.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { credentialGroupId } from '../core/plugin/credentials.js';
|
|
2
3
|
import { targetSchema } from '../core/target.js';
|
|
3
4
|
const mediaTypes = new Set(['image', 'audio', 'video', 'file']);
|
|
4
5
|
/** `file:` URLs and absolute paths (POSIX, Windows drive, UNC / root-relative). */
|
|
@@ -52,6 +53,24 @@ export const sendSchema = z
|
|
|
52
53
|
message: z.union([z.string(), z.array(segment)]),
|
|
53
54
|
})
|
|
54
55
|
.strict();
|
|
56
|
+
const credentialFields = { group: credentialGroupId, label: z.string().trim().min(1).max(80) };
|
|
57
|
+
export const pluginCredentialInput = z
|
|
58
|
+
.discriminatedUnion('mode', [
|
|
59
|
+
z.object({ ...credentialFields, mode: z.literal('generate') }),
|
|
60
|
+
z.object({
|
|
61
|
+
...credentialFields,
|
|
62
|
+
mode: z.literal('import'),
|
|
63
|
+
value: z
|
|
64
|
+
.string()
|
|
65
|
+
.min(1)
|
|
66
|
+
.max(4096)
|
|
67
|
+
.refine((value) => value.trim() && value.isWellFormed() && !/[\r\n]/.test(value), '请输入单行凭据原值'),
|
|
68
|
+
}),
|
|
69
|
+
])
|
|
70
|
+
.refine((input) => input.mode === 'generate' || !input.label.includes(input.value), {
|
|
71
|
+
path: ['label'],
|
|
72
|
+
message: '凭据名称不能包含凭据原值',
|
|
73
|
+
});
|
|
55
74
|
const playgroundUser = z.object({
|
|
56
75
|
id: z.string().min(1),
|
|
57
76
|
nickname: z.string().optional(),
|
|
@@ -117,6 +136,15 @@ export const uploadSchema = z.object({
|
|
|
117
136
|
overwrite: z.boolean().optional(),
|
|
118
137
|
});
|
|
119
138
|
export const purgeSchema = z.object({ purge: z.boolean() });
|
|
139
|
+
export const botAliasSchema = z.strictObject({
|
|
140
|
+
alias: z
|
|
141
|
+
.string()
|
|
142
|
+
.trim()
|
|
143
|
+
.min(1)
|
|
144
|
+
.max(80, '别名最多 80 个字符')
|
|
145
|
+
.refine((value) => value.isWellFormed() && !value.includes('\0') && !/[\r\n\u2028\u2029]/.test(value), '请输入单行别名')
|
|
146
|
+
.nullable(),
|
|
147
|
+
});
|
|
120
148
|
export const packageInstallSchema = z.object({
|
|
121
149
|
name: z.string(),
|
|
122
150
|
version: z.string().optional(),
|
package/dist/server/views.d.ts
CHANGED
|
@@ -44,6 +44,7 @@ export declare function pluginView(app: App, state: PluginState): {
|
|
|
44
44
|
enabled: boolean;
|
|
45
45
|
configSchema?: Record<string, unknown>;
|
|
46
46
|
capabilities?: import("../core/capabilities.ts").CapabilityRequirements;
|
|
47
|
+
hasCredentials: boolean;
|
|
47
48
|
defaultOnNewBots: boolean;
|
|
48
49
|
provides: string[];
|
|
49
50
|
inject: {
|
|
@@ -97,6 +98,7 @@ export declare function overview(app: App): {
|
|
|
97
98
|
bots: {
|
|
98
99
|
platform: string;
|
|
99
100
|
selfId: string;
|
|
101
|
+
alias?: string;
|
|
100
102
|
connectionId?: string;
|
|
101
103
|
lastOnlineAt?: number;
|
|
102
104
|
nickname: string | undefined;
|
|
@@ -118,6 +120,7 @@ export declare function overview(app: App): {
|
|
|
118
120
|
export declare function panelBot(app: App, identity: BotIdentity): {
|
|
119
121
|
platform: string;
|
|
120
122
|
selfId: string;
|
|
123
|
+
alias?: string;
|
|
121
124
|
connectionId?: string;
|
|
122
125
|
lastOnlineAt?: number;
|
|
123
126
|
nickname: string | undefined;
|
|
@@ -129,6 +132,7 @@ export declare function panelBot(app: App, identity: BotIdentity): {
|
|
|
129
132
|
export declare function panelBots(app: App): {
|
|
130
133
|
platform: string;
|
|
131
134
|
selfId: string;
|
|
135
|
+
alias?: string;
|
|
132
136
|
connectionId?: string;
|
|
133
137
|
lastOnlineAt?: number;
|
|
134
138
|
nickname: string | undefined;
|
|
@@ -150,6 +154,7 @@ export declare function botPluginView(app: App, bot: BotAccount, name: string):
|
|
|
150
154
|
enabled: boolean;
|
|
151
155
|
configSchema?: Record<string, unknown>;
|
|
152
156
|
capabilities?: import("../core/capabilities.ts").CapabilityRequirements;
|
|
157
|
+
hasCredentials: boolean;
|
|
153
158
|
defaultOnNewBots: boolean;
|
|
154
159
|
provides: string[];
|
|
155
160
|
inject: {
|
package/dist/server/views.js
CHANGED
|
@@ -39,6 +39,7 @@ export function commandView(app, command) {
|
|
|
39
39
|
};
|
|
40
40
|
}
|
|
41
41
|
export function pluginView(app, state) {
|
|
42
|
+
const { credentialGroups, ...view } = state;
|
|
42
43
|
const value = app.plugins.getConfig(state.name);
|
|
43
44
|
const page = app.getPanelPage(state.name);
|
|
44
45
|
let config;
|
|
@@ -53,7 +54,8 @@ export function pluginView(app, state) {
|
|
|
53
54
|
}
|
|
54
55
|
}
|
|
55
56
|
return {
|
|
56
|
-
...
|
|
57
|
+
...view,
|
|
58
|
+
hasCredentials: Boolean(credentialGroups?.length) || app.storage.credentials.has(state.name),
|
|
57
59
|
defaultOnNewBots: app.config.plugins[state.name]?.defaultOnNewBots ?? false,
|
|
58
60
|
provides: [...state.provides],
|
|
59
61
|
inject: [...state.inject],
|