import { describe, it, expect } from 'vitest'; import request from 'supertest'; import rateLimit from 'express-rate-limit'; import { buildApp } from '../helpers.js'; import { createApp } from '../../src/app.js'; import { prisma } from '../../src/lib/prisma.js'; import { RATE_LIMIT_BODY } from '../../src/middleware/rateLimit.js'; describe('app-level behavior', () => { it('responds on /health', async () => { const app = buildApp(); const res = await app.get('/health'); expect(res.status).toBe(200); expect(res.body.status).toBe('ok'); expect(typeof res.body.uptime).toBe('number'); }); it('returns 404 JSON for unknown routes outside /api/v1', async () => { const app = buildApp(); const res = await app.get('/nope'); expect(res.status).toBe(404); expect(res.body).toEqual({ error: { code: 'NOT_FOUND', message: 'Route not found' } }); }); it('auth guards unknown /api/v1 sub-paths (401 before 404)', async () => { const app = buildApp(); const res = await app.get('/api/v1/does-not-exist'); expect(res.status).toBe(401); }); it('returns 401 for unknown methods on protected resources', async () => { const app = buildApp(); const res = await app.put('/api/v1/plans'); expect(res.status).toBe(401); }); it('serves the swagger docs', async () => { const app = buildApp(); const res = await app.get('/api/docs/'); expect(res.status).toBe(200); expect(res.headers['content-type']).toContain('html'); }); it('rejects a disallowed CORS origin', async () => { const app = buildApp(); const res = await app.get('/api/v1/exercises').set('Origin', 'https://evil.example.com'); expect(res.headers['access-control-allow-origin']).toBeUndefined(); }); it('allows a localhost CORS origin', async () => { const app = buildApp(); const res = await app.get('/api/v1/exercises').set('Origin', 'http://localhost:5173'); expect(res.headers['access-control-allow-origin']).toBe('http://localhost:5173'); }); it('rate limiting responds 429 with the standard JSON error body', async () => { const limited = rateLimit({ windowMs: 60_000, limit: 1, standardHeaders: 'draft-7', legacyHeaders: false, message: RATE_LIMIT_BODY, }); const app = request(createApp({ prisma, apiLimiter: limited })); expect((await app.get('/api/v1/exercises')).status).toBe(401); const res = await app.get('/api/v1/exercises'); expect(res.status).toBe(429); expect(res.headers['content-type']).toContain('application/json'); expect(res.body).toEqual(RATE_LIMIT_BODY); }); });