Open History to see the last commit
1import { AuthTerminalOperateScope, type EnvironmentId } from "@t3tools/contracts";
2import { isLoopbackHost } from "@t3tools/shared/preview";
3import { msg } from "gt-react";
4
5import { isElectron } from "~/env";
6import { m } from "~/i18n/messages";
7import { readLocalApi } from "~/localApi";
8import { useEnvironment } from "~/state/environments";
9import {
10 canForwardPorts,
11 forwardedUrl,
12 forwardPort,
13 useForwardLocality,
14} from "~/state/portForwards";
15import { useEnvironmentScope } from "~/state/session";
16
17import {
18 resolveReachableExternalServerUrl,
19 tunnelsEnvironmentLoopback,
20} from "./browserTargetResolver";
21
22/** The port of an http(s) URL on localhost, 127.0.0.1 or ::1; null for any other URL. */
23export function loopbackWebPort(url: string): number | null {
24 try {
25 const parsed = new URL(url);
26 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
27 if (!isLoopbackHost(parsed.hostname)) return null;
28 return Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
29 } catch {
30 return null;
31 }
32}
33
34/**
35 * Opens a URL from an environment's output in the system browser. That browser reaches another
36 * machine's loopback only through a desktop forward or the environment's private address, so
37 * those URLs open through one or not at all.
38 */
39export function useOpenInSystemBrowser(
40 environmentId: EnvironmentId | null,
41): (url: string) => Promise<void> {
42 const environment = useEnvironment(environmentId);
43 const forwardable =
44 useEnvironmentScope(environmentId, AuthTerminalOperateScope) &&
45 environment?.connection.phase === "connected" &&
46 canForwardPorts(environment);
47 const locality = useForwardLocality(forwardable ? environmentId : null);
48 return async (url) => {
49 const api = readLocalApi();
50 if (!api) throw new Error(m(msg("Link opening is unavailable.")));
51 const port = loopbackWebPort(url);
52 if (environmentId === null || port === null) {
53 await api.shell.openExternal(url);
54 return;
55 }
56 const unreachable = () =>
57 new Error(
58 m(
59 msg(
60 "localhost:{port} runs on another machine, and port forwarding isn't available for it right now.",
61 { port },
62 ),
63 ),
64 );
65 if (!isElectron) {
66 // No forward on the web: use the environment's own private address, or refuse.
67 let reachable: string;
68 try {
69 reachable = resolveReachableExternalServerUrl(environmentId, url);
70 } catch {
71 throw unreachable();
72 }
73 await api.shell.openExternal(reachable);
74 return;
75 }
76 if (locality === "local" || !tunnelsEnvironmentLoopback(environment?.entry.target)) {
77 await api.shell.openExternal(url);
78 return;
79 }
80 if (!forwardable) throw unreachable();
81 // Starting a forward runs the probe; only a confirmed local environment opens directly.
82 const forward = await forwardPort(environmentId, port);
83 await api.shell.openExternal(forwardedUrl(forward, url));
84 };
85}