Add Node.js authclient (mirrors the Go shared/backend/authclient)
Lets any Node service validate requests against AuthGuard instead of maintaining its own local user table - the missing piece needed to wire AuthGuard into OutdoorGamesPlatform/server-node and any other Node service, matching what authclient already provides for Go. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
51a8e11ef6
commit
858cc1ac63
3 files changed
+209
No files matched your search
@@ -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);
|
||||||
|
}
|
||||||
@@ -31,3 +31,4 @@ export {
|
|||||||
verifyTotp,
|
verifyTotp,
|
||||||
} from './totp.js';
|
} from './totp.js';
|
||||||
export { runMigrations } from './migrate.js';
|
export { runMigrations } from './migrate.js';
|
||||||
|
export { AuthClient, InvalidSessionError, createAuthClient } from './authclient.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' });
|
||||||
|
});
|
||||||
Reference in new issue
Block a user