@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
@@ -0,0 +1,196 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
2
+ import { seg } from '../../core/message/index.js';
3
+ import { base64Media, download, localMedia, mediaName, remoteMedia } from '../media-source.js';
4
+ import { uploadSchema } from './protocol.js';
5
+ const cdnBase = 'https://novac2c.cdn.weixin.qq.com/c2c';
6
+ const maxMedia = 25 * 1024 * 1024;
7
+ const mediaTimeout = 30_000;
8
+ const maxReferences = 1024;
9
+ const mediaPrefix = 'weixin-media:';
10
+ const uploadTypes = { image: 1, video: 2, file: 3 };
11
+ function cdnUrl(value) {
12
+ const url = new URL(value);
13
+ if (url.protocol !== 'https:' ||
14
+ url.username ||
15
+ url.password ||
16
+ url.port ||
17
+ url.hash ||
18
+ !url.hostname.endsWith('.cdn.weixin.qq.com'))
19
+ throw new Error('微信返回了不受信任的媒体地址');
20
+ return url;
21
+ }
22
+ function resolveCdnUrl(action, full, param, key) {
23
+ if (full)
24
+ return cdnUrl(full);
25
+ if (!param)
26
+ throw new Error('微信未返回媒体传输地址');
27
+ const url = new URL(`${cdnBase}/${action}`);
28
+ url.searchParams.set('encrypted_query_param', param);
29
+ if (key)
30
+ url.searchParams.set('filekey', key);
31
+ return url;
32
+ }
33
+ function decodeKey(imageKey, mediaKey) {
34
+ const hex = /^[a-f0-9]{32}$/i;
35
+ if (imageKey) {
36
+ if (!hex.test(imageKey))
37
+ throw new Error('图片加密密钥格式不正确');
38
+ return Buffer.from(imageKey, 'hex');
39
+ }
40
+ if (!mediaKey)
41
+ return undefined;
42
+ const key = Buffer.from(mediaKey, 'base64');
43
+ if (key.toString('base64').replace(/=+$/, '') !== mediaKey.replace(/=+$/, ''))
44
+ throw new Error('媒体加密密钥格式不正确');
45
+ if (key.length === 16)
46
+ return key;
47
+ if (key.length === 32 && hex.test(key.toString('latin1')))
48
+ return Buffer.from(key.toString('latin1'), 'hex');
49
+ throw new Error('媒体加密密钥长度不正确');
50
+ }
51
+ async function toWav(bytes) {
52
+ const { decode, getDuration, isSilk } = await import('silk-wasm');
53
+ if (bytes.length > 1024 * 1024 || !isSilk(bytes) || getDuration(bytes) > 5 * 60_000)
54
+ throw new Error('不是可转换的 SILK 语音');
55
+ const rate = 24_000;
56
+ const { data } = await decode(bytes, rate);
57
+ if (!data.length || data.length > maxMedia - 44)
58
+ throw new Error('语音解码结果超出范围');
59
+ const wav = Buffer.alloc(44 + data.length);
60
+ wav.write('RIFF');
61
+ wav.writeUInt32LE(wav.length - 8, 4);
62
+ wav.write('WAVEfmt ', 8);
63
+ wav.writeUInt32LE(16, 16);
64
+ wav.writeUInt16LE(1, 20);
65
+ wav.writeUInt16LE(1, 22);
66
+ wav.writeUInt32LE(rate, 24);
67
+ wav.writeUInt32LE(rate * 2, 28);
68
+ wav.writeUInt16LE(2, 32);
69
+ wav.writeUInt16LE(16, 34);
70
+ wav.write('data', 36);
71
+ wav.writeUInt32LE(data.length, 40);
72
+ wav.set(data, 44);
73
+ return wav;
74
+ }
75
+ export class WeixinMedia {
76
+ #references = new Map();
77
+ #shutdown;
78
+ constructor(shutdown) {
79
+ this.#shutdown = shutdown;
80
+ }
81
+ remember(kind, ref, name, imageKey) {
82
+ if (!ref.full_url && !ref.encrypt_query_param)
83
+ return undefined;
84
+ const handle = `${mediaPrefix}${randomUUID()}`;
85
+ this.#references.set(handle, { kind, ref, imageKey });
86
+ const first = this.#references.keys().next();
87
+ if (this.#references.size > maxReferences && !first.done)
88
+ this.#references.delete(first.value);
89
+ return kind === 'file' ? seg.file(handle, { name }) : seg[kind](handle);
90
+ }
91
+ async download(handle, format, signal = this.#signal()) {
92
+ const entry = this.#references.get(handle);
93
+ if (!entry)
94
+ throw new Error('微信媒体已过期或不属于此机器人');
95
+ if (format === 'wav' && entry.kind !== 'audio')
96
+ throw new Error('只有 SILK 语音可转换为 WAV');
97
+ try {
98
+ const url = resolveCdnUrl('download', entry.ref.full_url, entry.ref.encrypt_query_param);
99
+ const key = decodeKey(entry.imageKey, entry.ref.aes_key);
100
+ if (!key && entry.kind !== 'image')
101
+ throw new Error('微信未提供媒体加密密钥');
102
+ let bytes = await download(url, signal, maxMedia + (key ? 16 : 0));
103
+ if (key) {
104
+ const cipher = createDecipheriv('aes-128-ecb', key, null);
105
+ bytes = Buffer.concat([cipher.update(bytes), cipher.final()]);
106
+ }
107
+ if (bytes.length > maxMedia)
108
+ throw new Error('媒体超过大小限制');
109
+ const result = format === 'wav' ? await toWav(bytes) : bytes;
110
+ signal.throwIfAborted();
111
+ return result;
112
+ }
113
+ catch {
114
+ throw new Error(signal.aborted ? '微信媒体下载已取消或超时' : '微信媒体下载、解密或转码失败');
115
+ }
116
+ }
117
+ async upload(userId, segment, request) {
118
+ const signal = this.#signal();
119
+ const source = segment.data.file;
120
+ let bytes;
121
+ let sourceName;
122
+ try {
123
+ signal.throwIfAborted();
124
+ if (source.startsWith(mediaPrefix))
125
+ bytes = await this.download(source, 'original', signal);
126
+ else if (source.startsWith('base64://'))
127
+ bytes = base64Media(source.slice(9), maxMedia);
128
+ else {
129
+ const url = new URL(source);
130
+ sourceName = mediaName(decodeURIComponent(url.pathname));
131
+ bytes =
132
+ url.protocol === 'file:'
133
+ ? await localMedia(url, signal, maxMedia)
134
+ : await remoteMedia(url, signal, maxMedia);
135
+ }
136
+ if (!bytes.length || bytes.length > maxMedia)
137
+ throw new Error('媒体超过大小限制或内容为空');
138
+ }
139
+ catch {
140
+ throw new Error(signal.aborted ? '微信媒体读取已取消或超时' : '无法读取微信待发送媒体,请检查来源及大小');
141
+ }
142
+ const filekey = randomBytes(16).toString('hex');
143
+ const aeskey = randomBytes(16);
144
+ const hexKey = aeskey.toString('hex');
145
+ const cipher = createCipheriv('aes-128-ecb', aeskey, null);
146
+ const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()]);
147
+ signal.throwIfAborted();
148
+ const params = await request('getuploadurl', uploadSchema, {
149
+ filekey,
150
+ media_type: uploadTypes[segment.type],
151
+ to_user_id: userId,
152
+ rawsize: bytes.length,
153
+ rawfilemd5: createHash('md5').update(bytes).digest('hex'),
154
+ filesize: encrypted.length,
155
+ no_need_thumb: true,
156
+ aeskey: hexKey,
157
+ }, 15_000, signal);
158
+ let encryptedParam;
159
+ try {
160
+ const url = resolveCdnUrl('upload', params.upload_full_url, params.upload_param, filekey);
161
+ const response = await fetch(url, {
162
+ method: 'POST',
163
+ headers: { 'Content-Type': 'application/octet-stream' },
164
+ body: encrypted,
165
+ signal,
166
+ redirect: 'error',
167
+ });
168
+ const param = response.headers.get('x-encrypted-param');
169
+ await response.body?.cancel();
170
+ if (response.status !== 200 || !param || param.length > 8192)
171
+ throw new Error('媒体上传未完成');
172
+ encryptedParam = param;
173
+ }
174
+ catch {
175
+ throw new Error(signal.aborted ? '微信媒体上传已取消或超时' : '微信媒体上传失败');
176
+ }
177
+ const media = {
178
+ encrypt_query_param: encryptedParam,
179
+ aes_key: Buffer.from(hexKey).toString('base64'),
180
+ encrypt_type: 1,
181
+ };
182
+ const name = segment.type === 'file' ? (mediaName(segment.data.name) ?? sourceName ?? 'file.bin') : undefined;
183
+ const saved = this.remember(segment.type, media, name);
184
+ if (!saved)
185
+ throw new Error('微信媒体上传后缺少下载标识');
186
+ const item = segment.type === 'image'
187
+ ? { type: 2, image_item: { media, mid_size: encrypted.length } }
188
+ : segment.type === 'video'
189
+ ? { type: 5, video_item: { media, video_size: encrypted.length } }
190
+ : { type: 4, file_item: { media, file_name: name, len: String(bytes.length) } };
191
+ return { item, segment: saved };
192
+ }
193
+ #signal() {
194
+ return AbortSignal.any([this.#shutdown, AbortSignal.timeout(mediaTimeout)]);
195
+ }
196
+ }
@@ -0,0 +1,12 @@
1
+ import { type Message } from '../../core/message/index.ts';
2
+ import type { WeixinMedia } from './media.ts';
3
+ import type { Item } from './protocol.ts';
4
+ export declare class WeixinMessages {
5
+ private readonly recent;
6
+ private readonly media;
7
+ constructor(media: WeixinMedia);
8
+ incoming(userId: string, messageId: string, items: Item[]): Message;
9
+ remember(userId: string, id: string, message: Message): void;
10
+ private key;
11
+ private content;
12
+ }
@@ -0,0 +1,79 @@
1
+ import { seg } from '../../core/message/index.js';
2
+ import { mediaName } from '../media-source.js';
3
+ const maxRecent = 512;
4
+ export class WeixinMessages {
5
+ recent = new Map();
6
+ media;
7
+ constructor(media) {
8
+ this.media = media;
9
+ }
10
+ incoming(userId, messageId, items) {
11
+ const message = [];
12
+ const body = [];
13
+ const quotes = new Set();
14
+ for (const [index, item] of items.entries()) {
15
+ const ref = item.ref_msg;
16
+ if (ref) {
17
+ const id = ref.svr_id ?? ref.message_item?.msg_id ?? `${messageId}:quote:${index}`;
18
+ if (!quotes.has(id)) {
19
+ const inline = ref.message_item && this.content(ref.message_item);
20
+ const quoted = inline?.length ? inline : this.recent.get(this.key(userId, id));
21
+ message.push({
22
+ type: 'reply',
23
+ data: { id, ...(ref.title && { title: ref.title }), ...(quoted && { message: quoted }) },
24
+ });
25
+ quotes.add(id);
26
+ }
27
+ }
28
+ const content = this.content(item);
29
+ if (item.msg_id && item.msg_id !== messageId)
30
+ this.remember(userId, item.msg_id, content);
31
+ message.push(...content);
32
+ body.push(...content);
33
+ }
34
+ this.remember(userId, messageId, body);
35
+ return message;
36
+ }
37
+ remember(userId, id, message) {
38
+ if (!message.length)
39
+ return;
40
+ const key = this.key(userId, id);
41
+ this.recent.delete(key);
42
+ this.recent.set(key, message.slice(0, 16));
43
+ const first = this.recent.keys().next();
44
+ if (this.recent.size > maxRecent && !first.done)
45
+ this.recent.delete(first.value);
46
+ }
47
+ key(userId, id) {
48
+ return JSON.stringify([userId, id]);
49
+ }
50
+ content(item) {
51
+ const single = (segment) => (segment ? [segment] : []);
52
+ switch (item.type) {
53
+ case 1:
54
+ return item.text_item?.text ? [seg.text(item.text_item.text)] : [];
55
+ case 2:
56
+ return item.image_item?.media
57
+ ? single(this.media.remember('image', item.image_item.media, undefined, item.image_item.aeskey))
58
+ : [];
59
+ case 3: {
60
+ const message = [];
61
+ const voice = item.voice_item;
62
+ const audio = voice?.media && this.media.remember('audio', voice.media);
63
+ if (audio)
64
+ message.push(audio);
65
+ if (voice?.text)
66
+ message.push(seg.text(voice.text));
67
+ return message;
68
+ }
69
+ case 4:
70
+ return item.file_item?.media
71
+ ? single(this.media.remember('file', item.file_item.media, mediaName(item.file_item.file_name)))
72
+ : [];
73
+ case 5:
74
+ return item.video_item?.media ? single(this.media.remember('video', item.video_item.media)) : [];
75
+ default:
76
+ return [];
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,145 @@
1
+ import { z } from 'zod';
2
+ export declare const platform = "weixin-clawbot";
3
+ export declare const apiOrigin = "https://ilinkai.weixin.qq.com";
4
+ export declare function ilinkOrigin(value: string): string;
5
+ export declare const accountSchema: z.ZodObject<{
6
+ selfId: z.ZodString;
7
+ token: z.ZodString;
8
+ apiBaseUrl: z.ZodDefault<z.ZodString>;
9
+ }, z.core.$strict>;
10
+ export type Account = z.output<typeof accountSchema>;
11
+ export declare const cdnSchema: z.ZodObject<{
12
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
13
+ aes_key: z.ZodOptional<z.ZodString>;
14
+ full_url: z.ZodOptional<z.ZodString>;
15
+ }, z.core.$strip>;
16
+ export declare const itemSchema: z.ZodObject<{
17
+ type: z.ZodOptional<z.ZodInt>;
18
+ msg_id: z.ZodOptional<z.ZodString>;
19
+ text_item: z.ZodOptional<z.ZodObject<{
20
+ text: z.ZodOptional<z.ZodString>;
21
+ }, z.core.$strip>>;
22
+ image_item: z.ZodOptional<z.ZodObject<{
23
+ media: z.ZodOptional<z.ZodObject<{
24
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
25
+ aes_key: z.ZodOptional<z.ZodString>;
26
+ full_url: z.ZodOptional<z.ZodString>;
27
+ }, z.core.$strip>>;
28
+ aeskey: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strip>>;
30
+ video_item: z.ZodOptional<z.ZodObject<{
31
+ media: z.ZodOptional<z.ZodObject<{
32
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
33
+ aes_key: z.ZodOptional<z.ZodString>;
34
+ full_url: z.ZodOptional<z.ZodString>;
35
+ }, z.core.$strip>>;
36
+ }, z.core.$strip>>;
37
+ file_item: z.ZodOptional<z.ZodObject<{
38
+ media: z.ZodOptional<z.ZodObject<{
39
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
40
+ aes_key: z.ZodOptional<z.ZodString>;
41
+ full_url: z.ZodOptional<z.ZodString>;
42
+ }, z.core.$strip>>;
43
+ file_name: z.ZodOptional<z.ZodString>;
44
+ }, z.core.$strip>>;
45
+ voice_item: z.ZodOptional<z.ZodObject<{
46
+ media: z.ZodOptional<z.ZodObject<{
47
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
48
+ aes_key: z.ZodOptional<z.ZodString>;
49
+ full_url: z.ZodOptional<z.ZodString>;
50
+ }, z.core.$strip>>;
51
+ text: z.ZodOptional<z.ZodString>;
52
+ }, z.core.$strip>>;
53
+ ref_msg: z.ZodCatch<z.ZodOptional<z.ZodObject<{
54
+ message_item: z.ZodOptional<z.ZodObject<{
55
+ type: z.ZodOptional<z.ZodInt>;
56
+ msg_id: z.ZodOptional<z.ZodString>;
57
+ text_item: z.ZodOptional<z.ZodObject<{
58
+ text: z.ZodOptional<z.ZodString>;
59
+ }, z.core.$strip>>;
60
+ image_item: z.ZodOptional<z.ZodObject<{
61
+ media: z.ZodOptional<z.ZodObject<{
62
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
63
+ aes_key: z.ZodOptional<z.ZodString>;
64
+ full_url: z.ZodOptional<z.ZodString>;
65
+ }, z.core.$strip>>;
66
+ aeskey: z.ZodOptional<z.ZodString>;
67
+ }, z.core.$strip>>;
68
+ video_item: z.ZodOptional<z.ZodObject<{
69
+ media: z.ZodOptional<z.ZodObject<{
70
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
71
+ aes_key: z.ZodOptional<z.ZodString>;
72
+ full_url: z.ZodOptional<z.ZodString>;
73
+ }, z.core.$strip>>;
74
+ }, z.core.$strip>>;
75
+ file_item: z.ZodOptional<z.ZodObject<{
76
+ media: z.ZodOptional<z.ZodObject<{
77
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
78
+ aes_key: z.ZodOptional<z.ZodString>;
79
+ full_url: z.ZodOptional<z.ZodString>;
80
+ }, z.core.$strip>>;
81
+ file_name: z.ZodOptional<z.ZodString>;
82
+ }, z.core.$strip>>;
83
+ voice_item: z.ZodOptional<z.ZodObject<{
84
+ media: z.ZodOptional<z.ZodObject<{
85
+ encrypt_query_param: z.ZodOptional<z.ZodString>;
86
+ aes_key: z.ZodOptional<z.ZodString>;
87
+ full_url: z.ZodOptional<z.ZodString>;
88
+ }, z.core.$strip>>;
89
+ text: z.ZodOptional<z.ZodString>;
90
+ }, z.core.$strip>>;
91
+ }, z.core.$strip>>;
92
+ svr_id: z.ZodOptional<z.ZodString>;
93
+ title: z.ZodOptional<z.ZodString>;
94
+ }, z.core.$strip>>>;
95
+ }, z.core.$strip>;
96
+ declare const inboundSchema: z.ZodObject<{
97
+ message_id: z.ZodOptional<z.ZodString>;
98
+ message_type: z.ZodOptional<z.ZodInt>;
99
+ from_user_id: z.ZodOptional<z.ZodString>;
100
+ group_id: z.ZodOptional<z.ZodString>;
101
+ create_time_ms: z.ZodOptional<z.ZodNumber>;
102
+ context_token: z.ZodOptional<z.ZodString>;
103
+ item_list: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
104
+ }, z.core.$strip>;
105
+ export type Inbound = z.output<typeof inboundSchema>;
106
+ export declare const updatesSchema: z.ZodObject<{
107
+ get_updates_buf: z.ZodOptional<z.ZodString>;
108
+ longpolling_timeout_ms: z.ZodOptional<z.ZodInt>;
109
+ msgs: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
110
+ }, z.core.$strip>;
111
+ export type Item = z.output<typeof itemSchema>;
112
+ export declare function readInbound(value: unknown): Inbound | undefined;
113
+ export declare const sentSchema: z.ZodObject<{
114
+ message_id: z.ZodOptional<z.ZodString>;
115
+ }, z.core.$strip>;
116
+ export declare const errorSchema: z.ZodObject<{
117
+ ret: z.ZodOptional<z.ZodInt>;
118
+ errcode: z.ZodOptional<z.ZodInt>;
119
+ }, z.core.$strip>;
120
+ export declare const uploadSchema: z.ZodObject<{
121
+ upload_full_url: z.ZodOptional<z.ZodString>;
122
+ upload_param: z.ZodOptional<z.ZodString>;
123
+ }, z.core.$strip>;
124
+ export declare const typingSchema: z.ZodObject<{
125
+ typing_ticket: z.ZodString;
126
+ }, z.core.$strip>;
127
+ export type IlinkRequest = <T extends z.ZodType>(operation: string, schema: T, data: Record<string, unknown>, timeout?: number, signal?: AbortSignal) => Promise<z.output<T>>;
128
+ export declare class IlinkError extends Error {
129
+ readonly expired: boolean;
130
+ readonly retryable: boolean;
131
+ readonly httpStatus?: number;
132
+ readonly platformCode?: number;
133
+ constructor(operation: string, details: string, { expired, retryable, httpStatus, platformCode, }?: {
134
+ expired?: boolean;
135
+ retryable?: boolean;
136
+ httpStatus?: number;
137
+ platformCode?: number;
138
+ });
139
+ }
140
+ export declare function ilink<T extends z.ZodType>(url: URL, operation: string, schema: T, signal: AbortSignal, options?: {
141
+ data?: Record<string, unknown>;
142
+ token?: string;
143
+ timeout?: number;
144
+ }): Promise<z.output<T>>;
145
+ export {};
@@ -0,0 +1,178 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { botIdentitySchema } from '../../core/identity.js';
4
+ import { limitedBytes } from '../media-source.js';
5
+ export const platform = 'weixin-clawbot';
6
+ export const apiOrigin = 'https://ilinkai.weixin.qq.com';
7
+ const revision = '2.4.10';
8
+ const appHeaders = {
9
+ 'iLink-App-Id': 'bot',
10
+ 'iLink-App-ClientVersion': String((2 << 16) | (4 << 8) | 10),
11
+ };
12
+ const jsonLimit = 8 * 1024 * 1024;
13
+ export function ilinkOrigin(value) {
14
+ const url = new URL(value);
15
+ if (url.protocol !== 'https:' ||
16
+ url.username ||
17
+ url.password ||
18
+ url.port ||
19
+ url.search ||
20
+ url.hash ||
21
+ url.pathname !== '/' ||
22
+ (url.hostname !== 'ilinkai.wechat.com' && !/^(?:ilinkai|idc-\d+)\.weixin\.qq\.com$/.test(url.hostname)))
23
+ throw new Error('微信返回了不受信任的 iLink 地址');
24
+ return url.origin;
25
+ }
26
+ export const accountSchema = z.strictObject({
27
+ selfId: botIdentitySchema.shape.selfId.max(512),
28
+ token: z
29
+ .string()
30
+ .trim()
31
+ .min(1)
32
+ .max(4096)
33
+ .regex(/^[ -~]+$/)
34
+ .meta({ writeOnly: true }),
35
+ apiBaseUrl: z
36
+ .string()
37
+ .refine((value) => {
38
+ try {
39
+ ilinkOrigin(value);
40
+ return true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }, '请使用微信 iLink HTTPS 地址')
46
+ .default(apiOrigin)
47
+ .meta({ writeOnly: true }),
48
+ });
49
+ const messageId = z.string().min(1).max(128);
50
+ export const cdnSchema = z.object({
51
+ encrypt_query_param: z.string().max(8192).optional(),
52
+ aes_key: z.string().max(128).optional(),
53
+ full_url: z.string().max(8192).optional(),
54
+ });
55
+ const mediaFields = { media: cdnSchema.optional() };
56
+ const contentSchema = z.object({
57
+ type: z.int().optional(),
58
+ msg_id: messageId.optional(),
59
+ text_item: z.object({ text: z.string().max(16_000).optional() }).optional(),
60
+ image_item: z.object({ ...mediaFields, aeskey: z.string().max(128).optional() }).optional(),
61
+ video_item: z.object(mediaFields).optional(),
62
+ file_item: z.object({ ...mediaFields, file_name: z.string().max(1024).optional() }).optional(),
63
+ voice_item: z.object({ ...mediaFields, text: z.string().max(16_000).optional() }).optional(),
64
+ });
65
+ export const itemSchema = contentSchema.extend({
66
+ ref_msg: z
67
+ .object({
68
+ message_item: contentSchema.optional(),
69
+ svr_id: messageId.optional(),
70
+ title: z.string().max(4096).optional(),
71
+ })
72
+ .optional()
73
+ .catch(undefined),
74
+ });
75
+ const inboundSchema = z.object({
76
+ message_id: messageId.optional(),
77
+ message_type: z.int().optional(),
78
+ from_user_id: z.string().regex(/^\S+$/).max(512).optional(),
79
+ group_id: z.string().optional(),
80
+ create_time_ms: z.number().optional(),
81
+ context_token: z.string().max(16384).optional(),
82
+ item_list: z.array(z.unknown()).max(128).optional(),
83
+ });
84
+ export const updatesSchema = z.object({
85
+ get_updates_buf: z.string().optional(),
86
+ longpolling_timeout_ms: z.int().positive().optional(),
87
+ msgs: z.array(z.unknown()).optional(),
88
+ });
89
+ export function readInbound(value) {
90
+ const message = inboundSchema.safeParse(value);
91
+ return message.success && message.data.message_type === 1 && !message.data.group_id
92
+ ? message.data
93
+ : undefined;
94
+ }
95
+ export const sentSchema = z.object({ message_id: messageId.optional() });
96
+ export const errorSchema = z.object({ ret: z.int().optional(), errcode: z.int().optional() });
97
+ export const uploadSchema = z.object({
98
+ upload_full_url: z.string().max(8192).optional(),
99
+ upload_param: z.string().max(8192).optional(),
100
+ });
101
+ export const typingSchema = z.object({ typing_ticket: z.string().min(1).max(4096) });
102
+ export class IlinkError extends Error {
103
+ expired;
104
+ retryable;
105
+ httpStatus;
106
+ platformCode;
107
+ constructor(operation, details, { expired = false, retryable = false, httpStatus, platformCode, } = {}) {
108
+ super(`微信 ${operation} ${details}`);
109
+ this.expired = expired;
110
+ this.retryable = retryable;
111
+ this.httpStatus = httpStatus;
112
+ this.platformCode = platformCode;
113
+ }
114
+ }
115
+ export async function ilink(url, operation, schema, signal, options = {}) {
116
+ const { data, token, timeout = 15_000 } = options;
117
+ const deadline = AbortSignal.timeout(timeout);
118
+ const headers = new Headers(appHeaders);
119
+ if (data) {
120
+ headers.set('Content-Type', 'application/json');
121
+ headers.set('AuthorizationType', 'ilink_bot_token');
122
+ headers.set('X-WECHAT-UIN', Buffer.from(String(randomBytes(4).readUInt32BE())).toString('base64'));
123
+ }
124
+ if (token)
125
+ headers.set('Authorization', `Bearer ${token}`);
126
+ let bytes;
127
+ try {
128
+ const response = await fetch(url, {
129
+ method: data ? 'POST' : 'GET',
130
+ redirect: 'error',
131
+ headers,
132
+ signal: AbortSignal.any([signal, deadline]),
133
+ ...(data && {
134
+ body: JSON.stringify(token ? { ...data, base_info: { channel_version: revision, bot_agent: 'AsaBot/0.1.0' } } : data),
135
+ }),
136
+ });
137
+ if (!response.ok) {
138
+ await response.body?.cancel();
139
+ const status = response.status;
140
+ throw new IlinkError(operation, `失败(HTTP ${status})`, {
141
+ expired: !!token && status === 401,
142
+ httpStatus: status,
143
+ retryable: status === 408 || status === 429 || status >= 500,
144
+ });
145
+ }
146
+ bytes = await limitedBytes(response, jsonLimit);
147
+ }
148
+ catch (error) {
149
+ signal.throwIfAborted();
150
+ if (error instanceof IlinkError)
151
+ throw error;
152
+ if (deadline.aborted)
153
+ throw deadline.reason;
154
+ throw new IlinkError(operation, '请求失败', { retryable: true });
155
+ }
156
+ let result;
157
+ try {
158
+ result = JSON.parse(bytes.toString('utf8'), (key, value, context) => typeof value === 'number' && (key === 'message_id' || key === 'msg_id' || key === 'svr_id')
159
+ ? context?.source
160
+ : value);
161
+ }
162
+ catch {
163
+ throw new IlinkError(operation, '响应格式不正确');
164
+ }
165
+ const status = errorSchema.safeParse(result);
166
+ if (status.success) {
167
+ const { ret, errcode } = status.data;
168
+ if (ret === -14 || errcode === -14)
169
+ throw new IlinkError(operation, '授权已失效,请重新扫码', { expired: true, platformCode: -14 });
170
+ const code = ret || errcode;
171
+ if (code)
172
+ throw new IlinkError(operation, `失败(错误码 ${code})`, { platformCode: code });
173
+ }
174
+ const parsed = schema.safeParse(result);
175
+ if (!status.success || !parsed.success)
176
+ throw new IlinkError(operation, '响应格式不正确');
177
+ return parsed.data;
178
+ }
@@ -0,0 +1,2 @@
1
+ import type { QrConnectionSetup } from '../../core/adapter.ts';
2
+ export declare const weixinSetup: QrConnectionSetup;