import { isIP } from 'node:net'; import type { Api, Model } from '@earendil-works/pi-ai'; import type { ExtensionContext } from '@earendil-works/pi-coding-agent'; function isPrivateHost(host: string): boolean { if (host === 'localhost' || host.endsWith('.localhost') || host === '::1') { return true; } if (isIP(host) === 4) { const [first = 0, second = 0] = host.split('.').map(Number); return ( first === 127 || first === 10 || (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168) ); } return isIP(host) === 6 && /^(fc|fd)/.test(host); } // No DNS guessing or cloud fallback. This checks the destination, not the // implementation of a third-party provider configured by the owner. export function isLocalEndpoint(value: unknown): boolean { if (typeof value !== 'string') { return false; } try { const url = new URL(value); if (url.protocol !== 'http:' && url.protocol !== 'https:') { return false; } return isPrivateHost(url.hostname.replace(/^\[|\]$/g, '').toLowerCase()); } catch { return false; } } export async function requireLocalEndpoint( registry: ExtensionContext['modelRegistry'], model: Model, ): Promise { const auth = await registry.getApiKeyAndHeaders(model); if (!auth.ok) { throw new Error('request-failed'); } if (!isLocalEndpoint(auth.baseUrl ?? model.baseUrl)) { throw new Error('local-endpoint-required'); } }