import test from 'node:test'; import assert from 'node:assert/strict'; import { APIError, 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; const bodyText = res.body === undefined ? '' : JSON.stringify(res.body); return { status: res.status, ok: res.status >= 200 && res.status < 300, json: async () => res.body, text: async () => bodyText, headers: { getSetCookie: () => res.cookies ?? [] }, }; }; } // Records every (url, init) pair a fakeFetch call received, for assertions // on method/headers/body without a full fetch mock library. function recordingFetch(responses) { const calls = []; const inner = fakeFetch(responses); const wrapped = async (url, init) => { calls.push({ url, init }); return inner(url, init); }; wrapped.calls = calls; return wrapped; } test('constructor assumes https for a bare public host', () => { assert.equal(new AuthClient('auth.example.com').baseUrl, 'https://auth.example.com'); assert.equal(new AuthClient('auth.example.com:8080').baseUrl, 'https://auth.example.com:8080'); }); test('constructor assumes http for a bare private/loopback/link-local host', () => { assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'http://192.168.1.50:8080'); assert.equal(new AuthClient('10.1.2.3:8080').baseUrl, 'http://10.1.2.3:8080'); assert.equal(new AuthClient('172.20.0.5:8080').baseUrl, 'http://172.20.0.5:8080'); assert.equal(new AuthClient('127.0.0.1:8080').baseUrl, 'http://127.0.0.1:8080'); assert.equal(new AuthClient('169.254.1.1:8080').baseUrl, 'http://169.254.1.1:8080'); assert.equal(new AuthClient('localhost:8080').baseUrl, 'http://localhost:8080'); assert.equal(new AuthClient('authguard.local:8080').baseUrl, 'http://authguard.local:8080'); assert.equal(new AuthClient('[::1]:8080').baseUrl, 'http://[::1]:8080'); assert.equal(new AuthClient('[fd00::1]:8080').baseUrl, 'http://[fd00::1]:8080'); }); test('constructor assumes https for a 172.x address outside the 16-31 private range', () => { assert.equal(new AuthClient('172.32.0.5:8080').baseUrl, 'https://172.32.0.5:8080'); }); test('constructor leaves an explicit scheme alone', () => { assert.equal(new AuthClient('http://auth.example.com').baseUrl, 'http://auth.example.com'); assert.equal(new AuthClient('https://auth.example.com').baseUrl, 'https://auth.example.com'); assert.equal(new AuthClient('HTTP://auth.example.com').baseUrl, 'HTTP://auth.example.com'); assert.equal(new AuthClient('https://192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080'); }); test('constructor strips a trailing slash before checking the scheme', () => { assert.equal(new AuthClient('auth.example.com/').baseUrl, 'https://auth.example.com'); }); test('constructor trims whitespace and leaves an empty base URL empty', () => { assert.equal(new AuthClient(' auth.example.com ').baseUrl, 'https://auth.example.com'); assert.equal(new AuthClient('').baseUrl, ''); }); test('setBaseUrl retargets a pending client (constructed with "") to its first real URL', async () => { const client = new AuthClient('', { fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]), }); await assert.rejects(() => client.validate('good-token'), /no base URL/); client.setBaseUrl('https://auth.example.com'); assert.equal(client.baseUrl, 'https://auth.example.com'); const user = await client.validate('good-token'); assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' }); }); test('setBaseUrl ignores a blank value, leaving the previous URL in place', () => { const client = new AuthClient('https://auth.example.com'); client.setBaseUrl(' '); assert.equal(client.baseUrl, 'https://auth.example.com'); }); 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('validate reuses a positive and a negative answer within the cache window', async () => { const fetchImpl = recordingFetch([ { status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }, { status: 401, body: { valid: false } }, ]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); assert.deepEqual(await client.validate('good-token'), { id: 7, username: 'gabriel', role: 'admin' }); assert.deepEqual(await client.validate('good-token'), { id: 7, username: 'gabriel', role: 'admin' }); await assert.rejects(() => client.validate('bad-token'), InvalidSessionError); await assert.rejects(() => client.validate('bad-token'), InvalidSessionError); assert.equal(fetchImpl.calls.length, 2); }); test('logout drops the cached answer for that token', async () => { const fetchImpl = recordingFetch([ { status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }, { status: 200, body: {} }, { status: 401, body: { valid: false } }, ]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.validate('good-token'); await client.logout('good-token'); await assert.rejects(() => client.validate('good-token'), InvalidSessionError); assert.equal(fetchImpl.calls.length, 3); }); test('setBaseUrl clears cached answers', async () => { const fetchImpl = recordingFetch([ { status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }, ]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.validate('good-token'); client.setBaseUrl('https://auth2.example.com'); await client.validate('good-token'); assert.equal(fetchImpl.calls.length, 2); }); 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('tokenFromRequest treats a malformed cookie escape as no token', () => { const client = new AuthClient('https://auth.example.com'); const req = { headers: { cookie: 'auth_session=bad%zz; other=1' } }; assert.equal(client.tokenFromRequest(req), ''); }); test('middleware answers 401 instead of rejecting on a malformed cookie', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]), }); let statusCode = null; const res = { status(code) { statusCode = code; return { json: () => {} }; }, }; await client.middleware()({ headers: { cookie: 'auth_session=100%' } }, res, () => { throw new Error('next should not be called'); }); assert.equal(statusCode, 401); }); 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' }); }); // --- register/login/.../setupStatus: the additional surface a service that // runs its own login/admin screens proxied to AuthGuard needs, beyond the // original validate()-only surface. --- test('setupStatus reflects AuthGuard setup_required', async () => { for (const setupRequired of [true, false]) { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: { setup_required: setupRequired } }]), }); assert.equal(await client.setupStatus(), setupRequired); } }); test('register returns the user and forwards Set-Cookie values', async () => { const fetchImpl = recordingFetch([ { status: 201, body: { user: { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', totp_enabled: false } }, cookies: ['auth_session=abc; HttpOnly'], }, ]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); const result = await client.register('root', 'root@example.com', 'correct horse battery staple'); assert.deepEqual(result.user, { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', totpEnabled: false, }); assert.deepEqual(result.cookies, ['auth_session=abc; HttpOnly']); const sent = JSON.parse(fetchImpl.calls[0].init.body); assert.deepEqual(sent, { username: 'root', email: 'root@example.com', password: 'correct horse battery staple' }); }); test('login success reports totpEnabled from AuthGuard', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([ { status: 200, body: { user: { id: 2, username: 'alice', email: 'alice@example.com', role: 'user', totp_enabled: true } }, cookies: ['auth_session=xyz'], }, ]), }); const result = await client.login('alice', 'correct horse battery staple', '123456'); assert.equal(result.user.username, 'alice'); assert.equal(result.user.totpEnabled, true); assert.deepEqual(result.cookies, ['auth_session=xyz']); }); test('login raises APIError with totpRequired on a 401 asking for a code', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([ { status: 401, body: { error: 'two-factor authentication code required', totp_required: true } }, ]), }); await assert.rejects( () => client.login('alice', 'correct horse battery staple'), (err) => err instanceof APIError && err.statusCode === 401 && err.totpRequired === true, ); }); test('login raises APIError without totpRequired on invalid credentials', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 401, body: { error: 'invalid username/email or password' } }]), }); await assert.rejects( () => client.login('alice', 'wrong password'), (err) => err instanceof APIError && err.totpRequired === false && err.detailMessage === 'invalid username/email or password', ); }); test('logout returns the clearing cookies', async () => { const fetchImpl = recordingFetch([{ status: 200, body: { ok: true }, cookies: ['auth_session=; Max-Age=0'] }]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); const cookies = await client.logout('a-token'); assert.deepEqual(cookies, ['auth_session=; Max-Age=0']); assert.equal(fetchImpl.calls[0].init.headers.Authorization, 'Bearer a-token'); }); test('me resolves the public user', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([ { status: 200, body: { user: { id: 3, username: 'bob', email: 'bob@example.com', role: 'admin', totp_enabled: false } } }, ]), }); const user = await client.me('a-token'); assert.equal(user.id, 3); assert.equal(user.role, 'admin'); }); test('totpEnable returns the provisioned secret', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: { secret: 'SECRET', otpauth_url: 'otpauth://...', enabled: false } }]), }); const result = await client.totpEnable('a-token'); assert.equal(result.secret, 'SECRET'); assert.equal(result.enabled, false); }); test('totpVerify and totpDisable send the code as {token}', async () => { let fetchImpl = recordingFetch([{ status: 200, body: { enabled: true } }]); let client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.totpVerify('a-token', '123456'); assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '123456' }); fetchImpl = recordingFetch([{ status: 200, body: { enabled: false } }]); client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.totpDisable('a-token', '654321'); assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '654321' }); }); test('requestPasswordReset with no identifier sends an empty body (targets the superadmin)', async () => { const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.requestPasswordReset(); assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), {}); }); test('confirmPasswordReset sends the code and new password', async () => { const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.confirmPasswordReset('ABCD1234', 'a brand new passphrase'); assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { code: 'ABCD1234', password: 'a brand new passphrase' }); }); test('listManagedUsers maps every row', async () => { const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([ { status: 200, body: { users: [ { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', created_at: '2026-01-01T00:00:00Z' }, { id: 2, username: 'bob', email: 'bob@example.com', role: 'user', created_at: '2026-01-02T00:00:00Z' }, ], }, }, ]), }); const users = await client.listManagedUsers('a-token'); assert.equal(users.length, 2); assert.deepEqual(users[0], { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', createdAt: '2026-01-01T00:00:00Z', }); }); test('createManagedUser sends only the given fields', async () => { const fetchImpl = recordingFetch([ { status: 201, body: { user: { id: 4, username: 'carol', email: 'carol@example.com', role: 'user', created_at: '' } } }, ]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); const created = await client.createManagedUser('a-token', { username: 'carol', email: 'carol@example.com', password: 'correct horse battery staple', }); assert.equal(created.username, 'carol'); const sent = JSON.parse(fetchImpl.calls[0].init.body); assert.equal('role' in sent, false); }); test('updateManagedUser PUTs to /api/admin/users/{id}', async () => { const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.updateManagedUser('a-token', 5, { email: 'new@example.com' }); assert.equal(fetchImpl.calls[0].init.method, 'PUT'); assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/5'); assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { email: 'new@example.com' }); }); test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => { const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]); const client = new AuthClient('https://auth.example.com', { fetchImpl }); await client.deleteManagedUser('a-token', 6); assert.equal(fetchImpl.calls[0].init.method, 'DELETE'); assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6'); }); test('credential calls send the end user address as X-Forwarded-For when given a clientIp', async () => { const user = { id: 1, username: 'a', email: '', role: 'user' }; const fetchImpl = recordingFetch([{ status: 200, body: { user } }]); const client = new AuthClient('https://authguard.example', { fetchImpl }); await client.login('a', 'secret-password', '', { clientIp: '203.0.113.9' }); await client.register('a', 'a@b.com', 'secret-password', { clientIp: '2001:db8::1' }); await client.totpVerify('tok', '123456', { clientIp: '203.0.113.9' }); await client.totpDisable('tok', '123456', { clientIp: '203.0.113.9' }); await client.requestPasswordReset('a', { clientIp: '203.0.113.9' }); await client.confirmPasswordReset('CODE', 'secret-password', { clientIp: '203.0.113.9' }); assert.deepEqual( fetchImpl.calls.map((call) => call.init.headers['X-Forwarded-For']), ['203.0.113.9', '2001:db8::1', '203.0.113.9', '203.0.113.9', '203.0.113.9', '203.0.113.9'], ); }); test('no X-Forwarded-For is sent without a clientIp, or for a value that is not an IP address', async () => { const user = { id: 1, username: 'a', email: '', role: 'user' }; const fetchImpl = recordingFetch([{ status: 200, body: { user } }]); const client = new AuthClient('https://authguard.example', { fetchImpl }); await client.login('a', 'secret-password'); await client.login('a', 'secret-password', '', { clientIp: '203.0.113.9\r\nX-Evil: 1' }); await client.login('a', 'secret-password', '', { clientIp: 'not-an-ip' }); await client.me('tok'); for (const call of fetchImpl.calls) { assert.equal('X-Forwarded-For' in call.init.headers, false); } });