GitNexus/gitnexus/src/server/git-clone.ts
Gergő Magyar 6424d8b09c
fix(web): replace broken Browse-for-folder with upload directory picker (#1850)
* fix(web): replace broken Browse-for-folder with server-side directory picker

The "Browse for folder" button used `<input type="file" webkitdirectory>`
which only exposes relative paths via `webkitRelativePath`. The code
extracted just the folder name (e.g. `myproject`), causing the server to
reject it with "path must be an absolute path". No browser API can
expose absolute filesystem paths, so the approach was fundamentally
broken on all platforms.

- Add `GET /api/fs/list` endpoint that lists subdirectories at a given
  absolute server-side path (rate-limited, validated)
- Add `listDirectories()` client function in backend-client.ts
- Add `DirectoryPicker` modal component with breadcrumb navigation
- Replace broken `webkitdirectory` input in RepoAnalyzer with the new
  server-side directory picker
- Update i18n strings (en + zh-CN)
- Add unit tests for the new endpoint (9 tests)

Docker users can now browse `/workspace/` and other container paths
directly from the UI. Manual path entry continues to work unchanged.

Closes #1518

* test(e2e): add Playwright tests for server-side directory picker

13 Playwright e2e tests covering the full DirectoryPicker flow:
- Open/display: modal opens, shows root dirs, displays current path
- Navigation: click into dirs, breadcrumb back-nav, home button
- Selection: populates path input, returns absolute path, close without selecting
- Edge cases: empty dir, API error, manual typing still works

Also updates existing onboarding.spec.ts to match the renamed
"Browse server directories" button, and adds data-testid attributes
to DirectoryPicker and RepoAnalyzer for reliable e2e targeting.

* fix(a11y): add accessibility and UX polish to DirectoryPicker

- Add role="dialog", aria-modal, aria-label to the modal panel
- Add aria-label to close button, home button
- Add aria-hidden to decorative icons (chevrons, backdrop)
- Add role="status" to loading spinner with sr-only label
- Add role="alert" to error state
- Add aria-current="location" to active breadcrumb segment
- Wrap breadcrumb in nav landmark with aria-label
- Add Escape key handler to dismiss the modal
- Auto-focus the modal panel on open
- Add focus-visible ring styles to all interactive elements
  (matches existing focus-visible:ring-2 ring-accent/40 pattern)
- Increase breadcrumb button padding (px-1.5 py-1) for better
  touch targets
- Increase directory entry padding (py-2.5) for touch comfort
- Add active:bg-hover/70 pressed state on directory entries
- Add active:bg-accent/80 pressed state on select button

* chore(autofix): apply prettier + eslint fixes via /autofix command

* fix: skip traversal guard for bare root paths in /api/fs/list (#2109)

* fix(web): replace server-side directory picker with secure folder upload

PR #1850 review found the new GET /api/fs/list directory-browsing endpoint
enumerated any absolute server path (CodeQL js/path-injection, plus a DoS and
cross-origin enumeration via the CORS/PNA allow-list). Browsers can't hand the
server an absolute path, so rather than harden the endpoint, remove it and
upload the folder instead — webkitdirectory exposes the file contents.

- Add POST /api/analyze/upload: busboy-streamed multipart ingest into an
  mkdtemp sandbox under UPLOAD_ROOT with resolve-then-contain write
  sanitization, hard size/count/dir caps, manifest-first ordering, and
  guaranteed cleanup; promote (atomic same-filesystem rename, no EXDEV) and
  analyze via the shared job/worker machinery, never returning a server path.
- Frontend: <input webkitdirectory> upload flow with client-side filtering
  (.git/node_modules/build), XHR progress, accessibility, en/zh-CN i18n.
- Remove /api/fs/list + handleFsListRequest, DirectoryPicker, listDirectories
  and their tests.
- Harden the adjacent /api/analyze {path} route: localhost-only CORS on write
  routes + realpath/exists/isDir validation replacing the inert
  normalize!==resolve guard.
- Extend DELETE /api/repo cleanup to upload dirs (by entry.path) and add a
  startup sweep for orphaned staging dirs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(review): resolve CodeQL path-injection + CSRF introduced by the upload change

The first push surfaced two new CodeQL alerts in the newly-added code (the
upload sandbox itself passed — its resolve-then-contain sanitizer is recognized):

- HIGH js/path-injection at the analyze route: the KTD11 in-route
  `fs.realpath(repoLocalPath)` / `fs.stat` was a user-controlled filesystem
  read with no security gain (the worker already reads the path; cross-origin
  reach is closed by requireLocalhostOrigin). Drop the in-route fs calls; keep
  only the absolute-path check + the localhost-origin guard.
- MEDIUM js/client-side-request-forgery: the new raw `xhr.open` was a fresh
  request sink. Route the upload through the shared, origin-validated
  fetchWithTimeout instead (the centralized sink all other calls use). Trades
  the upload-progress percentage for an indeterminate "Uploading…" state.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(review): resolve tri-review findings on the upload flow

A multi-agent review of the upload implementation surfaced a P0 plus several
P2/P3s; all are addressed here.

- P0: the upload handler took the single analysis slot (createJob) before
  validating/promoting, so any failure in that window left a queued job that
  was never failed — wedging ALL analysis until restart (trivially triggered by
  a single-segment manifest). Now: validate the folder before taking the slot,
  release it via failJob on any pre-launch error, and reject single-segment /
  multi-top manifests during ingest (also fixes a silent file-drop).
- CI: rate-limit.test's source-regex broke when Prettier wrapped the
  /api/analyze registration; made it wrapping-tolerant.
- Resource: the startup sweep now also removes stale promoted upload dirs with
  no .gitnexus index (orphans from analyses that failed before registering).
- Frontend: guard against post-unmount SSE opening, reset upload state on
  cancel/mode-change, guard concurrent uploads, fall back to the folder name,
  add aria-busy, and fix the {{count}} plural ("1 files").
- Maintainability: extract launchAnalysisWorker into analyze-launch.ts (DI +
  typed WorkerMessage IPC), move requireLocalhostOrigin to middleware.ts, share
  REPO_NAME_PATTERN, tighten UploadJobRef, name the collision-retry constant.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(web): reset isMountedRef on mount (StrictMode double-invoke)

The mount effect set isMountedRef=false on cleanup but never back to true on
re-mount, so under React StrictMode's mount->unmount->mount the ref stayed
false for the component's lifetime — trackJob then always early-returned and
the upload never advanced past 'starting' (caught by the folder-upload e2e).
Set it true at the start of the effect.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(review): de-flake upload-ingest cleanup test via injectable staging root

ingestUpload gains an IngestOptions.root override (mirroring SweepOptions.root)
so the test asserts cleanup against a per-test mkdtemp root instead of counting
global ~/.gitnexus/uploads/.staging-* entries, which raced parallel forks.
Production default stays UPLOAD_ROOT (promote rename same-filesystem invariant).

* fix(web): make stale analyze/upload requests inert after mode switch, cancel, or unmount

A folder upload (or URL analyze) still in flight when the user switched modes
could resolve later, call trackJob(), and drive the old job's SSE stream under
the new mode's form. The only guard was isMountedRef — mode change and cancel
never unmount the component.

- requestControllerRef: per-request AbortController doubling as the staleness
  token (captured per closure, checked after the await; the abort error is
  matched via signal.aborted, never error identity, since it surfaces both as
  BackendError('Request aborted') and as a raw AbortError from response.json())
- uploadFolder() now takes an optional AbortSignal; fetchWithTimeout already
  merges caller signals via AbortSignal.any
- a stale-but-created job gets a fire-and-forget cancelAnalyze(jobId) (skipped
  when a live tracking session owns the id) so the single analyze slot is freed
- handleModeChange early-returns on same-tab clicks and resets phase to input
  so an aborted request can't strand the form at 'starting'
- fixed the stale breaker comment: resilientFetch records AbortError as
  breaker-neutral (recordNeutral), not as a retryable-network penalty

* refactor(web): consolidate stale-request guard plumbing

- single invalidateRequest() helper for the abort+null pattern (4 sites)
- drop isMountedRef checks subsumed by the aborted-controller token
  (unmount aborts the controller, and unlike isMountedRef the token stays
  correct across a StrictMode unmount/remount)
- dedup the component test's render/mock scaffolding
- countStaging filters on the exported STAGING_PREFIX, not a magic string

* fix(web): scope stale-job cancellation to the upload path

Code review caught a regression in the first cut: URL analyzes dedup-alias by
repo (createJob returns the existing active job's id), so a stale resolution's
fire-and-forget cancel could kill a job another session — or the user's own
fresh resubmit — is actively watching; the jobIdRef ownership guard was
order-dependent and instance-local. Uploads always own a fresh, never-deduped
job, so the cancel is kept (unconditionally) there and dropped on the URL path,
where a same-URL resubmit re-attaches via dedup and the server's job timeout /
TTL sweep bounds the slot occupancy.

Also: remove the isMountedRef machinery outright (zero readers remain — the
aborted-controller token subsumes it and stays correct across StrictMode
remounts), make the e2e abort check ERR_ABORTED-specific, and let a broken
test root fail loudly instead of passing vacuously.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Sparsh <73558748+prajapatisparsh@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 20:50:59 +01:00

459 lines
17 KiB
TypeScript

/**
* Git Clone Utility
*
* Shallow-clones repositories into ~/.gitnexus/repos/{name}/.
* If already cloned, does git pull instead.
*/
import { spawn } from 'child_process';
import path from 'path';
import os from 'os';
import fs from 'fs/promises';
import { isIP } from 'net';
import { logger } from '../core/logger.js';
import { parseRepoNameFromUrl } from '../storage/git.js';
/** Root directory for all cloned repositories. Targets must resolve inside this. */
const CLONE_ROOT = path.resolve(path.join(os.homedir(), '.gitnexus', 'repos'));
// A valid git repository name is filesystem-safe: alphanumerics plus `. _ -`.
// Rejecting anything else (including `..`, `/`, `\`, shell metacharacters)
// guarantees getCloneDir(repoName) cannot escape CLONE_ROOT regardless of
// how the caller derived repoName.
export const REPO_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/;
/**
* Extract the repository name from a git URL (HTTPS or SSH).
*
* Throws if the URL does not yield a filesystem-safe last segment. A name
* like `..` or `foo/bar` would otherwise let `getCloneDir(name)` escape the
* clone root via path traversal.
*/
export function extractRepoName(url: string): string {
const name = parseRepoNameFromUrl(url);
if (
!name ||
name === '.' ||
name === '..' ||
name === 'unknown' ||
!REPO_NAME_PATTERN.test(name)
) {
throw new Error('Could not extract a valid repository name from URL');
}
return name;
}
/** Get the clone target directory for a repo name. */
export function getCloneDir(repoName: string): string {
// Re-validate at the boundary even though extractRepoName already checked —
// callers may pass a repoName from another source (test fixtures, scripts).
if (!repoName || repoName === '.' || repoName === '..' || !REPO_NAME_PATTERN.test(repoName)) {
throw new Error('Invalid repository name');
}
return path.join(CLONE_ROOT, repoName);
}
// Cloud metadata hostnames that must never be reachable via user-supplied URLs
const BLOCKED_HOSTNAMES = new Set([
'localhost',
'metadata.google.internal',
'metadata.azure.com',
'metadata.internal',
]);
/**
* Validate a git URL to prevent SSRF attacks.
* Only allows https:// and http:// schemes. Blocks private/internal addresses,
* IPv6 private ranges, cloud metadata hostnames, and numeric IP encodings.
*/
export function validateGitUrl(url: string): void {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error('Invalid URL');
}
if (!['https:', 'http:'].includes(parsed.protocol)) {
throw new Error('Only https:// and http:// git URLs are allowed');
}
const host = parsed.hostname.toLowerCase();
// Block known dangerous hostnames (cloud metadata services)
if (BLOCKED_HOSTNAMES.has(host)) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// Strip IPv6 brackets if present (URL parser behavior varies across Node versions)
let normalizedHost = host;
if (host.startsWith('[') && host.endsWith(']')) {
normalizedHost = host.slice(1, -1);
}
// Check if this is an IPv6 address
// Use manual colon detection as fallback since isIP may return 0 for some
// normalized IPv6 forms (e.g. ::ffff:7f00:1)
const isIPv6 = isIP(normalizedHost) === 6 || normalizedHost.includes(':');
if (isIPv6) {
assertNotPrivateIPv6(normalizedHost);
return;
}
// Check if this is an IPv4 address (including numeric encodings)
if (isIP(normalizedHost) === 4) {
assertNotPrivateIPv4(normalizedHost);
return;
}
// For non-IP hostnames, check for numeric IP tricks
// Decimal encoding: 2130706433 = 127.0.0.1
// Hex encoding: 0x7f000001 = 127.0.0.1
if (/^\d+$/.test(host) || /^0x[0-9a-f]+$/i.test(host)) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// Standard IPv4 regex checks for dotted notation
if (
/^127\./.test(host) ||
/^10\./.test(host) ||
/^172\.(1[6-9]|2\d|3[01])\./.test(host) ||
/^192\.168\./.test(host) ||
/^169\.254\./.test(host) ||
/^0\./.test(host) ||
host === '0.0.0.0' ||
/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(host) ||
/^198\.1[89]\./.test(host)
) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
}
function assertNotPrivateIPv6(ip: string): void {
// Expand common compressed forms for comparison
const lower = ip.toLowerCase();
// IPv6 loopback
if (lower === '::1' || lower === '0:0:0:0:0:0:0:1') {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// Unspecified address
if (lower === '::' || lower === '0:0:0:0:0:0:0:0') {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// IPv6 Unique Local Address (fc00::/7 = fc and fd prefixes)
if (lower.startsWith('fc') || lower.startsWith('fd')) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// IPv6 link-local (fe80::/10)
if (
lower.startsWith('fe80') ||
lower.startsWith('fe8') ||
lower.startsWith('fe9') ||
lower.startsWith('fea') ||
lower.startsWith('feb')
) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// IPv4-mapped IPv6 (::ffff:x.x.x.x or ::ffff:hex:hex)
// Node may normalize ::ffff:127.0.0.1 to ::ffff:7f00:1
if (lower.startsWith('::ffff:')) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// Also catch the expanded form: 0:0:0:0:0:ffff:
if (lower.includes(':ffff:')) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// IPv4-compatible IPv6 (RFC 4291 § 2.5.5.1, deprecated form: ::w.x.y.z).
// Node's URL parser collapses http://[::127.0.0.1]/ to "::7f00:1" — the IPv4
// is hidden in the last 32 bits without the ::ffff: marker, so the check
// above misses it. The form is still routable to the embedded IPv4 on most
// network stacks, so any address compressed to ::xxxx[:yyyy] must be blocked.
if (/^::[0-9a-f]{1,4}(:[0-9a-f]{1,4})?$/.test(lower)) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// NAT64 well-known prefix (RFC 6052 § 2.1: 64:ff9b::/96, plus the local
// 64:ff9b:1::/48 from RFC 8215). Maps any IPv4 address — including private
// ranges — into IPv6, so a host with NAT64 can reach the embedded IPv4 via
// e.g. 64:ff9b::7f00:1 → 127.0.0.1.
// The check intentionally covers the full 64:ff9b::/32 block (broader than
// the two cited ranges): IANA reserves it for IPv4-IPv6 translation, so
// blocking the whole prefix is defensively sound and prevents a narrower
// CIDR check from quietly re-opening the bypass for 64:ff9b:1::/48 or any
// future translation assignment.
if (lower.startsWith('64:ff9b:')) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
// 6to4 (RFC 3056, 2002::/16). Encodes an IPv4 address in bits 17-48, so
// 2002:7f00:0001::1 routes to 127.0.0.1 on 6to4-capable stacks. The
// protocol was deprecated by RFC 7526 and the public relay anycast
// (192.88.99.1) has been retired, so broad-blocking the prefix has near-
// zero false-positive cost while closing the IPv4-embedded bypass.
// Teredo (2001::/32) embeds IPv4 obfuscated by XOR; precise blocking is
// impractical and is out of scope here.
if (lower.startsWith('2002:')) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
}
function assertNotPrivateIPv4(ip: string): void {
const parts = ip.split('.').map(Number);
const [a, b] = parts;
if (
a === 127 ||
a === 10 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254) ||
a === 0 ||
(a === 100 && b >= 64 && b <= 127) ||
(a === 198 && (b === 18 || b === 19))
) {
throw new Error('Cloning from private/internal addresses is not allowed');
}
}
export interface CloneProgress {
phase: 'cloning' | 'pulling';
message: string;
}
/**
* Build the `git clone` argument list for a given URL and target directory.
*
* The `--` separator is non-negotiable: it stops git from parsing a URL that
* starts with `--` (e.g. `--upload-pack=evil`) as an option flag, which would
* otherwise execute an attacker-chosen subprocess (CodeQL
* js/second-order-command-line-injection, alerts #166/#167).
*
* Exported so the separator placement is testable without mocking spawn.
*/
export function buildCloneArgs(url: string, targetDir: string): string[] {
return ['clone', '--depth', '1', '--', url, targetDir];
}
/**
* Normalize a git URL into a comparable form.
*
* Two URLs are considered the same repository when their normalized forms
* are identical: lowercased hostname, no trailing `.git`, no trailing
* slashes on the path, default port stripped. Path comparison stays
* case-sensitive because that's how Git hosts treat the path component on
* the wire (case-folding GitHub's web UI is a separate convenience).
*
* Returns the original input if URL parsing fails — the caller can still
* compare with the literal string for non-URL forms (e.g. SSH `git@host:`).
*/
export function normalizeGitUrlForCompare(url: string): string {
// Strip trailing slashes and a trailing `.git` for both URL and SSH forms.
let trimmed = url;
while (trimmed.length > 0 && trimmed[trimmed.length - 1] === '/') {
trimmed = trimmed.slice(0, -1);
}
if (trimmed.endsWith('.git')) trimmed = trimmed.slice(0, -4);
try {
const parsed = new URL(trimmed);
parsed.hostname = parsed.hostname.toLowerCase();
// strip default ports
if (
(parsed.protocol === 'https:' && parsed.port === '443') ||
(parsed.protocol === 'http:' && parsed.port === '80')
) {
parsed.port = '';
}
// Strip credentials — never material to repo identity, and including
// them would let two equivalent URLs (with/without basic auth) compare
// unequal.
parsed.username = '';
parsed.password = '';
// Recompose without trailing slash on the path.
let pathname = parsed.pathname;
while (pathname.length > 1 && pathname[pathname.length - 1] === '/') {
pathname = pathname.slice(0, -1);
}
parsed.pathname = pathname;
return `${parsed.protocol}//${parsed.hostname}${parsed.port ? ':' + parsed.port : ''}${parsed.pathname}`;
} catch {
// Non-URL forms (e.g. `git@github.com:owner/repo`) — return the trimmed
// form lowercased on the hostname-ish prefix. SSH-form normalization
// is best-effort; exact-string compare is sufficient for the threat
// model (mismatched origins still differ at the literal level).
return trimmed.toLowerCase();
}
}
/**
* Read `remote.origin.url` from an existing clone using `git config --get`.
*
* Returns `null` if the config key is absent, the spawn fails, or the
* directory isn't a git repository. The caller decides what a missing
* remote means for its threat model — for cloneOrPull, a missing remote
* on an existing clone is treated as a refuse-to-pull condition.
*/
export function getRemoteOriginUrl(cwd: string): Promise<string | null> {
return new Promise((resolve) => {
const proc = spawn('git', ['config', '--get', 'remote.origin.url'], {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
});
let stdout = '';
proc.stdout.on('data', (chunk: Buffer) => {
stdout += chunk;
});
proc.on('close', (code) => {
if (code === 0 && stdout.trim()) {
resolve(stdout.trim());
} else {
resolve(null);
}
});
proc.on('error', () => resolve(null));
});
}
/**
* Verify that an existing clone's `remote.origin.url` matches the requested
* URL (after normalization). Throws on mismatch or missing remote.
*
* Closes the wrong-repo silent-analysis vector that Codex's adversarial
* review on PR #1325 surfaced: clone dirs are keyed by URL basename, so a
* request for `https://gitlab.example/attacker/repo.git` would otherwise
* collide with an existing `~/.gitnexus/repos/repo` cloned from a different
* origin and `git pull --ff-only` would silently succeed against the wrong
* remote.
*
* Exported so the comparison logic is testable in isolation against any
* tmpdir-based fixture, without needing to populate CLONE_ROOT.
*/
export async function assertRemoteMatchesRequestedUrl(
targetDir: string,
requestedUrl: string,
): Promise<void> {
const remoteUrl = await getRemoteOriginUrl(targetDir);
if (remoteUrl === null) {
throw new Error(`Existing clone at ${targetDir} has no remote.origin — refusing to pull`);
}
if (normalizeGitUrlForCompare(remoteUrl) !== normalizeGitUrlForCompare(requestedUrl)) {
throw new Error(
`Existing clone at ${targetDir} has remote ${remoteUrl}, not the requested URL ${requestedUrl}`,
);
}
}
/**
* Clone or pull a git repository.
* If targetDir doesn't exist: git clone --depth 1
* If targetDir exists with .git: git pull --ff-only (after verifying the
* existing clone's remote.origin matches the requested URL).
*
* Security:
* - targetDir must resolve inside CLONE_ROOT (~/.gitnexus/repos/). The
* path.relative containment barrier below is the inline canonical idiom
* CodeQL's js/path-injection sanitizer recognizes.
* - validateGitUrl runs unconditionally on the requested URL — both the
* clone path and the pull path. An earlier shape only validated on the
* clone branch; an existing clone with the same basename let an
* attacker's URL skip the SSRF / scheme / private-IP checks (Codex
* adversarial review on PR #1325).
* - When the target already has `.git`, the existing clone's
* remote.origin.url is fetched and compared (normalized) to the
* requested URL. Refuses to pull if they differ — this closes the
* wrong-repo silent-analysis vector where two URLs sharing a basename
* would collide on the same on-disk clone dir.
* - The git URL is passed after a `--` separator so a value beginning with
* `--` (e.g. `--upload-pack=evil`) cannot be interpreted as a git option
* (CodeQL js/second-order-command-line-injection).
*/
export async function cloneOrPull(
url: string,
targetDir: string,
onProgress?: (progress: CloneProgress) => void,
): Promise<string> {
// Containment barrier — inline with the canonical path.relative idiom so
// CodeQL recognizes the sanitizer at every following filesystem and
// subprocess sink. The same `safeTarget` is used for every downstream
// path operation — no reassignment that the analyzer could lose track of.
//
// Limitation: this is a lexical containment check, not a realpath check.
// If an attacker can place a symlink under CLONE_ROOT pointing outside it,
// the lexical check passes but the clone lands at the symlink target. That
// requires pre-existing local write access to CLONE_ROOT, so the threat
// model considers it out of scope; CodeQL js/path-injection accepts the
// lexical form. Tracked as a follow-up if defense-in-depth is needed.
const safeTarget = path.resolve(targetDir);
const rel = path.relative(CLONE_ROOT, safeTarget);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new Error(`Clone target must be a subdirectory of ${CLONE_ROOT}`);
}
// Always validate the requested URL — the prior shape only ran this in
// the code path where the repo was cloned. Now it runs unconditionally,
// preventing SSRF / blocked-host bypasses even when targetDir already exists.
validateGitUrl(url);
const exists = await fs.access(path.join(safeTarget, '.git')).then(
() => true,
() => false,
);
if (exists) {
// Confirm the existing clone is actually the same repository the caller
// requested. Without this check, a pull would silently succeed against
// whatever remote the dir was originally cloned from.
await assertRemoteMatchesRequestedUrl(safeTarget, url);
onProgress?.({ phase: 'pulling', message: 'Pulling latest changes...' });
await runGit(['pull', '--ff-only'], safeTarget);
} else {
await fs.mkdir(path.dirname(safeTarget), { recursive: true });
onProgress?.({ phase: 'cloning', message: `Cloning ${url}...` });
await runGit(buildCloneArgs(url, safeTarget));
}
return safeTarget;
}
function runGit(args: string[], cwd?: string): Promise<void> {
return new Promise((resolve, reject) => {
const proc = spawn('git', args, {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
env: {
...process.env,
// Prevent git from prompting for credentials (hangs the process)
GIT_TERMINAL_PROMPT: '0',
// Ensure no credential helper tries to open a GUI prompt
GIT_ASKPASS: process.platform === 'win32' ? 'echo' : '/bin/true',
},
});
let stderr = '';
proc.stderr.on('data', (chunk: Buffer) => {
stderr += chunk;
});
proc.on('close', (code) => {
if (code === 0) resolve();
else {
// Log full stderr internally but don't expose it to API callers (SSRF mitigation)
if (stderr.trim()) logger.error(`git ${args[0]} stderr: ${stderr.trim()}`);
reject(new Error(`git ${args[0]} failed (exit code ${code})`));
}
});
proc.on('error', (err) => {
reject(new Error(`Failed to spawn git: ${err.message}`));
});
});
}