125 lines
4.3 KiB
JavaScript
125 lines
4.3 KiB
JavaScript
// 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);
|
||
|
|
}
|