import https from 'node:https'; import { readFileSync } from 'node:fs'; // The client of the operator's state API. It trusts only the operator's // CA, which the webhook writes into GOFER_CA, and reads the pod's token // from its file on every request, because the kubelet replaces the file // before each token expires. export class OperatorAPI { constructor({ url, ca, tokenFile, namespace, profile }) { this.base = new URL(`${url}/v1/namespaces/${encodeURIComponent(namespace)}/browserprofiles/${encodeURIComponent(profile)}/`); this.agent = new https.Agent({ ca, keepAlive: true }); this.tokenFile = tokenFile; } // request gives up after a fixed time, and sooner when signal aborts, // which the save on SIGTERM uses to keep each request inside its // deadline. request(method, path, { headers = {}, body, signal } = {}) { const url = new URL(path, this.base); const token = readFileSync(this.tokenFile, 'utf8').trim(); return new Promise((resolve, reject) => { const req = https.request(url, { method, agent: this.agent, signal, headers: { authorization: `Bearer ${token}`, ...headers }, }, res => { const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: Buffer.concat(chunks).toString('utf8') })); }); req.on('error', reject); req.setTimeout(30_000, () => req.destroy(new Error(`${method} ${url} timed out`))); req.end(body); }); } // Answers each secret's value and origins. async secrets() { const res = await this.request('GET', 'secrets'); if (res.status !== 200) throw new Error(`reading secrets: ${res.status} ${res.text}`); return JSON.parse(res.text); } }