Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

git-exec.ts

121 lines4.6 KB

1/**
2 * An exec-backed {@link SandboxGit} implementation. Providers without a native
3 * git API (local-process, Docker) get a uniform `sandbox.git` by desugaring to
4 * `process.exec("git …")`. Providers WITH native git (Daytona, Cloudflare) may
5 * supply their own implementation instead.
6 *
7 * Security:
8 * - Every interpolated value is single-quote escaped (no shell injection).
9 * - A `--` end-of-options separator precedes untrusted positionals and values
10 * are rejected if they begin with `-`, so a repo URL / ref / path can't
11 * smuggle a git flag (e.g. `--upload-pack=…`).
12 * - Auth tokens NEVER appear in argv (they'd leak via `ps` / process logs).
13 * Instead a one-shot `credential.helper` reads the token from the child
14 * process ENV. The helper string is single-quoted so the OUTER shell never
15 * expands the env var — only git's own helper subshell does, at use time.
16 *
17 * NOTE: `SandboxProcess.exec` takes a command STRING by design (the sandbox
18 * runs shell commands), so we mitigate flag smuggling with `--` + validation
19 * rather than an argv array.
20 */
21import type { SandboxGit, SandboxProcess } from './contracts'
22​
23/** POSIX single-quote escape: wrap in '…' and escape embedded quotes. */
24function q(value: string): string {
25 return `'${value.replace(/'/g, `'\\''`)}'`
27​
28/** Reject values that could be parsed as a git flag when used as a positional. */
29function assertNoLeadingDash(value: string, name: string): void {
30 if (value.startsWith('-')) {
31 throw new Error(
32 `git-exec: ${name} "${value}" must not begin with "-" (argument-injection guard).`,
33 )
34 }
36​
37// Credential helper that prints creds read from the child ENV. Single-quoted at
38// the call site so the outer shell passes it literally; git expands the vars in
39// its own helper subshell, keeping the token out of argv.
40const CREDENTIAL_HELPER =
41 '!f() { echo "username=${GIT_ASKPASS_USER}"; echo "password=${GIT_ASKPASS_TOKEN}"; }; f'
42​
43export function createExecBackedGit(
44 process: SandboxProcess,
45 defaultRoot: string,
46): SandboxGit {
47 const at = (dir?: string): string => {
48 const d = dir ?? defaultRoot
49 assertNoLeadingDash(d, 'dir')
50 return q(d)
51 }
52​
53 return {
54 clone: async ({ url, dir, ref, auth, depth }) => {
55 assertNoLeadingDash(url, 'url')
56 const target = dir ?? defaultRoot
57 assertNoLeadingDash(target, 'dir')
58 if (ref !== undefined) assertNoLeadingDash(ref, 'ref')
59 const refArg = ref ? `--branch ${q(ref)} ` : ''
60 const resolvedDepth = depth ?? 1
61 // `depth` is interpolated unquoted into the command, so validate it the
62 // same way other positionals are guarded — a non-positive-integer (e.g. an
63 // untyped caller passing a string) must never reach the shell.
64 if (
65 resolvedDepth !== 'full' &&
66 (!Number.isInteger(resolvedDepth) || resolvedDepth <= 0)
67 ) {
68 throw new Error('git-exec: depth must be a positive integer or "full".')
69 }
70 const depthArg =
71 resolvedDepth === 'full'
72 ? ''
73 : `--depth ${resolvedDepth} --single-branch `
74​
75 // `git clone` does not create missing parents. gitSkill clones into
76 // `<root>/.tanstack-skills/<name>`, so create that parent first.
77 const parentSlash = target.lastIndexOf('/')
78 if (parentSlash > 0) {
79 await process.exec(`mkdir -p ${q(target.slice(0, parentSlash))}`)
80 }
81​
82 if (auth?.token) {
83 await process.exec(
84 `git -c credential.helper=${q(CREDENTIAL_HELPER)} clone ${refArg}${depthArg}-- ${q(url)} ${q(target)}`,
85 {
86 // Token lives only in the child env, never in argv.
87 env: {
88 GIT_ASKPASS_USER: auth.username ?? 'x-access-token',
89 GIT_ASKPASS_TOKEN: auth.token,
90 GIT_TERMINAL_PROMPT: '0',
91 },
92 },
93 )
94 return
95 }
96​
97 await process.exec(
98 `git clone ${refArg}${depthArg}-- ${q(url)} ${q(target)}`,
99 )
100 },
101 status: async (dir) =>
102 (await process.exec(`git -C ${at(dir)} status --porcelain`)).stdout,
103 add: async (paths, dir) => {
104 paths.forEach((p, i) => assertNoLeadingDash(p, `path[${i}]`))
105 await process.exec(`git -C ${at(dir)} add -- ${paths.map(q).join(' ')}`)
106 },
107 commit: async (message, dir) => {
108 await process.exec(`git -C ${at(dir)} commit -m ${q(message)}`)
109 },
110 push: async (dir) => {
111 await process.exec(`git -C ${at(dir)} push`)
112 },
113 pull: async (dir) => {
114 await process.exec(`git -C ${at(dir)} pull`)
115 },
116 branch: async (dir) =>
117 (
118 await process.exec(`git -C ${at(dir)} rev-parse --abbrev-ref HEAD`)
119 ).stdout.trim(),
120 }