@botharness/im-provider 4.32.0-botharness.3 → 4.32.0-botharness.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PROVENANCE.json +6 -6
- package/lib/client.js +2 -2
- package/lib/index.js +291 -291
- package/package.json +2 -2
- package/plugin-src/host/channels/weixin/production.mjs +2 -1
- package/plugin-src/host/delivery-adapter.mjs +7 -1
- package/src/channels/weixin/config-store.mjs +2 -0
- package/src/channels/weixin/external-consumer.mjs +67 -0
- package/src/channels/weixin/external-files.mjs +60 -0
- package/src/channels/weixin/state-store.mjs +14 -1
- package/src/channels/weixin/weixin-api.mjs +45 -6
- package/src/channels/weixin/weixin-controller.mjs +94 -1
- package/src/channels/weixin/weixin-runtime.mjs +47 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botharness/im-provider",
|
|
3
|
-
"version": "4.32.0-botharness.
|
|
3
|
+
"version": "4.32.0-botharness.5",
|
|
4
4
|
"icon": "./assets/logo-plugin-message-link-gradient.webp",
|
|
5
5
|
"description": "BotHarness-qualified IM Provider, maintained from dsh-im",
|
|
6
6
|
"keywords": [
|
|
@@ -176,6 +176,6 @@
|
|
|
176
176
|
},
|
|
177
177
|
"botharness": {
|
|
178
178
|
"managedByProduct": true,
|
|
179
|
-
"upstreamSource": "
|
|
179
|
+
"upstreamSource": "8852e87f29813fc8626c039e49e278c2383c47aa"
|
|
180
180
|
}
|
|
181
181
|
}
|
|
@@ -157,7 +157,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
157
157
|
configStore: observedConfigStore,
|
|
158
158
|
logger,
|
|
159
159
|
diagnostics,
|
|
160
|
-
createRuntime: async ({ botId, config: accountConfig, token }) => {
|
|
160
|
+
createRuntime: async ({ botId, config: accountConfig, token, externalConsumer }) => {
|
|
161
161
|
const state = await stateFor(botId);
|
|
162
162
|
await workspaces.ensure(botId, {
|
|
163
163
|
defaultAgentPreset: config.agentPreset,
|
|
@@ -171,6 +171,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
171
171
|
api,
|
|
172
172
|
config: accountConfig,
|
|
173
173
|
token,
|
|
174
|
+
externalConsumer: (message, signal) => externalConsumer(message, state, signal),
|
|
174
175
|
harness: workspaceScope.harness,
|
|
175
176
|
state: workspaceScope.state,
|
|
176
177
|
contextEnhancement: { botId, getSettings: () => workspaces.contextEnhancementFor(botId) },
|
|
@@ -269,7 +269,13 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
|
|
|
269
269
|
ownsBot: (botId) => workspaces.has(botId),
|
|
270
270
|
listBots: () => workspaces.listBotIds(),
|
|
271
271
|
async listTargets(botId) {
|
|
272
|
-
|
|
272
|
+
let targets = [...workspaces.listDeliveryTargets(botId)];
|
|
273
|
+
if (channel === 'weixin' && typeof coreController.describeDeliveryAccount === 'function') {
|
|
274
|
+
const paired = await coreController.describeDeliveryAccount(botId);
|
|
275
|
+
targets = targets.filter(target => target.kind === 'user' && target.route?.toUserId === paired?.account?.ownerUserId);
|
|
276
|
+
if (paired?.account?.ownerUserId && !targets.some(target => target.kind === 'user' && target.route?.toUserId === paired.account.ownerUserId))
|
|
277
|
+
targets.push({ targetId: 'paired-owner', name: '扫码绑定者私聊', kind: 'user', route: { toUserId: paired.account.ownerUserId } });
|
|
278
|
+
}
|
|
273
279
|
const configured = new Map(
|
|
274
280
|
sessionSyncConfigs(workspaces, botId).map((target) => [target.targetId, target]),
|
|
275
281
|
);
|
|
@@ -57,6 +57,7 @@ function normalizeAccount(value, invalid = () => null) {
|
|
|
57
57
|
} catch (error) {
|
|
58
58
|
return invalid('.baseUrl', error?.code === 'untrusted-base-url' ? 'untrusted-api-url' : 'invalid-api-url');
|
|
59
59
|
}
|
|
60
|
+
if (value.consumerMode != null && value.consumerMode !== 'external-consumer') return invalid('.consumerMode', 'invalid-mode');
|
|
60
61
|
return Object.freeze({
|
|
61
62
|
botId,
|
|
62
63
|
accountId,
|
|
@@ -65,6 +66,7 @@ function normalizeAccount(value, invalid = () => null) {
|
|
|
65
66
|
baseUrl,
|
|
66
67
|
createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
|
|
67
68
|
connectedAt: cleanString(value.connectedAt),
|
|
69
|
+
...(value.consumerMode == null ? {} : { consumerMode: value.consumerMode }),
|
|
68
70
|
});
|
|
69
71
|
}
|
|
70
72
|
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { deriveWeixinBotIdentity, maskWeixinAccountId } from './config-store.mjs';
|
|
3
|
+
import { extractWeixinText, weixinMessageId } from './weixin-api.mjs';
|
|
4
|
+
|
|
5
|
+
export function weixinRefusal(code) { return Object.assign(new Error(code), { code }); }
|
|
6
|
+
const continuation = value => typeof value === 'string' && value.length > 0 && value.length <= 16384;
|
|
7
|
+
const id = value => typeof value === 'string' && value.length > 0 && value.length <= 512 && value.trim() === value;
|
|
8
|
+
|
|
9
|
+
/** Identity comes from the stored server-confirmed QR pairing, not a fabricated auth.test API.
|
|
10
|
+
* A different credential invalidates all grants even if its local reference is unchanged. */
|
|
11
|
+
export function pairedWeixinAccount(config, token) {
|
|
12
|
+
if (!id(config?.accountId) || !id(config?.ownerUserId) || !config.connectedAt || typeof token !== 'string' || !token.trim()
|
|
13
|
+
|| deriveWeixinBotIdentity(config.accountId).botId !== config.botId) throw weixinRefusal('account-unverified');
|
|
14
|
+
const credentialHash = createHash('sha256').update(token).digest('hex');
|
|
15
|
+
const identity = { provider: 'weixin', accountId: config.accountId, ownerUserId: config.ownerUserId,
|
|
16
|
+
baseUrl: config.baseUrl, credentialHash };
|
|
17
|
+
return Object.freeze({ accountId: config.accountId, ownerUserId: config.ownerUserId,
|
|
18
|
+
name: `微信 · ${maskWeixinAccountId(config.accountId)}`,
|
|
19
|
+
fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Paired-owner text and opt-in native files. No group, mention, or thread is invented. */
|
|
23
|
+
export function normalizeWeixinExternalText(message, { botId, account, sourceFiles = false }) {
|
|
24
|
+
if (message?.message_type !== 1 || message.from_user_id !== account.ownerUserId) return null;
|
|
25
|
+
if (message.to_user_id !== account.accountId) throw weixinRefusal('account-changed');
|
|
26
|
+
if (!Array.isArray(message.item_list) || !message.item_list.length
|
|
27
|
+
|| message.item_list.some(item => item?.type !== 1 && !(sourceFiles && item?.type === 4))) return null;
|
|
28
|
+
const messageId = weixinMessageId(message);
|
|
29
|
+
const files = message.item_list.filter(item => item?.type === 4);
|
|
30
|
+
if (files.length > 1) throw weixinRefusal('resource-unavailable');
|
|
31
|
+
const nativeFile = files[0]?.file_item;
|
|
32
|
+
if (files.length && (!nativeFile || !id(nativeFile.file_name)
|
|
33
|
+
|| /[\x00-\x1f\x7f/\\]/.test(nativeFile.file_name))) throw weixinRefusal('resource-unavailable');
|
|
34
|
+
const text = extractWeixinText(message) || (nativeFile ? `[File: ${nativeFile.file_name}]` : '');
|
|
35
|
+
const time = typeof message.create_time_ms === 'string' ? Number(message.create_time_ms) : message.create_time_ms;
|
|
36
|
+
if (!messageId || !/^\d+$/.test(messageId) || !text?.trim() || text.length > 16000
|
|
37
|
+
|| !Number.isSafeInteger(time) || time <= 0 || !continuation(message.context_token)) throw weixinRefusal('invalid-inbound');
|
|
38
|
+
const at = new Date(time);
|
|
39
|
+
if (!Number.isFinite(at.getTime())) throw weixinRefusal('invalid-inbound');
|
|
40
|
+
const conversationId = account.ownerUserId;
|
|
41
|
+
const resourceKey = nativeFile ? createHash('sha256').update(JSON.stringify([
|
|
42
|
+
account.fingerprint, conversationId, messageId, nativeFile.file_name, nativeFile.len ?? null,
|
|
43
|
+
])).digest('hex') : undefined;
|
|
44
|
+
const size = nativeFile?.len === undefined ? undefined : Number(nativeFile.len);
|
|
45
|
+
if (nativeFile?.len !== undefined && (!/^\d+$/.test(String(nativeFile.len))
|
|
46
|
+
|| !Number.isSafeInteger(size) || size < 0)) throw weixinRefusal('resource-unavailable');
|
|
47
|
+
const attachments = nativeFile ? Object.freeze([Object.freeze({
|
|
48
|
+
id: createHash('sha256').update(JSON.stringify([account.fingerprint, conversationId, messageId, resourceKey])).digest('hex'),
|
|
49
|
+
messageId, resourceKey, name: nativeFile.file_name,
|
|
50
|
+
...(size > 0 ? { sizeBytes: size } : {}), mediaType: 'application/octet-stream',
|
|
51
|
+
})]) : undefined;
|
|
52
|
+
return Object.freeze({ version: 1, channel: 'weixin', botId, fingerprint: account.fingerprint,
|
|
53
|
+
eventId: messageId, messageId, actor: Object.freeze({ kind: 'user', id: account.ownerUserId }),
|
|
54
|
+
conversation: Object.freeze({ kind: 'dm', id: conversationId }), mentions: Object.freeze([]),
|
|
55
|
+
mentionedAccount: false, at: at.toISOString(), text, ...(attachments ? { attachments } : {}),
|
|
56
|
+
reply: Object.freeze({ messageId, conversationId, actorId: account.ownerUserId }),
|
|
57
|
+
replay: Object.freeze({ kind: 'provider-redelivery', resumeCursor: false, gapPossible: true }) });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function checkedWeixinRoute(route, account, source) {
|
|
61
|
+
if (!route || Object.keys(route).some(key => !['messageId', 'conversationId', 'actorId'].includes(key))
|
|
62
|
+
|| route.conversationId !== account.ownerUserId || route.actorId !== account.ownerUserId
|
|
63
|
+
|| !id(route.messageId) || !source || source.fingerprint !== account.fingerprint
|
|
64
|
+
|| source.actorId !== route.actorId || source.messageId !== route.messageId
|
|
65
|
+
|| source.expiresAt <= Date.now() || !continuation(source.contextToken)) throw weixinRefusal('stale-route');
|
|
66
|
+
return { messageId: route.messageId, conversationId: route.conversationId, actorId: route.actorId };
|
|
67
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { weixinRefusal } from './external-consumer.mjs';
|
|
2
|
+
|
|
3
|
+
export const WEIXIN_EXTERNAL_FILE_LIMIT = 25 * 1024 * 1024;
|
|
4
|
+
|
|
5
|
+
/** A source-scoped file ticket is private state, not a model-readable download URL. */
|
|
6
|
+
export function privateWeixinFile(message, event) {
|
|
7
|
+
if (!event.attachments?.length) return undefined;
|
|
8
|
+
const file = message.item_list.find(item => item.type === 4)?.file_item;
|
|
9
|
+
const media = file?.media;
|
|
10
|
+
if (!media || typeof media !== 'object'
|
|
11
|
+
|| typeof media.aes_key !== 'string' || !media.aes_key || media.aes_key.length > 128
|
|
12
|
+
|| ![media.encrypt_query_param, media.full_url].some(value => typeof value === 'string' && value.length > 0 && value.length <= 16384))
|
|
13
|
+
throw weixinRefusal('resource-unavailable');
|
|
14
|
+
return { attachment: event.attachments[0], item: { file_name: file.file_name,
|
|
15
|
+
...(file.len === undefined ? {} : { len: String(file.len) }),
|
|
16
|
+
media: { aes_key: media.aes_key, encrypt_type: media.encrypt_type,
|
|
17
|
+
...(typeof media.encrypt_query_param === 'string' && media.encrypt_query_param.length <= 16384
|
|
18
|
+
? { encrypt_query_param: media.encrypt_query_param } : {}),
|
|
19
|
+
...(typeof media.full_url === 'string' && media.full_url.length <= 16384
|
|
20
|
+
? { full_url: media.full_url } : {}) } } };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function readWeixinExternalFile(api, source, attachment, { signal, assertCurrent }) {
|
|
24
|
+
assertCurrent();
|
|
25
|
+
const saved = source.file;
|
|
26
|
+
if (!saved || !attachment || Object.keys(attachment).some(key => !['id', 'messageId', 'resourceKey', 'name', 'sizeBytes', 'mediaType'].includes(key))
|
|
27
|
+
|| ['id', 'messageId', 'resourceKey', 'name', 'sizeBytes', 'mediaType'].some(key => attachment[key] !== saved.attachment[key]))
|
|
28
|
+
throw weixinRefusal('stale-route');
|
|
29
|
+
if (attachment.sizeBytes > WEIXIN_EXTERNAL_FILE_LIMIT) throw weixinRefusal('artifact-too-large');
|
|
30
|
+
const file = api.inboundFiles({ item_list: [{ type: 4, file_item: saved.item }] })[0];
|
|
31
|
+
if (!file) throw weixinRefusal('resource-unavailable');
|
|
32
|
+
const data = await file.load({ signal, maxBytes: WEIXIN_EXTERNAL_FILE_LIMIT });
|
|
33
|
+
assertCurrent();
|
|
34
|
+
if (!(data instanceof Uint8Array) || data.byteLength === 0) throw weixinRefusal('resource-unavailable');
|
|
35
|
+
if (data.byteLength > WEIXIN_EXTERNAL_FILE_LIMIT) throw weixinRefusal('artifact-too-large');
|
|
36
|
+
if (saved.item.len !== undefined && data.byteLength !== Number(saved.item.len)) throw weixinRefusal('resource-unavailable');
|
|
37
|
+
return (async function* () { assertCurrent(); yield new Uint8Array(data); assertCurrent(); })();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function replyWeixinExternalFile(api, request, file, { signal, assertCurrent }) {
|
|
41
|
+
if (typeof file?.id !== 'string' || !file.id || file.id.length > 512
|
|
42
|
+
|| typeof file.name !== 'string' || !file.name.trim() || file.name.length > 512
|
|
43
|
+
|| /[\x00-\x1f\x7f/\\]/.test(file.name) || !(file.bytes instanceof Uint8Array)
|
|
44
|
+
|| !file.bytes.byteLength || file.bytes.byteLength > WEIXIN_EXTERNAL_FILE_LIMIT) throw weixinRefusal('bad-request');
|
|
45
|
+
assertCurrent();
|
|
46
|
+
try {
|
|
47
|
+
const result = await api.sendFile({ ...request, signal,
|
|
48
|
+
file: { artifactId: file.id, fileName: file.name, bytes: Buffer.from(file.bytes) },
|
|
49
|
+
beforeSend: assertCurrent });
|
|
50
|
+
assertCurrent();
|
|
51
|
+
if (typeof result?.messageId !== 'string' || !result.messageId.startsWith('dsh-weixin-'))
|
|
52
|
+
throw weixinRefusal('provider-result-unknown');
|
|
53
|
+
return { sent: true };
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error?.code === 'artifact-provider-failed') throw weixinRefusal('file-upload-failed');
|
|
56
|
+
if (['artifact-permission-required', 'artifact-too-large', 'artifact-provider-rejected', 'artifact-rate-limited'].includes(error?.code))
|
|
57
|
+
throw weixinRefusal('file-provider-rejected');
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -100,6 +100,7 @@ function normalizeState(value) {
|
|
|
100
100
|
return {
|
|
101
101
|
version: 1,
|
|
102
102
|
sessions,
|
|
103
|
+
externalReplySources: Object.fromEntries(Object.entries(value.externalReplySources ?? {}).filter(([key, entry]) => /^\d+$/.test(key) && entry?.messageId === key && entry.expiresAt > Date.now()).slice(-1000)),
|
|
103
104
|
...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
|
|
104
105
|
seenMessageIds: Array.isArray(value.seenMessageIds)
|
|
105
106
|
? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
|
|
@@ -166,6 +167,18 @@ export class WeixinStateStore {
|
|
|
166
167
|
await this.#persist();
|
|
167
168
|
}
|
|
168
169
|
|
|
170
|
+
externalReplySource(messageId) {
|
|
171
|
+
return structuredClone(this.#state.externalReplySources?.[messageId]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async rememberExternalReplySource(source) {
|
|
175
|
+
const entries = Object.entries(this.#state.externalReplySources ?? {})
|
|
176
|
+
.filter(([key, value]) => key !== source.messageId && value.expiresAt > Date.now()).slice(-999);
|
|
177
|
+
entries.push([source.messageId, structuredClone(source)]);
|
|
178
|
+
this.#state.externalReplySources = Object.fromEntries(entries);
|
|
179
|
+
await this.#persist();
|
|
180
|
+
}
|
|
181
|
+
|
|
169
182
|
sessionFor(key) {
|
|
170
183
|
return this.#state.sessions[key] ?? null;
|
|
171
184
|
}
|
|
@@ -264,7 +277,7 @@ export class WeixinStateStore {
|
|
|
264
277
|
}
|
|
265
278
|
|
|
266
279
|
snapshot() {
|
|
267
|
-
const { contextTokens, ...state } = this.#state;
|
|
280
|
+
const { contextTokens, externalReplySources, ...state } = this.#state;
|
|
268
281
|
return structuredClone(state);
|
|
269
282
|
}
|
|
270
283
|
|
|
@@ -205,7 +205,7 @@ export function extractWeixinImages(message, { fetchImpl = fetch } = {}) {
|
|
|
205
205
|
return images;
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
async function fetchWeixinFileCiphertext(url, { fetchImpl, signal }) {
|
|
208
|
+
async function fetchWeixinFileCiphertext(url, { fetchImpl, signal, maxBytes }) {
|
|
209
209
|
const response = await fetchImpl(new URL(url), {
|
|
210
210
|
method: 'GET',
|
|
211
211
|
signal,
|
|
@@ -219,7 +219,25 @@ async function fetchWeixinFileCiphertext(url, { fetchImpl, signal }) {
|
|
|
219
219
|
{ status: response?.status },
|
|
220
220
|
);
|
|
221
221
|
}
|
|
222
|
-
|
|
222
|
+
const tooLarge = () => Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
|
|
223
|
+
const declared = Number(response.headers?.get?.('content-length'));
|
|
224
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
225
|
+
await response.body?.cancel?.().catch(() => undefined);
|
|
226
|
+
throw tooLarge();
|
|
227
|
+
}
|
|
228
|
+
if (!response.body?.[Symbol.asyncIterator]) throw Object.assign(new Error('resource-unavailable'), { code: 'resource-unavailable' });
|
|
229
|
+
const chunks = [];
|
|
230
|
+
let size = 0;
|
|
231
|
+
try {
|
|
232
|
+
for await (const chunk of response.body) {
|
|
233
|
+
signal?.throwIfAborted();
|
|
234
|
+
size += chunk.byteLength;
|
|
235
|
+
if (size > maxBytes) throw tooLarge();
|
|
236
|
+
chunks.push(Buffer.from(chunk));
|
|
237
|
+
}
|
|
238
|
+
signal?.throwIfAborted();
|
|
239
|
+
return Buffer.concat(chunks, size);
|
|
240
|
+
} finally { await response.body.cancel?.().catch(() => undefined); }
|
|
223
241
|
}
|
|
224
242
|
|
|
225
243
|
/** Convert native iLink file items into lazily downloaded, decrypted file references. */
|
|
@@ -233,13 +251,17 @@ export function extractWeixinFiles(message, { fetchImpl = fetch } = {}) {
|
|
|
233
251
|
files.push({
|
|
234
252
|
name: nonEmptyString(fileItem.file_name) ?? (files.length === 0 ? 'file' : `file-${files.length + 1}`),
|
|
235
253
|
...(Number.isFinite(declaredSize) && declaredSize >= 0 ? { size: declaredSize } : {}),
|
|
236
|
-
load: async ({ signal } = {}) => {
|
|
254
|
+
load: async ({ signal, maxBytes = 25 * 1024 * 1024 } = {}) => {
|
|
237
255
|
signal?.throwIfAborted();
|
|
256
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > 25 * 1024 * 1024) throw new TypeError('Invalid file byte limit');
|
|
257
|
+
if (Number.isFinite(declaredSize) && declaredSize > maxBytes) throw Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
|
|
238
258
|
const key = parseWeixinImageAesKey(fileItem);
|
|
239
259
|
const url = weixinImageDownloadUrl(fileItem.media);
|
|
240
|
-
const ciphertext = await fetchWeixinFileCiphertext(url, { fetchImpl, signal });
|
|
260
|
+
const ciphertext = await fetchWeixinFileCiphertext(url, { fetchImpl, signal, maxBytes: maxBytes + 16 });
|
|
241
261
|
signal?.throwIfAborted();
|
|
242
|
-
|
|
262
|
+
const plaintext = decryptWeixinImage(ciphertext, key);
|
|
263
|
+
if (plaintext.length > maxBytes) throw Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
|
|
264
|
+
return plaintext;
|
|
243
265
|
},
|
|
244
266
|
});
|
|
245
267
|
}
|
|
@@ -475,7 +497,18 @@ async function requestJson(fetchImpl, {
|
|
|
475
497
|
);
|
|
476
498
|
}
|
|
477
499
|
try {
|
|
478
|
-
|
|
500
|
+
// Native IDs may exceed Number.MAX_SAFE_INTEGER. Read their original JSON
|
|
501
|
+
// lexemes before numeric precision is lost; other protocol values keep
|
|
502
|
+
// their original types (ret/errcode and timestamps are not message IDs).
|
|
503
|
+
return JSON.parse(await response.text(), (key, value, context) => {
|
|
504
|
+
if ((key === 'message_id' || key === 'msg_id') && typeof value === 'number') {
|
|
505
|
+
if (!context?.source || !/^\d+$/.test(context.source)) {
|
|
506
|
+
throw new TypeError('Invalid native Weixin message ID');
|
|
507
|
+
}
|
|
508
|
+
return context.source;
|
|
509
|
+
}
|
|
510
|
+
return value;
|
|
511
|
+
});
|
|
479
512
|
} catch (error) {
|
|
480
513
|
throw new WeixinApiError('invalid-response', '微信服务返回了无法解析的响应。', { cause: error });
|
|
481
514
|
}
|
|
@@ -516,6 +549,7 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
|
|
|
516
549
|
contextToken,
|
|
517
550
|
runId,
|
|
518
551
|
signal,
|
|
552
|
+
beforeSend,
|
|
519
553
|
}, { mediaType, createItem }) {
|
|
520
554
|
const recipient = nonEmptyString(toUserId);
|
|
521
555
|
if (!recipient || !file || typeof file !== 'object'
|
|
@@ -589,6 +623,8 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
|
|
|
589
623
|
aes_key: Buffer.from(aesKey.toString('hex')).toString('base64'),
|
|
590
624
|
encrypt_type: 1,
|
|
591
625
|
};
|
|
626
|
+
await beforeSend?.();
|
|
627
|
+
signal?.throwIfAborted();
|
|
592
628
|
let response;
|
|
593
629
|
try {
|
|
594
630
|
response = await requestJson(fetchImpl, {
|
|
@@ -929,6 +965,9 @@ export function weixinMessageTimestampMs(messageId, { now = Date.now() } = {}) {
|
|
|
929
965
|
|
|
930
966
|
export function weixinMessageId(message) {
|
|
931
967
|
if (message?.message_id !== undefined && message.message_id !== null) {
|
|
968
|
+
if (typeof message.message_id === 'number' && !Number.isSafeInteger(message.message_id)) {
|
|
969
|
+
return null;
|
|
970
|
+
}
|
|
932
971
|
return String(message.message_id);
|
|
933
972
|
}
|
|
934
973
|
return nonEmptyString(message?.client_id);
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { ExclusiveInboundConsumers } from '../shared/exclusive-inbound-consumers.mjs';
|
|
2
|
+
import { pairedWeixinAccount, normalizeWeixinExternalText, weixinRefusal } from './external-consumer.mjs';
|
|
3
|
+
import { privateWeixinFile } from './external-files.mjs';
|
|
1
4
|
import { randomUUID } from 'node:crypto';
|
|
2
5
|
import { createWeixinDiagnostics, knownWeixinErrorCode, weixinStageError } from './connection-error.mjs';
|
|
3
6
|
|
|
@@ -61,6 +64,7 @@ function preserveActivationError(error, fallbackCode) {
|
|
|
61
64
|
}
|
|
62
65
|
|
|
63
66
|
export class WeixinController {
|
|
67
|
+
#inboundConsumers = new ExclusiveInboundConsumers();
|
|
64
68
|
#api;
|
|
65
69
|
#credentials;
|
|
66
70
|
#configStore;
|
|
@@ -145,6 +149,73 @@ export class WeixinController {
|
|
|
145
149
|
this.#touch();
|
|
146
150
|
}
|
|
147
151
|
|
|
152
|
+
async #deliveryAccount(config, signal) {
|
|
153
|
+
signal?.throwIfAborted();
|
|
154
|
+
if (this.#closed) throw weixinRefusal('provider-unavailable');
|
|
155
|
+
return pairedWeixinAccount(config, await this.#resolveToken(config.tokenRef));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async describeDeliveryAccount(botId) {
|
|
159
|
+
return this.#withBotTransition(botId, async () => {
|
|
160
|
+
const config = this.#configStore.get(botId);
|
|
161
|
+
if (!config) throw weixinRefusal('unknown-bot');
|
|
162
|
+
const account = await this.#deliveryAccount(config);
|
|
163
|
+
return { version: 1, botId, channel: 'weixin', account,
|
|
164
|
+
connected: this.#runtimes.get(botId)?.status?.ready === true,
|
|
165
|
+
capabilities: ['proactive-text-checked', 'exclusive-text-consumer', 'reply-text-checked',
|
|
166
|
+
'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked',
|
|
167
|
+
'source-file-checked', 'reply-file-checked', 'reply-file-fence-checked'] };
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false } = {}) {
|
|
172
|
+
return this.#withBotTransition(botId, async () => {
|
|
173
|
+
const config = this.#configStore.get(botId);
|
|
174
|
+
if (!config) throw weixinRefusal('unknown-bot');
|
|
175
|
+
const account = await this.#deliveryAccount(config, signal);
|
|
176
|
+
if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
|
|
177
|
+
const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceFiles });
|
|
178
|
+
try {
|
|
179
|
+
const saved = await this.#configStore.save({ ...config, consumerMode: 'external-consumer' });
|
|
180
|
+
await this.#startRuntime(saved, await this.#resolveToken(saved.tokenRef));
|
|
181
|
+
signal?.throwIfAborted();
|
|
182
|
+
return dispose;
|
|
183
|
+
} catch (error) { dispose(); throw error; }
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async #checkedRuntime(botId, expectedFingerprint, signal) {
|
|
188
|
+
const config = this.#configStore.get(botId);
|
|
189
|
+
if (!config) throw weixinRefusal('unknown-bot');
|
|
190
|
+
const account = await this.#deliveryAccount(config, signal);
|
|
191
|
+
if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
|
|
192
|
+
const runtime = this.#runtimes.get(botId);
|
|
193
|
+
if (config.consumerMode !== 'external-consumer' || !runtime?.status?.ready) throw weixinRefusal('capability-unavailable');
|
|
194
|
+
const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
|
|
195
|
+
return { runtime, account, signal: signal ? AbortSignal.any([signal, lease]) : lease };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async qualifyReplyChecked(botId, route, options = {}) {
|
|
199
|
+
return this.#withBotTransition(botId, async () => {
|
|
200
|
+
const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
|
|
201
|
+
return checked.runtime.qualifyReplyChecked(route, checked);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async replyChecked(botId, route, text, options = {}) {
|
|
206
|
+
return this.#withBotTransition(botId, async () => {
|
|
207
|
+
const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
|
|
208
|
+
return checked.runtime.replyChecked(route, text, { ...options, ...checked });
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async externalFileChecked(botId, route, file, options = {}) {
|
|
213
|
+
return this.#withBotTransition(botId, async () => {
|
|
214
|
+
const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
|
|
215
|
+
return checked.runtime.externalFileChecked(route, file, { ...options, ...checked });
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
148
219
|
async startProvisioning() {
|
|
149
220
|
if (this.#closed) throw new Error('dsh-weixin controller is closed');
|
|
150
221
|
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
|
@@ -285,11 +356,17 @@ export class WeixinController {
|
|
|
285
356
|
error.code = 'bot-not-connected';
|
|
286
357
|
throw error;
|
|
287
358
|
}
|
|
359
|
+
if (options.expectedFingerprint !== undefined) {
|
|
360
|
+
const account = await this.#deliveryAccount(config, options.signal);
|
|
361
|
+
if (account.fingerprint !== options.expectedFingerprint) throw weixinRefusal('account-changed');
|
|
362
|
+
if (target?.kind !== 'user' || target.route?.toUserId !== account.ownerUserId) throw weixinRefusal('invalid-target');
|
|
363
|
+
}
|
|
288
364
|
return runtime.sendProactiveText(target, text, options);
|
|
289
365
|
});
|
|
290
366
|
}
|
|
291
367
|
|
|
292
368
|
async deleteBot(botId) {
|
|
369
|
+
this.#inboundConsumers.remove(botId);
|
|
293
370
|
const config = this.#configStore.get(botId);
|
|
294
371
|
if (!config) throw weixinStageError('workspace-bot-not-found', undefined, 'account.remove');
|
|
295
372
|
const warnings = [];
|
|
@@ -405,6 +482,7 @@ export class WeixinController {
|
|
|
405
482
|
}
|
|
406
483
|
|
|
407
484
|
async close() {
|
|
485
|
+
this.#inboundConsumers.close();
|
|
408
486
|
if (this.#closed) return;
|
|
409
487
|
this.#closed = true;
|
|
410
488
|
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
|
@@ -523,6 +601,7 @@ export class WeixinController {
|
|
|
523
601
|
baseUrl,
|
|
524
602
|
createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
|
|
525
603
|
connectedAt: new Date().toISOString(),
|
|
604
|
+
...(previousConfig?.consumerMode ? { consumerMode: previousConfig.consumerMode } : {}),
|
|
526
605
|
};
|
|
527
606
|
let previousToken;
|
|
528
607
|
try {
|
|
@@ -589,7 +668,21 @@ export class WeixinController {
|
|
|
589
668
|
await this.#stopRuntime(config.botId);
|
|
590
669
|
let runtime;
|
|
591
670
|
try {
|
|
592
|
-
|
|
671
|
+
const account = config.consumerMode === 'external-consumer' ? pairedWeixinAccount(config, token) : undefined;
|
|
672
|
+
runtime = await this.#createRuntime({ botId: config.botId, config, token,
|
|
673
|
+
externalConsumer: async (message, state, signal) => {
|
|
674
|
+
const current = await this.#deliveryAccount(this.#configStore.get(config.botId), signal);
|
|
675
|
+
if (current.fingerprint !== account.fingerprint) throw weixinRefusal('account-changed');
|
|
676
|
+
this.#inboundConsumers.signalFor(config.botId, account.fingerprint).throwIfAborted();
|
|
677
|
+
const event = normalizeWeixinExternalText(message, { botId: config.botId, account,
|
|
678
|
+
sourceFiles: this.#inboundConsumers.acceptsFiles(config.botId) });
|
|
679
|
+
if (!event) return { accepted: true, ignored: true };
|
|
680
|
+
await state.rememberExternalReplySource({ messageId: event.messageId, actorId: event.actor.id,
|
|
681
|
+
fingerprint: account.fingerprint, contextToken: message.context_token,
|
|
682
|
+
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
|
|
683
|
+
...(event.attachments?.length ? { file: privateWeixinFile(message, event) } : {}) });
|
|
684
|
+
return this.#inboundConsumers.accept(config.botId, event, signal);
|
|
685
|
+
} });
|
|
593
686
|
} catch (error) {
|
|
594
687
|
throw preserveActivationError(error, 'runtime-prepare-failed');
|
|
595
688
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { checkedWeixinRoute, weixinRefusal } from './external-consumer.mjs';
|
|
2
|
+
import { readWeixinExternalFile, replyWeixinExternalFile } from './external-files.mjs';
|
|
1
3
|
import { createWeixinDiagnostics } from './connection-error.mjs';
|
|
2
4
|
import { DEFAULT_WEIXIN_MAX_MESSAGE_CHARS, WeixinApiError, rejectedProviderResponse } from './weixin-api.mjs';
|
|
3
5
|
import {
|
|
@@ -116,6 +118,7 @@ export class WeixinRuntime {
|
|
|
116
118
|
#token;
|
|
117
119
|
#harness;
|
|
118
120
|
#state;
|
|
121
|
+
#externalConsumer;
|
|
119
122
|
#contextEnhancement;
|
|
120
123
|
#accessPolicy;
|
|
121
124
|
#logger;
|
|
@@ -137,6 +140,7 @@ export class WeixinRuntime {
|
|
|
137
140
|
harness,
|
|
138
141
|
state,
|
|
139
142
|
contextEnhancement,
|
|
143
|
+
externalConsumer,
|
|
140
144
|
accessPolicy,
|
|
141
145
|
logger = console,
|
|
142
146
|
diagnostics,
|
|
@@ -153,6 +157,7 @@ export class WeixinRuntime {
|
|
|
153
157
|
this.#harness = harness;
|
|
154
158
|
this.#state = state;
|
|
155
159
|
this.#contextEnhancement = contextEnhancement;
|
|
160
|
+
this.#externalConsumer = externalConsumer;
|
|
156
161
|
this.#accessPolicy = accessPolicy;
|
|
157
162
|
this.#logger = logger;
|
|
158
163
|
this.#diagnostics = diagnostics ?? createWeixinDiagnostics({ logger });
|
|
@@ -192,7 +197,7 @@ export class WeixinRuntime {
|
|
|
192
197
|
await this.#notifyStart();
|
|
193
198
|
this.#abortController = new AbortController();
|
|
194
199
|
const signal = this.#abortController.signal;
|
|
195
|
-
this.#bridge = new WeixinHarnessBridge({
|
|
200
|
+
this.#bridge = this.#config.consumerMode === 'external-consumer' ? null : new WeixinHarnessBridge({
|
|
196
201
|
api: this.#api,
|
|
197
202
|
baseUrl: this.#config.baseUrl,
|
|
198
203
|
token: this.#token,
|
|
@@ -276,6 +281,11 @@ export class WeixinRuntime {
|
|
|
276
281
|
this.#status.connectionError = null;
|
|
277
282
|
|
|
278
283
|
for (const message of orderWeixinMessages(response?.msgs)) {
|
|
284
|
+
if (this.#config.consumerMode === 'external-consumer') {
|
|
285
|
+
if (!this.#externalConsumer) throw weixinRefusal('consumer-unavailable');
|
|
286
|
+
await this.#externalConsumer(message, signal);
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
279
289
|
void this.#bridge.accept(message).catch((error) => {
|
|
280
290
|
if (signal.aborted) return;
|
|
281
291
|
this.#logger.error?.(
|
|
@@ -301,6 +311,42 @@ export class WeixinRuntime {
|
|
|
301
311
|
}
|
|
302
312
|
}
|
|
303
313
|
|
|
314
|
+
async qualifyReplyChecked(route, { account, signal } = {}) {
|
|
315
|
+
signal?.throwIfAborted();
|
|
316
|
+
return checkedWeixinRoute(route, account, this.#state.externalReplySource(route?.messageId));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async replyChecked(route, text, { account, signal, receipt = false, beforeSend } = {}) {
|
|
320
|
+
const checked = await this.qualifyReplyChecked(route, { account, signal });
|
|
321
|
+
if (typeof text !== 'string' || !text.trim() || [...text].length > this.#maxMessageChars)
|
|
322
|
+
throw weixinRefusal('bad-request');
|
|
323
|
+
const source = this.#state.externalReplySource(checked.messageId);
|
|
324
|
+
signal?.throwIfAborted();
|
|
325
|
+
if (beforeSend && beforeSend() !== true) throw weixinRefusal('stale-route');
|
|
326
|
+
const result = await this.#api.sendText({ baseUrl: this.#config.baseUrl, token: this.#token,
|
|
327
|
+
toUserId: checked.actorId, contextToken: source.contextToken, text, signal });
|
|
328
|
+
const clientId = result?.providerMessageIds?.[0];
|
|
329
|
+
if (typeof clientId !== 'string' || !clientId.startsWith('dsh-weixin-'))
|
|
330
|
+
throw weixinRefusal('provider-result-unknown');
|
|
331
|
+
return { sent: true, ...(receipt ? { receipt: { version: 1, messageId: clientId,
|
|
332
|
+
conversationId: checked.conversationId, identityKind: 'client-acknowledgement' } } : {}) };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async externalFileChecked(route, file, { account, signal, reply = false, beforeSend } = {}) {
|
|
336
|
+
const source = this.#state.externalReplySource(route?.messageId);
|
|
337
|
+
checkedWeixinRoute(route, account, source);
|
|
338
|
+
const assertCurrent = () => {
|
|
339
|
+
signal?.throwIfAborted();
|
|
340
|
+
checkedWeixinRoute(route, account, this.#state.externalReplySource(route.messageId));
|
|
341
|
+
if (reply && (!beforeSend || beforeSend() !== true)) throw weixinRefusal('stale-route');
|
|
342
|
+
};
|
|
343
|
+
return reply ? replyWeixinExternalFile(this.#api, {
|
|
344
|
+
baseUrl: this.#config.baseUrl, token: this.#token, toUserId: route.actorId,
|
|
345
|
+
contextToken: source.contextToken,
|
|
346
|
+
}, file, { signal, assertCurrent })
|
|
347
|
+
: readWeixinExternalFile(this.#api, source, file, { signal, assertCurrent });
|
|
348
|
+
}
|
|
349
|
+
|
|
304
350
|
async stop() {
|
|
305
351
|
const warnings = [];
|
|
306
352
|
const monitor = this.#monitor;
|