@asabot/core 0.1.0 → 0.2.1

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 (170) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +93 -14
  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 +9 -2
  106. package/dist/core/message/segment.js +3 -13
  107. package/dist/core/message/types.d.ts +2 -0
  108. package/dist/core/permission.d.ts +2 -1
  109. package/dist/core/permission.js +7 -2
  110. package/dist/core/plugin/context.d.ts +17 -11
  111. package/dist/core/plugin/context.js +48 -21
  112. package/dist/core/plugin/definition.d.ts +7 -0
  113. package/dist/core/plugin/execution.d.ts +3 -0
  114. package/dist/core/plugin/execution.js +3 -0
  115. package/dist/core/plugin/icon.d.ts +2 -0
  116. package/dist/core/plugin/icon.js +14 -0
  117. package/dist/core/plugin/manager.d.ts +26 -7
  118. package/dist/core/plugin/manager.js +179 -56
  119. package/dist/core/plugin/packages.d.ts +4 -0
  120. package/dist/core/plugin/packages.js +39 -9
  121. package/dist/core/plugin/tasks.d.ts +131 -24
  122. package/dist/core/plugin/tasks.js +517 -117
  123. package/dist/core/plugin/types.d.ts +14 -0
  124. package/dist/core/ratelimit.js +6 -1
  125. package/dist/core/storage/index.d.ts +3 -1
  126. package/dist/core/storage/index.js +52 -2
  127. package/dist/core/target.d.ts +24 -6
  128. package/dist/core/target.js +26 -6
  129. package/dist/core/utils/merge.d.ts +3 -0
  130. package/dist/core/utils/merge.js +18 -0
  131. package/dist/core/utils/redact.d.ts +6 -0
  132. package/dist/core/utils/redact.js +76 -0
  133. package/dist/index.d.ts +14 -6
  134. package/dist/index.js +7 -2
  135. package/dist/plugins/admin.js +30 -3
  136. package/dist/plugins/help.js +1 -0
  137. package/dist/plugins/history.d.ts +4 -0
  138. package/dist/plugins/history.js +13 -3
  139. package/dist/plugins/http.js +1 -0
  140. package/dist/plugins/long-message.js +20 -12
  141. package/dist/plugins/status.js +1 -0
  142. package/dist/server/auth.d.ts +5 -1
  143. package/dist/server/auth.js +11 -7
  144. package/dist/server/connection-setups.d.ts +126 -0
  145. package/dist/server/connection-setups.js +188 -0
  146. package/dist/server/groups.d.ts +1 -0
  147. package/dist/server/groups.js +8 -8
  148. package/dist/server/index.d.ts +1 -0
  149. package/dist/server/index.js +230 -29
  150. package/dist/server/schemas.d.ts +6 -2
  151. package/dist/server/settings.d.ts +66 -20
  152. package/dist/server/settings.js +158 -61
  153. package/dist/server/views.d.ts +97 -17
  154. package/dist/server/views.js +48 -13
  155. package/dist/testing/create-test-app.js +2 -2
  156. package/dist/testing/dispatch-fixture.js +2 -1
  157. package/dist/testing/fake-bot.d.ts +2 -1
  158. package/dist/testing/fake-bot.js +4 -1
  159. package/docs/DEPLOY.md +211 -0
  160. package/docs/FEISHU.md +170 -0
  161. package/docs/WECOM.md +107 -0
  162. package/docs/WEIXIN-CLAWBOT.md +56 -0
  163. package/package.json +29 -3
  164. package/web/dist/assets/index-ogXTSYEt.css +2 -0
  165. package/web/dist/assets/index-r9XycpMd.js +51 -0
  166. package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-CIohfKSa.js} +3 -3
  167. package/web/dist/index.html +2 -2
  168. package/web/dist/plugin-pages/_sdk.js +26 -1
  169. package/web/dist/assets/index-BI5GCpiI.css +0 -2
  170. package/web/dist/assets/index-C-rshHwD.js +0 -51
@@ -1,7 +1,8 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { z } from 'zod';
3
- import { supports } from '../core/bot.js';
3
+ import { sendTo, supports } from '../core/bot.js';
4
4
  import { durationSchema } from '../core/config/schema.js';
5
+ import { DeliveryAttempt } from '../core/delivery.js';
5
6
  import { isSegment, seg } from '../core/message/index.js';
6
7
  import { definePlugin } from '../core/plugin/definition.js';
7
8
  function textOf(segment) {
@@ -80,6 +81,7 @@ function renderText(message) {
80
81
  export default definePlugin({
81
82
  name: 'long-message',
82
83
  description: '将长消息转发、渲染或分段发送',
84
+ defaultOnNewBots: true,
83
85
  inject: { optional: ['render'] },
84
86
  config: z.object({
85
87
  threshold: z.number().int().positive().default(1000),
@@ -91,11 +93,12 @@ export default definePlugin({
91
93
  setup(ctx) {
92
94
  const render = ctx.injectOptional('render');
93
95
  const signal = ctx.signal;
94
- ctx.beforeSend(async ({ bot, target, message }) => {
96
+ ctx.beforeSend(async ({ bot, target, message, sendFirst, sendPart }) => {
95
97
  if (message.some((segment) => !['text', 'at', 'face', 'reply', 'markdown'].includes(segment.type)))
96
98
  return;
97
99
  const config = ctx.configFor({
98
100
  platform: bot.platform,
101
+ selfId: bot.selfId,
99
102
  ...(target.type === 'group' ? { groupId: target.id } : {}),
100
103
  });
101
104
  const imageMarkdown = async (parts) => {
@@ -113,7 +116,7 @@ export default definePlugin({
113
116
  return [...message.filter((segment) => isSegment(segment, 'reply')), seg.image(image)];
114
117
  }
115
118
  const chunks = splitMessage(message, config.chunkSize);
116
- if (config.strategy !== 'split' && supports(bot, 'sendForward')) {
119
+ if (!sendFirst && !sendPart && config.strategy !== 'split' && supports(bot, 'sendForward')) {
117
120
  const nodes = await Promise.all(chunks.map(async (chunk) => ({
118
121
  userId: bot.selfId,
119
122
  nickname: bot.nickname ?? bot.selfId,
@@ -122,21 +125,26 @@ export default definePlugin({
122
125
  return { deliver: () => bot.sendForward(target, nodes) };
123
126
  }
124
127
  // Split sending can take far longer than the hook timeout, so it runs as a delivery after the hook chain.
128
+ const attempt = new DeliveryAttempt(bot, target);
125
129
  return {
126
- deliver: async () => {
127
- let sent = await (target.type === 'group'
128
- ? bot.sendGroup(target.id, await imageMarkdown(chunks[0]))
129
- : bot.sendPrivate(target.id, await imageMarkdown(chunks[0])));
130
+ deliver: () => attempt.run(async () => {
131
+ const first = await imageMarkdown(chunks[0]);
132
+ let sent = attempt.confirm(await (sendFirst
133
+ ? sendFirst(first)
134
+ : sendPart
135
+ ? sendPart(first)
136
+ : sendTo(bot, target, first)));
137
+ let destination = { ...target, thread: target.thread ?? sent.thread };
130
138
  for (const chunk of chunks.slice(1)) {
131
139
  if (config.splitInterval)
132
140
  await delay(config.splitInterval, undefined, { signal });
133
- const content = await imageMarkdown(chunk);
134
- sent = await (target.type === 'group'
135
- ? bot.sendGroup(target.id, content)
136
- : bot.sendPrivate(target.id, content));
141
+ const part = await imageMarkdown(chunk);
142
+ sent = attempt.confirm(await (sendPart ? sendPart(part) : sendTo(bot, destination, part)));
143
+ if (!destination.thread && sent.thread)
144
+ destination = { ...destination, thread: sent.thread };
137
145
  }
138
146
  return sent;
139
- },
147
+ }),
140
148
  };
141
149
  }, { priority: -100 });
142
150
  },
@@ -10,6 +10,7 @@ export function createStatusPlugin(app) {
10
10
  return definePlugin({
11
11
  name: 'status',
12
12
  description: '查看运行状态',
13
+ defaultOnNewBots: true,
13
14
  setup(ctx) {
14
15
  ctx
15
16
  .command('ping')
@@ -4,6 +4,10 @@ export declare class PanelAuth {
4
4
  attempt(ip: string): boolean;
5
5
  create(): string;
6
6
  authenticated(cookie: string | undefined): boolean;
7
- remove(cookie: string | undefined): void;
7
+ session(cookie: string | undefined): {
8
+ token: string;
9
+ expiresAt: number;
10
+ } | undefined;
11
+ remove(cookie: string | undefined): string | undefined;
8
12
  private token;
9
13
  }
@@ -27,22 +27,26 @@ export class PanelAuth {
27
27
  return token;
28
28
  }
29
29
  authenticated(cookie) {
30
+ return this.session(cookie) !== undefined;
31
+ }
32
+ session(cookie) {
30
33
  const token = this.token(cookie);
31
34
  if (!token)
32
- return false;
33
- const expires = this.sessions.get(token);
34
- if (expires === undefined)
35
- return false;
36
- if (expires <= Date.now()) {
35
+ return undefined;
36
+ const expiresAt = this.sessions.get(token);
37
+ if (expiresAt === undefined)
38
+ return undefined;
39
+ if (expiresAt <= Date.now()) {
37
40
  this.sessions.delete(token);
38
- return false;
41
+ return undefined;
39
42
  }
40
- return true;
43
+ return { token, expiresAt };
41
44
  }
42
45
  remove(cookie) {
43
46
  const token = this.token(cookie);
44
47
  if (token)
45
48
  this.sessions.delete(token);
49
+ return token;
46
50
  }
47
51
  token(cookie) {
48
52
  return cookie
@@ -0,0 +1,126 @@
1
+ import { z } from 'zod';
2
+ import type { App } from '../core/app.ts';
3
+ import { type ConnectionSetupSaveInput, type SettingsService } from './settings.ts';
4
+ export declare const connectionSetupInput: z.ZodObject<{
5
+ adapter: z.ZodString;
6
+ connectionId: z.ZodOptional<z.ZodString>;
7
+ }, z.core.$strict>;
8
+ export declare const verificationInput: z.ZodObject<{
9
+ code: z.ZodString;
10
+ }, z.core.$strict>;
11
+ export declare class ConnectionSetups {
12
+ private readonly app;
13
+ private readonly settings;
14
+ private readonly drafts;
15
+ constructor(app: App, settings: SettingsService);
16
+ start(owner: {
17
+ token: string;
18
+ expiresAt: number;
19
+ }, input: z.output<typeof connectionSetupInput>): {
20
+ status: 'starting' | 'scanned' | 'expired' | 'already-bound';
21
+ id: string;
22
+ expiresAt: number;
23
+ } | {
24
+ status: 'failed';
25
+ detail?: string;
26
+ id: string;
27
+ expiresAt: number;
28
+ } | {
29
+ status: 'waiting';
30
+ image: string;
31
+ id: string;
32
+ expiresAt: number;
33
+ } | {
34
+ status: 'verification';
35
+ retry: boolean;
36
+ id: string;
37
+ expiresAt: number;
38
+ } | {
39
+ status: 'authorized';
40
+ selfId: string;
41
+ replaces?: string;
42
+ missingAdmin: boolean;
43
+ id: string;
44
+ expiresAt: number;
45
+ } | {
46
+ status: 'saved';
47
+ connectionId: string;
48
+ id: string;
49
+ expiresAt: number;
50
+ };
51
+ status(owner: string, id: string): {
52
+ status: 'starting' | 'scanned' | 'expired' | 'already-bound';
53
+ id: string;
54
+ expiresAt: number;
55
+ } | {
56
+ status: 'failed';
57
+ detail?: string;
58
+ id: string;
59
+ expiresAt: number;
60
+ } | {
61
+ status: 'waiting';
62
+ image: string;
63
+ id: string;
64
+ expiresAt: number;
65
+ } | {
66
+ status: 'verification';
67
+ retry: boolean;
68
+ id: string;
69
+ expiresAt: number;
70
+ } | {
71
+ status: 'authorized';
72
+ selfId: string;
73
+ replaces?: string;
74
+ missingAdmin: boolean;
75
+ id: string;
76
+ expiresAt: number;
77
+ } | {
78
+ status: 'saved';
79
+ connectionId: string;
80
+ id: string;
81
+ expiresAt: number;
82
+ };
83
+ verify(owner: string, id: string, code: string): {
84
+ status: 'starting' | 'scanned' | 'expired' | 'already-bound';
85
+ id: string;
86
+ expiresAt: number;
87
+ } | {
88
+ status: 'failed';
89
+ detail?: string;
90
+ id: string;
91
+ expiresAt: number;
92
+ } | {
93
+ status: 'waiting';
94
+ image: string;
95
+ id: string;
96
+ expiresAt: number;
97
+ } | {
98
+ status: 'verification';
99
+ retry: boolean;
100
+ id: string;
101
+ expiresAt: number;
102
+ } | {
103
+ status: 'authorized';
104
+ selfId: string;
105
+ replaces?: string;
106
+ missingAdmin: boolean;
107
+ id: string;
108
+ expiresAt: number;
109
+ } | {
110
+ status: 'saved';
111
+ connectionId: string;
112
+ id: string;
113
+ expiresAt: number;
114
+ };
115
+ save(owner: string, id: string, options: ConnectionSetupSaveInput): Promise<{
116
+ connectionId: string;
117
+ }>;
118
+ cancel(owner: string, id: string): void;
119
+ revoke(owner?: string): void;
120
+ private activeCount;
121
+ private require;
122
+ private view;
123
+ private drop;
124
+ private finish;
125
+ private poll;
126
+ }
@@ -0,0 +1,188 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
3
+ import QRCode from 'qrcode';
4
+ import { z } from 'zod';
5
+ import { connectionSchema } from '../core/connections.js';
6
+ import { QrSetupError } from '../core/errors.js';
7
+ import { actorIdentitySchema, botIdentitySchema } from '../core/identity.js';
8
+ import { ConnectionSetupError, } from './settings.js';
9
+ export const connectionSetupInput = z.strictObject({
10
+ adapter: connectionSchema.shape.adapter,
11
+ connectionId: connectionSchema.shape.id.optional(),
12
+ });
13
+ export const verificationInput = z.strictObject({ code: z.string().trim().min(1).max(64) });
14
+ const lifetime = 5 * 60_000;
15
+ export class ConnectionSetups {
16
+ app;
17
+ settings;
18
+ drafts = new Map();
19
+ constructor(app, settings) {
20
+ this.app = app;
21
+ this.settings = settings;
22
+ }
23
+ start(owner, input) {
24
+ const { adapter, connectionId } = input;
25
+ const definition = this.app.connections.definition(adapter);
26
+ const { setup, accountId } = definition;
27
+ if (!setup)
28
+ throw new ConnectionSetupError(400, '此适配器不支持扫码接入');
29
+ const existing = connectionId && this.app.config.connections.find((record) => record.id === connectionId);
30
+ if (connectionId && (!existing || existing.adapter !== adapter))
31
+ throw new ConnectionSetupError(404, '找不到对应的连接');
32
+ if (this.drafts.size >= 64 || this.activeCount(owner.token) >= 4)
33
+ throw new ConnectionSetupError(429, '进行中的扫码过多,请取消其他扫码后重试');
34
+ const config = existing ? definition.configSchema.parse(existing.config) : undefined;
35
+ const id = randomUUID();
36
+ const expiresAt = Math.min(Date.now() + lifetime, owner.expiresAt);
37
+ const draft = {
38
+ id,
39
+ owner: owner.token,
40
+ adapter,
41
+ connectionId: connectionId ?? randomUUID(),
42
+ ...(existing && { previousAccount: { selfId: accountId(config), config } }),
43
+ expiresAt,
44
+ controller: new AbortController(),
45
+ timer: setTimeout(() => this.drop(id), Math.max(0, expiresAt - Date.now())).unref(),
46
+ state: { status: 'starting' },
47
+ };
48
+ this.drafts.set(id, draft);
49
+ void this.poll(draft, setup, accountId);
50
+ return this.view(draft);
51
+ }
52
+ status(owner, id) {
53
+ return this.view(this.require(owner, id));
54
+ }
55
+ verify(owner, id, code) {
56
+ const draft = this.require(owner, id);
57
+ if (draft.state.status !== 'verification')
58
+ throw new ConnectionSetupError(409, '当前不需要验证码');
59
+ draft.state = { status: 'scanned' };
60
+ const { setup, accountId } = this.app.connections.definition(draft.adapter);
61
+ if (!setup)
62
+ throw new Error('Missing QR provider');
63
+ void this.poll(draft, setup, accountId, code);
64
+ return this.view(draft);
65
+ }
66
+ save(owner, id, options) {
67
+ const draft = this.require(owner, id);
68
+ if (draft.state.status === 'saved')
69
+ return Promise.resolve({ connectionId: draft.connectionId });
70
+ if (draft.saving)
71
+ return draft.saving;
72
+ if (!draft.account)
73
+ throw new ConnectionSetupError(409, '请先完成扫码授权');
74
+ draft.saving = this.settings
75
+ .saveConnectionSetup({
76
+ id: draft.connectionId,
77
+ adapter: draft.adapter,
78
+ previousAccount: draft.previousAccount,
79
+ account: draft.account,
80
+ options,
81
+ signal: draft.controller.signal,
82
+ })
83
+ .then(() => {
84
+ this.finish(draft, { status: 'saved', connectionId: draft.connectionId });
85
+ return { connectionId: draft.connectionId };
86
+ })
87
+ .finally(() => {
88
+ draft.saving = undefined;
89
+ });
90
+ return draft.saving;
91
+ }
92
+ cancel(owner, id) {
93
+ const draft = this.require(owner, id);
94
+ if (draft.state.status === 'saved')
95
+ return;
96
+ if (draft.saving)
97
+ throw new ConnectionSetupError(409, '正在保存连接');
98
+ this.drop(id);
99
+ }
100
+ revoke(owner) {
101
+ for (const draft of this.drafts.values())
102
+ if (!owner || draft.owner === owner)
103
+ this.drop(draft.id);
104
+ }
105
+ activeCount(owner) {
106
+ return [...this.drafts.values()].filter((draft) => draft.owner === owner &&
107
+ ['starting', 'waiting', 'scanned', 'verification', 'authorized'].includes(draft.state.status)).length;
108
+ }
109
+ require(owner, id) {
110
+ const draft = this.drafts.get(id);
111
+ if (!draft || draft.owner !== owner || draft.expiresAt <= Date.now())
112
+ throw new ConnectionSetupError(404, '扫码已结束,请重新扫码');
113
+ return draft;
114
+ }
115
+ view(draft) {
116
+ return { id: draft.id, expiresAt: draft.expiresAt, ...draft.state };
117
+ }
118
+ drop(id) {
119
+ const draft = this.drafts.get(id);
120
+ if (!draft)
121
+ return;
122
+ clearTimeout(draft.timer);
123
+ this.finish(draft, { status: 'expired' });
124
+ this.drafts.delete(id);
125
+ }
126
+ finish(draft, state) {
127
+ draft.state = state;
128
+ draft.challenge = undefined;
129
+ draft.account = undefined;
130
+ draft.previousAccount = undefined;
131
+ draft.controller.abort();
132
+ }
133
+ async poll(draft, setup, accountId, code) {
134
+ const signal = draft.controller.signal;
135
+ try {
136
+ if (!draft.challenge) {
137
+ const challenge = await setup.start(signal);
138
+ signal.throwIfAborted();
139
+ const image = await QRCode.toDataURL(challenge.content, { margin: 4, scale: 6 });
140
+ signal.throwIfAborted();
141
+ draft.challenge = challenge;
142
+ draft.state = { status: 'waiting', image };
143
+ }
144
+ const challenge = draft.challenge;
145
+ while (!signal.aborted) {
146
+ const update = await challenge.poll(code);
147
+ signal.throwIfAborted();
148
+ switch (update.status) {
149
+ case 'verification':
150
+ draft.state = { status: 'verification', retry: update.retry };
151
+ return;
152
+ case 'authorized': {
153
+ const definition = this.app.connections.definition(draft.adapter);
154
+ const config = definition.configSchema.parse(update.config);
155
+ const selfId = botIdentitySchema.shape.selfId.parse(accountId(config));
156
+ const adminUserId = actorIdentitySchema.shape.userId.optional().parse(update.adminUserId);
157
+ const previous = draft.previousAccount?.selfId;
158
+ draft.challenge = undefined;
159
+ draft.account = { selfId, config: update.config, adminUserId };
160
+ draft.state = {
161
+ status: 'authorized',
162
+ selfId,
163
+ ...(previous && previous !== selfId && { replaces: previous }),
164
+ missingAdmin: previous !== selfId && !adminUserId,
165
+ };
166
+ return;
167
+ }
168
+ case 'expired':
169
+ case 'already-bound':
170
+ this.finish(draft, { status: update.status });
171
+ return;
172
+ case 'scanned':
173
+ draft.state = { status: 'scanned' };
174
+ break;
175
+ }
176
+ code = undefined;
177
+ await sleep(750, undefined, { signal, ref: false });
178
+ }
179
+ }
180
+ catch (error) {
181
+ if (signal.aborted)
182
+ return;
183
+ const detail = error instanceof QrSetupError ? error.message : undefined;
184
+ this.app.logger.warn({ adapter: draft.adapter, stage: draft.state.status, detail }, 'Connection setup failed');
185
+ this.finish(draft, { status: 'failed', detail });
186
+ }
187
+ }
188
+ }
@@ -3,6 +3,7 @@ export interface GroupView {
3
3
  groupKey: string;
4
4
  platform: string;
5
5
  groupId: string;
6
+ selfId: string;
6
7
  name?: string;
7
8
  bots: string[];
8
9
  rules: {
@@ -1,3 +1,5 @@
1
+ import { groupKeyOf } from '../core/dispatch/types.js';
2
+ import { groupIdentity } from '../core/identity.js';
1
3
  export class Groups {
2
4
  app;
3
5
  cache = new WeakMap();
@@ -24,9 +26,10 @@ export class Groups {
24
26
  const sources = new Map();
25
27
  for (const { bot, groups } of fetched) {
26
28
  for (const item of groups) {
27
- const groupKey = `${bot.platform}:${item.groupId}`;
29
+ const groupKey = groupKeyOf({ ...bot, groupId: item.groupId });
28
30
  const current = sources.get(groupKey) ?? {
29
31
  platform: bot.platform,
32
+ selfId: bot.selfId,
30
33
  groupId: item.groupId,
31
34
  ...(item.groupName === '' ? {} : { name: item.groupName }),
32
35
  bots: new Set(),
@@ -39,23 +42,20 @@ export class Groups {
39
42
  }
40
43
  const summaries = this.app.storage.groupRuleSummaries();
41
44
  for (const rule of summaries) {
42
- const separator = rule.groupKey.indexOf(':');
43
- if (separator <= 0 || separator === rule.groupKey.length - 1)
44
- continue;
45
- const platform = rule.groupKey.slice(0, separator);
46
- const groupId = rule.groupKey.slice(separator + 1);
45
+ const { platform, selfId, groupId } = groupIdentity(rule.groupKey);
47
46
  if (!sources.has(rule.groupKey))
48
- sources.set(rule.groupKey, { platform, groupId, bots: new Set() });
47
+ sources.set(rule.groupKey, { platform, selfId, groupId, bots: new Set() });
49
48
  }
50
49
  const rules = new Map(summaries.map((item) => [item.groupKey, item]));
51
50
  return [...sources.entries()]
52
51
  .sort(([a], [b]) => a.localeCompare(b))
53
52
  .map(([groupKey, source]) => {
54
53
  const summary = rules.get(groupKey) ?? { plugins: 0, configs: 0, commands: 0 };
55
- const access = this.app.storage.groupAccess(groupKey);
54
+ const access = this.app.storage.groupAccess(`${source.platform}:${source.groupId}`);
56
55
  return {
57
56
  groupKey,
58
57
  platform: source.platform,
58
+ selfId: source.selfId,
59
59
  groupId: source.groupId,
60
60
  ...(source.name === undefined ? {} : { name: source.name }),
61
61
  bots: [...source.bots].sort(),
@@ -5,6 +5,7 @@ export declare class HttpServer implements ServerService {
5
5
  private readonly auth;
6
6
  private readonly playground;
7
7
  private readonly settings;
8
+ private readonly connectionSetups;
8
9
  private readonly groups;
9
10
  private readonly http;
10
11
  private readonly websocket;