import test from 'node:test'; import assert from 'node:assert/strict'; import { AuthClient, InvalidSessionError } from '../src/authclient.js'; function fakeFetch(responses) { let call = 0; return async () => { const res = responses[Math.min(call, responses.length - 1)]; call += 1; return { status: res.status, json: async () => res.body, }; }; } test('validate resolves the user on a valid session', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]), }); const user = await client.validate('good-token'); assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' }); }); test('validate throws InvalidSessionError on an empty token', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: {} }]) }); await assert.rejects(() => client.validate(''), InvalidSessionError); await assert.rejects(() => client.validate(' '), InvalidSessionError); }); test('validate throws InvalidSessionError when AuthGuard reports invalid', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]), }); await assert.rejects(() => client.validate('bad-token'), InvalidSessionError); }); test('tokenFromRequest prefers the Authorization header over the cookie', () => { const client = new AuthClient('https://auth.example.com'); const req = { headers: { authorization: 'Bearer header-token', cookie: 'auth_session=cookie-token; other=1', }, }; assert.equal(client.tokenFromRequest(req), 'header-token'); }); test('tokenFromRequest falls back to the auth_session cookie', () => { const client = new AuthClient('https://auth.example.com'); const req = { headers: { cookie: 'other=1; auth_session=cookie-token' } }; assert.equal(client.tokenFromRequest(req), 'cookie-token'); }); test('middleware attaches authUser on success and 401s on failure', async () => { const okClient = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]), }); const req = { headers: { authorization: 'Bearer t' } }; let nextCalled = false; await okClient.middleware()(req, { status: () => ({ json: () => {} }) }, () => { nextCalled = true; }); assert.equal(nextCalled, true); assert.deepEqual(req.authUser, { id: 1, username: 'a', role: 'user' }); const badClient = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]), }); let statusCode = null; let jsonBody = null; const res = { status(code) { statusCode = code; return { json: (body) => (jsonBody = body) }; }, }; await badClient.middleware()({ headers: {} }, res, () => { throw new Error('next should not be called'); }); assert.equal(statusCode, 401); assert.deepEqual(jsonBody, { error: 'authentication required' }); });