Open History to see the last commit
1import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts";
2import type {
3 RelayManagedEndpoint,
4 RelayManagedEndpointProviderKind,
5} from "@t3tools/contracts/relay";
6import { parseUrl } from "@t3tools/shared/url";
7
8// Require managed discovery: stale tunnel config after a publish-only switch causes endpoint_provider_not_managed.
9export function isManagedTunnelActive(
10 linkState: EnvironmentCloudLinkStateResult,
11 relayProviderKind: RelayManagedEndpointProviderKind | undefined,
12) {
13 const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked;
14 return (
15 linkState.linkRevoked !== true &&
16 localManagedTunnel &&
17 (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel")
18 );
19}
20
21// The URL ends up in commands people paste into a shell, so only plain DNS names pass.
22const TUNNEL_HOSTNAME = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/i;
23
24/**
25 * An environment's MCP URL on its T3 Connect tunnel, or null. This machine reports its own
26 * tunnel hostname; a saved machine's comes from T3 Connect, and only a tunnel counts there,
27 * since a publish-only link registers its local address as `manual`.
28 */
29export function t3ConnectMcpUrl(input: {
30 readonly thisMachine: boolean;
31 readonly tunnelHostname: string | undefined;
32 readonly relayEndpoint: RelayManagedEndpoint | undefined;
33}): string | null {
34 const url = input.thisMachine
35 ? parseUrl(`https://${input.tunnelHostname ?? ""}`)
36 : input.relayEndpoint?.providerKind === "cloudflare_tunnel"
37 ? parseUrl(input.relayEndpoint.httpBaseUrl)
38 : null;
39 return url?.protocol === "https:" && TUNNEL_HOSTNAME.test(url.hostname)
40 ? `${url.origin}/mcp`
41 : null;
42}
43
44/** Where T3 Connect can be turned on for an environment: from here, only by policy, or on its host. */
45export type T3ConnectTurnOn =
46 | { readonly kind: "here" }
47 | { readonly kind: "policy"; readonly reason: string }
48 | { readonly kind: "on-host" };
49
50/**
51 * Settings and the MCP wizard share this, so a Turn on control shows only where linking works.
52 * `linkableHere` is the environment's own answer for this session (its link state).
53 */
54export function resolveT3ConnectTurnOn(input: {
55 readonly desktopApp: boolean;
56 readonly linkableHere: boolean;
57 readonly cloudConfigured: boolean;
58 readonly canReadRelay: boolean;
59 readonly canWriteRelay: boolean;
60 readonly connectDenial: string | undefined;
61}): T3ConnectTurnOn {
62 if (input.connectDenial !== undefined) return { kind: "policy", reason: input.connectDenial };
63 return input.desktopApp &&
64 input.linkableHere &&
65 input.cloudConfigured &&
66 input.canReadRelay &&
67 input.canWriteRelay
68 ? { kind: "here" }
69 : { kind: "on-host" };
70}