79 lines
4.3 KiB
JavaScript
79 lines
4.3 KiB
JavaScript
// Bus-only in-memory management client. Values never enter receipts or errors.
|
|
import http from 'node:http';
|
|
import { ProxyError, refuse, sha256, regularBytes, validManagementKey } from './common.mjs';
|
|
import { lstatSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
const KEY_PATH = '/v8/management/config/access/api-keys';
|
|
const validKeys = value => Array.isArray(value) && value.length <= 100000 && value.every(k => typeof k === 'string' && k.length > 0 && k.length <= 4096 && !/[\r\n\x00]/.test(k));
|
|
export class ManagementClient {
|
|
#base; #key; #receipt; #timeout;
|
|
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000 }) {
|
|
let u; try { u = new URL(baseUrl); } catch { refuse('proxy-client-invalid'); }
|
|
if (u.protocol !== 'http:' || u.hostname !== '127.0.0.1' || !u.port || Number(u.port) < 1024 || u.port === '8317'
|
|
|| u.username || u.password || u.pathname !== '/' || u.search || u.hash
|
|
|| !validManagementKey(key)
|
|
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0) refuse('proxy-client-invalid');
|
|
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout;
|
|
}
|
|
#request(method, keys, onStatus) {
|
|
// node:http addresses the fixed numeric loopback directly. An ambient fetch
|
|
// dispatcher or HTTP_PROXY cannot send the Authorization header elsewhere.
|
|
let deadline;
|
|
return new Promise((resolve, reject) => {
|
|
let received = false;
|
|
const req = http.request(this.#base + KEY_PATH, {
|
|
method, headers: { Authorization: `Bearer ${this.#key}`, ...(method === 'PUT' ? { 'Content-Type': 'application/json' } : {}) },
|
|
}, response => {
|
|
received = true; onStatus(response.statusCode);
|
|
const error = response.statusCode >= 300 && response.statusCode < 400 ? 'proxy-client-redirect'
|
|
: response.statusCode < 200 || response.statusCode >= 300 ? 'proxy-client-refused' : null;
|
|
if (error) { response.destroy(); reject(new ProxyError(error)); return; }
|
|
let size = 0; const chunks = [];
|
|
response.on('data', chunk => {
|
|
size += chunk.length;
|
|
if (size > 8 * 1024 * 1024) { response.destroy(); reject(new ProxyError('proxy-client-response')); }
|
|
else chunks.push(chunk);
|
|
});
|
|
response.on('aborted', () => reject(new ProxyError('proxy-client-response')));
|
|
response.on('error', () => reject(new ProxyError('proxy-client-response')));
|
|
response.on('end', () => {
|
|
try { resolve(JSON.parse(Buffer.concat(chunks))); }
|
|
catch { reject(new ProxyError('proxy-client-response')); }
|
|
});
|
|
});
|
|
req.on('error', () => reject(new ProxyError(received ? 'proxy-client-response' : 'proxy-client-down')));
|
|
deadline = setTimeout(() => { req.destroy(); reject(new ProxyError('proxy-client-down')); }, this.#timeout);
|
|
req.end(method === 'PUT' ? JSON.stringify(keys) : undefined);
|
|
}).finally(() => clearTimeout(deadline));
|
|
}
|
|
async #call(method, keys) {
|
|
let status = 0, ids = [];
|
|
try {
|
|
const body = await this.#request(method, keys, value => { status = value; });
|
|
if (method === 'GET') {
|
|
if (!validKeys(body)) refuse('proxy-client-response');
|
|
ids = body.map(sha256).map(h => h.slice(0, 12));
|
|
return body;
|
|
}
|
|
if (!body || body.status !== 'ok') refuse('proxy-client-response');
|
|
ids = keys.map(sha256).map(h => h.slice(0, 12));
|
|
return { ok: true };
|
|
} finally { this.#receipt({ call: `${method} ${KEY_PATH}`, status, keyIds: ids }); }
|
|
}
|
|
getKeys() { return this.#call('GET'); }
|
|
putKeys(keys) { if (!validKeys(keys)) refuse('proxy-client-invalid'); return this.#call('PUT', keys); }
|
|
}
|
|
|
|
// Trusted bus boot only: no CLI/Console/session exports this value or client.
|
|
export async function loadManagementClient({ configDir, proxy, receipt }) {
|
|
const file = join(configDir, 'secrets', 'proxy-management.key');
|
|
let key;
|
|
try {
|
|
const stat = lstatSync(file);
|
|
if ((stat.mode & 0o777) !== 0o600 || !stat.isFile() || stat.isSymbolicLink()) refuse('proxy-management-key-invalid');
|
|
key = regularBytes(file, 'proxy-management-key-invalid').toString('utf8');
|
|
if (!validManagementKey(key)) refuse('proxy-management-key-invalid');
|
|
} catch { refuse('proxy-management-key-invalid'); }
|
|
return new ManagementClient({ baseUrl: `http://127.0.0.1:${proxy.port}`, key, receipt });
|
|
}
|