/** * HTTP route suite — REST endpoints that sit outside tRPC. * * Covers catalogue §3.1 HTTP-02..20 (HTTP-01 lives in 00-harness.test.ts). * * These are live HTTP calls against the running backend. Where the current * implementation diverges from the catalogue's intent the case is prefixed * `(current)` and carries a comment describing the observed contract. */ import { rawMutation, rest } from '../helpers/api' import { staffSession, userSession } from '../helpers/sessions' import { userCredentials } from '../helpers/env' jest.setTimeout(180_000) /** The first entry of a tRPC batch response (or the body itself when unbatched). */ function batch0(body: unknown): any { return Array.isArray(body) ? (body as any[])[0] : (body as any) } function resultData(body: unknown): any { return batch0(body)?.result?.data } function errorCode(body: unknown): string | undefined { return batch0(body)?.error?.data?.code } function errorMessage(body: unknown): string { return String(batch0(body)?.error?.message ?? '') } async function json(res: Response): Promise { return (await res.json()) as any } /** Login a user over REST with the web caller interface and return the cookie + token. */ async function webCookieLogin() { const { identifier, password } = userCredentials() const res = await rest('/api/trpc/user.auth.login?batch=1', { method: 'POST', headers: { 'content-type': 'application/json', 'Caller-Interface': 'web' }, body: JSON.stringify({ 0: { identifier, password } }), }) const cookie = res.headers.get('set-cookie') ?? '' const match = cookie.match(/auth_token=([^;]+)/) return { res, cookie, token: match?.[1] ?? '', body: await json(res) } } describe('HTTP routes (§3.1)', () => { it('HTTP-02: GET /api/seed is public and returns OK', async () => { const res = await rest('/api/seed') expect(res.status).toBe(200) const body = await json(res) expect(body.status).toBe('OK') expect(body.timestamp).toEqual(expect.any(String)) }) it('HTTP-03: GET /api/test is reachable after the auth middleware', async () => { const staff = await staffSession() const res = await rest('/api/test', { headers: { Authorization: `Bearer ${staff.token}` } }) expect(res.status).toBe(200) const body = await json(res) expect(body.status).toBe('ok') expect(body.message).toEqual(expect.any(String)) // (current) only `/api/test` is registered; the catalogue's trailing-slash // form `/api/test/` falls through Hono's exact matcher and 404s. const slash = await rest('/api/test/', { headers: { Authorization: `Bearer ${staff.token}` } }) expect(slash.status).toBe(404) }) it('HTTP-04: GET /api/test without a token is 401 with a clear message', async () => { const res = await rest('/api/test') expect(res.status).toBe(401) const body = await json(res) expect(body.message).toMatch(/authorization token required/i) }) it('HTTP-05: GET /api/health stays 200 with an invalid token (public)', async () => { const res = await rest('/api/health', { headers: { Authorization: 'Bearer not-a-real-token' } }) expect(res.status).toBe(200) const body = await json(res) expect(body.status).toBe('OK') }) it('HTTP-06: GET /api/v1/cm/products/summary?tagId= returns tagged products', async () => { const user = await userSession() const res = await rest('/api/v1/cm/products/summary?tagId=1', { headers: { Authorization: `Bearer ${user.token}` }, }) expect(res.status).toBe(200) const body = await json(res) expect(body.count).toBeGreaterThan(0) expect(Array.isArray(body.products)).toBe(true) expect(body.products.length).toBe(body.count) }) it('HTTP-07: products summary without a token is 401', async () => { const res = await rest('/api/v1/cm/products/summary?tagId=1') expect(res.status).toBe(401) }) it('HTTP-08: products summary without tagId returns every product', async () => { const user = await userSession() const res = await rest('/api/v1/cm/products/summary', { headers: { Authorization: `Bearer ${user.token}` }, }) expect(res.status).toBe(200) const body = await json(res) expect(body.count).toBeGreaterThan(0) expect(body.products.length).toBe(body.count) }) it('HTTP-09: non-numeric tagId falls back to no filter (current parseInt semantics)', async () => { const user = await userSession() const headers = { Authorization: `Bearer ${user.token}` } const all = await json(await rest('/api/v1/cm/products/summary', { headers })) const bogus = await json(await rest('/api/v1/cm/products/summary?tagId=abc', { headers })) // parseInt('abc') -> NaN -> undefined filter, so both calls return the full list. expect(bogus.count).toBe(all.count) expect(bogus.products.length).toBe(all.products.length) }) it('HTTP-10: unknown tagId returns an empty result', async () => { const user = await userSession() const res = await rest('/api/v1/cm/products/summary?tagId=999999', { headers: { Authorization: `Bearer ${user.token}` }, }) expect(res.status).toBe(200) const body = await json(res) expect(body).toEqual({ products: [], count: 0 }) }) it('HTTP-11: products summary exposes the documented product fields', async () => { const user = await userSession() const res = await rest('/api/v1/cm/products/summary', { headers: { Authorization: `Bearer ${user.token}` }, }) const body = await json(res) const product = body.products[0] expect(typeof product.id).toBe('number') expect(typeof product.name).toBe('string') expect(['string', 'number']).toContain(typeof product.price) expect(['string', 'number']).toContain(typeof product.marketPrice) expect(product.unit === null || typeof product.unit === 'string').toBe(true) expect(typeof product.productQuantity).toBe('number') expect(typeof product.isOutOfStock).toBe('boolean') expect(Array.isArray(product.images)).toBe(true) expect(product.nextDeliveryDate === null || typeof product.nextDeliveryDate === 'string').toBe(true) }) it('HTTP-12: products summary images are public/signed asset URLs', async () => { const user = await userSession() const res = await rest('/api/v1/cm/products/summary', { headers: { Authorization: `Bearer ${user.token}` }, }) const body = await json(res) const images: string[] = body.products.flatMap((p: any) => p.images ?? []) expect(images.length).toBeGreaterThan(0) for (const image of images) { expect(image).toMatch(/^https?:\/\//) } }) it('(current) HTTP-13: unknown /api/* is 404 once authenticated, 401 otherwise', async () => { const user = await userSession() const authed = await rest('/api/does-not-exist', { headers: { Authorization: `Bearer ${user.token}` }, }) expect(authed.status).toBe(404) // (current) the catch-all `router.use('*', authenticateUser)` runs before // routing, so an unauthenticated unknown /api path fails auth first (401) // instead of 404. const anon = await rest('/api/does-not-exist') expect(anon.status).toBe(401) }) it('HTTP-14: malformed JSON is a 400 tRPC error and does not crash the worker', async () => { const res = await rawMutation('user.auth.login', null, { headers: { 'content-type': 'application/json' }, body: '{ this is not json', }) expect(res.status).toBe(400) expect(errorCode(res.body)).toBe('BAD_REQUEST') expect(errorMessage(res.body)).toMatch(/json/i) // The process is still serving after the parse error. const health = await rest('/api/health') expect(health.status).toBe(200) }) it('HTTP-15: CORS echoes an allowed origin', async () => { const res = await rest('/api/health', { headers: { Origin: 'http://localhost:5174' } }) expect(res.status).toBe(200) expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5174') }) it('HTTP-16: CORS does not echo a disallowed origin', async () => { const res = await rest('/api/health', { headers: { Origin: 'http://evil.example.com' } }) expect(res.status).toBe(200) expect(res.headers.get('access-control-allow-origin')).toBeNull() }) it('HTTP-17: CORS preflight allows Authorization and Caller-Interface', async () => { const res = await rest('/api/trpc/user.auth.login?batch=1', { method: 'OPTIONS', headers: { Origin: 'http://localhost:5174', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'content-type, authorization, caller-interface', }, }) expect(res.status).toBeLessThan(300) expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5174') const allowHeaders = (res.headers.get('access-control-allow-headers') ?? '').toLowerCase() expect(allowHeaders).toContain('authorization') expect(allowHeaders).toContain('caller-interface') const allowMethods = (res.headers.get('access-control-allow-methods') ?? '').toUpperCase() expect(allowMethods).toContain('POST') }) it('HTTP-18: web caller-interface login sets an auth cookie', async () => { const { res, cookie } = await webCookieLogin() expect(res.status).toBe(200) expect(cookie).toMatch(/auth_token=/) }) it('HTTP-19: a cookie-only request is authenticated (no bearer)', async () => { const { token } = await webCookieLogin() expect(token.length).toBeGreaterThan(20) const res = await rest('/api/trpc/user.user.getSelfData?batch=1&input=%7B%7D', { headers: { cookie: `auth_token=${token}` }, }) expect(res.status).toBe(200) const data = resultData(await json(res)) expect(data?.success).toBe(true) expect(data?.data?.user?.id).toEqual(expect.any(Number)) }) it('HTTP-20: the auth cookie carries HttpOnly/Secure/SameSite=Lax/Path=/', async () => { const { cookie } = await webCookieLogin() expect(cookie).toMatch(/HttpOnly/i) expect(cookie).toMatch(/Secure/i) expect(cookie).toMatch(/SameSite=Lax/i) expect(cookie).toMatch(/Path=\//i) }) })