This commit is contained in:
1 parent
8d7c2f69ff
commit
a018f3da4c
18 files changed
+747
-46
No files matched your search
@@ -18,3 +18,36 @@ Pass a service-specific `tableName` to `runMigrations` when multiple services
|
||||
share one PostgreSQL database, so their migration histories cannot collide.
|
||||
|
||||
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
|
||||
|
||||
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
|
||||
|
||||
`AuthClient` (`src/authclient.js`) trades a service's own local user table for
|
||||
HTTP calls to a centralized AuthGuard instance, mirroring the Go/Python/Java
|
||||
clients. `client.setBaseUrl(url)` retargets an existing client's AuthGuard
|
||||
URL in place, so a client can be constructed with `new AuthClient('')`
|
||||
(usable right away, failing closed until a real URL arrives) and be handed a
|
||||
URL later, rather than needing one known up front.
|
||||
|
||||
`coreconfig` (`src/coreconfig.js`, the Node equivalent of
|
||||
`shared/backend/coreconfig` and `shared_backend.coreconfig`) is a small
|
||||
`Store` that holds AuthGuard's/CarrierNode's current base URL(s) and updates
|
||||
live whenever ProjectConfigurator pushes a fresh
|
||||
`PUT /api/core-services/internal` - wire `store.onUpdate` to
|
||||
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
|
||||
|
||||
```js
|
||||
import { AuthClient, CoreConfigStore } from '@gabriel20xx/node-backend';
|
||||
|
||||
const authClient = new AuthClient('');
|
||||
const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
|
||||
coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
|
||||
|
||||
// in your own route for PUT /api/core-services/internal:
|
||||
app.put('/api/core-services/internal', (req, res) => {
|
||||
if (req.get('X-Internal-Auth') !== process.env.INTERNAL_SERVICE_SECRET) {
|
||||
return res.status(401).json({ error: 'internal service authentication required' });
|
||||
}
|
||||
const info = coreConfig.set(req.body);
|
||||
res.json({ ok: true, info: info.toJSON() });
|
||||
});
|
||||
```
|
||||
@@ -14,6 +14,7 @@
|
||||
"./config": "./src/config.js",
|
||||
"./db": "./src/db.js",
|
||||
"./auth": "./src/auth.js",
|
||||
"./coreconfig": "./src/coreconfig.js",
|
||||
"./migrate": "./src/migrate.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
|
||||
@@ -87,6 +87,27 @@ export class AuthClient {
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* 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
|
||||
* INTERNAL_SERVICE_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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @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],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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. Returns the resulting Info. Minimal Express usage:
|
||||
*
|
||||
* app.put('/api/core-services/internal', (req, res) => {
|
||||
* if (req.get('X-Internal-Auth') !== process.env.INTERNAL_SERVICE_SECRET) {
|
||||
* return res.status(401).json({ error: 'internal service authentication required' });
|
||||
* }
|
||||
* const info = coreConfigStore.set(Info.fromJSON(req.body));
|
||||
* 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));
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -32,3 +32,4 @@ export {
|
||||
} from './totp.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
||||
export { Info as CoreConfigInfo, Store as CoreConfigStore } from './coreconfig.js';
|
||||
@@ -68,6 +68,25 @@ test('constructor trims whitespace and leaves an empty base URL empty', () => {
|
||||
assert.equal(new AuthClient('').baseUrl, '');
|
||||
});
|
||||
|
||||
test('setBaseUrl retargets a pending client (constructed with "") to its first real URL', async () => {
|
||||
const client = new AuthClient('', {
|
||||
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
|
||||
});
|
||||
await assert.rejects(() => client.validate('good-token'), /no base URL/);
|
||||
|
||||
client.setBaseUrl('https://auth.example.com');
|
||||
|
||||
assert.equal(client.baseUrl, 'https://auth.example.com');
|
||||
const user = await client.validate('good-token');
|
||||
assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' });
|
||||
});
|
||||
|
||||
test('setBaseUrl ignores a blank value, leaving the previous URL in place', () => {
|
||||
const client = new AuthClient('https://auth.example.com');
|
||||
client.setBaseUrl(' ');
|
||||
assert.equal(client.baseUrl, 'https://auth.example.com');
|
||||
});
|
||||
|
||||
test('validate resolves the user on a valid session', async () => {
|
||||
const client = new AuthClient('https://auth.example.com', {
|
||||
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Info, Store } from '../src/coreconfig.js';
|
||||
|
||||
test('store seeds from the fallback Info', () => {
|
||||
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
|
||||
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
|
||||
assert.deepEqual(store.carrierNodeUrls, ['http://carrier.example.com']);
|
||||
});
|
||||
|
||||
test('store defaults to empty with no fallback', () => {
|
||||
const store = new Store();
|
||||
assert.equal(store.authGuardUrl, '');
|
||||
assert.deepEqual(store.carrierNodeUrls, []);
|
||||
});
|
||||
|
||||
test('set ignores a blank authGuardUrl rather than clobbering the existing one', () => {
|
||||
const store = new Store({ authGuardUrl: 'http://auth.example.com' });
|
||||
store.set({ authGuardUrl: '', carrierNodeUrl: 'http://carrier.example.com' });
|
||||
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
|
||||
});
|
||||
|
||||
test('set only replaces carrierNodeUrls when the push actually carries one', () => {
|
||||
const store = new Store({ carrierNodeUrl: 'http://carrier.example.com' });
|
||||
store.set({ authGuardUrl: 'http://auth.example.com' });
|
||||
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
|
||||
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||
});
|
||||
|
||||
test('onUpdate is called with the resulting Info after set', () => {
|
||||
const store = new Store();
|
||||
const seen = [];
|
||||
store.onUpdate((info) => seen.push(info));
|
||||
store.set({ authGuardUrl: 'http://auth.example.com' });
|
||||
assert.equal(seen.length, 1);
|
||||
assert.equal(seen[0].authGuardUrl, 'http://auth.example.com');
|
||||
});
|
||||
|
||||
test('Info.fromJSON/toJSON round-trip the wire shape', () => {
|
||||
const payload = {
|
||||
authGuardUrl: 'http://auth.example.com',
|
||||
carrierNodeUrl: 'http://carrier.example.com',
|
||||
carrierNodeUrls: ['http://carrier.example.com', 'http://carrier2.example.com'],
|
||||
};
|
||||
const info = Info.fromJSON(payload);
|
||||
assert.deepEqual(info.carrierNodeUrls, ['http://carrier.example.com', 'http://carrier2.example.com']);
|
||||
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
|
||||
});
|
||||
Reference in new issue
Block a user