diff --git a/packages/node-backend/src/authclient.js b/packages/node-backend/src/authclient.js new file mode 100644 index 0000000..1399d1b --- /dev/null +++ b/packages/node-backend/src/authclient.js @@ -0,0 +1,125 @@ +// authclient.js is how any Node service in this workspace adopts a +// centralized AuthGuard instance instead of embedding auth.js's AuthStore +// directly against its own private database. +// +// A service that switches to AuthGuard trades "its own local user table" +// for "one HTTP call per request to AuthGuard's /api/session/validate", +// gaining a single shared identity across every project that does the +// same. Mirrors shared/backend/authclient (the Go equivalent) - keep the +// two in sync if either changes shape. + +const DEFAULT_COOKIE_NAME = 'auth_session'; +const DEFAULT_TIMEOUT_MS = 5000; + +export class InvalidSessionError extends Error { + constructor(message = 'authclient: invalid or missing session') { + super(message); + this.name = 'InvalidSessionError'; + } +} + +export class AuthClient { + /** + * @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required. + * @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options] + */ + constructor(baseUrl, options = {}) { + this.baseUrl = String(baseUrl ?? '').trim().replace(/\/+$/, ''); + this.cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME; + this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + this.fetchImpl = options.fetchImpl ?? fetch; + } + + /** + * Calls AuthGuard's GET /api/session/validate with token as a Bearer + * credential and returns the resolved user. Throws InvalidSessionError + * when AuthGuard reports the session as not valid, and a plain Error for + * any transport/decoding failure. + * @param {string} token + * @returns {Promise<{id: number, username: string, role: string}>} + */ + async validate(token) { + if (!this.baseUrl) { + throw new Error('authclient: client has no base URL'); + } + const trimmed = String(token ?? '').trim(); + if (!trimmed) { + throw new InvalidSessionError(); + } + + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), this.timeoutMs); + let response; + try { + response = await this.fetchImpl(`${this.baseUrl}/api/session/validate`, { + headers: { Authorization: `Bearer ${trimmed}` }, + signal: controller.signal, + }); + } catch (err) { + throw new Error(`authclient: call AuthGuard: ${err.message}`, { cause: err }); + } finally { + clearTimeout(timer); + } + + let payload; + try { + payload = await response.json(); + } catch (err) { + if (response.status === 401) { + throw new InvalidSessionError(); + } + throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err }); + } + + if (response.status !== 200 || !payload?.valid) { + throw new InvalidSessionError(); + } + return { id: payload.user_id, username: payload.username, role: payload.role }; + } + + /** + * Express middleware: extracts the session token from an incoming + * request (the configured cookie, falling back to an Authorization: + * Bearer header), validates it against AuthGuard, and either responds + * 401 or attaches the resolved user to req.authUser before calling next. + */ + middleware() { + return async (req, res, next) => { + const token = this.tokenFromRequest(req); + try { + req.authUser = await this.validate(token); + next(); + } catch { + // Fail closed on both an invalid session and a transport/decoding + // failure talking to AuthGuard - a service outage should not be + // treated as "this visitor is authenticated". + res.status(401).json({ error: 'authentication required' }); + } + }; + } + + tokenFromRequest(req) { + const header = req.headers?.authorization; + if (header?.startsWith('Bearer ')) { + const token = header.slice('Bearer '.length).trim(); + if (token) return token; + } + const cookieHeader = req.headers?.cookie; + if (cookieHeader) { + const match = cookieHeader + .split(';') + .map(part => part.trim()) + .find(part => part.startsWith(`${this.cookieName}=`)); + if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1)); + } + return ''; + } +} + +/** + * @param {string} baseUrl + * @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options] + */ +export function createAuthClient(baseUrl, options) { + return new AuthClient(baseUrl, options); +} diff --git a/packages/node-backend/src/index.js b/packages/node-backend/src/index.js index fda2b68..cd42b03 100644 --- a/packages/node-backend/src/index.js +++ b/packages/node-backend/src/index.js @@ -31,3 +31,4 @@ export { verifyTotp, } from './totp.js'; export { runMigrations } from './migrate.js'; +export { AuthClient, InvalidSessionError, createAuthClient } from './authclient.js'; diff --git a/packages/node-backend/test/authclient.test.js b/packages/node-backend/test/authclient.test.js new file mode 100644 index 0000000..2684505 --- /dev/null +++ b/packages/node-backend/test/authclient.test.js @@ -0,0 +1,83 @@ +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' }); +});