From 6311581e788e8b3ab51f9b10fb459f8ea472a852 Mon Sep 17 00:00:00 2001 From: Entropy-Enthalpy <55441397+Entropy-Enthalpy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:16:10 +0800 Subject: [PATCH] fix(feishu): expose typed original message inspection to consumers --- docs/checked-feishu-source.md | 43 +++++ src/channels/feishu/external-consumer.mjs | 37 +++- src/channels/feishu/history-reader.mjs | 32 +++- src/channels/feishu/multi-bot-controller.mjs | 37 ++-- .../feishu/external-consumer.test.mjs | 178 ++++++++++++++++++ test/history-reader.test.mjs | 25 +++ 6 files changed, 322 insertions(+), 30 deletions(-) create mode 100644 docs/checked-feishu-source.md diff --git a/docs/checked-feishu-source.md b/docs/checked-feishu-source.md new file mode 100644 index 000000000..19739b44a --- /dev/null +++ b/docs/checked-feishu-source.md @@ -0,0 +1,43 @@ +# Checked original Feishu message + +An exclusive Feishu/Lark consumer can inspect an original Human group-text +message before accepting it: + +```js +const source = await ctx.dshIm.historyChecked( + botId, + event.reply, + { scope: 'message', limit: 1 }, + { expectedFingerprint: event.fingerprint, signal }, +); +``` + +This uses the existing `history-text-checked` capability and current consumer +lease. It performs one native message GET with `user_id_type: 'open_id'` and no +history-list request. The result has `scope: 'message'`, +`coverage: 'provider-verified-source'`, `source`, and `events: [source]`. +Pagination and nearby-history options are rejected for this scope. + +The provider checks the message, conversation, actor and thread/reply identities +against the original route. Edited messages are rejected as `stale-route`. +Missing edit status or unsupported source content returns `source-unavailable`. +The current account, runtime and consumer lease are checked across the read, +including a read made inside an inbound acceptance callback. + +The [native GET contract](https://open.feishu.cn/document/server-docs/im-v1/message/get.md) +returns Human mention IDs as `open_id` and Bot mention IDs as `app_id` when +`user_id_type` is specified. Normalized mentions preserve that namespace in +`idType`, alongside their `id` and placeholder `key`. Bot `app_id` mentions have +`kind: 'bot'`. A mention of the receiving application matches its verified +application ID. An `open_id` from another receiving application's view is not +used as an application ID. + +Live inbound events preserve the authenticated application ID and an explicitly +provided tenant ID. Mention names and typed metadata remain optional. Missing +tenant data in a GET response is not filled from another event or a cached +account. The consumer remains responsible for relating the returned source to +its accepted event and for any user authorization based on that source. + +Existing `group`, `thread`, and `nearby` history scopes keep their pagination and +Human-text coverage. List requests use the native list parameters, without the +GET-specific `user_id_type` option. diff --git a/src/channels/feishu/external-consumer.mjs b/src/channels/feishu/external-consumer.mjs index 1f77643ba..672f1a929 100644 --- a/src/channels/feishu/external-consumer.mjs +++ b/src/channels/feishu/external-consumer.mjs @@ -17,7 +17,15 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr const conversationId = identifier(message?.chat_id); const eventId = identifier(event?.event_id ?? event?.header?.event_id); const eventApp = event?.app_id ?? event?.header?.app_id; - if (eventApp !== undefined && eventApp !== appId) throw refusal('account-changed'); + if (eventApp !== undefined && eventApp !== appId + || event?.header?.app_id !== undefined && event.header.app_id !== appId) throw refusal('account-changed'); + const tenant = event?.tenant_key ?? event?.header?.tenant_key; + const tenantId = identifier(tenant); + if (tenant !== undefined && !tenantId + || event?.tenant_key !== undefined && event?.header?.tenant_key !== undefined + && event.tenant_key !== event.header.tenant_key + || tenantId && event?.sender?.tenant_key !== undefined && event.sender.tenant_key !== tenantId) + throw refusal('invalid-inbound'); const botSender = isBotSenderType(event?.sender); if (botSender && (message?.chat_type !== 'group' || !identifier(botOpenId) || !actorId || actorId === botOpenId || event?.sender?.sender_id?.app_id === appId)) return null; @@ -27,13 +35,27 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr if (message.mentions !== undefined && (!Array.isArray(message.mentions) || message.mentions.length > 100)) throw refusal('invalid-inbound'); const mentions = Object.freeze((message.mentions ?? []).map(mention => { - const id = identifier(mention?.id?.open_id ?? mention?.open_id); + const idType = mention?.id_type ?? 'open_id'; + const id = identifier(idType === 'app_id' ? mention?.id?.app_id + : mention?.id?.open_id ?? mention?.open_id); const key = identifier(mention?.key); - if (!id || !key) throw refusal('invalid-inbound'); + if (!id || !key || !['open_id', 'app_id'].includes(idType)) + throw refusal('invalid-inbound'); const name = identifier(mention?.name); - return Object.freeze({ id, key, ...(name ? { name } : {}) }); + const mentionTenant = identifier(mention?.tenant_key); + const type = mention?.mentioned_type; + if (mention?.tenant_key !== undefined && !mentionTenant + || type !== undefined && !identifier(type) + || idType === 'app_id' && type === 'user') throw refusal('invalid-inbound'); + return Object.freeze({ id, key, ...(name ? { name } : {}), + ...(mention?.id_type === undefined ? {} : { idType }), + ...(mentionTenant ? { tenantId: mentionTenant } : {}), + ...(type === undefined ? {} : { mentionedType: type }), + ...(idType === 'app_id' ? { kind: 'bot' } + : ['user', 'bot', 'app'].includes(type) ? { kind: type === 'user' ? 'user' : 'bot' } : {}) }); })); - if (botSender && !mentions.some(mention => mention.id === botOpenId)) return null; + const mentionedAccount = mentions.some(mention => mention.id === (mention.idType === 'app_id' ? appId : botOpenId)); + if (botSender && !mentionedAccount) return null; if (!actorId || !messageId || !conversationId || !eventId || !/^[a-f0-9]{64}$/.test(fingerprint ?? '')) throw refusal('invalid-inbound'); let text; @@ -50,11 +72,12 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr ...(identifier(message.parent_id) ? { parentId: message.parent_id } : {}), }); return Object.freeze({ - version: 1, channel: 'feishu', botId, fingerprint, eventId, messageId, + version: 1, channel: 'feishu', botId, fingerprint, appId, eventId, messageId, + ...(tenantId ? { tenantId } : {}), actor: Object.freeze({ kind: botSender ? 'bot' : 'user', id: actorId, ...(identifier(event.sender.sender_name) ? { name: event.sender.sender_name } : {}) }), conversation: Object.freeze({ kind: message.chat_type === 'group' ? 'group' : 'dm', id: conversationId }), - mentions, mentionedAccount: mentions.some(mention => mention.id === botOpenId), + mentions, mentionedAccount, at: timestamp.toISOString(), text, reply: route, replay: Object.freeze({ kind: 'provider-redelivery', resumeCursor: false, gapPossible: true }), }); diff --git a/src/channels/feishu/history-reader.mjs b/src/channels/feishu/history-reader.mjs index 5a22468ee..19a01da4e 100644 --- a/src/channels/feishu/history-reader.mjs +++ b/src/channels/feishu/history-reader.mjs @@ -15,14 +15,16 @@ function check(response) { // Lark has Chat/time-range listing and Thread listing, not a native around-message API. export async function readExternalHistory(client, identity, route, query, signal) { if (!route || !identifier(route.messageId) || !identifier(route.conversationId) - || !identifier(route.actorId) || ['threadId', 'rootId', 'parentId'].some(key => route[key] !== undefined && !identifier(route[key])) || !['group', 'nearby', 'thread'].includes(query?.scope) + || !identifier(route.actorId) || ['threadId', 'rootId', 'parentId'].some(key => route[key] !== undefined && !identifier(route[key])) || !['message', 'group', 'nearby', 'thread'].includes(query?.scope) || !Number.isInteger(query.limit) || query.limit < 1 || query.limit > 20 || (query.cursor !== undefined && (typeof query.cursor !== 'string' || !query.cursor || query.cursor.length > 4096))) refuse('bad-request'); + if (query.scope === 'message' && (query.limit !== 1 || query.cursor !== undefined + || query.beforeCount !== undefined || query.afterCount !== undefined)) refuse('bad-request'); if (query.scope === 'nearby' && [query.beforeCount ?? 10, query.afterCount ?? 5] .some(value => !Number.isInteger(value) || value < 0 || value > 20)) refuse('bad-request'); signal?.throwIfAborted(); - const reference = await client.im.v1.message.get({ path: { message_id: route.messageId }, params: { with_sender_name: true } }, { signal }); + const reference = await client.im.v1.message.get({ path: { message_id: route.messageId }, params: { with_sender_name: true, user_id_type: 'open_id' } }, { signal }); signal?.throwIfAborted(); check(reference); const source = (Array.isArray(reference?.data?.items) ? reference.data.items : []).find(item => item?.message_id === route.messageId); @@ -35,6 +37,26 @@ export async function readExternalHistory(client, identity, route, query, signal signal?.throwIfAborted(); const seconds = Math.floor(Number(source.create_time) / 1000); if (!Number.isFinite(seconds) || seconds <= 0) refuse('stale-route'); + // Explicit user_id_type preserves Human open_id and returns Bot app_id. + // https://open.feishu.cn/document/server-docs/im-v1/message/get.md + // Bot open_id equality across receiving apps is not an identity contract. + const normalize = item => normalizeExternalText({ event_id: `history:${item.message_id}`, + sender: { sender_type: 'user', sender_id: { open_id: item.sender.id }, sender_name: item.sender.sender_name, + ...(item.sender.tenant_key === undefined ? {} : { tenant_key: item.sender.tenant_key }) }, + message: { ...item, chat_type: 'group', message_type: item.msg_type, content: item.body?.content, + mentions: (item.mentions ?? []).map(mention => ({ ...mention, + id: { [mention?.id_type === 'app_id' ? 'app_id' : 'open_id']: mention?.id } })) }, + }, identity); + if (query.scope === 'message') { + if (source.updated === true) refuse('stale-route'); + if (source.updated !== false) refuse('source-unavailable'); + let anchor; + try { anchor = normalize(source); } + catch (error) { if (error?.code !== 'invalid-inbound') throw error; refuse('source-unavailable'); } + if (!anchor) refuse('source-unavailable'); + return { version: 1, scope: 'message', source: anchor, events: [anchor], omitted: 0, + hasMore: false, coverage: 'provider-verified-source' }; + } const readPage = async params => { const response = await client.im.v1.message.list({ params }, { signal }); signal?.throwIfAborted(); @@ -51,11 +73,7 @@ export async function readExternalHistory(client, identity, route, query, signal || item.sender?.id_type !== 'open_id') { ++omitted; continue; } if (item.mentions !== undefined && (!Array.isArray(item.mentions) || item.mentions.length > 100)) { ++omitted; continue; } let event; - try { event = normalizeExternalText({ event_id: `history:${item.message_id}`, - sender: { sender_type: 'user', sender_id: { open_id: item.sender.id }, sender_name: item.sender.sender_name }, - message: { ...item, chat_type: 'group', message_type: item.msg_type, content: item.body?.content, - mentions: (item.mentions ?? []).map(mention => ({ ...mention, id: { open_id: mention?.id } })) }, - }, identity); } catch (error) { + try { event = normalize(item); } catch (error) { if (error?.code !== 'invalid-inbound') throw error; ++omitted; continue; } diff --git a/src/channels/feishu/multi-bot-controller.mjs b/src/channels/feishu/multi-bot-controller.mjs index edadd7714..cc851f0ac 100644 --- a/src/channels/feishu/multi-bot-controller.mjs +++ b/src/channels/feishu/multi-bot-controller.mjs @@ -633,27 +633,32 @@ export class MultiBotDshFeishuController { async historyChecked(botId, route, query, { expectedFingerprint, signal } = {}) { this.#assertOpen('capability-unavailable'); - return this.#withBotTransition(botId, async () => { + // Read-only inspection can run inside the external consumer's acceptance. + // Capture its current owner rather than queue behind that same callback. + const config = this.#requireBot(botId), runtime = this.#runtimes.get(botId); + const original = configuredBotFingerprint(config); + const assertCurrent = () => { this.#assertOpen('capability-unavailable'); - signal?.throwIfAborted(); - const config = this.#requireBot(botId); - const account = await this.#deliveryAccount(config); - this.#assertOpen('capability-unavailable'); - signal?.throwIfAborted(); - if (account.fingerprint !== expectedFingerprint) + if (this.#runtimes.get(botId) !== runtime + || configuredBotFingerprint(this.#requireBot(botId)) !== original) throw Object.assign(new Error('account-changed'), { code: 'account-changed' }); - const runtime = this.#runtimes.get(botId); if (config.consumerMode !== 'external-consumer' || !isConnected(connectionStatus(runtime)) || typeof runtime.historyChecked !== 'function') throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' }); - const leaseSignal = this.#inboundConsumers.signalFor(botId, expectedFingerprint); - const readSignal = signal ? AbortSignal.any([signal, leaseSignal]) : leaseSignal; - const result = await runtime.historyChecked({ botId, appId: config.appId, - botOpenId: config.botOpenId, fingerprint: account.fingerprint }, route, query, { signal: readSignal }); - this.#assertOpen('capability-unavailable'); - readSignal.throwIfAborted(); - return result; - }); + }; + signal?.throwIfAborted(); + const account = await this.#deliveryAccount(config); + assertCurrent(); + signal?.throwIfAborted(); + if (account.fingerprint !== expectedFingerprint) + throw Object.assign(new Error('account-changed'), { code: 'account-changed' }); + const leaseSignal = this.#inboundConsumers.signalFor(botId, expectedFingerprint); + const readSignal = signal ? AbortSignal.any([signal, leaseSignal]) : leaseSignal; + const result = await runtime.historyChecked({ botId, appId: config.appId, + botOpenId: config.botOpenId, fingerprint: account.fingerprint }, route, query, { signal: readSignal }); + assertCurrent(); + readSignal.throwIfAborted(); + return result; } async qualifyReplyChecked(botId, route, { expectedFingerprint, signal } = {}) { diff --git a/test/channels/feishu/external-consumer.test.mjs b/test/channels/feishu/external-consumer.test.mjs index 0a7babc7f..c4cb44c46 100644 --- a/test/channels/feishu/external-consumer.test.mjs +++ b/test/channels/feishu/external-consumer.test.mjs @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { createServer } from 'node:http'; import { normalizeExternalText, ExclusiveInboundConsumers } from '../../../src/channels/feishu/external-consumer.mjs'; const fingerprint = 'a'.repeat(64); @@ -128,6 +129,39 @@ test('group evidence requires authenticated account identity and valid mention a assert.throws(() => normalized(input), { code: 'invalid-inbound' }); }); +test('preserves the platform tenant and complete typed mentions without treating message text as identity', () => { + const input = event(); + input.tenant_key = 'tenant-current'; + input.sender.tenant_key = 'tenant-current'; + input.message.mentions = [ + { key: '@_user_1', id: { open_id: 'bot-open-id' }, tenant_key: 'tenant-current', mentioned_type: 'app' }, + { key: '@_user_2', id: { open_id: 'other-bot' }, tenant_key: 'tenant-current', mentioned_type: 'bot' }, + { key: '@_user_3', id: { open_id: 'human' }, tenant_key: 'tenant-current', mentioned_type: 'user' }, + ]; + const result = normalized(input); + assert.equal(result.appId, 'app'); + assert.equal(result.tenantId, 'tenant-current'); + assert.deepEqual(result.mentions.map(value => [value.id, value.tenantId, value.kind]), [ + ['bot-open-id', 'tenant-current', 'bot'], ['other-bot', 'tenant-current', 'bot'], ['human', 'tenant-current', 'user'], + ]); + assert.throws(() => normalized({ ...input, sender: { ...input.sender, tenant_key: 'other' } }), { code: 'invalid-inbound' }); + assert.throws(() => normalized({ ...input, header: { tenant_key: 'other' } }), { code: 'invalid-inbound' }); + assert.throws(() => normalized({ ...input, message: { ...input.message, + mentions: [{ key: '@_user_1', id: { open_id: 'other-bot' }, id_type: 'user_id' }] } }), { code: 'invalid-inbound' }); + const future = normalized({ ...input, message: { ...input.message, + mentions: [{ key: '@_user_1', id: { open_id: 'other-bot' }, mentioned_type: 'future-type' }] } }); + assert.equal(future.mentions[0].mentionedType, 'future-type'); + assert.equal(future.mentions[0].kind, undefined); + assert.throws(() => normalized({ ...input, message: { ...input.message, + mentions: [{ key: '@_user_1', id: { open_id: 'other-bot' }, mentioned_type: 1 }] } }), { code: 'invalid-inbound' }); + const ordinary = event(); + ordinary.sender.tenant_key = 'sender-only'; + ordinary.message.content = JSON.stringify({ text: '@other-bot tenant-current' }); + ordinary.message.mentions = []; + assert.equal(normalized(ordinary).tenantId, undefined); + assert.deepEqual(normalized(ordinary).mentions, []); +}); + test('file metadata is explicitly negotiated while legacy text consumers retain their version 1 envelope', () => { const consumers = new ExclusiveInboundConsumers(); @@ -155,3 +189,147 @@ test('own app echo is opt-in, authenticated separately, and never admitted as Hu assert.equal(events, 0); assert.equal(echoes, 1); dispose(); await assert.rejects(consumers.accept('own', echo, undefined, true), { code: 'consumer-unavailable' }); }); + +test('typed source inspection works inside first consumer acceptance through the official SDK', { timeout: 5000 }, async () => { + const lark = await import('@larksuiteoapi/node-sdk'); + const { verifyFeishuApp } = await import('../../../src/channels/feishu/feishu-app.mjs'); + const { FeishuRuntime } = await import('../../../src/channels/feishu/feishu-runtime.mjs'); + const { MultiBotDshFeishuController } = await import('../../../src/channels/feishu/multi-bot-controller.mjs'); + const { createDeliveryAdapter } = await import('../../../plugin-src/host/delivery-adapter.mjs'); + const { createDeliveryService } = await import('../../../plugin-src/host/delivery-service.mjs'); + const configs = ['a', 'b'].map(suffix => ({ id: `account_${suffix}`, appId: `cli_${suffix}`, + botOpenId: `ou_bot_${suffix}`, domain: 'feishu', secretRef: suffix, ownerOpenIds: ['*'], consumerMode: 'external-consumer' })); + const requests = []; + let changed = false; + const mentions = configs.map((config, index) => ({ key: `@_user_${index + 1}`, id: { open_id: config.botOpenId }, + tenant_key: 'tenant-current', mentioned_type: 'bot', name: 'Research Bot' })); + mentions.push({ key: '@_user_3', id: { open_id: 'ou-human' }, tenant_key: 'tenant-current', mentioned_type: 'user', name: 'Researcher' }); + const original = { message_id: 'om-original', chat_id: 'oc-original', chat_type: 'group', message_type: 'text', + content: JSON.stringify({ text: '@_user_1 @_user_2 review this result' }), mentions, create_time: '1790787600000' }; + const apiMessage = { message_id: original.message_id, chat_id: original.chat_id, msg_type: 'text', updated: false, + create_time: original.create_time, body: { content: original.content }, + sender: { sender_type: 'user', id_type: 'open_id', id: 'ou-requester', sender_name: 'Researcher' }, + mentions: mentions.map(({ mentioned_type: _type, ...mention }, index) => ({ ...mention, + id: configs[index]?.appId ?? mention.id.open_id, id_type: configs[index] ? 'app_id' : 'open_id' })) }; + const server = createServer(async (request, response) => { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : undefined; + const path = new URL(request.url, 'http://localhost').pathname; + requests.push({ path, method: request.method }); + let result; + if (path === '/open-apis/auth/v3/tenant_access_token/internal') { + assert.equal(body.app_secret, 'local-fixture-secret'); + assert.ok(configs.some(config => config.appId === body.app_id)); + result = { code: 0, tenant_access_token: `local-token-${body.app_id}`, expire: 7200 }; + } else { + const config = configs.find(row => request.headers.authorization === `Bearer local-token-${row.appId}`); + assert.ok(config, 'The SDK and verifier must authenticate their official reads'); + if (path === '/open-apis/bot/v3/info/') result = { code: 0, + bot: { app_name: 'Research Bot', open_id: changed && config.id === 'account_b' ? 'ou-replaced' : config.botOpenId, activate_status: 1 } }; + else if (path === '/open-apis/im/v1/messages/om-original') { + assert.equal(new URL(request.url, 'http://localhost').searchParams.get('user_id_type'), 'open_id'); + result = { code: 0, data: { items: [{ ...apiMessage, + sender: { ...apiMessage.sender, id: `ou-requester-${config.appId}` } }], has_more: false } }; + } + else if (path === '/open-apis/im/v1/chats/oc-original') result = { code: 0, data: { name: 'Research discussion' } }; + else throw new Error(`Unexpected official operation ${request.method} ${path}`); + } + response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(result)); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const origin = `http://127.0.0.1:${server.address().port}`; + const httpInstance = { async request(options) { + const official = new URL(options.url); + assert.equal(official.origin, 'https://open.feishu.cn'); + const target = new URL(official.pathname, origin); + for (const [key, value] of Object.entries(options.params ?? {})) target.searchParams.set(key, String(value)); + const response = await fetch(target, { method: options.method, headers: options.headers, signal: options.signal, + ...(options.data === undefined || ['GET', 'HEAD'].includes(String(options.method).toUpperCase()) + ? {} : { body: JSON.stringify(options.data) }) }); + return response.json(); + }, post(url, data, options) { return this.request({ ...options, method: 'POST', url, data }); }, + get(url, options) { return this.request({ ...options, method: 'GET', url }); } }; + const dispatchers = new Map(), firstEvents = []; + let inspectOnStart = false; + const envelope = config => ({ schema: '2.0', header: { event_type: 'im.message.receive_v1', + event_id: `event-${config.id}`, app_id: config.appId, tenant_key: 'tenant-current' }, + event: { sender: { sender_type: 'user', sender_id: { open_id: `ou-requester-${config.appId}` }, sender_name: 'Researcher', + tenant_key: 'tenant-current' }, message: { ...original, mentions: mentions.map((mention, index) => ({ ...mention, + id: { open_id: configs[index] && configs[index].appId !== config.appId + ? `ou-bot-other-view-${config.appId}` : mention.id.open_id } })) } } }); + class WSClient { + constructor(options) { this.options = options; } + async start({ eventDispatcher }) { + dispatchers.set(this.options.appId, eventDispatcher); this.options.onReady(); + // The first authenticated platform callback arrives as soon as WS is ready. + if (inspectOnStart) { + const first = eventDispatcher.invoke(envelope(configs.find(row => row.appId === this.options.appId))); + firstEvents.push(first); void first.catch(() => undefined); + } + } + getConnectionStatus() { return { state: 'connected' }; } + close() {} + } + const logger = { info() {}, warn() {}, error() {}, debug() {} }; + const controller = new MultiBotDshFeishuController({ registerApp: async () => {}, logger, + verifyApp: options => verifyFeishuApp({ ...options, httpInstance }), + credentials: { resolve: async () => ({ value: 'local-fixture-secret' }) }, + configStore: { list: () => structuredClone(configs), getBot: id => structuredClone(configs.find(row => row.id === id)), + saveBot: async value => { Object.assign(configs.find(row => row.id === value.id), value); return structuredClone(value); } }, + createRuntime: async ({ config, appSecret, acceptExternal }) => new FeishuRuntime({ + lark: { ...lark, defaultHttpInstance: httpInstance, WSClient }, botId: config.id, + appId: config.appId, botOpenId: config.botOpenId, appSecret, domain: config.domain, + ownerOpenIds: ['*'], consumerMode: 'external-consumer', acceptExternal, + harness: { ensureRunning: async () => {} }, state: {}, slashCommands: false, logger, + }), + }); + const service = createDeliveryService(); + const disposeAdapter = service.registerAdapter(createDeliveryAdapter({ channel: 'feishu', coreController: controller, + workspaces: { has: id => configs.some(row => row.id === id) }, stateFor: async () => ({}) })); + const received = [], sources = []; + const consumers = []; + try { + await controller.initialize(); + inspectOnStart = true; + for (const config of configs) { + const account = await service.describeBot(config.id); + consumers.push(await service.consumeInbound(config.id, { expectedFingerprint: account.account.fingerprint, + onEvent: async value => { + received.push(value); + sources.push(await service.historyChecked(config.id, value.reply, { scope: 'message', limit: 1 }, + { expectedFingerprint: account.account.fingerprint })); + return { accepted: true }; + } })); + await firstEvents.at(-1); + const receiving = await service.describeBot(config.id); + assert.equal(receiving.connected, true); + const event = received.at(-1); + assert.equal(event.tenantId, 'tenant-current'); + assert.equal(event.messageId, original.message_id); + assert.equal(event.conversation.id, original.chat_id); + assert.equal(event.fingerprint, account.account.fingerprint); + assert.equal(event.mentionedAccount, true); + assert.ok(event.mentions.some(mention => mention.id === `ou-bot-other-view-${config.appId}`)); + const history = sources.at(-1); + assert.equal(history.source, history.events[0]); + assert.equal(history.source.messageId, event.messageId); + assert.equal(history.source.text, event.text); + assert.equal(history.events[0].tenantId, undefined); + assert.deepEqual(history.events[0].mentions.filter(mention => mention.idType === 'app_id').map(mention => mention.id), + configs.map(row => row.appId)); + assert.equal(history.events[0].mentions.find(mention => mention.idType === 'open_id').id, 'ou-human'); + assert.equal(history.events[0].mentionedAccount, true); + } + assert.equal(received.length, 2); + assert.ok(requests.some(row => row.path === '/open-apis/bot/v3/info/')); + assert.ok(requests.some(row => row.path === '/open-apis/im/v1/messages/om-original')); + assert.equal(requests.some(row => row.path === '/open-apis/im/v1/messages'), false); + assert.ok(requests.every(row => row.method === 'GET' || row.path === '/open-apis/auth/v3/tenant_access_token/internal')); + changed = true; + await assert.rejects(service.describeBot('account_b'), { code: 'account-changed' }); + } finally { + for (const dispose of consumers) dispose(); + disposeAdapter(); await controller.close(); + server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/test/history-reader.test.mjs b/test/history-reader.test.mjs index fe3bcf200..dc2d05dc5 100644 --- a/test/history-reader.test.mjs +++ b/test/history-reader.test.mjs @@ -49,3 +49,28 @@ test('requests server names and preserves sender / mention IDs without guessing assert.deepEqual(page.events[0].mentions,[{id:'ou-bot',key:'@_user_1',name:'QA Bot'}]); assert.deepEqual(page.events[1].actor,{kind:'user',id:'ou-human'}); }); + +test('keeps checked history in its actual ID namespace and never invents an absent tenant', async () => { + const invalid = {...item('om-anchor'), mentions:[{key:'@_user_1',id:'someone',id_type:'user_id'}]}; + const valid = {...item('om-anchor'), updated:false, mentions:[{key:'@_user_1',id:'cli-1',id_type:'app_id', + tenant_key:'tenant-current'}, {key:'@_user_2',id:'ou-human',id_type:'open_id',tenant_key:'tenant-current'}]}; + const bot = client(); + bot.im.v1.message.get = async () => ({code:0,data:{items:[valid]}}); + const page = await readExternalHistory(bot,identity,route,{scope:'message',limit:1}); + assert.equal(page.omitted,0); + assert.equal(page.events.length,1); + assert.equal(bot.calls.length,0); + assert.equal(page.coverage,'provider-verified-source'); + assert.equal(page.source,page.events[0]); + assert.equal(page.events[0].tenantId,undefined); + assert.equal(page.events[0].appId,identity.appId); + assert.deepEqual(page.events[0].mentions,[{id:'cli-1',idType:'app_id',key:'@_user_1',tenantId:'tenant-current',kind:'bot'}, + {id:'ou-human',idType:'open_id',key:'@_user_2',tenantId:'tenant-current'}]); + assert.equal(page.events[0].mentionedAccount,true); + bot.im.v1.message.get = async () => ({code:0,data:{items:[{...valid,updated:true}]}}); + await assert.rejects(readExternalHistory(bot,identity,route,{scope:'message',limit:1}),{code:'stale-route'}); + bot.im.v1.message.get = async () => ({code:0,data:{items:[{...valid,updated:undefined}]}}); + await assert.rejects(readExternalHistory(bot,identity,route,{scope:'message',limit:1}),{code:'source-unavailable'}); + bot.im.v1.message.get = async () => ({code:0,data:{items:[invalid]}}); + await assert.rejects(readExternalHistory(bot,identity,route,{scope:'message',limit:1}),{code:'source-unavailable'}); +});