api-client.test.ts42 lines · main
| 1 | import { test } from 'node:test'; |
| 2 | import { strict as assert } from 'node:assert'; |
| 3 | import { createServer } from 'node:http'; |
| 4 | import { apiCall } from './api-client.js'; |
| 5 | |
| 6 | test('apiCall sends Bearer when bearer option is set', async () => { |
| 7 | const seen: string[] = []; |
| 8 | const srv = createServer((req, res) => { |
| 9 | seen.push(req.headers.authorization ?? ''); |
| 10 | res.writeHead(200, { 'content-type': 'application/json' }); |
| 11 | res.end('{}'); |
| 12 | }); |
| 13 | await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r())); |
| 14 | const port = (srv.address() as { port: number }).port; |
| 15 | await apiCall('/x', { apiOrigin: `http://127.0.0.1:${port}`, bearer: 'tok' }); |
| 16 | srv.close(); |
| 17 | assert.equal(seen[0], 'Bearer tok'); |
| 18 | }); |
| 19 | |
| 20 | test('apiCall still works with apiKey (back-compat)', async () => { |
| 21 | const seen: { header: string; ok: boolean }[] = []; |
| 22 | const srv = createServer((req, res) => { |
| 23 | const auth = req.headers.authorization ?? ''; |
| 24 | seen.push({ header: auth, ok: auth.length > 0 }); |
| 25 | res.writeHead(200, { 'content-type': 'application/json' }); |
| 26 | res.end('{}'); |
| 27 | }); |
| 28 | await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r())); |
| 29 | const port = (srv.address() as { port: number }).port; |
| 30 | await apiCall('/x', { apiOrigin: `http://127.0.0.1:${port}`, apiKey: 'brk_test' }); |
| 31 | srv.close(); |
| 32 | assert.equal(seen[0]?.ok, true); |
| 33 | // The exact header format is whatever the existing brk_ auth uses |
| 34 | // (Bearer brk_test or x-api-key: brk_test) — just confirm it was sent. |
| 35 | }); |
| 36 | |
| 37 | test('apiCall throws when neither apiKey nor bearer provided', async () => { |
| 38 | await assert.rejects( |
| 39 | () => apiCall('/x', { apiOrigin: 'http://127.0.0.1:0' }), |
| 40 | /apiKey|bearer/i, |
| 41 | ); |
| 42 | }); |