import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; import type { Hono, MiddlewareHandler } from 'hono'; type Role = 'read' | 'admin' | 'service'; const verifiedPrincipals = new WeakMap(); const credentialRequests = new WeakSet(); const researchPrincipals = new WeakMap(); const researchBearer = (request: Request) => /^Bearer sb-research\./i.test(request.headers.get('authorization') ?? ''); /** Research routes opt into this accessor; privileged service/operator accessors never impersonate agents. */ export function getResearchHttpPrincipal( request: Request ): 'operator' | 'service' | `agent:${string}` | undefined { return researchPrincipals.get(request) ?? getCredentialHttpPrincipal(request); } /** Server-owned identity established only after successful HTTP authorization. */ export function getVerifiedHttpPrincipal(request: Request): 'operator' | 'service' | undefined { return verifiedPrincipals.get(request); } /** Catalog authorship/review needs a credential, not the loopback development bypass. */ export function getCredentialHttpPrincipal(request: Request): 'operator' | 'service' | undefined { return credentialRequests.has(request) ? verifiedPrincipals.get(request) : undefined; } export interface HttpSecurityOptions { readToken?: string; adminToken?: string; serviceToken?: string; disabled?: boolean; environment?: string; hostname?: string; origins?: string[]; browserSessions?: boolean; /** Explicit web API HTTP capability; never used by synchronous authorize or WebSocket upgrades. */ resolveResearchCredential?: ( request: Request ) => Promise<{ principal: `agent:${string}` } | Response | undefined>; } const cookieName = 'stock_bot_session'; const sessionSeconds = 3600; const digest = (value: string) => createHash('sha256').update(value).digest(); const equal = (a: string, b: string) => timingSafeEqual(digest(a), digest(b)); export function httpSecurityOptions(env: NodeJS.ProcessEnv = process.env): HttpSecurityOptions { return { readToken: env.STOCK_BOT_READ_TOKEN, adminToken: env.STOCK_BOT_ADMIN_TOKEN, serviceToken: env.STOCK_BOT_SERVICE_TOKEN, disabled: env.STOCK_BOT_AUTH_DISABLED === 'true', environment: env.NODE_ENV ?? 'development', hostname: env.STOCK_BOT_HTTP_HOST ?? '127.0.0.1', origins: env.STOCK_BOT_ALLOWED_ORIGINS?.split(',') .map(origin => origin.trim()) .filter(Boolean), }; } /** A small operator boundary, not a multi-user identity provider. Secure by default. */ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOptions()) { const environment = options.environment ?? 'development'; const hostname = options.hostname ?? '127.0.0.1'; const disabled = options.disabled === true; if ( disabled && (environment === 'production' || !['127.0.0.1', '::1', 'localhost'].includes(hostname)) ) { throw new Error( 'Authentication may only be disabled on an explicit loopback development/test listener' ); } const tokens = { read: options.readToken, admin: options.adminToken, service: options.serviceToken, }; if (!disabled) { if (!tokens.admin || !tokens.service) { throw new Error( 'Set STOCK_BOT_ADMIN_TOKEN and STOCK_BOT_SERVICE_TOKEN before starting HTTP services' ); } const values = Object.values(tokens).filter((value): value is string => !!value); if ( values.some(value => value.length < 32 || value.trim() !== value) || new Set(values).size !== values.length ) { throw new Error( 'HTTP access tokens must be distinct, unpadded secrets of at least 32 characters' ); } } const allowedOrigins = options.origins ?? (environment === 'production' ? [] : [ 'http://localhost:3000', 'http://localhost:4200', 'http://localhost:5173', 'http://localhost:5174', 'http://127.0.0.1:3000', 'http://127.0.0.1:5173', ]); if (allowedOrigins.includes('*') || allowedOrigins.includes('null')) { throw new Error('Explicit trusted HTTP origins are required'); } const originAllowed = (request: Request) => { const origin = request.headers.get('origin'); return !!origin && (origin === new URL(request.url).origin || allowedOrigins.includes(origin)); }; const signingKey = (role: 'read' | 'admin') => tokens[role]; const signature = (payload: string, key: string) => createHmac('sha256', key).update(`stock-bot-ui:${payload}`).digest('base64url'); function roleForToken(value: string): Role | undefined { for (const role of ['read', 'admin', 'service'] as const) { if (tokens[role] && equal(value, tokens[role])) { return role; } } return undefined; } function authenticate(request: Request): { role: Role; cookie: boolean } | undefined { if (disabled) { return { role: 'admin', cookie: false }; } const authorization = request.headers.get('authorization'); if (authorization) { const match = /^Bearer ([^\s]+)$/i.exec(authorization); const role = match?.[1] ? roleForToken(match[1]) : undefined; return role ? { role, cookie: false } : undefined; } if (!options.browserSessions) { return undefined; } const value = request.headers .get('cookie') ?.split(';') .map(part => part.trim()) .find(part => part.startsWith(`${cookieName}=`)) ?.slice(cookieName.length + 1); if (!value || value.length > 512) { return; } const [role, expiry, nonce, mac, extra] = value.split('.'); if ( (role !== 'read' && role !== 'admin') || extra || !nonce || !mac || !/^\d+$/.test(expiry ?? '') ) { return; } const expiresAt = Number(expiry); if ( !Number.isSafeInteger(expiresAt) || expiresAt <= Date.now() / 1000 || expiresAt > Date.now() / 1000 + sessionSeconds + 10 ) { return; } const key = signingKey(role); if (!key || !equal(mac, signature(`${role}.${expiry}.${nonce}`, key))) { return; } return { role, cookie: true }; } function authorize(request: Request, admin = false): Response | undefined { researchPrincipals.delete(request); verifiedPrincipals.delete(request); if (researchBearer(request)) { return Response.json( { error: 'Research credentials are unavailable on this interface' }, { status: 403, headers: { 'Cache-Control': 'no-store' } } ); } credentialRequests.delete(request); const identity = authenticate(request); if (!identity) { return Response.json( { error: 'Authentication required' }, { status: 401, headers: { 'WWW-Authenticate': 'Bearer', 'Cache-Control': 'no-store' } } ); } if (admin && identity.role === 'read') { return Response.json({ error: 'Administrator access required' }, { status: 403 }); } const isWebSocket = request.headers.get('upgrade')?.toLowerCase() === 'websocket'; const mutates = !['GET', 'HEAD', 'OPTIONS'].includes(request.method); // Browser sessions are CSRF-protected. WebSocket upgrades validate Origin as well. if ( (isWebSocket && request.headers.has('origin') && !originAllowed(request)) || (identity.cookie && (mutates || isWebSocket) && !originAllowed(request)) ) { return Response.json({ error: 'Untrusted request origin' }, { status: 403 }); } if (identity.role !== 'read') { verifiedPrincipals.set(request, identity.role === 'service' ? 'service' : 'operator'); if (!disabled) { credentialRequests.add(request); } } return undefined; } const middleware: MiddlewareHandler = async (context, next) => { const path = context.req.path; if ( path === '/health' || path.startsWith('/health/') || (options.browserSessions && path === '/api/auth/session') || context.req.method === 'OPTIONS' ) { await next(); return undefined; } if (researchBearer(context.req.raw)) { context.header('Cache-Control', 'no-store'); if (disabled || !options.resolveResearchCredential || context.req.header('upgrade')) { return context.json( { error: 'Research credentials are unavailable on this interface' }, 403 ); } if (context.req.header('origin') && !originAllowed(context.req.raw)) { return context.json({ error: 'Untrusted request origin' }, 403); } const resolved = await options.resolveResearchCredential(context.req.raw); if (resolved instanceof Response) { return resolved; } if (!resolved) { return context.json({ error: 'Invalid or disabled research credential' }, 401); } researchPrincipals.set(context.req.raw, resolved.principal); await next(); return undefined; } const admin = !['GET', 'HEAD'].includes(context.req.method) || /^\/api\/(queue|operations|handlers)(\/|$)/.test(path); const rejection = authorize(context.req.raw, admin); if (rejection) { return rejection; } await next(); return undefined; }; function mount(app: Hono): void { app.use('*', middleware); if (!options.browserSessions) { return; } const cookie = (value: string, maxAge: number) => `${cookieName}=${value}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${environment === 'production' ? '; Secure' : ''}`; app.get('/api/auth/session', context => { const identity = authenticate(context.req.raw); context.header('Cache-Control', 'no-store'); return context.json( { authenticated: !!identity, role: identity?.role }, identity ? 200 : 401 ); }); let attempts = 0; let windowStart = Date.now(); app.post('/api/auth/session', async context => { context.header('Cache-Control', 'no-store'); if (Date.now() - windowStart > 60_000) { attempts = 0; windowStart = Date.now(); } if (++attempts > 30) { return context.json({ error: 'Too many sign-in attempts' }, 429); } if (context.req.header('origin') && !originAllowed(context.req.raw)) { return context.json({ error: 'Untrusted request origin' }, 403); } if (!context.req.header('content-type')?.startsWith('application/json')) { return context.json({ error: 'JSON required' }, 415); } const input: unknown = await context.req.json().catch(() => null); const token = input && typeof input === 'object' && 'token' in input && typeof input.token === 'string' ? input.token : ''; if (token.length > 4096) { return context.json({ error: 'Invalid access token' }, 401); } if (token.startsWith('sb-research.')) { return context.json( { error: 'Research credentials cannot establish browser sessions' }, 403 ); } const role = disabled ? 'admin' : roleForToken(token); if (!role || role === 'service') { return context.json({ error: 'Invalid access token' }, 401); } const key = signingKey(role); if (key) { const payload = `${role}.${Math.floor(Date.now() / 1000) + sessionSeconds}.${randomBytes(16).toString('hex')}`; context.header( 'Set-Cookie', cookie(`${payload}.${signature(payload, key)}`, sessionSeconds) ); } return context.json({ authenticated: true, role }); }); app.delete('/api/auth/session', context => { if (!originAllowed(context.req.raw)) { return context.json({ error: 'Untrusted request origin' }, 403); } context.header('Set-Cookie', cookie('', 0)); context.header('Cache-Control', 'no-store'); return context.json({ authenticated: false }); }); } return { mount, authorize, hostname, allowedOrigins, researchEnabled: !disabled && !!options.resolveResearchCredential, }; } export type HttpSecurity = ReturnType; /** Used only by server-to-server clients; never expose this token to the browser. */ export function authenticatedServiceFetch( input: string | URL | Request, init?: RequestInit ): Promise { const token = process.env.STOCK_BOT_SERVICE_TOKEN; if (!token) { const target = new URL(input instanceof Request ? input.url : input.toString()); if ( process.env.STOCK_BOT_AUTH_DISABLED !== 'true' || process.env.NODE_ENV === 'production' || !['localhost', '127.0.0.1', '[::1]'].includes(target.hostname) ) { throw new Error('STOCK_BOT_SERVICE_TOKEN is required for internal HTTP requests'); } } const headers = new Headers(input instanceof Request ? input.headers : undefined); new Headers(init?.headers).forEach((value, key) => headers.set(key, value)); if (token) { headers.set('Authorization', `Bearer ${token}`); } return fetch(input, { ...init, headers, redirect: 'error' }); }