wishforge-ide/scripts/local-services.mjs
eust-w 3623d318af ✨ Sandbox the local POC's protected checks and installations on macOS, by operator opt-in
In the development host mode, protected checks and dependency
installations ran directly as the operator. They run the agent's code:
a test it wrote could read the home directory's secrets, reach the
network, or plant Git configuration that the trusted Git commands after
it would execute.

With WF_HOST_CHECK_SANDBOX=true they run under Seatbelt instead. File
contents in the home directory are unreadable except the command's own
directory and the paths the operator lists; it may write only there,
in the caches the operator lists and in a temporary directory of its
own, never in a .git directory. Only installations reach the network;
checks may use loopback ports by opt-in, for test suites that start
local servers. The platform's own ports (control plane, Temporal and
its web UI, database, object storage, provisioner, Git service, IDE,
console) stay blocked in any case: the local start lists them from
their configured addresses. Checks get no answer from the keychain,
and a command whose home is the executor's (holding its credentials)
gets a private one. A sandbox that cannot start leaves the run waiting
on infrastructure; verification evidence records checkSandbox.

scripts/check-host-check-sandbox.ts checks all of this on the target
Mac, from outside the sandbox, then runs the POC's installation and
checks sandboxed on a recent droboticflow source. Enabled on the local
POC, a real wish passed through both, including a repair round for the
agent's own failing tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:10:47 +08:00

189 lines
7.0 KiB
JavaScript

// Starts local development processes, reuses ones that are already running and
// stops everything it started when one of them exits.
import { spawn } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
export function loadLocalEnvironment() {
try {
process.loadEnvFile('.env.local');
} catch {
throw new Error('.env.local is missing; run npm run setup:local first');
}
if (process.env.WF_DEPLOYMENT_MODE !== 'development')
throw new Error('Local services need WF_DEPLOYMENT_MODE=development in .env.local; run npm run setup:local');
}
const LOOPBACK = ['127.0.0.1', 'localhost', '::1'];
/**
* Where the web console listens, and the address its readiness is checked at. Only the production
* build may listen beyond loopback, and only with local sign-in: the development server hands any
* visitor its source maps and hot-reload channel.
*/
export function webListener(env = process.env) {
const host = env.WF_WEB_HOST || '127.0.0.1';
const port = Number(env.WF_WEB_PORT || 3000);
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('WF_WEB_PORT must be a TCP port.');
if (!LOOPBACK.includes(host)) {
if (env.WF_LOCAL_ACCESS !== 'true')
throw new Error('A web listener beyond loopback requires local sign-in (WF_LOCAL_ACCESS=true).');
if (env.WF_WEB_SERVE_MODE !== 'production')
throw new Error(
'Only the production web build may listen beyond loopback: run npm run local:build and set WF_WEB_SERVE_MODE=production.',
);
}
// A wildcard listener answers on loopback; one bound to a single address only there.
const probe = ['0.0.0.0', '::'].includes(host) ? '127.0.0.1' : host.includes(':') ? `[${host}]` : host;
return { host, port, probe };
}
const inherited = () =>
Object.fromEntries(
['PATH', 'HOME', 'TMPDIR', 'LANG', 'TERM', 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY']
.filter(key => process.env[key])
.map(key => [key, process.env[key]]),
);
/**
* The ports of this machine's WishForge services, from their configured addresses: sandboxed host
* checks may never reach them, even when they may use loopback (WF_HOST_CHECK_BLOCKED_PORTS).
* Temporal's web interface (8233) is included; it can stop workflows like Temporal itself.
*/
export function platformPorts(env = process.env) {
const ports = new Set([8233, Number(env.WF_WEB_PORT || 3000), Number(env.WF_GIT_PORT || 4504)]);
const addresses = [
env.WF_API_URL,
env.WF_CONTROL_PLANE_URL,
env.DATABASE_URL,
env.S3_ENDPOINT,
env.WF_PROVISIONER_URL,
env.WF_GIT_SERVICE_URL,
env.WF_IDE_GATEWAY_URL,
env.WF_IDE_PUBLIC_URL,
...(env.WF_IDE_ALLOWED_UPSTREAM_ORIGINS ?? '').split(','),
env.TEMPORAL_ADDRESS && `grpc://${env.TEMPORAL_ADDRESS}`,
];
for (const address of addresses.filter(Boolean)) {
try {
const url = new URL(address.trim());
const port = Number(url.port || { 'http:': 80, 'https:': 443 }[url.protocol]);
if (port) ports.add(port);
} catch {
// Not an address; nothing to block.
}
}
for (const port of (env.WF_HOST_CHECK_BLOCKED_PORTS ?? '').split(',')) if (port.trim()) ports.add(Number(port));
return [...ports].filter(port => Number.isInteger(port) && port > 0 && port < 65536).sort((a, b) => a - b);
}
/** Each process sees only the settings matching its patterns, plus the deployment mode. */
export function environment(patterns, extra = {}) {
return {
...inherited(),
...Object.fromEntries(Object.entries(process.env).filter(([key]) => patterns.some(pattern => pattern.test(key)))),
WF_DEPLOYMENT_MODE: 'development',
NODE_ENV: 'development',
...extra,
};
}
async function healthy(service) {
try {
const response = await fetch(service.url, { signal: AbortSignal.timeout(1000) });
if (!response.ok) return false;
if (!service.identity) return true;
return (await response.json()).service === service.identity;
} catch {
return false;
}
}
/**
* SIGTERM to a service's process group, so whatever it spawned stops with it; SIGKILL to what
* remains of the group once the service exits or `graceMs` passes.
*/
function stopGroup(child, graceMs) {
const signal = name => {
try {
process.kill(-child.pid, name);
} catch {
/* The group has no processes left. */
}
};
return new Promise(resolve => {
const done = () => {
clearTimeout(timer);
signal('SIGKILL');
resolve();
};
const timer = setTimeout(done, graceMs);
if (child.exitCode !== null || child.signalCode !== null) return done();
child.once('exit', done);
signal('SIGTERM');
});
}
/**
* `url` is a readiness check; a service that answers there already is reused, unless `reuse`
* is false, as under the LaunchAgent supervisor, where it may be a leftover running old code.
* Services without one (Temporal workers) count as ready once they stay up for a moment. Each
* service runs in its own process group; stopping waits until every group is gone, within the
* supervisor's 20 seconds.
*/
export async function startServices(services, banner, { reuse = true, graceMs = 10_000 } = {}) {
const children = [];
let stopping;
const stop = (code = 0) =>
(stopping ??= (async () => {
process.exitCode = code;
await Promise.all(children.map(child => stopGroup(child, graceMs)));
})());
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => void stop());
for (const service of services) {
if (stopping) return { stop };
if (service.url && (await healthy(service))) {
if (!reuse) {
await stop(1);
throw new Error(
`${service.name}: ${service.url} already answers; stop that process before starting these services.`,
);
}
console.log(`${service.name}: reusing the service already running at ${service.url}`);
continue;
}
const child = spawn(process.execPath, service.args, {
cwd: service.cwd,
env: service.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
});
children.push(child);
for (const output of [child.stdout, child.stderr])
output.on('data', bytes =>
String(bytes)
.split('\n')
.filter(Boolean)
.forEach(line => console.log(`[${service.name}] ${line}`)),
);
child.once('exit', code => {
if (!stopping) {
console.error(`${service.name} exited (${code}); stopping the services this command started.`);
void stop(code || 1);
}
});
let ready = false;
for (let attempt = 0; attempt < (service.url ? 90 : 2) && !stopping; attempt++) {
if (service.url && (await healthy(service))) {
ready = true;
break;
}
await delay(1000);
}
if (!service.url && !stopping) ready = true;
if (!ready) {
await stop(1);
throw new Error(`${service.name} did not become ready; check its output above.`);
}
}
console.log(banner);
if (!children.length) console.log('Every service was already running; nothing was started.');
return { stop };
}