@botharness/im-provider 4.32.0-botharness.4 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botharness/im-provider",
3
- "version": "4.32.0-botharness.4",
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": "589e5507d47ab21de5b39c776a598452744a5368"
179
+ "upstreamSource": "8852e87f29813fc8626c039e49e278c2383c47aa"
180
180
  }
181
181
  }
@@ -19,24 +19,40 @@ export function pairedWeixinAccount(config, token) {
19
19
  fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') });
20
20
  }
21
21
 
22
- /** First tracer is paired-owner plain text only. No group, mention, or thread is invented. */
23
- export function normalizeWeixinExternalText(message, { botId, account }) {
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
24
  if (message?.message_type !== 1 || message.from_user_id !== account.ownerUserId) return null;
25
25
  if (message.to_user_id !== account.accountId) throw weixinRefusal('account-changed');
26
26
  if (!Array.isArray(message.item_list) || !message.item_list.length
27
- || message.item_list.some(item => item?.type !== 1)) return null;
27
+ || message.item_list.some(item => item?.type !== 1 && !(sourceFiles && item?.type === 4))) return null;
28
28
  const messageId = weixinMessageId(message);
29
- const text = extractWeixinText(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}]` : '');
30
35
  const time = typeof message.create_time_ms === 'string' ? Number(message.create_time_ms) : message.create_time_ms;
31
36
  if (!messageId || !/^\d+$/.test(messageId) || !text?.trim() || text.length > 16000
32
37
  || !Number.isSafeInteger(time) || time <= 0 || !continuation(message.context_token)) throw weixinRefusal('invalid-inbound');
33
38
  const at = new Date(time);
34
39
  if (!Number.isFinite(at.getTime())) throw weixinRefusal('invalid-inbound');
35
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;
36
52
  return Object.freeze({ version: 1, channel: 'weixin', botId, fingerprint: account.fingerprint,
37
53
  eventId: messageId, messageId, actor: Object.freeze({ kind: 'user', id: account.ownerUserId }),
38
54
  conversation: Object.freeze({ kind: 'dm', id: conversationId }), mentions: Object.freeze([]),
39
- mentionedAccount: false, at: at.toISOString(), text,
55
+ mentionedAccount: false, at: at.toISOString(), text, ...(attachments ? { attachments } : {}),
40
56
  reply: Object.freeze({ messageId, conversationId, actorId: account.ownerUserId }),
41
57
  replay: Object.freeze({ kind: 'provider-redelivery', resumeCursor: false, gapPossible: true }) });
42
58
  }
@@ -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
+ }
@@ -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
- return Buffer.from(await response.arrayBuffer());
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
- return decryptWeixinImage(ciphertext, key);
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
  }
@@ -527,6 +549,7 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
527
549
  contextToken,
528
550
  runId,
529
551
  signal,
552
+ beforeSend,
530
553
  }, { mediaType, createItem }) {
531
554
  const recipient = nonEmptyString(toUserId);
532
555
  if (!recipient || !file || typeof file !== 'object'
@@ -600,6 +623,8 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
600
623
  aes_key: Buffer.from(aesKey.toString('hex')).toString('base64'),
601
624
  encrypt_type: 1,
602
625
  };
626
+ await beforeSend?.();
627
+ signal?.throwIfAborted();
603
628
  let response;
604
629
  try {
605
630
  response = await requestJson(fetchImpl, {
@@ -1,5 +1,6 @@
1
1
  import { ExclusiveInboundConsumers } from '../shared/exclusive-inbound-consumers.mjs';
2
2
  import { pairedWeixinAccount, normalizeWeixinExternalText, weixinRefusal } from './external-consumer.mjs';
3
+ import { privateWeixinFile } from './external-files.mjs';
3
4
  import { randomUUID } from 'node:crypto';
4
5
  import { createWeixinDiagnostics, knownWeixinErrorCode, weixinStageError } from './connection-error.mjs';
5
6
 
@@ -162,18 +163,18 @@ export class WeixinController {
162
163
  return { version: 1, botId, channel: 'weixin', account,
163
164
  connected: this.#runtimes.get(botId)?.status?.ready === true,
164
165
  capabilities: ['proactive-text-checked', 'exclusive-text-consumer', 'reply-text-checked',
165
- 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked'] };
166
+ 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked',
167
+ 'source-file-checked', 'reply-file-checked', 'reply-file-fence-checked'] };
166
168
  });
167
169
  }
168
170
 
169
171
  async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false } = {}) {
170
172
  return this.#withBotTransition(botId, async () => {
171
- if (sourceFiles) throw weixinRefusal('capability-unavailable');
172
173
  const config = this.#configStore.get(botId);
173
174
  if (!config) throw weixinRefusal('unknown-bot');
174
175
  const account = await this.#deliveryAccount(config, signal);
175
176
  if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
176
- const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal });
177
+ const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceFiles });
177
178
  try {
178
179
  const saved = await this.#configStore.save({ ...config, consumerMode: 'external-consumer' });
179
180
  await this.#startRuntime(saved, await this.#resolveToken(saved.tokenRef));
@@ -208,6 +209,13 @@ export class WeixinController {
208
209
  });
209
210
  }
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
+
211
219
  async startProvisioning() {
212
220
  if (this.#closed) throw new Error('dsh-weixin controller is closed');
213
221
  if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
@@ -666,11 +674,13 @@ export class WeixinController {
666
674
  const current = await this.#deliveryAccount(this.#configStore.get(config.botId), signal);
667
675
  if (current.fingerprint !== account.fingerprint) throw weixinRefusal('account-changed');
668
676
  this.#inboundConsumers.signalFor(config.botId, account.fingerprint).throwIfAborted();
669
- const event = normalizeWeixinExternalText(message, { botId: config.botId, account });
677
+ const event = normalizeWeixinExternalText(message, { botId: config.botId, account,
678
+ sourceFiles: this.#inboundConsumers.acceptsFiles(config.botId) });
670
679
  if (!event) return { accepted: true, ignored: true };
671
680
  await state.rememberExternalReplySource({ messageId: event.messageId, actorId: event.actor.id,
672
681
  fingerprint: account.fingerprint, contextToken: message.context_token,
673
- expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000 });
682
+ expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
683
+ ...(event.attachments?.length ? { file: privateWeixinFile(message, event) } : {}) });
674
684
  return this.#inboundConsumers.accept(config.botId, event, signal);
675
685
  } });
676
686
  } catch (error) {
@@ -1,4 +1,5 @@
1
1
  import { checkedWeixinRoute, weixinRefusal } from './external-consumer.mjs';
2
+ import { readWeixinExternalFile, replyWeixinExternalFile } from './external-files.mjs';
2
3
  import { createWeixinDiagnostics } from './connection-error.mjs';
3
4
  import { DEFAULT_WEIXIN_MAX_MESSAGE_CHARS, WeixinApiError, rejectedProviderResponse } from './weixin-api.mjs';
4
5
  import {
@@ -331,6 +332,21 @@ export class WeixinRuntime {
331
332
  conversationId: checked.conversationId, identityKind: 'client-acknowledgement' } } : {}) };
332
333
  }
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
+
334
350
  async stop() {
335
351
  const warnings = [];
336
352
  const monitor = this.#monitor;