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:
1 parent
d2801b2d6c
commit
fe9efc155e
18 files changed
+1837
-9
No files matched your search
@@ -36,6 +36,7 @@ import dbCheck from './middleware/dbCheck.js';
|
||||
|
||||
import { readAuthConfig, accountMiddleware, createAuthRouter, clientConfig as authClientConfig } from './fork/auth/index.js';
|
||||
import { getStorage } from './storage/index.js';
|
||||
import { createGitBackend } from './fork/git/index.js';
|
||||
|
||||
import cors from 'cors';
|
||||
|
||||
@@ -123,6 +124,9 @@ export default async function createApp(vite) {
|
||||
brewAuthorExists : (name)=>getStorage().brews.existsAuthor(name)
|
||||
}));
|
||||
|
||||
// Fork: Git-Backend (ADR 0003): /api/git/* und Abgleich bei GET /edit/:id, vor pageRoutes
|
||||
app.use(createGitBackend({ getStorage, api, splitTextStyleAndMetadata }).router);
|
||||
|
||||
app.use(homebrewApi);
|
||||
app.use(adminApi(vite));
|
||||
app.use(vaultApi);
|
||||
|
||||
@@ -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 };
|
||||
@@ -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
|
||||
};
|
||||
};
|
||||
@@ -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 };
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -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***@');
|
||||
};
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
@@ -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 };
|
||||
@@ -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 }) };
|
||||
};
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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 };
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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';
|
||||
};
|
||||
+10
-6
@@ -13,6 +13,7 @@ import { splitTextStyleAndMetadata,
|
||||
brewSnippetsToJSON, debugTextMismatch } from '../shared/helpers.js';
|
||||
import checkClientVersion from './middleware/check-client-version.js';
|
||||
import dbCheck from './middleware/dbCheck.js';
|
||||
import { beforeBrewSave as gitBeforeBrewSave, afterBrewSave as gitAfterBrewSave } from './fork/git/hooks.js'; // [fork] ADR-0003
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
@@ -270,7 +271,7 @@ const api = {
|
||||
newHomebrew = api.excludeStubProps(newHomebrew);
|
||||
newHomebrew.googleId = googleId;
|
||||
}
|
||||
|
||||
|
||||
// [fork] ADR-0002
|
||||
saved = await getStorage().brews.create(newHomebrew)
|
||||
.catch((err)=>{
|
||||
@@ -400,18 +401,20 @@ const api = {
|
||||
brew.invitedAuthors = _.uniq(_.filter(brew.invitedAuthors, (a)=>req.account.username !== a));
|
||||
}
|
||||
|
||||
// [fork] ADR-0003: Git-Commit vor dem DB-Save; bei null wurde schon geantwortet (z. B. Konflikt G01)
|
||||
const gitCtx = await gitBeforeBrewSave({ brew, req, res });
|
||||
if(!gitCtx) return;
|
||||
|
||||
//=====----- Update to or remove from Google Drive -----=========//
|
||||
const originalGoogleId = brew.googleId;
|
||||
const { saveToGoogle, removeFromGoogle } = req.query;
|
||||
|
||||
if(brew.googleId && removeFromGoogle) { // If removing from google, remove the brew's googleId
|
||||
brew.googleId = undefined;
|
||||
}
|
||||
else if(!brew.googleId && saveToGoogle) { // If adding to google, create new google document and record the googleId
|
||||
} else if(!brew.googleId && saveToGoogle) { // If adding to google, create new google document and record the googleId
|
||||
brew.googleId = await api.newGoogleBrew(req.account, brew, res);
|
||||
if(!brew.googleId) return;
|
||||
}
|
||||
else if(brew.googleId) { // If already on google, update the google brew
|
||||
} else if(brew.googleId) { // If already on google, update the google brew
|
||||
const updated = await GoogleActions.updateGoogleBrew(api.excludeGoogleProps(brew), req.ip);
|
||||
if(!updated) return;
|
||||
}
|
||||
@@ -433,6 +436,7 @@ const api = {
|
||||
res.status(err.status || 500).send(err.message || 'Unable to save brew to Homebrewery database');
|
||||
});
|
||||
|
||||
await gitAfterBrewSave(gitCtx, saved); // [fork] ADR-0003
|
||||
if(!saved) return;
|
||||
|
||||
if(originalGoogleId && removeFromGoogle) {
|
||||
@@ -471,7 +475,7 @@ const api = {
|
||||
throw (err);
|
||||
}
|
||||
|
||||
let brew = req.brew;
|
||||
const brew = req.brew;
|
||||
const { googleId, editId } = brew;
|
||||
const account = req.account;
|
||||
const isOwner = account && (brew.authors.length === 0 || brew.authors[0] === account.username);
|
||||
|
||||
@@ -92,9 +92,8 @@ export const createGitConnectionRepository = (db)=>({
|
||||
export const createBrewGitLinkRepository = (db)=>({
|
||||
// Legt den Link an oder ersetzt ihn (höchstens einer pro Brew)
|
||||
async upsert({ brewId, ...rest }) {
|
||||
const row = { brew_id: brewId, ...toRow(LINK, rest) };
|
||||
const { brew_id, ...set } = row;
|
||||
return rowToLink(await db.insertInto('brew_git_links').values(row)
|
||||
const set = toRow(LINK, rest);
|
||||
return rowToLink(await db.insertInto('brew_git_links').values({ brew_id: brewId, ...set })
|
||||
.onConflict((oc)=>oc.column('brew_id').doUpdateSet(set)).returningAll().executeTakeFirstOrThrow());
|
||||
},
|
||||
async findByBrewId(brewId) {
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
// Integration ohne Netz und ohne Datenbank (ADR 0003, "Tests"): echtes `git` gegen einen lokalen
|
||||
// `git http-backend` mit Basic-Auth, Storage im Speicher. Die DB-Varianten laufen in git-backend.db.test.js.
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import express from 'express';
|
||||
import supertest from 'supertest';
|
||||
import api from '../../server/homebrew.api.js';
|
||||
import { splitTextStyleAndMetadata } from '../../shared/helpers.js';
|
||||
import { readGitConfig } from '../../server/fork/git/config.js';
|
||||
import { createGitService } from '../../server/fork/git/brewSync.js';
|
||||
import { createGitRouter } from '../../server/fork/git/routes.js';
|
||||
import { createTokenCrypto } from '../../server/fork/git/crypto.js';
|
||||
import { createGitClient } from '../../server/fork/git/gitClient.js';
|
||||
import packageJSON from '../../package.json' with { type: 'json' };
|
||||
import { startGitHttpServer } from './git-http-test-server.js';
|
||||
import { createMemoryStorage } from './git-memory-storage.js';
|
||||
|
||||
const silent = process.env.GIT_TEST_LOG ? console : { warn: ()=>{}, error: ()=>{}, log: ()=>{} };
|
||||
const version = { 'Homebrewery-Version': packageJSON.version };
|
||||
const asAccount = (a)=>({ 'x-account': JSON.stringify(a) });
|
||||
|
||||
const KEY = crypto.randomBytes(32).toString('base64');
|
||||
let remote; let storage; let svc; let request; let workdir; let alice; let bob; let cfg;
|
||||
const ALICE = ()=>({ username: 'alice', uid: alice.id });
|
||||
const NC = { username: 'carol' }; // naturalcrit-Konto ohne uid
|
||||
|
||||
const build = (overrides = {}, serviceOverrides = {})=>{
|
||||
cfg = { ...readGitConfig({ HB_GIT_TOKEN_KEY: KEY, HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_WORKDIR: workdir }),
|
||||
allowHttp : true, allowPrivate : true, openTimeoutMs : 1000, timeoutMs : 5000, ...overrides };
|
||||
svc = createGitService({ cfg, getStorage: ()=>storage, api, splitTextStyleAndMetadata, logger: silent, ...serviceOverrides });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, res, next)=>{ if(req.headers['x-account']) req.account = JSON.parse(req.headers['x-account']); next(); });
|
||||
app.use(createGitRouter(svc, { logger: silent }));
|
||||
app.get('/edit/:id', (req, res)=>res.send('editor'));
|
||||
request = supertest(app);
|
||||
};
|
||||
|
||||
const newConn = async (extra = {})=>{
|
||||
const { url } = remote.createRepo(`r${Math.random().toString(36).slice(2)}.git`);
|
||||
const res = await request.post('/api/git/connections').set(version).set(asAccount(ALICE()))
|
||||
.send({ label: 'Test', repoUrl: url, authUsername: remote.username, token: remote.token, ...extra });
|
||||
expect(res.status).toBe(201);
|
||||
return { url, dir: path.join(remote.dirRoot ?? '', ''), conn: res.body };
|
||||
};
|
||||
|
||||
const repoDir = (url)=>{ const name = new URL(url).pathname.slice(1); return remote.dirOf(name); };
|
||||
|
||||
const leftovers = ()=>{
|
||||
const procs = fs.readdirSync('/proc').filter((p)=>/^\d+$/.test(p)).filter((p)=>{
|
||||
try { return fs.readlinkSync(`/proc/${p}/cwd`).startsWith(workdir); } catch { return false; }
|
||||
});
|
||||
return { procs, dirs: fs.existsSync(workdir) ? fs.readdirSync(workdir) : [] };
|
||||
};
|
||||
|
||||
beforeAll(async ()=>{
|
||||
remote = await startGitHttpServer();
|
||||
workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-work-'));
|
||||
});
|
||||
afterAll(async ()=>{
|
||||
await remote.close();
|
||||
fs.rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async ()=>{
|
||||
storage = createMemoryStorage();
|
||||
alice = await storage.users.create({ username: 'alice', displayName: 'Alice A.' });
|
||||
bob = await storage.users.create({ username: 'bob' });
|
||||
build();
|
||||
});
|
||||
|
||||
describe('Verbindungen', ()=>{
|
||||
test('Token wird verschlüsselt gespeichert und nie ausgeliefert oder geloggt', async ()=>{
|
||||
const logs = [];
|
||||
build({}, { logger: { warn: (...a)=>logs.push(a.join(' ')), error: (...a)=>logs.push(a.join(' ')) } });
|
||||
const { conn } = await newConn();
|
||||
expect(conn).toMatchObject({ hasToken: true, defaultBranch: 'main', brewDir: 'brews', assetsDir: 'assets' });
|
||||
expect(JSON.stringify(conn)).not.toContain(remote.token);
|
||||
expect(conn.tokenEnc).toBeUndefined();
|
||||
const stored = await storage.gitConnections.findById(conn.id);
|
||||
expect(stored.tokenEnc).toMatch(/^v1\./);
|
||||
expect(stored.tokenEnc).not.toContain(remote.token);
|
||||
|
||||
const list = await request.get('/api/git/connections').set(version).set(asAccount(ALICE()));
|
||||
expect(JSON.stringify(list.body)).not.toContain(remote.token);
|
||||
expect(list.body).toHaveLength(1);
|
||||
|
||||
// Fehlerfall mit falschem Token: weder Antwort noch Log enthalten ihn
|
||||
await request.patch(`/api/git/connections/${conn.id}`).set(version).set(asAccount(ALICE())).send({ token: 'falscher-token-xyz' });
|
||||
const test = await request.post(`/api/git/connections/${conn.id}/test`).set(version).set(asAccount(ALICE()));
|
||||
expect(test.status).toBe(502);
|
||||
expect(test.body.HBErrorCode).toBe('G02');
|
||||
expect(JSON.stringify(test.body)).not.toContain('falscher-token-xyz');
|
||||
expect(logs.join('\n')).not.toContain('falscher-token-xyz');
|
||||
expect(logs.join('\n')).not.toContain(remote.token);
|
||||
});
|
||||
|
||||
test('Test-Button, Branches und Dateiliste', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const dir = repoDir(url);
|
||||
remote.commitFile(dir, 'main', 'brews/eins.md', 'x');
|
||||
remote.commitFile(dir, 'dev', 'brews/zwei.md', 'y');
|
||||
const a = asAccount(ALICE());
|
||||
const t = await request.post(`/api/git/connections/${conn.id}/test`).set(version).set(a);
|
||||
expect(t.body).toMatchObject({ ok: true, branchCount: 2 });
|
||||
const b = await request.get(`/api/git/connections/${conn.id}/branches`).set(version).set(a);
|
||||
expect(b.body.branches).toEqual(['dev', 'main']);
|
||||
const f = await request.get(`/api/git/connections/${conn.id}/files`).query({ branch: 'dev', dir: 'brews' }).set(version).set(a);
|
||||
expect(f.body.files).toEqual(['brews/zwei.md']);
|
||||
const nope = await request.get(`/api/git/connections/${conn.id}/files`).query({ branch: 'gibtsnicht' }).set(version).set(a);
|
||||
expect(nope.body.HBErrorCode).toBe('G03');
|
||||
});
|
||||
|
||||
test('Verbindungen sind pro Benutzer: fremde Verbindung → 404', async ()=>{
|
||||
const { conn } = await newConn();
|
||||
const other = { username: 'bob', uid: bob.id };
|
||||
const res = await request.delete(`/api/git/connections/${conn.id}`).set(version).set(asAccount(other));
|
||||
expect(res.status).toBe(404);
|
||||
expect((await request.get('/api/git/connections').set(version).set(asAccount(other))).body).toEqual([]);
|
||||
expect((await request.delete(`/api/git/connections/${conn.id}`).set(version).set(asAccount(ALICE()))).status).toBe(204);
|
||||
});
|
||||
|
||||
test('ungültige Eingaben: URL mit Zugangsdaten, SSRF-Ziel, fehlender Token', async ()=>{
|
||||
build({ allowPrivate: false, allowHttp: false });
|
||||
const post = (body)=>request.post('/api/git/connections').set(version).set(asAccount(ALICE())).send(body);
|
||||
expect((await post({ label: 'x', repoUrl: 'https://u:p@git.example.test/a/b', token: 't' })).body.HBErrorCode).toBe('G08');
|
||||
expect((await post({ label: 'x', repoUrl: 'https://127.0.0.1/a/b', token: 't' })).body.HBErrorCode).toBe('G08');
|
||||
expect((await post({ label: 'x', repoUrl: 'https://169.254.169.254/latest', token: 't' })).status).toBe(400);
|
||||
expect((await post({ label: 'x', repoUrl: 'http://git.example.test/a/b', token: 't' })).status).toBe(400);
|
||||
build({ allowedHosts: ['git.example.test'] });
|
||||
expect((await post({ label: 'x', repoUrl: 'https://anderer.example.test/a/b', token: 't' })).status).toBe(400);
|
||||
expect((await post({ label: 'x', repoUrl: 'https://git.example.test/a/b' })).status).toBe(400);
|
||||
expect((await post({ label: '', repoUrl: 'https://git.example.test/a/b', token: 't' })).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Zugriffsregeln', ()=>{
|
||||
test('ohne Schlüssel: 503; ohne OIDC-uid: 403 G07; Status/Pull brauchen nur Bearbeitungsrecht', async ()=>{
|
||||
build({ enabled: false, key: undefined });
|
||||
const off = await request.get('/api/git/connections').set(version).set(asAccount(ALICE()));
|
||||
expect(off.status).toBe(503);
|
||||
build();
|
||||
for (const [method, url] of [['get', '/api/git/connections'], ['post', '/api/git/connections'], ['post', '/api/git/brews'], ['post', '/api/git/brews/import'], ['post', '/api/git/brews/abc/link'], ['delete', '/api/git/brews/abc/link']]) {
|
||||
const res = await request[method](url).set(version).set(asAccount(NC)).send({});
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([403, 'G07']);
|
||||
}
|
||||
const anon = await request.get('/api/git/connections').set(version);
|
||||
expect([anon.status, anon.body.HBErrorCode]).toEqual([403, 'G07']);
|
||||
|
||||
// Status und Pull mit Bearbeitungsrecht (naturalcrit-Mitautor)
|
||||
const { conn } = await newConn();
|
||||
const brew = await storage.brews.create({ title: 'T', text: 'Hallo', authors: ['alice', 'carol'] });
|
||||
await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'brews/t.md' }).expect(200);
|
||||
const st = await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(NC));
|
||||
expect(st.status).toBe(200);
|
||||
expect(st.body).toMatchObject({ linked: true, branch: 'main', path: 'brews/t.md', isConnectionOwner: false });
|
||||
expect((await request.post(`/api/git/brews/${brew.editId}/pull`).set(version).set(asAccount(NC))).status).toBe(200);
|
||||
// ohne Bearbeitungsrecht
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount({ username: 'dave' }))).status).toBe(401);
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version)).status).toBe(401);
|
||||
// Lösen darf nur der Besitzer der Verbindung
|
||||
expect((await request.delete(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount({ username: 'bob', uid: bob.id }))).status).toBe(401);
|
||||
});
|
||||
|
||||
test('Client-Version wird geprüft', async ()=>{
|
||||
const res = await request.get('/api/git/connections').set(asAccount(ALICE()));
|
||||
expect(res.status).toBe(412);
|
||||
});
|
||||
|
||||
test('fremde Verbindung kann nicht zum Verknüpfen genutzt werden', async ()=>{
|
||||
const { conn } = await newConn();
|
||||
const brew = await storage.brews.create({ title: 'B', text: 'x', authors: ['bob'] });
|
||||
const res = await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount({ username: 'bob', uid: bob.id })).send({ connectionId: conn.id, path: 'a.md' });
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Brew anlegen, importieren, verknüpfen', ()=>{
|
||||
test('Root-Commit in leerem Repo, Autor = Benutzer, Committer = Homebrewery', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const res = await request.post('/api/git/brews').set(version).set(asAccount(ALICE()))
|
||||
.send({ connectionId: conn.id, brew: { title: 'Mein Brew', text: '# Hallo\n', renderer: 'V3' } });
|
||||
expect(res.status).toBe(200);
|
||||
const dir = repoDir(url);
|
||||
const file = remote.readFile(dir, 'main', 'brews/mein-brew.md');
|
||||
expect(file).toContain('```metadata');
|
||||
expect(file).toContain('# Hallo');
|
||||
expect(remote.log(dir, 'main')).toEqual(['Alice A.|Homebrewery|Create brews/mein-brew.md via Homebrewery']);
|
||||
const link = await storage.brewGitLinks.findByBrewId(res.body.id);
|
||||
expect(link).toMatchObject({ branch: 'main', path: 'brews/mein-brew.md', lastCommitSha: remote.head(dir, 'main'), lastError: null });
|
||||
expect(res.body.authors).toEqual(['alice']);
|
||||
// existierende Datei → G06
|
||||
const dup = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'brews/mein-brew.md', brew: { title: 'x', text: 'y' } });
|
||||
expect([dup.status, dup.body.HBErrorCode]).toEqual([409, 'G06']);
|
||||
});
|
||||
|
||||
test('neuer Branch in nicht leerem Repo setzt auf default_branch auf', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const dir = repoDir(url);
|
||||
const base = remote.commitFile(dir, 'main', 'README.md', 'hi');
|
||||
const res = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'neu', brew: { title: 'Auf Branch', text: 'x' } });
|
||||
expect(res.status).toBe(200);
|
||||
expect(remote.log(dir, 'neu')).toHaveLength(2);
|
||||
expect(remote.readFile(dir, 'neu', 'README.md')).toBe('hi');
|
||||
expect(remote.head(dir, 'main')).toBe(base);
|
||||
});
|
||||
|
||||
test('Import liest eine vorhandene Datei, Doppel-Import → G06', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const dir = repoDir(url);
|
||||
remote.commitFile(dir, 'main', 'brews/alt.md', '```metadata\ntitle: Alt\ndescription: D\nrenderer: V3\n```\n\n# Text\n');
|
||||
const res = await request.post('/api/git/brews/import').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'main', path: 'brews/alt.md' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ title: 'Alt', description: 'D', renderer: 'V3', authors: ['alice'] });
|
||||
expect(res.body.text).toContain('# Text');
|
||||
const link = await storage.brewGitLinks.findByBrewId(res.body.id);
|
||||
expect(link.lastBlobSha).toMatch(/^[0-9a-f]{40}$/);
|
||||
const again = await request.post('/api/git/brews/import').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'main', path: 'brews/alt.md' });
|
||||
expect(again.body.HBErrorCode).toBe('G06');
|
||||
const missing = await request.post('/api/git/brews/import').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'main', path: 'brews/fehlt.md' });
|
||||
expect(missing.body.HBErrorCode).toBe('G03');
|
||||
});
|
||||
|
||||
test('Pfad-Validierung und Google-Brews', async ()=>{
|
||||
const { conn } = await newConn();
|
||||
for (const bad of ['../x.md', '/x.md', '.git/x.md', 'x.txt']) {
|
||||
const res = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: bad, brew: { title: 't', text: 'x' } });
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([400, 'G08']);
|
||||
}
|
||||
const g = await storage.brews.create({ title: 'G', text: 'x', authors: ['alice'], googleId: '1abc' });
|
||||
const res = await request.post(`/api/git/brews/${g.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'g.md' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
test('Lösen der Verknüpfung lässt Brew und Datei bestehen', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const brew = await storage.brews.create({ title: 'T', text: 'Hallo', authors: ['alice'] });
|
||||
await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: conn.id }).expect(200);
|
||||
expect(remote.readFile(repoDir(url), 'main', 'brews/t.md')).toBe('Hallo');
|
||||
await request.delete(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).expect(204);
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(ALICE()))).body).toEqual({ linked: false });
|
||||
expect(await storage.brews.findByEditId(brew.editId)).not.toBeNull();
|
||||
expect(remote.readFile(repoDir(url), 'main', 'brews/t.md')).toBe('Hallo');
|
||||
});
|
||||
});
|
||||
|
||||
// Hilfsfunktion: verknüpften Brew anlegen und Speichern über den Hook simulieren
|
||||
const linked = async (text = 'Version 1')=>{
|
||||
const { url, conn } = await newConn();
|
||||
const created = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'brews/b.md', brew: { title: 'B', text } });
|
||||
const dir = repoDir(url);
|
||||
const brew = await storage.brews.findByEditId(created.body.editId);
|
||||
const fakeRes = ()=>{ const r = { status(c) { r.code = c; return r; }, json(b) { r.body = b; return r; } }; return r; };
|
||||
const save = async (newText, query = {}, account = ALICE())=>{
|
||||
const res = fakeRes();
|
||||
const current = await storage.brews.findByEditId(brew.editId);
|
||||
const ctx = await svc.beforeBrewSave({ brew: { ...current, text: newText }, req: { query, account }, res });
|
||||
if(ctx) {
|
||||
const saved = await storage.brews.update({ ...current, text: newText, version: current.version + 1 });
|
||||
await svc.afterBrewSave(ctx, saved);
|
||||
}
|
||||
return { ctx, res };
|
||||
};
|
||||
return { url, dir, conn, brew, save };
|
||||
};
|
||||
|
||||
describe('Speichern (Hook beforeBrewSave/afterBrewSave)', ()=>{
|
||||
test('Save erzeugt einen Commit und aktualisiert den Link', async ()=>{
|
||||
const { dir, brew, save } = await linked();
|
||||
const { ctx } = await save('Version 2');
|
||||
expect(ctx.git.commit).toBe(remote.head(dir, 'main'));
|
||||
expect(remote.readFile(dir, 'main', 'brews/b.md')).toBe('Version 2');
|
||||
expect(remote.log(dir, 'main')[0]).toBe('Alice A.|Homebrewery|Update brews/b.md via Homebrewery');
|
||||
const link = await storage.brewGitLinks.findByBrewId(brew.id);
|
||||
expect(link).toMatchObject({ lastCommitSha: ctx.git.commit, lastBlobSha: ctx.git.blob, lastError: null });
|
||||
expect(svc.locks.keyCount).toBe(0);
|
||||
});
|
||||
|
||||
test('unveränderter Inhalt erzeugt keinen leeren Commit', async ()=>{
|
||||
const { dir, brew, save } = await linked('gleich');
|
||||
const before = remote.head(dir, 'main');
|
||||
await save((await storage.brews.findByEditId(brew.editId)).text);
|
||||
expect(remote.head(dir, 'main')).toBe(before);
|
||||
});
|
||||
|
||||
test('fremder Commit auf anderer Datei ist kein Konflikt', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
remote.commitFile(dir, 'main', 'andere.md', 'fremd');
|
||||
const { res, ctx } = await save('Version 2');
|
||||
expect(res.code).toBeUndefined();
|
||||
expect(ctx.git.commit).toBe(remote.head(dir, 'main'));
|
||||
expect(remote.readFile(dir, 'main', 'andere.md')).toBe('fremd'); // nichts überschrieben
|
||||
expect(remote.log(dir, 'main')).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('fremder Commit auf derselben Datei → 409 G01, weder Git noch DB ändern sich', async ()=>{
|
||||
const { dir, brew, save } = await linked();
|
||||
const foreign = remote.commitFile(dir, 'main', 'brews/b.md', 'Fremde Version');
|
||||
const linkBefore = await storage.brewGitLinks.findByBrewId(brew.id);
|
||||
const { ctx, res } = await save('Meine Version');
|
||||
expect(ctx).toBeNull();
|
||||
expect(res.code).toBe(409);
|
||||
expect(res.body).toMatchObject({ HBErrorCode: 'G01', remoteCommitSha: foreign });
|
||||
expect(res.body.remoteBlobSha).toMatch(/^[0-9a-f]{40}$/);
|
||||
expect(remote.head(dir, 'main')).toBe(foreign);
|
||||
expect((await storage.brews.findByEditId(brew.editId)).text).toContain('Version 1');
|
||||
expect(await storage.brewGitLinks.findByBrewId(brew.id)).toEqual(linkBefore);
|
||||
expect(svc.locks.keyCount).toBe(0); // Mutex trotz Fehler freigegeben
|
||||
});
|
||||
|
||||
test('gitOverwrite=<remoteBlob>: normaler Commit auf dem neuen Stand, fremde Historie bleibt', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Fremde Version');
|
||||
const conflict = (await save('Meine Version')).res.body;
|
||||
const { ctx, res } = await save('Meine Version', { gitOverwrite: conflict.remoteBlobSha });
|
||||
expect(res.code).toBeUndefined();
|
||||
expect(remote.readFile(dir, 'main', 'brews/b.md')).toBe('Meine Version');
|
||||
const log = remote.log(dir, 'main');
|
||||
expect(log).toHaveLength(3);
|
||||
expect(log[1]).toBe('Dritter|Dritter|extern');
|
||||
expect(ctx.git.commit).toBe(remote.head(dir, 'main'));
|
||||
// falsche Overwrite-ID gilt nicht
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Noch fremder');
|
||||
expect((await save('Meine Version 2', { gitOverwrite: conflict.remoteBlobSha })).res.code).toBe(409);
|
||||
});
|
||||
|
||||
test('Push-Rennen: Non-Fast-Forward führt zu erneutem Versuch (max. 3), dann G05', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
const real = createGitClient(cfg);
|
||||
let raced = 0;
|
||||
build({}, { client: { ...real, fetchHead: async (...a)=>{ const h = await real.fetchHead(...a); if(raced < 1) { raced++; remote.commitFile(dir, 'main', `race${raced}.md`, 'x'); } return h; } } });
|
||||
const res1 = await save('Nach Rennen');
|
||||
expect(res1.res.code).toBeUndefined();
|
||||
expect(raced).toBe(1);
|
||||
expect(remote.readFile(dir, 'main', 'brews/b.md')).toBe('Nach Rennen');
|
||||
expect(remote.readFile(dir, 'main', 'race1.md')).toBe('x');
|
||||
|
||||
// dauerhaft verlorenes Rennen → 503 G05
|
||||
build({}, { client: { ...real, fetchHead: async (...a)=>{ const h = await real.fetchHead(...a); raced++; remote.commitFile(dir, 'main', `race${raced}.md`, 'x'); return h; } } });
|
||||
const res2 = await save('Nie');
|
||||
expect([res2.res.code, res2.res.body.HBErrorCode]).toEqual([503, 'G05']);
|
||||
expect(raced).toBe(4);
|
||||
});
|
||||
|
||||
test('falscher Token → 502 G02, DB unverändert', async ()=>{
|
||||
const { brew, conn, save } = await linked();
|
||||
await storage.gitConnections.update(conn.id, { tokenEnc: createTokenCrypto({ key: cfg.key }).encrypt('kaputt', conn.id) });
|
||||
const { res } = await save('X');
|
||||
expect([res.code, res.body.HBErrorCode]).toEqual([502, 'G02']);
|
||||
expect(JSON.stringify(res.body)).not.toContain(remote.token);
|
||||
expect((await storage.brews.findByEditId(brew.editId)).text).toContain('Version 1');
|
||||
});
|
||||
|
||||
test('saveToGoogle bei Git-Brew → 400', async ()=>{
|
||||
const { save } = await linked();
|
||||
const { res } = await save('X', { saveToGoogle: 'true' });
|
||||
expect([res.code, res.body.HBErrorCode]).toEqual([400, 'G08']);
|
||||
});
|
||||
|
||||
test('Mitautor ohne uid speichert mit dem Token des Verbindungsbesitzers', async ()=>{
|
||||
const { dir, brew, save } = await linked();
|
||||
await storage.brews.update({ ...(await storage.brews.findByEditId(brew.editId)), authors: ['alice', 'carol'] });
|
||||
const { res } = await save('Von Carol', {}, NC);
|
||||
expect(res.code).toBeUndefined();
|
||||
expect(remote.log(dir, 'main')[0]).toBe('carol|Homebrewery|Update brews/b.md via Homebrewery');
|
||||
});
|
||||
|
||||
test('gleichzeitige Saves desselben Brews werden serialisiert (kein falscher Konflikt)', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
const [a, b] = await Promise.all([save('Parallel A'), save('Parallel B')]);
|
||||
expect([a.res.code, b.res.code]).toEqual([undefined, undefined]);
|
||||
expect(remote.log(dir, 'main')).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('zu große Datei → 413 G09', async ()=>{
|
||||
build({ maxFileBytes: 100 });
|
||||
const { res } = await (async ()=>{
|
||||
const { conn } = await newConn();
|
||||
return { res: await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, brew: { title: 'Groß', text: 'x'.repeat(500) } }) };
|
||||
})();
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([413, 'G09']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pull und Abgleich beim Öffnen', ()=>{
|
||||
test('Pull übernimmt den Remote-Stand in den Snapshot (Version + 1)', async ()=>{
|
||||
const { dir, brew } = await linked();
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', '```metadata\ntitle: Neu von außen\n```\n\nRemote-Text\n');
|
||||
const res = await request.post(`/api/git/brews/${brew.editId}/pull`).set(version).set(asAccount(ALICE()));
|
||||
expect(res.status).toBe(200);
|
||||
const after = await storage.brews.findByEditId(brew.editId);
|
||||
expect(after).toMatchObject({ title: 'Neu von außen', version: brew.version + 1 });
|
||||
expect(after.text).toContain('Remote-Text');
|
||||
expect(res.body).toMatchObject({ linked: true, lastCommitSha: remote.head(dir, 'main'), lastError: null });
|
||||
});
|
||||
|
||||
test('Öffnen holt externe Änderungen, ohne Änderung bleibt der Snapshot', async ()=>{
|
||||
const { dir, brew } = await linked();
|
||||
const a = asAccount(ALICE());
|
||||
await request.get(`/edit/${brew.editId}`).set(a).expect(200);
|
||||
expect((await storage.brews.findByEditId(brew.editId)).version).toBe(brew.version);
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Extern geändert');
|
||||
await request.get(`/edit/${brew.editId}`).set(a).expect(200);
|
||||
const after = await storage.brews.findByEditId(brew.editId);
|
||||
expect(after.text).toBe('Extern geändert');
|
||||
expect(after.version).toBe(brew.version + 1);
|
||||
});
|
||||
|
||||
test('hängender Server: Editor öffnet nach höchstens HB_GIT_OPEN_TIMEOUT_MS + 500 ms, last_error=G04, keine Reste', async ()=>{
|
||||
const { brew } = await linked();
|
||||
remote.setHang(true);
|
||||
const t0 = Date.now();
|
||||
const res = await request.get(`/edit/${brew.editId}`).set(asAccount(ALICE()));
|
||||
const took = Date.now() - t0;
|
||||
remote.setHang(false);
|
||||
expect(res.status).toBe(200);
|
||||
expect(took).toBeLessThan(cfg.openTimeoutMs + 500);
|
||||
const link = await storage.brewGitLinks.findByBrewId(brew.id);
|
||||
expect(link.lastError).toBe('G04');
|
||||
expect((await storage.brews.findByEditId(brew.editId)).text).toContain('Version 1');
|
||||
const left = leftovers();
|
||||
expect(left.procs).toEqual([]);
|
||||
expect(left.dirs).toEqual([]);
|
||||
expect(svc.locks.keyCount).toBe(0);
|
||||
// der Status zeigt den Fehler, ein späterer Abgleich löscht ihn
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(ALICE()))).body.lastError).toBe('G04');
|
||||
await request.get(`/edit/${brew.editId}`).set(asAccount(ALICE())).expect(200);
|
||||
expect((await storage.brewGitLinks.findByBrewId(brew.id)).lastError).toBeNull();
|
||||
});
|
||||
|
||||
test('Abgleich ohne Anmeldung oder Bearbeitungsrecht greift nicht auf Git zu', async ()=>{
|
||||
const { brew } = await linked();
|
||||
remote.requests.length = 0;
|
||||
await request.get(`/edit/${brew.editId}`).expect(200);
|
||||
await request.get(`/edit/${brew.editId}`).set(asAccount({ username: 'dave' })).expect(200);
|
||||
expect(remote.requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Aufräumen', ()=>{
|
||||
test('nach allen Operationen bleiben weder git-Prozesse noch temporäre Verzeichnisse', ()=>{
|
||||
const left = leftovers();
|
||||
expect(left.procs).toEqual([]);
|
||||
expect(left.dirs).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
// Lokales Git-Remote für Tests (ADR 0003, "Tests"): `git http-backend` hinter einem kleinen Node-HTTP-Server mit
|
||||
// Basic-Auth-Prüfung. Repos liegen als Bare-Repos mit uploadpack.allowFilter=true und http.receivepack=true.
|
||||
import http from 'http';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { execFileSync, spawn } from 'child_process';
|
||||
|
||||
const git = (args, opts = {})=>execFileSync('git', args, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], ...opts }).trim();
|
||||
|
||||
export const startGitHttpServer = async ({ username = 'tester', token = 'secret-token-123' } = {})=>{
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-remote-'));
|
||||
let hang = false;
|
||||
const requests = [];
|
||||
|
||||
const server = http.createServer((req, res)=>{
|
||||
requests.push(`${req.method} ${req.url}`);
|
||||
if(hang) return; // antwortet nie
|
||||
const auth = req.headers.authorization;
|
||||
const expected = `Basic ${Buffer.from(`${username}:${token}`).toString('base64')}`;
|
||||
if(auth !== expected) {
|
||||
res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="git"' });
|
||||
return res.end('unauthorized');
|
||||
}
|
||||
const url = new URL(req.url, 'http://x');
|
||||
const chunks = [];
|
||||
req.on('data', (c)=>chunks.push(c));
|
||||
req.on('end', ()=>{
|
||||
const body = Buffer.concat(chunks);
|
||||
const cgi = spawn('git', ['http-backend'], {
|
||||
env : {
|
||||
PATH : process.env.PATH,
|
||||
GIT_PROJECT_ROOT : root,
|
||||
GIT_HTTP_EXPORT_ALL : '1',
|
||||
REQUEST_METHOD : req.method,
|
||||
PATH_INFO : url.pathname,
|
||||
QUERY_STRING : url.search.slice(1),
|
||||
CONTENT_TYPE : req.headers['content-type'] || '',
|
||||
CONTENT_LENGTH : String(body.length),
|
||||
REMOTE_USER : username,
|
||||
REMOTE_ADDR : '127.0.0.1',
|
||||
HTTP_CONTENT_ENCODING : req.headers['content-encoding'] || '',
|
||||
HTTP_GIT_PROTOCOL : req.headers['git-protocol'] || ''
|
||||
}
|
||||
});
|
||||
cgi.stdin.on('error', ()=>{});
|
||||
cgi.stdin.end(body);
|
||||
const out = [];
|
||||
cgi.stdout.on('data', (c)=>out.push(c));
|
||||
cgi.on('close', ()=>{
|
||||
const buf = Buffer.concat(out);
|
||||
const sep = buf.indexOf('\r\n\r\n');
|
||||
if(sep < 0) { res.writeHead(500); return res.end(); }
|
||||
const headers = {};
|
||||
let status = 200;
|
||||
for (const line of buf.subarray(0, sep).toString().split('\r\n')) {
|
||||
const i = line.indexOf(':');
|
||||
if(i < 0) continue;
|
||||
const k = line.slice(0, i).trim();
|
||||
const v = line.slice(i + 1).trim();
|
||||
if(k.toLowerCase() === 'status') status = parseInt(v, 10); else headers[k] = v;
|
||||
}
|
||||
res.writeHead(status, headers);
|
||||
res.end(buf.subarray(sep + 4));
|
||||
});
|
||||
});
|
||||
});
|
||||
await new Promise((resolve)=>server.listen(0, '127.0.0.1', resolve));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
|
||||
return {
|
||||
base, username, token, requests, root,
|
||||
dirOf : (name)=>path.join(root, name),
|
||||
setHang : (v)=>{ hang = v; },
|
||||
// Legt ein leeres Bare-Repo an und liefert URL + Pfad
|
||||
createRepo : (name = 'r.git')=>{
|
||||
const dir = path.join(root, name);
|
||||
git(['init', '--bare', '-q', '-b', 'main', dir]);
|
||||
git(['-C', dir, 'config', 'uploadpack.allowFilter', 'true']);
|
||||
git(['-C', dir, 'config', 'uploadpack.allowAnySHA1InWant', 'true']);
|
||||
git(['-C', dir, 'config', 'http.receivepack', 'true']);
|
||||
return { url: `${base}/${name}`, dir };
|
||||
},
|
||||
// Commit direkt im Bare-Repo (simuliert Push eines Dritten). Liefert die Commit-ID.
|
||||
commitFile : (dir, branch, filePath, content, message = 'extern')=>{
|
||||
const env = { ...process.env, GIT_AUTHOR_NAME: 'Dritter', GIT_AUTHOR_EMAIL: 'd@example.test', GIT_COMMITTER_NAME: 'Dritter', GIT_COMMITTER_EMAIL: 'd@example.test', GIT_INDEX_FILE: path.join(dir, 'tmp-idx') };
|
||||
let parent;
|
||||
try { parent = git(['-C', dir, 'rev-parse', '--verify', `refs/heads/${branch}`]); } catch {}
|
||||
if(parent) git(['-C', dir, 'read-tree', parent], { env });
|
||||
const blob = git(['-C', dir, 'hash-object', '-w', '--stdin'], { input: content, env });
|
||||
git(['-C', dir, 'update-index', '--add', '--cacheinfo', `100644,${blob},${filePath}`], { env });
|
||||
const tree = git(['-C', dir, 'write-tree'], { env });
|
||||
const commit = git(['-C', dir, 'commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', message], { env });
|
||||
git(['-C', dir, 'update-ref', `refs/heads/${branch}`, commit]);
|
||||
fs.rmSync(env.GIT_INDEX_FILE, { force: true });
|
||||
return commit;
|
||||
},
|
||||
readFile : (dir, branch, filePath)=>git(['-C', dir, 'show', `refs/heads/${branch}:${filePath}`]),
|
||||
log : (dir, branch)=>git(['-C', dir, 'log', '--format=%an|%cn|%s', `refs/heads/${branch}`]).split('\n'),
|
||||
head : (dir, branch)=>git(['-C', dir, 'rev-parse', `refs/heads/${branch}`]),
|
||||
close : async ()=>{
|
||||
await new Promise((resolve)=>{ server.closeAllConnections?.(); server.close(resolve); });
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
// In-Memory-Storage mit dem Repository-Vertrag aus ADR 0002/0003 (nur für Tests ohne Datenbank).
|
||||
export const createMemoryStorage = ()=>{
|
||||
const users = new Map(); const brews = new Map(); const conns = new Map(); const links = new Map();
|
||||
const clone = (o)=>o ? structuredClone(o) : null;
|
||||
return {
|
||||
users : {
|
||||
async create(u) { const user = { id: randomUUID(), displayName: null, ...u }; users.set(user.id, user); return clone(user); },
|
||||
async findById(id) { return clone(users.get(id)); }
|
||||
},
|
||||
brews : {
|
||||
async create(b) { const brew = { ...b, id: randomUUID(), editId: b.editId ?? `e${randomUUID().slice(0, 11)}`, shareId: b.shareId ?? `s${randomUUID().slice(0, 11)}`, version: b.version ?? 1 }; brews.set(brew.id, brew); return clone(brew); },
|
||||
async findByEditId(editId) { return clone([...brews.values()].find((b)=>b.editId === editId)); },
|
||||
async update(b) { if(!brews.has(b.id)) return null; brews.set(b.id, { ...brews.get(b.id), ...b }); return clone(brews.get(b.id)); },
|
||||
async deleteById(id) { links.delete(id); return brews.delete(id); }
|
||||
},
|
||||
gitConnections : {
|
||||
async create(c) { const conn = { createdAt: new Date(), updatedAt: new Date(), lastVerifiedAt: null, authUsername: 'git', brewDir: 'brews', assetsDir: 'assets', ...c }; conns.set(conn.id, conn); return clone(conn); },
|
||||
async findById(id) { return clone(conns.get(id)); },
|
||||
async findByIdForOwner(id, uid) { const c = conns.get(id); return c && c.ownerUserId === uid ? clone(c) : null; },
|
||||
async listByOwner(uid) { return [...conns.values()].filter((c)=>c.ownerUserId === uid).map(clone); },
|
||||
async update(id, patch) { if(!conns.has(id)) return null; Object.assign(conns.get(id), patch); return clone(conns.get(id)); },
|
||||
async delete(id) { for (const [k, l] of links)if(l.connectionId === id) links.delete(k); return conns.delete(id); }
|
||||
},
|
||||
brewGitLinks : {
|
||||
async upsert({ brewId, ...rest }) {
|
||||
for (const [k, l] of links)if(k !== brewId && l.connectionId === rest.connectionId && l.branch === rest.branch && l.path === rest.path) throw new Error('unique');
|
||||
links.set(brewId, { lastCommitSha: null, lastBlobSha: null, lastSyncedAt: null, lastError: null, ...links.get(brewId), brewId, ...rest }); return clone(links.get(brewId));
|
||||
},
|
||||
async findByBrewId(id) { return clone(links.get(id)); },
|
||||
async findByLocation(cid, branch, path) { return clone([...links.values()].find((l)=>l.connectionId === cid && l.branch === branch && l.path === path)); },
|
||||
async update(id, patch) { if(!links.has(id)) return null; Object.assign(links.get(id), patch); return clone(links.get(id)); },
|
||||
async delete(id) { return links.delete(id); }
|
||||
}
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user