Sync shared snapshot from f585792

This commit is contained in:
Gabriel20xx committed 2026-09-13 21:09:52 +02:00
1 parent 803c3ab3ce
commit aae8d3807d
4 files changed
+71 -4

No files matched your search

@@ -0,0 +1,5 @@
---
"@gabriel20xx/node-backend": patch
---
`AuthClient` accepts a `projectKey` option, sent as `X-Project-Key` on every request, so AuthGuard can enforce per-user project-access restriction for Node consumers the same way the Go and Python clients already do.
@@ -98,6 +98,14 @@ public final class AuthClient {
public static final String DEFAULT_COOKIE_NAME = "auth_session";
public static final int DEFAULT_TIMEOUT_MILLIS = 5000;
/**
* Header attached to every request when the client is 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
* {@code authclient.ProjectKeyHeader}.
*/
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
@@ -110,6 +118,7 @@ public final class AuthClient {
private final String baseUrl;
private final String cookieName;
private final int timeoutMillis;
private final String projectKey;
public AuthClient(String baseUrl) {
this(baseUrl, DEFAULT_COOKIE_NAME, DEFAULT_TIMEOUT_MILLIS);
@@ -126,9 +135,24 @@ public final class AuthClient {
* @param timeoutMillis connect and read timeout used by {@link #validate(String)}.
*/
public AuthClient(String baseUrl, String cookieName, int timeoutMillis) {
this(baseUrl, cookieName, timeoutMillis, "");
}
/**
* @param baseUrl AuthGuard's base URL (e.g. {@code https://auth.example.com}), no trailing slash required.
* @param cookieName cookie {@link #extractToken} falls back to when there is no Authorization header;
* blank/null defaults to {@link #DEFAULT_COOKIE_NAME}.
* @param timeoutMillis connect and read timeout used by {@link #validate(String)}.
* @param projectKey identifies this project to AuthGuard on every request (see
* {@link #PROJECT_KEY_HEADER}), enabling per-user project-access
* restriction. Normally a project's own lowercase identifier, matching
* the key ProjectConfigurator registers it under. Blank/null disables it.
*/
public AuthClient(String baseUrl, String cookieName, int timeoutMillis, String projectKey) {
this.baseUrl = normalizeBaseUrl(baseUrl);
this.cookieName = cookieName == null || cookieName.trim().isEmpty() ? DEFAULT_COOKIE_NAME : cookieName.trim();
this.timeoutMillis = timeoutMillis;
this.projectKey = projectKey == null ? "" : projectKey.trim().toLowerCase();
}
/**
@@ -583,6 +607,9 @@ public final class AuthClient {
connection.setRequestMethod(method);
connection.setConnectTimeout(timeoutMillis);
connection.setReadTimeout(timeoutMillis);
if (!projectKey.isEmpty()) {
connection.setRequestProperty(PROJECT_KEY_HEADER, projectKey);
}
if (token != null && !token.isEmpty()) {
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
}
@@ -673,6 +700,9 @@ public final class AuthClient {
URL url = new URL(baseUrl + "/api/session/validate");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (!projectKey.isEmpty()) {
connection.setRequestProperty(PROJECT_KEY_HEADER, projectKey);
}
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
connection.setConnectTimeout(timeoutMillis);
connection.setReadTimeout(timeoutMillis);
+18 -3
View File
@@ -25,6 +25,12 @@
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);
@@ -63,13 +69,22 @@ export class AuthClient {
* 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}} [options]
* @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 } : {};
}
static _normalizeBaseUrl(baseUrl) {
@@ -142,7 +157,7 @@ export class AuthClient {
let response;
try {
response = await this.fetchImpl(`${this.baseUrl}/api/session/validate`, {
headers: { Authorization: `Bearer ${trimmed}` },
headers: { Authorization: `Bearer ${trimmed}`, ...this._projectKeyHeaders() },
signal: controller.signal,
});
} catch (err) {
@@ -220,7 +235,7 @@ export class AuthClient {
if (!this.baseUrl) {
throw new Error('authclient: client has no base URL');
}
const headers = {};
const headers = { ...this._projectKeyHeaders() };
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
@@ -61,6 +61,12 @@ DEFAULT_TIMEOUT = 5.0
_BEARER_PREFIX = "Bearer "
# PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
# constructed with project_key, 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.
PROJECT_KEY_HEADER = "X-Project-Key"
def _normalize_base_url(base_url: str) -> str:
trimmed = str(base_url or "").strip().rstrip("/")
@@ -205,6 +211,7 @@ class AuthClient:
*,
cookie_name: str = DEFAULT_COOKIE_NAME,
timeout: float = DEFAULT_TIMEOUT,
project_key: str = "",
) -> None:
"""base_url is AuthGuard's base URL, e.g. "https://auth.example.com"
(no trailing slash required). May be given without a scheme (e.g.
@@ -221,6 +228,11 @@ class AuthClient:
self.base_url = _normalize_base_url(base_url)
self.cookie_name = cookie_name
self.timeout = timeout
# project_key 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.
self.project_key = (project_key or "").strip().lower()
# --- session validation (the original, minimal surface) ----------------
@@ -238,9 +250,12 @@ class AuthClient:
return await asyncio.to_thread(self._validate_sync, trimmed)
def _validate_sync(self, token: str) -> AuthGuardUser:
headers = {"Authorization": f"{_BEARER_PREFIX}{token}"}
if self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key
request = urllib.request.Request(
f"{self.base_url}/api/session/validate",
headers={"Authorization": f"{_BEARER_PREFIX}{token}"},
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
@@ -301,6 +316,8 @@ class AuthClient:
) -> tuple[dict[str, Any], list[str]]:
data = None
headers: dict[str, str] = {}
if self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"