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

t3ConnectState.ts

69 lines2.6 KB

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