import { randomUUID } from 'crypto'; import { nanoid } from 'nanoid'; 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, editId: nanoid(12), shareId: nanoid(12) }); // wie newBrew im Upstream 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, editId: nanoid(12), shareId: nanoid(12) }); 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 first = await loadEditableBrew(editId, account); return svc.locks.withKey(first.id, async ()=>{ // Brew und Link unter dem Lock neu lesen, damit ein gleichzeitiger Save nicht überschrieben wird const brew = await loadEditableBrew(editId, account); 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 };