Skip to content

Commit 1a8b244

Browse files
ulughbeckclaude
andcommitted
fix(server): pick the right GitHub account per repository
Hosts with several gh accounts read each repository with an account that can see it, without switching the CLI default. SSH host aliases resolve to their real host so routing finds the provider. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8f75697 commit 1a8b244

15 files changed

Lines changed: 1260 additions & 291 deletions

‎apps/server/src/project/RepositoryIdentityResolver.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,87 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
128128
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), layerResolver)));
129129
});
130130

131+
it.effect.each(["git@github-work:Team/private.git", "ssh://git@github-work/Team/private.git"])(
132+
"resolves the SSH host alias in %s while preserving the Git locator",
133+
(remoteUrl) => {
134+
const calls: Array<Parameters<ProcessRunner.ProcessRunner["Service"]["run"]>[0]> = [];
135+
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
136+
run: (input) =>
137+
Effect.sync(() => {
138+
calls.push(input);
139+
return {
140+
stdout:
141+
input.command === "ssh"
142+
? "hostname github.com\nuser git\nport 22\n"
143+
: input.args.includes("rev-parse")
144+
? "/repo\n"
145+
: `origin\t${remoteUrl} (fetch)\n`,
146+
stderr: "",
147+
code: ChildProcessSpawner.ExitCode(0),
148+
timedOut: false,
149+
stdoutTruncated: false,
150+
stderrTruncated: false,
151+
stdoutInvalidUtf8: false,
152+
stderrInvalidUtf8: false,
153+
};
154+
}),
155+
});
156+
const resolverLayer = Layer.effect(
157+
RepositoryIdentityResolver.RepositoryIdentityResolver,
158+
RepositoryIdentityResolver.make(),
159+
).pipe(Layer.provide(processRunner));
160+
return Effect.gen(function* () {
161+
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
162+
const identity = yield* resolver.resolve("/repo");
163+
expect(identity?.canonicalKey).toBe("github.com/team/private");
164+
expect(identity?.provider).toBe("github");
165+
expect(identity?.locator.remoteUrl).toBe(remoteUrl);
166+
// An aliased origin is still this repository, not a separate upstream.
167+
expect(identity?.origin).toBeUndefined();
168+
expect(yield* resolver.resolve("/repo")).toEqual(identity);
169+
expect(calls.filter((call) => call.command === "ssh")).toHaveLength(1);
170+
expect(calls.at(-1)?.args).toEqual([
171+
"-G",
172+
"-o",
173+
"CanonicalizeHostname=no",
174+
"--",
175+
"github-work",
176+
]);
177+
}).pipe(Effect.provide(resolverLayer));
178+
},
179+
);
180+
181+
it.effect("does not treat an unknown HTTPS host as an SSH alias", () => {
182+
const calls: string[] = [];
183+
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
184+
run: (input) =>
185+
Effect.sync(() => {
186+
calls.push(input.command);
187+
return {
188+
stdout: input.args.includes("rev-parse")
189+
? "/repo\n"
190+
: "origin\thttps://forge.test/team/repo.git (fetch)\n",
191+
stderr: "",
192+
code: ChildProcessSpawner.ExitCode(0),
193+
timedOut: false,
194+
stdoutTruncated: false,
195+
stderrTruncated: false,
196+
stdoutInvalidUtf8: false,
197+
stderrInvalidUtf8: false,
198+
};
199+
}),
200+
});
201+
const resolverLayer = Layer.effect(
202+
RepositoryIdentityResolver.RepositoryIdentityResolver,
203+
RepositoryIdentityResolver.make(),
204+
).pipe(Layer.provide(processRunner));
205+
return Effect.gen(function* () {
206+
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
207+
expect((yield* resolver.resolve("/repo"))?.canonicalKey).toBe("forge.test/team/repo");
208+
expect(calls).toEqual(["git", "git"]);
209+
}).pipe(Effect.provide(resolverLayer));
210+
});
211+
131212
it.effect("retries Git root discovery after the negative TTL", () => {
132213
const calls: Array<ReadonlyArray<string>> = [];
133214
let rootAttempts = 0;

‎apps/server/src/project/RepositoryIdentityResolver.ts‎

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import * as Effect from "effect/Effect";
1010
import * as Exit from "effect/Exit";
1111
import * as Layer from "effect/Layer";
1212

13+
import { parseSshResolveOutput } from "@t3tools/ssh/command";
14+
1315
import * as ProcessRunner from "../processRunner.ts";
1416

1517
const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
@@ -90,9 +92,12 @@ function buildRepositoryIdentity(input: {
9092
readonly remoteUrl: string;
9193
readonly originUrl: string | undefined;
9294
readonly rootPath: string;
95+
readonly resolvedRemoteUrl: string;
9396
}): RepositoryIdentity {
94-
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
95-
const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
97+
const canonicalKey = normalizeGitRemoteUrl(input.resolvedRemoteUrl);
98+
const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(
99+
input.resolvedRemoteUrl,
100+
);
96101
const repositoryPath = repositoryPathOf(canonicalKey);
97102
const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
98103
const [owner] = repositoryPathSegments;
@@ -137,6 +142,43 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.
137142
},
138143
);
139144

145+
const SSH_HOST_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
146+
147+
function parseSshRemote(
148+
remoteUrl: string,
149+
): { readonly host: string; readonly path: string } | null {
150+
if (remoteUrl.startsWith("ssh://")) {
151+
const url = URL.parse(remoteUrl);
152+
return url === null ? null : { host: url.hostname, path: url.pathname.replace(/^\/+/, "") };
153+
}
154+
const scp = /^[^@/:]+@([^/:]+):([^/].*)$/.exec(remoteUrl);
155+
return scp === null ? null : { host: scp[1]!, path: scp[2]! };
156+
}
157+
158+
/**
159+
* An SSH remote such as `git@github-work:team/repo` names a `Host` alias from the user's SSH
160+
* config. Its configured `HostName` is what the provider is known by, so the remote is rewritten
161+
* onto that host. Anything that is not a resolvable alias comes back unchanged.
162+
*/
163+
const resolveSshAliasRemoteUrl = Effect.fn("RepositoryIdentityResolver.resolveSshAliasRemoteUrl")(
164+
function* (remoteUrl: string): Effect.fn.Return<string, never, ProcessRunner.ProcessRunner> {
165+
const remote = parseSshRemote(remoteUrl);
166+
if (remote === null || !SSH_HOST_PATTERN.test(remote.host)) return remoteUrl;
167+
const processRunner = yield* ProcessRunner.ProcessRunner;
168+
const result = yield* processRunner
169+
.run({
170+
command: "ssh",
171+
args: ["-G", "-o", "CanonicalizeHostname=no", "--", remote.host],
172+
timeout: Duration.seconds(5),
173+
timeoutBehavior: "timedOutResult",
174+
})
175+
.pipe(Effect.option);
176+
if (result._tag === "None" || result.value.code !== 0) return remoteUrl;
177+
const { hostname } = parseSshResolveOutput(remote.host, result.value.stdout);
178+
return SSH_HOST_PATTERN.test(hostname) ? `https://${hostname}/${remote.path}` : remoteUrl;
179+
},
180+
);
181+
140182
const resolveRepositoryIdentityFromCacheKey = Effect.fn(
141183
"RepositoryIdentityResolver.resolveFromCacheKey",
142184
)(function* (
@@ -156,9 +198,18 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn(
156198

157199
const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
158200
const remote = pickPrimaryRemote(remotes);
159-
return remote
160-
? buildRepositoryIdentity({ ...remote, originUrl: remotes.get("origin"), rootPath: cacheKey })
161-
: null;
201+
if (remote === null) return null;
202+
// Git keeps the alias in the locator; provider detection and API routing use its real host.
203+
const resolvedRemoteUrl =
204+
detectSourceControlProviderFromGitRemoteUrl(remote.remoteUrl)?.kind === "unknown"
205+
? yield* resolveSshAliasRemoteUrl(remote.remoteUrl)
206+
: remote.remoteUrl;
207+
return buildRepositoryIdentity({
208+
...remote,
209+
originUrl: remote.remoteName === "origin" ? resolvedRemoteUrl : remotes.get("origin"),
210+
rootPath: cacheKey,
211+
resolvedRemoteUrl,
212+
});
162213
});
163214

164215
export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (

0 commit comments

Comments
 (0)