@devries-cameron20 / t3code Mirror · read-only / commits / a49d18cf3b
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 19:30 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 21:23 UTC a49d18cf3b97fa48681d0ed1f9c6caedbd292f54
8 files changed +209 -55
apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
+97 -1
@@ -9,7 +9,11 @@ import * as Layer from "effect/Layer";
9 import * as PlatformError from "effect/PlatformError";
10 import { ChildProcessSpawner } from "effect/process";
11
12 -import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts";
12 +import {
13 + GitCommandError,
14 + SourceControlProviderError,
15 + type SourceControlCloneRepositoryInput,
16 +} from "@t3tools/contracts";
17
18 import * as ServerConfig from "../config.ts";
19 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
246 }).pipe(Effect.provide(NodeServices.layer)),
247 );
248
249 +function rejectingSsh(
250 + urls: Array<string>,
251 + httpsFails: boolean,
252 + reason: GitCommandError["reason"] = "authentication_failed",
253 +) {
254 + return {
255 + execute: (input: GitVcsDriver.ExecuteGitInput) =>
256 + Effect.gen(function* () {
257 + const url = input.args.at(-2)!;
258 + urls.push(url);
259 + if (url.startsWith("https://") && !httpsFails) return processOutput();
260 + yield* (
261 + input.progress?.onStderrLine?.(
262 + url.startsWith("https://")
263 + ? "fatal: could not read Username for 'https://github.com': terminal prompts disabled"
264 + : "git@github.com: Permission denied (publickey).",
265 + ) ?? Effect.void
266 + );
267 + return yield* new GitCommandError({
268 + operation: input.operation,
269 + command: "git",
270 + cwd: input.cwd,
271 + reason,
272 + detail: "Git command exited with a non-zero status.",
273 + });
274 + }),
275 + } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
276 +}
277 +
278 +const cloneInTemporaryDirectory = (
279 + git: Partial<GitVcsDriver.GitVcsDriver["Service"]>,
280 + input: Omit<SourceControlCloneRepositoryInput, "destinationPath">,
281 +) =>
282 + Effect.gen(function* () {
283 + const fs = yield* FileSystem.FileSystem;
284 + const path = yield* Path.Path;
285 + const parent = yield* fs
286 + .makeTempDirectoryScoped({ prefix: "t3-clone-fallback-" })
287 + .pipe(Effect.orDie);
288 + return yield* Effect.gen(function* () {
289 + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
290 + return yield* service.cloneRepository({
291 + ...input,
292 + destinationPath: path.join(parent, "t3code"),
293 + });
294 + }).pipe(Effect.provide(layer({ git }).pipe(Layer.orDie)));
295 + }).pipe(Effect.provide(NodeServices.layer));
296 +
297 +it.effect("retries a clone over HTTPS when the SSH login is refused", () =>
298 + Effect.gen(function* () {
299 + const urls: Array<string> = [];
300 + const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), {
301 + remoteUrl: CLONE_URLS.sshUrl,
302 + });
303 +
304 + assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl, "https://github.com/octocat/t3code.git"]);
305 + assert.strictEqual(result.remoteUrl, "https://github.com/octocat/t3code.git");
306 + }),
307 +);
308 +
309 +it.effect("reports both failures when the HTTPS retry fails too", () =>
310 + Effect.gen(function* () {
311 + const urls: Array<string> = [];
312 + const error = yield* Effect.flip(
313 + cloneInTemporaryDirectory(rejectingSsh(urls, true), { remoteUrl: CLONE_URLS.sshUrl }),
314 + );
315 +
316 + assert.strictEqual(urls.length, 2);
317 + assert.strictEqual(
318 + error.detail,
319 + "git@github.com: Permission denied (publickey). Cloning over HTTPS instead also failed: fatal: could not read Username for 'https://github.com': terminal prompts disabled",
320 + );
321 + }),
322 +);
323 +
324 +it.effect.each([
325 + ["the caller asked for SSH", "ssh", "authentication_failed"],
326 + ["git failed for another reason", undefined, "remote_unreachable"],
327 +] as const)("does not retry over HTTPS when %s", ([, protocol, reason]) =>
328 + Effect.gen(function* () {
329 + const urls: Array<string> = [];
330 + yield* Effect.flip(
331 + cloneInTemporaryDirectory(rejectingSsh(urls, false, reason), {
332 + remoteUrl: CLONE_URLS.sshUrl,
333 + ...(protocol === undefined ? {} : { protocol }),
334 + }),
335 + );
336 +
337 + assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl]);
338 + }),
339 +);
340 +
341 it.effect("strips embedded credentials from the remote URL it reports", () =>
342 Effect.gen(function* () {
343 const fs = yield* FileSystem.FileSystem;
apps/server/src/sourceControl/SourceControlRepositoryService.ts
+62 -11
@@ -7,6 +7,7 @@ import * as Schedule from "effect/Schedule";
7 import * as Schema from "effect/Schema";
8
9 import {
10 + GitCommandError,
11 SourceControlProviderError,
12 SourceControlRepositoryError,
13 type GitCommandFailureReason,
@@ -31,8 +32,10 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
32 import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
33 import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
34 import * as HostProcess from "@t3tools/shared/HostProcess";
35 +import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl";
36 const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
37 const isSourceControlProviderError = Schema.is(SourceControlProviderError);
38 +const isGitCommandError = Schema.is(GitCommandError);
39 const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
40
41 export class SourceControlRepositoryService extends Context.Service<
@@ -169,6 +172,27 @@ function publishPushFailureDetail(input: {
172 }
173 }
174
175 +/**
176 + * Adding a project clones over SSH for most hosts, and a machine with no SSH
177 + * key there would fail every time, while the host's HTTPS credential helper
178 + * may be set up. A clone whose SSH login was refused is retried once over
179 + * HTTPS, unless the caller asked for SSH. A looked-up repository has the
180 + * provider's own HTTPS URL; any other URL is rewritten, which is refused
181 + * where it would have to guess.
182 + */
183 +function httpsFallbackUrl(
184 + input: SourceControlCloneRepositoryInput,
185 + prepared: SourceControlPreparedClone,
186 +): string | null {
187 + if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null;
188 + if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url;
189 + return cloneUrlForProtocol(prepared.cloneUrl, "https");
190 +}
191 +
192 +const isSshRejection = (error: SourceControlRepositoryError) =>
193 + isGitCommandError(error.cause) &&
194 + (error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified");
195 +
196 function selectRemoteUrl(
197 urls: SourceControlRepositoryCloneUrls,
198 protocol: SourceControlCloneProtocol | undefined,
@@ -312,11 +336,12 @@ export const make = Effect.gen(function* () {
336 } satisfies SourceControlPreparedClone;
337 });
338
315 - const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
339 + const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* (
340 input: SourceControlCloneRepositoryInput,
341 + destinationPath: string,
342 + cloneUrl: string,
343 options?: SourceControlCloneOptions,
344 ) {
319 - const prepared = yield* prepareClone(input);
345 const onProgress = options?.onProgress;
346 // Git interleaves progress redraws with its real messages on stderr. The
347 // last non-progress lines are what explain a failure ("Repository not
@@ -336,14 +361,8 @@ export const make = Effect.gen(function* () {
361 yield* git
362 .execute({
363 operation: "SourceControlRepositoryService.cloneRepository",
339 - cwd: path.dirname(prepared.destinationPath),
340 - args: [
341 - "clone",
342 - "--progress",
343 - "--",
344 - prepared.cloneUrl,
345 - path.basename(prepared.destinationPath),
346 - ],
364 + cwd: path.dirname(destinationPath),
365 + args: ["clone", "--progress", "--", cloneUrl, path.basename(destinationPath)],
366 timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
367 // Progress redraws add up on a slow multi-GB clone. The buffered copy
368 // is never read (the tail is kept by hand above), so keep it small
@@ -368,10 +387,42 @@ export const make = Effect.gen(function* () {
387 }),
388 ),
389 );
390 + });
391 +
392 + const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
393 + input: SourceControlCloneRepositoryInput,
394 + options?: SourceControlCloneOptions,
395 + ) {
396 + const prepared = yield* prepareClone(input);
397 + const httpsUrl = httpsFallbackUrl(input, prepared);
398 + const remoteUrl = yield* runClone(
399 + input,
400 + prepared.destinationPath,
401 + prepared.cloneUrl,
402 + options,
403 + ).pipe(
404 + Effect.as(prepared.remoteUrl),
405 + Effect.catch((sshError) =>
406 + httpsUrl === null || !isSshRejection(sshError)
407 + ? Effect.fail(sshError)
408 + : runClone(input, prepared.destinationPath, httpsUrl, options).pipe(
409 + Effect.as(redactRemoteUrl(httpsUrl)),
410 + Effect.mapError(
411 + (httpsError) =>
412 + new SourceControlRepositoryError({
413 + operation: "cloneRepository",
414 + provider: sshError.provider,
415 + detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`,
416 + cause: httpsError.cause,
417 + }),
418 + ),
419 + ),
420 + ),
421 + );
422
423 return {
424 cwd: prepared.destinationPath,
374 - remoteUrl: prepared.remoteUrl,
425 + remoteUrl,
426 repository: prepared.repository,
427 };
428 });
apps/web/src/components/AddProjectToMachineDialog.tsx
+5 -3
@@ -11,6 +11,11 @@ import {
11 type ScopedProjectRef,
12 resolveEnvironmentMachineKind,
13 } from "@t3tools/contracts";
14 +import {
15 + type CloneProtocol,
16 + cloneUrlForProtocol,
17 + cloneUrlProtocol,
18 +} from "@t3tools/shared/cloneUrl";
19 import { ArrowRightIcon } from "lucide-react";
20 import { useEffect, useId, useState } from "react";
21 import { create } from "zustand";
@@ -21,10 +26,7 @@ import { useNewThreadHandler } from "../hooks/useHandleNewThread";
26 import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
27 import {
28 COPYABLE_FILE_MAX_BYTES,
24 - type CloneProtocol,
29 addProjectToMachine,
26 - cloneUrlForProtocol,
27 - cloneUrlProtocol,
30 isDefaultCopiedFile,
31 } from "../lib/addProjectToMachine";
32 import { formatBytes } from "../lib/formatBytes";
apps/web/src/lib/addProjectToMachine.ts
-38
@@ -17,47 +17,9 @@ import { environmentProjectClonesAtom, silenceProjectCloneToasts } from "../stat
17 import { projectEnvironment } from "../state/projects";
18 import { sourceControlEnvironment } from "../state/sourceControl";
19
20 -export type CloneProtocol = "ssh" | "https";
21 -
20 /** Matches the server's read cap: a larger file would arrive truncated. */
21 export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
22
25 -const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
26 -const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
27 -const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
28 -
29 -function parseCloneUrl(
30 - url: string,
31 -): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
32 - const trimmed = url.trim();
33 - const ssh = SSH_URL.exec(trimmed);
34 - if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
35 - const https = HTTPS_URL.exec(trimmed);
36 - if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
37 - const scp = SCP_LIKE_URL.exec(trimmed);
38 - if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
39 - return null;
40 -}
41 -
42 -export function cloneUrlProtocol(url: string): CloneProtocol | null {
43 - return parseCloneUrl(url)?.protocol ?? null;
44 -}
45 -
46 -/**
47 - * Rewrites a clone URL to the other protocol, because the target machine may
48 - * only have SSH keys or only an HTTPS credential helper. Returns null when the
49 - * URL cannot be rewritten safely, such as a custom port.
50 - */
51 -export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
52 - const parsed = parseCloneUrl(url);
53 - if (!parsed) return null;
54 - if (parsed.protocol === protocol) return url.trim();
55 - if (parsed.customPort) return null;
56 - return protocol === "ssh"
57 - ? `git@${parsed.host}:${parsed.path}`
58 - : `https://${parsed.host}/${parsed.path}`;
59 -}
60 -
23 const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
24
25 /** Env files are the ignored files people almost always want on a new machine. */
docs/user/source-control.md
+3 -1
@@ -134,7 +134,9 @@ Use **Add Project** in the command palette (`Cmd/Ctrl+K`) to clone a repository.
134 provider or paste a Git URL, then choose where to save it. The project opens right away while the
135 clone runs in the background: you can write your first prompt, and sending waits until the files
136 are in place. A toast tracks progress and lets you cancel; if the clone fails, retry it from the
137 -toast or from the banner above the composer.
137 +toast or from the banner above the composer. When the host refuses the machine's SSH key, T3 Code
138 +clones over HTTPS with Git's credentials for that host instead, and the project's remote uses the
139 +HTTPS URL.
140
141 For a local Git repository without a remote, **Publish Repository** creates a hosted repository,
142 adds it as `origin`, and pushes your commits. If there are no commits yet, it creates the remote;
packages/shared/package.json
+4
@@ -502,6 +502,10 @@
502 "./markdownMath": {
503 "types": "./src/markdownMath.ts",
504 "import": "./src/markdownMath.ts"
505 + },
506 + "./cloneUrl": {
507 + "types": "./src/cloneUrl.ts",
508 + "import": "./src/cloneUrl.ts"
509 }
510 },
511 "scripts": {
packages/shared/src/cloneUrl.test.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { cloneUrlForProtocol, cloneUrlProtocol } from "./addProjectToMachine";
3 +import { cloneUrlForProtocol, cloneUrlProtocol } from "./cloneUrl.ts";
4
5 describe("cloneUrlForProtocol", () => {
6 it("switches between scp-style SSH and HTTPS", () => {
packages/shared/src/cloneUrl.ts new
+37
@@ -0,0 +1,37 @@
1 +export type CloneProtocol = "ssh" | "https";
2 +
3 +const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
4 +const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
5 +const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
6 +
7 +function parseCloneUrl(
8 + url: string,
9 +): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
10 + const trimmed = url.trim();
11 + const ssh = SSH_URL.exec(trimmed);
12 + if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
13 + const https = HTTPS_URL.exec(trimmed);
14 + if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
15 + const scp = SCP_LIKE_URL.exec(trimmed);
16 + if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
17 + return null;
18 +}
19 +
20 +export function cloneUrlProtocol(url: string): CloneProtocol | null {
21 + return parseCloneUrl(url)?.protocol ?? null;
22 +}
23 +
24 +/**
25 + * Rewrites a clone URL to the other protocol, because the target machine may
26 + * only have SSH keys or only an HTTPS credential helper. Returns null when the
27 + * URL cannot be rewritten safely, such as a custom port.
28 + */
29 +export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
30 + const parsed = parseCloneUrl(url);
31 + if (!parsed) return null;
32 + if (parsed.protocol === protocol) return url.trim();
33 + if (parsed.customPort) return null;
34 + return protocol === "ssh"
35 + ? `git@${parsed.host}:${parsed.path}`
36 + : `https://${parsed.host}/${parsed.path}`;
37 +}