206 lines
6.9 KiB
JavaScript
206 lines
6.9 KiB
JavaScript
/**
|
|
* Lets any Node service in this workspace receive AuthGuard's and
|
|
* CarrierNode's current base URL(s) pushed from ProjectConfigurator, instead
|
|
* of hardcoding them in its own env vars. Mirrors shared/backend/coreconfig
|
|
* (Go) and shared/packages/python-backend/src/shared_backend/coreconfig.py
|
|
* (Python) exactly - same Info shape, same Store semantics - translated to
|
|
* Node idioms; keep all three in sync if any changes shape. See
|
|
* ProjectConfigurator/README.md's "Pushing core service info to other
|
|
* projects" section for the wire contract this module implements the
|
|
* receiving end of.
|
|
*
|
|
* Framework-agnostic: this module has no HTTP server of its own. A service
|
|
* wires the actual `PUT /api/core-services/internal` route in its own
|
|
* framework (Express, plain `http`, ...), gated behind its own
|
|
* SECRET check the same way its other internal-service
|
|
* routes already are, decodes the JSON body with `Info.fromJSON`, and calls
|
|
* `store.set(info)` - see `Store.set`'s doc comment for a minimal Express
|
|
* example.
|
|
*/
|
|
|
|
import crypto from 'node:crypto';
|
|
|
|
/**
|
|
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
|
|
*/
|
|
|
|
export class Info {
|
|
/**
|
|
* @param {InfoLike} [fields]
|
|
*/
|
|
constructor({ authGuardUrl = '', carrierNodeUrl = '', carrierNodeUrls = [] } = {}) {
|
|
this.authGuardUrl = authGuardUrl;
|
|
this.carrierNodeUrl = carrierNodeUrl;
|
|
this.carrierNodeUrls = carrierNodeUrls;
|
|
}
|
|
|
|
/** Decodes the JSON body ProjectConfigurator's push carries (coreServiceInfo). */
|
|
static fromJSON(data) {
|
|
const raw = data ?? {};
|
|
let urls = Array.isArray(raw.carrierNodeUrls)
|
|
? raw.carrierNodeUrls.map((u) => String(u ?? '').trim()).filter(Boolean)
|
|
: [];
|
|
if (urls.length === 0) {
|
|
const single = String(raw.carrierNodeUrl ?? '').trim();
|
|
if (single) urls = [single];
|
|
}
|
|
return new Info({
|
|
authGuardUrl: String(raw.authGuardUrl ?? '').trim(),
|
|
carrierNodeUrl: urls[0] ?? '',
|
|
carrierNodeUrls: urls,
|
|
});
|
|
}
|
|
|
|
toJSON() {
|
|
return {
|
|
authGuardUrl: this.authGuardUrl,
|
|
carrierNodeUrl: this.carrierNodeUrl,
|
|
carrierNodeUrls: [...this.carrierNodeUrls],
|
|
};
|
|
}
|
|
}
|
|
|
|
/** Shortest SECRET a service accepts for its internal routes. */
|
|
export const MIN_INTERNAL_SECRET_LENGTH = 16;
|
|
|
|
/**
|
|
* Placeholders from .env.example files and the bare variable name. They are
|
|
* public, so they never gate a route.
|
|
*/
|
|
export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']);
|
|
|
|
/**
|
|
* True when the configured secret is strong enough to gate an internal route:
|
|
* at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
|
* placeholder. Length counts characters, as the Python and Go helpers do.
|
|
* @param {unknown} secret
|
|
* @returns {boolean}
|
|
*/
|
|
export function internalSecretUsable(secret) {
|
|
const value = String(secret ?? '');
|
|
return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value);
|
|
}
|
|
|
|
/**
|
|
* True when the X-Internal-Auth value equals the configured secret. A secret
|
|
* that is not usable (see internalSecretUsable) never matches, and the
|
|
* comparison is constant-time.
|
|
* @param {unknown} provided
|
|
* @param {unknown} secret
|
|
* @returns {boolean}
|
|
*/
|
|
export function internalSecretMatches(provided, secret) {
|
|
if (!internalSecretUsable(secret)) return false;
|
|
const expected = Buffer.from(String(secret));
|
|
const actual = Buffer.from(String(provided ?? ''));
|
|
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
|
}
|
|
|
|
function isServiceUrl(value) {
|
|
try {
|
|
const url = new URL(value);
|
|
return (url.protocol === 'http:' || url.protocol === 'https:') && url.host !== '';
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function normalize(info) {
|
|
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
|
|
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
|
|
cleaned = [String(info.carrierNodeUrl).trim()];
|
|
}
|
|
return new Info({
|
|
authGuardUrl: String(info.authGuardUrl ?? '').trim(),
|
|
carrierNodeUrl: cleaned[0] ?? '',
|
|
carrierNodeUrls: cleaned,
|
|
});
|
|
}
|
|
|
|
export class Store {
|
|
/**
|
|
* Holds the most recently pushed Info, defaulting to whatever fallback was
|
|
* given (typically this service's own AUTHGUARD_URL/CARRIERNODE_URL env
|
|
* vars, or "" now that they're optional) until ProjectConfigurator's first
|
|
* push arrives - or forever, if this deployment isn't registered with a
|
|
* ProjectConfigurator instance at all, in which case those env vars (if
|
|
* set) keep working exactly as before.
|
|
* @param {InfoLike} [fallback]
|
|
*/
|
|
constructor(fallback = {}) {
|
|
this._info = normalize(fallback instanceof Info ? fallback : new Info(fallback));
|
|
this._onUpdate = null;
|
|
}
|
|
|
|
get() {
|
|
return this._info;
|
|
}
|
|
|
|
get authGuardUrl() {
|
|
return this._info.authGuardUrl;
|
|
}
|
|
|
|
get carrierNodeUrl() {
|
|
return this._info.carrierNodeUrl;
|
|
}
|
|
|
|
get carrierNodeUrls() {
|
|
return this._info.carrierNodeUrls;
|
|
}
|
|
|
|
/**
|
|
* Registers fn to be called (synchronously, so keep it fast) with the new
|
|
* Info after every set() - e.g. an AuthClient's setBaseUrl for a client
|
|
* that isn't already reading through Store on every call. Only one
|
|
* callback is kept; a second registration replaces the first.
|
|
* @param {(info: Info) => void} fn
|
|
*/
|
|
onUpdate(fn) {
|
|
this._onUpdate = fn;
|
|
}
|
|
|
|
/**
|
|
* Replaces the current Info, field by field, ignoring a blank/empty field
|
|
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
|
|
* the other value. Every URL must be an http or https URL with a host;
|
|
* otherwise nothing is changed and an error is thrown. Returns the resulting
|
|
* Info. Minimal Express usage:
|
|
*
|
|
* app.put('/api/core-services/internal', (req, res) => {
|
|
* if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
|
|
* return res.status(401).json({ error: 'internal service authentication required' });
|
|
* }
|
|
* let info;
|
|
* try {
|
|
* info = coreConfigStore.set(Info.fromJSON(req.body));
|
|
* } catch (error) {
|
|
* return res.status(400).json({ error: error.message });
|
|
* }
|
|
* res.json({ ok: true, info: info.toJSON() });
|
|
* });
|
|
*
|
|
* @param {InfoLike | Info} nextInfo
|
|
* @returns {Info}
|
|
*/
|
|
set(nextInfo) {
|
|
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
|
|
const badUrl = [next.authGuardUrl, ...next.carrierNodeUrls].find(
|
|
(url) => url && !isServiceUrl(url)
|
|
);
|
|
if (badUrl !== undefined) {
|
|
throw new TypeError(`core service URL must be an http or https URL with a host: ${badUrl}`);
|
|
}
|
|
if (next.authGuardUrl) {
|
|
this._info.authGuardUrl = next.authGuardUrl;
|
|
}
|
|
if (next.carrierNodeUrls.length > 0) {
|
|
this._info.carrierNodeUrls = next.carrierNodeUrls;
|
|
this._info.carrierNodeUrl = next.carrierNodeUrls[0];
|
|
}
|
|
if (this._onUpdate) {
|
|
this._onUpdate(this._info);
|
|
}
|
|
return this._info;
|
|
}
|
|
}
|