import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { readFileSync } from 'node:fs' import { join } from 'node:path' // --------------------------------------------------------------------------- // Config โ€” reads from env, must match the running server // --------------------------------------------------------------------------- const BASE = 'http://localhost:3456' const API_KEY = process.env.API_KEY || 'test-api-key' const AUTH = { Authorization: `Bearer ${API_KEY}` } const JSON_HEADERS = { ...AUTH, 'Content-Type': 'application/json' } const WEBHOOK_TOKEN = process.env.WEBHOOK_TOKEN || '' const TEST_IMAGE = readFileSync(join(import.meta.dir, 'fixtures/test-image.png')) const TEST_FILE = readFileSync(join(import.meta.dir, 'fixtures/test-file.txt')) const TEST_VIDEO = readFileSync(join(import.meta.dir, 'fixtures/test-video.mp4')) const LOGIN_POLL_INTERVAL_MS = 2_000 const LOGIN_TIMEOUT_MS = 120_000 // 2 minutes to scan QR // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- const get = async (path: string) => fetch(`${BASE}${path}`, { headers: AUTH }) const post = async (path: string, body?: unknown) => fetch(`${BASE}${path}`, { method: 'POST', headers: JSON_HEADERS, body: body !== undefined ? JSON.stringify(body) : undefined, }) const postForm = async (path: string, form: FormData) => fetch(`${BASE}${path}`, { method: 'POST', headers: AUTH, body: form }) const json = (res: Response) => res.json() as Promise> const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) const getStatus = async () => json(await get('/status')) // --------------------------------------------------------------------------- // Setup: ensure clean login // --------------------------------------------------------------------------- beforeAll(async () => { const status = await getStatus() // If already logged in, logout first to test full lifecycle if (status.logged_in) { console.log('โณ Already logged in, logging out first...') await post('/auth/logout') const after = await getStatus() if (after.logged_in) throw new Error('Failed to logout') console.log('โœ… Logged out') } }, 10_000) afterAll(async () => { // Cleanup: logout after all tests const status = await getStatus() if (status.logged_in) { console.log('๐Ÿงน Cleaning up: logging out...') await post('/auth/logout') console.log('โœ… Logged out') } }, 10_000) // =========================================================================== // Phase 1: Tests that DON'T require login // =========================================================================== describe('1. Bearer auth middleware', () => { test('missing header โ†’ 401', async () => { const res = await fetch(`${BASE}/status`) expect(res.status).toBe(401) expect((await json(res)).message).toBe('Missing Authorization header') }) test('wrong token โ†’ 401', async () => { const res = await fetch(`${BASE}/status`, { headers: { Authorization: 'Bearer wrong' }, }) expect(res.status).toBe(401) expect((await json(res)).message).toBe('Invalid token') }) }) describe('2. GET /status (before login)', () => { test('returns not-logged-in status', async () => { const res = await get('/status') expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(body.logged_in).toBe(false) expect(body.user_id).toBeNull() expect(typeof body.polling).toBe('boolean') expect(Array.isArray(body.webhook_urls)).toBe(true) }) }) describe('3. Login guard (before login)', () => { test('all authed routes โ†’ 401 Not logged in', async () => { const routes: [string, string][] = [ ['POST', '/messages/send'], ['GET', '/messages/updates'], ['POST', '/media/presign'], ['POST', '/media/download'], ['POST', '/typing/start'], ['POST', '/typing/stop'], ['POST', '/config'], ] for (const [method, path] of routes) { const res = method === 'GET' ? await get(path) : await post(path, {}) expect(res.status).toBe(401) expect((await json(res)).message).toBe('Not logged in') } }) }) describe('4. 404 (before login)', () => { test('unknown route โ†’ 401 (login guard catches before 404)', async () => { const res = await get('/does-not-exist') expect(res.status).toBe(401) expect((await json(res)).ok).toBe(false) }) }) // =========================================================================== // Phase 2: Login flow // =========================================================================== describe('5. POST /auth/login', () => { test( 'full login flow: get QR โ†’ wait for scan โ†’ confirmed โ†’ wait for first message', async () => { // Start login const res = await post('/auth/login') expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(typeof body.qr_url).toBe('string') console.log(`\n${'='.repeat(60)}`) console.log('๐Ÿ“ฑ Please scan QR code to login (2 min timeout)') console.log('QR URL:', body.qr_url) console.log(`${'='.repeat(60)}\n`) // Poll until confirmed const loginDeadline = Date.now() + LOGIN_TIMEOUT_MS let confirmed = false while (Date.now() < loginDeadline) { await sleep(LOGIN_POLL_INTERVAL_MS) const status = await getStatus() if (status.login_status === 'scanned') { console.log('๐Ÿ“ฑ Scanned, waiting for confirmation...') } if (status.logged_in) { confirmed = true console.log(`โœ… Login success! user_id=${status.user_id}`) break } if (status.login_status === 'failed') { throw new Error(`Login failed: ${status.login_error}`) } } expect(confirmed).toBe(true) // Wait for user to send a message so context_token gets cached console.log(`\n${'='.repeat(60)}`) console.log('๐Ÿ’ฌ Please send a message to the bot on WeChat (waiting for context_token)') console.log(`${'='.repeat(60)}\n`) const msgDeadline = Date.now() + LOGIN_TIMEOUT_MS let gotMessage = false while (Date.now() < msgDeadline) { await sleep(LOGIN_POLL_INTERVAL_MS) const updatesRes = await get('/messages/updates') const updates = await json(updatesRes) if ((updates.count as number) > 0) { gotMessage = true console.log(`โœ… Message received! count=${updates.count}`) break } } expect(gotMessage).toBe(true) }, (LOGIN_TIMEOUT_MS + 10_000) * 2, ) test('login again โ†’ 409 conflict', async () => { const res = await post('/auth/login') expect(res.status).toBe(409) }) }) // =========================================================================== // Phase 3: Tests that REQUIRE login // =========================================================================== describe('6. GET /status (after login)', () => { test('returns logged-in status', async () => { const res = await get('/status') const body = await json(res) expect(body.ok).toBe(true) expect(body.logged_in).toBe(true) expect(typeof body.user_id).toBe('string') expect(body.polling).toBe(true) }) }) describe('7. 404 (after login)', () => { test('unknown route โ†’ 404', async () => { const res = await get('/does-not-exist') expect(res.status).toBe(404) expect((await json(res)).ok).toBe(false) }) }) // --------------------------------------------------------------------------- // Messages // --------------------------------------------------------------------------- describe('8. POST /messages/send โ€” validation', () => { test('missing to โ†’ 400', async () => { const res = await post('/messages/send', { items: [{ type: 'text', text: 'hi' }], }) expect(res.status).toBe(400) }) test('empty items โ†’ 400', async () => { const res = await post('/messages/send', { to: 'self', items: [] }) expect(res.status).toBe(400) }) test('invalid item type โ†’ 400', async () => { const res = await post('/messages/send', { to: 'self', items: [{ type: 'sticker' }], }) expect(res.status).toBe(400) }) test('file without file_name โ†’ 400', async () => { const res = await post('/messages/send', { to: 'self', items: [{ type: 'file', cdn: { encrypt_query_param: 'x', aes_key: 'y' } }], }) expect(res.status).toBe(400) }) }) describe('9. POST /messages/send โ€” real send', () => { test('send text to self', async () => { const res = await post('/messages/send', { to: 'self', items: [{ type: 'text', text: `[test] ${new Date().toISOString()}` }], }) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) const results = body.results as Record[] expect(results).toHaveLength(1) const first = results.at(0) expect(first).toBeDefined() expect(first?.type).toBe('text') expect(first?.ok).toBe(true) expect(typeof first?.client_id).toBe('string') }) test('send multiple texts', async () => { const res = await post('/messages/send', { to: 'self', items: [ { type: 'text', text: '[test] msg 1' }, { type: 'text', text: '[test] msg 2' }, ], }) const body = await json(res) expect(body.ok).toBe(true) expect(body.results as unknown[]).toHaveLength(2) }) test('send image via url', async () => { const res = await post('/messages/send', { to: 'self', items: [{ type: 'image', url: 'https://wechat.design/uploads/740a6c40367a4d2db0bc8c80ccc8018e.jpg' }], }) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) const results = body.results as Record[] expect(results).toHaveLength(1) expect(results[0]?.type).toBe('image') expect(results[0]?.ok).toBe(true) expect(typeof results[0]?.client_id).toBe('string') }, 30_000) }) // --------------------------------------------------------------------------- // Messages updates // --------------------------------------------------------------------------- describe('10. GET /messages/updates', () => { test('returns message buffer', async () => { const res = await get('/messages/updates') expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(typeof body.count).toBe('number') expect(Array.isArray(body.messages)).toBe(true) }) test('?after=999999999 โ†’ empty', async () => { const res = await get('/messages/updates?after=999999999') const body = await json(res) expect(body.count).toBe(0) }) test('invalid after is ignored', async () => { const res = await get('/messages/updates?after=not-a-number') expect(res.status).toBe(200) }) }) // --------------------------------------------------------------------------- // Media upload // --------------------------------------------------------------------------- describe('11. POST /media/upload โ€” validation', () => { test('missing file โ†’ 400', async () => { const form = new FormData() form.append('to', 'self') const res = await postForm('/media/upload', form) expect(res.status).toBe(400) }) test('missing to โ†’ 400', async () => { const form = new FormData() form.append('file', new File(['x'], 'test.txt')) const res = await postForm('/media/upload', form) expect(res.status).toBe(400) }) }) describe('12. POST /media/upload โ€” real upload', () => { test('upload image', async () => { const form = new FormData() form.append('file', new File([TEST_IMAGE], 'test.png', { type: 'image/png' })) form.append('to', 'self') const res = await postForm('/media/upload', form) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(body.media_type).toBe('image') expect(body.file_name).toBe('test.png') expect(typeof body.filekey).toBe('string') expect(typeof body.encrypt_query_param).toBe('string') expect(typeof body.aes_key).toBe('string') expect(typeof body.file_size).toBe('number') expect(typeof body.file_size_ciphertext).toBe('number') }) test('upload then send image via cdn reference', async () => { const form = new FormData() form.append('file', new File([TEST_IMAGE], 'test.png', { type: 'image/png' })) form.append('to', 'self') const uploadRes = await postForm('/media/upload', form) expect(uploadRes.status).toBe(200) const uploaded = await json(uploadRes) expect(uploaded.ok).toBe(true) const sendRes = await post('/messages/send', { to: 'self', items: [ { type: 'image', cdn: { encrypt_query_param: uploaded.encrypt_query_param, aes_key: uploaded.aes_key, }, }, ], }) expect(sendRes.status).toBe(200) const sendBody = await json(sendRes) expect(sendBody.ok).toBe(true) const results = sendBody.results as Record[] expect(results).toHaveLength(1) expect(results[0]?.type).toBe('image') expect(results[0]?.ok).toBe(true) }, 30_000) test('upload then send file via cdn reference', async () => { const form = new FormData() form.append('file', new File([TEST_FILE], 'test-file.txt', { type: 'text/plain' })) form.append('to', 'self') const uploadRes = await postForm('/media/upload', form) expect(uploadRes.status).toBe(200) const uploaded = await json(uploadRes) expect(uploaded.ok).toBe(true) expect(uploaded.media_type).toBe('file') const sendRes = await post('/messages/send', { to: 'self', items: [ { type: 'file', file_name: 'test-file.txt', cdn: { encrypt_query_param: uploaded.encrypt_query_param, aes_key: uploaded.aes_key, }, }, ], }) expect(sendRes.status).toBe(200) const sendBody = await json(sendRes) expect(sendBody.ok).toBe(true) const results = sendBody.results as Record[] expect(results).toHaveLength(1) expect(results[0]?.type).toBe('file') expect(results[0]?.ok).toBe(true) }, 30_000) test('upload then send video via cdn reference', async () => { const form = new FormData() form.append('file', new File([TEST_VIDEO], 'test-video.mp4', { type: 'video/mp4' })) form.append('to', 'self') const uploadRes = await postForm('/media/upload', form) expect(uploadRes.status).toBe(200) const uploaded = await json(uploadRes) expect(uploaded.ok).toBe(true) expect(uploaded.media_type).toBe('video') const sendRes = await post('/messages/send', { to: 'self', items: [ { type: 'video', cdn: { encrypt_query_param: uploaded.encrypt_query_param, aes_key: uploaded.aes_key, }, }, ], }) expect(sendRes.status).toBe(200) const sendBody = await json(sendRes) expect(sendBody.ok).toBe(true) const results = sendBody.results as Record[] expect(results).toHaveLength(1) expect(results[0]?.type).toBe('video') expect(results[0]?.ok).toBe(true) }, 60_000) }) // --------------------------------------------------------------------------- // Media presign // --------------------------------------------------------------------------- describe('13. POST /media/presign', () => { test('missing required fields โ†’ 400', async () => { const res = await post('/media/presign', { to: 'self' }) expect(res.status).toBe(400) }) test('returns presigned url', async () => { const res = await post('/media/presign', { to: 'self', filekey: `test_fk_${Date.now()}`, media_type: 1, rawsize: 100, rawfilemd5: 'd41d8cd98f00b204e9800998ecf8427e', filesize: 112, aeskey: '00112233445566778899aabbccddeeff', }) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(typeof body.upload_param === 'string' || typeof body.upload_full_url === 'string').toBe(true) }) }) // --------------------------------------------------------------------------- // Media download // --------------------------------------------------------------------------- describe('14. POST /media/download โ€” validation', () => { test('missing fields โ†’ 400', async () => { const res = await post('/media/download', { aes_key: 'key' }) expect(res.status).toBe(400) }) test('invalid url โ†’ 400', async () => { const res = await post('/media/download', { full_url: 'not-a-url', aes_key: 'dGVzdA==', file_name: 'test.txt', }) expect(res.status).toBe(400) }) }) // --------------------------------------------------------------------------- // Typing // --------------------------------------------------------------------------- describe('15. POST /typing/start', () => { test('missing to โ†’ 400', async () => { const res = await post('/typing/start', {}) expect(res.status).toBe(400) }) test('sends typing indicator', async () => { const res = await post('/typing/start', { to: 'self' }) expect(res.status).toBe(200) expect((await json(res)).ok).toBe(true) }) }) describe('16. POST /typing/stop', () => { test('missing to โ†’ 400', async () => { const res = await post('/typing/stop', {}) expect(res.status).toBe(400) }) test('cancels typing indicator', async () => { const res = await post('/typing/stop', { to: 'self' }) expect(res.status).toBe(200) expect((await json(res)).ok).toBe(true) }) }) // --------------------------------------------------------------------------- // Config // --------------------------------------------------------------------------- describe('17. POST /config', () => { test('missing to โ†’ 400', async () => { const res = await post('/config', {}) expect(res.status).toBe(400) }) test('returns config with typing_ticket', async () => { const res = await post('/config', { to: 'self' }) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(typeof body.typing_ticket).toBe('string') }) }) // --------------------------------------------------------------------------- // Webhook (incoming) // --------------------------------------------------------------------------- describe('18. POST /webhook/:token', () => { test('skips bearer auth', async () => { const res = await fetch(`${BASE}/webhook/some-token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'test' }), }) const body = await json(res) expect(body.message).not.toBe('Missing Authorization header') }) test('invalid token โ†’ 401', async () => { const res = await fetch(`${BASE}/webhook/definitely-wrong`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'test' }), }) expect(res.status).toBe(401) }) test('empty text โ†’ 400', async () => { if (!WEBHOOK_TOKEN) return const res = await fetch(`${BASE}/webhook/${WEBHOOK_TOKEN}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: ' ' }), }) expect(res.status).toBe(400) }) test('send via text/plain', async () => { if (!WEBHOOK_TOKEN) return const res = await fetch(`${BASE}/webhook/${WEBHOOK_TOKEN}`, { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: `[test] webhook plain ${new Date().toISOString()}`, }) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) expect(typeof body.client_id).toBe('string') }) test('send via JSON', async () => { if (!WEBHOOK_TOKEN) return const res = await fetch(`${BASE}/webhook/${WEBHOOK_TOKEN}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: `[test] webhook json ${new Date().toISOString()}`, }), }) expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) }) }) // =========================================================================== // Phase 4: Logout // =========================================================================== describe('19. POST /auth/logout', () => { test('logout โ†’ 200', async () => { const res = await post('/auth/logout') expect(res.status).toBe(200) const body = await json(res) expect(body.ok).toBe(true) }) test('status is logged out', async () => { const status = await getStatus() expect(status.logged_in).toBe(false) expect(status.user_id).toBeNull() }) test('logout again โ†’ 400', async () => { const res = await post('/auth/logout') expect(res.status).toBe(400) }) test('authed routes blocked again', async () => { const res = await post('/messages/send', { to: 'self', items: [{ type: 'text', text: 'should fail' }], }) expect(res.status).toBe(401) }) })