fix: explain missing Feishu image permission

This commit is contained in:
xmanrui 2026-08-19 03:13:11 +08:00
parent 0e7a0931c4
commit 26558e5e71
4 changed files with 288 additions and 109 deletions

File diff suppressed because one or more lines are too long

View file

@ -1,5 +1,11 @@
import { ImagePromptError } from '../shared/image-prompt.mjs';
const FEISHU_MISSING_MESSAGE_SCOPE_CODE = 99991672;
const FEISHU_ERROR_BODY_LIMIT = 64 * 1024;
const FEISHU_ERROR_BODY_TIMEOUT_MS = 1_000;
const FEISHU_IMAGE_PERMISSION_MESSAGE =
'飞书机器人缺少图片读取权限。请在飞书开放平台为该应用添加 im:message:readonly,发布新版本并完成必要的管理员审批后,再重新发送图片。';
export function conversationKey(event) {
const chatType = event?.message?.chat_type;
if (chatType === 'p2p') {
@ -119,17 +125,98 @@ async function readBoundedStream(stream, { signal, maxBytes }) {
}
}
function providerCode(value) {
if (!value || typeof value !== 'object') return null;
const code = value.code ?? value.error?.code;
return Number.isSafeInteger(Number(code)) ? Number(code) : null;
}
async function readFeishuErrorBody(stream, signal) {
if (!stream || typeof stream[Symbol.asyncIterator] !== 'function') return null;
signal?.throwIfAborted();
const timeout = AbortSignal.timeout(FEISHU_ERROR_BODY_TIMEOUT_MS);
const readSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
const abort = () => stream.destroy?.(readSignal.reason);
readSignal.addEventListener('abort', abort, { once: true });
const chunks = [];
let size = 0;
try {
for await (const chunk of stream) {
const data = Buffer.from(chunk);
size += data.length;
if (size > FEISHU_ERROR_BODY_LIMIT) {
stream.destroy?.();
return null;
}
chunks.push(data);
}
return Buffer.concat(chunks, size).toString('utf8');
} catch {
signal?.throwIfAborted();
return null;
} finally {
readSignal.removeEventListener('abort', abort);
}
}
async function feishuProviderCode(error, signal) {
const pending = [error];
const seen = new Set();
while (pending.length > 0 && seen.size < 8) {
const value = pending.shift();
if (!value || (typeof value !== 'object' && typeof value !== 'function') || seen.has(value)) {
continue;
}
seen.add(value);
const directCode = providerCode(value);
const data = value.response?.data ?? value.data;
if (directCode === FEISHU_MISSING_MESSAGE_SCOPE_CODE) {
data?.destroy?.();
return directCode;
}
if (data && typeof data[Symbol.asyncIterator] === 'function') {
const body = await readFeishuErrorBody(data, signal);
try {
const parsedCode = providerCode(JSON.parse(body));
if (parsedCode === FEISHU_MISSING_MESSAGE_SCOPE_CODE) return parsedCode;
} catch {
// Non-JSON provider failures keep the generic image download message.
}
} else {
const dataCode = providerCode(data);
if (dataCode === FEISHU_MISSING_MESSAGE_SCOPE_CODE) return dataCode;
}
pending.push(value.cause);
}
return null;
}
async function feishuImageDownloadError(error, signal) {
if (await feishuProviderCode(error, signal) !== FEISHU_MISSING_MESSAGE_SCOPE_CODE) return error;
return new ImagePromptError(
'feishu-image-permission-required',
'Feishu image download requires the im:message:readonly tenant scope',
FEISHU_IMAGE_PERMISSION_MESSAGE,
{ cause: error },
);
}
function feishuImageSource(event, client, key) {
return {
async load({ signal, maxBytes }) {
signal?.throwIfAborted();
const resource = await client?.im?.v1?.messageResource?.get?.({
path: {
message_id: event.message.message_id,
file_key: key,
},
params: { type: 'image' },
});
let resource;
try {
resource = await client?.im?.v1?.messageResource?.get?.({
path: {
message_id: event.message.message_id,
file_key: key,
},
params: { type: 'image' },
});
} catch (error) {
throw await feishuImageDownloadError(error, signal);
}
signal?.throwIfAborted();
const size = declaredSize(resource?.headers);
if (size !== null && size > maxBytes) {

View file

@ -277,6 +277,51 @@ test('bridge downloads an inbound Feishu image once and submits structured Harne
assert.deepEqual(sent, ['看到了一张图片']);
});
test('bridge tells users to grant im:message:readonly when Feishu rejects image access', async () => {
const fixture = stateFixture([['p2p:ou_user', 'session-image-permission']]);
const sent = [];
const providerError = new Error('Request failed with status code 400');
providerError.code = 'ERR_BAD_REQUEST';
providerError.response = {
status: 400,
data: Readable.from([Buffer.from(JSON.stringify({
code: 99991672,
msg: 'secret-shaped provider detail /private/path',
}))]),
};
const client = {
im: { v1: {
messageResource: { get: async () => { throw providerError; } },
message: { create: async (request) => {
sent.push(JSON.parse(request.data.content).text);
return { code: 0, data: { message_id: 'om_permission_reply' } };
} },
} },
};
const bridge = new FeishuHarnessBridge({
client,
channel: {},
harness: {
sessionExists: async () => true,
ask: async () => assert.fail('permission failures must not reach Harness'),
},
state: fixture.state,
status: bridgeStatus(),
allowedSenderOpenIds: new Set(['ou_user']),
});
await bridge.accept(event('om_image_permission', '', {
message_type: 'image',
content: JSON.stringify({ image_key: 'img_permission' }),
}));
await bridge.waitForIdle();
assert.equal(sent.length, 1);
assert.match(sent[0], /im:message:readonly/);
assert.match(sent[0], /发布新版本/);
assert.doesNotMatch(sent[0], /99991672|HTTP 400|secret-shaped|private\/path/);
});
test('bridge sends Feishu post text and all embedded images as one structured prompt', async () => {
const fixture = stateFixture([['group:oc_post_group', 'session-post']]);
const downloaded = [];

View file

@ -132,6 +132,53 @@ test('Feishu image loading rejects declared or streamed data above the caller li
}
});
test('Feishu image loading maps the missing message scope to an actionable error', async () => {
const providerError = new Error('Request failed with status code 400');
const body = Buffer.from(JSON.stringify({
code: 99991672,
msg: 'missing required tenant scope',
}));
providerError.response = {
status: 400,
data: Readable.from([body.subarray(0, 9), body.subarray(9)]),
};
const message = extractInboundMessage({
message: {
message_id: 'om_permission',
message_type: 'image',
content: JSON.stringify({ image_key: 'img_permission' }),
},
}, { im: { v1: { messageResource: { get: async () => { throw providerError; } } } } });
await assert.rejects(message.images[0].load({ maxBytes: 1024 }), (error) => {
assert.equal(error.code, 'feishu-image-permission-required');
assert.match(error.userMessage, /im:message:readonly/);
assert.match(error.userMessage, /发布新版本/);
assert.equal(error.cause, providerError);
return true;
});
});
test('Feishu image loading leaves unrelated provider failures on the generic path', async () => {
const providerError = new Error('Request failed with status code 400');
providerError.response = {
status: 400,
data: Readable.from([Buffer.from(JSON.stringify({ code: 99991400 }))]),
};
const message = extractInboundMessage({
message: {
message_id: 'om_other_error',
message_type: 'image',
content: JSON.stringify({ image_key: 'img_other_error' }),
},
}, { im: { v1: { messageResource: { get: async () => { throw providerError; } } } } });
await assert.rejects(
message.images[0].load({ maxBytes: 1024 }),
(error) => error === providerError,
);
});
test('malformed Feishu image content does not create a downloadable image reference', () => {
assert.deepEqual(extractInboundMessage({
message: { message_type: 'image', content: '{not-json' },