import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { mkdtemp, readFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createServer } from 'node:net'; import { randomBytes } from 'node:crypto'; import { DatabaseSync } from 'node:sqlite'; const directory = await mkdtemp(join(tmpdir(), 'demand-feishu-http-')); const port = await new Promise(resolve => { const server = createServer(); server.listen(0, '127.0.0.1', () => { const port = server.address().port; server.close(() => resolve(port)); }); }); const origin = `http://127.0.0.1:${port}`; const basePath = process.env.NEXT_PUBLIC_BASE_PATH || ''; const initial = randomBytes(24).toString('hex'), password = randomBytes(24).toString('hex'); let server, logs = '', checks = 0; const verify = (condition, message) => { assert(condition, message); checks++; }; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); async function call(path, { body, cookie, method, headers = {}, form } = {}) { const response = await fetch(origin + basePath + path, { method: method || (body || form ? 'POST' : 'GET'), redirect: 'manual', headers: { 'x-test-client-ip': '198.51.100.20', ...(body || form ? { Origin: origin, 'Content-Type': form ? 'application/x-www-form-urlencoded' : 'application/json' } : {}), ...(cookie ? { Cookie: cookie } : {}), ...headers }, body: form ? new URLSearchParams(form).toString() : body ? JSON.stringify(body) : undefined }); const text = await response.text(); let data; try { data = JSON.parse(text); } catch { data = text; } return { status: response.status, data, headers: response.headers, cookies: response.headers.getSetCookie().map(c => c.split(';')[0]) }; } async function oauth(intent, cookie = '', code = 'bound') { const start = await call('/api/auth/feishu/start', { cookie, form: { intent, next: '/?demand=REQ-NOT-ACCESSIBLE' } }); verify(start.status === 303, 'OAuth start redirects'); const url = new URL(start.headers.get('location')); verify(url.origin === 'https://accounts.feishu.cn', 'authorization origin is fixed'); verify(url.searchParams.get('redirect_uri') === origin + basePath + '/api/auth/feishu/callback', 'callback respects base path'); const state = url.searchParams.get('state'); const flowCookie = [cookie, ...start.cookies].filter(Boolean).join('; '); return { cookie: flowCookie, path: '/api/auth/feishu/callback?state=' + state + '&code=' + code + '.' + url.searchParams.get('code_challenge') }; } try { server = spawn(process.execPath, ['--import', './tests/feishu-fetch.fixture.mjs', 'scripts/start.mjs'], { env: { ...process.env, NODE_ENV: 'production', HOSTNAME: '127.0.0.1', PORT: String(port), APP_URL: origin, DATA_DIR: directory, INITIAL_ADMIN_USERNAME: 'feishu_http_admin', INITIAL_ADMIN_PASSWORD: initial, LOGIN_CLIENT_IP_HEADER: 'x-test-client-ip', FEISHU_APP_ID: 'cli_http_test', FEISHU_APP_SECRET: 'http-test-secret', FEISHU_TENANT_KEY: 'tenant_http_test', FEISHU_BOT_WEBHOOK: 'https://open.feishu.cn/open-apis/bot/v2/hook/http-test-hook', FEISHU_BOT_SECRET: 'http-test-signature' }, stdio: ['ignore', 'pipe', 'pipe'], }); server.stdout.on('data', c => { logs += c; }); server.stderr.on('data', c => { logs += c; }); let ready = false; for (let i = 0; i < 100; i++) { if (server.exitCode !== null) throw new Error(logs); try { if ((await call('/api/health')).status === 200) { ready = true; break; } } catch {} await sleep(150); } assert(ready, logs); verify((await call('/api/admin/feishu')).status === 401, 'anonymous cannot read notifications'); verify((await call('/api/admin/feishu', { body: { action: 'test' } })).status === 401, 'anonymous cannot send test'); verify((await call('/login')).data.includes('飞书登录'), 'configured login appears'); const forged = await call('/api/auth/feishu/start', { form: { intent: 'bind' }, headers: { Origin: 'https://evil.example' } }); verify(!forged.headers.get('location').includes('accounts.feishu.cn'), 'cross-origin bind rejected'); for (const ip of ['', 'invalid', '198.51.100.20, 198.51.100.21']) { const denied = await call('/api/auth/feishu/start', { form: { intent: 'login' }, headers: { 'x-test-client-ip': ip, 'x-forwarded-for': '198.51.100.20' } }); verify(denied.headers.get('location').includes('feishuError=source') && !denied.cookies.length, 'OAuth rejects missing or invalid trusted source'); } for (let attempt = 0; attempt < 60; attempt++) { const start = await call('/api/auth/feishu/start', { form: { intent: 'login' }, headers: { 'x-test-client-ip': '198.51.100.90' } }); assert(start.headers.get('location').startsWith('https://accounts.feishu.cn/')); } const limited = await call('/api/auth/feishu/start', { form: { intent: 'login' }, headers: { 'x-test-client-ip': '198.51.100.90' } }); verify(limited.headers.get('location').includes('feishuError=rate_limited') && !limited.cookies.length, 'OAuth shows a rate-limit error instead of creating state'); const limitDb = new DatabaseSync(join(directory, 'demand-center.sqlite')); verify(limitDb.prepare('SELECT COUNT(*) AS n FROM feishu_oauth_states').get().n === 60, 'denied OAuth attempts do not insert rows'); limitDb.close(); let login = await call('/api/auth/login', { body: { username: 'feishu_http_admin', password: initial } }); let admin = login.cookies[0]; verify((await call('/api/admin/feishu', { cookie: admin })).status === 403, 'initial password guard applies to integration settings'); login = await call('/api/auth/password', { cookie: admin, body: { currentPassword: initial, newPassword: password } }); admin = login.cookies[0]; const settings = await call('/api/admin/feishu', { cookie: admin }); verify(settings.status === 200 && settings.data.botConfigured, 'admin can read redacted configuration'); verify(!JSON.stringify(settings.data).includes('http-test-secret') && !JSON.stringify(settings.data).includes('http-test-hook'), 'secrets never returned'); const flow = await oauth('bind', admin); const bound = await call(flow.path, { cookie: flow.cookie }); verify(bound.status === 303 && bound.headers.get('location').endsWith('/account/feishu?bound=1'), 'binding callback succeeds'); verify(bound.cookies.some(c => c === 'demand_feishu_state='), 'state cookie cleared'); verify((await call(flow.path, { cookie: flow.cookie })).headers.get('location').includes('expired'), 'replay fails'); await call('/api/auth/logout', { cookie: admin, method: 'POST', headers: { Origin: origin } }); const loginFlow = await oauth('login'); const loggedIn = await call(loginFlow.path, { cookie: loginFlow.cookie }); admin = loggedIn.cookies.find(c => c.startsWith('demand_session=')); verify(Boolean(admin), 'bound identity creates local session'); verify(loggedIn.headers.get('location') === origin + basePath + '/?demand=REQ-NOT-ACCESSIBLE', 'deep link survives OAuth login'); verify((await call('/api/auth/me', { cookie: admin })).status === 200, 'OAuth session authenticates'); const unbound = await oauth('login', '', 'unbound'); const registered = await call(unbound.path, { cookie: unbound.cookie }); let autoCookie = registered.cookies.find(cookie => cookie.startsWith('demand_session=')); verify(registered.status === 303 && Boolean(autoCookie) && !registered.headers.get('location').includes('/account/password'), 'first Feishu login registers and logs in without password setup'); const autoUser = (await call('/api/auth/me', { cookie: autoCookie })).data.user; verify(autoUser.role === 'user' && !autoUser.mustChangePassword && /^feishu_/.test(autoUser.username), 'auto-registration is a regular member with a generated account'); verify((await call('/api/demands', { cookie: autoCookie })).status === 200, 'registered member can immediately use workspace'); verify((await call('/api/admin/users', { cookie: autoCookie })).status === 403, 'registered member has no admin rights'); verify((await call('/api/auth/login', { body: { username: autoUser.username, password: 'dummy timing password that never authenticates' } })).status === 401, 'passwordless account cannot authenticate with timing dummy password'); verify((await call('/api/account/feishu', { cookie: autoCookie, method: 'DELETE', body: { password } })).status === 409, 'cannot remove the only available login method'); const repeat = await oauth('login', '', 'unbound'); const repeatLogin = await call(repeat.path, { cookie: repeat.cookie }); autoCookie = repeatLogin.cookies.find(cookie => cookie.startsWith('demand_session=')); verify((await call('/api/auth/me', { cookie: autoCookie })).data.user.userId === autoUser.userId, 'repeat login reuses auto-created account'); verify((await call('/api/auth/password', { body: { newPassword: password } })).status === 401, 'first password setup requires a session'); const firstPassword = await call('/api/auth/password', { cookie: autoCookie, body: { newPassword: password } }); verify(firstPassword.status === 200 && firstPassword.cookies.length === 1, 'Feishu member can optionally set first system password'); verify((await call('/api/auth/me', { cookie: autoCookie })).status === 401, 'first password setup revokes old sessions'); autoCookie = firstPassword.cookies[0]; verify((await call('/api/auth/password', { cookie: autoCookie, body: { newPassword: initial } })).status === 400, 'later password changes still require current password'); verify((await call('/api/auth/login', { body: { username: autoUser.username, password } })).status === 200, 'optional password enables normal account login'); await call('/api/admin/users', { cookie: admin, method: 'PATCH', body: { id: autoUser.userId, action: 'disable' } }); const disabledFlow = await oauth('login', '', 'unbound'); const disabledLogin = await call(disabledFlow.path, { cookie: disabledFlow.cookie }); verify(!disabledLogin.cookies.some(cookie => cookie.startsWith('demand_session=')) && disabledLogin.headers.get('location').includes('feishuError='), 'disabled Feishu account cannot bypass disable by re-registering'); await call('/api/admin/users', { cookie: admin, method: 'PATCH', body: { id: autoUser.userId, action: 'enable' } }); autoCookie = (await call('/api/auth/login', { body: { username: autoUser.username, password } })).cookies[0]; const autoUnlink = await call('/api/account/feishu', { cookie: autoCookie, method: 'DELETE', body: { password } }); verify(autoUnlink.status === 200, 'registered member can unlink after setting password'); autoCookie = autoUnlink.cookies[0]; const member = await call('/api/admin/users', { cookie: admin, body: { username: 'feishu_http_member', displayName: '联调成员', password: initial, role: 'user' } }); verify(member.status === 201, 'create member'); const ml = await call('/api/auth/login', { body: { username: 'feishu_http_member', password: initial } }); const mc = await call('/api/auth/password', { cookie: ml.cookies[0], body: { currentPassword: initial, newPassword: password } }); verify((await call('/api/admin/feishu', { cookie: mc.cookies[0] })).status === 403, 'regular member cannot read global notifications'); verify((await call('/api/admin/feishu', { cookie: admin, body: { action: 'test' }, headers: { Origin: 'https://evil.example' } })).status === 403, 'bot management requires same origin'); verify((await call('/api/admin/feishu', { cookie: admin, body: { action: 'test' } })).status === 200, 'signed test message accepted by mock'); verify((await call('/api/admin/feishu', { cookie: admin, body: { action: 'test' } })).status === 429, 'test message rate limited'); const fields = { title: '飞书通知联调需求', project: '测试项目', module: '测试模块', type: '新增功能', proposer: '联调管理员', department: '测试部门', source: '本地', owner: '管理员', background: '私密正文不推送', impact: '业务', goal: '验证通知', expectedDate: '', noFixedDate: true, dateReason: '', scope: '', outOfScope: '', criteria: '', priority: 'P2', priorityReason: '', dataSource: '', dataContact: '', noData: true, risk: '', pending: '', references: '', version: 'v1.0' }; const draft = await call('/api/demands', { cookie: admin, body: { action: 'create', mode: 'draft', fields } }); verify(draft.status === 200, 'draft save succeeds'); verify((await call('/api/admin/feishu', { cookie: admin })).data.deliveries.length === 0, 'draft has no notification'); const created = await call('/api/demands', { cookie: admin, body: { action: 'update', id: draft.data.demand.id, revision: 1, mode: 'register', fields } }); verify(created.status === 200, 'draft becomes formal demand'); verify(!(await call('/api/demands', { cookie: autoCookie })).data.demands.some(demand => demand.id === created.data.demand.id), 'new member cannot read another account demand'); const conflict = await call('/api/demands', { cookie: admin, body: { action: 'update', id: draft.data.demand.id, revision: 1, mode: 'register', fields } }); verify(conflict.status === 409, 'conflicting write rejected'); let deliveries; for (let i = 0; i < 60; i++) { deliveries = (await call('/api/admin/feishu', { cookie: admin })).data.deliveries; if (deliveries[0]?.status === 'sent') break; await sleep(150); } verify(deliveries.length === 1 && deliveries[0].status === 'sent', 'instrumentation worker drains committed outbox'); const messages = (await readFile(join(directory, 'messages.jsonl'), 'utf8')).trim().split('\n').map(JSON.parse); const nodes = messages[1].content.post.zh_cn.content.flat(); const deliveredText = nodes.map(node => node.text).join('\n'); verify(messages.length === 2 && deliveredText.includes(created.data.demand.id) && !deliveredText.includes(fields.background), 'only minimal notification and test delivered'); verify(nodes.some(node => node.tag === 'a' && node.href === origin + basePath + '/?demand=' + created.data.demand.id), 'notification links respect deployment prefix'); const historyDb = new DatabaseSync(join(directory, 'demand-center.sqlite')); const target = historyDb.prepare('SELECT target_key FROM feishu_notifications LIMIT 1').get().target_key; const insert = historyDb.prepare('INSERT INTO feishu_notifications (id,demand_id,revision,target_key,content,status,attempts,next_attempt_at,created_at) VALUES (?,?,?,?,?,?,?,?,?)'); for (let index = 1; index <= 52; index++) insert.run('old-failed-' + String(index).padStart(3, '0'), created.data.demand.id, 100 + index, target, '需有序 · 历史失败通知', 'failed', 5, 0, '2026-01-01T00:00:00.000Z'); for (let index = 1; index <= 50; index++) insert.run('new-sent-' + String(index).padStart(3, '0'), created.data.demand.id, 200 + index, target, '需有序 · 较新通知', 'sent', 1, 0, '2026-02-01T00:00:00.000Z'); historyDb.close(); const recent = await call('/api/admin/feishu', { cookie: admin }); verify(recent.data.failedCount === 52 && recent.data.deliveries.every(item => item.status === 'sent') && recent.data.nextCursor, 'failure count stays visible outside the current page'); const failures = await call('/api/admin/feishu?filter=failed', { cookie: admin }); verify(failures.data.deliveries.length === 50 && failures.data.nextCursor, 'failed-only list exposes old failures with pagination'); const oldPageUrl = '/api/admin/feishu?filter=failed&cursor=' + failures.data.nextCursor; const oldPage = await call(oldPageUrl, { cookie: admin }); verify(oldPage.data.deliveries.length === 2 && oldPage.data.nextCursor === null, 'second failed-only page is reachable'); const retried = await call(oldPageUrl, { cookie: admin, body: { action: 'retry', id: oldPage.data.deliveries[0].id } }); verify(retried.status === 200 && retried.data.deliveryFilter === 'failed' && retried.data.failedCount === 51 && retried.data.deliveries.length === 1, 'old failure can be retried without resetting the selected page'); verify((await call('/api/admin/feishu?filter=unexpected', { cookie: admin })).status === 400, 'invalid filter rejected'); verify((await call('/api/admin/feishu?cursor=invalid!', { cookie: admin, body: { action: 'test' } })).status === 400, 'invalid paging rejected before sending test message'); if (process.env.FEISHU_BROWSER_PYTHON) { const browser = spawn(process.env.FEISHU_BROWSER_PYTHON, ['tests/feishu.browser.py'], { env: { ...process.env, TEST_ORIGIN: origin + basePath, TEST_USERNAME: 'feishu_http_admin', TEST_PASSWORD: password, TEST_DEMAND_ID: created.data.demand.id }, stdio: 'inherit' }); assert.equal(await new Promise(resolve => browser.on('exit', resolve)), 0, 'browser verification failed'); } const unlinked = await call('/api/account/feishu', { cookie: admin, method: 'DELETE', body: { password } }); verify(unlinked.status === 200 && unlinked.cookies.some(c => c.startsWith('demand_session=')), 'unlink rotates current session'); verify((await call('/api/auth/me', { cookie: admin })).status === 401, 'old session invalid after unlink'); const db = new DatabaseSync(join(directory, 'demand-center.sqlite')); verify(db.prepare('SELECT COUNT(*) AS n FROM feishu_identities').get().n === 0, 'binding removed'); db.close(); console.log(`Feishu HTTP integration passed: ${checks} checks (all external calls mocked).`); } catch (error) { console.error(logs); throw error; } finally { if (server?.exitCode === null) { server.kill('SIGTERM'); await new Promise(resolve => server.once('exit', resolve)); } await rm(directory, { recursive: true, force: true }); }