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

sshRemote.ts

130 lines4.6 KB

1import * as Schema from "effect/Schema";
2import * as Clock from "effect/Clock";
3import * as Effect from "effect/Effect";
4import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
5import type * as SourceControlHost from "./SourceControlHost.ts";
6​
7const SSH_HOSTNAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/u;
8const PUBLIC_HOSTS = new Set([
9 "github.com",
10 "gitlab.com",
11 "bitbucket.org",
12 "codeberg.org",
13 "ssh.dev.azure.com",
14]);
15​
16const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
17const SSH_CACHE_TTL_MS = 30_000;
18const SSH_CACHE_CAPACITY = 256;
19// Process adapters own their environment; never reuse results across adapters.
20const hostnameCaches = new WeakMap<
21 SourceControlHost.SourceControlHost["Service"]["process"],
22 Map<string, { readonly hostname: string; readonly expiresAt: number }>
23>();
24​
25/** Keeps the original repository path when replacing the host. */
26function parseSshRemote(remoteUrl: string) {
27 const value = remoteUrl.trim();
28​
29 if (value.toLowerCase().startsWith("ssh://")) {
30 const url = URL.parse(value);
31 if (url === null) return null;
32​
33 const authorityStart = "ssh://".length;
34 const pathStart = value.indexOf("/", authorityStart);
35 const authority = value.slice(authorityStart, pathStart === -1 ? undefined : pathStart);
36 const hostnameStart = authorityStart + authority.lastIndexOf("@") + 1;
37​
38 return {
39 hostname: url.hostname,
40 username: url.username,
41 port: url.port,
42 prefix: value.slice(0, hostnameStart),
43 suffix: value.slice(hostnameStart + url.hostname.length),
44 };
45 }
46​
47 const userEnd = value.indexOf("@");
48 const hostnameEnd = value.indexOf(":", userEnd + 1);
49 if (userEnd === -1 || hostnameEnd === -1) return null;
50​
51 return {
52 hostname: value.slice(userEnd + 1, hostnameEnd),
53 username: value.slice(0, userEnd),
54 port: "",
55 prefix: value.slice(0, userEnd + 1),
56 suffix: value.slice(hostnameEnd),
57 };
59​
60function readSshHostname(stdout: string) {
61 for (const line of stdout.split("\n")) {
62 const [key, value] = line.trim().split(/\s+/u);
63 if (key?.toLowerCase() === "hostname") return value;
64 }
66​
67/** Resolves github.com SSH aliases for API lookup. Other hosts keep their existing routing. */
68export const resolveSshRemoteUrl = Effect.fn("resolveSshRemoteUrl")(function* (input: {
69 readonly remoteUrl: string;
70 readonly cwd: string;
71 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
72}) {
73 if (!isSshRemoteUrl(input.remoteUrl)) return input.remoteUrl;
74​
75 const remote = parseSshRemote(input.remoteUrl);
76 // Accept host names and aliases. Reject values that SSH can treat as command options.
77 if (remote === null || !SSH_HOSTNAME_PATTERN.test(remote.hostname)) return input.remoteUrl;
78 // A public API host can use a different SSH endpoint, such as GitHub's port-443 host.
79 if (PUBLIC_HOSTS.has(remote.hostname.toLowerCase())) return input.remoteUrl;
80​
81 let cache = hostnameCaches.get(input.process);
82 if (cache === undefined) {
83 cache = new Map();
84 hostnameCaches.set(input.process, cache);
85 }
86 const key = encodeCacheKey([input.cwd, remote.username, remote.port, remote.hostname]);
87 const now = yield* Clock.currentTimeMillis;
88 for (const [entryKey, entry] of cache) {
89 if (entry.expiresAt <= now) cache.delete(entryKey);
90 }
91 const cached = cache.get(key);
92 if (cached !== undefined) {
93 return cached.hostname === "github.com" || cached.hostname === "ssh.github.com"
94 ? `${remote.prefix}github.com${remote.suffix}`
95 : input.remoteUrl;
96 }
97​
98 const output = yield* input.process
99 .run({
100 operation: "source-control.resolve-ssh-host",
101 command: "ssh",
102 args: [
103 "-G",
104 ...(remote.username ? ["-l", remote.username] : []),
105 ...(remote.port ? ["-p", remote.port] : []),
106 remote.hostname,
107 ],
108 cwd: input.cwd,
109 timeoutMs: 5_000,
110 maxOutputBytes: 64_000,
111 })
112 .pipe(Effect.orElseSucceed(() => null));
113​
114 const resolvedHostname =
115 output?.exitCode === 0 ? readSshHostname(output.stdout)?.toLowerCase() : undefined;
116 if (resolvedHostname !== undefined && SSH_HOSTNAME_PATTERN.test(resolvedHostname)) {
117 if (cache.size >= SSH_CACHE_CAPACITY) {
118 const oldest = cache.keys().next().value;
119 if (oldest !== undefined) cache.delete(oldest);
120 }
121 cache.set(key, {
122 hostname: resolvedHostname,
123 expiresAt: (yield* Clock.currentTimeMillis) + SSH_CACHE_TTL_MS,
124 });
125 }
126 if (resolvedHostname !== "github.com" && resolvedHostname !== "ssh.github.com")
127 return input.remoteUrl;
128​
129 return `${remote.prefix}github.com${remote.suffix}`;
130});