Extend Go/Python/Node authclient with the full AuthGuard API surface
Previously each authclient only supported GET /api/session/validate - the "just gate requests behind a valid session" case. A service that runs its own login/register/admin-user-management screens proxied to AuthGuard (GameStream's pattern, now also used by InfiniteVideo and OutdoorGames) needs much more: register, login, logout, me, totp_enable/verify/disable, password-reset request/confirm, and managed-user list/create/update/delete. The Go client already had this full surface from GameStream's original migration; Python and Node only had validate(), so both gained the same method set as Go, mirroring its behavior and JSON wire shapes exactly (register/login/logout return the raw Set-Cookie values to forward, totp_required surfaces on a 401 from login, etc). Also adds a SetupStatus/ setup_status/setupStatus method (GET /api/setup-status) so a service's own first-launch flow can tell whether AuthGuard already has an account before showing its own account-creation form, and adds totp_enabled to the Go client's PublicUser (AuthGuard has reported it for a while; the client just hadn't picked it up). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
db733a6bf4
commit
f5a20b72af
7 files changed
+1169
-42
No files matched your search
@@ -3,10 +3,24 @@
|
||||
// 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.
|
||||
// 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;
|
||||
@@ -18,6 +32,28 @@ export class InvalidSessionError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -30,6 +66,8 @@ export class AuthClient {
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
// --- 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
|
||||
@@ -114,6 +152,250 @@ export class AuthClient {
|
||||
}
|
||||
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 = {};
|
||||
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<boolean>}
|
||||
*/
|
||||
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<string[]>}
|
||||
*/
|
||||
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<object[]>}
|
||||
*/
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user