feat(git): Teilen von Git-Brews über Server-Snapshot (#9) (#25)
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (push) Successful in 2m12s
CI / Storage (mongo) (push) Successful in 1m41s
CI / Storage (postgres) (push) Successful in 1m13s
Image / Image bauen und pushen (push) Successful in 5m18s

Co-authored-by: Dev (Paperclip) <dev-bot@noreply.git.morlana.online>
This commit was merged in pull request #25.
This commit is contained in:
dev-bot Bot authored and Gitea committed 2026-11-26 01:01:31 +00:00
1 parent adaa10a4dc
commit 3a77763641
8 files changed
+94 -4

No files matched your search

+2
View File
@@ -1,5 +1,6 @@
import './git.less';
import React, { useEffect, useState } from 'react';
import Moment from 'moment';
import Nav from '@navbar/nav.jsx';
import { gitApi } from './gitApi.js';
@@ -43,6 +44,7 @@ const GitNavItem = ({ brew, lastSavedTime, onLinkedChange })=>{
<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.snapshotAt && <div className='meta' title='Stand, den Teilen-Links ausliefern'>Teilen-Stand: {Moment(status.snapshotAt).format('LLL')}</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>}
+8
View File
@@ -117,3 +117,11 @@ HB_TEST_POSTGRES_URL=… HB_TEST_MONGODB_URI=… npx jest server/storage tests/f
`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`.
## Teilen (Snapshot, ADR 0003 §6)
Share-, Fetch-, CSS-, Metadaten-, Quelltext- und Download-Routen liefern den DB-Snapshot und greifen nie auf Git
zu. Leser brauchen weder Konto noch Repo-Zugriff und sehen weder Token noch Repo-URL oder Pfad (auch bei privaten
Repos). Der Snapshot wird bei jedem erfolgreichen Speichern, Pull und Abgleich beim Öffnen aktualisiert. Sein
Zeitpunkt (`updatedAt`) steht im Share-Link-Metadatenmenü („vor … “) und im Git-Menü des Editors als „Teilen-Stand“
(`snapshotAt` in `GET /api/git/brews/:editId`). Commits außerhalb der App erscheinen erst nach Öffnen im Editor oder Pull.
+4 -3
View File
@@ -27,7 +27,7 @@ export const publicConnection = (conn)=>({
lastVerifiedAt : conn.lastVerifiedAt
});
const publicStatus = (link, conn, { isConnectionOwner = false } = {})=>link ? {
const publicStatus = (link, conn, { isConnectionOwner = false, brew } = {})=>link ? {
linked : true,
connectionId : conn?.id,
connectionLabel : conn?.label,
@@ -37,6 +37,7 @@ const publicStatus = (link, conn, { isConnectionOwner = false } = {})=>link ? {
lastCommitSha : link.lastCommitSha,
lastSyncedAt : link.lastSyncedAt,
lastError : link.lastError,
snapshotAt : brew?.updatedAt ?? null, // Stand, den Share-Links ausliefern (ADR 0003 §6)
isConnectionOwner
} : { linked: false };
@@ -321,7 +322,7 @@ export const createGitService = ({ cfg, getStorage, api, splitTextStyleAndMetada
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 });
return publicStatus(link, conn, { isConnectionOwner: true, brew });
});
},
@@ -339,7 +340,7 @@ export const createGitService = ({ cfg, getStorage, api, splitTextStyleAndMetada
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 });
return publicStatus(link, conn, { isConnectionOwner: !!account.uid && conn?.ownerUserId === account.uid, brew });
},
async pull(account, editId) {
+2 -1
View File
@@ -33,7 +33,8 @@ const HomebrewSchema = mongoose.Schema({
}, { versionKey: false });
HomebrewSchema.pre('save', function() {
if(this.text !== undefined) {
// Nur bei neuem/geändertem Text: der Default '' beim Laden darf textBin nicht überschreiben.
if(this.text !== undefined && (this.isNew || this.isModified('text'))) {
this.textBin = zlib.deflateRawSync(this.text);
this.text = undefined;
}
+10
View File
@@ -164,6 +164,16 @@ export const runBrewRepositoryContract = (createBrews)=>{
expect(new Date(r2.lastViewed).getTime()).toBeGreaterThan(before.getTime());
expect((await brews.findByShareId(b.shareId)).views).toBe(2);
});
test('Text bleibt nach incrementViews und update ohne text erhalten', async ()=>{
const b = await brews.create(sample());
await brews.incrementViews(b.shareId);
expect((await brews.findByShareId(b.shareId)).text).toBe(sample().text);
await brews.update({ id: b.id, title: 'Neu' });
expect((await brews.findByShareId(b.shareId)).text).toBe(sample().text);
await brews.update({ id: b.id, text: '' });
expect((await brews.findByShareId(b.shareId)).text).toBe('');
});
});
describe('Vault-Suche', ()=>{
+1
View File
@@ -99,6 +99,7 @@ export const createBrewRepository = ()=>{
const doc = await HomebrewModel.findOne({ _id: brew.id });
if(!doc) return null;
const merged = _.assign(doc, withoutId(brew));
if(brew.text !== undefined) merged.markModified('text'); // auch bei text === '' (Default) speichern
const saved = await merged.save();
const plain = toPlain(saved);
if(brew.text !== undefined) plain.text = brew.text;
+51
View File
@@ -151,6 +151,57 @@ for (const { driver, url } of backends) {
expect(await storage.getStorage().brewGitLinks.findByBrewId(created.body.id)).toBeNull();
});
test('Teilen: alle Leser-Routen ohne Anmeldung und ohne Git, Snapshot-Zeit steigt, normale Brews unberührt', async ()=>{
const { url: repoUrl } = remote.createRepo('share.git');
const conn = await api('post', '/api/git/connections').send({ label: 'Privat', repoUrl, authUsername: remote.username, token: remote.token });
const created = await api('post', '/api/git/brews').send({ connectionId: conn.body.id, path: 'brews/share.md', brew: { title: 'Geteilt', text: '```css\n.snap { color: red; }\n```\n\nSnapshot Eins', renderer: 'V3' } });
expect(created.status).toBe(200);
const { editId, shareId } = created.body;
const plain = await api('post', '/api').send({ title: 'Normal', text: 'Ohne Git', renderer: 'V3' });
expect(plain.status).toBe(200);
const readerRoutes = (id)=>[`/share/${id}`, `/api/fetch/${id}`, `/metadata/${id}`, `/source/${id}`, `/download/${id}`, `/css/${id}`];
const readAll = async (id)=>{
const out = {};
for (const route of readerRoutes(id)) {
const res = await request.get(route); // bewusst ohne Cookie: Leser ohne Konto
expect([route, res.status]).toEqual([route, 200]);
out[route] = res;
const body = `${res.text ?? ''}${JSON.stringify(res.body ?? {})}`;
expect(body).not.toContain(remote.token);
expect(body).not.toContain(repoUrl);
expect(body).not.toContain('brews/share.md');
}
return out;
};
remote.setHang(true); // Git nicht erreichbar → Share darf nicht davon abhängen
let before;
try { before = await readAll(shareId); } finally { remote.setHang(false); }
expect(before[`/source/${shareId}`].text).toContain('Snapshot Eins');
expect(before[`/download/${shareId}`].text).toContain('Snapshot Eins');
const t1 = new Date(JSON.parse(before[`/metadata/${shareId}`].text ?? JSON.stringify(before[`/metadata/${shareId}`].body)).updatedAt);
// Jedes erfolgreiche Speichern aktualisiert den Snapshot und seinen Zeitpunkt
await new Promise((r)=>setTimeout(r, 20));
expect((await save(editId, 'Snapshot Zwei')).status).toBe(200);
remote.setHang(true);
let after;
try { after = await readAll(shareId); } finally { remote.setHang(false); }
expect(after[`/source/${shareId}`].text).toContain('Snapshot Zwei');
const t2 = new Date(after[`/metadata/${shareId}`].body.updatedAt);
expect(t2.getTime()).toBeGreaterThan(t1.getTime());
const st = await api('get', `/api/git/brews/${editId}`);
expect(new Date(st.body.snapshotAt).getTime()).toBe(t2.getTime());
// Normaler Brew: gleiche Routen, kein Git-Feld
const normal = await request.get(`/api/fetch/${plain.body.shareId}`);
expect(normal.status).toBe(200);
expect(normal.body.brew.text).toContain('Ohne Git');
expect((await request.get(`/source/${plain.body.shareId}`)).text).toContain('Ohne Git');
expect((await api('get', `/api/git/brews/${plain.body.editId}`)).body).toEqual({ linked: false });
});
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']);
+16
View File
@@ -383,6 +383,22 @@ describe('Speichern (Hook beforeBrewSave/afterBrewSave)', ()=>{
});
});
describe('Teilen (Snapshot)', ()=>{
test('Status nennt den Zeitpunkt des Snapshots, ohne Token oder Zugangsdaten', async ()=>{
const { brew, save } = await linked();
const stamp = new Date('2026-01-02T03:04:05Z');
await storage.brews.update({ ...(await storage.brews.findByEditId(brew.editId)), updatedAt: stamp });
let st = await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(ALICE()));
expect(new Date(st.body.snapshotAt)).toEqual(stamp);
const later = new Date('2026-02-02T03:04:05Z');
await save('Version 2');
await storage.brews.update({ ...(await storage.brews.findByEditId(brew.editId)), updatedAt: later });
st = await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(ALICE()));
expect(new Date(st.body.snapshotAt)).toEqual(later);
expect(JSON.stringify(st.body)).not.toContain(remote.token);
});
});
describe('Pull und Abgleich beim Öffnen', ()=>{
test('Pull übernimmt den Remote-Stand in den Snapshot (Version + 1)', async ()=>{
const { dir, brew } = await linked();