From e06c5780b31fe42b2e874b30cbe4b9332b253772 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 26 Apr 2026 19:13:05 -0700 Subject: [PATCH] feat(remote): add advertised endpoint registry Co-authored-by: codex --- apps/desktop/package.json | 1 + apps/desktop/src/main.ts | 31 +- apps/desktop/src/preload.ts | 2 + apps/desktop/src/serverExposure.test.ts | 97 +++++- apps/desktop/src/serverExposure.ts | 95 +++++- .../settings/ConnectionsSettings.tsx | 278 ++++++++++++------ .../settings/SettingsPanels.browser.tsx | 2 + apps/web/src/localApi.test.ts | 1 + bun.lock | 1 + .../src/advertisedEndpoint.test.ts | 61 ++++ .../client-runtime/src/advertisedEndpoint.ts | 78 +++++ packages/client-runtime/src/index.ts | 1 + packages/contracts/src/index.ts | 1 + packages/contracts/src/ipc.ts | 2 + packages/contracts/src/remoteAccess.ts | 68 +++++ 15 files changed, 634 insertions(+), 85 deletions(-) create mode 100644 packages/client-runtime/src/advertisedEndpoint.test.ts create mode 100644 packages/client-runtime/src/advertisedEndpoint.ts create mode 100644 packages/contracts/src/remoteAccess.ts diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 165395507e..316228fd1a 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -20,6 +20,7 @@ "electron-updater": "^6.6.2" }, "devDependencies": { + "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "@types/node": "catalog:", diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index c5507c6fb0..c5713d2035 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -55,7 +55,10 @@ import { } from "./clientPersistence.ts"; import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts"; import { showDesktopConfirmDialog } from "./confirmDialog.ts"; -import { resolveDesktopServerExposure } from "./serverExposure.ts"; +import { + resolveDesktopCoreAdvertisedEndpoints, + resolveDesktopServerExposure, +} from "./serverExposure.ts"; import { syncShellEnvironment } from "./syncShellEnvironment.ts"; import { waitForBackendStartupReady } from "./backendStartupReadiness.ts"; import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts"; @@ -102,6 +105,7 @@ const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secr const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret"; const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; +const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints"; const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3"); const STATE_DIR = Path.join(BASE_DIR, "userdata"); const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json"); @@ -297,6 +301,7 @@ function backendChildEnv(): NodeJS.ProcessEnv { delete env.T3CODE_DESKTOP_WS_URL; delete env.T3CODE_DESKTOP_LAN_ACCESS; delete env.T3CODE_DESKTOP_LAN_HOST; + delete env.T3CODE_DESKTOP_HTTPS_ENDPOINTS; return env; } @@ -308,6 +313,20 @@ function getDesktopServerExposureState(): DesktopServerExposureState { }; } +function getDesktopAdvertisedEndpoints() { + const exposure = resolveDesktopServerExposure({ + mode: desktopServerExposureMode, + port: backendPort, + networkInterfaces: OS.networkInterfaces(), + ...(backendAdvertisedHost ? { advertisedHostOverride: backendAdvertisedHost } : {}), + }); + return resolveDesktopCoreAdvertisedEndpoints({ + port: backendPort, + exposure, + customHttpsEndpointUrls: resolveCustomHttpsEndpointUrls(), + }); +} + function getDesktopSecretStorage() { return { isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(), @@ -321,6 +340,13 @@ function resolveAdvertisedHostOverride(): string | undefined { return override && override.length > 0 ? override : undefined; } +function resolveCustomHttpsEndpointUrls(): readonly string[] { + return (process.env.T3CODE_DESKTOP_HTTPS_ENDPOINTS ?? "") + .split(",") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0); +} + async function applyDesktopServerExposureMode( mode: DesktopServerExposureMode, options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean }, @@ -1669,6 +1695,9 @@ function registerIpcHandlers(): void { return nextState; }); + ipcMain.removeHandler(GET_ADVERTISED_ENDPOINTS_CHANNEL); + ipcMain.handle(GET_ADVERTISED_ENDPOINTS_CHANNEL, async () => getDesktopAdvertisedEndpoints()); + ipcMain.removeHandler(PICK_FOLDER_CHANNEL); ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => { const owner = BrowserWindow.getFocusedWindow() ?? mainWindow; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index a675604872..e918e782ab 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -24,6 +24,7 @@ const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secr const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret"; const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; +const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints"; contextBridge.exposeInMainWorld("desktopBridge", { getAppBranding: () => { @@ -53,6 +54,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId), getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL), setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode), + getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL), pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options), confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message), setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme), diff --git a/apps/desktop/src/serverExposure.test.ts b/apps/desktop/src/serverExposure.test.ts index c83bbc210e..86e9d3a655 100644 --- a/apps/desktop/src/serverExposure.test.ts +++ b/apps/desktop/src/serverExposure.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; -import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts"; +import { + resolveDesktopCoreAdvertisedEndpoints, + resolveDesktopServerExposure, + resolveLanAdvertisedHost, +} from "./serverExposure.ts"; describe("resolveLanAdvertisedHost", () => { it("prefers an explicit host override", () => { @@ -74,6 +78,97 @@ describe("resolveLanAdvertisedHost", () => { }); }); +describe("resolveDesktopCoreAdvertisedEndpoints", () => { + it("advertises loopback and LAN endpoints without provider-specific assumptions", () => { + const exposure = resolveDesktopServerExposure({ + mode: "network-accessible", + port: 3773, + networkInterfaces: { + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + }); + + expect( + resolveDesktopCoreAdvertisedEndpoints({ + port: 3773, + exposure, + customHttpsEndpointUrls: ["https://desktop.example.ts.net"], + }), + ).toEqual([ + { + id: "desktop-loopback:3773", + label: "This machine", + provider: { + id: "desktop-core", + label: "Desktop", + kind: "core", + isAddon: false, + }, + httpBaseUrl: "http://127.0.0.1:3773/", + wsBaseUrl: "ws://127.0.0.1:3773/", + reachability: "loopback", + compatibility: { + hostedHttpsApp: "mixed-content-blocked", + desktopApp: "compatible", + }, + source: "desktop-core", + status: "available", + description: "Loopback endpoint for this desktop app.", + }, + { + id: "desktop-lan:http://192.168.1.44:3773", + label: "Local network", + provider: { + id: "desktop-core", + label: "Desktop", + kind: "core", + isAddon: false, + }, + httpBaseUrl: "http://192.168.1.44:3773/", + wsBaseUrl: "ws://192.168.1.44:3773/", + reachability: "lan", + compatibility: { + hostedHttpsApp: "mixed-content-blocked", + desktopApp: "compatible", + }, + source: "desktop-core", + status: "available", + isDefault: true, + description: "Reachable from devices on the same network.", + }, + { + id: "manual:https://desktop.example.ts.net", + label: "Custom HTTPS", + provider: { + id: "manual", + label: "Manual", + kind: "manual", + isAddon: false, + }, + httpBaseUrl: "https://desktop.example.ts.net/", + wsBaseUrl: "wss://desktop.example.ts.net/", + reachability: "public", + compatibility: { + hostedHttpsApp: "compatible", + desktopApp: "compatible", + }, + source: "user", + status: "unknown", + description: "User-configured HTTPS endpoint for this desktop backend.", + }, + ]); + }); +}); + describe("resolveDesktopServerExposure", () => { it("keeps the desktop server loopback-only when local-only mode is selected", () => { expect( diff --git a/apps/desktop/src/serverExposure.ts b/apps/desktop/src/serverExposure.ts index 65c99b60e1..fb6b284b9e 100644 --- a/apps/desktop/src/serverExposure.ts +++ b/apps/desktop/src/serverExposure.ts @@ -1,5 +1,13 @@ import type { NetworkInterfaceInfo } from "node:os"; -import type { DesktopServerExposureMode } from "@t3tools/contracts"; +import { + createAdvertisedEndpoint, + type CreateAdvertisedEndpointInput, +} from "@t3tools/client-runtime"; +import type { + AdvertisedEndpoint, + AdvertisedEndpointProvider, + DesktopServerExposureMode, +} from "@t3tools/contracts"; const DESKTOP_LOOPBACK_HOST = "127.0.0.1"; const DESKTOP_LAN_BIND_HOST = "0.0.0.0"; @@ -13,6 +21,26 @@ export interface DesktopServerExposure { readonly advertisedHost: string | null; } +export interface DesktopAdvertisedEndpointInput { + readonly port: number; + readonly exposure: DesktopServerExposure; + readonly customHttpsEndpointUrls?: readonly string[]; +} + +const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { + id: "desktop-core", + label: "Desktop", + kind: "core", + isAddon: false, +}; + +const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { + id: "manual", + label: "Manual", + kind: "manual", + isAddon: false, +}; + const normalizeOptionalHost = (value: string | undefined): string | undefined => { const normalized = value?.trim(); return normalized && normalized.length > 0 ? normalized : undefined; @@ -78,3 +106,68 @@ export function resolveDesktopServerExposure(input: { advertisedHost, }; } + +function createDesktopEndpoint( + input: Omit, +): AdvertisedEndpoint { + return createAdvertisedEndpoint({ + ...input, + provider: DESKTOP_CORE_ENDPOINT_PROVIDER, + source: "desktop-core", + }); +} + +function createManualEndpoint( + input: Omit, +): AdvertisedEndpoint { + return createAdvertisedEndpoint({ + ...input, + provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER, + source: "user", + }); +} + +export function resolveDesktopCoreAdvertisedEndpoints( + input: DesktopAdvertisedEndpointInput, +): readonly AdvertisedEndpoint[] { + const endpoints: AdvertisedEndpoint[] = [ + createDesktopEndpoint({ + id: `desktop-loopback:${input.port}`, + label: "This machine", + httpBaseUrl: input.exposure.localHttpUrl, + reachability: "loopback", + status: "available", + description: "Loopback endpoint for this desktop app.", + }), + ]; + + if (input.exposure.endpointUrl) { + endpoints.push( + createDesktopEndpoint({ + id: `desktop-lan:${input.exposure.endpointUrl}`, + label: "Local network", + httpBaseUrl: input.exposure.endpointUrl, + reachability: "lan", + status: "available", + isDefault: true, + description: "Reachable from devices on the same network.", + }), + ); + } + + for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) { + endpoints.push( + createManualEndpoint({ + id: `manual:${customEndpointUrl}`, + label: "Custom HTTPS", + httpBaseUrl: customEndpointUrl, + reachability: "public", + hostedHttpsCompatibility: "compatible", + status: "unknown", + description: "User-configured HTTPS endpoint for this desktop backend.", + }), + ); + } + + return endpoints; +} diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index f6ab384d9f..3328952c7b 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -3,6 +3,7 @@ import { memo, useCallback, useEffect, useMemo, useState } from "react"; import { type AuthClientSession, type AuthPairingLink, + type AdvertisedEndpoint, type DesktopServerExposureState, type EnvironmentId, } from "@t3tools/contracts"; @@ -244,6 +245,31 @@ function removeDesktopClientSession( return current.filter((clientSession) => clientSession.sessionId !== sessionId); } +function selectPairingEndpoint( + endpoints: ReadonlyArray, +): AdvertisedEndpoint | null { + const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable"); + return ( + availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ?? + availableEndpoints.find((endpoint) => endpoint.isDefault) ?? + availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ?? + null + ); +} + +function resolveAdvertisedEndpointPairingUrl( + endpoint: AdvertisedEndpoint, + credential: string, +): string { + if (endpoint.compatibility.hostedHttpsApp === "compatible") { + return ( + resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ?? + resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential) + ); + } + return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential); +} + function resolveCurrentOriginPairingUrl(credential: string): string { const url = new URL("/pair", window.location.href); return setPairingTokenOnUrl(url, credential).toString(); @@ -252,6 +278,7 @@ function resolveCurrentOriginPairingUrl(credential: string): string { type PairingLinkListRowProps = { pairingLink: ServerPairingLinkRecord; endpointUrl: string | null | undefined; + endpoints: ReadonlyArray; revokingPairingLinkId: string | null; onRevoke: (id: string) => void; }; @@ -259,6 +286,7 @@ type PairingLinkListRowProps = { const PairingLinkListRow = memo(function PairingLinkListRow({ pairingLink, endpointUrl, + endpoints, revokingPairingLinkId, onRevoke, }: PairingLinkListRowProps) { @@ -280,12 +308,17 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ : null, [endpointUrl, pairingLink.credential], ); + const endpointPairingUrl = useMemo(() => { + const endpoint = selectPairingEndpoint(endpoints); + return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null; + }, [endpoints, pairingLink.credential]); const shareablePairingUrl = - endpointUrl != null && endpointUrl !== "" + endpointPairingUrl ?? + (endpointUrl != null && endpointUrl !== "" ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)) : isLoopbackHostname(window.location.hostname) ? null - : currentOriginPairingUrl; + : currentOriginPairingUrl); const copyValue = shareablePairingUrl ?? pairingLink.credential; const canCopyToClipboard = typeof window !== "undefined" && @@ -622,6 +655,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio type PairingClientsListProps = { endpointUrl: string | null | undefined; + endpoints: ReadonlyArray; isLoading: boolean; pairingLinks: ReadonlyArray; clientSessions: ReadonlyArray; @@ -633,6 +667,7 @@ type PairingClientsListProps = { const PairingClientsList = memo(function PairingClientsList({ endpointUrl, + endpoints, isLoading, pairingLinks, clientSessions, @@ -648,6 +683,7 @@ const PairingClientsList = memo(function PairingClientsList({ key={pairingLink.id} pairingLink={pairingLink} endpointUrl={endpointUrl} + endpoints={endpoints} revokingPairingLinkId={revokingPairingLinkId} onRevoke={onRevokePairingLink} /> @@ -671,6 +707,58 @@ const PairingClientsList = memo(function PairingClientsList({ ); }); +type AdvertisedEndpointListRowProps = { + endpoint: AdvertisedEndpoint; +}; + +const endpointCompatibilityLabel = (endpoint: AdvertisedEndpoint): string => { + if (endpoint.compatibility.hostedHttpsApp === "compatible") { + return "Works with hosted app"; + } + if (endpoint.compatibility.hostedHttpsApp === "mixed-content-blocked") { + return "Desktop or direct browser only"; + } + if (endpoint.compatibility.hostedHttpsApp === "requires-configuration") { + return "Needs HTTPS setup"; + } + return "Compatibility unknown"; +}; + +const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({ + endpoint, +}: AdvertisedEndpointListRowProps) { + return ( +
+
+
+
+ +

{endpoint.label}

+ {endpoint.provider.isAddon ? ( + + Add-on + + ) : null} +
+

+ {endpoint.httpBaseUrl} +

+
+

+ {endpointCompatibilityLabel(endpoint)} +

+
+
+ ); +}); + type SavedBackendListRowProps = { environmentId: EnvironmentId; reconnectingEnvironmentId: EnvironmentId | null; @@ -776,6 +864,9 @@ export function ConnectionsSettings() { const [desktopServerExposureState, setDesktopServerExposureState] = useState(null); + const [desktopAdvertisedEndpoints, setDesktopAdvertisedEndpoints] = useState< + ReadonlyArray + >([]); const [desktopServerExposureError, setDesktopServerExposureError] = useState(null); const [desktopPairingLinks, setDesktopPairingLinks] = useState< ReadonlyArray @@ -1107,8 +1198,21 @@ export function ConnectionsSettings() { error instanceof Error ? error.message : "Failed to load network exposure state."; setDesktopServerExposureError(message); }); + void desktopBridge + .getAdvertisedEndpoints() + .then((endpoints) => { + if (cancelled) return; + setDesktopAdvertisedEndpoints(endpoints); + }) + .catch((error: unknown) => { + if (cancelled) return; + const message = + error instanceof Error ? error.message : "Failed to load reachable endpoints."; + setDesktopServerExposureError(message); + }); } else { setDesktopServerExposureState(null); + setDesktopAdvertisedEndpoints([]); setDesktopServerExposureError(null); } @@ -1125,6 +1229,7 @@ export function ConnectionsSettings() { setDesktopClientSessions([]); setDesktopAccessManagementError(null); setDesktopServerExposureState(null); + setDesktopAdvertisedEndpoints([]); setDesktopServerExposureError(null); }, [canManageLocalBackend]); const visibleDesktopPairingLinks = useMemo( @@ -1137,87 +1242,95 @@ export function ConnectionsSettings() { <> {desktopBridge ? ( - {desktopServerExposureError} - ) : null - } - control={ - { - if (isUpdatingDesktopServerExposure) return; - if (!open) setPendingDesktopServerExposureMode(null); - }} - > - { - setPendingDesktopServerExposureMode( - checked ? "network-accessible" : "local-only", - ); + <> + {desktopServerExposureError} + ) : null + } + control={ + { + if (isUpdatingDesktopServerExposure) return; + if (!open) setPendingDesktopServerExposureMode(null); }} - aria-label="Enable network access" - /> - - - - {pendingDesktopServerExposureMode === "network-accessible" - ? "Enable network access?" - : "Disable network access?"} - - - {pendingDesktopServerExposureMode === "network-accessible" - ? "T3 Code will restart to expose this environment over the network." - : "T3 Code will restart and limit this environment back to this machine."} - - - - - } - > - Cancel - - - - - - } - /> + > + { + setPendingDesktopServerExposureMode( + checked ? "network-accessible" : "local-only", + ); + }} + aria-label="Enable network access" + /> + + + + {pendingDesktopServerExposureMode === "network-accessible" + ? "Enable network access?" + : "Disable network access?"} + + + {pendingDesktopServerExposureMode === "network-accessible" + ? "T3 Code will restart to expose this environment over the network." + : "T3 Code will restart and limit this environment back to this machine."} + + + + + } + > + Cancel + + + + + + } + /> + {desktopAdvertisedEndpoints.map((endpoint) => ( + + ))} + ) : ( >; + readonly advertisedEndpoints?: Awaited>; readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"]; readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"]; }): DesktopBridge => { @@ -307,6 +308,7 @@ const createDesktopBridgeStub = (overrides?: { endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null, advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null, })), + getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []), pickFolder: vi.fn().mockResolvedValue(null), confirm: vi.fn().mockResolvedValue(false), setTheme: vi.fn().mockResolvedValue(undefined), diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index c361cbd787..de5f057875 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -179,6 +179,7 @@ function makeDesktopBridge(overrides: Partial = {}): DesktopBridg endpointUrl: null, advertisedHost: null, }), + getAdvertisedEndpoints: async () => [], pickFolder: async () => null, confirm: async () => true, setTheme: async () => undefined, diff --git a/bun.lock b/bun.lock index a8dc482f46..f405bba68e 100644 --- a/bun.lock +++ b/bun.lock @@ -21,6 +21,7 @@ "electron-updater": "^6.6.2", }, "devDependencies": { + "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "@types/node": "catalog:", diff --git a/packages/client-runtime/src/advertisedEndpoint.test.ts b/packages/client-runtime/src/advertisedEndpoint.test.ts new file mode 100644 index 0000000000..1cbfde87bd --- /dev/null +++ b/packages/client-runtime/src/advertisedEndpoint.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; + +import { + classifyHostedHttpsCompatibility, + createAdvertisedEndpoint, + deriveWsBaseUrl, + normalizeHttpBaseUrl, +} from "./advertisedEndpoint.ts"; + +const coreProvider = { + id: "desktop-core", + label: "Desktop", + kind: "core", + isAddon: false, +} as const; + +describe("advertised endpoint helpers", () => { + it("normalizes HTTP and WebSocket base URLs", () => { + expect(normalizeHttpBaseUrl("https://example.com/path?x=1#hash")).toBe("https://example.com/"); + expect(normalizeHttpBaseUrl("wss://example.com/socket")).toBe("https://example.com/"); + expect(deriveWsBaseUrl("https://example.com/api")).toBe("wss://example.com/"); + expect(deriveWsBaseUrl("http://127.0.0.1:3773")).toBe("ws://127.0.0.1:3773/"); + }); + + it("marks HTTP endpoints as blocked from hosted HTTPS apps", () => { + expect(classifyHostedHttpsCompatibility("http://192.168.1.44:3773")).toBe( + "mixed-content-blocked", + ); + expect(classifyHostedHttpsCompatibility("https://desktop.example.com", "compatible")).toBe( + "compatible", + ); + }); + + it("creates provider-neutral endpoint records", () => { + expect( + createAdvertisedEndpoint({ + id: "lan:http://192.168.1.44:3773", + label: "LAN", + provider: coreProvider, + httpBaseUrl: "http://192.168.1.44:3773", + reachability: "lan", + source: "desktop-core", + isDefault: true, + }), + ).toEqual({ + id: "lan:http://192.168.1.44:3773", + label: "LAN", + provider: coreProvider, + httpBaseUrl: "http://192.168.1.44:3773/", + wsBaseUrl: "ws://192.168.1.44:3773/", + reachability: "lan", + compatibility: { + hostedHttpsApp: "mixed-content-blocked", + desktopApp: "compatible", + }, + source: "desktop-core", + status: "available", + isDefault: true, + }); + }); +}); diff --git a/packages/client-runtime/src/advertisedEndpoint.ts b/packages/client-runtime/src/advertisedEndpoint.ts new file mode 100644 index 0000000000..314d8272c8 --- /dev/null +++ b/packages/client-runtime/src/advertisedEndpoint.ts @@ -0,0 +1,78 @@ +import type { + AdvertisedEndpoint, + AdvertisedEndpointHostedHttpsCompatibility, + AdvertisedEndpointProvider, + AdvertisedEndpointReachability, + AdvertisedEndpointSource, + AdvertisedEndpointStatus, +} from "@t3tools/contracts"; + +export interface CreateAdvertisedEndpointInput { + readonly id: string; + readonly label: string; + readonly provider: AdvertisedEndpointProvider; + readonly httpBaseUrl: string; + readonly reachability: AdvertisedEndpointReachability; + readonly hostedHttpsCompatibility?: AdvertisedEndpointHostedHttpsCompatibility; + readonly desktopCompatibility?: "compatible" | "unknown"; + readonly source: AdvertisedEndpointSource; + readonly status?: AdvertisedEndpointStatus; + readonly isDefault?: boolean; + readonly description?: string; +} + +export function normalizeHttpBaseUrl(rawValue: string): string { + const url = new URL(rawValue); + if (url.protocol === "ws:") { + url.protocol = "http:"; + } else if (url.protocol === "wss:") { + url.protocol = "https:"; + } + + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error(`Endpoint must use HTTP or HTTPS. Received ${url.protocol}`); + } + + url.pathname = "/"; + url.search = ""; + url.hash = ""; + return url.toString(); +} + +export function deriveWsBaseUrl(httpBaseUrl: string): string { + const url = new URL(normalizeHttpBaseUrl(httpBaseUrl)); + url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; + return url.toString(); +} + +export function classifyHostedHttpsCompatibility( + httpBaseUrl: string, + fallback: AdvertisedEndpointHostedHttpsCompatibility = "unknown", +): AdvertisedEndpointHostedHttpsCompatibility { + const url = new URL(normalizeHttpBaseUrl(httpBaseUrl)); + if (url.protocol === "http:") { + return "mixed-content-blocked"; + } + return fallback === "mixed-content-blocked" ? "unknown" : fallback; +} + +export function createAdvertisedEndpoint(input: CreateAdvertisedEndpointInput): AdvertisedEndpoint { + const httpBaseUrl = normalizeHttpBaseUrl(input.httpBaseUrl); + return { + id: input.id, + label: input.label, + provider: input.provider, + httpBaseUrl, + wsBaseUrl: deriveWsBaseUrl(httpBaseUrl), + reachability: input.reachability, + compatibility: { + hostedHttpsApp: + input.hostedHttpsCompatibility ?? classifyHostedHttpsCompatibility(httpBaseUrl), + desktopApp: input.desktopCompatibility ?? "compatible", + }, + source: input.source, + status: input.status ?? "available", + ...(input.isDefault === undefined ? {} : { isDefault: input.isDefault }), + ...(input.description === undefined ? {} : { description: input.description }), + }; +} diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 9ca76328a8..2a1f15ae0e 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -1,2 +1,3 @@ +export * from "./advertisedEndpoint.ts"; export * from "./knownEnvironment.ts"; export * from "./scoped.ts"; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 47081d8df1..c86b7a2f6c 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -1,6 +1,7 @@ export * from "./baseSchemas.ts"; export * from "./auth.ts"; export * from "./environment.ts"; +export * from "./remoteAccess.ts"; export * from "./ipc.ts"; export * from "./terminal.ts"; export * from "./provider.ts"; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index a1abc0fa4a..1aeaf02a45 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -52,6 +52,7 @@ import type { OrchestrationThreadStreamItem, } from "./orchestration.ts"; import type { EnvironmentId } from "./baseSchemas.ts"; +import type { AdvertisedEndpoint } from "./remoteAccess.ts"; import { EditorId } from "./editor.ts"; import { ServerSettings, type ClientSettings, type ServerSettingsPatch } from "./settings.ts"; @@ -160,6 +161,7 @@ export interface DesktopBridge { removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; getServerExposureState: () => Promise; setServerExposureMode: (mode: DesktopServerExposureMode) => Promise; + getAdvertisedEndpoints: () => Promise; pickFolder: (options?: PickFolderOptions) => Promise; confirm: (message: string) => Promise; setTheme: (theme: DesktopTheme) => Promise; diff --git a/packages/contracts/src/remoteAccess.ts b/packages/contracts/src/remoteAccess.ts new file mode 100644 index 0000000000..70a20d7aeb --- /dev/null +++ b/packages/contracts/src/remoteAccess.ts @@ -0,0 +1,68 @@ +import { Schema } from "effect"; + +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; + +export const AdvertisedEndpointProviderKind = Schema.Literals([ + "core", + "private-network", + "tunnel", + "manual", +]); +export type AdvertisedEndpointProviderKind = typeof AdvertisedEndpointProviderKind.Type; + +export const AdvertisedEndpointReachability = Schema.Literals([ + "loopback", + "lan", + "private-network", + "public", +]); +export type AdvertisedEndpointReachability = typeof AdvertisedEndpointReachability.Type; + +export const AdvertisedEndpointHostedHttpsCompatibility = Schema.Literals([ + "compatible", + "mixed-content-blocked", + "requires-configuration", + "unknown", +]); +export type AdvertisedEndpointHostedHttpsCompatibility = + typeof AdvertisedEndpointHostedHttpsCompatibility.Type; + +export const AdvertisedEndpointStatus = Schema.Literals(["available", "unavailable", "unknown"]); +export type AdvertisedEndpointStatus = typeof AdvertisedEndpointStatus.Type; + +export const AdvertisedEndpointSource = Schema.Literals([ + "desktop-core", + "desktop-addon", + "server", + "user", +]); +export type AdvertisedEndpointSource = typeof AdvertisedEndpointSource.Type; + +export const AdvertisedEndpointProvider = Schema.Struct({ + id: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + kind: AdvertisedEndpointProviderKind, + isAddon: Schema.Boolean, +}); +export type AdvertisedEndpointProvider = typeof AdvertisedEndpointProvider.Type; + +export const AdvertisedEndpointCompatibility = Schema.Struct({ + hostedHttpsApp: AdvertisedEndpointHostedHttpsCompatibility, + desktopApp: Schema.Literals(["compatible", "unknown"]), +}); +export type AdvertisedEndpointCompatibility = typeof AdvertisedEndpointCompatibility.Type; + +export const AdvertisedEndpoint = Schema.Struct({ + id: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + provider: AdvertisedEndpointProvider, + httpBaseUrl: TrimmedNonEmptyString, + wsBaseUrl: TrimmedNonEmptyString, + reachability: AdvertisedEndpointReachability, + compatibility: AdvertisedEndpointCompatibility, + source: AdvertisedEndpointSource, + status: AdvertisedEndpointStatus, + isDefault: Schema.optional(Schema.Boolean), + description: Schema.optional(TrimmedNonEmptyString), +}); +export type AdvertisedEndpoint = typeof AdvertisedEndpoint.Type;