Compare commits
@@ -56,6 +56,21 @@ APP_SECRET="bitte-aendern-mindestens-32-zeichen-langer-zufallswert"
|
||||
# Lebensdauer einer Anmeldung in Tagen.
|
||||
SESSION_TTL_DAYS="30"
|
||||
|
||||
# ── Benachrichtigungen ───────────────────────────────────────
|
||||
# ntfy und Webhook brauchen nichts weiter – die Ziele werden in der
|
||||
# Anwendung unter "Mein Konto" eingerichtet.
|
||||
#
|
||||
# E-Mail steht erst zur Verfuegung, wenn SMTP_HOST gesetzt ist:
|
||||
# SMTP_HOST="smtp.example.com"
|
||||
# SMTP_PORT="587"
|
||||
# SMTP_SECURE="false" # true bei Port 465, sonst STARTTLS
|
||||
# SMTP_USER="nebula@example.com"
|
||||
# SMTP_PASSWORD="geheim"
|
||||
# SMTP_FROM="Nebula <nebula@example.com>"
|
||||
|
||||
# Timeout fuer das Zustellen in Millisekunden
|
||||
NOTIFY_TIMEOUT_MS="10000"
|
||||
|
||||
# ── Ausgehende Git-Zugriffe ──────────────────────────────────
|
||||
# Timeout fuer Git-API-Aufrufe in Millisekunden
|
||||
GIT_API_TIMEOUT_MS="15000"
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# Prueft jeden Push und jeden Pull Request.
|
||||
#
|
||||
# Die Datei liegt unter .gitea/workflows und wird von Gitea Actions gelesen.
|
||||
# Die Syntax ist mit GitHub Actions kompatibel – wer das Repo dorthin
|
||||
# spiegelt, kopiert sie nach .github/workflows.
|
||||
#
|
||||
# Voraussetzung: In der Gitea-Instanz muessen Actions aktiviert sein
|
||||
# (app.ini: [actions] ENABLED = true) und mindestens ein Runner registriert.
|
||||
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
pruefen:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: nebula
|
||||
POSTGRES_PASSWORD: nebula
|
||||
# Der Name muss "test" enthalten – global-setup.ts leert die
|
||||
# Datenbank und weigert sich bei allem anderen.
|
||||
POSTGRES_DB: nebula_e2e_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U nebula"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 20
|
||||
|
||||
env:
|
||||
DATABASE_URL: postgresql://nebula:nebula@localhost:5432/nebula_e2e_test?schema=public
|
||||
E2E_DATABASE_URL: postgresql://nebula:nebula@localhost:5432/nebula_e2e_test?schema=public
|
||||
# Nur fuer den Lauf – keine echten Daten im Spiel.
|
||||
APP_SECRET: ci-lauf-schluessel-nur-fuer-die-pipeline-0123456789
|
||||
NEXT_TELEMETRY_DISABLED: "1"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
- name: Abhaengigkeiten
|
||||
run: npm ci
|
||||
|
||||
- name: Typen pruefen
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Unit-Tests
|
||||
run: npm test
|
||||
|
||||
- name: Browser fuer die Oberflaechentests
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
# Baut zuerst und startet den Server dann selbst (siehe
|
||||
# playwright.config.ts, webServer).
|
||||
- name: Ende-zu-Ende-Tests
|
||||
run: npm run test:e2e
|
||||
|
||||
- name: Bericht bei Fehlschlag sichern
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: playwright-bericht
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
retention-days: 7
|
||||
@@ -46,6 +46,12 @@ yarn-error.log*
|
||||
# Sicherungen aus scripts/backup.* – enthalten alle Daten der Instanz
|
||||
/backups
|
||||
|
||||
# Playwright
|
||||
/test-results
|
||||
/playwright-report
|
||||
/blob-report
|
||||
/playwright/.cache
|
||||
|
||||
# editors
|
||||
.idea/
|
||||
.vscode/*
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# Nebula – Hinweise für Claude Code
|
||||
|
||||
Dashboard für Vibe-Coding-Projekte. Next.js 15 (App Router), TypeScript,
|
||||
Tailwind 4, Prisma, PostgreSQL. Oberfläche und Texte sind **deutsch**.
|
||||
|
||||
Funktionsumfang: [FEATURES.md](FEATURES.md) · Geplantes: [ROADMAP.md](ROADMAP.md) ·
|
||||
Betrieb: [README.md](README.md)
|
||||
|
||||
## Womit man arbeitet
|
||||
|
||||
```bash
|
||||
docker compose up -d db # Postgres, muss laufen
|
||||
npm run dev # Entwicklung
|
||||
npm test # Unit-Tests (Vitest, ohne DB)
|
||||
npx tsc --noEmit # Typprüfung
|
||||
npm run build # Produktionsbau
|
||||
docker compose --profile full up -d --build # alles im Container
|
||||
```
|
||||
|
||||
**Vor dem `npm run build` einen laufenden `npm start`/`npm run dev` beenden.**
|
||||
Sonst hält der Prozess die Prisma-Engine-DLL und der Bau bricht unter Windows
|
||||
mit `EPERM … query_engine-windows.dll.node` ab.
|
||||
|
||||
## Nicht verhandelbar
|
||||
|
||||
**Datentrennung.** Jede Abfrage filtert auf den Besitzer, und zwar an erster
|
||||
Stelle in der `where`-Klausel. Schreiben und Löschen laufen über
|
||||
`updateMany`/`deleteMany` mit `ownerId`, damit fremde Datensätze gar nicht
|
||||
erst getroffen werden. Fremde IDs liefern **404, nicht 403** — die Antwort
|
||||
soll nicht bestätigen, dass es den Datensatz gibt.
|
||||
|
||||
**Jeder Endpunkt prüft selbst.** `requireUserApi()` bzw. `requireUserPage()`
|
||||
sind die Sicherheitsgrenze. Die Middleware schaut nur, ob überhaupt ein
|
||||
Cookie mitkommt — im Edge-Runtime gibt es keine Datenbank.
|
||||
|
||||
**Eingaben validieren.** Zod an jeder API-Grenze, Body über `readJsonBody`
|
||||
(erzwingt `application/json` und begrenzt die Größe).
|
||||
|
||||
**Keine Geheimnisse nach außen.** Git-Tokens verlassen den Server nie;
|
||||
Verbindungen werden über `connectionSafeSelect` geladen. Projekt-Exporte
|
||||
enthalten grundsätzlich keine Tokens.
|
||||
|
||||
**Ausgehende Aufrufe nur über `lib/git/http.ts`** — dort greift der
|
||||
SSRF-Schutz (`lib/security/ssrf.ts`).
|
||||
|
||||
## Fallstricke, die schon zugeschlagen haben
|
||||
|
||||
- **`node:`-Module in Client-Komponenten.** `lib/crypto`, `lib/auth/password`,
|
||||
`lib/git/index` ziehen `node:crypto`/`node:net` nach. Client-Komponenten
|
||||
importieren stattdessen `lib/git/meta` bzw. `lib/auth/constants`.
|
||||
- **`instrumentation.ts` wird auch für Edge übersetzt.** Der dynamische Import
|
||||
muss *innerhalb* von `if (process.env.NEXT_RUNTIME === "nodejs")` stehen,
|
||||
sonst scheitert der Bau an `node:crypto`.
|
||||
- **Eigene CSS-Klassen gehören in `app/components.css`** und dort in
|
||||
`@layer components`. Außerhalb eines Layers gewinnen sie gegen
|
||||
Tailwind-Utilities — dann greift `pl-9` neben `.field` nicht mehr.
|
||||
- **Menüs und Dialoge über Portal.** Karten setzen `overflow-hidden` und
|
||||
`backdrop-filter`; Letzteres erzeugt einen neuen Bezugsrahmen, in dem
|
||||
`position: fixed` und `z-index` nicht mehr wie erwartet wirken. Dafür gibt
|
||||
es `components/ui/Popover.tsx` und `components/ui/Modal.tsx`.
|
||||
- **Overlays brauchen einen deckenden Hintergrund** (`.popover`), nicht
|
||||
`.glass` — dessen 3,5 % Deckkraft lassen alles durchscheinen.
|
||||
- **Datumsangaben** über `lib/utils` formatieren (feste Zeitzone), sonst
|
||||
weichen Server-Render und Hydration voneinander ab. Relative Zeiten
|
||||
bekommen `suppressHydrationWarning`.
|
||||
|
||||
## Migrationen
|
||||
|
||||
`prisma migrate dev` ist hier nicht benutzbar (interaktiv). Stattdessen:
|
||||
|
||||
```bash
|
||||
docker exec nebula-db psql -U nebula -d postgres -c "CREATE DATABASE nebula_shadow"
|
||||
npx prisma migrate diff --from-migrations prisma/migrations \
|
||||
--to-schema-datamodel prisma/schema.prisma \
|
||||
--shadow-database-url postgresql://nebula:nebula@localhost:5432/nebula_shadow \
|
||||
--script --output prisma/migrations/<stempel>_<name>/migration.sql
|
||||
npx prisma migrate deploy
|
||||
```
|
||||
|
||||
**`--from-migrations`, nicht `--from-schema-datasource`.** Letzteres
|
||||
vergleicht mit der *laufenden* Datenbank. Ist eine eben erzeugte Migration
|
||||
dort noch nicht eingespielt, steht ihr Inhalt in der nächsten gleich noch
|
||||
einmal.
|
||||
|
||||
**Die erzeugte SQL vor dem Anwenden lesen.** Der Volltextindex
|
||||
`Note_fulltext_idx` ist ein Ausdrucksindex, den Prisma nicht kennt (er wird
|
||||
bislang in Ruhe gelassen, aber das ist nicht garantiert).
|
||||
|
||||
**Datenmigrationen von Hand schreiben.** `migrate diff` kennt nur den
|
||||
Zielzustand: Spalten, die woandershin wandern, würde es ersatzlos löschen.
|
||||
Vorgehen wie in `20260726230000_repositories`: neue Tabelle anlegen, Bestand
|
||||
per `INSERT … SELECT` übernehmen, dann erst die alten Spalten entfernen.
|
||||
Danach `migrate diff` erneut laufen lassen — kommt „empty migration“ heraus,
|
||||
stimmt das Ergebnis mit dem Schema überein. Und gegen eine Kopie mit echten
|
||||
Daten prüfen, nicht nur gegen eine leere Datenbank.
|
||||
|
||||
## Prüfen, nicht behaupten
|
||||
|
||||
Vor „fertig": `npx tsc --noEmit`, `npm test`, `npm run build`.
|
||||
|
||||
Bei Änderungen an der Oberfläche **hinsehen**. Chrome ist installiert, ein
|
||||
Skript mit `playwright-core` und `channel: "chrome"` genügt für Screenshots.
|
||||
Mehrere Anzeigefehler dieses Projekts sind ausschließlich so aufgefallen.
|
||||
|
||||
Wer den Standalone-Bau von Hand startet (`node .next/standalone/server.js`),
|
||||
muss vorher `.next/static` und `public` danebenkopieren — sonst lädt kein
|
||||
JavaScript, die Seite bleibt serverseitig gerendert, und Formulare senden
|
||||
sich nativ ab. Das sieht aus wie ein Anwendungsfehler, ist aber keiner:
|
||||
|
||||
```bash
|
||||
cp -r .next/static .next/standalone/.next/ && cp -r public .next/standalone/
|
||||
```
|
||||
|
||||
`pkill` gibt es in dieser Git-Bash nicht. Prozesse über PowerShell beenden
|
||||
(`Get-CimInstance Win32_Process … | Stop-Process`) — sonst läuft der alte
|
||||
Server weiter, hält die Prisma-DLL und blockiert den nächsten Bau.
|
||||
|
||||
**Niemals gegen die echte Datenbank testen.** Eine Wegwerf-Datenbank anlegen
|
||||
und danach löschen:
|
||||
|
||||
```bash
|
||||
docker exec nebula-db psql -U nebula -d postgres -c "CREATE DATABASE nebula_test"
|
||||
DATABASE_URL=postgresql://nebula:nebula@localhost:5432/nebula_test npx prisma migrate deploy
|
||||
```
|
||||
|
||||
## Sprache
|
||||
|
||||
Code-Kommentare, Commit-Nachrichten und Oberfläche auf Deutsch, **ohne
|
||||
Umlaute in Bezeichnern und Commit-Nachrichten** (bestehende Konvention).
|
||||
In Markdown-Dateien und in der Oberfläche sind Umlaute erwünscht.
|
||||
|
||||
Commits: Conventional Commits, Betreff deutsch, Rumpf erklärt **warum** —
|
||||
nicht was der Diff ohnehin zeigt.
|
||||
+213
-10
@@ -27,6 +27,14 @@ sonst würden Konten ausgesperrt. Nach der Einrichtung ist `/setup` dauerhaft ge
|
||||
- **Passkey (WebAuthn).** Fingerabdruck, Gesichtserkennung oder Sicherheitsschlüssel. Die
|
||||
Anmeldung läuft über auffindbare Credentials, ein Benutzername ist also nicht nötig.
|
||||
Mehrere Passkeys pro Konto, benennbar und einzeln entfernbar.
|
||||
- **Zwei-Faktor per TOTP.** Zeitbasiertes Einmalkennwort zusätzlich zum Passwort, für jede
|
||||
gängige Authenticator-App. Einrichtung über QR-Code oder abgetippten Schlüssel; scharf
|
||||
wird er erst nach einem bestätigten Code, damit sich niemand aussperrt, der den Scan
|
||||
nicht hinbekommt. Dazu zehn **Wiederherstellungscodes**, jeder genau einmal gültig —
|
||||
sie werden nur bei der Ausgabe angezeigt. Abschalten und Neuerzeugen verlangen das
|
||||
Passwort, nicht bloß eine offene Sitzung.
|
||||
- Die Passkey-Anmeldung fragt **nicht** nach dem zweiten Faktor: der Passkey ist bereits an
|
||||
ein Gerät gebunden und damit selbst der zweite Faktor.
|
||||
- Ein Konto kann **ausschließlich** per Passkey nutzbar sein. Der letzte Passkey lässt sich
|
||||
dann nicht entfernen, solange kein Passwort gesetzt ist.
|
||||
- Fehlversuche werden gezählt; nach acht sperrt sich das Konto für 15 Minuten.
|
||||
@@ -35,9 +43,9 @@ sonst würden Konten ausgesperrt. Nach der Einrichtung ist `/setup` dauerhaft ge
|
||||
|
||||
### 0.3 Mein Konto
|
||||
|
||||
Anzeigename und E-Mail ändern · Passwort setzen oder wechseln · Passkeys verwalten ·
|
||||
aktive Sitzungen einsehen (Browser, Betriebssystem, IP, letzte Aktivität) · überall
|
||||
abmelden, wobei das eigene Gerät angemeldet bleibt.
|
||||
Anzeigename und E-Mail ändern · Passwort setzen oder wechseln · Zwei-Faktor einrichten und
|
||||
abschalten · Passkeys verwalten · aktive Sitzungen einsehen (Browser, Betriebssystem, IP,
|
||||
letzte Aktivität) · überall abmelden, wobei das eigene Gerät angemeldet bleibt.
|
||||
|
||||
### 0.4 Benutzerverwaltung (Administratoren)
|
||||
|
||||
@@ -117,6 +125,19 @@ Der Status ist **direkt auf der Projektkarte** umschaltbar, ohne den Detailberei
|
||||
- **Archiv** ist standardmäßig ausgeblendet und per Schalter einblendbar.
|
||||
- **Leerzustände** mit direktem Einstieg statt einer leeren Fläche.
|
||||
|
||||
### Schnellsuche
|
||||
|
||||
**`Strg+K`** (auf dem Mac `Cmd+K`) öffnet überall eine Palette:
|
||||
|
||||
- **Projekte** nach Name, Kurzbeschreibung und Tags — ohne Eingabe stehen die letzten
|
||||
gleich bereit
|
||||
- **Notizen** über dieselbe Volltextsuche wie im Board, entprellt ab zwei Zeichen
|
||||
- **Bereiche**: Dashboard, Git-Verbindungen, Mein Konto, Admin-Einstellungen
|
||||
|
||||
Bedienung über Tastatur: Pfeile wählen, `Enter` öffnet, `Esc` schließt. Die Projektliste
|
||||
wird beim ersten Öffnen geholt und dann behalten — sie bei jedem Tastendruck neu zu laden
|
||||
wäre Verschwendung.
|
||||
|
||||
### Kanban
|
||||
|
||||
Spalten je Status, Karten per Ziehen verschiebbar. Der Wechsel wird sofort angezeigt und
|
||||
@@ -137,6 +158,52 @@ Anzahl Notizen · Warnung bei Sync-Fehler · Tags · Statusauswahl · Priorität
|
||||
|
||||
---
|
||||
|
||||
## 2a. Aufgaben je Projekt
|
||||
|
||||
Jedes Projekt hat ein eigenes Aufgabenbrett mit vier Spalten: **Offen · In Arbeit ·
|
||||
Blockiert · Erledigt**.
|
||||
|
||||
- **Ziehen und Ablegen** zwischen den Spalten **und innerhalb** einer Spalte. Anders als
|
||||
beim Projektbrett ist die Reihenfolge hier bedeutsam, deshalb wird sie gespeichert.
|
||||
- Gezogen wird am Griff links, damit ein Klick auf die Karte weiter den Dialog öffnet.
|
||||
- Eine Aufgabe braucht nur einen Titel. Optional: Beschreibung (Markdown),
|
||||
Fälligkeitsdatum und Labels.
|
||||
- **Fälligkeiten** färben sich mit: überfällig rot, heute gelb, in den nächsten Tagen
|
||||
gedämpft.
|
||||
- Erledigtes wird durchgestrichen; der Zeitpunkt wird festgehalten und beim Zurückziehen
|
||||
wieder gelöscht.
|
||||
|
||||
### Aus Git-Issues übernehmen
|
||||
|
||||
Im Git-Panel, Reiter *Issues*: ein Klick macht aus den offenen Issues Aufgaben — Titel,
|
||||
Labels und ein Link zurück ins Git-System.
|
||||
|
||||
- Grundlage ist der **zuletzt geholte Stand**, hier wird nichts nachgeladen. Ein Klick
|
||||
soll nicht ungefragt fremde APIs ansprechen; wer den neuesten Stand will, gleicht
|
||||
vorher ab.
|
||||
- Die Issue-Nummer bleibt an der Aufgabe und ist je Projekt eindeutig. Ein zweiter Klick
|
||||
legt deshalb **keine Dubletten** an, auch wenn die Aufgabe inzwischen verschoben oder
|
||||
umbenannt wurde.
|
||||
- Ohne Repo-Stand meldet der Server das mit einem Hinweis statt still nichts zu tun.
|
||||
|
||||
### Fortschritt aus Aufgaben
|
||||
|
||||
Pro Projekt umschaltbar. Ist es an, ergibt sich der Fortschritt aus dem Anteil erledigter
|
||||
Aufgaben und wird bei jeder Änderung neu berechnet — der Regler ist dann gesperrt, statt
|
||||
einen Wert anzubieten, der gleich wieder überschrieben würde.
|
||||
|
||||
Auf der Projektkarte im Dashboard steht das Verhältnis als `3/8`.
|
||||
|
||||
### Wie die Reihenfolge gespeichert wird
|
||||
|
||||
Beim Ablegen schickt die Oberfläche je Spalte die **vollständige Liste** der Aufgaben in
|
||||
ihrer neuen Reihenfolge; der Server vergibt daraus Position und Status. Das ist
|
||||
wiederholbar, kommt ohne Positionsrechnerei im Browser aus, und ein verlorener Aufruf
|
||||
lässt sich einfach erneut senden. IDs, die nicht zum Projekt gehören, werden ignoriert
|
||||
statt verschoben.
|
||||
|
||||
---
|
||||
|
||||
## 3. Notizen
|
||||
|
||||
- **Beliebig viele Notizen pro Projekt**, mit optionalem Titel und mehrzeiligem Text.
|
||||
@@ -156,6 +223,31 @@ Anzahl Notizen · Warnung bei Sync-Fehler · Tags · Statusauswahl · Priorität
|
||||
|
||||
## 4. Git-Anbindung
|
||||
|
||||
### 4.0 Mehrere Repositories je Projekt
|
||||
|
||||
Ein Vorhaben besteht oft aus mehreren Repositories — Frontend und Backend etwa, oder
|
||||
App und Infrastruktur. Sie gehören trotzdem in **eine** Karte.
|
||||
|
||||
- Im Git-Panel steht eine Leiste mit allen Repositories des Projekts, sobald es mehr als
|
||||
eines gibt. Jedes hat eigene Kennzahlen, Listen, CI und eigenen Abgleich; „Alle" gleicht
|
||||
sie nacheinander ab — nicht gleichzeitig, denn ein Schwung Anfragen an denselben Anbieter
|
||||
ist genau das, worauf Rate-Limits reagieren.
|
||||
- Eine frei wählbare **Bezeichnung** („Frontend") tritt an die Stelle von `owner/name`.
|
||||
- Das erste Repository ist das **führende**. Wo nur eines dargestellt werden kann — auf der
|
||||
Karte im Dashboard, im Kanban —, ist es dieses. Die Karte zeigt daneben `+2 Repos`.
|
||||
Ein Abgleichsfehler an *irgendeinem* Repository erscheint auf der Karte, sonst bliebe er
|
||||
unbemerkt.
|
||||
- **Stillstand** bemisst sich am jüngsten Commit über alle Repositories: an einem Vorhaben
|
||||
wird gearbeitet, sobald an einem seiner Teile gearbeitet wird.
|
||||
- Benachrichtigungen merken sich den gemeldeten Zustand **je Repository**. Sonst verdeckte
|
||||
ein rotes Frontend die rote Pipeline des Backends. Der Betreff nennt das Repository nur,
|
||||
wenn es nicht ohnehin so heißt wie das Projekt.
|
||||
- Übernommene Issues merken sich, aus welchem Repository sie stammen — Frontend und Backend
|
||||
haben beide ein Issue Nummer 5, und das sind zwei Aufgaben.
|
||||
|
||||
Der Projektdialog bearbeitet weiterhin nur das führende Repository; weitere verwaltet das
|
||||
Git-Panel. Beim Anlegen eines Projekts entsteht aus den Git-Feldern das erste.
|
||||
|
||||
### 4.1 Unterstützte Systeme
|
||||
|
||||
| System | API | Authentifizierung | Besonderheit |
|
||||
@@ -289,6 +381,75 @@ Dateneinsicht. Ein Administrator sieht dadurch weiterhin keine fremden Projekte.
|
||||
|
||||
---
|
||||
|
||||
## 4b. Benachrichtigungen
|
||||
|
||||
Einzurichten unter *Mein Konto → Benachrichtigungen*, pro Konto und beliebig viele Ziele.
|
||||
|
||||
### Anlässe
|
||||
|
||||
| Anlass | Wann |
|
||||
| --- | --- |
|
||||
| ⚠️ **Abgleich fehlgeschlagen** | Das Git-System war nicht erreichbar oder hat abgelehnt |
|
||||
| 🔴 **CI rot** | Der letzte Lauf auf dem Default-Branch ist fehlgeschlagen |
|
||||
| 🏷️ **Neues Release** | Ein neuer Tag oder ein neues Release ist aufgetaucht |
|
||||
| 🕸️ **Projekt steht still** | Seit längerem kein Commit — Schwelle einstellbar, Vorgabe 60 Tage |
|
||||
|
||||
### Nur bei Änderung
|
||||
|
||||
Der entscheidende Punkt: Gemeldet wird **ausschließlich, wenn sich etwas ändert**
|
||||
gegenüber dem, worüber zuletzt benachrichtigt wurde. Ein Repository mit abgelaufenem
|
||||
Token meldet sich also **einmal**, nicht bei jedem stündlichen Durchlauf. Wird der Fehler
|
||||
ein anderer, kommt eine neue Meldung; ist er behoben und tritt später erneut auf, ebenso.
|
||||
|
||||
Zwei Feinheiten:
|
||||
|
||||
- **Beim allerersten Abgleich** eines Repositories wird kein Release gemeldet — sonst
|
||||
wäre jede bereits vorhandene Version eine „Neuigkeit".
|
||||
- Der Merkstand wird auch dann fortgeschrieben, wenn **kein** Ziel eingerichtet ist. Sonst
|
||||
käme beim ersten eingerichteten Ziel die ganze Vergangenheit hinterher.
|
||||
|
||||
### Stillstand
|
||||
|
||||
Der einzige Anlass, der an keinem Ereignis hängt — es passiert ja gerade nichts. Deshalb
|
||||
ein eigener Durchlauf, **höchstens einmal am Tag**, unabhängig vom automatischen Abgleich.
|
||||
Hört niemand auf diesen Anlass, läuft die Prüfung gar nicht erst.
|
||||
|
||||
Maßstab ist ausschließlich der **letzte Commit** im verknüpften Repository. Das
|
||||
Änderungsdatum des Projekts taugt nicht: jeder Abgleich fasst es an und würde den
|
||||
Stillstand immer wieder zurücksetzen. Projekte **ohne Repository** bleiben deshalb außen
|
||||
vor, ebenso fertige und archivierte.
|
||||
|
||||
Gemeldet wird je Projekt einmal. Erneut erst, wenn danach wieder ein Commit kam und es
|
||||
seitdem wieder still geworden ist — ein Projekt, das aufwacht und wieder einschläft, meldet
|
||||
sich also ein zweites Mal.
|
||||
|
||||
Die Schwelle setzt ein Administrator unter *Admin-Einstellungen → Stillstand* (14 Tage bis
|
||||
ein Jahr). Eine Änderung wirkt sofort, nicht erst nach 24 Stunden.
|
||||
|
||||
### Zustellwege
|
||||
|
||||
| Weg | Details |
|
||||
| --- | --- |
|
||||
| **ntfy** | Vollständige Themen-URL. Titel, Priorität und Symbol als Kopfzeilen; optionales Bearer-Token für geschützte Themen. Läuft auch gegen ein selbst gehostetes ntfy im eigenen Netz. |
|
||||
| **Webhook** | JSON per POST mit Anlass, Titel, Text, Projektbezug und Tieflink. Mit hinterlegtem Geheimnis wird der Rumpf per HMAC-SHA256 signiert (`X-Nebula-Signature`), damit der Empfänger die Herkunft prüfen kann. |
|
||||
| **E-Mail** | Über SMTP. Steht erst zur Verfügung, wenn `SMTP_HOST` in der `.env` gesetzt ist — sonst ist die Auswahl in der Oberfläche gesperrt und erklärt, warum. |
|
||||
|
||||
Jedes Ziel lässt sich einzeln **testen** und **pausieren**; Ergebnis und Zeitpunkt der
|
||||
letzten Zustellung stehen an der Karte.
|
||||
|
||||
### Absicherung
|
||||
|
||||
- Zieladressen sind Benutzereingaben, die der Server abruft — sie laufen deshalb durch
|
||||
denselben **SSRF-Schutz** wie die Git-Verbindungen. Ein ntfy im eigenen Netz bleibt
|
||||
erlaubt, Loopback und Cloud-Metadaten nicht.
|
||||
- Redirects werden **nicht verfolgt**: ein Umleitungsziel wäre nicht geprüft.
|
||||
- Geheimnisse liegen AES-256-GCM-verschlüsselt und verlassen den Server nie; die
|
||||
Oberfläche zeigt nur einen Hinweis wie `test…mnis`.
|
||||
- Eine fehlgeschlagene Zustellung lässt den Abgleich nicht scheitern — der Fehler landet
|
||||
am Ziel, nicht im Sync.
|
||||
|
||||
---
|
||||
|
||||
## 5. Oberfläche
|
||||
|
||||
- **Dark Glassmorphism**: milchige Glasflächen, driftende Nebel im Hintergrund, feines
|
||||
@@ -313,11 +474,17 @@ Dateneinsicht. Ein Administrator sieht dadurch weiterhin keine fremden Projekte.
|
||||
| `Session` | Serverseitige Sitzungen (nur der Token-Hash) |
|
||||
| `Credential` | Passkeys inkl. öffentlichem Schlüssel und Signaturzähler |
|
||||
| `WebAuthnChallenge` | Kurzlebige, einmalig verwendbare Challenges |
|
||||
| `RecoveryCode` | Wiederherstellungscodes für die Zwei-Faktor-Anmeldung (nur der Hash) |
|
||||
| `PendingLogin` | Zwischenzustand zwischen Passwort und zweitem Faktor, fünf Minuten gültig |
|
||||
| `AppSettings` | Betriebsart und Registrierung (eine Zeile) |
|
||||
| `Project` | Projektstammdaten, Status, Fortschritt, Repo-Verknüpfung, Besitzer |
|
||||
| `Project` | Projektstammdaten, Status, Fortschritt, Besitzer |
|
||||
| `Repository` | Repositories eines Projekts inkl. Abgleichstand (n:1 zu Projekt) |
|
||||
| `Task` | Aufgaben mit Spalte, Position, Fälligkeit, Labels und Issue-Herkunft |
|
||||
| `Activity` | Verlauf je Projekt, neueste zuerst, auf 200 Einträge begrenzt |
|
||||
| `NotificationTarget` | Zustellwege je Konto, mit verschlüsseltem Geheimnis |
|
||||
| `Note` | Notizen (n:1 zu Projekt, Cascade-Delete) |
|
||||
| `GitConnection` | Git-Systeme inkl. verschlüsseltem Token, Besitzer |
|
||||
| `RepoSnapshot` | Zwischengespeicherter Repo-Stand (1:1 zu Projekt) |
|
||||
| `RepoSnapshot` | Zwischengespeicherter Repo-Stand (1:1 zu Repository) |
|
||||
|
||||
`Project.ownerId` und `GitConnection.ownerId` sind bewusst optional: so überleben Daten aus
|
||||
der Zeit vor der Benutzerverwaltung die Migration und werden beim Anlegen des ersten Kontos
|
||||
@@ -368,8 +535,10 @@ nicht verloren gehen. Indizes auf Status, Verbindung und Änderungsdatum.
|
||||
|
||||
### 6.4 Tests
|
||||
|
||||
`npm test` führt die Unit-Tests aus — reine Logik, kein DOM, keine Datenbank, unter einer
|
||||
Sekunde:
|
||||
Zwei Ebenen. `npm run test:all` führt beide aus.
|
||||
|
||||
**`npm test` — Unit-Tests** (Vitest, 56 Stück, unter einer Sekunde, ohne DOM und ohne
|
||||
Datenbank):
|
||||
|
||||
| Bereich | Was geprüft wird |
|
||||
| --- | --- |
|
||||
@@ -377,11 +546,45 @@ Sekunde:
|
||||
| `git/parse` | URL-Zerlegung für https, SSH, verschachtelte GitLab-Gruppen und Oberflächenpfade; Provider-Erkennung; Bildung der Aktivitätskurve |
|
||||
| `security/ssrf` | Sperrlisten für Loopback, Link-Local, Metadaten-Endpunkt, CGNAT und Multicast; Formprüfung; die drei Umgebungsschalter |
|
||||
| `auth/password` | scrypt-Rundlauf, unterschiedliches Salz, Ablageformat, Verhalten bei kaputten Hashes, Passwortregeln |
|
||||
| `tasks` | Berechnung des abgeleiteten Fortschritts, Spaltenreihenfolge |
|
||||
| `notify/pending` | Wann eine Benachrichtigung fällig ist: neuer Fehler ja, gleicher Fehler nein; CI-Wechsel nach rot; Release erst ab dem zweiten Abgleich |
|
||||
| `notify/stale` | Stillstandsschwelle, keine Zweitmeldung, aber erneute Meldung nach zwischenzeitlicher Aktivität |
|
||||
| `validation` | Dass jeder Anlass, den die Oberfläche anbietet, auch vom Schema akzeptiert wird — entstanden aus genau diesem Fehler |
|
||||
|
||||
Bewusst ohne Datenbank- und Browsertests: die brauchen Infrastruktur und gehören in eine
|
||||
CI-Pipeline. Das steht in der [ROADMAP](ROADMAP.md).
|
||||
**`npm run test:e2e` — Ende-zu-Ende** (Playwright, 13 Stück, rund 20 Sekunden). Läuft
|
||||
gegen die gebaute Anwendung mit eigener Datenbank auf Port 3111 — also durch Middleware,
|
||||
Authentifizierung, Validierung und Datenbank hindurch:
|
||||
|
||||
### 6.5 API
|
||||
| Datei | Was geprüft wird |
|
||||
| --- | --- |
|
||||
| `e2e/api.spec.ts` | Einrichtung sperrt sich nach dem ersten Konto · kein Zugriff ohne Anmeldung · fremdes Origin und falscher Content-Type abgewiesen · SSRF geblockt · **Datentrennung zwischen zwei Konten** · Aufgaben-Reihenfolge, abgeleiteter Fortschritt und untergeschobene IDs · Export ohne Geheimnisse, Import je Strategie |
|
||||
| `e2e/ui.spec.ts` | Anmelden · Projekt anlegen · Aufgaben anlegen und **per Ziehen verschieben** (inklusive Prüfung nach dem Neuladen) · Volltextsuche · Abmelden sperrt geschützte Seiten wieder |
|
||||
|
||||
Zwei Dinge sind bewusst so gebaut:
|
||||
|
||||
- **Die Testdatenbank kann nicht die echte sein.** `e2e/global-setup.ts` bricht ab, wenn
|
||||
der Datenbankname nicht `test` enthält — vor dem `TRUNCATE`. Der teuerste denkbare
|
||||
Fehler wäre eine Testreihe, die die Produktivdaten leert.
|
||||
- **Playwright startet den Server selbst** (`webServer` in `playwright.config.ts`) mit
|
||||
eigener `DATABASE_URL` und eigenem Port. Eine laufende Instanz auf 3000 stört nicht.
|
||||
|
||||
Einmalig vorbereiten:
|
||||
|
||||
```bash
|
||||
docker exec nebula-db psql -U nebula -d postgres -c "CREATE DATABASE nebula_e2e_test"
|
||||
```
|
||||
|
||||
### 6.5 Fortlaufende Prüfung
|
||||
|
||||
`.gitea/workflows/ci.yml` prüft jeden Push und jeden Pull Request: Typen, Unit-Tests,
|
||||
Bau und Ende-zu-Ende-Tests gegen einen frischen PostgreSQL-Dienst. Schlägt etwas fehl,
|
||||
wird der Playwright-Bericht als Artefakt abgelegt.
|
||||
|
||||
Dafür müssen in der Gitea-Instanz Actions aktiviert sein (`app.ini`: `[actions] ENABLED
|
||||
= true`) und ein Runner registriert. Die Syntax ist GitHub-kompatibel — für GitHub die
|
||||
Datei nach `.github/workflows/` kopieren.
|
||||
|
||||
### 6.6 API
|
||||
|
||||
Zehn REST-Endpunkte für Projekte, Notizen, Verbindungen, Sync, Repo-Listen und Health.
|
||||
Alles, was die Oberfläche kann, ist damit auch scriptbar. Übersicht in der
|
||||
|
||||
@@ -127,6 +127,8 @@ Alle Variablen sind in [`.env.example`](.env.example) dokumentiert.
|
||||
| `GIT_ALLOW_LOOPBACK` | Git-Instanz auf demselben Rechner erlauben | `false` |
|
||||
| `GIT_BLOCK_PRIVATE` | Zugriff ins private LAN sperren | `false` |
|
||||
| `GIT_ALLOWED_HOSTS` | Strengster Modus: nur diese Hosts erlauben | leer |
|
||||
| `NOTIFY_TIMEOUT_MS` | Timeout beim Zustellen von Benachrichtigungen | `10000` |
|
||||
| `SMTP_HOST` … `SMTP_FROM` | SMTP-Zugang; ohne `SMTP_HOST` steht der Weg „E-Mail" nicht zur Verfügung | leer |
|
||||
|
||||
`APP_NAME`, `APP_TAGLINE` und `APP_URL` werden **zur Laufzeit** gelesen. Dasselbe
|
||||
Docker-Image lässt sich also ohne Neubau umbenennen oder unter einer anderen Adresse
|
||||
@@ -301,6 +303,9 @@ nebula/
|
||||
| `npm test` | Unit-Tests (Vitest), unter einer Sekunde |
|
||||
| `npm run test:watch` | Tests im Beobachtungsmodus |
|
||||
| `npm run typecheck` | TypeScript prüfen |
|
||||
| `npm test` | Unit-Tests (Vitest, ohne Datenbank) |
|
||||
| `npm run test:e2e` | Ende-zu-Ende-Tests (Playwright, baut vorher) |
|
||||
| `npm run test:all` | Beides nacheinander |
|
||||
| `npm run docker:db` | Nur die Datenbank starten |
|
||||
| `npm run docker:up` / `docker:down` | Kompletten Stack starten / stoppen |
|
||||
| `npm run docker:tools` | Adminer auf `http://localhost:8080` |
|
||||
@@ -319,12 +324,15 @@ ausschließlich Daten des angemeldeten Kontos.
|
||||
| `GET` | `/api/health` | Status inkl. Datenbankverbindung (Docker-Healthcheck) |
|
||||
| `POST` | `/api/auth/setup` | Administratorkonto anlegen (nur beim ersten Mal) |
|
||||
| `POST` | `/api/auth/login` `/api/auth/logout` `/api/auth/register` | Anmeldung |
|
||||
| `POST` | `/api/auth/mfa` | Zweiter Faktor: Einmalkennwort oder Wiederherstellungscode |
|
||||
| `GET` | `/api/auth/session` | Aktuelle Sitzung und Instanzzustand |
|
||||
| `POST` | `/api/auth/passkey/{login,register}/{options,verify}` | WebAuthn |
|
||||
| `PATCH` | `/api/account/profile` | Eigenes Profil |
|
||||
| `POST` | `/api/account/password` | Eigenes Passwort setzen |
|
||||
| `GET` `DELETE` | `/api/account/sessions` | Eigene Sitzungen / überall abmelden |
|
||||
| `PATCH` `DELETE` | `/api/account/passkeys/:id` | Passkey umbenennen / entfernen |
|
||||
| `GET` `POST` `PUT` `DELETE` | `/api/account/totp` | Zwei-Faktor: Zustand, einrichten, aktivieren, abschalten |
|
||||
| `POST` | `/api/account/totp/recovery` | Neue Wiederherstellungscodes |
|
||||
| `GET` `PATCH` | `/api/admin/settings` | Betriebsart, Registrierung, Abgleich (Admin) |
|
||||
| `POST` | `/api/admin/sync/run` | Abgleich sofort anstoßen (Admin) |
|
||||
| `GET` `POST` | `/api/admin/users` | Konten auflisten / anlegen (Admin) |
|
||||
@@ -335,8 +343,19 @@ ausschließlich Daten des angemeldeten Kontos.
|
||||
| `POST` | `/api/projects/import` | Import, mit `dryRun` für die Vorschau |
|
||||
| `GET` | `/api/admin/backup` | Vollständige Sicherung als JSON (Admin) |
|
||||
| `GET` | `/api/search?q=` | Volltextsuche über die eigenen Notizen |
|
||||
| `GET` `POST` | `/api/notifications` | Benachrichtigungsziele |
|
||||
| `PATCH` `DELETE` | `/api/notifications/:id` | Ziel ändern / entfernen |
|
||||
| `POST` | `/api/notifications/:id/test` | Testnachricht senden |
|
||||
| `GET` `PATCH` `DELETE` | `/api/projects/:id` | Projekt lesen / ändern / löschen |
|
||||
| `POST` | `/api/projects/:id/sync` | Repo-Daten vom Git-System holen |
|
||||
| `POST` | `/api/projects/:id/sync` | Alle Repositories des Projekts abgleichen |
|
||||
| `GET` | `/api/projects/:id/activity` | Verlauf des Projekts (`?limit=`) |
|
||||
| `GET` `POST` | `/api/projects/:id/repositories` | Repositories des Projekts |
|
||||
| `PATCH` `DELETE` | `/api/repositories/:id` | Repository ändern / vom Projekt lösen |
|
||||
| `POST` | `/api/repositories/:id/sync` | Ein einzelnes Repository abgleichen |
|
||||
| `GET` `POST` | `/api/projects/:id/tasks` | Aufgaben des Projekts |
|
||||
| `PATCH` | `/api/projects/:id/tasks/reorder` | Neue Reihenfolge nach dem Ziehen |
|
||||
| `POST` | `/api/projects/:id/tasks/from-issues` | Offene Issues als Aufgaben übernehmen |
|
||||
| `PATCH` `DELETE` | `/api/tasks/:id` | Aufgabe ändern / löschen |
|
||||
| `GET` `POST` | `/api/projects/:id/notes` | Notizen des Projekts |
|
||||
| `PATCH` `DELETE` | `/api/notes/:id` | Notiz ändern / löschen |
|
||||
| `GET` `POST` | `/api/connections` | Git-Verbindungen |
|
||||
|
||||
+15
-46
@@ -11,50 +11,24 @@ Was bereits steht, listet [FEATURES.md](FEATURES.md).
|
||||
|
||||
## 1 · Als Nächstes empfohlen
|
||||
|
||||
### 1.1 Tests ausbauen: Datenbank und Browser `L`
|
||||
|
||||
Das Fundament steht — 51 Unit-Tests der reinen Logik laufen in unter einer
|
||||
Sekunde. Was fehlt, ist die Schicht darüber:
|
||||
|
||||
- **Integrationstests** gegen eine Wegwerf-Datenbank: Datentrennung zwischen
|
||||
Konten, Import-Strategien, Backoff des Abgleichs
|
||||
- **Playwright** für die Wege durch die App: Einrichtung, Anmeldung, Kanban
|
||||
- **CI-Pipeline** bei GitHub oder Gitea Actions
|
||||
|
||||
Ich prüfe bislang alles von Hand, inklusive Screenshots. Das trägt nicht
|
||||
dauerhaft und macht jede weitere Änderung teurer als nötig.
|
||||
|
||||
### 1.2 Benachrichtigungen `M`
|
||||
|
||||
Bei Sync-Fehlern, roter CI, neuen Releases oder Projekten, die lange
|
||||
stillstehen. Kanäle: E-Mail (SMTP), ntfy, generischer Webhook. Zusammen mit
|
||||
dem automatischen Abgleich und dem CI-Status ergibt das ein brauchbares
|
||||
Frühwarnsystem — die Daten liegen bereits vor.
|
||||
|
||||
### 1.3 Aufgaben und Checklisten `M`
|
||||
|
||||
Eigene Entität statt Freitext, mit Häkchen und automatisch berechnetem
|
||||
Fortschritt. Ersetzt das manuelle Schieben des Reglers. Die Markdown-
|
||||
Checklisten in Notizen sind ein Vorgeschmack, aber nicht auswertbar.
|
||||
|
||||
---
|
||||
|
||||
## 2 · Danach
|
||||
|
||||
### 2.1 Webhooks statt Polling `M`
|
||||
### 1.1 Webhooks statt Polling `M`
|
||||
|
||||
Ein Push aktualisiert den Snapshot sofort, statt bis zum nächsten Durchlauf
|
||||
zu warten. Braucht einen öffentlich erreichbaren Endpunkt mit
|
||||
Signaturprüfung je Provider — sinnvoll erst, wenn die Instanz von außen
|
||||
erreichbar ist. Der Zeitplan bleibt als Rückfalllösung.
|
||||
|
||||
### 2.2 Commit-Aktivität als Heatmap `S`
|
||||
---
|
||||
|
||||
## 2 · Danach
|
||||
|
||||
### 2.1 Commit-Aktivität als Heatmap `S`
|
||||
|
||||
Die Sparkline gibt es auf Karte und Projektseite. Eine Heatmap über ein Jahr
|
||||
wäre die nächste Ausbaustufe — dafür braucht es allerdings mehr als eine
|
||||
Seite Commits, also Paginierung oder die Statistik-Endpunkte.
|
||||
|
||||
### 2.3 Kanban mit freier Reihenfolge `M`
|
||||
### 2.2 Kanban mit freier Reihenfolge `M`
|
||||
|
||||
Heute folgt die Reihenfolge innerhalb einer Spalte der gewählten Sortierung.
|
||||
Frei sortieren hieße, eine Position je Projekt zu speichern.
|
||||
@@ -63,17 +37,7 @@ Frei sortieren hieße, eine Position je Projekt zu speichern.
|
||||
|
||||
## 3 · Größere Brocken
|
||||
|
||||
### 3.1 Mehrere Repositories je Projekt `M`
|
||||
|
||||
Frontend und Backend getrennt, aber ein Projekt. Erfordert eine Zwischentabelle
|
||||
und Anpassungen in der Anzeige.
|
||||
|
||||
### 3.2 Zwei-Faktor per TOTP `M`
|
||||
|
||||
Als Alternative zum Passkey — nützlich, wenn die Instanz aus dem Internet
|
||||
erreichbar ist und nicht jedes Gerät Passkeys kann.
|
||||
|
||||
### 3.3 Passwort-Zurücksetzen per E-Mail `M`
|
||||
### 3.1 Passwort-Zurücksetzen per E-Mail `M`
|
||||
|
||||
Heute setzt ein Administrator das Passwort neu. Selbstbedienung braucht SMTP
|
||||
und damit eine weitere Konfiguration — lohnt erst im Mehrbenutzerbetrieb.
|
||||
@@ -89,10 +53,9 @@ Voraussetzung, falls du das Projekt veröffentlichen willst.
|
||||
|
||||
| Idee | Aufwand | Nutzen |
|
||||
| --- | --- | --- |
|
||||
| Schnellsuche per `Strg+K` | `S` | Springt direkt zu Projekt oder Aktion |
|
||||
| Suchtreffer in Notizen hervorheben | `S` | In der Notiz selbst, nicht nur in der Trefferliste |
|
||||
| Mehrfachauswahl im Board | `S` | Status oder Tags für mehrere auf einmal |
|
||||
| Aktivitätsverlauf je Projekt | `S` | Wer hat wann was geändert |
|
||||
| Wiederkehrende Aufgaben | `M` | Etwa „jeden Montag Abhängigkeiten prüfen" |
|
||||
| Projektvorlagen | `S` | Neues Projekt mit vorgefüllten Tags und Notizen |
|
||||
| Hell/Dunkel umschaltbar | `M` | Aktuell nur dunkel |
|
||||
| Eigenes Logo und Farbe | `S` | Ergänzt `APP_NAME` |
|
||||
@@ -132,6 +95,12 @@ Damit klar ist, was **nicht** kommt und warum:
|
||||
| Export, Import und Sicherung | ✓ |
|
||||
| **v0.3.0** Markdown, Volltextsuche über Notizen, PR- und Issue-Listen, Testfundament | ✓ |
|
||||
| **v0.4.0** Kanban mit Drag & Drop, CI-Status je Branch, Commit-Aktivität | ✓ |
|
||||
| **v0.5.0** Aufgabenbrett je Projekt mit sortierbaren Spalten, Fortschritt aus Aufgaben | ✓ |
|
||||
| **v0.6.0** Ende-zu-Ende-Tests mit Playwright, CI-Pipeline für Gitea Actions | ✓ |
|
||||
| **v0.7.0** Benachrichtigungen über ntfy, Webhook und E-Mail | ✓ |
|
||||
| **v0.8.0** Stillstehende Projekte melden, Schwelle im Adminbereich | ✓ |
|
||||
| **v0.9.0** Schnellsuche per `Strg+K`, Aufgaben aus Git-Issues | ✓ |
|
||||
| **v1.0.0** Aktivitätsverlauf je Projekt, Zwei-Faktor per TOTP, mehrere Repositories je Projekt | ✓ |
|
||||
|
||||
Zur Entscheidung beim Export: Git-Tokens gehen **nicht** mit. Die Verbindung wird nur
|
||||
beschrieben, das Token ist nach dem Import neu zu hinterlegen. Snapshots bleiben
|
||||
|
||||
@@ -59,6 +59,13 @@ services:
|
||||
APP_URL: ${APP_URL:-http://localhost:3000}
|
||||
SESSION_TTL_DAYS: ${SESSION_TTL_DAYS:-30}
|
||||
GIT_API_TIMEOUT_MS: ${GIT_API_TIMEOUT_MS:-15000}
|
||||
NOTIFY_TIMEOUT_MS: ${NOTIFY_TIMEOUT_MS:-10000}
|
||||
SMTP_HOST: ${SMTP_HOST:-}
|
||||
SMTP_PORT: ${SMTP_PORT:-587}
|
||||
SMTP_SECURE: ${SMTP_SECURE:-}
|
||||
SMTP_USER: ${SMTP_USER:-}
|
||||
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
|
||||
SMTP_FROM: ${SMTP_FROM:-}
|
||||
GIT_ALLOW_LOOPBACK: ${GIT_ALLOW_LOOPBACK:-false}
|
||||
GIT_BLOCK_PRIVATE: ${GIT_BLOCK_PRIVATE:-false}
|
||||
GIT_ALLOWED_HOSTS: ${GIT_ALLOWED_HOSTS:-}
|
||||
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
import { expect, test, type APIRequestContext } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Tests ueber HTTP gegen die laufende Anwendung – also durch Middleware,
|
||||
* Authentifizierung, Validierung und Datenbank hindurch. Genau die Dinge,
|
||||
* die Unit-Tests nicht erreichen.
|
||||
*
|
||||
* Die Tests bauen aufeinander auf und laufen in dieser Reihenfolge, weil sie
|
||||
* sich eine Datenbank teilen (siehe playwright.config.ts, workers: 1).
|
||||
*/
|
||||
|
||||
const ADMIN = { username: "chefin", password: "ein-langes-testpasswort" };
|
||||
const ZWEITER = { username: "zweiter", password: "noch-ein-langes-passwort" };
|
||||
|
||||
async function login(request: APIRequestContext, user: { username: string; password: string }) {
|
||||
const response = await request.post("/api/auth/login", { data: user });
|
||||
expect(response.ok(), `Anmeldung als ${user.username}`).toBeTruthy();
|
||||
}
|
||||
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
test("Einrichtung legt das erste Konto an und sperrt sich danach", async ({ request }) => {
|
||||
const response = await request.post("/api/auth/setup", {
|
||||
data: { ...ADMIN, mode: "MULTI_USER" },
|
||||
});
|
||||
expect(response.status()).toBe(200);
|
||||
expect((await response.json()).user.role).toBe("ADMIN");
|
||||
|
||||
// Ein zweiter Aufruf darf kein weiteres Adminkonto erzeugen.
|
||||
const wieder = await request.post("/api/auth/setup", {
|
||||
data: { username: "eindringling", password: "ein-langes-testpasswort" },
|
||||
});
|
||||
expect(wieder.status()).toBe(409);
|
||||
});
|
||||
|
||||
test("ohne Anmeldung ist nichts zu holen", async ({ playwright }) => {
|
||||
const anonym = await playwright.request.newContext({ baseURL: test.info().project.use.baseURL });
|
||||
for (const pfad of ["/api/projects", "/api/connections", "/api/admin/users"]) {
|
||||
expect((await anonym.get(pfad)).status(), pfad).toBe(401);
|
||||
}
|
||||
await anonym.dispose();
|
||||
});
|
||||
|
||||
test("Fremdes Origin wird abgewiesen", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
const response = await request.post("/api/projects", {
|
||||
data: { name: "Von woanders" },
|
||||
headers: { Origin: "https://boese.example" },
|
||||
});
|
||||
expect(response.status()).toBe(403);
|
||||
});
|
||||
|
||||
test("Content-Type wird erzwungen", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
const response = await request.post("/api/projects", {
|
||||
headers: { "Content-Type": "text/plain" },
|
||||
data: JSON.stringify({ name: "Umgehung" }),
|
||||
});
|
||||
expect(response.status()).toBe(415);
|
||||
});
|
||||
|
||||
test("SSRF: interne Adressen werden geblockt", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
for (const ziel of ["http://127.0.0.1:5432", "http://169.254.169.254", "http://0.0.0.0"]) {
|
||||
const response = await request.post("/api/connections", {
|
||||
data: { name: `ssrf-${ziel}`, provider: "GITEA", baseUrl: ziel },
|
||||
});
|
||||
expect(response.status(), ziel).toBe(422);
|
||||
}
|
||||
});
|
||||
|
||||
test("Datentrennung zwischen zwei Konten", async ({ request, playwright }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
const angelegt = await request.post("/api/projects", {
|
||||
data: { name: "Geheimprojekt", status: "IN_DEVELOPMENT" },
|
||||
});
|
||||
expect(angelegt.status()).toBe(201);
|
||||
const projektId = (await angelegt.json()).project.id;
|
||||
|
||||
const aufgabe = await request.post(`/api/projects/${projektId}/tasks`, {
|
||||
data: { title: "Nicht fuer fremde Augen" },
|
||||
});
|
||||
expect(aufgabe.status()).toBe(201);
|
||||
const aufgabenId = (await aufgabe.json()).task.id;
|
||||
|
||||
// Zweites Konto anlegen und in einem eigenen Kontext anmelden.
|
||||
const neu = await request.post("/api/admin/users", {
|
||||
data: { ...ZWEITER, role: "USER" },
|
||||
});
|
||||
expect(neu.status()).toBe(201);
|
||||
|
||||
const fremd = await playwright.request.newContext({
|
||||
baseURL: test.info().project.use.baseURL,
|
||||
});
|
||||
await login(fremd, ZWEITER);
|
||||
|
||||
expect((await (await fremd.get("/api/projects")).json()).projects).toHaveLength(0);
|
||||
|
||||
// Fremde IDs muessen 404 liefern, nicht 403 – sonst waere die Existenz
|
||||
// des Datensatzes bestaetigt.
|
||||
expect((await fremd.get(`/api/projects/${projektId}`)).status()).toBe(404);
|
||||
expect(
|
||||
(await fremd.patch(`/api/projects/${projektId}`, { data: { name: "uebernommen" } })).status(),
|
||||
).toBe(404);
|
||||
expect((await fremd.delete(`/api/projects/${projektId}`)).status()).toBe(404);
|
||||
expect((await fremd.get(`/api/projects/${projektId}/tasks`)).status()).toBe(404);
|
||||
expect((await fremd.patch(`/api/tasks/${aufgabenId}`, { data: { title: "x" } })).status()).toBe(
|
||||
404,
|
||||
);
|
||||
|
||||
// Adminwege bleiben zu.
|
||||
expect((await fremd.get("/api/admin/users")).status()).toBe(403);
|
||||
expect(
|
||||
(await fremd.patch("/api/admin/settings", { data: { mode: "SINGLE_USER" } })).status(),
|
||||
).toBe(403);
|
||||
|
||||
// Und das Original ist unveraendert.
|
||||
const danach = await (await request.get(`/api/projects/${projektId}`)).json();
|
||||
expect(danach.project.name).toBe("Geheimprojekt");
|
||||
expect(danach.project.tasks).toHaveLength(1);
|
||||
|
||||
await fremd.dispose();
|
||||
});
|
||||
|
||||
test("Aufgaben: Reihenfolge, abgeleiteter Fortschritt, fremde IDs", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
const projekt = (
|
||||
await (await request.post("/api/projects", { data: { name: "Aufgabenprojekt" } })).json()
|
||||
).project;
|
||||
|
||||
const titel = ["eins", "zwei", "drei"];
|
||||
const ids: string[] = [];
|
||||
for (const title of titel) {
|
||||
const response = await request.post(`/api/projects/${projekt.id}/tasks`, {
|
||||
data: { title, status: "TODO" },
|
||||
});
|
||||
ids.push((await response.json()).task.id);
|
||||
}
|
||||
|
||||
// Neue Aufgaben haengen sich hinten an.
|
||||
const angelegt = (await (await request.get(`/api/projects/${projekt.id}/tasks`)).json()).tasks;
|
||||
expect(angelegt.map((task: { position: number }) => task.position)).toEqual([0, 1, 2]);
|
||||
|
||||
// Umdrehen.
|
||||
const gedreht = [...ids].reverse();
|
||||
const reorder = await request.patch(`/api/projects/${projekt.id}/tasks/reorder`, {
|
||||
data: { columns: { TODO: gedreht } },
|
||||
});
|
||||
expect(reorder.ok()).toBeTruthy();
|
||||
const nachher = (await (await request.get(`/api/projects/${projekt.id}/tasks`)).json()).tasks;
|
||||
expect(nachher.map((task: { title: string }) => task.title)).toEqual(["drei", "zwei", "eins"]);
|
||||
|
||||
// Eine nach DONE – Fortschritt folgt, sobald eingeschaltet.
|
||||
await request.patch(`/api/projects/${projekt.id}`, { data: { progressFromTasks: true } });
|
||||
await request.patch(`/api/tasks/${ids[0]}`, { data: { status: "DONE" } });
|
||||
|
||||
const mitFortschritt = (
|
||||
await (await request.get(`/api/projects/${projekt.id}`)).json()
|
||||
).project;
|
||||
expect(mitFortschritt.progress).toBe(33);
|
||||
|
||||
// Eine ID aus einem anderen Projekt darf nicht verschoben werden.
|
||||
const anderes = (
|
||||
await (await request.post("/api/projects", { data: { name: "Anderes" } })).json()
|
||||
).project;
|
||||
const fremdeAufgabe = (
|
||||
await (
|
||||
await request.post(`/api/projects/${anderes.id}/tasks`, { data: { title: "fremd" } })
|
||||
).json()
|
||||
).task;
|
||||
|
||||
const untergeschoben = await request.patch(`/api/projects/${projekt.id}/tasks/reorder`, {
|
||||
data: { columns: { DOING: [fremdeAufgabe.id] } },
|
||||
});
|
||||
const ergebnis = await untergeschoben.json();
|
||||
expect(ergebnis.updated).toBe(0);
|
||||
expect(ergebnis.ignored).toBe(1);
|
||||
|
||||
const unveraendert = (
|
||||
await (await request.get(`/api/projects/${anderes.id}/tasks`)).json()
|
||||
).tasks[0];
|
||||
expect(unveraendert.status).toBe("TODO");
|
||||
});
|
||||
|
||||
test("Issues als Aufgaben uebernehmen, ohne Dubletten", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
const projekt = (
|
||||
await (await request.post("/api/projects", { data: { name: "Issue-Projekt" } })).json()
|
||||
).project;
|
||||
|
||||
// Ohne verknuepftes Repository gibt es nichts zu uebernehmen.
|
||||
const ohneRepo = await request.post(`/api/projects/${projekt.id}/tasks/from-issues`, {
|
||||
data: {},
|
||||
});
|
||||
expect(ohneRepo.status()).toBe(409);
|
||||
|
||||
// Mit Repository, aber ohne geholten Stand ebenfalls nicht – der Server
|
||||
// laedt hier bewusst nichts nach.
|
||||
await request.patch(`/api/projects/${projekt.id}`, {
|
||||
data: { repoUrl: "https://github.com/vercel/swr" },
|
||||
});
|
||||
const ohneStand = await request.post(`/api/projects/${projekt.id}/tasks/from-issues`, {
|
||||
data: {},
|
||||
});
|
||||
expect(ohneStand.status()).toBe(409);
|
||||
|
||||
// Nach einem bestimmten, das es nicht gibt, ist dagegen 404 richtig.
|
||||
const fremdesRepo = await request.post(`/api/projects/${projekt.id}/tasks/from-issues`, {
|
||||
data: { repositoryId: "gibt-es-nicht" },
|
||||
});
|
||||
expect(fremdesRepo.status()).toBe(404);
|
||||
});
|
||||
|
||||
test("Mehrere Repositories je Projekt", async ({ request, playwright }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
// Beim Anlegen setzen die Git-Felder das fuehrende Repository.
|
||||
const projekt = (
|
||||
await (
|
||||
await request.post("/api/projects", {
|
||||
data: { name: "Zwei Teile", repoUrl: "https://github.com/vercel/swr" },
|
||||
})
|
||||
).json()
|
||||
).project;
|
||||
|
||||
expect(projekt.repositories).toHaveLength(1);
|
||||
expect(projekt.repositories[0].repoOwner).toBe("vercel");
|
||||
expect(projekt.repositories[0].repoName).toBe("swr");
|
||||
|
||||
// Ein zweites dazu.
|
||||
const zweites = await request.post(`/api/projects/${projekt.id}/repositories`, {
|
||||
data: { label: "Backend", repoUrl: "https://github.com/vercel/next.js" },
|
||||
});
|
||||
expect(zweites.status()).toBe(201);
|
||||
const backendId = (await zweites.json()).repository.id;
|
||||
|
||||
// Dasselbe Repo zweimal ist immer ein Versehen.
|
||||
const doppelt = await request.post(`/api/projects/${projekt.id}/repositories`, {
|
||||
data: { repoUrl: "https://github.com/vercel/next.js" },
|
||||
});
|
||||
expect(doppelt.status()).toBe(409);
|
||||
|
||||
// Halbe Angaben ergeben kein Repository.
|
||||
const leer = await request.post(`/api/projects/${projekt.id}/repositories`, {
|
||||
data: { label: "Nur ein Name" },
|
||||
});
|
||||
expect(leer.status()).toBe(422);
|
||||
|
||||
const geladen = (await (await request.get(`/api/projects/${projekt.id}`)).json()).project;
|
||||
expect(geladen.repositories).toHaveLength(2);
|
||||
// Das fuehrende steht vorn.
|
||||
expect(geladen.repositories[0].repoName).toBe("swr");
|
||||
expect(geladen.repositories[1].label).toBe("Backend");
|
||||
|
||||
// Der Projekt-PATCH bearbeitet weiterhin nur das fuehrende.
|
||||
await request.patch(`/api/projects/${projekt.id}`, { data: { autoSync: false } });
|
||||
const danach = (await (await request.get(`/api/projects/${projekt.id}`)).json()).project;
|
||||
expect(danach.repositories[0].autoSync).toBe(false);
|
||||
expect(danach.repositories[1].autoSync).toBe(true);
|
||||
|
||||
// Fremde Konten kommen an kein Repository.
|
||||
const fremd = await playwright.request.newContext({
|
||||
baseURL: test.info().project.use.baseURL,
|
||||
});
|
||||
await login(fremd, ZWEITER);
|
||||
expect((await fremd.get(`/api/projects/${projekt.id}/repositories`)).status()).toBe(404);
|
||||
expect((await fremd.patch(`/api/repositories/${backendId}`, { data: {} })).status()).toBe(404);
|
||||
expect((await fremd.delete(`/api/repositories/${backendId}`)).status()).toBe(404);
|
||||
expect((await fremd.post(`/api/repositories/${backendId}/sync`)).status()).toBe(404);
|
||||
await fremd.dispose();
|
||||
|
||||
// Entfernen laesst das andere stehen.
|
||||
expect((await request.delete(`/api/repositories/${backendId}`)).ok()).toBeTruthy();
|
||||
const zumSchluss = (await (await request.get(`/api/projects/${projekt.id}`)).json()).project;
|
||||
expect(zumSchluss.repositories).toHaveLength(1);
|
||||
expect(zumSchluss.repositories[0].repoName).toBe("swr");
|
||||
});
|
||||
|
||||
test("Export enthaelt keine Geheimnisse, Import beachtet die Strategie", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
await request.post("/api/connections", {
|
||||
data: {
|
||||
name: "Mit Token",
|
||||
provider: "GITEA",
|
||||
baseUrl: "https://gitea.example.com",
|
||||
token: "streng-geheimes-token",
|
||||
},
|
||||
});
|
||||
|
||||
const roh = await (await request.get("/api/projects/export")).text();
|
||||
expect(roh).not.toContain("streng-geheimes-token");
|
||||
expect(roh).not.toContain("tokenCipher");
|
||||
expect(roh).not.toContain("ownerId");
|
||||
|
||||
const datei = JSON.parse(roh);
|
||||
const vorher = datei.projects.length;
|
||||
|
||||
// Version 2: die Repositories stehen als Liste in der Datei.
|
||||
expect(datei.version).toBe(2);
|
||||
const mitRepo = datei.projects.find((entry: { name: string }) => entry.name === "Zwei Teile");
|
||||
expect(mitRepo.repositories).toHaveLength(1);
|
||||
expect(mitRepo.repositories[0].repoName).toBe("swr");
|
||||
|
||||
// Ueberspringen aendert nichts.
|
||||
const uebersprungen = await request.post("/api/projects/import", {
|
||||
data: { data: datei, strategy: "skip", dryRun: false },
|
||||
});
|
||||
expect((await uebersprungen.json()).summary.skipped).toBe(vorher);
|
||||
|
||||
// Zusaetzlich anlegen verdoppelt.
|
||||
const zusaetzlich = await request.post("/api/projects/import", {
|
||||
data: { data: datei, strategy: "rename", dryRun: false },
|
||||
});
|
||||
expect((await zusaetzlich.json()).summary.renamed).toBe(vorher);
|
||||
|
||||
const jetzt = (await (await request.get("/api/projects")).json()).projects;
|
||||
expect(jetzt).toHaveLength(vorher * 2);
|
||||
|
||||
// Muell wird abgewiesen.
|
||||
const muell = await request.post("/api/projects/import", {
|
||||
data: { data: { irgendwas: true }, strategy: "skip", dryRun: true },
|
||||
});
|
||||
expect(muell.status()).toBe(422);
|
||||
});
|
||||
|
||||
test("Dateien der Version 1 bleiben lesbar", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
// Damals stand genau ein Repository flach am Projekt. Wer eine solche
|
||||
// Sicherung liegen hat, soll sie weiterhin einspielen koennen.
|
||||
const alt = {
|
||||
kind: "nebula.projects",
|
||||
version: 1,
|
||||
projects: [
|
||||
{
|
||||
name: "Aus Version eins",
|
||||
repoUrl: "https://github.com/vercel/swr",
|
||||
repoOwner: "vercel",
|
||||
repoName: "swr",
|
||||
autoSync: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const gelesen = await request.post("/api/projects/import", {
|
||||
data: { data: alt, strategy: "rename", dryRun: false },
|
||||
});
|
||||
expect(gelesen.ok()).toBeTruthy();
|
||||
|
||||
const projekte = (await (await request.get("/api/projects")).json()).projects;
|
||||
const uebernommen = projekte.find(
|
||||
(entry: { name: string }) => entry.name === "Aus Version eins",
|
||||
);
|
||||
expect(uebernommen.repositories).toHaveLength(1);
|
||||
expect(uebernommen.repositories[0].repoOwner).toBe("vercel");
|
||||
expect(uebernommen.repositories[0].autoSync).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
/**
|
||||
* Bereitet die Testdatenbank vor: Schema einspielen und leeren.
|
||||
*
|
||||
* Die Datenbank muss vorher existieren. Anlegen ist bewusst nicht Teil des
|
||||
* Setups – in CI erzeugt sie der Postgres-Dienst, oertlich einmalig:
|
||||
*
|
||||
* docker exec nebula-db psql -U nebula -d postgres -c "CREATE DATABASE nebula_e2e_test"
|
||||
*/
|
||||
|
||||
const DATABASE_URL =
|
||||
process.env.E2E_DATABASE_URL ??
|
||||
"postgresql://nebula:nebula@localhost:5432/nebula_e2e_test?schema=public";
|
||||
|
||||
/**
|
||||
* Reihenfolge egal, weil CASCADE – aber vollstaendig muss sie sein, sonst
|
||||
* schleppen Laeufe Reste mit.
|
||||
*/
|
||||
const TABLES = [
|
||||
"Task",
|
||||
"Note",
|
||||
"RepoSnapshot",
|
||||
"Project",
|
||||
"Credential",
|
||||
"Session",
|
||||
"WebAuthnChallenge",
|
||||
"GitConnection",
|
||||
"User",
|
||||
"AppSettings",
|
||||
];
|
||||
|
||||
export default async function globalSetup() {
|
||||
const name = new URL(DATABASE_URL).pathname.replace(/^\//, "");
|
||||
|
||||
// Schutz vor dem teuersten aller Fehler: eine Testreihe, die die echte
|
||||
// Datenbank leert. Der Name muss "test" enthalten, sonst passiert nichts.
|
||||
if (!name.includes("test")) {
|
||||
throw new Error(
|
||||
`Die Testdatenbank heisst "${name}" und enthaelt nicht "test". ` +
|
||||
"Aus Sicherheitsgruenden abgebrochen – E2E_DATABASE_URL pruefen.",
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`[e2e] Datenbank: ${name}`);
|
||||
|
||||
execFileSync("npx", ["prisma", "migrate", "deploy"], {
|
||||
env: { ...process.env, DATABASE_URL },
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const prisma = new PrismaClient({ datasources: { db: { url: DATABASE_URL } } });
|
||||
try {
|
||||
const list = TABLES.map((table) => `"${table}"`).join(", ");
|
||||
await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE`);
|
||||
console.log("[e2e] Datenbank geleert.");
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Ein Weg durch die Oberflaeche, wie ihn ein Mensch geht: anmelden, Projekt
|
||||
* anlegen, Aufgaben verwalten. Keine Vollabdeckung – die Wege, die kaputt
|
||||
* gehen duerfen, ohne dass es jemand merkt.
|
||||
*
|
||||
* Setzt voraus, dass api.spec.ts das Konto bereits angelegt hat; laeuft
|
||||
* alphabetisch danach.
|
||||
*/
|
||||
|
||||
const KONTO = { username: "chefin", password: "ein-langes-testpasswort" };
|
||||
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto("/login");
|
||||
await page.fill("#login-username", KONTO.username);
|
||||
await page.fill("#login-password", KONTO.password);
|
||||
await page.click('button[type="submit"]');
|
||||
await expect(page.getByText("Vibe Coding Kontrollzentrum")).toBeVisible();
|
||||
});
|
||||
|
||||
test("Dashboard zeigt Kennzahlen und Projekte", async ({ page }) => {
|
||||
await expect(page.getByRole("heading", { name: /Deine Projekte/ })).toBeVisible();
|
||||
await expect(page.getByText("Projekte", { exact: false }).first()).toBeVisible();
|
||||
// Keine unbeabsichtigten Fehler in der Konsole.
|
||||
expect(page.url()).toContain("/");
|
||||
});
|
||||
|
||||
test("Projekt anlegen und wiederfinden", async ({ page }) => {
|
||||
await page.getByRole("button", { name: /Neues Projekt/ }).click();
|
||||
await expect(page.getByRole("dialog")).toBeVisible();
|
||||
|
||||
await page.fill("#project-name", "Oberflaechentest");
|
||||
await page.fill("#project-summary", "Von Playwright angelegt.");
|
||||
await page.getByRole("button", { name: "Projekt anlegen" }).click();
|
||||
|
||||
await expect(page.getByRole("dialog")).toBeHidden();
|
||||
await expect(page.getByText("Oberflaechentest")).toBeVisible();
|
||||
});
|
||||
|
||||
test("Aufgaben anlegen und per Ziehen verschieben", async ({ page }) => {
|
||||
await page.getByRole("link", { name: /Projekt Oberflaechentest/ }).click();
|
||||
await expect(page.getByRole("heading", { name: "Oberflaechentest" })).toBeVisible();
|
||||
|
||||
// Zwei Aufgaben ueber den Dialog anlegen.
|
||||
for (const titel of ["Erste Aufgabe", "Zweite Aufgabe"]) {
|
||||
await page.getByRole("button", { name: "Aufgabe", exact: true }).click();
|
||||
await expect(page.getByRole("dialog")).toBeVisible();
|
||||
await page.fill("#task-title", titel);
|
||||
await page.getByRole("button", { name: "Anlegen" }).click();
|
||||
await expect(page.getByRole("dialog")).toBeHidden();
|
||||
}
|
||||
|
||||
const offen = page.locator('[data-task-column="TODO"]');
|
||||
const inArbeit = page.locator('[data-task-column="DOING"]');
|
||||
await expect(offen.getByText("Erste Aufgabe")).toBeVisible();
|
||||
await expect(offen.getByText("Zweite Aufgabe")).toBeVisible();
|
||||
|
||||
// Erste Aufgabe nach "In Arbeit" ziehen.
|
||||
const griff = offen.locator('button[aria-label$="verschieben"]').first();
|
||||
const von = await griff.boundingBox();
|
||||
const nach = await inArbeit.boundingBox();
|
||||
expect(von && nach).toBeTruthy();
|
||||
|
||||
await page.mouse.move(von!.x + von!.width / 2, von!.y + von!.height / 2);
|
||||
await page.mouse.down();
|
||||
// Erst ueber die Aktivierungsschwelle des Sensors (5 Pixel) hinaus.
|
||||
await page.mouse.move(von!.x + 30, von!.y + 10, { steps: 6 });
|
||||
await page.mouse.move(nach!.x + nach!.width / 2, nach!.y + 60, { steps: 20 });
|
||||
// dnd-kit wertet die Bewegung in einem eigenen Frame aus. Ohne diese
|
||||
// Pause faende das Loslassen noch kein Ziel und die Karte spraenge zurueck.
|
||||
await page.waitForTimeout(250);
|
||||
await page.mouse.up();
|
||||
|
||||
await expect(inArbeit.getByText("Erste Aufgabe")).toBeVisible();
|
||||
|
||||
// Und der Server hat es auch so gespeichert.
|
||||
await page.reload();
|
||||
await expect(
|
||||
page.locator('[data-task-column="DOING"]').getByText("Erste Aufgabe"),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("Volltextsuche findet Notizen", async ({ page }) => {
|
||||
await page.getByRole("link", { name: /Projekt Oberflaechentest/ }).click();
|
||||
await page.getByRole("button", { name: "Notiz", exact: true }).click();
|
||||
|
||||
await page.getByPlaceholder(/Gedanken/).fill("Suchbegriff Zaunkoenig steht hier.");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByText("Zaunkoenig", { exact: false })).toBeVisible();
|
||||
|
||||
// exact, sonst trifft es auch "Zurueck zum Dashboard".
|
||||
await page.getByRole("link", { name: "Dashboard", exact: true }).click();
|
||||
await page.getByPlaceholder(/durchsuchen/).fill("Zaunkoenig");
|
||||
|
||||
await expect(page.getByText("Treffer in Notizen")).toBeVisible();
|
||||
});
|
||||
|
||||
test("Schnellsuche findet Projekt und Notiz", async ({ page }) => {
|
||||
await page.keyboard.press("Control+k");
|
||||
await expect(page.getByRole("dialog", { name: "Schnellsuche" })).toBeVisible();
|
||||
|
||||
// Ohne Eingabe stehen Projekte und Bereiche bereit.
|
||||
await expect(page.getByRole("dialog").getByText("Oberflaechentest")).toBeVisible();
|
||||
|
||||
await page.getByPlaceholder(/Projekt, Notiz oder Bereich/).fill("Zaunkoenig");
|
||||
await expect(page.getByRole("dialog").getByText(/in Oberflaechentest/)).toBeVisible();
|
||||
|
||||
// Enter springt zum ersten Treffer.
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("heading", { name: "Oberflaechentest" })).toBeVisible();
|
||||
|
||||
// Escape schliesst wieder.
|
||||
await page.keyboard.press("Control+k");
|
||||
await expect(page.getByRole("dialog", { name: "Schnellsuche" })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByRole("dialog", { name: "Schnellsuche" })).toBeHidden();
|
||||
});
|
||||
|
||||
test("Abmelden fuehrt zurueck zur Anmeldung", async ({ page }) => {
|
||||
await page.getByRole("button", { name: /Benutzermenue/ }).click();
|
||||
await page.getByRole("menuitem", { name: "Abmelden" }).click();
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
|
||||
// Und die geschuetzte Seite ist wieder zu.
|
||||
await page.goto("/");
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
});
|
||||
Generated
+403
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "nebula",
|
||||
"version": "0.1.0",
|
||||
"version": "0.9.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nebula",
|
||||
"version": "0.1.0",
|
||||
"version": "0.9.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -17,6 +17,8 @@
|
||||
"@simplewebauthn/server": "^13.3.2",
|
||||
"lucide-react": "^0.511.0",
|
||||
"next": "^15.3.3",
|
||||
"nodemailer": "^9.0.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -25,8 +27,11 @@
|
||||
"zod": "^3.25.28"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.62.0",
|
||||
"@tailwindcss/postcss": "^4.1.7",
|
||||
"@types/node": "^22.15.21",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.1.5",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"prisma": "^6.8.2",
|
||||
@@ -1513,6 +1518,22 @@
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.0.tgz",
|
||||
"integrity": "sha512-9zOJ6ZQRAena31MpOH9VSzIz8Ou3YJ/wtY/eQm5T2uhfhG7/U3COrMS8xOtUrZrp9OgdmzEnIYODye3nY1VqzA==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.62.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@prisma/client": {
|
||||
"version": "6.19.3",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.19.3.tgz",
|
||||
@@ -2302,6 +2323,26 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/nodemailer": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.1.tgz",
|
||||
"integrity": "sha512-PxpaInm8V1JQDd4j0ds5HfvWQk8JupS1C0Picb96QJsrrRDjBH+DlK7L4ZdNSqNULhiZRQHc40nLVShaGxXAMw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/qrcode": {
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
|
||||
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.2.17",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
|
||||
@@ -2446,6 +2487,30 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
|
||||
@@ -2509,6 +2574,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001806",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz",
|
||||
@@ -2621,6 +2695,35 @@
|
||||
"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
|
||||
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.0",
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/comma-separated-tokens": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
|
||||
@@ -2678,6 +2781,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decamelize": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
|
||||
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/decode-named-character-reference": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
|
||||
@@ -2747,6 +2859,12 @@
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/dijkstrajs": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "16.6.1",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
|
||||
@@ -2771,6 +2889,12 @@
|
||||
"fast-check": "^3.23.1"
|
||||
}
|
||||
},
|
||||
"node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/empathic": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz",
|
||||
@@ -2940,6 +3064,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
|
||||
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^5.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -2955,6 +3092,15 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/giget": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz",
|
||||
@@ -3085,6 +3231,15 @@
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-hexadecimal": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
|
||||
@@ -3390,6 +3545,18 @@
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
||||
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/longest-streak": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
|
||||
@@ -4373,6 +4540,15 @@
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.0.3.tgz",
|
||||
"integrity": "sha512-n+YP+NKwR5zRWa60k3GiQ6Q3B4KXCoAw40dAKeCtYn020iNN74aWK2liXIC3ZEATeGql7we3tE3t8QwhY0eskw==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nypm": {
|
||||
"version": "0.6.8",
|
||||
"resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.8.tgz",
|
||||
@@ -4419,6 +4595,42 @@
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-try": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-locate": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
|
||||
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/p-try": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/parse-entities": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
|
||||
@@ -4444,6 +4656,15 @@
|
||||
"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
|
||||
@@ -4489,6 +4710,61 @@
|
||||
"pathe": "^2.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.62.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.0.tgz",
|
||||
"integrity": "sha512-Z14dG305dgaLu6foB1TXQagFiW8JfSUIUaUuPaKQ6NtBPKF1P/qXcqfh6c6K/icPqdy37JmjbiBXf6JNg6Sylw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.62.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.62.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.0.tgz",
|
||||
"integrity": "sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright/node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.23",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz",
|
||||
@@ -4589,6 +4865,23 @@
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
|
||||
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dijkstrajs": "^1.0.1",
|
||||
"pngjs": "^5.0.0",
|
||||
"yargs": "^15.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"qrcode": "bin/qrcode"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rc9": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz",
|
||||
@@ -4748,6 +5041,21 @@
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
|
||||
@@ -4801,6 +5109,12 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/sharp": {
|
||||
"version": "0.34.5",
|
||||
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
|
||||
@@ -4886,6 +5200,20 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/stringify-entities": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
|
||||
@@ -4900,6 +5228,18 @@
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/style-to-js": {
|
||||
"version": "1.1.21",
|
||||
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
|
||||
@@ -5373,6 +5713,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/which-module": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
||||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/why-is-node-running": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||
@@ -5390,6 +5736,61 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
|
||||
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^6.0.0",
|
||||
"decamelize": "^1.2.0",
|
||||
"find-up": "^4.1.0",
|
||||
"get-caller-file": "^2.0.1",
|
||||
"require-directory": "^2.1.1",
|
||||
"require-main-filename": "^2.0.0",
|
||||
"set-blocking": "^2.0.0",
|
||||
"string-width": "^4.2.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^4.0.0",
|
||||
"yargs-parser": "^18.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "18.1.3",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"camelcase": "^5.0.0",
|
||||
"decamelize": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.76",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
|
||||
+10
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nebula",
|
||||
"version": "0.5.0",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Nebula – Dashboard fuer Vibe-Coding Projekte mit Git-Anbindung (GitHub, GitLab, Gitea)",
|
||||
"scripts": {
|
||||
@@ -25,7 +25,10 @@
|
||||
"setup": "node scripts/setup.mjs",
|
||||
"postinstall": "prisma generate",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
"test:watch": "vitest",
|
||||
"test:e2e": "npm run build && playwright test",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"test:all": "npm test && npm run test:e2e"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
@@ -39,6 +42,8 @@
|
||||
"@simplewebauthn/server": "^13.3.2",
|
||||
"lucide-react": "^0.511.0",
|
||||
"next": "^15.3.3",
|
||||
"nodemailer": "^9.0.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -47,8 +52,11 @@
|
||||
"zod": "^3.25.28"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.62.0",
|
||||
"@tailwindcss/postcss": "^4.1.7",
|
||||
"@types/node": "^22.15.21",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.1.5",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"prisma": "^6.8.2",
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Ende-zu-Ende-Tests gegen die echte Anwendung.
|
||||
*
|
||||
* Playwright startet den Produktionsserver selbst und richtet ihn auf eine
|
||||
* eigene Datenbank. Der Port ist bewusst ein anderer als 3000 und 3100,
|
||||
* damit eine laufende Instanz nicht stoert.
|
||||
*
|
||||
* Voraussetzung: ein Bau (`npm run build`) und eine leere Datenbank, deren
|
||||
* Name "test" enthaelt – siehe global-setup.ts. Beides erledigt
|
||||
* `npm run test:e2e`.
|
||||
*/
|
||||
|
||||
const PORT = Number(process.env.E2E_PORT ?? 3111);
|
||||
const BASE_URL = `http://localhost:${PORT}`;
|
||||
|
||||
const DATABASE_URL =
|
||||
process.env.E2E_DATABASE_URL ??
|
||||
"postgresql://nebula:nebula@localhost:5432/nebula_e2e_test?schema=public";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
// Die Tests teilen sich eine Datenbank, deshalb nacheinander.
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: process.env.CI ? 1 : 0,
|
||||
reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : [["list"]],
|
||||
timeout: 60_000,
|
||||
expect: { timeout: 10_000 },
|
||||
|
||||
globalSetup: "./e2e/global-setup.ts",
|
||||
|
||||
use: {
|
||||
baseURL: BASE_URL,
|
||||
locale: "de-DE",
|
||||
timezoneId: "Europe/Berlin",
|
||||
trace: "retain-on-failure",
|
||||
screenshot: "only-on-failure",
|
||||
// Oertlich der installierte Chrome, damit kein Browser geladen werden
|
||||
// muss. In CI gibt es keinen – dort das mitgelieferte Chromium
|
||||
// (siehe "playwright install chromium" im Arbeitsablauf).
|
||||
...(process.env.CI ? {} : { channel: "chrome" as const }),
|
||||
},
|
||||
|
||||
webServer: {
|
||||
command: "npm start",
|
||||
url: `${BASE_URL}/api/health`,
|
||||
reuseExistingServer: false,
|
||||
timeout: 120_000,
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
env: {
|
||||
DATABASE_URL,
|
||||
PORT: String(PORT),
|
||||
APP_URL: BASE_URL,
|
||||
NODE_ENV: "production",
|
||||
// Fester Schluessel, damit Laeufe vergleichbar bleiben.
|
||||
APP_SECRET: "e2e-test-secret-nur-fuer-die-testlaeufe-1234567890",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotificationChannel" AS ENUM ('WEBHOOK', 'NTFY', 'EMAIL');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotificationEvent" AS ENUM ('SYNC_FAILED', 'CI_FAILED', 'NEW_RELEASE');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Project" ADD COLUMN "notifiedCiState" TEXT,
|
||||
ADD COLUMN "notifiedRelease" TEXT,
|
||||
ADD COLUMN "notifiedSyncError" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "NotificationTarget" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"channel" "NotificationChannel" NOT NULL,
|
||||
"target" TEXT NOT NULL,
|
||||
"secretCipher" TEXT,
|
||||
"secretHint" TEXT,
|
||||
"events" "NotificationEvent"[] DEFAULT ARRAY[]::"NotificationEvent"[],
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"lastSentAt" TIMESTAMP(3),
|
||||
"lastOk" BOOLEAN,
|
||||
"lastMessage" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "NotificationTarget_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NotificationTarget_userId_idx" ON "NotificationTarget"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "NotificationTarget_userId_name_key" ON "NotificationTarget"("userId", "name");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "NotificationTarget" ADD CONSTRAINT "NotificationTarget_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "NotificationEvent" ADD VALUE 'PROJECT_STALE';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "AppSettings" ADD COLUMN "lastStaleCheckAt" TIMESTAMP(3),
|
||||
ADD COLUMN "staleAfterDays" INTEGER NOT NULL DEFAULT 60;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Project" ADD COLUMN "notifiedStaleAt" TIMESTAMP(3);
|
||||
@@ -0,0 +1,6 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Task" ADD COLUMN "sourceIssue" INTEGER,
|
||||
ADD COLUMN "sourceUrl" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Task_projectId_sourceIssue_key" ON "Task"("projectId", "sourceIssue");
|
||||
@@ -0,0 +1,24 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ActivityKind" AS ENUM ('PROJECT_CREATED', 'PROJECT_UPDATED', 'STATUS_CHANGED', 'NOTE_ADDED', 'NOTE_UPDATED', 'NOTE_DELETED', 'TASK_ADDED', 'TASK_MOVED', 'TASK_DELETED', 'TASKS_IMPORTED', 'REPO_LINKED', 'REPO_COMMITS', 'SYNC_FAILED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Activity" (
|
||||
"id" TEXT NOT NULL,
|
||||
"projectId" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"kind" "ActivityKind" NOT NULL,
|
||||
"summary" TEXT NOT NULL,
|
||||
"meta" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Activity_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Activity_projectId_createdAt_idx" ON "Activity"("projectId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,47 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "totpEnabledAt" TIMESTAMP(3),
|
||||
ADD COLUMN "totpSecretCipher" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "RecoveryCode" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"codeHash" TEXT NOT NULL,
|
||||
"usedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PendingLogin" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "PendingLogin_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "RecoveryCode_codeHash_key" ON "RecoveryCode"("codeHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RecoveryCode_userId_idx" ON "RecoveryCode"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PendingLogin_tokenHash_key" ON "PendingLogin"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PendingLogin_userId_idx" ON "PendingLogin"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PendingLogin_expiresAt_idx" ON "PendingLogin"("expiresAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PendingLogin" ADD CONSTRAINT "PendingLogin_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,113 @@
|
||||
-- Mehrere Repositories je Projekt.
|
||||
--
|
||||
-- Die Git-Felder wandern vom Projekt in eine eigene Tabelle. Bestehende
|
||||
-- Projekte bekommen daraus genau ein Repository, damit nichts verlorengeht;
|
||||
-- der Snapshot haengt danach am Repository statt am Projekt.
|
||||
--
|
||||
-- Von Hand geschrieben: prisma migrate diff wuerde die Spalten am Projekt
|
||||
-- ersatzlos loeschen und die Snapshots gleich mit.
|
||||
|
||||
-- ── 1. Neue Tabelle ─────────────────────────────────────────
|
||||
CREATE TABLE "Repository" (
|
||||
"id" TEXT NOT NULL,
|
||||
"projectId" TEXT NOT NULL,
|
||||
"label" TEXT,
|
||||
"repoUrl" TEXT,
|
||||
"repoOwner" TEXT,
|
||||
"repoName" TEXT,
|
||||
"defaultBranch" TEXT,
|
||||
"connectionId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"lastSyncedAt" TIMESTAMP(3),
|
||||
"syncError" TEXT,
|
||||
"autoSync" BOOLEAN NOT NULL DEFAULT true,
|
||||
"syncFailureCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"notifiedSyncError" TEXT,
|
||||
"notifiedCiState" TEXT,
|
||||
"notifiedRelease" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Repository_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE INDEX "Repository_projectId_position_idx" ON "Repository"("projectId", "position");
|
||||
CREATE INDEX "Repository_connectionId_idx" ON "Repository"("connectionId");
|
||||
|
||||
ALTER TABLE "Repository" ADD CONSTRAINT "Repository_projectId_fkey"
|
||||
FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "Repository" ADD CONSTRAINT "Repository_connectionId_fkey"
|
||||
FOREIGN KEY ("connectionId") REFERENCES "GitConnection"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- ── 2. Bestand uebernehmen ──────────────────────────────────
|
||||
-- Nur Projekte, an denen wirklich etwas haengt. Ein Projekt, das bloss eine
|
||||
-- Verbindung ausgewaehlt hatte, ohne je ein Repo zu nennen, braucht keine
|
||||
-- leere Zeile.
|
||||
INSERT INTO "Repository" (
|
||||
"id", "projectId", "repoUrl", "repoOwner", "repoName", "defaultBranch",
|
||||
"connectionId", "position", "lastSyncedAt", "syncError", "autoSync",
|
||||
"syncFailureCount", "notifiedSyncError", "notifiedCiState", "notifiedRelease",
|
||||
"createdAt", "updatedAt"
|
||||
)
|
||||
SELECT
|
||||
gen_random_uuid()::text, "id", "repoUrl", "repoOwner", "repoName", "defaultBranch",
|
||||
"connectionId", 0, "lastSyncedAt", "syncError", "autoSync",
|
||||
"syncFailureCount", "notifiedSyncError", "notifiedCiState", "notifiedRelease",
|
||||
"createdAt", CURRENT_TIMESTAMP
|
||||
FROM "Project"
|
||||
WHERE "repoUrl" IS NOT NULL
|
||||
OR ("repoOwner" IS NOT NULL AND "repoName" IS NOT NULL);
|
||||
|
||||
-- ── 3. Snapshots umhaengen ──────────────────────────────────
|
||||
ALTER TABLE "RepoSnapshot" ADD COLUMN "repositoryId" TEXT;
|
||||
|
||||
UPDATE "RepoSnapshot" AS s
|
||||
SET "repositoryId" = r."id"
|
||||
FROM "Repository" AS r
|
||||
WHERE r."projectId" = s."projectId";
|
||||
|
||||
-- Ein Snapshot ohne zugehoeriges Repository kann nur entstanden sein, wenn
|
||||
-- jemand die Repo-Angaben nachtraeglich geleert hat. Er ist ohnehin nicht
|
||||
-- mehr zuzuordnen und beim naechsten Abgleich neu geholt.
|
||||
DELETE FROM "RepoSnapshot" WHERE "repositoryId" IS NULL;
|
||||
|
||||
ALTER TABLE "RepoSnapshot" ALTER COLUMN "repositoryId" SET NOT NULL;
|
||||
ALTER TABLE "RepoSnapshot" DROP CONSTRAINT "RepoSnapshot_projectId_fkey";
|
||||
DROP INDEX "RepoSnapshot_projectId_key";
|
||||
ALTER TABLE "RepoSnapshot" DROP COLUMN "projectId";
|
||||
|
||||
CREATE UNIQUE INDEX "RepoSnapshot_repositoryId_key" ON "RepoSnapshot"("repositoryId");
|
||||
ALTER TABLE "RepoSnapshot" ADD CONSTRAINT "RepoSnapshot_repositoryId_fkey"
|
||||
FOREIGN KEY ("repositoryId") REFERENCES "Repository"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- ── 4. Herkunft uebernommener Aufgaben ──────────────────────
|
||||
-- Bisher war die Issue-Nummer je Projekt eindeutig. Mit mehreren Repos
|
||||
-- reicht das nicht mehr: Frontend und Backend haben beide ein Issue 5.
|
||||
ALTER TABLE "Task" ADD COLUMN "sourceRepositoryId" TEXT;
|
||||
|
||||
UPDATE "Task" AS t
|
||||
SET "sourceRepositoryId" = r."id"
|
||||
FROM "Repository" AS r
|
||||
WHERE r."projectId" = t."projectId" AND t."sourceIssue" IS NOT NULL;
|
||||
|
||||
DROP INDEX "Task_projectId_sourceIssue_key";
|
||||
CREATE UNIQUE INDEX "Task_projectId_sourceRepositoryId_sourceIssue_key"
|
||||
ON "Task"("projectId", "sourceRepositoryId", "sourceIssue");
|
||||
|
||||
-- ── 5. Projekt aufraeumen ───────────────────────────────────
|
||||
ALTER TABLE "Project" DROP CONSTRAINT "Project_connectionId_fkey";
|
||||
DROP INDEX "Project_connectionId_idx";
|
||||
|
||||
ALTER TABLE "Project"
|
||||
DROP COLUMN "repoUrl",
|
||||
DROP COLUMN "repoOwner",
|
||||
DROP COLUMN "repoName",
|
||||
DROP COLUMN "defaultBranch",
|
||||
DROP COLUMN "connectionId",
|
||||
DROP COLUMN "lastSyncedAt",
|
||||
DROP COLUMN "syncError",
|
||||
DROP COLUMN "autoSync",
|
||||
DROP COLUMN "syncFailureCount",
|
||||
DROP COLUMN "notifiedSyncError",
|
||||
DROP COLUMN "notifiedCiState",
|
||||
DROP COLUMN "notifiedRelease";
|
||||
+221
-20
@@ -33,6 +33,44 @@ enum GitProvider {
|
||||
GITEA
|
||||
}
|
||||
|
||||
/// Zustellwege fuer Benachrichtigungen.
|
||||
enum NotificationChannel {
|
||||
WEBHOOK
|
||||
NTFY
|
||||
EMAIL
|
||||
}
|
||||
|
||||
/// Anlaesse, ueber die benachrichtigt werden kann.
|
||||
enum NotificationEvent {
|
||||
/// Ein Abgleich mit dem Git-System ist fehlgeschlagen.
|
||||
SYNC_FAILED
|
||||
/// Der letzte CI-Lauf auf dem Default-Branch ist rot.
|
||||
CI_FAILED
|
||||
/// Im Repository ist ein neuer Tag oder ein neues Release aufgetaucht.
|
||||
NEW_RELEASE
|
||||
/// Seit laengerem kein Commit mehr – der sanfte Stups.
|
||||
PROJECT_STALE
|
||||
}
|
||||
|
||||
/// Was im Verlauf eines Projekts festgehalten wird. Bewusst grob: der
|
||||
/// Verlauf soll erzaehlen, was passiert ist, und nicht jede Feldaenderung
|
||||
/// mitschreiben.
|
||||
enum ActivityKind {
|
||||
PROJECT_CREATED
|
||||
PROJECT_UPDATED
|
||||
STATUS_CHANGED
|
||||
NOTE_ADDED
|
||||
NOTE_UPDATED
|
||||
NOTE_DELETED
|
||||
TASK_ADDED
|
||||
TASK_MOVED
|
||||
TASK_DELETED
|
||||
TASKS_IMPORTED
|
||||
REPO_LINKED
|
||||
REPO_COMMITS
|
||||
SYNC_FAILED
|
||||
}
|
||||
|
||||
/// Spalten des Aufgabenbretts innerhalb eines Projekts.
|
||||
enum TaskStatus {
|
||||
TODO
|
||||
@@ -74,10 +112,21 @@ model User {
|
||||
failedLoginCount Int @default(0)
|
||||
lockedUntil DateTime?
|
||||
|
||||
/// TOTP-Schluessel, AES-256-GCM-verschluesselt (siehe src/lib/crypto.ts).
|
||||
/// Hinterlegt heisst noch nicht scharf: erst ein bestaetigter Code setzt
|
||||
/// totpEnabledAt. Bis dahin darf die Anmeldung nicht danach fragen, sonst
|
||||
/// sperrt sich aus, wer die Einrichtung abbricht.
|
||||
totpSecretCipher String?
|
||||
totpEnabledAt DateTime?
|
||||
|
||||
sessions Session[]
|
||||
credentials Credential[]
|
||||
projects Project[]
|
||||
connections GitConnection[]
|
||||
notificationTargets NotificationTarget[]
|
||||
activities Activity[]
|
||||
recoveryCodes RecoveryCode[]
|
||||
pendingLogins PendingLogin[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -122,6 +171,45 @@ model Credential {
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
/// Ein Wiederherstellungscode fuer den Fall, dass der Authenticator weg ist.
|
||||
/// Jeder Code gilt genau einmal.
|
||||
model RecoveryCode {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
/// SHA-256 des Codes. Kein langsames Verfahren wie bei Passwoertern: die
|
||||
/// Codes sind zufaellig erzeugt und lang genug, dass Raten aussichtslos
|
||||
/// ist – und bei einer Anmeldung waeren sonst zehn teure Vergleiche noetig.
|
||||
codeHash String @unique
|
||||
|
||||
usedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
/// Zwischenzustand einer Anmeldung: Passwort stimmt, der zweite Faktor fehlt
|
||||
/// noch. Bewusst eine eigene Zeile und keine halbfertige Sitzung – so kann
|
||||
/// aus diesem Zustand nichts entstehen, was einer Anmeldung aehnelt.
|
||||
model PendingLogin {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
/// Wie bei der Sitzung liegt nur der SHA-256-Hash des Cookie-Tokens hier.
|
||||
tokenHash String @unique
|
||||
/// Fehlversuche. Nach zu vielen wird der Vorgang verworfen, damit die
|
||||
/// sechs Stellen nicht in Ruhe durchprobiert werden koennen.
|
||||
attempts Int @default(0)
|
||||
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
/// Kurzlebige WebAuthn-Challenge. Wird nach Gebrauch geloescht, damit sie
|
||||
/// kein zweites Mal verwendet werden kann.
|
||||
model WebAuthnChallenge {
|
||||
@@ -163,6 +251,12 @@ model AppSettings {
|
||||
/// Kurzbericht des letzten Durchlaufs: { synced, failed, skipped, ms }
|
||||
lastAutoSyncReport Json?
|
||||
|
||||
// ── Stillstand ─────────────────────────────────────────────
|
||||
/// Ab wie vielen Tagen ohne Commit ein Projekt als stillstehend gilt.
|
||||
staleAfterDays Int @default(60)
|
||||
/// Die Pruefung laeuft hoechstens einmal am Tag.
|
||||
lastStaleCheckAt DateTime?
|
||||
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
@@ -192,7 +286,7 @@ model GitConnection {
|
||||
ownerId String?
|
||||
owner User? @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
|
||||
projects Project[]
|
||||
repositories Repository[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -222,15 +316,61 @@ model Project {
|
||||
tags String[] @default([])
|
||||
favorite Boolean @default(false)
|
||||
|
||||
// ── Git-Anbindung ──────────────────────────────────────────
|
||||
/// Besitzer. Nullable wie bei GitConnection, damit Bestandsdaten beim
|
||||
/// Einrichten des ersten Kontos uebernommen werden koennen.
|
||||
ownerId String?
|
||||
owner User? @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
|
||||
/// Fortschritt aus dem Verhaeltnis erledigter Aufgaben berechnen statt
|
||||
/// von Hand zu schieben. Nur sinnvoll, wenn es ueberhaupt Aufgaben gibt.
|
||||
progressFromTasks Boolean @default(false)
|
||||
|
||||
/// Wann zuletzt wegen Stillstands gemeldet wurde. Erneut gemeldet wird
|
||||
/// erst, wenn danach wieder ein Commit kam und es dann wieder still wurde.
|
||||
/// Bleibt am Projekt: Stillstand ist eine Aussage ueber das Vorhaben, nicht
|
||||
/// ueber ein einzelnes Repository.
|
||||
notifiedStaleAt DateTime?
|
||||
|
||||
notes Note[]
|
||||
tasks Task[]
|
||||
activities Activity[]
|
||||
repositories Repository[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([ownerId, slug])
|
||||
@@index([status])
|
||||
@@index([updatedAt])
|
||||
@@index([ownerId])
|
||||
}
|
||||
|
||||
/// Ein Repository eines Projekts. Ein Vorhaben besteht oft aus mehreren –
|
||||
/// Frontend und Backend etwa –, gehoert aber in eine Karte.
|
||||
///
|
||||
/// Das erste Repository (position 0) ist das fuehrende: seine Kennzahlen
|
||||
/// stehen auf der Projektkarte, wo fuer mehrere kein Platz ist.
|
||||
model Repository {
|
||||
id String @id @default(cuid())
|
||||
projectId String
|
||||
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||
|
||||
/// Frei waehlbare Bezeichnung wie "Frontend". Leer heisst: der Repo-Name
|
||||
/// steht fuer sich.
|
||||
label String?
|
||||
|
||||
repoUrl String?
|
||||
/// Owner bzw. Namespace/Gruppe (bei GitLab auch verschachtelt: "gruppe/subgruppe")
|
||||
repoOwner String?
|
||||
repoName String?
|
||||
defaultBranch String?
|
||||
|
||||
connectionId String?
|
||||
connection GitConnection? @relation(fields: [connectionId], references: [id], onDelete: SetNull)
|
||||
|
||||
/// Reihenfolge in der Anzeige.
|
||||
position Int @default(0)
|
||||
|
||||
lastSyncedAt DateTime?
|
||||
syncError String?
|
||||
/// Am automatischen Abgleich teilnehmen. Einzeln abschaltbar, etwa bei
|
||||
@@ -240,27 +380,51 @@ model Project {
|
||||
/// jedem Fehlschlag wird der naechste Versuch weiter hinausgezoegert.
|
||||
syncFailureCount Int @default(0)
|
||||
|
||||
/// Besitzer. Nullable wie bei GitConnection, damit Bestandsdaten beim
|
||||
/// Einrichten des ersten Kontos uebernommen werden koennen.
|
||||
ownerId String?
|
||||
owner User? @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
/// Woruber zuletzt benachrichtigt wurde. Gemeldet wird nur bei einer
|
||||
/// Aenderung – sonst kaeme bei einem dauerhaft kaputten Repo mit jedem
|
||||
/// Abgleich dieselbe Nachricht. Je Repository, nicht je Projekt: sonst
|
||||
/// verdeckt ein rotes Frontend die rote Pipeline des Backends.
|
||||
notifiedSyncError String?
|
||||
notifiedCiState String?
|
||||
notifiedRelease String?
|
||||
|
||||
/// Fortschritt aus dem Verhaeltnis erledigter Aufgaben berechnen statt
|
||||
/// von Hand zu schieben. Nur sinnvoll, wenn es ueberhaupt Aufgaben gibt.
|
||||
progressFromTasks Boolean @default(false)
|
||||
|
||||
notes Note[]
|
||||
tasks Task[]
|
||||
snapshot RepoSnapshot?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([ownerId, slug])
|
||||
@@index([status])
|
||||
@@index([projectId, position])
|
||||
@@index([connectionId])
|
||||
@@index([updatedAt])
|
||||
@@index([ownerId])
|
||||
}
|
||||
|
||||
/// Ein Zustellweg fuer Benachrichtigungen, gehoert genau einem Konto.
|
||||
model NotificationTarget {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
channel NotificationChannel
|
||||
|
||||
/// Webhook-URL, ntfy-Themen-URL oder E-Mail-Adresse.
|
||||
target String
|
||||
/// Optionales Geheimnis, AES-256-GCM verschluesselt: Bearer-Token fuer
|
||||
/// ntfy oder ein Signaturschluessel fuer den Webhook.
|
||||
secretCipher String?
|
||||
secretHint String?
|
||||
|
||||
/// Worueber dieses Ziel benachrichtigt werden will.
|
||||
events NotificationEvent[] @default([])
|
||||
isActive Boolean @default(true)
|
||||
|
||||
lastSentAt DateTime?
|
||||
lastOk Boolean?
|
||||
lastMessage String?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([userId, name])
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
/// Eine Aufgabe innerhalb eines Projekts – die Karten des Aufgabenbretts.
|
||||
@@ -281,12 +445,49 @@ model Task {
|
||||
/// Zeitpunkt, zu dem die Aufgabe nach DONE gewandert ist.
|
||||
doneAt DateTime?
|
||||
|
||||
/// Stammt die Aufgabe aus einem Git-Issue? Nummer, Repository und Link
|
||||
/// merken, damit dasselbe Issue nicht zweimal uebernommen wird.
|
||||
sourceIssue Int?
|
||||
sourceUrl String?
|
||||
/// Aus welchem Repository. Muss mit in die Eindeutigkeit: Frontend und
|
||||
/// Backend haben beide ein Issue Nummer 5, und das sind zwei Aufgaben.
|
||||
sourceRepositoryId String?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
/// Verhindert Dubletten beim erneuten Uebernehmen. Mehrere Aufgaben ohne
|
||||
/// Herkunft sind erlaubt: NULL gilt in Postgres als verschieden.
|
||||
@@unique([projectId, sourceRepositoryId, sourceIssue])
|
||||
@@index([projectId, status, position])
|
||||
}
|
||||
|
||||
/// Ein Eintrag im Verlauf eines Projekts: was ist wann passiert.
|
||||
model Activity {
|
||||
id String @id @default(cuid())
|
||||
projectId String
|
||||
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||
|
||||
/// Wer. null bedeutet: die Anwendung selbst, also der Zeitgeber beim
|
||||
/// automatischen Abgleich.
|
||||
userId String?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
|
||||
kind ActivityKind
|
||||
/// Fertig formulierter Einzeiler. Die Formulierung beim Schreiben
|
||||
/// festzuhalten spart der Anzeige das Nachschlagen von Namen, die es
|
||||
/// spaeter womoeglich nicht mehr gibt – etwa den einer geloeschten Notiz.
|
||||
summary String
|
||||
/// Zusatzangaben wie { from: "IDEA", to: "DONE" }. Fuer die Anzeige nicht
|
||||
/// noetig, aber nuetzlich, falls spaeter ausgewertet werden soll.
|
||||
meta Json?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
/// Absteigend gelesen, immer je Projekt.
|
||||
@@index([projectId, createdAt])
|
||||
}
|
||||
|
||||
/// Freie Notizen zu einem Projekt.
|
||||
model Note {
|
||||
id String @id @default(cuid())
|
||||
@@ -302,12 +503,12 @@ model Note {
|
||||
@@index([pinned])
|
||||
}
|
||||
|
||||
/// Zwischengespeicherter Stand des verknuepften Repositories. Wird beim
|
||||
/// Sync ueberschrieben, damit das Dashboard auch ohne Netz Daten zeigt.
|
||||
/// Zwischengespeicherter Stand eines Repositories. Wird beim Sync
|
||||
/// ueberschrieben, damit das Dashboard auch ohne Netz Daten zeigt.
|
||||
model RepoSnapshot {
|
||||
id String @id @default(cuid())
|
||||
projectId String @unique
|
||||
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||
repositoryId String @unique
|
||||
repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
fullName String?
|
||||
description String?
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AccountManager, type AccountData } from "@/components/account/AccountManager";
|
||||
import {
|
||||
NotificationSection,
|
||||
type NotificationTargetEntry,
|
||||
} from "@/components/account/NotificationSection";
|
||||
import { emailAvailable } from "@/lib/notify";
|
||||
import { requireUserPage } from "@/lib/auth/guard";
|
||||
import { WEBAUTHN_AVAILABLE } from "@/lib/config";
|
||||
import { prisma } from "@/lib/db";
|
||||
@@ -13,7 +18,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
export default async function AccountPage() {
|
||||
const user = await requireUserPage();
|
||||
|
||||
const [passkeys, sessions] = await Promise.all([
|
||||
const [passkeys, sessions, targets, konto, offeneCodes] = await Promise.all([
|
||||
prisma.credential.findMany({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
@@ -37,6 +42,27 @@ export default async function AccountPage() {
|
||||
},
|
||||
orderBy: { lastSeenAt: "desc" },
|
||||
}),
|
||||
prisma.notificationTarget.findMany({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
channel: true,
|
||||
target: true,
|
||||
secretHint: true,
|
||||
events: true,
|
||||
isActive: true,
|
||||
lastSentAt: true,
|
||||
lastOk: true,
|
||||
lastMessage: true,
|
||||
},
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.user.findUniqueOrThrow({
|
||||
where: { id: user.id },
|
||||
select: { totpEnabledAt: true },
|
||||
}),
|
||||
prisma.recoveryCode.count({ where: { userId: user.id, usedAt: null } }),
|
||||
]);
|
||||
|
||||
const data: AccountData = {
|
||||
@@ -48,6 +74,11 @@ export default async function AccountPage() {
|
||||
passkeys,
|
||||
sessions,
|
||||
passkeysAvailable: WEBAUTHN_AVAILABLE,
|
||||
totp: {
|
||||
enabled: Boolean(konto.totpEnabledAt),
|
||||
enabledAt: konto.totpEnabledAt,
|
||||
recoveryCodesLeft: offeneCodes,
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -60,6 +91,11 @@ export default async function AccountPage() {
|
||||
</header>
|
||||
|
||||
<AccountManager data={data} />
|
||||
|
||||
<NotificationSection
|
||||
targets={targets as unknown as NotificationTargetEntry[]}
|
||||
emailAvailable={emailAvailable()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+12
-2
@@ -19,7 +19,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
export default async function AdminPage() {
|
||||
const admin = await requireAdminPage();
|
||||
|
||||
const [settings, users, eligible] = await Promise.all([
|
||||
const [settings, users, eligible, staleListeners] = await Promise.all([
|
||||
getAppSettings(),
|
||||
prisma.user.findMany({
|
||||
select: userSafeSelect,
|
||||
@@ -27,7 +27,9 @@ export default async function AdminPage() {
|
||||
}),
|
||||
// Bewusst ueber alle Konten: der Abgleich ist ein Serverauftrag, keine
|
||||
// Dateneinsicht. Gezaehlt wird nur, nicht gelesen.
|
||||
prisma.project.count({
|
||||
// Gezaehlt werden Repositories, nicht Projekte: sie sind die Einheit, in
|
||||
// der abgeglichen und begrenzt wird.
|
||||
prisma.repository.count({
|
||||
where: {
|
||||
autoSync: true,
|
||||
OR: [
|
||||
@@ -36,6 +38,9 @@ export default async function AdminPage() {
|
||||
],
|
||||
},
|
||||
}),
|
||||
prisma.notificationTarget.count({
|
||||
where: { isActive: true, events: { has: "PROJECT_STALE" } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const data: AdminData = {
|
||||
@@ -54,6 +59,11 @@ export default async function AdminPage() {
|
||||
lastReport: (settings.lastAutoSyncReport as AutoSyncReport | null) ?? null,
|
||||
eligible,
|
||||
},
|
||||
stale: {
|
||||
afterDays: settings.staleAfterDays,
|
||||
lastCheckAt: settings.lastStaleCheckAt,
|
||||
listeners: staleListeners,
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { verifyPassword } from "@/lib/auth/password";
|
||||
import { issueRecoveryCodes } from "@/lib/auth/recovery";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const schema = z.object({ password: z.string().min(1).max(200) });
|
||||
|
||||
/**
|
||||
* Neue Wiederherstellungscodes. Die alten verfallen dabei – sonst waeren
|
||||
* Zettel im Umlauf, von denen niemand mehr weiss, welche noch gelten.
|
||||
*
|
||||
* Verlangt das Passwort, wie das Abschalten auch: die Codes sind gleichwertig
|
||||
* zum zweiten Faktor.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = schema.safeParse(body.data);
|
||||
if (!parsed.success) return jsonError("Bitte das Passwort angeben.", 422);
|
||||
|
||||
const user = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: auth.user.id },
|
||||
select: { passwordHash: true, totpEnabledAt: true },
|
||||
});
|
||||
|
||||
if (!user.totpEnabledAt) {
|
||||
return jsonError("Die Zwei-Faktor-Anmeldung ist nicht aktiv.", 409);
|
||||
}
|
||||
if (!(await verifyPassword(parsed.data.password, user.passwordHash))) {
|
||||
return jsonError("Das Passwort stimmt nicht.", 401);
|
||||
}
|
||||
|
||||
return NextResponse.json({ recoveryCodes: await issueRecoveryCodes(auth.user.id) });
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import QRCode from "qrcode";
|
||||
import { z } from "zod";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { verifyPassword } from "@/lib/auth/password";
|
||||
import { countUnusedRecoveryCodes, issueRecoveryCodes } from "@/lib/auth/recovery";
|
||||
import { generateTotpSecret, groupSecret, otpauthUri, verifyTotp } from "@/lib/auth/totp";
|
||||
import { APP_NAME } from "@/lib/config";
|
||||
import { encryptSecret, tryDecryptSecret } from "@/lib/crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { formatZodError } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Zwei-Faktor-Anmeldung per Einmalkennwort.
|
||||
*
|
||||
* Die Einrichtung laeuft in zwei Schritten: POST legt einen Schluessel an und
|
||||
* zeigt ihn als QR-Code, PUT schaltet ihn nach einem bestaetigten Code scharf.
|
||||
* Erst dann fragt die Anmeldung danach. Wer die Einrichtung abbricht oder den
|
||||
* QR-Code nie scannt, sperrt sich so nicht aus.
|
||||
*/
|
||||
|
||||
/** Zustand fuer die Anzeige. */
|
||||
export async function GET() {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const user = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: auth.user.id },
|
||||
select: { totpEnabledAt: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
enabled: Boolean(user.totpEnabledAt),
|
||||
enabledAt: user.totpEnabledAt,
|
||||
recoveryCodesLeft: user.totpEnabledAt
|
||||
? await countUnusedRecoveryCodes(auth.user.id)
|
||||
: 0,
|
||||
});
|
||||
}
|
||||
|
||||
/** Schritt 1: Schluessel erzeugen und als QR-Code zurueckgeben. */
|
||||
export async function POST() {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const user = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: auth.user.id },
|
||||
select: { totpEnabledAt: true, username: true },
|
||||
});
|
||||
|
||||
if (user.totpEnabledAt) {
|
||||
return jsonError(
|
||||
"Die Zwei-Faktor-Anmeldung ist bereits aktiv. Bitte zuerst abschalten.",
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
// Bei jedem Anlauf ein frischer Schluessel: ein halb eingerichteter aus
|
||||
// einem frueheren Versuch koennte in einer Authenticator-App liegen, ohne
|
||||
// dass hier bekannt waere, in welcher.
|
||||
const secret = generateTotpSecret();
|
||||
await prisma.user.update({
|
||||
where: { id: auth.user.id },
|
||||
data: { totpSecretCipher: encryptSecret(secret) },
|
||||
});
|
||||
|
||||
const uri = otpauthUri({ secret, account: user.username, issuer: APP_NAME });
|
||||
|
||||
return NextResponse.json({
|
||||
// Das Bild als data:-URI, damit die Content-Security-Policy nichts
|
||||
// nachladen muss. img-src erlaubt data: bereits.
|
||||
qr: await QRCode.toDataURL(uri, { margin: 1, width: 320 }),
|
||||
uri,
|
||||
/** Zum Abtippen, falls die Kamera nicht mitspielt. */
|
||||
secret: groupSecret(secret),
|
||||
});
|
||||
}
|
||||
|
||||
const enableSchema = z.object({ code: z.string().min(6).max(10) });
|
||||
|
||||
/** Schritt 2: Code bestaetigen, scharfschalten, Wiederherstellungscodes ausgeben. */
|
||||
export async function PUT(request: Request) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = enableSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: auth.user.id },
|
||||
select: { totpSecretCipher: true, totpEnabledAt: true },
|
||||
});
|
||||
|
||||
if (user.totpEnabledAt) return jsonError("Die Zwei-Faktor-Anmeldung ist bereits aktiv.", 409);
|
||||
|
||||
const secret = tryDecryptSecret(user.totpSecretCipher);
|
||||
if (!secret) {
|
||||
return jsonError("Es liegt kein Schluessel vor. Bitte die Einrichtung neu starten.", 409);
|
||||
}
|
||||
|
||||
if (!verifyTotp(secret, parsed.data.code)) {
|
||||
return jsonError(
|
||||
"Der Code stimmt nicht. Geht die Uhr des Geraets richtig?",
|
||||
401,
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: auth.user.id },
|
||||
data: { totpEnabledAt: new Date() },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
// Einmalige Ausgabe: gespeichert wird nur ihr Hash.
|
||||
recoveryCodes: await issueRecoveryCodes(auth.user.id),
|
||||
});
|
||||
}
|
||||
|
||||
const disableSchema = z.object({ password: z.string().min(1).max(200) });
|
||||
|
||||
/** Abschalten. Verlangt das Passwort, nicht nur eine offene Sitzung. */
|
||||
export async function DELETE(request: Request) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = disableSchema.safeParse(body.data);
|
||||
if (!parsed.success) return jsonError("Bitte das Passwort angeben.", 422);
|
||||
|
||||
const user = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: auth.user.id },
|
||||
select: { passwordHash: true, totpEnabledAt: true },
|
||||
});
|
||||
|
||||
if (!user.totpEnabledAt) return jsonError("Die Zwei-Faktor-Anmeldung ist nicht aktiv.", 409);
|
||||
|
||||
// Ein unbeaufsichtigter Rechner mit offener Sitzung soll den zweiten Faktor
|
||||
// nicht im Vorbeigehen entfernen koennen.
|
||||
if (!(await verifyPassword(parsed.data.password, user.passwordHash))) {
|
||||
return jsonError("Das Passwort stimmt nicht.", 401);
|
||||
}
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.user.update({
|
||||
where: { id: auth.user.id },
|
||||
data: { totpSecretCipher: null, totpEnabledAt: null },
|
||||
}),
|
||||
prisma.recoveryCode.deleteMany({ where: { userId: auth.user.id } }),
|
||||
prisma.pendingLogin.deleteMany({ where: { userId: auth.user.id } }),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -37,6 +37,7 @@ export async function PATCH(request: Request) {
|
||||
autoSyncIntervalMinutes,
|
||||
autoSyncActiveOnly,
|
||||
autoSyncBatchSize,
|
||||
staleAfterDays,
|
||||
} = parsed.data;
|
||||
|
||||
// Der Wechsel in den Einzelbetrieb wuerde weitere Konten aussperren –
|
||||
@@ -57,6 +58,11 @@ export async function PATCH(request: Request) {
|
||||
...(autoSyncIntervalMinutes !== undefined ? { autoSyncIntervalMinutes } : {}),
|
||||
...(autoSyncActiveOnly !== undefined ? { autoSyncActiveOnly } : {}),
|
||||
...(autoSyncBatchSize !== undefined ? { autoSyncBatchSize } : {}),
|
||||
// Neue Schwelle: die Pruefung soll beim naechsten Tick greifen, nicht
|
||||
// erst in 24 Stunden.
|
||||
...(staleAfterDays !== undefined
|
||||
? { staleAfterDays, lastStaleCheckAt: null }
|
||||
: {}),
|
||||
};
|
||||
|
||||
const settings = await prisma.appSettings.upsert({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createPendingLogin, setMfaCookie } from "@/lib/auth/mfa";
|
||||
import { fakeVerifyDelay, verifyPassword } from "@/lib/auth/password";
|
||||
import { createSession, setSessionCookie } from "@/lib/auth/session";
|
||||
import { lockRemainingSeconds, noteFailedLogin, noteSuccessfulLogin } from "@/lib/auth/users";
|
||||
@@ -68,6 +69,18 @@ export async function POST(request: Request) {
|
||||
return jsonError(GENERIC, 401);
|
||||
}
|
||||
|
||||
// Das Passwort stimmt. Ist ein zweiter Faktor eingerichtet, entsteht hier
|
||||
// noch keine Sitzung, sondern nur ein Vorgang mit kurzer Frist.
|
||||
if (user.totpEnabledAt) {
|
||||
// Die Zaehler bleiben stehen, bis die Anmeldung wirklich durch ist:
|
||||
// sonst liesse sich ueber wiederholte Passworteingaben die Sperre
|
||||
// umgehen, die falsche Passwoerter aufbaut.
|
||||
const token = await createPendingLogin(user.id);
|
||||
const response = NextResponse.json({ ok: false, mfaRequired: true });
|
||||
setMfaCookie(response, token);
|
||||
return response;
|
||||
}
|
||||
|
||||
await noteSuccessfulLogin(user.id);
|
||||
resetRateLimit(`login:user:${username}`);
|
||||
resetRateLimit(`login:ip:${ip}`);
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
clearMfaCookie,
|
||||
discardPendingLogin,
|
||||
noteMfaFailure,
|
||||
readPendingLogin,
|
||||
} from "@/lib/auth/mfa";
|
||||
import { redeemRecoveryCode } from "@/lib/auth/recovery";
|
||||
import { createSession, setSessionCookie } from "@/lib/auth/session";
|
||||
import { verifyTotp } from "@/lib/auth/totp";
|
||||
import { noteSuccessfulLogin } from "@/lib/auth/users";
|
||||
import { LIMITS, rateLimit } from "@/lib/security/rateLimit";
|
||||
import { clientIp, jsonError, readJsonBody, tooManyRequests } from "@/lib/security/request";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Der zweite Schritt der Anmeldung: Einmalkennwort oder
|
||||
* Wiederherstellungscode.
|
||||
*
|
||||
* Der Vorgang steckt im kurzlebigen Cookie aus Schritt eins. Wer hier ohne
|
||||
* diesen Cookie ankommt, hat kein Passwort vorgezeigt und bekommt nichts.
|
||||
*/
|
||||
|
||||
const schema = z.object({
|
||||
code: z.string().min(1).max(40),
|
||||
});
|
||||
|
||||
const GENERIC = "Der Code stimmt nicht.";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ip = clientIp(request);
|
||||
const limited = rateLimit(`mfa:${ip}`, LIMITS.login.limit, LIMITS.login.windowMs);
|
||||
if (!limited.ok) return tooManyRequests(limited.retryAfter);
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = schema.safeParse(body.data);
|
||||
if (!parsed.success) return jsonError(GENERIC, 401);
|
||||
|
||||
const pending = await readPendingLogin();
|
||||
if (!pending) {
|
||||
const response = jsonError(
|
||||
"Die Anmeldung ist abgelaufen. Bitte melde dich neu an.",
|
||||
401,
|
||||
);
|
||||
clearMfaCookie(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
if (!pending.user.isActive) {
|
||||
await discardPendingLogin(pending.id);
|
||||
const response = jsonError("Dieses Konto ist deaktiviert.", 403);
|
||||
clearMfaCookie(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
const eingabe = parsed.data.code.trim();
|
||||
|
||||
// Sechs Ziffern sind ein Einmalkennwort, alles andere ein
|
||||
// Wiederherstellungscode. Beide Wege zu probieren waere unnoetig – die
|
||||
// Formate ueberschneiden sich nicht.
|
||||
const istZiffern = /^[\d\s]+$/.test(eingabe);
|
||||
const erfolg = istZiffern
|
||||
? Boolean(pending.user.totpSecret) && verifyTotp(pending.user.totpSecret!, eingabe)
|
||||
: await redeemRecoveryCode(pending.user.id, eingabe);
|
||||
|
||||
if (!erfolg) {
|
||||
const weiterMoeglich = await noteMfaFailure(pending.id);
|
||||
if (!weiterMoeglich) {
|
||||
const response = jsonError(
|
||||
"Zu viele Fehlversuche. Bitte melde dich neu an.",
|
||||
429,
|
||||
);
|
||||
clearMfaCookie(response);
|
||||
return response;
|
||||
}
|
||||
return jsonError(GENERIC, 401);
|
||||
}
|
||||
|
||||
await discardPendingLogin(pending.id);
|
||||
await noteSuccessfulLogin(pending.user.id);
|
||||
|
||||
const session = await createSession(pending.user.id, {
|
||||
userAgent: request.headers.get("user-agent"),
|
||||
ip,
|
||||
});
|
||||
|
||||
const response = NextResponse.json({
|
||||
ok: true,
|
||||
user: { id: pending.user.id, username: pending.user.username, role: pending.user.role },
|
||||
});
|
||||
setSessionCookie(response, session.token, session.expiresAt);
|
||||
clearMfaCookie(response);
|
||||
return response;
|
||||
}
|
||||
@@ -14,7 +14,7 @@ type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
const safeSelect = {
|
||||
...connectionSafeSelect,
|
||||
_count: { select: { projects: true } },
|
||||
_count: { select: { repositories: true } },
|
||||
};
|
||||
|
||||
export async function PATCH(request: Request, { params }: Params) {
|
||||
|
||||
@@ -14,7 +14,7 @@ export const dynamic = "force-dynamic";
|
||||
/** Verbindungen ohne Token-Chiffrat – das verlaesst den Server nie. */
|
||||
const safeSelect = {
|
||||
...connectionSafeSelect,
|
||||
_count: { select: { projects: true } },
|
||||
_count: { select: { repositories: true } },
|
||||
};
|
||||
|
||||
export async function GET() {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
@@ -44,6 +45,18 @@ export async function PATCH(request: Request, { params }: Params) {
|
||||
},
|
||||
});
|
||||
|
||||
// Nur Anheften ist keine inhaltliche Aenderung und kommt nicht in den
|
||||
// Verlauf – sonst steht dort dreimal dieselbe Notiz, weil jemand unschluessig war.
|
||||
if (parsed.data.title !== undefined || parsed.data.content !== undefined) {
|
||||
await recordActivity({
|
||||
projectId: note.projectId,
|
||||
userId: auth.user.id,
|
||||
kind: "NOTE_UPDATED",
|
||||
summary: `Notiz bearbeitet: ${shorten(updated.title || updated.content)}`,
|
||||
meta: { noteId: id },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ note: updated });
|
||||
}
|
||||
|
||||
@@ -53,10 +66,25 @@ export async function DELETE(_request: Request, { params }: Params) {
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// Vor dem Loeschen lesen: danach ist nicht mehr feststellbar, worum es ging.
|
||||
const vorher = await prisma.note.findFirst({
|
||||
where: { id, project: { ownerId: auth.user.id } },
|
||||
select: { projectId: true, title: true, content: true },
|
||||
});
|
||||
|
||||
const result = await prisma.note.deleteMany({
|
||||
where: { id, project: { ownerId: auth.user.id } },
|
||||
});
|
||||
if (result.count === 0) return jsonError("Notiz nicht gefunden", 404);
|
||||
|
||||
if (vorher) {
|
||||
await recordActivity({
|
||||
projectId: vorher.projectId,
|
||||
userId: auth.user.id,
|
||||
kind: "NOTE_DELETED",
|
||||
summary: `Notiz gelöscht: ${shorten(vorher.title || vorher.content)}`,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { encryptSecret, tokenHint } from "@/lib/crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { BlockedHostError, assertAllowedUrl } from "@/lib/security/ssrf";
|
||||
import { targetSafeSelect } from "@/lib/notify/types";
|
||||
import { formatZodError, notificationTargetUpdateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function PATCH(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await prisma.notificationTarget.findFirst({
|
||||
where: { id, userId: auth.user.id },
|
||||
});
|
||||
if (!existing) return jsonError("Ziel nicht gefunden", 404);
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = notificationTargetUpdateSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const update: Record<string, unknown> = {};
|
||||
|
||||
if (data.name !== undefined) update.name = data.name;
|
||||
if (data.events !== undefined) update.events = data.events;
|
||||
if (data.isActive !== undefined) update.isActive = data.isActive;
|
||||
|
||||
if (data.target !== undefined) {
|
||||
if (existing.channel !== "EMAIL") {
|
||||
try {
|
||||
await assertAllowedUrl(data.target);
|
||||
} catch (error) {
|
||||
if (error instanceof BlockedHostError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, fields: { target: error.message } },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
update.target = data.target;
|
||||
}
|
||||
|
||||
// Leeres Feld heisst "unveraendert", null heisst "entfernen".
|
||||
if (data.secret !== undefined) {
|
||||
if (data.secret) {
|
||||
update.secretCipher = encryptSecret(data.secret);
|
||||
update.secretHint = tokenHint(data.secret);
|
||||
} else {
|
||||
update.secretCipher = null;
|
||||
update.secretHint = null;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const target = await prisma.notificationTarget.update({
|
||||
where: { id },
|
||||
data: update,
|
||||
select: targetSafeSelect,
|
||||
});
|
||||
return NextResponse.json({ target });
|
||||
} catch {
|
||||
return jsonError("Name bereits vergeben.", 409);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
const result = await prisma.notificationTarget.deleteMany({
|
||||
where: { id, userId: auth.user.id },
|
||||
});
|
||||
if (result.count === 0) return jsonError("Ziel nicht gefunden", 404);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { deliver } from "@/lib/notify/channels";
|
||||
import { testMessage } from "@/lib/notify";
|
||||
import { LIMITS, rateLimit } from "@/lib/security/rateLimit";
|
||||
import { clientIp, jsonError, tooManyRequests } from "@/lib/security/request";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
/** Schickt eine Testnachricht an genau dieses Ziel. */
|
||||
export async function POST(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
// Loest einen ausgehenden Aufruf aus – entsprechend begrenzt.
|
||||
const limited = rateLimit(
|
||||
`notify-test:${auth.user.id}:${clientIp(request)}`,
|
||||
LIMITS.outbound.limit,
|
||||
LIMITS.outbound.windowMs,
|
||||
);
|
||||
if (!limited.ok) return tooManyRequests(limited.retryAfter);
|
||||
|
||||
const { id } = await params;
|
||||
const target = await prisma.notificationTarget.findFirst({
|
||||
where: { id, userId: auth.user.id },
|
||||
});
|
||||
if (!target) return jsonError("Ziel nicht gefunden", 404);
|
||||
|
||||
const result = await deliver(target, testMessage());
|
||||
|
||||
await prisma.notificationTarget.update({
|
||||
where: { id },
|
||||
data: { lastSentAt: new Date(), lastOk: result.ok, lastMessage: result.message },
|
||||
});
|
||||
|
||||
return NextResponse.json(result, { status: result.ok ? 200 : 502 });
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { encryptSecret, tokenHint } from "@/lib/crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { readJsonBody } from "@/lib/security/request";
|
||||
import { targetSafeSelect } from "@/lib/notify/types";
|
||||
import { BlockedHostError, assertAllowedUrl } from "@/lib/security/ssrf";
|
||||
import { formatZodError, notificationTargetCreateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const targets = await prisma.notificationTarget.findMany({
|
||||
where: { userId: auth.user.id },
|
||||
select: targetSafeSelect,
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
return NextResponse.json({ targets });
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = notificationTargetCreateSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const { name, channel, target, secret, events, isActive } = parsed.data;
|
||||
|
||||
// Webhook und ntfy ruft der Server spaeter selbst auf – gleiche Pruefung
|
||||
// wie bei den Git-Verbindungen.
|
||||
if (channel !== "EMAIL") {
|
||||
try {
|
||||
await assertAllowedUrl(target);
|
||||
} catch (error) {
|
||||
if (error instanceof BlockedHostError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, fields: { target: error.message } },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const duplicate = await prisma.notificationTarget.findFirst({
|
||||
where: { userId: auth.user.id, name },
|
||||
select: { id: true },
|
||||
});
|
||||
if (duplicate) {
|
||||
return NextResponse.json(
|
||||
{ error: "Name bereits vergeben.", fields: { name: "Name bereits vergeben" } },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
const created = await prisma.notificationTarget.create({
|
||||
data: {
|
||||
userId: auth.user.id,
|
||||
name,
|
||||
channel,
|
||||
target,
|
||||
secretCipher: secret ? encryptSecret(secret) : null,
|
||||
secretHint: secret ? tokenHint(secret) : null,
|
||||
events,
|
||||
isActive,
|
||||
},
|
||||
select: targetSafeSelect,
|
||||
});
|
||||
|
||||
return NextResponse.json({ target: created }, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { ACTIVITY_LIMIT } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError } from "@/lib/security/request";
|
||||
import { ownedProject } from "@/lib/tasks";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
/** Der Verlauf eines Projekts, neueste Eintraege zuerst. */
|
||||
export async function GET(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
if (!(await ownedProject(id, auth.user.id))) {
|
||||
return jsonError("Projekt nicht gefunden", 404);
|
||||
}
|
||||
|
||||
// Number(null) waere 0 und damit endlich – ohne die Pruefung auf den
|
||||
// fehlenden Parameter kaeme genau ein Eintrag zurueck.
|
||||
const roh = new URL(request.url).searchParams.get("limit");
|
||||
const angefragt = roh === null ? Number.NaN : Number(roh);
|
||||
const take = Number.isFinite(angefragt)
|
||||
? Math.min(Math.max(angefragt, 1), ACTIVITY_LIMIT)
|
||||
: 30;
|
||||
|
||||
const activities = await prisma.activity.findMany({
|
||||
where: { projectId: id },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take,
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
summary: true,
|
||||
createdAt: true,
|
||||
user: { select: { username: true, displayName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ activities });
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { exportFileName } from "@/lib/export/format";
|
||||
import { buildExportFile, toMarkdown } from "@/lib/export/project";
|
||||
import { buildExportFile, exportInclude, toMarkdown } from "@/lib/export/project";
|
||||
import { jsonError } from "@/lib/security/request";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -24,11 +24,17 @@ export async function GET(request: Request, { params }: Params) {
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id, ownerId: auth.user.id },
|
||||
include: {
|
||||
notes: { orderBy: [{ pinned: "desc" }, { createdAt: "asc" }] },
|
||||
tasks: { orderBy: [{ status: "asc" }, { position: "asc" }] },
|
||||
...exportInclude,
|
||||
// Fuer die Markdown-Fassung zusaetzlich der gespeicherte Stand, damit
|
||||
// die Datei auch ohne Netz vollstaendig ist.
|
||||
repositories: {
|
||||
include: {
|
||||
connection: { select: { name: true, provider: true, baseUrl: true } },
|
||||
snapshot: true,
|
||||
},
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) return jsonError("Projekt nicht gefunden", 404);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
@@ -64,5 +65,13 @@ export async function POST(request: Request, { params }: Params) {
|
||||
// Projekt "anfassen", damit die Sortierung nach Aktivitaet stimmt.
|
||||
await prisma.project.update({ where: { id }, data: { updatedAt: new Date() } });
|
||||
|
||||
await recordActivity({
|
||||
projectId: id,
|
||||
userId: auth.user.id,
|
||||
kind: "NOTE_ADDED",
|
||||
summary: `Notiz angelegt: ${shorten(note.title || note.content)}`,
|
||||
meta: { noteId: note.id },
|
||||
});
|
||||
|
||||
return NextResponse.json({ note }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { connectionSafeSelect } from "@/lib/projects";
|
||||
import {
|
||||
completeRepoInput,
|
||||
namesRepository,
|
||||
nextRepoPosition,
|
||||
repoTitle,
|
||||
} from "@/lib/repositories";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { ownedProject } from "@/lib/tasks";
|
||||
import { formatZodError, repositoryCreateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
/** Hoechstzahl je Projekt. Wer mehr braucht, hat mehrere Vorhaben. */
|
||||
const MAX_REPOS = 20;
|
||||
|
||||
const include = {
|
||||
connection: { select: connectionSafeSelect },
|
||||
snapshot: true,
|
||||
} as const;
|
||||
|
||||
export async function GET(_request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
if (!(await ownedProject(id, auth.user.id))) {
|
||||
return jsonError("Projekt nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const repositories = await prisma.repository.findMany({
|
||||
where: { projectId: id },
|
||||
include,
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
});
|
||||
|
||||
return NextResponse.json({ repositories });
|
||||
}
|
||||
|
||||
export async function POST(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
if (!(await ownedProject(id, auth.user.id))) {
|
||||
return jsonError("Projekt nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = repositoryCreateSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const eingabe = completeRepoInput(parsed.data);
|
||||
if (!namesRepository(eingabe)) {
|
||||
return jsonError("Bitte eine Repo-URL oder Owner und Name angeben.", 422);
|
||||
}
|
||||
|
||||
// Eine fremde Verbindung darf nicht untergeschoben werden.
|
||||
if (eingabe.connectionId) {
|
||||
const connection = await prisma.gitConnection.findFirst({
|
||||
where: { id: eingabe.connectionId, ownerId: auth.user.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!connection) return jsonError("Git-Verbindung nicht gefunden.", 404);
|
||||
}
|
||||
|
||||
const vorhanden = await prisma.repository.count({ where: { projectId: id } });
|
||||
if (vorhanden >= MAX_REPOS) {
|
||||
return jsonError(`Mehr als ${MAX_REPOS} Repositories je Projekt sind nicht vorgesehen.`, 409);
|
||||
}
|
||||
|
||||
// Dasselbe Repo zweimal am selben Projekt ist immer ein Versehen.
|
||||
if (eingabe.repoOwner && eingabe.repoName) {
|
||||
const doppelt = await prisma.repository.findFirst({
|
||||
where: { projectId: id, repoOwner: eingabe.repoOwner, repoName: eingabe.repoName },
|
||||
select: { id: true },
|
||||
});
|
||||
if (doppelt) {
|
||||
return jsonError(
|
||||
`${eingabe.repoOwner}/${eingabe.repoName} ist mit diesem Projekt bereits verknuepft.`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const repository = await prisma.repository.create({
|
||||
data: {
|
||||
projectId: id,
|
||||
label: eingabe.label ?? null,
|
||||
repoUrl: eingabe.repoUrl ?? null,
|
||||
repoOwner: eingabe.repoOwner ?? null,
|
||||
repoName: eingabe.repoName ?? null,
|
||||
connectionId: eingabe.connectionId ?? null,
|
||||
autoSync: eingabe.autoSync ?? true,
|
||||
position: await nextRepoPosition(id),
|
||||
},
|
||||
include,
|
||||
});
|
||||
|
||||
await recordActivity({
|
||||
projectId: id,
|
||||
userId: auth.user.id,
|
||||
kind: "REPO_LINKED",
|
||||
summary: `Repository verknüpft: ${shorten(repoTitle(repository))}`,
|
||||
meta: { repositoryId: repository.id },
|
||||
});
|
||||
|
||||
return NextResponse.json({ repository }, { status: 201 });
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { ProjectStatus } from "@prisma/client";
|
||||
import { NextResponse } from "next/server";
|
||||
import { describeFields, describeStatus, recordActivities, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { parseRepoUrl } from "@/lib/git";
|
||||
import { projectDetailInclude, projectListInclude, uniqueSlug } from "@/lib/projects";
|
||||
import { applyLeadingRepo, type RepoInput } from "@/lib/repositories";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { refreshDerivedProgress } from "@/lib/tasks";
|
||||
import { formatZodError, projectUpdateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -74,35 +77,97 @@ export async function PATCH(request: Request, { params }: Params) {
|
||||
"accent",
|
||||
"tags",
|
||||
"favorite",
|
||||
"autoSync",
|
||||
"connectionId",
|
||||
"progressFromTasks",
|
||||
] as const) {
|
||||
if (data[key] !== undefined) update[key] = data[key];
|
||||
}
|
||||
|
||||
if (data.repoUrl !== undefined) {
|
||||
update.repoUrl = data.repoUrl;
|
||||
const parsedUrl = data.repoUrl ? parseRepoUrl(data.repoUrl) : null;
|
||||
if (parsedUrl) {
|
||||
update.repoOwner = data.repoOwner ?? parsedUrl.owner;
|
||||
update.repoName = data.repoName ?? parsedUrl.name;
|
||||
} else if (!data.repoUrl) {
|
||||
update.repoOwner = null;
|
||||
update.repoName = null;
|
||||
}
|
||||
}
|
||||
if (data.repoOwner !== undefined) update.repoOwner = data.repoOwner;
|
||||
if (data.repoName !== undefined) update.repoName = data.repoName;
|
||||
await prisma.project.update({ where: { id }, data: update });
|
||||
|
||||
const project = await prisma.project.update({
|
||||
// Die Git-Felder gehen an das fuehrende Repository. Sie hier weiterhin
|
||||
// anzunehmen erspart der Oberflaeche zwei Aufrufe fuer einen Speichervorgang.
|
||||
const repoFelder = {
|
||||
repoUrl: data.repoUrl,
|
||||
repoOwner: data.repoOwner,
|
||||
repoName: data.repoName,
|
||||
connectionId: data.connectionId,
|
||||
autoSync: data.autoSync,
|
||||
};
|
||||
const repoBeruehrt = Object.values(repoFelder).some((value) => value !== undefined);
|
||||
if (repoBeruehrt) await applyLeadingRepo(id, repoFelder);
|
||||
|
||||
await noteChanges(id, auth.user.id, existing, update, repoBeruehrt ? repoFelder : null);
|
||||
|
||||
// Wird die Ableitung eingeschaltet, soll der Wert sofort stimmen und nicht
|
||||
// erst beim naechsten Aufgabenwechsel.
|
||||
if (data.progressFromTasks === true) {
|
||||
await refreshDerivedProgress(id);
|
||||
}
|
||||
|
||||
const project = await prisma.project.findUniqueOrThrow({
|
||||
where: { id },
|
||||
data: update,
|
||||
include: projectListInclude,
|
||||
});
|
||||
|
||||
return NextResponse.json({ project });
|
||||
}
|
||||
|
||||
/**
|
||||
* Haelt fest, was sich geaendert hat. Status und Repo-Verknuepfung bekommen
|
||||
* einen eigenen Eintrag – sie sind die Vorgaenge, die man spaeter sucht. Alles
|
||||
* uebrige fasst ein Eintrag zusammen, sonst ertraenkt eine Feinjustage der
|
||||
* Farbe den Verlauf.
|
||||
*/
|
||||
async function noteChanges(
|
||||
projectId: string,
|
||||
userId: string,
|
||||
before: { status: ProjectStatus },
|
||||
update: Record<string, unknown>,
|
||||
repo: RepoInput | null,
|
||||
) {
|
||||
const rest = Object.keys(update).filter((key) => key !== "status" && key !== "slug");
|
||||
const entries: Parameters<typeof recordActivities>[0] = [];
|
||||
|
||||
if (update.status !== undefined && update.status !== before.status) {
|
||||
const to = update.status as ProjectStatus;
|
||||
entries.push({
|
||||
projectId,
|
||||
userId,
|
||||
kind: "STATUS_CHANGED",
|
||||
summary: describeStatus(before.status, to),
|
||||
meta: { from: before.status, to },
|
||||
});
|
||||
}
|
||||
|
||||
// Nur die Verknuepfung selbst ist eine Nachricht wert. Ob der automatische
|
||||
// Abgleich an oder aus ist, gehoert zu den uebrigen Feldern.
|
||||
if (repo && (repo.repoUrl !== undefined || repo.repoName !== undefined)) {
|
||||
const ziel = repo.repoUrl ?? (repo.repoOwner ? `${repo.repoOwner}/${repo.repoName}` : null);
|
||||
entries.push({
|
||||
projectId,
|
||||
userId,
|
||||
kind: "REPO_LINKED",
|
||||
summary: ziel ? `Repository verknüpft: ${shorten(ziel)}` : "Repository-Angaben geleert",
|
||||
meta: { repoUrl: repo.repoUrl ?? null },
|
||||
});
|
||||
}
|
||||
if (repo?.autoSync !== undefined) rest.push("autoSync");
|
||||
if (repo?.connectionId !== undefined) rest.push("connectionId");
|
||||
|
||||
const felder = describeFields(rest);
|
||||
if (felder) {
|
||||
entries.push({
|
||||
projectId,
|
||||
userId,
|
||||
kind: "PROJECT_UPDATED",
|
||||
summary: felder,
|
||||
meta: { fields: rest },
|
||||
});
|
||||
}
|
||||
|
||||
await recordActivities(entries);
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { recordActivity } from "@/lib/activity";
|
||||
import { repoTitle } from "@/lib/repositories";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { nextPosition, ownedProject, refreshDerivedProgress } from "@/lib/tasks";
|
||||
import { asArray, type TicketInfo } from "@/types";
|
||||
import { formatZodError } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
const schema = z.object({
|
||||
/** Leer heisst: alle offenen Issues aus dem Snapshot. */
|
||||
numbers: z.array(z.number().int()).max(200).optional(),
|
||||
/** Aus welchem Repository. Leer heisst: dem fuehrenden. */
|
||||
repositoryId: z.string().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Uebernimmt offene Issues des verknuepften Repositories als Aufgaben.
|
||||
*
|
||||
* Grundlage ist der zuletzt geholte Snapshot – hier wird nichts nachgeladen,
|
||||
* damit ein Klick nicht ungefragt fremde APIs anspricht. Wer den neuesten
|
||||
* Stand will, gleicht vorher ab.
|
||||
*
|
||||
* Bereits uebernommene Issues werden uebersprungen: die Nummer steht an der
|
||||
* Aufgabe und ist je Projekt eindeutig. Ein zweiter Aufruf legt also keine
|
||||
* Dubletten an, auch wenn die Aufgabe inzwischen verschoben oder umbenannt
|
||||
* wurde.
|
||||
*/
|
||||
export async function POST(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
if (!(await ownedProject(id, auth.user.id))) {
|
||||
return jsonError("Projekt nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = schema.safeParse(body.data ?? {});
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
// Die Besitzerbedingung laeuft ueber das Projekt, dessen Besitz eben
|
||||
// geprueft wurde – eine fremde Repository-ID trifft hier also nichts.
|
||||
const repository = await prisma.repository.findFirst({
|
||||
where: { projectId: id, ...(parsed.data.repositoryId ? { id: parsed.data.repositoryId } : {}) },
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
include: { snapshot: true },
|
||||
});
|
||||
|
||||
if (!repository) {
|
||||
// 404 nur, wenn nach einem bestimmten gefragt wurde. Wer nichts angibt,
|
||||
// hat schlicht noch keines verknuepft – und das ist kein "nicht gefunden".
|
||||
return parsed.data.repositoryId
|
||||
? jsonError("Repository nicht gefunden", 404)
|
||||
: jsonError("Kein Repository verknuepft. Bitte zuerst eines hinterlegen.", 409);
|
||||
}
|
||||
|
||||
const snapshot = repository.snapshot;
|
||||
if (!snapshot) {
|
||||
return jsonError(
|
||||
"Noch kein Repo-Stand vorhanden. Bitte zuerst synchronisieren.",
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const alle = asArray<TicketInfo>(snapshot.issues);
|
||||
const gewuenscht = parsed.data.numbers;
|
||||
const auswahl = gewuenscht?.length
|
||||
? alle.filter((issue) => gewuenscht.includes(issue.number))
|
||||
: alle;
|
||||
|
||||
if (auswahl.length === 0) {
|
||||
return NextResponse.json({ created: 0, skipped: 0, tasks: [] });
|
||||
}
|
||||
|
||||
const vorhanden = await prisma.task.findMany({
|
||||
where: {
|
||||
projectId: id,
|
||||
sourceRepositoryId: repository.id,
|
||||
sourceIssue: { in: auswahl.map((issue) => issue.number) },
|
||||
},
|
||||
select: { sourceIssue: true },
|
||||
});
|
||||
const bekannt = new Set(vorhanden.map((task) => task.sourceIssue));
|
||||
|
||||
const neu = auswahl.filter((issue) => !bekannt.has(issue.number));
|
||||
let position = await nextPosition(id, "TODO");
|
||||
|
||||
const angelegt = [];
|
||||
for (const issue of neu) {
|
||||
angelegt.push(
|
||||
await prisma.task.create({
|
||||
data: {
|
||||
projectId: id,
|
||||
title: issue.title.slice(0, 200),
|
||||
// Der Link ist das Wichtigste – der Text steht im Git-System.
|
||||
description: issue.url ? `[Issue #${issue.number}](${issue.url})` : null,
|
||||
status: "TODO",
|
||||
position: position++,
|
||||
labels: issue.labels.slice(0, 8),
|
||||
sourceIssue: issue.number,
|
||||
sourceUrl: issue.url,
|
||||
sourceRepositoryId: repository.id,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (angelegt.length > 0) {
|
||||
await refreshDerivedProgress(id);
|
||||
await prisma.project.update({ where: { id }, data: { updatedAt: new Date() } });
|
||||
// Ein Eintrag fuer den Vorgang, nicht einer je Aufgabe: sonst besteht der
|
||||
// Verlauf nach einer Uebernahme aus nichts anderem mehr.
|
||||
await recordActivity({
|
||||
projectId: id,
|
||||
userId: auth.user.id,
|
||||
kind: "TASKS_IMPORTED",
|
||||
summary:
|
||||
angelegt.length === 1
|
||||
? `1 Issue aus ${repoTitle(repository)} als Aufgabe übernommen`
|
||||
: `${angelegt.length} Issues aus ${repoTitle(repository)} als Aufgaben übernommen`,
|
||||
meta: {
|
||||
repositoryId: repository.id,
|
||||
numbers: angelegt.map((task) => task.sourceIssue),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
created: angelegt.length,
|
||||
skipped: auswahl.length - angelegt.length,
|
||||
tasks: angelegt,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
@@ -65,5 +66,13 @@ export async function POST(request: Request, { params }: Params) {
|
||||
// Damit die Sortierung nach Aktivitaet stimmt.
|
||||
await prisma.project.update({ where: { id }, data: { updatedAt: new Date() } });
|
||||
|
||||
await recordActivity({
|
||||
projectId: id,
|
||||
userId: auth.user.id,
|
||||
kind: "TASK_ADDED",
|
||||
summary: `Aufgabe angelegt: ${shorten(task.title, 50)}`,
|
||||
meta: { taskId: task.id },
|
||||
});
|
||||
|
||||
return NextResponse.json({ task }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { recordActivity } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { exportFileSchema, type ExportedProject } from "@/lib/export/format";
|
||||
import {
|
||||
exportFileSchema,
|
||||
repositoriesOf,
|
||||
type ExportedRepository,
|
||||
} from "@/lib/export/format";
|
||||
import { uniqueSlug } from "@/lib/projects";
|
||||
import { LIMITS, rateLimit } from "@/lib/security/rateLimit";
|
||||
import {
|
||||
@@ -84,7 +89,7 @@ export async function POST(request: Request) {
|
||||
select: { id: true, name: true, provider: true, baseUrl: true },
|
||||
});
|
||||
|
||||
function matchConnection(described: ExportedProject["connection"]) {
|
||||
function matchConnection(described: ExportedRepository["connection"]) {
|
||||
if (!described) return null;
|
||||
const byName = connections.find(
|
||||
(candidate) => candidate.name.toLowerCase() === described.name.toLowerCase(),
|
||||
@@ -104,12 +109,26 @@ export async function POST(request: Request) {
|
||||
|
||||
for (const incoming of file.projects) {
|
||||
const slug = incoming.slug || slugify(incoming.name) || "projekt";
|
||||
const connection = matchConnection(incoming.connection);
|
||||
const connectionState: ItemResult["connection"] = incoming.connection
|
||||
? connection
|
||||
? "matched"
|
||||
: "missing"
|
||||
: "none";
|
||||
|
||||
// Version 1 kannte ein Repository je Projekt und schrieb es flach; seit
|
||||
// Version 2 steht eine Liste da. repositoriesOf glaettet den Unterschied.
|
||||
const eingehendeRepos = repositoriesOf(incoming);
|
||||
const repos = eingehendeRepos.map((repo, index) => ({
|
||||
label: repo.label ?? null,
|
||||
repoUrl: repo.repoUrl ?? null,
|
||||
repoOwner: repo.repoOwner ?? null,
|
||||
repoName: repo.repoName ?? null,
|
||||
autoSync: repo.autoSync ?? true,
|
||||
connectionId: matchConnection(repo.connection ?? null)?.id ?? null,
|
||||
position: index,
|
||||
}));
|
||||
|
||||
// Fuer die Rueckmeldung genuegt, ob ueberhaupt eine beschriebene
|
||||
// Verbindung fehlt – welche, steht in der Datei.
|
||||
const beschrieben = eingehendeRepos.filter((repo) => repo.connection);
|
||||
const fehlend = beschrieben.filter((repo) => !matchConnection(repo.connection ?? null));
|
||||
const connectionState: ItemResult["connection"] =
|
||||
beschrieben.length === 0 ? "none" : fehlend.length > 0 ? "missing" : "matched";
|
||||
|
||||
const existing = await prisma.project.findFirst({
|
||||
where: { slug, ownerId: auth.user.id },
|
||||
@@ -122,7 +141,7 @@ export async function POST(request: Request) {
|
||||
action: "create",
|
||||
notes: incoming.notes.length,
|
||||
connection: connectionState,
|
||||
connectionName: incoming.connection?.name,
|
||||
connectionName: (fehlend[0] ?? beschrieben[0])?.connection?.name,
|
||||
};
|
||||
|
||||
if (existing && strategy === "skip") {
|
||||
@@ -154,11 +173,6 @@ export async function POST(request: Request) {
|
||||
accent: incoming.accent,
|
||||
tags: incoming.tags,
|
||||
favorite: incoming.favorite,
|
||||
autoSync: incoming.autoSync,
|
||||
repoUrl: incoming.repoUrl ?? null,
|
||||
repoOwner: incoming.repoOwner ?? null,
|
||||
repoName: incoming.repoName ?? null,
|
||||
connectionId: connection?.id ?? null,
|
||||
progressFromTasks: incoming.progressFromTasks,
|
||||
};
|
||||
|
||||
@@ -194,23 +208,43 @@ export async function POST(request: Request) {
|
||||
await prisma.$transaction([
|
||||
prisma.note.deleteMany({ where: { projectId: existing.id } }),
|
||||
prisma.task.deleteMany({ where: { projectId: existing.id } }),
|
||||
// Wie Notizen und Aufgaben: austauschen statt zusammenfuehren. Der
|
||||
// gesammelte Repo-Stand geht dabei mit, ist aber beim naechsten
|
||||
// Abgleich zurueck.
|
||||
prisma.repository.deleteMany({ where: { projectId: existing.id } }),
|
||||
prisma.project.update({
|
||||
where: { id: existing.id },
|
||||
data: { ...data, slug, notes: { create: notes }, tasks: { create: tasks } },
|
||||
data: {
|
||||
...data,
|
||||
slug,
|
||||
notes: { create: notes },
|
||||
tasks: { create: tasks },
|
||||
repositories: { create: repos },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
results.push({ ...base, action: "overwrite" });
|
||||
} else {
|
||||
const finalSlug = existing ? await uniqueSlug(incoming.name, auth.user.id) : slug;
|
||||
await prisma.project.create({
|
||||
const angelegt = await prisma.project.create({
|
||||
data: {
|
||||
...data,
|
||||
ownerId: auth.user.id,
|
||||
slug: finalSlug,
|
||||
notes: { create: notes },
|
||||
tasks: { create: tasks },
|
||||
repositories: { create: repos },
|
||||
},
|
||||
});
|
||||
// Der Verlauf wird nicht mitexportiert – der erste Eintrag hier haelt
|
||||
// wenigstens fest, woher das Projekt stammt.
|
||||
await recordActivity({
|
||||
projectId: angelegt.id,
|
||||
userId: auth.user.id,
|
||||
kind: "PROJECT_CREATED",
|
||||
summary: "Aus einer Exportdatei importiert",
|
||||
meta: { notes: notes.length, tasks: tasks.length },
|
||||
});
|
||||
results.push({
|
||||
...base,
|
||||
action: existing ? "rename" : "create",
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { parseRepoUrl } from "@/lib/git";
|
||||
import { projectListInclude, uniqueSlug } from "@/lib/projects";
|
||||
import { applyLeadingRepo } from "@/lib/repositories";
|
||||
import { LIMITS, rateLimit } from "@/lib/security/rateLimit";
|
||||
import { clientIp, jsonError, readJsonBody, tooManyRequests } from "@/lib/security/request";
|
||||
import { statusOf } from "@/lib/status";
|
||||
import { formatZodError, projectCreateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -72,18 +74,7 @@ export async function POST(request: Request) {
|
||||
if (!connection) return jsonError("Git-Verbindung nicht gefunden.", 404);
|
||||
}
|
||||
|
||||
// Owner/Name aus der URL ableiten, falls nicht explizit angegeben.
|
||||
let repoOwner = data.repoOwner ?? null;
|
||||
let repoName = data.repoName ?? null;
|
||||
if (data.repoUrl && (!repoOwner || !repoName)) {
|
||||
const parsedUrl = parseRepoUrl(data.repoUrl);
|
||||
if (parsedUrl) {
|
||||
repoOwner = repoOwner ?? parsedUrl.owner;
|
||||
repoName = repoName ?? parsedUrl.name;
|
||||
}
|
||||
}
|
||||
|
||||
const project = await prisma.project.create({
|
||||
const angelegt = await prisma.project.create({
|
||||
data: {
|
||||
ownerId: auth.user.id,
|
||||
name: data.name,
|
||||
@@ -96,14 +87,34 @@ export async function POST(request: Request) {
|
||||
accent: data.accent,
|
||||
tags: data.tags,
|
||||
favorite: data.favorite,
|
||||
autoSync: data.autoSync,
|
||||
repoUrl: data.repoUrl ?? null,
|
||||
repoOwner,
|
||||
repoName,
|
||||
connectionId: data.connectionId ?? null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
// Die Git-Angaben werden zum fuehrenden Repository – falls welche kamen.
|
||||
await applyLeadingRepo(angelegt.id, {
|
||||
repoUrl: data.repoUrl,
|
||||
repoOwner: data.repoOwner,
|
||||
repoName: data.repoName,
|
||||
connectionId: data.connectionId,
|
||||
autoSync: data.autoSync,
|
||||
});
|
||||
|
||||
const project = await prisma.project.findUniqueOrThrow({
|
||||
where: { id: angelegt.id },
|
||||
include: projectListInclude,
|
||||
});
|
||||
|
||||
await recordActivity({
|
||||
projectId: project.id,
|
||||
userId: auth.user.id,
|
||||
kind: "PROJECT_CREATED",
|
||||
summary:
|
||||
data.status === "IDEA"
|
||||
? "Als Idee angelegt"
|
||||
: `Angelegt mit Status „${statusOf(data.status).label}“`,
|
||||
meta: { status: data.status },
|
||||
});
|
||||
|
||||
return NextResponse.json({ project }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { connectionSafeSelect } from "@/lib/projects";
|
||||
import { completeRepoInput, ownedRepository, repoTitle } from "@/lib/repositories";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { formatZodError, repositoryUpdateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function PATCH(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await ownedRepository(id, auth.user.id);
|
||||
if (!existing) return jsonError("Repository nicht gefunden", 404);
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = repositoryUpdateSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const eingabe = completeRepoInput(parsed.data);
|
||||
|
||||
if (eingabe.connectionId) {
|
||||
const connection = await prisma.gitConnection.findFirst({
|
||||
where: { id: eingabe.connectionId, ownerId: auth.user.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!connection) return jsonError("Git-Verbindung nicht gefunden.", 404);
|
||||
}
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
for (const key of ["label", "repoUrl", "repoOwner", "repoName", "connectionId", "autoSync"] as const) {
|
||||
if (eingabe[key] !== undefined) data[key] = eingabe[key];
|
||||
}
|
||||
if (parsed.data.position !== undefined) data.position = parsed.data.position;
|
||||
|
||||
// Zeigt das Repo woandershin, taugt der gesammelte Stand nicht mehr. Ihn
|
||||
// stehen zu lassen waere schlimmer als ihn zu verlieren: er saehe echt aus.
|
||||
const zieltWoandershin =
|
||||
(eingabe.repoOwner !== undefined && eingabe.repoOwner !== existing.repoOwner) ||
|
||||
(eingabe.repoName !== undefined && eingabe.repoName !== existing.repoName);
|
||||
if (zieltWoandershin) {
|
||||
data.lastSyncedAt = null;
|
||||
data.syncError = null;
|
||||
data.syncFailureCount = 0;
|
||||
data.notifiedSyncError = null;
|
||||
data.notifiedCiState = null;
|
||||
data.notifiedRelease = null;
|
||||
await prisma.repoSnapshot.deleteMany({ where: { repositoryId: id } });
|
||||
}
|
||||
|
||||
const repository = await prisma.repository.update({
|
||||
where: { id },
|
||||
data,
|
||||
include: { connection: { select: connectionSafeSelect }, snapshot: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({ repository });
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// Vor dem Loeschen lesen: danach ist nicht mehr feststellbar, worum es ging.
|
||||
const vorher = await ownedRepository(id, auth.user.id);
|
||||
if (!vorher) return jsonError("Repository nicht gefunden", 404);
|
||||
|
||||
await prisma.repository.delete({ where: { id } });
|
||||
|
||||
await recordActivity({
|
||||
projectId: vorher.projectId,
|
||||
userId: auth.user.id,
|
||||
kind: "REPO_LINKED",
|
||||
summary: `Repository entfernt: ${shorten(repoTitle(vorher))}`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { connectionSafeSelect } from "@/lib/projects";
|
||||
import { ownedRepository } from "@/lib/repositories";
|
||||
import { LIMITS, rateLimit } from "@/lib/security/rateLimit";
|
||||
import { clientIp, jsonError, tooManyRequests } from "@/lib/security/request";
|
||||
import { syncRepository } from "@/lib/sync";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
/** Gleicht ein einzelnes Repository ab. */
|
||||
export async function POST(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
// Dieser Endpunkt loest ausgehende Verbindungen aus – hier wird enger
|
||||
// begrenzt als bei reinen Datenbankzugriffen.
|
||||
const limited = rateLimit(
|
||||
`outbound:${auth.user.id}:${clientIp(request)}`,
|
||||
LIMITS.outbound.limit,
|
||||
LIMITS.outbound.windowMs,
|
||||
);
|
||||
if (!limited.ok) return tooManyRequests(limited.retryAfter);
|
||||
|
||||
const { id } = await params;
|
||||
if (!(await ownedRepository(id, auth.user.id))) {
|
||||
return jsonError("Repository nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const result = await syncRepository(id);
|
||||
|
||||
const repository = await prisma.repository.findUnique({
|
||||
where: { id },
|
||||
include: { connection: { select: connectionSafeSelect }, snapshot: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ...result, repository }, { status: result.ok ? 200 : 502 });
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { TaskStatus } from "@prisma/client";
|
||||
import { NextResponse } from "next/server";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { nextPosition, refreshDerivedProgress } from "@/lib/tasks";
|
||||
import { TASK_STATUS_META, nextPosition, refreshDerivedProgress } from "@/lib/tasks";
|
||||
import { formatZodError, taskUpdateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -13,7 +15,7 @@ type Params = { params: Promise<{ id: string }> };
|
||||
async function ownedTask(taskId: string, ownerId: string) {
|
||||
return prisma.task.findFirst({
|
||||
where: { id: taskId, project: { ownerId } },
|
||||
select: { id: true, projectId: true, status: true },
|
||||
select: { id: true, projectId: true, status: true, title: true },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,6 +59,20 @@ export async function PATCH(request: Request, { params }: Params) {
|
||||
const task = await prisma.task.update({ where: { id }, data: update });
|
||||
await refreshDerivedProgress(existing.projectId);
|
||||
|
||||
// Nur der Spaltenwechsel kommt in den Verlauf. Ein umbenannter Titel oder
|
||||
// ein neues Label sind zu kleinteilig, um die Geschichte des Projekts zu
|
||||
// erzaehlen – und beim Ziehen im Brett ist der Wechsel die eigentliche Tat.
|
||||
if (update.status !== undefined) {
|
||||
const nach = update.status as TaskStatus;
|
||||
await recordActivity({
|
||||
projectId: existing.projectId,
|
||||
userId: auth.user.id,
|
||||
kind: "TASK_MOVED",
|
||||
summary: `Aufgabe „${shorten(task.title, 50)}“ → ${TASK_STATUS_META[nach].label}`,
|
||||
meta: { taskId: id, from: existing.status, to: nach },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ task });
|
||||
}
|
||||
|
||||
@@ -71,5 +87,12 @@ export async function DELETE(_request: Request, { params }: Params) {
|
||||
await prisma.task.delete({ where: { id } });
|
||||
await refreshDerivedProgress(existing.projectId);
|
||||
|
||||
await recordActivity({
|
||||
projectId: existing.projectId,
|
||||
userId: auth.user.id,
|
||||
kind: "TASK_DELETED",
|
||||
summary: `Aufgabe gelöscht: ${shorten(existing.title, 50)}`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export default async function ConnectionsPage() {
|
||||
|
||||
const connections = await prisma.gitConnection.findMany({
|
||||
where: { ownerId: user.id },
|
||||
select: { ...connectionSafeSelect, _count: { select: { projects: true } } },
|
||||
select: { ...connectionSafeSelect, _count: { select: { repositories: true } } },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { CommandPalette } from "@/components/CommandPalette";
|
||||
import { TopNav } from "@/components/TopNav";
|
||||
import { getSessionUser } from "@/lib/auth/session";
|
||||
import { APP_NAME, APP_TAGLINE, APP_VERSION } from "@/lib/config";
|
||||
@@ -45,6 +46,9 @@ export default async function RootLayout({
|
||||
|
||||
<TopNav user={user} appName={APP_NAME} tagline={APP_TAGLINE} />
|
||||
|
||||
{/* Nur fuer Angemeldete – auf der Anmeldeseite gibt es nichts zu suchen. */}
|
||||
{user ? <CommandPalette isAdmin={user.role === "ADMIN"} /> : null}
|
||||
|
||||
<main className="mx-auto w-full max-w-[1400px] px-4 pb-24 pt-6 sm:px-6 lg:px-8">
|
||||
{children}
|
||||
</main>
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ export default async function DashboardPage() {
|
||||
const ideas = active.filter((project) => project.status === "IDEA").length;
|
||||
const inDev = active.filter((project) => project.status === "IN_DEVELOPMENT").length;
|
||||
const done = active.filter((project) => project.status === "DONE").length;
|
||||
const linked = active.filter((project) => Boolean(project.repoOwner && project.repoName)).length;
|
||||
const linked = active.filter((project) => project.repositories.length > 0).length;
|
||||
|
||||
const averageProgress =
|
||||
active.length > 0
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { FileText } from "lucide-react";
|
||||
import { ActivityFeed } from "@/components/ActivityFeed";
|
||||
import { GitPanel } from "@/components/GitPanel";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { NotesPanel } from "@/components/NotesPanel";
|
||||
@@ -85,8 +86,12 @@ export default async function ProjectPage({ params }: PageProps) {
|
||||
<NotesPanel projectId={detail.id} notes={detail.notes} />
|
||||
</div>
|
||||
|
||||
<div className="lg:col-span-7">
|
||||
<GitPanel project={detail} />
|
||||
<div className="space-y-6 lg:col-span-7">
|
||||
<GitPanel
|
||||
project={detail}
|
||||
connections={connections as unknown as ConnectionSafe[]}
|
||||
/>
|
||||
<ActivityFeed projectId={detail.id} initial={detail.activities} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
AlertTriangle,
|
||||
ArrowRight,
|
||||
Bot,
|
||||
Download,
|
||||
GitCommitHorizontal,
|
||||
History,
|
||||
Link2,
|
||||
Loader2,
|
||||
NotebookPen,
|
||||
Pencil,
|
||||
Plus,
|
||||
Signpost,
|
||||
Sparkles,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import type { ActivityEntry, ActivityKind } from "@/types";
|
||||
import { formatDateTime, formatRelative } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Der Verlauf eines Projekts: was ist wann passiert.
|
||||
*
|
||||
* Die erste Seite kommt mit der Seite mit, weitere holt der Knopf nach. Die
|
||||
* Alternative – alles gleich mitzuladen – wuerde jeden Seitenaufruf mit
|
||||
* zweihundert Eintraegen belasten, von denen man selten mehr als die
|
||||
* obersten fuenf liest.
|
||||
*/
|
||||
|
||||
const KINDS: Record<ActivityKind, { icon: typeof Sparkles; color: string }> = {
|
||||
PROJECT_CREATED: { icon: Sparkles, color: "text-violet-300" },
|
||||
PROJECT_UPDATED: { icon: Pencil, color: "text-slate-400" },
|
||||
STATUS_CHANGED: { icon: Signpost, color: "text-cyan-300" },
|
||||
NOTE_ADDED: { icon: NotebookPen, color: "text-blue-300" },
|
||||
NOTE_UPDATED: { icon: Pencil, color: "text-blue-300" },
|
||||
NOTE_DELETED: { icon: Trash2, color: "text-rose-300" },
|
||||
TASK_ADDED: { icon: Plus, color: "text-emerald-300" },
|
||||
TASK_MOVED: { icon: ArrowRight, color: "text-violet-300" },
|
||||
TASK_DELETED: { icon: Trash2, color: "text-rose-300" },
|
||||
TASKS_IMPORTED: { icon: Download, color: "text-amber-300" },
|
||||
REPO_LINKED: { icon: Link2, color: "text-cyan-300" },
|
||||
REPO_COMMITS: { icon: GitCommitHorizontal, color: "text-emerald-300" },
|
||||
SYNC_FAILED: { icon: AlertTriangle, color: "text-rose-300" },
|
||||
};
|
||||
|
||||
export function ActivityFeed({
|
||||
projectId,
|
||||
initial,
|
||||
}: {
|
||||
projectId: string;
|
||||
initial: ActivityEntry[];
|
||||
}) {
|
||||
const [entries, setEntries] = useState(initial);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Kam eine volle Seite, gibt es womoeglich noch mehr.
|
||||
const [complete, setComplete] = useState(initial.length < 20);
|
||||
|
||||
async function loadAll() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/projects/${projectId}/activity?limit=200`);
|
||||
if (!response.ok) throw new Error("Verlauf konnte nicht geladen werden.");
|
||||
const payload = await response.json();
|
||||
setEntries(payload.activities as ActivityEntry[]);
|
||||
setComplete(true);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="glass p-5">
|
||||
<h2 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wider text-slate-300">
|
||||
<History className="h-4 w-4 text-violet-300" />
|
||||
Verlauf
|
||||
</h2>
|
||||
|
||||
{entries.length === 0 ? (
|
||||
<p className="mt-3 text-sm text-slate-500">
|
||||
Noch nichts passiert. Sobald du etwas änderst, steht es hier.
|
||||
</p>
|
||||
) : (
|
||||
<ol className="mt-4 space-y-0">
|
||||
{entries.map((entry, index) => {
|
||||
const meta = KINDS[entry.kind] ?? KINDS.PROJECT_UPDATED;
|
||||
const Icon = meta.icon;
|
||||
const letzter = index === entries.length - 1;
|
||||
|
||||
return (
|
||||
<li key={entry.id} className="relative flex gap-3 pb-4">
|
||||
{/* Die Linie endet am letzten Eintrag, statt ins Leere zu laufen. */}
|
||||
{!letzter ? (
|
||||
<span
|
||||
aria-hidden
|
||||
className="absolute left-3 top-7 h-[calc(100%-1.25rem)] w-px bg-white/15"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<span className="relative z-10 mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[#0d1020] ring-1 ring-white/10">
|
||||
<Icon className={`h-3.5 w-3.5 ${meta.color}`} />
|
||||
</span>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm leading-snug text-slate-200">{entry.summary}</p>
|
||||
<p className="mt-0.5 flex items-center gap-1.5 text-xs text-slate-500">
|
||||
<time dateTime={new Date(entry.createdAt).toISOString()}>
|
||||
{formatRelative(entry.createdAt)}
|
||||
</time>
|
||||
<span aria-hidden>·</span>
|
||||
<span>{formatDateTime(entry.createdAt)}</span>
|
||||
{/* Ohne Benutzer war es der automatische Abgleich. */}
|
||||
{entry.user ? null : (
|
||||
<>
|
||||
<span aria-hidden>·</span>
|
||||
<Bot className="h-3 w-3" aria-hidden />
|
||||
<span>automatisch</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
{error ? <p className="mt-2 text-xs text-rose-300">{error}</p> : null}
|
||||
|
||||
{!complete ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={loadAll}
|
||||
disabled={loading}
|
||||
className="btn btn-ghost mt-1 w-full text-xs"
|
||||
>
|
||||
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Älteres anzeigen
|
||||
</button>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Bell,
|
||||
CornerDownLeft,
|
||||
GitBranch,
|
||||
LayoutDashboard,
|
||||
Loader2,
|
||||
NotebookPen,
|
||||
Plus,
|
||||
Search,
|
||||
Settings,
|
||||
UserRound,
|
||||
} from "lucide-react";
|
||||
import type { ProjectStatus } from "@prisma/client";
|
||||
import { statusOf } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Schnellsuche, zu erreichen mit Strg+K beziehungsweise Cmd+K.
|
||||
*
|
||||
* Springt zu einem Projekt, zu einer Notiz oder direkt in einen Bereich.
|
||||
* Die Projektliste wird beim ersten Oeffnen geholt und dann behalten – sie
|
||||
* bei jedem Tastendruck neu zu laden waere Verschwendung, und veraltet ist
|
||||
* sie hoechstens um die Dauer einer Sitzung.
|
||||
*/
|
||||
|
||||
interface ProjectHit {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
summary: string | null;
|
||||
status: ProjectStatus;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
interface NoteHit {
|
||||
projectId: string;
|
||||
noteId: string;
|
||||
title: string | null;
|
||||
snippet: string;
|
||||
}
|
||||
|
||||
interface Action {
|
||||
id: string;
|
||||
label: string;
|
||||
hint: string;
|
||||
icon: typeof LayoutDashboard;
|
||||
href: string;
|
||||
adminOnly?: boolean;
|
||||
}
|
||||
|
||||
const ACTIONS: Action[] = [
|
||||
{ id: "dashboard", label: "Dashboard", hint: "Alle Projekte", icon: LayoutDashboard, href: "/" },
|
||||
{
|
||||
id: "connections",
|
||||
label: "Git-Verbindungen",
|
||||
hint: "GitHub, GitLab, Gitea",
|
||||
icon: GitBranch,
|
||||
href: "/connections",
|
||||
},
|
||||
{ id: "account", label: "Mein Konto", hint: "Profil, Passkeys", icon: UserRound, href: "/account" },
|
||||
{
|
||||
id: "notify",
|
||||
label: "Benachrichtigungen",
|
||||
hint: "Ziele verwalten",
|
||||
icon: Bell,
|
||||
href: "/account",
|
||||
},
|
||||
{
|
||||
id: "admin",
|
||||
label: "Admin-Einstellungen",
|
||||
hint: "Betriebsart, Abgleich, Konten",
|
||||
icon: Settings,
|
||||
href: "/admin",
|
||||
adminOnly: true,
|
||||
},
|
||||
];
|
||||
|
||||
type Entry =
|
||||
| { kind: "action"; key: string; action: Action }
|
||||
| { kind: "project"; key: string; project: ProjectHit }
|
||||
| { kind: "note"; key: string; note: NoteHit; projectName: string };
|
||||
|
||||
export function CommandPalette({ isAdmin }: { isAdmin: boolean }) {
|
||||
const router = useRouter();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [projects, setProjects] = useState<ProjectHit[] | null>(null);
|
||||
const [notes, setNotes] = useState<NoteHit[]>([]);
|
||||
const [active, setActive] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
// Strg+K oeffnet, Escape schliesst. In Eingabefeldern nicht stoeren –
|
||||
// ausser beim Kuerzel selbst, das soll ueberall greifen.
|
||||
useEffect(() => {
|
||||
function onKey(event: KeyboardEvent) {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
|
||||
event.preventDefault();
|
||||
setOpen((value) => !value);
|
||||
} else if (event.key === "Escape") {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => document.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
// Projektliste beim ersten Oeffnen holen.
|
||||
useEffect(() => {
|
||||
if (!open || projects !== null) return;
|
||||
setLoading(true);
|
||||
fetch("/api/projects")
|
||||
.then((response) => (response.ok ? response.json() : { projects: [] }))
|
||||
.then((body) => setProjects(body.projects ?? []))
|
||||
.catch(() => setProjects([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, [open, projects]);
|
||||
|
||||
// Notizen sucht der Server – entprellt, wie im Board.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const needle = query.trim();
|
||||
if (needle.length < 2) {
|
||||
setNotes([]);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/search?q=${encodeURIComponent(needle)}`, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) return;
|
||||
const body = (await response.json()) as { hits: NoteHit[] };
|
||||
setNotes(body.hits ?? []);
|
||||
} catch {
|
||||
// Abbruch beim Weitertippen ist der Normalfall.
|
||||
}
|
||||
}, 250);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [open, query]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setQuery("");
|
||||
setNotes([]);
|
||||
setActive(0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const entries = useMemo<Entry[]>(() => {
|
||||
const needle = query.toLowerCase().trim();
|
||||
const result: Entry[] = [];
|
||||
|
||||
const passendeAktionen = ACTIONS.filter(
|
||||
(action) =>
|
||||
(!action.adminOnly || isAdmin) &&
|
||||
(!needle ||
|
||||
action.label.toLowerCase().includes(needle) ||
|
||||
action.hint.toLowerCase().includes(needle)),
|
||||
);
|
||||
|
||||
const passendeProjekte = (projects ?? []).filter(
|
||||
(project) =>
|
||||
!needle ||
|
||||
project.name.toLowerCase().includes(needle) ||
|
||||
(project.summary ?? "").toLowerCase().includes(needle) ||
|
||||
project.tags.some((tag) => tag.includes(needle)),
|
||||
);
|
||||
|
||||
// Bei leerer Eingabe stehen die Projekte oben – danach sucht man
|
||||
// normalerweise.
|
||||
if (!needle) {
|
||||
for (const project of passendeProjekte.slice(0, 6)) {
|
||||
result.push({ kind: "project", key: `p-${project.id}`, project });
|
||||
}
|
||||
for (const action of passendeAktionen) {
|
||||
result.push({ kind: "action", key: `a-${action.id}`, action });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
for (const project of passendeProjekte.slice(0, 8)) {
|
||||
result.push({ kind: "project", key: `p-${project.id}`, project });
|
||||
}
|
||||
for (const hit of notes.slice(0, 5)) {
|
||||
result.push({
|
||||
kind: "note",
|
||||
key: `n-${hit.noteId}`,
|
||||
note: hit,
|
||||
projectName:
|
||||
(projects ?? []).find((project) => project.id === hit.projectId)?.name ?? "Projekt",
|
||||
});
|
||||
}
|
||||
for (const action of passendeAktionen) {
|
||||
result.push({ kind: "action", key: `a-${action.id}`, action });
|
||||
}
|
||||
return result;
|
||||
}, [query, projects, notes, isAdmin]);
|
||||
|
||||
useEffect(() => {
|
||||
setActive((current) => Math.min(current, Math.max(0, entries.length - 1)));
|
||||
}, [entries.length]);
|
||||
|
||||
const go = useCallback(
|
||||
(entry: Entry) => {
|
||||
setOpen(false);
|
||||
if (entry.kind === "action") router.push(entry.action.href);
|
||||
else if (entry.kind === "project") router.push(`/projects/${entry.project.id}`);
|
||||
else router.push(`/projects/${entry.note.projectId}`);
|
||||
},
|
||||
[router],
|
||||
);
|
||||
|
||||
function onInputKey(event: React.KeyboardEvent) {
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
setActive((current) => (current + 1) % Math.max(1, entries.length));
|
||||
} else if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
setActive((current) => (current - 1 + entries.length) % Math.max(1, entries.length));
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
const entry = entries[active];
|
||||
if (entry) go(entry);
|
||||
}
|
||||
}
|
||||
|
||||
// Ausgewaehlten Eintrag im Blick behalten.
|
||||
useEffect(() => {
|
||||
listRef.current
|
||||
?.querySelector<HTMLElement>(`[data-index="${active}"]`)
|
||||
?.scrollIntoView({ block: "nearest" });
|
||||
}, [active]);
|
||||
|
||||
if (!mounted || !open) return null;
|
||||
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 z-[130] flex items-start justify-center p-4 pt-[12vh]">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Schnellsuche schliessen"
|
||||
onClick={() => setOpen(false)}
|
||||
className="fixed inset-0 cursor-default bg-[#03040c]/80 backdrop-blur-sm"
|
||||
/>
|
||||
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Schnellsuche"
|
||||
className="popover fade-up relative z-10 w-full max-w-xl overflow-hidden rounded-2xl"
|
||||
>
|
||||
<div className="flex items-center gap-3 border-b border-white/8 px-4 py-3">
|
||||
<Search className="h-4 w-4 shrink-0 text-slate-500" />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
onKeyDown={onInputKey}
|
||||
placeholder="Projekt, Notiz oder Bereich…"
|
||||
className="w-full bg-transparent text-sm text-slate-100 outline-none placeholder:text-slate-600"
|
||||
/>
|
||||
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin text-slate-600" /> : null}
|
||||
</div>
|
||||
|
||||
<div ref={listRef} className="max-h-[22rem] overflow-y-auto p-1.5">
|
||||
{entries.length === 0 ? (
|
||||
<p className="px-3 py-8 text-center text-sm text-slate-500">
|
||||
{loading ? "Lade…" : "Nichts gefunden."}
|
||||
</p>
|
||||
) : (
|
||||
entries.map((entry, index) => (
|
||||
<button
|
||||
key={entry.key}
|
||||
type="button"
|
||||
data-index={index}
|
||||
onMouseMove={() => setActive(index)}
|
||||
onClick={() => go(entry)}
|
||||
className={cn(
|
||||
"flex w-full items-start gap-3 rounded-lg px-3 py-2 text-left transition-colors",
|
||||
index === active ? "bg-white/8" : "hover:bg-white/5",
|
||||
)}
|
||||
>
|
||||
{entry.kind === "action" ? (
|
||||
<>
|
||||
<entry.action.icon className="mt-0.5 h-4 w-4 shrink-0 text-slate-500" />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-sm text-slate-200">
|
||||
{entry.action.label}
|
||||
</span>
|
||||
<span className="block truncate text-[11px] text-slate-500">
|
||||
{entry.action.hint}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
) : entry.kind === "project" ? (
|
||||
<>
|
||||
<span
|
||||
className="mt-1.5 h-2 w-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: statusOf(entry.project.status).color }}
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm text-slate-200">
|
||||
{entry.project.name}
|
||||
</span>
|
||||
<span className="block truncate text-[11px] text-slate-500">
|
||||
{entry.project.summary ?? statusOf(entry.project.status).label}
|
||||
</span>
|
||||
</span>
|
||||
<span className="mt-0.5 shrink-0 text-[10px] uppercase tracking-wider text-slate-600">
|
||||
{statusOf(entry.project.status).short}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<NotebookPen className="mt-0.5 h-4 w-4 shrink-0 text-violet-300/70" />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-sm text-slate-200">
|
||||
{entry.note.title ?? "Notiz"}
|
||||
<span className="ml-1.5 text-[11px] text-slate-500">
|
||||
in {entry.projectName}
|
||||
</span>
|
||||
</span>
|
||||
<span className="block truncate text-[11px] text-slate-500">
|
||||
{entry.note.snippet.replace(/\[\[|\]\]/g, "")}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 border-t border-white/6 px-4 py-2 text-[10px] text-slate-600">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Kbd>↑</Kbd>
|
||||
<Kbd>↓</Kbd>
|
||||
waehlen
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Kbd>
|
||||
<CornerDownLeft className="h-2.5 w-2.5" />
|
||||
</Kbd>
|
||||
oeffnen
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Kbd>Esc</Kbd>
|
||||
schliessen
|
||||
</span>
|
||||
<span className="ml-auto inline-flex items-center gap-1">
|
||||
<Plus className="h-2.5 w-2.5" />
|
||||
<Kbd>Strg</Kbd>
|
||||
<Kbd>K</Kbd>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
function Kbd({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<kbd className="inline-flex min-w-[1.2rem] items-center justify-center rounded border border-white/12 bg-white/5 px-1 py-0.5 font-sans text-[10px] text-slate-400">
|
||||
{children}
|
||||
</kbd>
|
||||
);
|
||||
}
|
||||
@@ -140,8 +140,8 @@ export function ConnectionsManager({ connections }: { connections: ConnectionWit
|
||||
}
|
||||
|
||||
async function remove(connection: ConnectionWithCount) {
|
||||
const linked = connection._count?.projects ?? 0;
|
||||
const hint = linked > 0 ? `\n\n${linked} Projekt(e) verlieren die Verknuepfung.` : "";
|
||||
const linked = connection._count?.repositories ?? 0;
|
||||
const hint = linked > 0 ? `\n\n${linked} Repository(s) verlieren die Verknuepfung.` : "";
|
||||
if (!window.confirm(`Verbindung „${connection.name}“ loeschen?${hint}`)) return;
|
||||
setBusyId(connection.id);
|
||||
await fetch(`/api/connections/${connection.id}`, { method: "DELETE" }).catch(() => undefined);
|
||||
@@ -257,9 +257,9 @@ export function ConnectionsManager({ connections }: { connections: ConnectionWit
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<dt className="text-slate-500">Projekte</dt>
|
||||
<dt className="text-slate-500">Repositories</dt>
|
||||
<dd className="tabular-nums text-slate-300">
|
||||
{connection._count?.projects ?? 0}
|
||||
{connection._count?.repositories ?? 0}
|
||||
</dd>
|
||||
</div>
|
||||
{connection.lastCheckedAt ? (
|
||||
|
||||
+201
-15
@@ -12,22 +12,29 @@ import {
|
||||
GitMerge,
|
||||
GitPullRequest,
|
||||
HardDrive,
|
||||
ListPlus,
|
||||
Loader2,
|
||||
Lock,
|
||||
Package,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Star,
|
||||
Tag,
|
||||
Unlink,
|
||||
} from "lucide-react";
|
||||
import { CiBadge } from "@/components/CiBadge";
|
||||
import { RepositoryDialog } from "@/components/RepositoryDialog";
|
||||
import { Sparkline } from "@/components/Sparkline";
|
||||
import { repoTitle } from "@/lib/git/meta";
|
||||
import { asArray, asRecord } from "@/types";
|
||||
import type {
|
||||
BranchInfo,
|
||||
CommitInfo,
|
||||
ConnectionSafe,
|
||||
ProjectDetail,
|
||||
ReleaseInfo,
|
||||
RepositoryWithSnapshot,
|
||||
TagInfo,
|
||||
TicketInfo,
|
||||
} from "@/types";
|
||||
@@ -44,13 +51,56 @@ const TABS = [
|
||||
|
||||
type TabKey = (typeof TABS)[number]["key"];
|
||||
|
||||
export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
export function GitPanel({
|
||||
project,
|
||||
connections,
|
||||
}: {
|
||||
project: ProjectDetail;
|
||||
connections: ConnectionSafe[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [tab, setTab] = useState<TabKey>("pulls");
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
|
||||
const snapshot = project.snapshot;
|
||||
const repositories = project.repositories;
|
||||
const [selectedId, setSelectedId] = useState<string | null>(repositories[0]?.id ?? null);
|
||||
|
||||
// Nach dem Entfernen zeigt die Auswahl ins Leere – dann auf das fuehrende
|
||||
// zurueckfallen, statt eine leere Ansicht zu zeigen.
|
||||
const repository = repositories.find((entry) => entry.id === selectedId) ?? repositories[0] ?? null;
|
||||
|
||||
/** Offene Issues als Aufgaben anlegen – ohne erneuten Abruf beim Provider. */
|
||||
async function importIssues() {
|
||||
if (!repository) return;
|
||||
setImporting(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
const response = await fetch(`/api/projects/${project.id}/tasks/from-issues`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ repositoryId: repository.id }),
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body.error ?? "Uebernahme fehlgeschlagen.");
|
||||
setMessage({
|
||||
ok: true,
|
||||
text:
|
||||
body.created === 0
|
||||
? `Nichts Neues – alle ${body.skipped} Issues sind bereits als Aufgabe vorhanden.`
|
||||
: `${body.created} Aufgabe(n) angelegt${body.skipped ? `, ${body.skipped} uebersprungen` : ""}.`,
|
||||
});
|
||||
router.refresh();
|
||||
} catch (caught) {
|
||||
setMessage({ ok: false, text: caught instanceof Error ? caught.message : String(caught) });
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const snapshot = repository?.snapshot ?? null;
|
||||
const branches = asArray<BranchInfo>(snapshot?.branches);
|
||||
const tags = asArray<TagInfo>(snapshot?.tags);
|
||||
const commits = asArray<CommitInfo>(snapshot?.commits);
|
||||
@@ -60,13 +110,15 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
const issues = asArray<TicketInfo>(snapshot?.issues);
|
||||
const activity = asArray<number>(snapshot?.commitActivity);
|
||||
|
||||
const hasRepo = Boolean(project.repoOwner && project.repoName) || Boolean(project.repoUrl);
|
||||
|
||||
async function sync() {
|
||||
/** Ein einzelnes Repository oder – ohne Argument – alle. */
|
||||
async function sync(nurDieses?: string) {
|
||||
setSyncing(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
const response = await fetch(`/api/projects/${project.id}/sync`, { method: "POST" });
|
||||
const url = nurDieses
|
||||
? `/api/repositories/${nurDieses}/sync`
|
||||
: `/api/projects/${project.id}/sync`;
|
||||
const response = await fetch(url, { method: "POST" });
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
setMessage({ ok: response.ok, text: payload.message ?? "Unbekannte Antwort." });
|
||||
router.refresh();
|
||||
@@ -80,16 +132,41 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasRepo) {
|
||||
async function removeRepository(entry: RepositoryWithSnapshot) {
|
||||
if (
|
||||
!window.confirm(
|
||||
`„${repoTitle(entry)}“ vom Projekt loesen? Der geholte Stand geht dabei verloren.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await fetch(`/api/repositories/${entry.id}`, { method: "DELETE" }).catch(() => undefined);
|
||||
setSelectedId(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
if (!repository) {
|
||||
return (
|
||||
<>
|
||||
<div className="glass px-5 py-10 text-center">
|
||||
<GitBranch className="mx-auto h-8 w-8 text-slate-600" />
|
||||
<h3 className="mt-3 text-sm font-semibold text-slate-200">Kein Repository verknuepft</h3>
|
||||
<p className="mx-auto mt-1 max-w-sm text-sm text-slate-500">
|
||||
Hinterlege im Projekt eine Repository-URL und waehle eine Git-Verbindung, um
|
||||
Branches, Tags, Commits und Releases hier zu sehen.
|
||||
Verknuepfe ein Repository, um Branches, Tags, Commits und Releases hier zu sehen.
|
||||
Ein Projekt darf auch mehrere haben – etwa Frontend und Backend.
|
||||
</p>
|
||||
<button type="button" className="btn btn-primary mt-4" onClick={() => setAddOpen(true)}>
|
||||
<Plus className="h-4 w-4" />
|
||||
Repository verknuepfen
|
||||
</button>
|
||||
</div>
|
||||
<RepositoryDialog
|
||||
open={addOpen}
|
||||
onClose={() => setAddOpen(false)}
|
||||
projectId={project.id}
|
||||
connections={connections}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -100,12 +177,53 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Auswahl, sobald es mehr als eines gibt. Bei einem einzigen waere eine
|
||||
Leiste mit genau einem Knopf nur Ballast. */}
|
||||
{repositories.length > 1 ? (
|
||||
<div className="glass flex flex-wrap items-center gap-1.5 p-2" role="tablist">
|
||||
{repositories.map((entry) => {
|
||||
const aktiv = entry.id === repository.id;
|
||||
return (
|
||||
<button
|
||||
key={entry.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={aktiv}
|
||||
onClick={() => setSelectedId(entry.id)}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs transition-colors",
|
||||
aktiv
|
||||
? "bg-white/9 text-white"
|
||||
: "text-slate-400 hover:bg-white/5 hover:text-slate-200",
|
||||
)}
|
||||
>
|
||||
{entry.syncError ? (
|
||||
<AlertTriangle className="h-3 w-3 text-rose-300" />
|
||||
) : (
|
||||
<GitBranch className="h-3 w-3 text-slate-500" />
|
||||
)}
|
||||
{repoTitle(entry)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAddOpen(true)}
|
||||
className="ml-auto rounded-lg p-1.5 text-slate-500 transition-colors hover:bg-white/5 hover:text-violet-300"
|
||||
aria-label="Weiteres Repository verknuepfen"
|
||||
title="Weiteres Repository verknuepfen"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Kopf mit Sync */}
|
||||
<div className="glass flex flex-wrap items-center justify-between gap-3 p-4">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="truncate font-mono text-sm text-slate-100">
|
||||
{snapshot?.fullName ?? `${project.repoOwner}/${project.repoName}`}
|
||||
{snapshot?.fullName ?? repoTitle(repository)}
|
||||
</h2>
|
||||
{snapshot?.visibility ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-md bg-white/6 px-1.5 py-0.5 text-[10px] uppercase tracking-wider text-slate-400">
|
||||
@@ -131,13 +249,50 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
<CiBadge state={snapshot?.ciState} name={snapshot?.ciName} url={snapshot?.ciUrl} />
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-slate-500" suppressHydrationWarning>
|
||||
{project.lastSyncedAt
|
||||
? `Zuletzt synchronisiert ${formatRelative(project.lastSyncedAt)} · ${formatDateTime(project.lastSyncedAt)}`
|
||||
{repository.lastSyncedAt
|
||||
? `Zuletzt synchronisiert ${formatRelative(repository.lastSyncedAt)} · ${formatDateTime(repository.lastSyncedAt)}`
|
||||
: "Noch nie synchronisiert."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button type="button" className="btn btn-primary" onClick={sync} disabled={syncing}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{repositories.length > 1 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => sync()}
|
||||
disabled={syncing}
|
||||
title="Alle Repositories dieses Projekts abgleichen"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Alle
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAddOpen(true)}
|
||||
className="btn btn-ghost"
|
||||
title="Weiteres Repository verknuepfen"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Repository
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeRepository(repository)}
|
||||
className="rounded-lg p-2 text-slate-500 transition-colors hover:bg-rose-500/10 hover:text-rose-300"
|
||||
aria-label={`${repoTitle(repository)} vom Projekt loesen`}
|
||||
title="Vom Projekt loesen"
|
||||
>
|
||||
<Unlink className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => sync(repository.id)}
|
||||
disabled={syncing}
|
||||
>
|
||||
{syncing ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
@@ -146,6 +301,14 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
Jetzt synchronisieren
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<RepositoryDialog
|
||||
open={addOpen}
|
||||
onClose={() => setAddOpen(false)}
|
||||
projectId={project.id}
|
||||
connections={connections}
|
||||
/>
|
||||
|
||||
{message ? (
|
||||
<p
|
||||
@@ -160,10 +323,10 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{project.syncError && !message ? (
|
||||
{repository.syncError && !message ? (
|
||||
<p className="flex items-start gap-2 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<span>{project.syncError}</span>
|
||||
<span>{repository.syncError}</span>
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
@@ -329,7 +492,30 @@ export function GitPanel({ project }: { project: ProjectDetail }) {
|
||||
/>
|
||||
) : null}
|
||||
{tab === "issues" ? (
|
||||
<>
|
||||
{issues.length > 0 ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-white/6 bg-white/2 px-4 py-2">
|
||||
<p className="text-[11px] text-slate-500">
|
||||
Aus offenen Issues Aufgaben machen. Bereits uebernommene werden
|
||||
uebersprungen.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-2.5 py-1 text-[11px]"
|
||||
onClick={importIssues}
|
||||
disabled={importing}
|
||||
>
|
||||
{importing ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<ListPlus className="h-3 w-3" />
|
||||
)}
|
||||
Als Aufgaben uebernehmen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<TicketList tickets={issues} empty="Keine offenen Issues." icon={CircleDot} />
|
||||
</>
|
||||
) : null}
|
||||
{tab === "branches" ? <BranchList branches={branches} /> : null}
|
||||
{tab === "tags" ? <TagList tags={tags} /> : null}
|
||||
|
||||
@@ -256,11 +256,12 @@ function KanbanCard({
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-2.5 gap-y-1 text-[10px] text-slate-500">
|
||||
<CiBadge state={project.snapshot?.ciState} compact />
|
||||
{project.snapshot?.defaultBranch ? (
|
||||
{/* Auf der schmalen Kanban-Karte nur das fuehrende Repository. */}
|
||||
<CiBadge state={project.repositories[0]?.snapshot?.ciState} compact />
|
||||
{project.repositories[0]?.snapshot?.defaultBranch ? (
|
||||
<span className="inline-flex items-center gap-1 font-mono">
|
||||
<GitBranch className="h-3 w-3" />
|
||||
{project.snapshot.defaultBranch}
|
||||
{project.repositories[0].snapshot.defaultBranch}
|
||||
</span>
|
||||
) : null}
|
||||
{project._count.notes > 0 ? (
|
||||
|
||||
@@ -140,7 +140,9 @@ export function ProjectBoard({
|
||||
(project.summary ?? "").toLowerCase().includes(needle) ||
|
||||
(project.description ?? "").toLowerCase().includes(needle) ||
|
||||
project.tags.some((tag) => tag.includes(needle)) ||
|
||||
(project.snapshot?.fullName ?? "").toLowerCase().includes(needle) ||
|
||||
project.repositories.some((repo) =>
|
||||
(repo.snapshot?.fullName ?? "").toLowerCase().includes(needle),
|
||||
) ||
|
||||
// Treffer in Notizen kommen vom Server dazu.
|
||||
noteHitProjectIds.has(project.id)
|
||||
);
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { CiBadge } from "@/components/CiBadge";
|
||||
import { Sparkline } from "@/components/Sparkline";
|
||||
import { StatusSelect } from "@/components/StatusSelect";
|
||||
import { repoTitle } from "@/lib/git/meta";
|
||||
import { PRIORITY_META, accentOf } from "@/lib/status";
|
||||
import { cn, formatRelative, truncate } from "@/lib/utils";
|
||||
import { asArray, type ProjectListItem } from "@/types";
|
||||
@@ -31,7 +32,14 @@ const PROVIDER_LABEL: Record<string, string> = {
|
||||
export function ProjectCard({ project, index = 0 }: { project: ProjectListItem; index?: number }) {
|
||||
const accent = accentOf(project.accent);
|
||||
const priority = PRIORITY_META[project.priority] ?? PRIORITY_META[2];
|
||||
const snapshot = project.snapshot;
|
||||
// Auf der Karte ist nur fuer eines Platz: das fuehrende. Wie viele es
|
||||
// insgesamt sind, sagt die Zahl daneben.
|
||||
const leading = project.repositories[0] ?? null;
|
||||
const snapshot = leading?.snapshot ?? null;
|
||||
const weitere = project.repositories.length - 1;
|
||||
// Ein Fehler an irgendeinem Repo gehoert auf die Karte, nicht nur einer am
|
||||
// fuehrenden – sonst bliebe er unbemerkt.
|
||||
const syncError = project.repositories.find((repo) => repo.syncError)?.syncError ?? null;
|
||||
const activity = asArray<number>(snapshot?.commitActivity);
|
||||
const [favorite, setFavorite] = useState(project.favorite);
|
||||
|
||||
@@ -125,10 +133,20 @@ export function ProjectCard({ project, index = 0 }: { project: ProjectListItem;
|
||||
<div className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-2 text-[11px] text-slate-400">
|
||||
<CiBadge state={snapshot?.ciState} name={snapshot?.ciName} compact />
|
||||
|
||||
{project.connection ? (
|
||||
{leading?.connection ? (
|
||||
<span className="glass-soft inline-flex items-center gap-1.5 px-2 py-1">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-violet-400" aria-hidden="true" />
|
||||
{PROVIDER_LABEL[project.connection.provider] ?? project.connection.provider}
|
||||
{PROVIDER_LABEL[leading.connection.provider] ?? leading.connection.provider}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{weitere > 0 ? (
|
||||
<span
|
||||
className="inline-flex items-center gap-1.5"
|
||||
title={project.repositories.map((repo) => repoTitle(repo)).join(", ")}
|
||||
>
|
||||
<GitBranch className="h-3.5 w-3.5 text-slate-500" />+{weitere} Repo
|
||||
{weitere === 1 ? "" : "s"}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
@@ -173,11 +191,8 @@ export function ProjectCard({ project, index = 0 }: { project: ProjectListItem;
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{project.syncError ? (
|
||||
<span
|
||||
className="inline-flex items-center gap-1.5 text-rose-300/80"
|
||||
title={project.syncError}
|
||||
>
|
||||
{syncError ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-rose-300/80" title={syncError}>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
Sync-Fehler
|
||||
</span>
|
||||
|
||||
@@ -87,11 +87,14 @@ export function ProjectDialog({ open, onClose, connections, project }: ProjectDi
|
||||
accent: project.accent,
|
||||
tags: project.tags.join(", "),
|
||||
favorite: project.favorite,
|
||||
connectionId: project.connectionId ?? "",
|
||||
repoUrl: project.repoUrl ?? "",
|
||||
repoOwner: project.repoOwner ?? "",
|
||||
repoName: project.repoName ?? "",
|
||||
autoSync: project.autoSync,
|
||||
// Der Dialog bearbeitet das fuehrende Repository. Weitere
|
||||
// verwaltet das Git-Panel – hier wuerde eine Liste den Dialog
|
||||
// sprengen, in dem es eigentlich um das Projekt geht.
|
||||
connectionId: project.repositories[0]?.connectionId ?? "",
|
||||
repoUrl: project.repositories[0]?.repoUrl ?? "",
|
||||
repoOwner: project.repositories[0]?.repoOwner ?? "",
|
||||
repoName: project.repositories[0]?.repoName ?? "",
|
||||
autoSync: project.repositories[0]?.autoSync ?? true,
|
||||
progressFromTasks: project.progressFromTasks,
|
||||
}
|
||||
: EMPTY,
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { ProjectDialog } from "@/components/ProjectDialog";
|
||||
import { StatusSelect } from "@/components/StatusSelect";
|
||||
import { Popover } from "@/components/ui/Popover";
|
||||
import { repoTitle } from "@/lib/git/meta";
|
||||
import { PRIORITY_META, accentOf } from "@/lib/status";
|
||||
import { cn, formatDate } from "@/lib/utils";
|
||||
import type { ConnectionSafe, ProjectDetail } from "@/types";
|
||||
@@ -132,24 +133,22 @@ export function ProjectHeader({
|
||||
angelegt {formatDate(project.createdAt)}
|
||||
</span>
|
||||
<span style={{ color: priority.color }}>Prioritaet: {priority.label}</span>
|
||||
{project.connection ? (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{project.connection.name}
|
||||
<span className="text-slate-700">·</span>
|
||||
{project.connection.provider}
|
||||
</span>
|
||||
) : null}
|
||||
{project.repoUrl ? (
|
||||
{/* Alle Repositories verlinken – bei einem einzigen sieht das aus
|
||||
wie vorher, bei mehreren steht jedes fuer sich. */}
|
||||
{project.repositories
|
||||
.filter((repository) => repository.repoUrl)
|
||||
.map((repository) => (
|
||||
<a
|
||||
href={project.repoUrl}
|
||||
key={repository.id}
|
||||
href={repository.repoUrl!}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="inline-flex items-center gap-1.5 text-violet-300 transition-colors hover:text-violet-200"
|
||||
>
|
||||
Repository
|
||||
{project.repositories.length === 1 ? "Repository" : repoTitle(repository)}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
) : null}
|
||||
))}
|
||||
</div>
|
||||
|
||||
{project.tags.length > 0 ? (
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, RefreshCw, Search } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
import type { ConnectionSafe, RepoListEntry, RepositoryWithSnapshot } from "@/types";
|
||||
|
||||
/**
|
||||
* Ein weiteres Repository mit einem Projekt verknuepfen – oder ein
|
||||
* vorhandenes umbenennen und umhaengen.
|
||||
*
|
||||
* Beim Anlegen des Projekts genuegt der Projektdialog: dort setzen die
|
||||
* Git-Felder das erste Repository. Alles darueber hinaus laeuft hier.
|
||||
*/
|
||||
|
||||
interface FormState {
|
||||
label: string;
|
||||
connectionId: string;
|
||||
repoUrl: string;
|
||||
repoOwner: string;
|
||||
repoName: string;
|
||||
autoSync: boolean;
|
||||
}
|
||||
|
||||
const EMPTY: FormState = {
|
||||
label: "",
|
||||
connectionId: "",
|
||||
repoUrl: "",
|
||||
repoOwner: "",
|
||||
repoName: "",
|
||||
autoSync: true,
|
||||
};
|
||||
|
||||
export function RepositoryDialog({
|
||||
open,
|
||||
onClose,
|
||||
projectId,
|
||||
connections,
|
||||
repository,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
projectId: string;
|
||||
connections: ConnectionSafe[];
|
||||
/** Vorhandenes = Bearbeiten, sonst Verknuepfen. */
|
||||
repository?: RepositoryWithSnapshot | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [form, setForm] = useState<FormState>(EMPTY);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [repos, setRepos] = useState<RepoListEntry[]>([]);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [filter, setFilter] = useState("");
|
||||
|
||||
const isEdit = Boolean(repository);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
setPickerOpen(false);
|
||||
setRepos([]);
|
||||
setFilter("");
|
||||
setForm(
|
||||
repository
|
||||
? {
|
||||
label: repository.label ?? "",
|
||||
connectionId: repository.connectionId ?? "",
|
||||
repoUrl: repository.repoUrl ?? "",
|
||||
repoOwner: repository.repoOwner ?? "",
|
||||
repoName: repository.repoName ?? "",
|
||||
autoSync: repository.autoSync,
|
||||
}
|
||||
: EMPTY,
|
||||
);
|
||||
}, [open, repository]);
|
||||
|
||||
const gefiltert = useMemo(() => {
|
||||
const needle = filter.toLowerCase().trim();
|
||||
if (!needle) return repos.slice(0, 60);
|
||||
return repos.filter((repo) => repo.fullPath.toLowerCase().includes(needle)).slice(0, 60);
|
||||
}, [repos, filter]);
|
||||
|
||||
function update<K extends keyof FormState>(key: K, value: FormState[K]) {
|
||||
setForm((previous) => ({ ...previous, [key]: value }));
|
||||
}
|
||||
|
||||
async function loadRepos() {
|
||||
if (!form.connectionId) {
|
||||
setError("Bitte zuerst eine Git-Verbindung auswaehlen.");
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/connections/${form.connectionId}/repos`);
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error ?? "Repos konnten nicht geladen werden.");
|
||||
setRepos(payload.repos ?? []);
|
||||
setPickerOpen(true);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function pick(repo: RepoListEntry) {
|
||||
setForm((previous) => ({
|
||||
...previous,
|
||||
repoUrl: repo.htmlUrl,
|
||||
repoOwner: repo.owner,
|
||||
repoName: repo.name,
|
||||
}));
|
||||
setPickerOpen(false);
|
||||
}
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(
|
||||
isEdit ? `/api/repositories/${repository?.id}` : `/api/projects/${projectId}/repositories`,
|
||||
{
|
||||
method: isEdit ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
label: form.label,
|
||||
connectionId: form.connectionId || null,
|
||||
repoUrl: form.repoUrl,
|
||||
repoOwner: form.repoOwner,
|
||||
repoName: form.repoName,
|
||||
autoSync: form.autoSync,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(payload.error ?? "Speichern fehlgeschlagen.");
|
||||
onClose();
|
||||
router.refresh();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
width="lg"
|
||||
title={isEdit ? "Repository bearbeiten" : "Repository verknuepfen"}
|
||||
description={
|
||||
isEdit
|
||||
? "Zeigt das Repository woandershin, wird der geholte Stand verworfen."
|
||||
: "Ein Projekt darf mehrere Repositories haben – etwa Frontend und Backend."
|
||||
}
|
||||
>
|
||||
<form onSubmit={submit} className="space-y-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="field-label" htmlFor="repo-label">
|
||||
Bezeichnung (optional)
|
||||
</label>
|
||||
<input
|
||||
id="repo-label"
|
||||
className="field"
|
||||
value={form.label}
|
||||
onChange={(event) => update("label", event.target.value)}
|
||||
placeholder="Frontend"
|
||||
maxLength={80}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
Ohne Angabe steht schlicht owner/name da.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="repo-connection">
|
||||
Verbindung
|
||||
</label>
|
||||
<select
|
||||
id="repo-connection"
|
||||
className="field"
|
||||
value={form.connectionId}
|
||||
onChange={(event) => update("connectionId", event.target.value)}
|
||||
>
|
||||
<option value="">– keine –</option>
|
||||
{connections.map((connection) => (
|
||||
<option key={connection.id} value={connection.id}>
|
||||
{connection.name} ({connection.provider})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost w-full"
|
||||
onClick={loadRepos}
|
||||
disabled={loading || !form.connectionId}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
)}
|
||||
Repos laden
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-2">
|
||||
<label className="field-label" htmlFor="repo-url">
|
||||
Repository-URL
|
||||
</label>
|
||||
<input
|
||||
id="repo-url"
|
||||
className="field"
|
||||
value={form.repoUrl}
|
||||
onChange={(event) => update("repoUrl", event.target.value)}
|
||||
placeholder="https://github.com/user/repo"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="repo-owner">
|
||||
Owner / Gruppe
|
||||
</label>
|
||||
<input
|
||||
id="repo-owner"
|
||||
className="field font-mono text-xs"
|
||||
value={form.repoOwner}
|
||||
onChange={(event) => update("repoOwner", event.target.value)}
|
||||
placeholder="wird aus der URL abgeleitet"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="repo-name">
|
||||
Repository
|
||||
</label>
|
||||
<input
|
||||
id="repo-name"
|
||||
className="field font-mono text-xs"
|
||||
value={form.repoName}
|
||||
onChange={(event) => update("repoName", event.target.value)}
|
||||
placeholder="wird aus der URL abgeleitet"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2.5 text-sm text-slate-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.autoSync}
|
||||
onChange={(event) => update("autoSync", event.target.checked)}
|
||||
className="mt-0.5 h-4 w-4 accent-violet-500"
|
||||
/>
|
||||
<span>
|
||||
Am automatischen Abgleich teilnehmen
|
||||
<span className="mt-0.5 block text-[11px] text-slate-600">
|
||||
Wirkt nur, wenn der Abgleich im Adminbereich eingeschaltet ist. Manuell
|
||||
synchronisieren geht unabhaengig davon immer.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{pickerOpen ? (
|
||||
<div className="rounded-xl border border-white/8 bg-[#080a18]/70">
|
||||
<div className="flex items-center gap-2 border-b border-white/6 px-3 py-2">
|
||||
<Search className="h-3.5 w-3.5 text-slate-500" />
|
||||
<input
|
||||
className="w-full bg-transparent text-sm text-slate-200 outline-none placeholder:text-slate-600"
|
||||
placeholder={`${repos.length} Repositories durchsuchen…`}
|
||||
value={filter}
|
||||
onChange={(event) => setFilter(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ul className="max-h-56 overflow-y-auto p-1">
|
||||
{gefiltert.map((repo) => (
|
||||
<li key={repo.fullPath}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => pick(repo)}
|
||||
className="flex w-full items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left hover:bg-white/6"
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate font-mono text-xs text-slate-200">
|
||||
{repo.fullPath}
|
||||
</span>
|
||||
{repo.description ? (
|
||||
<span className="block truncate text-[11px] text-slate-500">
|
||||
{repo.description}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="shrink-0 text-[10px] uppercase text-slate-600">
|
||||
{repo.visibility}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{gefiltert.length === 0 ? (
|
||||
<li className="px-3 py-4 text-center text-xs text-slate-500">Keine Treffer.</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<p className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-end gap-3 pt-1">
|
||||
<button type="button" className="btn btn-ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary" disabled={saving}>
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||
{isEdit ? "Speichern" : "Verknuepfen"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -108,6 +108,9 @@ function UserMenu({ user }: { user: SessionUser }) {
|
||||
className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/4 py-1.5 pl-1.5 pr-3 text-sm text-slate-200 transition-colors hover:bg-white/8"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
// Auf schmalen Anzeigen bleibt nur das Kuerzel sichtbar – ohne
|
||||
// Beschriftung liest ein Screenreader dann nur zwei Buchstaben vor.
|
||||
aria-label={`Benutzermenue fuer ${label}`}
|
||||
>
|
||||
<span className="grid h-7 w-7 place-items-center rounded-lg bg-gradient-to-br from-violet-500/80 to-cyan-400/70 text-[11px] font-semibold text-white">
|
||||
{initials}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { TotpSection, type TotpState } from "@/components/account/TotpSection";
|
||||
import { PASSWORD_MIN_LENGTH } from "@/lib/auth/constants";
|
||||
import { cn, formatDateTime, formatRelative } from "@/lib/utils";
|
||||
|
||||
@@ -43,6 +44,7 @@ export interface AccountData {
|
||||
passkeys: PasskeyEntry[];
|
||||
sessions: SessionEntry[];
|
||||
passkeysAvailable: boolean;
|
||||
totp: TotpState;
|
||||
}
|
||||
|
||||
type Notice = { ok: boolean; text: string } | null;
|
||||
@@ -52,6 +54,7 @@ export function AccountManager({ data }: { data: AccountData }) {
|
||||
<div className="space-y-6">
|
||||
<ProfileSection data={data} />
|
||||
<PasswordSection hasPassword={data.hasPassword} />
|
||||
<TotpSection state={data.totp} hasPassword={data.hasPassword} />
|
||||
<PasskeySection passkeys={data.passkeys} available={data.passkeysAvailable} />
|
||||
<SessionSection sessions={data.sessions} />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Bell,
|
||||
BellRing,
|
||||
CheckCircle2,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
Mail,
|
||||
Pencil,
|
||||
Plus,
|
||||
Trash2,
|
||||
Webhook,
|
||||
XCircle,
|
||||
} from "lucide-react";
|
||||
import type { NotificationChannel, NotificationEvent } from "@prisma/client";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
import { EVENT_META, NOTIFICATION_EVENTS } from "@/lib/notify/types";
|
||||
import { cn, formatRelative } from "@/lib/utils";
|
||||
|
||||
export interface NotificationTargetEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
channel: NotificationChannel;
|
||||
target: string;
|
||||
secretHint: string | null;
|
||||
events: NotificationEvent[];
|
||||
isActive: boolean;
|
||||
lastSentAt: string | Date | null;
|
||||
lastOk: boolean | null;
|
||||
lastMessage: string | null;
|
||||
}
|
||||
|
||||
const CHANNEL_META: Record<
|
||||
NotificationChannel,
|
||||
{ label: string; icon: typeof Webhook; hint: string; placeholder: string }
|
||||
> = {
|
||||
NTFY: {
|
||||
label: "ntfy",
|
||||
icon: BellRing,
|
||||
hint: "Vollstaendige Themen-URL, z. B. https://ntfy.sh/mein-geheimes-thema",
|
||||
placeholder: "https://ntfy.sh/mein-thema",
|
||||
},
|
||||
WEBHOOK: {
|
||||
label: "Webhook",
|
||||
icon: Webhook,
|
||||
hint: "Bekommt JSON per POST. Mit Geheimnis wird der Rumpf signiert (X-Nebula-Signature).",
|
||||
placeholder: "https://mein-dienst.de/haken",
|
||||
},
|
||||
EMAIL: {
|
||||
label: "E-Mail",
|
||||
icon: Mail,
|
||||
hint: "Braucht SMTP-Zugangsdaten in der .env der Instanz.",
|
||||
placeholder: "ich@example.com",
|
||||
},
|
||||
};
|
||||
|
||||
export function NotificationSection({
|
||||
targets,
|
||||
emailAvailable,
|
||||
}: {
|
||||
targets: NotificationTargetEntry[];
|
||||
emailAvailable: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<NotificationTargetEntry | null>(null);
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
|
||||
async function test(entry: NotificationTargetEntry) {
|
||||
setBusyId(entry.id);
|
||||
setNotice(null);
|
||||
try {
|
||||
const response = await fetch(`/api/notifications/${entry.id}/test`, { method: "POST" });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
setNotice({ ok: response.ok, text: body.message ?? body.error ?? "Unbekannte Antwort." });
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(entry: NotificationTargetEntry) {
|
||||
if (!window.confirm(`Ziel „${entry.name}“ entfernen?`)) return;
|
||||
setBusyId(entry.id);
|
||||
await fetch(`/api/notifications/${entry.id}`, { method: "DELETE" }).catch(() => undefined);
|
||||
setBusyId(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function toggle(entry: NotificationTargetEntry) {
|
||||
setBusyId(entry.id);
|
||||
await fetch(`/api/notifications/${entry.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ isActive: !entry.isActive }),
|
||||
}).catch(() => undefined);
|
||||
setBusyId(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="glass p-5">
|
||||
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-violet-500/12 text-violet-300">
|
||||
<Bell className="h-4 w-4" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wider text-slate-200">
|
||||
Benachrichtigungen
|
||||
</h2>
|
||||
<p className="mt-1 max-w-xl text-sm text-slate-400">
|
||||
Meldung bei fehlgeschlagenem Abgleich, roter CI oder neuem Release. Gemeldet
|
||||
wird nur bei einer <strong className="text-slate-300">Aenderung</strong> –
|
||||
nicht bei jedem Durchlauf.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-3 py-1.5 text-xs"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
Ziel hinzufuegen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{targets.length === 0 ? (
|
||||
<p className="rounded-xl border border-dashed border-white/8 px-4 py-6 text-center text-sm text-slate-500">
|
||||
Noch kein Ziel eingerichtet.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{targets.map((entry) => {
|
||||
const meta = CHANNEL_META[entry.channel];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<div key={entry.id} className="glass-soft px-3 py-3">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="flex flex-wrap items-center gap-2 text-sm text-slate-100">
|
||||
<Icon className="h-3.5 w-3.5 shrink-0 text-violet-300" />
|
||||
{entry.name}
|
||||
<span className="rounded bg-white/6 px-1.5 py-0.5 text-[10px] uppercase tracking-wider text-slate-400">
|
||||
{meta.label}
|
||||
</span>
|
||||
{!entry.isActive ? (
|
||||
<span className="rounded bg-slate-500/15 px-1.5 py-0.5 text-[10px] text-slate-400">
|
||||
pausiert
|
||||
</span>
|
||||
) : null}
|
||||
{entry.secretHint ? (
|
||||
<span className="inline-flex items-center gap-1 font-mono text-[10px] text-amber-300/70">
|
||||
<KeyRound className="h-2.5 w-2.5" />
|
||||
{entry.secretHint}
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p className="mt-0.5 truncate font-mono text-[11px] text-slate-500">
|
||||
{entry.target}
|
||||
</p>
|
||||
<p className="mt-1.5 flex flex-wrap gap-1">
|
||||
{entry.events.map((event) => (
|
||||
<span
|
||||
key={event}
|
||||
className="rounded bg-white/6 px-1.5 py-0.5 text-[10px] text-slate-400"
|
||||
>
|
||||
{EVENT_META[event].emoji} {EVENT_META[event].label}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
{entry.lastSentAt ? (
|
||||
<p
|
||||
className={cn(
|
||||
"mt-1.5 flex items-center gap-1.5 text-[11px]",
|
||||
entry.lastOk ? "text-emerald-200/80" : "text-rose-200/80",
|
||||
)}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{entry.lastOk ? (
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
) : (
|
||||
<XCircle className="h-3 w-3" />
|
||||
)}
|
||||
{formatRelative(entry.lastSentAt)} · {entry.lastMessage}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
{busyId === entry.id ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-slate-500" />
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-2.5 py-1.5 text-xs"
|
||||
onClick={() => test(entry)}
|
||||
>
|
||||
Testen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-2.5 py-1.5 text-xs"
|
||||
onClick={() => toggle(entry)}
|
||||
title={entry.isActive ? "Pausieren" : "Fortsetzen"}
|
||||
>
|
||||
{entry.isActive ? "Pause" : "An"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-lg p-1.5 text-slate-500 transition-colors hover:bg-white/8 hover:text-violet-300"
|
||||
onClick={() => {
|
||||
setEditing(entry);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
aria-label="Bearbeiten"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-lg p-1.5 text-slate-500 transition-colors hover:bg-rose-500/12 hover:text-rose-300"
|
||||
onClick={() => remove(entry)}
|
||||
aria-label="Entfernen"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notice ? (
|
||||
<p
|
||||
className={cn(
|
||||
"mt-3 rounded-lg border px-3 py-2 text-sm",
|
||||
notice.ok
|
||||
? "border-emerald-500/30 bg-emerald-500/10 text-emerald-200"
|
||||
: "border-rose-500/30 bg-rose-500/10 text-rose-200",
|
||||
)}
|
||||
>
|
||||
{notice.text}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!emailAvailable ? (
|
||||
<p className="mt-3 text-[11px] text-slate-600">
|
||||
E-Mail steht nicht bereit: In der <code className="text-violet-300">.env</code> der
|
||||
Instanz fehlt <code className="text-violet-300">SMTP_HOST</code>. ntfy und Webhook
|
||||
funktionieren ohne weitere Einrichtung.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<TargetDialog
|
||||
open={dialogOpen}
|
||||
entry={editing}
|
||||
emailAvailable={emailAvailable}
|
||||
onClose={() => {
|
||||
setDialogOpen(false);
|
||||
setEditing(null);
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function TargetDialog({
|
||||
open,
|
||||
entry,
|
||||
emailAvailable,
|
||||
onClose,
|
||||
}: {
|
||||
open: boolean;
|
||||
entry: NotificationTargetEntry | null;
|
||||
emailAvailable: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [channel, setChannel] = useState<NotificationChannel>("NTFY");
|
||||
const [target, setTarget] = useState("");
|
||||
const [secret, setSecret] = useState("");
|
||||
const [events, setEvents] = useState<NotificationEvent[]>(["SYNC_FAILED", "CI_FAILED"]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
|
||||
const isEdit = Boolean(entry);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setName(entry?.name ?? "");
|
||||
setChannel(entry?.channel ?? "NTFY");
|
||||
setTarget(entry?.target ?? "");
|
||||
setSecret("");
|
||||
setEvents(entry?.events ?? ["SYNC_FAILED", "CI_FAILED"]);
|
||||
setError(null);
|
||||
setFieldErrors({});
|
||||
}, [open, entry]);
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setFieldErrors({});
|
||||
|
||||
const body: Record<string, unknown> = { name, target, events };
|
||||
if (!isEdit) body.channel = channel;
|
||||
if (!isEdit || secret.trim()) body.secret = secret;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
isEdit ? `/api/notifications/${entry?.id}` : "/api/notifications",
|
||||
{
|
||||
method: isEdit ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
setFieldErrors(payload.fields ?? {});
|
||||
throw new Error(payload.error ?? "Speichern fehlgeschlagen.");
|
||||
}
|
||||
onClose();
|
||||
router.refresh();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const meta = CHANNEL_META[channel];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
width="md"
|
||||
title={isEdit ? "Ziel bearbeiten" : "Neues Benachrichtigungsziel"}
|
||||
description={
|
||||
isEdit ? "Der Zustellweg selbst laesst sich nicht mehr aendern." : undefined
|
||||
}
|
||||
>
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
{!isEdit ? (
|
||||
<div>
|
||||
<span className="field-label">Weg</span>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{(Object.keys(CHANNEL_META) as NotificationChannel[]).map((value) => {
|
||||
const option = CHANNEL_META[value];
|
||||
const Icon = option.icon;
|
||||
const disabled = value === "EMAIL" && !emailAvailable;
|
||||
return (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => setChannel(value)}
|
||||
title={disabled ? "Kein SMTP in der .env hinterlegt" : undefined}
|
||||
className={cn(
|
||||
"rounded-xl border px-3 py-2.5 text-sm transition-all disabled:opacity-40",
|
||||
channel === value
|
||||
? "border-violet-400/60 bg-violet-500/12 text-white"
|
||||
: "border-white/9 text-slate-400 hover:border-white/20",
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center justify-center gap-1.5">
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
{option.label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="notify-name">
|
||||
Name *
|
||||
</label>
|
||||
<input
|
||||
id="notify-name"
|
||||
className="field"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Handy"
|
||||
required
|
||||
maxLength={60}
|
||||
/>
|
||||
{fieldErrors.name ? (
|
||||
<p className="mt-1 text-xs text-rose-300">{fieldErrors.name}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="notify-target">
|
||||
{channel === "EMAIL" ? "E-Mail-Adresse *" : "URL *"}
|
||||
</label>
|
||||
<input
|
||||
id="notify-target"
|
||||
className="field font-mono text-xs"
|
||||
value={target}
|
||||
onChange={(e) => setTarget(e.target.value)}
|
||||
placeholder={meta.placeholder}
|
||||
required
|
||||
/>
|
||||
<p className="mt-1 text-[11px] text-slate-500">{meta.hint}</p>
|
||||
{fieldErrors.target ? (
|
||||
<p className="mt-1 text-xs text-rose-300">{fieldErrors.target}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{channel !== "EMAIL" ? (
|
||||
<div>
|
||||
<label className="field-label" htmlFor="notify-secret">
|
||||
Geheimnis {isEdit ? "(leer = unveraendert)" : "(optional)"}
|
||||
</label>
|
||||
<input
|
||||
id="notify-secret"
|
||||
className="field font-mono text-xs"
|
||||
type="password"
|
||||
value={secret}
|
||||
onChange={(e) => setSecret(e.target.value)}
|
||||
autoComplete="off"
|
||||
placeholder={isEdit ? "••••••••" : ""}
|
||||
/>
|
||||
<p className="mt-1 text-[11px] text-slate-500">
|
||||
{channel === "NTFY"
|
||||
? "Wird als Bearer-Token gesendet – fuer geschuetzte Themen."
|
||||
: "Signiert den Rumpf per HMAC-SHA256 im Kopf X-Nebula-Signature."}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<span className="field-label">Anlaesse *</span>
|
||||
<div className="space-y-1.5">
|
||||
{NOTIFICATION_EVENTS.map((event) => {
|
||||
const option = EVENT_META[event];
|
||||
const checked = events.includes(event);
|
||||
return (
|
||||
<label
|
||||
key={event}
|
||||
className="flex cursor-pointer items-start gap-2.5 rounded-lg border border-white/8 bg-black/20 px-3 py-2"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(e) =>
|
||||
setEvents((current) =>
|
||||
e.target.checked
|
||||
? [...current, event]
|
||||
: current.filter((value) => value !== event),
|
||||
)
|
||||
}
|
||||
className="mt-0.5 h-4 w-4 accent-violet-500"
|
||||
/>
|
||||
<span>
|
||||
<span className="block text-sm text-slate-200">
|
||||
{option.emoji} {option.label}
|
||||
</span>
|
||||
<span className="mt-0.5 block text-[11px] text-slate-500">
|
||||
{option.description}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{fieldErrors.events ? (
|
||||
<p className="mt-1 text-xs text-rose-300">{fieldErrors.events}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<button type="button" className="btn btn-ghost" onClick={onClose} disabled={busy}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={busy || events.length === 0}
|
||||
>
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||
Speichern
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Check,
|
||||
Copy,
|
||||
Download,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
ShieldOff,
|
||||
Smartphone,
|
||||
} from "lucide-react";
|
||||
import { cn, formatDateTime } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Zwei-Faktor-Anmeldung per Einmalkennwort.
|
||||
*
|
||||
* Die Einrichtung ist bewusst zweistufig: erst der QR-Code, dann ein Code zur
|
||||
* Bestaetigung. Scharf wird der Schluessel erst danach – sonst waere jemand,
|
||||
* der den QR-Code nicht scannen konnte, beim naechsten Anmelden ausgesperrt.
|
||||
*/
|
||||
|
||||
export interface TotpState {
|
||||
enabled: boolean;
|
||||
enabledAt: string | Date | null;
|
||||
recoveryCodesLeft: number;
|
||||
}
|
||||
|
||||
type Notice = { ok: boolean; text: string } | null;
|
||||
|
||||
export function TotpSection({
|
||||
state,
|
||||
hasPassword,
|
||||
}: {
|
||||
state: TotpState;
|
||||
hasPassword: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
|
||||
// Einrichtung
|
||||
const [setup, setSetup] = useState<{ qr: string; secret: string } | null>(null);
|
||||
const [code, setCode] = useState("");
|
||||
|
||||
// Wird genau einmal angezeigt, direkt nach dem Erzeugen.
|
||||
const [codes, setCodes] = useState<string[] | null>(null);
|
||||
|
||||
// Abschalten und Neuerzeugen verlangen beides das Passwort.
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirming, setConfirming] = useState<"disable" | "recovery" | null>(null);
|
||||
|
||||
async function call(url: string, method: string, body?: unknown) {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(payload.error ?? "Das hat nicht geklappt.");
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function start() {
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
const payload = await call("/api/account/totp", "POST");
|
||||
setSetup({ qr: payload.qr, secret: payload.secret });
|
||||
} catch (caught) {
|
||||
setNotice({ ok: false, text: caught instanceof Error ? caught.message : String(caught) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirm(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
const payload = await call("/api/account/totp", "PUT", { code });
|
||||
setSetup(null);
|
||||
setCode("");
|
||||
setCodes(payload.recoveryCodes);
|
||||
router.refresh();
|
||||
} catch (caught) {
|
||||
setNotice({ ok: false, text: caught instanceof Error ? caught.message : String(caught) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitPassword(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
if (confirming === "disable") {
|
||||
await call("/api/account/totp", "DELETE", { password });
|
||||
setNotice({ ok: true, text: "Die Zwei-Faktor-Anmeldung ist abgeschaltet." });
|
||||
setCodes(null);
|
||||
} else {
|
||||
const payload = await call("/api/account/totp/recovery", "POST", { password });
|
||||
setCodes(payload.recoveryCodes);
|
||||
setNotice({ ok: true, text: "Neue Codes erzeugt. Die alten gelten nicht mehr." });
|
||||
}
|
||||
setConfirming(null);
|
||||
setPassword("");
|
||||
router.refresh();
|
||||
} catch (caught) {
|
||||
setNotice({ ok: false, text: caught instanceof Error ? caught.message : String(caught) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="glass p-5">
|
||||
<div className="mb-4 flex items-start gap-3">
|
||||
<span
|
||||
className={cn(
|
||||
"grid h-9 w-9 shrink-0 place-items-center rounded-xl",
|
||||
state.enabled
|
||||
? "bg-emerald-500/12 text-emerald-300"
|
||||
: "bg-violet-500/12 text-violet-300",
|
||||
)}
|
||||
>
|
||||
<ShieldCheck className="h-4 w-4" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wider text-slate-200">
|
||||
Zwei-Faktor-Anmeldung
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-slate-400">
|
||||
{state.enabled
|
||||
? `Aktiv seit ${formatDateTime(state.enabledAt)}. Nach dem Passwort fragt die Anmeldung nach einem Code.`
|
||||
: "Ein zeitbasiertes Einmalkennwort zusätzlich zum Passwort — aus einer Authenticator-App."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hasPassword ? (
|
||||
<p className="rounded-lg border border-white/8 bg-black/25 px-3 py-2 text-sm text-slate-400">
|
||||
Dieses Konto hat kein Passwort und meldet sich per Passkey an. Ein zweiter Faktor
|
||||
käme dabei nie zum Einsatz — der Passkey ist bereits an dein Gerät gebunden.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{/* Frisch erzeugte Wiederherstellungscodes, einmalige Anzeige. */}
|
||||
{codes ? <RecoveryCodes codes={codes} onDone={() => setCodes(null)} /> : null}
|
||||
|
||||
{hasPassword && !state.enabled && !setup && !codes ? (
|
||||
<button type="button" onClick={start} disabled={busy} className="btn btn-primary">
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Smartphone className="h-4 w-4" />}
|
||||
Einrichten
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{/* Schritt 1: QR-Code scannen, Schritt 2: Code bestaetigen. */}
|
||||
{setup ? (
|
||||
<form onSubmit={confirm} className="space-y-4">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-start">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- data-URI, kein Netzabruf */}
|
||||
<img
|
||||
src={setup.qr}
|
||||
alt="QR-Code für die Authenticator-App"
|
||||
width={160}
|
||||
height={160}
|
||||
className="shrink-0 rounded-xl bg-white p-2"
|
||||
/>
|
||||
<div className="min-w-0 space-y-2 text-sm text-slate-400">
|
||||
<p>
|
||||
Scanne den Code mit deiner Authenticator-App — etwa Aegis, 2FAS, Ente Auth
|
||||
oder dem Passwortmanager deiner Wahl.
|
||||
</p>
|
||||
<p>Geht die Kamera nicht, trage den Schlüssel von Hand ein:</p>
|
||||
<code className="block break-all rounded-lg border border-white/8 bg-black/30 px-3 py-2 font-mono text-xs text-violet-200">
|
||||
{setup.secret}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-xs">
|
||||
<label className="field-label" htmlFor="totp-code">
|
||||
Code aus der App
|
||||
</label>
|
||||
<input
|
||||
id="totp-code"
|
||||
className="field text-center text-lg tracking-[0.35em]"
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={7}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy}>
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
|
||||
Aktivieren
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => {
|
||||
setSetup(null);
|
||||
setCode("");
|
||||
setNotice(null);
|
||||
}}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{state.enabled && !setup ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-slate-400">
|
||||
{state.recoveryCodesLeft > 0 ? (
|
||||
<>
|
||||
Noch <strong className="text-slate-200">{state.recoveryCodesLeft}</strong>{" "}
|
||||
Wiederherstellungscodes übrig.
|
||||
</>
|
||||
) : (
|
||||
<span className="text-amber-200">
|
||||
Keine Wiederherstellungscodes mehr übrig. Ohne sie hilft bei einem verlorenen
|
||||
Gerät nichts mehr — bitte neue erzeugen.
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
{confirming ? (
|
||||
<form onSubmit={submitPassword} className="max-w-sm space-y-3">
|
||||
<div>
|
||||
<label className="field-label" htmlFor="totp-password">
|
||||
Passwort bestätigen
|
||||
</label>
|
||||
<input
|
||||
id="totp-password"
|
||||
className="field"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
className={cn("btn", confirming === "disable" ? "btn-danger" : "btn-primary")}
|
||||
disabled={busy}
|
||||
>
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||
{confirming === "disable" ? "Abschalten" : "Neue Codes erzeugen"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => {
|
||||
setConfirming(null);
|
||||
setPassword("");
|
||||
}}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => setConfirming("recovery")}
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Neue Wiederherstellungscodes
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost text-rose-200"
|
||||
onClick={() => setConfirming("disable")}
|
||||
>
|
||||
<ShieldOff className="h-4 w-4" />
|
||||
Abschalten
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{notice ? (
|
||||
<p
|
||||
className={cn(
|
||||
"mt-3 rounded-lg border px-3 py-2 text-sm",
|
||||
notice.ok
|
||||
? "border-emerald-500/30 bg-emerald-500/10 text-emerald-200"
|
||||
: "border-rose-500/30 bg-rose-500/10 text-rose-200",
|
||||
)}
|
||||
>
|
||||
{notice.text}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Codes werden nur dieses eine Mal gezeigt. Deshalb Kopieren und
|
||||
* Herunterladen direkt daneben – und ein Knopf, der das Wegklicken zu einer
|
||||
* bewussten Handlung macht.
|
||||
*/
|
||||
function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const text = codes.join("\n");
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
// Ohne Zwischenablage-Recht bleibt Markieren von Hand.
|
||||
}
|
||||
}
|
||||
|
||||
function download() {
|
||||
const url = URL.createObjectURL(new Blob([`${text}\n`], { type: "text/plain" }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "nebula-wiederherstellungscodes.txt";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-4 rounded-xl border border-amber-500/30 bg-amber-500/8 p-4">
|
||||
<h3 className="text-sm font-semibold text-amber-100">Wiederherstellungscodes</h3>
|
||||
<p className="mt-1 text-sm text-amber-200/80">
|
||||
Jeder Code gilt einmal. Bewahre sie an einem sicheren Ort auf — sie sind der einzige
|
||||
Weg zurück, wenn dein Gerät verloren geht. <strong>Sie werden nur jetzt angezeigt.</strong>
|
||||
</p>
|
||||
|
||||
<ul className="mt-3 grid grid-cols-2 gap-1.5 font-mono text-sm text-amber-50 sm:grid-cols-2">
|
||||
{codes.map((entry) => (
|
||||
<li key={entry} className="rounded-md bg-black/25 px-2.5 py-1.5">
|
||||
{entry}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" onClick={copy} className="btn btn-ghost text-xs">
|
||||
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
{copied ? "Kopiert" : "Kopieren"}
|
||||
</button>
|
||||
<button type="button" onClick={download} className="btn btn-ghost text-xs">
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
Herunterladen
|
||||
</button>
|
||||
<button type="button" onClick={onDone} className="btn btn-ghost text-xs">
|
||||
Ich habe sie gesichert
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Download,
|
||||
Fingerprint,
|
||||
FolderGit2,
|
||||
Hourglass,
|
||||
Loader2,
|
||||
Lock,
|
||||
Plus,
|
||||
@@ -67,6 +68,12 @@ export interface AdminData {
|
||||
/** Projekte mit Repository, die grundsaetzlich in Frage kommen. */
|
||||
eligible: number;
|
||||
};
|
||||
stale: {
|
||||
afterDays: number;
|
||||
lastCheckAt: string | Date | null;
|
||||
/** Wie viele Konten ueberhaupt auf Stillstand hoeren. */
|
||||
listeners: number;
|
||||
};
|
||||
}
|
||||
|
||||
type Notice = { ok: boolean; text: string } | null;
|
||||
@@ -187,6 +194,7 @@ export function AdminManager({ data }: { data: AdminData }) {
|
||||
</section>
|
||||
|
||||
<AutoSyncSection data={data.autoSync} />
|
||||
<StaleSection data={data.stale} />
|
||||
|
||||
{/* ── Instanz ─────────────────────────────────────── */}
|
||||
<section className="glass p-5">
|
||||
@@ -574,6 +582,124 @@ function AutoSyncSection({ data }: { data: AdminData["autoSync"] }) {
|
||||
);
|
||||
}
|
||||
|
||||
const STALE_OPTIONS = [14, 30, 60, 90, 180, 365];
|
||||
|
||||
function StaleSection({ data }: { data: AdminData["stale"] }) {
|
||||
const router = useRouter();
|
||||
const [days, setDays] = useState(data.afterDays);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
|
||||
async function save(value: number) {
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
const response = await fetch("/api/admin/settings", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ staleAfterDays: value }),
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body.error ?? "Speichern fehlgeschlagen.");
|
||||
setNotice({ ok: true, text: "Gespeichert." });
|
||||
router.refresh();
|
||||
} catch (caught) {
|
||||
setDays(data.afterDays);
|
||||
setNotice({ ok: false, text: caught instanceof Error ? caught.message : String(caught) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="glass p-5">
|
||||
<div className="mb-4 flex items-start gap-3">
|
||||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-amber-500/12 text-amber-300">
|
||||
<Hourglass className="h-4 w-4" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wider text-slate-200">
|
||||
Stillstand
|
||||
</h2>
|
||||
<p className="mt-1 max-w-xl text-sm text-slate-400">
|
||||
Ab wann ein Projekt als eingeschlafen gilt. Massstab ist der letzte Commit im
|
||||
verknuepften Repository – das Aenderungsdatum taugt nicht, weil jeder Abgleich
|
||||
es anfasst. Projekte ohne Repository bleiben aussen vor, ebenso fertige und
|
||||
archivierte.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="field-label" htmlFor="stale-days">
|
||||
Schwelle
|
||||
</label>
|
||||
<select
|
||||
id="stale-days"
|
||||
className="field"
|
||||
value={days}
|
||||
disabled={busy}
|
||||
onChange={(event) => {
|
||||
const value = Number(event.target.value);
|
||||
setDays(value);
|
||||
void save(value);
|
||||
}}
|
||||
>
|
||||
{STALE_OPTIONS.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
nach {value} Tagen ohne Commit
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<dl className="grid grid-cols-2 gap-3">
|
||||
<div className="glass-soft px-3 py-2.5">
|
||||
<dt className="text-[11px] uppercase tracking-wider text-slate-500">
|
||||
Letzte Pruefung
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-slate-200" suppressHydrationWarning>
|
||||
{data.lastCheckAt ? formatRelative(data.lastCheckAt) : "noch keine"}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="glass-soft px-3 py-2.5">
|
||||
<dt className="text-[11px] uppercase tracking-wider text-slate-500">
|
||||
Empfaenger
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm tabular-nums text-slate-200">{data.listeners}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
{data.listeners === 0 ? (
|
||||
<p className="mt-3 text-[11px] text-slate-600">
|
||||
Niemand hoert derzeit auf diesen Anlass – die Pruefung laeuft dann gar nicht
|
||||
erst. Einzurichten unter „Mein Konto → Benachrichtigungen“.
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-3 text-[11px] text-slate-600">
|
||||
Die Pruefung laeuft hoechstens einmal am Tag. Je Projekt wird einmal gemeldet;
|
||||
erneut erst, wenn danach wieder ein Commit kam und es wieder still wurde.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{notice ? (
|
||||
<p
|
||||
className={cn(
|
||||
"mt-3 rounded-lg border px-3 py-2 text-sm",
|
||||
notice.ok
|
||||
? "border-emerald-500/30 bg-emerald-500/10 text-emerald-200"
|
||||
: "border-rose-500/30 bg-rose-500/10 text-rose-200",
|
||||
)}
|
||||
>
|
||||
{notice.text}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ModeCard({
|
||||
active,
|
||||
disabled,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { startAuthentication } from "@simplewebauthn/browser";
|
||||
import { Fingerprint, KeyRound, Loader2, LogIn } from "lucide-react";
|
||||
import { Fingerprint, KeyRound, Loader2, LogIn, ShieldCheck } from "lucide-react";
|
||||
|
||||
export function LoginForm({
|
||||
passkeysAvailable,
|
||||
@@ -18,8 +18,11 @@ export function LoginForm({
|
||||
const router = useRouter();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState<"password" | "passkey" | null>(null);
|
||||
const [busy, setBusy] = useState<"password" | "passkey" | "code" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
/** Passwort stimmt, jetzt fehlt der zweite Faktor. */
|
||||
const [mfa, setMfa] = useState(false);
|
||||
const [code, setCode] = useState("");
|
||||
|
||||
function done() {
|
||||
// replace statt push: die Anmeldeseite soll nicht im Verlauf landen.
|
||||
@@ -39,6 +42,14 @@ export function LoginForm({
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(payload.error ?? "Anmeldung fehlgeschlagen.");
|
||||
|
||||
// Zweiter Faktor eingerichtet: das Passwort allein reicht nicht.
|
||||
if (payload.mfaRequired) {
|
||||
setMfa(true);
|
||||
setPassword("");
|
||||
setBusy(null);
|
||||
return;
|
||||
}
|
||||
done();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
@@ -46,6 +57,26 @@ export function LoginForm({
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCode(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy("code");
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch("/api/auth/mfa", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(payload.error ?? "Der Code stimmt nicht.");
|
||||
done();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
setCode("");
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function loginWithPasskey() {
|
||||
setBusy("passkey");
|
||||
setError(null);
|
||||
@@ -82,6 +113,70 @@ export function LoginForm({
|
||||
}
|
||||
}
|
||||
|
||||
// Beim zweiten Schritt bleibt nur noch der Code stehen. Benutzername und
|
||||
// Passwort daneben einzublenden wuerde nur zum erneuten Absenden verleiten.
|
||||
if (mfa) {
|
||||
return (
|
||||
<form onSubmit={submitCode} className="space-y-4">
|
||||
<div className="flex items-start gap-2 rounded-lg border border-white/8 bg-black/25 px-3 py-2 text-sm text-slate-400">
|
||||
<ShieldCheck className="mt-0.5 h-4 w-4 shrink-0 text-violet-300" />
|
||||
<span>
|
||||
Bitte den sechsstelligen Code aus deiner Authenticator-App eingeben. Kein
|
||||
Zugriff darauf? Ein Wiederherstellungscode geht auch.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="login-code">
|
||||
Code
|
||||
</label>
|
||||
<input
|
||||
id="login-code"
|
||||
className="field text-center text-lg tracking-[0.35em]"
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
// Nicht type="number": das schluckt fuehrende Nullen und die
|
||||
// Bindestriche der Wiederherstellungscodes.
|
||||
inputMode="text"
|
||||
autoComplete="one-time-code"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
maxLength={40}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<button type="submit" className="btn btn-primary w-full py-2.5" disabled={busy !== null}>
|
||||
{busy === "code" ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<LogIn className="h-4 w-4" />
|
||||
)}
|
||||
Bestätigen
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMfa(false);
|
||||
setCode("");
|
||||
setError(null);
|
||||
}}
|
||||
className="w-full text-center text-sm text-slate-500 hover:text-slate-300"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{passkeysAvailable ? (
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describeFields, describeStatus, shorten } from "./activity";
|
||||
|
||||
describe("describeFields", () => {
|
||||
it("nennt ein einzelnes Feld beim Namen", () => {
|
||||
expect(describeFields(["name"])).toBe("Name geändert");
|
||||
});
|
||||
|
||||
it("zaehlt zwei und drei Felder auf", () => {
|
||||
expect(describeFields(["name", "tags"])).toBe("Name und Tags geändert");
|
||||
expect(describeFields(["name", "tags", "priority"])).toBe(
|
||||
"Name, Tags und Priorität geändert",
|
||||
);
|
||||
});
|
||||
|
||||
it("fasst ab vier Feldern zusammen, statt eine Litanei zu bilden", () => {
|
||||
expect(describeFields(["name", "tags", "priority", "accent"])).toBe("4 Felder geändert");
|
||||
});
|
||||
|
||||
it("zaehlt zusammengehoerende Felder nur einmal", () => {
|
||||
// repoOwner und repoName sind fuer den Leser eine einzige Aenderung.
|
||||
expect(describeFields(["repoOwner", "repoName"])).toBe("Repository geändert");
|
||||
});
|
||||
|
||||
it("liefert null, wenn nichts Nennenswertes dabei war", () => {
|
||||
// slug wird nur mitgeschrieben, wenn sich der Name aendert – der Name
|
||||
// steht dann ohnehin schon in der Liste.
|
||||
expect(describeFields([])).toBeNull();
|
||||
expect(describeFields(["slug", "updatedAt"])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("describeStatus", () => {
|
||||
it("uebersetzt beide Seiten in die Anzeigenamen", () => {
|
||||
expect(describeStatus("IDEA", "IN_DEVELOPMENT")).toBe("Status: Idee → In Entwicklung");
|
||||
});
|
||||
|
||||
it("laesst unbekannte Werte stehen, statt sie zu verschlucken", () => {
|
||||
expect(describeStatus("IDEA", "PHANTASIE")).toBe("Status: Idee → PHANTASIE");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shorten", () => {
|
||||
it("laesst Kurzes unangetastet", () => {
|
||||
expect(shorten("Kurzer Titel")).toBe("Kurzer Titel");
|
||||
});
|
||||
|
||||
it("kuerzt auf die vorgegebene Laenge einschliesslich Auslassungszeichen", () => {
|
||||
const gekuerzt = shorten("x".repeat(100), 20);
|
||||
expect(gekuerzt).toHaveLength(20);
|
||||
expect(gekuerzt.endsWith("…")).toBe(true);
|
||||
});
|
||||
|
||||
it("macht aus Zeilenumbruechen eine Zeile", () => {
|
||||
expect(shorten("Erste Zeile\n\n zweite Zeile ")).toBe("Erste Zeile zweite Zeile");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { ActivityKind, Prisma } from "@prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { STATUS_META } from "@/lib/status";
|
||||
|
||||
/**
|
||||
* Verlauf je Projekt: was ist wann passiert.
|
||||
*
|
||||
* Der Einzeiler wird beim Schreiben formuliert und nicht erst beim Anzeigen.
|
||||
* Das ist Absicht: ein Eintrag soll auch dann noch lesbar sein, wenn es die
|
||||
* Notiz oder die Aufgabe, um die es ging, laengst nicht mehr gibt.
|
||||
*/
|
||||
|
||||
/** Wie viele Eintraege je Projekt aufgehoben werden. */
|
||||
export const ACTIVITY_LIMIT = 200;
|
||||
|
||||
type Entry = {
|
||||
projectId: string;
|
||||
/** null = die Anwendung selbst, etwa der Zeitgeber beim Abgleich. */
|
||||
userId?: string | null;
|
||||
kind: ActivityKind;
|
||||
summary: string;
|
||||
meta?: Prisma.InputJsonValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* Haelt einen Vorgang fest. Wirft nie: der Verlauf ist Beiwerk, und daran
|
||||
* darf die eigentliche Aenderung nicht scheitern.
|
||||
*/
|
||||
export async function recordActivity(entry: Entry): Promise<void> {
|
||||
try {
|
||||
await prisma.activity.create({
|
||||
data: {
|
||||
projectId: entry.projectId,
|
||||
userId: entry.userId ?? null,
|
||||
kind: entry.kind,
|
||||
summary: entry.summary,
|
||||
meta: entry.meta,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[activity] konnte nicht geschrieben werden:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Mehrere Vorgaenge auf einmal – ein Rundgang statt vieler. */
|
||||
export async function recordActivities(entries: Entry[]): Promise<void> {
|
||||
if (entries.length === 0) return;
|
||||
try {
|
||||
await prisma.activity.createMany({
|
||||
data: entries.map((entry) => ({
|
||||
projectId: entry.projectId,
|
||||
userId: entry.userId ?? null,
|
||||
kind: entry.kind,
|
||||
summary: entry.summary,
|
||||
meta: entry.meta,
|
||||
})),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[activity] konnte nicht geschrieben werden:", error);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Formulierungshilfen ──────────────────────────────────────
|
||||
|
||||
const FIELD_LABELS: Record<string, string> = {
|
||||
name: "Name",
|
||||
summary: "Kurzbeschreibung",
|
||||
description: "Beschreibung",
|
||||
priority: "Priorität",
|
||||
progress: "Fortschritt",
|
||||
accent: "Farbe",
|
||||
tags: "Tags",
|
||||
favorite: "Favorit",
|
||||
autoSync: "Automatischer Abgleich",
|
||||
progressFromTasks: "Fortschritt aus Aufgaben",
|
||||
connectionId: "Git-Verbindung",
|
||||
repoUrl: "Repository",
|
||||
repoOwner: "Repository",
|
||||
repoName: "Repository",
|
||||
defaultBranch: "Standard-Branch",
|
||||
};
|
||||
|
||||
/**
|
||||
* Aus geaenderten Feldnamen einen lesbaren Satz machen: "Name und Tags
|
||||
* geändert". Doppelte Bezeichnungen fallen weg – wer repoOwner und repoName
|
||||
* zusammen setzt, hat einmal das Repository geaendert, nicht zweimal.
|
||||
*/
|
||||
export function describeFields(fields: string[]): string | null {
|
||||
const labels: string[] = [];
|
||||
for (const field of fields) {
|
||||
const label = FIELD_LABELS[field];
|
||||
if (label && !labels.includes(label)) labels.push(label);
|
||||
}
|
||||
if (labels.length === 0) return null;
|
||||
if (labels.length === 1) return `${labels[0]} geändert`;
|
||||
|
||||
// Ab vier Feldern wird die Aufzaehlung laenger als sie nuetzt.
|
||||
if (labels.length > 3) return `${labels.length} Felder geändert`;
|
||||
return `${labels.slice(0, -1).join(", ")} und ${labels.at(-1)} geändert`;
|
||||
}
|
||||
|
||||
/** "Idee → In Entwicklung" */
|
||||
export function describeStatus(from: string, to: string): string {
|
||||
const label = (value: string) =>
|
||||
STATUS_META[value as keyof typeof STATUS_META]?.label ?? value;
|
||||
return `Status: ${label(from)} → ${label(to)}`;
|
||||
}
|
||||
|
||||
/** Kuerzt lange Titel, damit ein Eintrag eine Zeile bleibt. */
|
||||
export function shorten(text: string, max = 70): string {
|
||||
const clean = text.replace(/\s+/g, " ").trim();
|
||||
return clean.length <= max ? clean : `${clean.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stutzt den Verlauf auf die neuesten Eintraege je Projekt zurueck. Laeuft
|
||||
* im taeglichen Durchgang des Zeitgebers mit – bei jedem Schreiben zu
|
||||
* pruefen waere eine zusaetzliche Abfrage fuer nichts.
|
||||
*/
|
||||
export async function pruneActivities(): Promise<number> {
|
||||
const rows = await prisma.$queryRaw<{ count: bigint }[]>`
|
||||
WITH nummeriert AS (
|
||||
SELECT "id", ROW_NUMBER() OVER (
|
||||
PARTITION BY "projectId" ORDER BY "createdAt" DESC, "id" DESC
|
||||
) AS rang
|
||||
FROM "Activity"
|
||||
), geloescht AS (
|
||||
DELETE FROM "Activity"
|
||||
WHERE "id" IN (SELECT "id" FROM nummeriert WHERE rang > ${ACTIVITY_LIMIT})
|
||||
RETURNING 1
|
||||
)
|
||||
SELECT COUNT(*)::bigint AS count FROM geloescht
|
||||
`;
|
||||
return Number(rows[0]?.count ?? 0);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { cookies } from "next/headers";
|
||||
import type { NextResponse } from "next/server";
|
||||
import { COOKIES_SECURE, MFA_COOKIE, MFA_TTL_MS } from "@/lib/config";
|
||||
import { tryDecryptSecret } from "@/lib/crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
/**
|
||||
* Der Zwischenzustand zwischen Passwort und zweitem Faktor.
|
||||
*
|
||||
* Bewusst nicht als halbfertige Sitzung: eine Sitzungszeile mit einem
|
||||
* "noch nicht gueltig"-Merker waere eine Zeile, die bei einem vergessenen
|
||||
* Filter irgendwo doch als Anmeldung durchgeht. Ein eigenes Modell kann
|
||||
* dieses Versehen nicht passieren.
|
||||
*/
|
||||
|
||||
/** Nach so vielen Fehlversuchen ist der Vorgang verbrannt. */
|
||||
export const MFA_MAX_ATTEMPTS = 5;
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("base64url");
|
||||
}
|
||||
|
||||
export async function createPendingLogin(userId: string): Promise<string> {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
|
||||
// Aeltere Vorgaenge desselben Kontos verwerfen: es kann nur einen geben,
|
||||
// sonst sammeln sich bei jedem Anlauf neue Rateversuche an.
|
||||
await prisma.pendingLogin.deleteMany({
|
||||
where: { OR: [{ userId }, { expiresAt: { lt: new Date() } }] },
|
||||
});
|
||||
|
||||
await prisma.pendingLogin.create({
|
||||
data: {
|
||||
userId,
|
||||
tokenHash: hashToken(token),
|
||||
expiresAt: new Date(Date.now() + MFA_TTL_MS),
|
||||
},
|
||||
});
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
export function setMfaCookie(response: NextResponse, token: string) {
|
||||
response.cookies.set({
|
||||
name: MFA_COOKIE,
|
||||
value: token,
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: COOKIES_SECURE,
|
||||
path: "/",
|
||||
maxAge: Math.floor(MFA_TTL_MS / 1000),
|
||||
});
|
||||
}
|
||||
|
||||
export function clearMfaCookie(response: NextResponse) {
|
||||
response.cookies.set({
|
||||
name: MFA_COOKIE,
|
||||
value: "",
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: COOKIES_SECURE,
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
});
|
||||
}
|
||||
|
||||
export interface PendingLoginState {
|
||||
id: string;
|
||||
attempts: number;
|
||||
user: {
|
||||
id: string;
|
||||
username: string;
|
||||
role: "ADMIN" | "USER";
|
||||
isActive: boolean;
|
||||
/** Entschluesselter TOTP-Schluessel; null, wenn er nicht lesbar ist. */
|
||||
totpSecret: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Liest den laufenden Vorgang aus dem Cookie. */
|
||||
export async function readPendingLogin(): Promise<PendingLoginState | null> {
|
||||
const store = await cookies();
|
||||
const token = store.get(MFA_COOKIE)?.value;
|
||||
if (!token) return null;
|
||||
|
||||
const pending = await prisma.pendingLogin.findUnique({
|
||||
where: { tokenHash: hashToken(token) },
|
||||
include: { user: true },
|
||||
});
|
||||
if (!pending) return null;
|
||||
|
||||
if (pending.expiresAt.getTime() <= Date.now()) {
|
||||
await prisma.pendingLogin.delete({ where: { id: pending.id } }).catch(() => undefined);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: pending.id,
|
||||
attempts: pending.attempts,
|
||||
user: {
|
||||
id: pending.user.id,
|
||||
username: pending.user.username,
|
||||
role: pending.user.role,
|
||||
isActive: pending.user.isActive,
|
||||
totpSecret: tryDecryptSecret(pending.user.totpSecretCipher),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Zaehlt einen Fehlversuch. Gibt zurueck, ob noch Versuche offen sind. */
|
||||
export async function noteMfaFailure(id: string): Promise<boolean> {
|
||||
const updated = await prisma.pendingLogin.update({
|
||||
where: { id },
|
||||
data: { attempts: { increment: 1 } },
|
||||
select: { attempts: true },
|
||||
});
|
||||
|
||||
if (updated.attempts >= MFA_MAX_ATTEMPTS) {
|
||||
await prisma.pendingLogin.delete({ where: { id } }).catch(() => undefined);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function discardPendingLogin(id: string): Promise<void> {
|
||||
await prisma.pendingLogin.delete({ where: { id } }).catch(() => undefined);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { hashCode, normalizeCode } from "./recovery";
|
||||
|
||||
describe("normalizeCode", () => {
|
||||
it("setzt den Bindestrich, wenn er beim Abtippen fehlt", () => {
|
||||
expect(normalizeCode("a7k2mp9xqd")).toBe("a7k2m-p9xqd");
|
||||
});
|
||||
|
||||
it("nimmt Grossschreibung und Leerzeichen hin", () => {
|
||||
// Aus einem Ausdruck abgeschrieben sieht ein Code selten so aus wie
|
||||
// beim Erzeugen.
|
||||
expect(normalizeCode("A7K2M-P9XQD")).toBe("a7k2m-p9xqd");
|
||||
expect(normalizeCode(" a7k2m p9xqd ")).toBe("a7k2m-p9xqd");
|
||||
expect(normalizeCode("a7k2m—p9xqd")).toBe("a7k2m-p9xqd");
|
||||
});
|
||||
|
||||
it("laesst zu kurze Eingaben unveraendert, statt sie zurechtzubiegen", () => {
|
||||
expect(normalizeCode("abc")).toBe("abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hashCode", () => {
|
||||
it("bildet Schreibweisen desselben Codes auf denselben Hash ab", () => {
|
||||
expect(hashCode("A7K2M-P9XQD")).toBe(hashCode("a7k2mp9xqd"));
|
||||
});
|
||||
|
||||
it("unterscheidet verschiedene Codes", () => {
|
||||
expect(hashCode("a7k2m-p9xqd")).not.toBe(hashCode("a7k2m-p9xqe"));
|
||||
});
|
||||
|
||||
it("gibt den Code nicht preis", () => {
|
||||
expect(hashCode("a7k2m-p9xqd")).not.toContain("a7k2m");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { createHash, randomInt, timingSafeEqual } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
/**
|
||||
* Wiederherstellungscodes fuer den Fall, dass der Authenticator verloren geht.
|
||||
*
|
||||
* Ohne sie waere die Zwei-Faktor-Anmeldung eine Falle: ein neues Handy, und
|
||||
* das Konto ist zu. Ein Administrator kann zwar aushelfen – im
|
||||
* Einzelbenutzerbetrieb ist der Administrator aber genau die ausgesperrte
|
||||
* Person.
|
||||
*/
|
||||
|
||||
/** Wie viele Codes bei der Einrichtung erzeugt werden. */
|
||||
export const RECOVERY_CODE_COUNT = 10;
|
||||
|
||||
/**
|
||||
* Alphabet ohne die Paare, die man beim Abschreiben verwechselt: kein O/0,
|
||||
* kein I/l/1, kein B/8. Die Codes werden von Hand aus einem Ausdruck oder
|
||||
* Passwortmanager uebertragen, oft unter Zeitdruck.
|
||||
*/
|
||||
const ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
|
||||
const GROUP = 5;
|
||||
|
||||
/** Ein Code der Form "a7k2m-p9xqd" – rund 50 Bit Zufall. */
|
||||
function generateCode(): string {
|
||||
const zeichen = Array.from(
|
||||
{ length: GROUP * 2 },
|
||||
() => ALPHABET[randomInt(ALPHABET.length)],
|
||||
).join("");
|
||||
return `${zeichen.slice(0, GROUP)}-${zeichen.slice(GROUP)}`;
|
||||
}
|
||||
|
||||
/** Vereinheitlicht Eingaben: Grossschreibung und fehlender Bindestrich. */
|
||||
export function normalizeCode(input: string): string {
|
||||
const clean = input.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
if (clean.length !== GROUP * 2) return clean;
|
||||
return `${clean.slice(0, GROUP)}-${clean.slice(GROUP)}`;
|
||||
}
|
||||
|
||||
export function hashCode(code: string): string {
|
||||
return createHash("sha256").update(normalizeCode(code)).digest("base64url");
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt einen frischen Satz und verwirft den alten. Gibt die Codes im
|
||||
* Klartext zurueck – das ist die einzige Gelegenheit, sie zu sehen.
|
||||
*/
|
||||
export async function issueRecoveryCodes(userId: string): Promise<string[]> {
|
||||
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, generateCode);
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.recoveryCode.deleteMany({ where: { userId } }),
|
||||
prisma.recoveryCode.createMany({
|
||||
data: codes.map((code) => ({ userId, codeHash: hashCode(code) })),
|
||||
}),
|
||||
]);
|
||||
|
||||
return codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loest einen Code ein. Ein Code gilt genau einmal; verbraucht wird er auch
|
||||
* dann, wenn die Anmeldung danach aus anderem Grund scheitert – lieber ein
|
||||
* Code zu viel verbraucht als einer, der zweimal geht.
|
||||
*/
|
||||
export async function redeemRecoveryCode(userId: string, input: string): Promise<boolean> {
|
||||
const eingabe = normalizeCode(input);
|
||||
if (eingabe.length < GROUP * 2) return false;
|
||||
|
||||
const offen = await prisma.recoveryCode.findMany({
|
||||
where: { userId, usedAt: null },
|
||||
select: { id: true, codeHash: true },
|
||||
});
|
||||
|
||||
const gesucht = Buffer.from(hashCode(eingabe), "utf8");
|
||||
let treffer: string | null = null;
|
||||
for (const code of offen) {
|
||||
const vorhanden = Buffer.from(code.codeHash, "utf8");
|
||||
// Nicht abbrechen, sobald es passt: die Laufzeit soll nicht verraten,
|
||||
// an welcher Stelle der Liste der Code stand.
|
||||
if (vorhanden.length === gesucht.length && timingSafeEqual(vorhanden, gesucht)) {
|
||||
treffer = code.id;
|
||||
}
|
||||
}
|
||||
|
||||
if (!treffer) return false;
|
||||
|
||||
// updateMany mit der Bedingung "noch unbenutzt": zwei gleichzeitige
|
||||
// Versuche mit demselben Code koennen so nicht beide durchkommen.
|
||||
const result = await prisma.recoveryCode.updateMany({
|
||||
where: { id: treffer, usedAt: null },
|
||||
data: { usedAt: new Date() },
|
||||
});
|
||||
return result.count === 1;
|
||||
}
|
||||
|
||||
/** Wie viele Codes noch ungenutzt sind – fuer den Hinweis im Konto. */
|
||||
export async function countUnusedRecoveryCodes(userId: string): Promise<number> {
|
||||
return prisma.recoveryCode.count({ where: { userId, usedAt: null } });
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
TOTP_PERIOD,
|
||||
base32Decode,
|
||||
base32Encode,
|
||||
counterFor,
|
||||
generateTotpSecret,
|
||||
groupSecret,
|
||||
otpauthUri,
|
||||
totpCode,
|
||||
verifyTotp,
|
||||
} from "./totp";
|
||||
|
||||
describe("Base32", () => {
|
||||
// Testvektoren aus RFC 4648, Abschnitt 10 – ohne die Auffuellzeichen,
|
||||
// die Authenticator-Apps nicht erwarten.
|
||||
it.each([
|
||||
["", ""],
|
||||
["f", "MY"],
|
||||
["fo", "MZXQ"],
|
||||
["foo", "MZXW6"],
|
||||
["foob", "MZXW6YQ"],
|
||||
["fooba", "MZXW6YTB"],
|
||||
["foobar", "MZXW6YTBOI"],
|
||||
])("kodiert %j als %j", (klartext, erwartet) => {
|
||||
expect(base32Encode(Buffer.from(klartext, "utf8"))).toBe(erwartet);
|
||||
});
|
||||
|
||||
it("dekodiert zurueck, auch mit Leerzeichen und Auffuellzeichen", () => {
|
||||
expect(base32Decode("MZXW6YTBOI").toString("utf8")).toBe("foobar");
|
||||
expect(base32Decode("mzxw 6ytb oi").toString("utf8")).toBe("foobar");
|
||||
expect(base32Decode("MZXW6YTBOI======").toString("utf8")).toBe("foobar");
|
||||
});
|
||||
|
||||
it("weist fremde Zeichen ab, statt still Unsinn zu liefern", () => {
|
||||
// 0, 1 und 8 gehoeren nicht zum Alphabet – gerade sie werden aber gern
|
||||
// mit O, I und B verwechselt.
|
||||
expect(() => base32Decode("MZXW0YTB")).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TOTP nach RFC 6238", () => {
|
||||
// Der Schluessel aus Anhang B des RFC: die ASCII-Ziffern 1234567890,
|
||||
// zweimal hintereinander.
|
||||
const SECRET = base32Encode(Buffer.from("12345678901234567890", "utf8"));
|
||||
|
||||
/**
|
||||
* Der RFC nennt achtstellige Codes. Sechs Stellen sind davon die letzten
|
||||
* sechs – gerechnet wird modulo 10^6 statt 10^8.
|
||||
*/
|
||||
it.each([
|
||||
[59, "287082"],
|
||||
[1111111109, "081804"],
|
||||
[1111111111, "050471"],
|
||||
[1234567890, "005924"],
|
||||
[2000000000, "279037"],
|
||||
[20000000000, "353130"],
|
||||
])("liefert zum Zeitpunkt %i den Code %s", (sekunden, erwartet) => {
|
||||
const counter = Math.floor(sekunden / TOTP_PERIOD);
|
||||
expect(totpCode(SECRET, counter)).toBe(erwartet);
|
||||
});
|
||||
|
||||
it("rechnet Zeitpunkte in Fenster um", () => {
|
||||
expect(counterFor(new Date(59_000))).toBe(1);
|
||||
expect(counterFor(new Date(1111111109_000))).toBe(37037036);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyTotp", () => {
|
||||
const SECRET = base32Encode(Buffer.from("12345678901234567890", "utf8"));
|
||||
const JETZT = new Date(1111111109_000);
|
||||
|
||||
it("nimmt den Code des aktuellen Fensters an", () => {
|
||||
expect(verifyTotp(SECRET, "081804", JETZT)).toBe(true);
|
||||
});
|
||||
|
||||
it("nimmt auch das vorige und das naechste Fenster an", () => {
|
||||
// Eine um bis zu 30 Sekunden falsch gehende Uhr soll niemanden aussperren.
|
||||
const vorher = new Date(JETZT.getTime() - TOTP_PERIOD * 1000);
|
||||
const nachher = new Date(JETZT.getTime() + TOTP_PERIOD * 1000);
|
||||
expect(verifyTotp(SECRET, "081804", vorher)).toBe(true);
|
||||
expect(verifyTotp(SECRET, "081804", nachher)).toBe(true);
|
||||
});
|
||||
|
||||
it("lehnt ein Fenster weiter ab", () => {
|
||||
const zuFrueh = new Date(JETZT.getTime() - 2 * TOTP_PERIOD * 1000);
|
||||
expect(verifyTotp(SECRET, "081804", zuFrueh)).toBe(false);
|
||||
});
|
||||
|
||||
it("lehnt falsche Codes und Unfug ab", () => {
|
||||
expect(verifyTotp(SECRET, "000000", JETZT)).toBe(false);
|
||||
expect(verifyTotp(SECRET, "", JETZT)).toBe(false);
|
||||
expect(verifyTotp(SECRET, "81804", JETZT)).toBe(false);
|
||||
expect(verifyTotp(SECRET, "abcdef", JETZT)).toBe(false);
|
||||
// Fuehrende Nullen duerfen nicht als Zahl verlorengehen.
|
||||
expect(verifyTotp(SECRET, "81804 ", JETZT)).toBe(false);
|
||||
});
|
||||
|
||||
it("sieht ueber Leerzeichen in der Eingabe hinweg", () => {
|
||||
expect(verifyTotp(SECRET, "081 804", JETZT)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Einrichtung", () => {
|
||||
it("erzeugt Schluessel, die sich unterscheiden und lang genug sind", () => {
|
||||
const a = generateTotpSecret();
|
||||
const b = generateTotpSecret();
|
||||
expect(a).not.toBe(b);
|
||||
// 20 Byte ergeben 32 Base32-Zeichen.
|
||||
expect(a).toHaveLength(32);
|
||||
expect(base32Decode(a)).toHaveLength(20);
|
||||
});
|
||||
|
||||
it("baut eine otpauth-URI mit Aussteller im Label und im Parameter", () => {
|
||||
const uri = otpauthUri({ secret: "ABCD", account: "chefin", issuer: "Nebula" });
|
||||
expect(uri).toContain("otpauth://totp/Nebula%3Achefin?");
|
||||
expect(uri).toContain("secret=ABCD");
|
||||
expect(uri).toContain("issuer=Nebula");
|
||||
expect(uri).toContain("digits=6");
|
||||
expect(uri).toContain("period=30");
|
||||
});
|
||||
|
||||
it("gruppiert den Schluessel zum Abtippen", () => {
|
||||
expect(groupSecret("ABCDEFGH")).toBe("ABCD EFGH");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
/**
|
||||
* Zeitbasierte Einmalkennwoerter nach RFC 6238 (TOTP über HMAC-SHA1).
|
||||
*
|
||||
* Selbst gerechnet statt als Abhaengigkeit: es sind wenige Zeilen, das
|
||||
* Verfahren steht seit 2011 fest, und der RFC bringt Testvektoren mit –
|
||||
* die Richtigkeit laesst sich also beweisen statt nur behaupten
|
||||
* (siehe totp.test.ts).
|
||||
*
|
||||
* SHA-1 ist hier kein Mangel. Es geht nicht um Kollisionsresistenz, sondern
|
||||
* um HMAC mit einem geheimen Schluessel, und jede Authenticator-App der Welt
|
||||
* erwartet genau diese Voreinstellung.
|
||||
*/
|
||||
|
||||
/** Stellenzahl des Codes. */
|
||||
export const TOTP_DIGITS = 6;
|
||||
/** Laenge eines Zeitfensters in Sekunden. */
|
||||
export const TOTP_PERIOD = 30;
|
||||
/**
|
||||
* Wie viele Fenster in jede Richtung zusaetzlich gelten. Eines deckt eine um
|
||||
* bis zu 30 Sekunden falsch gehende Uhr ab – mehr wuerde den Zeitraum
|
||||
* unnoetig verbreitern, in dem ein abgefangener Code noch taugt.
|
||||
*/
|
||||
export const TOTP_WINDOW = 1;
|
||||
|
||||
const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
|
||||
/** Base32 nach RFC 4648, ohne Auffuellzeichen – so erwarten es die Apps. */
|
||||
export function base32Encode(data: Buffer): string {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let output = "";
|
||||
|
||||
for (const byte of data) {
|
||||
value = (value << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
|
||||
return output;
|
||||
}
|
||||
|
||||
export function base32Decode(input: string): Buffer {
|
||||
// Leerzeichen und Auffuellzeichen grosszuegig hinnehmen: Benutzer tippen
|
||||
// den Schluessel gelegentlich aus einer Anzeige in Vierergruppen ab.
|
||||
const clean = input.toUpperCase().replace(/[\s-]/g, "").replace(/=+$/, "");
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
const bytes: number[] = [];
|
||||
|
||||
for (const char of clean) {
|
||||
const index = BASE32_ALPHABET.indexOf(char);
|
||||
if (index === -1) throw new Error("Ungueltiges Zeichen im Base32-Schluessel");
|
||||
value = (value << 5) | index;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
bytes.push((value >>> (bits - 8)) & 255);
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
return Buffer.from(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Neuer Schluessel. 20 Byte entsprechen der Empfehlung des RFC fuer
|
||||
* HMAC-SHA1 und ergeben 32 Base32-Zeichen.
|
||||
*/
|
||||
export function generateTotpSecret(): string {
|
||||
return base32Encode(randomBytes(20));
|
||||
}
|
||||
|
||||
/** Der Code fuer ein bestimmtes Zeitfenster. */
|
||||
export function totpCode(secret: string, counter: number): string {
|
||||
const key = base32Decode(secret);
|
||||
|
||||
// Zaehler als 8-Byte-Zahl in Big-Endian. BigInt, weil er theoretisch
|
||||
// ueber 2^32 hinausgeht – praktisch erst in einigen tausend Jahren, aber
|
||||
// die Bitschieberei mit Zahlen waere hier ohnehin heikel.
|
||||
const buffer = Buffer.alloc(8);
|
||||
buffer.writeBigUInt64BE(BigInt(counter));
|
||||
|
||||
const digest = createHmac("sha1", key).update(buffer).digest();
|
||||
|
||||
// Dynamic Truncation nach RFC 4226, Abschnitt 5.3.
|
||||
const offset = digest[digest.length - 1] & 0x0f;
|
||||
const binary =
|
||||
((digest[offset] & 0x7f) << 24) |
|
||||
((digest[offset + 1] & 0xff) << 16) |
|
||||
((digest[offset + 2] & 0xff) << 8) |
|
||||
(digest[offset + 3] & 0xff);
|
||||
|
||||
return String(binary % 10 ** TOTP_DIGITS).padStart(TOTP_DIGITS, "0");
|
||||
}
|
||||
|
||||
/** Das Zeitfenster, in dem ein Zeitpunkt liegt. */
|
||||
export function counterFor(at: Date = new Date()): number {
|
||||
return Math.floor(at.getTime() / 1000 / TOTP_PERIOD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prueft einen eingegebenen Code. Vergleicht in konstanter Zeit und probiert
|
||||
* die Nachbarfenster mit, damit eine leicht abweichende Uhr nicht stoert.
|
||||
*/
|
||||
export function verifyTotp(
|
||||
secret: string,
|
||||
code: string,
|
||||
at: Date = new Date(),
|
||||
window: number = TOTP_WINDOW,
|
||||
): boolean {
|
||||
const eingabe = code.replace(/\s/g, "");
|
||||
if (!/^\d+$/.test(eingabe) || eingabe.length !== TOTP_DIGITS) return false;
|
||||
|
||||
const jetzt = counterFor(at);
|
||||
let treffer = false;
|
||||
for (let schritt = -window; schritt <= window; schritt += 1) {
|
||||
// Nicht fruehzeitig abbrechen: sonst haengt die Laufzeit davon ab,
|
||||
// welches Fenster gepasst hat.
|
||||
if (constantEquals(totpCode(secret, jetzt + schritt), eingabe)) treffer = true;
|
||||
}
|
||||
return treffer;
|
||||
}
|
||||
|
||||
function constantEquals(a: string, b: string): boolean {
|
||||
const left = Buffer.from(a, "utf8");
|
||||
const right = Buffer.from(b, "utf8");
|
||||
if (left.length !== right.length) return false;
|
||||
return timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die URI, die als QR-Code angezeigt wird. Das Label enthaelt sowohl den
|
||||
* Aussteller als auch das Konto – so schreiben es die Authenticator-Apps
|
||||
* vor, sonst steht in der Liste nur ein nackter Benutzername.
|
||||
*/
|
||||
export function otpauthUri(options: {
|
||||
secret: string;
|
||||
account: string;
|
||||
issuer: string;
|
||||
}): string {
|
||||
const label = `${options.issuer}:${options.account}`;
|
||||
const query = new URLSearchParams({
|
||||
secret: options.secret,
|
||||
issuer: options.issuer,
|
||||
algorithm: "SHA1",
|
||||
digits: String(TOTP_DIGITS),
|
||||
period: String(TOTP_PERIOD),
|
||||
});
|
||||
return `otpauth://totp/${encodeURIComponent(label)}?${query.toString()}`;
|
||||
}
|
||||
|
||||
/** Der Schluessel in Vierergruppen – zum Abtippen, wenn die Kamera streikt. */
|
||||
export function groupSecret(secret: string): string {
|
||||
return secret.replace(/(.{4})/g, "$1 ").trim();
|
||||
}
|
||||
@@ -79,6 +79,14 @@ export const SESSION_TTL_MS = SESSION_TTL_DAYS * 24 * 60 * 60 * 1000;
|
||||
|
||||
export const SESSION_COOKIE = "nebula_session";
|
||||
|
||||
/**
|
||||
* Cookie fuer die halbfertige Anmeldung zwischen Passwort und zweitem Faktor.
|
||||
* Kurzlebig – wer den Code nicht binnen fuenf Minuten eingibt, faengt von
|
||||
* vorne an.
|
||||
*/
|
||||
export const MFA_COOKIE = "nebula_mfa";
|
||||
export const MFA_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
/** Wird beim Start einmal geloggt, damit Fehlkonfiguration frueh auffaellt. */
|
||||
export function describeConfig(): string {
|
||||
return [
|
||||
|
||||
@@ -12,10 +12,17 @@ import { z } from "zod";
|
||||
* ein Abgleich nach dem Import holt sie zurueck.
|
||||
* - keine Datenbank-IDs. Die gelten nur in der Instanz, aus der exportiert
|
||||
* wurde.
|
||||
* - kein Verlauf. Er beschreibt, was in *dieser* Instanz passiert ist, und
|
||||
* verwiese nach dem Import auf Konten, die es dort nicht gibt. Der Import
|
||||
* setzt stattdessen einen eigenen ersten Eintrag.
|
||||
*/
|
||||
|
||||
export const EXPORT_KIND = "nebula.projects";
|
||||
export const EXPORT_VERSION = 1;
|
||||
/**
|
||||
* 2 seit den mehreren Repositories je Projekt. Dateien der Version 1 werden
|
||||
* weiter gelesen: ihre einzelnen Repo-Felder werden zum ersten Repository.
|
||||
*/
|
||||
export const EXPORT_VERSION = 2;
|
||||
|
||||
const STATUS = ["IDEA", "OPEN", "PLANNING", "IN_DEVELOPMENT", "DONE", "ARCHIVED"] as const;
|
||||
const PROVIDERS = ["GITHUB", "GITLAB", "GITEA"] as const;
|
||||
@@ -43,6 +50,16 @@ export const exportedConnectionSchema = z.object({
|
||||
baseUrl: z.string().max(300),
|
||||
});
|
||||
|
||||
export const exportedRepositorySchema = z.object({
|
||||
label: z.string().max(80).nullable().optional(),
|
||||
repoUrl: z.string().max(500).nullable().optional(),
|
||||
repoOwner: z.string().max(200).nullable().optional(),
|
||||
repoName: z.string().max(200).nullable().optional(),
|
||||
autoSync: z.boolean().optional().default(true),
|
||||
/** Nur zur Wiedererkennung – ohne Token. */
|
||||
connection: exportedConnectionSchema.nullable().optional(),
|
||||
});
|
||||
|
||||
export const exportedProjectSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
slug: z.string().max(60).optional(),
|
||||
@@ -54,11 +71,17 @@ export const exportedProjectSchema = z.object({
|
||||
accent: z.string().max(20).optional().default("violet"),
|
||||
tags: z.array(z.string().max(30)).max(12).optional().default([]),
|
||||
favorite: z.boolean().optional().default(false),
|
||||
/** Seit Version 2. */
|
||||
repositories: z.array(exportedRepositorySchema).max(20).optional(),
|
||||
/**
|
||||
* Version 1 kannte genau ein Repository und schrieb es flach ans Projekt.
|
||||
* Die Felder bleiben lesbar, damit aeltere Dateien weiter importierbar
|
||||
* sind; geschrieben werden sie nicht mehr.
|
||||
*/
|
||||
autoSync: z.boolean().optional().default(true),
|
||||
repoUrl: z.string().max(500).nullable().optional(),
|
||||
repoOwner: z.string().max(200).nullable().optional(),
|
||||
repoName: z.string().max(200).nullable().optional(),
|
||||
/** Nur zur Wiedererkennung – ohne Token. */
|
||||
connection: exportedConnectionSchema.nullable().optional(),
|
||||
notes: z.array(exportedNoteSchema).max(500).optional().default([]),
|
||||
tasks: z.array(exportedTaskSchema).max(1000).optional().default([]),
|
||||
@@ -75,6 +98,26 @@ export const exportFileSchema = z.object({
|
||||
});
|
||||
|
||||
export type ExportedProject = z.infer<typeof exportedProjectSchema>;
|
||||
export type ExportedRepository = z.infer<typeof exportedRepositorySchema>;
|
||||
|
||||
/**
|
||||
* Die Repositories einer Exportdatei – gleich, ob sie aus Version 2 stammt
|
||||
* oder aus der Zeit mit genau einem Repo je Projekt.
|
||||
*/
|
||||
export function repositoriesOf(project: ExportedProject): ExportedRepository[] {
|
||||
if (project.repositories?.length) return project.repositories;
|
||||
if (!project.repoUrl && !(project.repoOwner && project.repoName)) return [];
|
||||
return [
|
||||
{
|
||||
label: null,
|
||||
repoUrl: project.repoUrl ?? null,
|
||||
repoOwner: project.repoOwner ?? null,
|
||||
repoName: project.repoName ?? null,
|
||||
autoSync: project.autoSync,
|
||||
connection: project.connection ?? null,
|
||||
},
|
||||
];
|
||||
}
|
||||
export type ExportFile = z.infer<typeof exportFileSchema>;
|
||||
|
||||
/** Dateiname ohne Sonderzeichen, mit Datumsstempel. */
|
||||
|
||||
+68
-26
@@ -1,14 +1,27 @@
|
||||
import type { GitConnection, Note, Project, RepoSnapshot, Task } from "@prisma/client";
|
||||
import type {
|
||||
GitConnection,
|
||||
Note,
|
||||
Prisma,
|
||||
Project,
|
||||
RepoSnapshot,
|
||||
Repository,
|
||||
Task,
|
||||
} from "@prisma/client";
|
||||
import { APP_NAME } from "@/lib/config";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { repoTitle } from "@/lib/repositories";
|
||||
import { PRIORITY_META, statusOf } from "@/lib/status";
|
||||
import { formatDate, formatDateTime } from "@/lib/utils";
|
||||
import { EXPORT_KIND, EXPORT_VERSION, type ExportFile, type ExportedProject } from "./format";
|
||||
|
||||
type ProjectForExport = Project & {
|
||||
export type RepositoryForExport = Repository & {
|
||||
connection: Pick<GitConnection, "name" | "provider" | "baseUrl"> | null;
|
||||
};
|
||||
|
||||
export type ProjectForExport = Project & {
|
||||
notes: Note[];
|
||||
tasks: Task[];
|
||||
connection: Pick<GitConnection, "name" | "provider" | "baseUrl"> | null;
|
||||
repositories: RepositoryForExport[];
|
||||
};
|
||||
|
||||
/** Formt einen Datensatz in das Austauschformat um – ohne Geheimnisse. */
|
||||
@@ -24,17 +37,25 @@ export function toExportedProject(project: ProjectForExport): ExportedProject {
|
||||
accent: project.accent,
|
||||
tags: project.tags,
|
||||
favorite: project.favorite,
|
||||
autoSync: project.autoSync,
|
||||
repoUrl: project.repoUrl,
|
||||
repoOwner: project.repoOwner,
|
||||
repoName: project.repoName,
|
||||
connection: project.connection
|
||||
// Version 1 hatte ein autoSync am Projekt. Das Feld ist im Schema noch
|
||||
// vorhanden, damit alte Dateien lesbar bleiben; geschrieben wird der
|
||||
// Wert des fuehrenden Repositories, damit eine Version-2-Datei auch von
|
||||
// einer aelteren Instanz noch sinnvoll gelesen werden koennte.
|
||||
autoSync: project.repositories[0]?.autoSync ?? true,
|
||||
repositories: project.repositories.map((repository) => ({
|
||||
label: repository.label,
|
||||
repoUrl: repository.repoUrl,
|
||||
repoOwner: repository.repoOwner,
|
||||
repoName: repository.repoName,
|
||||
autoSync: repository.autoSync,
|
||||
connection: repository.connection
|
||||
? {
|
||||
name: project.connection.name,
|
||||
provider: project.connection.provider,
|
||||
baseUrl: project.connection.baseUrl,
|
||||
name: repository.connection.name,
|
||||
provider: repository.connection.provider,
|
||||
baseUrl: repository.connection.baseUrl,
|
||||
}
|
||||
: null,
|
||||
})),
|
||||
notes: project.notes.map((note) => ({
|
||||
title: note.title,
|
||||
content: note.content,
|
||||
@@ -72,15 +93,21 @@ export async function loadProjectsForExport(
|
||||
): Promise<ProjectForExport[]> {
|
||||
return prisma.project.findMany({
|
||||
where: { ownerId, ...(projectId ? { id: projectId } : {}) },
|
||||
include: {
|
||||
notes: { orderBy: [{ pinned: "desc" }, { createdAt: "asc" }] },
|
||||
tasks: { orderBy: [{ status: "asc" }, { position: "asc" }] },
|
||||
connection: { select: { name: true, provider: true, baseUrl: true } },
|
||||
},
|
||||
include: exportInclude,
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
/** Der Umfang, den der Export braucht – an beiden Aufrufstellen derselbe. */
|
||||
export const exportInclude = {
|
||||
notes: { orderBy: [{ pinned: "desc" }, { createdAt: "asc" }] },
|
||||
tasks: { orderBy: [{ status: "asc" }, { position: "asc" }] },
|
||||
repositories: {
|
||||
include: { connection: { select: { name: true, provider: true, baseUrl: true } } },
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
} satisfies Prisma.ProjectInclude;
|
||||
|
||||
// ── Markdown ─────────────────────────────────────────────────
|
||||
|
||||
const PROVIDER_LABEL: Record<string, string> = {
|
||||
@@ -102,7 +129,9 @@ const TASK_LABEL: Record<string, string> = {
|
||||
* Datei auch ohne Netz vollstaendig ist.
|
||||
*/
|
||||
export function toMarkdown(
|
||||
project: ProjectForExport & { snapshot: RepoSnapshot | null },
|
||||
project: ProjectForExport & {
|
||||
repositories: Array<RepositoryForExport & { snapshot: RepoSnapshot | null }>;
|
||||
},
|
||||
): string {
|
||||
const status = statusOf(project.status);
|
||||
const priority = PRIORITY_META[project.priority] ?? PRIORITY_META[2];
|
||||
@@ -119,22 +148,31 @@ export function toMarkdown(
|
||||
lines.push(`| Tags | ${project.tags.map((tag) => `\`${tag}\``).join(", ")} |`);
|
||||
}
|
||||
lines.push(`| Angelegt | ${formatDateTime(project.createdAt)} |`);
|
||||
if (project.repoUrl) lines.push(`| Repository | ${project.repoUrl} |`);
|
||||
if (project.connection) {
|
||||
const label = PROVIDER_LABEL[project.connection.provider] ?? project.connection.provider;
|
||||
lines.push(`| Git-System | ${label} (${project.connection.baseUrl}) |`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
if (project.description) {
|
||||
lines.push("## Beschreibung", "", project.description, "");
|
||||
}
|
||||
|
||||
const snapshot = project.snapshot;
|
||||
if (snapshot) {
|
||||
lines.push("## Stand des Repositories", "");
|
||||
lines.push(`Abgerufen am ${formatDateTime(snapshot.fetchedAt)}.`, "");
|
||||
for (const repository of project.repositories) {
|
||||
const titel = repoTitle(repository);
|
||||
lines.push(
|
||||
project.repositories.length === 1
|
||||
? "## Repository"
|
||||
: `## Repository: ${titel}`,
|
||||
"",
|
||||
);
|
||||
|
||||
lines.push("| | |", "| --- | --- |");
|
||||
if (repository.repoUrl) lines.push(`| Adresse | ${repository.repoUrl} |`);
|
||||
if (repository.connection) {
|
||||
const label =
|
||||
PROVIDER_LABEL[repository.connection.provider] ?? repository.connection.provider;
|
||||
lines.push(`| Git-System | ${label} (${repository.connection.baseUrl}) |`);
|
||||
}
|
||||
|
||||
const snapshot = repository.snapshot;
|
||||
if (snapshot) {
|
||||
if (snapshot.defaultBranch) lines.push(`| Default-Branch | \`${snapshot.defaultBranch}\` |`);
|
||||
if (snapshot.latestTag) lines.push(`| Neuester Tag | \`${snapshot.latestTag}\` |`);
|
||||
lines.push(`| Branches | ${snapshot.branchCount} |`);
|
||||
@@ -147,6 +185,10 @@ export function toMarkdown(
|
||||
`${snapshot.lastCommitMessage ?? ""} |`,
|
||||
);
|
||||
}
|
||||
lines.push(`| Abgerufen | ${formatDateTime(snapshot.fetchedAt)} |`);
|
||||
} else {
|
||||
lines.push("| Stand | noch nie abgeglichen |");
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,25 @@ export const PROVIDER_META: Record<
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Wie ein Repository in Ueberschriften und Meldungen heisst.
|
||||
*
|
||||
* Steht hier und nicht bei den uebrigen Repository-Helfern, weil die
|
||||
* Oberflaeche sie braucht: lib/repositories zieht Prisma und damit
|
||||
* node:-Module nach, die in einer Client-Komponente nicht landen duerfen.
|
||||
*/
|
||||
export function repoTitle(repo: {
|
||||
label?: string | null;
|
||||
repoOwner?: string | null;
|
||||
repoName?: string | null;
|
||||
repoUrl?: string | null;
|
||||
}): string {
|
||||
if (repo.label) return repo.label;
|
||||
if (repo.repoOwner && repo.repoName) return `${repo.repoOwner}/${repo.repoName}`;
|
||||
if (repo.repoName) return repo.repoName;
|
||||
return repo.repoUrl ?? "Repository";
|
||||
}
|
||||
|
||||
export function guessProvider(host: string): ProviderKind {
|
||||
const lower = host.toLowerCase();
|
||||
if (lower.includes("github")) return "GITHUB";
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import nodemailer from "nodemailer";
|
||||
import type { NotificationTarget } from "@prisma/client";
|
||||
import { tryDecryptSecret } from "@/lib/crypto";
|
||||
import { APP_NAME, APP_URL } from "@/lib/config";
|
||||
import { BlockedHostError, assertAllowedUrl } from "@/lib/security/ssrf";
|
||||
import type { DeliveryResult, NotificationMessage } from "./types";
|
||||
|
||||
/**
|
||||
* Zustellung einer Nachricht ueber den gewaehlten Weg.
|
||||
*
|
||||
* Zwei Dinge gelten fuer alle Wege:
|
||||
* - Die Zieladresse ist eine Benutzereingabe und wird serverseitig
|
||||
* abgerufen. Sie laeuft deshalb durch denselben SSRF-Schutz wie die
|
||||
* Git-Verbindungen. Ein ntfy im eigenen Netz bleibt damit erlaubt,
|
||||
* Loopback und Metadaten-Endpunkte nicht.
|
||||
* - Fehler werden zurueckgegeben, nicht geworfen. Eine kaputte
|
||||
* Benachrichtigung darf einen Abgleich nicht scheitern lassen.
|
||||
*/
|
||||
|
||||
const TIMEOUT_MS = Number(process.env.NOTIFY_TIMEOUT_MS ?? 10_000);
|
||||
|
||||
async function postJson(
|
||||
url: string,
|
||||
body: unknown,
|
||||
headers: Record<string, string>,
|
||||
): Promise<DeliveryResult> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...headers },
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
// Ein Redirect koennte auf ein anderes Ziel fuehren, als geprueft
|
||||
// wurde – deshalb gar nicht erst folgen.
|
||||
redirect: "manual",
|
||||
});
|
||||
if (!response.ok && response.status !== 0) {
|
||||
return { ok: false, message: `Antwort ${response.status} von ${new URL(url).host}` };
|
||||
}
|
||||
return { ok: true, message: `Zugestellt (${response.status})` };
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
return { ok: false, message: `Zeitueberschreitung nach ${TIMEOUT_MS} ms` };
|
||||
}
|
||||
return { ok: false, message: error instanceof Error ? error.message : String(error) };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebhook(
|
||||
target: NotificationTarget,
|
||||
message: NotificationMessage,
|
||||
): Promise<DeliveryResult> {
|
||||
const payload = {
|
||||
source: APP_NAME,
|
||||
event: message.event,
|
||||
title: message.title,
|
||||
body: message.body,
|
||||
url: message.url,
|
||||
project: message.project,
|
||||
at: message.at,
|
||||
};
|
||||
const raw = JSON.stringify(payload);
|
||||
|
||||
const headers: Record<string, string> = { "User-Agent": `${APP_NAME}-Notify` };
|
||||
|
||||
// Mit Geheimnis wird der Rumpf signiert, damit der Empfaenger pruefen
|
||||
// kann, dass die Nachricht wirklich von hier kommt.
|
||||
const secret = tryDecryptSecret(target.secretCipher);
|
||||
if (secret) {
|
||||
headers["X-Nebula-Signature"] = `sha256=${createHmac("sha256", secret).update(raw).digest("hex")}`;
|
||||
}
|
||||
|
||||
return postJson(target.target, raw, headers);
|
||||
}
|
||||
|
||||
async function sendNtfy(
|
||||
target: NotificationTarget,
|
||||
message: NotificationMessage,
|
||||
): Promise<DeliveryResult> {
|
||||
const headers: Record<string, string> = {
|
||||
Title: encodeHeader(message.title),
|
||||
Priority: message.priority === "high" ? "high" : "default",
|
||||
Tags: message.event === "TEST" ? "bell" : "warning",
|
||||
};
|
||||
if (message.url) headers.Click = message.url;
|
||||
|
||||
const secret = tryDecryptSecret(target.secretCipher);
|
||||
if (secret) headers.Authorization = `Bearer ${secret}`;
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(target.target, {
|
||||
method: "POST",
|
||||
// ntfy nimmt den Rumpf als reinen Text.
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8", ...headers },
|
||||
body: message.body,
|
||||
signal: controller.signal,
|
||||
redirect: "manual",
|
||||
});
|
||||
if (!response.ok) {
|
||||
return { ok: false, message: `Antwort ${response.status} von ntfy` };
|
||||
}
|
||||
return { ok: true, message: "An ntfy zugestellt" };
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
return { ok: false, message: `Zeitueberschreitung nach ${TIMEOUT_MS} ms` };
|
||||
}
|
||||
return { ok: false, message: error instanceof Error ? error.message : String(error) };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kopfzeilen duerfen nur Latin-1 enthalten. Emojis werden deshalb entfernt,
|
||||
* nicht durch Fragezeichen ersetzt – aus "🔴 Projekt: CI ist rot" wuerde
|
||||
* sonst "?? Projekt: CI ist rot". Das Sinnbild traegt ohnehin der
|
||||
* Tags-Header, den ntfy selbst in ein Symbol umsetzt.
|
||||
*/
|
||||
function encodeHeader(value: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return value.replace(/[^\x20-\xFF]/g, "").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
export interface SmtpConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
password?: string;
|
||||
from: string;
|
||||
}
|
||||
|
||||
/** Liest die SMTP-Einstellungen aus der Umgebung, falls vorhanden. */
|
||||
export function smtpConfig(): SmtpConfig | null {
|
||||
const host = process.env.SMTP_HOST?.trim();
|
||||
if (!host) return null;
|
||||
|
||||
const port = Number(process.env.SMTP_PORT ?? 587);
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
// Port 465 spricht von Anfang an TLS, 587 steigt per STARTTLS um.
|
||||
secure: process.env.SMTP_SECURE
|
||||
? /^(1|true|yes|on)$/i.test(process.env.SMTP_SECURE)
|
||||
: port === 465,
|
||||
user: process.env.SMTP_USER?.trim() || undefined,
|
||||
password: process.env.SMTP_PASSWORD || undefined,
|
||||
from: process.env.SMTP_FROM?.trim() || `${APP_NAME} <nebula@localhost>`,
|
||||
};
|
||||
}
|
||||
|
||||
export const emailAvailable = () => smtpConfig() !== null;
|
||||
|
||||
async function sendEmail(
|
||||
target: NotificationTarget,
|
||||
message: NotificationMessage,
|
||||
): Promise<DeliveryResult> {
|
||||
const config = smtpConfig();
|
||||
if (!config) {
|
||||
return { ok: false, message: "Kein SMTP hinterlegt – SMTP_HOST in der .env setzen." };
|
||||
}
|
||||
|
||||
try {
|
||||
const transport = nodemailer.createTransport({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.secure,
|
||||
auth: config.user ? { user: config.user, pass: config.password } : undefined,
|
||||
connectionTimeout: TIMEOUT_MS,
|
||||
greetingTimeout: TIMEOUT_MS,
|
||||
});
|
||||
|
||||
const zeilen = [message.body];
|
||||
if (message.url) zeilen.push("", message.url);
|
||||
zeilen.push("", `— ${APP_NAME}, ${APP_URL}`);
|
||||
|
||||
await transport.sendMail({
|
||||
from: config.from,
|
||||
to: target.target,
|
||||
subject: message.title,
|
||||
text: zeilen.join("\n"),
|
||||
});
|
||||
|
||||
return { ok: true, message: `An ${target.target} versendet` };
|
||||
} catch (error) {
|
||||
return { ok: false, message: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
|
||||
/** Stellt eine Nachricht ueber den Weg des Ziels zu. */
|
||||
export async function deliver(
|
||||
target: NotificationTarget,
|
||||
message: NotificationMessage,
|
||||
): Promise<DeliveryResult> {
|
||||
if (target.channel === "EMAIL") return sendEmail(target, message);
|
||||
|
||||
// Webhook und ntfy rufen eine vom Benutzer angegebene Adresse auf.
|
||||
try {
|
||||
await assertAllowedUrl(target.target);
|
||||
} catch (error) {
|
||||
if (error instanceof BlockedHostError) return { ok: false, message: error.message };
|
||||
throw error;
|
||||
}
|
||||
|
||||
return target.channel === "NTFY" ? sendNtfy(target, message) : sendWebhook(target, message);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { NotificationEvent, Project, RepoSnapshot, Repository } from "@prisma/client";
|
||||
import { APP_NAME, APP_URL } from "@/lib/config";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { repoTitle } from "@/lib/repositories";
|
||||
import { deliver } from "./channels";
|
||||
import { EVENT_META, type NotificationMessage } from "./types";
|
||||
|
||||
export * from "./types";
|
||||
export { emailAvailable, smtpConfig } from "./channels";
|
||||
|
||||
/**
|
||||
* Entscheidet nach einem Abgleich, worueber zu benachrichtigen ist, und
|
||||
* stellt zu.
|
||||
*
|
||||
* Gemeldet wird ausschliesslich bei einer **Aenderung** gegenueber dem,
|
||||
* worueber zuletzt benachrichtigt wurde. Sonst kaeme bei einem Repo mit
|
||||
* abgelaufenem Token mit jedem stuendlichen Durchlauf dieselbe Nachricht.
|
||||
* Der zuletzt gemeldete Zustand steht am Repository – nicht am Projekt, sonst
|
||||
* verdeckte ein rotes Frontend die rote Pipeline des Backends.
|
||||
*
|
||||
* Fehler beim Zustellen werden geschluckt: eine kaputte Benachrichtigung
|
||||
* darf den Abgleich nicht scheitern lassen.
|
||||
*/
|
||||
export async function notifyAfterSync(repositoryId: string): Promise<void> {
|
||||
try {
|
||||
const repository = await prisma.repository.findUnique({
|
||||
where: { id: repositoryId },
|
||||
include: { snapshot: true, project: true },
|
||||
});
|
||||
if (!repository?.project.ownerId) return;
|
||||
|
||||
const faellig = pendingEvents(repository.project, repository, repository.snapshot);
|
||||
if (faellig.length === 0) return;
|
||||
|
||||
const ziele = await prisma.notificationTarget.findMany({
|
||||
where: {
|
||||
userId: repository.project.ownerId,
|
||||
isActive: true,
|
||||
events: { hasSome: faellig.map((entry) => entry.event) },
|
||||
},
|
||||
});
|
||||
|
||||
// Auch ohne Ziel den Merkstand fortschreiben: sonst kaeme beim ersten
|
||||
// eingerichteten Ziel gleich die gesamte Vergangenheit hinterher.
|
||||
await prisma.repository.update({
|
||||
where: { id: repository.id },
|
||||
data: {
|
||||
notifiedSyncError: repository.syncError,
|
||||
notifiedCiState: repository.snapshot?.ciState ?? null,
|
||||
notifiedRelease: currentRelease(repository.snapshot),
|
||||
},
|
||||
});
|
||||
|
||||
if (ziele.length === 0) return;
|
||||
|
||||
for (const eintrag of faellig) {
|
||||
const passende = ziele.filter((ziel) => ziel.events.includes(eintrag.event));
|
||||
for (const ziel of passende) {
|
||||
const ergebnis = await deliver(ziel, eintrag.message);
|
||||
await prisma.notificationTarget.update({
|
||||
where: { id: ziel.id },
|
||||
data: {
|
||||
lastSentAt: new Date(),
|
||||
lastOk: ergebnis.ok,
|
||||
lastMessage: ergebnis.message,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[nebula] Benachrichtigung fehlgeschlagen:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function currentRelease(snapshot: RepoSnapshot | null): string | null {
|
||||
if (!snapshot) return null;
|
||||
return snapshot.latestRelease ?? snapshot.latestTag ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vergleicht den aktuellen Stand mit dem zuletzt gemeldeten.
|
||||
* Exportiert, weil hier die eigentliche Entscheidung faellt – siehe Tests.
|
||||
*/
|
||||
export function pendingEvents(
|
||||
project: Project,
|
||||
repository: Repository,
|
||||
snapshot: RepoSnapshot | null,
|
||||
): Array<{ event: NotificationEvent; message: NotificationMessage }> {
|
||||
const treffer: Array<{ event: NotificationEvent; message: NotificationMessage }> = [];
|
||||
const projektUrl = `${APP_URL}/projects/${project.id}`;
|
||||
const bezug = { id: project.id, name: project.name, slug: project.slug };
|
||||
const jetzt = new Date().toISOString();
|
||||
|
||||
/**
|
||||
* Der Betreff nennt das Repository nur, wenn es nicht ohnehin so heisst
|
||||
* wie das Projekt. "nebula – nebula: CI ist rot" liest niemand gern.
|
||||
*/
|
||||
const titel = repoTitle(repository);
|
||||
const woher =
|
||||
titel.toLowerCase() === project.name.toLowerCase() ||
|
||||
titel.toLowerCase().endsWith(`/${project.name.toLowerCase()}`)
|
||||
? project.name
|
||||
: `${project.name} · ${titel}`;
|
||||
|
||||
if (repository.syncError && repository.syncError !== repository.notifiedSyncError) {
|
||||
treffer.push({
|
||||
event: "SYNC_FAILED",
|
||||
message: {
|
||||
event: "SYNC_FAILED",
|
||||
title: `${EVENT_META.SYNC_FAILED.emoji} ${woher}: Abgleich fehlgeschlagen`,
|
||||
body: repository.syncError,
|
||||
priority: "high",
|
||||
url: projektUrl,
|
||||
project: bezug,
|
||||
at: jetzt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const ci = snapshot?.ciState ?? null;
|
||||
if (ci === "failure" && ci !== repository.notifiedCiState) {
|
||||
treffer.push({
|
||||
event: "CI_FAILED",
|
||||
message: {
|
||||
event: "CI_FAILED",
|
||||
title: `${EVENT_META.CI_FAILED.emoji} ${woher}: CI ist rot`,
|
||||
body:
|
||||
`Der letzte Lauf auf ${snapshot?.ciBranch ?? "dem Default-Branch"} ist ` +
|
||||
`fehlgeschlagen${snapshot?.ciName ? ` (${snapshot.ciName})` : ""}.`,
|
||||
priority: "high",
|
||||
url: snapshot?.ciUrl ?? projektUrl,
|
||||
project: bezug,
|
||||
at: jetzt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const release = currentRelease(snapshot);
|
||||
// Beim allerersten Abgleich ist notifiedRelease noch leer – dann waere
|
||||
// jede vorhandene Version eine "Neuigkeit". Deshalb nur melden, wenn
|
||||
// vorher schon einmal etwas festgehalten wurde.
|
||||
if (release && repository.notifiedRelease && release !== repository.notifiedRelease) {
|
||||
treffer.push({
|
||||
event: "NEW_RELEASE",
|
||||
message: {
|
||||
event: "NEW_RELEASE",
|
||||
title: `${EVENT_META.NEW_RELEASE.emoji} ${woher}: ${release}`,
|
||||
body: `Neue Version im Repository: ${release} (vorher ${repository.notifiedRelease}).`,
|
||||
priority: "normal",
|
||||
url: snapshot?.htmlUrl ?? projektUrl,
|
||||
project: bezug,
|
||||
at: jetzt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return treffer;
|
||||
}
|
||||
|
||||
/** Nachricht fuer den Knopf "Testen" an einem Ziel. */
|
||||
export function testMessage(): NotificationMessage {
|
||||
return {
|
||||
event: "TEST",
|
||||
title: `🔔 ${APP_NAME}: Testnachricht`,
|
||||
body:
|
||||
"Wenn du das liest, ist der Zustellweg eingerichtet. " +
|
||||
"Echte Meldungen kommen nur bei einer Aenderung – nicht bei jedem Abgleich.",
|
||||
priority: "normal",
|
||||
url: APP_URL,
|
||||
project: null,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Project, RepoSnapshot, Repository } from "@prisma/client";
|
||||
import { pendingEvents } from "./index";
|
||||
|
||||
/**
|
||||
* Die Entprellung ist der Kern: gemeldet wird nur bei einer Aenderung
|
||||
* gegenueber dem zuletzt gemeldeten Stand. Ohne sie kaeme bei einem Repo mit
|
||||
* abgelaufenem Token mit jedem stuendlichen Durchlauf dieselbe Nachricht.
|
||||
*
|
||||
* Der Merkstand liegt am Repository, nicht am Projekt – sonst verdeckte ein
|
||||
* rotes Frontend die rote Pipeline des Backends.
|
||||
*/
|
||||
|
||||
const PROJEKT: Project = {
|
||||
id: "p1",
|
||||
name: "Testprojekt",
|
||||
slug: "testprojekt",
|
||||
} as Project;
|
||||
|
||||
function repo(overrides: Partial<Repository> = {}): Repository {
|
||||
return {
|
||||
id: "r1",
|
||||
projectId: "p1",
|
||||
label: null,
|
||||
repoOwner: "wer",
|
||||
repoName: "testprojekt",
|
||||
repoUrl: null,
|
||||
syncError: null,
|
||||
notifiedSyncError: null,
|
||||
notifiedCiState: null,
|
||||
notifiedRelease: null,
|
||||
...overrides,
|
||||
} as Repository;
|
||||
}
|
||||
|
||||
function snapshot(overrides: Partial<RepoSnapshot> = {}): RepoSnapshot {
|
||||
return {
|
||||
ciState: null,
|
||||
ciBranch: "main",
|
||||
ciName: null,
|
||||
ciUrl: null,
|
||||
latestTag: null,
|
||||
latestRelease: null,
|
||||
htmlUrl: null,
|
||||
...overrides,
|
||||
} as RepoSnapshot;
|
||||
}
|
||||
|
||||
const events = (r: Repository, s: RepoSnapshot | null) =>
|
||||
pendingEvents(PROJEKT, r, s).map((entry) => entry.event);
|
||||
|
||||
describe("Abgleichsfehler", () => {
|
||||
it("meldet einen neuen Fehler", () => {
|
||||
expect(events(repo({ syncError: "404" }), null)).toEqual(["SYNC_FAILED"]);
|
||||
});
|
||||
|
||||
it("meldet denselben Fehler kein zweites Mal", () => {
|
||||
expect(events(repo({ syncError: "404", notifiedSyncError: "404" }), null)).toEqual([]);
|
||||
});
|
||||
|
||||
it("meldet, wenn sich der Fehler aendert", () => {
|
||||
expect(
|
||||
events(repo({ syncError: "401 Token", notifiedSyncError: "404" }), null),
|
||||
).toEqual(["SYNC_FAILED"]);
|
||||
});
|
||||
|
||||
it("meldet nichts, wenn kein Fehler vorliegt", () => {
|
||||
expect(events(repo({ syncError: null, notifiedSyncError: "404" }), null)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CI", () => {
|
||||
it("meldet den Wechsel auf rot", () => {
|
||||
expect(events(repo(), snapshot({ ciState: "failure" }))).toEqual(["CI_FAILED"]);
|
||||
});
|
||||
|
||||
it("meldet dauerhaft rote CI nur einmal", () => {
|
||||
expect(
|
||||
events(repo({ notifiedCiState: "failure" }), snapshot({ ciState: "failure" })),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("meldet nicht, wenn die CI gruen ist", () => {
|
||||
expect(
|
||||
events(repo({ notifiedCiState: "failure" }), snapshot({ ciState: "success" })),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("meldet erneut, wenn die CI nach gruen wieder rot wird", () => {
|
||||
expect(
|
||||
events(repo({ notifiedCiState: "success" }), snapshot({ ciState: "failure" })),
|
||||
).toEqual(["CI_FAILED"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Release", () => {
|
||||
it("schweigt beim allerersten Abgleich", () => {
|
||||
// Sonst waere jede bereits vorhandene Version eine "Neuigkeit".
|
||||
expect(
|
||||
events(repo({ notifiedRelease: null }), snapshot({ latestTag: "v1.0.0" })),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("meldet eine neue Version", () => {
|
||||
expect(
|
||||
events(repo({ notifiedRelease: "v1.0.0" }), snapshot({ latestTag: "v1.1.0" })),
|
||||
).toEqual(["NEW_RELEASE"]);
|
||||
});
|
||||
|
||||
it("meldet dieselbe Version nicht erneut", () => {
|
||||
expect(
|
||||
events(repo({ notifiedRelease: "v1.1.0" }), snapshot({ latestTag: "v1.1.0" })),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("zieht den Releasenamen dem Tag vor", () => {
|
||||
const treffer = pendingEvents(
|
||||
PROJEKT,
|
||||
repo({ notifiedRelease: "alt" }),
|
||||
snapshot({ latestTag: "v2.0.0", latestRelease: "Zweite Ausgabe" }),
|
||||
);
|
||||
expect(treffer[0].message.title).toContain("Zweite Ausgabe");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Betreff bei mehreren Repositories", () => {
|
||||
it("nennt das Repository nicht, wenn es ohnehin so heisst wie das Projekt", () => {
|
||||
// "Testprojekt · wer/testprojekt: CI ist rot" liest niemand gern.
|
||||
const treffer = pendingEvents(
|
||||
PROJEKT,
|
||||
repo({ repoOwner: "wer", repoName: "testprojekt" }),
|
||||
snapshot({ ciState: "failure" }),
|
||||
);
|
||||
expect(treffer[0].message.title).toContain("Testprojekt: CI ist rot");
|
||||
expect(treffer[0].message.title).not.toContain("wer/");
|
||||
});
|
||||
|
||||
it("nennt es, sobald es sich unterscheidet", () => {
|
||||
const treffer = pendingEvents(
|
||||
PROJEKT,
|
||||
repo({ label: "Backend" }),
|
||||
snapshot({ ciState: "failure" }),
|
||||
);
|
||||
expect(treffer[0].message.title).toContain("Testprojekt · Backend");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mehrere Anlaesse gleichzeitig", () => {
|
||||
it("meldet Fehler und rote CI zusammen", () => {
|
||||
expect(
|
||||
events(repo({ syncError: "Zeitueberschreitung" }), snapshot({ ciState: "failure" })),
|
||||
).toEqual(["SYNC_FAILED", "CI_FAILED"]);
|
||||
});
|
||||
|
||||
it("haengt Projektbezug und Tieflink an jede Nachricht", () => {
|
||||
const treffer = pendingEvents(PROJEKT, repo({ syncError: "404" }), null);
|
||||
expect(treffer[0].message.project?.slug).toBe("testprojekt");
|
||||
expect(treffer[0].message.url).toContain("/projects/p1");
|
||||
expect(treffer[0].message.priority).toBe("high");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { newestCommit } from "./stale";
|
||||
import { daysSince, isStaleDue } from "./stale";
|
||||
|
||||
/**
|
||||
* Die Entscheidung, wann ein Projekt als eingeschlafen gilt – und vor allem,
|
||||
* wann es *nicht* erneut gemeldet wird.
|
||||
*/
|
||||
|
||||
const TAG = 86_400_000;
|
||||
const jetzt = new Date("2026-07-26T12:00:00Z");
|
||||
const vorTagen = (tage: number) => new Date(jetzt.getTime() - tage * TAG);
|
||||
/** Schwelle: 60 Tage. */
|
||||
const cutoff = vorTagen(60);
|
||||
|
||||
describe("isStaleDue", () => {
|
||||
it("meldet ein Projekt, dessen letzter Commit laenger zurueckliegt", () => {
|
||||
expect(isStaleDue({ notifiedStaleAt: null }, vorTagen(90), cutoff)).toBe(true);
|
||||
});
|
||||
|
||||
it("meldet nichts innerhalb der Frist", () => {
|
||||
expect(isStaleDue({ notifiedStaleAt: null }, vorTagen(30), cutoff)).toBe(false);
|
||||
});
|
||||
|
||||
it("meldet nichts genau an der Schwelle", () => {
|
||||
expect(isStaleDue({ notifiedStaleAt: null }, cutoff, cutoff)).toBe(false);
|
||||
});
|
||||
|
||||
it("meldet nichts ohne bekannten letzten Commit", () => {
|
||||
// Ein Projekt ohne Repository oder ohne Snapshot laesst sich nicht
|
||||
// beurteilen – lieber schweigen als raten.
|
||||
expect(isStaleDue({ notifiedStaleAt: null }, null, cutoff)).toBe(false);
|
||||
});
|
||||
|
||||
it("meldet dasselbe Projekt kein zweites Mal", () => {
|
||||
expect(isStaleDue({ notifiedStaleAt: vorTagen(5) }, vorTagen(90), cutoff)).toBe(false);
|
||||
});
|
||||
|
||||
it("meldet erneut, wenn zwischendurch gearbeitet wurde und es wieder still ist", () => {
|
||||
// Gemeldet vor 200 Tagen, danach ein Commit vor 90 Tagen, seitdem Ruhe.
|
||||
expect(isStaleDue({ notifiedStaleAt: vorTagen(200) }, vorTagen(90), cutoff)).toBe(true);
|
||||
});
|
||||
|
||||
it("meldet nicht erneut, wenn der Commit vor der letzten Meldung lag", () => {
|
||||
expect(isStaleDue({ notifiedStaleAt: vorTagen(10) }, vorTagen(90), cutoff)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("daysSince", () => {
|
||||
it("zaehlt volle Tage", () => {
|
||||
expect(daysSince(vorTagen(60), jetzt)).toBe(60);
|
||||
expect(daysSince(vorTagen(1), jetzt)).toBe(1);
|
||||
});
|
||||
|
||||
it("rundet angebrochene Tage ab", () => {
|
||||
expect(daysSince(new Date(jetzt.getTime() - 1.9 * TAG), jetzt)).toBe(1);
|
||||
});
|
||||
|
||||
it("liefert null fuer soeben", () => {
|
||||
expect(daysSince(jetzt, jetzt)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("newestCommit", () => {
|
||||
it("nimmt den juengsten Commit ueber alle Repositories", () => {
|
||||
// An einem Vorhaben wird gearbeitet, sobald an einem seiner Teile
|
||||
// gearbeitet wird – ein ruhendes Backend macht es nicht stillstehend.
|
||||
const juengster = newestCommit([
|
||||
{ lastCommitAt: vorTagen(90) },
|
||||
{ lastCommitAt: vorTagen(3) },
|
||||
{ lastCommitAt: vorTagen(40) },
|
||||
]);
|
||||
expect(daysSince(juengster!, jetzt)).toBe(3);
|
||||
});
|
||||
|
||||
it("uebergeht Repositories ohne Commit-Datum", () => {
|
||||
const juengster = newestCommit([{ lastCommitAt: null }, { lastCommitAt: vorTagen(5) }]);
|
||||
expect(daysSince(juengster!, jetzt)).toBe(5);
|
||||
});
|
||||
|
||||
it("liefert null, wenn nirgends ein Commit bekannt ist", () => {
|
||||
expect(newestCommit([])).toBeNull();
|
||||
expect(newestCommit([{ lastCommitAt: null }])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { Project, RepoSnapshot } from "@prisma/client";
|
||||
import { APP_URL } from "@/lib/config";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { statusOf } from "@/lib/status";
|
||||
import { deliver } from "./channels";
|
||||
import { EVENT_META, type NotificationMessage } from "./types";
|
||||
|
||||
/**
|
||||
* Meldet Projekte, in denen laenger nichts passiert ist.
|
||||
*
|
||||
* Anders als die uebrigen Anlaesse haengt dieser an keinem Ereignis – es
|
||||
* passiert ja gerade nichts. Deshalb ein eigener Durchlauf, hoechstens
|
||||
* einmal am Tag.
|
||||
*
|
||||
* Massstab ist ausschliesslich der letzte Commit in den verknuepften
|
||||
* Repositories. Das Aenderungsdatum des Projekts taugt nicht: jeder Abgleich
|
||||
* fasst es an und wuerde den Stillstand immer wieder zuruecksetzen.
|
||||
* Projekte ohne Repository bleiben folglich aussen vor.
|
||||
*
|
||||
* Bei mehreren Repositories zaehlt der juengste Commit. Ein Vorhaben steht
|
||||
* nicht still, solange an einem seiner Teile gearbeitet wird.
|
||||
*/
|
||||
|
||||
export interface StaleReport {
|
||||
at: string;
|
||||
checked: number;
|
||||
stale: number;
|
||||
notified: number;
|
||||
thresholdDays: number;
|
||||
}
|
||||
|
||||
/** Entscheidet, ob ein Projekt jetzt zu melden ist. */
|
||||
export function isStaleDue(
|
||||
project: Pick<Project, "notifiedStaleAt">,
|
||||
lastCommitAt: Date | null,
|
||||
cutoff: Date,
|
||||
): boolean {
|
||||
// Ohne bekannten letzten Commit gibt es nichts zu beurteilen.
|
||||
if (!lastCommitAt) return false;
|
||||
// Noch innerhalb der Frist.
|
||||
if (lastCommitAt >= cutoff) return false;
|
||||
// Noch nie gemeldet: jetzt.
|
||||
if (!project.notifiedStaleAt) return true;
|
||||
// Schon gemeldet – erneut nur, wenn danach wieder ein Commit kam und es
|
||||
// seitdem wieder still geworden ist.
|
||||
return lastCommitAt > project.notifiedStaleAt;
|
||||
}
|
||||
|
||||
/** Wie viele volle Tage seit dem letzten Commit vergangen sind. */
|
||||
export function daysSince(date: Date, now: Date = new Date()): number {
|
||||
return Math.floor((now.getTime() - date.getTime()) / 86_400_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Der juengste Commit ueber alle Repositories hinweg. Massgeblich ist das
|
||||
* regste Repo: an einem Vorhaben wird gearbeitet, sobald an irgendeinem
|
||||
* seiner Teile gearbeitet wird.
|
||||
*/
|
||||
export function newestCommit(
|
||||
snapshots: Array<{ lastCommitAt: Date | null }>,
|
||||
): Date | null {
|
||||
let juengster: Date | null = null;
|
||||
for (const snapshot of snapshots) {
|
||||
if (!snapshot.lastCommitAt) continue;
|
||||
if (!juengster || snapshot.lastCommitAt > juengster) juengster = snapshot.lastCommitAt;
|
||||
}
|
||||
return juengster;
|
||||
}
|
||||
|
||||
function message(
|
||||
project: Project,
|
||||
snapshot: RepoSnapshot | null,
|
||||
tage: number,
|
||||
): NotificationMessage {
|
||||
return {
|
||||
event: "PROJECT_STALE",
|
||||
title: `${EVENT_META.PROJECT_STALE.emoji} ${project.name}: seit ${tage} Tagen kein Commit`,
|
||||
body:
|
||||
`Der letzte Commit liegt ${tage} Tage zurueck. ` +
|
||||
`Status: ${statusOf(project.status).label}. Vielleicht abschliessen oder archivieren?`,
|
||||
priority: "normal",
|
||||
url: snapshot?.htmlUrl ?? `${APP_URL}/projects/${project.id}`,
|
||||
project: { id: project.id, name: project.name, slug: project.slug },
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Durchlauf. Meldet je Projekt hoechstens einmal und schreibt den
|
||||
* Merkstand fort – auch dann, wenn niemand zuhoert.
|
||||
*/
|
||||
export async function runStaleCheck(thresholdDays: number): Promise<StaleReport> {
|
||||
const now = new Date();
|
||||
const cutoff = new Date(now.getTime() - thresholdDays * 86_400_000);
|
||||
|
||||
const kandidaten = await prisma.project.findMany({
|
||||
where: {
|
||||
// Fertige und archivierte Projekte duerfen ruhen.
|
||||
status: { notIn: ["DONE", "ARCHIVED"] },
|
||||
ownerId: { not: null },
|
||||
repositories: { some: { snapshot: { isNot: null } } },
|
||||
},
|
||||
include: {
|
||||
repositories: {
|
||||
include: { snapshot: true },
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const letzterCommit = new Map(
|
||||
kandidaten.map((project) => [
|
||||
project.id,
|
||||
newestCommit(project.repositories.map((repo) => repo.snapshot).filter((s) => s !== null)),
|
||||
]),
|
||||
);
|
||||
|
||||
const faellig = kandidaten.filter((project) =>
|
||||
isStaleDue(project, letzterCommit.get(project.id) ?? null, cutoff),
|
||||
);
|
||||
|
||||
let zugestellt = 0;
|
||||
|
||||
for (const project of faellig) {
|
||||
const lastCommitAt = letzterCommit.get(project.id);
|
||||
if (!lastCommitAt || !project.ownerId) continue;
|
||||
// Fuer den Link in der Meldung reicht das fuehrende Repository.
|
||||
const snapshot = project.repositories[0]?.snapshot ?? null;
|
||||
|
||||
const ziele = await prisma.notificationTarget.findMany({
|
||||
where: { userId: project.ownerId, isActive: true, events: { has: "PROJECT_STALE" } },
|
||||
});
|
||||
|
||||
for (const ziel of ziele) {
|
||||
const ergebnis = await deliver(
|
||||
ziel,
|
||||
message(project, snapshot, daysSince(lastCommitAt, now)),
|
||||
);
|
||||
zugestellt += 1;
|
||||
await prisma.notificationTarget.update({
|
||||
where: { id: ziel.id },
|
||||
data: { lastSentAt: now, lastOk: ergebnis.ok, lastMessage: ergebnis.message },
|
||||
});
|
||||
}
|
||||
|
||||
// Auch ohne Ziel vermerken, sonst kaeme beim ersten eingerichteten Ziel
|
||||
// die gesamte Vergangenheit hinterher.
|
||||
await prisma.project.update({
|
||||
where: { id: project.id },
|
||||
data: { notifiedStaleAt: now },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
at: now.toISOString(),
|
||||
checked: kandidaten.length,
|
||||
stale: faellig.length,
|
||||
notified: zugestellt,
|
||||
thresholdDays,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { NotificationEvent } from "@prisma/client";
|
||||
|
||||
/** Reihenfolge fuer die Oberflaeche. */
|
||||
export const NOTIFICATION_EVENTS: NotificationEvent[] = [
|
||||
"SYNC_FAILED",
|
||||
"CI_FAILED",
|
||||
"NEW_RELEASE",
|
||||
"PROJECT_STALE",
|
||||
];
|
||||
|
||||
export const EVENT_META: Record<
|
||||
NotificationEvent,
|
||||
{ label: string; description: string; emoji: string }
|
||||
> = {
|
||||
SYNC_FAILED: {
|
||||
label: "Abgleich fehlgeschlagen",
|
||||
description: "Das Git-System war nicht erreichbar oder hat abgelehnt.",
|
||||
emoji: "⚠️",
|
||||
},
|
||||
CI_FAILED: {
|
||||
label: "CI rot",
|
||||
description: "Der letzte Lauf auf dem Default-Branch ist fehlgeschlagen.",
|
||||
emoji: "🔴",
|
||||
},
|
||||
NEW_RELEASE: {
|
||||
label: "Neues Release",
|
||||
description: "Im Repository ist ein neuer Tag oder ein Release aufgetaucht.",
|
||||
emoji: "🏷️",
|
||||
},
|
||||
PROJECT_STALE: {
|
||||
label: "Projekt steht still",
|
||||
description: "Seit laengerem kein Commit mehr. Die Schwelle setzt ein Administrator.",
|
||||
emoji: "🕸️",
|
||||
},
|
||||
};
|
||||
|
||||
/** Eine fertig formulierte Nachricht, unabhaengig vom Zustellweg. */
|
||||
export interface NotificationMessage {
|
||||
event: NotificationEvent | "TEST";
|
||||
title: string;
|
||||
body: string;
|
||||
/** Fuer ntfy: hoehere Zahl bedeutet auffaelliger. */
|
||||
priority: "normal" | "high";
|
||||
/** Link zurueck ins Dashboard oder ins Repository. */
|
||||
url: string | null;
|
||||
project: { id: string; name: string; slug: string } | null;
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface DeliveryResult {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Felder eines Ziels, die an den Browser gehen duerfen – ohne Chiffrat.
|
||||
* Liegt hier und nicht in der Route: Next laesst in route.ts nur bestimmte
|
||||
* Exporte zu und bricht den Bau bei allem anderen ab.
|
||||
*/
|
||||
export const targetSafeSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
channel: true,
|
||||
target: true,
|
||||
secretHint: true,
|
||||
events: true,
|
||||
isActive: true,
|
||||
lastSentAt: true,
|
||||
lastOk: true,
|
||||
lastMessage: true,
|
||||
createdAt: true,
|
||||
} as const;
|
||||
+25
-4
@@ -46,9 +46,19 @@ export const connectionSafeSelect = Prisma.validator<Prisma.GitConnectionSelect>
|
||||
updatedAt: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* Ein Repository mitsamt Verbindung und Stand. Die Reihenfolge ist ueberall
|
||||
* dieselbe: das fuehrende zuerst, denn auf der Karte ist nur fuer eines Platz.
|
||||
*/
|
||||
export const repositoryInclude = Prisma.validator<Prisma.ProjectInclude>()({
|
||||
repositories: {
|
||||
include: { connection: { select: connectionSafeSelect }, snapshot: true },
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
});
|
||||
|
||||
export const projectListInclude = Prisma.validator<Prisma.ProjectInclude>()({
|
||||
connection: { select: connectionSafeSelect },
|
||||
snapshot: true,
|
||||
...repositoryInclude,
|
||||
_count: { select: { notes: true, tasks: true } },
|
||||
// Nur die offenen Aufgaben zaehlen – fuer die Anzeige "3 von 8" auf der
|
||||
// Karte, ohne die Aufgaben selbst mitzuladen.
|
||||
@@ -56,13 +66,24 @@ export const projectListInclude = Prisma.validator<Prisma.ProjectInclude>()({
|
||||
});
|
||||
|
||||
export const projectDetailInclude = Prisma.validator<Prisma.ProjectInclude>()({
|
||||
connection: { select: connectionSafeSelect },
|
||||
snapshot: true,
|
||||
...repositoryInclude,
|
||||
notes: {
|
||||
orderBy: [{ pinned: "desc" }, { updatedAt: "desc" }],
|
||||
},
|
||||
tasks: {
|
||||
orderBy: [{ status: "asc" }, { position: "asc" }],
|
||||
},
|
||||
// Erste Seite des Verlaufs; weitere holt die Anzeige bei Bedarf nach.
|
||||
activities: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
summary: true,
|
||||
createdAt: true,
|
||||
user: { select: { username: true, displayName: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { notes: true, tasks: true } },
|
||||
});
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { repoTitle } from "./git/meta";
|
||||
import { completeRepoInput, namesRepository } from "./repositories";
|
||||
|
||||
describe("completeRepoInput", () => {
|
||||
it("leitet Owner und Name aus der URL ab", () => {
|
||||
expect(completeRepoInput({ repoUrl: "https://github.com/vercel/swr" })).toMatchObject({
|
||||
repoOwner: "vercel",
|
||||
repoName: "swr",
|
||||
});
|
||||
});
|
||||
|
||||
it("laesst ausdruecklich gesetzte Werte in Ruhe", () => {
|
||||
// Bei GitLab-Untergruppen weiss der Benutzer es besser als die Ableitung.
|
||||
expect(
|
||||
completeRepoInput({
|
||||
repoUrl: "https://gitlab.com/gruppe/untergruppe/dings",
|
||||
repoOwner: "gruppe/untergruppe",
|
||||
repoName: "dings",
|
||||
}),
|
||||
).toMatchObject({ repoOwner: "gruppe/untergruppe", repoName: "dings" });
|
||||
});
|
||||
|
||||
it("kommt ohne URL und mit unbrauchbarer URL zurecht", () => {
|
||||
expect(completeRepoInput({ repoOwner: "a", repoName: "b" }).repoUrl).toBeUndefined();
|
||||
expect(completeRepoInput({ repoUrl: "kein-link" }).repoOwner).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("namesRepository", () => {
|
||||
it("erkennt, wann ueberhaupt ein Repo benannt wurde", () => {
|
||||
expect(namesRepository({ repoUrl: "https://github.com/a/b" })).toBe(true);
|
||||
expect(namesRepository({ repoOwner: "a", repoName: "b" })).toBe(true);
|
||||
});
|
||||
|
||||
it("laesst Halbes nicht durchgehen", () => {
|
||||
// Ein Owner ohne Namen ergibt kein Repository, sondern eine leere Zeile.
|
||||
expect(namesRepository({})).toBe(false);
|
||||
expect(namesRepository({ repoOwner: "a" })).toBe(false);
|
||||
expect(namesRepository({ label: "Frontend" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("repoTitle", () => {
|
||||
it("zieht die Bezeichnung allem anderen vor", () => {
|
||||
expect(repoTitle({ label: "Frontend", repoOwner: "a", repoName: "b" })).toBe("Frontend");
|
||||
});
|
||||
|
||||
it("faellt ueber owner/name auf die URL zurueck", () => {
|
||||
expect(repoTitle({ repoOwner: "vercel", repoName: "swr" })).toBe("vercel/swr");
|
||||
expect(repoTitle({ repoName: "swr" })).toBe("swr");
|
||||
expect(repoTitle({ repoUrl: "https://example.com/x" })).toBe("https://example.com/x");
|
||||
expect(repoTitle({})).toBe("Repository");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { parseRepoUrl } from "@/lib/git";
|
||||
import { repoTitle } from "@/lib/git/meta";
|
||||
|
||||
// Der Titel steht in lib/git/meta, weil ihn auch Client-Komponenten
|
||||
// brauchen – dieses Modul zieht Prisma nach. Hier weitergereicht, damit
|
||||
// serverseitiger Code nur eine Anlaufstelle hat.
|
||||
export { repoTitle };
|
||||
|
||||
/**
|
||||
* Ein Projekt kann mehrere Repositories haben – Frontend und Backend etwa,
|
||||
* aber ein Vorhaben.
|
||||
*
|
||||
* Das erste (position 0) ist das fuehrende. Wo nur eines dargestellt werden
|
||||
* kann, ist es dieses: auf der Karte im Dashboard, im Kopf der Projektseite
|
||||
* und in allem, was die alte Projekt-API weiterhin annimmt.
|
||||
*/
|
||||
|
||||
/** Angaben, aus denen ein Repository entsteht. */
|
||||
export interface RepoInput {
|
||||
label?: string | null;
|
||||
repoUrl?: string | null;
|
||||
repoOwner?: string | null;
|
||||
repoName?: string | null;
|
||||
connectionId?: string | null;
|
||||
autoSync?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ergaenzt Owner und Name aus der URL, wenn sie nicht angegeben wurden.
|
||||
* Ohne das muesste man beides von Hand eintragen, obwohl es in der URL steht.
|
||||
*/
|
||||
export function completeRepoInput(input: RepoInput): RepoInput {
|
||||
if (!input.repoUrl || (input.repoOwner && input.repoName)) return input;
|
||||
|
||||
const parsed = parseRepoUrl(input.repoUrl);
|
||||
if (!parsed) return input;
|
||||
|
||||
return {
|
||||
...input,
|
||||
repoOwner: input.repoOwner ?? parsed.owner,
|
||||
repoName: input.repoName ?? parsed.name,
|
||||
};
|
||||
}
|
||||
|
||||
/** Hat die Eingabe ueberhaupt ein Repository benannt? */
|
||||
export function namesRepository(input: RepoInput): boolean {
|
||||
return Boolean(input.repoUrl || (input.repoOwner && input.repoName));
|
||||
}
|
||||
|
||||
/** Prueft Existenz und Besitz in einem Zug – ueber das Projekt. */
|
||||
export async function ownedRepository(repositoryId: string, ownerId: string) {
|
||||
return prisma.repository.findFirst({
|
||||
where: { id: repositoryId, project: { ownerId } },
|
||||
});
|
||||
}
|
||||
|
||||
/** Naechste freie Position am Ende der Liste. */
|
||||
export async function nextRepoPosition(projectId: string): Promise<number> {
|
||||
const last = await prisma.repository.findFirst({
|
||||
where: { projectId },
|
||||
orderBy: { position: "desc" },
|
||||
select: { position: true },
|
||||
});
|
||||
return (last?.position ?? -1) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt die Angaben am fuehrenden Repository – und legt es an, falls es noch
|
||||
* keines gibt.
|
||||
*
|
||||
* Damit bleibt die Projekt-API unveraendert bedienbar: wer beim Anlegen oder
|
||||
* Bearbeiten eine Repo-URL mitgibt, bekommt weiterhin das erwartete Ergebnis,
|
||||
* ohne von der neuen Tabelle wissen zu muessen.
|
||||
*
|
||||
* Eine geleerte URL entfernt das Repository nicht, sondern raeumt nur seine
|
||||
* Felder – der gesammelte Stand haengt daran, und ein versehentlich
|
||||
* geleertes Feld soll ihn nicht mitnehmen.
|
||||
*/
|
||||
export async function applyLeadingRepo(projectId: string, input: RepoInput): Promise<void> {
|
||||
const vollstaendig = completeRepoInput(input);
|
||||
|
||||
const fuehrend = await prisma.repository.findFirst({
|
||||
where: { projectId },
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!fuehrend) {
|
||||
if (!namesRepository(vollstaendig)) return;
|
||||
await prisma.repository.create({
|
||||
data: {
|
||||
projectId,
|
||||
label: vollstaendig.label ?? null,
|
||||
repoUrl: vollstaendig.repoUrl ?? null,
|
||||
repoOwner: vollstaendig.repoOwner ?? null,
|
||||
repoName: vollstaendig.repoName ?? null,
|
||||
connectionId: vollstaendig.connectionId ?? null,
|
||||
autoSync: vollstaendig.autoSync ?? true,
|
||||
position: 0,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
if (vollstaendig.label !== undefined) data.label = vollstaendig.label;
|
||||
if (vollstaendig.repoUrl !== undefined) data.repoUrl = vollstaendig.repoUrl;
|
||||
if (vollstaendig.repoOwner !== undefined) data.repoOwner = vollstaendig.repoOwner;
|
||||
if (vollstaendig.repoName !== undefined) data.repoName = vollstaendig.repoName;
|
||||
if (vollstaendig.connectionId !== undefined) data.connectionId = vollstaendig.connectionId;
|
||||
if (vollstaendig.autoSync !== undefined) data.autoSync = vollstaendig.autoSync;
|
||||
|
||||
if (Object.keys(data).length === 0) return;
|
||||
await prisma.repository.update({ where: { id: fuehrend.id }, data });
|
||||
}
|
||||
+146
-27
@@ -1,6 +1,9 @@
|
||||
import type { Project } from "@prisma/client";
|
||||
import type { Repository } from "@prisma/client";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { clientForConnection, createClient, parseRepoUrl } from "@/lib/git";
|
||||
import { notifyAfterSync } from "@/lib/notify";
|
||||
import { repoTitle } from "@/lib/repositories";
|
||||
import type { RepoSnapshotData } from "@/lib/git/types";
|
||||
|
||||
export interface SyncResult {
|
||||
@@ -10,21 +13,21 @@ export interface SyncResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Holt den aktuellen Stand des verknuepften Repositories und schreibt ihn
|
||||
* als Snapshot in die Datenbank. Fehler werden am Projekt vermerkt statt
|
||||
* geworfen, damit ein kaputtes Repo nicht das ganze Dashboard blockiert.
|
||||
* Holt den aktuellen Stand eines Repositories und schreibt ihn als Snapshot
|
||||
* in die Datenbank. Fehler werden am Repository vermerkt statt geworfen,
|
||||
* damit ein kaputtes Repo nicht das ganze Dashboard blockiert.
|
||||
*/
|
||||
export async function syncProject(projectId: string): Promise<SyncResult> {
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: projectId },
|
||||
export async function syncRepository(repositoryId: string): Promise<SyncResult> {
|
||||
const repository = await prisma.repository.findUnique({
|
||||
where: { id: repositoryId },
|
||||
include: { connection: true },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return { ok: false, message: "Projekt nicht gefunden." };
|
||||
if (!repository) {
|
||||
return { ok: false, message: "Repository nicht gefunden." };
|
||||
}
|
||||
|
||||
const ref = resolveRepoRef(project);
|
||||
const ref = resolveRepoRef(repository);
|
||||
if (!ref) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -33,11 +36,11 @@ export async function syncProject(projectId: string): Promise<SyncResult> {
|
||||
}
|
||||
|
||||
let client;
|
||||
if (project.connection) {
|
||||
client = clientForConnection(project.connection);
|
||||
if (repository.connection) {
|
||||
client = clientForConnection(repository.connection);
|
||||
} else {
|
||||
// Ohne gespeicherte Verbindung: anonymer Zugriff anhand der URL.
|
||||
const parsed = project.repoUrl ? parseRepoUrl(project.repoUrl) : null;
|
||||
const parsed = repository.repoUrl ? parseRepoUrl(repository.repoUrl) : null;
|
||||
if (!parsed) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -53,7 +56,9 @@ export async function syncProject(projectId: string): Promise<SyncResult> {
|
||||
|
||||
try {
|
||||
const data = await client.fetchRepo(ref);
|
||||
await persistSnapshot(project.id, data);
|
||||
await persistSnapshot(repository, data);
|
||||
// Nach dem Speichern, damit die Meldung den neuen Stand sieht.
|
||||
await notifyAfterSync(repository.id);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Snapshot aktualisiert: ${data.branches.length} Branches, ${data.tags.length} Tags.`,
|
||||
@@ -61,8 +66,8 @@ export async function syncProject(projectId: string): Promise<SyncResult> {
|
||||
};
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
await prisma.project.update({
|
||||
where: { id: project.id },
|
||||
await prisma.repository.update({
|
||||
where: { id: repository.id },
|
||||
data: {
|
||||
syncError: message,
|
||||
lastSyncedAt: new Date(),
|
||||
@@ -70,23 +75,122 @@ export async function syncProject(projectId: string): Promise<SyncResult> {
|
||||
syncFailureCount: { increment: 1 },
|
||||
},
|
||||
});
|
||||
// Nur der Uebergang in den Fehlerzustand kommt in den Verlauf. Ein Repo
|
||||
// mit abgelaufenem Token schlaegt sonst stuendlich neu auf.
|
||||
if (!repository.syncError) {
|
||||
await recordActivity({
|
||||
projectId: repository.projectId,
|
||||
kind: "SYNC_FAILED",
|
||||
summary: `Abgleich von ${repoTitle(repository)} fehlgeschlagen: ${shorten(message, 100)}`,
|
||||
});
|
||||
}
|
||||
await notifyAfterSync(repository.id);
|
||||
return { ok: false, message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Owner/Name aus den Feldern oder ersatzweise aus der URL bestimmen. */
|
||||
export function resolveRepoRef(project: Project) {
|
||||
if (project.repoOwner && project.repoName) {
|
||||
return { owner: project.repoOwner, name: project.repoName };
|
||||
export interface ProjectSyncResult extends SyncResult {
|
||||
/** Ergebnis je Repository – auch dann, wenn nur eines dranhaengt. */
|
||||
repositories: Array<{ id: string; title: string } & SyncResult>;
|
||||
}
|
||||
if (project.repoUrl) {
|
||||
const parsed = parseRepoUrl(project.repoUrl);
|
||||
|
||||
/**
|
||||
* Gleicht alle Repositories eines Projekts ab, nacheinander.
|
||||
*
|
||||
* Nacheinander und nicht parallel: die Repos eines Projekts liegen meist
|
||||
* beim selben Anbieter, und ein Schwung gleichzeitiger Anfragen ist genau
|
||||
* das, worauf Rate-Limits reagieren.
|
||||
*/
|
||||
export async function syncProject(projectId: string): Promise<ProjectSyncResult> {
|
||||
const repositories = await prisma.repository.findMany({
|
||||
where: { projectId },
|
||||
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
|
||||
});
|
||||
|
||||
if (repositories.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Kein Repository hinterlegt – bitte eines verknuepfen.",
|
||||
repositories: [],
|
||||
};
|
||||
}
|
||||
|
||||
const ergebnisse = [];
|
||||
for (const repository of repositories) {
|
||||
ergebnisse.push({
|
||||
id: repository.id,
|
||||
title: repoTitle(repository),
|
||||
...(await syncRepository(repository.id)),
|
||||
});
|
||||
}
|
||||
|
||||
const fehler = ergebnisse.filter((entry) => !entry.ok);
|
||||
|
||||
return {
|
||||
// Erfolgreich nur, wenn kein einziges Repo gescheitert ist. Ein "teilweise
|
||||
// ok" waere eine Meldung, die man wegklickt, ohne hinzusehen.
|
||||
ok: fehler.length === 0,
|
||||
message:
|
||||
fehler.length === 0
|
||||
? ergebnisse.length === 1
|
||||
? ergebnisse[0].message
|
||||
: `${ergebnisse.length} Repositories abgeglichen.`
|
||||
: fehler.map((entry) => `${entry.title}: ${entry.message}`).join(" · "),
|
||||
fetchedAt: new Date().toISOString(),
|
||||
repositories: ergebnisse,
|
||||
};
|
||||
}
|
||||
|
||||
/** Owner/Name aus den Feldern oder ersatzweise aus der URL bestimmen. */
|
||||
export function resolveRepoRef(
|
||||
repository: Pick<Repository, "repoOwner" | "repoName" | "repoUrl">,
|
||||
) {
|
||||
if (repository.repoOwner && repository.repoName) {
|
||||
return { owner: repository.repoOwner, name: repository.repoName };
|
||||
}
|
||||
if (repository.repoUrl) {
|
||||
const parsed = parseRepoUrl(repository.repoUrl);
|
||||
if (parsed) return { owner: parsed.owner, name: parsed.name };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function persistSnapshot(projectId: string, data: RepoSnapshotData) {
|
||||
/**
|
||||
* Haelt neue Commits im Verlauf fest.
|
||||
*
|
||||
* Der Abgleich laeuft im Zweifel stuendlich, ein Eintrag je Durchlauf waere
|
||||
* also unbrauchbar. Vermerkt wird nur, wenn sich der letzte Commit tatsaechlich
|
||||
* geaendert hat – und beim allerersten Abgleich gar nicht: dass ein Repo
|
||||
* Commits hat, ist keine Neuigkeit.
|
||||
*/
|
||||
async function noteNewCommits(
|
||||
repository: Repository,
|
||||
vorher: string | null,
|
||||
data: RepoSnapshotData,
|
||||
) {
|
||||
const neuester = data.commits[0]?.sha ?? null;
|
||||
if (!neuester || !vorher || neuester === vorher) return;
|
||||
|
||||
// Wie viele Commits liegen zwischen altem und neuem Stand? Steht der alte
|
||||
// nicht mehr in der Liste, waren es mehr als eine Seite – dann lieber ohne
|
||||
// Zahl als mit einer falschen.
|
||||
const index = data.commits.findIndex((commit) => commit.sha === vorher);
|
||||
const anzahl = index > 0 ? index : null;
|
||||
const wo = data.defaultBranch ? `${repoTitle(repository)} · ${data.defaultBranch}` : repoTitle(repository);
|
||||
const betreff = shorten(data.commits[0]?.message ?? "", 60);
|
||||
|
||||
await recordActivity({
|
||||
projectId: repository.projectId,
|
||||
kind: "REPO_COMMITS",
|
||||
summary:
|
||||
anzahl === null
|
||||
? `Neue Commits in ${wo}: ${betreff}`
|
||||
: `${anzahl} neue${anzahl === 1 ? "r" : ""} Commit${anzahl === 1 ? "" : "s"} in ${wo}: ${betreff}`,
|
||||
meta: { repositoryId: repository.id, from: vorher, to: neuester, count: anzahl },
|
||||
});
|
||||
}
|
||||
|
||||
async function persistSnapshot(repository: Repository, data: RepoSnapshotData) {
|
||||
const latestCommit = data.commits[0] ?? null;
|
||||
const latestRelease =
|
||||
data.releases.find((release) => !release.draft && !release.prerelease) ?? data.releases[0] ?? null;
|
||||
@@ -129,14 +233,20 @@ async function persistSnapshot(projectId: string, data: RepoSnapshotData) {
|
||||
fetchedAt: new Date(),
|
||||
};
|
||||
|
||||
// Vor dem Ueberschreiben lesen – danach ist der alte Stand weg.
|
||||
const vorher = await prisma.repoSnapshot.findUnique({
|
||||
where: { repositoryId: repository.id },
|
||||
select: { lastCommitSha: true },
|
||||
});
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.repoSnapshot.upsert({
|
||||
where: { projectId },
|
||||
create: { projectId, ...payload },
|
||||
where: { repositoryId: repository.id },
|
||||
create: { repositoryId: repository.id, ...payload },
|
||||
update: payload,
|
||||
}),
|
||||
prisma.project.update({
|
||||
where: { id: projectId },
|
||||
prisma.repository.update({
|
||||
where: { id: repository.id },
|
||||
data: {
|
||||
lastSyncedAt: new Date(),
|
||||
syncError: null,
|
||||
@@ -145,5 +255,14 @@ async function persistSnapshot(projectId: string, data: RepoSnapshotData) {
|
||||
repoUrl: data.htmlUrl ?? undefined,
|
||||
},
|
||||
}),
|
||||
// Das Projekt mit anfassen. Solange die Git-Felder daran hingen, geschah
|
||||
// das nebenbei; jetzt muss es ausdruecklich passieren, sonst faellt ein
|
||||
// regelmaessig abgeglichenes Projekt in der Sortierung nach hinten.
|
||||
prisma.project.update({
|
||||
where: { id: repository.projectId },
|
||||
data: { updatedAt: new Date() },
|
||||
}),
|
||||
]);
|
||||
|
||||
await noteNewCommits(repository, vorher?.lastCommitSha ?? null, data);
|
||||
}
|
||||
|
||||
+70
-16
@@ -1,7 +1,9 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { pruneActivities } from "@/lib/activity";
|
||||
import { getAppSettings } from "@/lib/auth/settings";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { syncProject } from "@/lib/sync";
|
||||
import { runStaleCheck } from "@/lib/notify/stale";
|
||||
import { syncRepository } from "@/lib/sync";
|
||||
|
||||
/**
|
||||
* Automatischer Abgleich mit den Git-Systemen.
|
||||
@@ -20,6 +22,8 @@ import { syncProject } from "@/lib/sync";
|
||||
*/
|
||||
|
||||
const TICK_MS = 60_000;
|
||||
/** Stillstand aendert sich langsam – einmal am Tag genuegt. */
|
||||
const STALE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
||||
/** Kleine Verschnaufpause zwischen zwei Projekten. */
|
||||
const PAUSE_MS = 400;
|
||||
/** Hoechstens so lange wird nach Fehlschlaegen zurueckgehalten. */
|
||||
@@ -64,18 +68,65 @@ export function startAutoSyncScheduler() {
|
||||
async function tick() {
|
||||
try {
|
||||
const settings = await getAppSettings();
|
||||
if (!settings.autoSyncEnabled) return;
|
||||
|
||||
if (settings.autoSyncEnabled) {
|
||||
const intervalMs = Math.max(5, settings.autoSyncIntervalMinutes) * 60_000;
|
||||
const last = settings.lastAutoSyncAt?.getTime() ?? 0;
|
||||
if (Date.now() - last < intervalMs) return;
|
||||
|
||||
if (Date.now() - last >= intervalMs) {
|
||||
await runAutoSyncPass("zeitplan");
|
||||
}
|
||||
}
|
||||
|
||||
// Unabhaengig vom Abgleich: beides ergibt sich aus dem gespeicherten
|
||||
// Stand, dafuer muss nichts geholt werden.
|
||||
await dailyChores();
|
||||
} catch (error) {
|
||||
console.error("[nebula] Automatischer Abgleich fehlgeschlagen:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Was hoechstens einmal am Tag zu tun ist: den Verlauf stutzen und nach
|
||||
* stillstehenden Projekten sehen.
|
||||
*/
|
||||
async function dailyChores() {
|
||||
const settings = await getAppSettings();
|
||||
const last = settings.lastStaleCheckAt?.getTime() ?? 0;
|
||||
if (Date.now() - last < STALE_CHECK_INTERVAL_MS) return;
|
||||
|
||||
const zuhoerer = await prisma.notificationTarget.count({
|
||||
where: { isActive: true, events: { has: "PROJECT_STALE" } },
|
||||
});
|
||||
|
||||
// Zeitstempel auch ohne Zuhoerer setzen, damit nicht jede Minute gezaehlt
|
||||
// wird.
|
||||
await prisma.appSettings.update({
|
||||
where: { id: "singleton" },
|
||||
data: { lastStaleCheckAt: new Date() },
|
||||
});
|
||||
|
||||
// Der Verlauf waechst mit jeder Aenderung; einmal am Tag zurueckschneiden
|
||||
// reicht, um ihn beschraenkt zu halten.
|
||||
try {
|
||||
const entfernt = await pruneActivities();
|
||||
if (entfernt > 0) console.log(`[nebula] Verlauf gestutzt: ${entfernt} Eintraege entfernt.`);
|
||||
} catch (error) {
|
||||
console.error("[nebula] Verlauf konnte nicht gestutzt werden:", error);
|
||||
}
|
||||
|
||||
// Die Stillstandspruefung laeuft nur, wenn jemand zuhoert – sonst waere sie
|
||||
// reine Datenbanklast.
|
||||
if (zuhoerer === 0) return;
|
||||
|
||||
const report = await runStaleCheck(Math.max(1, settings.staleAfterDays));
|
||||
if (report.stale > 0) {
|
||||
console.log(
|
||||
`[nebula] Stillstand: ${report.stale} von ${report.checked} Projekten ` +
|
||||
`ueber ${report.thresholdDays} Tage ohne Commit, ${report.notified} Meldungen.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Durchlauf. Laeuft nie zweimal gleichzeitig – ein zweiter Aufruf
|
||||
* waehrend eines laufenden Durchlaufs bekommt null zurueck.
|
||||
@@ -96,42 +147,45 @@ export async function runAutoSyncPass(
|
||||
const batchSize = Math.max(1, Math.min(200, settings.autoSyncBatchSize));
|
||||
const intervalMs = Math.max(5, settings.autoSyncIntervalMinutes) * 60_000;
|
||||
|
||||
const where: Prisma.ProjectWhereInput = {
|
||||
// Gezaehlt und begrenzt wird seit dem Umbau je Repository, nicht je
|
||||
// Projekt: sonst zoege ein Projekt mit fuenf Repos fuenfmal so viele
|
||||
// Anfragen nach sich wie sein Platz im Kontingent hergibt.
|
||||
const where: Prisma.RepositoryWhereInput = {
|
||||
autoSync: true,
|
||||
// Ohne Repository gibt es nichts abzugleichen.
|
||||
// Ohne Angaben gibt es nichts abzugleichen.
|
||||
OR: [
|
||||
{ AND: [{ repoOwner: { not: null } }, { repoName: { not: null } }] },
|
||||
{ repoUrl: { not: null } },
|
||||
],
|
||||
...(settings.autoSyncActiveOnly
|
||||
? { status: { notIn: ["DONE", "ARCHIVED"] } }
|
||||
? { project: { status: { notIn: ["DONE", "ARCHIVED"] } } }
|
||||
: {}),
|
||||
};
|
||||
|
||||
// Grosszuegig holen: ein Teil faellt gleich der Zurueckhaltung zum Opfer.
|
||||
const candidates = await prisma.project.findMany({
|
||||
const candidates = await prisma.repository.findMany({
|
||||
where,
|
||||
orderBy: [{ lastSyncedAt: { sort: "asc", nulls: "first" } }],
|
||||
take: batchSize * 4,
|
||||
select: { id: true, name: true, lastSyncedAt: true, syncFailureCount: true },
|
||||
select: { id: true, lastSyncedAt: true, syncFailureCount: true },
|
||||
});
|
||||
|
||||
const due = candidates.filter((project) => {
|
||||
if (project.syncFailureCount === 0) return true;
|
||||
if (!project.lastSyncedAt) return true;
|
||||
const due = candidates.filter((repository) => {
|
||||
if (repository.syncFailureCount === 0) return true;
|
||||
if (!repository.lastSyncedAt) return true;
|
||||
|
||||
// Nach jedem Fehlschlag doppelt so lange warten, gedeckelt.
|
||||
const steps = Math.min(project.syncFailureCount, MAX_BACKOFF_STEPS);
|
||||
const steps = Math.min(repository.syncFailureCount, MAX_BACKOFF_STEPS);
|
||||
const wait = intervalMs * 2 ** steps;
|
||||
const ready = Date.now() - project.lastSyncedAt.getTime() >= wait;
|
||||
const ready = Date.now() - repository.lastSyncedAt.getTime() >= wait;
|
||||
if (!ready) skipped += 1;
|
||||
return ready;
|
||||
});
|
||||
|
||||
const batch = due.slice(0, batchSize);
|
||||
|
||||
for (const project of batch) {
|
||||
const result = await syncProject(project.id);
|
||||
for (const repository of batch) {
|
||||
const result = await syncRepository(repository.id);
|
||||
if (result.ok) synced += 1;
|
||||
else failed += 1;
|
||||
if (PAUSE_MS > 0) await new Promise((resolve) => setTimeout(resolve, PAUSE_MS));
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NOTIFICATION_EVENTS } from "@/lib/notify/types";
|
||||
import { notificationTargetCreateSchema } from "./validation";
|
||||
|
||||
/**
|
||||
* Dieser Test entstand aus einem Fehler: beim Ergaenzen eines neuen
|
||||
* Anlasses war das Zod-Schema nicht mitgezogen worden, die API lehnte ihn
|
||||
* mit 422 ab. Die Liste steht an zwei Stellen – hier wird geprueft, dass
|
||||
* sie zusammenpassen.
|
||||
*/
|
||||
|
||||
const basis = {
|
||||
name: "Handy",
|
||||
channel: "NTFY" as const,
|
||||
target: "https://ntfy.sh/mein-thema",
|
||||
};
|
||||
|
||||
describe("notificationTargetCreateSchema", () => {
|
||||
it("kennt jeden Anlass, den die Oberflaeche anbietet", () => {
|
||||
for (const event of NOTIFICATION_EVENTS) {
|
||||
const ergebnis = notificationTargetCreateSchema.safeParse({
|
||||
...basis,
|
||||
events: [event],
|
||||
});
|
||||
expect(ergebnis.success, `Anlass ${event} wird abgelehnt`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("verlangt mindestens einen Anlass", () => {
|
||||
expect(notificationTargetCreateSchema.safeParse({ ...basis, events: [] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("weist unbekannte Anlaesse ab", () => {
|
||||
expect(
|
||||
notificationTargetCreateSchema.safeParse({ ...basis, events: ["WAS_AUCH_IMMER"] })
|
||||
.success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("verlangt bei E-Mail eine Adresse, keine URL", () => {
|
||||
const alsUrl = notificationTargetCreateSchema.safeParse({
|
||||
name: "Post",
|
||||
channel: "EMAIL",
|
||||
target: "https://example.com",
|
||||
events: ["SYNC_FAILED"],
|
||||
});
|
||||
expect(alsUrl.success).toBe(false);
|
||||
|
||||
const alsAdresse = notificationTargetCreateSchema.safeParse({
|
||||
name: "Post",
|
||||
channel: "EMAIL",
|
||||
target: "ich@example.com",
|
||||
events: ["SYNC_FAILED"],
|
||||
});
|
||||
expect(alsAdresse.success).toBe(true);
|
||||
});
|
||||
|
||||
it("verlangt bei Webhook und ntfy eine http-URL", () => {
|
||||
for (const channel of ["WEBHOOK", "NTFY"] as const) {
|
||||
expect(
|
||||
notificationTargetCreateSchema.safeParse({
|
||||
name: "X",
|
||||
channel,
|
||||
target: "ich@example.com",
|
||||
events: ["SYNC_FAILED"],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,12 @@ export const projectCreateSchema = z.object({
|
||||
accent: z.enum(ACCENTS).default("violet"),
|
||||
tags: z.array(z.string().trim().min(1).max(30)).max(12).default([]),
|
||||
favorite: z.boolean().default(false),
|
||||
/**
|
||||
* Die Git-Felder liegen seit dem Umbau am Repository, bleiben hier aber
|
||||
* stehen: sie setzen das fuehrende Repository und legen es notfalls an.
|
||||
* So kommt man mit einem Aufruf zu Projekt und Repo, und bestehende
|
||||
* Aufrufer – auch der Import – muessen nichts wissen.
|
||||
*/
|
||||
repoUrl: z.preprocess(emptyToNull, z.string().trim().max(500).nullable().optional()),
|
||||
repoOwner: z.preprocess(emptyToNull, z.string().trim().max(200).nullable().optional()),
|
||||
repoName: z.preprocess(emptyToNull, z.string().trim().max(200).nullable().optional()),
|
||||
@@ -29,6 +35,22 @@ export const projectCreateSchema = z.object({
|
||||
|
||||
export const projectUpdateSchema = projectCreateSchema.partial();
|
||||
|
||||
// ── Repositories ─────────────────────────────────────────────
|
||||
|
||||
export const repositoryCreateSchema = z.object({
|
||||
label: z.preprocess(emptyToNull, z.string().trim().max(80).nullable().optional()),
|
||||
repoUrl: z.preprocess(emptyToNull, z.string().trim().max(500).nullable().optional()),
|
||||
repoOwner: z.preprocess(emptyToNull, z.string().trim().max(200).nullable().optional()),
|
||||
repoName: z.preprocess(emptyToNull, z.string().trim().max(200).nullable().optional()),
|
||||
connectionId: z.preprocess(emptyToNull, z.string().trim().nullable().optional()),
|
||||
autoSync: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export const repositoryUpdateSchema = repositoryCreateSchema.partial().extend({
|
||||
/** Zum Umsortieren; 0 ist das fuehrende. */
|
||||
position: z.coerce.number().int().min(0).max(50).optional(),
|
||||
});
|
||||
|
||||
// ── Aufgaben ─────────────────────────────────────────────────
|
||||
|
||||
const TASK_STATUS = ["TODO", "DOING", "BLOCKED", "DONE"] as const;
|
||||
@@ -146,6 +168,8 @@ export const profileUpdateSchema = z.object({
|
||||
export const adminSettingsSchema = z.object({
|
||||
mode: z.enum(["SINGLE_USER", "MULTI_USER"]).optional(),
|
||||
allowRegistration: z.boolean().optional(),
|
||||
/** Ab wie vielen Tagen ohne Commit ein Projekt als stillstehend gilt. */
|
||||
staleAfterDays: z.coerce.number().int().min(7).max(365).optional(),
|
||||
autoSyncEnabled: z.boolean().optional(),
|
||||
/** Untergrenze 5 Minuten – haeufiger waere den Git-APIs gegenueber unfair. */
|
||||
autoSyncIntervalMinutes: z.coerce.number().int().min(5).max(10080).optional(),
|
||||
@@ -170,6 +194,40 @@ export const adminUserUpdateSchema = z.object({
|
||||
password: z.preprocess(emptyToNull, z.string().max(200).nullable().optional()),
|
||||
});
|
||||
|
||||
// ── Benachrichtigungen ───────────────────────────────────────
|
||||
|
||||
const CHANNELS = ["WEBHOOK", "NTFY", "EMAIL"] as const;
|
||||
const EVENTS = ["SYNC_FAILED", "CI_FAILED", "NEW_RELEASE", "PROJECT_STALE"] as const;
|
||||
|
||||
export const notificationTargetCreateSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1, "Name darf nicht leer sein").max(60),
|
||||
channel: z.enum(CHANNELS),
|
||||
target: z.string().trim().min(1, "Ziel fehlt").max(500),
|
||||
/** Bearer-Token fuer ntfy oder Signaturschluessel fuer den Webhook. */
|
||||
secret: z.preprocess(emptyToNull, z.string().trim().max(300).nullable().optional()),
|
||||
events: z.array(z.enum(EVENTS)).min(1, "Mindestens ein Anlass"),
|
||||
isActive: z.boolean().default(true),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.channel === "EMAIL"
|
||||
? /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.target)
|
||||
: /^https?:\/\//i.test(value.target),
|
||||
{
|
||||
message: "E-Mail-Adresse bzw. URL mit http:// oder https:// erwartet",
|
||||
path: ["target"],
|
||||
},
|
||||
);
|
||||
|
||||
export const notificationTargetUpdateSchema = z.object({
|
||||
name: z.string().trim().min(1).max(60).optional(),
|
||||
target: z.string().trim().min(1).max(500).optional(),
|
||||
secret: z.preprocess(emptyToNull, z.string().trim().max(300).nullable().optional()),
|
||||
events: z.array(z.enum(EVENTS)).min(1).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const passkeyNameSchema = z.object({
|
||||
name: z.preprocess(emptyToNull, z.string().trim().max(60).nullable().optional()),
|
||||
});
|
||||
|
||||
+25
-5
@@ -1,9 +1,11 @@
|
||||
import type {
|
||||
ActivityKind,
|
||||
GitProvider,
|
||||
Note,
|
||||
Project,
|
||||
ProjectStatus,
|
||||
RepoSnapshot,
|
||||
Repository,
|
||||
Task,
|
||||
TaskStatus,
|
||||
} from "@prisma/client";
|
||||
@@ -32,22 +34,38 @@ export interface ConnectionSafe {
|
||||
}
|
||||
|
||||
export interface ConnectionWithCount extends ConnectionSafe {
|
||||
_count?: { projects: number };
|
||||
_count?: { repositories: number };
|
||||
}
|
||||
|
||||
/** Ein Repository samt Verbindung und zuletzt geholtem Stand. */
|
||||
export interface RepositoryWithSnapshot extends Repository {
|
||||
connection: ConnectionSafe | null;
|
||||
snapshot: RepoSnapshot | null;
|
||||
}
|
||||
|
||||
export interface ProjectListItem extends Project {
|
||||
connection: ConnectionSafe | null;
|
||||
snapshot: RepoSnapshot | null;
|
||||
/** Das fuehrende zuerst – siehe repositoryInclude. */
|
||||
repositories: RepositoryWithSnapshot[];
|
||||
_count: { notes: number; tasks: number };
|
||||
/** Nur die erledigten – siehe projectListInclude. */
|
||||
tasks: { id: string }[];
|
||||
}
|
||||
|
||||
/** Ein Eintrag im Projektverlauf, so wie ihn die Anzeige braucht. */
|
||||
export interface ActivityEntry {
|
||||
id: string;
|
||||
kind: ActivityKind;
|
||||
summary: string;
|
||||
createdAt: Date | string;
|
||||
/** null bedeutet: die Anwendung selbst, etwa der automatische Abgleich. */
|
||||
user: { username: string; displayName: string | null } | null;
|
||||
}
|
||||
|
||||
export interface ProjectDetail extends Project {
|
||||
connection: ConnectionSafe | null;
|
||||
snapshot: RepoSnapshot | null;
|
||||
repositories: RepositoryWithSnapshot[];
|
||||
notes: Note[];
|
||||
tasks: Task[];
|
||||
activities: ActivityEntry[];
|
||||
_count: { notes: number; tasks: number };
|
||||
}
|
||||
|
||||
@@ -63,6 +81,7 @@ export interface RepoListEntry {
|
||||
}
|
||||
|
||||
export type {
|
||||
ActivityKind,
|
||||
BranchInfo,
|
||||
CiInfo,
|
||||
CommitInfo,
|
||||
@@ -70,6 +89,7 @@ export type {
|
||||
ProjectStatus,
|
||||
ReleaseInfo,
|
||||
RepoSnapshot,
|
||||
Repository,
|
||||
TagInfo,
|
||||
Task,
|
||||
TaskStatus,
|
||||
|
||||
Reference in New Issue
Block a user