Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/checked-feishu-source.md
Original file line number Diff line number Diff line change
@@ -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.
37 changes: 30 additions & 7 deletions src/channels/feishu/external-consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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 }),
});
Expand Down
32 changes: 25 additions & 7 deletions src/channels/feishu/history-reader.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();
Expand All @@ -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;
}
Expand Down
37 changes: 21 additions & 16 deletions src/channels/feishu/multi-bot-controller.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 } = {}) {
Expand Down
Loading