Skip to content
Merged
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
578 changes: 290 additions & 288 deletions lib/index.js

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions plugin-src/host/delivery-adapter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
return coreController.approvalCardChecked(botId, route, card, options);
},
questionCardChecked: (botId, route, card, options) => {
if (channel !== 'feishu' || typeof coreController.questionCardChecked !== 'function')
throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
return coreController.questionCardChecked(botId, route, card, options);
},
historyChecked: (botId, route, query, options) => {
if (typeof coreController.historyChecked !== 'function')
throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
Expand Down
14 changes: 14 additions & 0 deletions plugin-src/host/delivery-service.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,20 @@ export class DeliveryService {
} catch (error) { throw publicOperationError(error, 'send-result-unknown'); }
}

async questionCardChecked(botId, route, card, options = {}) {
const id = botIdOf(botId);
cancellation(options.signal);
if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '') || typeof options.beforeSend !== 'function') throw deliveryError('bad-request');
const registration = await this.#checkedRegistrationFor(id);
if (registration.adapter.channel !== 'feishu' || typeof registration.adapter.questionCardChecked !== 'function') throw deliveryError('capability-unavailable');
this.#assertRegistered(registration);
try {
return await registration.adapter.questionCardChecked(id, route, card, { ...options,
signal: options.signal ? AbortSignal.any([options.signal, registration.controller.signal]) : registration.controller.signal,
beforeSend: () => { this.#assertRegistered(registration); return options.beforeSend() === true; } });
} catch (error) { throw publicOperationError(error, 'send-result-unknown'); }
}

async historyChecked(botId, route, query, options = {}) {
const id = botIdOf(botId);
cancellation(options.signal);
Expand Down
2 changes: 2 additions & 0 deletions plugin-src/host/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ export function createImHostPlugin(internals = {}) {
inboundVersion: 1,
fileVersion: 1,
approvalCardVersion: 1,
questionCardVersion: 1,
questionCardChecked: (botId, route, card, options) => deliveryService.questionCardChecked(botId, route, card, options),
approvalRuleCardVersion: 2,
pairingCardVersion: 1,
approvalCardChecked: (botId, route, card, options) => deliveryService.approvalCardChecked(botId, route, card, options),
Expand Down
20 changes: 13 additions & 7 deletions src/channels/feishu/external-cards.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { qualifyExternalReply } from './reply-context.mjs';
import { questionActionValues } from './external-questions.mjs';

const refuse = (code) => { throw Object.assign(new Error(code), { code }); };
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
Expand Down Expand Up @@ -62,7 +63,8 @@ export function normalizeExternalCardAction(event, identity) {
const appId = event?.header?.app_id ?? event?.app_id;
if (appId !== undefined && appId !== identity.appId) refuse('account-changed');
const value = event?.action?.value;
if (!['botharness/approval-v1', 'botharness/pairing-v1', 'botharness/approval-rule-v1'].includes(value?.namespace)) return null;
const question = value?.namespace === 'botharness/question-v1';
if (!question && !['botharness/approval-v1', 'botharness/pairing-v1', 'botharness/approval-rule-v1'].includes(value?.namespace)) return null;
const actorId = event?.operator?.open_id;
const messageId = event?.context?.open_message_id;
const conversationId = event?.context?.open_chat_id;
Expand All @@ -84,13 +86,13 @@ export function normalizeExternalCardAction(event, identity) {
return Object.freeze({ kind: 'pairing', version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
actorId, messageId, conversationId, requestId: value.requestId, action: value.action, ...(roleId ? { roleId } : {}) });
}
if (event.action.tag !== 'button' || !['allowed-once', 'rejected'].includes(value.action)) refuse('invalid-inbound');
if (event.action.tag !== 'button' || (!question && !['allowed-once', 'rejected'].includes(value.action))) refuse('invalid-inbound');
return Object.freeze({ version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
actorId, messageId, conversationId, requestId: value.requestId, action: value.action });
actorId, messageId, conversationId, requestId: value.requestId, ...(question ? { action: 'answer', values: questionActionValues(event) } : { action: value.action }) });
}

export async function replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend } = {}) {
const content = externalApprovalCard(card);
export async function replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend, render = externalApprovalCard } = {}) {
const content = render(card);
assertCurrent?.();
const current = await qualifyExternalReply(client, route, signal);
if (current.actorId !== route.actorId) refuse('stale-route');
Expand All @@ -107,8 +109,8 @@ export async function replyExternalApprovalCard(client, route, card, { signal, a
return { sent: true, receipt: { version: 1, messageId: result.data.message_id, conversationId: result.data.chat_id } };
}

export async function updateExternalApprovalCard(client, identity, receipt, card, { signal, assertCurrent, beforeSend } = {}) {
const content = externalApprovalCard(card);
export async function updateExternalApprovalCard(client, identity, receipt, card, { signal, assertCurrent, beforeSend, render = externalApprovalCard, privateOnly = false } = {}) {
const content = render(card);
if (!identifier(receipt?.messageId, 'om') || !identifier(receipt?.conversationId, 'oc')) refuse('bad-request');
assertCurrent?.();
const result = await client.im.v1.message.get({ path: { message_id: receipt.messageId } }, { signal });
Expand All @@ -117,6 +119,10 @@ export async function updateExternalApprovalCard(client, identity, receipt, card
((source.sender.id_type === 'app_id' && source.sender.id === identity.appId) ||
(source.sender.id_type === 'open_id' && source.sender.id === identity.botOpenId));
if (result?.code !== 0 || !ownSender || source.deleted || source.chat_id !== receipt.conversationId || source.msg_type !== 'interactive') refuse('stale-route');
if (privateOnly) {
const chat = await client.im.v1.chat.get({ path: { chat_id: receipt.conversationId } }, { signal });
if (chat?.code !== 0 || chat?.data?.chat_mode !== 'p2p') refuse('stale-route');
}
assertCurrent?.();
signal?.throwIfAborted();
if (typeof beforeSend !== 'function' || beforeSend() !== true) refuse('stale-route');
Expand Down
55 changes: 55 additions & 0 deletions src/channels/feishu/external-questions.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const text = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
const refuse = () => { throw Object.assign(new Error('bad-request'), { code: 'bad-request' }); };
const plain = (value) => String(value).replace(/[\\`*_{}[\]()<>#|!]/g, (character) => String.fromCharCode(92) + character);
export function externalQuestionCard(value) {
if (!value || !uuid.test(value.requestId ?? '') || !/^[A-F0-9]{12}$/.test(value.reference ?? '') ||
!text(value.detail, 16000) || !['pending', 'answered', 'cancelled', 'expired', 'web-required'].includes(value.status) ||
!Array.isArray(value.questions) || value.questions.length > 3 || JSON.stringify(value.questions).length > 16000) refuse();
const labels = { pending: 'Human question / Human 提问', answered: 'Answered / 已回答', cancelled: 'Cancelled / 已取消', expired: 'Expired / 已过期', 'web-required': 'Check in Web / 请在 Web 核对' };
const elements = [{ tag: 'markdown', content: plain(labels[value.status] + '\n' + value.detail) }];
if (value.status === 'pending') {
if (!value.questions.length) refuse();
const fields = value.questions.flatMap((question, index) => {
if (!text(question.id, 512) || !text(question.question, 16000) ||
question.options !== undefined && (!Array.isArray(question.options) || question.options.length > 100)) refuse();
if ([question.header, question.detail].some((value) => value !== undefined && typeof value !== 'string')) refuse();
const fields = [{ tag: 'markdown', content: plain([question.header, (index + 1) + '. ' + question.question, question.detail].filter(Boolean).join('\n')) }];
for (const option of question.options ?? []) {
if (option.description !== undefined && typeof option.description !== 'string') refuse();
if (option.description) fields.push({ tag: 'markdown', content: plain(option.label + ': ' + option.description) });
}
if (question.options?.length) fields.push({ tag: question.multiSelect === true ? 'multi_select_static' : 'select_static',
name: 'q' + index + '_choices', placeholder: { tag: 'plain_text', content: 'Choose / 选择' },
options: question.options.map((option, pick) => {
if (!text(option.label, 2000)) refuse();
return { text: { tag: 'plain_text', content: option.label }, value: String(pick) };
}) });
fields.push({ tag: 'input', name: 'q' + index + '_custom', input_type: 'multiline_text', max_length: 1000,
placeholder: { tag: 'plain_text', content: 'Or enter your answer / 或填写自己的答案' } });
return fields;
});
fields.push({ tag: 'button', name: 'answer_submit', type: 'primary_filled', form_action_type: 'submit',
text: { tag: 'plain_text', content: 'Submit answers / 提交答案' },
behaviors: [{ type: 'callback', value: { namespace: 'botharness/question-v1', requestId: value.requestId, count: value.questions.length } }] });
elements.push({ tag: 'form', name: 'questions', elements: fields });
}
return JSON.stringify({ schema: '2.0', config: { update_multi: true },
header: { title: { tag: 'plain_text', content: labels[value.status] + ' · ' + value.reference }, template: 'blue' }, body: { elements } });
}
export function questionActionValues(event) {
const count = event.action.value.count;
const form = event.action.form_value;
if (!Number.isInteger(count) || count < 1 || count > 3 || !form || typeof form !== 'object' || Array.isArray(form) || JSON.stringify(form).length > 16000) refuse();
const allowed = new Set(Array.from({ length: count }, (_, i) => ['q' + i + '_choices', 'q' + i + '_custom']).flat());
if (Object.keys(form).some((key) => !allowed.has(key))) refuse();
return Array.from({ length: count }, (_, i) => {
const selected = form['q' + i + '_choices'];
const values = selected === undefined || selected === null || selected === '' ? [] : Array.isArray(selected) ? selected : [selected];
if (values.length > 100 || values.some((value) => typeof value !== 'string' || !/^(0|[1-9][0-9]?)$/.test(value)) || new Set(values).size !== values.length) refuse();
const custom = form['q' + i + '_custom'];
if (custom !== undefined && (typeof custom !== 'string' || custom.length > 1000)) refuse();
return { selected: values.map(Number), ...(custom?.trim() ? { custom: custom.trim() } : {}) };
});
}
13 changes: 13 additions & 0 deletions src/channels/feishu/feishu-runtime.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { consumeExternalCardAction } from './external-cards.mjs';
import { reactExternalMessage } from './external-reactions.mjs';
import { createExternalNameCache, externalNames } from './external-names.mjs';
import { externalQuestionCard } from './external-questions.mjs';
import { qualifyExternalReply } from './reply-context.mjs';
import { readExternalHistory } from './history-reader.mjs';
import { externalAttachments, readExternalFile, replyExternalFile } from './external-files.mjs';
Expand Down Expand Up @@ -872,6 +873,18 @@ export class FeishuRuntime {
: replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend });
}

async questionCardChecked(identity, route, card, { signal, beforeSend, update = false } = {}) {
const client = this.#client;
const assertCurrent = () => {
signal?.throwIfAborted();
if (!client || this.#client !== client || this.#consumerMode !== 'external-consumer')
throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
};
assertCurrent();
return update ? updateExternalApprovalCard(client, identity, route, card, { signal, assertCurrent, beforeSend, render: externalQuestionCard, privateOnly: true })
: replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend, render: externalQuestionCard, privateOnly: true });
}

async historyChecked(identity, route, query, { signal } = {}) {
const client = this.#client;
if (!client || this.#consumerMode !== 'external-consumer')
Expand Down
19 changes: 18 additions & 1 deletion src/channels/feishu/multi-bot-controller.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ export class MultiBotDshFeishuController {
const account = await this.#deliveryAccount(config);
return { version: 1, botId, channel: 'feishu', account,
connected: isConnected(connectionStatus(this.#runtimes.get(botId))),
capabilities: ['reachable-conversations-checked', 'proactive-fence-checked', 'proactive-text-checked', 'proactive-receipt-checked', 'own-text-echo', 'exclusive-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked', 'approval-card-checked', 'approval-card-update-checked', 'approval-action-consumer', 'reaction-write-checked', 'source-image-checked', 'approval-rule-card-checked', 'approval-rule-all-opaque-card-checked', 'pairing-card-checked'] };
capabilities: ['question-card-checked', 'question-card-update-checked', 'question-action-consumer', 'reachable-conversations-checked', 'proactive-fence-checked', 'proactive-text-checked', 'proactive-receipt-checked', 'own-text-echo', 'exclusive-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked', 'approval-card-checked', 'approval-card-update-checked', 'approval-action-consumer', 'reaction-write-checked', 'source-image-checked', 'approval-rule-card-checked', 'approval-rule-all-opaque-card-checked', 'pairing-card-checked'] };
});
}

Expand Down Expand Up @@ -728,6 +728,23 @@ export class MultiBotDshFeishuController {
});
}

async questionCardChecked(botId, route, card, { expectedFingerprint, signal, beforeSend, update = false } = {}) {
this.#assertOpen();
return this.#withBotTransition(botId, async () => {
this.#assertOpen();
signal?.throwIfAborted();
const config = this.#requireBot(botId);
const account = await this.#deliveryAccount(config);
if (account.fingerprint !== expectedFingerprint) 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.questionCardChecked !== 'function') throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
return runtime.questionCardChecked({ appId: config.appId, botOpenId: config.botOpenId }, route, card,
{ signal: signal ? AbortSignal.any([signal, lease]) : lease, beforeSend, update });
});
}

async externalFileChecked(botId, route, value, { expectedFingerprint, signal, reply = false } = {}) {
this.#assertOpen();
return this.#withBotTransition(botId, async () => {
Expand Down
2 changes: 1 addition & 1 deletion test/channels/feishu/external-cards.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ test('exact rule preview and nonce-bound confirmation remain separate from ordin
confirmed.action.value = { namespace: 'botharness/approval-v1', requestId, action: 'confirm-exact', confirmationId };
assert.throws(() => normalizeExternalCardAction(confirmed, identity), { code: 'invalid-inbound' });
confirmed.action.value.namespace = 'botharness/question-v1';
assert.equal(normalizeExternalCardAction(confirmed, identity), null);
assert.throws(() => normalizeExternalCardAction(confirmed, identity), { code: 'bad-request' });
assert.throws(() => externalApprovalCard({ ...card, rules: ['all-opaque'] }), { code: 'bad-request' });
assert.throws(() => externalApprovalCard({ ...card, ruleConfirmation: { id: 'forged', kind: 'exact' } }), { code: 'bad-request' });
assert.equal(JSON.parse(externalApprovalCard({ ...card, ruleConfirmation: { id: confirmationId, kind: 'exact' }, status: 'executed' })).elements.length, 1);
Expand Down
Loading
Loading