import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; describe('server-v2 /api/v1 bearer auth', () => { let server: RunningServer | undefined; let home: string | undefined; beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-auth-middleware-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); }); afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; } if (home !== undefined) { await rm(home, { recursive: true, force: true }); home = undefined; } }); it('allows healthz without a token', async () => { const res = await server!.app.inject({ method: 'GET', url: '/api/v1/healthz' }); expect(res.statusCode).toBe(200); }); it('rejects /api/v1/auth without a token with 40101', async () => { const res = await server!.app.inject({ method: 'GET', url: '/api/v1/auth' }); expect(res.statusCode).toBe(401); const body = res.json() as Record; expect(body['code']).toBe(40101); }); it('rejects /api/v1/auth with a wrong token', async () => { const res = await server!.app.inject({ method: 'GET', url: '/api/v1/auth', headers: { authorization: 'Bearer wrong-token' }, }); expect(res.statusCode).toBe(401); const body = res.json() as Record; expect(body['code']).toBe(40101); }); it('accepts /api/v1/auth with the persistent token', async () => { const token = server!.authTokenService.getToken(); const res = await server!.app.inject({ method: 'GET', url: '/api/v1/auth', headers: { authorization: `Bearer ${token}` }, }); expect(res.statusCode).toBe(200); const body = res.json() as Record; expect(body['code']).toBe(0); }); it('requires auth for /openapi.json', async () => { const res = await server!.app.inject({ method: 'GET', url: '/openapi.json' }); expect(res.statusCode).toBe(401); }); });