import { isPrivateUrlResolved } from './ssrf'; export type LlmProviderKind = 'local' | 'hosted'; const ALLOWED_LOCAL_PROVIDER_HOSTS = new Set([ 'localhost', '127.0.0.1', '::1', 'host.docker.internal', ]); function statusError(message: string, statusCode: number): Error & { statusCode: number } { return Object.assign(new Error(message), { statusCode }); } // Validates an LLM provider baseUrl before we persist it or hit it. Local providers must // target the loopback/docker-host set; hosted providers must be https and non-loopback. // Returns the URL normalized (trailing slash stripped) so downstream string compares match. export function validateProviderBaseUrl(baseUrl: string, type: LlmProviderKind): string { let parsed: URL; try { parsed = new URL(baseUrl); } catch { throw statusError('baseUrl must be a valid absolute URL', 400); } if (!['http:', 'https:'].includes(parsed.protocol)) { throw statusError('baseUrl must use http or https', 400); } if (parsed.username || parsed.password) { throw statusError('baseUrl must not include embedded credentials', 400); } if (!parsed.hostname) { throw statusError('baseUrl hostname is required', 400); } if (type === 'local') { if (!ALLOWED_LOCAL_PROVIDER_HOSTS.has(parsed.hostname)) { throw statusError( 'Local providers must use localhost, 127.0.0.1, ::1, or host.docker.internal', 400, ); } } else { if (parsed.protocol !== 'https:') { throw statusError('Hosted providers must use https', 400); } if (ALLOWED_LOCAL_PROVIDER_HOSTS.has(parsed.hostname)) { throw statusError('Hosted providers must not target local machine addresses', 400); } } parsed.pathname = parsed.pathname.replace(/\/+$/, ''); if (!parsed.pathname) { parsed.pathname = ''; } return parsed.toString(); } export async function assertProviderBaseUrlAllowed(baseUrl: string, type: LlmProviderKind): Promise { const normalized = validateProviderBaseUrl(baseUrl, type); const parsed = new URL(normalized); if (type === 'hosted' && await isPrivateUrlResolved(parsed)) { throw statusError('Hosted providers must not resolve to private or internal addresses', 400); } } // Rewrites local provider loopback hosts to host.docker.internal so requests originating // inside the substrate container can still reach a model server running on the host. export function resolveProviderBaseUrl(baseUrl: string, type: LlmProviderKind): string { const parsed = new URL(validateProviderBaseUrl(baseUrl, type)); if (type === 'local' && (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '::1')) { parsed.hostname = 'host.docker.internal'; } return parsed.toString().replace(/\/$/, ''); }