Files
tap/tests/feishu-fetch.fixture.mjs
T

29 lines
1.9 KiB
JavaScript

// Only loaded by the isolated test process via --import. Never imported by application code.
import { appendFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
if (!process.env.DATA_DIR?.includes('demand-feishu-http-')) throw new Error('Feishu fixture requires an isolated test directory.');
const original = globalThis.fetch;
globalThis.fetch = async (input, init = {}) => {
const url = String(input);
if (url === 'https://open.feishu.cn/open-apis/authen/v2/oauth/token') {
const data = JSON.parse(init.body);
const [identity, challenge] = data.code.split('.');
if (init.headers['Content-Type'] !== 'application/json' || data.client_id !== 'cli_http_test' || data.client_secret !== 'http-test-secret' || !data.code_verifier || !data.redirect_uri.endsWith('/api/auth/feishu/callback')) throw new Error('Invalid OAuth token exchange.');
if (createHash('sha256').update(data.code_verifier).digest('base64url') !== challenge) return Response.json({ code: 20049 }, { status: 400 });
return Response.json({ code: 0, access_token: 'mock-' + identity });
}
if (url === 'https://open.feishu.cn/open-apis/authen/v1/user_info') {
const identity = init.headers.Authorization.replace('Bearer mock-', '');
return Response.json({ code: 0, data: { open_id: identity === 'bound' ? 'ou_http_test' : 'ou_' + identity, tenant_key: 'tenant_http_test', name: identity === 'browser-new' ? '飞书新成员' : '飞书联调用户' } });
}
if (url === 'https://open.feishu.cn/open-apis/bot/v2/hook/http-test-hook') {
const data = JSON.parse(init.body);
appendFileSync(join(process.env.DATA_DIR, 'messages.jsonl'), JSON.stringify(data) + '\n');
return Response.json(existsSync(join(process.env.DATA_DIR, 'fail-bot')) ? { code: 19021 } : { code: 0 });
}
if (url.includes('feishu.cn')) throw new Error('Unexpected Feishu request blocked by test fixture.');
return original(input, init);
};