"use strict"; const assert = require("node:assert/strict"); const { execFile, spawn, spawnSync } = require("node:child_process"); const { randomUUID, webcrypto } = require("node:crypto"); const { once } = require("node:events"); const fs = require("node:fs/promises"); const http = require("node:http"); const os = require("node:os"); const path = require("node:path"); const { setTimeout: delay } = require("node:timers/promises"); const { promisify } = require("node:util"); const vm = require("node:vm"); const source = path.join(__dirname, ".."); const files = ["index.js", "db.js", "nodes.js", "package.json", "mysql-schema.sql", "ecosystem.config.template.js"]; const directories = ["AgentWorker", "public", "views", "services", "utils", "routes", "scripts", "node_modules"]; const origin = "http://127.0.0.1:3000"; const serviceSocket = "/run/fixture-agent-service.sock"; const fixtureSecret = "synthetic-session-secret-for-the-isolated-agent-staging-run"; const fixturePassword = "Synthetic-fixture-password-123!"; const exec = promisify(execFile); function runIsolated(args) { const binds = [...files, ...directories].flatMap((name) => ["--ro-bind", path.join(source, name), `/source/${name}`]); const child = spawnSync("bwrap", [ "--unshare-all", "--die-with-parent", "--uid", "0", "--gid", "0", "--clearenv", "--setenv", "PATH", "/usr/bin:/usr/sbin", "--setenv", "HOME", "/tmp", "--setenv", "DOTENV_CONFIG_QUIET", "true", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/sbin", "/sbin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--tmpfs", "/run", "--tmpfs", "/usr/local/lib", "--dir", "/etc", "--dir", "/source", "--dir", "/fixture", ...binds, "--chdir", "/fixture", "/usr/bin/node", "/source/scripts/verify-agent-worker-staging.js", "--isolated", ...args, ], { stdio: "inherit", timeout: args.includes("--load") ? 480_000 : 180_000 }); if (child.error) throw child.error; process.exitCode = child.status ?? 1; } async function until(description, check, timeout = 20_000, interval = 80) { const deadline = Date.now() + timeout; do { const result = await check(); if (result) return result; await delay(interval); } while (Date.now() < deadline); throw new Error(`Timed out: ${description}`); } function requestService(args) { const [operation, action] = args; assert.ok(args.length === 2 && operation === "agent-service" && ["start", "stop", "restart"].includes(action)); return new Promise((resolve, reject) => { const request = http.request({ socketPath: serviceSocket, path: `/${action}`, method: "POST", timeout: 15_000 }, (response) => { response.on("error", reject); response.on("aborted", () => reject(new Error("Fixture service response interrupted"))); response.resume(); response.on("end", () => response.statusCode === 204 ? resolve() : reject(new Error("Fixture service failed"))); }); request.on("error", reject); request.on("timeout", () => request.destroy(new Error("Fixture service timed out"))); request.end(); }); } function createBrowser() { const cookies = new Map(); return async function request(route, options = {}) { const headers = { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", origin, referer: `${origin}/`, "sec-fetch-site": "same-origin", ...options.headers, }; if (cookies.size) headers.cookie = [...cookies].map(([key, value]) => `${key}=${value}`).join("; "); const response = await fetch(`${origin}${route}`, { redirect: "manual", signal: AbortSignal.timeout(8000), ...options, headers }); for (const cookie of response.headers.getSetCookie()) { const pair = cookie.split(";", 1)[0]; const separator = pair.indexOf("="); if (separator > 0) cookies.set(pair.slice(0, separator), pair.slice(separator + 1)); } return response; }; } async function login(email, signInAddress) { const request = createBrowser(); const proxyHeaders = signInAddress ? { "x-forwarded-for": signInAddress } : {}; const page = await request("/login", { headers: proxyHeaders }); assert.equal(page.status, 200, `fixture login page returned ${page.status}`); const html = await page.text(); const botProof = html.match(/name="botProof"[^>]*value="([a-f0-9]+)"/)?.[1]; const csrf = html.match(/name="_csrf"[^>]*value="([a-f0-9]+)"/)?.[1]; assert.ok(botProof && csrf, `login did not render browser proof and CSRF fields (${JSON.stringify({ contentType: page.headers.get("content-type"), title: html.match(/