ci: expand CI checks and make consumer sync opt-in

- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:14:31 +00:00
1 parent 199a5efaef
commit 22887fef03
100 files changed
+9740 -429

No files matched your search

+82 -13
View File
@@ -22,8 +22,16 @@
// requestPasswordReset/confirmPasswordReset, list/create/update/delete
// ManagedUser(s), setupStatus.
import { createHash } from 'node:crypto';
import { isIP } from 'node:net';
const DEFAULT_COOKIE_NAME = 'auth_session';
const DEFAULT_TIMEOUT_MS = 5000;
// validate() results, positive and negative, are reused for this long so a burst of requests
// with one token costs one AuthGuard call. Revocation through this client (logout) clears the
// entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
const VALIDATION_CACHE_TTL_MS = 2000;
const MAX_VALIDATION_CACHE_ENTRIES = 10000;
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
// constructed with a projectKey, identifying the calling project to
@@ -31,6 +39,14 @@ const DEFAULT_TIMEOUT_MS = 5000;
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
export const PROJECT_KEY_HEADER = 'X-Project-Key';
// FORWARDED_FOR_HEADER carries the end user's address on the credential calls (the `clientIp`
// option of register, login, totpVerify, totpDisable and the password-reset calls), so AuthGuard's
// per-address limits see the end user instead of this service. AuthGuard reads it only when the
// calling service's own address is in its TRUSTED_PROXIES, so sending it changes nothing for a
// deployment that has not opted in. Pass an address the caller has already verified, never a raw
// request header; anything that is not an IP address is ignored.
export const FORWARDED_FOR_HEADER = 'X-Forwarded-For';
export class InvalidSessionError extends Error {
constructor(message = 'authclient: invalid or missing session') {
super(message);
@@ -81,6 +97,40 @@ export class AuthClient {
// Normally a project's own lowercase identifier, matching the key
// ProjectConfigurator registers it under.
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
this._validationCache = new Map();
}
_validationKey(token) {
return createHash('sha256').update(token).digest('hex');
}
/** Returns the cached validate() outcome for token: a user, null for a known-invalid session, or undefined on a miss. */
_cachedValidation(token) {
const key = this._validationKey(token);
const entry = this._validationCache.get(key);
if (!entry) return undefined;
if (Date.now() >= entry.expires) {
this._validationCache.delete(key);
return undefined;
}
return entry.user;
}
_cacheValidation(token, user) {
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
const now = Date.now();
for (const [key, entry] of this._validationCache) {
if (now >= entry.expires) this._validationCache.delete(key);
}
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
// Map keeps insertion order, so this drops the oldest entry.
this._validationCache.delete(this._validationCache.keys().next().value);
}
}
this._validationCache.set(this._validationKey(token), {
user,
expires: Date.now() + VALIDATION_CACHE_TTL_MS,
});
}
_projectKeyHeaders() {
@@ -105,6 +155,7 @@ export class AuthClient {
const normalized = AuthClient._normalizeBaseUrl(baseUrl);
if (normalized) {
this.baseUrl = normalized;
this._validationCache.clear();
}
}
@@ -172,6 +223,13 @@ export class AuthClient {
if (!trimmed) {
throw new InvalidSessionError();
}
const cached = this._cachedValidation(trimmed);
if (cached === null) {
throw new InvalidSessionError();
}
if (cached !== undefined) {
return { ...cached };
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -192,15 +250,22 @@ export class AuthClient {
payload = await response.json();
} catch (err) {
if (response.status === 401) {
this._cacheValidation(trimmed, null);
throw new InvalidSessionError();
}
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
}
if (response.status !== 200 || !payload?.valid) {
if (response.status === 401 || (response.status === 200 && !payload?.valid)) {
this._cacheValidation(trimmed, null);
throw new InvalidSessionError();
}
return { id: payload.user_id, username: payload.username, role: payload.role };
if (response.status !== 200) {
throw new InvalidSessionError();
}
const user = { id: payload.user_id, username: payload.username, role: payload.role };
this._cacheValidation(trimmed, user);
return { ...user };
}
/**
@@ -258,13 +323,14 @@ export class AuthClient {
* AuthClient._call exactly.
* @returns {Promise<{payload: any, cookies: string[]}>}
*/
async _call(method, path, { token = '', body } = {}) {
async _call(method, path, { token = '', body, clientIp } = {}) {
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}`;
if (typeof clientIp === 'string' && isIP(clientIp.trim())) headers[FORWARDED_FOR_HEADER] = clientIp.trim();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -353,9 +419,10 @@ export class AuthClient {
* starting a session for it.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async register(username, email, password) {
async register(username, email, password, { clientIp } = {}) {
const { payload, cookies } = await this._call('POST', '/api/register', {
body: { username, email, password },
clientIp,
});
return { user: AuthClient._publicUser(payload), cookies };
}
@@ -366,10 +433,10 @@ export class AuthClient {
* enabled and no valid code was supplied.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async login(usernameOrEmail, password, totpToken = '') {
async login(usernameOrEmail, password, totpToken = '', { clientIp } = {}) {
const body = { username_or_email: usernameOrEmail, password };
if (totpToken) body.totp_token = totpToken;
const { payload, cookies } = await this._call('POST', '/api/login', { body });
const { payload, cookies } = await this._call('POST', '/api/login', { body, clientIp });
return { user: AuthClient._publicUser(payload), cookies };
}
@@ -381,6 +448,7 @@ export class AuthClient {
*/
async logout(token) {
const { cookies } = await this._call('POST', '/api/logout', { token });
this._validationCache.delete(this._validationKey(String(token ?? '').trim()));
return cookies;
}
@@ -411,8 +479,8 @@ export class AuthClient {
* 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 } });
async totpVerify(token, code, { clientIp } = {}) {
await this._call('POST', '/api/totp/verify', { token, body: { token: code }, clientIp });
}
/**
@@ -420,8 +488,8 @@ export class AuthClient {
* 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 } });
async totpDisable(token, code, { clientIp } = {}) {
await this._call('POST', '/api/totp/disable', { token, body: { token: code }, clientIp });
}
// --- password reset ("break glass", console-only - see AuthGuard's README) --
@@ -434,9 +502,9 @@ export class AuthClient {
* the intended place to drive this, not an individual project (see
* AuthGuard's README's "Web UI" section).
*/
async requestPasswordReset(usernameOrEmail = '') {
async requestPasswordReset(usernameOrEmail = '', { clientIp } = {}) {
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
await this._call('POST', '/api/password-reset/request', { body });
await this._call('POST', '/api/password-reset/request', { body, clientIp });
}
/**
@@ -444,9 +512,10 @@ export class AuthClient {
* relayed out-of-band and a new password, and invalidates every
* existing session for that account.
*/
async confirmPasswordReset(code, newPassword) {
async confirmPasswordReset(code, newPassword, { clientIp } = {}) {
await this._call('POST', '/api/password-reset/confirm', {
body: { code, password: newPassword },
clientIp,
});
}