The PIN moves from 8.0.42 to 8.0.79 with the upstream archive checksum and the extracted binary checksum. The panel stays 1.26.7. proxy.json keeps the binary path of the PIN it was created under. A path of the form <dataRoot>/opt/cliproxyapi/<version>/cli-proxy-api now validates and reads as the current pinned path, so an instance created on 8.0.42 needs no edit. The runner still runs only the verified pinned install. 8.0.79 applies a key-list PUT by an async reload a few milliseconds after it answers, so a just-issued key answers 401 at first. Preflight now probes again on 401 only, for at most ISSUE_PROBE_TIMEOUT_MS (2 s). Any other non-2xx still refuses on the first answer.
111 lines
6.5 KiB
JavaScript
111 lines
6.5 KiB
JavaScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import net from 'node:net';
|
|
import { randomBytes } from 'node:crypto';
|
|
import { PIN, refuse, safePath, regularBytes, sha256, validManagementKey, proxyTiming } from './common.mjs';
|
|
export function installPaths(dataRoot, pin = PIN) {
|
|
const dir = path.join(dataRoot, 'opt', 'cliproxyapi', pin.version);
|
|
return { dir, binary: path.join(dir, 'cli-proxy-api'), panel: path.join(dir, 'static', 'management.html') };
|
|
}
|
|
// proxy.json records the install path from the PIN it was created under, and nothing
|
|
// rewrites it. After a PIN bump an earlier release's path under this data root stays valid
|
|
// and reads as the current pinned path. The runner executes only the hash-verified pinned
|
|
// install, never the recorded path, so an old value selects nothing.
|
|
const releasePath = (dataRoot, binary) => {
|
|
const base = path.join(dataRoot, 'opt', 'cliproxyapi') + path.sep;
|
|
if (typeof binary !== 'string' || !binary.startsWith(base)) return false;
|
|
const [version, file, ...rest] = binary.slice(base.length).split(path.sep);
|
|
return rest.length === 0 && file === 'cli-proxy-api' && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(version);
|
|
};
|
|
export function validateProxy(value, dataRoot, pin = PIN) {
|
|
const pinned = installPaths(dataRoot, pin).binary;
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
|| Object.keys(value).some(k => !['binary', 'port', 'rotateGraceMinutes', 'firstOutputSeconds'].includes(k))
|
|
|| !Number.isInteger(value.port) || value.port < 1024 || value.port > 65535 || value.port === 8317
|
|
|| (value.binary !== pinned && !releasePath(dataRoot, value.binary))) refuse('proxy-config-invalid');
|
|
return { port: value.port, binary: pinned, ...proxyTiming(value) };
|
|
}
|
|
export function loadProxy(configDir, dataRoot) {
|
|
const file = path.join(configDir, 'proxy.json');
|
|
try { fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return undefined; refuse('proxy-config-invalid'); }
|
|
try { return validateProxy(JSON.parse(regularBytes(file, 'proxy-config-invalid')), dataRoot); }
|
|
catch (error) {
|
|
if (['proxy-rotate-grace-invalid', 'proxy-first-output-invalid'].includes(error.code)) throw error;
|
|
refuse('proxy-config-invalid');
|
|
}
|
|
}
|
|
export function verifyInstall(dataRoot, pin = PIN) {
|
|
const paths = installPaths(dataRoot, pin);
|
|
for (const [file, hash] of [[paths.binary, pin.binary.sha256], [paths.panel, pin.panel.sha256]]) {
|
|
try { fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') refuse('proxy-install-missing'); refuse('proxy-install-invalid'); }
|
|
if (sha256(regularBytes(file, 'proxy-install-invalid')) !== hash) refuse('proxy-install-invalid');
|
|
}
|
|
return paths;
|
|
}
|
|
async function reservePort(wanted) {
|
|
if (wanted !== undefined && (!Number.isInteger(wanted) || wanted < 1024 || wanted > 65535 || wanted === 8317)) refuse('proxy-config-invalid');
|
|
const server = net.createServer();
|
|
try {
|
|
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(wanted ?? 0, '127.0.0.1', resolve); });
|
|
const port = server.address().port;
|
|
if (port === 8317 || port < 1024) { await new Promise(r => server.close(r)); return reservePort(wanted); }
|
|
return { port, release: () => new Promise(r => server.close(r)) };
|
|
} catch { refuse('proxy-port-in-use'); }
|
|
}
|
|
export function initialConfig({ dataRoot, port, key, sentinel }) {
|
|
return {
|
|
'config-version': 8,
|
|
server: { host: '127.0.0.1', port },
|
|
management: { 'allow-remote': false, 'secret-key': key, 'disable-control-panel': false, 'disable-auto-update-panel': true },
|
|
access: { 'api-keys': [sentinel] },
|
|
oauth: { 'auth-dir': path.join(dataRoot, 'proxy', 'auth') },
|
|
observability: { logs: { 'logging-to-file': true } },
|
|
routing: { strategy: 'fill-first', 'session-affinity': true, 'session-affinity-rebind-on': 'quota', retry: { 'request-retry': 0 } },
|
|
};
|
|
}
|
|
// Called only by the bus's path-bound human verb, never by an agent or the tester.
|
|
export async function initializeProxy({ configDir, dataRoot, key, port, pin = PIN, ...options }) {
|
|
if (!validManagementKey(key)) refuse('proxy-key-invalid');
|
|
const timing = proxyTiming(options);
|
|
safePath(configDir, 'proxy-init-failed'); safePath(dataRoot, 'proxy-init-failed');
|
|
const paths = verifyInstall(dataRoot, pin);
|
|
const settingsFile = path.join(configDir, 'proxy.json'), proxyDir = path.join(dataRoot, 'proxy');
|
|
const secrets = path.join(configDir, 'secrets'), keyFile = path.join(secrets, 'proxy-management.key');
|
|
for (const file of [settingsFile, proxyDir, keyFile]) {
|
|
try { fs.lstatSync(file); refuse('proxy-already-initialized'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
}
|
|
const lockFile = path.join(configDir, '.proxy-init.lock');
|
|
let lock;
|
|
try { lock = fs.openSync(lockFile, 'wx', 0o600); } catch { refuse('proxy-init-busy'); }
|
|
let reservation, ownsProxy = false, ownsKey = false, ownsSettings = false, ownsSecrets = false;
|
|
try {
|
|
reservation = await reservePort(port);
|
|
safePath(secrets, 'proxy-init-failed');
|
|
try { fs.mkdirSync(secrets, { mode: 0o700 }); ownsSecrets = true; }
|
|
catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
const stat = fs.lstatSync(secrets);
|
|
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o777) !== 0o700) refuse('proxy-init-failed');
|
|
fs.mkdirSync(proxyDir, { mode: 0o700 }); ownsProxy = true;
|
|
for (const name of ['auth', 'logs']) fs.mkdirSync(path.join(proxyDir, name), { mode: 0o700 });
|
|
const keyFd = fs.openSync(keyFile, 'wx', 0o600); ownsKey = true;
|
|
try { fs.writeFileSync(keyFd, key); } finally { fs.closeSync(keyFd); }
|
|
const tag = sha256(configDir).slice(0, 12);
|
|
const sentinel = `msk-${tag}-sentinel-${randomBytes(32).toString('base64url')}`;
|
|
fs.writeFileSync(path.join(proxyDir, 'config.yaml'), JSON.stringify(initialConfig({ dataRoot, port: reservation.port, key, sentinel }), null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
const settings = { port: reservation.port, binary: paths.binary, ...timing };
|
|
const settingsFd = fs.openSync(settingsFile, 'wx', 0o600); ownsSettings = true;
|
|
try { fs.writeFileSync(settingsFd, JSON.stringify(settings, null, 2) + '\n'); } finally { fs.closeSync(settingsFd); }
|
|
return settings;
|
|
} catch (e) {
|
|
if (ownsSettings) fs.unlinkSync(settingsFile);
|
|
if (ownsKey) fs.unlinkSync(keyFile);
|
|
if (ownsProxy) fs.rmSync(proxyDir, { recursive: true });
|
|
if (ownsSecrets) fs.rmdirSync(secrets);
|
|
if (e.code?.startsWith('proxy-')) throw e;
|
|
refuse('proxy-init-failed');
|
|
} finally {
|
|
if (reservation) await reservation.release();
|
|
fs.closeSync(lock); fs.unlinkSync(lockFile);
|
|
}
|
|
}
|