diff --git a/REMOTE.md b/REMOTE.md index 2d7edb1c15..61a1cc3b5c 100644 --- a/REMOTE.md +++ b/REMOTE.md @@ -27,10 +27,12 @@ If you are already running the desktop app and want to make it reachable from ot The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks. -When no user default is saved, the app chooses the best reachable endpoint for pairing links: +When no user default is saved, the app uses the built-in LAN endpoint for pairing links when +available. You can set another endpoint as the default from the expanded endpoint list. -- HTTPS/WSS-compatible endpoints are preferred because they work from `https://app.t3.codes`. -- Non-loopback HTTP endpoints are used for direct LAN pairing when HTTPS is not available. +- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default + automatically. +- Non-loopback HTTP endpoints are useful for direct LAN pairing. - Loopback-only endpoints are not useful for another device unless that device is the same machine. If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link. @@ -43,7 +45,13 @@ Depending on your Tailscale setup, this may include: - the machine's `100.x.y.z` Tailnet IP - a MagicDNS name -- an HTTPS MagicDNS endpoint when Tailscale HTTPS is available for the machine +- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend + +The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as +`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this +backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend +with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale +Serve to proxy HTTPS traffic to the local backend. The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow. @@ -75,6 +83,19 @@ From there, connect from another device in either of these ways: Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument. +For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve: + +```bash +npx t3 serve --tailscale-serve +``` + +By default this configures Tailscale Serve on HTTPS port 443 and advertises +`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port: + +```bash +npx t3 serve --tailscale-serve --tailscale-serve-port 8443 +``` + > Note > The GUIs do not currently support adding projects on remote environments. > For now, use `t3 project ...` on the server machine instead. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 316228fd1a..53bee5f63a 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -15,6 +15,7 @@ "smoke-test": "node scripts/smoke-test.mjs" }, "dependencies": { + "@effect/platform-node": "catalog:", "effect": "catalog:", "electron": "40.6.0", "electron-updater": "^6.6.2" @@ -23,6 +24,7 @@ "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", + "@t3tools/tailscale": "workspace:*", "@types/node": "catalog:", "effect-acp": "workspace:*", "tsdown": "catalog:", diff --git a/apps/desktop/src/desktopSettings.test.ts b/apps/desktop/src/desktopSettings.test.ts index 9b467d22ca..c012e39b5f 100644 --- a/apps/desktop/src/desktopSettings.test.ts +++ b/apps/desktop/src/desktopSettings.test.ts @@ -9,6 +9,7 @@ import { readDesktopSettings, resolveDefaultDesktopSettings, setDesktopServerExposurePreference, + setDesktopTailscaleServePreference, setDesktopUpdateChannelPreference, writeDesktopSettings, } from "./desktopSettings.ts"; @@ -35,6 +36,8 @@ describe("desktopSettings", () => { it("defaults packaged nightly builds to the nightly update channel", () => { expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({ serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "nightly", updateChannelConfiguredByUser: false, }); @@ -45,12 +48,16 @@ describe("desktopSettings", () => { writeDesktopSettings(settingsPath, { serverExposureMode: "network-accessible", + tailscaleServeEnabled: true, + tailscaleServePort: 8443, updateChannel: "latest", updateChannelConfiguredByUser: true, }); expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({ serverExposureMode: "network-accessible", + tailscaleServeEnabled: true, + tailscaleServePort: 8443, updateChannel: "latest", updateChannelConfiguredByUser: true, }); @@ -61,6 +68,8 @@ describe("desktopSettings", () => { setDesktopServerExposurePreference( { serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "latest", updateChannelConfiguredByUser: false, }, @@ -68,6 +77,29 @@ describe("desktopSettings", () => { ), ).toEqual({ serverExposureMode: "network-accessible", + tailscaleServeEnabled: false, + tailscaleServePort: 443, + updateChannel: "latest", + updateChannelConfiguredByUser: false, + }); + }); + + it("persists the requested Tailscale Serve preference", () => { + expect( + setDesktopTailscaleServePreference( + { + serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, + updateChannel: "latest", + updateChannelConfiguredByUser: false, + }, + { enabled: true, port: 8443 }, + ), + ).toEqual({ + serverExposureMode: "local-only", + tailscaleServeEnabled: true, + tailscaleServePort: 8443, updateChannel: "latest", updateChannelConfiguredByUser: false, }); @@ -78,6 +110,8 @@ describe("desktopSettings", () => { setDesktopUpdateChannelPreference( { serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "latest", updateChannelConfiguredByUser: false, }, @@ -85,6 +119,8 @@ describe("desktopSettings", () => { ), ).toEqual({ serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "nightly", updateChannelConfiguredByUser: true, }); @@ -103,6 +139,8 @@ describe("desktopSettings", () => { expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({ serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "nightly", updateChannelConfiguredByUser: false, }); @@ -121,6 +159,8 @@ describe("desktopSettings", () => { expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({ serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "nightly", updateChannelConfiguredByUser: false, }); @@ -140,8 +180,30 @@ describe("desktopSettings", () => { expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({ serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: 443, updateChannel: "latest", updateChannelConfiguredByUser: true, }); }); + + it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => { + const settingsPath = makeSettingsPath(); + fs.writeFileSync( + settingsPath, + JSON.stringify({ + tailscaleServeEnabled: true, + tailscaleServePort: 0, + }), + "utf8", + ); + + expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({ + serverExposureMode: "local-only", + tailscaleServeEnabled: true, + tailscaleServePort: 443, + updateChannel: "latest", + updateChannelConfiguredByUser: false, + }); + }); }); diff --git a/apps/desktop/src/desktopSettings.ts b/apps/desktop/src/desktopSettings.ts index 6ece5189cc..854c363e09 100644 --- a/apps/desktop/src/desktopSettings.ts +++ b/apps/desktop/src/desktopSettings.ts @@ -6,12 +6,18 @@ import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts"; export interface DesktopSettings { readonly serverExposureMode: DesktopServerExposureMode; + readonly tailscaleServeEnabled: boolean; + readonly tailscaleServePort: number; readonly updateChannel: DesktopUpdateChannel; readonly updateChannelConfiguredByUser: boolean; } +export const DEFAULT_TAILSCALE_SERVE_PORT = 443; + export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { serverExposureMode: "local-only", + tailscaleServeEnabled: false, + tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT, updateChannel: "latest", updateChannelConfiguredByUser: false, }; @@ -35,6 +41,26 @@ export function setDesktopServerExposurePreference( }; } +export function setDesktopTailscaleServePreference( + settings: DesktopSettings, + input: { readonly enabled: boolean; readonly port?: number }, +): DesktopSettings { + const port = normalizeTailscaleServePort(input.port); + return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port + ? settings + : { + ...settings, + tailscaleServeEnabled: input.enabled, + tailscaleServePort: port, + }; +} + +export function normalizeTailscaleServePort(value: unknown): number { + return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535 + ? value + : DEFAULT_TAILSCALE_SERVE_PORT; +} + export function setDesktopUpdateChannelPreference( settings: DesktopSettings, requestedChannel: DesktopUpdateChannel, @@ -57,6 +83,8 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D const raw = FS.readFileSync(settingsPath, "utf8"); const parsed = JSON.parse(raw) as { readonly serverExposureMode?: unknown; + readonly tailscaleServeEnabled?: unknown; + readonly tailscaleServePort?: unknown; readonly updateChannel?: unknown; readonly updateChannelConfiguredByUser?: unknown; }; @@ -72,6 +100,8 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D return { serverExposureMode: parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only", + tailscaleServeEnabled: parsed.tailscaleServeEnabled === true, + tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort), updateChannel: updateChannelConfiguredByUser && parsedUpdateChannel !== null ? parsedUpdateChannel diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 74baa16c54..f80f34b264 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -41,6 +41,7 @@ import { DEFAULT_DESKTOP_SETTINGS, readDesktopSettings, setDesktopServerExposurePreference, + setDesktopTailscaleServePreference, setDesktopUpdateChannelPreference, writeDesktopSettings, } from "./desktopSettings.ts"; @@ -107,6 +108,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 SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled"; 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"); @@ -304,6 +306,8 @@ function backendChildEnv(): NodeJS.ProcessEnv { delete env.T3CODE_DESKTOP_LAN_ACCESS; delete env.T3CODE_DESKTOP_LAN_HOST; delete env.T3CODE_DESKTOP_HTTPS_ENDPOINTS; + delete env.T3CODE_TAILSCALE_SERVE; + delete env.T3CODE_TAILSCALE_SERVE_PORT; return env; } @@ -312,6 +316,8 @@ function getDesktopServerExposureState(): DesktopServerExposureState { mode: desktopServerExposureMode, endpointUrl: backendEndpointUrl, advertisedHost: backendAdvertisedHost, + tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled, + tailscaleServePort: desktopSettings.tailscaleServePort, }; } @@ -329,6 +335,8 @@ async function getDesktopAdvertisedEndpoints() { }); const tailscaleEndpoints = await resolveTailscaleAdvertisedEndpoints({ port: backendPort, + serveEnabled: desktopSettings.tailscaleServeEnabled, + servePort: desktopSettings.tailscaleServePort, networkInterfaces: OS.networkInterfaces(), }); return [...coreEndpoints, ...tailscaleEndpoints]; @@ -394,6 +402,16 @@ async function applyDesktopServerExposureMode( return getDesktopServerExposureState(); } +async function applyDesktopTailscaleServeEnabled(input: { + readonly enabled: boolean; + readonly port?: number; +}): Promise { + desktopSettings = setDesktopTailscaleServePreference(desktopSettings, input); + writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings); + relaunchDesktopApp(input.enabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled"); + return getDesktopServerExposureState(); +} + function relaunchDesktopApp(reason: string): void { writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`); setImmediate(() => { @@ -1446,6 +1464,8 @@ function startBackend(): void { t3Home: BASE_DIR, host: backendBindHost, desktopBootstrapToken: backendBootstrapToken, + tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled, + tailscaleServePort: desktopSettings.tailscaleServePort, ...(backendObservabilitySettings.otlpTracesUrl ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl } : {}), @@ -1715,6 +1735,28 @@ function registerIpcHandlers(): void { return nextState; }); + ipcMain.removeHandler(SET_TAILSCALE_SERVE_ENABLED_CHANNEL); + ipcMain.handle(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, async (_event, rawInput: unknown) => { + if (typeof rawInput !== "object" || rawInput === null) { + throw new Error("Invalid Tailscale Serve input."); + } + const input = rawInput as { readonly enabled?: unknown; readonly port?: unknown }; + if (typeof input.enabled !== "boolean") { + throw new Error("Invalid Tailscale Serve input."); + } + const nextSettings = setDesktopTailscaleServePreference(desktopSettings, { + enabled: input.enabled, + ...(typeof input.port === "number" ? { port: input.port } : {}), + }); + if (nextSettings === desktopSettings) { + return getDesktopServerExposureState(); + } + return applyDesktopTailscaleServeEnabled({ + enabled: input.enabled, + port: nextSettings.tailscaleServePort, + }); + }); + ipcMain.removeHandler(GET_ADVERTISED_ENDPOINTS_CHANNEL); ipcMain.handle(GET_ADVERTISED_ENDPOINTS_CHANNEL, async () => getDesktopAdvertisedEndpoints()); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index fdfaf20813..d9ae6ed936 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -32,6 +32,7 @@ const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt"; const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt"; const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; +const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled"; const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints"; contextBridge.exposeInMainWorld("desktopBridge", { @@ -86,6 +87,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password), getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL), setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode), + setTailscaleServeEnabled: (input) => + ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input), getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL), pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options), confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message), diff --git a/apps/desktop/src/tailscaleEndpointProvider.test.ts b/apps/desktop/src/tailscaleEndpointProvider.test.ts index d228a2c3bf..2e92b7ee5d 100644 --- a/apps/desktop/src/tailscaleEndpointProvider.test.ts +++ b/apps/desktop/src/tailscaleEndpointProvider.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { Effect } from "effect"; import { isTailscaleIpv4Address, @@ -14,12 +15,14 @@ describe("tailscale endpoint provider", () => { expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false); }); - it("parses MagicDNS names from tailscale status", () => { + it("parses MagicDNS names from tailscale status", async () => { expect( - parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })), + Effect.runSync( + parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })), + ), ).toBe("desktop.tail.ts.net"); - expect(parseTailscaleMagicDnsName("{}")).toBeNull(); - expect(parseTailscaleMagicDnsName("not-json")).toBeNull(); + expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull(); + await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined(); }); it("resolves Tailscale endpoints as add-on advertised endpoints", async () => { @@ -62,7 +65,7 @@ describe("tailscale endpoint provider", () => { description: "Reachable from devices on the same Tailnet.", }, { - id: "tailscale-magicdns:https://desktop.tail.ts.net:3773", + id: "tailscale-magicdns:https://desktop.tail.ts.net/", label: "Tailscale HTTPS", provider: { id: "tailscale", @@ -70,17 +73,50 @@ describe("tailscale endpoint provider", () => { kind: "private-network", isAddon: true, }, - httpBaseUrl: "https://desktop.tail.ts.net:3773/", - wsBaseUrl: "wss://desktop.tail.ts.net:3773/", + httpBaseUrl: "https://desktop.tail.ts.net/", + wsBaseUrl: "wss://desktop.tail.ts.net/", reachability: "private-network", compatibility: { hostedHttpsApp: "requires-configuration", desktopApp: "compatible", }, source: "desktop-addon", - status: "unknown", + status: "unavailable", description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.", }, ]); }); + + it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => { + await expect( + resolveTailscaleAdvertisedEndpoints({ + port: 3773, + networkInterfaces: {}, + statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }), + serveEnabled: true, + probe: async () => true, + }), + ).resolves.toEqual([ + { + id: "tailscale-magicdns:https://desktop.tail.ts.net/", + label: "Tailscale HTTPS", + provider: { + id: "tailscale", + label: "Tailscale", + kind: "private-network", + isAddon: true, + }, + httpBaseUrl: "https://desktop.tail.ts.net/", + wsBaseUrl: "wss://desktop.tail.ts.net/", + reachability: "private-network", + compatibility: { + hostedHttpsApp: "compatible", + desktopApp: "compatible", + }, + source: "desktop-addon", + status: "available", + description: "HTTPS endpoint served by Tailscale Serve.", + }, + ]); + }); }); diff --git a/apps/desktop/src/tailscaleEndpointProvider.ts b/apps/desktop/src/tailscaleEndpointProvider.ts index 75e3096d6b..053eac5d44 100644 --- a/apps/desktop/src/tailscaleEndpointProvider.ts +++ b/apps/desktop/src/tailscaleEndpointProvider.ts @@ -1,11 +1,24 @@ -import * as ChildProcess from "node:child_process"; import type { NetworkInterfaceInfo } from "node:os"; +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { createAdvertisedEndpoint, type CreateAdvertisedEndpointInput, } from "@t3tools/client-runtime"; import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts"; +import { + buildTailscaleHttpsBaseUrl, + isTailscaleIpv4Address, + parseTailscaleMagicDnsName, + probeTailscaleHttpsEndpoint, + readTailscaleStatus, +} from "@t3tools/tailscale"; +import { Effect, Layer } from "effect"; + +export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale"; + +const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici); const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { id: "tailscale", @@ -14,17 +27,6 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { isAddon: true, }; -const TAILSCALE_STATUS_TIMEOUT_MS = 1_500; - -interface TailscaleStatusSelf { - readonly DNSName?: unknown; - readonly TailscaleIPs?: unknown; -} - -interface TailscaleStatusJson { - readonly Self?: TailscaleStatusSelf; -} - function createTailscaleEndpoint( input: Omit, ): AdvertisedEndpoint { @@ -35,24 +37,6 @@ function createTailscaleEndpoint( }); } -export function isTailscaleIpv4Address(address: string): boolean { - const parts = address.split("."); - if (parts.length !== 4) { - return false; - } - const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10)); - if ( - first === undefined || - second === undefined || - third === undefined || - fourth === undefined || - [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255) - ) { - return false; - } - return first === 100 && second >= 64 && second <= 127; -} - export function resolveTailscaleIpAdvertisedEndpoints(input: { readonly port: number; readonly networkInterfaces: NodeJS.Dict; @@ -86,72 +70,72 @@ export function resolveTailscaleIpAdvertisedEndpoints(input: { return endpoints; } -export function parseTailscaleMagicDnsName(rawStatusJson: string): string | null { - let parsed: TailscaleStatusJson; - try { - parsed = JSON.parse(rawStatusJson) as TailscaleStatusJson; - } catch { - return null; - } - - const dnsName = parsed.Self?.DNSName; - if (typeof dnsName !== "string") { - return null; - } - - const normalized = dnsName.trim().replace(/\.$/u, ""); - return normalized.length > 0 ? normalized : null; -} - -export function resolveTailscaleMagicDnsAdvertisedEndpoint(input: { +export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: { readonly dnsName: string | null; - readonly port: number; -}): AdvertisedEndpoint | null { + readonly serveEnabled: boolean; + readonly servePort?: number; + readonly probe?: (baseUrl: string) => Promise; +}): Promise { if (!input.dnsName) { return null; } - const httpBaseUrl = `https://${input.dnsName}:${input.port}`; + const httpBaseUrl = buildTailscaleHttpsBaseUrl({ + magicDnsName: input.dnsName, + ...(input.servePort === undefined ? {} : { servePort: input.servePort }), + }); + const isReachable = input.serveEnabled + ? await (input.probe?.(httpBaseUrl) ?? + Effect.runPromise( + probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe( + Effect.provide(TailscaleDesktopLayer), + ), + )) + : false; + return createTailscaleEndpoint({ id: `tailscale-magicdns:${httpBaseUrl}`, label: "Tailscale HTTPS", httpBaseUrl, reachability: "private-network", - hostedHttpsCompatibility: "requires-configuration", - status: "unknown", - description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.", - }); -} - -async function readTailscaleStatusJson(): Promise { - return await new Promise((resolve) => { - const child = ChildProcess.execFile( - "tailscale", - ["status", "--json"], - { timeout: TAILSCALE_STATUS_TIMEOUT_MS, windowsHide: true }, - (error, stdout) => { - if (error) { - resolve(null); - return; - } - resolve(stdout); - }, - ); - child.once("error", () => resolve(null)); + hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration", + status: isReachable ? "available" : "unavailable", + description: isReachable + ? "HTTPS endpoint served by Tailscale Serve." + : "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.", }); } export async function resolveTailscaleAdvertisedEndpoints(input: { readonly port: number; + readonly serveEnabled?: boolean; + readonly servePort?: number; readonly networkInterfaces: NodeJS.Dict; readonly statusJson?: string | null; + readonly probe?: (baseUrl: string) => Promise; }): Promise { const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input); - const statusJson = - input.statusJson === undefined ? await readTailscaleStatusJson() : input.statusJson; - const magicDnsEndpoint = resolveTailscaleMagicDnsAdvertisedEndpoint({ - dnsName: statusJson ? parseTailscaleMagicDnsName(statusJson) : null, - port: input.port, + const dnsName = + input.statusJson === undefined + ? await Effect.runPromise( + readTailscaleStatus.pipe( + Effect.map((status) => status.magicDnsName), + Effect.catch(() => Effect.succeed(null)), + Effect.provide(TailscaleDesktopLayer), + ), + ) + : input.statusJson + ? await Effect.runPromise( + parseTailscaleMagicDnsName(input.statusJson).pipe( + Effect.catch(() => Effect.succeed(null)), + ), + ) + : null; + const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({ + dnsName, + serveEnabled: input.serveEnabled === true, + ...(input.servePort === undefined ? {} : { servePort: input.servePort }), + ...(input.probe === undefined ? {} : { probe: input.probe }), }); return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints; diff --git a/apps/server/package.json b/apps/server/package.json index 13a8124cb2..c562e0401e 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -40,6 +40,7 @@ "@effect/vitest": "catalog:", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", + "@t3tools/tailscale": "workspace:*", "@t3tools/web": "workspace:*", "@types/bun": "catalog:", "@types/node": "catalog:", diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts index 5adece7302..2e13d33aab 100644 --- a/apps/server/src/cli-config.test.ts +++ b/apps/server/src/cli-config.test.ts @@ -46,6 +46,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.none(), ).pipe( @@ -87,6 +89,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); }), ); @@ -108,6 +112,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.some(true), logWebSocketEvents: Option.some(true), + tailscaleServeEnabled: Option.some(true), + tailscaleServePort: Option.some(8443), }, Option.some("Debug"), ).pipe( @@ -149,6 +155,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: true, logWebSocketEvents: true, + tailscaleServeEnabled: true, + tailscaleServePort: 8443, }); }), ); @@ -161,6 +169,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { noBrowser: true, autoBootstrapProjectFromCwd: true, logWebSocketEvents: true, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); @@ -176,6 +186,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.some(false), logWebSocketEvents: Option.some(false), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.none(), ).pipe( @@ -212,6 +224,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); }), ); @@ -229,6 +243,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { noBrowser: true, autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, + tailscaleServeEnabled: false, + tailscaleServePort: 443, otlpTracesUrl: "http://localhost:4318/v1/traces", otlpMetricsUrl: "http://localhost:4318/v1/metrics", }); @@ -246,6 +262,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.none(), ).pipe( @@ -281,6 +299,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); assert.equal(join(baseDir, "dev"), resolved.stateDir); }), @@ -305,6 +325,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.none(), ).pipe( @@ -346,6 +368,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { noBrowser: false, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); @@ -361,6 +385,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.some("Debug"), ).pipe( @@ -399,6 +425,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: true, logWebSocketEvents: true, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); }), ); @@ -432,6 +460,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.none(), ).pipe( @@ -463,6 +493,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); }), ); @@ -485,6 +517,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, Option.none(), { @@ -522,6 +556,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }); }), ); diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts index 7ebde01067..3ef8c44195 100644 --- a/apps/server/src/cli.test.ts +++ b/apps/server/src/cli.test.ts @@ -76,6 +76,8 @@ const makeCliTestServerConfig = (baseDir: string) => desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, } satisfies ServerConfigShape; }); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index 4fc23a1ded..bcf8bee861 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -78,6 +78,8 @@ const BootstrapEnvelopeSchema = Schema.Struct({ desktopBootstrapToken: Schema.optional(Schema.String), autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), logWebSocketEvents: Schema.optional(Schema.Boolean), + tailscaleServeEnabled: Schema.optional(Schema.Boolean), + tailscaleServePort: Schema.optional(PortSchema), otlpTracesUrl: Schema.optional(Schema.String), otlpMetricsUrl: Schema.optional(Schema.String), }); @@ -126,6 +128,17 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe( Flag.withAlias("log-ws-events"), Flag.optional, ); +const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe( + Flag.withDescription( + "Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.", + ), + Flag.optional, +); +const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe( + Flag.withSchema(PortSchema), + Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."), + Flag.optional, +); const EnvServerConfig = Config.all({ logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")), @@ -174,6 +187,14 @@ const EnvServerConfig = Config.all({ Config.option, Config.map(Option.getOrUndefined), ), + tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), }); interface CliServerFlags { @@ -187,6 +208,8 @@ interface CliServerFlags { readonly bootstrapFd: Option.Option; readonly autoBootstrapProjectFromCwd: Option.Option; readonly logWebSocketEvents: Option.Option; + readonly tailscaleServeEnabled: Option.Option; + readonly tailscaleServePort: Option.Option; } interface CliAuthLocationFlags { @@ -233,6 +256,8 @@ export const resolveServerConfig = ( bootstrapFd: flags.bootstrapFd ?? Option.none(), autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(), logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(), + tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(), + tailscaleServePort: flags.tailscaleServePort ?? Option.none(), } satisfies CliServerFlags; const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd; const bootstrapEnvelope = @@ -323,6 +348,22 @@ export const resolveServerConfig = ( ), () => Boolean(devUrl), ); + const tailscaleServeEnabled = Option.getOrElse( + resolveOptionPrecedence( + normalizedFlags.tailscaleServeEnabled, + Option.fromUndefinedOr(env.tailscaleServeEnabled), + Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled), + ), + () => false, + ); + const tailscaleServePort = Option.getOrElse( + resolveOptionPrecedence( + normalizedFlags.tailscaleServePort, + Option.fromUndefinedOr(env.tailscaleServePort), + Option.fromUndefinedOr(bootstrap?.tailscaleServePort), + ), + () => 443, + ); const staticDir = devUrl ? undefined : yield* resolveStaticDir(); const host = Option.getOrElse( resolveOptionPrecedence( @@ -365,6 +406,8 @@ export const resolveServerConfig = ( desktopBootstrapToken, autoBootstrapProjectFromCwd, logWebSocketEvents, + tailscaleServeEnabled, + tailscaleServePort, }; return config; @@ -386,6 +429,8 @@ const resolveCliAuthConfig = ( bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), + tailscaleServeEnabled: Option.none(), + tailscaleServePort: Option.none(), }, cliLogLevel, ); @@ -766,6 +811,8 @@ const sharedServerCommandFlags = { bootstrapFd: bootstrapFdFlag, autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, logWebSocketEvents: logWebSocketEventsFlag, + tailscaleServeEnabled: tailscaleServeFlag, + tailscaleServePort: tailscaleServePortFlag, } as const; const authLocationFlags = sharedServerLocationFlags; diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 7840c76115..4d8e1cb7e7 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -65,6 +65,8 @@ export interface ServerConfigShape extends ServerDerivedPaths { readonly desktopBootstrapToken: string | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; + readonly tailscaleServeEnabled: boolean; + readonly tailscaleServePort: number; } export const deriveServerPaths = Effect.fn(function* ( @@ -158,6 +160,8 @@ export class ServerConfig extends Context.Service clearPersistedServerRuntimeState(config.serverRuntimeStatePath), ), ); + const tailscaleServeLayer = config.tailscaleServeEnabled + ? Layer.effectDiscard( + ensureTailscaleServe({ + localPort: config.port, + servePort: config.tailscaleServePort, + localHost: "127.0.0.1", + }).pipe( + Effect.tap(() => + Effect.logInfo("Tailscale Serve configured", { + localPort: config.port, + servePort: config.tailscaleServePort, + }), + ), + Effect.catch((cause) => + Effect.logWarning("Failed to configure Tailscale Serve", { + cause, + localPort: config.port, + servePort: config.tailscaleServePort, + }), + ), + ), + ) + : Layer.empty; const serverApplicationLayer = Layer.mergeAll( HttpRouter.serve(makeRoutesLayer, { @@ -313,6 +337,7 @@ export const makeServerLayer = Layer.unwrap( }), httpListeningLayer, runtimeStateLayer, + tailscaleServeLayer, ); return serverApplicationLayer.pipe( diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 95e504207d..41ab20310b 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -1,5 +1,17 @@ -import { ChevronDownIcon, PlusIcon, QrCodeIcon, RefreshCwIcon } from "lucide-react"; -import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react"; +import { + ChevronDownIcon, + PlusIcon, + QrCodeIcon, + RefreshCwIcon, +} from "lucide-react"; +import { + type ReactNode, + memo, + useCallback, + useEffect, + useMemo, + useState, +} from "react"; import { type AuthClientSession, type AuthPairingLink, @@ -13,8 +25,14 @@ import { DateTime } from "effect"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { cn } from "../../lib/utils"; -import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat"; -import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls"; +import { + formatElapsedDurationLabel, + formatExpiresInLabel, +} from "../../timestampFormat"; +import { + resolveDesktopPairingUrl, + resolveHostedPairingUrl, +} from "./pairingUrls"; import { SettingsPageContainer, SettingsRow, @@ -24,6 +42,7 @@ import { import { Input } from "../ui/input"; import { Dialog, + DialogClose, DialogFooter, DialogDescription, DialogHeader, @@ -77,6 +96,8 @@ import { } from "~/environments/runtime"; import { useUiStateStore } from "~/uiStateStore"; +const DEFAULT_TAILSCALE_SERVE_PORT = 443; + const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short", @@ -111,7 +132,9 @@ function ConnectionStatusDot({ )} /> ) : null} - + ); @@ -137,7 +160,10 @@ function ConnectionStatusDot({ return ( - + {tooltipText} @@ -153,7 +179,9 @@ function getSavedBackendStatusTooltip( if (connectionState === "connected") { const connectedAt = runtime?.connectedAt ?? record.lastConnectedAt; - return connectedAt ? `Connected for ${formatElapsedDurationLabel(connectedAt, nowMs)}` : null; + return connectedAt + ? `Connected for ${formatElapsedDurationLabel(connectedAt, nowMs)}` + : null; } if (connectionState === "connecting") { @@ -169,8 +197,12 @@ function getSavedBackendStatusTooltip( : "Not connected yet."; } -function formatDesktopSshTarget(target: NonNullable): string { - const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname; +function formatDesktopSshTarget( + target: NonNullable, +): string { + const authority = target.username + ? `${target.username}@${target.hostname}` + : target.hostname; return target.port ? `${authority}:${target.port}` : authority; } @@ -220,7 +252,10 @@ function parseManualDesktopSshTarget(input: { throw new Error("SSH host or alias is required."); } - if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) { + if ( + port !== null && + (!Number.isInteger(port) || port <= 0 || port > 65_535) + ) { throw new Error("SSH port must be between 1 and 65535."); } @@ -233,19 +268,26 @@ function parseManualDesktopSshTarget(input: { } /** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */ -const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5"; -const ENDPOINT_ROW_CLASSNAME = "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5"; +const ITEM_ROW_CLASSNAME = + "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5"; +const ENDPOINT_ROW_CLASSNAME = + "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5"; const ITEM_ROW_INNER_CLASSNAME = "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"; -function sortDesktopPairingLinks(links: ReadonlyArray) { +function sortDesktopPairingLinks( + links: ReadonlyArray, +) { return [...links].toSorted( - (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(), + (left, right) => + new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(), ); } -function sortDesktopClientSessions(sessions: ReadonlyArray) { +function sortDesktopClientSessions( + sessions: ReadonlyArray, +) { return [...sessions].toSorted((left, right) => { if (left.current !== right.current) { return left.current ? -1 : 1; @@ -253,11 +295,15 @@ function sortDesktopClientSessions(sessions: ReadonlyArray, next: ServerPairingLinkRecord, ) { - const existingIndex = current.findIndex((pairingLink) => pairingLink.id === next.id); + const existingIndex = current.findIndex( + (pairingLink) => pairingLink.id === next.id, + ); if (existingIndex === -1) { return sortDesktopPairingLinks([...current, next]); } @@ -290,7 +340,10 @@ function upsertDesktopPairingLink( return sortDesktopPairingLinks(updated); } -function removeDesktopPairingLink(current: ReadonlyArray, id: string) { +function removeDesktopPairingLink( + current: ReadonlyArray, + id: string, +) { return current.filter((pairingLink) => pairingLink.id !== id); } @@ -313,30 +366,43 @@ function removeDesktopClientSession( current: ReadonlyArray, sessionId: ServerClientSessionRecord["sessionId"], ) { - return current.filter((clientSession) => clientSession.sessionId !== sessionId); + return current.filter( + (clientSession) => clientSession.sessionId !== sessionId, + ); } function selectPairingEndpoint( endpoints: ReadonlyArray, defaultEndpointKey?: string | null, ): AdvertisedEndpoint | null { - const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable"); + const availableEndpoints = endpoints.filter( + (endpoint) => endpoint.status !== "unavailable", + ); if (defaultEndpointKey) { const selectedEndpoint = availableEndpoints.find( - (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey, + (endpoint) => + endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey, ); if (selectedEndpoint) { return selectedEndpoint; } } return ( - availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ?? availableEndpoints.find((endpoint) => endpoint.isDefault) ?? - availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ?? + availableEndpoints.find( + (endpoint) => endpoint.reachability !== "loopback", + ) ?? + availableEndpoints.find( + (endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible", + ) ?? null ); } +function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean { + return endpoint.id.startsWith("tailscale-magicdns:"); +} + function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string { if (endpoint.id.startsWith("desktop-loopback:")) { return "desktop-core:loopback:http"; @@ -347,7 +413,7 @@ function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string { if (endpoint.id.startsWith("tailscale-ip:")) { return "tailscale:ip:http"; } - if (endpoint.id.startsWith("tailscale-magicdns:")) { + if (isTailscaleHttpsEndpoint(endpoint)) { return "tailscale:magicdns:https"; } @@ -379,6 +445,15 @@ function resolveCurrentOriginPairingUrl(credential: string): string { return setPairingTokenOnUrl(url, credential).toString(); } +function isHostedAppPairingUrl(value: string): boolean { + try { + const url = new URL(value); + return url.pathname === "/pair" && url.searchParams.has("host"); + } catch { + return false; + } +} + type PairingLinkListRowProps = { pairingLink: ServerPairingLinkRecord; endpointUrl: string | null | undefined; @@ -416,27 +491,44 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ ); const endpointPairingUrl = useMemo(() => { const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey); - return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null; + return endpoint + ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) + : null; }, [defaultEndpointKey, endpoints, pairingLink.credential]); const endpointCopyOptions = useMemo( () => endpoints .filter((endpoint) => endpoint.status !== "unavailable") - .map((endpoint) => ({ - key: endpointDefaultPreferenceKey(endpoint), - label: endpoint.label, - url: resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential), - })), + .map((endpoint) => { + const url = resolveAdvertisedEndpointPairingUrl( + endpoint, + pairingLink.credential, + ); + return { + key: endpointDefaultPreferenceKey(endpoint), + label: endpoint.label, + url, + detail: isHostedAppPairingUrl(url) + ? "Hosted app link" + : "Backend pairing URL", + }; + }), [endpoints, pairingLink.credential], ); const shareablePairingUrl = endpointPairingUrl ?? (endpointUrl != null && endpointUrl !== "" - ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)) + ? (hostedPairingUrl ?? + resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)) : isLoopbackHostname(window.location.hostname) ? null : currentOriginPairingUrl); const revealValue = shareablePairingUrl ?? pairingLink.credential; + const isShareableHostedAppPairingUrl = + shareablePairingUrl !== null && isHostedAppPairingUrl(shareablePairingUrl); + const copyLinkLabel = isShareableHostedAppPairingUrl + ? "Copy hosted app link" + : "Copy pairing URL"; const canCopyToClipboard = typeof window !== "undefined" && window.isSecureContext && @@ -463,7 +555,9 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ ? "Could not copy pairing URL" : "Could not copy pairing code" : "Clipboard copy unavailable", - description: canCopyToClipboard ? error.message : "Showing the full value instead.", + description: canCopyToClipboard + ? error.message + : "Showing the full value instead.", }), ); }, @@ -503,7 +597,9 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ tooltipText={`Link created at ${formatAccessTimestamp(pairingLink.createdAt)}`} dotClassName="bg-amber-400" /> -

{primaryLabel}

+

+ {primaryLabel} +

{shareablePairingUrl ? ( <> @@ -521,7 +617,12 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ > - +

- {[roleLabel, formatExpiresInLabel(pairingLink.expiresAt, nowMs)].join(" · ")} + {[ + roleLabel, + formatExpiresInLabel(pairingLink.expiresAt, nowMs), + ].join(" · ")}

{shareablePairingUrl === null ? (

- Copy the token and pair from another client using this backend's reachable host. + Copy the token and pair from another client using this + backend's reachable host.

) : null}
- + {canCopyToClipboard ? ( <> @@ -573,12 +685,16 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ {endpointCopyOptions.map((option) => ( copyPairingValue(option.url, "link")} + onClick={() => + copyPairingValue(option.url, "link") + } > - {option.label} + + {option.label} + - Pairing URL + {option.detail} @@ -587,8 +703,12 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ ) : ( - ) ) : null} @@ -600,10 +720,18 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ )} - {shareablePairingUrl ? "Pairing link" : "Pairing code"} + + {shareablePairingUrl + ? isShareableHostedAppPairingUrl + ? "Hosted app pairing link" + : "Pairing link" + : "Pairing code"} + {shareablePairingUrl - ? "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect." + ? isShareableHostedAppPairingUrl + ? "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect." + : "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect." : "Clipboard copy is unavailable here. Manually copy this code into another client."} @@ -629,7 +757,10 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ ) : null} - {canCopyToClipboard ? ( @@ -678,7 +809,8 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({ const roleLabel = clientSession.role === "owner" ? "Owner" : "Client"; const deviceInfoBits = [ clientSession.client.deviceType !== "unknown" - ? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1) + ? clientSession.client.deviceType[0]?.toUpperCase() + + clientSession.client.deviceType.slice(1) : null, clientSession.client.os ?? null, clientSession.client.browser ?? null, @@ -686,7 +818,9 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({ ].filter((value): value is string => value !== null); const primaryLabel = clientSession.client.label ?? - ([clientSession.client.os, clientSession.client.browser].filter(Boolean).join(" · ") || + ([clientSession.client.os, clientSession.client.browser] + .filter(Boolean) + .join(" · ") || clientSession.subject); return ( @@ -699,7 +833,9 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({ dotClassName={isLive ? "bg-success" : "bg-muted-foreground/30"} pingClassName={isLive ? "bg-success/60 duration-2000" : null} /> -

{primaryLabel}

+

+ {primaryLabel} +

{clientSession.current ? ( This device @@ -718,7 +854,9 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({ disabled={revokingClientSessionId === clientSession.sessionId} onClick={() => void onRevokeSession(clientSession.sessionId)} > - {revokingClientSessionId === clientSession.sessionId ? "Revoking…" : "Revoke"} + {revokingClientSessionId === clientSession.sessionId + ? "Revoking…" + : "Revoke"} ) : null}
@@ -733,103 +871,112 @@ type AuthorizedClientsHeaderActionProps = { onRevokeOtherClients: () => void; }; -const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({ - clientSessions, - isRevokingOtherClients, - onRevokeOtherClients, -}: AuthorizedClientsHeaderActionProps) { - const [dialogOpen, setDialogOpen] = useState(false); - const [pairingLabel, setPairingLabel] = useState(""); - const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false); +const AuthorizedClientsHeaderAction = memo( + function AuthorizedClientsHeaderAction({ + clientSessions, + isRevokingOtherClients, + onRevokeOtherClients, + }: AuthorizedClientsHeaderActionProps) { + const [dialogOpen, setDialogOpen] = useState(false); + const [pairingLabel, setPairingLabel] = useState(""); + const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false); - const handleCreatePairingLink = useCallback(async () => { - setIsCreatingPairingLink(true); - try { - await createServerPairingCredential(pairingLabel); - setPairingLabel(""); - setDialogOpen(false); - } catch (error) { - const message = error instanceof Error ? error.message : "Failed to create pairing URL."; - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not create pairing URL", - description: message, - }), - ); - } finally { - setIsCreatingPairingLink(false); - } - }, [pairingLabel]); + const handleCreatePairingLink = useCallback(async () => { + setIsCreatingPairingLink(true); + try { + await createServerPairingCredential(pairingLabel); + setPairingLabel(""); + setDialogOpen(false); + } catch (error) { + const message = + error instanceof Error + ? error.message + : "Failed to create pairing URL."; + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not create pairing URL", + description: message, + }), + ); + } finally { + setIsCreatingPairingLink(false); + } + }, [pairingLabel]); - return ( -
- - { - setDialogOpen(open); - if (!open) { - setPairingLabel(""); + return ( +
+ - } - /> - - - Create pairing link - - Generate a one-time link that another device can use to pair with this backend as an - authorized client. - - - -
- ); -}); + onClick={() => setDialogOpen(false)} + > + Cancel + + + + +
+
+ ); + }, +); type PairingClientsListProps = { endpointUrl: string | null | undefined; @@ -841,7 +988,9 @@ type PairingClientsListProps = { revokingPairingLinkId: string | null; revokingClientSessionId: string | null; onRevokePairingLink: (id: string) => void; - onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void; + onRevokeClientSession: ( + sessionId: ServerClientSessionRecord["sessionId"], + ) => void; }; const PairingClientsList = memo(function PairingClientsList({ @@ -879,9 +1028,13 @@ const PairingClientsList = memo(function PairingClientsList({ /> ))} - {pairingLinks.length === 0 && clientSessions.length === 0 && !isLoading ? ( + {pairingLinks.length === 0 && + clientSessions.length === 0 && + !isLoading ? (
-

No pairing links or client sessions.

+

+ No pairing links or client sessions. +

) : null} @@ -892,26 +1045,45 @@ type AdvertisedEndpointListRowProps = { endpoint: AdvertisedEndpoint; isDefault: boolean; onSetDefault: (endpoint: AdvertisedEndpoint) => void; + onSetupTailscaleServe: (endpoint: AdvertisedEndpoint) => void; + onDisableTailscaleServe: (endpoint: AdvertisedEndpoint) => void; + isUpdatingTailscaleServe: boolean; }; const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({ endpoint, isDefault, onSetDefault, + onSetupTailscaleServe, + onDisableTailscaleServe, + isUpdatingTailscaleServe, }: AdvertisedEndpointListRowProps) { + const isAvailable = endpoint.status === "available"; + const needsTailscaleSetup = + isTailscaleHttpsEndpoint(endpoint) && endpoint.status !== "available"; + const canDisableTailscaleServe = + isTailscaleHttpsEndpoint(endpoint) && endpoint.status === "available"; + const shouldShowEndpointUrl = !needsTailscaleSetup; return ( -
+

{endpoint.label}

-

- {endpoint.httpBaseUrl} -

+ {shouldShowEndpointUrl ? ( +

+ {endpoint.httpBaseUrl} +

+ ) : null} + {!isAvailable ? ( + + Setup required + + ) : null}
{isDefault ? ( @@ -919,8 +1091,32 @@ const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({ Default ) : null} - {!isDefault ? ( - + ) : null} + {canDisableTailscaleServe ? ( + + ) : null} + {!needsTailscaleSetup && !isDefault ? ( + ) : null} @@ -947,19 +1143,34 @@ function NetworkAccessDescription({ return fallback; } + const summary = ( + <> + {endpoint.httpBaseUrl} + {hiddenEndpointCount > 0 ? ( + + {expanded ? "Hide" : `+${hiddenEndpointCount}`} + + ) : null} + + ); + return ( - - Reachable at {endpoint.httpBaseUrl} + + Reachable at {hiddenEndpointCount > 0 ? ( - ) : null} + ) : ( + + {summary} + + )} ); } @@ -980,8 +1191,12 @@ function SavedBackendListRow({ onRemove, }: SavedBackendListRowProps) { const nowMs = useRelativeTimeTick(1_000); - const record = useSavedEnvironmentRegistryStore((state) => state.byId[environmentId] ?? null); - const runtime = useSavedEnvironmentRuntimeStore((state) => state.byId[environmentId] ?? null); + const record = useSavedEnvironmentRegistryStore( + (state) => state.byId[environmentId] ?? null, + ); + const runtime = useSavedEnvironmentRuntimeStore( + (state) => state.byId[environmentId] ?? null, + ); if (!record) { return null; @@ -996,11 +1211,17 @@ function SavedBackendListRow({ : connectionState === "error" ? "bg-destructive" : "bg-muted-foreground/40"; - const roleLabel = runtime?.role ? (runtime.role === "owner" ? "Owner" : "Client") : null; + const roleLabel = runtime?.role + ? runtime.role === "owner" + ? "Owner" + : "Client" + : null; const descriptorLabel = runtime?.descriptor?.label ?? null; const statusTooltip = getSavedBackendStatusTooltip(runtime, record, nowMs); const metadataBits = [ - record.desktopSsh ? `SSH ${formatDesktopSshTarget(record.desktopSsh)}` : null, + record.desktopSsh + ? `SSH ${formatDesktopSshTarget(record.desktopSsh)}` + : null, roleLabel, record.lastConnectedAt ? `Last connected ${formatAccessTimestamp(record.lastConnectedAt)}` @@ -1016,16 +1237,24 @@ function SavedBackendListRow({ tooltipText={statusTooltip} dotClassName={stateDotClassName} pingClassName={ - connectionState === "connecting" ? "bg-warning/60 duration-2000" : null + connectionState === "connecting" + ? "bg-warning/60 duration-2000" + : null } /> -

{record.label}

+

+ {record.label} +

{metadataBits.length > 0 ? ( -

{metadataBits.join(" · ")}

+

+ {metadataBits.join(" · ")} +

) : null} {descriptorLabel && descriptorLabel !== record.label ? ( -

Server label: {descriptorLabel}

+

+ Server label: {descriptorLabel} +

) : null}
@@ -1035,7 +1264,9 @@ function SavedBackendListRow({ disabled={reconnectingEnvironmentId === environmentId} onClick={() => void onReconnect(environmentId)} > - {reconnectingEnvironmentId === environmentId ? "Reconnecting…" : "Reconnect"} + {reconnectingEnvironmentId === environmentId + ? "Reconnecting…" + : "Reconnect"} + + + + { + if (isUpdatingTailscaleServe) return; + if (!open) setPendingTailscaleServeEndpoint(null); + }} + > + + + Set up Tailscale HTTPS? + + T3 Code will restart the local backend with Tailscale + Serve enabled and ask Tailscale to proxy HTTPS traffic + to this backend. + + + + + {!isTailscaleServePortValid ? ( +

+ Enter a port from 1 to 65535. +

+ ) : null} +
+

+ HTTPS endpoint +

+

+ {pendingTailscaleServeBaseUrl ?? + "Pending MagicDNS endpoint"} +

+
+
+ + + } + > + Cancel + + + +
+
) : ( - Network exposure changes restart the backend and must be controlled where the - server process is launched. + Network exposure changes restart the backend and must be + controlled where the server process is launched. } @@ -1824,7 +2489,7 @@ export function ConnectionsSettings() { )} - {isLocalBackendNetworkAccessible ? ( + {isLocalBackendRemotelyReachable ? ( {desktopAccessManagementError ? (
-

{desktopAccessManagementError}

+

+ {desktopAccessManagementError} +

) : null} Add Environment - Pair another environment to this client. + + Pair another environment to this client. +
{discoveredSshHostsError ? ( -

{discoveredSshHostsError}

+

+ {discoveredSshHostsError} +

) : null}
@@ -2049,9 +2735,15 @@ export function ConnectionsSettings() { void handleConnectSshHost(nextTarget)} + onConnect={(nextTarget) => + void handleConnectSshHost(nextTarget) + } /> ))} {hasLoadedDiscoveredSshHosts && @@ -2059,7 +2751,8 @@ export function ConnectionsSettings() { discoveredSshHosts.length === 0 ? (

- No SSH hosts were discovered from ~/.ssh/config or{" "} + No SSH hosts were discovered from{" "} + ~/.ssh/config or{" "} known_hosts.

@@ -2067,14 +2760,17 @@ export function ConnectionsSettings() {
{savedBackendError ? ( -

{savedBackendError}

+

+ {savedBackendError} +

) : null}

Enter a host manually

- Use an alias or enter host, username, and port directly. + Use an alias or enter host, username, and port + directly.

- Uses your existing SSH keys, agent, and config. Password and - keyboard-interactive prompts open through your system SSH dialog when - needed. + Uses your existing SSH keys, agent, and config. + Password and keyboard-interactive prompts open + through your system SSH dialog when needed.
)} {savedBackendMode !== "ssh" && savedBackendError ? ( -

{savedBackendError}

+

+ {savedBackendError} +

) : null} {savedBackendMode !== "ssh" ? (
) : null} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index cb3cb0ee87..3a89e17d6c 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -348,6 +348,8 @@ const createDesktopBridgeStub = (overrides?: { mode: "local-only", endpointUrl: null, advertisedHost: null, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }, ), setServerExposureMode: @@ -356,7 +358,16 @@ const createDesktopBridgeStub = (overrides?: { mode, endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null, advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null, + tailscaleServeEnabled: false, + tailscaleServePort: 443, })), + setTailscaleServeEnabled: vi.fn().mockImplementation(async (input) => ({ + mode: overrides?.serverExposureState?.mode ?? "network-accessible", + endpointUrl: overrides?.serverExposureState?.endpointUrl ?? "http://192.168.1.44:3773", + advertisedHost: overrides?.serverExposureState?.advertisedHost ?? "192.168.1.44", + tailscaleServeEnabled: input.enabled, + tailscaleServePort: input.port ?? 443, + })), getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []), pickFolder: vi.fn().mockResolvedValue(null), confirm: vi.fn().mockResolvedValue(false), @@ -488,6 +499,8 @@ describe("GeneralSettingsPanel observability", () => { mode: "local-only", endpointUrl: null, advertisedHost: null, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }, advertisedEndpoints: [ { @@ -558,6 +571,8 @@ describe("GeneralSettingsPanel observability", () => { mode: "network-accessible", endpointUrl: "http://192.168.86.39:3773", advertisedHost: "192.168.86.39", + tailscaleServeEnabled: false, + tailscaleServePort: 443, }, advertisedEndpoints: [ { @@ -680,6 +695,8 @@ describe("GeneralSettingsPanel observability", () => { mode: "network-accessible", endpointUrl: "http://192.168.1.44:3773", advertisedHost: "192.168.1.44", + tailscaleServeEnabled: false, + tailscaleServePort: 443, }, }); let pairingLinks: Array = []; @@ -796,6 +813,8 @@ describe("GeneralSettingsPanel observability", () => { mode: "network-accessible", endpointUrl: "http://192.168.1.44:3773", advertisedHost: "192.168.1.44", + tailscaleServeEnabled: false, + tailscaleServePort: 443, }, }); let clientSessions: Array = [ diff --git a/apps/web/src/components/ui/alert-dialog.tsx b/apps/web/src/components/ui/alert-dialog.tsx index 5c65f261f5..84bcff9631 100644 --- a/apps/web/src/components/ui/alert-dialog.tsx +++ b/apps/web/src/components/ui/alert-dialog.tsx @@ -18,7 +18,7 @@ function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backd return ( { }); }); + it("derives backend urls and token from a hosted app pairing link", () => { + expect( + resolveRemotePairingTarget({ + pairingUrl: + "https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.tailnet.ts.net%3A44342%2F#token=pairing-token", + }), + ).toEqual({ + credential: "pairing-token", + httpBaseUrl: "https://desktop.tailnet.ts.net:44342/", + wsBaseUrl: "wss://desktop.tailnet.ts.net:44342/", + }); + }); + it("derives backend urls from a host and pairing code", () => { expect( resolveRemotePairingTarget({ diff --git a/apps/web/src/environments/remote/target.ts b/apps/web/src/environments/remote/target.ts index 311450d5fa..ad925f014c 100644 --- a/apps/web/src/environments/remote/target.ts +++ b/apps/web/src/environments/remote/target.ts @@ -1,4 +1,5 @@ import { getPairingTokenFromUrl } from "../../pairingUrl"; +import { readHostedPairingRequest } from "../../hostedPairing"; export interface ResolvedRemotePairingTarget { readonly credential: string; @@ -57,6 +58,16 @@ export function resolveRemotePairingTarget(input: { const pairingUrl = input.pairingUrl?.trim() ?? ""; if (pairingUrl.length > 0) { const url = new URL(pairingUrl, window.location.origin); + const hostedPairingRequest = readHostedPairingRequest(url); + if (hostedPairingRequest) { + const hostedBackendUrl = normalizeRemoteBaseUrl(hostedPairingRequest.host); + return { + credential: hostedPairingRequest.token, + httpBaseUrl: toHttpBaseUrl(hostedBackendUrl), + wsBaseUrl: toWsBaseUrl(hostedBackendUrl), + }; + } + const credential = getPairingTokenFromUrl(url) ?? ""; if (!credential) { throw new Error("Pairing URL is missing its token."); diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index a02241315f..772e264f3a 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -191,11 +191,22 @@ function makeDesktopBridge(overrides: Partial = {}): DesktopBridg mode: "local-only", endpointUrl: null, advertisedHost: null, + tailscaleServeEnabled: false, + tailscaleServePort: 443, }), setServerExposureMode: async () => ({ mode: "local-only", endpointUrl: null, advertisedHost: null, + tailscaleServeEnabled: false, + tailscaleServePort: 443, + }), + setTailscaleServeEnabled: async (input) => ({ + mode: "local-only", + endpointUrl: null, + advertisedHost: null, + tailscaleServeEnabled: input.enabled, + tailscaleServePort: input.port ?? 443, }), getAdvertisedEndpoints: async () => [], pickFolder: async () => null, diff --git a/apps/web/vercel.json b/apps/web/vercel.json index 1323cdac34..ecfa7a47fc 100644 --- a/apps/web/vercel.json +++ b/apps/web/vercel.json @@ -1,4 +1,6 @@ { + "buildCommand": "turbo build --filter @t3tools/web && bun ../../scripts/apply-web-brand-assets.ts production", + "installCommand": "bun add -g turbo && bun install --filter '@t3tools/contracts' --filter '@t3tools/client-runtime' --filter '@t3tools/scripts' --filter '@t3tools/web'", "rewrites": [ { "source": "/(.*)", diff --git a/bun.lock b/bun.lock index f405bba68e..9f6acee0aa 100644 --- a/bun.lock +++ b/bun.lock @@ -16,6 +16,7 @@ "name": "@t3tools/desktop", "version": "0.0.21", "dependencies": { + "@effect/platform-node": "catalog:", "effect": "catalog:", "electron": "40.6.0", "electron-updater": "^6.6.2", @@ -24,6 +25,7 @@ "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", + "@t3tools/tailscale": "workspace:*", "@types/node": "catalog:", "effect-acp": "workspace:*", "tsdown": "catalog:", @@ -64,6 +66,7 @@ "@effect/vitest": "catalog:", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", + "@t3tools/tailscale": "workspace:*", "@t3tools/web": "workspace:*", "@types/bun": "catalog:", "@types/node": "catalog:", @@ -198,6 +201,21 @@ "vitest": "catalog:", }, }, + "packages/tailscale": { + "name": "@t3tools/tailscale", + "version": "0.0.0-alpha.1", + "dependencies": { + "@effect/platform-node": "catalog:", + "effect": "catalog:", + }, + "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:", + }, + }, "scripts": { "name": "@t3tools/scripts", "dependencies": { @@ -740,6 +758,8 @@ "@t3tools/shared": ["@t3tools/shared@workspace:packages/shared"], + "@t3tools/tailscale": ["@t3tools/tailscale@workspace:packages/tailscale"], + "@t3tools/web": ["@t3tools/web@workspace:apps/web"], "@tailwindcss/node": ["@tailwindcss/node@4.2.1", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.19.0", "jiti": "^2.6.1", "lightningcss": "1.31.1", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.2.1" } }, "sha512-jlx6sLk4EOwO6hHe1oCGm1Q4AN/s0rSrTTPBGPM0/RQ6Uylwq17FuU8IeJJKEjtc6K6O07zsvP+gDO6MMWo7pg=="], diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index f6cdbacfa7..f256789f72 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -176,6 +176,8 @@ export interface DesktopServerExposureState { mode: DesktopServerExposureMode; endpointUrl: string | null; advertisedHost: string | null; + tailscaleServeEnabled: boolean; + tailscaleServePort: number; } export interface PickFolderOptions { @@ -213,6 +215,10 @@ export interface DesktopBridge { resolveSshPasswordPrompt: (requestId: string, password: string | null) => Promise; getServerExposureState: () => Promise; setServerExposureMode: (mode: DesktopServerExposureMode) => Promise; + setTailscaleServeEnabled: (input: { + readonly enabled: boolean; + readonly port?: number; + }) => Promise; getAdvertisedEndpoints: () => Promise; pickFolder: (options?: PickFolderOptions) => Promise; confirm: (message: string) => Promise; diff --git a/packages/tailscale/package.json b/packages/tailscale/package.json new file mode 100644 index 0000000000..7088559c74 --- /dev/null +++ b/packages/tailscale/package.json @@ -0,0 +1,28 @@ +{ + "name": "@t3tools/tailscale", + "version": "0.0.0-alpha.1", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "import": "./src/index.ts" + } + }, + "scripts": { + "prepare": "effect-language-service patch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@effect/platform-node": "catalog:", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/tailscale/src/index.ts b/packages/tailscale/src/index.ts new file mode 100644 index 0000000000..b6cba8d7b4 --- /dev/null +++ b/packages/tailscale/src/index.ts @@ -0,0 +1 @@ +export * from "./tailscale.ts"; diff --git a/packages/tailscale/src/tailscale.test.ts b/packages/tailscale/src/tailscale.test.ts new file mode 100644 index 0000000000..7bcad80664 --- /dev/null +++ b/packages/tailscale/src/tailscale.test.ts @@ -0,0 +1,120 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Layer, Sink, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { + buildTailscaleHttpsBaseUrl, + ensureTailscaleServe, + isTailscaleIpv4Address, + parseTailscaleMagicDnsName, + parseTailscaleStatus, + readTailscaleStatus, +} from "./tailscale.ts"; + +const encoder = new TextEncoder(); +const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`; +const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`; + +function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) { + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(encoder.encode(result.stdout ?? "")), + stderr: Stream.make(encoder.encode(result.stderr ?? "")), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); +} + +function mockSpawnerLayer( + handler: ( + command: string, + args: ReadonlyArray, + ) => { stdout?: string; stderr?: string; code?: number }, +) { + return Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const childProcess = command as unknown as { + readonly command: string; + readonly args: ReadonlyArray; + }; + return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args))); + }), + ); +} + +describe("tailscale", () => { + it.effect("detects Tailnet IPv4 addresses", () => + Effect.sync(() => { + assert.equal(isTailscaleIpv4Address("100.64.0.1"), true); + assert.equal(isTailscaleIpv4Address("100.127.255.254"), true); + assert.equal(isTailscaleIpv4Address("100.128.0.1"), false); + assert.equal(isTailscaleIpv4Address("192.168.1.44"), false); + }), + ); + + it.effect("parses MagicDNS names from tailscale status", () => + Effect.gen(function* () { + const dnsName = yield* parseTailscaleMagicDnsName(tailscaleStatusJson); + assert.equal(dnsName, "desktop.tail.ts.net"); + assert.equal(yield* parseTailscaleMagicDnsName("{}"), null); + }), + ); + + it.effect("parses status facts", () => + Effect.gen(function* () { + const status = yield* parseTailscaleStatus(tailscaleStatusJson); + assert.deepEqual(status, { + magicDnsName: "desktop.tail.ts.net", + tailnetIpv4Addresses: ["100.100.100.100"], + }); + }), + ); + + it.effect("builds clean HTTPS base URLs", () => + Effect.sync(() => { + assert.equal( + buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net" }), + "https://desktop.tail.ts.net/", + ); + assert.equal( + buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net", servePort: 8443 }), + "https://desktop.tail.ts.net:8443/", + ); + }), + ); + + it.effect("reads tailscale status through the process spawner service", () => { + const layer = mockSpawnerLayer((command, args) => { + assert.equal(command, "tailscale"); + assert.deepEqual(args, ["status", "--json"]); + return { + stdout: tailscaleStatusWithSingleIpJson, + }; + }); + + return Effect.gen(function* () { + const status = yield* readTailscaleStatus.pipe(Effect.provide(layer)); + assert.deepEqual(status, { + magicDnsName: "desktop.tail.ts.net", + tailnetIpv4Addresses: ["100.90.1.2"], + }); + }); + }); + + it.effect("configures tailscale serve through the process spawner service", () => { + const layer = mockSpawnerLayer((command, args) => { + assert.equal(command, "tailscale"); + assert.deepEqual(args, ["serve", "--bg", "--https=8443", "http://127.0.0.1:13773"]); + return {}; + }); + + return ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(Effect.provide(layer)); + }); +}); diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts new file mode 100644 index 0000000000..46d1183667 --- /dev/null +++ b/packages/tailscale/src/tailscale.ts @@ -0,0 +1,291 @@ +import { Data, Effect, Option, Schema, Stream } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/unstable/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +export const DEFAULT_TAILSCALE_SERVE_PORT = 443; +export const TAILSCALE_STATUS_TIMEOUT_MS = 1_500; +export const TAILSCALE_SERVE_TIMEOUT_MS = 10_000; +export const TAILSCALE_PROBE_TIMEOUT_MS = 2_500; + +export class TailscaleCommandError extends Data.TaggedError("TailscaleCommandError")<{ + readonly command: readonly string[]; + readonly message: string; + readonly exitCode: number | null; + readonly stderr: string; +}> {} + +export class TailscaleStatusParseError extends Data.TaggedError("TailscaleStatusParseError")<{ + readonly cause: unknown; +}> {} + +export class TailscaleUnavailableError extends Data.TaggedError("TailscaleUnavailableError")<{ + readonly reason: string; +}> {} + +const TailscaleStatusSelf = Schema.Struct({ + DNSName: Schema.optional(Schema.Unknown), + TailscaleIPs: Schema.optional(Schema.Unknown), +}); + +const TailscaleStatusJson = Schema.Struct({ + Self: Schema.optional(TailscaleStatusSelf), +}); + +export type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type; +export type TailscaleStatusJson = typeof TailscaleStatusJson.Type; + +export interface TailscaleStatus { + readonly magicDnsName: string | null; + readonly tailnetIpv4Addresses: readonly string[]; +} + +const collectStdout = (stream: Stream.Stream): Effect.Effect => + stream.pipe( + Stream.decodeText(), + Stream.runFold( + () => "", + (acc, chunk) => acc + chunk, + ), + ); + +const collectStderr = collectStdout; + +const tailscaleCommandError = ( + args: readonly string[], + message: string, + exitCode: number | null, + stderr = "", +): TailscaleCommandError => + new TailscaleCommandError({ + command: ["tailscale", ...args], + message, + exitCode, + stderr, + }); + +const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson)); + +function normalizeMagicDnsName(status: TailscaleStatusJson): string | null { + const dnsName = status.Self?.DNSName; + if (typeof dnsName !== "string") { + return null; + } + + const normalized = dnsName.trim().replace(/\.$/u, ""); + return normalized.length > 0 ? normalized : null; +} + +export const parseTailscaleMagicDnsName = ( + rawStatusJson: string, +): Effect.Effect => + decodeTailscaleStatusJson(rawStatusJson).pipe( + Effect.mapError((cause) => new TailscaleStatusParseError({ cause })), + Effect.map(normalizeMagicDnsName), + ); + +export function isTailscaleIpv4Address(address: string): boolean { + const parts = address.split("."); + if (parts.length !== 4) { + return false; + } + const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10)); + if ( + first === undefined || + second === undefined || + third === undefined || + fourth === undefined || + [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255) + ) { + return false; + } + return first === 100 && second >= 64 && second <= 127; +} + +export const parseTailscaleStatus = ( + rawStatusJson: string, +): Effect.Effect => + decodeTailscaleStatusJson(rawStatusJson).pipe( + Effect.mapError((cause) => new TailscaleStatusParseError({ cause })), + Effect.map((parsed) => { + const rawIps = parsed.Self?.TailscaleIPs; + const tailnetIpv4Addresses = Array.isArray(rawIps) + ? rawIps + .filter((address): address is string => typeof address === "string") + .filter(isTailscaleIpv4Address) + : []; + + return { + magicDnsName: normalizeMagicDnsName(parsed), + tailnetIpv4Addresses, + }; + }), + ); + +export const readTailscaleStatus: Effect.Effect< + TailscaleStatus, + TailscaleCommandError | TailscaleStatusParseError, + ChildProcessSpawner.ChildProcessSpawner +> = Effect.gen(function* () { + const args = ["status", "--json"]; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner + .spawn( + ChildProcess.make("tailscale", args, { + shell: process.platform === "win32", + }), + ) + .pipe( + Effect.mapError((cause) => + tailscaleCommandError( + args, + cause instanceof Error ? cause.message : "Failed to spawn tailscale status.", + null, + ), + ), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectStdout(child.stdout), + collectStderr(child.stderr), + child.exitCode.pipe(Effect.map(Number)), + ], + { concurrency: "unbounded" }, + ).pipe( + Effect.mapError((cause) => + tailscaleCommandError( + args, + cause instanceof Error ? cause.message : "Failed to run tailscale status.", + null, + ), + ), + ); + if (exitCode !== 0) { + return yield* tailscaleCommandError( + args, + `Tailscale status exited with code ${exitCode}.`, + exitCode, + stderr, + ); + } + return yield* parseTailscaleStatus(stdout); +}).pipe( + Effect.scoped, + Effect.timeoutOption(TAILSCALE_STATUS_TIMEOUT_MS), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => + Effect.fail( + tailscaleCommandError(["status", "--json"], "Tailscale status timed out.", null), + ), + onSome: Effect.succeed, + }), + ), +); + +export function buildTailscaleHttpsBaseUrl(input: { + readonly magicDnsName: string; + readonly servePort?: number; +}): string { + const url = new URL(`https://${input.magicDnsName}`); + const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT; + if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) { + url.port = String(servePort); + } + url.pathname = "/"; + return url.toString(); +} + +export const ensureTailscaleServe = (input: { + readonly localPort: number; + readonly servePort?: number; + readonly localHost?: string; +}): Effect.Effect => { + const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT; + const localHost = input.localHost ?? "127.0.0.1"; + const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`]; + return Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner + .spawn( + ChildProcess.make("tailscale", args, { + shell: process.platform === "win32", + }), + ) + .pipe( + Effect.mapError((cause) => + tailscaleCommandError( + args, + cause instanceof Error ? cause.message : "Failed to spawn tailscale serve.", + null, + ), + ), + ); + const [stderr, exitCode] = yield* Effect.all( + [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))], + { concurrency: "unbounded" }, + ).pipe( + Effect.mapError((cause) => + tailscaleCommandError( + args, + cause instanceof Error ? cause.message : "Failed to run tailscale serve.", + null, + ), + ), + ); + if (exitCode !== 0) { + return yield* tailscaleCommandError( + args, + `Tailscale serve exited with code ${exitCode}.`, + exitCode, + stderr, + ); + } + }).pipe( + Effect.scoped, + Effect.timeoutOption(TAILSCALE_SERVE_TIMEOUT_MS), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => Effect.fail(tailscaleCommandError(args, "Tailscale serve timed out.", null)), + onSome: Effect.succeed, + }), + ), + ); +}; + +export const probeTailscaleHttpsEndpoint = (input: { + readonly baseUrl: string; + readonly timeoutMs?: number; +}): Effect.Effect => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const response = yield* Effect.gen(function* () { + const url = new URL("/.well-known/t3/environment", input.baseUrl); + const request = HttpClientRequest.get(url.toString()); + return yield* client.execute(request); + }).pipe(Effect.timeoutOption(input.timeoutMs ?? TAILSCALE_PROBE_TIMEOUT_MS)); + + return Option.match(response, { + onNone: () => false, + onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300, + }); + }).pipe(Effect.catch(() => Effect.succeed(false))); + +export const resolveTailscaleHttpsBaseUrl = ( + input: { + readonly servePort?: number; + } = {}, +): Effect.Effect< + string | null, + TailscaleCommandError | TailscaleStatusParseError, + ChildProcessSpawner.ChildProcessSpawner +> => + readTailscaleStatus.pipe( + Effect.map((status) => + status.magicDnsName + ? buildTailscaleHttpsBaseUrl({ + magicDnsName: status.magicDnsName, + ...(input.servePort === undefined ? {} : { servePort: input.servePort }), + }) + : null, + ), + ); diff --git a/packages/tailscale/tsconfig.json b/packages/tailscale/tsconfig.json new file mode 100644 index 0000000000..2f8e6d4df6 --- /dev/null +++ b/packages/tailscale/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "plugins": [ + { + "name": "@effect/language-service", + "diagnosticSeverity": { + "importFromBarrel": "error", + "anyUnknownInErrorContext": "warning", + "instanceOfSchema": "warning", + "deterministicKeys": "warning" + } + } + ] + }, + "include": ["src"] +} diff --git a/scripts/apply-web-brand-assets.ts b/scripts/apply-web-brand-assets.ts new file mode 100644 index 0000000000..1bbdd237c2 --- /dev/null +++ b/scripts/apply-web-brand-assets.ts @@ -0,0 +1,56 @@ +#!/usr/bin/env node + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, FileSystem, Option, Path } from "effect"; +import { Argument, Command } from "effect/unstable/cli"; +import { resolveWebIconOverrides, type WebAssetBrand } from "./lib/brand-assets.ts"; + +const WEB_ASSET_BRANDS = [ + "development", + "production", +] as const satisfies ReadonlyArray; + +export const applyWebBrandAssets = Effect.fn("applyWebBrandAssets")(function* ( + brand: WebAssetBrand, + targetDirectory: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const repoRoot = yield* path.fromFileUrl(new URL("..", import.meta.url)); + + yield* Effect.forEach( + resolveWebIconOverrides(brand, targetDirectory), + (override) => + fs.copyFile( + path.join(repoRoot, override.sourceRelativePath), + path.join(repoRoot, override.targetRelativePath), + ), + { concurrency: "unbounded" }, + ); +}); + +export const applyWebBrandAssetsCommand = Command.make( + "apply-web-brand-assets", + { + brand: Argument.choice("brand", WEB_ASSET_BRANDS).pipe( + Argument.withDescription("Asset brand to copy into the hosted web output directory."), + ), + targetDirectory: Argument.string("target-directory").pipe( + Argument.withDescription("Output directory that contains the hosted web build assets."), + Argument.optional, + ), + }, + ({ brand, targetDirectory }) => + applyWebBrandAssets( + brand, + Option.getOrElse(targetDirectory, () => "apps/web/dist"), + ), +).pipe(Command.withDescription("Copy web brand assets into a built hosted web app.")); + +if (import.meta.main) { + Command.run(applyWebBrandAssetsCommand, { version: "0.0.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain, + ); +} diff --git a/scripts/lib/brand-assets.test.ts b/scripts/lib/brand-assets.test.ts new file mode 100644 index 0000000000..8c85455185 --- /dev/null +++ b/scripts/lib/brand-assets.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; + +import { + BRAND_ASSET_PATHS, + DEVELOPMENT_ICON_OVERRIDES, + PUBLISH_ICON_OVERRIDES, + resolveWebIconOverrides, +} from "./brand-assets.ts"; + +describe("brand-assets", () => { + it("maps server publish web assets to production icons", () => { + expect(PUBLISH_ICON_OVERRIDES).toEqual([ + { + sourceRelativePath: BRAND_ASSET_PATHS.productionWebFaviconIco, + targetRelativePath: "dist/client/favicon.ico", + }, + { + sourceRelativePath: BRAND_ASSET_PATHS.productionWebFavicon16Png, + targetRelativePath: "dist/client/favicon-16x16.png", + }, + { + sourceRelativePath: BRAND_ASSET_PATHS.productionWebFavicon32Png, + targetRelativePath: "dist/client/favicon-32x32.png", + }, + { + sourceRelativePath: BRAND_ASSET_PATHS.productionWebAppleTouchIconPng, + targetRelativePath: "dist/client/apple-touch-icon.png", + }, + ]); + }); + + it("maps server build web assets to development icons", () => { + expect(DEVELOPMENT_ICON_OVERRIDES[0]).toEqual({ + sourceRelativePath: BRAND_ASSET_PATHS.developmentWebFaviconIco, + targetRelativePath: "dist/client/favicon.ico", + }); + }); + + it("can target hosted web dist directly", () => { + expect(resolveWebIconOverrides("production", "apps/web/dist")).toContainEqual({ + sourceRelativePath: BRAND_ASSET_PATHS.productionWebAppleTouchIconPng, + targetRelativePath: "apps/web/dist/apple-touch-icon.png", + }); + }); +}); diff --git a/scripts/lib/brand-assets.ts b/scripts/lib/brand-assets.ts index 6cc777e22b..56c44cbbd5 100644 --- a/scripts/lib/brand-assets.ts +++ b/scripts/lib/brand-assets.ts @@ -19,45 +19,60 @@ export const BRAND_ASSET_PATHS = { developmentWebAppleTouchIconPng: "assets/dev/blueprint-web-apple-touch-180.png", } as const; +export type WebAssetBrand = "development" | "production"; + export interface IconOverride { readonly sourceRelativePath: string; readonly targetRelativePath: string; } -export const DEVELOPMENT_ICON_OVERRIDES: ReadonlyArray = [ - { - sourceRelativePath: BRAND_ASSET_PATHS.developmentWebFaviconIco, - targetRelativePath: "dist/client/favicon.ico", - }, - { - sourceRelativePath: BRAND_ASSET_PATHS.developmentWebFavicon16Png, - targetRelativePath: "dist/client/favicon-16x16.png", - }, - { - sourceRelativePath: BRAND_ASSET_PATHS.developmentWebFavicon32Png, - targetRelativePath: "dist/client/favicon-32x32.png", - }, - { - sourceRelativePath: BRAND_ASSET_PATHS.developmentWebAppleTouchIconPng, - targetRelativePath: "dist/client/apple-touch-icon.png", - }, -]; +const WEB_ICON_TARGET_FILENAMES = { + faviconIco: "favicon.ico", + favicon16Png: "favicon-16x16.png", + favicon32Png: "favicon-32x32.png", + appleTouchIconPng: "apple-touch-icon.png", +} as const; -export const PUBLISH_ICON_OVERRIDES: ReadonlyArray = [ - { - sourceRelativePath: BRAND_ASSET_PATHS.productionWebFaviconIco, - targetRelativePath: "dist/client/favicon.ico", +const WEB_ICON_SOURCE_PATHS_BY_BRAND = { + development: { + faviconIco: BRAND_ASSET_PATHS.developmentWebFaviconIco, + favicon16Png: BRAND_ASSET_PATHS.developmentWebFavicon16Png, + favicon32Png: BRAND_ASSET_PATHS.developmentWebFavicon32Png, + appleTouchIconPng: BRAND_ASSET_PATHS.developmentWebAppleTouchIconPng, }, - { - sourceRelativePath: BRAND_ASSET_PATHS.productionWebFavicon16Png, - targetRelativePath: "dist/client/favicon-16x16.png", + production: { + faviconIco: BRAND_ASSET_PATHS.productionWebFaviconIco, + favicon16Png: BRAND_ASSET_PATHS.productionWebFavicon16Png, + favicon32Png: BRAND_ASSET_PATHS.productionWebFavicon32Png, + appleTouchIconPng: BRAND_ASSET_PATHS.productionWebAppleTouchIconPng, }, - { - sourceRelativePath: BRAND_ASSET_PATHS.productionWebFavicon32Png, - targetRelativePath: "dist/client/favicon-32x32.png", - }, - { - sourceRelativePath: BRAND_ASSET_PATHS.productionWebAppleTouchIconPng, - targetRelativePath: "dist/client/apple-touch-icon.png", - }, -]; +} as const satisfies Record>; + +export function resolveWebIconOverrides( + brand: WebAssetBrand, + targetDirectory: string, +): ReadonlyArray { + const sourcePaths = WEB_ICON_SOURCE_PATHS_BY_BRAND[brand]; + return [ + { + sourceRelativePath: sourcePaths.faviconIco, + targetRelativePath: `${targetDirectory}/${WEB_ICON_TARGET_FILENAMES.faviconIco}`, + }, + { + sourceRelativePath: sourcePaths.favicon16Png, + targetRelativePath: `${targetDirectory}/${WEB_ICON_TARGET_FILENAMES.favicon16Png}`, + }, + { + sourceRelativePath: sourcePaths.favicon32Png, + targetRelativePath: `${targetDirectory}/${WEB_ICON_TARGET_FILENAMES.favicon32Png}`, + }, + { + sourceRelativePath: sourcePaths.appleTouchIconPng, + targetRelativePath: `${targetDirectory}/${WEB_ICON_TARGET_FILENAMES.appleTouchIconPng}`, + }, + ]; +} + +export const DEVELOPMENT_ICON_OVERRIDES = resolveWebIconOverrides("development", "dist/client"); + +export const PUBLISH_ICON_OVERRIDES = resolveWebIconOverrides("production", "dist/client"); diff --git a/turbo.json b/turbo.json index e6ebeee912..0b19d93c4a 100644 --- a/turbo.json +++ b/turbo.json @@ -11,6 +11,8 @@ "T3CODE_NO_BROWSER", "T3CODE_HOME", "T3CODE_AUTH_TOKEN", + "T3CODE_TAILSCALE_SERVE", + "T3CODE_TAILSCALE_SERVE_PORT", "T3CODE_DESKTOP_WS_URL", "T3CODE_TRACE_MIN_LEVEL", "T3CODE_TRACE_TIMING_ENABLED",