|
| 1 | +import { exec as execCallback } from 'child_process'; |
| 2 | +import { promisify } from 'util'; |
| 3 | +import { config, getHealthCheckConfig, HealthCheckConfig } from '../common/EnvConfig.js'; |
| 4 | + |
| 5 | +const exec = promisify(execCallback); |
| 6 | + |
| 7 | +export interface Route { |
| 8 | + ip: string; |
| 9 | + port: number; |
| 10 | + priority: number; |
| 11 | + healthCheck?: HealthCheckConfig; |
| 12 | +} |
| 13 | + |
| 14 | +export interface RouteRegistrationResult { |
| 15 | + success: boolean; |
| 16 | + message: string; |
| 17 | + routes?: Route[]; |
| 18 | + domain?: string; |
| 19 | + error?: string; |
| 20 | +} |
| 21 | + |
| 22 | +interface ProviderInfo { |
| 23 | + providerUrl: string; |
| 24 | + userId: string; |
| 25 | + signature: string; |
| 26 | +} |
| 27 | + |
| 28 | +// Store active route refresh intervals |
| 29 | +const refreshIntervals = new Map<string, NodeJS.Timeout>(); |
| 30 | + |
| 31 | +/** |
| 32 | + * Parse provider string into components |
| 33 | + */ |
| 34 | +function parseProviderString(providerString: string): ProviderInfo { |
| 35 | + const [providerUrl, userId = '', signature = ''] = providerString.split(','); |
| 36 | + return { providerUrl, userId, signature }; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Extract the provider's public IP from the provider URL |
| 41 | + * The provider URL format is typically: https://provider.domain.com:port |
| 42 | + * We need to resolve this to get the actual IP, or use the VPN_ENDPOINT_ANNOUNCE if available |
| 43 | + */ |
| 44 | +async function getProviderPublicIp(providerUrl: string): Promise<string> { |
| 45 | + // Extract hostname from URL |
| 46 | + const url = new URL(providerUrl); |
| 47 | + const hostname = url.hostname; |
| 48 | + |
| 49 | + // If it's already an IP, return it |
| 50 | + if (/^(\d{1,3}\.){3}\d{1,3}$/.test(hostname)) { |
| 51 | + return hostname; |
| 52 | + } |
| 53 | + |
| 54 | + // Try to resolve the hostname to an IP |
| 55 | + try { |
| 56 | + const { stdout } = await exec(`getent hosts ${hostname} | awk '{ print $1 }' | head -1`); |
| 57 | + const ip = stdout.trim(); |
| 58 | + if (ip) { |
| 59 | + return ip; |
| 60 | + } |
| 61 | + } catch { |
| 62 | + // Fall through to use hostname |
| 63 | + } |
| 64 | + |
| 65 | + // Return hostname if we can't resolve (gateway will resolve it) |
| 66 | + return hostname; |
| 67 | +} |
| 68 | + |
| 69 | +/** |
| 70 | + * Register tunnel route with mesh-router-backend |
| 71 | + * POST /router/api/routes/:userid/:sig { routes: Route[] } |
| 72 | + */ |
| 73 | +export async function registerTunnelRoute( |
| 74 | + providerString: string, |
| 75 | + tunnelPort: number = 443 |
| 76 | +): Promise<RouteRegistrationResult> { |
| 77 | + const backendUrl = config.BACKEND_URL; |
| 78 | + |
| 79 | + if (!backendUrl) { |
| 80 | + console.log('[RouteRegistrar] BACKEND_URL not configured, skipping route registration'); |
| 81 | + return { |
| 82 | + success: true, |
| 83 | + message: 'Route registration skipped (no BACKEND_URL)', |
| 84 | + }; |
| 85 | + } |
| 86 | + |
| 87 | + const { providerUrl, userId, signature } = parseProviderString(providerString); |
| 88 | + |
| 89 | + if (!userId || !signature) { |
| 90 | + return { |
| 91 | + success: false, |
| 92 | + message: 'Route registration failed', |
| 93 | + error: 'Missing userId or signature in provider string', |
| 94 | + }; |
| 95 | + } |
| 96 | + |
| 97 | + try { |
| 98 | + // Get the provider's public IP (this is where the gateway will route traffic) |
| 99 | + const providerIp = await getProviderPublicIp(providerUrl); |
| 100 | + const healthCheck = getHealthCheckConfig(); |
| 101 | + |
| 102 | + const route: Route = { |
| 103 | + ip: providerIp, |
| 104 | + port: tunnelPort, |
| 105 | + priority: config.ROUTE_PRIORITY, |
| 106 | + }; |
| 107 | + |
| 108 | + if (healthCheck) { |
| 109 | + route.healthCheck = healthCheck; |
| 110 | + } |
| 111 | + |
| 112 | + const url = `${backendUrl}/router/api/routes/${encodeURIComponent(userId)}/${encodeURIComponent(signature)}`; |
| 113 | + const jsonData = JSON.stringify({ routes: [route] }).replace(/"/g, '\\"'); |
| 114 | + const curlCommand = `curl -s -X POST -H "Content-Type: application/json" -d "${jsonData}" "${url}"`; |
| 115 | + |
| 116 | + const { stdout } = await exec(curlCommand); |
| 117 | + const response = JSON.parse(stdout); |
| 118 | + |
| 119 | + if (response.error) { |
| 120 | + return { |
| 121 | + success: false, |
| 122 | + message: 'Route registration failed', |
| 123 | + error: response.error, |
| 124 | + }; |
| 125 | + } |
| 126 | + |
| 127 | + console.log(`[RouteRegistrar] Route registered: ${providerIp}:${tunnelPort} (priority: ${config.ROUTE_PRIORITY})`); |
| 128 | + |
| 129 | + return { |
| 130 | + success: true, |
| 131 | + message: response.message || 'Route registered successfully', |
| 132 | + routes: response.routes, |
| 133 | + domain: response.domain, |
| 134 | + }; |
| 135 | + } catch (error) { |
| 136 | + return { |
| 137 | + success: false, |
| 138 | + message: 'Route registration request failed', |
| 139 | + error: error instanceof Error ? error.message : String(error), |
| 140 | + }; |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Start the route refresh loop for a provider |
| 146 | + */ |
| 147 | +export function startRouteRefreshLoop(providerString: string, tunnelPort: number = 443): void { |
| 148 | + // Stop any existing refresh loop for this provider |
| 149 | + stopRouteRefreshLoop(providerString); |
| 150 | + |
| 151 | + if (!config.BACKEND_URL) { |
| 152 | + console.log('[RouteRegistrar] BACKEND_URL not configured, not starting refresh loop'); |
| 153 | + return; |
| 154 | + } |
| 155 | + |
| 156 | + const refreshInterval = config.ROUTE_REFRESH_INTERVAL * 1000; |
| 157 | + console.log(`[RouteRegistrar] Starting route refresh loop (interval: ${config.ROUTE_REFRESH_INTERVAL}s)`); |
| 158 | + |
| 159 | + const interval = setInterval(async () => { |
| 160 | + try { |
| 161 | + const result = await registerTunnelRoute(providerString, tunnelPort); |
| 162 | + if (!result.success) { |
| 163 | + console.error(`[RouteRegistrar] Route refresh failed: ${result.error}`); |
| 164 | + } |
| 165 | + } catch (error) { |
| 166 | + console.error('[RouteRegistrar] Route refresh error:', error); |
| 167 | + } |
| 168 | + }, refreshInterval); |
| 169 | + |
| 170 | + refreshIntervals.set(providerString, interval); |
| 171 | +} |
| 172 | + |
| 173 | +/** |
| 174 | + * Stop the route refresh loop for a provider |
| 175 | + */ |
| 176 | +export function stopRouteRefreshLoop(providerString: string): void { |
| 177 | + const interval = refreshIntervals.get(providerString); |
| 178 | + if (interval) { |
| 179 | + clearInterval(interval); |
| 180 | + refreshIntervals.delete(providerString); |
| 181 | + console.log('[RouteRegistrar] Stopped route refresh loop'); |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +/** |
| 186 | + * Stop all route refresh loops |
| 187 | + */ |
| 188 | +export function stopAllRouteRefreshLoops(): void { |
| 189 | + for (const [providerString, interval] of refreshIntervals) { |
| 190 | + clearInterval(interval); |
| 191 | + console.log(`[RouteRegistrar] Stopped route refresh loop for ${providerString.split(',')[0]}`); |
| 192 | + } |
| 193 | + refreshIntervals.clear(); |
| 194 | +} |
0 commit comments