feat(git): Git-Backend über HTTPS + PAT (ADR 0003): Krypto, SSRF-Policy, git-Client ohne Arbeitskopie, Sync/Konflikte, /api/git/*, Hooks und Tests

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dev-bot BotandClaude Sonnet 5.5 committed 2026-11-25 14:34:11 +00:00
1 parent d2801b2d6c
commit fe9efc155e
18 files changed
+1837 -9

No files matched your search

+448
View File
@@ -0,0 +1,448 @@
import { randomUUID } from 'crypto';
import { GitError, redact } from './errors.js';
import { createTokenCrypto } from './crypto.js';
import { createGitClient } from './gitClient.js';
import { createLocks } from './locks.js';
import { assertUrlAllowed } from './urlPolicy.js';
import { validatePath, validateDir, validateBranch, slugify } from './validate.js';
// Kernlogik des Git-Backends (ADR 0003 §5): Verbindungen, Laden, Speichern, Konflikte, Pull.
const MAX_PUSH_ATTEMPTS = 3;
const noreplyEmail = (username, host)=>`${String(username).replace(/[^A-Za-z0-9._-]+/g, '-')}@users.noreply.${host}`;
export const publicConnection = (conn)=>({
id : conn.id,
label : conn.label,
repoUrl : conn.repoUrl,
authUsername : conn.authUsername,
hasToken : !!conn.tokenEnc,
defaultBranch : conn.defaultBranch,
brewDir : conn.brewDir,
assetsDir : conn.assetsDir,
createdAt : conn.createdAt,
updatedAt : conn.updatedAt,
lastVerifiedAt : conn.lastVerifiedAt
});
const publicStatus = (link, conn, { isConnectionOwner = false } = {})=>link ? {
linked : true,
connectionId : conn?.id,
connectionLabel : conn?.label,
repoUrl : conn?.repoUrl,
branch : link.branch,
path : link.path,
lastCommitSha : link.lastCommitSha,
lastSyncedAt : link.lastSyncedAt,
lastError : link.lastError,
isConnectionOwner
} : { linked: false };
export const createGitService = ({ cfg, getStorage, api, splitTextStyleAndMetadata, client, locks, logger = console })=>{
const tokenCrypto = cfg.enabled ? createTokenCrypto({ key: cfg.key, oldKeys: cfg.oldKeys }) : undefined;
client ??= createGitClient(cfg);
locks ??= createLocks({ maxConcurrency: cfg.maxConcurrency, maxQueue: cfg.maxQueue });
const storage = ()=>getStorage();
const committer = { name: cfg.committerName, email: cfg.committerEmail };
const logGit = (what, err)=>logger.warn?.(`[git] ${what}: ${err?.HBErrorCode ?? ''} ${err?.detail ?? err?.message ?? err}`);
// --- Token ---
const getToken = async (conn)=>{
let res;
try { res = tokenCrypto.decrypt(conn.tokenEnc, conn.id); } catch {
throw new GitError('G02', 'Der gespeicherte Token kann nicht entschlüsselt werden. Bitte Token neu hinterlegen.');
}
if(res.rotate) {
await storage().gitConnections.update(conn.id, { tokenEnc: tokenCrypto.encrypt(res.token, conn.id) })
.catch((e)=>logGit('Token-Rotation fehlgeschlagen', e));
}
return res.token;
};
// Operation gegen das Remote einer Verbindung unter globalem Limit
const withConn = async (conn, fn, { signal } = {})=>{
const token = await getToken(conn);
return locks.withSlot(()=>client.withRepo({ repoUrl: conn.repoUrl, authUsername: conn.authUsername, token, signal }, fn), { signal });
};
// --- Rechte ---
const isBrewOwner = (brew, account)=>!!account && (brew.authors?.length === 0 || brew.authors?.[0] === account.username);
const canEdit = (brew, account)=>!!account && (brew.authors?.length === 0
|| brew.authors?.includes(account.username) || brew.invitedAuthors?.includes(account.username));
const requireUid = (account)=>{
if(!account?.uid) throw new GitError('G07');
return account.uid;
};
const accessError = (account)=>account
? Object.assign(new GitError('G08', 'Du bist kein Autor dieses Brews.', { status: 401 }), { HBErrorCode: '03' })
: Object.assign(new GitError('G08', 'Nicht angemeldet.', { status: 401 }), { HBErrorCode: '04' });
const loadEditableBrew = async (editId, account)=>{
const brew = await storage().brews.findByEditId(editId);
if(!brew) throw new GitError('G08', 'Brew nicht gefunden.', { status: 404 });
if(!canEdit(brew, account)) throw accessError(account);
return brew;
};
const authorOf = async (account)=>{
let name = account?.username ?? 'Homebrewery';
if(account?.uid) {
const user = await storage().users.findById(account.uid).catch(()=>null);
name = user?.displayName || account.username;
}
return { name, email: noreplyEmail(account?.username ?? 'homebrewery', cfg.noreplyHost) };
};
// --- Verbindungen ---
const parseConnectionInput = async (input, { partial })=>{
const out = {};
const str = (v)=>typeof v === 'string' ? v.trim() : v;
if(!partial || input.label !== undefined) {
const label = str(input.label);
if(typeof label !== 'string' || label.length < 1 || label.length > 80) throw new GitError('G08', 'Die Bezeichnung muss 1–80 Zeichen lang sein.');
out.label = label;
}
if(!partial || input.repoUrl !== undefined) {
out.repoUrl = str(input.repoUrl);
await assertUrlAllowed(out.repoUrl, cfg);
}
if(input.authUsername !== undefined || !partial) {
const u = str(input.authUsername) || 'git';
if(typeof u !== 'string' || u.length > 100 || u.includes(':') || /[\0-\x1f]/.test(u)) throw new GitError('G08', 'Ungültiger Benutzername für den Git-Server.');
out.authUsername = u;
}
if(input.token !== undefined && input.token !== '') {
if(typeof input.token !== 'string' || input.token.length > 2000 || /[\0-\x1f\s]/.test(input.token)) throw new GitError('G08', 'Ungültiger Token.');
out.token = input.token;
} else if(!partial) throw new GitError('G08', 'Der Token fehlt.');
if(input.defaultBranch !== undefined && input.defaultBranch !== '') out.defaultBranch = await validateBranch(str(input.defaultBranch));
if(input.brewDir !== undefined) out.brewDir = validateDir(str(input.brewDir));
if(input.assetsDir !== undefined) out.assetsDir = validateDir(str(input.assetsDir));
return out;
};
const svc = {
enabled : cfg.enabled,
cfg,
locks,
canEdit,
isBrewOwner,
async listConnections(account) {
const uid = requireUid(account);
return (await storage().gitConnections.listByOwner(uid)).map(publicConnection);
},
async createConnection(account, input) {
const uid = requireUid(account);
const data = await parseConnectionInput(input ?? {}, { partial: false });
const { token, ...rest } = data;
const id = randomUUID();
const conn = { id, ownerUserId: uid, ...rest, tokenEnc: tokenCrypto.encrypt(token, id) };
// Standard-Branch aus dem Remote (best effort): Fehler hier verhindern das Anlegen nicht, der Test-Button zeigt sie
let verified = false;
if(!conn.defaultBranch) {
conn.defaultBranch = 'main';
try {
const { defaultBranch } = await withConn(conn, (repo)=>client.lsRemote(repo));
if(defaultBranch) conn.defaultBranch = defaultBranch;
verified = true;
} catch (err) { logGit('ls-remote beim Anlegen', err); }
}
if(verified) conn.lastVerifiedAt = new Date();
return publicConnection(await storage().gitConnections.create(conn));
},
async updateConnection(account, id, input) {
const uid = requireUid(account);
const existing = await storage().gitConnections.findByIdForOwner(id, uid);
if(!existing) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
const { token, ...patch } = await parseConnectionInput(input ?? {}, { partial: true });
if(token) patch.tokenEnc = tokenCrypto.encrypt(token, existing.id);
return publicConnection(await storage().gitConnections.update(existing.id, patch));
},
async deleteConnection(account, id) {
const uid = requireUid(account);
const existing = await storage().gitConnections.findByIdForOwner(id, uid);
if(!existing) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
await storage().gitConnections.delete(existing.id);
},
async ownedConnection(account, id) {
const uid = requireUid(account);
const conn = await storage().gitConnections.findByIdForOwner(id, uid);
if(!conn) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
return conn;
},
async testConnection(account, id) {
const conn = await svc.ownedConnection(account, id);
const { defaultBranch, heads } = await withConn(conn, (repo)=>client.lsRemote(repo));
await storage().gitConnections.update(conn.id, { lastVerifiedAt: new Date(), ...(defaultBranch && !conn.defaultBranch ? { defaultBranch } : {}) });
return { ok: true, defaultBranch: defaultBranch ?? conn.defaultBranch, branchCount: heads.length };
},
async listBranches(account, id) {
const conn = await svc.ownedConnection(account, id);
const { defaultBranch, heads } = await withConn(conn, (repo)=>client.lsRemote(repo));
return { defaultBranch: defaultBranch ?? conn.defaultBranch, branches: heads.map((h)=>h.name).sort() };
},
async listFiles(account, id, { branch, dir }) {
const conn = await svc.ownedConnection(account, id);
branch = await validateBranch(branch || conn.defaultBranch);
dir = validateDir(dir ?? '');
const files = await withConn(conn, async (repo)=>{
const head = await client.fetchHead(repo, branch);
if(!head) throw new GitError('G03');
return client.listFiles(repo, head, dir);
});
return { branch, files };
},
// --- Schreiben ---
/**
* Schreibt `content` per Commit in Datei `path` auf `branch` (Schritte 2–4 aus ADR 0003 §5).
* `expectedBlob`: Blob-ID, die wir zuletzt gesehen haben (null: Datei soll neu sein).
* `overwrite`: Blob-ID aus gitOverwrite (bewusstes Überschreiben des fremden Stands).
*/
async commitContent(conn, { branch, filePath, content, expectedBlob, overwrite, author, signal }) {
if(Buffer.byteLength(content) > cfg.maxFileBytes) throw new GitError('G09');
for (let attempt = 1; attempt <= MAX_PUSH_ATTEMPTS; attempt++) {
const result = await withConn(conn, async (repo)=>{
const head = await client.fetchHead(repo, branch);
let parent = head;
if(!head && !(await client.isEmptyRemote(repo))) {
// Neuer Branch in nicht leerem Repo: auf Kopf von default_branch aufsetzen
parent = await client.fetchHead(repo, conn.defaultBranch);
if(!parent) throw new GitError('G03', 'Der Standard-Branch der Verbindung existiert im Repository nicht.');
}
const remoteBlob = parent ? await client.blobAt(repo, parent, filePath) : null;
if((remoteBlob ?? null) !== (expectedBlob ?? null) && overwrite !== (remoteBlob ?? 'none')) {
if(expectedBlob === null && remoteBlob) throw new GitError('G06', undefined, { extra: { remoteCommitSha: parent, remoteBlobSha: remoteBlob } });
throw new GitError('G01', undefined, { extra: { remoteCommitSha: parent, remoteBlobSha: remoteBlob } });
}
const message = `${remoteBlob ? 'Update' : 'Create'} ${filePath} via Homebrewery`;
const { commit, blob } = await client.buildCommit(repo, { parent, filePath, content, author, message, committer });
if(head && blob === remoteBlob) return { commit: head, blob, unchanged: true };
try {
await client.push(repo, commit, branch);
} catch (err) {
if(err.kind === 'rejected') return { retry: true };
throw err;
}
return { commit, blob };
}, { signal });
if(!result.retry) return result;
}
throw new GitError('G05');
},
// --- Lesen ---
async readRemote(conn, { branch, filePath, signal, withContent = true }) {
return withConn(conn, async (repo)=>{
const head = await client.fetchHead(repo, branch);
if(!head) return { head: null, blob: null, content: null };
const blob = await client.blobAt(repo, head, filePath);
const wantContent = typeof withContent === 'function' ? withContent(blob) : withContent;
const content = blob && wantContent ? await client.readBlob(repo, blob) : null;
return { head, blob, content };
}, { signal });
},
// Remote-Stand in den DB-Snapshot übernehmen (Pull und Abgleich beim Öffnen)
async applyRemote(brew, link, { head, blob, content }) {
const fields = { text: content.replaceAll('\r\n', '\n') };
splitTextStyleAndMetadata(fields);
const updated = {
...brew,
text : content.replaceAll('\r\n', '\n'),
version : (brew.version || 1) + 1,
updatedAt : new Date()
};
if(typeof fields.title === 'string' && fields.title.trim()) updated.title = fields.title.trim().slice(0, 100);
if(typeof fields.description === 'string') updated.description = fields.description.trim();
if(typeof fields.renderer === 'string') updated.renderer = fields.renderer;
if(typeof fields.lang === 'string') updated.lang = fields.lang;
const saved = await storage().brews.update(updated);
await storage().brewGitLinks.update(brew.id, { lastCommitSha: head, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
return saved;
},
// --- Brews ---
async createBrew(account, { connectionId, branch, path: filePath, brew }) {
const conn = await svc.ownedConnection(account, connectionId);
if(!brew || typeof brew.text !== 'string') throw new GitError('G08', 'Der Brew fehlt oder hat keinen Text.');
delete brew.editId; delete brew.shareId; delete brew.googleId; delete brew.id; delete brew._id;
branch = await validateBranch(branch || conn.defaultBranch);
api.beforeNewSave(account, brew);
filePath = validatePath(filePath || `${conn.brewDir ? `${conn.brewDir}/` : ''}${slugify(brew.title)}.md`);
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06');
const author = await authorOf(account);
const { commit, blob } = await svc.commitContent(conn, { branch, filePath, content: brew.text, expectedBlob: null, author });
const saved = await storage().brews.create(brew);
await storage().brewGitLinks.upsert({ brewId: saved.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: commit, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
return saved;
},
async importBrew(account, { connectionId, branch, path: filePath }) {
const conn = await svc.ownedConnection(account, connectionId);
branch = await validateBranch(branch || conn.defaultBranch);
filePath = validatePath(filePath);
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06', 'Die Datei ist bereits mit einem Brew verknüpft.');
const { head, blob, content } = await svc.readRemote(conn, { branch, filePath });
if(!blob) throw new GitError('G03');
const brew = { text: content };
splitTextStyleAndMetadata(brew);
if(!brew.title) brew.title = filePath.split('/').pop().replace(/\.md$/, '');
api.beforeNewSave(account, brew);
const saved = await storage().brews.create(brew);
await storage().brewGitLinks.upsert({ brewId: saved.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: head, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
return saved;
},
async linkBrew(account, editId, { connectionId, branch, path: filePath }) {
const conn = await svc.ownedConnection(account, connectionId);
const brew = await loadEditableBrew(editId, account);
if(!isBrewOwner(brew, account)) throw new GitError('G08', 'Nur der Besitzer des Brews darf ihn verknüpfen.', { status: 403 });
if(brew.googleId) throw new GitError('G08', 'Ein Brew liegt entweder in Google Drive oder in Git.');
if(await storage().brewGitLinks.findByBrewId(brew.id)) throw new GitError('G08', 'Der Brew ist bereits mit einem Repository verknüpft.');
branch = await validateBranch(branch || conn.defaultBranch);
filePath = validatePath(filePath || `${conn.brewDir ? `${conn.brewDir}/` : ''}${slugify(brew.title)}.md`);
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06');
const author = await authorOf(account);
return svc.locks.withKey(brew.id, async ()=>{
const { commit, blob } = await svc.commitContent(conn, { branch, filePath, content: brew.text, expectedBlob: null, author });
const link = await storage().brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: commit, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
return publicStatus(link, conn, { isConnectionOwner: true });
});
},
async unlinkBrew(account, editId) {
const brew = await loadEditableBrew(editId, account);
const link = await storage().brewGitLinks.findByBrewId(brew.id);
if(!link) return;
const conn = await storage().gitConnections.findByIdForOwner(link.connectionId, requireUid(account));
if(!conn || !isBrewOwner(brew, account)) throw new GitError('G07', 'Nur der Besitzer der Verbindung und des Brews darf die Verknüpfung lösen.');
await storage().brewGitLinks.delete(brew.id);
},
async status(account, editId) {
const brew = await loadEditableBrew(editId, account);
const link = await storage().brewGitLinks.findByBrewId(brew.id);
if(!link) return { linked: false };
const conn = await storage().gitConnections.findById(link.connectionId);
return publicStatus(link, conn, { isConnectionOwner: !!account.uid && conn?.ownerUserId === account.uid });
},
async pull(account, editId) {
const brew = await loadEditableBrew(editId, account);
return svc.locks.withKey(brew.id, async ()=>{
const link = await storage().brewGitLinks.findByBrewId(brew.id);
if(!link) throw new GitError('G08', 'Der Brew ist nicht mit Git verknüpft.');
const conn = await storage().gitConnections.findById(link.connectionId);
if(!conn) throw new GitError('G08', 'Die Verbindung existiert nicht mehr.');
const state = await svc.readRemote(conn, { branch: link.branch, filePath: link.path }).catch(async (err)=>{
await storage().brewGitLinks.update(brew.id, { lastError: err.HBErrorCode ?? 'G05' });
throw err;
});
if(!state.blob) throw new GitError('G03');
await svc.applyRemote(brew, link, state);
return svc.status(account, editId);
});
},
// Abgleich beim Öffnen (Express-Middleware für GET /edit/:id), eigenes Zeitbudget
openSyncMiddleware() {
return async (req, res, next)=>{
try {
if(!cfg.enabled || !req.account) return next();
let id;
try { id = api.getId(req).id; } catch { return next(); }
const brew = await storage().brews.findByEditId(id);
if(!brew || !canEdit(brew, req.account)) return next();
const link = await storage().brewGitLinks.findByBrewId(brew.id);
if(!link) return next();
const conn = await storage().gitConnections.findById(link.connectionId);
if(!conn) return next();
const signal = AbortSignal.timeout(cfg.openTimeoutMs);
try {
await locks.withKey(brew.id, async ()=>{
const current = await storage().brewGitLinks.findByBrewId(brew.id);
const fresh = await storage().brews.findByEditId(id);
// Inhalt nur laden, wenn sich der Blob geändert hat (im selben Repo-Zugriff)
const state = await svc.readRemote(conn, { branch: link.branch, filePath: link.path, signal, withContent: (blob)=>blob !== current.lastBlobSha });
if(!state.blob) throw new GitError('G03');
if(state.content !== null) {
await svc.applyRemote(fresh, current, state);
} else if(current.lastError) {
await storage().brewGitLinks.update(brew.id, { lastError: null });
}
}, { signal });
} catch (err) {
const code = signal.aborted ? 'G04' : (err.HBErrorCode ?? 'G05');
logGit(`Abgleich beim Öffnen von ${id} fehlgeschlagen`, err);
await storage().brewGitLinks.update(brew.id, { lastError: code }).catch(()=>{});
}
} catch (err) {
logGit('Abgleich beim Öffnen', err);
}
next();
};
},
// --- Hooks für updateBrew (ADR 0003 §5, "Speichern") ---
// Liefert null, wenn bereits geantwortet wurde (Fehler), sonst ein Kontextobjekt.
async beforeBrewSave({ brew, req, res }) {
if(!cfg.enabled || !brew?.id) return {};
const link = await storage().brewGitLinks.findByBrewId(brew.id);
if(!link) return {};
const conn = await storage().gitConnections.findById(link.connectionId);
if(!conn) return {};
const fail = (err)=>{
if(!(err instanceof GitError)) { logGit('Speichern', err); err = new GitError('G05', 'Speichern im Repository fehlgeschlagen.'); } else if(err.HBErrorCode !== 'G01') logGit(`Speichern von ${brew.editId}`, err);
res.status(err.status).json(err.toBody());
return null;
};
if(req.query?.saveToGoogle) return fail(new GitError('G08', 'Ein Brew liegt entweder in Google Drive oder in Git.'));
let release;
try {
// Mutex pro Brew, bis afterBrewSave ihn freigibt (Commit und DB-Save sind eine Einheit)
release = await svc.locks.acquireKey(brew.id);
const author = await authorOf(req.account);
const overwrite = typeof req.query?.gitOverwrite === 'string' ? req.query.gitOverwrite : undefined;
// Basis der Konflikterkennung unter dem Mutex frisch lesen (ein paralleler Save kann sie verschoben haben)
const fresh = await storage().brewGitLinks.findByBrewId(brew.id);
const result = await svc.commitContent(conn, { branch: fresh.branch, filePath: fresh.path, content: brew.text, expectedBlob: fresh.lastBlobSha, overwrite, author });
return { link: fresh, git: { commit: result.commit, blob: result.blob }, release };
} catch (err) {
release?.();
return fail(err);
}
},
async afterBrewSave(ctx, saved) {
if(!ctx?.git) return;
try {
if(saved) {
await storage().brewGitLinks.update(ctx.link.brewId, { lastCommitSha: ctx.git.commit, lastBlobSha: ctx.git.blob, lastSyncedAt: new Date(), lastError: null });
}
} catch (err) {
logGit('Link nach dem Speichern aktualisieren', err);
} finally {
ctx.release?.();
}
}
};
return svc;
};
export { redact };
+45
View File
@@ -0,0 +1,45 @@
import os from 'os';
import path from 'path';
import crypto from 'crypto';
// Konfiguration des Git-Backends ausschließlich aus Umgebungsvariablen (ADR 0003, "Konfiguration").
const bool = (v, def = false)=>{
if(v === undefined || v === null || v === '') return def;
return ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase());
};
const int = (v, def, { min = 1, max = Number.MAX_SAFE_INTEGER } = {})=>{
const n = parseInt(v, 10);
return Number.isFinite(n) ? Math.min(Math.max(n, min), max) : def;
};
export const parseKey = (value, name = 'HB_GIT_TOKEN_KEY')=>{
const key = Buffer.from(String(value).trim(), 'base64');
if(key.length !== 32) throw new Error(`${name} muss 32 Byte (base64) lang sein, z. B. openssl rand -base64 32`);
return key;
};
export const keyId = (key)=>crypto.createHash('sha256').update(key).digest('hex').slice(0, 8);
export const readGitConfig = (env = process.env)=>{
const key = env.HB_GIT_TOKEN_KEY ? parseKey(env.HB_GIT_TOKEN_KEY) : undefined;
const oldKeys = (env.HB_GIT_TOKEN_KEYS_OLD || '').split(',').map((s)=>s.trim()).filter(Boolean).map((k)=>parseKey(k, 'HB_GIT_TOKEN_KEYS_OLD'));
const timeoutMs = int(env.HB_GIT_TIMEOUT_MS, 20000, { min: 1000 });
const publicHost = (()=>{ try { return new URL(env.HB_PUBLIC_URL).hostname; } catch { return 'localhost'; } })();
return {
enabled : !!key,
key,
oldKeys,
allowedHosts : (env.HB_GIT_ALLOWED_HOSTS || '').split(',').map((s)=>s.trim().toLowerCase()).filter(Boolean),
allowPrivate : bool(env.HB_GIT_ALLOW_PRIVATE),
allowHttp : bool(env.HB_GIT_ALLOW_HTTP),
workdir : env.HB_GIT_WORKDIR || path.join(os.tmpdir(), 'hb-git'),
timeoutMs,
openTimeoutMs : int(env.HB_GIT_OPEN_TIMEOUT_MS, 4000, { min: 1000, max: timeoutMs }),
maxFileBytes : int(env.HB_GIT_MAX_FILE_BYTES, 5 * 1024 * 1024),
maxConcurrency : int(env.HB_GIT_MAX_CONCURRENCY, 2),
maxQueue : 20,
committerName : env.HB_GIT_COMMITTER_NAME || 'Homebrewery',
committerEmail : env.HB_GIT_COMMITTER_EMAIL || `homebrewery@${publicHost}`,
noreplyHost : publicHost
};
};
+35
View File
@@ -0,0 +1,35 @@
import crypto from 'crypto';
import { keyId } from './config.js';
// Token-Verschlüsselung (ADR 0003 §3): AES-256-GCM, Format v1.<kid>.<iv>.<ciphertext>.<tag> (base64url),
// AAD = `git-connection:<id>`.
const b64 = (buf)=>buf.toString('base64url');
const unb64 = (s)=>Buffer.from(s, 'base64url');
export const createTokenCrypto = ({ key, oldKeys = [] })=>{
if(!key) throw new Error('Kein Schlüssel für die Token-Verschlüsselung konfiguriert');
const current = { kid: keyId(key), key };
const all = new Map([[current.kid, key], ...oldKeys.map((k)=>[keyId(k), k])]);
return {
encrypt(token, connectionId) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(Buffer.from(`git-connection:${connectionId}`));
const ct = Buffer.concat([cipher.update(String(token), 'utf8'), cipher.final()]);
return ['v1', current.kid, b64(iv), b64(ct), b64(cipher.getAuthTag())].join('.');
},
// → { token, rotate } (rotate: mit altem Schlüssel entschlüsselt, bitte neu verschlüsseln)
decrypt(enc, connectionId) {
const parts = String(enc).split('.');
if(parts.length !== 5 || parts[0] !== 'v1') throw new Error('Unbekanntes Token-Format');
const k = all.get(parts[1]);
if(!k) throw new Error('Schlüssel zum Entschlüsseln nicht vorhanden');
const decipher = crypto.createDecipheriv('aes-256-gcm', k, unb64(parts[2]));
decipher.setAAD(Buffer.from(`git-connection:${connectionId}`));
decipher.setAuthTag(unb64(parts[4]));
const token = Buffer.concat([decipher.update(unb64(parts[3])), decipher.final()]).toString('utf8');
return { token, rotate: parts[1] !== current.kid };
}
};
};
+39
View File
@@ -0,0 +1,39 @@
// Fehlercodes des Git-Backends (ADR 0003). G01–G07 stehen in der ADR, G08–G10 sind Ergänzungen der Umsetzung.
export const GIT_ERRORS = {
G01 : { status: 409, message: 'Die Datei wurde im Repository geändert (Konflikt).' },
G02 : { status: 502, message: 'Anmeldung am Git-Server fehlgeschlagen (Token ungültig oder ohne Schreibrecht).' },
G03 : { status: 502, message: 'Repository, Branch oder Datei nicht gefunden.' },
G04 : { status: 504, message: 'Der Git-Server ist nicht erreichbar oder zu langsam.' },
G05 : { status: 503, message: 'Speichern im Repository nicht möglich (zu viele gleichzeitige Änderungen oder Server ausgelastet).' },
G06 : { status: 409, message: 'Die Datei existiert im Repository bereits.' },
G07 : { status: 403, message: 'Das Git-Backend steht nur Konten mit OIDC-Anmeldung zur Verfügung.' },
G08 : { status: 400, message: 'Ungültige Eingabe.' },
G09 : { status: 413, message: 'Die Datei ist zu groß.' },
G10 : { status: 503, message: 'Das Git-Backend ist auf diesem Server nicht aktiviert (HB_GIT_TOKEN_KEY fehlt).' }
};
export class GitError extends Error {
constructor(code, message, extra = {}) {
super(message ?? GIT_ERRORS[code]?.message ?? code);
this.name = 'GitError';
this.HBErrorCode = code;
this.status = extra.status ?? GIT_ERRORS[code]?.status ?? 500;
this.extra = extra.extra ?? {};
}
toBody() {
return { HBErrorCode: this.HBErrorCode, message: this.message, ...this.extra };
}
}
// Entfernt Token (auch als Basic-Header) und Authorization-Header aus Text vor dem Loggen/Ausliefern.
export const redact = (text, ...secrets)=>{
let out = String(text ?? '');
for (const secret of secrets.filter((s)=>s && String(s).length >= 3)) {
const s = String(secret);
out = out.split(s).join('***');
out = out.split(Buffer.from(s).toString('base64')).join('***');
}
return out
.replace(/(authorization:\s*(?:basic|bearer)\s+)\S+/gi, '$1***')
.replace(/(https?:\/\/)[^\s/@]+@/gi, '$1***@');
};
+197
View File
@@ -0,0 +1,197 @@
import crypto from 'crypto';
import { readGitConfig, keyId } from './config.js';
import { createTokenCrypto } from './crypto.js';
import { assertUrlAllowed, parseRepoUrl, isPrivateAddress } from './urlPolicy.js';
import { validatePath, validateBranch, validateDir, slugify } from './validate.js';
import { redact, GitError } from './errors.js';
import { createLocks, createSemaphore } from './locks.js';
const key = ()=>crypto.randomBytes(32);
describe('Token-Verschlüsselung (ADR 0003 §3)', ()=>{
const k = key();
const c = createTokenCrypto({ key: k });
test('Roundtrip, Format v1.<kid>.<iv>.<ct>.<tag>, zufälliger IV', ()=>{
const enc = c.encrypt('ghp_geheim', 'conn-1');
const parts = enc.split('.');
expect(parts).toHaveLength(5);
expect(parts[0]).toBe('v1');
expect(parts[1]).toBe(keyId(k));
expect(enc).not.toContain('ghp_geheim');
expect(c.decrypt(enc, 'conn-1')).toEqual({ token: 'ghp_geheim', rotate: false });
expect(c.encrypt('ghp_geheim', 'conn-1')).not.toBe(enc);
});
test('falsche AAD (andere Verbindung) schlägt fehl', ()=>{
const enc = c.encrypt('t', 'conn-1');
expect(()=>c.decrypt(enc, 'conn-2')).toThrow();
});
test('manipuliertes Chiffrat und unbekanntes Format schlagen fehl', ()=>{
const enc = c.encrypt('t', 'conn-1').split('.');
enc[3] = Buffer.from('xxxx').toString('base64url');
expect(()=>c.decrypt(enc.join('.'), 'conn-1')).toThrow();
expect(()=>c.decrypt('quatsch', 'conn-1')).toThrow();
});
test('Rotation: alter Schlüssel entschlüsselt und meldet rotate', ()=>{
const old = key();
const enc = createTokenCrypto({ key: old }).encrypt('t', 'c');
const rotated = createTokenCrypto({ key: k, oldKeys: [old] });
expect(rotated.decrypt(enc, 'c')).toEqual({ token: 't', rotate: true });
expect(()=>createTokenCrypto({ key: k }).decrypt(enc, 'c')).toThrow(/Schlüssel/);
});
});
describe('Konfiguration', ()=>{
test('ohne HB_GIT_TOKEN_KEY deaktiviert', ()=>{
expect(readGitConfig({}).enabled).toBe(false);
});
test('Schlüssel muss 32 Byte lang sein', ()=>{
expect(()=>readGitConfig({ HB_GIT_TOKEN_KEY: Buffer.from('kurz').toString('base64') })).toThrow(/32 Byte/);
expect(readGitConfig({ HB_GIT_TOKEN_KEY: key().toString('base64') }).enabled).toBe(true);
});
test('Standardwerte und Grenzen', ()=>{
const cfg = readGitConfig({ HB_GIT_TOKEN_KEY: key().toString('base64'), HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_OPEN_TIMEOUT_MS: '999999' });
expect(cfg).toMatchObject({ timeoutMs: 20000, openTimeoutMs: 20000, maxFileBytes: 5242880, maxConcurrency: 2, committerName: 'Homebrewery', committerEmail: 'homebrewery@hb.example.test', allowPrivate: false, allowHttp: false });
expect(readGitConfig({ HB_GIT_OPEN_TIMEOUT_MS: '10' }).openTimeoutMs).toBe(1000);
expect(readGitConfig({}).openTimeoutMs).toBe(4000);
});
});
describe('URL-Policy (SSRF)', ()=>{
const cfg = { allowedHosts: [], allowPrivate: false, allowHttp: false };
const pub = async ()=>[{ address: '93.184.216.34' }];
test.each([
['http://git.example.test/a/b', /https/],
['https://user:pw@git.example.test/a/b', /Zugangsdaten/],
['https://git.example.test/a/b?x=1', /Query/],
['https://git.example.test/a/b#f', /Query/],
['https://git.example.test/', /Pfad/],
['ssh://git@git.example.test/a/b', /https/],
['file:///etc/passwd', /https/],
['kein url', /ungültig/]
])('lehnt %s ab', async (url, msg)=>{
await expect(assertUrlAllowed(url, cfg, { lookup: pub })).rejects.toThrow(msg);
});
test('öffentlicher Host ist erlaubt', async ()=>{
await expect(assertUrlAllowed('https://git.example.test:8443/a/b.git', cfg, { lookup: pub })).resolves.toBeDefined();
});
test.each(['127.0.0.1', '10.1.2.3', '172.16.0.1', '172.31.255.255', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '::1', 'fd00::1', 'fe80::1', '::ffff:127.0.0.1', '224.0.0.1'])('%s gilt als intern', (ip)=>{
expect(isPrivateAddress(ip)).toBe(true);
});
test.each(['8.8.8.8', '93.184.216.34', '172.32.0.1', '2606:4700::1111'])('%s gilt als öffentlich', (ip)=>{
expect(isPrivateAddress(ip)).toBe(false);
});
test('Host, der auf interne Adresse auflöst, wird abgelehnt (auch gemischt)', async ()=>{
const lookup = async ()=>[{ address: '93.184.216.34' }, { address: '10.0.0.5' }];
await expect(assertUrlAllowed('https://evil.example.test/a/b', cfg, { lookup })).rejects.toThrow(/privat|intern/i);
await expect(assertUrlAllowed('https://127.0.0.1/a/b', cfg, { lookup: pub })).rejects.toThrow();
await expect(assertUrlAllowed('https://[::1]/a/b', cfg, { lookup: pub })).rejects.toThrow();
});
test('HB_GIT_ALLOW_PRIVATE erlaubt interne Ziele, HB_GIT_ALLOW_HTTP http://', async ()=>{
await expect(assertUrlAllowed('http://127.0.0.1:3000/a/b', { ...cfg, allowPrivate: true, allowHttp: true })).resolves.toBeDefined();
expect(()=>parseRepoUrl('http://x.test/a/b', { allowHttp: true })).not.toThrow();
});
test('Allowlist: nur passende Hosts, Wildcard *.example.org', async ()=>{
const c = { ...cfg, allowedHosts: ['github.com', '*.example.org'] };
const never = async ()=>{ throw new Error('kein DNS nötig'); };
await expect(assertUrlAllowed('https://github.com/a/b', c, { lookup: never })).resolves.toBeDefined();
await expect(assertUrlAllowed('https://git.example.org/a/b', c, { lookup: never })).resolves.toBeDefined();
await expect(assertUrlAllowed('https://example.org/a/b', c, { lookup: never })).rejects.toThrow(/nicht erlaubt/);
await expect(assertUrlAllowed('https://evilgithub.com/a/b', c, { lookup: never })).rejects.toThrow(/nicht erlaubt/);
});
});
describe('Pfad- und Branch-Validierung', ()=>{
test.each(['brews/a.md', 'a.md', 'x/y/z.md'])('Pfad %s ok', (p)=>expect(validatePath(p)).toBe(p));
test.each(['', '/abs.md', '../a.md', 'a/../b.md', 'a//b.md', 'a/./b.md', '.git/config.md', 'x/.git/a.md', 'a.txt', 'a\\b.md', `${'a'.repeat(256)}.md`, 'a\0.md'])('Pfad %j abgelehnt', (p)=>{
expect(()=>validatePath(p)).toThrow(GitError);
});
test('Ordner', ()=>{
expect(validateDir('brews/')).toBe('brews');
expect(validateDir('')).toBe('');
expect(()=>validateDir('../x')).toThrow();
expect(()=>validateDir('/x')).toThrow();
});
test('Branch per git check-ref-format', async ()=>{
await expect(validateBranch('main')).resolves.toBe('main');
await expect(validateBranch('feature/x-1')).resolves.toBe('feature/x-1');
for (const bad of ['', '-x', 'a..b', 'a b', 'a~1', 'a^', 'a:b', 'a?', 'a*', 'a[', 'x.lock', '@{-1}', '--upload-pack=evil', 'a//b', '/a']) {
await expect(validateBranch(bad)).rejects.toBeInstanceOf(GitError);
}
});
test('slugify', ()=>{
expect(slugify('Dungeon Mäster: Teil 1!')).toBe('dungeon-master-teil-1');
expect(slugify('')).toBe('brew');
expect(slugify('../../etc')).toBe('etc');
});
});
describe('redact', ()=>{
test('entfernt Token, Basic-Header und Userinfo', ()=>{
const token = 'ghp_abcdef123456';
const basic = Buffer.from(`git:${token}`).toString('base64');
const text = `fatal: x ${token} Authorization: Basic ${basic} https://git:${token}@host/a ${Buffer.from(token).toString('base64')}`;
const out = redact(text, token);
expect(out).not.toContain(token);
expect(out).not.toContain(basic);
expect(out).not.toContain(Buffer.from(token).toString('base64'));
expect(out).not.toMatch(/Basic [A-Za-z0-9+/=]{8,}/);
});
});
describe('Locks', ()=>{
test('Concurrency-Limit und Queue-Limit (503/G05)', async ()=>{
const sem = createSemaphore(1, 1);
const r1 = await sem.acquire();
const p2 = sem.acquire();
await expect(sem.acquire()).rejects.toMatchObject({ HBErrorCode: 'G05' });
r1();
(await p2)();
expect(sem.active).toBe(0);
});
test('Warten wird per AbortSignal abgebrochen (G04)', async ()=>{
const sem = createSemaphore(1);
const r1 = await sem.acquire();
const ac = new AbortController();
const p = sem.acquire(ac.signal);
ac.abort();
await expect(p).rejects.toMatchObject({ HBErrorCode: 'G04' });
r1();
(await sem.acquire())();
expect(sem.waiting).toBe(0);
});
test('Mutex pro Brew serialisiert, verschiedene Brews laufen parallel, Schlüssel werden aufgeräumt', async ()=>{
const locks = createLocks();
const order = [];
const task = (name, ms)=>locks.withKey('brew-1', async ()=>{ order.push(`start ${name}`); await new Promise((r)=>setTimeout(r, ms)); order.push(`end ${name}`); });
await Promise.all([task('a', 30), task('b', 1)]);
expect(order).toEqual(['start a', 'end a', 'start b', 'end b']);
let parallel = 0; let max = 0;
await Promise.all(['x', 'y'].map((k)=>locks.withKey(k, async ()=>{ max = Math.max(max, ++parallel); await new Promise((r)=>setTimeout(r, 20)); parallel--; })));
expect(max).toBe(2);
expect(locks.keyCount).toBe(0);
});
test('acquireKey/release hält den Mutex über mehrere Schritte', async ()=>{
const locks = createLocks();
const release = await locks.acquireKey('k');
let got = false;
const p = locks.withKey('k', async ()=>{ got = true; });
await new Promise((r)=>setTimeout(r, 10));
expect(got).toBe(false);
release(); release();
await p;
expect(got).toBe(true);
});
});
+203
View File
@@ -0,0 +1,203 @@
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/<branch> (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');
+13
View File
@@ -0,0 +1,13 @@
// Einhängepunkte für homebrew.api.js (ADR 0003 §5). Ohne konfigurierten Service (Git-Backend aus, Unit-Specs)
// sind alle Hooks wirkungslos, damit die Upstream-Datei nur zwei Zeilen braucht.
let service;
export const configureGitHooks = (svc)=>{ service = svc; };
// → null: Antwort wurde bereits gesendet (Fehler, z. B. Konflikt G01); sonst Kontext (ggf. leer)
export const beforeBrewSave = async (args)=>service ? service.beforeBrewSave(args) : {};
// `saved` ist das Ergebnis des DB-Saves (falsy bei Fehler). Gibt den Brew-Mutex in jedem Fall frei.
export const afterBrewSave = async (ctx, saved)=>{ if(service) await service.afterBrewSave(ctx, saved); };
export default { configureGitHooks, beforeBrewSave, afterBrewSave };
+18
View File
@@ -0,0 +1,18 @@
import { readGitConfig } from './config.js';
import { createGitService } from './brewSync.js';
import { createGitRouter } from './routes.js';
import { configureGitHooks } from './hooks.js';
export { readGitConfig, createGitService, createGitRouter, configureGitHooks };
/**
* Hängt das Git-Backend ein: Service anlegen, Hooks setzen, Router liefern.
* @param {{ getStorage: ()=>object, api: object, splitTextStyleAndMetadata: Function, env?: object, logger?: object }} deps
*/
export const createGitBackend = ({ getStorage, api, splitTextStyleAndMetadata, env = process.env, logger = console })=>{
const cfg = readGitConfig(env);
if(!cfg.enabled) logger.warn?.('Git-Backend deaktiviert: HB_GIT_TOKEN_KEY ist nicht gesetzt (openssl rand -base64 32).');
const service = createGitService({ cfg, getStorage, api, splitTextStyleAndMetadata, logger });
configureGitHooks(cfg.enabled ? service : undefined);
return { service, router: createGitRouter(service, { logger }) };
};
+72
View File
@@ -0,0 +1,72 @@
import { GitError } from './errors.js';
// Zählender Semaphor mit begrenzter Warteschlange und Abbruch per AbortSignal.
export const createSemaphore = (max, maxQueue = Infinity)=>{
let active = 0;
const queue = [];
const release = ()=>{
const next = queue.shift();
if(next) { next.grant(); } else { active--; }
};
return {
get active() { return active; },
get waiting() { return queue.length; },
acquire(signal) {
if(signal?.aborted) return Promise.reject(new GitError('G04'));
if(active < max) { active++; return Promise.resolve(release); }
if(queue.length >= maxQueue) return Promise.reject(new GitError('G05', 'Der Server ist mit Git-Operationen ausgelastet, bitte später erneut versuchen.'));
return new Promise((resolve, reject)=>{
const entry = {
grant : ()=>{ signal?.removeEventListener('abort', onAbort); resolve(release); }
};
const onAbort = ()=>{
const i = queue.indexOf(entry);
if(i >= 0) queue.splice(i, 1);
reject(new GitError('G04'));
};
signal?.addEventListener('abort', onAbort, { once: true });
queue.push(entry);
});
}
};
};
// Globales Limit (HB_GIT_MAX_CONCURRENCY) und Mutex pro Brew (prozesslokal).
export const createLocks = ({ maxConcurrency = 2, maxQueue = 20 } = {})=>{
const global = createSemaphore(maxConcurrency, maxQueue);
const perKey = new Map();
const locks = {
global,
async withSlot(fn, { signal } = {}) {
const release = await global.acquire(signal);
try { return await fn(); } finally { release(); }
},
// Mutex pro Schlüssel; liefert release() für Fälle, in denen er über mehrere Schritte gehalten wird
async acquireKey(key, { signal } = {}) {
let entry = perKey.get(key);
if(!entry) { entry = { sem: createSemaphore(1), users: 0 }; perKey.set(key, entry); }
entry.users++;
let release;
try {
release = await entry.sem.acquire(signal);
} catch (err) {
if(--entry.users === 0) perKey.delete(key);
throw err;
}
let released = false;
return ()=>{
if(released) return;
released = true;
release();
if(--entry.users === 0) perKey.delete(key);
};
},
async withKey(key, fn, { signal } = {}) {
const release = await locks.acquireKey(key, { signal });
try { return await fn(); } finally { release(); }
},
get keyCount() { return perKey.size; }
};
return locks;
};
+65
View File
@@ -0,0 +1,65 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import checkClientVersion from '../../middleware/check-client-version.js';
import dbCheck from '../../middleware/dbCheck.js';
import { GitError } from './errors.js';
import { publicConnection } from './brewSync.js';
// /api/git/* (ADR 0003 §4, §5, §7). Verwaltungsrouten verlangen ein OIDC-Konto (req.account.uid);
// Status und Pull verlangen nur das Bearbeitungsrecht am Brew.
export const createGitRouter = (svc, { logger = console } = {})=>{
const router = express.Router();
const send = (res, status, body)=>res.status(status).json(body);
const requireEnabled = (req, res, next)=>{
if(!svc.enabled) return send(res, 503, new GitError('G10').toBody());
next();
};
const requireOidc = (req, res, next)=>{
if(!req.account?.uid) return send(res, 403, new GitError('G07').toBody());
next();
};
const requireAccount = (req, res, next)=>{
if(!req.account) return send(res, 401, { HBErrorCode: '04', message: 'Nicht angemeldet.' });
next();
};
const handle = (fn)=>asyncHandler(async (req, res)=>{
try {
await fn(req, res);
} catch (err) {
if(err instanceof GitError || (err?.HBErrorCode && err?.status)) {
if(err.detail) logger.warn?.(`[git] ${req.method} ${req.path}: ${err.HBErrorCode} ${err.detail}`);
return send(res, err.status, err.toBody ? err.toBody() : { HBErrorCode: err.HBErrorCode, message: err.message });
}
logger.error?.(`[git] ${req.method} ${req.path}:`, err?.message);
send(res, 500, { HBErrorCode: 'G05', message: 'Interner Fehler im Git-Backend.' });
}
});
router.use('/api/git', dbCheck, checkClientVersion, requireEnabled);
// Verbindungen
router.get('/api/git/connections', requireOidc, handle(async (req, res)=>send(res, 200, await svc.listConnections(req.account))));
router.post('/api/git/connections', requireOidc, handle(async (req, res)=>send(res, 201, await svc.createConnection(req.account, req.body))));
router.patch('/api/git/connections/:id', requireOidc, handle(async (req, res)=>send(res, 200, await svc.updateConnection(req.account, req.params.id, req.body))));
router.delete('/api/git/connections/:id', requireOidc, handle(async (req, res)=>{ await svc.deleteConnection(req.account, req.params.id); res.status(204).end(); }));
router.post('/api/git/connections/:id/test', requireOidc, handle(async (req, res)=>send(res, 200, await svc.testConnection(req.account, req.params.id))));
router.get('/api/git/connections/:id/branches', requireOidc, handle(async (req, res)=>send(res, 200, await svc.listBranches(req.account, req.params.id))));
router.get('/api/git/connections/:id/files', requireOidc, handle(async (req, res)=>send(res, 200, await svc.listFiles(req.account, req.params.id, { branch: req.query.branch, dir: req.query.dir }))));
// Brews
router.post('/api/git/brews', requireOidc, handle(async (req, res)=>send(res, 200, await svc.createBrew(req.account, req.body ?? {}))));
router.post('/api/git/brews/import', requireOidc, handle(async (req, res)=>send(res, 200, await svc.importBrew(req.account, req.body ?? {}))));
router.post('/api/git/brews/:editId/link', requireOidc, handle(async (req, res)=>send(res, 200, await svc.linkBrew(req.account, req.params.editId, req.body ?? {}))));
router.delete('/api/git/brews/:editId/link', requireOidc, handle(async (req, res)=>{ await svc.unlinkBrew(req.account, req.params.editId); res.status(204).end(); }));
router.get('/api/git/brews/:editId', requireAccount, handle(async (req, res)=>send(res, 200, await svc.status(req.account, req.params.editId))));
router.post('/api/git/brews/:editId/pull', requireAccount, handle(async (req, res)=>send(res, 200, await svc.pull(req.account, req.params.editId))));
// Abgleich beim Öffnen, muss vor pageRoutes registriert sein
router.get('/edit/:id', svc.openSyncMiddleware());
return router;
};
export { publicConnection };
+57
View File
@@ -0,0 +1,57 @@
import dns from 'dns';
import net from 'net';
import { GitError } from './errors.js';
// URL- und Host-Prüfung (ADR 0003 §4, SSRF-Schutz).
export const parseRepoUrl = (value, { allowHttp = false } = {})=>{
let u;
try { u = new URL(String(value)); } catch { throw new GitError('G08', 'Die Repository-URL ist ungültig.'); }
const okProtocol = u.protocol === 'https:' || (allowHttp && u.protocol === 'http:');
if(!okProtocol) throw new GitError('G08', 'Nur https://-URLs sind erlaubt.');
if(u.username || u.password) throw new GitError('G08', 'Die URL darf keine Zugangsdaten enthalten.');
if(u.search || u.hash) throw new GitError('G08', 'Die URL darf keine Query oder kein Fragment enthalten.');
if(!u.hostname || u.pathname === '/' || u.pathname === '') throw new GitError('G08', 'Die URL muss einen Repository-Pfad enthalten.');
if(String(value).length > 500) throw new GitError('G08', 'Die URL ist zu lang.');
return u;
};
const hostMatches = (host, pattern)=>pattern.startsWith('*.') ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1 : host === pattern;
const v4Private = (ip)=>{
const [a, b] = ip.split('.').map(Number);
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || a >= 224;
};
export const isPrivateAddress = (address)=>{
let ip = address.toLowerCase();
if(ip.startsWith('::ffff:') && net.isIPv4(ip.slice(7))) ip = ip.slice(7);
if(net.isIPv4(ip)) return v4Private(ip);
if(net.isIPv6(ip)) {
return ip === '::' || ip === '::1' || /^f[cd]/.test(ip) || /^fe[89ab]/.test(ip) || ip.startsWith('ff');
}
return true;
};
/**
* Wirft G08, wenn die URL nicht erlaubt ist. `lookup` ist für Tests austauschbar.
*/
export const assertUrlAllowed = async (value, cfg, { lookup = dns.promises.lookup } = {})=>{
const u = parseRepoUrl(value, cfg);
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
if(cfg.allowedHosts?.length) {
if(!cfg.allowedHosts.some((p)=>hostMatches(host, p)))
throw new GitError('G08', 'Dieser Git-Host ist auf dieser Instanz nicht erlaubt.');
return u;
}
if(cfg.allowPrivate) return u;
let addrs;
if(net.isIP(host)) addrs = [{ address: host }];
else {
try { addrs = await lookup(host, { all: true }); } catch { throw new GitError('G04', 'Der Git-Host konnte nicht aufgelöst werden.'); }
}
if(!addrs.length || addrs.some((a)=>isPrivateAddress(a.address)))
throw new GitError('G08', 'Interne oder private Adressen sind als Git-Ziel nicht erlaubt.');
return u;
};
+39
View File
@@ -0,0 +1,39 @@
import { execFile } from 'child_process';
import { GitError } from './errors.js';
// Pfad- und Branch-Validierung (ADR 0003 §2).
export const validatePath = (p)=>{
const bad = (msg)=>{ throw new GitError('G08', `Ungültiger Pfad: ${msg}`); };
if(typeof p !== 'string' || !p) bad('leer');
if(p.length > 255) bad('länger als 255 Zeichen');
if(p.startsWith('/') || p.includes('\\') || /[\0-\x1f]/.test(p)) bad('nur relative Pfade mit / erlaubt');
const parts = p.split('/');
if(parts.some((s)=>s === '' || s === '.' || s === '..')) bad('kein .., . oder leere Segmente');
if(parts[0].toLowerCase() === '.git' || parts.some((s)=>s.toLowerCase() === '.git')) bad('nicht unter .git');
if(!p.endsWith('.md')) bad('Endung .md erforderlich');
return p;
};
// Ordner (ohne Endung-Pflicht), für brewDir/assetsDir und Dateilisten
export const validateDir = (d)=>{
if(d === '' || d === undefined || d === null) return '';
if(typeof d !== 'string' || d.length > 255 || d.startsWith('/') || d.includes('\\') || /[\0-\x1f]/.test(d))
throw new GitError('G08', 'Ungültiger Ordner.');
const parts = d.replace(/\/+$/, '').split('/');
if(parts.some((s)=>s === '' || s === '.' || s === '..' || s.toLowerCase() === '.git'))
throw new GitError('G08', 'Ungültiger Ordner.');
return parts.join('/');
};
// `git check-ref-format` auf refs/heads/<name> (nicht --branch: das expandiert z. B. "@{-1}").
export const validateBranch = (name)=>new Promise((resolve, reject)=>{
const bad = ()=>reject(new GitError('G08', 'Ungültiger Branch-Name.'));
if(typeof name !== 'string' || !name || name.length > 255 || name.startsWith('-') || /[\0-\x1f]/.test(name)) return bad();
execFile('git', ['check-ref-format', `refs/heads/${name}`], { timeout: 5000 }, (err)=>err ? bad() : resolve(name));
});
export const slugify = (title)=>{
const s = String(title || '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
return s || 'brew';
};