feat(git): Git-Backend über HTTPS + PAT (ADR 0003, FLW-86) (#19)
Repositories gitConnections/brewGitLinks (Mongo/PG), Krypto, SSRF-Policy mit net.BlockList, git-Client ohne Arbeitskopie, Sync/Konflikte, /api/git/*, Client (Verbindungen, Git-Status, Konfliktdialog), Autosave 60 s für Git-Brews (F6), Tests und Doku. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Dev (Paperclip) <dev-bot@noreply.git.morlana.online>
This commit was merged in pull request #19.
This commit is contained in:
1 parent
06b7ad2c77
commit
448c67912f
44 files changed
+3080
-13
No files matched your search
@@ -53,3 +53,22 @@ HB_OIDC_CLIENT_SECRET=dev-only-client-secret
|
||||
# HB_OIDC_LINK_BY_EMAIL=false
|
||||
# HB_OIDC_END_SESSION=false
|
||||
# HB_OIDC_LABEL=Anmelden
|
||||
|
||||
# --- Git-Backend (ADR 0003, docs/git/) -----------------------------------------
|
||||
# Brews in beliebigen Git-Repos speichern (HTTPS + Personal Access Token). Nur für OIDC-Konten.
|
||||
# Ohne Schlüssel ist das Feature aus. Erzeugen: openssl rand -base64 32 (Schlüssel nie einchecken, nicht verlieren:
|
||||
# ohne ihn sind gespeicherte Tokens unbrauchbar)
|
||||
# HB_GIT_TOKEN_KEY=
|
||||
# Alte Schlüssel (kommagetrennt) nur zum Entschlüsseln bei Rotation
|
||||
# HB_GIT_TOKEN_KEYS_OLD=
|
||||
# Empfohlen im Betrieb: nur diese Hosts (Wildcards wie *.example.org erlaubt)
|
||||
# HB_GIT_ALLOWED_HOSTS=git.example.org,github.com
|
||||
# Nur für Entwicklung: private Ziele (z. B. Gitea im Compose-Netz) und http:// erlauben
|
||||
# HB_GIT_ALLOW_PRIVATE=false
|
||||
# HB_GIT_ALLOW_HTTP=false
|
||||
# HB_GIT_TIMEOUT_MS=20000
|
||||
# HB_GIT_OPEN_TIMEOUT_MS=4000
|
||||
# HB_GIT_MAX_FILE_BYTES=5242880
|
||||
# HB_GIT_MAX_CONCURRENCY=2
|
||||
# HB_GIT_COMMITTER_NAME=Homebrewery
|
||||
# HB_GIT_COMMITTER_EMAIL=
|
||||
@@ -111,6 +111,10 @@ Hinweise: Die IdPs laufen unter `keycloak.localhost:8080` bzw. `authentik.localh
|
||||
|
||||
Der Fork bringt einen generischen OIDC-Login (Authorization Code + PKCE) mit. Konfiguration nur über Umgebungsvariablen (`HB_OIDC_ISSUER`, `HB_OIDC_CLIENT_ID`, `HB_OIDC_CLIENT_SECRET`, `HB_PUBLIC_URL`, `HB_SESSION_SECRET`, …, Vorlage in `.env.example`). Die bisherigen Logins (`naturalcrit`: Benutzername/Passwort, Google) bleiben Standard und lassen sich über `HB_AUTH_PROVIDERS` abschalten, abgeschaltete Methoden verschwinden aus der UI und ihre Endpunkte sind gesperrt. Einrichtung, Variablen und Kontozuordnung: [docs/auth/README.md](./docs/auth/README.md), [Keycloak](./docs/auth/keycloak.md), [authentik](./docs/auth/authentik.md). Entscheidung: [ADR 0001](./docs/adr/0001-auth-oidc.md).
|
||||
|
||||
#### Brews in Git speichern
|
||||
|
||||
Angemeldete OIDC-Nutzer können Brews in einem beliebigen Git-Repository speichern (HTTPS + Personal Access Token, providerneutral: Gitea, Forgejo, GitHub, GitLab, …). Speichern erzeugt einen Commit, beim Öffnen wird der Remote-Stand übernommen, Konflikte werden erkannt und angezeigt. Das Feature ist aus, solange `HB_GIT_TOKEN_KEY` fehlt. Einrichtung, Variablen, Sicherheit und Anbieter-Hinweise: [docs/git/README.md](./docs/git/README.md). Entscheidung: [ADR 0003](./docs/adr/0003-git-backend-und-teilen.md).
|
||||
|
||||
### Running the application on FreeBSD or FreeNAS
|
||||
|
||||
Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import './git.less';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { gitApi } from './gitApi.js';
|
||||
|
||||
// Verbindungen verwalten (ADR 0003 §7): anlegen, testen, löschen, Brews aus dem Repo importieren.
|
||||
// Das Token-Feld ist reines Eingabefeld und wird nie vorbefüllt; der Server gibt den Token nie zurück.
|
||||
const EMPTY = { label: '', repoUrl: '', authUsername: 'git', token: '' };
|
||||
|
||||
const GitConnectionsPanel = ()=>{
|
||||
const [state, setState] = useState('loading'); // loading | off | ready
|
||||
const [conns, setConns] = useState([]);
|
||||
const [form, setForm] = useState(EMPTY);
|
||||
const [msg, setMsg] = useState({}); // pro Verbindung: { ok, text }
|
||||
const [formError, setFormError] = useState('');
|
||||
const [files, setFiles] = useState({}); // pro Verbindung: { branch, files }
|
||||
|
||||
const reload = ()=>gitApi.listConnections().then((list)=>{ setConns(list); setState('ready'); })
|
||||
.catch((err)=>{ if([403, 503].includes(err.status)) setState('off'); else { setFormError(err.message); setState('ready'); } });
|
||||
useEffect(()=>{ reload(); }, []);
|
||||
|
||||
if(state !== 'ready') return null; // Git-Backend deaktiviert oder kein OIDC-Konto
|
||||
|
||||
const set = (id, ok, text)=>setMsg((m)=>({ ...m, [id]: { ok, text } }));
|
||||
|
||||
const create = async (e)=>{
|
||||
e.preventDefault();
|
||||
setFormError('');
|
||||
try {
|
||||
await gitApi.createConnection(form);
|
||||
setForm(EMPTY);
|
||||
await reload();
|
||||
} catch (err) { setFormError(err.message); }
|
||||
};
|
||||
|
||||
const test = (c)=>gitApi.testConnection(c.id)
|
||||
.then((r)=>{ set(c.id, true, `Verbindung ok (Standard-Branch ${r.defaultBranch ?? '?'}, ${r.branchCount} Branches)`); reload(); })
|
||||
.catch((err)=>set(c.id, false, `${err.HBErrorCode ?? ''} ${err.message}`));
|
||||
|
||||
const remove = async (c)=>{
|
||||
if(!window.confirm(`Verbindung „${c.label}“ löschen? Verknüpfte Brews bleiben als normale Brews erhalten.`)) return;
|
||||
await gitApi.deleteConnection(c.id).catch((err)=>set(c.id, false, err.message));
|
||||
reload();
|
||||
};
|
||||
|
||||
const showFiles = (c)=>gitApi.listFiles(c.id, c.defaultBranch, c.brewDir)
|
||||
.then((r)=>setFiles((f)=>({ ...f, [c.id]: { branch: r.branch, files: r.files } })))
|
||||
.catch((err)=>set(c.id, false, `${err.HBErrorCode ?? ''} ${err.message}`));
|
||||
|
||||
const importFile = (c, branch, path)=>gitApi.importBrew({ connectionId: c.id, branch, path })
|
||||
.then((brew)=>{ window.location.href = `/edit/${brew.editId}`; })
|
||||
.catch((err)=>set(c.id, false, `${err.HBErrorCode ?? ''} ${err.message}`));
|
||||
|
||||
return (
|
||||
<div className='dataGroup gitConnections'>
|
||||
<h3>Git-Verbindungen <i className='fab fa-git-alt'></i></h3>
|
||||
<p>Brews in einem beliebigen Git-Repository speichern (HTTPS + Personal Access Token). Der Token wird verschlüsselt gespeichert und nie angezeigt.</p>
|
||||
{conns.map((c)=>(
|
||||
<div className='gitConn' key={c.id}>
|
||||
<div className='label'>{c.label}</div>
|
||||
<div className='url'>{c.repoUrl}</div>
|
||||
<div className='meta'>Standard-Branch {c.defaultBranch}, Ordner {c.brewDir || '/'}{c.lastVerifiedAt ? '' : ' · noch nicht getestet'}</div>
|
||||
<div className='actions'>
|
||||
<button onClick={()=>test(c)}>Testen</button>
|
||||
<button onClick={()=>showFiles(c)}>Brews aus Repo importieren</button>
|
||||
<button onClick={()=>remove(c)}>Löschen</button>
|
||||
</div>
|
||||
{msg[c.id] && <div className={msg[c.id].ok ? 'ok' : 'error'}>{msg[c.id].text}</div>}
|
||||
{files[c.id] && (
|
||||
<ul className='files'>
|
||||
{files[c.id].files.length === 0 && <li>Keine .md-Dateien in {c.brewDir || '/'} auf {files[c.id].branch}.</li>}
|
||||
{files[c.id].files.map((f)=>(
|
||||
<li key={f}>{f} <button onClick={()=>importFile(c, files[c.id].branch, f)}>Importieren</button></li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<form onSubmit={create}>
|
||||
<strong>Neue Verbindung</strong>
|
||||
<input placeholder='Bezeichnung' value={form.label} required maxLength={80} onChange={(e)=>setForm({ ...form, label: e.target.value })} />
|
||||
<input placeholder='https://git.example.org/nutzer/repo.git' value={form.repoUrl} required onChange={(e)=>setForm({ ...form, repoUrl: e.target.value })} />
|
||||
<input placeholder='Benutzername (Standard: git)' value={form.authUsername} onChange={(e)=>setForm({ ...form, authUsername: e.target.value })} />
|
||||
<input type='password' autoComplete='off' placeholder='Personal Access Token' value={form.token} required onChange={(e)=>setForm({ ...form, token: e.target.value })} />
|
||||
<button type='submit'>Verbindung anlegen</button>
|
||||
{formError && <div className='error'>{formError}</div>}
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GitConnectionsPanel;
|
||||
@@ -0,0 +1,62 @@
|
||||
import React, { useState } from 'react';
|
||||
import Nav from '@navbar/nav.jsx';
|
||||
import { gitApi, setGitOverwrite, SAVE_EVENT } from './gitApi.js';
|
||||
|
||||
// Fehlertexte und Konfliktdialog für G01–G10 (ADR 0003 §5, §7).
|
||||
const TEXTS = {
|
||||
G02 : 'Anmeldung am Git-Server fehlgeschlagen. Prüfe den Token der Verbindung (Account-Seite).',
|
||||
G03 : 'Repository, Branch oder Datei wurden nicht gefunden.',
|
||||
G04 : 'Der Git-Server ist nicht erreichbar oder zu langsam. Deine Änderungen sind noch nicht gespeichert, bitte später erneut speichern.',
|
||||
G05 : 'Speichern im Repository ist gerade nicht möglich (viele gleichzeitige Änderungen). Bitte gleich erneut speichern.',
|
||||
G06 : 'Die Datei existiert im Repository bereits.',
|
||||
G07 : 'Das Git-Backend steht nur Konten mit OIDC-Anmeldung zur Verfügung.',
|
||||
G08 : 'Ungültige Eingabe für Git.',
|
||||
G09 : 'Die Datei ist für das Git-Backend zu groß.',
|
||||
G10 : 'Das Git-Backend ist auf diesem Server nicht aktiviert.'
|
||||
};
|
||||
|
||||
const downloadOwnVersion = (brew)=>{
|
||||
const blob = new Blob([brew?.text ?? ''], { type: 'text/markdown' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `${(brew?.title || 'brew').replace(/[^\w-]+/g, '_')}-meine-version.md`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
};
|
||||
|
||||
const GitErrorNavItem = ({ error, clearError, brew })=>{
|
||||
const body = error.response?.body ?? {};
|
||||
const code = body.HBErrorCode;
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if(code === 'G01') {
|
||||
const keepMine = ()=>{
|
||||
setGitOverwrite(body.remoteBlobSha ?? 'none');
|
||||
clearError();
|
||||
document.dispatchEvent(new CustomEvent(SAVE_EVENT));
|
||||
};
|
||||
const loadRemote = async ()=>{
|
||||
setBusy(true);
|
||||
try { await gitApi.pull(brew.editId); window.location.reload(); } catch { setBusy(false); }
|
||||
};
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Konflikt
|
||||
<div className='errorContainer'>
|
||||
Die Datei wurde im Git-Repository geändert{body.remoteCommitSha ? ` (${body.remoteCommitSha.slice(0, 7)})` : ''}.<br />
|
||||
<div className='confirm' onClick={busy ? undefined : keepMine}>Meine Version behalten</div>
|
||||
<div className='deny' onClick={busy ? undefined : ()=>downloadOwnVersion(brew)}>Meine Version sichern</div>
|
||||
<div className='deny' onClick={busy ? undefined : loadRemote}>Remote-Version laden</div>
|
||||
<div className='deny' onClick={clearError}>Abbrechen</div>
|
||||
</div>
|
||||
</Nav.item>;
|
||||
}
|
||||
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={clearError}>
|
||||
{TEXTS[code] ?? body.message ?? 'Git-Fehler.'}
|
||||
</div>
|
||||
</Nav.item>;
|
||||
};
|
||||
|
||||
export default GitErrorNavItem;
|
||||
@@ -0,0 +1,82 @@
|
||||
import './git.less';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import Nav from '@navbar/nav.jsx';
|
||||
import { gitApi } from './gitApi.js';
|
||||
|
||||
// Git-Status im Editor-Navbar (ADR 0003 §7): Branch, Pfad, kurzer SHA, Fehler; Pull; Verknüpfen/Lösen.
|
||||
const short = (sha)=>sha ? sha.slice(0, 7) : '';
|
||||
|
||||
const GitNavItem = ({ brew, lastSavedTime, onLinkedChange })=>{
|
||||
const editId = brew?.editId;
|
||||
const [status, setStatus] = useState(null); // null: unbekannt/aus
|
||||
const [conns, setConns] = useState(null);
|
||||
const [form, setForm] = useState({ connectionId: '', branch: '', path: '' });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const refresh = ()=>gitApi.status(editId).then(setStatus).catch(()=>setStatus(null));
|
||||
useEffect(()=>{ if(editId) refresh(); }, [editId, lastSavedTime]);
|
||||
|
||||
// Verbindungen nur laden, wenn verknüpft werden soll (403/503: Git nicht verfügbar → Item bleibt unsichtbar)
|
||||
useEffect(()=>{
|
||||
if(status && !status.linked && conns === null) {
|
||||
gitApi.listConnections().then((list)=>{ setConns(list); setForm((f)=>({ ...f, connectionId: list[0]?.id ?? '' })); }).catch(()=>setConns(false));
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(()=>{ onLinkedChange?.(!!status?.linked); }, [status?.linked]);
|
||||
|
||||
if(!editId || !status) return null;
|
||||
|
||||
const run = async (fn)=>{
|
||||
setBusy(true); setError('');
|
||||
try { await fn(); await refresh(); } catch (err) { setError(`${err.HBErrorCode ?? ''} ${err.message}`.trim()); }
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
if(status.linked) {
|
||||
return (
|
||||
<Nav.dropdown className='gitNav'>
|
||||
<Nav.item icon={status.lastError ? 'fas fa-exclamation-triangle' : 'fab fa-git-alt'} className={status.lastError ? 'error' : ''}>
|
||||
{status.branch}
|
||||
</Nav.item>
|
||||
<div className='gitDropdown'>
|
||||
<div className='meta'>{status.connectionLabel}: {status.repoUrl}</div>
|
||||
<div className='meta'>{status.branch} · {status.path}{status.lastCommitSha ? ` · ${short(status.lastCommitSha)}` : ''}</div>
|
||||
{status.lastError === 'G04' && <div className='error'>Git nicht erreichbar, angezeigt wird der zuletzt gespeicherte Stand.</div>}
|
||||
{status.lastError && status.lastError !== 'G04' && <div className='error'>Letzter Fehler: {status.lastError}</div>}
|
||||
{error && <div className='error'>{error}</div>}
|
||||
<button disabled={busy} onClick={()=>run(async ()=>{
|
||||
if(!window.confirm('Remote-Stand laden? Ungespeicherte Änderungen im Editor gehen verloren.')) return;
|
||||
await gitApi.pull(editId);
|
||||
window.location.reload();
|
||||
})}>Pull</button>
|
||||
{status.isConnectionOwner && <button disabled={busy} onClick={()=>run(async ()=>{
|
||||
if(window.confirm('Verknüpfung lösen? Der Brew bleibt erhalten, die Datei im Repository auch.')) await gitApi.unlinkBrew(editId);
|
||||
})}>Verknüpfung lösen</button>}
|
||||
</div>
|
||||
</Nav.dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
if(!conns || conns.length === 0) return null; // nichts zu verknüpfen (kein OIDC-Konto oder keine Verbindung)
|
||||
|
||||
return (
|
||||
<Nav.dropdown className='gitNav'>
|
||||
<Nav.item icon='fab fa-git-alt'>Git</Nav.item>
|
||||
<div className='gitDropdown'>
|
||||
<select value={form.connectionId} onChange={(e)=>setForm({ ...form, connectionId: e.target.value })}>
|
||||
{conns.map((c)=><option key={c.id} value={c.id}>{c.label}</option>)}
|
||||
</select>
|
||||
<input placeholder='Branch (Standard der Verbindung)' value={form.branch} onChange={(e)=>setForm({ ...form, branch: e.target.value })} />
|
||||
<input placeholder='Pfad, z. B. brews/mein-brew.md' value={form.path} onChange={(e)=>setForm({ ...form, path: e.target.value })} />
|
||||
{error && <div className='error'>{error}</div>}
|
||||
<button disabled={busy || !form.connectionId} onClick={()=>run(()=>gitApi.linkBrew(editId, { connectionId: form.connectionId, branch: form.branch || undefined, path: form.path || undefined }))}>
|
||||
In Git speichern
|
||||
</button>
|
||||
</div>
|
||||
</Nav.dropdown>
|
||||
);
|
||||
};
|
||||
|
||||
export default GitNavItem;
|
||||
@@ -0,0 +1,35 @@
|
||||
@import '@sharedStyles/core.less';
|
||||
|
||||
.gitConnections {
|
||||
.gitConn {
|
||||
padding : 8px 0;
|
||||
border-bottom : 1px solid #cccccc;
|
||||
.label { font-weight : 800; }
|
||||
.url, .meta { font-size : 0.9em; color : #555555; word-break : break-all; }
|
||||
.actions button { margin : 4px 6px 0 0; }
|
||||
}
|
||||
form {
|
||||
display : grid;
|
||||
gap : 6px;
|
||||
margin-top : 10px;
|
||||
input { padding : 4px; }
|
||||
}
|
||||
.error { color : @red; font-weight : 800; }
|
||||
.ok { color : @teal; font-weight : 800; }
|
||||
ul.files { list-style : none; padding : 0; li { margin : 2px 0; } }
|
||||
}
|
||||
|
||||
.gitNav {
|
||||
.gitDropdown {
|
||||
display : grid;
|
||||
gap : 6px;
|
||||
min-width : 260px;
|
||||
padding : 8px;
|
||||
font-size : 12px;
|
||||
color : white;
|
||||
background-color : #333333;
|
||||
input, select { padding : 3px; }
|
||||
.error { color : #ff9a9a; font-weight : 800; }
|
||||
.meta { opacity : 0.8; word-break : break-all; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import superagent from 'superagent';
|
||||
import request from '../../homebrew/utils/request-middleware.js';
|
||||
|
||||
const patch = (path)=>superagent.patch(path).set('Homebrewery-Version', global.version);
|
||||
|
||||
// Dünne Hülle um /api/git/* (ADR 0003 §7). Fehler tragen `HBErrorCode` und `message` des Servers.
|
||||
const unwrap = (promise)=>promise.then((res)=>res.body).catch((err)=>{
|
||||
const body = err.response?.body ?? {};
|
||||
const e = new Error(body.message || err.message);
|
||||
e.status = err.response?.status;
|
||||
e.HBErrorCode = body.HBErrorCode;
|
||||
e.body = body;
|
||||
throw e;
|
||||
});
|
||||
|
||||
export const gitApi = {
|
||||
listConnections : ()=>unwrap(request.get('/api/git/connections')),
|
||||
createConnection : (data)=>unwrap(request.post('/api/git/connections').send(data)),
|
||||
updateConnection : (id, data)=>unwrap(patch(`/api/git/connections/${id}`).send(data)),
|
||||
deleteConnection : (id)=>unwrap(request.delete(`/api/git/connections/${id}`)),
|
||||
testConnection : (id)=>unwrap(request.post(`/api/git/connections/${id}/test`)),
|
||||
listBranches : (id)=>unwrap(request.get(`/api/git/connections/${id}/branches`)),
|
||||
listFiles : (id, branch, dir)=>unwrap(request.get(`/api/git/connections/${id}/files`).query({ branch, dir })),
|
||||
importBrew : (data)=>unwrap(request.post('/api/git/brews/import').send(data)),
|
||||
linkBrew : (editId, data)=>unwrap(request.post(`/api/git/brews/${editId}/link`).send(data)),
|
||||
unlinkBrew : (editId)=>unwrap(request.delete(`/api/git/brews/${editId}/link`)),
|
||||
status : (editId)=>unwrap(request.get(`/api/git/brews/${editId}`)),
|
||||
pull : (editId)=>unwrap(request.post(`/api/git/brews/${editId}/pull`))
|
||||
};
|
||||
|
||||
// "Meine Version behalten" (Konfliktdialog G01): der nächste Save hängt ?gitOverwrite=<blob> an.
|
||||
let overwriteBlob = null;
|
||||
export const setGitOverwrite = (blob)=>{ overwriteBlob = blob; };
|
||||
export const consumeGitOverwrite = ()=>{ const b = overwriteBlob; overwriteBlob = null; return b; };
|
||||
export const SAVE_EVENT = 'hb:git-save';
|
||||
@@ -1,8 +1,9 @@
|
||||
import './error-navitem.less';
|
||||
import React from 'react';
|
||||
import Nav from './nav.jsx';
|
||||
import GitErrorNavItem from '../../fork/git/GitErrorNavItem.jsx'; // [fork] ADR-0003
|
||||
|
||||
const ErrorNavItem = ({ error = '', clearError })=>{
|
||||
const ErrorNavItem = ({ error = '', clearError, brew })=>{
|
||||
const response = error.response;
|
||||
const errorCode = error.code;
|
||||
const status = response?.status;
|
||||
@@ -17,6 +18,8 @@ const ErrorNavItem = ({ error = '', clearError })=>{
|
||||
console.log(errMsg);
|
||||
} catch {}
|
||||
|
||||
if(typeof HBErrorCode === 'string' && /^G\d\d$/.test(HBErrorCode)) return <GitErrorNavItem error={error} clearError={clearError} brew={brew} />; // [fork] ADR-0003, vor der 409-Behandlung
|
||||
|
||||
if(status === 409) {
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
|
||||
@@ -2,6 +2,7 @@ import React from 'react';
|
||||
import moment from 'moment';
|
||||
import UIPage from '../basePages/uiPage/uiPage.jsx';
|
||||
import NaturalCritIcon from '@components/svg/naturalcrit-d20.svg.jsx';
|
||||
import GitConnectionsPanel from '../../../fork/git/GitConnectionsPanel.jsx'; // [fork] ADR-0003
|
||||
|
||||
let SAVEKEY = '';
|
||||
|
||||
@@ -68,6 +69,7 @@ const AccountPage = (props)=>{
|
||||
{renderSaveLocationButton('Homebrewery', 'HOMEBREWERY')}
|
||||
{renderSaveLocationButton('Google Drive', 'GOOGLE-DRIVE', accountDetails.googleId)}
|
||||
</div>
|
||||
<GitConnectionsPanel />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -23,6 +23,8 @@ import VaultNavItem from '@navbar/vault.navitem.jsx';
|
||||
import PrintNavItem from '@navbar/print.navitem.jsx';
|
||||
import ShareNavItem from '@navbar/share.navitem.jsx';
|
||||
import RecentNavItems from '@navbar/recent.navitem.jsx';
|
||||
import GitNavItem from '../../../../fork/git/GitNavItem.jsx'; // [fork] ADR-0003
|
||||
import { SAVE_EVENT as GIT_SAVE_EVENT } from '../../../../fork/git/gitApi.js';
|
||||
const { both: RecentNavItem } = RecentNavItems;
|
||||
import googleDriveIcon from '../../../googleDrive.svg';
|
||||
|
||||
@@ -34,6 +36,7 @@ const METAKEY = 'HB_newPage_meta';
|
||||
const SAVEKEY_PREFIX = 'HB_editor_defaultSave_';
|
||||
|
||||
const SAVE_TIMEOUT = 10000; //Autosave 10 seconds after last change
|
||||
const GIT_SAVE_TIMEOUT = 60000; // [fork] ADR-0003 F6: Autosave für Git-verknüpfte Brews 60 s (ein Commit pro Save)
|
||||
const UNSAVED_WARNING_TIMEOUT = 900000; //Warn user afer 15 minutes of unsaved changes
|
||||
const UNSAVED_WARNING_POPUP_TIMEOUT = 4000; //Show the warning for 4 seconds
|
||||
|
||||
@@ -53,6 +56,7 @@ const EditorPage = (props)=>{
|
||||
const [currentBrew, setCurrentBrew] = useState(brew);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [lastSavedTime, setLastSavedTime] = useState(new Date());
|
||||
const [gitLinked, setGitLinked] = useState(false); // [fork]
|
||||
const [autoSaveEnabled, setAutoSaveEnabled] = useState(!sandbox);
|
||||
const [warnUnsavedChanges, setWarnUnsavedChanges] = useState(true);
|
||||
const [unsavedChanges, setUnsavedChanges] = useState(false);
|
||||
@@ -94,12 +98,15 @@ const EditorPage = (props)=>{
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleControlKeys);
|
||||
const handleGitSave = ()=>trySave(true, true, saveGoogle); // [fork] ADR-0003: "Meine Version behalten"
|
||||
document.addEventListener(GIT_SAVE_EVENT, handleGitSave);
|
||||
window.onbeforeunload = ()=>{
|
||||
if(unsavedChangesRef.current)
|
||||
return 'You have unsaved changes!';
|
||||
};
|
||||
return ()=>{
|
||||
document.removeEventListener('keydown', handleControlKeys);
|
||||
document.removeEventListener(GIT_SAVE_EVENT, handleGitSave);
|
||||
window.onbeforeunload = null;
|
||||
};
|
||||
}, []);
|
||||
@@ -207,7 +214,8 @@ const EditorPage = (props)=>{
|
||||
clearTimeout(saveTimeout.current);
|
||||
if(isSaving) return;
|
||||
if(!forceSave && !hasChanges) return;
|
||||
const newTimeout = forceSave ? 0 : SAVE_TIMEOUT;
|
||||
const autoSaveTimeout = gitLinked ? GIT_SAVE_TIMEOUT : SAVE_TIMEOUT; // [fork] ADR-0003 F6
|
||||
const newTimeout = forceSave ? 0 : autoSaveTimeout;
|
||||
|
||||
saveTimeout.current = setTimeout(async ()=>{
|
||||
setIsSaving(true);
|
||||
@@ -372,11 +380,12 @@ const EditorPage = (props)=>{
|
||||
<Nav.section>
|
||||
{(pageName == 'editPage') && renderGoogleDriveIcon()}
|
||||
{error
|
||||
? <ErrorNavItem error={error} clearError={clearError} />
|
||||
? <ErrorNavItem error={error} clearError={clearError} brew={currentBrew} />
|
||||
: <Nav.dropdown className='save-menu'>
|
||||
{renderSaveButton()}
|
||||
{(pageName == 'editPage') && renderAutoSaveButton()}
|
||||
</Nav.dropdown>}
|
||||
{(pageName == 'editPage') && <GitNavItem brew={currentBrew} lastSavedTime={lastSavedTime} onLinkedChange={setGitLinked} />}
|
||||
<NewBrewItem />
|
||||
<PrintNavItem />
|
||||
<HelpNavItem />
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DEFAULT_BREW_LOAD } from '../../../../server/brewDefaults.js';
|
||||
|
||||
// Page specific imports
|
||||
import { gzipSync, strToU8 } from 'fflate';
|
||||
import { consumeGitOverwrite } from '../../../fork/git/gitApi.js'; // [fork] ADR-0003
|
||||
import { updateHistory, versionHistoryGarbageCollection } from '../../utils/versionHistory.js';
|
||||
|
||||
const EditPage = (props)=>{
|
||||
@@ -22,10 +23,11 @@ const EditPage = (props)=>{
|
||||
|
||||
const compressedBrew = gzipSync(strToU8(JSON.stringify(brew)));
|
||||
const transfer = saveToGoogle === _.isNil(brew.googleId);
|
||||
const params = transfer ? `?${saveToGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true` : '';
|
||||
const gitOverwrite = consumeGitOverwrite(); // [fork] ADR-0003: nur nach "Meine Version behalten"
|
||||
const params = [transfer && `${saveToGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true`, gitOverwrite && `gitOverwrite=${encodeURIComponent(gitOverwrite)}`].filter(Boolean).join('&');
|
||||
|
||||
const res = await request
|
||||
.put(`/api/update/${brew.editId}${params}`)
|
||||
.put(`/api/update/${brew.editId}${params ? `?${params}` : ''}`)
|
||||
.set('Content-Encoding', 'gzip')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(compressedBrew);
|
||||
|
||||
@@ -32,6 +32,18 @@ services:
|
||||
HB_OIDC_LABEL: ${HB_OIDC_LABEL:-}
|
||||
HB_SESSION_SECRET: ${HB_SESSION_SECRET:-}
|
||||
HB_SESSION_TTL: ${HB_SESSION_TTL:-}
|
||||
# Git-Backend (ADR 0003, docs/git/). Ohne HB_GIT_TOKEN_KEY ist es deaktiviert.
|
||||
HB_GIT_TOKEN_KEY: ${HB_GIT_TOKEN_KEY:-}
|
||||
HB_GIT_TOKEN_KEYS_OLD: ${HB_GIT_TOKEN_KEYS_OLD:-}
|
||||
HB_GIT_ALLOWED_HOSTS: ${HB_GIT_ALLOWED_HOSTS:-}
|
||||
HB_GIT_ALLOW_PRIVATE: ${HB_GIT_ALLOW_PRIVATE:-}
|
||||
HB_GIT_ALLOW_HTTP: ${HB_GIT_ALLOW_HTTP:-}
|
||||
HB_GIT_TIMEOUT_MS: ${HB_GIT_TIMEOUT_MS:-}
|
||||
HB_GIT_OPEN_TIMEOUT_MS: ${HB_GIT_OPEN_TIMEOUT_MS:-}
|
||||
HB_GIT_MAX_FILE_BYTES: ${HB_GIT_MAX_FILE_BYTES:-}
|
||||
HB_GIT_MAX_CONCURRENCY: ${HB_GIT_MAX_CONCURRENCY:-}
|
||||
HB_GIT_COMMITTER_NAME: ${HB_GIT_COMMITTER_NAME:-}
|
||||
HB_GIT_COMMITTER_EMAIL: ${HB_GIT_COMMITTER_EMAIL:-}
|
||||
ports: !override
|
||||
- "${APP_PORT:-8000}:8000"
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# Git-Backend: Brews in beliebigen Git-Repositories
|
||||
|
||||
Umsetzung von [ADR 0003](../adr/0003-git-backend-und-teilen.md) (Gitea #8). Funktioniert mit MongoDB und
|
||||
PostgreSQL und ist nur für **OIDC-Konten** verfügbar (Verbindungen gehören einem `users`-Datensatz,
|
||||
[ADR 0001](../adr/0001-auth-oidc.md)). naturalcrit-Konten können verknüpfte Brews mitbearbeiten und über
|
||||
Status/Pull ansehen, aber nichts selbst verknüpfen (`403 G07`).
|
||||
|
||||
## Einschalten
|
||||
|
||||
```bash
|
||||
openssl rand -base64 32 # → HB_GIT_TOKEN_KEY
|
||||
```
|
||||
|
||||
Ohne `HB_GIT_TOKEN_KEY` ist das Backend deaktiviert (Warnung beim Start, `/api/git/*` antwortet `503 G10`,
|
||||
gespeicherte Brews werden wie bisher nur in der DB gespeichert). Den Schlüssel **nicht verlieren**: Ohne ihn
|
||||
sind gespeicherte Tokens unbrauchbar (Nutzer müssen sie neu eintragen).
|
||||
|
||||
| Variable | Standard | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `HB_GIT_TOKEN_KEY` | – | aktiviert das Feature, 32 Byte base64 |
|
||||
| `HB_GIT_TOKEN_KEYS_OLD` | – | alte Schlüssel (kommagetrennt), nur zum Entschlüsseln; bei der nächsten Nutzung wird neu verschlüsselt |
|
||||
| `HB_GIT_ALLOWED_HOSTS` | – | Host-Allowlist (`git.example.org,*.example.org`). Im Betrieb empfohlen |
|
||||
| `HB_GIT_ALLOW_PRIVATE` | `false` | private/Loopback-Ziele erlauben (z. B. Gitea im selben Compose-Netz) |
|
||||
| `HB_GIT_ALLOW_HTTP` | `false` | `http://` erlauben, nur für lokale Entwicklung |
|
||||
| `HB_GIT_WORKDIR` | `os.tmpdir()/hb-git` | temporäre Bare-Repos (`0700`, werden nach jeder Operation gelöscht) |
|
||||
| `HB_GIT_TIMEOUT_MS` | `20000` | pro `git`-Aufruf |
|
||||
| `HB_GIT_OPEN_TIMEOUT_MS` | `4000` | Gesamtbudget für den Abgleich beim Öffnen des Editors (1000 bis `HB_GIT_TIMEOUT_MS`) |
|
||||
| `HB_GIT_MAX_FILE_BYTES` | `5242880` | größte Brew-Datei |
|
||||
| `HB_GIT_MAX_CONCURRENCY` | `2` | gleichzeitige Git-Operationen pro Prozess (weitere warten, max. 20, sonst `503 G05`) |
|
||||
| `HB_GIT_COMMITTER_NAME` / `_EMAIL` | `Homebrewery` / `homebrewery@<Host aus HB_PUBLIC_URL>` | Committer; Autor ist der speichernde Nutzer |
|
||||
|
||||
Das Docker-Image enthält `git` bereits. Außerhalb von Docker muss `git` (≥ 2.30) im `PATH` liegen.
|
||||
|
||||
## Benutzung
|
||||
|
||||
1. **Verbindung anlegen** (Account-Seite → „Git-Verbindungen“): Bezeichnung, HTTPS-URL des Repos, Benutzername,
|
||||
Personal Access Token mit Schreibrecht auf das Repo. „Testen“ prüft Erreichbarkeit und Token.
|
||||
Der Token ist write-only: Die API gibt ihn nie zurück, er erscheint in keinem Log und keiner Fehlermeldung.
|
||||
2. **Brew verknüpfen** (Editor → Navbar „Git“): Verbindung, Branch und Pfad (`brews/mein-brew.md`) wählen. Der
|
||||
Brew wird dabei als Datei ins Repo geschrieben. Oder umgekehrt: Account-Seite → „Brews aus Repo importieren“.
|
||||
3. **Speichern** erzeugt pro Save einen Commit (auch Autosave; bei verknüpften Brews 60 s nach der letzten Änderung statt 10 s). Nie Force-Push.
|
||||
4. **Öffnen** holt den aktuellen Remote-Stand in den Snapshot. Ist der Git-Server nicht erreichbar (oder
|
||||
langsamer als `HB_GIT_OPEN_TIMEOUT_MS`), öffnet sich der zuletzt gespeicherte Stand und die Navbar warnt.
|
||||
5. **Konflikt** (`409 G01`): Die Datei wurde im Repo geändert. Dialog: „Meine Version behalten“ (neuer Commit
|
||||
auf dem neuen Stand, Historie bleibt), „Meine Version sichern“ (Download), „Remote-Version laden“ (Pull),
|
||||
„Abbrechen“. Änderungen an *anderen* Dateien sind kein Konflikt.
|
||||
|
||||
Teilen funktioniert unverändert und ohne Git-Zugriff: Ausgeliefert wird der zuletzt über die App gespeicherte
|
||||
oder per Öffnen/Pull übernommene Stand. Löschen eines Brews löscht die Datei im Repo **nicht**.
|
||||
|
||||
## Dateiformat
|
||||
|
||||
Exakt die Ausgabe von `mergeBrewText` (dieselbe Datei wie beim Upstream-Download): ```` ```metadata ```` (YAML),
|
||||
optional ```` ```css ```` und der Text. Nicht in der Datei: Autoren, `published`, Views, `shareId`/`editId`, Version.
|
||||
|
||||
## Anbieter
|
||||
|
||||
HTTPS + PAT mit Basic-Auth, ohne Anbieter-API. Als Benutzername passt bei allen `git` (beliebig), bei GitHub
|
||||
und Gitea auch der eigene Benutzername.
|
||||
|
||||
| Anbieter | Token | Benutzername |
|
||||
| --- | --- | --- |
|
||||
| Gitea / Forgejo | Einstellungen → Anwendungen → Zugriffstoken, Scope `write:repository` | beliebig / eigener |
|
||||
| GitHub | Fine-grained Token mit „Contents: Read and write“ auf dem Repo | beliebig / eigener |
|
||||
| GitLab | Project/Personal Access Token, Scope `write_repository` | `oauth2` oder eigener |
|
||||
|
||||
## Fehlercodes
|
||||
|
||||
| Code | HTTP | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `G01` | 409 | Konflikt: Datei im Repo geändert (`remoteCommitSha`, `remoteBlobSha` in der Antwort) |
|
||||
| `G02` | 502 | Anmeldung am Git-Server fehlgeschlagen (Token ungültig/ohne Schreibrecht) |
|
||||
| `G03` | 502 | Repository, Branch oder Datei nicht gefunden |
|
||||
| `G04` | 504 | Git-Server nicht erreichbar oder zu langsam |
|
||||
| `G05` | 503 | Push-Rennen nach 3 Versuchen verloren oder Server ausgelastet |
|
||||
| `G06` | 409 | Datei existiert im Repo bereits (Anlegen/Verknüpfen) |
|
||||
| `G07` | 403 | Nur für OIDC-Konten |
|
||||
| `G08` | 400 | ungültige Eingabe (URL, Pfad, Branch, …) |
|
||||
| `G09` | 413 | Datei größer als `HB_GIT_MAX_FILE_BYTES` |
|
||||
| `G10` | 503 | Git-Backend nicht aktiviert |
|
||||
|
||||
G08–G10 sind Ergänzungen zur ADR.
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- Token: AES-256-GCM, Format `v1.<kid>.<iv>.<ct>.<tag>`, AAD `git-connection:<id>`, nie im Klartext in der DB.
|
||||
- `git` startet nur über `execFile`/`spawn` ohne Shell; Zugangsdaten gehen per `GIT_CONFIG_*`-Umgebung
|
||||
(`http.extraHeader`) an den Prozess, nie in Argumente, URL oder Dateien. `credential.helper` ist leer,
|
||||
Redirects sind aus, nur `https` (bzw. `http` mit `HB_GIT_ALLOW_HTTP`).
|
||||
- SSRF-Schutz vor jeder Operation: nur `https://`, keine Benutzerinfo, Allowlist oder DNS-Auflösung mit
|
||||
Sperre für Loopback, private, Link-Local- und CGNAT-Adressen. Restrisiko DNS-Rebinding: im Betrieb
|
||||
`HB_GIT_ALLOWED_HOSTS` setzen.
|
||||
- Mitautoren speichern mit dem Token des Verbindungsbesitzers.
|
||||
- Nur ein App-Prozess (Mutex pro Brew ist prozesslokal).
|
||||
|
||||
## Abweichungen von ADR 0003
|
||||
|
||||
- Zusätzliche Codes `G08` (ungültige Eingabe), `G09` (Datei zu groß), `G10` (Feature aus).
|
||||
- `afterBrewSave(ctx, saved)` wird in jedem Fall aufgerufen (auch bei fehlgeschlagenem DB-Save), weil der
|
||||
Brew-Mutex von `beforeBrewSave` bis dahin gehalten wird; der Link wird nur bei Erfolg aktualisiert.
|
||||
- Datei im Repo nach externem Löschen: `gitOverwrite=none` bestätigt das Neuanlegen.
|
||||
- Abgleich beim Öffnen und Pull laden den Inhalt im selben Repo-Zugriff wie den Blob-Vergleich (ein zweites
|
||||
frisches Repo hätte den Blob nicht).
|
||||
- Die `git`-Prozesse laufen in eigener Prozessgruppe, damit Abbruch (Zeitbudget) auch `git-remote-http` beendet.
|
||||
- Spike (ADR: „vor M3-Start Pflicht“) gegen Gitea 1.24 über HTTP und lokalen `git http-backend` gelaufen
|
||||
(Root-Commit in leerem Repo, `--filter=blob:none`-Fetch mit Lazy-Blob, Push, Non-Fast-Forward-Ablehnung);
|
||||
nachvollziehbar mit `scripts/git-e2e-gitea.sh`. GitHub wurde nicht geprüft (kein Zugang in der Entwicklungs-VM),
|
||||
das Protokoll ist identisch.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
npx jest server/fork/git tests/fork/git-backend.test.js # ohne Datenbank: echtes git gegen lokalen http-backend
|
||||
HB_TEST_POSTGRES_URL=… HB_TEST_MONGODB_URI=… npx jest server/storage tests/fork --runInBand # inkl. DB-Varianten
|
||||
```
|
||||
|
||||
`tests/fork/git-http-test-server.js` startet `git http-backend` hinter einem Node-Server mit Basic-Auth
|
||||
(Remote mit `uploadpack.allowFilter` und `http.receivepack`). Gegen eine echte Gitea-Instanz (Wegwerf-Container): `scripts/git-e2e-gitea.sh`; gegen ein beliebiges
|
||||
Remote (GitHub, GitLab, …): `GIT_E2E_URL=… GIT_E2E_USER=… GIT_E2E_TOKEN=… node scripts/git-e2e.mjs`.
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Startet eine Wegwerf-Gitea-Instanz (Docker, SQLite), legt Benutzer, Token und Repo an und führt
|
||||
# scripts/git-e2e.mjs dagegen aus. Container wird am Ende gestoppt. Nur Dev-Zugangsdaten.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
NAME=hb-e2e-gitea
|
||||
PORT=${GITEA_E2E_PORT:-3300}
|
||||
IMAGE=${GITEA_IMAGE:-gitea/gitea:1.24}
|
||||
PASS="e2e-$(openssl rand -hex 8)"
|
||||
cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; }
|
||||
trap cleanup EXIT
|
||||
cleanup
|
||||
docker run -d --name "$NAME" --memory 400m -p "127.0.0.1:${PORT}:3000" \
|
||||
-e GITEA__database__DB_TYPE=sqlite3 -e GITEA__security__INSTALL_LOCK=true \
|
||||
-e GITEA__server__ROOT_URL="http://127.0.0.1:${PORT}/" -e GITEA__service__DISABLE_REGISTRATION=true "$IMAGE" >/dev/null
|
||||
for _ in $(seq 1 60); do curl -fs "http://127.0.0.1:${PORT}/api/healthz" >/dev/null && break; sleep 2; done
|
||||
docker exec -u git "$NAME" gitea admin user create --admin --username tester --password "$PASS" --email tester@example.test --must-change-password=false >/dev/null
|
||||
TOKEN=$(curl -fs -u "tester:$PASS" -H 'Content-Type: application/json' -X POST "http://127.0.0.1:${PORT}/api/v1/users/tester/tokens" \
|
||||
-d '{"name":"e2e","scopes":["write:repository","write:user"]}' | sed -n 's/.*"sha1":"\([^"]*\)".*/\1/p')
|
||||
curl -fs -u "tester:$PASS" -H 'Content-Type: application/json' -X POST "http://127.0.0.1:${PORT}/api/v1/user/repos" -d '{"name":"hb-e2e"}' >/dev/null
|
||||
GIT_E2E_URL="http://127.0.0.1:${PORT}/tester/hb-e2e.git" GIT_E2E_USER=tester GIT_E2E_TOKEN="$TOKEN" \
|
||||
GIT_E2E_ALLOW_HTTP=true GIT_E2E_ALLOW_PRIVATE=true node scripts/git-e2e.mjs
|
||||
@@ -0,0 +1,104 @@
|
||||
// E2E-Prüfung des Git-Backends gegen ein echtes Remote (Gitea, Forgejo, GitHub, GitLab, lokales Remote).
|
||||
// Nutzung: GIT_E2E_URL=https://host/owner/repo.git GIT_E2E_USER=name GIT_E2E_TOKEN=… node scripts/git-e2e.mjs
|
||||
// (lokale/private Ziele: GIT_E2E_ALLOW_PRIVATE=true, http://: GIT_E2E_ALLOW_HTTP=true). Das Repo darf leer sein.
|
||||
// Es werden nur Dateien unter hb-e2e-<zeit>/ angelegt. Der Token wird nie ausgegeben.
|
||||
import crypto from 'crypto';
|
||||
import os from 'os';
|
||||
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 { createMemoryStorage } from '../tests/fork/git-memory-storage.js';
|
||||
|
||||
const { GIT_E2E_URL: url, GIT_E2E_USER: user = 'git', GIT_E2E_TOKEN: token } = process.env;
|
||||
if(!url || !token) { console.error('GIT_E2E_URL und GIT_E2E_TOKEN setzen.'); process.exit(2); }
|
||||
|
||||
const cfg = { ...readGitConfig({ HB_GIT_TOKEN_KEY: crypto.randomBytes(32).toString('base64'), HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_WORKDIR: `${os.tmpdir()}/hb-git-e2e` }),
|
||||
allowHttp: process.env.GIT_E2E_ALLOW_HTTP === 'true', allowPrivate: process.env.GIT_E2E_ALLOW_PRIVATE === 'true', timeoutMs: 60000 };
|
||||
const storage = createMemoryStorage();
|
||||
const quiet = { warn: (...a)=>console.log(' [warn]', ...a), error: console.error, log: ()=>{} };
|
||||
const svc = createGitService({ cfg, getStorage: ()=>storage, api, splitTextStyleAndMetadata, logger: quiet });
|
||||
|
||||
let failed = 0;
|
||||
const step = async (name, fn)=>{
|
||||
process.stdout.write(`- ${name} … `);
|
||||
try { const r = await fn(); console.log('ok'); return r; } catch (err) { failed++; console.log(`FEHLER ${err.HBErrorCode ?? ''} ${err.message}`); }
|
||||
};
|
||||
const expectCode = async (code, fn)=>{
|
||||
try { await fn(); } catch (err) { if(err.HBErrorCode === code) return err; throw new Error(`erwartet ${code}, erhalten ${err.HBErrorCode ?? err.message}`); }
|
||||
throw new Error(`erwartet ${code}, aber kein Fehler`);
|
||||
};
|
||||
const assert = (cond, msg)=>{ if(!cond) throw new Error(msg); };
|
||||
|
||||
const dir = `hb-e2e-${Date.now()}`;
|
||||
const alice = await storage.users.create({ username: 'e2e', displayName: 'E2E Tester' });
|
||||
const account = { username: 'e2e', uid: alice.id };
|
||||
const author = { name: 'E2E Tester', email: 'e2e@users.noreply.hb.example.test' };
|
||||
|
||||
const conn = await step('Verbindung anlegen und testen', async ()=>{
|
||||
const c = await svc.createConnection(account, { label: 'e2e', repoUrl: url, authUsername: user, token });
|
||||
assert(c.hasToken && !JSON.stringify(c).includes(token), 'Token in Antwort');
|
||||
const t = await svc.testConnection(account, c.id);
|
||||
console.log(`(Standard-Branch ${t.defaultBranch}, ${t.branchCount} Branches) `);
|
||||
return c;
|
||||
});
|
||||
if(!conn) process.exit(1);
|
||||
const stored = await storage.gitConnections.findById(conn.id);
|
||||
|
||||
const brew = await step('Brew anlegen (Commit)', ()=>svc.createBrew(account, { connectionId: conn.id, path: `${dir}/a.md`, brew: { title: 'E2E Brew', text: 'Version 1', renderer: 'V3' } }));
|
||||
const save = async (text, query = {}, who = account)=>{
|
||||
const current = await storage.brews.findByEditId(brew.editId);
|
||||
const res = { code: undefined, status(c) { this.code = c; return this; }, json(b) { this.body = b; return this; } };
|
||||
const ctx = await svc.beforeBrewSave({ brew: { ...current, text }, req: { query, account: who }, res });
|
||||
if(ctx) await svc.afterBrewSave(ctx, await storage.brews.update({ ...current, text, version: current.version + 1 }));
|
||||
return { ctx, res };
|
||||
};
|
||||
const link = ()=>storage.brewGitLinks.findByBrewId(brew.id);
|
||||
|
||||
await step('Speichern erzeugt neuen Commit', async ()=>{
|
||||
const before = (await link()).lastCommitSha;
|
||||
const { ctx } = await save('Version 2');
|
||||
assert(ctx?.git?.commit && ctx.git.commit !== before, 'kein neuer Commit');
|
||||
});
|
||||
await step('Laden holt den Remote-Stand (Pull)', async ()=>{
|
||||
const l = await link();
|
||||
const conn2 = await storage.gitConnections.findById(conn.id);
|
||||
const state = await svc.readRemote(conn2, { branch: l.branch, filePath: l.path });
|
||||
assert(state.content.includes('Version 2'), 'Inhalt fehlt');
|
||||
assert(state.blob === l.lastBlobSha, 'Blob weicht ab');
|
||||
});
|
||||
await step('Fremder Commit auf derselben Datei → Konflikt G01', async ()=>{
|
||||
const l = await link();
|
||||
await svc.commitContent(await storage.gitConnections.findById(conn.id), { branch: l.branch, filePath: l.path, content: 'Extern geändert', expectedBlob: l.lastBlobSha, author: { name: 'Extern', email: 'x@example.test' } });
|
||||
const { ctx, res } = await save('Meine Version');
|
||||
assert(ctx === null && res.code === 409 && res.body.HBErrorCode === 'G01', 'kein Konflikt');
|
||||
globalThis.remoteBlob = res.body.remoteBlobSha;
|
||||
});
|
||||
await step('„Meine Version behalten“ (gitOverwrite) schreibt normalen Commit', async ()=>{
|
||||
const { ctx, res } = await save('Meine Version', { gitOverwrite: globalThis.remoteBlob });
|
||||
assert(ctx?.git && res.code === undefined, 'Overwrite fehlgeschlagen');
|
||||
});
|
||||
await step('Pull übernimmt externe Änderung in den Snapshot', async ()=>{
|
||||
const l = await link();
|
||||
await svc.commitContent(await storage.gitConnections.findById(conn.id), { branch: l.branch, filePath: l.path, content: '```metadata\ntitle: Extern 2\n```\n\nVon außen\n', expectedBlob: l.lastBlobSha, author });
|
||||
await svc.pull(account, brew.editId);
|
||||
const b = await storage.brews.findByEditId(brew.editId);
|
||||
assert(b.title === 'Extern 2' && b.text.includes('Von außen'), 'Snapshot nicht aktualisiert');
|
||||
});
|
||||
await step('Neuer Branch in nicht leerem Repo', async ()=>{
|
||||
const b2 = await svc.createBrew(account, { connectionId: conn.id, branch: `hb-e2e-${Date.now()}`, path: `${dir}/b.md`, brew: { title: 'Branch Brew', text: 'x' } });
|
||||
assert(b2.editId, 'kein Brew');
|
||||
});
|
||||
await step('Dateiliste und Import', async ()=>{
|
||||
const files = await svc.listFiles(account, conn.id, { branch: (await link()).branch, dir });
|
||||
assert(files.files.includes(`${dir}/a.md`), 'Datei fehlt in der Liste');
|
||||
const imported = await svc.importBrew(account, { connectionId: conn.id, branch: (await link()).branch, path: `${dir}/a.md` }).catch((e)=>e);
|
||||
assert(imported.HBErrorCode === 'G06', 'Doppel-Import nicht abgelehnt');
|
||||
});
|
||||
await step('Falscher Token → G02 ohne Token in der Meldung', async ()=>{
|
||||
await storage.gitConnections.update(conn.id, { tokenEnc: (await import('../server/fork/git/crypto.js')).createTokenCrypto({ key: cfg.key }).encrypt('falsch-xyz', conn.id) });
|
||||
const err = await expectCode('G02', ()=>svc.testConnection(account, conn.id));
|
||||
assert(!JSON.stringify(err.toBody()).includes(token) && !JSON.stringify(err.toBody()).includes('falsch-xyz'), 'Token in Fehlermeldung');
|
||||
});
|
||||
console.log(failed ? `\n${failed} Schritt(e) fehlgeschlagen` : `\nAlles ok (Dateien unter ${dir}/)`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -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,451 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { GitError, redact } from './errors.js';
|
||||
import { createTokenCrypto } from './crypto.js';
|
||||
import { createGitClient } from './gitClient.js';
|
||||
import { createLocks } from './locks.js';
|
||||
import { assertUrlAllowed } from './urlPolicy.js';
|
||||
import { validatePath, validateDir, validateBranch, slugify } from './validate.js';
|
||||
|
||||
// Kernlogik des Git-Backends (ADR 0003 §5): Verbindungen, Laden, Speichern, Konflikte, Pull.
|
||||
|
||||
const MAX_PUSH_ATTEMPTS = 3;
|
||||
|
||||
const noreplyEmail = (username, host)=>`${String(username).replace(/[^A-Za-z0-9._-]+/g, '-')}@users.noreply.${host}`;
|
||||
|
||||
export const publicConnection = (conn)=>({
|
||||
id : conn.id,
|
||||
label : conn.label,
|
||||
repoUrl : conn.repoUrl,
|
||||
authUsername : conn.authUsername,
|
||||
hasToken : !!conn.tokenEnc,
|
||||
defaultBranch : conn.defaultBranch,
|
||||
brewDir : conn.brewDir,
|
||||
assetsDir : conn.assetsDir,
|
||||
createdAt : conn.createdAt,
|
||||
updatedAt : conn.updatedAt,
|
||||
lastVerifiedAt : conn.lastVerifiedAt
|
||||
});
|
||||
|
||||
const publicStatus = (link, conn, { isConnectionOwner = false } = {})=>link ? {
|
||||
linked : true,
|
||||
connectionId : conn?.id,
|
||||
connectionLabel : conn?.label,
|
||||
repoUrl : conn?.repoUrl,
|
||||
branch : link.branch,
|
||||
path : link.path,
|
||||
lastCommitSha : link.lastCommitSha,
|
||||
lastSyncedAt : link.lastSyncedAt,
|
||||
lastError : link.lastError,
|
||||
isConnectionOwner
|
||||
} : { linked: false };
|
||||
|
||||
export const createGitService = ({ cfg, getStorage, api, splitTextStyleAndMetadata, client, locks, logger = console })=>{
|
||||
const tokenCrypto = cfg.enabled ? createTokenCrypto({ key: cfg.key, oldKeys: cfg.oldKeys }) : undefined;
|
||||
client ??= createGitClient(cfg);
|
||||
locks ??= createLocks({ maxConcurrency: cfg.maxConcurrency, maxQueue: cfg.maxQueue });
|
||||
|
||||
const storage = ()=>getStorage();
|
||||
const committer = { name: cfg.committerName, email: cfg.committerEmail };
|
||||
|
||||
const logGit = (what, err)=>logger.warn?.(`[git] ${what}: ${err?.HBErrorCode ?? ''} ${err?.detail ?? err?.message ?? err}`);
|
||||
|
||||
// --- Token ---
|
||||
const getToken = async (conn)=>{
|
||||
let res;
|
||||
try { res = tokenCrypto.decrypt(conn.tokenEnc, conn.id); } catch {
|
||||
throw new GitError('G02', 'Der gespeicherte Token kann nicht entschlüsselt werden. Bitte Token neu hinterlegen.');
|
||||
}
|
||||
if(res.rotate) {
|
||||
await storage().gitConnections.update(conn.id, { tokenEnc: tokenCrypto.encrypt(res.token, conn.id) })
|
||||
.catch((e)=>logGit('Token-Rotation fehlgeschlagen', e));
|
||||
}
|
||||
return res.token;
|
||||
};
|
||||
|
||||
// Operation gegen das Remote einer Verbindung unter globalem Limit
|
||||
const withConn = async (conn, fn, { signal } = {})=>{
|
||||
const token = await getToken(conn);
|
||||
return locks.withSlot(()=>client.withRepo({ repoUrl: conn.repoUrl, authUsername: conn.authUsername, token, signal }, fn), { signal });
|
||||
};
|
||||
|
||||
// --- Rechte ---
|
||||
const isBrewOwner = (brew, account)=>!!account && (brew.authors?.length === 0 || brew.authors?.[0] === account.username);
|
||||
const canEdit = (brew, account)=>!!account && (brew.authors?.length === 0
|
||||
|| brew.authors?.includes(account.username) || brew.invitedAuthors?.includes(account.username));
|
||||
|
||||
const requireUid = (account)=>{
|
||||
if(!account?.uid) throw new GitError('G07');
|
||||
return account.uid;
|
||||
};
|
||||
|
||||
const accessError = (account)=>account
|
||||
? Object.assign(new GitError('G08', 'Du bist kein Autor dieses Brews.', { status: 401 }), { HBErrorCode: '03' })
|
||||
: Object.assign(new GitError('G08', 'Nicht angemeldet.', { status: 401 }), { HBErrorCode: '04' });
|
||||
|
||||
const loadEditableBrew = async (editId, account)=>{
|
||||
const brew = await storage().brews.findByEditId(editId);
|
||||
if(!brew) throw new GitError('G08', 'Brew nicht gefunden.', { status: 404 });
|
||||
if(!canEdit(brew, account)) throw accessError(account);
|
||||
return brew;
|
||||
};
|
||||
|
||||
const authorOf = async (account)=>{
|
||||
let name = account?.username ?? 'Homebrewery';
|
||||
if(account?.uid) {
|
||||
const user = await storage().users.findById(account.uid).catch(()=>null);
|
||||
name = user?.displayName || account.username;
|
||||
}
|
||||
return { name, email: noreplyEmail(account?.username ?? 'homebrewery', cfg.noreplyHost) };
|
||||
};
|
||||
|
||||
// --- Verbindungen ---
|
||||
const parseConnectionInput = async (input, { partial })=>{
|
||||
const out = {};
|
||||
const str = (v)=>typeof v === 'string' ? v.trim() : v;
|
||||
if(!partial || input.label !== undefined) {
|
||||
const label = str(input.label);
|
||||
if(typeof label !== 'string' || label.length < 1 || label.length > 80) throw new GitError('G08', 'Die Bezeichnung muss 1–80 Zeichen lang sein.');
|
||||
out.label = label;
|
||||
}
|
||||
if(!partial || input.repoUrl !== undefined) {
|
||||
out.repoUrl = str(input.repoUrl);
|
||||
await assertUrlAllowed(out.repoUrl, cfg);
|
||||
}
|
||||
if(input.authUsername !== undefined || !partial) {
|
||||
const u = str(input.authUsername) || 'git';
|
||||
if(typeof u !== 'string' || u.length > 100 || u.includes(':') || /[\0-\x1f]/.test(u)) throw new GitError('G08', 'Ungültiger Benutzername für den Git-Server.');
|
||||
out.authUsername = u;
|
||||
}
|
||||
if(input.token !== undefined && input.token !== '') {
|
||||
if(typeof input.token !== 'string' || input.token.length > 2000 || /[\0-\x1f\s]/.test(input.token)) throw new GitError('G08', 'Ungültiger Token.');
|
||||
out.token = input.token;
|
||||
} else if(!partial) throw new GitError('G08', 'Der Token fehlt.');
|
||||
if(input.defaultBranch !== undefined && input.defaultBranch !== '') out.defaultBranch = await validateBranch(str(input.defaultBranch));
|
||||
if(input.brewDir !== undefined) out.brewDir = validateDir(str(input.brewDir));
|
||||
if(input.assetsDir !== undefined) out.assetsDir = validateDir(str(input.assetsDir));
|
||||
return out;
|
||||
};
|
||||
|
||||
const svc = {
|
||||
enabled : cfg.enabled,
|
||||
cfg,
|
||||
locks,
|
||||
canEdit,
|
||||
isBrewOwner,
|
||||
|
||||
async listConnections(account) {
|
||||
const uid = requireUid(account);
|
||||
return (await storage().gitConnections.listByOwner(uid)).map(publicConnection);
|
||||
},
|
||||
|
||||
async createConnection(account, input) {
|
||||
const uid = requireUid(account);
|
||||
const data = await parseConnectionInput(input ?? {}, { partial: false });
|
||||
const { token, ...rest } = data;
|
||||
const id = randomUUID();
|
||||
const conn = { id, ownerUserId: uid, ...rest, tokenEnc: tokenCrypto.encrypt(token, id) };
|
||||
// Standard-Branch aus dem Remote (best effort): Fehler hier verhindern das Anlegen nicht, der Test-Button zeigt sie
|
||||
let verified = false;
|
||||
if(!conn.defaultBranch) {
|
||||
conn.defaultBranch = 'main';
|
||||
try {
|
||||
const { defaultBranch } = await withConn(conn, (repo)=>client.lsRemote(repo));
|
||||
if(defaultBranch) conn.defaultBranch = defaultBranch;
|
||||
verified = true;
|
||||
} catch (err) { logGit('ls-remote beim Anlegen', err); }
|
||||
}
|
||||
if(verified) conn.lastVerifiedAt = new Date();
|
||||
return publicConnection(await storage().gitConnections.create(conn));
|
||||
},
|
||||
|
||||
async updateConnection(account, id, input) {
|
||||
const uid = requireUid(account);
|
||||
const existing = await storage().gitConnections.findByIdForOwner(id, uid);
|
||||
if(!existing) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
|
||||
const { token, ...patch } = await parseConnectionInput(input ?? {}, { partial: true });
|
||||
if(token) patch.tokenEnc = tokenCrypto.encrypt(token, existing.id);
|
||||
return publicConnection(await storage().gitConnections.update(existing.id, patch));
|
||||
},
|
||||
|
||||
async deleteConnection(account, id) {
|
||||
const uid = requireUid(account);
|
||||
const existing = await storage().gitConnections.findByIdForOwner(id, uid);
|
||||
if(!existing) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
|
||||
await storage().gitConnections.delete(existing.id);
|
||||
},
|
||||
|
||||
async ownedConnection(account, id) {
|
||||
const uid = requireUid(account);
|
||||
const conn = await storage().gitConnections.findByIdForOwner(id, uid);
|
||||
if(!conn) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
|
||||
return conn;
|
||||
},
|
||||
|
||||
async testConnection(account, id) {
|
||||
const conn = await svc.ownedConnection(account, id);
|
||||
const { defaultBranch, heads } = await withConn(conn, (repo)=>client.lsRemote(repo));
|
||||
await storage().gitConnections.update(conn.id, { lastVerifiedAt: new Date(), ...(defaultBranch && !conn.defaultBranch ? { defaultBranch } : {}) });
|
||||
return { ok: true, defaultBranch: defaultBranch ?? conn.defaultBranch, branchCount: heads.length };
|
||||
},
|
||||
|
||||
async listBranches(account, id) {
|
||||
const conn = await svc.ownedConnection(account, id);
|
||||
const { defaultBranch, heads } = await withConn(conn, (repo)=>client.lsRemote(repo));
|
||||
return { defaultBranch: defaultBranch ?? conn.defaultBranch, branches: heads.map((h)=>h.name).sort() };
|
||||
},
|
||||
|
||||
async listFiles(account, id, { branch, dir }) {
|
||||
const conn = await svc.ownedConnection(account, id);
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
dir = validateDir(dir ?? '');
|
||||
const files = await withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
if(!head) throw new GitError('G03');
|
||||
return client.listFiles(repo, head, dir);
|
||||
});
|
||||
return { branch, files };
|
||||
},
|
||||
|
||||
// --- Schreiben ---
|
||||
/**
|
||||
* Schreibt `content` per Commit in Datei `path` auf `branch` (Schritte 2–4 aus ADR 0003 §5).
|
||||
* `expectedBlob`: Blob-ID, die wir zuletzt gesehen haben (null: Datei soll neu sein).
|
||||
* `overwrite`: Blob-ID aus gitOverwrite (bewusstes Überschreiben des fremden Stands).
|
||||
*/
|
||||
async commitContent(conn, { branch, filePath, content, expectedBlob, overwrite, author, signal }) {
|
||||
if(Buffer.byteLength(content) > cfg.maxFileBytes) throw new GitError('G09');
|
||||
for (let attempt = 1; attempt <= MAX_PUSH_ATTEMPTS; attempt++) {
|
||||
const result = await withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
let parent = head;
|
||||
if(!head && !(await client.isEmptyRemote(repo))) {
|
||||
// Neuer Branch in nicht leerem Repo: auf Kopf von default_branch aufsetzen
|
||||
parent = await client.fetchHead(repo, conn.defaultBranch);
|
||||
if(!parent) throw new GitError('G03', 'Der Standard-Branch der Verbindung existiert im Repository nicht.');
|
||||
}
|
||||
const remoteBlob = parent ? await client.blobAt(repo, parent, filePath) : null;
|
||||
if((remoteBlob ?? null) !== (expectedBlob ?? null) && overwrite !== (remoteBlob ?? 'none')) {
|
||||
if(expectedBlob === null && remoteBlob) throw new GitError('G06', undefined, { extra: { remoteCommitSha: parent, remoteBlobSha: remoteBlob } });
|
||||
throw new GitError('G01', undefined, { extra: { remoteCommitSha: parent, remoteBlobSha: remoteBlob } });
|
||||
}
|
||||
const message = `${remoteBlob ? 'Update' : 'Create'} ${filePath} via Homebrewery`;
|
||||
const { commit, blob } = await client.buildCommit(repo, { parent, filePath, content, author, message, committer });
|
||||
if(head && blob === remoteBlob) return { commit: head, blob, unchanged: true };
|
||||
try {
|
||||
await client.push(repo, commit, branch);
|
||||
} catch (err) {
|
||||
if(err.kind === 'rejected') return { retry: true };
|
||||
throw err;
|
||||
}
|
||||
return { commit, blob };
|
||||
}, { signal });
|
||||
if(!result.retry) return result;
|
||||
}
|
||||
throw new GitError('G05');
|
||||
},
|
||||
|
||||
// --- Lesen ---
|
||||
async readRemote(conn, { branch, filePath, signal, withContent = true }) {
|
||||
return withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
if(!head) return { head: null, blob: null, content: null };
|
||||
const blob = await client.blobAt(repo, head, filePath);
|
||||
const wantContent = typeof withContent === 'function' ? withContent(blob) : withContent;
|
||||
const content = blob && wantContent ? await client.readBlob(repo, blob) : null;
|
||||
return { head, blob, content };
|
||||
}, { signal });
|
||||
},
|
||||
|
||||
// Remote-Stand in den DB-Snapshot übernehmen (Pull und Abgleich beim Öffnen)
|
||||
async applyRemote(brew, link, { head, blob, content }) {
|
||||
const fields = { text: content.replaceAll('\r\n', '\n') };
|
||||
splitTextStyleAndMetadata(fields);
|
||||
const updated = {
|
||||
...brew,
|
||||
text : content.replaceAll('\r\n', '\n'),
|
||||
version : (brew.version || 1) + 1,
|
||||
updatedAt : new Date()
|
||||
};
|
||||
if(typeof fields.title === 'string' && fields.title.trim()) updated.title = fields.title.trim().slice(0, 100);
|
||||
if(typeof fields.description === 'string') updated.description = fields.description.trim();
|
||||
if(typeof fields.renderer === 'string') updated.renderer = fields.renderer;
|
||||
if(typeof fields.lang === 'string') updated.lang = fields.lang;
|
||||
const saved = await storage().brews.update(updated);
|
||||
await storage().brewGitLinks.update(brew.id, { lastCommitSha: head, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return saved;
|
||||
},
|
||||
|
||||
// --- Brews ---
|
||||
async createBrew(account, { connectionId, branch, path: filePath, brew }) {
|
||||
const conn = await svc.ownedConnection(account, connectionId);
|
||||
if(!brew || typeof brew.text !== 'string') throw new GitError('G08', 'Der Brew fehlt oder hat keinen Text.');
|
||||
delete brew.editId; delete brew.shareId; delete brew.googleId; delete brew.id; delete brew._id;
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
api.beforeNewSave(account, brew);
|
||||
filePath = validatePath(filePath || `${conn.brewDir ? `${conn.brewDir}/` : ''}${slugify(brew.title)}.md`);
|
||||
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06');
|
||||
const author = await authorOf(account);
|
||||
const { commit, blob } = await svc.commitContent(conn, { branch, filePath, content: brew.text, expectedBlob: null, author });
|
||||
const saved = await storage().brews.create({ ...brew, editId: nanoid(12), shareId: nanoid(12) }); // wie newBrew im Upstream
|
||||
await storage().brewGitLinks.upsert({ brewId: saved.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: commit, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return saved;
|
||||
},
|
||||
|
||||
async importBrew(account, { connectionId, branch, path: filePath }) {
|
||||
const conn = await svc.ownedConnection(account, connectionId);
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
filePath = validatePath(filePath);
|
||||
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06', 'Die Datei ist bereits mit einem Brew verknüpft.');
|
||||
const { head, blob, content } = await svc.readRemote(conn, { branch, filePath });
|
||||
if(!blob) throw new GitError('G03');
|
||||
const brew = { text: content };
|
||||
splitTextStyleAndMetadata(brew);
|
||||
if(!brew.title) brew.title = filePath.split('/').pop().replace(/\.md$/, '');
|
||||
api.beforeNewSave(account, brew);
|
||||
const saved = await storage().brews.create({ ...brew, editId: nanoid(12), shareId: nanoid(12) });
|
||||
await storage().brewGitLinks.upsert({ brewId: saved.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: head, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return saved;
|
||||
},
|
||||
|
||||
async linkBrew(account, editId, { connectionId, branch, path: filePath }) {
|
||||
const conn = await svc.ownedConnection(account, connectionId);
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
if(!isBrewOwner(brew, account)) throw new GitError('G08', 'Nur der Besitzer des Brews darf ihn verknüpfen.', { status: 403 });
|
||||
if(brew.googleId) throw new GitError('G08', 'Ein Brew liegt entweder in Google Drive oder in Git.');
|
||||
if(await storage().brewGitLinks.findByBrewId(brew.id)) throw new GitError('G08', 'Der Brew ist bereits mit einem Repository verknüpft.');
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
filePath = validatePath(filePath || `${conn.brewDir ? `${conn.brewDir}/` : ''}${slugify(brew.title)}.md`);
|
||||
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06');
|
||||
const author = await authorOf(account);
|
||||
return svc.locks.withKey(brew.id, async ()=>{
|
||||
const { commit, blob } = await svc.commitContent(conn, { branch, filePath, content: brew.text, expectedBlob: null, author });
|
||||
const link = await storage().brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: commit, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return publicStatus(link, conn, { isConnectionOwner: true });
|
||||
});
|
||||
},
|
||||
|
||||
async unlinkBrew(account, editId) {
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return;
|
||||
const conn = await storage().gitConnections.findByIdForOwner(link.connectionId, requireUid(account));
|
||||
if(!conn || !isBrewOwner(brew, account)) throw new GitError('G07', 'Nur der Besitzer der Verbindung und des Brews darf die Verknüpfung lösen.');
|
||||
await storage().brewGitLinks.delete(brew.id);
|
||||
},
|
||||
|
||||
async status(account, editId) {
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return { linked: false };
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
return publicStatus(link, conn, { isConnectionOwner: !!account.uid && conn?.ownerUserId === account.uid });
|
||||
},
|
||||
|
||||
async pull(account, editId) {
|
||||
const first = await loadEditableBrew(editId, account);
|
||||
return svc.locks.withKey(first.id, async ()=>{
|
||||
// Brew und Link unter dem Lock neu lesen, damit ein gleichzeitiger Save nicht überschrieben wird
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) throw new GitError('G08', 'Der Brew ist nicht mit Git verknüpft.');
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) throw new GitError('G08', 'Die Verbindung existiert nicht mehr.');
|
||||
const state = await svc.readRemote(conn, { branch: link.branch, filePath: link.path }).catch(async (err)=>{
|
||||
await storage().brewGitLinks.update(brew.id, { lastError: err.HBErrorCode ?? 'G05' });
|
||||
throw err;
|
||||
});
|
||||
if(!state.blob) throw new GitError('G03');
|
||||
await svc.applyRemote(brew, link, state);
|
||||
return svc.status(account, editId);
|
||||
});
|
||||
},
|
||||
|
||||
// Abgleich beim Öffnen (Express-Middleware für GET /edit/:id), eigenes Zeitbudget
|
||||
openSyncMiddleware() {
|
||||
return async (req, res, next)=>{
|
||||
try {
|
||||
if(!cfg.enabled || !req.account) return next();
|
||||
let id;
|
||||
try { id = api.getId(req).id; } catch { return next(); }
|
||||
const brew = await storage().brews.findByEditId(id);
|
||||
if(!brew || !canEdit(brew, req.account)) return next();
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return next();
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) return next();
|
||||
|
||||
const signal = AbortSignal.timeout(cfg.openTimeoutMs);
|
||||
try {
|
||||
await locks.withKey(brew.id, async ()=>{
|
||||
const current = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
const fresh = await storage().brews.findByEditId(id);
|
||||
// Inhalt nur laden, wenn sich der Blob geändert hat (im selben Repo-Zugriff)
|
||||
const state = await svc.readRemote(conn, { branch: link.branch, filePath: link.path, signal, withContent: (blob)=>blob !== current.lastBlobSha });
|
||||
if(!state.blob) throw new GitError('G03');
|
||||
if(state.content !== null) {
|
||||
await svc.applyRemote(fresh, current, state);
|
||||
} else if(current.lastError) {
|
||||
await storage().brewGitLinks.update(brew.id, { lastError: null });
|
||||
}
|
||||
}, { signal });
|
||||
} catch (err) {
|
||||
const code = signal.aborted ? 'G04' : (err.HBErrorCode ?? 'G05');
|
||||
logGit(`Abgleich beim Öffnen von ${id} fehlgeschlagen`, err);
|
||||
await storage().brewGitLinks.update(brew.id, { lastError: code }).catch(()=>{});
|
||||
}
|
||||
} catch (err) {
|
||||
logGit('Abgleich beim Öffnen', err);
|
||||
}
|
||||
next();
|
||||
};
|
||||
},
|
||||
|
||||
// --- Hooks für updateBrew (ADR 0003 §5, "Speichern") ---
|
||||
// Liefert null, wenn bereits geantwortet wurde (Fehler), sonst ein Kontextobjekt.
|
||||
async beforeBrewSave({ brew, req, res }) {
|
||||
if(!cfg.enabled || !brew?.id) return {};
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return {};
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) return {};
|
||||
const fail = (err)=>{
|
||||
if(!(err instanceof GitError)) { logGit('Speichern', err); err = new GitError('G05', 'Speichern im Repository fehlgeschlagen.'); } else if(err.HBErrorCode !== 'G01') logGit(`Speichern von ${brew.editId}`, err);
|
||||
res.status(err.status).json(err.toBody());
|
||||
return null;
|
||||
};
|
||||
if(req.query?.saveToGoogle) return fail(new GitError('G08', 'Ein Brew liegt entweder in Google Drive oder in Git.'));
|
||||
|
||||
let release;
|
||||
try {
|
||||
// Mutex pro Brew, bis afterBrewSave ihn freigibt (Commit und DB-Save sind eine Einheit)
|
||||
release = await svc.locks.acquireKey(brew.id);
|
||||
const author = await authorOf(req.account);
|
||||
const overwrite = typeof req.query?.gitOverwrite === 'string' ? req.query.gitOverwrite : undefined;
|
||||
// Basis der Konflikterkennung unter dem Mutex frisch lesen (ein paralleler Save kann sie verschoben haben)
|
||||
const fresh = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
const result = await svc.commitContent(conn, { branch: fresh.branch, filePath: fresh.path, content: brew.text, expectedBlob: fresh.lastBlobSha, overwrite, author });
|
||||
return { link: fresh, git: { commit: result.commit, blob: result.blob }, release };
|
||||
} catch (err) {
|
||||
release?.();
|
||||
return fail(err);
|
||||
}
|
||||
},
|
||||
|
||||
async afterBrewSave(ctx, saved) {
|
||||
if(!ctx?.git) return;
|
||||
try {
|
||||
if(saved) {
|
||||
await storage().brewGitLinks.update(ctx.link.brewId, { lastCommitSha: ctx.git.commit, lastBlobSha: ctx.git.blob, lastSyncedAt: new Date(), lastError: null });
|
||||
}
|
||||
} catch (err) {
|
||||
logGit('Link nach dem Speichern aktualisieren', err);
|
||||
} finally {
|
||||
ctx.release?.();
|
||||
}
|
||||
}
|
||||
};
|
||||
return svc;
|
||||
};
|
||||
|
||||
export { redact };
|
||||
@@ -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,201 @@
|
||||
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', '::ffff:7f00:1', '::ffff:a9fe:a9fe', '::ffff:10.0.0.1', '0:0:0:0:0:ffff:7f00:1', '64:ff9b::7f00:1', '::7f00:1', '::a9fe:a9fe', '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.each(['[::ffff:127.0.0.1]', '[::ffff:a9fe:a9fe]', '[::ffff:10.0.0.1]', '[64:ff9b::7f00:1]', '[::7f00:1]'])('IPv6-Literal %s in der URL wird abgelehnt', async (host)=>{
|
||||
await expect(assertUrlAllowed(`https://${host}/a/b.git`, cfg, { lookup: pub })).rejects.toMatchObject({ HBErrorCode: 'G08' });
|
||||
});
|
||||
|
||||
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,61 @@
|
||||
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 blocked = new net.BlockList();
|
||||
[
|
||||
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
|
||||
['172.16.0.0', 12], ['192.0.0.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['224.0.0.0', 3]
|
||||
].forEach(([n, p])=>blocked.addSubnet(n, p, 'ipv4'));
|
||||
[
|
||||
['::', 96], // IPv4-kompatibel (::a.b.c.d), schließt :: und ::1 ein
|
||||
['::1', 128], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8],
|
||||
['64:ff9b::', 96], // NAT64
|
||||
['2002::', 16] // 6to4
|
||||
].forEach(([n, p])=>blocked.addSubnet(n, p, 'ipv6'));
|
||||
// IPv4-gemappte Adressen (::ffff:a.b.c.d, auch als ::ffff:7f00:1) prüft BlockList selbst gegen die IPv4-Regeln.
|
||||
|
||||
export const isPrivateAddress = (address)=>{
|
||||
const ip = String(address).toLowerCase().replace(/^\[|\]$/g, '').split('%')[0];
|
||||
if(net.isIPv4(ip)) return blocked.check(ip, 'ipv4');
|
||||
if(net.isIPv6(ip)) return blocked.check(ip, 'ipv6');
|
||||
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';
|
||||
};
|
||||
@@ -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();
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// Contract-Suite für gitConnections und brewGitLinks (ADR 0002 §5, ADR 0003 §2).
|
||||
// Aufruf: runGitRepositoryContract(async ()=>({ users, brews, gitConnections, brewGitLinks, cleanup }))
|
||||
export const runGitRepositoryContract = (createRepos)=>{
|
||||
let r;
|
||||
let alice;
|
||||
let bob;
|
||||
let conn;
|
||||
let brew;
|
||||
|
||||
beforeAll(async ()=>{
|
||||
r = await createRepos();
|
||||
alice = await r.users.create({ username: 'alice-git' });
|
||||
bob = await r.users.create({ username: 'bob-git' });
|
||||
brew = await r.brews.create({ title: 'Git-Brew', text: 'Hallo', authors: ['alice-git'] });
|
||||
});
|
||||
afterAll(async ()=>{ await r.cleanup?.(); });
|
||||
|
||||
test('Verbindung anlegen: Standardwerte, plain object, Token nur als Chiffrat', async ()=>{
|
||||
conn = await r.gitConnections.create({ ownerUserId: alice.id, label: 'Gitea', repoUrl: 'https://git.example.test/a/b.git', tokenEnc: 'v1.x.y.z.t' });
|
||||
expect(conn.id).toEqual(expect.any(String));
|
||||
expect(conn).toMatchObject({ ownerUserId: alice.id, label: 'Gitea', authUsername: 'git', defaultBranch: 'main', brewDir: 'brews', assetsDir: 'assets', tokenEnc: 'v1.x.y.z.t', lastVerifiedAt: null });
|
||||
expect(conn.constructor).toBe(Object);
|
||||
});
|
||||
|
||||
test('Besitz: findByIdForOwner mit fremder userId liefert null, listByOwner nur eigene', async ()=>{
|
||||
expect((await r.gitConnections.findByIdForOwner(conn.id, alice.id)).id).toBe(conn.id);
|
||||
expect(await r.gitConnections.findByIdForOwner(conn.id, bob.id)).toBeNull();
|
||||
expect(await r.gitConnections.findByIdForOwner('unbekannt', alice.id)).toBeNull();
|
||||
expect((await r.gitConnections.listByOwner(alice.id)).map((c)=>c.id)).toEqual([conn.id]);
|
||||
expect(await r.gitConnections.listByOwner(bob.id)).toEqual([]);
|
||||
expect(await r.gitConnections.findById('unbekannt')).toBeNull();
|
||||
});
|
||||
|
||||
test('update ändert Felder und updatedAt, nie den Besitzer', async ()=>{
|
||||
const upd = await r.gitConnections.update(conn.id, { label: 'Neu', ownerUserId: bob.id, lastVerifiedAt: new Date(), defaultBranch: 'dev' });
|
||||
expect(upd).toMatchObject({ label: 'Neu', ownerUserId: alice.id, defaultBranch: 'dev' });
|
||||
expect(upd.lastVerifiedAt).toBeInstanceOf(Date);
|
||||
expect(await r.gitConnections.update('unbekannt', { label: 'x' })).toBeNull();
|
||||
});
|
||||
|
||||
test('Link: upsert, find, (Verbindung, Branch, Pfad) ist eindeutig', async ()=>{
|
||||
const link = await r.brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md', lastCommitSha: 'c1', lastBlobSha: 'b1', lastSyncedAt: new Date() });
|
||||
expect(link).toMatchObject({ brewId: brew.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md', lastCommitSha: 'c1', lastBlobSha: 'b1', lastError: null });
|
||||
expect((await r.brewGitLinks.findByBrewId(brew.id)).path).toBe('brews/a.md');
|
||||
expect((await r.brewGitLinks.findByLocation(conn.id, 'main', 'brews/a.md')).brewId).toBe(brew.id);
|
||||
expect(await r.brewGitLinks.findByLocation(conn.id, 'main', 'andere.md')).toBeNull();
|
||||
|
||||
const other = await r.brews.create({ title: 'Zweiter', text: 'x', authors: ['alice-git'] });
|
||||
await expect(r.brewGitLinks.upsert({ brewId: other.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md' })).rejects.toBeDefined();
|
||||
await r.brewGitLinks.upsert({ brewId: other.id, connectionId: conn.id, branch: 'main', path: 'brews/b.md' });
|
||||
expect((await r.brewGitLinks.listByConnection(conn.id)).length).toBe(2);
|
||||
await r.brews.deleteById(other.id);
|
||||
});
|
||||
|
||||
test('upsert ersetzt den Link des Brews (höchstens einer pro Brew)', async ()=>{
|
||||
await r.brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch: 'dev', path: 'brews/a.md' });
|
||||
expect(await r.brewGitLinks.findByLocation(conn.id, 'main', 'brews/a.md')).toBeNull();
|
||||
expect((await r.brewGitLinks.findByBrewId(brew.id)).branch).toBe('dev');
|
||||
expect((await r.brewGitLinks.listByConnection(conn.id)).length).toBe(1);
|
||||
});
|
||||
|
||||
test('update des Links setzt SHA und Fehlercode', async ()=>{
|
||||
const upd = await r.brewGitLinks.update(brew.id, { lastCommitSha: 'c2', lastBlobSha: 'b2', lastError: 'G04' });
|
||||
expect(upd).toMatchObject({ lastCommitSha: 'c2', lastBlobSha: 'b2', lastError: 'G04' });
|
||||
expect((await r.brewGitLinks.update(brew.id, { lastError: null })).lastError).toBeNull();
|
||||
expect(await r.brewGitLinks.update('unbekannt', { lastError: 'x' })).toBeNull();
|
||||
});
|
||||
|
||||
test('Rename eines Autors lässt Verbindungen und Links unverändert', async ()=>{
|
||||
await r.brews.renameAuthor('alice-git', 'alice-neu');
|
||||
expect((await r.gitConnections.listByOwner(alice.id)).map((c)=>c.id)).toEqual([conn.id]);
|
||||
expect((await r.brewGitLinks.findByBrewId(brew.id)).connectionId).toBe(conn.id);
|
||||
});
|
||||
|
||||
test('Brew löschen entfernt den Link, Verbindung bleibt', async ()=>{
|
||||
const tmp = await r.brews.create({ title: 'Tmp', text: 'x', authors: ['alice-git'] });
|
||||
await r.brewGitLinks.upsert({ brewId: tmp.id, connectionId: conn.id, branch: 'main', path: 'brews/tmp.md' });
|
||||
expect(await r.brews.deleteById(tmp.id)).toBe(true);
|
||||
expect(await r.brewGitLinks.findByBrewId(tmp.id)).toBeNull();
|
||||
const tmp2 = await r.brews.create({ title: 'Tmp2', text: 'x', authors: ['alice-git'], editId: 'tmp2editid12' });
|
||||
await r.brewGitLinks.upsert({ brewId: tmp2.id, connectionId: conn.id, branch: 'main', path: 'brews/tmp2.md' });
|
||||
expect(await r.brews.deleteByEditId('tmp2editid12')).toBe(true);
|
||||
expect(await r.brewGitLinks.findByBrewId(tmp2.id)).toBeNull();
|
||||
expect(await r.gitConnections.findById(conn.id)).not.toBeNull();
|
||||
});
|
||||
|
||||
test('Verbindung löschen entfernt ihre Links, der Brew bleibt', async ()=>{
|
||||
const c2 = await r.gitConnections.create({ ownerUserId: bob.id, label: 'B', repoUrl: 'https://git.example.test/b/c.git', tokenEnc: 't' });
|
||||
const b2 = await r.brews.create({ title: 'B2', text: 'x', authors: ['bob-git'] });
|
||||
await r.brewGitLinks.upsert({ brewId: b2.id, connectionId: c2.id, branch: 'main', path: 'x.md' });
|
||||
expect(await r.gitConnections.delete(c2.id)).toBe(true);
|
||||
expect(await r.gitConnections.delete(c2.id)).toBe(false);
|
||||
expect(await r.brewGitLinks.findByBrewId(b2.id)).toBeNull();
|
||||
expect(await r.brews.findByEditId(b2.editId)).not.toBeNull();
|
||||
});
|
||||
|
||||
test('Benutzer löschen entfernt Verbindungen und Links, Brews bleiben', async ()=>{
|
||||
expect(await r.users.delete(alice.id)).toBe(true);
|
||||
expect(await r.gitConnections.findById(conn.id)).toBeNull();
|
||||
expect(await r.brewGitLinks.findByBrewId(brew.id)).toBeNull();
|
||||
expect(await r.brews.findByEditId(brew.editId)).not.toBeNull();
|
||||
});
|
||||
};
|
||||
@@ -1,7 +1,9 @@
|
||||
import _ from 'lodash';
|
||||
import mongoose from 'mongoose';
|
||||
import zlib from 'zlib';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { model as HomebrewModel } from '../../homebrew.model.js';
|
||||
import { getGitModels } from './git.js';
|
||||
|
||||
// BrewRepository (Mongo, ADR 0002): ruft exakt die Statics/Methoden auf, die der Upstream-Code
|
||||
// bisher direkt aufgerufen hat (HomebrewModel.get, getByUser, increaseView, findOne …).
|
||||
@@ -41,6 +43,13 @@ const mapIds = (docs)=>docs.map((doc)=>{
|
||||
|
||||
const asProjection = (fields)=>fields && !Array.isArray(fields) ? Object.keys(fields).filter((k)=>fields[k]) : fields;
|
||||
|
||||
// Kaskade (ADR 0003 §2): beim Löschen eines Brews fällt seine Git-Verknüpfung weg.
|
||||
// Ohne Verbindung (Unit-Specs mit gemocktem Modell) gibt es nichts zu löschen.
|
||||
const connected = ()=>mongoose.connection.readyState === 1;
|
||||
const removeGitLink = async (brewId)=>{
|
||||
if(connected()) await getGitModels().Link.deleteOne({ brewId });
|
||||
};
|
||||
|
||||
export const createBrewRepository = ()=>{
|
||||
const find = async (query, fields)=>{
|
||||
const doc = await (fields ? HomebrewModel.get(query, asProjection(fields)) : HomebrewModel.get(query))
|
||||
@@ -98,11 +107,16 @@ export const createBrewRepository = ()=>{
|
||||
|
||||
async deleteById(id) {
|
||||
const res = await HomebrewModel.deleteOne({ _id: id });
|
||||
return (res?.deletedCount ?? 0) > 0;
|
||||
const deleted = (res?.deletedCount ?? 0) > 0;
|
||||
if(deleted) await removeGitLink(String(id));
|
||||
return deleted;
|
||||
},
|
||||
async deleteByEditId(editId) {
|
||||
const doc = connected() ? await HomebrewModel.findOne({ editId }, { _id: 1 }) : null;
|
||||
const res = await HomebrewModel.deleteOne({ editId });
|
||||
return (res?.deletedCount ?? 0) > 0;
|
||||
const deleted = (res?.deletedCount ?? 0) > 0;
|
||||
if(deleted && doc) await removeGitLink(String(doc._id));
|
||||
return deleted;
|
||||
},
|
||||
|
||||
async incrementViews(shareId) {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
// Fork-Entitäten "GitConnection" und "BrewGitLink" (ADR 0003 §2). Eigene Collections, keine Upstream-Modelle.
|
||||
const ConnectionSchema = new mongoose.Schema({
|
||||
id : { type: String, required: true, unique: true },
|
||||
ownerUserId : { type: String, required: true, index: true },
|
||||
label : { type: String, required: true },
|
||||
repoUrl : { type: String, required: true },
|
||||
authUsername : { type: String, default: 'git' },
|
||||
tokenEnc : { type: String, required: true },
|
||||
defaultBranch : { type: String, default: 'main' },
|
||||
brewDir : { type: String, default: 'brews' },
|
||||
assetsDir : { type: String, default: 'assets' },
|
||||
createdAt : { type: Date, default: Date.now },
|
||||
updatedAt : { type: Date, default: Date.now },
|
||||
lastVerifiedAt : { type: Date }
|
||||
}, { collection: 'gitconnections', versionKey: false });
|
||||
|
||||
const LinkSchema = new mongoose.Schema({
|
||||
brewId : { type: String, required: true, unique: true },
|
||||
connectionId : { type: String, required: true, index: true },
|
||||
branch : { type: String, required: true },
|
||||
path : { type: String, required: true },
|
||||
lastCommitSha : { type: String },
|
||||
lastBlobSha : { type: String },
|
||||
lastSyncedAt : { type: Date },
|
||||
lastError : { type: String }
|
||||
}, { collection: 'brewgitlinks', versionKey: false });
|
||||
LinkSchema.index({ connectionId: 1, branch: 1, path: 1 }, { unique: true });
|
||||
|
||||
export const getGitModels = (connection = mongoose.connection)=>({
|
||||
Connection : connection.models.ForkGitConnection ?? connection.model('ForkGitConnection', ConnectionSchema),
|
||||
Link : connection.models.ForkBrewGitLink ?? connection.model('ForkBrewGitLink', LinkSchema)
|
||||
});
|
||||
|
||||
const nul = (v)=>v ?? null;
|
||||
|
||||
const connToPlain = (doc)=>{
|
||||
if(!doc) return null;
|
||||
const o = doc.toObject ? doc.toObject() : doc;
|
||||
return {
|
||||
id : o.id,
|
||||
ownerUserId : o.ownerUserId,
|
||||
label : o.label,
|
||||
repoUrl : o.repoUrl,
|
||||
authUsername : o.authUsername,
|
||||
tokenEnc : o.tokenEnc,
|
||||
defaultBranch : o.defaultBranch,
|
||||
brewDir : o.brewDir,
|
||||
assetsDir : o.assetsDir,
|
||||
createdAt : o.createdAt,
|
||||
updatedAt : o.updatedAt,
|
||||
lastVerifiedAt : nul(o.lastVerifiedAt)
|
||||
};
|
||||
};
|
||||
|
||||
const linkToPlain = (doc)=>{
|
||||
if(!doc) return null;
|
||||
const o = doc.toObject ? doc.toObject() : doc;
|
||||
return {
|
||||
brewId : o.brewId,
|
||||
connectionId : o.connectionId,
|
||||
branch : o.branch,
|
||||
path : o.path,
|
||||
lastCommitSha : nul(o.lastCommitSha),
|
||||
lastBlobSha : nul(o.lastBlobSha),
|
||||
lastSyncedAt : nul(o.lastSyncedAt),
|
||||
lastError : nul(o.lastError)
|
||||
};
|
||||
};
|
||||
|
||||
const CONN_FIELDS = ['label', 'repoUrl', 'authUsername', 'tokenEnc', 'defaultBranch', 'brewDir', 'assetsDir', 'lastVerifiedAt'];
|
||||
const LINK_FIELDS = ['connectionId', 'branch', 'path', 'lastCommitSha', 'lastBlobSha', 'lastSyncedAt', 'lastError'];
|
||||
const pick = (obj, fields)=>Object.fromEntries(fields.filter((f)=>obj[f] !== undefined).map((f)=>[f, obj[f]]));
|
||||
|
||||
export const createGitConnectionRepository = (connection = mongoose.connection)=>{
|
||||
const { Connection, Link } = getGitModels(connection);
|
||||
return {
|
||||
Model : Connection,
|
||||
async create({ id, ownerUserId, ...rest }) {
|
||||
return connToPlain(await Connection.create({ id: id ?? randomUUID(), ownerUserId: String(ownerUserId), ...pick(rest, CONN_FIELDS) }));
|
||||
},
|
||||
async findById(id) { return connToPlain(await Connection.findOne({ id: String(id) })); },
|
||||
async findByIdForOwner(id, userId) {
|
||||
return connToPlain(await Connection.findOne({ id: String(id), ownerUserId: String(userId) }));
|
||||
},
|
||||
async listByOwner(userId) {
|
||||
return (await Connection.find({ ownerUserId: String(userId) }).sort({ createdAt: 1, id: 1 })).map(connToPlain);
|
||||
},
|
||||
async update(id, patch) {
|
||||
return connToPlain(await Connection.findOneAndUpdate({ id: String(id) }, { $set: { ...pick(patch, CONN_FIELDS), updatedAt: new Date() } }, { returnDocument: 'after' }));
|
||||
},
|
||||
async delete(id) {
|
||||
const res = await Connection.deleteOne({ id: String(id) });
|
||||
if(res.deletedCount > 0) await Link.deleteMany({ connectionId: String(id) });
|
||||
return res.deletedCount > 0;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const createBrewGitLinkRepository = (connection = mongoose.connection)=>{
|
||||
const { Link } = getGitModels(connection);
|
||||
return {
|
||||
Model : Link,
|
||||
async upsert({ brewId, ...rest }) {
|
||||
return linkToPlain(await Link.findOneAndUpdate({ brewId: String(brewId) }, { $set: pick(rest, LINK_FIELDS) },
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }));
|
||||
},
|
||||
async findByBrewId(brewId) { return linkToPlain(await Link.findOne({ brewId: String(brewId) })); },
|
||||
async findByLocation(connectionId, branch, path) {
|
||||
return linkToPlain(await Link.findOne({ connectionId: String(connectionId), branch, path }));
|
||||
},
|
||||
async listByConnection(connectionId) { return (await Link.find({ connectionId: String(connectionId) })).map(linkToPlain); },
|
||||
async update(brewId, patch) {
|
||||
return linkToPlain(await Link.findOneAndUpdate({ brewId: String(brewId) }, { $set: pick(patch, LINK_FIELDS) }, { returnDocument: 'after' }));
|
||||
},
|
||||
async delete(brewId) { return (await Link.deleteOne({ brewId: String(brewId) })).deletedCount > 0; }
|
||||
};
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import DB from '../../db.js';
|
||||
import { createUserRepository } from './users.js';
|
||||
import { createBrewRepository } from './brews.js';
|
||||
import { createNotificationRepository } from './notifications.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './git.js';
|
||||
|
||||
// Mongo-Implementierung der Storage-Schicht (ADR 0002). Ruft die Statics und Methoden der
|
||||
// unveränderten Upstream-Modelle (homebrew.model.js, notifications.model.js) auf.
|
||||
@@ -10,6 +11,8 @@ export const createMongoStorage = (config)=>{
|
||||
const brews = createBrewRepository();
|
||||
const notifications = createNotificationRepository();
|
||||
let users;
|
||||
let gitConnections;
|
||||
let brewGitLinks;
|
||||
return {
|
||||
driver : 'mongo',
|
||||
brews,
|
||||
@@ -18,6 +21,8 @@ export const createMongoStorage = (config)=>{
|
||||
await DB.connect(config);
|
||||
if(!config.get('local_environments').includes(config.get('node_env'))) {
|
||||
await this.users.Model.syncIndexes(); // nur Fork-Modelle, nie Homebrew
|
||||
await this.gitConnections.Model.syncIndexes();
|
||||
await this.brewGitLinks.Model.syncIndexes();
|
||||
}
|
||||
},
|
||||
async disconnect() {
|
||||
@@ -29,6 +34,14 @@ export const createMongoStorage = (config)=>{
|
||||
get users() {
|
||||
users ??= createUserRepository();
|
||||
return users;
|
||||
},
|
||||
get gitConnections() {
|
||||
gitConnections ??= createGitConnectionRepository();
|
||||
return gitConnections;
|
||||
},
|
||||
get brewGitLinks() {
|
||||
brewGitLinks ??= createBrewGitLinkRepository();
|
||||
return brewGitLinks;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -7,6 +7,8 @@ import { createNotificationRepository } from './notifications.js';
|
||||
import { model as HomebrewModel } from '../../homebrew.model.js';
|
||||
import { model as NotificationModel } from '../../notifications.model.js';
|
||||
import { runUserRepositoryContract } from '../contract/users.contract.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './git.js';
|
||||
import { runGitRepositoryContract } from '../contract/git.contract.js';
|
||||
import { runBrewRepositoryContract, runNotificationRepositoryContract } from '../contract/brews.contract.js';
|
||||
|
||||
const uri = process.env.HB_TEST_MONGODB_URI;
|
||||
@@ -45,3 +47,16 @@ suite('Mongo BrewRepository (Contract)', ()=>{
|
||||
suite('Mongo NotificationRepository (Contract)', ()=>{
|
||||
runNotificationRepositoryContract(async ()=>({ notifications: createNotificationRepository(), cleanup: await connectGlobal() }));
|
||||
});
|
||||
|
||||
suite('Mongo Git-Repositories (Contract)', ()=>{
|
||||
runGitRepositoryContract(async ()=>{
|
||||
const cleanup = await connectGlobal();
|
||||
const users = createUserRepository();
|
||||
const gitConnections = createGitConnectionRepository();
|
||||
const brewGitLinks = createBrewGitLinkRepository();
|
||||
await users.Model.init();
|
||||
await gitConnections.Model.init();
|
||||
await brewGitLinks.Model.init();
|
||||
return { users, brews: createBrewRepository(), gitConnections, brewGitLinks, cleanup };
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { getGitModels } from './git.js';
|
||||
|
||||
// Fork-Entität "User" (ADR 0001 §4). Collection `users`, eigenes Schema, berührt keine Upstream-Modelle.
|
||||
const UserSchema = new mongoose.Schema({
|
||||
@@ -92,6 +93,13 @@ export const createUserRepository = (connection = mongoose.connection)=>{
|
||||
|
||||
async delete(id) {
|
||||
const res = await User.deleteOne({ id });
|
||||
if(res.deletedCount > 0) {
|
||||
// Kaskade (ADR 0002 §5): Verbindungen des Benutzers samt Links entfernen, Brews bleiben
|
||||
const { Connection, Link } = getGitModels(connection);
|
||||
const ids = (await Connection.find({ ownerUserId: String(id) }, { id: 1 })).map((c)=>c.id);
|
||||
await Link.deleteMany({ connectionId: { $in: ids } });
|
||||
await Connection.deleteMany({ ownerUserId: String(id) });
|
||||
}
|
||||
return res.deletedCount > 0;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Repositories für Git-Verbindungen und Brew-Verknüpfungen (PostgreSQL, ADR 0003 §2).
|
||||
// Gleicher Vertrag wie mongo/git.js. Ergebnisse: plain objects in camelCase.
|
||||
const UUID = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
const CONN = {
|
||||
label : 'label',
|
||||
repoUrl : 'repo_url',
|
||||
authUsername : 'auth_username',
|
||||
tokenEnc : 'token_enc',
|
||||
defaultBranch : 'default_branch',
|
||||
brewDir : 'brew_dir',
|
||||
assetsDir : 'assets_dir',
|
||||
lastVerifiedAt : 'last_verified_at'
|
||||
};
|
||||
const LINK = {
|
||||
connectionId : 'connection_id',
|
||||
branch : 'branch',
|
||||
path : 'path',
|
||||
lastCommitSha : 'last_commit_sha',
|
||||
lastBlobSha : 'last_blob_sha',
|
||||
lastSyncedAt : 'last_synced_at',
|
||||
lastError : 'last_error'
|
||||
};
|
||||
|
||||
const toRow = (map, patch)=>{
|
||||
const row = {};
|
||||
for (const [field, column] of Object.entries(map)) {
|
||||
if(patch[field] !== undefined) row[column] = patch[field];
|
||||
}
|
||||
return row;
|
||||
};
|
||||
|
||||
const rowToConnection = (r)=>!r ? null : ({
|
||||
id : r.id,
|
||||
ownerUserId : r.owner_user_id,
|
||||
label : r.label,
|
||||
repoUrl : r.repo_url,
|
||||
authUsername : r.auth_username,
|
||||
tokenEnc : r.token_enc,
|
||||
defaultBranch : r.default_branch,
|
||||
brewDir : r.brew_dir,
|
||||
assetsDir : r.assets_dir,
|
||||
createdAt : r.created_at,
|
||||
updatedAt : r.updated_at,
|
||||
lastVerifiedAt : r.last_verified_at ?? null
|
||||
});
|
||||
|
||||
const rowToLink = (r)=>!r ? null : ({
|
||||
brewId : r.brew_id,
|
||||
connectionId : r.connection_id,
|
||||
branch : r.branch,
|
||||
path : r.path,
|
||||
lastCommitSha : r.last_commit_sha ?? null,
|
||||
lastBlobSha : r.last_blob_sha ?? null,
|
||||
lastSyncedAt : r.last_synced_at ?? null,
|
||||
lastError : r.last_error ?? null
|
||||
});
|
||||
|
||||
export const createGitConnectionRepository = (db)=>({
|
||||
async create({ id, ownerUserId, ...rest }) {
|
||||
const values = { owner_user_id: ownerUserId, ...toRow(CONN, rest) };
|
||||
if(id) values.id = id;
|
||||
return rowToConnection(await db.insertInto('git_connections').values(values).returningAll().executeTakeFirstOrThrow());
|
||||
},
|
||||
async findById(id) {
|
||||
if(!UUID.test(String(id))) return null;
|
||||
return rowToConnection(await db.selectFrom('git_connections').selectAll().where('id', '=', id).executeTakeFirst());
|
||||
},
|
||||
async findByIdForOwner(id, userId) {
|
||||
if(!UUID.test(String(id)) || !UUID.test(String(userId))) return null;
|
||||
return rowToConnection(await db.selectFrom('git_connections').selectAll().where('id', '=', id).where('owner_user_id', '=', userId).executeTakeFirst());
|
||||
},
|
||||
async listByOwner(userId) {
|
||||
if(!UUID.test(String(userId))) return [];
|
||||
const rows = await db.selectFrom('git_connections').selectAll().where('owner_user_id', '=', userId).orderBy('created_at').orderBy('id').execute();
|
||||
return rows.map(rowToConnection);
|
||||
},
|
||||
async update(id, patch) {
|
||||
if(!UUID.test(String(id))) return null;
|
||||
const row = toRow(CONN, patch);
|
||||
if(!Object.keys(row).length) return this.findById(id);
|
||||
row.updated_at = new Date();
|
||||
return rowToConnection(await db.updateTable('git_connections').set(row).where('id', '=', id).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(id) {
|
||||
if(!UUID.test(String(id))) return false;
|
||||
const res = await db.deleteFrom('git_connections').where('id', '=', id).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
|
||||
export const createBrewGitLinkRepository = (db)=>({
|
||||
// Legt den Link an oder ersetzt ihn (höchstens einer pro Brew)
|
||||
async upsert({ brewId, ...rest }) {
|
||||
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) {
|
||||
if(!UUID.test(String(brewId))) return null;
|
||||
return rowToLink(await db.selectFrom('brew_git_links').selectAll().where('brew_id', '=', brewId).executeTakeFirst());
|
||||
},
|
||||
async findByLocation(connectionId, branch, path) {
|
||||
if(!UUID.test(String(connectionId))) return null;
|
||||
return rowToLink(await db.selectFrom('brew_git_links').selectAll()
|
||||
.where('connection_id', '=', connectionId).where('branch', '=', branch).where('path', '=', path).executeTakeFirst());
|
||||
},
|
||||
async listByConnection(connectionId) {
|
||||
if(!UUID.test(String(connectionId))) return [];
|
||||
return (await db.selectFrom('brew_git_links').selectAll().where('connection_id', '=', connectionId).execute()).map(rowToLink);
|
||||
},
|
||||
async update(brewId, patch) {
|
||||
if(!UUID.test(String(brewId))) return null;
|
||||
const row = toRow(LINK, patch);
|
||||
if(!Object.keys(row).length) return this.findByBrewId(brewId);
|
||||
return rowToLink(await db.updateTable('brew_git_links').set(row).where('brew_id', '=', brewId).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(brewId) {
|
||||
if(!UUID.test(String(brewId))) return false;
|
||||
const res = await db.deleteFrom('brew_git_links').where('brew_id', '=', brewId).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { createDb, checkServerVersion, migrateToLatest } from './db.js';
|
||||
import { createBrewRepository } from './brews.js';
|
||||
import { createNotificationRepository } from './notifications.js';
|
||||
import { createUserRepository } from './users.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './gitRepos.js';
|
||||
|
||||
// PostgreSQL-Implementierung der Storage-Schicht (ADR 0002). Kysely + pg, versionierte Migrationen
|
||||
// laufen beim Start (migrateToLatest). Konfiguration: HB_POSTGRES_URL, HB_POSTGRES_POOL_MAX.
|
||||
@@ -14,6 +15,8 @@ export const createPostgresStorage = (config, overrides = {})=>{
|
||||
repos.brews = createBrewRepository(db);
|
||||
repos.notifications = createNotificationRepository(db);
|
||||
repos.users = createUserRepository(db);
|
||||
repos.gitConnections = createGitConnectionRepository(db);
|
||||
repos.brewGitLinks = createBrewGitLinkRepository(db);
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -21,6 +24,8 @@ export const createPostgresStorage = (config, overrides = {})=>{
|
||||
get brews() { return repos.brews; },
|
||||
get notifications() { return repos.notifications; },
|
||||
get users() { return repos.users; },
|
||||
get gitConnections() { return repos.gitConnections; },
|
||||
get brewGitLinks() { return repos.brewGitLinks; },
|
||||
get pool() { return handle?.pool; }, // nur für Tests
|
||||
async connect() {
|
||||
const url = overrides.url ?? config?.get('hb_postgres_url');
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { sql } from 'kysely';
|
||||
|
||||
// ADR 0003 §2: Git-Verbindungen (pro Benutzer) und Brew-Verknüpfungen.
|
||||
export const up = async (db)=>{
|
||||
await sql`
|
||||
CREATE TABLE git_connections (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
label text NOT NULL,
|
||||
repo_url text NOT NULL,
|
||||
auth_username text NOT NULL DEFAULT 'git',
|
||||
token_enc text NOT NULL,
|
||||
default_branch text NOT NULL DEFAULT 'main',
|
||||
brew_dir text NOT NULL DEFAULT 'brews',
|
||||
assets_dir text NOT NULL DEFAULT 'assets',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_verified_at timestamptz
|
||||
)`.execute(db);
|
||||
await sql`CREATE INDEX git_connections_owner ON git_connections (owner_user_id)`.execute(db);
|
||||
|
||||
await sql`
|
||||
CREATE TABLE brew_git_links (
|
||||
brew_id uuid PRIMARY KEY REFERENCES brews(id) ON DELETE CASCADE,
|
||||
connection_id uuid NOT NULL REFERENCES git_connections(id) ON DELETE CASCADE,
|
||||
branch text NOT NULL,
|
||||
path text NOT NULL,
|
||||
last_commit_sha text,
|
||||
last_blob_sha text,
|
||||
last_synced_at timestamptz,
|
||||
last_error text,
|
||||
UNIQUE (connection_id, branch, path)
|
||||
)`.execute(db);
|
||||
};
|
||||
|
||||
export const down = async (db)=>{
|
||||
await sql`DROP TABLE IF EXISTS brew_git_links`.execute(db);
|
||||
await sql`DROP TABLE IF EXISTS git_connections`.execute(db);
|
||||
};
|
||||
@@ -1,7 +1,9 @@
|
||||
// Statische Migrationsliste (kein Dateisystem-Scan, damit es mit Vite/Jest/Node gleich läuft).
|
||||
// Neue Migration: Datei `NNNN_beschreibung.js` mit up(db)/down(db) anlegen und hier eintragen.
|
||||
import * as m0001 from './0001_initial.js';
|
||||
import * as m0002 from './0002_git_backend.js';
|
||||
|
||||
export default {
|
||||
'0001_initial' : m0001
|
||||
'0001_initial' : m0001,
|
||||
'0002_git_backend' : m0002
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import { randomBytes } from 'crypto';
|
||||
import pg from 'pg';
|
||||
import { createPostgresStorage } from './index.js';
|
||||
import { runUserRepositoryContract } from '../contract/users.contract.js';
|
||||
import { runGitRepositoryContract } from '../contract/git.contract.js';
|
||||
import { runBrewRepositoryContract, runNotificationRepositoryContract } from '../contract/brews.contract.js';
|
||||
|
||||
const url = process.env.HB_TEST_POSTGRES_URL;
|
||||
@@ -47,6 +48,13 @@ suite('Postgres NotificationRepository (Contract)', ()=>{
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Git-Repositories (Contract)', ()=>{
|
||||
runGitRepositoryContract(async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
return { users: storage.users, brews: storage.brews, gitConnections: storage.gitConnections, brewGitLinks: storage.brewGitLinks, cleanup };
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Verbindung und Migrationen', ()=>{
|
||||
test('Start ohne HB_POSTGRES_URL bricht mit klarer Meldung ab', async ()=>{
|
||||
const storage = createPostgresStorage({ get: ()=>undefined });
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// Git-Backend gegen die echte App und echte Datenbank (ADR 0003): Speichern über PUT /api/update/:id,
|
||||
// Konflikt G01, gitOverwrite, Pull, Teilen ohne Git-Zugriff. Läuft je Backend, das konfiguriert ist:
|
||||
// HB_TEST_POSTGRES_URL bzw. HB_TEST_MONGODB_URI (wie api-smoke.test.js).
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import supertest from 'supertest';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import pg from 'pg';
|
||||
import mongoose from 'mongoose';
|
||||
import { md5 } from 'hash-wasm';
|
||||
import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
|
||||
import createApp from '../../server/app.js';
|
||||
import storage from '../../server/storage/index.js';
|
||||
import packageJSON from '../../package.json' with { type: 'json' };
|
||||
import { startGitHttpServer } from './git-http-test-server.js';
|
||||
|
||||
const backends = [
|
||||
{ driver: 'postgres', url: process.env.HB_TEST_POSTGRES_URL },
|
||||
{ driver: 'mongo', url: process.env.HB_TEST_MONGODB_URI }
|
||||
];
|
||||
const version = { 'Homebrewery-Version': packageJSON.version };
|
||||
const SECRET = 's'.repeat(40);
|
||||
|
||||
for (const { driver, url } of backends) {
|
||||
const suite = url ? describe : describe.skip;
|
||||
if(!url) console.warn(`Git-Backend-DB-Test (${driver}): Datenbank-URL fehlt, übersprungen.`);
|
||||
|
||||
suite(`Git-Backend gegen ${driver}`, ()=>{
|
||||
let request; let cleanup; let remote; let workdir; let cookie; let user; let envBackup; let connectSpy;
|
||||
|
||||
beforeAll(async ()=>{
|
||||
envBackup = { ...process.env };
|
||||
workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-work-'));
|
||||
Object.assign(process.env, {
|
||||
HB_AUTH_PROVIDERS : 'oidc', HB_OIDC_ISSUER : 'https://idp.example.test', HB_OIDC_CLIENT_ID : 'hb', HB_OIDC_CLIENT_SECRET : 'x',
|
||||
HB_PUBLIC_URL : 'http://localhost:8000', HB_SESSION_SECRET : SECRET,
|
||||
HB_GIT_TOKEN_KEY : randomBytes(32).toString('base64'), HB_GIT_ALLOW_HTTP : 'true', HB_GIT_ALLOW_PRIVATE : 'true', HB_GIT_WORKDIR : workdir
|
||||
});
|
||||
remote = await startGitHttpServer();
|
||||
|
||||
const name = `test_${randomBytes(4).toString('hex')}`;
|
||||
const values = { hb_db_driver: driver, node_env: 'test', local_environments: ['local'] };
|
||||
if(driver === 'postgres') {
|
||||
const admin = new pg.Client({ connectionString: url });
|
||||
await admin.connect();
|
||||
await admin.query(`CREATE SCHEMA ${name}`);
|
||||
values.hb_postgres_url = `${url}${url.includes('?') ? '&' : '?'}options=-c%20search_path%3D${name}`;
|
||||
cleanup = async ()=>{ await storage.disconnect(); await admin.query(`DROP SCHEMA ${name} CASCADE`); await admin.end(); };
|
||||
} else {
|
||||
values.mongodb_uri = url;
|
||||
cleanup = async ()=>{ await mongoose.connection.dropDatabase(); await storage.disconnect(); };
|
||||
}
|
||||
const connect = mongoose.connect.bind(mongoose);
|
||||
connectSpy = jest.spyOn(mongoose, 'connect').mockImplementation((u, o)=>connect(u, { ...o, dbName: name, runtimeAdapters: { os } }));
|
||||
await storage.connect({ get: (key)=>values[key] });
|
||||
if(driver === 'mongo') {
|
||||
const { model } = await import('../../server/homebrew.model.js');
|
||||
await model.collection.createIndex({ shareId: 1 }, { unique: true });
|
||||
await model.collection.createIndex({ editId: 1 }, { unique: true });
|
||||
const git = storage.getStorage();
|
||||
await git.users.Model.init(); await git.gitConnections.Model.init(); await git.brewGitLinks.Model.init();
|
||||
}
|
||||
user = await storage.getStorage().users.create({ username: 'alice-git', displayName: 'Alice A.' });
|
||||
cookie = `hb_session=${jwt.sign({ v: 1, uid: user.id, username: 'alice-git', iss: 'https://idp.example.test', sub: 's1' }, SECRET, { algorithm: 'HS256', expiresIn: 3600 })}`;
|
||||
request = supertest.agent(await createApp()).set('X-Forwarded-Proto', 'https');
|
||||
});
|
||||
afterAll(async ()=>{
|
||||
await cleanup?.();
|
||||
connectSpy?.mockRestore();
|
||||
await remote?.close();
|
||||
fs.rmSync(workdir, { recursive: true, force: true });
|
||||
process.env = envBackup;
|
||||
});
|
||||
|
||||
const api = (method, url)=>request[method](url).set(version).set('Cookie', cookie);
|
||||
|
||||
const loadBrew = async (editId)=>{
|
||||
const b = await storage.getStorage().brews.findByEditId(editId);
|
||||
return b;
|
||||
};
|
||||
// Wie der Editor: Patches gegen den zuletzt geladenen (entpackten) Text
|
||||
const save = async (editId, newText, query = '')=>{
|
||||
const lookup = await request.get(`/admin/lookup/${editId}`).set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`);
|
||||
const loaded = lookup.body;
|
||||
const oldText = loaded.text.normalize('NFC');
|
||||
return api('put', `/api/update/${editId}${query}`).send({
|
||||
...loaded, text : newText, hash : await md5(oldText),
|
||||
patches : stringifyPatches(makePatches(encodeURI(oldText), encodeURI(newText)))
|
||||
});
|
||||
};
|
||||
|
||||
test('Verbindung anlegen, Brew in Git anlegen, speichern, Konflikt, Überschreiben, Pull, Teilen ohne Git', async ()=>{
|
||||
const { url: repoUrl, dir } = remote.createRepo('db.git');
|
||||
const conn = await api('post', '/api/git/connections').send({ label: 'Lokal', repoUrl, authUsername: remote.username, token: remote.token });
|
||||
expect(conn.status).toBe(201);
|
||||
expect(JSON.stringify(conn.body)).not.toContain(remote.token);
|
||||
|
||||
const created = await api('post', '/api/git/brews').send({ connectionId: conn.body.id, path: 'brews/db.md', brew: { title: 'DB Brew', text: 'Erste Fassung', renderer: 'V3' } });
|
||||
expect(created.status).toBe(200);
|
||||
const { editId, shareId } = created.body;
|
||||
if(process.env.GIT_TEST_LOG) console.log('CREATED', JSON.stringify(created.body), JSON.stringify(await storage.getStorage().brews.findByEditId(editId)));
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Erste Fassung');
|
||||
const status = await api('get', `/api/git/brews/${editId}`);
|
||||
expect(status.body).toMatchObject({ linked: true, path: 'brews/db.md', branch: 'main', isConnectionOwner: true });
|
||||
|
||||
// Speichern → Commit
|
||||
const s1 = await save(editId, 'Zweite Fassung');
|
||||
expect(s1.status).toBe(200);
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Zweite Fassung');
|
||||
expect(remote.log(dir, 'main')).toHaveLength(2);
|
||||
expect((await loadBrew(editId)).text).toContain('Zweite Fassung');
|
||||
expect((await api('get', `/api/git/brews/${editId}`)).body.lastCommitSha).toBe(remote.head(dir, 'main'));
|
||||
|
||||
// Teilen: Share-Routen brauchen keinen Git-Zugriff (Server hängt)
|
||||
remote.setHang(true);
|
||||
const shared = await request.get(`/source/${shareId}`);
|
||||
remote.setHang(false);
|
||||
expect(shared.status).toBe(200);
|
||||
expect(shared.text).toContain('Zweite Fassung');
|
||||
|
||||
// Fremder Commit → 409 G01
|
||||
remote.commitFile(dir, 'main', 'brews/db.md', '```metadata\ntitle: Extern\n```\n\nExterne Fassung\n');
|
||||
const conflict = await save(editId, 'Dritte Fassung');
|
||||
expect(conflict.status).toBe(409);
|
||||
expect(conflict.body).toMatchObject({ HBErrorCode: 'G01' });
|
||||
expect(conflict.body.remoteBlobSha).toMatch(/^[0-9a-f]{40}$/);
|
||||
expect((await loadBrew(editId)).text).toContain('Zweite Fassung'); // DB unverändert
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Externe Fassung');
|
||||
|
||||
// Meine Version behalten → Commit auf dem neuen Stand
|
||||
const over = await save(editId, 'Dritte Fassung', `?gitOverwrite=${conflict.body.remoteBlobSha}`);
|
||||
expect(over.status).toBe(200);
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Dritte Fassung');
|
||||
expect(remote.log(dir, 'main')).toHaveLength(4);
|
||||
|
||||
// Externer Commit, dann Pull → Snapshot folgt
|
||||
remote.commitFile(dir, 'main', 'brews/db.md', '```metadata\ntitle: Extern 2\n```\n\nVierte Fassung\n');
|
||||
const pulled = await api('post', `/api/git/brews/${editId}/pull`);
|
||||
expect(pulled.status).toBe(200);
|
||||
const after = await loadBrew(editId);
|
||||
expect(after.title).toBe('Extern 2');
|
||||
expect(after.text).toContain('Vierte Fassung');
|
||||
|
||||
// Löschen: Brew und Link weg, Datei bleibt (F9)
|
||||
const removed = await api('get', `/api/remove/${editId}`);
|
||||
expect(removed.status).toBe(204);
|
||||
expect(await loadBrew(editId)).toBeNull();
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Vierte Fassung');
|
||||
expect(await storage.getStorage().brewGitLinks.findByBrewId(created.body.id)).toBeNull();
|
||||
});
|
||||
|
||||
test('Konten ohne uid (nicht angemeldet) bekommen 403 G07', async ()=>{
|
||||
const res = await request.get('/api/git/connections').set(version);
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([403, 'G07']);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
// 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('Pull liest Brew unter dem Lock neu: Metadaten eines gleichzeitigen Saves bleiben erhalten', async ()=>{
|
||||
const { dir, brew } = await linked();
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Remote-Text\n');
|
||||
const release = await svc.locks.acquireKey(brew.id);
|
||||
const pending = request.post(`/api/git/brews/${brew.editId}/pull`).set(version).set(asAccount(ALICE())).then((r)=>r);
|
||||
await new Promise((r)=>setTimeout(r, 200)); // Pull hat den Brew gelesen und wartet auf den Lock
|
||||
const current = await storage.brews.findByEditId(brew.editId);
|
||||
await storage.brews.update({ ...current, tags: ['gleichzeitig'], version: current.version + 1 });
|
||||
release();
|
||||
const res = await pending;
|
||||
expect(res.status).toBe(200);
|
||||
const after = await storage.brews.findByEditId(brew.editId);
|
||||
expect(after.tags).toEqual(['gleichzeitig']);
|
||||
expect(after.version).toBe(current.version + 2);
|
||||
expect(after.text).toContain('Remote-Text');
|
||||
});
|
||||
|
||||
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