@asabot/core 0.1.0 → 0.2.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 (165) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +78 -13
  3. package/asabot.config.example.yaml +47 -29
  4. package/dist/adapters/feishu/adapter.d.ts +19 -0
  5. package/dist/adapters/feishu/adapter.js +621 -0
  6. package/dist/adapters/feishu/api.d.ts +142 -0
  7. package/dist/adapters/feishu/api.js +306 -0
  8. package/dist/adapters/feishu/bot.d.ts +95 -0
  9. package/dist/adapters/feishu/bot.js +539 -0
  10. package/dist/adapters/feishu/cards.d.ts +93 -0
  11. package/dist/adapters/feishu/cards.js +106 -0
  12. package/dist/adapters/feishu/config.d.ts +13 -0
  13. package/dist/adapters/feishu/config.js +36 -0
  14. package/dist/adapters/feishu/events.d.ts +33 -0
  15. package/dist/adapters/feishu/events.js +14 -0
  16. package/dist/adapters/feishu/index.d.ts +8 -0
  17. package/dist/adapters/feishu/index.js +5 -0
  18. package/dist/adapters/feishu/message.d.ts +64 -0
  19. package/dist/adapters/feishu/message.js +197 -0
  20. package/dist/adapters/feishu/transport.d.ts +34 -0
  21. package/dist/adapters/feishu/transport.js +110 -0
  22. package/dist/adapters/index.d.ts +1 -7
  23. package/dist/adapters/index.js +75 -6
  24. package/dist/adapters/loader.d.ts +6 -0
  25. package/dist/adapters/loader.js +73 -0
  26. package/dist/adapters/media-source.d.ts +7 -0
  27. package/dist/adapters/media-source.js +137 -0
  28. package/dist/adapters/onebot11/adapter.d.ts +5 -0
  29. package/dist/adapters/onebot11/adapter.js +23 -11
  30. package/dist/adapters/onebot11/api.d.ts +4 -1
  31. package/dist/adapters/onebot11/api.js +21 -8
  32. package/dist/adapters/onebot11/errors.d.ts +3 -0
  33. package/dist/adapters/onebot11/errors.js +6 -0
  34. package/dist/adapters/virtual/index.js +7 -1
  35. package/dist/adapters/wecom/adapter.d.ts +14 -0
  36. package/dist/adapters/wecom/adapter.js +220 -0
  37. package/dist/adapters/wecom/bot.d.ts +71 -0
  38. package/dist/adapters/wecom/bot.js +312 -0
  39. package/dist/adapters/wecom/cards.d.ts +37 -0
  40. package/dist/adapters/wecom/cards.js +30 -0
  41. package/dist/adapters/wecom/config.d.ts +8 -0
  42. package/dist/adapters/wecom/config.js +10 -0
  43. package/dist/adapters/wecom/events.d.ts +93 -0
  44. package/dist/adapters/wecom/events.js +46 -0
  45. package/dist/adapters/wecom/index.d.ts +7 -0
  46. package/dist/adapters/wecom/index.js +21 -0
  47. package/dist/adapters/wecom/media.d.ts +50 -0
  48. package/dist/adapters/wecom/media.js +149 -0
  49. package/dist/adapters/wecom/message.d.ts +151 -0
  50. package/dist/adapters/wecom/message.js +116 -0
  51. package/dist/adapters/wecom/transport.d.ts +39 -0
  52. package/dist/adapters/wecom/transport.js +116 -0
  53. package/dist/adapters/weixin-clawbot/adapter.d.ts +16 -0
  54. package/dist/adapters/weixin-clawbot/adapter.js +173 -0
  55. package/dist/adapters/weixin-clawbot/bot.d.ts +41 -0
  56. package/dist/adapters/weixin-clawbot/bot.js +254 -0
  57. package/dist/adapters/weixin-clawbot/index.d.ts +2 -0
  58. package/dist/adapters/weixin-clawbot/index.js +19 -0
  59. package/dist/adapters/weixin-clawbot/media.d.ts +57 -0
  60. package/dist/adapters/weixin-clawbot/media.js +196 -0
  61. package/dist/adapters/weixin-clawbot/message.d.ts +12 -0
  62. package/dist/adapters/weixin-clawbot/message.js +79 -0
  63. package/dist/adapters/weixin-clawbot/protocol.d.ts +145 -0
  64. package/dist/adapters/weixin-clawbot/protocol.js +178 -0
  65. package/dist/adapters/weixin-clawbot/setup.d.ts +2 -0
  66. package/dist/adapters/weixin-clawbot/setup.js +121 -0
  67. package/dist/bootstrap.d.ts +5 -0
  68. package/dist/bootstrap.js +5 -20
  69. package/dist/cli.js +9 -3
  70. package/dist/core/adapter.d.ts +69 -3
  71. package/dist/core/adapter.js +11 -1
  72. package/dist/core/app.d.ts +12 -9
  73. package/dist/core/app.js +50 -51
  74. package/dist/core/bot-accounts.d.ts +28 -0
  75. package/dist/core/bot-accounts.js +78 -0
  76. package/dist/core/bot-policies.d.ts +30 -0
  77. package/dist/core/bot-policies.js +112 -0
  78. package/dist/core/bot.d.ts +19 -1
  79. package/dist/core/bot.js +13 -0
  80. package/dist/core/capabilities.d.ts +54 -0
  81. package/dist/core/capabilities.js +25 -0
  82. package/dist/core/config/schema.d.ts +61 -8
  83. package/dist/core/config/schema.js +15 -3
  84. package/dist/core/config/write.js +5 -1
  85. package/dist/core/connections.d.ts +84 -0
  86. package/dist/core/connections.js +326 -0
  87. package/dist/core/delivery.d.ts +53 -0
  88. package/dist/core/delivery.js +115 -0
  89. package/dist/core/dispatch/api.d.ts +3 -1
  90. package/dist/core/dispatch/api.js +12 -5
  91. package/dist/core/dispatch/dispatcher.d.ts +1 -0
  92. package/dist/core/dispatch/dispatcher.js +35 -15
  93. package/dist/core/dispatch/outgoing.d.ts +1 -0
  94. package/dist/core/dispatch/outgoing.js +5 -3
  95. package/dist/core/dispatch/trace.d.ts +2 -0
  96. package/dist/core/dispatch/types.d.ts +6 -0
  97. package/dist/core/dispatch/types.js +1 -2
  98. package/dist/core/errors.d.ts +4 -1
  99. package/dist/core/errors.js +7 -1
  100. package/dist/core/event/session.d.ts +3 -1
  101. package/dist/core/event/session.js +7 -4
  102. package/dist/core/event/types.d.ts +5 -1
  103. package/dist/core/identity.d.ts +18 -0
  104. package/dist/core/identity.js +31 -0
  105. package/dist/core/logger.js +5 -1
  106. package/dist/core/message/types.d.ts +2 -0
  107. package/dist/core/permission.d.ts +2 -1
  108. package/dist/core/permission.js +7 -2
  109. package/dist/core/plugin/context.d.ts +10 -10
  110. package/dist/core/plugin/context.js +20 -18
  111. package/dist/core/plugin/definition.d.ts +5 -0
  112. package/dist/core/plugin/execution.d.ts +3 -0
  113. package/dist/core/plugin/execution.js +3 -0
  114. package/dist/core/plugin/manager.d.ts +18 -4
  115. package/dist/core/plugin/manager.js +137 -45
  116. package/dist/core/plugin/tasks.d.ts +131 -24
  117. package/dist/core/plugin/tasks.js +517 -117
  118. package/dist/core/plugin/types.d.ts +3 -0
  119. package/dist/core/ratelimit.js +6 -1
  120. package/dist/core/storage/index.d.ts +3 -1
  121. package/dist/core/storage/index.js +52 -2
  122. package/dist/core/target.d.ts +24 -6
  123. package/dist/core/target.js +26 -6
  124. package/dist/core/utils/merge.d.ts +3 -0
  125. package/dist/core/utils/merge.js +18 -0
  126. package/dist/core/utils/redact.d.ts +6 -0
  127. package/dist/core/utils/redact.js +76 -0
  128. package/dist/index.d.ts +13 -5
  129. package/dist/index.js +7 -2
  130. package/dist/plugins/admin.js +30 -3
  131. package/dist/plugins/help.js +1 -0
  132. package/dist/plugins/history.d.ts +4 -0
  133. package/dist/plugins/history.js +13 -3
  134. package/dist/plugins/http.js +1 -0
  135. package/dist/plugins/long-message.js +20 -12
  136. package/dist/plugins/status.js +1 -0
  137. package/dist/server/auth.d.ts +5 -1
  138. package/dist/server/auth.js +11 -7
  139. package/dist/server/connection-setups.d.ts +126 -0
  140. package/dist/server/connection-setups.js +188 -0
  141. package/dist/server/groups.d.ts +1 -0
  142. package/dist/server/groups.js +8 -8
  143. package/dist/server/index.d.ts +1 -0
  144. package/dist/server/index.js +229 -29
  145. package/dist/server/schemas.d.ts +6 -2
  146. package/dist/server/settings.d.ts +66 -20
  147. package/dist/server/settings.js +158 -61
  148. package/dist/server/views.d.ts +95 -17
  149. package/dist/server/views.js +48 -13
  150. package/dist/testing/create-test-app.js +2 -2
  151. package/dist/testing/dispatch-fixture.js +2 -1
  152. package/dist/testing/fake-bot.d.ts +2 -1
  153. package/dist/testing/fake-bot.js +4 -1
  154. package/docs/DEPLOY.md +190 -0
  155. package/docs/FEISHU.md +170 -0
  156. package/docs/WECOM.md +107 -0
  157. package/docs/WEIXIN-CLAWBOT.md +56 -0
  158. package/package.json +29 -3
  159. package/web/dist/assets/index-BAbj8e7E.css +2 -0
  160. package/web/dist/assets/index-CMuBy6y5.js +51 -0
  161. package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-MEN1AImu.js} +3 -3
  162. package/web/dist/index.html +2 -2
  163. package/web/dist/plugin-pages/_sdk.js +26 -1
  164. package/web/dist/assets/index-BI5GCpiI.css +0 -2
  165. package/web/dist/assets/index-C-rshHwD.js +0 -51
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { existsSync } from 'node:fs';
2
3
  import { createServer } from 'node:http';
3
4
  import { fileURLToPath } from 'node:url';
@@ -10,18 +11,35 @@ import { z } from 'zod';
10
11
  import { supports } from '../core/bot.js';
11
12
  import { commandOverrideSchema, logLevelSchema } from '../core/config/schema.js';
12
13
  import { deleteConfigValue, writeConfigValue } from '../core/config/write.js';
13
- import { NoBotOnlineError, PluginConfigError } from '../core/errors.js';
14
+ import { connectionSchema } from '../core/connections.js';
15
+ import { DeliveryError } from '../core/delivery.js';
16
+ import { ConfigError, PluginConfigError } from '../core/errors.js';
17
+ import { groupIdentity } from '../core/identity.js';
14
18
  import { getRecentLogs, subscribeLogs } from '../core/logger.js';
15
19
  import { plainText } from '../core/message/index.js';
20
+ import { TaskConflictError, taskStates } from '../core/plugin/tasks.js';
16
21
  import { ManagementError } from '../core/plugin/upload.js';
22
+ import { redactText, redactValue } from '../core/utils/redact.js';
17
23
  import { constantTimeEqual } from '../core/utils/security.js';
18
24
  import { PanelAuth } from './auth.js';
25
+ import { ConnectionSetups, connectionSetupInput, verificationInput } from './connection-setups.js';
19
26
  import { Groups } from './groups.js';
20
27
  import { Playground } from './playground.js';
21
28
  import { isPluginPageName, pluginPageFile, unsafePluginPageUrl } from './plugin-pages.js';
22
29
  import { accessSchema, packageInstallSchema, packageNameSchema, packageUninstallSchema, playgroundEventSchema, playgroundSchema, purgeSchema, sendSchema, uploadSchema, } from './schemas.js';
23
- import { SettingsService, SettingsValidationError, SetupCodeError, settingsInput, setupInput, } from './settings.js';
24
- import { botView, commandView, overview, pluginView } from './views.js';
30
+ import { ConnectionSetupError, connectionSetupSaveInput, SettingsService, SettingsValidationError, SetupCodeError, settingsInput, setupInput, } from './settings.js';
31
+ import { botPluginView, commandView, overview, panelBot, panelBots, pluginView } from './views.js';
32
+ const deliveryStatus = {
33
+ NO_BOT_ONLINE: 409,
34
+ CONVERSATION_UNAVAILABLE: 409,
35
+ RATE_LIMITED: 429,
36
+ DELIVERY_TIMEOUT: 504,
37
+ DELIVERY_UNCONFIRMED: 502,
38
+ DELIVERY_REJECTED: 502,
39
+ DELIVERY_UNSUPPORTED: 400,
40
+ DELIVERY_BLOCKED: 403,
41
+ DELIVERY_PREPARATION_FAILED: 400,
42
+ };
25
43
  class HttpError extends Error {
26
44
  status;
27
45
  code;
@@ -168,6 +186,7 @@ export class HttpServer {
168
186
  auth = new PanelAuth();
169
187
  playground;
170
188
  settings;
189
+ connectionSetups;
171
190
  groups;
172
191
  http;
173
192
  websocket = new WebSocketServer({ noServer: true });
@@ -176,6 +195,7 @@ export class HttpServer {
176
195
  this.app = app;
177
196
  this.playground = new Playground(app);
178
197
  this.settings = new SettingsService(app);
198
+ this.connectionSetups = new ConnectionSetups(app, this.settings);
179
199
  this.groups = new Groups(app);
180
200
  const routes = this.routes();
181
201
  const listener = getRequestListener(routes.fetch);
@@ -230,6 +250,7 @@ export class HttpServer {
230
250
  this.app.logger.info({ host: this.app.config.server.host, port: this.address()?.port }, 'HTTP server listening');
231
251
  }
232
252
  async stop() {
253
+ this.connectionSetups.revoke();
233
254
  for (const client of this.websocket.clients)
234
255
  client.terminate();
235
256
  const closed = this.http.listening
@@ -255,10 +276,23 @@ export class HttpServer {
255
276
  routes.onError((error, c) => {
256
277
  if (error instanceof HttpError)
257
278
  return failure(c, error);
279
+ if (error instanceof DeliveryError)
280
+ return c.json({
281
+ error: {
282
+ message: redactText(error.message, this.app.config),
283
+ ...error.publicFailure(this.app.config),
284
+ },
285
+ }, error.outcome === 'partial' ? 409 : deliveryStatus[error.code]);
258
286
  if (error instanceof PluginConfigError)
259
287
  return failure(c, new HttpError(400, 'BAD_REQUEST', 'Plugin configuration is invalid', error.issues));
260
288
  if (error instanceof SettingsValidationError)
261
289
  return failure(c, new HttpError(400, 'BAD_REQUEST', 'Configuration is invalid', error.issues));
290
+ if (error instanceof ConnectionSetupError) {
291
+ const code = { 400: 'BAD_REQUEST', 404: 'NOT_FOUND', 409: 'CONFLICT', 429: 'RATE_LIMITED' }[error.status];
292
+ return failure(c, new HttpError(error.status, code, error.message));
293
+ }
294
+ if (error instanceof ConfigError)
295
+ return failure(c, new HttpError(400, 'BAD_REQUEST', error.message));
262
296
  if (error instanceof SetupCodeError)
263
297
  return failure(c, new HttpError(401, 'UNAUTHORIZED', 'Invalid setup code'));
264
298
  if (error instanceof ManagementError)
@@ -379,7 +413,9 @@ export class HttpServer {
379
413
  return c.json({ ok: true });
380
414
  });
381
415
  panel.post('/logout', (c) => {
382
- this.auth.remove(c.req.header('cookie'));
416
+ const token = this.auth.remove(c.req.header('cookie'));
417
+ if (token)
418
+ this.connectionSetups.revoke(token);
383
419
  for (const [client, cookie] of this.clientSessions) {
384
420
  if (!this.auth.authenticated(cookie))
385
421
  client.close(1008, 'Session expired');
@@ -393,6 +429,50 @@ export class HttpServer {
393
429
  panel.get('/settings', async (c) => c.json(await this.settings.get()));
394
430
  panel.put('/settings', async (c) => c.json(await this.settings.update(await body(c, settingsInput))));
395
431
  panel.get('/overview', (c) => c.json(overview(this.app)));
432
+ const requireTask = (id) => {
433
+ const task = this.app.tasks.get(id);
434
+ if (!task)
435
+ throw new HttpError(404, 'NOT_FOUND', '任务不存在或历史已清理');
436
+ return task;
437
+ };
438
+ panel.get('/tasks', (c) => {
439
+ const input = z
440
+ .object({
441
+ plugin: z.string().max(200).optional(),
442
+ name: z.string().max(200).optional(),
443
+ state: z.enum(taskStates).optional(),
444
+ q: z.string().max(200).optional(),
445
+ offset: z.coerce.number().int().nonnegative().default(0),
446
+ limit: z.coerce.number().int().min(1).max(100).default(25),
447
+ })
448
+ .strict()
449
+ .safeParse(c.req.query());
450
+ if (!input.success)
451
+ throw new HttpError(400, 'BAD_REQUEST', '无效的任务筛选条件');
452
+ return c.json(redactValue(this.app.tasks.query(input.data), this.app.config));
453
+ });
454
+ panel.get('/tasks/:id', (c) => c.json(redactValue(requireTask(c.req.param('id')), this.app.config)));
455
+ panel.get('/tasks/:id/attempts', (c) => {
456
+ requireTask(c.req.param('id'));
457
+ return c.json(redactValue(this.app.tasks.attempts(c.req.param('id')), this.app.config));
458
+ });
459
+ panel.post('/tasks/:id/cancel', (c) => {
460
+ const id = requireTask(c.req.param('id')).id;
461
+ if (!this.app.tasks.cancel(id))
462
+ throw new HttpError(409, 'CONFLICT', '任务已结束或正在取消');
463
+ return c.json(redactValue(this.app.tasks.get(id), this.app.config));
464
+ });
465
+ panel.post('/tasks/:id/retry', (c) => {
466
+ const id = requireTask(c.req.param('id')).id;
467
+ try {
468
+ return c.json(redactValue(this.app.tasks.retry(id, { confirmDelivery: c.req.query('confirmDelivery') === '1' }), this.app.config));
469
+ }
470
+ catch (error) {
471
+ if (error instanceof TaskConflictError)
472
+ throw new HttpError(409, 'CONFLICT', error.message);
473
+ throw error;
474
+ }
475
+ });
396
476
  panel.get('/stats/messages', (c) => {
397
477
  const range = c.req.query('range') ?? '1h';
398
478
  if (range !== '1h' && range !== '24h')
@@ -409,13 +489,107 @@ export class HttpServer {
409
489
  };
410
490
  panel.all('/ext/:name', forwardPanelPlugin);
411
491
  panel.all('/ext/:name/*', forwardPanelPlugin);
412
- panel.get('/bots', (c) => c.json(this.app.bots.list().map((bot) => botView(this.app, bot))));
492
+ panel.get('/bots', (c) => c.json(panelBots(this.app)));
493
+ panel.get('/adapters', (c) => c.json(this.app.connections.catalog()));
494
+ const setupSession = (c) => {
495
+ const session = this.auth.session(c.req.header('cookie'));
496
+ if (!session)
497
+ throw new HttpError(401, 'UNAUTHORIZED', 'Authentication required');
498
+ c.header('Cache-Control', 'no-store');
499
+ return session;
500
+ };
501
+ panel.post('/connection-setups', async (c) => {
502
+ const input = await body(c, connectionSetupInput, 4096);
503
+ return c.json(this.connectionSetups.start(setupSession(c), input), 201);
504
+ });
505
+ panel.get('/connection-setups/:id', (c) => c.json(this.connectionSetups.status(setupSession(c).token, c.req.param('id'))));
506
+ panel.post('/connection-setups/:id/verify', async (c) => {
507
+ const { code } = await body(c, verificationInput, 4096);
508
+ return c.json(this.connectionSetups.verify(setupSession(c).token, c.req.param('id'), code));
509
+ });
510
+ panel.post('/connection-setups/:id/save', async (c) => {
511
+ const options = await body(c, connectionSetupSaveInput, 4096);
512
+ return c.json(await this.connectionSetups.save(setupSession(c).token, c.req.param('id'), options));
513
+ });
514
+ panel.delete('/connection-setups/:id', (c) => {
515
+ this.connectionSetups.cancel(setupSession(c).token, c.req.param('id'));
516
+ return c.body(null, 204);
517
+ });
518
+ panel.get('/connections', async (c) => c.json(await this.settings.connections()));
519
+ panel.post('/connections', async (c) => {
520
+ const input = await body(c, connectionSchema.extend({ id: connectionSchema.shape.id.default(randomUUID) }));
521
+ if (this.app.config.connections.some((item) => item.id === input.id))
522
+ throw new HttpError(409, 'CONFLICT', 'Connection ID already exists');
523
+ return c.json(await this.settings.saveConnection(input), 201);
524
+ });
525
+ panel.put('/connections/:id', async (c) => {
526
+ const id = c.req.param('id');
527
+ if (!this.app.config.connections.some((item) => item.id === id))
528
+ throw new HttpError(404, 'NOT_FOUND', 'Connection not found');
529
+ const input = await body(c, connectionSchema.omit({ id: true }));
530
+ return c.json(await this.settings.saveConnection({ ...input, id }));
531
+ });
532
+ panel.delete('/connections/:id', async (c) => c.json(await this.settings.removeConnection(c.req.param('id'))));
533
+ panel.post('/connections/:id/reconnect', async (c) => {
534
+ await this.app.plugins.serial(() => this.app.connections.reconnect(c.req.param('id')));
535
+ return c.json(await this.settings.connections());
536
+ });
537
+ const requireBot = (platform, selfId) => {
538
+ const bot = panelBot(this.app, { platform, selfId });
539
+ if (!bot)
540
+ throw new HttpError(404, 'NOT_FOUND', 'Bot not found');
541
+ return bot;
542
+ };
543
+ panel.get('/bots/:platform/:selfId', (c) => {
544
+ const bot = requireBot(c.req.param('platform'), c.req.param('selfId'));
545
+ return c.json({
546
+ bot,
547
+ admins: this.app.policies.admins(bot),
548
+ plugins: this.app.plugins.list().map((plugin) => botPluginView(this.app, bot, plugin.name)),
549
+ });
550
+ });
551
+ panel.put('/bots/:platform/:selfId/admins', async (c) => {
552
+ const bot = requireBot(c.req.param('platform'), c.req.param('selfId'));
553
+ const { admins } = await body(c, z.object({ admins: z.array(z.string().trim().min(1)).max(100) }).strict());
554
+ this.app.policies.setAdmins(bot, admins);
555
+ return c.json({ admins: this.app.policies.admins(bot) });
556
+ });
557
+ panel.put('/bots/:platform/:selfId/plugins/:name', async (c) => {
558
+ const bot = requireBot(c.req.param('platform'), c.req.param('selfId'));
559
+ const name = c.req.param('name');
560
+ this.requirePlugin(name);
561
+ const input = await body(c, z
562
+ .object({
563
+ enabled: z.boolean().nullable().optional(),
564
+ config: z.record(z.string(), z.unknown()).nullable().optional(),
565
+ })
566
+ .strict());
567
+ if (input.config !== undefined)
568
+ this.app.plugins.setBotConfig(name, bot, input.config);
569
+ if (input.enabled !== undefined)
570
+ this.app.plugins.setBotEnabled(name, bot, input.enabled);
571
+ return c.json(botPluginView(this.app, bot, name));
572
+ });
573
+ panel.get('/plugins/:name/bots', (c) => {
574
+ const name = c.req.param('name');
575
+ this.requirePlugin(name);
576
+ return c.json(panelBots(this.app).map((bot) => ({
577
+ bot,
578
+ application: botPluginView(this.app, bot, name),
579
+ })));
580
+ });
413
581
  panel.get('/groups', async (c) => c.json(await this.groups.list(c.req.query('refresh') === '1')));
414
582
  panel.get('/groups/:groupKey', async (c) => {
415
583
  const groupKey = c.req.param('groupKey');
416
- const group = (await this.groups.list()).find((item) => item.groupKey === groupKey);
417
- if (!group)
418
- throw new HttpError(404, 'NOT_FOUND', 'Group not found');
584
+ if (!/^[^:\s]+:[^:\s]+:group:[^\s]+$/.test(groupKey))
585
+ throw new HttpError(400, 'BAD_REQUEST', 'Invalid group key');
586
+ const identity = groupIdentity(groupKey);
587
+ const group = (await this.groups.list()).find((item) => item.groupKey === groupKey) ?? {
588
+ ...identity,
589
+ groupKey,
590
+ bots: [],
591
+ rules: { plugins: 0, configs: 0, commands: 0 },
592
+ };
419
593
  return c.json({
420
594
  group,
421
595
  plugins: this.app.plugins.list().map((plugin) => {
@@ -425,6 +599,19 @@ export class HttpServer {
425
599
  enabled: this.app.storage.isGroupEnabled(plugin.name, groupKey),
426
600
  configurable: plugin.configSchema !== undefined,
427
601
  ...(override === undefined ? {} : { override }),
602
+ ...(plugin.configSchema && this.app.plugins.getConfig(plugin.name) !== undefined
603
+ ? {
604
+ effectiveConfig: this.app.plugins.configFor(plugin.name, groupKey),
605
+ inheritedConfig: this.app.plugins.configFor(plugin.name, {
606
+ platform: identity.platform,
607
+ selfId: identity.selfId,
608
+ }),
609
+ configSources: this.app.plugins.configSources(plugin.name, {
610
+ ...identity,
611
+ groupId: group.groupId,
612
+ }),
613
+ }
614
+ : {}),
428
615
  };
429
616
  }),
430
617
  commands: this.app.dispatcher.registeredCommands().map((command) => ({
@@ -435,9 +622,10 @@ export class HttpServer {
435
622
  });
436
623
  });
437
624
  panel.get('/bots/:platform/:selfId/groups', async (c) => {
438
- const bot = this.app.getBot(c.req.param('platform'), c.req.param('selfId'));
439
- if (!bot)
440
- throw new HttpError(404, 'NOT_FOUND', 'Bot not found');
625
+ const { platform, selfId } = requireBot(c.req.param('platform'), c.req.param('selfId'));
626
+ const bot = this.app.getBot(platform, selfId);
627
+ if (bot?.status !== 'online')
628
+ throw new HttpError(409, 'NO_BOT_ONLINE', '机器人当前离线');
441
629
  const groups = await bot.getGroupList();
442
630
  return c.json(groups.map(({ groupId, groupName, memberCount }) => ({
443
631
  groupId,
@@ -518,6 +706,13 @@ export class HttpServer {
518
706
  throw new HttpError(409, 'CONFLICT', state.error ?? 'Plugin operation failed');
519
707
  return c.json(pluginView(this.app, state));
520
708
  });
709
+ panel.put('/plugins/:name/bot-default', async (c) => {
710
+ const name = c.req.param('name');
711
+ this.requirePlugin(name);
712
+ const { defaultOnNewBots } = await body(c, z.object({ defaultOnNewBots: z.boolean() }).strict());
713
+ await this.app.plugins.setDefaultOnNewBots(name, defaultOnNewBots);
714
+ return c.json(pluginView(this.app, this.requirePlugin(name)));
715
+ });
521
716
  panel.put('/plugins/:name/config', async (c) => {
522
717
  const name = c.req.param('name');
523
718
  this.requirePlugin(name);
@@ -546,8 +741,8 @@ export class HttpServer {
546
741
  .strict()
547
742
  .refine((value) => value.enabled !== undefined || value.config !== undefined, 'enabled or config is required'));
548
743
  const groupKey = c.req.param('groupKey');
549
- if (!/^[^:\s]+:[^\s]+$/.test(groupKey))
550
- throw new HttpError(400, 'BAD_REQUEST', 'Expected groupKey in platform:id format');
744
+ if (!/^[^:\s]+:[^:\s]+:group:[^\s]+$/.test(groupKey))
745
+ throw new HttpError(400, 'BAD_REQUEST', 'Expected groupKey in platform:selfId:group:id format');
551
746
  if (input.config !== undefined)
552
747
  this.app.plugins.setGroupConfig(name, groupKey, input.config);
553
748
  if (input.enabled !== undefined)
@@ -585,7 +780,7 @@ export class HttpServer {
585
780
  const input = await body(c, z
586
781
  .object({
587
782
  path: z.string().min(1),
588
- groupKey: z.string().regex(/^[^:\s]+:[^\s]+$/),
783
+ groupKey: z.string().regex(/^[^:\s]+:[^:\s]+:group:[^\s]+$/),
589
784
  enabled: z.boolean(),
590
785
  })
591
786
  .strict());
@@ -603,7 +798,7 @@ export class HttpServer {
603
798
  if (c.req.method === 'POST') {
604
799
  if (entry.list === 'block' &&
605
800
  entry.subject === 'user' &&
606
- this.app.isSuperuser(entry.key.slice(entry.key.indexOf(':') + 1)))
801
+ this.app.config.superusers.some((actor) => entry.key === `${actor.platform}:${actor.userId}`))
607
802
  throw new HttpError(409, 'CONFLICT', 'Cannot block a superuser');
608
803
  this.app.storage.access.add(entry.list, entry.subject, entry.key);
609
804
  }
@@ -646,7 +841,7 @@ export class HttpServer {
646
841
  throw new HttpError(401, 'UNAUTHORIZED', 'Invalid API token');
647
842
  await next();
648
843
  });
649
- api.get('/bots', (c) => c.json(this.app.bots.list().map((bot) => botView(this.app, bot))));
844
+ api.get('/bots', (c) => c.json(this.app.bots.list().map((bot) => panelBot(this.app, bot))));
650
845
  api.post('/send', async (c) => c.json(await this.send(await body(c, sendSchema))));
651
846
  routes.route('/api/v1', api);
652
847
  }
@@ -657,6 +852,9 @@ export class HttpServer {
657
852
  return plugin;
658
853
  }
659
854
  setSessionCookie(c) {
855
+ const token = this.auth.remove(c.req.header('cookie'));
856
+ if (token)
857
+ this.connectionSetups.revoke(token);
660
858
  setCookie(c, 'asabot_session', this.auth.create(), {
661
859
  httpOnly: true,
662
860
  sameSite: 'Strict',
@@ -667,15 +865,8 @@ export class HttpServer {
667
865
  packageOperation(operation) {
668
866
  return { ...operation, ...(operation.plugin ? { plugin: pluginView(this.app, operation.plugin) } : {}) };
669
867
  }
670
- async send(input) {
671
- try {
672
- return await this.app.send(input.target, input.message);
673
- }
674
- catch (error) {
675
- if (error instanceof NoBotOnlineError)
676
- throw new HttpError(409, 'CONFLICT', 'No matching online bot');
677
- throw error;
678
- }
868
+ send(input) {
869
+ return this.app.send(input.target, input.message);
679
870
  }
680
871
  connect(client, cookie) {
681
872
  this.clientSessions.set(client, cookie);
@@ -704,6 +895,9 @@ export class HttpServer {
704
895
  push(frame);
705
896
  });
706
897
  const unsubscribePanelEvents = this.app.subscribePanelEvents((event) => push({ type: 'plugin-event', ...event }));
898
+ const unsubscribePolicies = this.app.policies.subscribe(() => push({ type: 'policies' }));
899
+ const unsubscribeConnections = this.app.connections.subscribe(() => push({ type: 'connections' }));
900
+ const unsubscribeTasks = this.app.tasks.subscribe((id) => push({ type: 'task', id }));
707
901
  const ping = setInterval(() => {
708
902
  if (client.readyState !== WebSocket.OPEN)
709
903
  return;
@@ -735,6 +929,9 @@ export class HttpServer {
735
929
  unsubscribePackageUpdates();
736
930
  unsubscribeEvents();
737
931
  unsubscribePanelEvents();
932
+ unsubscribeTasks();
933
+ unsubscribeConnections();
934
+ unsubscribePolicies();
738
935
  });
739
936
  }
740
937
  eventFrame(event) {
@@ -742,15 +939,18 @@ export class HttpServer {
742
939
  return { type: 'plugin', plugin: pluginView(this.app, event.plugin) };
743
940
  if (event.kind === 'internal' &&
744
941
  (event.name === 'bot.online' || event.name === 'bot.offline') &&
745
- event.bot)
746
- return { type: 'bot', bot: botView(this.app, event.bot) };
942
+ event.bot) {
943
+ const bot = panelBot(this.app, event.bot);
944
+ if (bot)
945
+ return { type: 'bot', bot };
946
+ }
747
947
  if (event.kind === 'message')
748
948
  return {
749
949
  type: 'message',
750
950
  direction: 'in',
751
951
  platform: event.platform,
752
952
  selfId: event.selfId,
753
- channel: { type: event.messageType, id: event.groupId ?? event.userId },
953
+ channel: { type: event.messageType, id: event.groupId ?? event.userId, thread: event.thread },
754
954
  userId: event.userId,
755
955
  nickname: event.sender.nickname,
756
956
  avatar: supports(event.bot, 'getAvatarUrl') ? event.bot.getAvatarUrl?.(event.userId) : undefined,
@@ -764,7 +964,7 @@ export class HttpServer {
764
964
  direction: 'out',
765
965
  platform: sent.platform,
766
966
  selfId: sent.selfId,
767
- channel: { type: sent.messageType, id: sent.groupId ?? sent.userId },
967
+ channel: { type: sent.messageType, id: sent.groupId ?? sent.userId, thread: sent.thread },
768
968
  ...(sent.userId === undefined ? {} : { userId: sent.userId }),
769
969
  avatar: supports(sent.bot, 'getAvatarUrl') ? sent.bot.getAvatarUrl?.(sent.selfId) : undefined,
770
970
  preview: [...plainText(sent.message)].slice(0, 120).join(''),
@@ -1,13 +1,17 @@
1
1
  import { z } from 'zod';
2
2
  export declare const sendSchema: z.ZodObject<{
3
3
  target: z.ZodUnion<readonly [z.ZodObject<{
4
- platform: z.ZodString;
5
- selfId: z.ZodOptional<z.ZodString>;
6
4
  type: z.ZodEnum<{
7
5
  group: "group";
8
6
  private: "private";
9
7
  }>;
10
8
  id: z.ZodString;
9
+ thread: z.ZodOptional<z.ZodObject<{
10
+ id: z.ZodString;
11
+ rootMessageId: z.ZodString;
12
+ }, z.core.$strip>>;
13
+ platform: z.ZodString;
14
+ selfId: z.ZodOptional<z.ZodString>;
11
15
  }, z.core.$strip>, z.ZodPipe<z.ZodString, z.ZodTransform<import("../core/target.ts").Target, string>>]>;
12
16
  message: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodObject<{
13
17
  type: z.ZodString;
@@ -1,7 +1,12 @@
1
1
  import { z } from 'zod';
2
2
  import type { App } from '../core/app.ts';
3
+ import { type ConnectionConfig } from '../core/connections.ts';
3
4
  export declare const settingsInput: z.ZodObject<{
4
- superusers: z.ZodOptional<z.ZodArray<z.ZodString>>;
5
+ superusers: z.ZodOptional<z.ZodArray<z.ZodObject<{
6
+ platform: z.ZodString;
7
+ selfId: z.ZodString;
8
+ userId: z.ZodString;
9
+ }, z.core.$strict>>>;
5
10
  timezone: z.ZodOptional<z.ZodString>;
6
11
  command: z.ZodOptional<z.ZodObject<{
7
12
  prefixes: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -15,18 +20,34 @@ export declare const settingsInput: z.ZodObject<{
15
20
  off: "off";
16
21
  }>>;
17
22
  }, z.core.$strict>>;
18
- adapters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
19
23
  }, z.core.$strict>;
20
24
  export declare const setupInput: z.ZodObject<{
21
25
  code: z.ZodString;
22
26
  password: z.ZodString;
23
- superusers: z.ZodArray<z.ZodString>;
24
- adapters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
27
+ superusers: z.ZodArray<z.ZodObject<{
28
+ platform: z.ZodString;
29
+ selfId: z.ZodString;
30
+ userId: z.ZodString;
31
+ }, z.core.$strict>>;
25
32
  }, z.core.$strict>;
26
33
  type SettingsInput = z.output<typeof settingsInput>;
27
34
  type SetupInput = z.output<typeof setupInput>;
28
35
  export declare class SetupCodeError extends Error {
29
36
  }
37
+ export declare class ConnectionSetupError extends Error {
38
+ readonly status: 400 | 404 | 409 | 429;
39
+ constructor(status: ConnectionSetupError['status'], message: string);
40
+ }
41
+ export declare const connectionSetupSaveInput: z.ZodObject<{
42
+ name: z.ZodOptional<z.ZodString>;
43
+ enabled: z.ZodOptional<z.ZodBoolean>;
44
+ replace: z.ZodOptional<z.ZodBoolean>;
45
+ }, z.core.$strict>;
46
+ export type ConnectionSetupSaveInput = z.output<typeof connectionSetupSaveInput>;
47
+ export interface SetupAccount {
48
+ selfId: string;
49
+ config: unknown;
50
+ }
30
51
  export declare class SettingsValidationError extends Error {
31
52
  readonly issues: {
32
53
  path: string;
@@ -43,7 +64,11 @@ export declare class SettingsService {
43
64
  constructor(app: App);
44
65
  private raw;
45
66
  get(): Promise<{
46
- superusers: string[];
67
+ superusers: {
68
+ platform: string;
69
+ selfId: string;
70
+ userId: string;
71
+ }[];
47
72
  timezone: string;
48
73
  command: {
49
74
  prefixes: string[];
@@ -53,17 +78,14 @@ export declare class SettingsService {
53
78
  replyOnDenied: boolean;
54
79
  suggest: "always" | "direct" | "off";
55
80
  };
56
- adapters: {
57
- [k: string]: {
58
- value: unknown;
59
- schema: z.core.ZodStandardJSONSchemaPayload<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
60
- };
61
- };
62
- available: string[];
63
81
  restartRequired: string[];
64
82
  }>;
65
83
  update(input: SettingsInput): Promise<{
66
- superusers: string[];
84
+ superusers: {
85
+ platform: string;
86
+ selfId: string;
87
+ userId: string;
88
+ }[];
67
89
  timezone: string;
68
90
  command: {
69
91
  prefixes: string[];
@@ -73,16 +95,40 @@ export declare class SettingsService {
73
95
  replyOnDenied: boolean;
74
96
  suggest: "always" | "direct" | "off";
75
97
  };
76
- adapters: {
77
- [k: string]: {
78
- value: unknown;
79
- schema: z.core.ZodStandardJSONSchemaPayload<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
80
- };
81
- };
82
- available: string[];
83
98
  restartRequired: string[];
84
99
  }>;
85
100
  setup(input: SetupInput): Promise<void>;
101
+ connections(): Promise<{
102
+ id: string;
103
+ name: string;
104
+ adapter: string;
105
+ platform: string;
106
+ enabled: boolean;
107
+ state: 'disabled' | 'connecting' | 'waiting' | 'online' | 'retrying' | 'error' | 'offline' | 'reauthorize';
108
+ changedAt: number;
109
+ lastConnectedAt?: number;
110
+ lastError?: string;
111
+ errorAt?: number;
112
+ nextRetryAt?: number;
113
+ endpoints: string[];
114
+ bots: {
115
+ platform: string;
116
+ selfId: string;
117
+ }[];
118
+ config: unknown;
119
+ }[]>;
120
+ saveConnection(input: ConnectionConfig): Promise<unknown>;
121
+ saveConnectionSetup(input: {
122
+ id: string;
123
+ adapter: string;
124
+ previousAccount?: SetupAccount;
125
+ account: SetupAccount & {
126
+ adminUserId?: string;
127
+ };
128
+ options: ConnectionSetupSaveInput;
129
+ signal: AbortSignal;
130
+ }): Promise<void>;
131
+ removeConnection(id: string): Promise<unknown>;
86
132
  private persist;
87
133
  }
88
134
  export {};