Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302import { createHash, timingSafeEqual, randomUUID } from 'crypto';import { Hono } from 'hono';import { cors } from 'hono/cors';import { verifyProxyToken } from './utils/proxy-token';import { bufferRequestBodyWithLimit, cloneRequestWithBufferedBody, MAX_REQUEST_BODY_BYTES, parseContentLengthHeader,} from './utils/request-body';import systemRoutes from './routes/system';import tapRoutes from './routes/tap';import goatRoutes from './routes/goat';import webRoutes from './routes/web';import vmRoutes from './routes/vm';import containerRoutes from './routes/containers';import workspaceRoutes from './routes/workspace';import embeddingsRoutes from './routes/embeddings';import llmRoutes from './routes/llm';import eventsRoutes from './routes/events';import { CONFIG } from './config';import { serviceManager } from './services/service-manager';import { log } from './services/logger';import { errMessage, errStatus } from './services/errors';
// Timing-safe secret comparison to prevent timing side-channel attacksfunction safeEqual(provided: string | undefined, expected: string): boolean { if (typeof provided !== 'string') return false; const hash = (s: string) => createHash('sha256').update(s).digest(); return timingSafeEqual(hash(provided), hash(expected));}
type AppVars = { Variables: { requestId: string } };
const app = new Hono<AppVars>();
const ALLOWED_ORIGIN_PATTERNS = [ /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/, // Local dev (http) /^https?:\/\/[a-zA-Z0-9-]+\.local(:\d+)?$/, // mDNS hostnames (*.local) /^https:\/\/([a-zA-Z0-9-]+\.)?aetheros\.computer$/, // Live site /^https:\/\/aetheros(-[a-zA-Z0-9-]+)?\.vercel\.app$/, // Vercel preview/production deployments];
// Additional origins from env var (comma-separated, supports wildcard * patterns)const extraOrigins = (process.env.SUBSTRATE_ALLOWED_ORIGINS || '').split(',').filter(Boolean);
// Convert a wildcard pattern (e.g. "https://aetheros-*.vercel.app") to a RegExpfunction wildcardToRegex(pattern: string): RegExp { const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[a-zA-Z0-9-]+'); return new RegExp(`^${escaped}$`);}
const extraOriginPatterns = extraOrigins.filter(o => o.includes('*')).map(wildcardToRegex);const extraOriginExact = extraOrigins.filter(o => !o.includes('*'));
// Checks a browser Origin against the static allowlist plus any env-configured extras.// Used by both the CORS layer and the WebSocket upgrade path — keep them consistent.function isAllowedOrigin(origin: string): boolean { if (ALLOWED_ORIGIN_PATTERNS.some(p => p.test(origin))) return true; if (extraOriginExact.includes(origin)) return true; if (extraOriginPatterns.some(p => p.test(origin))) return true; return false;}
// CORSapp.use('*', cors({ origin: (origin) => { if (!origin) return origin; if (isAllowedOrigin(origin)) return origin; return undefined as unknown as string; }, allowHeaders: ['x-substrate-key', 'x-request-id', 'content-type', 'authorization'], exposeHeaders: ['x-request-id'], maxAge: 86400, credentials: false,}));
// Buffer request bodies once so downstream parsers cannot bypass the size cap.app.use('*', async (c, next) => { try { const contentLength = parseContentLengthHeader(c.req.header('content-length') || undefined); if (contentLength !== null && contentLength > MAX_REQUEST_BODY_BYTES) { return c.json({ error: 'Request body too large' }, 413); } } catch (error) { return c.json({ error: errMessage(error) }, errStatus(error) as 400); }
if (!['GET', 'HEAD'].includes(c.req.method.toUpperCase()) && c.req.raw.body) { try { const body = await bufferRequestBodyWithLimit(c.req.raw); (c.req as { raw: Request }).raw = cloneRequestWithBufferedBody(c.req.raw, body); } catch (error) { if (errStatus(error) === 413 || errStatus(error) === 400) { return c.json({ error: errMessage(error) }, errStatus(error) as 400 | 413); } throw error; } } await next();});
// Request correlation IDapp.use('*', async (c, next) => { const rid = c.req.header('x-request-id') || randomUUID(); c.set('requestId', rid); c.header('x-request-id', rid); await next();});
// Structured request loggingapp.use('*', async (c, next) => { const rid = c.get('requestId') ?? '?'; const started = Date.now(); let status = 200; try { await next(); status = c.res.status; } catch (err) { status = errStatus(err); throw err; // onError handles the response shape } finally { const ms = Date.now() - started; const level = status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info'; log[level]({ rid, method: c.req.method, path: c.req.path, status, ms }, 'request'); }});
// Public endpoints — no auth needed.app.get('/health', async (c) => { const healths = await serviceManager.healthAll(); const services: Record<string, string> = { api: 'running' }; for (const [name, health] of Object.entries(healths)) { services[name] = health.status; } return c.json({ status: 'ok', timestamp: new Date().toISOString(), services });});
// Readiness fails only on Tap downtime or hard core-service errors.app.get('/ready', async (c) => { const healths = await serviceManager.healthAll();
const tapRunning = healths['tap']?.status === 'running';
// Core services whose hard-error state should fail readiness. const coreCandidates = ['tap', 'llm', 'embeddings'] as const; const erroredCore = coreCandidates.filter( (name) => healths[name]?.status === 'error', );
const ready = tapRunning && erroredCore.length === 0;
const services: Record<string, string> = { api: 'running' }; for (const [name, health] of Object.entries(healths)) { services[name] = health.status; }
const body: Record<string, unknown> = { ready, timestamp: new Date().toISOString(), services, }; if (!ready) { body.reason = !tapRunning ? 'tap-not-running' : 'core-service-error'; if (erroredCore.length > 0) body.erroredCore = erroredCore; } return c.json(body, ready ? 200 : 503);});
// Authenticated routesconst authenticated = new Hono<AppVars>();
authenticated.use('*', async (c, next) => { const ip = clientIp(c); const now = Date.now(); const entry = rateLimitMap.get(ip);
if (!entry || now > entry.resetAt) { // Cap map size to prevent memory exhaustion from many unique IPs if (rateLimitMap.size >= RATE_LIMIT_MAX_ENTRIES) { // Evict oldest entries const iterator = rateLimitMap.keys(); for (let i = 0; i < 1000; i++) { const key = iterator.next().value; if (key) rateLimitMap.delete(key); } } rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); } else { entry.count++; if (entry.count > RATE_LIMIT_MAX) { c.header('Retry-After', String(Math.ceil((entry.resetAt - now) / 1000))); return c.json({ error: 'Too many requests' }, 429); } }
await next();});
// Authenticate after rate limiting so repeated bad keys still get throttled.authenticated.use('*', async (c, next) => { const suppliedKey = c.req.header('x-substrate-key'); if (safeEqual(suppliedKey, CONFIG.API_KEY)) { return next(); } // Iframe-friendly auth for proxy routes (iframes can't send custom headers) if (c.req.path.includes('/proxy/')) { const url = new URL(c.req.url);
// Preferred: short-lived signed token (doesn't expose the API key) const token = url.searchParams.get('token'); if (token) { // Extract container ID from the path: /containers/:id/proxy/... const match = c.req.path.match(/^\/containers\/([^/]+)\/proxy\//); if (match) { // `?u=<subject>` is required — tokens are always bound to a caller/ // session identifier so a leak can't be replayed elsewhere. const subject = url.searchParams.get('u') ?? ''; if (verifyProxyToken(token, match[1], CONFIG.API_KEY, subject)) { return next(); } } } // Raw API keys in query strings leak to access logs, browser history, // and referrer headers. Use the signed proxy-token flow instead. } return c.json({ error: 'Unauthorized substrate request' }, 401);});// Rate limiting — sliding window, 600 requests per minute per IP.// Runs before auth so repeated 401s still consume the caller's budget.const rateLimitMap = new Map<string, { count: number; resetAt: number }>();const RATE_LIMIT_WINDOW_MS = 60_000;const RATE_LIMIT_MAX = 600;const RATE_LIMIT_MAX_ENTRIES = 10_000;
setInterval(() => { const now = Date.now(); for (const [key, val] of rateLimitMap) { if (now > val.resetAt) rateLimitMap.delete(key); }}, 60_000);
// Only trust forwarded IP headers when a trusted proxy overwrites them.function clientIp(c: { req: { header: (k: string) => string | undefined; raw?: any } }): string { if (CONFIG.TRUST_PROXY) { const fwd = c.req.header('x-forwarded-for'); if (fwd) return fwd.split(',')[0]?.trim() || '0.0.0.0'; const real = c.req.header('x-real-ip'); if (real) return real; } // Fall back to the socket remote address, which is set by @hono/node-server. const rawReq: any = c.req.raw; const socketAddr = rawReq?.socket?.remoteAddress ?? rawReq?.connection?.remoteAddress; return typeof socketAddr === 'string' ? socketAddr : '0.0.0.0';}
function resetRateLimitState(): void { rateLimitMap.clear();}
function seedRateLimitState(ip: string, count: number, resetAt: number): void { rateLimitMap.set(ip, { count, resetAt });}
authenticated.route('/', systemRoutes);authenticated.route('/goat', goatRoutes);authenticated.route('/web', webRoutes);authenticated.route('/vms', vmRoutes);authenticated.route('/containers', containerRoutes);authenticated.route('/workspace', workspaceRoutes);authenticated.route('/embeddings', embeddingsRoutes);authenticated.route('/llm', llmRoutes);authenticated.route('/', eventsRoutes);authenticated.route('/', tapRoutes);
app.route('/', authenticated);
// Global error handler — unified response shape so clients can reliably parse// and so the request id ties a response back to a log line.app.onError((err, c) => { const rid = c.get('requestId') ?? '?'; if (err instanceof SyntaxError) { return c.json({ error: 'Invalid JSON body', requestId: rid }, 400); } const status = errStatus(err); if (status >= 500) { // Hide internals from the client on 5xx — the log line has the details. log.error({ rid, err: { message: errMessage(err) } }, 'unhandled error'); return c.json({ error: 'Internal server error', requestId: rid }, 500); } // 4xx with a throw-attached statusCode — safe to surface the message. return c.json({ error: errMessage(err), requestId: rid }, status as 400);});
export { safeEqual, isAllowedOrigin, clientIp, RATE_LIMIT_MAX, resetRateLimitState, seedRateLimitState };export default app;