// 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 "HTTP calls to AuthGuard's API", gaining a single shared identity // across every project that does the same. Mirrors shared/backend/authclient // (the Go equivalent) and shared/packages/python-backend/src/shared_backend/authclient.py // (the Python equivalent) - keep all three in sync if any changes shape. // // Two kinds of consumer, two parts of this module: // // - A service that only needs to gate requests behind "is this a valid // AuthGuard session" uses `AuthClient.validate` / `tokenFromRequest` / // `middleware()`, calling only GET /api/session/validate. This is the // original, minimal surface of this module. // - A service that runs its own login/register/admin-user-management // screens proxied to AuthGuard (mirroring shared/backend/authclient's full // method set - see e.g. Original/GameStream/backend/cmd/gamestreamd/auth.go // for the reference Go implementation of this pattern) uses the additional // methods below: register, login, logout, me, totpEnable/Verify/Disable, // requestPasswordReset/confirmPasswordReset, list/create/update/delete // ManagedUser(s), setupStatus. const DEFAULT_COOKIE_NAME = 'auth_session'; const DEFAULT_TIMEOUT_MS = 5000; // PROJECT_KEY_HEADER is the header AuthClient attaches to every request when // constructed with a projectKey, identifying the calling project to // AuthGuard so it can enforce per-user project-access restriction (see // AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader. export const PROJECT_KEY_HEADER = 'X-Project-Key'; export class InvalidSessionError extends Error { constructor(message = 'authclient: invalid or missing session') { super(message); this.name = 'InvalidSessionError'; } } // APIError is raised when AuthGuard responds with a non-2xx status to one of // the register/login/.../setupStatus methods below (not raised by // validate(), which uses InvalidSessionError for its one specific non-2xx // case). Mirrors Go's *authclient.APIError / Python's APIError - carries the // status code and (when AuthGuard's JSON body decoded successfully) its // {"error": "..."} message, so a caller can map it back onto its own // service's response shape/status code rather than exposing AuthGuard's // wording verbatim. export class APIError extends Error { constructor(statusCode, message, { totpRequired = false } = {}) { super(`authclient: authguard responded ${statusCode}: ${message}`); this.name = 'APIError'; this.statusCode = statusCode; this.detailMessage = message; // Mirrors AuthGuard's {"totp_required": true} flag on a 401 from // POST /api/login that means "credentials were correct, but this // account has two-factor auth enabled and no (or an incorrect) code // was supplied" - distinct from a plain invalid-credentials 401. this.totpRequired = totpRequired; } } export class AuthClient { /** * @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required. * May be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") - * the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 private, * or link-local address, or a ".local" name, defaults to "http://" (a plain-HTTP * AuthGuard on a local network is the common case for those), anything else * defaults to "https://". An explicit "http://" or "https://" is always left * as-is, overriding the inference. * @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch, projectKey?: string}} [options] */ constructor(baseUrl, options = {}) { this.baseUrl = AuthClient._normalizeBaseUrl(baseUrl); this.cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME; this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; this.fetchImpl = options.fetchImpl ?? fetch; // projectKey identifies this project to AuthGuard on every request (see // PROJECT_KEY_HEADER), enabling per-user project-access restriction. // Normally a project's own lowercase identifier, matching the key // ProjectConfigurator registers it under. this.projectKey = String(options.projectKey ?? '').trim().toLowerCase(); } _projectKeyHeaders() { return this.projectKey ? { [PROJECT_KEY_HEADER]: this.projectKey } : {}; } /** * Atomically replaces the AuthGuard base URL this client calls, * normalizing it the same way the constructor does. Mirrors Go's * authclient.Client.SetBaseURL / Python's AuthClient.set_base_url / Java's * AuthClient#setBaseUrl: the intended use is a project's own * coreconfig-equivalent push handler calling this on its live AuthClient * instance so a freshly pushed AuthGuard URL takes effect on the client's * very next call with no restart - including the very first URL a client * constructed with baseUrl "" (a "pending" client, not yet configured but * still meant to be used) ever receives. A blank baseUrl is ignored * (leaving the previous value in place) rather than leaving the client * unable to reach AuthGuard at all. * @param {string} baseUrl */ setBaseUrl(baseUrl) { const normalized = AuthClient._normalizeBaseUrl(baseUrl); if (normalized) { this.baseUrl = normalized; } } static _normalizeBaseUrl(baseUrl) { const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, ''); if (!trimmed) return trimmed; if (/^https?:\/\//i.test(trimmed)) return trimmed; return AuthClient._isPrivateHost(trimmed) ? `http://${trimmed}` : `https://${trimmed}`; } /** * Reports whether hostport (a bare "host" or "host:port", no scheme) names * a loopback, RFC1918/RFC4193 private, or link-local address, or a * ".local" mDNS name - the kind of host a plain-HTTP AuthGuard is * typically reachable at on a local network, as opposed to a public * hostname expected to terminate TLS itself. Never performs DNS * resolution: only literal IPs and the "localhost"/".local" names are * recognized, so a real public hostname that merely happens to resolve to * a private address still defaults to https. */ static _isPrivateHost(hostport) { let host = hostport; if (host.startsWith('[')) { const end = host.indexOf(']'); if (end !== -1) host = host.slice(1, end); } else { const parts = host.split(':'); if (parts.length === 2 && /^\d+$/.test(parts[1])) host = parts[0]; } host = host.toLowerCase(); if (host === 'localhost' || host.endsWith('.local')) return true; const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); if (ipv4) { const a = Number(ipv4[1]); const b = Number(ipv4[2]); return ( a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) ); } if (host === '::1') return true; if (/^fe80:/.test(host)) return true; if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; return false; } // --- session validation (the original, minimal surface) ----------------- /** * 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}`, ...this._projectKeyHeaders() }, 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) => { try { req.authUser = await this.validate(this.tokenFromRequest(req)); 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) { // A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent. try { return decodeURIComponent(match.slice(this.cookieName.length + 1)); } catch { return ''; } } } return ''; } // --- shared request/response plumbing for everything below -------------- /** * Runs one JSON request/response round trip against AuthGuard. Returns * the decoded JSON body (an empty object for a 2xx response with no * body) and the raw Set-Cookie header value(s) the response carried. * Throws APIError for a non-2xx response, a plain Error for a * transport/decoding failure - mirrors Go's Client.call / Python's * AuthClient._call exactly. * @returns {Promise<{payload: any, cookies: string[]}>} */ async _call(method, path, { token = '', body } = {}) { if (!this.baseUrl) { throw new Error('authclient: client has no base URL'); } const headers = { ...this._projectKeyHeaders() }; if (body !== undefined) headers['Content-Type'] = 'application/json'; if (token) headers.Authorization = `Bearer ${token}`; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeoutMs); let response; try { response = await this.fetchImpl(`${this.baseUrl}${path}`, { method, headers, body: body !== undefined ? JSON.stringify(body) : undefined, signal: controller.signal, }); } catch (err) { throw new Error(`authclient: call AuthGuard: ${err.message}`, { cause: err }); } finally { clearTimeout(timer); } // fetch's Headers.getSetCookie() (Node >= 18.14 / undici) returns every // Set-Cookie header value separately, unlike .get('set-cookie') which // would fold them into one comma-joined string and break parsing. const cookies = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []; let payload = {}; const text = await response.text(); if (text) { try { payload = JSON.parse(text); } catch (err) { if (!response.ok) { throw new APIError(response.status, `request failed (${response.status})`); } throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err }); } } if (!response.ok) { const message = payload?.error || `request failed (${response.status})`; throw new APIError(response.status, message, { totpRequired: Boolean(payload?.totp_required) }); } return { payload, cookies }; } static _publicUser(payload) { const user = payload?.user ?? {}; return { id: user.id, username: user.username ?? '', email: user.email ?? '', role: user.role ?? '', totpEnabled: Boolean(user.totp_enabled), }; } static _managedUser(user) { return { id: user?.id, username: user?.username ?? '', email: user?.email ?? '', role: user?.role ?? '', createdAt: user?.created_at ?? '', }; } // --- setup / registration ------------------------------------------------- /** * Calls GET /api/setup-status, an unauthenticated endpoint that reports * whether AuthGuard has any account at all. Accounts are centralized in * AuthGuard, so a caller with its own "first launch, create the initial * admin" flow should consult this first: when it returns false, some * account already exists (possibly created by a different project, or * directly against AuthGuard), and the caller should show its ordinary * login screen instead of its own account-creation form. * @returns {Promise} */ async setupStatus() { const { payload } = await this._call('GET', '/api/setup-status'); return Boolean(payload.setup_required); } /** * Calls POST /api/register, creating a new AuthGuard account and * starting a session for it. * @returns {Promise<{user: object, cookies: string[]}>} */ async register(username, email, password) { const { payload, cookies } = await this._call('POST', '/api/register', { body: { username, email, password }, }); return { user: AuthClient._publicUser(payload), cookies }; } /** * Calls POST /api/login. totpToken may be empty; AuthGuard raises an * APIError with totpRequired set when the account has two-factor auth * enabled and no valid code was supplied. * @returns {Promise<{user: object, cookies: string[]}>} */ async login(usernameOrEmail, password, totpToken = '') { const body = { username_or_email: usernameOrEmail, password }; if (totpToken) body.totp_token = totpToken; const { payload, cookies } = await this._call('POST', '/api/login', { body }); return { user: AuthClient._publicUser(payload), cookies }; } /** * Calls POST /api/logout, deleting the session identified by token * server-side. Returns the (cookie-clearing) Set-Cookie header value(s) * AuthGuard's response carried. * @returns {Promise} */ async logout(token) { const { cookies } = await this._call('POST', '/api/logout', { token }); return cookies; } /** Calls GET /api/me, resolving token to its account. */ async me(token) { const { payload } = await this._call('GET', '/api/me', { token }); return AuthClient._publicUser(payload); } // --- TOTP ----------------------------------------------------------------- /** * Calls POST /api/totp/enable, provisioning (or re-provisioning) a * pending TOTP secret for token's account. The secret is not active * until totpVerify confirms a generated code. * @returns {Promise<{secret: string, otpauthUrl: string, enabled: boolean}>} */ async totpEnable(token) { const { payload } = await this._call('POST', '/api/totp/enable', { token }); return { secret: payload.secret ?? '', otpauthUrl: payload.otpauth_url ?? '', enabled: Boolean(payload.enabled), }; } /** * Calls POST /api/totp/verify, confirming code against the pending * secret totpEnable provisioned and activating two-factor auth. */ async totpVerify(token, code) { await this._call('POST', '/api/totp/verify', { token, body: { token: code } }); } /** * Calls POST /api/totp/disable, turning two-factor auth off for token's * account. AuthGuard requires code to be one last valid TOTP code as * proof of possession. */ async totpDisable(token, code) { await this._call('POST', '/api/totp/disable', { token, body: { token: code } }); } // --- password reset ("break glass", console-only - see AuthGuard's README) -- /** * Calls POST /api/password-reset/request. AuthGuard prints a one-time * code to its own process console; only an operator with access to that * console can relay it onward. Called with no usernameOrEmail, the * target is AuthGuard's superadmin account - AuthGuard's own web UI is * the intended place to drive this, not an individual project (see * AuthGuard's README's "Web UI" section). */ async requestPasswordReset(usernameOrEmail = '') { const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {}; await this._call('POST', '/api/password-reset/request', { body }); } /** * Calls POST /api/password-reset/confirm with the code an operator * relayed out-of-band and a new password, and invalidates every * existing session for that account. */ async confirmPasswordReset(code, newPassword) { await this._call('POST', '/api/password-reset/confirm', { body: { code, password: newPassword }, }); } // --- admin user management -------------------------------------------------- /** * Calls GET /api/admin/users. token's account must satisfy AuthGuard's * CanManageUsers check (admin or superadmin), or this throws an * APIError with statusCode 401/403. * @returns {Promise} */ async listManagedUsers(token) { const { payload } = await this._call('GET', '/api/admin/users', { token }); return (payload.users ?? []).map(AuthClient._managedUser); } /** * Calls POST /api/admin/users. Only a superadmin actor may set role to * anything other than "user"; anyone else's requested role is silently * ignored by AuthGuard. * @param {{username: string, email: string, password: string, role?: string}} input */ async createManagedUser(token, input) { const { payload } = await this._call('POST', '/api/admin/users', { token, body: input }); return AuthClient._managedUser(payload.user); } /** * Calls PUT /api/admin/users/{id}. An omitted field means "leave * unchanged" (AuthGuard applies only non-empty fields); role is only * honored per AuthGuard's own authorization rules (only a superadmin * actor, and never onto/away from a superadmin target) - this client * does not re-implement or pre-validate those rules. * @param {{username?: string, email?: string, password?: string, role?: string}} input */ async updateManagedUser(token, id, input) { await this._call('PUT', `/api/admin/users/${encodeURIComponent(id)}`, { token, body: input }); } /** Calls DELETE /api/admin/users/{id}. */ async deleteManagedUser(token, id) { await this._call('DELETE', `/api/admin/users/${encodeURIComponent(id)}`, { token }); } } /** * @param {string} baseUrl * @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options] */ export function createAuthClient(baseUrl, options) { return new AuthClient(baseUrl, options); }