Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverExposure.ts

80 lines2.4 KB

1import type { NetworkInterfaceInfo } from "node:os";
2import type { DesktopServerExposureMode } from "@workbench/contracts";
3​
4const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
5const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
6​
7export interface DesktopServerExposure {
8 readonly mode: DesktopServerExposureMode;
9 readonly bindHost: string;
10 readonly localHttpUrl: string;
11 readonly localWsUrl: string;
12 readonly endpointUrl: string | null;
13 readonly advertisedHost: string | null;
15​
16const normalizeOptionalHost = (value: string | undefined): string | undefined => {
17 const normalized = value?.trim();
18 return normalized && normalized.length > 0 ? normalized : undefined;
19};
20​
21const isUsableLanIpv4Address = (address: string): boolean =>
22 !address.startsWith("127.") && !address.startsWith("169.254.");
23​
24export function resolveLanAdvertisedHost(
25 networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
26 explicitHost: string | undefined,
27): string | null {
28 const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
29 if (normalizedExplicitHost) {
30 return normalizedExplicitHost;
31 }
32​
33 for (const interfaceAddresses of Object.values(networkInterfaces)) {
34 if (!interfaceAddresses) continue;
35​
36 for (const address of interfaceAddresses) {
37 if (address.internal) continue;
38 if (address.family !== "IPv4") continue;
39 if (!isUsableLanIpv4Address(address.address)) continue;
40 return address.address;
41 }
42 }
43​
44 return null;
46​
47export function resolveDesktopServerExposure(input: {
48 readonly mode: DesktopServerExposureMode;
49 readonly port: number;
50 readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
51 readonly advertisedHostOverride?: string;
52}): DesktopServerExposure {
53 const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
54 const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
55​
56 if (input.mode === "local-only") {
57 return {
58 mode: input.mode,
59 bindHost: DESKTOP_LOOPBACK_HOST,
60 localHttpUrl,
61 localWsUrl,
62 endpointUrl: null,
63 advertisedHost: null,
64 };
65 }
66​
67 const advertisedHost = resolveLanAdvertisedHost(
68 input.networkInterfaces,
69 input.advertisedHostOverride,
70 );
71​
72 return {
73 mode: input.mode,
74 bindHost: DESKTOP_LAN_BIND_HOST,
75 localHttpUrl,
76 localWsUrl,
77 endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
78 advertisedHost,
79 };