#!/usr/bin/env node import { constants } from 'node:fs'; import { lstat, mkdir, open, readFile, rename, rm } from 'node:fs/promises'; import { networkInterfaces } from 'node:os'; import { randomUUID } from 'node:crypto'; import { isIP } from 'node:net'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { parseEnv } from 'node:util'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const KEY = 'WF_LOCAL_ALLOWED_ORIGINS'; export function isPrivateAddress(address) { if (isIP(address) !== 4) return false; const [a, b] = address.split('.').map(Number); return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168); } export function lanAddresses(interfaces = networkInterfaces()) { return Object.entries(interfaces).flatMap(([name, entries]) => (entries ?? []) .filter(entry => !entry.internal && isPrivateAddress(entry.address)) .map(entry => ({ interface: name, address: entry.address })), ); } /** Only an explicitly selected address already assigned to this machine may be added. */ export function networkPlan(source, address, interfaces = networkInterfaces()) { const env = parseEnv(source); if (env.WF_LOCAL_ACCESS !== 'true' || env.WF_DEPLOYMENT_MODE !== 'development') throw new Error('This command requires explicit local access in development mode.'); if (!lanAddresses(interfaces).some(entry => entry.address === address)) throw new Error('Select an RFC1918 IPv4 address currently assigned to this machine.'); const port = Number(env.WF_WEB_PORT || 3000); if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('Invalid local Web port.'); const previous = (env[KEY] || '') .split(',') .map(value => value.trim()) .filter(Boolean); const origins = previous.map(value => { const url = new URL(value); if (!['http:', 'https:'].includes(url.protocol) || url.origin !== value || url.username || url.password) throw new Error('Existing origins must be exact HTTP(S) origins; fix malformed entries first.'); return url; }); const selected = new URL(`http://${address}:${port}`).origin; const retained = origins .filter(url => !(url.protocol === 'http:' && isPrivateAddress(url.hostname) && Number(url.port || 80) === port)) .map(url => url.origin); const next = [ ...new Set([ new URL(`http://localhost:${port}`).origin, new URL(`http://127.0.0.1:${port}`).origin, ...retained, selected, ]), ]; const pattern = /^(?:export\s+)?WF_LOCAL_ALLOWED_ORIGINS\s*=.*$/gm; const matches = [...source.matchAll(pattern)]; if (matches.length !== 1 || parseEnv(matches[0][0])[KEY] !== env[KEY]) throw new Error('Expected one single-line WF_LOCAL_ALLOWED_ORIGINS assignment.'); const updated = source.replace(pattern, `${KEY}=${next.join(',')}`); return { address, url: selected, previous, origins: next, removed: previous.filter(value => !next.includes(value)), changed: updated !== source, source: updated, }; } export async function configureNetwork({ root = ROOT, address, apply = false, interfaces = networkInterfaces() }) { const file = path.join(root, '.env.local'); const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW); let source; try { const stat = await handle.stat(); if (!stat.isFile() || stat.mode & 0o077 || stat.uid !== process.getuid()) throw new Error('The local environment file must be operator-owned with mode 0600.'); source = await handle.readFile('utf8'); } finally { await handle.close(); } const plan = networkPlan(source, address, interfaces); const { source: updated, ...summary } = plan; if (!apply || !plan.changed) return { ...summary, applied: false }; const backups = path.join(root, '.wishforge/local-poc/network-backups'); await mkdir(backups, { recursive: true, mode: 0o700 }); const directory = await lstat(backups); if (!directory.isDirectory() || directory.mode & 0o077 || directory.uid !== process.getuid()) throw new Error('Network backups must be an operator-owned private directory.'); const id = randomUUID(); const backup = path.join(backups, `${id}.env`); const temporary = path.join(root, `.env.network-${id}.local`); const saved = await open(backup, 'wx', 0o600); try { await saved.writeFile(source); } finally { await saved.close(); } const next = await open(temporary, 'wx', 0o600); try { await next.writeFile(updated); } finally { await next.close(); } try { const latest = await lstat(file); if (!latest.isFile() || latest.isSymbolicLink() || (await readFile(file, 'utf8')) !== source) throw new Error('Local configuration changed during update; no configuration was replaced.'); await rename(temporary, file); } finally { await rm(temporary, { force: true }); } return { ...summary, applied: true, backup, restartRequired: true }; } export async function main(args) { if (!args.length) { console.log( JSON.stringify( { addresses: lanAddresses(), usage: 'configure-local-network.mjs --address [--apply]' }, null, 2, ), ); return; } if (args[0] !== '--address' || !args[1] || args.length > 3 || (args[2] && args[2] !== '--apply')) throw new Error('Usage: configure-local-network.mjs --address [--apply]'); console.log(JSON.stringify(await configureNetwork({ address: args[1], apply: args[2] === '--apply' }), null, 2)); } if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) main(process.argv.slice(2)).catch(error => { console.error(error.message); process.exitCode = 1; });