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

sshHostAlias.ts

151 lines5.7 KB

1import { detectSourceControlProviderFromGitRemoteUrl } from "@t3tools/shared/git";
2import * as NodeNet from "node:net";
3import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6​
7import * as ProcessRunner from "../processRunner.ts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";
10​
11// These documented SSH-over-443 endpoints share their public forge's identity.
12const SSH_ENDPOINT_HOSTS = new Map([
13 ["ssh.github.com", "github.com"],
14 ["altssh.gitlab.com", "gitlab.com"],
15 ["altssh.bitbucket.org", "bitbucket.org"],
16]);
17const PUBLIC_SSH_HOSTS = new Set([
18 "github.com",
19 "gitlab.com",
20 "bitbucket.org",
21 "ssh.dev.azure.com",
22 ...SSH_ENDPOINT_HOSTS.keys(),
23]);
24// Remote names can reach shell-expanded %h/%r tokens in local Match exec rules.
25const SSH_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/i;
26​
27const isSshName = (name: string | undefined) => name !== undefined && SSH_NAME_PATTERN.test(name);
28​
29interface SshRemote {
30 readonly user: string | undefined;
31 readonly host: string;
32 readonly port: string | undefined;
33 readonly path: string;
35​
36function parseSshRemote(remoteUrl: string): SshRemote | null {
37 const trimmed = remoteUrl.trim();
38 let remote: SshRemote | null = null;
39 if (/^(?:ssh|git\+ssh|ssh\+git):\/\//i.test(trimmed)) {
40 const url = URL.parse(trimmed.replace(/^[^:]+:/, "ssh:"));
41 if (url && url.pathname.length > 1) {
42 remote = {
43 user: url.username || undefined,
44 host: url.hostname,
45 port: url.port || undefined,
46 path: url.pathname,
47 };
48 }
49 } else if (!trimmed.includes("://")) {
50 const [, user, host = "", path] = /^(?:([^@/\s]+)@)?([^:/\s@]+):(\S+)$/.exec(trimmed) ?? [];
51 // A userless one-letter host is a Windows drive path.
52 if (path && (user || host.length > 1)) remote = { user, host, port: undefined, path };
53 }
54 return remote && isSshName(remote.host) && (remote.user === undefined || isSshName(remote.user))
55 ? remote
56 : null;
58​
59function parseSshConfig(stdout: string): ReadonlyMap<string, string> {
60 return new Map(
61 stdout.split("\n").flatMap((line) => {
62 const [key = "", ...value] = line.trim().split(/\s+/);
63 return value.length > 0 ? [[key.toLowerCase(), value.join(" ")] as const] : [];
64 }),
65 );
67​
68const readSshConfig = Effect.fn("sshHostAlias.readSshConfig")(function* (
69 remote: SshRemote,
70 cwd: string,
71) {
72 const environment = yield* HostProcess.Environment;
73 if (environment.GIT_SSH_COMMAND || environment.GIT_SSH || environment.GIT_SSH_VARIANT) return "";
74 const processRunner = yield* ProcessRunner.ProcessRunner;
75 const customTransport = yield* processRunner
76 .run({
77 command: "git",
78 args: ["-C", cwd, "config", "--get-regexp", "^(core\\.sshcommand|ssh\\.variant)$"],
79 env: explicitBareRepositoryEnv(environment, yield* HostProcess.Platform),
80 timeout: Duration.seconds(5),
81 timeoutBehavior: "timedOutResult",
82 })
83 .pipe(Effect.option);
84 // Arbitrary Git SSH commands may use another executable or configuration.
85 if (customTransport._tag === "None" || customTransport.value.code !== 1) return "";
86 const result = yield* processRunner
87 .run({
88 command: "ssh",
89 cwd,
90 args: [
91 "-G",
92 ...(remote.user ? ["-l", remote.user] : []),
93 ...(remote.port ? ["-p", remote.port] : []),
94 remote.host,
95 ],
96 timeout: Duration.seconds(5),
97 timeoutBehavior: "timedOutResult",
98 })
99 .pipe(Effect.option);
100 return result._tag === "Some" && result.value.code === 0 ? result.value.stdout : "";
101});
102​
103export const expandSshHostAlias = Effect.fn("sshHostAlias.expandSshHostAlias")(function* (
104 remoteUrl: string,
105 cwd: string,
106) {
107 const remote = parseSshRemote(remoteUrl);
108 if (!remote) return remoteUrl;
109​
110 const alias = remote.host.toLowerCase();
111 const config = parseSshConfig(
112 PUBLIC_SSH_HOSTS.has(alias) ? "" : yield* readSshConfig(remote, cwd),
113 );
114 const hostName = (config.get("hostname") ?? alias).toLowerCase().replace(/\.$/, "");
115 if (hostName.includes(":")) return remoteUrl;
116 const resolvedHost = SSH_ENDPOINT_HOSTS.get(hostName) ?? hostName;
117 const provider = detectSourceControlProviderFromGitRemoteUrl(`git@${resolvedHost}:`);
118 const isForge = provider !== null && provider.kind !== "unknown";
119 const aliasProvider = detectSourceControlProviderFromGitRemoteUrl(`git@${alias}:`);
120 const aliasIsForge = aliasProvider !== null && aliasProvider.kind !== "unknown";
121 const port = config.get("port") ?? remote.port;
122 const configUser = config.get("user");
123 const login = remote.user ?? configUser;
124 const user = remote.user ?? (isSshName(configUser) ? configUser : undefined);
125 const personalPath =
126 !isForge &&
127 login !== undefined &&
128 login !== "git" &&
129 (!remote.path.startsWith("/") || remote.path.startsWith("/~"));
130 const viaProxy = ["proxyjump", "proxycommand"].some(
131 (key) => (config.get(key) ?? "none") !== "none",
132 );
133 // Ambiguous endpoints and filesystem paths keep their literal identity.
134 // Known forges retain their existing SSH/HTTPS identity.
135 const host =
136 NodeNet.isIP(hostName) !== 0 ||
137 isLocalLoopbackHost(hostName) ||
138 (aliasIsForge && !isForge) ||
139 (!isForge && remote.path.startsWith("/")) ||
140 (!isForge && ((port !== undefined && port !== "22") || viaProxy)) ||
141 personalPath
142 ? alias
143 : resolvedHost;
144 // A non-git login can serve either a home directory or a self-hosted forge.
145 // Preserve the alias rather than inventing a repository path for either.
146 if (host === alias) return remoteUrl;
147 const path = remote.path;
148 return path.startsWith("/")
149 ? `ssh://${user ?? "git"}@${host}${path}`
150 : `${user ?? "git"}@${host}:${path}`;
151});