@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.
Files changed (37) hide show
  1. package/README.md +64 -2
  2. package/dist/core/bot-accounts.d.ts +2 -0
  3. package/dist/core/bot-accounts.js +7 -0
  4. package/dist/core/logger.js +4 -1
  5. package/dist/core/message/segment.js +3 -13
  6. package/dist/core/plugin/context.d.ts +15 -1
  7. package/dist/core/plugin/context.js +43 -3
  8. package/dist/core/plugin/credentials.d.ts +44 -0
  9. package/dist/core/plugin/credentials.js +45 -0
  10. package/dist/core/plugin/definition.d.ts +5 -0
  11. package/dist/core/plugin/icon.d.ts +2 -0
  12. package/dist/core/plugin/icon.js +14 -0
  13. package/dist/core/plugin/manager.d.ts +15 -3
  14. package/dist/core/plugin/manager.js +115 -34
  15. package/dist/core/plugin/packages.d.ts +4 -0
  16. package/dist/core/plugin/packages.js +39 -9
  17. package/dist/core/plugin/types.d.ts +24 -0
  18. package/dist/core/storage/credentials.d.ts +25 -0
  19. package/dist/core/storage/credentials.js +139 -0
  20. package/dist/core/storage/index.d.ts +2 -0
  21. package/dist/core/storage/index.js +10 -0
  22. package/dist/index.d.ts +2 -1
  23. package/dist/server/index.d.ts +1 -0
  24. package/dist/server/index.js +88 -21
  25. package/dist/server/schemas.d.ts +13 -0
  26. package/dist/server/schemas.js +28 -0
  27. package/dist/server/views.d.ts +7 -0
  28. package/dist/server/views.js +3 -1
  29. package/docs/DEPLOY.md +22 -1
  30. package/package.json +1 -1
  31. package/web/dist/assets/index-C3RsfNwC.js +51 -0
  32. package/web/dist/assets/index-Dz7T5hDM.css +2 -0
  33. package/web/dist/assets/{markdown-MEN1AImu.js → markdown-HrgPSKyp.js} +4 -4
  34. package/web/dist/assets/plugin-credentials-CuMBPnPO.js +1 -0
  35. package/web/dist/index.html +2 -2
  36. package/web/dist/assets/index-BAbj8e7E.css +0 -2
  37. package/web/dist/assets/index-CMuBy6y5.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 } 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';
@@ -22,6 +22,7 @@ export declare class HttpServer implements ServerService {
22
22
  private setSessionCookie;
23
23
  private packageOperation;
24
24
  private send;
25
+ private pushFrame;
25
26
  private connect;
26
27
  private eventFrame;
27
28
  }
@@ -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', 'Request exceeds 2 MB');
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', 'Request exceeds 2 MB');
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(new Request(url, c.req.raw));
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(new Request(url, c.req.raw));
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,7 +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))));
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
+ });
638
702
  panel.post('/plugins/rescan', async (c) => {
639
703
  const result = await this.app.plugins.rescan();
640
704
  return c.json({
@@ -868,27 +932,29 @@ export class HttpServer {
868
932
  send(input) {
869
933
  return this.app.send(input.target, input.message);
870
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
+ }
871
950
  connect(client, cookie) {
872
951
  this.clientSessions.set(client, cookie);
873
- const push = (frame) => {
874
- if (client.readyState !== WebSocket.OPEN)
875
- return;
876
- if (!this.auth.authenticated(cookie)) {
877
- client.close(1008, 'Session expired');
878
- return;
879
- }
880
- try {
881
- client.send(JSON.stringify(frame));
882
- }
883
- catch (error) {
884
- client.terminate();
885
- this.app.logger.warn({ err: error }, 'Panel WebSocket send failed');
886
- }
887
- };
952
+ const push = (frame) => this.pushFrame(client, cookie, frame);
888
953
  push({ type: 'hello', overview: overview(this.app) });
889
954
  const unsubscribeLogs = subscribeLogs((record) => push({ type: 'log', record }));
890
955
  const unsubscribePackages = this.app.plugins.packages.subscribe((operation) => push({ type: 'package', operation: this.packageOperation(operation) }));
891
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' }));
892
958
  const unsubscribeEvents = this.app.subscribeDispatch((event) => {
893
959
  const frame = this.eventFrame(event);
894
960
  if (frame)
@@ -927,6 +993,7 @@ export class HttpServer {
927
993
  unsubscribeLogs();
928
994
  unsubscribePackages();
929
995
  unsubscribePackageUpdates();
996
+ unsubscribePluginList();
930
997
  unsubscribeEvents();
931
998
  unsubscribePanelEvents();
932
999
  unsubscribeTasks();
@@ -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>;
@@ -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(),
@@ -35,6 +35,7 @@ export declare function pluginView(app: App, state: PluginState): {
35
35
  name: string;
36
36
  version?: string;
37
37
  description?: string;
38
+ iconUrl?: string;
38
39
  depends?: string[];
39
40
  source: 'builtin' | 'file' | 'package';
40
41
  path?: string;
@@ -43,6 +44,7 @@ export declare function pluginView(app: App, state: PluginState): {
43
44
  enabled: boolean;
44
45
  configSchema?: Record<string, unknown>;
45
46
  capabilities?: import("../core/capabilities.ts").CapabilityRequirements;
47
+ hasCredentials: boolean;
46
48
  defaultOnNewBots: boolean;
47
49
  provides: string[];
48
50
  inject: {
@@ -96,6 +98,7 @@ export declare function overview(app: App): {
96
98
  bots: {
97
99
  platform: string;
98
100
  selfId: string;
101
+ alias?: string;
99
102
  connectionId?: string;
100
103
  lastOnlineAt?: number;
101
104
  nickname: string | undefined;
@@ -117,6 +120,7 @@ export declare function overview(app: App): {
117
120
  export declare function panelBot(app: App, identity: BotIdentity): {
118
121
  platform: string;
119
122
  selfId: string;
123
+ alias?: string;
120
124
  connectionId?: string;
121
125
  lastOnlineAt?: number;
122
126
  nickname: string | undefined;
@@ -128,6 +132,7 @@ export declare function panelBot(app: App, identity: BotIdentity): {
128
132
  export declare function panelBots(app: App): {
129
133
  platform: string;
130
134
  selfId: string;
135
+ alias?: string;
131
136
  connectionId?: string;
132
137
  lastOnlineAt?: number;
133
138
  nickname: string | undefined;
@@ -140,6 +145,7 @@ export declare function botPluginView(app: App, bot: BotAccount, name: string):
140
145
  name: string;
141
146
  version?: string;
142
147
  description?: string;
148
+ iconUrl?: string;
143
149
  depends?: string[];
144
150
  source: 'builtin' | 'file' | 'package';
145
151
  path?: string;
@@ -148,6 +154,7 @@ export declare function botPluginView(app: App, bot: BotAccount, name: string):
148
154
  enabled: boolean;
149
155
  configSchema?: Record<string, unknown>;
150
156
  capabilities?: import("../core/capabilities.ts").CapabilityRequirements;
157
+ hasCredentials: boolean;
151
158
  defaultOnNewBots: boolean;
152
159
  provides: string[];
153
160
  inject: {
@@ -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
- ...state,
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],
package/docs/DEPLOY.md CHANGED
@@ -54,6 +54,27 @@ curl http://127.0.0.1:5140/healthz
54
54
 
55
55
  Compose 只启动 AsaBot;OneBot 服务需要自行准备。`/healthz` 检查 HTTP 服务是否运行,Bot 离线时也会返回成功,可结合响应中的 `bots.online` 查看连接状态。停止服务使用 `docker compose stop`。
56
56
 
57
+ ### 使用 GHCR 镜像
58
+
59
+ Linux x86-64 服务器可以直接拉取预构建镜像。在 `compose.yaml` 同目录下的 `compose.override.yaml` 中为 `asabot` 服务设置以下两项(已有端口、网络等配置可继续保留):
60
+
61
+ ```yaml
62
+ services:
63
+ asabot:
64
+ build: !reset null
65
+ image: ghcr.io/isyuah/asabot:latest
66
+ ```
67
+
68
+ `!reset` 清除主配置里的本地构建配置,需要 Docker Compose 2.24.4 或更新版本。初始化配置和目录后,首次启动和后续拉取新版使用同一条命令:
69
+
70
+ ```sh
71
+ docker compose up -d --pull always --wait asabot
72
+ ```
73
+
74
+ Compose 会先拉取镜像,再根据变更重建 AsaBot 容器,沿用宿主机上的 `config`、`data` 和 `plugins`。`latest` 会在发布时更新,已经运行的容器要在执行上述命令后才会换用新镜像。也可以指定版本号或 `sha-<完整 Git 提交哈希>` 标签来固定部署版本。
75
+
76
+ 维护者推送 `vX.Y.Z` 格式的 Git 标签后,[Publish container image](https://github.com/isyuah/AsaBot/actions/workflows/container.yml) 会发布 `X.Y.Z`、`sha-<完整 Git 提交哈希>` 和 `latest`。也可在 Actions 中对默认分支手动运行该工作流,更新 `latest` 和提交标签。[公开镜像](https://github.com/isyuah/AsaBot/pkgs/container/asabot)可以匿名拉取。
77
+
57
78
  也可直接构建和运行容器(示例为 Linux/macOS shell):
58
79
 
59
80
  ```sh
@@ -150,7 +171,7 @@ server {
150
171
 
151
172
  数据目录包含 `asabot.db`、SQLite 的 WAL 文件以及插件数据。备份前先停止 AsaBot,再备份整个数据目录、用户插件和实际使用的配置文件;环境变量和 `.env` 应单独安全保存。恢复时使用对应的数据、插件和配置,并确保容器用户有正确的读写权限。
152
173
 
153
- 升级前先停止服务并完成备份。更新仓库代码后,直接运行方式执行 `pnpm install --frozen-lockfile` 和 `pnpm --filter web build` 再启动;Compose 方式执行 `docker compose up -d --build`。升级后检查日志、`/healthz`、面板和 OneBot 连接。升级时保留原有数据挂载,不要清理数据卷。
174
+ 升级前先停止服务并完成备份。直接运行方式在更新仓库代码后执行 `pnpm install --frozen-lockfile` 和 `pnpm --filter web build` 再启动;Compose 按部署方式构建源码或[拉取 GHCR 镜像](#使用-ghcr-镜像)。升级后检查日志、`/healthz`、面板和 OneBot 连接。升级时保留原有数据挂载,不要清理数据卷。
154
175
 
155
176
  ### 从 0.1.x 迁移群规则
156
177
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asabot/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "协议无关的 TypeScript 聊天机器人框架,内置 Web 面板、任务中心及 OneBot 11、飞书、企业微信、微信 ClawBot 适配器",
5
5
  "license": "MIT",
6
6
  "repository": {