diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 72bbb01651100..996f3f13fca06 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -5,6 +5,7 @@ import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { vi } from "vite-plus/test"; @@ -81,6 +82,52 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect("keys a remote behind an SSH host alias by the host ssh config resolves it to", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const aliasDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-ssh-alias-test-", + }); + const plainDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-ssh-plain-test-", + }); + + yield* git(aliasDir, ["init"]); + yield* git(aliasDir, ["remote", "add", "origin", "git@github.com-personal:owner/repo.git"]); + yield* git(plainDir, ["init"]); + yield* git(plainDir, ["remote", "add", "origin", "git@github.com:owner/repo.git"]); + + const runner = yield* ProcessRunner.ProcessRunner; + // Stands in for `Host github.com-personal` / `HostName github.com` in ~/.ssh/config. + const resolver = yield* RepositoryIdentityResolver.make().pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: (input) => + input.command === "ssh" && input.args.includes("-G") + ? Effect.succeed({ + stdout: input.args.some((arg) => arg.includes("github.com-personal")) + ? "user git\nhostname github.com\nport 22\n" + : `hostname ${input.args.at(-1) ?? ""}\nport 22\n`, + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }) + : runner.run(input), + }), + ); + + const aliasIdentity = yield* resolver.resolve(aliasDir); + const plainIdentity = yield* resolver.resolve(plainDir); + + expect(plainIdentity?.canonicalKey).toBe("github.com/owner/repo"); + expect(aliasIdentity?.canonicalKey).toBe(plainIdentity?.canonicalKey); + expect(aliasIdentity?.locator.remoteUrl).toBe("git@github.com-personal:owner/repo.git"); + }).pipe(Effect.provide(ProcessRunner.layer)), + ); + it.effect("keeps a literal .git in an Azure DevOps repository name", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 1a992388da2f1..22144cb6b9649 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -2,6 +2,7 @@ import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/co import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; import { canonicalRepositoryPath, normalizeGitRemoteUrl } from "@t3tools/shared/git"; +import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -132,12 +133,58 @@ function repositoryPathOf(canonicalKey: string, remoteUrl: string): string { ); } +// A leading `-` on the user or host would be read by ssh as an option. +const SSH_REMOTE = /^((?:ssh:\/\/)?)((?:[^-@/:][^@/:]*@)?)([A-Za-z0-9][A-Za-z0-9._-]*)([:/].*)$/su; +const SSH_HOST_NAME = /^[a-z0-9][a-z0-9.-]*$/u; +const IPV4 = /^[\d.]+$/u; + +// Keys an SSH remote by the host its ssh config alias (`Host github.com-personal`) points at. +// A dotted host may be a forge whose SSH endpoint has another name, so only a public forge +// replaces it. `ssh -G` prints the configuration it would use and opens no connection. +const sshResolvedRemoteUrl = Effect.fn("RepositoryIdentityResolver.sshResolvedRemoteUrl")( + function* (remoteUrl: string) { + const match = isSshRemoteUrl(remoteUrl) ? SSH_REMOTE.exec(remoteUrl.trim()) : null; + if (!match) return remoteUrl; + const [, scheme = "", user = "", host = "", rest = ""] = match; + if (sourceControlDefinitions.findByPublicHost(host)) return remoteUrl; + const processRunner = yield* ProcessRunner.ProcessRunner; + const result = yield* processRunner + .run({ + command: "ssh", + args: ["-G", `${user}${host}`], + timeout: Duration.seconds(5), + maxOutputBytes: 64_000, + outputMode: "truncate", + timeoutBehavior: "timedOutResult", + }) + .pipe(Effect.option); + if (result._tag === "None" || result.value.code !== 0) return remoteUrl; + const hostName = result.value.stdout + .split("\n") + .find((line) => line.startsWith("hostname ")) + ?.slice("hostname ".length) + .trim() + .toLowerCase(); + if ( + hostName === undefined || + !SSH_HOST_NAME.test(hostName) || + IPV4.test(hostName) || + hostName === host.toLowerCase() || + (host.includes(".") && !sourceControlDefinitions.findByPublicHost(hostName)) + ) { + return remoteUrl; + } + return `${scheme}${user}${hostName}${rest}`; + }, +); + function buildRepositoryOrigin( originUrl: string | undefined, + originKeyUrl: string | undefined, canonicalKey: string, ): RepositoryIdentity["origin"] { if (!originUrl) return undefined; - const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originUrl); + const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originKeyUrl ?? originUrl); if (originKey === canonicalKey) return undefined; const displayName = repositoryPathOf(originKey, originUrl); return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) }; @@ -146,16 +193,18 @@ function buildRepositoryOrigin( function buildRepositoryIdentity(input: { readonly remoteName: string; readonly remoteUrl: string; + readonly keyUrl: string; readonly originUrl: string | undefined; + readonly originKeyUrl: string | undefined; readonly rootPath: string; }): RepositoryIdentity { - const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl); + const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.keyUrl); const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl); const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl); const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0); const [owner] = repositoryPathSegments; const repositoryName = repositoryPathSegments.at(-1); - const origin = buildRepositoryOrigin(input.originUrl, canonicalKey); + const origin = buildRepositoryOrigin(input.originUrl, input.originKeyUrl, canonicalKey); return { canonicalKey, @@ -298,13 +347,20 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn( ? resolvedResult.value.stdout : ""; const remote = pickPrimaryRemote(remotes, resolved); - return remote - ? buildRepositoryIdentity({ - ...remote, - originUrl: remotes.get("origin"), - rootPath: cacheKey.rootPath, - }) - : null; + if (!remote) return null; + const originUrl = remotes.get("origin"); + const keyUrl = yield* sshResolvedRemoteUrl(remote.remoteUrl); + const originKeyUrl = + originUrl === undefined || originUrl === remote.remoteUrl + ? keyUrl + : yield* sshResolvedRemoteUrl(originUrl); + return buildRepositoryIdentity({ + ...remote, + keyUrl, + originUrl, + originKeyUrl, + rootPath: cacheKey.rootPath, + }); }); export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (