Skip to content
TypeScript

fix(source-control): clones retry over HTTPS when the SSH key is refused (#23170)

Julius Marmingea49d18cf3b97
diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
index 3620555b30d..14615a39856 100644
--- a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
+++ b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
@@ -9,7 +9,11 @@ import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/process";
-import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts";
+import {
+ GitCommandError,
+ SourceControlProviderError,
+ type SourceControlCloneRepositoryInput,
+} from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
@@ -242,6 +246,98 @@ it.effect("reports clone progress from git's stderr and keeps its error text on
}).pipe(Effect.provide(NodeServices.layer)),
);
+function rejectingSsh(
+ urls: Array<string>,
+ httpsFails: boolean,
+ reason: GitCommandError["reason"] = "authentication_failed",
+) {
+ return {
+ execute: (input: GitVcsDriver.ExecuteGitInput) =>
+ Effect.gen(function* () {
+ const url = input.args.at(-2)!;
+ urls.push(url);
+ if (url.startsWith("https://") && !httpsFails) return processOutput();
+ yield* (
+ input.progress?.onStderrLine?.(
+ url.startsWith("https://")
+ ? "fatal: could not read Username for 'https://github.com': terminal prompts disabled"
+ : "[email protected]: Permission denied (publickey).",
+ ) ?? Effect.void
+ );
+ return yield* new GitCommandError({
+ operation: input.operation,
+ command: "git",
+ cwd: input.cwd,
+ reason,
+ detail: "Git command exited with a non-zero status.",
+ });
+ }),
+ } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
+}
+
+const cloneInTemporaryDirectory = (
+ git: Partial<GitVcsDriver.GitVcsDriver["Service"]>,
+ input: Omit<SourceControlCloneRepositoryInput, "destinationPath">,
+) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const parent = yield* fs
+ .makeTempDirectoryScoped({ prefix: "t3-clone-fallback-" })
+ .pipe(Effect.orDie);
+ return yield* Effect.gen(function* () {
+ const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
+ return yield* service.cloneRepository({
+ ...input,
+ destinationPath: path.join(parent, "t3code"),
+ });
+ }).pipe(Effect.provide(layer({ git }).pipe(Layer.orDie)));
+ }).pipe(Effect.provide(NodeServices.layer));
+
+it.effect("retries a clone over HTTPS when the SSH login is refused", () =>
+ Effect.gen(function* () {
+ const urls: Array<string> = [];
+ const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), {
+ remoteUrl: CLONE_URLS.sshUrl,
+ });
+
+ assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl, "https://github.com/octocat/t3code.git"]);
+ assert.strictEqual(result.remoteUrl, "https://github.com/octocat/t3code.git");
+ }),
+);
+
+it.effect("reports both failures when the HTTPS retry fails too", () =>
+ Effect.gen(function* () {
+ const urls: Array<string> = [];
+ const error = yield* Effect.flip(
+ cloneInTemporaryDirectory(rejectingSsh(urls, true), { remoteUrl: CLONE_URLS.sshUrl }),
+ );
+
+ assert.strictEqual(urls.length, 2);
+ assert.strictEqual(
+ error.detail,
+ "[email protected]: Permission denied (publickey). Cloning over HTTPS instead also failed: fatal: could not read Username for 'https://github.com': terminal prompts disabled",
+ );
+ }),
+);
+
+it.effect.each([
+ ["the caller asked for SSH", "ssh", "authentication_failed"],
+ ["git failed for another reason", undefined, "remote_unreachable"],
+] as const)("does not retry over HTTPS when %s", ([, protocol, reason]) =>
+ Effect.gen(function* () {
+ const urls: Array<string> = [];
+ yield* Effect.flip(
+ cloneInTemporaryDirectory(rejectingSsh(urls, false, reason), {
+ remoteUrl: CLONE_URLS.sshUrl,
+ ...(protocol === undefined ? {} : { protocol }),
+ }),
+ );
+
+ assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl]);
+ }),
+);
+
it.effect("strips embedded credentials from the remote URL it reports", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts
index bca8279ef2e..64fd0c9eec6 100644
--- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts
+++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts
@@ -7,6 +7,7 @@ import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import {
+ GitCommandError,
SourceControlProviderError,
SourceControlRepositoryError,
type GitCommandFailureReason,
@@ -31,8 +32,10 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl";
const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
+const isGitCommandError = Schema.is(GitCommandError);
const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
export class SourceControlRepositoryService extends Context.Service<
@@ -169,6 +172,27 @@ function publishPushFailureDetail(input: {
}
}
+/**
+ * Adding a project clones over SSH for most hosts, and a machine with no SSH
+ * key there would fail every time, while the host's HTTPS credential helper
+ * may be set up. A clone whose SSH login was refused is retried once over
+ * HTTPS, unless the caller asked for SSH. A looked-up repository has the
+ * provider's own HTTPS URL; any other URL is rewritten, which is refused
+ * where it would have to guess.
+ */
+function httpsFallbackUrl(
+ input: SourceControlCloneRepositoryInput,
+ prepared: SourceControlPreparedClone,
+): string | null {
+ if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null;
+ if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url;
+ return cloneUrlForProtocol(prepared.cloneUrl, "https");
+}
+
+const isSshRejection = (error: SourceControlRepositoryError) =>
+ isGitCommandError(error.cause) &&
+ (error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified");
+
function selectRemoteUrl(
urls: SourceControlRepositoryCloneUrls,
protocol: SourceControlCloneProtocol | undefined,
@@ -312,11 +336,12 @@ export const make = Effect.gen(function* () {
} satisfies SourceControlPreparedClone;
});
- const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
+ const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* (
input: SourceControlCloneRepositoryInput,
+ destinationPath: string,
+ cloneUrl: string,
options?: SourceControlCloneOptions,
) {
- const prepared = yield* prepareClone(input);
const onProgress = options?.onProgress;
// Git interleaves progress redraws with its real messages on stderr. The
// last non-progress lines are what explain a failure ("Repository not
@@ -336,14 +361,8 @@ export const make = Effect.gen(function* () {
yield* git
.execute({
operation: "SourceControlRepositoryService.cloneRepository",
- cwd: path.dirname(prepared.destinationPath),
- args: [
- "clone",
- "--progress",
- "--",
- prepared.cloneUrl,
- path.basename(prepared.destinationPath),
- ],
+ cwd: path.dirname(destinationPath),
+ args: ["clone", "--progress", "--", cloneUrl, path.basename(destinationPath)],
timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
// Progress redraws add up on a slow multi-GB clone. The buffered copy
// is never read (the tail is kept by hand above), so keep it small
@@ -368,10 +387,42 @@ export const make = Effect.gen(function* () {
}),
),
);
+ });
+
+ const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
+ input: SourceControlCloneRepositoryInput,
+ options?: SourceControlCloneOptions,
+ ) {
+ const prepared = yield* prepareClone(input);
+ const httpsUrl = httpsFallbackUrl(input, prepared);
+ const remoteUrl = yield* runClone(
+ input,
+ prepared.destinationPath,
+ prepared.cloneUrl,
+ options,
+ ).pipe(
+ Effect.as(prepared.remoteUrl),
+ Effect.catch((sshError) =>
+ httpsUrl === null || !isSshRejection(sshError)
+ ? Effect.fail(sshError)
+ : runClone(input, prepared.destinationPath, httpsUrl, options).pipe(
+ Effect.as(redactRemoteUrl(httpsUrl)),
+ Effect.mapError(
+ (httpsError) =>
+ new SourceControlRepositoryError({
+ operation: "cloneRepository",
+ provider: sshError.provider,
+ detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`,
+ cause: httpsError.cause,
+ }),
+ ),
+ ),
+ ),
+ );
return {
cwd: prepared.destinationPath,
- remoteUrl: prepared.remoteUrl,
+ remoteUrl,
repository: prepared.repository,
};
});
diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx
index 1d917de3510..fc6dce938ec 100644
--- a/apps/web/src/components/AddProjectToMachineDialog.tsx
+++ b/apps/web/src/components/AddProjectToMachineDialog.tsx
@@ -11,6 +11,11 @@ import {
type ScopedProjectRef,
resolveEnvironmentMachineKind,
} from "@t3tools/contracts";
+import {
+ type CloneProtocol,
+ cloneUrlForProtocol,
+ cloneUrlProtocol,
+} from "@t3tools/shared/cloneUrl";
import { ArrowRightIcon } from "lucide-react";
import { useEffect, useId, useState } from "react";
import { create } from "zustand";
@@ -21,10 +26,7 @@ import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
import {
COPYABLE_FILE_MAX_BYTES,
- type CloneProtocol,
addProjectToMachine,
- cloneUrlForProtocol,
- cloneUrlProtocol,
isDefaultCopiedFile,
} from "../lib/addProjectToMachine";
import { formatBytes } from "../lib/formatBytes";
diff --git a/apps/web/src/lib/addProjectToMachine.ts b/apps/web/src/lib/addProjectToMachine.ts
index 367420c45e0..bccfc9d8491 100644
--- a/apps/web/src/lib/addProjectToMachine.ts
+++ b/apps/web/src/lib/addProjectToMachine.ts
@@ -17,47 +17,9 @@ import { environmentProjectClonesAtom, silenceProjectCloneToasts } from "../stat
import { projectEnvironment } from "../state/projects";
import { sourceControlEnvironment } from "../state/sourceControl";
-export type CloneProtocol = "ssh" | "https";
-
/** Matches the server's read cap: a larger file would arrive truncated. */
export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
-const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
-const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
-const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
-
-function parseCloneUrl(
- url: string,
-): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
- const trimmed = url.trim();
- const ssh = SSH_URL.exec(trimmed);
- if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
- const https = HTTPS_URL.exec(trimmed);
- if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
- const scp = SCP_LIKE_URL.exec(trimmed);
- if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
- return null;
-}
-
-export function cloneUrlProtocol(url: string): CloneProtocol | null {
- return parseCloneUrl(url)?.protocol ?? null;
-}
-
-/**
- * Rewrites a clone URL to the other protocol, because the target machine may
- * only have SSH keys or only an HTTPS credential helper. Returns null when the
- * URL cannot be rewritten safely, such as a custom port.
- */
-export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
- const parsed = parseCloneUrl(url);
- if (!parsed) return null;
- if (parsed.protocol === protocol) return url.trim();
- if (parsed.customPort) return null;
- return protocol === "ssh"
- ? `git@${parsed.host}:${parsed.path}`
- : `https://${parsed.host}/${parsed.path}`;
-}
-
const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
/** Env files are the ignored files people almost always want on a new machine. */
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index 651ab18a40a..cb323ea4c3b 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -134,7 +134,9 @@ Use **Add Project** in the command palette (`Cmd/Ctrl+K`) to clone a repository.
provider or paste a Git URL, then choose where to save it. The project opens right away while the
clone runs in the background: you can write your first prompt, and sending waits until the files
are in place. A toast tracks progress and lets you cancel; if the clone fails, retry it from the
-toast or from the banner above the composer.
+toast or from the banner above the composer. When the host refuses the machine's SSH key, T3 Code
+clones over HTTPS with Git's credentials for that host instead, and the project's remote uses the
+HTTPS URL.
For a local Git repository without a remote, **Publish Repository** creates a hosted repository,
adds it as `origin`, and pushes your commits. If there are no commits yet, it creates the remote;
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 31828017d81..a1c50c656f3 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -502,6 +502,10 @@
"./markdownMath": {
"types": "./src/markdownMath.ts",
"import": "./src/markdownMath.ts"
+ },
+ "./cloneUrl": {
+ "types": "./src/cloneUrl.ts",
+ "import": "./src/cloneUrl.ts"
}
},
"scripts": {
diff --git a/apps/web/src/lib/addProjectToMachine.test.ts b/packages/shared/src/cloneUrl.test.ts
similarity index 94%
rename from apps/web/src/lib/addProjectToMachine.test.ts
rename to packages/shared/src/cloneUrl.test.ts
index 7da234579bb..a55192f25e0 100644
--- a/apps/web/src/lib/addProjectToMachine.test.ts
+++ b/packages/shared/src/cloneUrl.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { cloneUrlForProtocol, cloneUrlProtocol } from "./addProjectToMachine";
+import { cloneUrlForProtocol, cloneUrlProtocol } from "./cloneUrl.ts";
describe("cloneUrlForProtocol", () => {
it("switches between scp-style SSH and HTTPS", () => {
diff --git a/packages/shared/src/cloneUrl.ts b/packages/shared/src/cloneUrl.ts
new file mode 100644
index 00000000000..e4d0fa18bee
--- /dev/null
+++ b/packages/shared/src/cloneUrl.ts
@@ -0,0 +1,37 @@
+export type CloneProtocol = "ssh" | "https";
+
+const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
+const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
+const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
+
+function parseCloneUrl(
+ url: string,
+): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
+ const trimmed = url.trim();
+ const ssh = SSH_URL.exec(trimmed);
+ if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
+ const https = HTTPS_URL.exec(trimmed);
+ if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
+ const scp = SCP_LIKE_URL.exec(trimmed);
+ if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
+ return null;
+}
+
+export function cloneUrlProtocol(url: string): CloneProtocol | null {
+ return parseCloneUrl(url)?.protocol ?? null;
+}
+
+/**
+ * Rewrites a clone URL to the other protocol, because the target machine may
+ * only have SSH keys or only an HTTPS credential helper. Returns null when the
+ * URL cannot be rewritten safely, such as a custom port.
+ */
+export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
+ const parsed = parseCloneUrl(url);
+ if (!parsed) return null;
+ if (parsed.protocol === protocol) return url.trim();
+ if (parsed.customPort) return null;
+ return protocol === "ssh"
+ ? `git@${parsed.host}:${parsed.path}`
+ : `https://${parsed.host}/${parsed.path}`;
+}