Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187import { readFileSync, existsSync } from 'fs';import { resolve } from 'path';import { SubstrateClient } from '../client.js';import { loadConfig, envGet } from '../config.js';import * as d from '../utils/display.js';
export async function securityCommand(opts: { key?: string; url?: string }) { const config = loadConfig(opts); const client = new SubstrateClient(config);
d.header('Security Audit'); d.line();
let passed = 0; let warnings = 0; let issues = 0;
function pass(msg: string) { d.success(msg); passed++; } function warning(msg: string) { d.warn(msg); warnings++; } function issue(msg: string) { d.error(msg); issues++; }
async function probe(path: string, init: RequestInit = {}): Promise<Response | null> { try { return await fetch(`${config.apiUrl}${path}`, { ...init, signal: AbortSignal.timeout(5000), }); } catch { return null; } }
// 1. API key check const apiKey = envGet('SUBSTRATE_API_KEY', config.envFile); if (!apiKey) { issue('SUBSTRATE_API_KEY not set'); } else if (apiKey.length < 32) { warning(`API key is short (${apiKey.length} chars, recommend 64)`); } else { pass(`API key is set (${apiKey.length} chars)`); }
// 2. Check .env permissions if (existsSync(config.envFile)) { if (process.platform === 'win32') { warning('.env ACLs were not checked on Windows — restrict this file to your user account before launch'); } else { try { const { statSync } = await import('fs'); const stat = statSync(config.envFile); const mode = (stat.mode & 0o777).toString(8); if (stat.mode & 0o044) { warning(`.env is world/group-readable (${mode}) — consider chmod 600`); } else { pass(`.env permissions OK (${mode})`); } } catch { warning('Could not check .env permissions'); } } } else { issue('.env file not found'); }
// 3. Docker compose port bindings const composeFile = resolve(config.substrateDir, 'docker-compose.yml'); if (existsSync(composeFile)) { const compose = readFileSync(composeFile, 'utf-8'); if (compose.includes('127.0.0.1:')) { pass('Ports bound to 127.0.0.1'); } else if (compose.includes('0.0.0.0:')) { issue('Ports bound to 0.0.0.0 — exposed on all interfaces'); } else { pass('Port bindings look OK'); } if (compose.includes('workspace-data:/workspace:ro')) { pass('Workspace volume is read-only in the substrate API container'); } else if (compose.includes('workspace-data:/workspace')) { warning('Workspace volume is writable in the substrate API container'); } const latestImages = Array.from(compose.matchAll(/image:\s+([^\s#]+:latest)\b/g)).map(m => m[1]); if (latestImages.length > 0) { warning(`Mutable latest image tags in compose: ${latestImages.join(', ')}`); } }
// 4. Caddyfile security headers const caddyfile = resolve(config.substrateDir, 'Caddyfile'); if (existsSync(caddyfile)) { const caddy = readFileSync(caddyfile, 'utf-8'); const headers = ['X-Content-Type-Options', 'X-Frame-Options', 'Strict-Transport-Security']; const missing = headers.filter(h => !caddy.includes(h)); if (missing.length === 0) { pass('Caddy security headers configured'); } else { warning(`Caddy missing headers: ${missing.join(', ')}`); } }
// 5. Feature flags const terminalWs = envGet('SUBSTRATE_ENABLE_TERMINAL_WS', config.envFile); if (terminalWs === 'true') { issue('Substrate host terminal WebSocket is enabled — disable unless you explicitly need host shell access'); } else { pass('Substrate host terminal WebSocket is disabled'); }
const containersEnabled = envGet('SUBSTRATE_ENABLE_CONTAINERS', config.envFile); const workspaceEnabled = envGet('SUBSTRATE_ENABLE_WORKSPACE', config.envFile); if (workspaceEnabled === 'true' && containersEnabled !== 'true') { issue('Workspace is enabled but containers are disabled — workspace bootstrap and terminal access will fail'); }
// 6. Live API checks const health = await client.health(); if (health.ok) { pass('API is reachable and healthy');
const unauth = await probe('/services'); if (unauth?.status === 401) { pass('Authenticated routes reject missing API key'); } else if (unauth) { issue(`Authenticated route without key returned HTTP ${unauth.status}`); }
const badKey = await probe('/services', { headers: { 'x-substrate-key': 'invalid-key' }, }); if (badKey?.status === 401) { pass('Authenticated routes reject invalid API key'); } else if (badKey) { issue(`Authenticated route with invalid key returned HTTP ${badKey.status}`); }
// Check rate limiting const svc = await client.services(); if (svc.ok) { pass('Authenticated API access working'); } else if (svc.error.includes('429')) { pass('Rate limiting is active'); } else if (svc.error.includes('401')) { issue('API key is invalid — check SUBSTRATE_API_KEY'); } } else { warning(`API not reachable: ${health.error}`); }
// 7. Container security const containers = await client.containers(); if (containers.ok) { pass('Container orchestration responding'); const running = containers.data.containers.filter(c => c.status === 'running'); if (running.length > 0) { d.info(` ${running.length} container(s) running`); }
const images = await probe('/containers/images/allowed', { headers: { 'x-substrate-key': config.apiKey }, }); if (images?.ok) { const body = await images.json().catch(() => ({ images: [] })) as { images?: string[] }; const mutable = (body.images || []).filter(image => image.endsWith(':latest')); if (mutable.length > 0) { warning(`Mutable latest image tags in container allowlist: ${mutable.join(', ')}`); } else { pass('Container image allowlist avoids :latest tags'); } } } else if (containers.error.includes('403')) { pass('Container orchestration disabled (secure default)'); }
// 8. Docker socket if (existsSync('/var/run/docker.sock')) { warning('Docker socket mounted (required for container management)'); }
// Summary d.line(); const parts = []; if (passed > 0) parts.push(d.GREEN(`${passed} passed`)); if (warnings > 0) parts.push(d.YELLOW(`${warnings} warnings`)); if (issues > 0) parts.push(d.RED(`${issues} issues`)); d.info(parts.join(' · ')); d.line();}