import * as crypto from "crypto"; import * as net from "net"; import * as os from "os"; import { IDictionary } from "../../common/declarations"; import { isTruthyEnvFlag } from "../../common/helpers"; import { inject } from "../../common/di"; import { DevServerOriginService, IDevServerOriginOptions, } from "../../contracts/internal/dev-server-origin-service"; import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; import { Logger } from "../../contracts/logger"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; const LOOPBACK = "127.0.0.1"; const ANDROID_EMULATOR_HOST = "10.0.2.2"; export interface IDevServerOriginInputs { port: number; /** The dev server serves https. */ https?: boolean; /** `NS_HMR_HOST` as the user set it. */ envHost?: string; /** `NS_HMR_PREFER_LAN_HOST`: the LAN address wins over every route but `NS_HMR_HOST`. */ preferLan?: boolean; isAndroid: boolean; isEmulator: boolean; adbReverse?: boolean; /** The Mac's address on the device's USB tunnel. */ tunnelAddress?: string; lanAddress?: string; } /** * The origin a device uses for the dev server. The app uses the string * verbatim as module identity, so it is assembled here rather than * serialized through a URL parser. */ export function chooseDevServerOrigin(inputs: IDevServerOriginInputs): string { const scheme = inputs.https ? "https" : "http"; const envHost = inputs.envHost?.trim(); if (envHost) { return formatDevServerOrigin(envHost, inputs.port, scheme); } return formatDevServerOrigin( chooseDevServerHost(inputs), inputs.port, scheme, ); } /** Mirrors how `@nativescript/vite` decides to serve https. */ export function isDevServerHttps(env: NodeJS.ProcessEnv): boolean { return env.NS_HTTPS === "1" || env.NS_HTTPS === "true"; } function chooseDevServerHost(inputs: IDevServerOriginInputs): string { if (inputs.preferLan && inputs.lanAddress) { return inputs.lanAddress; } if (inputs.isAndroid) { if (inputs.adbReverse) { return LOOPBACK; } if (inputs.isEmulator) { return ANDROID_EMULATOR_HOST; } } else { if (inputs.isEmulator) { return LOOPBACK; } if (inputs.tunnelAddress) { return inputs.tunnelAddress; } } return inputs.lanAddress || LOOPBACK; } /** * `://:`, with an IPv6 host bracketed. `host` may carry * its own port (`host:port`, `[v6]:port`), which then wins over `port`. */ export function formatDevServerOrigin( host: string, port: number, scheme: "http" | "https" = "http", ): string { if (host.startsWith("[")) { const closing = host.indexOf("]"); if (closing !== -1) { const bracketed = host.slice(0, closing + 1); const explicitPort = parsePort(host.slice(closing + 1)); return `${scheme}://${bracketed}:${explicitPort ?? port}`; } } if (net.isIPv6(host)) { return `${scheme}://[${host}]:${port}`; } const colon = host.indexOf(":"); if (colon !== -1 && colon === host.lastIndexOf(":")) { const explicitPort = parsePort(host.slice(colon)); if (explicitPort !== undefined) { return `${scheme}://${host.slice(0, colon)}:${explicitPort}`; } } return `${scheme}://${host}:${port}`; } function parsePort(suffix: string): number | undefined { if (!/^:\d+$/.test(suffix)) { return undefined; } const port = Number(suffix.slice(1)); return port > 0 && port <= 65535 ? port : undefined; } /** * The first external IPv4 address, skipping link-local ones: macOS lists * 169.254.x.x on AWDL and idle USB interfaces, which other devices can't * reliably reach. */ export function guessLanAddress( interfaces: NodeJS.Dict, ): string | undefined { for (const entries of Object.values(interfaces)) { for (const entry of entries || []) { const family = entry?.family as string | number; if ( !entry || entry.internal || (family !== "IPv4" && family !== 4) || !entry.address || entry.address.startsWith("169.254.") ) { continue; } return entry.address; } } return undefined; } export class DevServerOriginServiceImpl implements DevServerOriginService { private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private logger = inject(Logger); private mobileHelper = inject("mobileHelper"); private viteHmrPortService = inject(ViteHmrPortService); private tokens: IDictionary = {}; private devices: IDictionary<{ platform: string; origin: string }> = {}; public getToken(platform: string): string { const key = platform.toLowerCase(); if (!this.tokens[key]) { this.tokens[key] = crypto.randomBytes(24).toString("base64url"); } return this.tokens[key]; } public async chooseOrigin( device: Mobile.IDevice, options: IDevServerOriginOptions = {}, ): Promise { const { identifier } = device.deviceInfo; const platform = device.deviceInfo.platform.toLowerCase(); const isAndroid = this.mobileHelper.isAndroidPlatform(platform); const inputs: IDevServerOriginInputs = { port: await this.viteHmrPortService.getPort(platform), https: isDevServerHttps(process.env), envHost: process.env.NS_HMR_HOST, preferLan: isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST), isAndroid, isEmulator: device.isEmulator, adbReverse: options.adbReverse, tunnelAddress: isAndroid ? undefined : this.iOSDeviceTunnelService.getHostAddress(identifier), lanAddress: guessLanAddress(this.getNetworkInterfaces()), }; const origin = chooseDevServerOrigin(inputs); this.devices[identifier] = { platform, origin }; this.logger.trace( `Vite dev server origin for ${identifier}: ${origin}`, inputs, ); const reachesLoopback = device.isEmulator || (isAndroid && options.adbReverse); if ( !reachesLoopback && !inputs.envHost?.trim() && !inputs.tunnelAddress && !inputs.lanAddress ) { this.logger.warn( `Found no LAN address on this machine, so ${device.deviceInfo.displayName || identifier} may not reach the Vite dev server at ${origin}. Set NS_HMR_HOST to an address the device can reach.`, ); } return origin; } public getOrigin(deviceIdentifier: string): string | undefined { return this.devices[deviceIdentifier]?.origin; } public getDevServerFile(deviceIdentifier: string): string | null { const device = this.devices[deviceIdentifier]; if (!device) { return null; } return JSON.stringify({ origin: device.origin, token: this.getToken(device.platform), }); } public forget(deviceIdentifier: string): void { delete this.devices[deviceIdentifier]; } protected getNetworkInterfaces(): NodeJS.Dict { return os.networkInterfaces(); } }