import { spawn } from 'child_process'; import fs from 'fs/promises'; import path from 'path'; import crypto from 'crypto'; import { GitError, redact } from './errors.js'; import { assertUrlAllowed } from './urlPolicy.js'; // Einzige Stelle, die `git` startet (execFile, nie Shell). Jede Operation läuft in einem frischen // Bare-Repo unter HB_GIT_WORKDIR, das danach gelöscht wird (ADR 0003 §4). const clean = (s)=>String(s ?? '').replace(/[\0-\x1f<>]/g, '').trim(); const classify = (stderr)=>{ const s = String(stderr); if(/couldn't find remote ref/i.test(s)) return 'no-ref'; if(/Authentication failed|HTTP Basic: Access denied|could not read (Username|Password)|returned error: (401|403)|Invalid username or password|Permission denied|remote: .*(denied|forbidden|not allowed)/i.test(s)) return 'G02'; if(/returned error: 404|not found|does not appear to be a git repository|repository .* does not exist/i.test(s)) return 'G03'; if(/non-fast-forward|\[rejected\]|fetch first|stale info|failed to push some refs|cannot lock ref|reference already exists/i.test(s)) return 'rejected'; if(/Could not resolve host|Failed to connect|Connection (refused|reset|timed out)|SSL|Operation too slow|timed out|Empty reply|unable to access/i.test(s)) return 'G04'; return 'other'; }; export const createGitClient = (cfg, { lookup, gitBinary = 'git' } = {})=>{ const baseEnv = (tmp, repoUrl, authUsername, token)=>{ const u = new URL(repoUrl); const entries = [ ['http.extraHeader', `Authorization: Basic ${Buffer.from(`${authUsername || 'git'}:${token}`).toString('base64')}`], ['protocol.allow', 'never'], ['protocol.https.allow', 'always'], ['http.followRedirects', 'false'], ['credential.helper', ''] ]; if(u.protocol === 'http:') entries.push(['protocol.http.allow', 'always']); const env = { PATH : process.env.PATH, HOME : tmp, LC_ALL : 'C', GIT_CONFIG_NOSYSTEM : '1', GIT_CONFIG_GLOBAL : '/dev/null', GIT_TERMINAL_PROMPT : '0', GIT_ASKPASS : '/bin/false', GIT_HTTP_LOW_SPEED_LIMIT : '1000', GIT_HTTP_LOW_SPEED_TIME : '10', GIT_CONFIG_COUNT : String(entries.length) }; entries.forEach(([k, v], i)=>{ env[`GIT_CONFIG_KEY_${i}`] = k; env[`GIT_CONFIG_VALUE_${i}`] = v; }); return env; }; /** * Öffnet ein temporäres Bare-Repo und ruft fn(repo) auf. `signal` (AbortSignal) bricht laufende * git-Prozesse mit SIGKILL ab, danach wird das Verzeichnis gelöscht. */ const withRepo = async ({ repoUrl, authUsername, token, signal }, fn)=>{ await assertUrlAllowed(repoUrl, cfg, { lookup }); await fs.mkdir(cfg.workdir, { recursive: true, mode: 0o700 }); const tmp = await fs.mkdtemp(path.join(cfg.workdir, 'op-')); const dir = path.join(tmp, 'repo.git'); const env = baseEnv(tmp, repoUrl, authUsername, token); const secrets = [token]; const run = (args, { input, extraEnv, binary = false, maxBytes = 1024 * 1024, cwd = dir } = {})=>new Promise((resolve, reject)=>{ if(signal?.aborted) return reject(new GitError('G04')); let aborted = false; let overflow = false; // Eigene Prozessgruppe (execFile reicht `detached` nicht durch): git startet git-remote-http als // Kindprozess, der beim Abbruch mit sterben muss. const child = spawn(gitBinary, args, { cwd, env: { ...env, ...extraEnv }, detached: true, stdio: ['pipe', 'pipe', 'pipe'] }); const kill = ()=>{ try { process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* schon beendet */ } } }; const out = []; let outBytes = 0; const err = []; let errBytes = 0; child.stdout.on('data', (c)=>{ outBytes += c.length; if(outBytes > maxBytes) { overflow = true; kill(); return; } out.push(c); }); child.stderr.on('data', (c)=>{ errBytes += c.length; if(errBytes < 64 * 1024) err.push(c); }); child.stdin.on('error', ()=>{}); const onAbort = ()=>{ aborted = true; kill(); }; // Kein AbortSignal.any/timeout: deren Quellsignale werden nur schwach gehalten const timer = setTimeout(onAbort, cfg.timeoutMs); signal?.addEventListener('abort', onAbort, { once: true }); const done = ()=>{ clearTimeout(timer); signal?.removeEventListener('abort', onAbort); }; child.on('error', (e)=>{ done(); reject(new GitError('G05', `git konnte nicht gestartet werden: ${e.code ?? e.message}`)); }); child.on('close', (code)=>{ done(); if(aborted) return reject(new GitError('G04')); if(overflow) return reject(new GitError('G09')); const stdout = Buffer.concat(out); if(code === 0) return resolve(binary ? stdout : stdout.toString('utf8')); const text = redact(Buffer.concat(err).toString('utf8'), ...secrets); const kind = classify(text); const known = ['G02', 'G03', 'G04'].includes(kind); const e = new GitError(known ? kind : 'G05', known ? undefined : 'Git-Operation fehlgeschlagen.'); e.kind = kind; e.detail = text.slice(0, 2000); // nur für das Server-Log, nie an den Client reject(e); }); if(input !== undefined) child.stdin.end(input); else child.stdin.end(); }); try { await run(['init', '--bare', '-q', dir], { cwd: tmp }); const idx = path.join(tmp, 'idx'); const repo = { run, async str(args, opts) { return String(await run(args, opts)).trim(); }, idx, url : repoUrl }; return await fn(repo); } finally { await fs.rm(tmp, { recursive: true, force: true }).catch(()=>{}); } }; // --- Operationen auf einem geöffneten Repo --- // Holt die Spitze von refs/heads/ (nur Commit und Trees). null, wenn der Branch fehlt. const fetchHead = async (repo, branch)=>{ try { await repo.run(['fetch', '-q', '--depth=1', '--filter=blob:none', '--no-tags', repo.url, `refs/heads/${branch}`]); } catch (err) { if(err.kind === 'no-ref') return null; throw err; } return repo.str(['rev-parse', '--verify', 'FETCH_HEAD^{commit}']); }; const isEmptyRemote = async (repo)=>{ const out = await repo.str(['ls-remote', '--heads', repo.url]); return out === ''; }; // Blob-ID der Datei im Commit (null: Datei fehlt) const blobAt = async (repo, head, filePath)=>{ if(!head) return null; let sha; try { sha = await repo.str(['rev-parse', '--verify', `${head}:${filePath}`]); } catch { return null; } const type = await repo.str(['cat-file', '-t', sha]); if(type !== 'blob') throw new (GitError)('G08', 'Der Pfad zeigt auf einen Ordner, nicht auf eine Datei.'); return sha; }; const readBlob = async (repo, sha)=>{ const buf = await repo.run(['cat-file', 'blob', sha], { binary: true, maxBytes: cfg.maxFileBytes + 1 }); if(buf.length > cfg.maxFileBytes) throw new GitError('G09'); return buf.toString('utf8'); }; // Baut einen Commit ohne Arbeitskopie. parent === null → Root-Commit. const buildCommit = async (repo, { parent, filePath, content, author, message, committer })=>{ const blob = await repo.str(['hash-object', '-w', '--stdin'], { input: content }); const extraEnv = { GIT_INDEX_FILE: repo.idx }; if(parent) await repo.run(['read-tree', parent], { extraEnv }); await repo.run(['update-index', '--add', '--cacheinfo', `100644,${blob},${filePath}`], { extraEnv }); const tree = await repo.str(['write-tree'], { extraEnv }); const commit = await repo.str(['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', message], { extraEnv : { GIT_AUTHOR_NAME : clean(author.name) || 'Homebrewery', GIT_AUTHOR_EMAIL : clean(author.email) || committer.email, GIT_COMMITTER_NAME : committer.name, GIT_COMMITTER_EMAIL : committer.email } }); return { commit, blob }; }; // Push ohne --force. Wirft e.kind === 'rejected' bei Non-Fast-Forward. const push = async (repo, commit, branch)=>{ await repo.run(['push', '-q', repo.url, `${commit}:refs/heads/${branch}`]); }; const lsRemote = async (repo)=>{ const out = await repo.str(['ls-remote', '--symref', repo.url, 'HEAD', 'refs/heads/*']); let defaultBranch; const heads = []; for (const line of out.split('\n').filter(Boolean)) { const sym = /^ref: refs\/heads\/(\S+)\tHEAD$/.exec(line); if(sym) { defaultBranch = sym[1]; continue; } const m = /^([0-9a-f]{40,64})\trefs\/heads\/(.+)$/.exec(line); if(m) heads.push({ name: m[2], sha: m[1] }); } return { defaultBranch, heads }; }; // Dateien (*.md) in einem Ordner des Branch-Kopfs const listFiles = async (repo, head, dir)=>{ const spec = dir ? `${head}:${dir}` : head; let out; try { out = await repo.str(['ls-tree', '-r', '--name-only', spec]); } catch { return []; } return out.split('\n').filter((f)=>f.endsWith('.md')).map((f)=>dir ? `${dir}/${f}` : f); }; return { withRepo, fetchHead, isEmptyRemote, blobAt, readBlob, buildCommit, push, lsRemote, listFiles }; }; export const randomId = ()=>crypto.randomBytes(8).toString('hex');