Files
tap/tests/feishu.test.ts
T

351 lines
23 KiB
TypeScript

import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createHash, createHmac } from 'node:crypto';
import { closeDatabases, getDatabase } from '../lib/server/database.ts';
import { AuthError, authenticateSession, changeAccountPassword, createAccount, hasAccountPassword, loginWithPassword, updateAccount } from '../lib/server/auth.ts';
import { beginFeishuAuth, completeFeishuAuth, consumeFeishuState, FeishuAuthError, getFeishuBinding, unbindFeishu } from '../lib/server/feishu-auth.ts';
import { feishuBotConfig, feishuCallbackUrl } from '../lib/server/feishu-config.ts';
import { deliverNextFeishuNotification, feishuStatus, parseFeishuDeliveryQuery, queueDemandNotification, retryFeishuNotification, signFeishuMessage } from '../lib/server/feishu-notifications.ts';
import { safeReturnTo } from '../lib/auth-return.ts';
import { feishuErrorMessage } from '../lib/feishu.ts';
import { emptyFields, type Demand } from '../lib/demand.ts';
import { PASSWORD_LOGIN_DISABLED, verifyPassword } from '../lib/server/password.ts';
const directory = mkdtempSync(join(tmpdir(), 'demand-feishu-tests-'));
const env = { ...process.env };
const realFetch = globalThis.fetch;
const password = 'Feishu local password 12345';
let adminId: string, adminToken: string, otherId: string, otherToken: string;
let openId = 'ou_test_admin', tenant = 'tenant_test';
let sent: Array<{ url: string; init: RequestInit }> = [];
let failBot = false;
const request = (url: string, cookie = '') => new Request(url, { headers: { cookie } });
const isError = (code: string) => (error: unknown) => error instanceof FeishuAuthError && error.code === code;
before(async () => {
Object.assign(process.env, { DATA_DIR: directory, APP_URL: 'https://demand.example.test', INITIAL_ADMIN_USERNAME: 'feishu.admin',
INITIAL_ADMIN_PASSWORD: password, FEISHU_APP_ID: 'cli_test', FEISHU_APP_SECRET: 'test-app-secret', FEISHU_TENANT_KEY: 'tenant_test',
FEISHU_BOT_WEBHOOK: 'https://open.feishu.cn/open-apis/bot/v2/hook/test-hook', FEISHU_BOT_SECRET: 'test-signing-secret' });
delete process.env.LOGIN_CLIENT_IP_HEADER;
const login = await loginWithPassword('feishu.admin', password);
adminId = login.user.userId;
adminToken = (await changeAccountPassword(adminId, password, password + ' changed')).token;
const other = await createAccount(adminId, { username: 'feishu.member', displayName: '其他用户', password, role: 'user' });
otherId = other.userId;
otherToken = (await changeAccountPassword(otherId, password, password + ' changed')).token;
globalThis.fetch = async (input, init = {}) => {
const url = String(input);
sent.push({ url, init });
if (url.endsWith('/authen/v2/oauth/token')) return Response.json({ code: 0, access_token: 'ephemeral-user-token' });
if (url.endsWith('/authen/v1/user_info')) return Response.json({ code: 0, data: { open_id: openId, tenant_key: tenant, name: '飞书测试用户' } });
if (url.includes('/bot/v2/hook/')) return Response.json(failBot ? { code: 19021, msg: 'secret echoed, must not be stored' } : { code: 0 });
throw new Error('Unexpected network call: ' + url);
};
});
after(() => { globalThis.fetch = realFetch; closeDatabases(); rmSync(directory, { recursive: true, force: true }); process.env = env; });
function start(intent = 'login', token = '', returnTo = '/?demand=REQ-TEST') {
const sessionCookie = token ? `demand_session=${token}` : '';
const started = beginFeishuAuth(request('https://demand.example.test/api/auth/feishu/start', sessionCookie), intent, returnTo);
const authorize = new URL(started.url);
const callback = request(feishuCallbackUrl() + '?state=' + authorize.searchParams.get('state') + '&code=test-code',
[sessionCookie, started.cookie.split(';')[0]].filter(Boolean).join('; '));
return { ...started, authorize, callback };
}
async function finish(flow: ReturnType<typeof start>) { return completeFeishuAuth(flow.callback, consumeFeishuState(flow.callback)); }
test('configuration never exposes secrets and return URLs cannot leave the app', () => {
assert.equal(feishuErrorMessage('__proto__'), '');
assert.equal(feishuErrorMessage(['unbound']), '');
for (const value of ['//evil.example', '/\\evil.example', 'https://evil.example', '/a/..//evil.example', '/api/auth/logout', '/login', '/\nevil']) assert.equal(safeReturnTo(value), '/');
assert.equal(safeReturnTo('/?demand=REQ-TEST'), '/?demand=REQ-TEST');
const status = JSON.stringify(feishuStatus());
for (const secret of ['test-hook', 'test-signing-secret', 'test-app-secret']) assert.ok(!status.includes(secret));
const webhook = process.env.FEISHU_BOT_WEBHOOK;
for (const value of ['http://localhost/hook/x', 'https://open.feishu.cn.evil.com/open-apis/bot/v2/hook/x', 'https://open.feishu.cn/open-apis/bot/v2/hook/x?secret=y']) {
process.env.FEISHU_BOT_WEBHOOK = value;
assert.throws(feishuBotConfig);
}
process.env.FEISHU_BOT_WEBHOOK = webhook;
});
test('OAuth uses PKCE, browser-bound state, single consumption and expiration', () => {
const flow = start();
assert.equal(flow.authorize.origin, 'https://accounts.feishu.cn');
assert.equal(flow.authorize.searchParams.get('code_challenge_method'), 'S256');
assert.ok(flow.cookie.includes('HttpOnly; SameSite=Lax; Max-Age=600; Secure'));
assert.throws(() => consumeFeishuState(request(flow.callback.url, 'demand_feishu_state=' + 'a'.repeat(43))), isError('expired'));
const state = consumeFeishuState(flow.callback);
assert.equal(flow.authorize.searchParams.get('code_challenge'), createHash('sha256').update(state.verifier).digest('base64url'));
assert.throws(() => consumeFeishuState(flow.callback), isError('expired'));
const expired = start();
getDatabase().prepare('UPDATE feishu_oauth_states SET expires_at = 0').run();
assert.throws(() => consumeFeishuState(expired.callback), isError('expired'));
});
test('OAuth checks trusted IP and shares the persistent password-login source quota before creating state', async () => {
process.env.LOGIN_CLIENT_IP_HEADER = 'x-real-ip';
const db = getDatabase();
db.prepare('DELETE FROM feishu_oauth_states').run();
const req = (ip: string, extra: Record<string, string> = {}) => new Request('https://demand.example.test/api/auth/feishu/start', { headers: { 'x-real-ip': ip, ...extra } });
try {
for (const ip of ['', 'invalid', '192.0.2.10, 192.0.2.11']) {
assert.throws(() => beginFeishuAuth(req(ip, { 'x-forwarded-for': '192.0.2.10' }), 'login', '/'), error => error instanceof AuthError && error.status === 403);
}
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM feishu_oauth_states').first<{ n: number }>()!.n, 0);
for (let i = 0; i < 59; i++) beginFeishuAuth(req('192.0.2.10'), 'login', '/');
await assert.rejects(() => loginWithPassword('missing.account', password, req('192.0.2.10')), error => error instanceof AuthError && error.status === 401);
closeDatabases();
assert.throws(() => beginFeishuAuth(req('192.0.2.10', { 'x-forwarded-for': '192.0.2.11' }), 'login', '/'), error => error instanceof AuthError && error.status === 429);
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM feishu_oauth_states').first<{ n: number }>()!.n, 59);
beginFeishuAuth(req('192.0.2.11'), 'login', '/');
getDatabase().prepare('UPDATE login_limits SET window_start = ?').bind(Date.now() - 61_000).run();
beginFeishuAuth(req('192.0.2.10'), 'login', '/');
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
});
test('first Feishu login registers a regular member without requiring a password or merging names', async () => {
openId = 'ou_new_member';
const first = await finish(start());
assert.equal(first.user.role, 'user');
assert.equal(first.user.mustChangePassword, false);
assert.equal(first.user.displayName, '飞书测试用户');
assert.match(first.user.username, /^feishu_[a-f0-9]{32}$/);
assert.ok(![adminId, otherId].includes(first.user.userId));
assert.equal(first.returnTo, '/?demand=REQ-TEST');
assert.equal(authenticateSession(first.token!)?.userId, first.user.userId);
assert.equal(hasAccountPassword(first.user.userId), false);
const storedHash = getDatabase().prepare('SELECT password_hash FROM accounts WHERE id = ?').bind(first.user.userId).first<{ password_hash: string }>()!.password_hash;
assert.equal(storedHash, PASSWORD_LOGIN_DISABLED);
assert.equal(await verifyPassword('dummy timing password that never authenticates', storedHash), false, 'older password verifiers also reject the disabled marker');
assert.equal(getFeishuBinding(first.user.userId)?.name, '飞书测试用户');
const again = await finish(start());
assert.equal(again.user.userId, first.user.userId);
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n, 3);
await assert.rejects(() => loginWithPassword(first.user.username, 'dummy timing password that never authenticates'), error => error instanceof AuthError && error.status === 401);
const req = request('https://demand.example.test/api/account/feishu', 'demand_session=' + again.token);
await assert.rejects(() => unbindFeishu(again.user, 'anything', req), /先设置系统密码/);
const withPassword = await changeAccountPassword(first.user.userId, undefined, password);
assert.equal(hasAccountPassword(first.user.userId), true);
assert.equal(authenticateSession(again.token!), null);
assert.ok(authenticateSession(withPassword.token));
assert.equal((await loginWithPassword(first.user.username, password)).user.userId, first.user.userId);
await assert.rejects(() => changeAccountPassword(first.user.userId, undefined, password + ' changed'), /当前密码/);
await updateAccount(adminId, { id: first.user.userId, action: 'disable' });
await assert.rejects(() => finish(start()), /账号已停用/);
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n, 3);
openId = 'ou_test_admin';
assert.throws(() => start('bind'), isError('session'));
});
test('concurrent first logins create one account; binding insertion failure rolls back account and session creation', async () => {
openId = 'ou_concurrent';
const count = () => getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n;
const before = count();
const [first, second] = await Promise.all([finish(start()), finish(start())]);
assert.equal(first.user.userId, second.user.userId);
assert.equal(count(), before + 1);
const db = getDatabase();
db.prepare("CREATE TRIGGER reject_registration BEFORE INSERT ON feishu_identities WHEN NEW.open_id = 'ou_rollback' BEGIN SELECT RAISE(ABORT, 'registration failure'); END").run();
openId = 'ou_rollback';
const sessionsBefore = db.prepare('SELECT COUNT(*) AS n FROM sessions').first<{ n: number }>()!.n;
try {
await assert.rejects(() => finish(start()), /registration failure/);
assert.equal(count(), before + 1);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM sessions').first<{ n: number }>()!.n, sessionsBefore);
} finally { db.prepare('DROP TRIGGER reject_registration').run(); openId = 'ou_test_admin'; }
});
test('binding preserves existing role and ownership and stores no OAuth tokens', async () => {
sent = [];
const flow = start('bind', adminToken);
const result = await finish(flow);
assert.equal(result.bound, true);
assert.equal(result.user.userId, adminId);
assert.equal(result.user.role, 'admin');
assert.equal(getFeishuBinding(adminId)?.name, '飞书测试用户');
assert.equal(Object.getPrototypeOf(getFeishuBinding(adminId)), Object.prototype, 'binding is serializable by React server components');
assert.equal(sent[0].url, 'https://open.feishu.cn/open-apis/authen/v2/oauth/token');
assert.equal((sent[0].init.headers as Record<string, string>)['Content-Type'], 'application/json');
const tokenBody = JSON.parse(sent[0].init.body as string);
assert.equal(tokenBody.redirect_uri, feishuCallbackUrl());
assert.equal(tokenBody.code_verifier.length, 43);
assert.equal(createHash('sha256').update(tokenBody.code_verifier).digest('base64url'), flow.authorize.searchParams.get('code_challenge'));
assert.equal((sent[1].init.headers as Record<string, string>).Authorization, 'Bearer ephemeral-user-token');
assert.equal(JSON.stringify(getDatabase().prepare('SELECT * FROM feishu_identities').all()).includes('ephemeral-user-token'), false);
const login = await finish(start());
assert.equal(login.user.userId, adminId);
assert.equal(login.returnTo, '/?demand=REQ-TEST');
assert.equal(authenticateSession(login.token!)?.role, 'admin');
});
test('tenant boundaries, identity conflicts, session switching and disabled users fail closed', async () => {
const before = getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n;
tenant = 'wrong-enterprise';
await assert.rejects(() => finish(start()), isError('tenant'));
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n, before);
tenant = 'tenant_test';
await assert.rejects(() => finish(start('bind', otherToken)), isError('conflict'));
const switched = start('bind', adminToken);
const changedRequest = request(switched.callback.url, switched.callback.headers.get('cookie')!.replace(adminToken, otherToken));
await assert.rejects(() => completeFeishuAuth(changedRequest, consumeFeishuState(changedRequest)), isError('session'));
openId = 'ou_other';
await finish(start('bind', otherToken));
await updateAccount(adminId, { id: otherId, action: 'disable' });
await assert.rejects(() => finish(start()), /账号已停用/);
await updateAccount(adminId, { id: otherId, action: 'enable' });
await updateAccount(adminId, { id: otherId, action: 'reset-password', password });
const resetLogin = await finish(start());
assert.equal(resetLogin.user.mustChangePassword, true);
assert.equal(resetLogin.returnTo, '/account/password');
openId = 'ou_test_admin';
});
test('cancellation and app rotation do not issue sessions', async () => {
const flow = start();
const cancelled = request(flow.callback.url + '&error=access_denied', flow.callback.headers.get('cookie')!);
await assert.rejects(() => completeFeishuAuth(cancelled, consumeFeishuState(cancelled)), isError('denied'));
const rotated = start();
process.env.FEISHU_APP_ID = 'cli_replaced';
await assert.rejects(() => finish(rotated), isError('expired'));
process.env.FEISHU_APP_ID = 'cli_test';
});
test('unlink requires password and revokes existing sessions and pending binding flows', async () => {
const user = authenticateSession(adminToken)!;
const req = request('https://demand.example.test/api/account/feishu', 'demand_session=' + adminToken);
await assert.rejects(() => unbindFeishu(user, 'wrong password', req));
assert.ok(getFeishuBinding(adminId));
const pending = start('bind', adminToken);
const unbound = await unbindFeishu(user, password + ' changed', req);
assert.equal(getFeishuBinding(adminId), null);
assert.equal(authenticateSession(adminToken), null);
assert.ok(authenticateSession(unbound.token));
assert.throws(() => consumeFeishuState(pending.callback), isError('expired'));
const newAccount = await finish(start());
assert.notEqual(newAccount.user.userId, adminId);
assert.equal(newAccount.user.role, 'user');
assert.equal(authenticateSession(unbound.token)?.userId, adminId, 'unlink keeps the original password account and data ownership');
adminToken = unbound.token;
});
function fixture(revision = 1): Demand {
return { id: 'REQ-FEISHU', revision, fields: { ...emptyFields, title: '通知需求', background: 'private body excluded' }, status: '待评审',
reviewReady: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), changes: [],
history: [{ time: new Date().toISOString(), actor: '测试成员', action: '提交评审', detail: 'private detail excluded' }] };
}
function queue(revision: number) { const d = fixture(revision); getDatabase().transaction(() => queueDemandNotification(d)); }
function due() { getDatabase().prepare("UPDATE feishu_notifications SET next_attempt_at = 0 WHERE status != 'sent'").run(); }
test('transactional outbox suppresses drafts, rolled-back saves and duplicate revisions', () => {
const d = fixture();
getDatabase().prepare('INSERT INTO demands (id, owner_id, payload, revision, updated_at) VALUES (?, ?, ?, 1, ?)')
.bind(d.id, adminId, JSON.stringify(d), d.updatedAt).run();
queueDemandNotification({ ...d, status: '草稿' });
assert.equal(feishuStatus().deliveries.length, 0);
assert.throws(() => getDatabase().transaction(() => { queueDemandNotification(d); throw new Error('rollback'); }));
assert.equal(feishuStatus().deliveries.length, 0);
queue(1); queue(1);
assert.equal(feishuStatus().deliveries.length, 1);
assert.equal(Object.getPrototypeOf(feishuStatus().deliveries[0]), Object.prototype, 'delivery is serializable by React server components');
const content = getDatabase().prepare('SELECT content FROM feishu_notifications').first<{ content: string }>()!.content;
assert.ok(content.includes('/?demand=REQ-FEISHU'));
assert.ok(!content.includes('private'));
});
test('signed delivery is sent once on success, with one lease across concurrent workers', async () => {
sent = [];
const results = await Promise.all([deliverNextFeishuNotification(), deliverNextFeishuNotification()]);
assert.equal(results.filter(Boolean).length, 1);
assert.equal(sent.length, 1);
const body = JSON.parse(sent[0].init.body as string);
assert.equal(body.sign, createHmac('sha256', body.timestamp + '\ntest-signing-secret').digest('base64'));
assert.equal(signFeishuMessage('100', 'secret'), createHmac('sha256', '100\nsecret').digest('base64'));
assert.equal(feishuStatus().deliveries[0].status, 'sent');
assert.equal(await deliverNextFeishuNotification(), false);
});
test('queued mention markup stays literal text and only the real detail link becomes a link node', async () => {
const d = fixture(10);
d.fields.title = '<at user_id="all">所有人</at> &lt;at user_id="all"&gt;';
d.history[0].actor = '<at user_id="ou_member">成员</at>';
getDatabase().transaction(() => queueDemandNotification(d));
assert.ok(getDatabase().prepare('SELECT content FROM feishu_notifications WHERE revision = 10').first<{ content: string }>()!.content.includes('<at'));
sent = [];
await deliverNextFeishuNotification();
const body = JSON.parse(sent[0].init.body as string);
assert.equal(body.msg_type, 'post');
const nodes = body.content.post.zh_cn.content.flat();
assert.ok(nodes.every((node: { tag: string }) => node.tag === 'text' || node.tag === 'a'));
assert.ok(nodes.some((node: { text: string }) => node.text === d.fields.title));
assert.ok(nodes.filter((node: { tag: string }) => node.tag === 'text').every((node: { un_escape: boolean }) => node.un_escape === false));
assert.equal(nodes.filter((node: { tag: string }) => node.tag === 'a').length, 1);
assert.equal(nodes.at(-1).href, 'https://demand.example.test/?demand=REQ-FEISHU');
});
test('failed messages retry with backoff, survive restart and can be manually retried', async () => {
queue(2); failBot = true;
for (let i = 0; i < 5; i++) {
due(); await deliverNextFeishuNotification();
closeDatabases();
const delivery = feishuStatus().deliveries.find(d => d.revision === 2)!;
assert.equal(delivery.attempts, i + 1);
assert.equal(delivery.status, i === 4 ? 'failed' : 'pending');
assert.ok(!delivery.lastError?.includes('secret echoed'));
assert.equal(await deliverNextFeishuNotification(), false);
}
const failed = feishuStatus().deliveries.find(d => d.revision === 2)!;
retryFeishuNotification(failed.id); failBot = false;
await deliverNextFeishuNotification();
assert.equal(feishuStatus().deliveries.find(d => d.revision === 2)?.status, 'sent');
assert.throws(() => retryFeishuNotification(failed.id));
});
test('changing destination cannot leak queued messages into another group', async () => {
queue(3); sent = [];
process.env.FEISHU_BOT_WEBHOOK = 'https://open.feishu.cn/open-apis/bot/v2/hook/new-target';
assert.equal(await deliverNextFeishuNotification(), false);
assert.equal(sent.length, 0);
const old = feishuStatus().deliveries.find(d => d.revision === 3)!;
assert.equal(old.status, 'failed');
assert.throws(() => retryFeishuNotification(old.id));
delete process.env.FEISHU_BOT_WEBHOOK;
queue(4);
assert.ok(!feishuStatus().deliveries.some(d => d.revision === 4));
});
test('old failed notifications remain discoverable and retryable across filtered cursor pages', () => {
process.env.FEISHU_BOT_WEBHOOK = 'https://open.feishu.cn/open-apis/bot/v2/hook/test-hook';
const db = getDatabase();
db.prepare('DELETE FROM feishu_notifications').run();
for (let revision = 1; revision <= 102; revision++) queue(revision);
// Equal timestamps force stable pagination on the ID tie-breaker.
db.prepare("UPDATE feishu_notifications SET status = 'failed', created_at = '2026-01-01T00:00:00.000Z' WHERE revision <= 52").run();
db.prepare("UPDATE feishu_notifications SET status = 'sent', created_at = '2026-02-01T00:00:00.000Z' WHERE revision > 52").run();
const first = feishuStatus();
assert.equal(first.failedCount, 52);
assert.equal(first.deliveries.filter(row => row.status === 'failed').length, 0);
assert.ok(first.nextCursor);
const query = (filter: string, cursor?: string | null) => parseFeishuDeliveryQuery(new URLSearchParams({ filter, ...(cursor ? { cursor } : {}) }));
const failedFirst = feishuStatus(query('failed'));
assert.equal(failedFirst.deliveries.length, 50);
assert.ok(failedFirst.deliveries.every(row => row.status === 'failed'));
const failedNext = feishuStatus(query('failed', failedFirst.nextCursor));
assert.equal(failedNext.deliveries.length, 2);
assert.equal(failedNext.nextCursor, null);
assert.equal(new Set([...failedFirst.deliveries, ...failedNext.deliveries].map(row => row.id)).size, 52);
const allSecond = feishuStatus(query('all', first.nextCursor));
assert.equal(allSecond.deliveries.length, 50);
// A new item must not shift the cursor and duplicate/skip records on later pages.
queue(103);
assert.deepEqual(feishuStatus(query('all', first.nextCursor)).deliveries.map(row => row.id), allSecond.deliveries.map(row => row.id));
retryFeishuNotification(failedNext.deliveries[0].id);
assert.equal(feishuStatus(query('failed')).failedCount, 51);
assert.equal(feishuStatus(query('failed', failedFirst.nextCursor)).deliveries.length, 1);
assert.throws(() => query('unexpected'), /筛选条件/);
for (const cursor of ['invalid!', 'a', 'a'.repeat(513), Buffer.from('{"createdAt":"bad","id":"x"}').toString('base64url')]) assert.throws(() => query('all', cursor), /分页参数/);
});