Compare commits
No files matched your search
@@ -9,3 +9,5 @@ data
|
||||
frontend/dist
|
||||
*.md
|
||||
!README.md
|
||||
# Desktop agent is built separately (agent/build.sh)
|
||||
agent
|
||||
@@ -32,6 +32,19 @@ LOGIN_IP_LOCKOUT=false
|
||||
CLIP_MAX_CHARS=200000
|
||||
MAX_REQUEST_BYTES=1048576
|
||||
|
||||
# File uploads (bytes): maximum per file, storage per user, and the free disk space
|
||||
# that must remain on the server (uploads are refused below it)
|
||||
FILE_MAX_BYTES=104857600
|
||||
FILE_QUOTA_BYTES=1073741824
|
||||
FILE_MIN_FREE_BYTES=2147483648
|
||||
|
||||
# --- Backup ----------------------------------------------------------------------
|
||||
# Daily consistent database snapshot to data/backups (hour in local time, see TZ)
|
||||
BACKUP_ENABLED=true
|
||||
BACKUP_HOUR=3
|
||||
BACKUP_KEEP_DAILY=7
|
||||
BACKUP_KEEP_WEEKLY=4
|
||||
|
||||
# Swagger UI under /api/docs; keep disabled on a publicly reachable instance
|
||||
ENABLE_API_DOCS=false
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Selbst gehostetes Web-Clipboard für das private Netz (LAN/VPN). Mehrere Benutzer synchronisieren Texte und Code-Snippets live zwischen ihren Geräten.
|
||||
|
||||
> **Stand:** Meilenstein 3 – Clips (Text und Code mit Syntax-Highlighting), Benutzer, Login, Admin-Verwaltung. Live-Sync folgt.
|
||||
> **Stand:** Meilenstein 9 – API-Tokens, iPhone-Kurzbefehle und Desktop-Agent (`agent/`); Projekte mit anderen Benutzern teilen; Dateiaustausch; Projekte und Suche; als PWA installierbar, für iPhone/iPad optimiert; Live-Sync, Clips (Text und Code mit Syntax-Highlighting), Benutzer, Login, Admin-Verwaltung.
|
||||
|
||||
## Aufbau
|
||||
|
||||
@@ -54,7 +54,7 @@ Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 100
|
||||
| `BIND_IP` | – (Pflicht) | Host-IP, an die der Port gebunden wird, z. B. `192.168.50.123` |
|
||||
| `APP_PORT` | `8085` | Veröffentlichter Host-Port |
|
||||
| `FORWARDED_ALLOW_IPS` | `127.0.0.1` | IP(s) des Reverse Proxy (NPM), dessen `X-Forwarded-*`-Header vertraut wird. Kommagetrennt. |
|
||||
| `ALLOWED_ORIGINS` | `https://clip.webbildhauer.com` | Erlaubte Origins für zustandsändernde Requests (und später WebSockets). Kommagetrennt. |
|
||||
| `ALLOWED_ORIGINS` | `https://clip.webbildhauer.com` | Erlaubte Origins für zustandsändernde Requests und WebSocket-Verbindungen aus dem Browser. Kommagetrennt. |
|
||||
| `COOKIE_SECURE` | `true` | Session-Cookie nur über HTTPS. Nur für lokale Entwicklung auf `false` setzen. |
|
||||
| `SESSION_IDLE_DAYS` | `30` | Session läuft nach so vielen Tagen ohne Nutzung ab |
|
||||
| `SESSION_MAX_DAYS` | `90` | Maximale Lebensdauer einer Session |
|
||||
@@ -63,7 +63,14 @@ Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 100
|
||||
| `LOGIN_FAILURE_WINDOW_MINUTES` | `15` | Zeitfenster und Sperrdauer |
|
||||
| `LOGIN_IP_LOCKOUT` | `false` | IP-Sperre aktivieren – **erst wenn `FORWARDED_ALLOW_IPS` gesetzt ist**, sonst teilen sich alle Benutzer die Proxy-IP |
|
||||
| `CLIP_MAX_CHARS` | `200000` | Maximale Zeichenzahl pro Clip |
|
||||
| `MAX_REQUEST_BYTES` | `1048576` | Maximale Größe eines API-Requests (1 MiB), größere werden mit 413 abgelehnt |
|
||||
| `MAX_REQUEST_BYTES` | `1048576` | Maximale Größe eines API-Requests (1 MiB), größere werden mit 413 abgelehnt. Gilt nicht für Datei-Uploads. |
|
||||
| `FILE_MAX_BYTES` | `104857600` | Maximale Größe pro Datei (100 MiB) |
|
||||
| `FILE_QUOTA_BYTES` | `1073741824` | Speicherplatz für Dateien pro Benutzer (1 GiB) |
|
||||
| `FILE_MIN_FREE_BYTES` | `2147483648` | Freier Speicher, der auf dem Server bleiben muss (2 GiB); darunter werden Uploads mit 507 abgelehnt |
|
||||
| `BACKUP_ENABLED` | `true` | Tägliche Datenbanksicherung nach `data/backups/` |
|
||||
| `BACKUP_HOUR` | `3` | Uhrzeit der Sicherung (Ortszeit laut `TZ`, 0–23) |
|
||||
| `BACKUP_KEEP_DAILY` | `7` | So viele neueste Sicherungen bleiben |
|
||||
| `BACKUP_KEEP_WEEKLY` | `4` | Zusätzlich die neueste Sicherung jeder der davor liegenden Kalenderwochen |
|
||||
| `ENABLE_API_DOCS` | `false` | Swagger UI unter `/api/docs`. Bei öffentlich erreichbarer Instanz aus lassen. |
|
||||
| `INITIAL_ADMIN_USERNAME` / `INITIAL_ADMIN_PASSWORD` | – | Optional: ersten Admin beim Start anlegen (siehe oben) |
|
||||
| `LOG_LEVEL` | `info` | Log-Level von Uvicorn |
|
||||
@@ -76,7 +83,7 @@ Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 100
|
||||
- CSRF: Token pro Session im lesbaren Cookie `lc_csrf`, muss bei POST/PUT/PATCH/DELETE als Header `X-CSRF-Token` mitgeschickt werden. Zusätzlich werden Requests mit fremdem `Origin` abgelehnt.
|
||||
- Fehlanmeldungen: Sperre pro Benutzername (und optional pro IP), Antwort HTTP 429. Gleiche Fehlermeldung für unbekannte Benutzer und falsche Passwörter.
|
||||
- Passwortänderung, Passwort-Reset und Deaktivierung beenden die betroffenen Sessions.
|
||||
- Datentrennung: Jede Clip-Abfrage filtert nach dem angemeldeten Benutzer. Fremde Clips liefern 404 wie nicht vorhandene, auch für Admins.
|
||||
- Datentrennung: Sichtbar sind nur eigene Clips und Clips in eigenen oder mit einem geteilten Projekten. Die Regel steht zentral in `backend/app/services/access.py` und gilt für Liste, Suche, Bearbeiten, Löschen, Download und Live-Sync. Unsichtbare Clips und Projekte liefern 404 wie nicht vorhandene, auch für Admins; fehlende Schreibrechte liefern 403.
|
||||
- Security-Header: CSP (`default-src 'self'`), `X-Frame-Options: DENY`, `nosniff`, Referrer- und Permissions-Policy; HSTS bei HTTPS (ohne `includeSubDomains`).
|
||||
- Dateiartige Pfade wie `/.env` liefern 404 statt der App-Startseite.
|
||||
- Die Instanz ist öffentlich erreichbar (keine Access List im NPM); Schutz durch Login, Sperre und die Maßnahmen oben.
|
||||
@@ -88,10 +95,92 @@ Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 100
|
||||
- „Kopieren“ nutzt die Clipboard API (braucht HTTPS), „Einfügen“ liest die Zwischenablage (Browser fragt nach Erlaubnis).
|
||||
- Konflikterkennung: Jeder Clip hat eine `version`. Wird er auf einem anderen Gerät geändert, meldet das Speichern einen Konflikt (HTTP 409) statt still zu überschreiben.
|
||||
|
||||
## Projekte und Suche
|
||||
|
||||
- Projekte gruppieren Clips (Name und eine von 8 Farben, höchstens 200 pro Benutzer). Ein Clip gehört zu keinem oder einem Projekt. Namen sind pro Benutzer eindeutig, ohne Rücksicht auf Groß-/Kleinschreibung.
|
||||
- Wird ein Projekt gelöscht, bleiben seine Clips erhalten und landen bei „Ohne Projekt“.
|
||||
- Die Suche findet Teiltexte in Titel und Inhalt („config“ findet `getConfig`), unabhängig von Groß-/Kleinschreibung, auch bei Umlauten und „ß“ = „ss“. `%` und `_` werden wörtlich gesucht. Kein Suchindex: bei einigen tausend Clips unkritisch.
|
||||
- Projekt und Suchbegriff stehen in der URL (`/?p=3&q=…`), damit funktionieren Lesezeichen und der Zurück-Button. Neue Clips landen im gerade angezeigten Projekt.
|
||||
- API: `GET/POST /api/projects`, `PATCH/DELETE /api/projects/{id}`; `GET /api/clips?project=<id>|none&q=<text>`.
|
||||
|
||||
## Teilen
|
||||
|
||||
- Geteilt werden Projekte, keine einzelnen Clips. Der Besitzer fügt unter „Projekte“ → „Teilen“ andere Benutzer hinzu (ohne Einladung/Annahme).
|
||||
- Rollen: **Besitzer** (umbenennen, löschen, Mitglieder verwalten), **Bearbeiten** (Clips und Dateien im Projekt anlegen, ändern, löschen, anheften), **Lesen** (ansehen, kopieren, herunterladen). Eigene Clips bleiben immer bearbeitbar.
|
||||
- „Alle“ zeigt auch Clips aus geteilten Projekten. Clips anderer tragen „von <Name>“, geteilte Projekte ein Personen-Symbol. Anheften gilt für alle Mitglieder.
|
||||
- Mitglieder können ein Projekt verlassen. Beim Verlassen, Entfernen oder Löschen des Projekts landen die eigenen Clips wieder bei „Ohne Projekt“; Clips der anderen sind dann nicht mehr sichtbar.
|
||||
- Dateien zählen beim Speicherplatz der Person, die sie hochgeladen hat.
|
||||
- Wird ein Benutzer gelöscht, verschwinden auch seine Clips aus geteilten Projekten. Wer nur gesperrt werden soll, wird besser deaktiviert.
|
||||
- API: `GET/POST /api/projects/{id}/members`, `PATCH/DELETE /api/projects/{id}/members/{user_id}` (DELETE mit eigener ID = verlassen), `GET /api/users` (nur Namen aktiver Benutzer, für die Auswahl beim Teilen).
|
||||
|
||||
## API-Tokens
|
||||
|
||||
- Unter „Konto“ → „Geräte-Tokens“ pro Gerät einen Token erstellen. Er wird **einmal** angezeigt; gespeichert wird nur sein SHA-256-Hash. Die Liste zeigt Anfang, Erstellung und letzte Nutzung (Zeit, IP); Widerrufen schließt auch die Live-Verbindung des Geräts sofort.
|
||||
- Anmeldung mit `Authorization: Bearer lc_…`, ohne Cookie und ohne CSRF-Token.
|
||||
- Erlaubt: Clips (lesen, anlegen, ändern, löschen, `GET /api/clips/latest`), Dateien, Projektliste und Projekt anlegen, Benutzernamen, Live-Sync per WebSocket (`/api/ws` mit dem Header, ohne `Origin`).
|
||||
- Nicht erlaubt: Konto, Passwort, Sessions, Token-Verwaltung, Admin-Funktionen, Projekte umbenennen/löschen/teilen. Ein gestohlener Token kann also weder weitere Tokens erzeugen noch das Konto übernehmen.
|
||||
- Tokens deaktivierter Benutzer sind ungültig; beim Löschen eines Benutzers werden sie mitgelöscht.
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer lc_…" https://clip.webbildhauer.com/api/clips/latest
|
||||
curl -H "Authorization: Bearer lc_…" -H "Content-Type: application/json" \
|
||||
-d '{"content":"Hallo vom Terminal"}' https://clip.webbildhauer.com/api/clips
|
||||
```
|
||||
|
||||
### iPhone/iPad: Kurzbefehle
|
||||
|
||||
iOS erlaubt keinen Agenten im Hintergrund. Mit einem Token und der App „Kurzbefehle“ geht es per Tipp, Action-Button oder Back-Tap (Einstellungen → Bedienungshilfen → Tippen → Auf Rückseite tippen).
|
||||
|
||||
**„Zwischenablage senden“**
|
||||
1. Aktion **Zwischenablage abrufen**.
|
||||
2. Aktion **Inhalte von URL abrufen**: URL `https://clip.webbildhauer.com/api/clips`, Methode **POST**, Header `Authorization` = `Bearer lc_…`, Anfragetext **JSON** mit Schlüssel `content` (Text) = Variable *Zwischenablage*.
|
||||
3. Optional **Mitteilung zeigen**: „Gesendet“.
|
||||
|
||||
**„Neuesten Clip holen“**
|
||||
1. Aktion **Inhalte von URL abrufen**: URL `https://clip.webbildhauer.com/api/clips/latest`, Methode **GET**, Header `Authorization` = `Bearer lc_…`.
|
||||
2. Aktion **Wörterbuchwert abrufen**: Wert für `content` in *Inhalte der URL*.
|
||||
3. Aktion **In Zwischenablage kopieren**.
|
||||
|
||||
Für jedes Gerät einen eigenen Token verwenden, dann lässt sich ein verlorenes iPhone einzeln widerrufen.
|
||||
|
||||
### Desktop-Agent
|
||||
|
||||
Der Agent unter [`agent/`](agent/README.md) synchronisiert die Zwischenablage von Windows-, macOS- und Linux-Rechnern automatisch (Text, beide Richtungen, Passwort-Manager-Inhalte werden nie gesendet). Bauen mit `agent/build.sh` (nur Docker nötig), Einrichtung und Autostart siehe [agent/README.md](agent/README.md).
|
||||
|
||||
## Dateien
|
||||
|
||||
- Dateien sind Clips der Art „Datei“: Sie stehen in derselben Liste, lassen sich Projekten zuordnen, anheften, über den Dateinamen suchen und werden live auf alle Geräte übertragen.
|
||||
- Hochladen über „Datei …“ (mehrere auf einmal; auf dem iPhone auch aus der Fotomediathek oder per Kamera), am Desktop zusätzlich per Drag & Drop oder Strg+V (z. B. Screenshots). Uploads laufen nacheinander mit Fortschrittsanzeige und lassen sich abbrechen.
|
||||
- Aufbewahrung beim Hochladen wählbar (1, 7 oder 30 Tage oder unbegrenzt, Standard 7 Tage) und später auf der Bearbeiten-Seite änderbar. Der stündliche Aufräumjob löscht abgelaufene Dateien und Dateien ohne Datenbankeintrag (z. B. von gelöschten Benutzern).
|
||||
- Grenzen: `FILE_MAX_BYTES` pro Datei, `FILE_QUOTA_BYTES` pro Benutzer, `FILE_MIN_FREE_BYTES` Reserve auf der Platte (der Server wird mit anderen Stacks geteilt). Der belegte Speicher steht unter „Konto“.
|
||||
- Ablage unter `data/files/<Benutzer-ID>/<Zufallsname>`; der Originalname steht nur in der Datenbank. Der Upload wird gestreamt (kein Zwischenspeichern im RAM).
|
||||
- Download immer als Anhang mit `Content-Security-Policy: sandbox` und `nosniff`. Als Bild angezeigt werden nur Dateien, deren Inhalt tatsächlich JPEG, PNG, GIF oder WebP ist (kein SVG).
|
||||
- In der installierten iPhone-App öffnen Downloads die iOS-Vorschau; weiter geht es dort über „Teilen“.
|
||||
- API: `POST /api/files?name=…&expires_days=7&project_id=…` mit der Datei als Request-Body (kein Multipart, `Content-Length` erforderlich); `GET /api/files/{clip_id}` (Download, `?inline=1` für Bildvorschau), `PATCH /api/files/{clip_id}` (`expires_days`), `GET /api/files/usage`.
|
||||
|
||||
## Live-Sync
|
||||
|
||||
- WebSocket unter `/api/ws`, angemeldet über das Session-Cookie. Der `Origin`-Header muss in `ALLOWED_ORIGINS` stehen.
|
||||
- Der Socket ist nur Server → Gerät: Änderungen laufen über die REST-API, der Server meldet `clip.created`, `clip.updated`, `clip.deleted` sowie `project.created`, `project.updated` und `project.deleted` an alle Geräte aller Benutzer, die den Clip bzw. das Projekt sehen. Wer die Sicht verliert (Clip aus geteiltem Projekt verschoben, Mitglied entfernt), bekommt `clip.deleted` bzw. `project.deleted`.
|
||||
- Heartbeat alle 30 s; Sessions werden alle 5 Minuten neu geprüft. Logout, Widerruf, Passwortänderung, Deaktivierung und Löschen schließen betroffene Verbindungen sofort (Code `4401`). Ein `lc-admin reset-password` aus einem anderen Prozess greift spätestens nach 5 Minuten.
|
||||
- Höchstens 20 Verbindungen pro Benutzer, eingehende Nachrichten max. 64 KiB.
|
||||
- Der Client verbindet sich nach Abbrüchen mit wachsender Wartezeit neu (1–30 s), sofort beim Zurückkehren in den Vordergrund, und lädt danach die Liste neu.
|
||||
- Funktioniert nur mit **einem** Uvicorn-Worker (Hub im Prozess). Mehrere Worker bräuchten einen Broker wie Redis.
|
||||
|
||||
## App installieren (PWA)
|
||||
|
||||
- **iPhone/iPad:** In Safari `https://clip.webbildhauer.com` öffnen → Teilen → „Zum Home-Bildschirm“.
|
||||
- **Android/Chrome/Edge:** Menü → „App installieren“. Danach erscheint „Clipboard“ auch im Teilen-Menü (Share Target): geteilte Texte/Links landen in der Schnell-Eingabe.
|
||||
- Der Service Worker cacht nur die App-Hülle (HTML, JS, CSS, Icons). **Clip-Inhalte werden nie auf dem Gerät gespeichert**; ohne Verbindung zeigt die App eine Offline-Seite.
|
||||
- Nach einem Deployment erscheint „Neue Version verfügbar – Neu laden“.
|
||||
- Icons: Quellen `frontend/public/icons/*.svg`, PNGs neu erzeugen mit `cd frontend && sh scripts/render-icons.sh` (nutzt das Playwright-Image mit Chromium).
|
||||
|
||||
## Reverse Proxy (Nginx Proxy Manager)
|
||||
|
||||
- Proxy Host → `http://192.168.50.123:8085`, **Websockets Support aktivieren** (ab Live-Sync nötig).
|
||||
- Proxy Host → `http://192.168.50.123:8085`, **Websockets Support aktivieren** (für den Live-Sync zwingend).
|
||||
- SSL im NPM terminieren. Die App spricht intern nur HTTP.
|
||||
- Option **„Cache Assets“ am besten deaktivieren**: Sie überschreibt die Cache-Header der App für `.js`/`.png` (die App setzt selbst `immutable` für gehashte Assets und `no-cache` für `sw.js`). Funktional unkritisch, da Browser den Service Worker am HTTP-Cache vorbei aktualisieren.
|
||||
- Upload-Größe: Mit der aktuellen NPM-Konfiguration gehen Dateien bis 100 MB durch (getestet). Wird `FILE_MAX_BYTES` erhöht und NPM antwortet mit 413, im Proxy Host unter „Advanced“ `client_max_body_size 200m;` (passend zum Limit) eintragen.
|
||||
- `FORWARDED_ALLOW_IPS` auf die IP setzen, mit der NPM die App erreicht. Sie steht nach einem Aufruf über NPM im Log:
|
||||
`docker compose logs app | grep "GET /api/health"` → erste Spalte ist die Absender-IP.
|
||||
Danach `docker compose up -d` (die Variable wird beim Start gelesen) und `LOGIN_IP_LOCKOUT=true` setzen.
|
||||
@@ -115,7 +204,7 @@ Auf dem Server ist kein Node installiert; Befehle laufen in einem Wegwerf-Contai
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
docker run --rm -v "$PWD":/app -w /app node:22.22.0-alpine sh -c "npm ci && npm run lint && npm run format:check && npm run build"
|
||||
docker run --rm -v "$PWD":/app -w /app node:22.22.0-alpine sh -c "npm ci && npm test && npm run lint && npm run format:check && npm run build"
|
||||
```
|
||||
|
||||
Mit lokalem Node: `npm run dev` startet Vite und leitet `/api` an `localhost:8000` weiter.
|
||||
@@ -129,20 +218,44 @@ cd backend
|
||||
DATA_DIR=./.devdata .venv/bin/alembic revision --autogenerate -m "beschreibung"
|
||||
```
|
||||
|
||||
## Backup und Restore
|
||||
|
||||
Der Host wird vom Proxmox Backup Server gesichert. Zusätzlich sollte die SQLite-Datenbank konsistent gesichert werden, da eine Kopie der laufenden Datei im WAL-Modus unvollständig sein kann:
|
||||
## Update
|
||||
|
||||
```bash
|
||||
# Backup (konsistent, auch im laufenden Betrieb)
|
||||
docker exec lan-clipboard python -c "import sqlite3; s=sqlite3.connect('/data/app.db'); d=sqlite3.connect('/data/backup.db'); s.backup(d); d.close()"
|
||||
mv data/backup.db "backup-$(date +%F).db"
|
||||
|
||||
# Restore
|
||||
docker compose stop
|
||||
cp backup-JJJJ-MM-TT.db data/app.db && rm -f data/app.db-wal data/app.db-shm
|
||||
chown 1000:1000 data/app.db
|
||||
docker compose up -d
|
||||
cd /opt/claude/lan-clipboard
|
||||
docker exec -u app lan-clipboard lc-admin backup # Sicherung vor dem Update
|
||||
git pull
|
||||
docker compose build
|
||||
docker compose up -d # Migrationen laufen beim Start
|
||||
curl http://192.168.50.123:8085/api/health
|
||||
```
|
||||
|
||||
Ein automatischer Backup-Job folgt später.
|
||||
Neue Variablen in `.env.example` mit der eigenen `.env` abgleichen (`diff .env.example .env`). Geöffnete Browser-Tabs und die installierte PWA zeigen danach „Neue Version verfügbar – Neu laden“.
|
||||
|
||||
## Backup und Restore
|
||||
|
||||
Der Host wird vom Proxmox Backup Server (PBS) gesichert. Damit er immer eine konsistente Datenbank erwischt, schreibt die App selbst täglich eine Sicherung:
|
||||
|
||||
- **Was:** konsistente Momentaufnahme von `data/app.db` (SQLite-Backup-API, entspricht `sqlite3 .backup`), geprüft mit `PRAGMA integrity_check`, gzip-komprimiert nach `data/backups/app-JJJJ-MM-TT.db.gz`. Nur eine vollständig geprüfte Datei bekommt diesen Namen.
|
||||
- **Wann:** täglich um `BACKUP_HOUR` (Standard 3:00 Uhr). War der Container zu der Zeit aus und ist die letzte Sicherung älter als 24 Stunden, wird sie eine Minute nach dem Start nachgeholt.
|
||||
- **Aufbewahrung:** die 7 neuesten plus je die neueste der 4 Kalenderwochen davor (`BACKUP_KEEP_DAILY`, `BACKUP_KEEP_WEEKLY`).
|
||||
- **Status:** im Admin-Bereich unter „Benutzer“ → „Datensicherung“ (rot, wenn seit über einem Tag keine Sicherung lief oder der letzte Versuch fehlschlug), Fehler auch im Log (`docker compose logs app | grep -i backup`).
|
||||
- **Von Hand**, z. B. vor einem Update: `docker exec -u app lan-clipboard lc-admin backup`
|
||||
- **Dateien** (`data/files/`) werden nicht zusätzlich kopiert: Sie werden nur angelegt und gelöscht, nie verändert, und der PBS erfasst sie auch im laufenden Betrieb vollständig. Eine eigene Kopie würde den Speicherbedarf verdoppeln.
|
||||
|
||||
### Wiederherstellen
|
||||
|
||||
```bash
|
||||
docker compose stop
|
||||
cp data/app.db "data/app.db.vorher-$(date +%F)" # aktuellen Stand aufheben
|
||||
gunzip -c data/backups/app-JJJJ-MM-TT.db.gz > data/app.db
|
||||
rm -f data/app.db-wal data/app.db-shm
|
||||
chown 1000:1000 data/app.db
|
||||
docker compose up -d # Migrationen laufen beim Start
|
||||
```
|
||||
|
||||
Datenbank und `data/files/` passen danach nicht immer genau zusammen:
|
||||
- Dateien, die **nach** der Sicherung hochgeladen wurden, haben keinen Datenbankeintrag mehr; der stündliche Aufräumjob löscht sie nach einer Stunde.
|
||||
- Dateien, die **seit** der Sicherung gelöscht wurden oder abgelaufen sind, erscheinen wieder als Clip, liefern beim Herunterladen aber 404. Solche Clips einfach löschen.
|
||||
- Sollen auch die Dateien auf den Stand der Sicherung zurück, `data/files/` aus dem PBS-Backup desselben Zeitpunkts zurückspielen.
|
||||
|
||||
Sitzungen und Tokens sind auf dem Stand der Sicherung: Seitdem angemeldete Geräte müssen sich neu anmelden, seitdem widerrufene Tokens gelten wieder und sollten erneut widerrufen werden.
|
||||
@@ -0,0 +1,2 @@
|
||||
/.cache/
|
||||
/dist/
|
||||
@@ -0,0 +1,68 @@
|
||||
# lc-agent – Desktop-Agent für LAN-Clipboard
|
||||
|
||||
Synchronisiert die Zwischenablage eines Rechners (Windows, macOS, Linux) automatisch mit LAN-Clipboard:
|
||||
|
||||
- **Senden:** Neu kopierter Text wird ein Clip im Projekt „Zwischenablage“ (einstellbar). Was beim Start schon in der Zwischenablage liegt, wird nicht gesendet.
|
||||
- **Empfangen:** Neue Text- und Code-Clips **des eigenen Benutzers** von anderen Geräten (Web-App, iPhone-Kurzbefehl, anderer Rechner) landen sofort in der Zwischenablage. Clips anderer Mitglieder geteilter Projekte werden nicht übernommen.
|
||||
- Empfangenes wird nicht zurückgeschickt; vom Agent gesendete Clips kommen nicht als „neu“ zurück.
|
||||
- Vom Agent gesendete Clips werden auf die letzten 50 pro Gerät begrenzt (`keep`), ältere löscht der Agent selbst.
|
||||
- Nur Text. Dateien und Bilder bleiben der Web-App vorbehalten.
|
||||
|
||||
## Passwörter und Datenschutz
|
||||
|
||||
- Inhalte, die ein Passwort-Manager als geheim markiert, werden **nie** gesendet:
|
||||
Windows `ExcludeClipboardContentFromMonitorProcessing` / `Clipboard Viewer Ignore`, macOS `org.nspasteboard.ConcealedType` (auch Transient/AutoGenerated), Linux `x-kde-passwordManagerHint` (KeePassXC u. a.).
|
||||
- Zusätzlich: Größengrenze (`max_chars`) und eigene Ausschlussmuster (`exclude`, reguläre Ausdrücke), z. B. `"^\\d{6}$"` für 2FA-Codes.
|
||||
- Das Protokoll enthält nie Inhalte, nur Zeichenzahlen.
|
||||
- Wer gar nichts automatisch senden will: `"direction": "receive"`.
|
||||
|
||||
## Einrichtung
|
||||
|
||||
1. In der Web-App unter **Konto → Geräte-Tokens** einen Token für dieses Gerät erstellen.
|
||||
2. Passende Datei aus `dist/` nehmen (siehe unten) und `lc-agent setup` ausführen: Server-Adresse, Token, Richtung, Projekt. Die Verbindung wird geprüft, die Konfiguration landet in
|
||||
- Windows: `%APPDATA%\lan-clipboard\agent.json`
|
||||
- macOS: `~/Library/Application Support/lan-clipboard/agent.json`
|
||||
- Linux: `~/.config/lan-clipboard/agent.json` (Rechte `0600`)
|
||||
3. Testen mit `lc-agent run` (Strg+C beendet), dann Autostart einrichten.
|
||||
|
||||
| System | Datei | Autostart |
|
||||
|---|---|---|
|
||||
| Windows | `lc-agent.exe` (Konsole, für `setup`), `lc-agentw.exe` (ohne Fenster) | `install/autostart-windows.ps1` (Verknüpfung im Autostart-Ordner) |
|
||||
| macOS Apple Silicon / Intel | `lc-agent-macos-apple` / `lc-agent-macos-intel` | `install/lan-clipboard.agent.plist` (LaunchAgent) |
|
||||
| Linux x86_64 / ARM | `lc-agent-linux-amd64` / `lc-agent-linux-arm64` | `install/lc-agent.service` (systemd-User-Unit) |
|
||||
|
||||
**Linux** braucht `wl-clipboard` (Wayland) oder `xclip` (X11), z. B. `sudo apt install wl-clipboard xclip`.
|
||||
|
||||
**macOS:** Die Dateien sind nicht signiert. Nach dem Herunterladen einmal `xattr -d com.apple.quarantine lc-agent-macos-apple` ausführen, sonst blockiert Gatekeeper den Start. Beim ersten Lauf fragt macOS evtl. nach Erlaubnis für den Zugriff auf die Zwischenablage bzw. auf „osascript“.
|
||||
|
||||
**Windows:** SmartScreen warnt bei unbekannten Programmen („Weitere Informationen“ → „Trotzdem ausführen“).
|
||||
|
||||
## Konfiguration (`agent.json`)
|
||||
|
||||
| Feld | Standard | Bedeutung |
|
||||
|---|---|---|
|
||||
| `server` | – | z. B. `https://clip.webbildhauer.com` (nur HTTPS, außer `localhost`) |
|
||||
| `token` | – | Geräte-Token `lc_…` |
|
||||
| `direction` | `both` | `both`, `send` (nur senden) oder `receive` (nur empfangen) |
|
||||
| `project` | `Zwischenablage` | Projekt für gesendete Clips; wird angelegt, falls es fehlt. Leer: kein Projekt |
|
||||
| `keep` | `50` | So viele eigene Clips behält der Agent auf dem Server |
|
||||
| `max_chars` | `100000` | Längere Inhalte werden nicht gesendet |
|
||||
| `exclude` | `[]` | Reguläre Ausdrücke; passende Inhalte werden nicht gesendet |
|
||||
| `poll_ms` | `700` | Abfrageintervall der Zwischenablage |
|
||||
|
||||
## Verhalten bei Fehlern
|
||||
|
||||
- Server beim Start nicht erreichbar (z. B. vor dem WLAN): neuer Versuch mit wachsender Wartezeit bis 1 Minute.
|
||||
- Live-Verbindung bricht ab: Wiederverbinden nach 1–30 s.
|
||||
- Token widerrufen oder Benutzer deaktiviert: Der Agent beendet sich mit Exit-Code **3** (systemd startet ihn dann nicht neu). Neuen Token erstellen und `lc-agent setup` ausführen.
|
||||
|
||||
## Entwicklung
|
||||
|
||||
```bash
|
||||
./build.sh # gofmt, go vet (Linux/Windows/macOS), Tests, Builds nach dist/ – nur Docker nötig
|
||||
```
|
||||
|
||||
- `internal/agent`: Abgleich-Logik (plattformunabhängig, mit Fakes getestet)
|
||||
- `internal/api`: REST und WebSocket mit Token
|
||||
- `internal/clipboard`: Windows nativ (user32, ohne cgo), macOS über `osascript` (JXA) und `pbcopy`, Linux über `wl-clipboard`/`xclip`
|
||||
- Getestet: Unit-Tests (auch mit Race-Detector) und ein Ende-zu-Ende-Test unter Linux (Xvfb + xclip gegen den echten Server). Windows und macOS sind gebaut, aber noch nicht auf echten Rechnern geprüft.
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Checks and builds lc-agent for all platforms in a throwaway Go container.
|
||||
# Output: dist/. Usage: ./build.sh (needs only Docker on the host)
|
||||
set -eu
|
||||
cd "$(dirname "$0")"
|
||||
VERSION="$(git describe --tags --always --dirty 2>/dev/null || echo dev)"
|
||||
|
||||
docker run --rm -v "$PWD":/src -w /src \
|
||||
-e GOMODCACHE=/src/.cache/mod -e GOCACHE=/src/.cache/build \
|
||||
-e GOFLAGS=-buildvcs=false -e CGO_ENABLED=0 -e VERSION="$VERSION" \
|
||||
golang:1.26-alpine sh -euc '
|
||||
test -z "$(gofmt -l .)" || { gofmt -l .; echo "gofmt: Dateien nicht formatiert"; exit 1; }
|
||||
for os in linux windows darwin; do GOOS=$os go vet ./...; done
|
||||
go test ./...
|
||||
rm -rf dist && mkdir dist
|
||||
build() { GOOS=$1 GOARCH=$2 go build -trimpath -ldflags "-s -w -X main.version=$VERSION ${4:-}" -o "dist/$3" ./cmd/lc-agent; }
|
||||
build linux amd64 lc-agent-linux-amd64
|
||||
build linux arm64 lc-agent-linux-arm64
|
||||
build darwin amd64 lc-agent-macos-intel
|
||||
build darwin arm64 lc-agent-macos-apple
|
||||
build windows amd64 lc-agent.exe
|
||||
# No console window; for autostart (log with -log)
|
||||
build windows amd64 lc-agentw.exe "-H=windowsgui"
|
||||
cd dist && sha256sum * > SHA256SUMS
|
||||
'
|
||||
ls -l dist
|
||||
@@ -0,0 +1,213 @@
|
||||
// lc-agent syncs the clipboard of this computer with LAN-Clipboard.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"lan-clipboard/agent/internal/agent"
|
||||
"lan-clipboard/agent/internal/api"
|
||||
"lan-clipboard/agent/internal/clipboard"
|
||||
"lan-clipboard/agent/internal/config"
|
||||
)
|
||||
|
||||
// Set at build time with -ldflags "-X main.version=…"
|
||||
var version = "dev"
|
||||
|
||||
// Exit code for a rejected token, so autostart (systemd) does not restart in a loop
|
||||
const exitUnauthorized = 3
|
||||
|
||||
const usage = `lc-agent – Zwischenablage mit LAN-Clipboard synchronisieren
|
||||
|
||||
Befehle:
|
||||
lc-agent setup Server und Token eingeben, Verbindung prüfen, Konfiguration speichern
|
||||
lc-agent run Synchronisieren (läuft, bis er beendet wird)
|
||||
lc-agent version Version anzeigen
|
||||
|
||||
Optionen:
|
||||
-config DATEI Konfigurationsdatei (Standard: %s)
|
||||
-log DATEI Protokoll in eine Datei statt auf die Konsole schreiben
|
||||
`
|
||||
|
||||
func main() {
|
||||
defaultPath, _ := config.DefaultPath()
|
||||
flags := flag.NewFlagSet("lc-agent", flag.ExitOnError)
|
||||
configPath := flags.String("config", defaultPath, "")
|
||||
logPath := flags.String("log", "", "")
|
||||
flags.Usage = func() { fmt.Fprintf(os.Stderr, usage, defaultPath) }
|
||||
|
||||
if len(os.Args) < 2 {
|
||||
flags.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
command := os.Args[1]
|
||||
flags.Parse(os.Args[2:])
|
||||
|
||||
var err error
|
||||
switch command {
|
||||
case "setup":
|
||||
err = setup(*configPath)
|
||||
case "run":
|
||||
err = run(*configPath, *logPath)
|
||||
case "version":
|
||||
fmt.Println("lc-agent", version)
|
||||
default:
|
||||
flags.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Fehler:", err)
|
||||
if errors.Is(err, api.ErrUnauthorized) {
|
||||
os.Exit(exitUnauthorized)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(configPath, logPath string) error {
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out := io.Writer(os.Stderr)
|
||||
if logPath != "" {
|
||||
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
out = file
|
||||
}
|
||||
logger := log.New(out, "", log.LstdFlags)
|
||||
|
||||
cb, err := clipboard.New()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := api.New(cfg.Server, cfg.Token, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a, err := agent.New(cfg, client, cb, logger, config.StatePath(configPath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := setupWithRetry(ctx, a, logger); err != nil {
|
||||
return explain(err)
|
||||
}
|
||||
err = a.Run(ctx)
|
||||
if err != nil {
|
||||
return explain(err)
|
||||
}
|
||||
logger.Print("Beendet")
|
||||
return nil
|
||||
}
|
||||
|
||||
func explain(err error) error {
|
||||
if errors.Is(err, api.ErrUnauthorized) {
|
||||
return fmt.Errorf("%w – neuen Token erstellen und \"lc-agent setup\" ausführen", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// setupWithRetry waits for the server, e.g. when the computer starts before the network.
|
||||
// Only a rejected token ends the agent.
|
||||
func setupWithRetry(ctx context.Context, a *agent.Agent, logger *log.Logger) error {
|
||||
delay := 2 * time.Second
|
||||
for {
|
||||
err := a.Setup(ctx)
|
||||
if ctx.Err() != nil {
|
||||
return nil // stopped while waiting (Ctrl+C, shutdown)
|
||||
}
|
||||
if err == nil || errors.Is(err, api.ErrUnauthorized) {
|
||||
return err
|
||||
}
|
||||
logger.Printf("Server nicht erreichbar (%v), neuer Versuch in %s", err, delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(delay):
|
||||
}
|
||||
delay = min(delay*2, time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
func setup(configPath string) error {
|
||||
in := bufio.NewReader(os.Stdin)
|
||||
cfg := config.Defaults()
|
||||
if existing, err := config.Load(configPath); err == nil {
|
||||
cfg = existing
|
||||
}
|
||||
|
||||
cfg.Server = ask(in, "Server-Adresse", cfg.Server)
|
||||
fmt.Print("Token (unter \"Konto\" → \"Geräte-Tokens\" erstellen): ")
|
||||
token, err := readSecret(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token != "" {
|
||||
cfg.Token = token
|
||||
}
|
||||
cfg.Direction = config.Direction(ask(in, "Richtung: both (senden und empfangen), send oder receive", string(cfg.Direction)))
|
||||
cfg.Project = ask(in, "Projekt für gesendete Clips (leer: keins)", cfg.Project)
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client, err := api.New(cfg.Server, cfg.Token, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user, err := client.Me(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("Verbindung fehlgeschlagen: %w", err)
|
||||
}
|
||||
if err := config.Save(configPath, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Verbunden als %s. Konfiguration gespeichert in %s\n", user.Username, configPath)
|
||||
fmt.Println("Starten mit: lc-agent run")
|
||||
return nil
|
||||
}
|
||||
|
||||
func ask(in *bufio.Reader, prompt, current string) string {
|
||||
if current != "" {
|
||||
fmt.Printf("%s [%s]: ", prompt, current)
|
||||
} else {
|
||||
fmt.Printf("%s: ", prompt)
|
||||
}
|
||||
line, _ := in.ReadString('\n')
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
return line
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// readSecret reads without echo when attached to a terminal.
|
||||
func readSecret(in *bufio.Reader) (string, error) {
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
data, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
return strings.TrimSpace(string(data)), err
|
||||
}
|
||||
line, err := in.ReadString('\n')
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(line), nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
module lan-clipboard/agent
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.15
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/term v0.47.0
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
|
||||
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
|
||||
@@ -0,0 +1,17 @@
|
||||
# Windows: start lc-agentw.exe (no console window) at login via the Startup folder.
|
||||
# Run in PowerShell from the folder containing lc-agentw.exe:
|
||||
# powershell -ExecutionPolicy Bypass -File autostart-windows.ps1
|
||||
$target = Join-Path $env:LOCALAPPDATA "lan-clipboard"
|
||||
New-Item -ItemType Directory -Force -Path $target | Out-Null
|
||||
Copy-Item -Force (Join-Path $PSScriptRoot "lc-agentw.exe") $target
|
||||
Copy-Item -Force (Join-Path $PSScriptRoot "lc-agent.exe") $target
|
||||
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
$link = $shell.CreateShortcut((Join-Path ([Environment]::GetFolderPath("Startup")) "LAN-Clipboard Agent.lnk"))
|
||||
$link.TargetPath = Join-Path $target "lc-agentw.exe"
|
||||
$link.Arguments = "run -log `"$target\agent.log`""
|
||||
$link.WorkingDirectory = $target
|
||||
$link.Save()
|
||||
Write-Host "Autostart eingerichtet. Jetzt einmalig einrichten mit:"
|
||||
Write-Host " & `"$target\lc-agent.exe`" setup"
|
||||
Write-Host "Danach abmelden/anmelden oder lc-agentw.exe direkt starten. Protokoll: $target\agent.log"
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<!--
|
||||
macOS LaunchAgent: starts lc-agent at login.
|
||||
cp lc-agent-macos-apple /usr/local/bin/lc-agent (Intel: lc-agent-macos-intel)
|
||||
cp lan-clipboard.agent.plist ~/Library/LaunchAgents/
|
||||
launchctl load ~/Library/LaunchAgents/lan-clipboard.agent.plist
|
||||
Replace USERNAME below with your macOS user name.
|
||||
-->
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>lan-clipboard.agent</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/usr/local/bin/lc-agent</string>
|
||||
<string>run</string>
|
||||
<string>-log</string>
|
||||
<string>/Users/USERNAME/Library/Logs/lc-agent.log</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>KeepAlive</key>
|
||||
<dict>
|
||||
<key>SuccessfulExit</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>ThrottleInterval</key>
|
||||
<integer>30</integer>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,20 @@
|
||||
# systemd user unit for Linux.
|
||||
# cp lc-agent-linux-amd64 ~/.local/bin/lc-agent && chmod +x ~/.local/bin/lc-agent
|
||||
# cp lc-agent.service ~/.config/systemd/user/
|
||||
# systemctl --user enable --now lc-agent
|
||||
# Log: journalctl --user -u lc-agent -f
|
||||
[Unit]
|
||||
Description=LAN-Clipboard agent (clipboard sync)
|
||||
# Needs the graphical session for the clipboard
|
||||
After=graphical-session.target
|
||||
PartOf=graphical-session.target
|
||||
|
||||
[Service]
|
||||
ExecStart=%h/.local/bin/lc-agent run
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
# Exit code 3: token revoked; restarting would not help
|
||||
RestartPreventExitStatus=3
|
||||
|
||||
[Install]
|
||||
WantedBy=graphical-session.target
|
||||
@@ -0,0 +1,304 @@
|
||||
// Package agent keeps the local clipboard and the server in sync.
|
||||
//
|
||||
// Sending: the clipboard is polled; new text becomes a clip in the agent's project.
|
||||
// Receiving: new text/code clips of the same user from other devices are written to
|
||||
// the clipboard. A hash of the last seen content prevents sending received text back.
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"lan-clipboard/agent/internal/api"
|
||||
"lan-clipboard/agent/internal/clipboard"
|
||||
"lan-clipboard/agent/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
minRetry = time.Second
|
||||
maxRetry = 30 * time.Second
|
||||
)
|
||||
|
||||
// Stands for "concealed content" so a secret staying in the clipboard is logged once
|
||||
var concealedHash = sha256.Sum256([]byte("\x00concealed\x00"))
|
||||
|
||||
// API is the part of the server client the agent uses (faked in tests).
|
||||
type API interface {
|
||||
Me(ctx context.Context) (api.User, error)
|
||||
Projects(ctx context.Context) ([]api.Project, error)
|
||||
CreateProject(ctx context.Context, name string) (api.Project, error)
|
||||
CreateClip(ctx context.Context, content string, projectID *int64) (api.Clip, error)
|
||||
DeleteClip(ctx context.Context, id int64) error
|
||||
Events(ctx context.Context, handle func(api.Event)) error
|
||||
}
|
||||
|
||||
// state is persisted between runs: the ids of clips this device created, oldest first.
|
||||
type state struct {
|
||||
Sent []int64 `json:"sent"`
|
||||
}
|
||||
|
||||
type Agent struct {
|
||||
cfg config.Config
|
||||
api API
|
||||
clipboard clipboard.Clipboard
|
||||
log *log.Logger
|
||||
statePath string
|
||||
patterns []*regexp.Regexp
|
||||
|
||||
mu sync.Mutex
|
||||
me int64
|
||||
projectID *int64
|
||||
lastHash [32]byte
|
||||
sent []int64
|
||||
// Clips created by this device; their live events are not written back
|
||||
own map[int64]bool
|
||||
}
|
||||
|
||||
func New(cfg config.Config, client API, cb clipboard.Clipboard, logger *log.Logger, statePath string) (*Agent, error) {
|
||||
patterns, err := cfg.Patterns()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Agent{
|
||||
cfg: cfg,
|
||||
api: client,
|
||||
clipboard: cb,
|
||||
log: logger,
|
||||
statePath: statePath,
|
||||
patterns: patterns,
|
||||
own: map[int64]bool{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Setup identifies the user, finds or creates the project and loads the state.
|
||||
// Whatever is in the clipboard at start is not sent: only later changes are.
|
||||
func (a *Agent) Setup(ctx context.Context) error {
|
||||
me, err := a.api.Me(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.me = me.ID
|
||||
if a.cfg.Project != "" {
|
||||
id, err := a.ensureProject(ctx, a.cfg.Project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.projectID = &id
|
||||
}
|
||||
a.loadState()
|
||||
if content, err := a.clipboard.Read(); err == nil {
|
||||
a.lastHash = sha256.Sum256([]byte(content.Text))
|
||||
}
|
||||
a.log.Printf("Verbunden als %s, Richtung %s, Projekt %q", me.Username, a.cfg.Direction, a.cfg.Project)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Agent) ensureProject(ctx context.Context, name string) (int64, error) {
|
||||
projects, err := a.api.Projects(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, p := range projects {
|
||||
// Only an own project: a shared one with the same name belongs to someone else
|
||||
if p.Role == "owner" && strings.EqualFold(p.Name, name) {
|
||||
return p.ID, nil
|
||||
}
|
||||
}
|
||||
project, err := a.api.CreateProject(ctx, name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
a.log.Printf("Projekt %q angelegt", name)
|
||||
return project.ID, nil
|
||||
}
|
||||
|
||||
// Run polls the clipboard and listens for live events until ctx ends or the token
|
||||
// is rejected.
|
||||
func (a *Agent) Run(ctx context.Context) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
errs := make(chan error, 2)
|
||||
if a.cfg.Direction.Sends() {
|
||||
go func() { errs <- a.pollLoop(ctx) }()
|
||||
}
|
||||
if a.cfg.Direction.Receives() {
|
||||
go func() { errs <- a.eventLoop(ctx) }()
|
||||
}
|
||||
err := <-errs
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *Agent) pollLoop(ctx context.Context) error {
|
||||
ticker := time.NewTicker(time.Duration(a.cfg.PollMs) * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
if err := a.Tick(ctx); errors.Is(err, api.ErrUnauthorized) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Agent) eventLoop(ctx context.Context) error {
|
||||
delay := minRetry
|
||||
for {
|
||||
started := time.Now()
|
||||
err := a.api.Events(ctx, a.HandleEvent)
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if errors.Is(err, api.ErrUnauthorized) {
|
||||
return err
|
||||
}
|
||||
if time.Since(started) > time.Minute {
|
||||
delay = minRetry // was connected for a while; start backing off anew
|
||||
}
|
||||
a.log.Printf("Live-Verbindung unterbrochen (%v), neuer Versuch in %s", err, delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(delay):
|
||||
}
|
||||
delay = min(delay*2, maxRetry)
|
||||
}
|
||||
}
|
||||
|
||||
// skipReason tells why a text is not sent, or "" if it may be sent.
|
||||
func (a *Agent) skipReason(text string) string {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return "leer"
|
||||
}
|
||||
if utf8.RuneCountInString(text) > a.cfg.MaxChars {
|
||||
return "zu lang"
|
||||
}
|
||||
for _, re := range a.patterns {
|
||||
if re.MatchString(text) {
|
||||
return "Ausschlussmuster"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Tick checks the clipboard once and sends new text. Content is never logged.
|
||||
func (a *Agent) Tick(ctx context.Context) error {
|
||||
content, err := a.clipboard.Read()
|
||||
if err != nil {
|
||||
return nil // transient (clipboard busy); try again next tick
|
||||
}
|
||||
hash := sha256.Sum256([]byte(content.Text))
|
||||
if content.Concealed {
|
||||
hash = concealedHash // the text is unknown; remember "a secret is there" instead
|
||||
}
|
||||
a.mu.Lock()
|
||||
if hash == a.lastHash {
|
||||
a.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
a.lastHash = hash
|
||||
a.mu.Unlock()
|
||||
if content.Concealed {
|
||||
a.log.Print("Von einem Passwort-Manager markierten Inhalt übersprungen")
|
||||
return nil
|
||||
}
|
||||
|
||||
if reason := a.skipReason(content.Text); reason != "" {
|
||||
if reason != "leer" {
|
||||
a.log.Printf("Inhalt nicht gesendet: %s", reason)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
clip, err := a.api.CreateClip(ctx, content.Text, a.projectID)
|
||||
if err != nil {
|
||||
a.log.Printf("Senden fehlgeschlagen: %v", err)
|
||||
return err
|
||||
}
|
||||
a.log.Printf("Gesendet (%d Zeichen)", utf8.RuneCountInString(content.Text))
|
||||
a.mu.Lock()
|
||||
a.own[clip.ID] = true
|
||||
a.sent = append(a.sent, clip.ID)
|
||||
excess := max(len(a.sent)-a.cfg.Keep, 0)
|
||||
old := append([]int64(nil), a.sent[:excess]...)
|
||||
a.sent = a.sent[excess:]
|
||||
a.mu.Unlock()
|
||||
for _, id := range old {
|
||||
if err := a.api.DeleteClip(ctx, id); err != nil {
|
||||
a.log.Printf("Alten Clip %d nicht gelöscht: %v", id, err)
|
||||
}
|
||||
}
|
||||
a.saveState()
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleEvent writes new text/code clips of the same user from other devices to the
|
||||
// clipboard.
|
||||
func (a *Agent) HandleEvent(event api.Event) {
|
||||
if event.Type != "clip.created" {
|
||||
return
|
||||
}
|
||||
var clip api.Clip
|
||||
if err := json.Unmarshal(event.Data, &clip); err != nil {
|
||||
return
|
||||
}
|
||||
if clip.Kind != "text" && clip.Kind != "code" {
|
||||
return
|
||||
}
|
||||
hash := sha256.Sum256([]byte(clip.Content))
|
||||
a.mu.Lock()
|
||||
// Clips of other members of shared projects stay out of this clipboard
|
||||
skip := clip.UserID != a.me || a.own[clip.ID] || hash == a.lastHash
|
||||
if !skip {
|
||||
a.lastHash = hash // so the next poll does not send it back
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if skip {
|
||||
return
|
||||
}
|
||||
if err := a.clipboard.Write(clip.Content); err != nil {
|
||||
a.log.Printf("Zwischenablage nicht gesetzt: %v", err)
|
||||
return
|
||||
}
|
||||
a.log.Printf("Empfangen (%d Zeichen)", utf8.RuneCountInString(clip.Content))
|
||||
}
|
||||
|
||||
func (a *Agent) loadState() {
|
||||
data, err := os.ReadFile(a.statePath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var s state
|
||||
if json.Unmarshal(data, &s) == nil {
|
||||
a.sent = s.Sent
|
||||
for _, id := range s.Sent {
|
||||
a.own[id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Agent) saveState() {
|
||||
a.mu.Lock()
|
||||
data, err := json.Marshal(state{Sent: a.sent})
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmp := a.statePath + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err == nil {
|
||||
os.Rename(tmp, a.statePath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"lan-clipboard/agent/internal/api"
|
||||
"lan-clipboard/agent/internal/clipboard"
|
||||
"lan-clipboard/agent/internal/config"
|
||||
)
|
||||
|
||||
const me = 1
|
||||
|
||||
type fakeClipboard struct {
|
||||
mu sync.Mutex
|
||||
content clipboard.Content
|
||||
writes []string
|
||||
}
|
||||
|
||||
func (f *fakeClipboard) Read() (clipboard.Content, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.content, nil
|
||||
}
|
||||
|
||||
func (f *fakeClipboard) Write(text string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.writes = append(f.writes, text)
|
||||
f.content = clipboard.Content{Text: text}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeClipboard) set(text string, concealed bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.content = clipboard.Content{Text: text, Concealed: concealed}
|
||||
}
|
||||
|
||||
type fakeAPI struct {
|
||||
projects []api.Project
|
||||
created []string
|
||||
clipIDs []int64
|
||||
deleted []int64
|
||||
nextID int64
|
||||
projName string
|
||||
}
|
||||
|
||||
func (f *fakeAPI) Me(context.Context) (api.User, error) {
|
||||
return api.User{ID: me, Username: "anna"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAPI) Projects(context.Context) ([]api.Project, error) { return f.projects, nil }
|
||||
|
||||
func (f *fakeAPI) CreateProject(_ context.Context, name string) (api.Project, error) {
|
||||
f.projName = name
|
||||
return api.Project{ID: 99, Name: name, Role: "owner"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAPI) CreateClip(_ context.Context, content string, _ *int64) (api.Clip, error) {
|
||||
f.nextID++
|
||||
f.created = append(f.created, content)
|
||||
f.clipIDs = append(f.clipIDs, f.nextID)
|
||||
return api.Clip{ID: f.nextID, UserID: me, Kind: "text", Content: content}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAPI) DeleteClip(_ context.Context, id int64) error {
|
||||
f.deleted = append(f.deleted, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeAPI) Events(context.Context, func(api.Event)) error { return nil }
|
||||
|
||||
type fixture struct {
|
||||
agent *Agent
|
||||
api *fakeAPI
|
||||
cb *fakeClipboard
|
||||
logs *bytes.Buffer
|
||||
state string
|
||||
}
|
||||
|
||||
func setup(t *testing.T, mutate func(*config.Config)) fixture {
|
||||
t.Helper()
|
||||
cfg := config.Defaults()
|
||||
cfg.Server, cfg.Token = "https://x.org", "lc_x"
|
||||
if mutate != nil {
|
||||
mutate(&cfg)
|
||||
}
|
||||
f := fixture{api: &fakeAPI{}, cb: &fakeClipboard{}, logs: &bytes.Buffer{}}
|
||||
f.state = filepath.Join(t.TempDir(), "state.json")
|
||||
f.cb.set("already there at start", false)
|
||||
a, err := New(cfg, f.api, f.cb, log.New(f.logs, "", 0), f.state)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.Setup(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.agent = a
|
||||
return f
|
||||
}
|
||||
|
||||
func (f fixture) tick(t *testing.T) {
|
||||
t.Helper()
|
||||
if err := f.agent.Tick(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func event(t *testing.T, kind string, clip api.Clip) api.Event {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(clip)
|
||||
return api.Event{Type: kind, Data: data}
|
||||
}
|
||||
|
||||
func TestSendsNewTextOnlyOnce(t *testing.T) {
|
||||
f := setup(t, nil)
|
||||
f.tick(t) // content present at start is not sent
|
||||
|
||||
f.cb.set("hello", false)
|
||||
f.tick(t)
|
||||
f.tick(t)
|
||||
|
||||
if strings.Join(f.api.created, "|") != "hello" {
|
||||
t.Fatalf("sent %q", f.api.created)
|
||||
}
|
||||
if strings.Contains(f.logs.String(), "hello") {
|
||||
t.Fatal("clipboard content must never be logged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeverSendsConcealedContent(t *testing.T) {
|
||||
f := setup(t, nil)
|
||||
f.cb.set("", true)
|
||||
f.tick(t)
|
||||
f.tick(t)
|
||||
f.tick(t)
|
||||
|
||||
if len(f.api.created) != 0 {
|
||||
t.Fatal("secret sent")
|
||||
}
|
||||
if n := strings.Count(f.logs.String(), "Passwort-Manager"); n != 1 {
|
||||
t.Fatalf("logged %d times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipsBlankLongAndExcludedText(t *testing.T) {
|
||||
f := setup(t, func(c *config.Config) {
|
||||
c.MaxChars = 10
|
||||
c.Exclude = []string{`^\d{6}$`}
|
||||
})
|
||||
for _, text := range []string{" \n", strings.Repeat("ä", 11), "123456"} {
|
||||
f.cb.set(text, false)
|
||||
f.tick(t)
|
||||
}
|
||||
f.cb.set(strings.Repeat("ä", 10), false)
|
||||
f.tick(t)
|
||||
|
||||
if len(f.api.created) != 1 || f.api.created[0] != strings.Repeat("ä", 10) {
|
||||
t.Fatalf("sent %q", f.api.created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceivesOwnClipsFromOtherDevices(t *testing.T) {
|
||||
f := setup(t, nil)
|
||||
f.agent.HandleEvent(event(t, "clip.created", api.Clip{ID: 50, UserID: me, Kind: "code", Content: "from phone"}))
|
||||
|
||||
if strings.Join(f.cb.writes, "|") != "from phone" {
|
||||
t.Fatalf("written %q", f.cb.writes)
|
||||
}
|
||||
f.tick(t) // must not bounce back to the server
|
||||
if len(f.api.created) != 0 {
|
||||
t.Fatalf("received text was sent back: %q", f.api.created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnoresOtherEvents(t *testing.T) {
|
||||
f := setup(t, nil)
|
||||
f.cb.set("mine", false)
|
||||
f.tick(t)
|
||||
ownID := f.api.clipIDs[0]
|
||||
|
||||
for _, e := range []api.Event{
|
||||
event(t, "clip.created", api.Clip{ID: ownID, UserID: me, Kind: "text", Content: "echo"}),
|
||||
event(t, "clip.created", api.Clip{ID: 60, UserID: 2, Kind: "text", Content: "other member"}),
|
||||
event(t, "clip.created", api.Clip{ID: 61, UserID: me, Kind: "file", Content: "bild.png"}),
|
||||
event(t, "clip.updated", api.Clip{ID: 62, UserID: me, Kind: "text", Content: "edited"}),
|
||||
{Type: "clip.created", Data: json.RawMessage(`not json`)},
|
||||
} {
|
||||
f.agent.HandleEvent(e)
|
||||
}
|
||||
if len(f.cb.writes) != 0 {
|
||||
t.Fatalf("written %q", f.cb.writes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirection(t *testing.T) {
|
||||
f := setup(t, func(c *config.Config) { c.Direction = config.Receive })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := f.agent.Run(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(f.api.created) != 0 {
|
||||
t.Fatal("receive-only agent sent something")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeepsOnlyTheNewestClips(t *testing.T) {
|
||||
f := setup(t, func(c *config.Config) { c.Keep = 2 })
|
||||
for _, text := range []string{"a", "b", "c", "d"} {
|
||||
f.cb.set(text, false)
|
||||
f.tick(t)
|
||||
}
|
||||
if got := f.api.deleted; len(got) != 2 || got[0] != 1 || got[1] != 2 {
|
||||
t.Fatalf("deleted %v, want [1 2]", got)
|
||||
}
|
||||
|
||||
// State survives a restart: the next send deletes clip 3
|
||||
again, _ := New(f.agent.cfg, f.api, f.cb, log.New(io.Discard, "", 0), f.state)
|
||||
again.Setup(context.Background())
|
||||
f.cb.set("e", false)
|
||||
again.Tick(context.Background())
|
||||
if got := f.api.deleted; len(got) != 3 || got[2] != 3 {
|
||||
t.Fatalf("deleted %v after restart", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectSetup(t *testing.T) {
|
||||
f := setup(t, nil)
|
||||
if f.api.projName != "Zwischenablage" || *f.agent.projectID != 99 {
|
||||
t.Fatalf("project not created: %q", f.api.projName)
|
||||
}
|
||||
|
||||
existing := &fakeAPI{projects: []api.Project{
|
||||
{ID: 5, Name: "zwischenablage", Role: "edit"}, // shared by someone else: not ours
|
||||
{ID: 6, Name: "Zwischenablage", Role: "owner"},
|
||||
}}
|
||||
cfg := f.agent.cfg
|
||||
a, _ := New(cfg, existing, f.cb, log.New(io.Discard, "", 0), f.state)
|
||||
a.Setup(context.Background())
|
||||
if *a.projectID != 6 || existing.projName != "" {
|
||||
t.Fatalf("existing own project not used: %v", *a.projectID)
|
||||
}
|
||||
|
||||
cfg.Project = ""
|
||||
none, _ := New(cfg, &fakeAPI{}, f.cb, log.New(io.Discard, "", 0), f.state)
|
||||
none.Setup(context.Background())
|
||||
if none.projectID != nil {
|
||||
t.Fatal("no project configured, but one is used")
|
||||
}
|
||||
}
|
||||
|
||||
// Polling and live events run in separate goroutines; run with -race.
|
||||
func TestTickAndEventsConcurrently(t *testing.T) {
|
||||
f := setup(t, nil)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range 200 {
|
||||
f.cb.set(strings.Repeat("x", i%7+1), false)
|
||||
f.agent.Tick(context.Background())
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range 200 {
|
||||
f.agent.HandleEvent(event(t, "clip.created", api.Clip{ID: int64(1000 + i), UserID: me, Kind: "text", Content: "remote"}))
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Package api talks to the LAN-Clipboard server with a device token.
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
// ErrUnauthorized means the token is invalid, revoked or its user deactivated.
|
||||
var ErrUnauthorized = errors.New("Token ungültig oder widerrufen")
|
||||
|
||||
const (
|
||||
closeUnauthorized = 4401
|
||||
// The server pings every 30 s; silence beyond this means the connection is dead
|
||||
readTimeout = 75 * time.Second
|
||||
// Largest event: a clip of up to 200,000 characters, JSON-escaped
|
||||
maxMessageBytes = 4 << 20
|
||||
)
|
||||
|
||||
type Clip struct {
|
||||
ID int64 `json:"id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
Kind string `json:"kind"`
|
||||
Content string `json:"content"`
|
||||
ProjectID *int64 `json:"project_id"`
|
||||
}
|
||||
|
||||
type Project struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// Event is a live-sync message, e.g. {"type": "clip.created", "data": {...}}.
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
base *url.URL
|
||||
token string
|
||||
userAgent string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(server, token, version string) (*Client, error) {
|
||||
base, err := url.Parse(strings.TrimRight(server, "/"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{
|
||||
base: base,
|
||||
token: token,
|
||||
userAgent: fmt.Sprintf("lc-agent/%s (%s)", version, runtime.GOOS),
|
||||
http: &http.Client{Timeout: 30 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader = bytes.NewReader(data)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.base.String()+path, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("%s %s: %s", method, path, errorDetail(resp))
|
||||
}
|
||||
if out == nil {
|
||||
return nil
|
||||
}
|
||||
return json.NewDecoder(resp.Body).Decode(out)
|
||||
}
|
||||
|
||||
func errorDetail(resp *http.Response) string {
|
||||
var payload struct {
|
||||
Detail any `json:"detail"`
|
||||
}
|
||||
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
if json.Unmarshal(data, &payload) == nil {
|
||||
if s, ok := payload.Detail.(string); ok {
|
||||
return fmt.Sprintf("%d %s", resp.StatusCode, s)
|
||||
}
|
||||
}
|
||||
return resp.Status
|
||||
}
|
||||
|
||||
func (c *Client) Me(ctx context.Context) (User, error) {
|
||||
var user User
|
||||
return user, c.do(ctx, http.MethodGet, "/api/users/me", nil, &user)
|
||||
}
|
||||
|
||||
func (c *Client) Projects(ctx context.Context) ([]Project, error) {
|
||||
var projects []Project
|
||||
return projects, c.do(ctx, http.MethodGet, "/api/projects", nil, &projects)
|
||||
}
|
||||
|
||||
func (c *Client) CreateProject(ctx context.Context, name string) (Project, error) {
|
||||
var project Project
|
||||
return project, c.do(ctx, http.MethodPost, "/api/projects", map[string]string{"name": name}, &project)
|
||||
}
|
||||
|
||||
func (c *Client) CreateClip(ctx context.Context, content string, projectID *int64) (Clip, error) {
|
||||
var clip Clip
|
||||
body := map[string]any{"content": content, "kind": "text", "project_id": projectID}
|
||||
return clip, c.do(ctx, http.MethodPost, "/api/clips", body, &clip)
|
||||
}
|
||||
|
||||
// DeleteClip deletes a clip; one that is already gone counts as success.
|
||||
func (c *Client) DeleteClip(ctx context.Context, id int64) error {
|
||||
err := c.do(ctx, http.MethodDelete, fmt.Sprintf("/api/clips/%d", id), nil, nil)
|
||||
if err != nil && strings.Contains(err.Error(), ": 404") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Events connects to the live sync and calls handle for every message until the
|
||||
// connection ends. It returns ErrUnauthorized if the server rejects the token.
|
||||
func (c *Client) Events(ctx context.Context, handle func(Event)) error {
|
||||
wsURL := *c.base
|
||||
wsURL.Scheme = map[string]string{"https": "wss", "http": "ws"}[c.base.Scheme]
|
||||
wsURL.Path += "/api/ws"
|
||||
|
||||
header := http.Header{}
|
||||
header.Set("Authorization", "Bearer "+c.token)
|
||||
header.Set("User-Agent", c.userAgent)
|
||||
conn, resp, err := websocket.Dial(ctx, wsURL.String(), &websocket.DialOptions{HTTPHeader: header})
|
||||
if err != nil {
|
||||
if resp != nil && resp.StatusCode == http.StatusUnauthorized {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
conn.SetReadLimit(maxMessageBytes)
|
||||
|
||||
for {
|
||||
readCtx, cancel := context.WithTimeout(ctx, readTimeout)
|
||||
_, data, err := conn.Read(readCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if websocket.CloseStatus(err) == closeUnauthorized {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return err
|
||||
}
|
||||
var event Event
|
||||
if json.Unmarshal(data, &event) == nil {
|
||||
handle(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
func newServer(t *testing.T, handler http.HandlerFunc) *Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
client, err := New(srv.URL+"/", "lc_token", "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func TestRequestsCarryTokenAndJSON(t *testing.T) {
|
||||
var seen *http.Request
|
||||
var body map[string]any
|
||||
client := newServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
seen = r
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
json.Unmarshal(data, &body)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
io.WriteString(w, `{"id": 7, "user_id": 1, "kind": "text", "content": "hi", "project_id": 3}`)
|
||||
})
|
||||
project := int64(3)
|
||||
|
||||
clip, err := client.CreateClip(context.Background(), "hi", &project)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if clip.ID != 7 || *clip.ProjectID != 3 {
|
||||
t.Fatalf("unexpected clip %+v", clip)
|
||||
}
|
||||
if seen.URL.Path != "/api/clips" || seen.Method != http.MethodPost {
|
||||
t.Fatalf("unexpected request %s %s", seen.Method, seen.URL.Path)
|
||||
}
|
||||
if seen.Header.Get("Authorization") != "Bearer lc_token" {
|
||||
t.Fatal("token missing")
|
||||
}
|
||||
if !strings.HasPrefix(seen.Header.Get("User-Agent"), "lc-agent/test") {
|
||||
t.Fatalf("user agent %q", seen.Header.Get("User-Agent"))
|
||||
}
|
||||
if body["content"] != "hi" || body["kind"] != "text" || body["project_id"] != float64(3) {
|
||||
t.Fatalf("unexpected body %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrors(t *testing.T) {
|
||||
status := http.StatusUnauthorized
|
||||
client := newServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
io.WriteString(w, `{"detail": "Projekt nicht gefunden."}`)
|
||||
})
|
||||
if _, err := client.Me(context.Background()); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("want ErrUnauthorized, got %v", err)
|
||||
}
|
||||
status = http.StatusNotFound
|
||||
if err := client.DeleteClip(context.Background(), 5); err != nil {
|
||||
t.Fatalf("deleting a missing clip should succeed: %v", err)
|
||||
}
|
||||
if _, err := client.CreateProject(context.Background(), "x"); err == nil ||
|
||||
!strings.Contains(err.Error(), "Projekt nicht gefunden.") {
|
||||
t.Fatalf("detail not reported: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsDeliversMessagesAndDetectsRevokedToken(t *testing.T) {
|
||||
client := newServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/ws" || r.Header.Get("Authorization") != "Bearer lc_token" {
|
||||
http.Error(w, "bad", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
conn, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
conn.Write(ctx, websocket.MessageText, []byte(`{"type":"hello"}`))
|
||||
conn.Write(ctx, websocket.MessageText, []byte(`{"type":"clip.created","data":{"id":1}}`))
|
||||
conn.Close(4401, "revoked")
|
||||
})
|
||||
|
||||
var types []string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
err := client.Events(ctx, func(e Event) { types = append(types, e.Type) })
|
||||
|
||||
if !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("want ErrUnauthorized, got %v", err)
|
||||
}
|
||||
if strings.Join(types, ",") != "hello,clip.created" {
|
||||
t.Fatalf("events %v", types)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Package clipboard reads and writes the system clipboard (text only) and detects
|
||||
// content that password managers mark as secret.
|
||||
package clipboard
|
||||
|
||||
// Content is the current clipboard text. Concealed is set when a password manager
|
||||
// marked it as secret; the text is then left empty and must never be sent anywhere.
|
||||
type Content struct {
|
||||
Text string
|
||||
Concealed bool
|
||||
}
|
||||
|
||||
// Clipboard is implemented per operating system (see New in the *_<os>.go files).
|
||||
type Clipboard interface {
|
||||
Read() (Content, error)
|
||||
Write(text string) error
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// JXA script: returns the pasteboard's change count and, if it changed since the count
|
||||
// passed as argument, its types and text. One osascript call per poll, no cgo needed.
|
||||
const readScript = `
|
||||
ObjC.import('AppKit');
|
||||
function run(argv) {
|
||||
const pb = $.NSPasteboard.generalPasteboard;
|
||||
const count = Number(pb.changeCount);
|
||||
if (String(count) === argv[0]) return JSON.stringify({ count: count, same: true });
|
||||
const types = ObjC.deepUnwrap(pb.types) || [];
|
||||
const text = ObjC.unwrap(pb.stringForType($.NSPasteboardTypeString)) || '';
|
||||
return JSON.stringify({ count: count, types: types, text: text });
|
||||
}`
|
||||
|
||||
type darwinClipboard struct {
|
||||
lastCount int
|
||||
last Content
|
||||
}
|
||||
|
||||
func New() (Clipboard, error) {
|
||||
return &darwinClipboard{lastCount: -1}, nil
|
||||
}
|
||||
|
||||
func (c *darwinClipboard) Read() (Content, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "osascript", "-l", "JavaScript", "-e", readScript,
|
||||
strconv.Itoa(c.lastCount)).Output()
|
||||
if err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
var result struct {
|
||||
Count int `json:"count"`
|
||||
Same bool `json:"same"`
|
||||
Types []string `json:"types"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := json.Unmarshal(out, &result); err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
if result.Same {
|
||||
return c.last, nil
|
||||
}
|
||||
c.lastCount = result.Count
|
||||
if isConcealed(result.Types) {
|
||||
c.last = Content{Concealed: true}
|
||||
} else {
|
||||
c.last = Content{Text: result.Text}
|
||||
}
|
||||
return c.last, nil
|
||||
}
|
||||
|
||||
func (c *darwinClipboard) Write(text string) error {
|
||||
cmd := exec.Command("pbcopy")
|
||||
// pbcopy only keeps non-ASCII text intact with a UTF-8 locale
|
||||
cmd.Env = append(os.Environ(), "LANG=en_US.UTF-8")
|
||||
cmd.Stdin = strings.NewReader(text)
|
||||
return cmd.Run()
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const commandTimeout = 3 * time.Second
|
||||
|
||||
// Linux has no clipboard API without a toolkit; the standard tools are used instead:
|
||||
// wl-clipboard on Wayland, xclip on X11.
|
||||
type linuxClipboard struct {
|
||||
listTypes []string
|
||||
read func(textType string) []string
|
||||
write []string
|
||||
}
|
||||
|
||||
// New picks Wayland or X11 depending on the session and the installed tools.
|
||||
func New() (Clipboard, error) {
|
||||
if os.Getenv("WAYLAND_DISPLAY") != "" && hasCommand("wl-paste") && hasCommand("wl-copy") {
|
||||
return &linuxClipboard{
|
||||
listTypes: []string{"wl-paste", "--list-types"},
|
||||
read: func(t string) []string { return []string{"wl-paste", "--no-newline", "--type", t} },
|
||||
write: []string{"wl-copy"},
|
||||
}, nil
|
||||
}
|
||||
if os.Getenv("DISPLAY") != "" && hasCommand("xclip") {
|
||||
return &linuxClipboard{
|
||||
listTypes: []string{"xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"},
|
||||
read: func(t string) []string { return []string{"xclip", "-selection", "clipboard", "-t", t, "-o"} },
|
||||
write: []string{"xclip", "-selection", "clipboard", "-i"},
|
||||
}, nil
|
||||
}
|
||||
return nil, errors.New("keine Zwischenablage gefunden: unter Wayland wl-clipboard, unter X11 xclip installieren")
|
||||
}
|
||||
|
||||
func hasCommand(name string) bool {
|
||||
_, err := exec.LookPath(name)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func run(args []string, stdin string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
|
||||
if stdin != "" {
|
||||
cmd.Stdin = strings.NewReader(stdin)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
err := cmd.Run()
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func (c *linuxClipboard) Read() (Content, error) {
|
||||
output, err := run(c.listTypes, "")
|
||||
if err != nil {
|
||||
// Empty clipboard: the tools exit with an error; not worth reporting
|
||||
return Content{}, nil
|
||||
}
|
||||
types := parseTypes(output)
|
||||
if isConcealed(types) {
|
||||
return Content{Concealed: true}, nil
|
||||
}
|
||||
textType := textType(types)
|
||||
if textType == "" {
|
||||
return Content{}, nil
|
||||
}
|
||||
text, err := run(c.read(textType), "")
|
||||
if err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
return Content{Text: text}, nil
|
||||
}
|
||||
|
||||
func (c *linuxClipboard) Write(text string) error {
|
||||
// xclip and wl-copy keep serving the selection in the background after we return
|
||||
cmd := exec.Command(c.write[0], c.write[1:]...)
|
||||
cmd.Stdin = strings.NewReader(text)
|
||||
return cmd.Run()
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
const (
|
||||
cfUnicodeText = 13
|
||||
gmemMoveable = 0x0002
|
||||
)
|
||||
|
||||
var (
|
||||
user32 = windows.NewLazySystemDLL("user32.dll")
|
||||
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
|
||||
openClipboard = user32.NewProc("OpenClipboard")
|
||||
closeClipboard = user32.NewProc("CloseClipboard")
|
||||
emptyClipboard = user32.NewProc("EmptyClipboard")
|
||||
getClipboardData = user32.NewProc("GetClipboardData")
|
||||
setClipboardData = user32.NewProc("SetClipboardData")
|
||||
isClipboardFormatAvailable = user32.NewProc("IsClipboardFormatAvailable")
|
||||
registerClipboardFormat = user32.NewProc("RegisterClipboardFormatW")
|
||||
globalAlloc = kernel32.NewProc("GlobalAlloc")
|
||||
globalFree = kernel32.NewProc("GlobalFree")
|
||||
globalLock = kernel32.NewProc("GlobalLock")
|
||||
globalUnlock = kernel32.NewProc("GlobalUnlock")
|
||||
)
|
||||
|
||||
// Formats that password managers and other tools set to keep content out of
|
||||
// clipboard history and sync tools (documented by Microsoft for cloud clipboard).
|
||||
var concealedFormats = []string{
|
||||
"ExcludeClipboardContentFromMonitorProcessing",
|
||||
"Clipboard Viewer Ignore",
|
||||
}
|
||||
|
||||
type windowsClipboard struct {
|
||||
concealed []uintptr
|
||||
}
|
||||
|
||||
func New() (Clipboard, error) {
|
||||
c := &windowsClipboard{}
|
||||
for _, name := range concealedFormats {
|
||||
ptr, err := windows.UTF16PtrFromString(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if id, _, _ := registerClipboardFormat.Call(uintptr(unsafe.Pointer(ptr))); id != 0 {
|
||||
c.concealed = append(c.concealed, id)
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// lockedMemory turns the address returned by GlobalLock into a pointer. The memory is
|
||||
// owned by Windows and locked, not part of the Go heap, so the garbage collector cannot
|
||||
// move it; reading the uintptr through a pointer keeps "go vet" from flagging the
|
||||
// (here intended) uintptr conversion.
|
||||
func lockedMemory(addr uintptr) unsafe.Pointer {
|
||||
return *(*unsafe.Pointer)(unsafe.Pointer(&addr))
|
||||
}
|
||||
|
||||
// open retries briefly: another program may hold the clipboard for a moment.
|
||||
func open() error {
|
||||
for i := 0; i < 10; i++ {
|
||||
if r, _, _ := openClipboard.Call(0); r != 0 {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
return errors.New("Zwischenablage ist belegt")
|
||||
}
|
||||
|
||||
func available(format uintptr) bool {
|
||||
r, _, _ := isClipboardFormatAvailable.Call(format)
|
||||
return r != 0
|
||||
}
|
||||
|
||||
func (c *windowsClipboard) Read() (Content, error) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
if err := open(); err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
defer closeClipboard.Call()
|
||||
|
||||
for _, format := range c.concealed {
|
||||
if available(format) {
|
||||
return Content{Concealed: true}, nil
|
||||
}
|
||||
}
|
||||
if !available(cfUnicodeText) {
|
||||
return Content{}, nil
|
||||
}
|
||||
handle, _, _ := getClipboardData.Call(cfUnicodeText)
|
||||
if handle == 0 {
|
||||
return Content{}, nil
|
||||
}
|
||||
ptr, _, _ := globalLock.Call(handle)
|
||||
if ptr == 0 {
|
||||
return Content{}, errors.New("Zwischenablage nicht lesbar")
|
||||
}
|
||||
defer globalUnlock.Call(handle)
|
||||
return Content{Text: windows.UTF16PtrToString((*uint16)(lockedMemory(ptr)))}, nil
|
||||
}
|
||||
|
||||
func (c *windowsClipboard) Write(text string) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
data, err := windows.UTF16FromString(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := open(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeClipboard.Call()
|
||||
emptyClipboard.Call()
|
||||
|
||||
size := uintptr(len(data) * 2)
|
||||
handle, _, _ := globalAlloc.Call(gmemMoveable, size)
|
||||
if handle == 0 {
|
||||
return errors.New("kein Speicher für die Zwischenablage")
|
||||
}
|
||||
ptr, _, _ := globalLock.Call(handle)
|
||||
if ptr == 0 {
|
||||
globalFree.Call(handle)
|
||||
return errors.New("kein Speicher für die Zwischenablage")
|
||||
}
|
||||
copy(unsafe.Slice((*uint16)(lockedMemory(ptr)), len(data)), data)
|
||||
globalUnlock.Call(handle)
|
||||
// On success the system owns the memory; only free it if the hand-over failed
|
||||
if r, _, _ := setClipboardData.Call(cfUnicodeText, handle); r == 0 {
|
||||
globalFree.Call(handle)
|
||||
return errors.New("Zwischenablage konnte nicht gesetzt werden")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package clipboard
|
||||
|
||||
import "strings"
|
||||
|
||||
// Markers set by password managers (KeePassXC, 1Password, Bitwarden, …) on Linux and macOS.
|
||||
// Windows uses registered clipboard formats instead (see clipboard_windows.go).
|
||||
var concealedTypes = map[string]bool{
|
||||
"x-kde-passwordManagerHint": true, // Linux (KDE convention, KeePassXC)
|
||||
"org.nspasteboard.ConcealedType": true, // macOS
|
||||
"org.nspasteboard.TransientType": true, // macOS: not meant to be kept
|
||||
"org.nspasteboard.AutoGeneratedType": true,
|
||||
}
|
||||
|
||||
// Text types offered by X11/Wayland clipboards, in order of preference.
|
||||
var textTypes = []string{"text/plain;charset=utf-8", "UTF8_STRING", "text/plain", "STRING", "TEXT"}
|
||||
|
||||
// parseTypes splits the output of "wl-paste --list-types" or "xclip -t TARGETS -o".
|
||||
func parseTypes(output string) []string {
|
||||
var types []string
|
||||
for _, line := range strings.Split(output, "\n") {
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
types = append(types, line)
|
||||
}
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
func isConcealed(types []string) bool {
|
||||
for _, t := range types {
|
||||
if concealedTypes[t] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// textType returns the best text type on offer, or "" (e.g. only an image was copied).
|
||||
func textType(types []string) string {
|
||||
offered := make(map[string]bool, len(types))
|
||||
for _, t := range types {
|
||||
offered[t] = true
|
||||
}
|
||||
for _, t := range textTypes {
|
||||
if offered[t] {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package clipboard
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseTypes(t *testing.T) {
|
||||
got := parseTypes("TARGETS\n UTF8_STRING \n\nx-kde-passwordManagerHint\n")
|
||||
if len(got) != 3 || got[1] != "UTF8_STRING" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcealedAndTextType(t *testing.T) {
|
||||
keepass := []string{"TARGETS", "x-kde-passwordManagerHint", "UTF8_STRING"}
|
||||
if !isConcealed(keepass) {
|
||||
t.Fatal("KeePassXC hint not detected")
|
||||
}
|
||||
if isConcealed([]string{"UTF8_STRING", "text/plain"}) {
|
||||
t.Fatal("plain text treated as secret")
|
||||
}
|
||||
if got := textType([]string{"STRING", "text/plain;charset=utf-8"}); got != "text/plain;charset=utf-8" {
|
||||
t.Fatalf("preferred type %q", got)
|
||||
}
|
||||
if textType([]string{"image/png"}) != "" {
|
||||
t.Fatal("image treated as text")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Package config loads and stores the agent configuration (server, token, options).
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Direction controls which way the clipboard is synchronised.
|
||||
type Direction string
|
||||
|
||||
const (
|
||||
Both Direction = "both"
|
||||
Send Direction = "send"
|
||||
Receive Direction = "receive"
|
||||
)
|
||||
|
||||
// Config is stored as JSON; the file contains the token and is only readable by the user.
|
||||
type Config struct {
|
||||
Server string `json:"server"`
|
||||
Token string `json:"token"`
|
||||
Direction Direction `json:"direction"`
|
||||
// Project for clips sent by the agent; created if missing. Empty: no project.
|
||||
Project string `json:"project"`
|
||||
// Number of own clips kept on the server; older ones are deleted by the agent.
|
||||
Keep int `json:"keep"`
|
||||
MaxChars int `json:"max_chars"`
|
||||
Exclude []string `json:"exclude"`
|
||||
PollMs int `json:"poll_ms"`
|
||||
}
|
||||
|
||||
// Defaults returns the configuration used for missing fields.
|
||||
func Defaults() Config {
|
||||
return Config{
|
||||
Direction: Both,
|
||||
Project: "Zwischenablage",
|
||||
Keep: 50,
|
||||
MaxChars: 100_000,
|
||||
Exclude: []string{},
|
||||
PollMs: 700,
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultPath is <user config dir>/lan-clipboard/agent.json.
|
||||
func DefaultPath() (string, error) {
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, "lan-clipboard", "agent.json"), nil
|
||||
}
|
||||
|
||||
// StatePath is the file next to the config that remembers the agent's own clips.
|
||||
func StatePath(configPath string) string {
|
||||
return filepath.Join(filepath.Dir(configPath), "agent-state.json")
|
||||
}
|
||||
|
||||
// Load reads the config file on top of the defaults and validates it.
|
||||
func Load(path string) (Config, error) {
|
||||
cfg := Defaults()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return cfg, fmt.Errorf("keine Konfiguration unter %s – zuerst \"lc-agent setup\" ausführen", path)
|
||||
}
|
||||
return cfg, err
|
||||
}
|
||||
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
return cfg, cfg.Validate()
|
||||
}
|
||||
|
||||
// Save writes the config atomically with permissions 0600 (directory 0700).
|
||||
func Save(path string, cfg Config) error {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
// Validate checks all fields; the token is only sent over HTTPS (or to localhost).
|
||||
func (c Config) Validate() error {
|
||||
u, err := url.Parse(c.Server)
|
||||
if err != nil || u.Host == "" {
|
||||
return fmt.Errorf("ungültige Server-Adresse %q", c.Server)
|
||||
}
|
||||
local := u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"
|
||||
if u.Scheme != "https" && !(u.Scheme == "http" && local) {
|
||||
return errors.New("die Server-Adresse muss mit https:// beginnen")
|
||||
}
|
||||
if !strings.HasPrefix(c.Token, "lc_") {
|
||||
return errors.New("der Token muss mit lc_ beginnen (unter \"Konto\" → \"Geräte-Tokens\" erstellen)")
|
||||
}
|
||||
switch c.Direction {
|
||||
case Both, Send, Receive:
|
||||
default:
|
||||
return fmt.Errorf("ungültige Richtung %q (both, send oder receive)", c.Direction)
|
||||
}
|
||||
if c.Keep < 1 || c.MaxChars < 1 || c.PollMs < 100 {
|
||||
return errors.New("keep und max_chars müssen ≥ 1 sein, poll_ms ≥ 100")
|
||||
}
|
||||
_, err = c.Patterns()
|
||||
return err
|
||||
}
|
||||
|
||||
// Patterns compiles the exclude expressions.
|
||||
func (c Config) Patterns() ([]*regexp.Regexp, error) {
|
||||
patterns := make([]*regexp.Regexp, 0, len(c.Exclude))
|
||||
for _, expr := range c.Exclude {
|
||||
re, err := regexp.Compile(expr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Ausschlussmuster %q: %w", expr, err)
|
||||
}
|
||||
patterns = append(patterns, re)
|
||||
}
|
||||
return patterns, nil
|
||||
}
|
||||
|
||||
// Sends and Receives tell whether the direction includes that way.
|
||||
func (d Direction) Sends() bool { return d == Both || d == Send }
|
||||
func (d Direction) Receives() bool { return d == Both || d == Receive }
|
||||
@@ -0,0 +1,87 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func valid() Config {
|
||||
cfg := Defaults()
|
||||
cfg.Server = "https://clip.example.org"
|
||||
cfg.Token = "lc_abc"
|
||||
return cfg
|
||||
}
|
||||
|
||||
func TestSaveAndLoad(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "sub", "agent.json")
|
||||
cfg := valid()
|
||||
cfg.Exclude = []string{`^\d{6}$`}
|
||||
if err := Save(path, cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Server != cfg.Server || got.Token != cfg.Token || got.Exclude[0] != cfg.Exclude[0] {
|
||||
t.Fatalf("roundtrip mismatch: %+v", got)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
info, _ := os.Stat(path)
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("config readable by others: %v", info.Mode())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFillsDefaults(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "agent.json")
|
||||
os.WriteFile(path, []byte(`{"server":"https://x.org","token":"lc_x"}`), 0o600)
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Direction != Both || cfg.Keep != 50 || cfg.Project != "Zwischenablage" {
|
||||
t.Fatalf("defaults missing: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingFileExplainsSetup(t *testing.T) {
|
||||
_, err := Load(filepath.Join(t.TempDir(), "nope.json"))
|
||||
if err == nil || !strings.Contains(err.Error(), "lc-agent setup") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
cases := map[string]func(*Config){
|
||||
"http to remote": func(c *Config) { c.Server = "http://clip.example.org" },
|
||||
"no host": func(c *Config) { c.Server = "https://" },
|
||||
"bad token": func(c *Config) { c.Token = "secret" },
|
||||
"bad direction": func(c *Config) { c.Direction = "sideways" },
|
||||
"keep zero": func(c *Config) { c.Keep = 0 },
|
||||
"poll too fast": func(c *Config) { c.PollMs = 10 },
|
||||
"bad exclude": func(c *Config) { c.Exclude = []string{"("} },
|
||||
}
|
||||
for name, mutate := range cases {
|
||||
cfg := valid()
|
||||
mutate(&cfg)
|
||||
if cfg.Validate() == nil {
|
||||
t.Errorf("%s: expected an error", name)
|
||||
}
|
||||
}
|
||||
local := valid()
|
||||
local.Server = "http://localhost:8000"
|
||||
if err := local.Validate(); err != nil {
|
||||
t.Errorf("localhost over http should be allowed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirection(t *testing.T) {
|
||||
if !Both.Sends() || !Both.Receives() || Send.Receives() || Receive.Sends() {
|
||||
t.Fatal("direction helpers wrong")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"""projects
|
||||
|
||||
Revision ID: 0004
|
||||
Revises: 0003
|
||||
Create Date: 2026-10-25 13:12:18.898120
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0004"
|
||||
down_revision: str | None = "0003"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"projects",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.String(length=100), nullable=False),
|
||||
sa.Column("name_key", sa.String(length=100), nullable=False),
|
||||
sa.Column("color", sa.String(length=16), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("user_id", "name_key", name="uq_projects_user_name"),
|
||||
)
|
||||
with op.batch_alter_table("clips", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("project_id", sa.Integer(), nullable=True))
|
||||
batch_op.create_index("ix_clips_user_project", ["user_id", "project_id"], unique=False)
|
||||
batch_op.create_foreign_key(
|
||||
"fk_clips_project_id", "projects", ["project_id"], ["id"], ondelete="SET NULL"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("clips", schema=None) as batch_op:
|
||||
batch_op.drop_constraint("fk_clips_project_id", type_="foreignkey")
|
||||
batch_op.drop_index("ix_clips_user_project")
|
||||
batch_op.drop_column("project_id")
|
||||
|
||||
op.drop_table("projects")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""files
|
||||
|
||||
Revision ID: 0005
|
||||
Revises: 0004
|
||||
Create Date: 2026-10-25 13:57:03.762901
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0005"
|
||||
down_revision: str | None = "0004"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"files",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("clip_id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("storage_name", sa.String(length=64), nullable=False),
|
||||
sa.Column("name", sa.String(length=255), nullable=False),
|
||||
sa.Column("content_type", sa.String(length=127), nullable=False),
|
||||
sa.Column("size", sa.BigInteger(), nullable=False),
|
||||
sa.Column("sha256", sa.String(length=64), nullable=False),
|
||||
sa.Column("previewable", sa.Boolean(), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["clip_id"], ["clips.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("clip_id"),
|
||||
sa.UniqueConstraint("storage_name"),
|
||||
)
|
||||
with op.batch_alter_table("files", schema=None) as batch_op:
|
||||
batch_op.create_index("ix_files_expires_at", ["expires_at"], unique=False)
|
||||
batch_op.create_index("ix_files_user", ["user_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# File clips cannot exist without their table; the files on disk stay as orphans
|
||||
op.execute("DELETE FROM clips WHERE kind = 'file'")
|
||||
with op.batch_alter_table("files", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_files_user")
|
||||
batch_op.drop_index("ix_files_expires_at")
|
||||
|
||||
op.drop_table("files")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""project members
|
||||
|
||||
Revision ID: 0006
|
||||
Revises: 0005
|
||||
Create Date: 2026-10-25 14:32:00.250799
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0006"
|
||||
down_revision: str | None = "0005"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"project_members",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("project_id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column(
|
||||
"role",
|
||||
sa.Enum("edit", "read", name="memberrole", native_enum=False, length=16),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["project_id"], ["projects.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("project_id", "user_id", name="uq_project_members"),
|
||||
)
|
||||
with op.batch_alter_table("project_members", schema=None) as batch_op:
|
||||
batch_op.create_index("ix_project_members_user", ["user_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Without sharing, clips may only sit in projects of their own owner
|
||||
op.execute(
|
||||
"UPDATE clips SET project_id = NULL WHERE project_id IS NOT NULL AND user_id != "
|
||||
"(SELECT user_id FROM projects WHERE projects.id = clips.project_id)"
|
||||
)
|
||||
with op.batch_alter_table("project_members", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_project_members_user")
|
||||
|
||||
op.drop_table("project_members")
|
||||
@@ -0,0 +1,43 @@
|
||||
"""api tokens
|
||||
|
||||
Revision ID: 0007
|
||||
Revises: 0006
|
||||
Create Date: 2026-10-25 14:49:30.200128
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0007"
|
||||
down_revision: str | None = "0006"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"api_tokens",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.String(length=100), nullable=False),
|
||||
sa.Column("token_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("prefix", sa.String(length=16), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("last_used_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("last_ip", sa.String(length=45), nullable=True),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("token_hash"),
|
||||
)
|
||||
with op.batch_alter_table("api_tokens", schema=None) as batch_op:
|
||||
batch_op.create_index("ix_api_tokens_user", ["user_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("api_tokens", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_api_tokens_user")
|
||||
|
||||
op.drop_table("api_tokens")
|
||||
@@ -1,10 +1,16 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.api.deps import AdminUser, DbSession
|
||||
from app.config import get_settings
|
||||
from app.models import User
|
||||
from app.schemas.auth import UserOut
|
||||
from app.schemas.users import UserCreate, UserUpdate
|
||||
from app.services import backup as backup_service
|
||||
from app.services import users as user_service
|
||||
from app.ws.hub import hub
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
@@ -32,13 +38,52 @@ def get_user(user_id: int, _admin: AdminUser, db: DbSession):
|
||||
|
||||
|
||||
@router.patch("/users/{user_id}", response_model=UserOut)
|
||||
def update_user(user_id: int, body: UserUpdate, admin: AdminUser, db: DbSession):
|
||||
def update_user(
|
||||
user_id: int, body: UserUpdate, admin: AdminUser, db: DbSession, background: BackgroundTasks
|
||||
):
|
||||
target = _get_user_or_404(db, user_id)
|
||||
return user_service.update_user(
|
||||
user = user_service.update_user(
|
||||
db, admin, target, role=body.role, is_active=body.is_active, password=body.password
|
||||
)
|
||||
if body.is_active is False or body.password is not None:
|
||||
background.add_task(hub.close_user, user_id)
|
||||
return user
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_user(user_id: int, admin: AdminUser, db: DbSession) -> None:
|
||||
def delete_user(user_id: int, admin: AdminUser, db: DbSession, background: BackgroundTasks) -> None:
|
||||
user_service.delete_user(db, admin, _get_user_or_404(db, user_id))
|
||||
background.add_task(hub.close_user, user_id)
|
||||
|
||||
|
||||
class BackupFile(BaseModel):
|
||||
name: str
|
||||
size: int
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class BackupStatus(BaseModel):
|
||||
enabled: bool
|
||||
hour: int
|
||||
latest: BackupFile | None
|
||||
count: int
|
||||
# No backup within the last day: something is wrong (or the job is disabled)
|
||||
stale: bool
|
||||
last_error: str | None
|
||||
|
||||
|
||||
@router.get("/backup", response_model=BackupStatus)
|
||||
def backup_status(_admin: AdminUser) -> BackupStatus:
|
||||
settings = get_settings()
|
||||
backups = backup_service.list_backups()
|
||||
latest = backups[0] if backups else None
|
||||
return BackupStatus(
|
||||
enabled=settings.backup_enabled,
|
||||
hour=settings.backup_hour,
|
||||
latest=None
|
||||
if latest is None
|
||||
else BackupFile(name=latest.path.name, size=latest.size, created_at=latest.created_at),
|
||||
count=len(backups),
|
||||
stale=backup_service.needs_catch_up(),
|
||||
last_error=backup_service.last_error,
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException, Request, Response, status
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, Response, status
|
||||
|
||||
from app.api.deps import (
|
||||
SESSION_COOKIE,
|
||||
@@ -20,6 +20,7 @@ from app.security import verify_password
|
||||
from app.services import sessions as session_service
|
||||
from app.services.auth import LoginBlocked, authenticate
|
||||
from app.services.users import set_password
|
||||
from app.ws.hub import hub
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
@@ -49,9 +50,12 @@ def login(body: LoginRequest, request: Request, response: Response, db: DbSessio
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def logout(session: CurrentSession, response: Response, db: DbSession) -> None:
|
||||
def logout(
|
||||
session: CurrentSession, response: Response, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
session_service.revoke_session(db, session.user_id, session.id)
|
||||
clear_session_cookies(response)
|
||||
background.add_task(hub.close_session, session.id)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
@@ -60,10 +64,16 @@ def me(user: CurrentUser):
|
||||
|
||||
|
||||
@router.post("/password", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def change_password(body: PasswordChangeRequest, session: CurrentSession, db: DbSession) -> None:
|
||||
def change_password(
|
||||
body: PasswordChangeRequest,
|
||||
session: CurrentSession,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> None:
|
||||
if not verify_password(session.user.password_hash, body.current_password):
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Das aktuelle Passwort ist falsch.")
|
||||
set_password(db, session.user, body.new_password, keep_session_id=session.id)
|
||||
background.add_task(hub.close_user, session.user_id, except_session_id=session.id)
|
||||
|
||||
|
||||
@router.get("/sessions", response_model=list[SessionOut])
|
||||
@@ -76,15 +86,23 @@ def list_sessions(session: CurrentSession, db: DbSession) -> list[SessionOut]:
|
||||
|
||||
@router.delete("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def revoke_session(
|
||||
session_id: int, session: CurrentSession, response: Response, db: DbSession
|
||||
session_id: int,
|
||||
session: CurrentSession,
|
||||
response: Response,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> None:
|
||||
if not session_service.revoke_session(db, session.user_id, session_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Sitzung nicht gefunden.")
|
||||
if session_id == session.id:
|
||||
clear_session_cookies(response)
|
||||
background.add_task(hub.close_session, session_id)
|
||||
|
||||
|
||||
@router.delete("/sessions", response_model=RevokedResponse)
|
||||
def revoke_other_sessions(session: CurrentSession, db: DbSession) -> RevokedResponse:
|
||||
def revoke_other_sessions(
|
||||
session: CurrentSession, db: DbSession, background: BackgroundTasks
|
||||
) -> RevokedResponse:
|
||||
revoked = session_service.revoke_other_sessions(db, session.user_id, session.id)
|
||||
background.add_task(hub.close_user, session.user_id, except_session_id=session.id)
|
||||
return RevokedResponse(revoked=revoked)
|
||||
@@ -1,21 +1,30 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Clip
|
||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||
from app.services import clips as clip_service
|
||||
from app.services.access import clip_audience
|
||||
|
||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
|
||||
# Fields that may be null on purpose (clearing them); all others are ignored when null
|
||||
_NULLABLE_FIELDS = {"title", "language"}
|
||||
_NULLABLE_FIELDS = {"title", "language", "project_id"}
|
||||
|
||||
# "none" or a project id
|
||||
_PROJECT_FILTER = r"^(none|[1-9][0-9]{0,17})$"
|
||||
|
||||
|
||||
def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
# Foreign and missing clips look the same, so ids of other users are not revealed
|
||||
def _clip_data(clip: Clip) -> dict:
|
||||
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||
|
||||
|
||||
def _get_visible_clip(db: DbSession, user: ApiUser, clip_id: int) -> Clip:
|
||||
# Invisible and missing clips look the same, so ids of other users are not revealed
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
if clip is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
@@ -24,46 +33,82 @@ def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
|
||||
@router.get("", response_model=ClipList)
|
||||
def list_clips(
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
offset: Annotated[int, Query(ge=0)] = 0,
|
||||
project: Annotated[str | None, Query(pattern=_PROJECT_FILTER)] = None,
|
||||
q: Annotated[str | None, Query(max_length=clip_service.SEARCH_MAX_LENGTH)] = None,
|
||||
) -> ClipList:
|
||||
items, total = clip_service.list_clips(db, user.id, limit, offset)
|
||||
project_filter = project if project in (None, clip_service.NO_PROJECT) else int(project)
|
||||
items, total = clip_service.list_clips(
|
||||
db, user.id, limit, offset, project=project_filter, query=q
|
||||
)
|
||||
return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession):
|
||||
return clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
def create_clip(body: ClipCreate, user: ApiUser, db: DbSession, background: BackgroundTasks):
|
||||
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
notify(
|
||||
background,
|
||||
clip_audience(db, clip.user_id, clip.project_id),
|
||||
"clip.created",
|
||||
_clip_data(clip),
|
||||
)
|
||||
return clip
|
||||
|
||||
|
||||
# Before /{clip_id}, which would otherwise answer "latest" with 422
|
||||
@router.get("/latest", response_model=ClipOut)
|
||||
def latest_clip(user: ApiUser, db: DbSession):
|
||||
"""For scripts such as the iPhone shortcut: newest text/code clip, pinned or not."""
|
||||
clip = clip_service.latest_text_clip(db, user.id)
|
||||
if clip is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Noch keine Clips.")
|
||||
return clip
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
return _get_own_clip(db, user, clip_id)
|
||||
def get_clip(clip_id: int, user: ApiUser, db: DbSession):
|
||||
return _get_visible_clip(db, user, clip_id)
|
||||
|
||||
|
||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||
def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession):
|
||||
clip = _get_own_clip(db, user, clip_id)
|
||||
def update_clip(
|
||||
clip_id: int,
|
||||
body: ClipUpdate,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
clip = _get_visible_clip(db, user, clip_id)
|
||||
changes = {
|
||||
field: getattr(body, field)
|
||||
for field in body.model_fields_set - {"version"}
|
||||
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
||||
}
|
||||
before = clip_audience(db, clip.user_id, clip.project_id)
|
||||
try:
|
||||
return clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||
clip = clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||
except clip_service.ClipConflict as exc:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
content={
|
||||
"detail": "Der Clip wurde inzwischen auf einem anderen Gerät geändert.",
|
||||
"current": ClipOut.model_validate(exc.current).model_dump(mode="json"),
|
||||
"current": _clip_data(exc.current),
|
||||
},
|
||||
)
|
||||
after = clip_audience(db, clip.user_id, clip.project_id)
|
||||
notify(background, after, "clip.updated", _clip_data(clip))
|
||||
# Moved out of a shared project: the others no longer see it
|
||||
notify(background, before - after, "clip.deleted", {"id": clip.id})
|
||||
return clip
|
||||
|
||||
|
||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None:
|
||||
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
def delete_clip(clip_id: int, user: ApiUser, db: DbSession, background: BackgroundTasks) -> None:
|
||||
clip = _get_visible_clip(db, user, clip_id)
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
clip_service.delete_clip(db, user.id, clip)
|
||||
notify(background, audience, "clip.deleted", {"id": clip_id})
|
||||
@@ -9,6 +9,7 @@ from app.db import get_db
|
||||
from app.middleware import SAFE_METHODS
|
||||
from app.models import User, UserSession
|
||||
from app.services.sessions import resolve_session
|
||||
from app.services.tokens import resolve_token
|
||||
|
||||
SESSION_COOKIE = "lc_session"
|
||||
CSRF_COOKIE = "lc_csrf"
|
||||
@@ -37,6 +38,28 @@ def get_current_user(session: CurrentSession) -> User:
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
|
||||
|
||||
def bearer_token(authorization: str | None) -> str | None:
|
||||
if authorization and authorization[:7].lower() == "bearer ":
|
||||
return authorization[7:].strip()
|
||||
return None
|
||||
|
||||
|
||||
def get_api_user(request: Request, db: DbSession) -> User:
|
||||
"""Session or device token (Authorization: Bearer). Only for the endpoints the desktop
|
||||
agent needs; admin, password, sessions and token management stay session-only."""
|
||||
plain = bearer_token(request.headers.get("authorization"))
|
||||
if plain is None:
|
||||
return get_current_session(request, db).user
|
||||
token = resolve_token(db, plain, client_ip(request))
|
||||
if token is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token ungültig oder widerrufen.")
|
||||
# No CSRF check: browsers never attach this header on their own
|
||||
return token.user
|
||||
|
||||
|
||||
ApiUser = Annotated[User, Depends(get_api_user)]
|
||||
|
||||
|
||||
def require_admin(user: CurrentUser) -> User:
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Nur für Administratoren.")
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, status
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.config import get_settings
|
||||
from app.schemas.clips import ClipOut
|
||||
from app.services import clips as clip_service
|
||||
from app.services import files as file_service
|
||||
from app.services.access import clip_audience
|
||||
|
||||
router = APIRouter(prefix="/files", tags=["files"])
|
||||
|
||||
UPLOAD_PATH = "/api/files"
|
||||
# A downloaded file must never run as a page of this origin
|
||||
_DOWNLOAD_CSP = "default-src 'none'; sandbox"
|
||||
|
||||
|
||||
class Usage(BaseModel):
|
||||
used_bytes: int
|
||||
quota_bytes: int
|
||||
max_file_bytes: int
|
||||
|
||||
|
||||
class ExpiryUpdate(BaseModel):
|
||||
expires_days: int
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
async def upload(
|
||||
request: Request,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
name: Annotated[str, Query(max_length=1000)],
|
||||
expires_days: int = 7,
|
||||
project_id: int | None = None,
|
||||
title: Annotated[str | None, Query(max_length=1000)] = None,
|
||||
):
|
||||
"""Raw file body (not multipart), streamed to disk; metadata in the query string."""
|
||||
length = request.headers.get("content-length", "")
|
||||
if not length.isdigit():
|
||||
raise HTTPException(status.HTTP_411_LENGTH_REQUIRED, "Content-Length fehlt.")
|
||||
clip = await file_service.store_upload(
|
||||
db,
|
||||
user.id,
|
||||
request.stream(),
|
||||
name=name,
|
||||
size=int(length),
|
||||
content_type=request.headers.get("content-type"),
|
||||
expires_days=expires_days,
|
||||
project_id=project_id,
|
||||
title=title,
|
||||
)
|
||||
out = ClipOut.model_validate(clip)
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
notify(background, audience, "clip.created", out.model_dump(mode="json"))
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/usage", response_model=Usage)
|
||||
def usage(user: ApiUser, db: DbSession) -> Usage:
|
||||
settings = get_settings()
|
||||
return Usage(
|
||||
used_bytes=file_service.used_bytes(db, user.id),
|
||||
quota_bytes=settings.file_quota_bytes,
|
||||
max_file_bytes=settings.file_max_bytes,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{clip_id}")
|
||||
def download(clip_id: int, user: ApiUser, db: DbSession, inline: bool = False):
|
||||
stored = file_service.get_file(db, user.id, clip_id)
|
||||
# Stored under the uploader, who may be another member of a shared project
|
||||
path = None if stored is None else file_service.file_path(stored.user_id, stored.storage_name)
|
||||
if stored is None or path is None or not path.is_file():
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Datei nicht gefunden.")
|
||||
# Only verified images may be shown in the browser; everything else is a download
|
||||
show_inline = inline and stored.previewable
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=stored.content_type,
|
||||
headers={
|
||||
"Content-Disposition": file_service.content_disposition(stored.name, show_inline),
|
||||
"Content-Security-Policy": _DOWNLOAD_CSP,
|
||||
"Cache-Control": "private, no-cache",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||
def update_expiry(
|
||||
clip_id: int,
|
||||
body: ExpiryUpdate,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
if clip is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
clip = file_service.set_expiry(db, user.id, clip, body.expires_days)
|
||||
out = ClipOut.model_validate(clip)
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
notify(background, audience, "clip.updated", out.model_dump(mode="json"))
|
||||
return out
|
||||
@@ -0,0 +1,11 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
from app.ws.hub import hub
|
||||
|
||||
|
||||
def notify(background: BackgroundTasks, user_ids: Iterable[int], event: str, data: dict) -> None:
|
||||
"""Tell all devices of these users about a change, after the response is sent."""
|
||||
for user_id in set(user_ids):
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
@@ -0,0 +1,181 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
|
||||
from app.api.deps import ApiUser, CurrentUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Project
|
||||
from app.schemas.projects import (
|
||||
MemberAdd,
|
||||
MemberOut,
|
||||
MemberUpdate,
|
||||
ProjectCreate,
|
||||
ProjectOut,
|
||||
ProjectUpdate,
|
||||
)
|
||||
from app.services import projects as project_service
|
||||
from app.services.access import project_audience
|
||||
from app.services.projects import ProjectView
|
||||
|
||||
# Device tokens may list and create projects (the agent sets up its own); managing
|
||||
# projects and members needs a browser session
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
|
||||
def _out(view: ProjectView) -> ProjectOut:
|
||||
p = view.project
|
||||
return ProjectOut(
|
||||
id=p.id,
|
||||
name=p.name,
|
||||
color=p.color,
|
||||
role=view.role.value,
|
||||
owner_name=view.owner_name,
|
||||
clip_count=view.clip_count,
|
||||
member_count=view.member_count,
|
||||
created_at=p.created_at,
|
||||
updated_at=p.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _view(db: DbSession, user: CurrentUser, project_id: int) -> ProjectView:
|
||||
view = project_service.view_project(db, user.id, project_id)
|
||||
if view is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Projekt nicht gefunden.")
|
||||
return view
|
||||
|
||||
|
||||
def _owned(db: DbSession, user: CurrentUser, project_id: int) -> Project:
|
||||
"""Only the owner manages a project; members get 403, everyone else 404."""
|
||||
view = _view(db, user, project_id)
|
||||
if view.project.user_id != user.id:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Nur der Besitzer kann das ändern.")
|
||||
return view.project
|
||||
|
||||
|
||||
def _notify_project(
|
||||
background: BackgroundTasks,
|
||||
db: DbSession,
|
||||
project_id: int,
|
||||
event: str,
|
||||
user_ids: Iterable[int],
|
||||
) -> None:
|
||||
"""Send each user the project as they see it (role and owner differ per viewer)."""
|
||||
for user_id in set(user_ids):
|
||||
view = project_service.view_project(db, user_id, project_id)
|
||||
if view is not None:
|
||||
notify(background, [user_id], event, _out(view).model_dump(mode="json"))
|
||||
|
||||
|
||||
@router.get("", response_model=list[ProjectOut])
|
||||
def list_projects(user: ApiUser, db: DbSession) -> list[ProjectOut]:
|
||||
return [_out(view) for view in project_service.list_projects(db, user.id)]
|
||||
|
||||
|
||||
@router.post("", response_model=ProjectOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_project(
|
||||
body: ProjectCreate, user: ApiUser, db: DbSession, background: BackgroundTasks
|
||||
) -> ProjectOut:
|
||||
project = project_service.create_project(db, user.id, **body.model_dump())
|
||||
out = _out(_view(db, user, project.id))
|
||||
notify(background, [user.id], "project.created", out.model_dump(mode="json"))
|
||||
return out
|
||||
|
||||
|
||||
@router.patch("/{project_id}", response_model=ProjectOut)
|
||||
def update_project(
|
||||
project_id: int,
|
||||
body: ProjectUpdate,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> ProjectOut:
|
||||
project = _owned(db, user, project_id)
|
||||
project_service.update_project(db, project, name=body.name, color=body.color)
|
||||
_notify_project(background, db, project_id, "project.updated", project_audience(db, project_id))
|
||||
return _out(_view(db, user, project_id))
|
||||
|
||||
|
||||
@router.delete("/{project_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_project(
|
||||
project_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
_owned(db, user, project_id)
|
||||
audience = project_audience(db, project_id)
|
||||
project_service.delete_project(db, user.id, project_id)
|
||||
# Clients detach: own clips move to "no project", clips of others disappear
|
||||
notify(background, audience, "project.deleted", {"id": project_id})
|
||||
|
||||
|
||||
# --- Members --------------------------------------------------------------------
|
||||
|
||||
|
||||
def _members_out(db: DbSession, project: Project) -> list[MemberOut]:
|
||||
return [
|
||||
MemberOut(user_id=m.user_id, username=m.username, role=m.role.value)
|
||||
for m in project_service.list_members(db, project)
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{project_id}/members", response_model=list[MemberOut])
|
||||
def list_members(project_id: int, user: CurrentUser, db: DbSession) -> list[MemberOut]:
|
||||
return _members_out(db, _view(db, user, project_id).project)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{project_id}/members", response_model=list[MemberOut], status_code=status.HTTP_201_CREATED
|
||||
)
|
||||
def add_member(
|
||||
project_id: int,
|
||||
body: MemberAdd,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> list[MemberOut]:
|
||||
project = _owned(db, user, project_id)
|
||||
added = project_service.add_member(db, project, body.username, body.role)
|
||||
# The new member's clients reload their clips when the project appears
|
||||
_notify_project(background, db, project_id, "project.created", [added.id])
|
||||
others = project_audience(db, project_id) - {added.id}
|
||||
_notify_project(background, db, project_id, "project.updated", others)
|
||||
return _members_out(db, project)
|
||||
|
||||
|
||||
@router.patch("/{project_id}/members/{member_id}", response_model=list[MemberOut])
|
||||
def update_member(
|
||||
project_id: int,
|
||||
member_id: int,
|
||||
body: MemberUpdate,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> list[MemberOut]:
|
||||
project = _owned(db, user, project_id)
|
||||
if not project_service.set_member_role(db, project, member_id, body.role):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Mitglied nicht gefunden.")
|
||||
_notify_project(background, db, project_id, "project.updated", [member_id])
|
||||
return _members_out(db, project)
|
||||
|
||||
|
||||
@router.delete("/{project_id}/members/{member_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def remove_member(
|
||||
project_id: int,
|
||||
member_id: int,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> None:
|
||||
"""The owner removes a member, or a member leaves (member_id = own id)."""
|
||||
if member_id != user.id:
|
||||
_owned(db, user, project_id)
|
||||
else:
|
||||
_view(db, user, project_id)
|
||||
moved = project_service.remove_member(db, project_id, member_id)
|
||||
if moved is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Mitglied nicht gefunden.")
|
||||
remaining = project_audience(db, project_id)
|
||||
# For the former member the project is gone; their clips are back in "no project"
|
||||
notify(background, [member_id], "project.deleted", {"id": project_id})
|
||||
# The others no longer see the former member's clips
|
||||
for clip_id in moved:
|
||||
notify(background, remaining, "clip.deleted", {"id": clip_id})
|
||||
_notify_project(background, db, project_id, "project.updated", remaining)
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.services import tokens as token_service
|
||||
from app.ws.hub import hub
|
||||
|
||||
# Session only: a device token must not be able to create or list tokens
|
||||
router = APIRouter(prefix="/tokens", tags=["tokens"])
|
||||
|
||||
|
||||
class TokenCreate(BaseModel):
|
||||
name: str = Field(max_length=1000)
|
||||
|
||||
|
||||
class TokenOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
prefix: str
|
||||
created_at: datetime
|
||||
last_used_at: datetime | None
|
||||
last_ip: str | None
|
||||
|
||||
|
||||
class TokenCreated(TokenOut):
|
||||
token: str = Field(description="Shown only once")
|
||||
|
||||
|
||||
@router.get("", response_model=list[TokenOut])
|
||||
def list_tokens(user: CurrentUser, db: DbSession):
|
||||
return token_service.list_tokens(db, user.id)
|
||||
|
||||
|
||||
@router.post("", response_model=TokenCreated, status_code=status.HTTP_201_CREATED)
|
||||
def create_token(body: TokenCreate, user: CurrentUser, db: DbSession) -> TokenCreated:
|
||||
token, plain = token_service.create_token(db, user.id, body.name)
|
||||
return TokenCreated(**TokenOut.model_validate(token).model_dump(), token=plain)
|
||||
|
||||
|
||||
@router.delete("/{token_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def revoke_token(
|
||||
token_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not token_service.revoke_token(db, user.id, token_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Token nicht gefunden.")
|
||||
background.add_task(hub.close_token, token_id)
|
||||
@@ -0,0 +1,30 @@
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.models import User
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class UserName(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserName)
|
||||
def me(user: ApiUser) -> UserName:
|
||||
"""Who a token belongs to (e.g. so the agent only takes over its owner's clips)."""
|
||||
return UserName(id=user.id, username=user.username)
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserName])
|
||||
def list_user_names(user: ApiUser, db: DbSession) -> list[UserName]:
|
||||
"""Names of the other active users, for sharing projects; nothing else is revealed."""
|
||||
rows = db.execute(
|
||||
select(User.id, User.username)
|
||||
.where(User.is_active, User.id != user.id)
|
||||
.order_by(User.username)
|
||||
)
|
||||
return [UserName(id=uid, username=name) for uid, name in rows]
|
||||
@@ -0,0 +1,106 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
|
||||
from app.api.deps import SESSION_COOKIE, bearer_token
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.services.sessions import is_session_valid, resolve_session
|
||||
from app.services.tokens import is_token_valid, resolve_token
|
||||
from app.ws.hub import CLOSE_UNAUTHORIZED, Connection, hub
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MAX_CONNECTIONS_PER_USER = 20
|
||||
PING_INTERVAL_SECONDS = 30
|
||||
REVALIDATE_INTERVAL_SECONDS = 300
|
||||
CLOSE_TOO_MANY = 4429
|
||||
|
||||
|
||||
def _resolve_session(token: str | None) -> tuple[int, int] | None:
|
||||
with _session_factory()() as db:
|
||||
session = resolve_session(db, token)
|
||||
return (session.id, session.user_id) if session else None
|
||||
|
||||
|
||||
def _resolve_token(plain: str, ip: str | None) -> tuple[int, int] | None:
|
||||
with _session_factory()() as db:
|
||||
token = resolve_token(db, plain, ip)
|
||||
return (token.id, token.user_id) if token else None
|
||||
|
||||
|
||||
def _still_valid(conn: Connection) -> bool:
|
||||
with _session_factory()() as db:
|
||||
if conn.token_id is not None:
|
||||
return is_token_valid(db, conn.token_id)
|
||||
return conn.session_id is not None and is_session_valid(db, conn.session_id)
|
||||
|
||||
|
||||
async def _heartbeat(conn: Connection) -> None:
|
||||
"""Keep the connection alive through the proxy and end it when the session ends."""
|
||||
last_check = time.monotonic()
|
||||
while True:
|
||||
await asyncio.sleep(PING_INTERVAL_SECONDS)
|
||||
await conn.websocket.send_json({"type": "ping"})
|
||||
if time.monotonic() - last_check >= REVALIDATE_INTERVAL_SECONDS:
|
||||
last_check = time.monotonic()
|
||||
if not await run_in_threadpool(_still_valid, conn):
|
||||
await conn.websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
|
||||
|
||||
async def _drain(conn: Connection) -> None:
|
||||
"""Clients do not send commands; reading only detects disconnects."""
|
||||
while True:
|
||||
await conn.websocket.receive_text()
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def websocket_endpoint(websocket: WebSocket) -> None:
|
||||
plain = bearer_token(websocket.headers.get("authorization"))
|
||||
origin = websocket.headers.get("origin")
|
||||
# Origin check protects the cookie-authenticated socket against cross-site hijacking.
|
||||
# The desktop agent sends a token and no Origin; browsers always send Origin and
|
||||
# cannot set an Authorization header on WebSockets.
|
||||
origin_ok = (origin or "").rstrip("/") in get_settings().allowed_origin_list
|
||||
if not origin_ok and not (plain is not None and origin is None):
|
||||
await websocket.close(code=4403) # before accept: handshake is rejected
|
||||
return
|
||||
|
||||
await websocket.accept()
|
||||
# Accept first so the client sees the close code and can redirect to login
|
||||
ip = websocket.client.host if websocket.client else None
|
||||
if plain is not None:
|
||||
ids = await run_in_threadpool(_resolve_token, plain, ip)
|
||||
else:
|
||||
ids = await run_in_threadpool(_resolve_session, websocket.cookies.get(SESSION_COOKIE))
|
||||
if ids is None:
|
||||
await websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
credential_id, user_id = ids
|
||||
if hub.count(user_id) >= MAX_CONNECTIONS_PER_USER:
|
||||
await websocket.close(code=CLOSE_TOO_MANY)
|
||||
return
|
||||
|
||||
conn = (
|
||||
Connection(websocket=websocket, user_id=user_id, token_id=credential_id)
|
||||
if plain is not None
|
||||
else Connection(websocket=websocket, user_id=user_id, session_id=credential_id)
|
||||
)
|
||||
hub.add(conn)
|
||||
try:
|
||||
await websocket.send_json({"type": "hello"})
|
||||
tasks = [asyncio.create_task(_heartbeat(conn)), asyncio.create_task(_drain(conn))]
|
||||
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
for task in done:
|
||||
exc = task.exception()
|
||||
if exc is not None and not isinstance(exc, WebSocketDisconnect | RuntimeError):
|
||||
raise exc
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
hub.remove(conn)
|
||||
@@ -7,6 +7,7 @@ import sys
|
||||
|
||||
from app.db import _session_factory
|
||||
from app.models import Role
|
||||
from app.services import backup as backup_service
|
||||
from app.services.users import UserError, create_user, get_by_username, set_password
|
||||
|
||||
|
||||
@@ -33,6 +34,14 @@ def _reset_password(args: argparse.Namespace) -> None:
|
||||
print(f"Passwort für '{user.username}' gesetzt, alle Sitzungen wurden beendet.")
|
||||
|
||||
|
||||
def _backup(_args: argparse.Namespace) -> None:
|
||||
try:
|
||||
info = backup_service.create_backup()
|
||||
except backup_service.BackupError as exc:
|
||||
raise UserError(f"Sicherung fehlgeschlagen: {exc}") from exc
|
||||
print(f"Sicherung geschrieben: {info.path} ({info.size:,} Bytes)".replace(",", "."))
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="lc-admin", description="LAN-Clipboard Verwaltung")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
@@ -49,6 +58,9 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
p.add_argument("username")
|
||||
p.set_defaults(func=_reset_password)
|
||||
|
||||
p = sub.add_parser("backup", help="Datenbank jetzt sichern (nach /data/backups)")
|
||||
p.set_defaults(func=_backup)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
@@ -30,6 +31,17 @@ class Settings(BaseSettings):
|
||||
|
||||
clip_max_chars: int = 200_000
|
||||
|
||||
file_max_bytes: int = 100 * 1024 * 1024
|
||||
file_quota_bytes: int = 1024 * 1024 * 1024
|
||||
# Uploads are refused when the disk would drop below this; the server is shared
|
||||
file_min_free_bytes: int = 2 * 1024 * 1024 * 1024
|
||||
|
||||
# Daily consistent database snapshot to /data/backups (local time, see TZ)
|
||||
backup_enabled: bool = True
|
||||
backup_hour: int = Field(default=3, ge=0, le=23)
|
||||
backup_keep_daily: int = Field(default=7, ge=1)
|
||||
backup_keep_weekly: int = Field(default=4, ge=0)
|
||||
|
||||
initial_admin_username: str | None = None
|
||||
initial_admin_password: str | None = None
|
||||
|
||||
@@ -37,6 +49,10 @@ class Settings(BaseSettings):
|
||||
def database_url(self) -> str:
|
||||
return f"sqlite:///{self.data_dir / 'app.db'}"
|
||||
|
||||
@property
|
||||
def files_dir(self) -> Path:
|
||||
return self.data_dir / "files"
|
||||
|
||||
@property
|
||||
def allowed_origin_list(self) -> list[str]:
|
||||
return [o.strip().rstrip("/") for o in self.allowed_origins.split(",") if o.strip()]
|
||||
|
||||
@@ -7,7 +7,13 @@ from sqlalchemy.orm import Session, sessionmaker
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
def casefold(value: str | None) -> str | None:
|
||||
return None if value is None else value.casefold()
|
||||
|
||||
|
||||
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
|
||||
# SQLite's lower() only handles ASCII; this one also folds umlauts and ß for search
|
||||
dbapi_connection.create_function("lc_casefold", 1, casefold, deterministic=True)
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -9,7 +10,7 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import admin, auth, clips, health
|
||||
from app.api import admin, auth, clips, files, health, projects, tokens, users, ws
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -17,27 +18,45 @@ from app.middleware import (
|
||||
OriginCheckMiddleware,
|
||||
SecurityHeadersMiddleware,
|
||||
)
|
||||
from app.services import backup as backup_service
|
||||
from app.services import files as file_service
|
||||
from app.services.access import ProjectNotFound, ReadOnly
|
||||
from app.services.auth import delete_old_login_attempts
|
||||
from app.services.sessions import delete_expired_sessions
|
||||
from app.services.users import UserError, bootstrap_initial_admin
|
||||
from app.ws.hub import hub
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CLEANUP_INTERVAL_SECONDS = 3600
|
||||
# Give the app time to start before a missed backup is caught up
|
||||
BACKUP_CATCH_UP_DELAY_SECONDS = 60
|
||||
|
||||
|
||||
def _cleanup() -> None:
|
||||
def _cleanup() -> list[tuple[int, set[int]]]:
|
||||
"""Hourly housekeeping; returns (clip_id, audience) of expired file clips."""
|
||||
with _session_factory()() as db:
|
||||
sessions = delete_expired_sessions(db)
|
||||
attempts = delete_old_login_attempts(db)
|
||||
if sessions or attempts:
|
||||
logger.info("Cleanup: %d sessions, %d login attempts removed", sessions, attempts)
|
||||
expired = file_service.delete_expired(db)
|
||||
orphans = file_service.remove_orphans(db)
|
||||
if sessions or attempts or expired or orphans:
|
||||
logger.info(
|
||||
"Cleanup: %d sessions, %d login attempts, %d expired files, %d orphans removed",
|
||||
sessions,
|
||||
attempts,
|
||||
len(expired),
|
||||
orphans,
|
||||
)
|
||||
return expired
|
||||
|
||||
|
||||
async def _cleanup_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
await run_in_threadpool(_cleanup)
|
||||
for clip_id, audience in await run_in_threadpool(_cleanup):
|
||||
for user_id in audience:
|
||||
await hub.broadcast(user_id, {"type": "clip.deleted", "data": {"id": clip_id}})
|
||||
except Exception:
|
||||
logger.exception("Cleanup failed")
|
||||
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
|
||||
@@ -64,16 +83,49 @@ def _bootstrap_admin() -> None:
|
||||
logger.info("INITIAL_ADMIN_* ignored: users already exist; remove them from .env.")
|
||||
|
||||
|
||||
async def _run_backup() -> None:
|
||||
# Failures are logged with traceback and shown in the admin area
|
||||
with contextlib.suppress(backup_service.BackupError):
|
||||
await run_in_threadpool(backup_service.create_backup)
|
||||
|
||||
|
||||
async def _backup_loop() -> None:
|
||||
"""Daily at BACKUP_HOUR; a backup missed while the container was down is caught up."""
|
||||
await asyncio.sleep(BACKUP_CATCH_UP_DELAY_SECONDS)
|
||||
if await run_in_threadpool(backup_service.needs_catch_up):
|
||||
await _run_backup()
|
||||
while True:
|
||||
await asyncio.sleep(backup_service.seconds_until_next_run())
|
||||
await _run_backup()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
await run_in_threadpool(_bootstrap_admin)
|
||||
task = asyncio.create_task(_cleanup_loop())
|
||||
tasks = [asyncio.create_task(_cleanup_loop())]
|
||||
if get_settings().backup_enabled:
|
||||
tasks.append(asyncio.create_task(_backup_loop()))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
|
||||
|
||||
# Hashed build output never changes; everything else must be revalidated so updates arrive
|
||||
_IMMUTABLE = "public, max-age=31536000, immutable"
|
||||
_REVALIDATE = "no-cache"
|
||||
_MEDIA_TYPES = {".webmanifest": "application/manifest+json"}
|
||||
|
||||
|
||||
def _cache_control(relative: str) -> str:
|
||||
if relative.startswith("assets/") or relative.startswith("workbox-"):
|
||||
return _IMMUTABLE
|
||||
if relative.startswith("icons/"):
|
||||
return "public, max-age=86400"
|
||||
return _REVALIDATE # index.html, sw.js, manifest.webmanifest
|
||||
|
||||
|
||||
def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
||||
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
|
||||
root = static_dir.resolve()
|
||||
@@ -85,12 +137,16 @@ def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
||||
raise HTTPException(status_code=404)
|
||||
candidate = (root / path).resolve()
|
||||
if path and candidate.is_relative_to(root) and candidate.is_file():
|
||||
return FileResponse(candidate)
|
||||
return FileResponse(
|
||||
candidate,
|
||||
media_type=_MEDIA_TYPES.get(candidate.suffix),
|
||||
headers={"Cache-Control": _cache_control(path)},
|
||||
)
|
||||
# Paths that look like files (/.env, /wp-login.php, /.git/config) are not app routes
|
||||
segments = path.split("/")
|
||||
if "." in segments[-1] or any(seg.startswith(".") for seg in segments):
|
||||
raise HTTPException(status_code=404)
|
||||
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
||||
return FileResponse(index_file, headers={"Cache-Control": _REVALIDATE})
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
@@ -105,17 +161,41 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
# Last added runs first: security headers wrap every response, including rejections
|
||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
app.add_middleware(
|
||||
BodySizeLimitMiddleware,
|
||||
max_bytes=settings.max_request_bytes,
|
||||
exempt=frozenset({("POST", files.UPLOAD_PATH)}),
|
||||
)
|
||||
app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
app.include_router(clips.router, prefix="/api")
|
||||
app.include_router(projects.router, prefix="/api")
|
||||
app.include_router(files.router, prefix="/api")
|
||||
app.include_router(users.router, prefix="/api")
|
||||
app.include_router(tokens.router, prefix="/api")
|
||||
app.include_router(ws.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@app.exception_handler(file_service.FileRejected)
|
||||
def file_rejected_handler(_request: Request, exc: file_service.FileRejected) -> JSONResponse:
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
||||
|
||||
@app.exception_handler(ReadOnly)
|
||||
def read_only_handler(_request: Request, exc: ReadOnly) -> JSONResponse:
|
||||
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
@app.exception_handler(ProjectNotFound)
|
||||
def project_not_found_handler(_request: Request, _exc: ProjectNotFound) -> JSONResponse:
|
||||
# Same answer for foreign and missing projects, so ids of other users are not revealed
|
||||
return JSONResponse(
|
||||
{"detail": "Projekt nicht gefunden."}, status_code=status.HTTP_404_NOT_FOUND
|
||||
)
|
||||
|
||||
_register_frontend(app, settings.static_dir)
|
||||
return app
|
||||
|
||||
|
||||
@@ -26,21 +26,26 @@ class OriginCheckMiddleware:
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
|
||||
CONTENT_SECURITY_POLICY = "; ".join(
|
||||
def build_csp(allowed_origins: list[str]) -> str:
|
||||
# Older Safari does not match ws/wss against 'self', so list the socket origins explicitly
|
||||
ws_origins = [
|
||||
o.replace("https://", "wss://", 1) for o in allowed_origins if o.startswith("https://")
|
||||
]
|
||||
return "; ".join(
|
||||
[
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
" ".join(["connect-src 'self'", *ws_origins]),
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
SECURITY_HEADERS = [
|
||||
(b"content-security-policy", CONTENT_SECURITY_POLICY.encode()),
|
||||
(b"x-content-type-options", b"nosniff"),
|
||||
(b"referrer-policy", b"same-origin"),
|
||||
(b"x-frame-options", b"DENY"),
|
||||
@@ -54,15 +59,16 @@ HSTS_HEADER = (b"strict-transport-security", b"max-age=31536000")
|
||||
class SecurityHeadersMiddleware:
|
||||
"""Add security headers to every HTTP response; HSTS only for HTTPS requests."""
|
||||
|
||||
def __init__(self, app: ASGIApp) -> None:
|
||||
def __init__(self, app: ASGIApp, allowed_origins: list[str]) -> None:
|
||||
self.app = app
|
||||
self.csp_header = (b"content-security-policy", build_csp(allowed_origins).encode())
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
extra = list(SECURITY_HEADERS)
|
||||
extra = [self.csp_header, *SECURITY_HEADERS]
|
||||
if scope.get("scheme") == "https":
|
||||
extra.append(HSTS_HEADER)
|
||||
|
||||
@@ -84,13 +90,25 @@ class BodySizeLimitMiddleware:
|
||||
When a stream exceeds the limit, the 413 is sent here and the app sees a disconnect.
|
||||
"""
|
||||
|
||||
def __init__(self, app: ASGIApp, max_bytes: int, path_prefix: str = "/api/") -> None:
|
||||
def __init__(
|
||||
self,
|
||||
app: ASGIApp,
|
||||
max_bytes: int,
|
||||
path_prefix: str = "/api/",
|
||||
exempt: frozenset[tuple[str, str]] = frozenset(),
|
||||
) -> None:
|
||||
self.app = app
|
||||
self.max_bytes = max_bytes
|
||||
self.path_prefix = path_prefix
|
||||
# (method, path) pairs that enforce their own, larger limit (file uploads)
|
||||
self.exempt = exempt
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http" or not scope["path"].startswith(self.path_prefix):
|
||||
if (
|
||||
scope["type"] != "http"
|
||||
or not scope["path"].startswith(self.path_prefix)
|
||||
or (scope["method"], scope["path"]) in self.exempt
|
||||
):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
from app.models.api_token import ApiToken
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
from app.models.clip import Clip, ClipKind
|
||||
from app.models.file import StoredFile
|
||||
from app.models.login_attempt import LoginAttempt
|
||||
from app.models.member import MemberRole, ProjectMember
|
||||
from app.models.project import PROJECT_COLORS, Project
|
||||
from app.models.session import UserSession
|
||||
from app.models.user import Role, User
|
||||
|
||||
__all__ = [
|
||||
"ApiToken",
|
||||
"Base",
|
||||
"Clip",
|
||||
"ClipKind",
|
||||
"LoginAttempt",
|
||||
"MemberRole",
|
||||
"PROJECT_COLORS",
|
||||
"Project",
|
||||
"ProjectMember",
|
||||
"Role",
|
||||
"StoredFile",
|
||||
"UTCDateTime",
|
||||
"User",
|
||||
"UserSession",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class ApiToken(Base):
|
||||
"""Per-device token for the desktop agent and scripts; only its hash is stored."""
|
||||
|
||||
__tablename__ = "api_tokens"
|
||||
__table_args__ = (Index("ix_api_tokens_user", "user_id"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
# First characters of the token, so the user can tell tokens apart
|
||||
prefix: Mapped[str] = mapped_column(String(16))
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
last_used_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
last_ip: Mapped[str | None] = mapped_column(String(45))
|
||||
|
||||
user: Mapped[User] = relationship(lazy="joined")
|
||||
@@ -2,24 +2,37 @@ from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Enum, ForeignKey, Index, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.file import StoredFile
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class ClipKind(enum.StrEnum):
|
||||
TEXT = "text"
|
||||
CODE = "code"
|
||||
# Uploaded file; content holds the file name so search finds it
|
||||
FILE = "file"
|
||||
|
||||
|
||||
class Clip(Base):
|
||||
__tablename__ = "clips"
|
||||
__table_args__ = (Index("ix_clips_user_order", "user_id", "pinned", "updated_at"),)
|
||||
__table_args__ = (
|
||||
Index("ix_clips_user_order", "user_id", "pinned", "updated_at"),
|
||||
Index("ix_clips_user_project", "user_id", "project_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
project_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("projects.id", ondelete="SET NULL", name="fk_clips_project_id")
|
||||
)
|
||||
kind: Mapped[ClipKind] = mapped_column(
|
||||
Enum(ClipKind, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e])
|
||||
)
|
||||
@@ -31,3 +44,14 @@ class Clip(Base):
|
||||
version: Mapped[int] = mapped_column(default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
|
||||
# Shown on clips in shared projects ("von anna")
|
||||
owner: Mapped[User] = relationship(lazy="selectin")
|
||||
|
||||
@property
|
||||
def owner_name(self) -> str:
|
||||
return self.owner.username
|
||||
|
||||
file: Mapped[StoredFile | None] = relationship(
|
||||
back_populates="clip", lazy="selectin", passive_deletes=True
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import BigInteger, ForeignKey, Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.clip import Clip
|
||||
|
||||
|
||||
class StoredFile(Base):
|
||||
"""An uploaded file; belongs to exactly one clip of kind "file"."""
|
||||
|
||||
__tablename__ = "files"
|
||||
__table_args__ = (
|
||||
Index("ix_files_user", "user_id"),
|
||||
Index("ix_files_expires_at", "expires_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
clip_id: Mapped[int] = mapped_column(ForeignKey("clips.id", ondelete="CASCADE"), unique=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
# Random name on disk; the original name never touches the file system
|
||||
storage_name: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
content_type: Mapped[str] = mapped_column(String(127))
|
||||
size: Mapped[int] = mapped_column(BigInteger)
|
||||
sha256: Mapped[str] = mapped_column(String(64))
|
||||
# Only set when the content really is a JPEG/PNG/GIF/WebP image (checked on upload)
|
||||
previewable: Mapped[bool] = mapped_column(default=False)
|
||||
expires_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
|
||||
clip: Mapped[Clip] = relationship(back_populates="file")
|
||||
@@ -0,0 +1,34 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Enum, ForeignKey, Index, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
|
||||
class MemberRole(enum.StrEnum):
|
||||
EDIT = "edit"
|
||||
READ = "read"
|
||||
|
||||
|
||||
class ProjectMember(Base):
|
||||
"""A user a project is shared with; the owner is not stored here (projects.user_id)."""
|
||||
|
||||
__tablename__ = "project_members"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("project_id", "user_id", name="uq_project_members"),
|
||||
Index("ix_project_members_user", "user_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
project_id: Mapped[int] = mapped_column(ForeignKey("projects.id", ondelete="CASCADE"))
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
role: Mapped[MemberRole] = mapped_column(
|
||||
Enum(
|
||||
MemberRole, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e]
|
||||
)
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
@@ -0,0 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ForeignKey, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
# Fixed palette; the frontend maps these keys to colors that fit the dark theme
|
||||
PROJECT_COLORS = ("blue", "teal", "green", "amber", "orange", "red", "pink", "violet")
|
||||
|
||||
|
||||
class Project(Base):
|
||||
__tablename__ = "projects"
|
||||
__table_args__ = (UniqueConstraint("user_id", "name_key", name="uq_projects_user_name"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
# Case-folded name, so "Work" and "work" count as the same project
|
||||
name_key: Mapped[str] = mapped_column(String(100))
|
||||
color: Mapped[str] = mapped_column(String(16), default="blue")
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
@@ -14,6 +14,7 @@ class ClipCreate(BaseModel):
|
||||
content: str = Field(max_length=_CONTENT_MAX)
|
||||
language: str | None = Field(default=None, max_length=32)
|
||||
pinned: bool = False
|
||||
project_id: int | None = None
|
||||
|
||||
|
||||
class ClipUpdate(BaseModel):
|
||||
@@ -24,18 +25,33 @@ class ClipUpdate(BaseModel):
|
||||
content: str | None = Field(default=None, max_length=_CONTENT_MAX)
|
||||
language: str | None = Field(default=None, max_length=32)
|
||||
pinned: bool | None = None
|
||||
project_id: int | None = None
|
||||
version: int | None = Field(default=None, description="Expected version for conflict check")
|
||||
|
||||
|
||||
class FileOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
name: str
|
||||
content_type: str
|
||||
size: int
|
||||
previewable: bool
|
||||
expires_at: datetime | None
|
||||
|
||||
|
||||
class ClipOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
user_id: int
|
||||
owner_name: str
|
||||
kind: ClipKind
|
||||
title: str | None
|
||||
content: str
|
||||
language: str | None
|
||||
pinned: bool
|
||||
project_id: int | None
|
||||
file: FileOut | None = None
|
||||
version: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.models import PROJECT_COLORS
|
||||
|
||||
ProjectColor = Literal[PROJECT_COLORS] # type: ignore[valid-type]
|
||||
|
||||
|
||||
class ProjectCreate(BaseModel):
|
||||
name: str = Field(max_length=1000)
|
||||
color: ProjectColor = "blue"
|
||||
|
||||
|
||||
class ProjectUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=1000)
|
||||
color: ProjectColor | None = None
|
||||
|
||||
|
||||
class ProjectOut(BaseModel):
|
||||
"""A project as seen by one user (role and owner differ per viewer)."""
|
||||
|
||||
id: int
|
||||
name: str
|
||||
color: str
|
||||
role: Literal["owner", "edit", "read"]
|
||||
owner_name: str
|
||||
clip_count: int
|
||||
member_count: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class MemberOut(BaseModel):
|
||||
user_id: int
|
||||
username: str
|
||||
role: Literal["owner", "edit", "read"]
|
||||
|
||||
|
||||
class MemberAdd(BaseModel):
|
||||
username: str = Field(max_length=100)
|
||||
role: Literal["edit", "read"] = "edit"
|
||||
|
||||
|
||||
class MemberUpdate(BaseModel):
|
||||
role: Literal["edit", "read"]
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Who may see and change what.
|
||||
|
||||
A user sees their own clips plus every clip in a project they own or are a member of.
|
||||
Clips outside projects are private. All visibility checks go through this module.
|
||||
"""
|
||||
|
||||
import enum
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import Clip, MemberRole, Project, ProjectMember
|
||||
|
||||
|
||||
class ProjectRole(enum.StrEnum):
|
||||
OWNER = "owner"
|
||||
EDIT = "edit"
|
||||
READ = "read"
|
||||
|
||||
|
||||
WRITE_ROLES = frozenset({ProjectRole.OWNER, ProjectRole.EDIT})
|
||||
|
||||
|
||||
class ProjectNotFound(LookupError):
|
||||
"""The project does not exist or is not visible to the user."""
|
||||
|
||||
|
||||
class ReadOnly(PermissionError):
|
||||
"""The user may see, but not change this."""
|
||||
|
||||
|
||||
def accessible_project_ids(user_id: int):
|
||||
"""Subquery of the ids of all projects the user owns or is a member of."""
|
||||
return (
|
||||
select(Project.id)
|
||||
.where(Project.user_id == user_id)
|
||||
.union(select(ProjectMember.project_id).where(ProjectMember.user_id == user_id))
|
||||
)
|
||||
|
||||
|
||||
def visible_clip(user_id: int):
|
||||
"""SQL condition for clips the user may see."""
|
||||
return or_(Clip.user_id == user_id, Clip.project_id.in_(accessible_project_ids(user_id)))
|
||||
|
||||
|
||||
def project_role(db: Session, user_id: int, project_id: int) -> ProjectRole | None:
|
||||
owner_id = db.scalar(select(Project.user_id).where(Project.id == project_id))
|
||||
if owner_id is None:
|
||||
return None
|
||||
if owner_id == user_id:
|
||||
return ProjectRole.OWNER
|
||||
role = db.scalar(
|
||||
select(ProjectMember.role).where(
|
||||
ProjectMember.project_id == project_id, ProjectMember.user_id == user_id
|
||||
)
|
||||
)
|
||||
return None if role is None else ProjectRole(MemberRole(role).value)
|
||||
|
||||
|
||||
def require_project_write(db: Session, user_id: int, project_id: int) -> ProjectRole:
|
||||
"""For putting clips into a project: owner or editor."""
|
||||
role = project_role(db, user_id, project_id)
|
||||
if role is None:
|
||||
raise ProjectNotFound(project_id)
|
||||
if role not in WRITE_ROLES:
|
||||
raise ReadOnly("Nur Lesezugriff auf dieses Projekt.")
|
||||
return role
|
||||
|
||||
|
||||
def can_write_clip(db: Session, user_id: int, clip: Clip) -> bool:
|
||||
"""Own clips always; others' clips only in projects where the user may edit."""
|
||||
if clip.user_id == user_id:
|
||||
return True
|
||||
if clip.project_id is None:
|
||||
return False
|
||||
return project_role(db, user_id, clip.project_id) in WRITE_ROLES
|
||||
|
||||
|
||||
def require_clip_write(db: Session, user_id: int, clip: Clip) -> None:
|
||||
if not can_write_clip(db, user_id, clip):
|
||||
raise ReadOnly("Nur Lesezugriff auf dieses Projekt.")
|
||||
|
||||
|
||||
def project_audience(db: Session, project_id: int) -> set[int]:
|
||||
"""Owner and members: everyone who sees the project."""
|
||||
owner_id = db.scalar(select(Project.user_id).where(Project.id == project_id))
|
||||
members = db.scalars(
|
||||
select(ProjectMember.user_id).where(ProjectMember.project_id == project_id)
|
||||
)
|
||||
return ({owner_id} if owner_id is not None else set()) | set(members)
|
||||
|
||||
|
||||
def clip_audience(db: Session, owner_id: int, project_id: int | None) -> set[int]:
|
||||
"""Everyone who sees a clip: its owner, plus the project's audience."""
|
||||
audience = {owner_id}
|
||||
if project_id is not None:
|
||||
audience |= project_audience(db, project_id)
|
||||
return audience
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Daily consistent snapshot of the SQLite database.
|
||||
|
||||
The Proxmox Backup Server copies the host's files; a live SQLite file in WAL mode may be
|
||||
caught mid-write. This job writes a consistent, verified, compressed copy to
|
||||
/data/backups that the host backup then picks up. Uploaded files are write-once and are
|
||||
left to the host backup (see README).
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_NAME = re.compile(r"^app-(\d{4}-\d{2}-\d{2})\.db\.gz$")
|
||||
# A backup is "due" again after this long, e.g. when the container was down at night
|
||||
MAX_AGE = timedelta(hours=24)
|
||||
|
||||
|
||||
class BackupError(Exception):
|
||||
"""The snapshot could not be created or failed verification."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackupInfo:
|
||||
path: Path
|
||||
day: date
|
||||
size: int
|
||||
created_at: datetime
|
||||
|
||||
|
||||
# Result of the most recent attempt in this process, shown in the admin area
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
def backup_dir() -> Path:
|
||||
return get_settings().data_dir / "backups"
|
||||
|
||||
|
||||
def _database_path() -> Path:
|
||||
return get_settings().data_dir / "app.db"
|
||||
|
||||
|
||||
def list_backups() -> list[BackupInfo]:
|
||||
"""All backups, newest first; unrelated or temporary files are ignored."""
|
||||
directory = backup_dir()
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
backups = []
|
||||
for path in directory.iterdir():
|
||||
match = _NAME.match(path.name)
|
||||
if match and path.is_file():
|
||||
stat = path.stat()
|
||||
backups.append(
|
||||
BackupInfo(
|
||||
path=path,
|
||||
day=date.fromisoformat(match.group(1)),
|
||||
size=stat.st_size,
|
||||
created_at=datetime.fromtimestamp(stat.st_mtime).astimezone(),
|
||||
)
|
||||
)
|
||||
return sorted(backups, key=lambda b: b.day, reverse=True)
|
||||
|
||||
|
||||
def latest_backup() -> BackupInfo | None:
|
||||
backups = list_backups()
|
||||
return backups[0] if backups else None
|
||||
|
||||
|
||||
def _verify(path: Path) -> None:
|
||||
# closing(): sqlite3's own context manager only ends the transaction
|
||||
with closing(sqlite3.connect(path)) as conn:
|
||||
result = conn.execute("PRAGMA integrity_check").fetchone()[0]
|
||||
if result != "ok":
|
||||
raise BackupError(f"Integritätsprüfung fehlgeschlagen: {result}")
|
||||
|
||||
|
||||
def _remove_snapshot(snapshot: Path) -> None:
|
||||
for suffix in ("", "-wal", "-shm", "-journal"):
|
||||
Path(f"{snapshot}{suffix}").unlink(missing_ok=True)
|
||||
|
||||
|
||||
def create_backup(now: datetime | None = None) -> BackupInfo:
|
||||
"""Snapshot, verify and compress the database; a second run on the same day replaces
|
||||
that day's backup. Only a verified, complete file ever gets the final name."""
|
||||
global last_error
|
||||
now = now or datetime.now().astimezone()
|
||||
directory = backup_dir()
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
day = now.date().isoformat()
|
||||
snapshot = directory / f".app-{day}.db.tmp"
|
||||
compressed = directory / f".app-{day}.db.gz.tmp"
|
||||
final = directory / f"app-{day}.db.gz"
|
||||
try:
|
||||
_remove_snapshot(snapshot)
|
||||
# sqlite3 backup API: consistent copy while the app keeps writing
|
||||
with (
|
||||
closing(sqlite3.connect(_database_path())) as source,
|
||||
closing(sqlite3.connect(snapshot)) as target,
|
||||
):
|
||||
source.backup(target)
|
||||
# The copy inherits WAL mode; switch back so everything is in one file
|
||||
target.execute("PRAGMA journal_mode=DELETE")
|
||||
_verify(snapshot)
|
||||
with snapshot.open("rb") as raw, gzip.open(compressed, "wb", compresslevel=6) as out:
|
||||
shutil.copyfileobj(raw, out)
|
||||
os.replace(compressed, final)
|
||||
except Exception as exc:
|
||||
last_error = f"{now:%d.%m.%Y %H:%M}: {exc}"
|
||||
compressed.unlink(missing_ok=True)
|
||||
logger.exception("Backup failed")
|
||||
raise BackupError(str(exc)) from exc
|
||||
finally:
|
||||
_remove_snapshot(snapshot)
|
||||
|
||||
last_error = None
|
||||
removed = prune()
|
||||
info = next(b for b in list_backups() if b.path == final)
|
||||
logger.info(
|
||||
"Backup %s written (%d bytes), %d old backups removed", final.name, info.size, removed
|
||||
)
|
||||
return info
|
||||
|
||||
|
||||
def prune() -> int:
|
||||
"""Keep the newest KEEP_DAILY backups plus the newest one of each of the KEEP_WEEKLY
|
||||
calendar weeks before them; delete the rest. Returns the number deleted."""
|
||||
settings = get_settings()
|
||||
backups = list_backups()
|
||||
keep = {b.path for b in backups[: settings.backup_keep_daily]}
|
||||
weeks: set[tuple[int, int]] = set()
|
||||
for backup in backups[settings.backup_keep_daily :]:
|
||||
week = backup.day.isocalendar()[:2]
|
||||
if week not in weeks and len(weeks) < settings.backup_keep_weekly:
|
||||
weeks.add(week)
|
||||
keep.add(backup.path)
|
||||
removed = 0
|
||||
for backup in backups:
|
||||
if backup.path not in keep:
|
||||
backup.path.unlink(missing_ok=True)
|
||||
removed += 1
|
||||
return removed
|
||||
|
||||
|
||||
def needs_catch_up(now: datetime | None = None) -> bool:
|
||||
"""True when the newest backup is missing or older than a day."""
|
||||
now = now or datetime.now().astimezone()
|
||||
latest = latest_backup()
|
||||
return latest is None or now - latest.created_at > MAX_AGE
|
||||
|
||||
|
||||
def seconds_until_next_run(now: datetime | None = None) -> float:
|
||||
"""Seconds until the next BACKUP_HOUR:00 local time."""
|
||||
now = now or datetime.now().astimezone()
|
||||
run = now.replace(hour=get_settings().backup_hour, minute=0, second=0, microsecond=0)
|
||||
if run <= now:
|
||||
run += timedelta(days=1)
|
||||
return (run - now).total_seconds()
|
||||
@@ -1,15 +1,24 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy import delete, func, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.languages import LANGUAGES
|
||||
from app.models import Clip, ClipKind, utcnow
|
||||
from app.models import Clip, ClipKind, StoredFile, utcnow
|
||||
from app.services.access import require_clip_write, require_project_write, visible_clip
|
||||
from app.services.files import remove_from_disk
|
||||
from app.services.users import UserError
|
||||
|
||||
# Changing only these fields does not count as an edit (no new updated_at)
|
||||
_META_FIELDS = frozenset({"pinned"})
|
||||
_META_FIELDS = frozenset({"pinned", "project_id"})
|
||||
|
||||
# Fixed for file clips: content is the file name
|
||||
_CONTENT_FIELDS = frozenset({"kind", "content", "language"})
|
||||
|
||||
# Filter value for clips without a project
|
||||
NO_PROJECT = "none"
|
||||
SEARCH_MAX_LENGTH = 200
|
||||
|
||||
|
||||
class ClipConflict(Exception):
|
||||
@@ -31,7 +40,7 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
|
||||
title = (title or "").strip() or None
|
||||
if title is not None and len(title) > 200:
|
||||
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||
if kind == ClipKind.TEXT:
|
||||
if kind != ClipKind.CODE:
|
||||
language = None
|
||||
else:
|
||||
language = language or "plaintext"
|
||||
@@ -40,20 +49,60 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
|
||||
return title, language
|
||||
|
||||
|
||||
def list_clips(db: Session, user_id: int, limit: int, offset: int) -> tuple[list[Clip], int]:
|
||||
def _filters(user_id: int, project: int | str | None, query: str | None) -> list:
|
||||
conditions = [visible_clip(user_id)]
|
||||
if project == NO_PROJECT:
|
||||
# Clips without project are always private
|
||||
conditions += [Clip.user_id == user_id, Clip.project_id.is_(None)]
|
||||
elif project is not None:
|
||||
conditions.append(Clip.project_id == project)
|
||||
needle = (query or "").strip().casefold()
|
||||
if needle:
|
||||
# Substring match via instr(): no LIKE wildcards to escape, finds "config" in "getConfig"
|
||||
conditions.append(
|
||||
or_(
|
||||
func.instr(func.lc_casefold(Clip.title), needle) > 0,
|
||||
func.instr(func.lc_casefold(Clip.content), needle) > 0,
|
||||
)
|
||||
)
|
||||
return conditions
|
||||
|
||||
|
||||
def list_clips(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
limit: int,
|
||||
offset: int,
|
||||
*,
|
||||
project: int | str | None = None,
|
||||
query: str | None = None,
|
||||
) -> tuple[list[Clip], int]:
|
||||
"""Visible clips, optionally only those of a project (or NO_PROJECT) matching a query."""
|
||||
conditions = _filters(user_id, project, query)
|
||||
items = db.scalars(
|
||||
select(Clip)
|
||||
.where(Clip.user_id == user_id)
|
||||
.where(*conditions)
|
||||
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
)
|
||||
total = db.scalar(select(func.count()).select_from(Clip).where(Clip.user_id == user_id))
|
||||
total = db.scalar(select(func.count()).select_from(Clip).where(*conditions))
|
||||
return list(items), total or 0
|
||||
|
||||
|
||||
def latest_text_clip(db: Session, user_id: int) -> Clip | None:
|
||||
"""The most recently changed visible text or code clip, ignoring pinning."""
|
||||
return db.scalar(
|
||||
select(Clip)
|
||||
.where(visible_clip(user_id), Clip.kind != ClipKind.FILE)
|
||||
.order_by(Clip.updated_at.desc(), Clip.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
|
||||
def get_clip(db: Session, user_id: int, clip_id: int) -> Clip | None:
|
||||
return db.scalar(select(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
"""A clip the user may see (own or in a shared project), else None."""
|
||||
return db.scalar(select(Clip).where(Clip.id == clip_id, visible_clip(user_id)))
|
||||
|
||||
|
||||
def create_clip(
|
||||
@@ -65,10 +114,16 @@ def create_clip(
|
||||
title: str | None = None,
|
||||
language: str | None = None,
|
||||
pinned: bool = False,
|
||||
project_id: int | None = None,
|
||||
) -> Clip:
|
||||
if kind == ClipKind.FILE:
|
||||
raise UserError("Dateien werden über den Upload angelegt.")
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
if project_id is not None:
|
||||
require_project_write(db, user_id, project_id)
|
||||
clip = Clip(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
kind=kind,
|
||||
title=title,
|
||||
content=content,
|
||||
@@ -87,14 +142,29 @@ def update_clip(
|
||||
changes: dict[str, Any],
|
||||
expected_version: int | None = None,
|
||||
) -> Clip:
|
||||
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict."""
|
||||
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict.
|
||||
|
||||
The clip must be visible to the user (get_clip); write access is checked here.
|
||||
"""
|
||||
require_clip_write(db, user_id, clip)
|
||||
# Early check so a stale client gets the conflict, not a follow-up validation error
|
||||
if expected_version is not None and clip.version != expected_version:
|
||||
raise ClipConflict(clip)
|
||||
if clip.kind == ClipKind.FILE and set(changes) & _CONTENT_FIELDS:
|
||||
raise UserError("Bei Dateien lassen sich nur Titel, Projekt und Anheften ändern.")
|
||||
if changes.get("kind") == ClipKind.FILE and clip.kind != ClipKind.FILE:
|
||||
raise UserError("Ein Clip lässt sich nicht in eine Datei umwandeln.")
|
||||
kind = changes.get("kind", clip.kind)
|
||||
title = changes.get("title", clip.title)
|
||||
content = changes.get("content", clip.content)
|
||||
language = changes.get("language", clip.language)
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
project_id = changes.get("project_id", clip.project_id)
|
||||
if "project_id" in changes and project_id not in (None, clip.project_id):
|
||||
require_project_write(db, user_id, project_id)
|
||||
|
||||
values: dict[str, Any] = {
|
||||
"project_id": project_id,
|
||||
"kind": kind,
|
||||
"title": title,
|
||||
"content": content,
|
||||
@@ -106,7 +176,7 @@ def update_clip(
|
||||
values["updated_at"] = utcnow()
|
||||
|
||||
# Conditional UPDATE keeps the version check atomic across concurrent requests
|
||||
stmt = update(Clip).where(Clip.id == clip.id, Clip.user_id == user_id)
|
||||
stmt = update(Clip).where(Clip.id == clip.id)
|
||||
if expected_version is not None:
|
||||
stmt = stmt.where(Clip.version == expected_version)
|
||||
result = db.execute(stmt.values(**values).execution_options(synchronize_session=False))
|
||||
@@ -119,7 +189,14 @@ def update_clip(
|
||||
return clip
|
||||
|
||||
|
||||
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
|
||||
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
def delete_clip(db: Session, user_id: int, clip: Clip) -> None:
|
||||
"""Delete a visible clip; write access is checked here. Its file goes with it."""
|
||||
require_clip_write(db, user_id, clip)
|
||||
stored = db.execute(
|
||||
select(StoredFile.user_id, StoredFile.storage_name).where(StoredFile.clip_id == clip.id)
|
||||
).first()
|
||||
db.execute(delete(Clip).where(Clip.id == clip.id))
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
if stored is not None:
|
||||
# Stored under the uploader, who may be another member of a shared project
|
||||
remove_from_disk(stored.user_id, stored.storage_name)
|
||||
@@ -0,0 +1,292 @@
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import Clip, ClipKind, StoredFile, utcnow
|
||||
from app.services.access import (
|
||||
clip_audience,
|
||||
require_clip_write,
|
||||
require_project_write,
|
||||
visible_clip,
|
||||
)
|
||||
from app.services.users import UserError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Allowed lifetimes in days; 0 means the file is kept until deleted
|
||||
EXPIRY_CHOICES = frozenset({0, 1, 7, 30})
|
||||
NAME_MAX_LENGTH = 255
|
||||
FALLBACK_NAME = "datei"
|
||||
TMP_DIR_NAME = "tmp"
|
||||
# Files on disk without database row are only removed after this age, so an upload
|
||||
# that is just being committed is never touched
|
||||
ORPHAN_MIN_AGE_SECONDS = 3600
|
||||
STALE_UPLOAD_SECONDS = 6 * 3600
|
||||
|
||||
_CONTENT_TYPE = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$")
|
||||
# Magic bytes of the image formats every browser displays safely (no SVG: it can run script)
|
||||
_IMAGE_SIGNATURES = (
|
||||
(b"\xff\xd8\xff", "image/jpeg"),
|
||||
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
||||
(b"GIF87a", "image/gif"),
|
||||
(b"GIF89a", "image/gif"),
|
||||
)
|
||||
|
||||
|
||||
class FileRejected(Exception):
|
||||
"""Upload refused; status code and message go to the client unchanged."""
|
||||
|
||||
def __init__(self, status_code: int, detail: str) -> None:
|
||||
super().__init__(detail)
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def format_bytes(size: int) -> str:
|
||||
for unit, factor in (("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)):
|
||||
if size >= factor:
|
||||
return f"{size / factor:.1f}".rstrip("0").rstrip(".").replace(".", ",") + f" {unit}"
|
||||
return f"{size} B"
|
||||
|
||||
|
||||
def sanitize_name(name: str) -> str:
|
||||
"""Keep only the base name, without control characters, at most 255 characters."""
|
||||
name = unicodedata.normalize("NFC", name)
|
||||
name = re.split(r"[/\\]", name)[-1]
|
||||
name = "".join(ch for ch in name if not unicodedata.category(ch).startswith("C"))
|
||||
name = name.strip()
|
||||
if name in ("", ".", ".."):
|
||||
return FALLBACK_NAME
|
||||
if len(name) > NAME_MAX_LENGTH:
|
||||
stem, dot, ext = name.rpartition(".")
|
||||
if dot and stem and len(ext) <= 20:
|
||||
name = stem[: NAME_MAX_LENGTH - len(ext) - 1] + "." + ext
|
||||
else:
|
||||
name = name[:NAME_MAX_LENGTH]
|
||||
return name
|
||||
|
||||
|
||||
def sanitize_content_type(value: str | None) -> str:
|
||||
value = (value or "").split(";")[0].strip().lower()
|
||||
return value if _CONTENT_TYPE.fullmatch(value) else "application/octet-stream"
|
||||
|
||||
|
||||
def sniff_image(head: bytes) -> str | None:
|
||||
"""Image type from the first bytes, or None if it is not a previewable image."""
|
||||
for signature, content_type in _IMAGE_SIGNATURES:
|
||||
if head.startswith(signature):
|
||||
return content_type
|
||||
if len(head) >= 12 and head[:4] == b"RIFF" and head[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
return None
|
||||
|
||||
|
||||
def content_disposition(name: str, inline: bool = False) -> str:
|
||||
"""RFC 6266 header with ASCII fallback; quotes and line breaks cannot break out."""
|
||||
fallback = "".join(ch if 32 <= ord(ch) < 127 and ch not in '"\\' else "_" for ch in name)
|
||||
kind = "inline" if inline else "attachment"
|
||||
return f"{kind}; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}"
|
||||
|
||||
|
||||
def file_path(user_id: int, storage_name: str) -> Path:
|
||||
return get_settings().files_dir / str(user_id) / storage_name
|
||||
|
||||
|
||||
def remove_from_disk(user_id: int, storage_name: str) -> None:
|
||||
try:
|
||||
file_path(user_id, storage_name).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
logger.exception("Could not remove file %s of user %d", storage_name, user_id)
|
||||
|
||||
|
||||
def used_bytes(db: Session, user_id: int) -> int:
|
||||
total = db.scalar(select(func.sum(StoredFile.size)).where(StoredFile.user_id == user_id))
|
||||
return int(total or 0)
|
||||
|
||||
|
||||
def _expires_at(days: int):
|
||||
if days not in EXPIRY_CHOICES:
|
||||
raise UserError("Ungültige Ablaufzeit.")
|
||||
return utcnow() + timedelta(days=days) if days else None
|
||||
|
||||
|
||||
def _check_limits(db: Session, user_id: int, size: int) -> None:
|
||||
settings = get_settings()
|
||||
if size <= 0:
|
||||
raise FileRejected(400, "Die Datei ist leer.")
|
||||
if size > settings.file_max_bytes:
|
||||
raise FileRejected(
|
||||
413, f"Die Datei ist zu groß (höchstens {format_bytes(settings.file_max_bytes)})."
|
||||
)
|
||||
used = used_bytes(db, user_id)
|
||||
if used + size > settings.file_quota_bytes:
|
||||
free = max(settings.file_quota_bytes - used, 0)
|
||||
raise FileRejected(
|
||||
413,
|
||||
f"Nicht genug Speicherplatz: noch {format_bytes(free)} von "
|
||||
f"{format_bytes(settings.file_quota_bytes)} frei.",
|
||||
)
|
||||
settings.files_dir.mkdir(parents=True, exist_ok=True)
|
||||
if shutil.disk_usage(settings.files_dir).free - size < settings.file_min_free_bytes:
|
||||
raise FileRejected(507, "Auf dem Server ist gerade nicht genug Speicherplatz frei.")
|
||||
|
||||
|
||||
async def store_upload(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
chunks: AsyncIterator[bytes],
|
||||
*,
|
||||
name: str,
|
||||
size: int,
|
||||
content_type: str | None = None,
|
||||
expires_days: int = 7,
|
||||
project_id: int | None = None,
|
||||
title: str | None = None,
|
||||
) -> Clip:
|
||||
"""Stream an upload to disk and create its clip. size is the announced Content-Length."""
|
||||
name = sanitize_name(name)
|
||||
expires_at = _expires_at(expires_days)
|
||||
title = (title or "").strip() or None
|
||||
if title is not None and len(title) > 200:
|
||||
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||
if project_id is not None:
|
||||
require_project_write(db, user_id, project_id)
|
||||
_check_limits(db, user_id, size)
|
||||
|
||||
settings = get_settings()
|
||||
tmp_dir = settings.files_dir / TMP_DIR_NAME
|
||||
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||
storage_name = uuid.uuid4().hex
|
||||
tmp_path = tmp_dir / f"{storage_name}.part"
|
||||
final_path = file_path(user_id, storage_name)
|
||||
digest = hashlib.sha256()
|
||||
received = 0
|
||||
head = b""
|
||||
try:
|
||||
with tmp_path.open("xb") as out:
|
||||
async for chunk in chunks:
|
||||
received += len(chunk)
|
||||
if received > size:
|
||||
raise FileRejected(400, "Die Datei ist größer als angekündigt.")
|
||||
if len(head) < 16:
|
||||
head = (head + chunk)[:16]
|
||||
digest.update(chunk)
|
||||
out.write(chunk)
|
||||
if received != size:
|
||||
raise FileRejected(400, "Die Übertragung wurde unterbrochen.")
|
||||
|
||||
image_type = sniff_image(head)
|
||||
final_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(tmp_path, final_path)
|
||||
|
||||
clip = Clip(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
kind=ClipKind.FILE,
|
||||
title=title,
|
||||
content=name,
|
||||
)
|
||||
clip.file = StoredFile(
|
||||
user_id=user_id,
|
||||
storage_name=storage_name,
|
||||
name=name,
|
||||
content_type=image_type or sanitize_content_type(content_type),
|
||||
size=size,
|
||||
sha256=digest.hexdigest(),
|
||||
previewable=image_type is not None,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.add(clip)
|
||||
db.commit()
|
||||
return clip
|
||||
except BaseException:
|
||||
db.rollback()
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
final_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def get_file(db: Session, user_id: int, clip_id: int) -> StoredFile | None:
|
||||
"""The file of a clip the user may see, unless it has expired."""
|
||||
stored = db.scalar(
|
||||
select(StoredFile)
|
||||
.join(Clip, Clip.id == StoredFile.clip_id)
|
||||
.where(StoredFile.clip_id == clip_id, visible_clip(user_id))
|
||||
)
|
||||
if stored is None or (stored.expires_at is not None and stored.expires_at <= utcnow()):
|
||||
return None
|
||||
return stored
|
||||
|
||||
|
||||
def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip:
|
||||
"""Change how long a file is kept; counts as a change of the clip, not as an edit."""
|
||||
if clip.file is None:
|
||||
raise UserError("Dieser Clip ist keine Datei.")
|
||||
require_clip_write(db, user_id, clip)
|
||||
clip.file.expires_at = _expires_at(expires_days)
|
||||
db.execute(
|
||||
update(Clip)
|
||||
.where(Clip.id == clip.id)
|
||||
.values(version=Clip.version + 1)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(clip)
|
||||
return clip
|
||||
|
||||
|
||||
def delete_expired(db: Session) -> list[tuple[int, set[int]]]:
|
||||
"""Delete clips whose file has expired; returns (clip_id, audience) for notifications."""
|
||||
rows = db.execute(
|
||||
select(
|
||||
StoredFile.user_id.label("uploader_id"),
|
||||
StoredFile.storage_name,
|
||||
Clip.id,
|
||||
Clip.user_id.label("owner_id"),
|
||||
Clip.project_id,
|
||||
)
|
||||
.join(Clip, Clip.id == StoredFile.clip_id)
|
||||
.where(StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow())
|
||||
).all()
|
||||
if not rows:
|
||||
return []
|
||||
audiences = [(row.id, clip_audience(db, row.owner_id, row.project_id)) for row in rows]
|
||||
db.execute(delete(Clip).where(Clip.id.in_([row.id for row in rows])))
|
||||
db.commit()
|
||||
for row in rows:
|
||||
remove_from_disk(row.uploader_id, row.storage_name)
|
||||
return audiences
|
||||
|
||||
|
||||
def remove_orphans(db: Session) -> int:
|
||||
"""Remove files without database row (e.g. of deleted users) and stale partial uploads."""
|
||||
files_dir = get_settings().files_dir
|
||||
if not files_dir.is_dir():
|
||||
return 0
|
||||
known = set(db.scalars(select(StoredFile.storage_name)))
|
||||
now = time.time()
|
||||
removed = 0
|
||||
for path in files_dir.glob("*/*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.parent.name == TMP_DIR_NAME:
|
||||
stale = now - path.stat().st_mtime > STALE_UPLOAD_SECONDS
|
||||
else:
|
||||
stale = path.name not in known and now - path.stat().st_mtime > ORPHAN_MIN_AGE_SECONDS
|
||||
if stale:
|
||||
path.unlink(missing_ok=True)
|
||||
removed += 1
|
||||
return removed
|
||||
@@ -0,0 +1,249 @@
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import PROJECT_COLORS, Clip, MemberRole, Project, ProjectMember, User, utcnow
|
||||
from app.services.access import (
|
||||
ProjectNotFound,
|
||||
ProjectRole,
|
||||
accessible_project_ids,
|
||||
project_role,
|
||||
)
|
||||
from app.services.users import UserError, normalize_username
|
||||
|
||||
NAME_MAX_LENGTH = 100
|
||||
MAX_PROJECTS_PER_USER = 200
|
||||
MAX_MEMBERS_PER_PROJECT = 50
|
||||
|
||||
__all__ = ["ProjectNotFound"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProjectView:
|
||||
"""A project as one particular user sees it."""
|
||||
|
||||
project: Project
|
||||
role: ProjectRole
|
||||
owner_name: str
|
||||
clip_count: int
|
||||
member_count: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Member:
|
||||
user_id: int
|
||||
username: str
|
||||
role: ProjectRole
|
||||
|
||||
|
||||
def _validate_name(name: str) -> tuple[str, str]:
|
||||
name = " ".join(name.split())
|
||||
if not name:
|
||||
raise UserError("Der Projektname darf nicht leer sein.")
|
||||
if len(name) > NAME_MAX_LENGTH:
|
||||
raise UserError(f"Der Projektname ist zu lang (höchstens {NAME_MAX_LENGTH} Zeichen).")
|
||||
if any(unicodedata.category(ch).startswith("C") for ch in name):
|
||||
raise UserError("Der Projektname enthält ungültige Zeichen.")
|
||||
return name, name.casefold()
|
||||
|
||||
|
||||
def _validate_color(color: str) -> str:
|
||||
if color not in PROJECT_COLORS:
|
||||
raise UserError("Unbekannte Farbe.")
|
||||
return color
|
||||
|
||||
|
||||
def _duplicate() -> UserError:
|
||||
return UserError("Ein Projekt mit diesem Namen gibt es schon.")
|
||||
|
||||
|
||||
def _clip_count():
|
||||
return select(func.count(Clip.id)).where(Clip.project_id == Project.id).scalar_subquery()
|
||||
|
||||
|
||||
def _member_count():
|
||||
return (
|
||||
select(func.count(ProjectMember.id))
|
||||
.where(ProjectMember.project_id == Project.id)
|
||||
# Only Project comes from the outer query; ProjectMember is counted here
|
||||
.correlate(Project)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
|
||||
def list_projects(db: Session, user_id: int) -> list[ProjectView]:
|
||||
"""Own and shared projects, sorted by name, with clip counts of all members."""
|
||||
rows = db.execute(
|
||||
select(Project, User.username, _clip_count(), _member_count(), ProjectMember.role)
|
||||
.join(User, User.id == Project.user_id)
|
||||
.outerjoin(
|
||||
ProjectMember,
|
||||
(ProjectMember.project_id == Project.id) & (ProjectMember.user_id == user_id),
|
||||
)
|
||||
.where(Project.id.in_(accessible_project_ids(user_id)))
|
||||
.order_by(Project.name_key, Project.id)
|
||||
)
|
||||
return [
|
||||
ProjectView(
|
||||
project=project,
|
||||
role=ProjectRole.OWNER if project.user_id == user_id else ProjectRole(role),
|
||||
owner_name=owner_name,
|
||||
clip_count=clips,
|
||||
member_count=members,
|
||||
)
|
||||
for project, owner_name, clips, members, role in rows
|
||||
]
|
||||
|
||||
|
||||
def view_project(db: Session, user_id: int, project_id: int) -> ProjectView | None:
|
||||
"""One project as the user sees it, or None if it is not visible to them."""
|
||||
role = project_role(db, user_id, project_id)
|
||||
if role is None:
|
||||
return None
|
||||
project, owner_name, clips, members = db.execute(
|
||||
select(Project, User.username, _clip_count(), _member_count())
|
||||
.join(User, User.id == Project.user_id)
|
||||
.where(Project.id == project_id)
|
||||
).one()
|
||||
return ProjectView(project, role, owner_name, clips, members)
|
||||
|
||||
|
||||
def get_owned_project(db: Session, user_id: int, project_id: int) -> Project | None:
|
||||
return db.scalar(select(Project).where(Project.id == project_id, Project.user_id == user_id))
|
||||
|
||||
|
||||
def create_project(db: Session, user_id: int, *, name: str, color: str = "blue") -> Project:
|
||||
name, name_key = _validate_name(name)
|
||||
color = _validate_color(color)
|
||||
existing = db.scalar(select(func.count(Project.id)).where(Project.user_id == user_id))
|
||||
if (existing or 0) >= MAX_PROJECTS_PER_USER:
|
||||
raise UserError(f"Höchstens {MAX_PROJECTS_PER_USER} Projekte möglich.")
|
||||
project = Project(user_id=user_id, name=name, name_key=name_key, color=color)
|
||||
db.add(project)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise _duplicate() from None
|
||||
return project
|
||||
|
||||
|
||||
def update_project(
|
||||
db: Session, project: Project, *, name: str | None = None, color: str | None = None
|
||||
) -> Project:
|
||||
if name is not None:
|
||||
project.name, project.name_key = _validate_name(name)
|
||||
if color is not None:
|
||||
project.color = _validate_color(color)
|
||||
project.updated_at = utcnow()
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise _duplicate() from None
|
||||
db.refresh(project)
|
||||
return project
|
||||
|
||||
|
||||
def _detach_clips(db: Session, project_id: int, owner_id: int | None = None) -> list[int]:
|
||||
"""Move clips out of a project (all, or those of one user); returns their ids.
|
||||
|
||||
Versions are bumped so open editors holding the old project notice the change.
|
||||
"""
|
||||
conditions = [Clip.project_id == project_id]
|
||||
if owner_id is not None:
|
||||
conditions.append(Clip.user_id == owner_id)
|
||||
ids = list(db.scalars(select(Clip.id).where(*conditions)))
|
||||
if ids:
|
||||
db.execute(
|
||||
update(Clip)
|
||||
.where(Clip.id.in_(ids))
|
||||
.values(project_id=None, version=Clip.version + 1)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
return ids
|
||||
|
||||
|
||||
def delete_project(db: Session, user_id: int, project_id: int) -> bool:
|
||||
"""Delete an own project; all clips in it stay and move to their owners' "no project"."""
|
||||
if get_owned_project(db, user_id, project_id) is None:
|
||||
return False
|
||||
_detach_clips(db, project_id)
|
||||
db.execute(delete(Project).where(Project.id == project_id))
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
# --- Members --------------------------------------------------------------------
|
||||
|
||||
|
||||
def list_members(db: Session, project: Project) -> list[Member]:
|
||||
"""Owner first, then members by name."""
|
||||
owner = db.get(User, project.user_id)
|
||||
rows = db.execute(
|
||||
select(User.id, User.username, ProjectMember.role)
|
||||
.join(ProjectMember, ProjectMember.user_id == User.id)
|
||||
.where(ProjectMember.project_id == project.id)
|
||||
.order_by(User.username)
|
||||
)
|
||||
members = [Member(uid, name, ProjectRole(MemberRole(role).value)) for uid, name, role in rows]
|
||||
return [Member(owner.id, owner.username, ProjectRole.OWNER), *members]
|
||||
|
||||
|
||||
def _member_role(role: str) -> MemberRole:
|
||||
try:
|
||||
return MemberRole(role)
|
||||
except ValueError:
|
||||
raise UserError("Unbekannte Rolle.") from None
|
||||
|
||||
|
||||
def add_member(db: Session, project: Project, username: str, role: str) -> User:
|
||||
member_role = _member_role(role)
|
||||
user = db.scalar(
|
||||
select(User).where(User.username == normalize_username(username), User.is_active)
|
||||
)
|
||||
if user is None:
|
||||
raise UserError("Diesen Benutzer gibt es nicht.")
|
||||
if user.id == project.user_id:
|
||||
raise UserError("Das Projekt gehört dir bereits.")
|
||||
count = db.scalar(
|
||||
select(func.count(ProjectMember.id)).where(ProjectMember.project_id == project.id)
|
||||
)
|
||||
if (count or 0) >= MAX_MEMBERS_PER_PROJECT:
|
||||
raise UserError(f"Höchstens {MAX_MEMBERS_PER_PROJECT} Mitglieder pro Projekt.")
|
||||
db.add(ProjectMember(project_id=project.id, user_id=user.id, role=member_role))
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise UserError(f"{user.username} ist schon Mitglied.") from None
|
||||
return user
|
||||
|
||||
|
||||
def set_member_role(db: Session, project: Project, user_id: int, role: str) -> bool:
|
||||
result = db.execute(
|
||||
update(ProjectMember)
|
||||
.where(ProjectMember.project_id == project.id, ProjectMember.user_id == user_id)
|
||||
.values(role=_member_role(role))
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
def remove_member(db: Session, project_id: int, user_id: int) -> list[int] | None:
|
||||
"""Remove a member (or let them leave). Their clips in the project go back to their
|
||||
own "no project". Returns the ids of those clips, or None if they were no member."""
|
||||
result = db.execute(
|
||||
delete(ProjectMember).where(
|
||||
ProjectMember.project_id == project_id, ProjectMember.user_id == user_id
|
||||
)
|
||||
)
|
||||
if result.rowcount == 0:
|
||||
db.rollback()
|
||||
return None
|
||||
moved = _detach_clips(db, project_id, owner_id=user_id)
|
||||
db.commit()
|
||||
return moved
|
||||
@@ -32,11 +32,8 @@ def create_session(
|
||||
return session, token
|
||||
|
||||
|
||||
def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
"""Return the valid session for a raw token; expired sessions are deleted."""
|
||||
if not token:
|
||||
return None
|
||||
session = db.scalar(select(UserSession).where(UserSession.token_hash == hash_token(token)))
|
||||
def _validate(db: Session, session: UserSession | None, touch: bool) -> UserSession | None:
|
||||
"""Return the session if still valid; expired ones are deleted."""
|
||||
if session is None:
|
||||
return None
|
||||
|
||||
@@ -47,12 +44,25 @@ def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
if now - session.last_seen_at >= TOUCH_INTERVAL:
|
||||
if touch and now - session.last_seen_at >= TOUCH_INTERVAL:
|
||||
session.last_seen_at = now
|
||||
db.commit()
|
||||
return session
|
||||
|
||||
|
||||
def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
"""Return the valid session for a raw token and record activity."""
|
||||
if not token:
|
||||
return None
|
||||
session = db.scalar(select(UserSession).where(UserSession.token_hash == hash_token(token)))
|
||||
return _validate(db, session, touch=True)
|
||||
|
||||
|
||||
def is_session_valid(db: Session, session_id: int) -> bool:
|
||||
"""Re-check a known session (e.g. for long-lived WebSockets) without recording activity."""
|
||||
return _validate(db, db.get(UserSession, session_id), touch=False) is not None
|
||||
|
||||
|
||||
def list_sessions(db: Session, user_id: int) -> list[UserSession]:
|
||||
return list(
|
||||
db.scalars(
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import secrets
|
||||
import unicodedata
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import ApiToken, utcnow
|
||||
from app.security import hash_token
|
||||
from app.services.sessions import TOUCH_INTERVAL
|
||||
from app.services.users import UserError
|
||||
|
||||
TOKEN_PREFIX = "lc_" # noqa: S105 - public marker, not a secret
|
||||
SHOWN_PREFIX_LENGTH = 10
|
||||
NAME_MAX_LENGTH = 100
|
||||
MAX_TOKENS_PER_USER = 50
|
||||
|
||||
|
||||
def create_token(db: Session, user_id: int, name: str) -> tuple[ApiToken, str]:
|
||||
"""Create a token; the plain value is returned once and never stored."""
|
||||
name = " ".join(name.split())
|
||||
if not name:
|
||||
raise UserError("Bitte einen Namen für das Gerät angeben.")
|
||||
if len(name) > NAME_MAX_LENGTH:
|
||||
raise UserError(f"Der Name ist zu lang (höchstens {NAME_MAX_LENGTH} Zeichen).")
|
||||
if any(unicodedata.category(ch).startswith("C") for ch in name):
|
||||
raise UserError("Der Name enthält ungültige Zeichen.")
|
||||
count = db.scalar(select(func.count(ApiToken.id)).where(ApiToken.user_id == user_id))
|
||||
if (count or 0) >= MAX_TOKENS_PER_USER:
|
||||
raise UserError(f"Höchstens {MAX_TOKENS_PER_USER} Tokens möglich.")
|
||||
|
||||
plain = TOKEN_PREFIX + secrets.token_urlsafe(32)
|
||||
token = ApiToken(
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
token_hash=hash_token(plain),
|
||||
prefix=plain[:SHOWN_PREFIX_LENGTH],
|
||||
)
|
||||
db.add(token)
|
||||
db.commit()
|
||||
return token, plain
|
||||
|
||||
|
||||
def list_tokens(db: Session, user_id: int) -> list[ApiToken]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ApiToken).where(ApiToken.user_id == user_id).order_by(ApiToken.created_at)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def revoke_token(db: Session, user_id: int, token_id: int) -> bool:
|
||||
result = db.execute(
|
||||
delete(ApiToken).where(ApiToken.id == token_id, ApiToken.user_id == user_id)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
def resolve_token(db: Session, plain: str | None, ip: str | None = None) -> ApiToken | None:
|
||||
"""The token for a raw value if valid (owner active); records when it was last used."""
|
||||
if not plain or not plain.startswith(TOKEN_PREFIX):
|
||||
return None
|
||||
token = db.scalar(select(ApiToken).where(ApiToken.token_hash == hash_token(plain)))
|
||||
if token is None or not token.user.is_active:
|
||||
return None
|
||||
now = utcnow()
|
||||
if (
|
||||
token.last_used_at is None
|
||||
or now - token.last_used_at >= TOUCH_INTERVAL
|
||||
or (ip is not None and ip != token.last_ip)
|
||||
):
|
||||
token.last_used_at = now
|
||||
token.last_ip = ip
|
||||
db.commit()
|
||||
return token
|
||||
|
||||
|
||||
def is_token_valid(db: Session, token_id: int) -> bool:
|
||||
token = db.get(ApiToken, token_id)
|
||||
return token is not None and token.user.is_active
|
||||
@@ -0,0 +1,84 @@
|
||||
"""In-process registry of WebSocket connections, keyed by user.
|
||||
|
||||
All methods run on the event loop; sync request handlers reach them via BackgroundTasks.
|
||||
This only works with a single worker process (see CLAUDE.md).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from fastapi import WebSocket
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEND_TIMEOUT_SECONDS = 5
|
||||
CLOSE_UNAUTHORIZED = 4401
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class Connection:
|
||||
websocket: WebSocket
|
||||
user_id: int
|
||||
# Exactly one of these: browser session or device token
|
||||
session_id: int | None = None
|
||||
token_id: int | None = None
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self) -> None:
|
||||
self._by_user: dict[int, set[Connection]] = defaultdict(set)
|
||||
|
||||
def count(self, user_id: int) -> int:
|
||||
return len(self._by_user.get(user_id, ()))
|
||||
|
||||
def add(self, conn: Connection) -> None:
|
||||
self._by_user[conn.user_id].add(conn)
|
||||
|
||||
def remove(self, conn: Connection) -> None:
|
||||
conns = self._by_user.get(conn.user_id)
|
||||
if conns is not None:
|
||||
conns.discard(conn)
|
||||
if not conns:
|
||||
del self._by_user[conn.user_id]
|
||||
|
||||
async def broadcast(self, user_id: int, message: dict[str, Any]) -> None:
|
||||
"""Send a message to every connection of one user; dead connections are dropped."""
|
||||
text = json.dumps(message)
|
||||
for conn in list(self._by_user.get(user_id, ())):
|
||||
try:
|
||||
await asyncio.wait_for(conn.websocket.send_text(text), SEND_TIMEOUT_SECONDS)
|
||||
except Exception:
|
||||
logger.info("Dropping unresponsive WebSocket of user %s", user_id)
|
||||
self.remove(conn)
|
||||
await self._close(conn, 1011)
|
||||
|
||||
async def close_session(self, session_id: int) -> None:
|
||||
await self._close_where(lambda c: c.session_id == session_id)
|
||||
|
||||
async def close_token(self, token_id: int) -> None:
|
||||
await self._close_where(lambda c: c.token_id == token_id)
|
||||
|
||||
async def close_user(self, user_id: int, except_session_id: int | None = None) -> None:
|
||||
await self._close_where(
|
||||
lambda c: c.user_id == user_id and c.session_id != except_session_id
|
||||
)
|
||||
|
||||
async def _close_where(self, predicate) -> None:
|
||||
targets = [c for conns in self._by_user.values() for c in conns if predicate(c)]
|
||||
for conn in targets:
|
||||
self.remove(conn)
|
||||
await self._close(conn, CLOSE_UNAUTHORIZED)
|
||||
|
||||
@staticmethod
|
||||
async def _close(conn: Connection, code: int) -> None:
|
||||
try:
|
||||
await conn.websocket.close(code=code)
|
||||
except Exception: # already closed or broken
|
||||
logger.debug("WebSocket already closed", exc_info=True)
|
||||
|
||||
|
||||
hub = Hub()
|
||||
@@ -0,0 +1,212 @@
|
||||
import gzip
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import cli
|
||||
from app.config import get_settings
|
||||
from app.models import Role
|
||||
from app.services import backup
|
||||
from tests.conftest import login
|
||||
|
||||
|
||||
def restore(info, tmp_path):
|
||||
"""Decompress a backup the way the README describes and open it."""
|
||||
target = tmp_path / "restored.db"
|
||||
target.write_bytes(gzip.decompress(info.path.read_bytes()))
|
||||
return sqlite3.connect(target)
|
||||
|
||||
|
||||
def at(day: str, hour: int = 3) -> datetime:
|
||||
return datetime.fromisoformat(f"{day}T{hour:02d}:00:00").astimezone()
|
||||
|
||||
|
||||
def fake_backup(day: date, age_days: float = 0) -> None:
|
||||
directory = backup.backup_dir()
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"app-{day.isoformat()}.db.gz"
|
||||
path.write_bytes(b"x")
|
||||
stamp = datetime.now().timestamp() - age_days * 86400
|
||||
os.utime(path, (stamp, stamp))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_last_error():
|
||||
backup.last_error = None
|
||||
yield
|
||||
backup.last_error = None
|
||||
|
||||
|
||||
def test_backup_can_be_restored(app_env, make_user, tmp_path):
|
||||
make_user("anna")
|
||||
|
||||
info = backup.create_backup(at("2026-10-25"))
|
||||
|
||||
assert info.path.name == "app-2026-10-25.db.gz"
|
||||
assert info.size > 0
|
||||
# Nothing but the backup itself: no snapshot, -wal, -shm or temp files left over
|
||||
assert [p.name for p in backup.backup_dir().iterdir()] == [info.path.name]
|
||||
with closing(restore(info, tmp_path)) as conn:
|
||||
# A single self-contained file, not a WAL database that needs its -wal file
|
||||
assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "delete"
|
||||
assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
assert conn.execute("SELECT username FROM users").fetchall() == [("anna",)]
|
||||
assert conn.execute("SELECT version_num FROM alembic_version").fetchone() is not None
|
||||
|
||||
|
||||
def test_backup_is_a_snapshot(app_env, make_user, tmp_path):
|
||||
make_user("anna")
|
||||
info = backup.create_backup(at("2026-10-25"))
|
||||
make_user("bert")
|
||||
|
||||
with closing(restore(info, tmp_path)) as conn:
|
||||
assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_second_backup_of_a_day_replaces_the_first(app_env, make_user, tmp_path):
|
||||
backup.create_backup(at("2026-10-25", 3))
|
||||
make_user("anna")
|
||||
info = backup.create_backup(at("2026-10-25", 14))
|
||||
|
||||
assert [b.path.name for b in backup.list_backups()] == ["app-2026-10-25.db.gz"]
|
||||
with closing(restore(info, tmp_path)) as conn:
|
||||
assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_failed_verification_leaves_no_backup(app_env, monkeypatch):
|
||||
def broken(_path):
|
||||
raise backup.BackupError("Integritätsprüfung fehlgeschlagen: page 3 corrupt")
|
||||
|
||||
monkeypatch.setattr(backup, "_verify", broken)
|
||||
|
||||
with pytest.raises(backup.BackupError):
|
||||
backup.create_backup(at("2026-10-25"))
|
||||
assert list(backup.backup_dir().iterdir()) == []
|
||||
assert "page 3 corrupt" in backup.last_error
|
||||
|
||||
|
||||
def test_success_clears_last_error(app_env):
|
||||
backup.last_error = "earlier failure"
|
||||
backup.create_backup(at("2026-10-25"))
|
||||
assert backup.last_error is None
|
||||
|
||||
|
||||
def test_retention_keeps_daily_and_weekly(app_env, monkeypatch):
|
||||
monkeypatch.setenv("BACKUP_KEEP_DAILY", "7")
|
||||
monkeypatch.setenv("BACKUP_KEEP_WEEKLY", "4")
|
||||
get_settings.cache_clear()
|
||||
first = date(2026, 9, 1)
|
||||
for offset in range(55):
|
||||
fake_backup(first + timedelta(days=offset))
|
||||
(backup.backup_dir() / "notes.txt").write_text("not a backup")
|
||||
|
||||
removed = backup.prune()
|
||||
|
||||
kept = [b.day for b in backup.list_backups()]
|
||||
newest = first + timedelta(days=54) # 2026-10-25, a Sunday
|
||||
daily = [newest - timedelta(days=i) for i in range(7)]
|
||||
assert kept[:7] == daily
|
||||
# Then the newest backup of each of the 4 calendar weeks before
|
||||
assert kept[7:] == [
|
||||
date(2026, 10, 18),
|
||||
date(2026, 10, 11),
|
||||
date(2026, 10, 4),
|
||||
date(2026, 9, 27),
|
||||
]
|
||||
assert removed == 55 - 11
|
||||
assert (backup.backup_dir() / "notes.txt").exists()
|
||||
|
||||
|
||||
def test_needs_catch_up(app_env):
|
||||
assert backup.needs_catch_up() is True
|
||||
fake_backup(date.today(), age_days=0.5)
|
||||
assert backup.needs_catch_up() is False
|
||||
for path in backup.backup_dir().iterdir():
|
||||
path.unlink()
|
||||
fake_backup(date.today() - timedelta(days=2), age_days=1.5)
|
||||
assert backup.needs_catch_up() is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("now", "expected_hours"),
|
||||
[("02:00", 1), ("03:00", 24), ("04:30", 22.5), ("23:00", 4)],
|
||||
)
|
||||
def test_next_run(app_env, now, expected_hours):
|
||||
current = datetime.fromisoformat(f"2026-10-20T{now}:00").astimezone()
|
||||
assert backup.seconds_until_next_run(current) == expected_hours * 3600
|
||||
|
||||
|
||||
def test_backup_hour_is_validated(app_env, monkeypatch):
|
||||
monkeypatch.setenv("BACKUP_HOUR", "24")
|
||||
get_settings.cache_clear()
|
||||
with pytest.raises(ValueError):
|
||||
get_settings()
|
||||
|
||||
|
||||
def test_cli_backup(app_env, monkeypatch, capsys):
|
||||
monkeypatch.setenv("LC_ALLOW_ROOT", "1")
|
||||
assert cli.main(["backup"]) == 0
|
||||
assert "Sicherung geschrieben" in capsys.readouterr().out
|
||||
assert len(backup.list_backups()) == 1
|
||||
|
||||
|
||||
def test_admin_sees_backup_status(client, make_user):
|
||||
make_user("root", role=Role.ADMIN)
|
||||
login(client, "root")
|
||||
|
||||
status = client.get("/api/admin/backup").json()
|
||||
assert status["latest"] is None
|
||||
assert status["stale"] is True
|
||||
assert (status["enabled"], status["hour"]) == (True, 3)
|
||||
|
||||
info = backup.create_backup()
|
||||
status = client.get("/api/admin/backup").json()
|
||||
assert status["latest"]["name"] == info.path.name
|
||||
assert status["latest"]["size"] == info.size
|
||||
assert status["count"] == 1
|
||||
assert status["stale"] is False
|
||||
assert status["last_error"] is None
|
||||
|
||||
|
||||
def test_backup_status_is_admin_only(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
assert client.get("/api/admin/backup").status_code == 403
|
||||
|
||||
|
||||
def test_loop_catches_up_and_survives_failures(app_env, monkeypatch):
|
||||
import asyncio
|
||||
|
||||
from app import main
|
||||
|
||||
calls = []
|
||||
real = backup.create_backup
|
||||
loop = asyncio.new_event_loop()
|
||||
done = asyncio.Event()
|
||||
|
||||
def flaky():
|
||||
calls.append(len(calls))
|
||||
if len(calls) == 3:
|
||||
# Runs in the thread pool; wake the test on the event loop
|
||||
loop.call_soon_threadsafe(done.set)
|
||||
if len(calls) == 2:
|
||||
raise backup.BackupError("disk full")
|
||||
return real()
|
||||
|
||||
monkeypatch.setattr(main, "BACKUP_CATCH_UP_DELAY_SECONDS", 0)
|
||||
monkeypatch.setattr(backup, "create_backup", flaky)
|
||||
monkeypatch.setattr(backup, "seconds_until_next_run", lambda: 0.01)
|
||||
|
||||
async def run_briefly():
|
||||
task = asyncio.create_task(main._backup_loop())
|
||||
await asyncio.wait_for(done.wait(), timeout=10)
|
||||
task.cancel()
|
||||
|
||||
loop.run_until_complete(run_briefly())
|
||||
loop.close()
|
||||
# Catch-up at start, then scheduled runs; the failed second run did not stop the loop
|
||||
assert len(calls) >= 3
|
||||
assert len(backup.list_backups()) == 1
|
||||
@@ -0,0 +1,457 @@
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import Clip, StoredFile, utcnow
|
||||
from app.services import files as file_service
|
||||
from tests.conftest import login
|
||||
from tests.test_ws import connect
|
||||
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
|
||||
JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 64
|
||||
WEBP = b"RIFF\x00\x00\x00\x00WEBPVP8 " + b"\x00" * 32
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bert(client, make_user):
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as other:
|
||||
login(other, "bert")
|
||||
yield other
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def limits(monkeypatch):
|
||||
"""Set file limits via environment, like in production."""
|
||||
|
||||
def _set(**values):
|
||||
for key, value in values.items():
|
||||
monkeypatch.setenv(key.upper(), str(value))
|
||||
get_settings.cache_clear()
|
||||
|
||||
return _set
|
||||
|
||||
|
||||
def upload(c, data=b"hello file", name="note.txt", status=201, headers=None, **params):
|
||||
response = c.post(
|
||||
"/api/files",
|
||||
params={"name": name, **params},
|
||||
content=data,
|
||||
headers={"Content-Type": "text/plain", **(headers or {})},
|
||||
)
|
||||
assert response.status_code == status, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def stored_files():
|
||||
root = get_settings().files_dir
|
||||
return sorted(p for p in root.glob("*/*") if p.is_file()) if root.exists() else []
|
||||
|
||||
|
||||
# --- Upload and download --------------------------------------------------------
|
||||
|
||||
|
||||
def test_upload_creates_file_clip(anna):
|
||||
clip = upload(anna, b"hello file", "Notiz.txt", title=" Wichtig ")
|
||||
|
||||
assert clip["kind"] == "file"
|
||||
assert clip["content"] == "Notiz.txt"
|
||||
assert clip["title"] == "Wichtig"
|
||||
assert clip["language"] is None
|
||||
assert clip["file"]["name"] == "Notiz.txt"
|
||||
assert clip["file"]["size"] == 10
|
||||
assert clip["file"]["content_type"] == "text/plain"
|
||||
assert clip["file"]["previewable"] is False
|
||||
assert len(stored_files()) == 1
|
||||
# The original name never reaches the file system
|
||||
assert stored_files()[0].name != "Notiz.txt"
|
||||
|
||||
|
||||
def test_download_is_an_attachment(anna):
|
||||
clip = upload(
|
||||
anna, b"<html><script>alert(1)</script>", "page.html", headers={"Content-Type": "text/html"}
|
||||
)
|
||||
|
||||
response = anna.get(f"/api/files/{clip['id']}")
|
||||
assert response.status_code == 200
|
||||
assert response.content == b"<html><script>alert(1)</script>"
|
||||
assert response.headers["content-disposition"].startswith("attachment;")
|
||||
assert response.headers["content-security-policy"] == "default-src 'none'; sandbox"
|
||||
assert response.headers["x-content-type-options"] == "nosniff"
|
||||
assert response.headers["cache-control"] == "private, no-cache"
|
||||
|
||||
|
||||
def test_inline_request_is_ignored_for_non_images(anna):
|
||||
clip = upload(anna, b"<svg onload='x'/>", "x.svg", headers={"Content-Type": "image/svg+xml"})
|
||||
|
||||
assert clip["file"]["previewable"] is False
|
||||
response = anna.get(f"/api/files/{clip['id']}", params={"inline": 1})
|
||||
assert response.headers["content-disposition"].startswith("attachment;")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("data", "content_type"),
|
||||
[
|
||||
(PNG, "image/png"),
|
||||
(JPEG, "image/jpeg"),
|
||||
(WEBP, "image/webp"),
|
||||
(b"GIF89a" + PNG, "image/gif"),
|
||||
],
|
||||
)
|
||||
def test_real_images_are_previewable(anna, data, content_type):
|
||||
# Type comes from the content, not from what the client claims
|
||||
clip = upload(anna, data, "bild", headers={"Content-Type": "application/octet-stream"})
|
||||
|
||||
assert clip["file"]["previewable"] is True
|
||||
assert clip["file"]["content_type"] == content_type
|
||||
response = anna.get(f"/api/files/{clip['id']}", params={"inline": 1})
|
||||
assert response.headers["content-disposition"].startswith("inline;")
|
||||
assert response.headers["content-type"] == content_type
|
||||
|
||||
|
||||
def test_fake_image_is_not_previewable(anna):
|
||||
clip = upload(anna, b"<html>", "fake.png", headers={"Content-Type": "image/png"})
|
||||
assert clip["file"]["previewable"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raw", "expected"),
|
||||
[
|
||||
("../../etc/passwd", "passwd"),
|
||||
("C:\\Users\\x\\bericht.pdf", "bericht.pdf"),
|
||||
("a\r\nX-Evil: 1.txt", "aX-Evil: 1.txt"),
|
||||
(" .. ", "datei"),
|
||||
("Größe.txt", "Größe.txt"),
|
||||
],
|
||||
)
|
||||
def test_file_names_are_sanitized(anna, raw, expected):
|
||||
assert upload(anna, name=raw)["file"]["name"] == expected
|
||||
|
||||
|
||||
def test_long_names_keep_their_extension():
|
||||
name = file_service.sanitize_name("x" * 400 + ".tar.gz")
|
||||
assert len(name) == 255
|
||||
assert name.endswith(".gz")
|
||||
|
||||
|
||||
def test_content_disposition_cannot_break_out():
|
||||
header = file_service.content_disposition('a"b\\c ä.txt')
|
||||
assert header == "attachment; filename=\"a_b_c _.txt\"; filename*=UTF-8''a%22b%5Cc%20%C3%A4.txt"
|
||||
|
||||
|
||||
def test_download_header_with_umlauts(anna):
|
||||
clip = upload(anna, name="Bericht März.pdf")
|
||||
disposition = anna.get(f"/api/files/{clip['id']}").headers["content-disposition"]
|
||||
assert "filename*=UTF-8''Bericht%20M%C3%A4rz.pdf" in disposition
|
||||
|
||||
|
||||
def test_content_type_is_sanitized(anna):
|
||||
clip = upload(anna, headers={"Content-Type": "Text/Plain; charset=utf-8"})
|
||||
assert clip["file"]["content_type"] == "text/plain"
|
||||
clip = upload(anna, headers={"Content-Type": "bad type\r\nX: y"})
|
||||
assert clip["file"]["content_type"] == "application/octet-stream"
|
||||
|
||||
|
||||
def test_upload_larger_than_request_limit(anna):
|
||||
data = os.urandom(1024 * 1024 + 4096) # above the general 1 MiB request limit
|
||||
|
||||
clip = upload(anna, data, "random.bin")
|
||||
assert anna.get(f"/api/files/{clip['id']}").content == data
|
||||
# The general limit still applies everywhere else
|
||||
assert anna.post("/api/clips", content=b"x" * len(data)).status_code == 413
|
||||
|
||||
|
||||
def test_search_finds_file_names(anna):
|
||||
clip = upload(anna, name="steuer-2026.pdf")
|
||||
upload(anna, name="urlaub.jpg")
|
||||
|
||||
items = anna.get("/api/clips", params={"q": "STEUER"}).json()["items"]
|
||||
assert [c["id"] for c in items] == [clip["id"]]
|
||||
|
||||
|
||||
def test_upload_into_project(anna):
|
||||
project = anna.post("/api/projects", json={"name": "Docs"}).json()
|
||||
clip = upload(anna, project_id=project["id"])
|
||||
assert clip["project_id"] == project["id"]
|
||||
assert anna.get("/api/projects").json()[0]["clip_count"] == 1
|
||||
|
||||
|
||||
# --- Limits ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_empty_file_is_rejected(anna):
|
||||
assert upload(anna, b"", status=400)["detail"] == "Die Datei ist leer."
|
||||
|
||||
|
||||
def test_file_size_limit(anna, limits):
|
||||
limits(file_max_bytes=10)
|
||||
upload(anna, b"x" * 10)
|
||||
|
||||
detail = upload(anna, b"x" * 11, status=413)["detail"]
|
||||
assert detail == "Die Datei ist zu groß (höchstens 10 B)."
|
||||
assert len(stored_files()) == 1
|
||||
|
||||
|
||||
def test_quota_per_user(anna, bert, limits):
|
||||
limits(file_quota_bytes=2048)
|
||||
upload(anna, b"x" * 1500)
|
||||
|
||||
detail = upload(anna, b"x" * 1000, status=413)["detail"]
|
||||
assert detail == "Nicht genug Speicherplatz: noch 548 B von 2 KB frei."
|
||||
# Quota is per user
|
||||
upload(bert, b"x" * 1500)
|
||||
|
||||
|
||||
def test_minimum_free_disk_space(anna, limits, monkeypatch):
|
||||
limits(file_min_free_bytes=1000)
|
||||
monkeypatch.setattr(file_service.shutil, "disk_usage", lambda _path: SimpleNamespace(free=1500))
|
||||
|
||||
upload(anna, b"x" * 500)
|
||||
response = anna.post("/api/files", params={"name": "a"}, content=b"x" * 501)
|
||||
assert response.status_code == 507
|
||||
|
||||
|
||||
def test_content_length_is_required(anna):
|
||||
def body():
|
||||
yield b"chunk"
|
||||
|
||||
response = anna.post("/api/files", params={"name": "a"}, content=body())
|
||||
assert response.status_code == 411
|
||||
|
||||
|
||||
@pytest.mark.parametrize("days", [-1, 2, 365])
|
||||
def test_invalid_expiry(anna, days):
|
||||
upload(anna, expires_days=days, status=400)
|
||||
|
||||
|
||||
def test_foreign_or_unknown_project(anna, bert):
|
||||
project = anna.post("/api/projects", json={"name": "Docs"}).json()
|
||||
upload(bert, project_id=project["id"], status=404)
|
||||
upload(anna, project_id=999, status=404)
|
||||
assert stored_files() == []
|
||||
|
||||
|
||||
def test_upload_requires_login_and_csrf(anna, client):
|
||||
del anna.headers["X-CSRF-Token"]
|
||||
upload(anna, status=403)
|
||||
anna.cookies.clear()
|
||||
upload(anna, status=401)
|
||||
assert stored_files() == []
|
||||
|
||||
|
||||
def _chunks(*parts, fail=False):
|
||||
async def gen():
|
||||
for part in parts:
|
||||
yield part
|
||||
if fail:
|
||||
raise ConnectionError("client gone")
|
||||
|
||||
return gen()
|
||||
|
||||
|
||||
def test_aborted_upload_leaves_nothing_behind(db, make_user):
|
||||
user = make_user("anna")
|
||||
with pytest.raises(ConnectionError):
|
||||
asyncio.run(
|
||||
file_service.store_upload(db, user.id, _chunks(b"half", fail=True), name="a", size=8)
|
||||
)
|
||||
with pytest.raises(file_service.FileRejected, match="unterbrochen"):
|
||||
asyncio.run(file_service.store_upload(db, user.id, _chunks(b"half"), name="a", size=8))
|
||||
with pytest.raises(file_service.FileRejected, match="größer als angekündigt"):
|
||||
asyncio.run(
|
||||
file_service.store_upload(db, user.id, _chunks(b"too", b"long"), name="a", size=4)
|
||||
)
|
||||
|
||||
assert stored_files() == []
|
||||
assert db.query(StoredFile).count() == 0
|
||||
assert db.query(Clip).count() == 0
|
||||
|
||||
|
||||
# --- File clips -----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_file_clip_metadata_can_change(anna):
|
||||
clip = upload(anna)
|
||||
project = anna.post("/api/projects", json={"name": "Docs"}).json()
|
||||
|
||||
response = anna.patch(
|
||||
f"/api/clips/{clip['id']}",
|
||||
json={"title": "Neu", "pinned": True, "project_id": project["id"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["file"]["name"] == "note.txt"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"changes", [{"content": "other.txt"}, {"kind": "text"}, {"language": "python"}]
|
||||
)
|
||||
def test_file_clip_content_is_fixed(anna, changes):
|
||||
clip = upload(anna)
|
||||
response = anna.patch(f"/api/clips/{clip['id']}", json=changes)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_files_cannot_be_created_or_faked_as_clips(anna):
|
||||
assert anna.post("/api/clips", json={"content": "x", "kind": "file"}).status_code == 400
|
||||
text = anna.post("/api/clips", json={"content": "x"}).json()
|
||||
assert anna.patch(f"/api/clips/{text['id']}", json={"kind": "file"}).status_code == 400
|
||||
|
||||
|
||||
def test_deleting_clip_removes_file(anna):
|
||||
clip = upload(anna)
|
||||
assert len(stored_files()) == 1
|
||||
|
||||
assert anna.delete(f"/api/clips/{clip['id']}").status_code == 204
|
||||
assert stored_files() == []
|
||||
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_missing_file_on_disk_is_404(anna):
|
||||
clip = upload(anna)
|
||||
stored_files()[0].unlink()
|
||||
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_usage(anna, bert, limits):
|
||||
limits(file_quota_bytes=5000, file_max_bytes=1000)
|
||||
upload(anna, b"x" * 300)
|
||||
upload(anna, b"x" * 200)
|
||||
upload(bert, b"x" * 999)
|
||||
|
||||
assert anna.get("/api/files/usage").json() == {
|
||||
"used_bytes": 500,
|
||||
"quota_bytes": 5000,
|
||||
"max_file_bytes": 1000,
|
||||
}
|
||||
|
||||
|
||||
# --- Expiry ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_default_expiry_is_seven_days(anna):
|
||||
expires = upload(anna)["file"]["expires_at"]
|
||||
assert expires[:10] == (utcnow() + timedelta(days=7)).date().isoformat()
|
||||
assert upload(anna, expires_days=0)["file"]["expires_at"] is None
|
||||
|
||||
|
||||
def test_change_expiry(anna):
|
||||
clip = upload(anna, expires_days=1)
|
||||
|
||||
response = anna.patch(f"/api/files/{clip['id']}", json={"expires_days": 0})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["file"]["expires_at"] is None
|
||||
assert response.json()["version"] == clip["version"] + 1
|
||||
assert response.json()["updated_at"] == clip["updated_at"]
|
||||
|
||||
text = anna.post("/api/clips", json={"content": "x"}).json()
|
||||
assert anna.patch(f"/api/files/{text['id']}", json={"expires_days": 0}).status_code == 400
|
||||
|
||||
|
||||
def _expire(db, clip_id):
|
||||
stored = db.query(StoredFile).filter_by(clip_id=clip_id).one()
|
||||
stored.expires_at = utcnow() - timedelta(minutes=1)
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_expired_file_cannot_be_downloaded(anna, db):
|
||||
clip = upload(anna)
|
||||
_expire(db, clip["id"])
|
||||
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_cleanup_deletes_expired_files(anna, db):
|
||||
old = upload(anna, b"old", "old.txt")
|
||||
keep = upload(anna, b"keep", "keep.txt", expires_days=0)
|
||||
_expire(db, old["id"])
|
||||
user_id = db.query(Clip).filter_by(id=old["id"]).one().user_id
|
||||
|
||||
assert file_service.delete_expired(db) == [(old["id"], {user_id})]
|
||||
|
||||
ids = [c["id"] for c in anna.get("/api/clips").json()["items"]]
|
||||
assert ids == [keep["id"]]
|
||||
assert len(stored_files()) == 1
|
||||
assert file_service.delete_expired(db) == []
|
||||
|
||||
|
||||
def test_cleanup_removes_orphans_and_stale_uploads(anna, db):
|
||||
upload(anna)
|
||||
files_dir = get_settings().files_dir
|
||||
known = stored_files()[0]
|
||||
old = time.time() - 7 * 3600
|
||||
|
||||
orphan_old = files_dir / "99" / "deadbeef"
|
||||
orphan_new = files_dir / "99" / "cafebabe"
|
||||
stale_part = files_dir / "tmp" / "x.part"
|
||||
fresh_part = files_dir / "tmp" / "y.part"
|
||||
for path in (orphan_old, orphan_new, stale_part, fresh_part):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"x")
|
||||
for path in (orphan_old, stale_part, known):
|
||||
os.utime(path, (old, old))
|
||||
|
||||
assert file_service.remove_orphans(db) == 2
|
||||
assert {p.name for p in stored_files()} == {known.name, "cafebabe", "y.part"}
|
||||
|
||||
|
||||
def test_deleted_user_leaves_only_orphans(client, anna, db, make_user):
|
||||
from app.models import Role, User
|
||||
|
||||
upload(anna)
|
||||
make_user("root", role=Role.ADMIN)
|
||||
with TestClient(client.app, base_url="https://testserver") as admin:
|
||||
login(admin, "root")
|
||||
anna_id = db.query(User).filter_by(username="anna").one().id
|
||||
admin.delete(f"/api/admin/users/{anna_id}")
|
||||
|
||||
db.expire_all()
|
||||
assert db.query(StoredFile).count() == 0
|
||||
path = stored_files()[0]
|
||||
os.utime(path, (time.time() - 7200, time.time() - 7200))
|
||||
assert file_service.remove_orphans(db) == 1
|
||||
|
||||
|
||||
# --- Data separation ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_files_of_other_users_are_invisible(anna, bert):
|
||||
clip = upload(anna, b"secret")
|
||||
url = f"/api/files/{clip['id']}"
|
||||
|
||||
assert bert.get(url).status_code == 404
|
||||
assert bert.get(url, params={"inline": 1}).status_code == 404
|
||||
assert bert.patch(url, json={"expires_days": 0}).status_code == 404
|
||||
assert bert.delete(f"/api/clips/{clip['id']}").status_code == 404
|
||||
assert bert.get("/api/files/usage").json()["used_bytes"] == 0
|
||||
assert anna.get(url).content == b"secret"
|
||||
assert len(stored_files()) == 1
|
||||
|
||||
|
||||
# --- Live sync ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_upload_is_broadcast(anna):
|
||||
with connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
clip = upload(anna, name="live.txt")
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "clip.created"
|
||||
assert event["data"]["id"] == clip["id"]
|
||||
assert event["data"]["file"]["name"] == "live.txt"
|
||||
|
||||
anna.patch(f"/api/files/{clip['id']}", json={"expires_days": 30})
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "clip.updated"
|
||||
assert event["data"]["file"]["expires_at"] is not None
|
||||
@@ -82,3 +82,8 @@ def test_oversized_chunked_request_is_rejected(client):
|
||||
def test_normal_requests_pass_size_limit(client):
|
||||
response = client.post("/api/auth/login", json={"username": "x", "password": "y"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_csp_allows_websocket_to_own_origin(client):
|
||||
csp = client.get("/api/health").headers["content-security-policy"]
|
||||
assert "connect-src 'self' wss://testserver" in csp
|
||||
@@ -0,0 +1,352 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.conftest import login
|
||||
from tests.test_ws import connect
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bert(client, make_user):
|
||||
"""Second logged-in user with own client, for data separation tests."""
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as other:
|
||||
login(other, "bert")
|
||||
yield other
|
||||
|
||||
|
||||
def create_project(c, name="Work", **fields):
|
||||
response = c.post("/api/projects", json={"name": name, **fields})
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def create_clip(c, **fields):
|
||||
response = c.post("/api/clips", json={"content": "hello", **fields})
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def clip_ids(c, **params):
|
||||
response = c.get("/api/clips", params=params)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["total"] == len(body["items"])
|
||||
return [clip["id"] for clip in body["items"]]
|
||||
|
||||
|
||||
# --- Projects -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_create_and_list_projects_sorted_by_name(anna):
|
||||
create_project(anna, "zeta")
|
||||
project = create_project(anna, " Alpha Beta ", color="green")
|
||||
create_project(anna, "Mitte")
|
||||
|
||||
assert project["name"] == "Alpha Beta"
|
||||
assert project["color"] == "green"
|
||||
assert project["clip_count"] == 0
|
||||
names = [p["name"] for p in anna.get("/api/projects").json()]
|
||||
assert names == ["Alpha Beta", "Mitte", "zeta"]
|
||||
|
||||
|
||||
def test_default_color(anna):
|
||||
assert create_project(anna)["color"] == "blue"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"name": " "},
|
||||
{"name": "x" * 101},
|
||||
{"name": "bell\x07"},
|
||||
{"name": "zero\u200bwidth"},
|
||||
{"name": "ok", "color": "black"},
|
||||
{},
|
||||
],
|
||||
)
|
||||
def test_create_validation(anna, body):
|
||||
assert anna.post("/api/projects", json=body).status_code in (400, 422)
|
||||
|
||||
|
||||
def test_name_is_unique_per_user_ignoring_case(anna, bert):
|
||||
create_project(anna, "Straße")
|
||||
|
||||
response = anna.post("/api/projects", json={"name": "STRASSE"})
|
||||
assert response.status_code == 400
|
||||
assert "gibt es schon" in response.json()["detail"]
|
||||
# Another user may use the same name
|
||||
create_project(bert, "Straße")
|
||||
|
||||
|
||||
def test_rename_and_recolor(anna):
|
||||
project = create_project(anna, "Old")
|
||||
|
||||
response = anna.patch(f"/api/projects/{project['id']}", json={"name": "New"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["name"] == "New"
|
||||
assert response.json()["color"] == "blue"
|
||||
|
||||
response = anna.patch(f"/api/projects/{project['id']}", json={"color": "red"})
|
||||
assert (response.json()["name"], response.json()["color"]) == ("New", "red")
|
||||
|
||||
|
||||
def test_rename_to_existing_name_fails(anna):
|
||||
create_project(anna, "One")
|
||||
two = create_project(anna, "Two")
|
||||
|
||||
response = anna.patch(f"/api/projects/{two['id']}", json={"name": "one"})
|
||||
assert response.status_code == 400
|
||||
# Changing only the case of the own name is allowed
|
||||
assert anna.patch(f"/api/projects/{two['id']}", json={"name": "TWO"}).status_code == 200
|
||||
|
||||
|
||||
def test_project_limit(anna, monkeypatch):
|
||||
monkeypatch.setattr("app.services.projects.MAX_PROJECTS_PER_USER", 2)
|
||||
create_project(anna, "a")
|
||||
create_project(anna, "b")
|
||||
|
||||
response = anna.post("/api/projects", json={"name": "c"})
|
||||
assert response.status_code == 400
|
||||
assert "Höchstens 2" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_clip_count(anna):
|
||||
project = create_project(anna)
|
||||
create_clip(anna, project_id=project["id"])
|
||||
create_clip(anna, project_id=project["id"])
|
||||
create_clip(anna)
|
||||
|
||||
assert anna.get("/api/projects").json()[0]["clip_count"] == 2
|
||||
|
||||
|
||||
def test_delete_project_keeps_clips(anna):
|
||||
project = create_project(anna)
|
||||
clip = create_clip(anna, project_id=project["id"])
|
||||
|
||||
assert anna.delete(f"/api/projects/{project['id']}").status_code == 204
|
||||
|
||||
assert anna.get("/api/projects").json() == []
|
||||
current = anna.get(f"/api/clips/{clip['id']}").json()
|
||||
assert current["project_id"] is None
|
||||
assert current["content"] == "hello"
|
||||
# Version is bumped so a stale editor gets a conflict instead of a missing project
|
||||
assert current["version"] == clip["version"] + 1
|
||||
assert current["updated_at"] == clip["updated_at"]
|
||||
|
||||
|
||||
def test_stale_editor_gets_conflict_after_project_deletion(anna):
|
||||
project = create_project(anna)
|
||||
clip = create_clip(anna, project_id=project["id"])
|
||||
anna.delete(f"/api/projects/{project['id']}")
|
||||
|
||||
response = anna.patch(
|
||||
f"/api/clips/{clip['id']}",
|
||||
json={"content": "edit", "project_id": project["id"], "version": clip["version"]},
|
||||
)
|
||||
assert response.status_code == 409
|
||||
assert response.json()["current"]["project_id"] is None
|
||||
|
||||
|
||||
def test_requires_login(client):
|
||||
assert client.get("/api/projects").status_code == 401
|
||||
|
||||
|
||||
# --- Clips in projects ----------------------------------------------------------
|
||||
|
||||
|
||||
def test_assign_clip_to_project(anna):
|
||||
project = create_project(anna)
|
||||
clip = create_clip(anna)
|
||||
|
||||
response = anna.patch(f"/api/clips/{clip['id']}", json={"project_id": project["id"]})
|
||||
assert response.status_code == 200
|
||||
moved = response.json()
|
||||
assert moved["project_id"] == project["id"]
|
||||
# Moving is not an edit, so the clip keeps its place in the list
|
||||
assert moved["updated_at"] == clip["updated_at"]
|
||||
|
||||
response = anna.patch(f"/api/clips/{clip['id']}", json={"project_id": None})
|
||||
assert response.json()["project_id"] is None
|
||||
|
||||
|
||||
def test_other_fields_keep_project(anna):
|
||||
project = create_project(anna)
|
||||
clip = create_clip(anna, project_id=project["id"])
|
||||
|
||||
response = anna.patch(f"/api/clips/{clip['id']}", json={"content": "changed"})
|
||||
assert response.json()["project_id"] == project["id"]
|
||||
|
||||
|
||||
def test_unknown_project_is_rejected(anna):
|
||||
assert anna.post("/api/clips", json={"content": "x", "project_id": 999}).status_code == 404
|
||||
clip = create_clip(anna)
|
||||
response = anna.patch(f"/api/clips/{clip['id']}", json={"project_id": 999})
|
||||
assert response.status_code == 404
|
||||
assert response.json()["detail"] == "Projekt nicht gefunden."
|
||||
|
||||
|
||||
def test_filter_by_project(anna):
|
||||
work = create_project(anna, "Work")
|
||||
home = create_project(anna, "Home")
|
||||
a = create_clip(anna, project_id=work["id"])
|
||||
b = create_clip(anna, project_id=home["id"])
|
||||
c = create_clip(anna)
|
||||
|
||||
assert clip_ids(anna, project=work["id"]) == [a["id"]]
|
||||
assert clip_ids(anna, project=home["id"]) == [b["id"]]
|
||||
assert clip_ids(anna, project="none") == [c["id"]]
|
||||
assert set(clip_ids(anna)) == {a["id"], b["id"], c["id"]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["abc", "0", "-1", "1; drop", ""])
|
||||
def test_invalid_project_filter(anna, value):
|
||||
assert anna.get("/api/clips", params={"project": value}).status_code == 422
|
||||
|
||||
|
||||
# --- Search ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_search_finds_substrings_in_content_and_title(anna):
|
||||
code = create_clip(anna, kind="code", language="python", content="cfg = getConfig()")
|
||||
titled = create_clip(anna, title="Server-Config", content="port 8085")
|
||||
create_clip(anna, content="nothing here")
|
||||
|
||||
assert set(clip_ids(anna, q="config")) == {code["id"], titled["id"]}
|
||||
assert clip_ids(anna, q="8085") == [titled["id"]]
|
||||
assert clip_ids(anna, q="missing") == []
|
||||
|
||||
|
||||
def test_search_ignores_case_including_umlauts(anna):
|
||||
clip = create_clip(anna, content="Größe der ÜBERSICHT")
|
||||
|
||||
assert clip_ids(anna, q="größe") == [clip["id"]]
|
||||
assert clip_ids(anna, q="übersicht") == [clip["id"]]
|
||||
assert clip_ids(anna, q="GROESSE") == []
|
||||
assert clip_ids(anna, q="GRÖSSE") == [clip["id"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["%", "_", "100%", "a_b", "\\"])
|
||||
def test_search_treats_wildcards_literally(anna, query):
|
||||
match = create_clip(anna, content="100% done, a_b, back\\slash")
|
||||
create_clip(anna, content="plain text")
|
||||
|
||||
assert clip_ids(anna, q=query) == [match["id"]]
|
||||
|
||||
|
||||
def test_blank_search_returns_everything(anna):
|
||||
create_clip(anna)
|
||||
create_clip(anna)
|
||||
|
||||
assert len(clip_ids(anna, q=" ")) == 2
|
||||
|
||||
|
||||
def test_search_combined_with_project(anna):
|
||||
project = create_project(anna)
|
||||
inside = create_clip(anna, content="token abc", project_id=project["id"])
|
||||
create_clip(anna, content="token abc")
|
||||
create_clip(anna, content="other", project_id=project["id"])
|
||||
|
||||
assert clip_ids(anna, q="token", project=project["id"]) == [inside["id"]]
|
||||
|
||||
|
||||
def test_search_total_counts_all_matches(anna):
|
||||
for i in range(5):
|
||||
create_clip(anna, content=f"match {i}")
|
||||
create_clip(anna, content="other")
|
||||
|
||||
body = anna.get("/api/clips", params={"q": "match", "limit": 2}).json()
|
||||
assert len(body["items"]) == 2
|
||||
assert body["total"] == 5
|
||||
|
||||
|
||||
def test_search_length_limit(anna):
|
||||
assert anna.get("/api/clips", params={"q": "x" * 201}).status_code == 422
|
||||
|
||||
|
||||
# --- Data separation ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_projects_of_other_users_are_invisible(anna, bert):
|
||||
project = create_project(anna, "Secret")
|
||||
url = f"/api/projects/{project['id']}"
|
||||
|
||||
assert bert.get("/api/projects").json() == []
|
||||
assert bert.patch(url, json={"name": "Mine"}).status_code == 404
|
||||
assert bert.delete(url).status_code == 404
|
||||
assert anna.get("/api/projects").json()[0]["name"] == "Secret"
|
||||
|
||||
|
||||
def test_cannot_use_foreign_project_for_clips(anna, bert):
|
||||
project = create_project(anna)
|
||||
|
||||
response = bert.post("/api/clips", json={"content": "x", "project_id": project["id"]})
|
||||
assert response.status_code == 404
|
||||
clip = create_clip(bert)
|
||||
response = bert.patch(f"/api/clips/{clip['id']}", json={"project_id": project["id"]})
|
||||
assert response.status_code == 404
|
||||
assert anna.get("/api/projects").json()[0]["clip_count"] == 0
|
||||
|
||||
|
||||
def test_filters_and_search_never_return_foreign_clips(anna, bert):
|
||||
project = create_project(anna)
|
||||
create_clip(anna, content="secret anna", project_id=project["id"])
|
||||
create_clip(anna, content="secret anna")
|
||||
|
||||
assert clip_ids(bert, q="secret") == []
|
||||
assert clip_ids(bert, project=project["id"]) == []
|
||||
assert clip_ids(bert, project="none") == []
|
||||
|
||||
|
||||
def test_deleting_foreign_project_does_not_touch_its_clips(anna, bert):
|
||||
project = create_project(anna)
|
||||
clip = create_clip(anna, project_id=project["id"])
|
||||
|
||||
assert bert.delete(f"/api/projects/{project['id']}").status_code == 404
|
||||
assert anna.get(f"/api/clips/{clip['id']}").json()["project_id"] == project["id"]
|
||||
|
||||
|
||||
def test_deleting_user_removes_projects(client, anna, db, make_user):
|
||||
from app.models import Project, Role, User
|
||||
|
||||
project_id = create_project(anna)["id"]
|
||||
make_user("root", role=Role.ADMIN)
|
||||
with TestClient(client.app, base_url="https://testserver") as admin:
|
||||
login(admin, "root")
|
||||
anna_id = db.query(User).filter_by(username="anna").one().id
|
||||
assert admin.delete(f"/api/admin/users/{anna_id}").status_code == 204
|
||||
|
||||
db.expire_all()
|
||||
assert db.get(Project, project_id) is None
|
||||
|
||||
|
||||
# --- Live sync ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_project_events_reach_all_devices(anna, bert):
|
||||
with connect(anna) as ws, connect(bert) as bert_ws:
|
||||
ws.receive_json()
|
||||
bert_ws.receive_json()
|
||||
|
||||
project = create_project(anna, "Live")
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "project.created"
|
||||
assert event["data"]["name"] == "Live"
|
||||
|
||||
anna.patch(f"/api/projects/{project['id']}", json={"color": "pink"})
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "project.updated"
|
||||
assert event["data"]["color"] == "pink"
|
||||
|
||||
anna.delete(f"/api/projects/{project['id']}")
|
||||
assert ws.receive_json() == {"type": "project.deleted", "data": {"id": project["id"]}}
|
||||
|
||||
# Bert gets nothing of this; his first event is his own
|
||||
create_clip(bert)
|
||||
assert bert_ws.receive_json()["type"] == "clip.created"
|
||||
@@ -0,0 +1,39 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def built(static_dir):
|
||||
"""Minimal stand-in for the frontend build output."""
|
||||
(static_dir / "assets").mkdir()
|
||||
(static_dir / "icons").mkdir()
|
||||
(static_dir / "index.html").write_text("<html>spa</html>")
|
||||
(static_dir / "sw.js").write_text("self.addEventListener('fetch', () => {})")
|
||||
(static_dir / "workbox-abc123.js").write_text("// workbox")
|
||||
(static_dir / "manifest.webmanifest").write_text('{"name": "LAN-Clipboard"}')
|
||||
(static_dir / "assets" / "index-abc123.js").write_text("console.log(1)")
|
||||
(static_dir / "icons" / "icon-192.png").write_bytes(b"\\x89PNG")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/", "/clips/1", "/index.html", "/sw.js"])
|
||||
def test_entry_points_are_revalidated(built, client, path):
|
||||
assert client.get(path).headers["cache-control"] == "no-cache"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/assets/index-abc123.js", "/workbox-abc123.js"])
|
||||
def test_hashed_files_are_immutable(built, client, path):
|
||||
assert client.get(path).headers["cache-control"] == "public, max-age=31536000, immutable"
|
||||
|
||||
|
||||
def test_icons_are_cached_for_a_day(built, client):
|
||||
assert client.get("/icons/icon-192.png").headers["cache-control"] == "public, max-age=86400"
|
||||
|
||||
|
||||
def test_manifest_content_type(built, client):
|
||||
response = client.get("/manifest.webmanifest")
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"].startswith("application/manifest+json")
|
||||
assert response.headers["cache-control"] == "no-cache"
|
||||
|
||||
|
||||
def test_service_worker_is_javascript(built, client):
|
||||
assert "javascript" in client.get("/sw.js").headers["content-type"]
|
||||
@@ -0,0 +1,386 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import get_settings
|
||||
from tests.conftest import login
|
||||
from tests.test_ws import connect
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def users(client, make_user):
|
||||
"""anna owns projects, bert gets them shared, carl is an outsider."""
|
||||
clients = {}
|
||||
for name in ("anna", "bert", "carl"):
|
||||
make_user(name)
|
||||
c = TestClient(client.app, base_url="https://testserver")
|
||||
c.__enter__()
|
||||
login(c, name)
|
||||
clients[name] = c
|
||||
yield clients
|
||||
for c in clients.values():
|
||||
c.__exit__(None, None, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(users):
|
||||
return users["anna"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bert(users):
|
||||
return users["bert"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def carl(users):
|
||||
return users["carl"]
|
||||
|
||||
|
||||
def create_project(c, name="Team"):
|
||||
response = c.post("/api/projects", json={"name": name})
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def share(owner, project, username="bert", role="edit"):
|
||||
response = owner.post(
|
||||
f"/api/projects/{project['id']}/members", json={"username": username, "role": role}
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def create_clip(c, **fields):
|
||||
response = c.post("/api/clips", json={"content": "hello", **fields})
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def clip_ids(c, **params):
|
||||
return {clip["id"] for clip in c.get("/api/clips", params=params).json()["items"]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def team(anna):
|
||||
"""anna's project shared with bert as editor."""
|
||||
project = create_project(anna)
|
||||
share(anna, project)
|
||||
return project
|
||||
|
||||
|
||||
# --- Members --------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_owner_shares_project(anna, bert, carl):
|
||||
project = create_project(anna)
|
||||
members = share(anna, project, "BERT", "read")
|
||||
|
||||
assert members == [
|
||||
{"user_id": members[0]["user_id"], "username": "anna", "role": "owner"},
|
||||
{"user_id": members[1]["user_id"], "username": "bert", "role": "read"},
|
||||
]
|
||||
seen = bert.get("/api/projects").json()
|
||||
assert [(p["name"], p["role"], p["owner_name"], p["member_count"]) for p in seen] == [
|
||||
("Team", "read", "anna", 1)
|
||||
]
|
||||
assert anna.get("/api/projects").json()[0]["role"] == "owner"
|
||||
assert carl.get("/api/projects").json() == []
|
||||
assert bert.get(f"/api/projects/{project['id']}/members").json() == members
|
||||
assert carl.get(f"/api/projects/{project['id']}/members").status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("username", "message"),
|
||||
[("nobody", "gibt es nicht"), ("anna", "gehört dir bereits"), ("bert", "schon Mitglied")],
|
||||
)
|
||||
def test_invalid_members(anna, bert, team, username, message):
|
||||
response = anna.post(f"/api/projects/{team['id']}/members", json={"username": username})
|
||||
assert response.status_code == 400
|
||||
assert message in response.json()["detail"]
|
||||
|
||||
|
||||
def test_inactive_users_cannot_be_added(anna, carl, db):
|
||||
from app.models import User
|
||||
|
||||
db.query(User).filter_by(username="carl").one().is_active = False
|
||||
db.commit()
|
||||
project = create_project(anna)
|
||||
response = anna.post(f"/api/projects/{project['id']}/members", json={"username": "carl"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_only_owner_manages_project(anna, bert, carl, team):
|
||||
url = f"/api/projects/{team['id']}"
|
||||
anna_id = anna.get(f"{url}/members").json()[0]["user_id"]
|
||||
bert_id = anna.get(f"{url}/members").json()[1]["user_id"]
|
||||
|
||||
for c, status in ((bert, 403), (carl, 404)):
|
||||
assert c.patch(url, json={"name": "Mine"}).status_code == status
|
||||
assert c.delete(url).status_code == status
|
||||
assert c.post(f"{url}/members", json={"username": "carl"}).status_code == status
|
||||
assert c.patch(f"{url}/members/{bert_id}", json={"role": "read"}).status_code == status
|
||||
assert bert.delete(f"{url}/members/{anna_id}").status_code == 403
|
||||
assert anna.get(url + "/members").json()[1]["role"] == "edit"
|
||||
|
||||
|
||||
def test_change_role(anna, bert, team):
|
||||
url = f"/api/projects/{team['id']}/members"
|
||||
bert_id = anna.get(url).json()[1]["user_id"]
|
||||
|
||||
response = anna.patch(f"{url}/{bert_id}", json={"role": "read"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()[1]["role"] == "read"
|
||||
assert bert.get("/api/projects").json()[0]["role"] == "read"
|
||||
assert anna.patch(f"{url}/{bert_id}", json={"role": "owner"}).status_code == 422
|
||||
assert anna.patch(f"{url}/9999", json={"role": "read"}).status_code == 404
|
||||
|
||||
|
||||
def test_user_names(anna, db):
|
||||
from app.models import User
|
||||
|
||||
db.query(User).filter_by(username="carl").one().is_active = False
|
||||
db.commit()
|
||||
names = anna.get("/api/users").json()
|
||||
assert [u["username"] for u in names] == ["bert"]
|
||||
assert set(names[0]) == {"id", "username"}
|
||||
|
||||
|
||||
def test_project_names_are_unique_per_owner_only(anna, bert, team):
|
||||
create_project(bert, "Team")
|
||||
assert {p["owner_name"] for p in bert.get("/api/projects").json()} == {"anna", "bert"}
|
||||
|
||||
|
||||
# --- Visibility -----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_members_see_clips_in_shared_projects(anna, bert, carl, team):
|
||||
shared = create_clip(anna, content="team note", project_id=team["id"])
|
||||
private = create_clip(anna, content="private note")
|
||||
own = create_clip(bert, content="bert note", project_id=team["id"])
|
||||
|
||||
assert clip_ids(bert) == {shared["id"], own["id"]}
|
||||
assert clip_ids(bert, project=team["id"]) == {shared["id"], own["id"]}
|
||||
assert clip_ids(bert, q="team") == {shared["id"]}
|
||||
assert clip_ids(bert, project="none") == set()
|
||||
assert clip_ids(anna) == {shared["id"], private["id"], own["id"]}
|
||||
assert clip_ids(carl) == set()
|
||||
assert clip_ids(carl, project=team["id"]) == set()
|
||||
assert bert.get(f"/api/clips/{private['id']}").status_code == 404
|
||||
assert carl.get(f"/api/clips/{shared['id']}").status_code == 404
|
||||
|
||||
seen = bert.get(f"/api/clips/{shared['id']}").json()
|
||||
assert seen["owner_name"] == "anna"
|
||||
assert anna.get("/api/projects").json()[0]["clip_count"] == 2
|
||||
|
||||
|
||||
def test_editor_may_change_everything_in_project(anna, bert, team):
|
||||
clip = create_clip(anna, project_id=team["id"])
|
||||
url = f"/api/clips/{clip['id']}"
|
||||
|
||||
assert bert.patch(url, json={"content": "edited by bert"}).status_code == 200
|
||||
assert bert.patch(url, json={"pinned": True}).status_code == 200
|
||||
assert bert.delete(url).status_code == 204
|
||||
assert anna.get(url).status_code == 404
|
||||
|
||||
|
||||
def test_reader_may_only_look(anna, bert, team):
|
||||
bert_id = anna.get(f"/api/projects/{team['id']}/members").json()[1]["user_id"]
|
||||
own = create_clip(bert, content="written as editor", project_id=team["id"])
|
||||
anna.patch(f"/api/projects/{team['id']}/members/{bert_id}", json={"role": "read"})
|
||||
clip = create_clip(anna, project_id=team["id"])
|
||||
url = f"/api/clips/{clip['id']}"
|
||||
|
||||
assert bert.get(url).status_code == 200
|
||||
for response in (
|
||||
bert.patch(url, json={"content": "x"}),
|
||||
bert.patch(url, json={"pinned": True}),
|
||||
bert.delete(url),
|
||||
bert.post("/api/clips", json={"content": "x", "project_id": team["id"]}),
|
||||
):
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"] == "Nur Lesezugriff auf dieses Projekt."
|
||||
# Own clips stay editable
|
||||
assert bert.patch(f"/api/clips/{own['id']}", json={"content": "mine"}).status_code == 200
|
||||
|
||||
|
||||
def test_outsiders_cannot_touch_shared_clips(anna, carl, team):
|
||||
clip = create_clip(anna, project_id=team["id"])
|
||||
url = f"/api/clips/{clip['id']}"
|
||||
|
||||
assert carl.patch(url, json={"content": "x"}).status_code == 404
|
||||
assert carl.delete(url).status_code == 404
|
||||
assert (
|
||||
carl.post("/api/clips", json={"content": "x", "project_id": team["id"]}).status_code == 404
|
||||
)
|
||||
own = create_clip(carl)
|
||||
response = carl.patch(f"/api/clips/{own['id']}", json={"project_id": team["id"]})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_moving_a_clip_out_makes_it_private(anna, bert, team):
|
||||
clip = create_clip(anna, project_id=team["id"])
|
||||
|
||||
response = bert.patch(f"/api/clips/{clip['id']}", json={"project_id": None})
|
||||
assert response.status_code == 200
|
||||
assert bert.get(f"/api/clips/{clip['id']}").status_code == 404
|
||||
assert anna.get(f"/api/clips/{clip['id']}").json()["project_id"] is None
|
||||
|
||||
|
||||
def test_member_may_move_own_clip_into_shared_project(anna, bert, team):
|
||||
clip = create_clip(bert, content="for the team")
|
||||
bert.patch(f"/api/clips/{clip['id']}", json={"project_id": team["id"]})
|
||||
assert clip["id"] in clip_ids(anna)
|
||||
|
||||
|
||||
# --- Removal --------------------------------------------------------------------
|
||||
|
||||
|
||||
def _bert_id(anna, team):
|
||||
return anna.get(f"/api/projects/{team['id']}/members").json()[1]["user_id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("who", ["owner", "self"])
|
||||
def test_removed_member_keeps_own_clips_and_loses_access(anna, bert, team, who):
|
||||
theirs = create_clip(anna, project_id=team["id"])
|
||||
mine = create_clip(bert, project_id=team["id"])
|
||||
remover = anna if who == "owner" else bert
|
||||
|
||||
response = remover.delete(f"/api/projects/{team['id']}/members/{_bert_id(anna, team)}")
|
||||
assert response.status_code == 204
|
||||
|
||||
assert bert.get("/api/projects").json() == []
|
||||
assert clip_ids(bert) == {mine["id"]}
|
||||
moved = bert.get(f"/api/clips/{mine['id']}").json()
|
||||
assert moved["project_id"] is None
|
||||
assert moved["version"] == mine["version"] + 1
|
||||
assert clip_ids(bert, project="none") == {mine["id"]}
|
||||
assert clip_ids(anna) == {theirs["id"]}
|
||||
assert bert.get(f"/api/clips/{theirs['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_removing_twice_is_404(anna, bert, team):
|
||||
url = f"/api/projects/{team['id']}/members/{_bert_id(anna, team)}"
|
||||
assert anna.delete(url).status_code == 204
|
||||
assert anna.delete(url).status_code == 404
|
||||
assert bert.delete(url).status_code == 404
|
||||
|
||||
|
||||
def test_deleting_shared_project_returns_clips_to_owners(anna, bert, team):
|
||||
theirs = create_clip(anna, project_id=team["id"])
|
||||
mine = create_clip(bert, project_id=team["id"])
|
||||
|
||||
assert anna.delete(f"/api/projects/{team['id']}").status_code == 204
|
||||
assert clip_ids(anna) == {theirs["id"]}
|
||||
assert clip_ids(bert) == {mine["id"]}
|
||||
|
||||
|
||||
# --- Files ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def upload(c, data=b"data", **params):
|
||||
response = c.post("/api/files", params={"name": "f.txt", **params}, content=data)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_shared_files(anna, bert, carl, team):
|
||||
clip = upload(bert, b"from bert", project_id=team["id"])
|
||||
url = f"/api/files/{clip['id']}"
|
||||
|
||||
assert anna.get(url).content == b"from bert"
|
||||
assert carl.get(url).status_code == 404
|
||||
# Counts against the uploader
|
||||
assert bert.get("/api/files/usage").json()["used_bytes"] == 9
|
||||
assert anna.get("/api/files/usage").json()["used_bytes"] == 0
|
||||
|
||||
files_dir = get_settings().files_dir
|
||||
assert len(list(files_dir.glob("*/*"))) == 1
|
||||
assert anna.delete(f"/api/clips/{clip['id']}").status_code == 204
|
||||
assert [p for p in files_dir.glob("*/*") if p.is_file()] == []
|
||||
|
||||
|
||||
def test_readers_download_but_cannot_upload(anna, bert, team):
|
||||
anna.patch(f"/api/projects/{team['id']}/members/{_bert_id(anna, team)}", json={"role": "read"})
|
||||
clip = upload(anna, project_id=team["id"])
|
||||
|
||||
assert bert.get(f"/api/files/{clip['id']}").status_code == 200
|
||||
assert bert.patch(f"/api/files/{clip['id']}", json={"expires_days": 0}).status_code == 403
|
||||
response = bert.post("/api/files", params={"name": "x", "project_id": team["id"]}, content=b"x")
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_removed_member_cannot_download(anna, bert, team):
|
||||
clip = upload(anna, project_id=team["id"])
|
||||
anna.delete(f"/api/projects/{team['id']}/members/{_bert_id(anna, team)}")
|
||||
assert bert.get(f"/api/files/{clip['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_expired_files_notify_all_members(anna, bert, team, db):
|
||||
from app.models import StoredFile, User, utcnow
|
||||
from app.services import files as file_service
|
||||
|
||||
clip = upload(anna, project_id=team["id"])
|
||||
db.query(StoredFile).one().expires_at = utcnow()
|
||||
db.commit()
|
||||
ids = {u.username: u.id for u in db.query(User)}
|
||||
|
||||
assert file_service.delete_expired(db) == [(clip["id"], {ids["anna"], ids["bert"]})]
|
||||
|
||||
|
||||
# --- Live sync ------------------------------------------------------------------
|
||||
|
||||
|
||||
def _drain_hello(*sockets):
|
||||
for ws in sockets:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
|
||||
|
||||
def test_clip_events_reach_all_members_only(anna, bert, carl, team):
|
||||
with connect(anna) as a, connect(bert) as b, connect(carl) as c:
|
||||
_drain_hello(a, b, c)
|
||||
|
||||
clip = create_clip(bert, content="hi team", project_id=team["id"])
|
||||
for ws in (a, b):
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "clip.created"
|
||||
assert event["data"]["owner_name"] == "bert"
|
||||
|
||||
# Moved out of the project: the clip is bert's private again, anna no longer sees it
|
||||
anna.patch(f"/api/clips/{clip['id']}", json={"project_id": None}).raise_for_status()
|
||||
assert b.receive_json()["type"] == "clip.updated"
|
||||
assert a.receive_json() == {"type": "clip.deleted", "data": {"id": clip["id"]}}
|
||||
|
||||
create_clip(carl, content="carl's own")
|
||||
assert c.receive_json()["data"]["content"] == "carl's own"
|
||||
|
||||
|
||||
def test_membership_events(anna, bert):
|
||||
project = create_project(anna)
|
||||
with connect(anna) as a, connect(bert) as b:
|
||||
_drain_hello(a, b)
|
||||
|
||||
share(anna, project)
|
||||
event = b.receive_json()
|
||||
assert event["type"] == "project.created"
|
||||
assert (event["data"]["role"], event["data"]["owner_name"]) == ("edit", "anna")
|
||||
event = a.receive_json()
|
||||
assert event["type"] == "project.updated"
|
||||
assert (event["data"]["role"], event["data"]["member_count"]) == ("owner", 1)
|
||||
|
||||
anna.patch(f"/api/projects/{project['id']}", json={"name": "Renamed"})
|
||||
for ws, role in ((a, "owner"), (b, "edit")):
|
||||
event = ws.receive_json()
|
||||
assert (event["type"], event["data"]["name"], event["data"]["role"]) == (
|
||||
"project.updated",
|
||||
"Renamed",
|
||||
role,
|
||||
)
|
||||
|
||||
mine = create_clip(bert, project_id=project["id"])
|
||||
a.receive_json()
|
||||
b.receive_json()
|
||||
bert_id = _bert_id(anna, project)
|
||||
anna.delete(f"/api/projects/{project['id']}/members/{bert_id}")
|
||||
assert b.receive_json() == {"type": "project.deleted", "data": {"id": project["id"]}}
|
||||
assert a.receive_json() == {"type": "clip.deleted", "data": {"id": mine["id"]}}
|
||||
assert a.receive_json()["data"]["member_count"] == 0
|
||||
@@ -0,0 +1,246 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from app.api import ws as ws_module
|
||||
from app.models import ApiToken, Role, User
|
||||
from tests.conftest import login
|
||||
from tests.test_ws import connect
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
return client
|
||||
|
||||
|
||||
def create_token(c, name="Laptop"):
|
||||
response = c.post("/api/tokens", json={"name": name})
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def agent(anna):
|
||||
"""A client without cookies that authenticates with a device token only."""
|
||||
token = create_token(anna)["token"]
|
||||
with TestClient(anna.app, base_url="https://testserver") as c:
|
||||
c.headers["Authorization"] = f"Bearer {token}"
|
||||
yield c
|
||||
|
||||
|
||||
def ws_with_token(c, token, origin=None):
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
if origin:
|
||||
headers["Origin"] = origin
|
||||
return c.websocket_connect("/api/ws", headers=headers)
|
||||
|
||||
|
||||
# --- Managing tokens ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_create_token_shows_value_once(anna):
|
||||
created = create_token(anna, " Arbeits Laptop ")
|
||||
|
||||
assert created["name"] == "Arbeits Laptop"
|
||||
assert created["token"].startswith("lc_")
|
||||
assert len(created["token"]) > 40
|
||||
assert created["prefix"] == created["token"][:10]
|
||||
assert created["last_used_at"] is None
|
||||
listed = anna.get("/api/tokens").json()
|
||||
assert [t["name"] for t in listed] == ["Arbeits Laptop"]
|
||||
assert "token" not in listed[0]
|
||||
|
||||
|
||||
def test_only_the_hash_is_stored(anna, db):
|
||||
plain = create_token(anna)["token"]
|
||||
stored = db.query(ApiToken).one()
|
||||
assert plain not in (stored.token_hash, stored.prefix)
|
||||
assert len(stored.token_hash) == 64
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", " ", "x" * 101, "bad\x00name"])
|
||||
def test_token_name_validation(anna, name):
|
||||
assert anna.post("/api/tokens", json={"name": name}).status_code == 400
|
||||
|
||||
|
||||
def test_token_limit(anna, monkeypatch):
|
||||
monkeypatch.setattr("app.services.tokens.MAX_TOKENS_PER_USER", 1)
|
||||
create_token(anna)
|
||||
assert anna.post("/api/tokens", json={"name": "second"}).status_code == 400
|
||||
|
||||
|
||||
def test_tokens_of_other_users_are_invisible(anna, client, make_user):
|
||||
token = create_token(anna)
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as bert:
|
||||
login(bert, "bert")
|
||||
assert bert.get("/api/tokens").json() == []
|
||||
assert bert.delete(f"/api/tokens/{token['id']}").status_code == 404
|
||||
assert len(anna.get("/api/tokens").json()) == 1
|
||||
|
||||
|
||||
# --- Using tokens ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_works_without_cookie_or_csrf(agent):
|
||||
assert agent.cookies.get("lc_session") is None
|
||||
created = agent.post("/api/clips", json={"content": "from agent"})
|
||||
assert created.status_code == 201
|
||||
assert agent.get("/api/clips").json()["items"][0]["content"] == "from agent"
|
||||
assert (
|
||||
agent.patch(f"/api/clips/{created.json()['id']}", json={"pinned": True}).status_code == 200
|
||||
)
|
||||
assert agent.post("/api/files", params={"name": "a.txt"}, content=b"data").status_code == 201
|
||||
assert agent.get("/api/projects").status_code == 200
|
||||
assert agent.post("/api/projects", json={"name": "Zwischenablage"}).status_code == 201
|
||||
|
||||
|
||||
def test_token_records_last_use(anna, agent):
|
||||
agent.get("/api/clips")
|
||||
token = anna.get("/api/tokens").json()[0]
|
||||
assert token["last_used_at"] is not None
|
||||
assert token["last_ip"] == "testclient"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path", "body"),
|
||||
[
|
||||
("GET", "/api/auth/me", None),
|
||||
("GET", "/api/auth/sessions", None),
|
||||
("POST", "/api/auth/password", {"current_password": "x", "new_password": "y" * 12}),
|
||||
("GET", "/api/tokens", None),
|
||||
("POST", "/api/tokens", {"name": "more"}),
|
||||
("GET", "/api/admin/users", None),
|
||||
("PATCH", "/api/projects/1", {"name": "x"}),
|
||||
("DELETE", "/api/projects/1", None),
|
||||
("POST", "/api/projects/1/members", {"username": "x"}),
|
||||
],
|
||||
)
|
||||
def test_token_cannot_reach_account_admin_or_project_management(agent, method, path, body):
|
||||
assert agent.request(method, path, json=body).status_code == 401
|
||||
|
||||
|
||||
def test_admin_token_cannot_use_admin_api(client, make_user):
|
||||
make_user("root", role=Role.ADMIN)
|
||||
login(client, "root")
|
||||
token = create_token(client)["token"]
|
||||
with TestClient(client.app, base_url="https://testserver") as c:
|
||||
response = c.get("/api/admin/users", headers={"Authorization": f"Bearer {token}"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["lc_wrong", "not-a-token", "", "Bearer"])
|
||||
def test_invalid_tokens(client, value):
|
||||
response = client.get("/api/clips", headers={"Authorization": f"Bearer {value}"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_revoked_token_stops_working(anna, agent):
|
||||
token_id = anna.get("/api/tokens").json()[0]["id"]
|
||||
assert anna.delete(f"/api/tokens/{token_id}").status_code == 204
|
||||
assert agent.get("/api/clips").status_code == 401
|
||||
assert anna.delete(f"/api/tokens/{token_id}").status_code == 404
|
||||
|
||||
|
||||
def test_tokens_of_deactivated_or_deleted_users(anna, agent, db):
|
||||
user = db.query(User).filter_by(username="anna").one()
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
assert agent.get("/api/clips").status_code == 401
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
assert db.query(ApiToken).count() == 0
|
||||
|
||||
|
||||
def test_token_respects_data_separation(anna, client, make_user):
|
||||
secret = anna.post("/api/clips", json={"content": "anna only"}).json()
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as bert:
|
||||
login(bert, "bert")
|
||||
token = create_token(bert)["token"]
|
||||
bert.cookies.clear()
|
||||
bert.headers["Authorization"] = f"Bearer {token}"
|
||||
assert bert.get("/api/clips").json()["items"] == []
|
||||
assert bert.get(f"/api/clips/{secret['id']}").status_code == 404
|
||||
assert bert.delete(f"/api/clips/{secret['id']}").status_code == 404
|
||||
|
||||
|
||||
# --- WebSocket ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_websocket_with_token_and_without_origin(anna):
|
||||
token = create_token(anna)["token"]
|
||||
with ws_with_token(anna, token) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
anna.post("/api/clips", json={"content": "to the agent"})
|
||||
event = ws.receive_json()
|
||||
assert (event["type"], event["data"]["content"]) == ("clip.created", "to the agent")
|
||||
|
||||
|
||||
def test_websocket_token_with_foreign_origin_is_rejected(anna):
|
||||
token = create_token(anna)["token"]
|
||||
with (
|
||||
pytest.raises(WebSocketDisconnect) as exc,
|
||||
ws_with_token(anna, token, "https://evil.example") as ws,
|
||||
):
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4403
|
||||
|
||||
|
||||
def test_websocket_invalid_token_is_4401(client):
|
||||
with pytest.raises(WebSocketDisconnect) as exc, ws_with_token(client, "lc_nope") as ws:
|
||||
ws.receive_json()
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_revoking_token_closes_its_socket_only(anna):
|
||||
laptop = create_token(anna, "Laptop")
|
||||
desktop = create_token(anna, "Desktop")
|
||||
|
||||
with ws_with_token(anna, desktop["token"]) as desktop_ws, connect(anna) as browser_ws:
|
||||
desktop_ws.receive_json()
|
||||
browser_ws.receive_json()
|
||||
with (
|
||||
pytest.raises(WebSocketDisconnect) as exc,
|
||||
ws_with_token(anna, laptop["token"]) as laptop_ws,
|
||||
):
|
||||
laptop_ws.receive_json()
|
||||
anna.delete(f"/api/tokens/{laptop['id']}")
|
||||
laptop_ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
anna.post("/api/clips", json={"content": "still live"})
|
||||
assert desktop_ws.receive_json()["type"] == "clip.created"
|
||||
assert browser_ws.receive_json()["type"] == "clip.created"
|
||||
|
||||
|
||||
def test_token_socket_is_revalidated(anna, db, monkeypatch):
|
||||
monkeypatch.setattr(ws_module, "PING_INTERVAL_SECONDS", 0.05)
|
||||
monkeypatch.setattr(ws_module, "REVALIDATE_INTERVAL_SECONDS", 0)
|
||||
token = create_token(anna)["token"]
|
||||
|
||||
with pytest.raises(WebSocketDisconnect) as exc, ws_with_token(anna, token) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
db.query(User).filter_by(username="anna").one().is_active = False
|
||||
db.commit()
|
||||
while True:
|
||||
assert ws.receive_json() == {"type": "ping"}
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_latest_clip_ignores_pinning_and_files(agent):
|
||||
assert agent.get("/api/clips/latest").status_code == 404
|
||||
agent.post("/api/clips", json={"content": "older but pinned", "pinned": True})
|
||||
agent.post("/api/clips", json={"content": "newest text"})
|
||||
agent.post("/api/files", params={"name": "newer.txt"}, content=b"file")
|
||||
|
||||
assert agent.get("/api/clips/latest").json()["content"] == "newest text"
|
||||
|
||||
|
||||
def test_token_knows_its_user(agent, db):
|
||||
anna = db.query(User).filter_by(username="anna").one()
|
||||
assert agent.get("/api/users/me").json() == {"id": anna.id, "username": "anna"}
|
||||
@@ -0,0 +1,210 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from app.api import ws as ws_module
|
||||
from app.models import Role
|
||||
from tests.conftest import PASSWORD, login
|
||||
|
||||
ORIGIN = {"Origin": "https://testserver"}
|
||||
|
||||
|
||||
def connect(c: TestClient, headers=ORIGIN):
|
||||
# TestClient always uses ws:// and therefore drops Secure cookies; browsers use wss://
|
||||
cookie = "; ".join(f"{name}={value}" for name, value in c.cookies.items())
|
||||
return c.websocket_connect("/api/ws", headers={**headers, "Cookie": cookie})
|
||||
|
||||
|
||||
def expect_close(c: TestClient, code: int, headers=ORIGIN) -> None:
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(c, headers) as ws:
|
||||
ws.receive_json()
|
||||
ws.receive_json()
|
||||
assert exc.value.code == code
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def second_client(client):
|
||||
def _make(username: str, password: str = PASSWORD) -> TestClient:
|
||||
other = TestClient(client.app, base_url="https://testserver")
|
||||
login(other, username, password)
|
||||
return other
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
# --- Handshake ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_connect_with_session(anna):
|
||||
with connect(anna) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
|
||||
|
||||
def test_connect_without_session_is_closed_4401(client):
|
||||
expect_close(client, 4401)
|
||||
|
||||
|
||||
def test_foreign_origin_is_rejected(anna):
|
||||
expect_close(anna, 4403, {"Origin": "https://evil.example"})
|
||||
|
||||
|
||||
def test_missing_origin_is_rejected(anna):
|
||||
expect_close(anna, 4403, {})
|
||||
|
||||
|
||||
def test_connection_limit(anna, monkeypatch):
|
||||
monkeypatch.setattr(ws_module, "MAX_CONNECTIONS_PER_USER", 2)
|
||||
with connect(anna) as ws1, connect(anna) as ws2:
|
||||
ws1.receive_json()
|
||||
ws2.receive_json()
|
||||
expect_close(anna, 4429)
|
||||
|
||||
|
||||
# --- Clip events ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_clip_events_reach_all_devices_of_user(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
with connect(anna) as laptop_ws, connect(phone) as phone_ws:
|
||||
laptop_ws.receive_json()
|
||||
phone_ws.receive_json()
|
||||
|
||||
clip = phone.post("/api/clips", json={"content": "from phone"}).json()
|
||||
for ws in (laptop_ws, phone_ws):
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "clip.created"
|
||||
assert event["data"]["id"] == clip["id"]
|
||||
assert event["data"]["content"] == "from phone"
|
||||
|
||||
phone.patch(f"/api/clips/{clip['id']}", json={"content": "edited"})
|
||||
event = laptop_ws.receive_json()
|
||||
assert event["type"] == "clip.updated"
|
||||
assert event["data"]["content"] == "edited"
|
||||
assert event["data"]["version"] == 2
|
||||
phone_ws.receive_json()
|
||||
|
||||
phone.delete(f"/api/clips/{clip['id']}")
|
||||
assert laptop_ws.receive_json() == {"type": "clip.deleted", "data": {"id": clip["id"]}}
|
||||
|
||||
|
||||
def test_no_event_on_conflict(anna):
|
||||
clip = anna.post("/api/clips", json={"content": "x"}).json()
|
||||
with connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
assert (
|
||||
anna.patch(f"/api/clips/{clip['id']}", json={"content": "y", "version": 99}).status_code
|
||||
== 409
|
||||
)
|
||||
anna.post("/api/clips", json={"content": "marker"})
|
||||
# The next event is the marker, so the conflict produced none
|
||||
assert ws.receive_json()["data"]["content"] == "marker"
|
||||
|
||||
|
||||
def test_events_are_not_sent_to_other_users(anna, make_user, second_client):
|
||||
make_user("bert")
|
||||
bert = second_client("bert")
|
||||
with connect(bert) as bert_ws:
|
||||
bert_ws.receive_json()
|
||||
|
||||
anna.post("/api/clips", json={"content": "anna's secret"})
|
||||
bert.post("/api/clips", json={"content": "marker"})
|
||||
|
||||
event = bert_ws.receive_json()
|
||||
assert event["data"]["content"] == "marker"
|
||||
|
||||
|
||||
# --- Session end closes sockets -------------------------------------------------
|
||||
|
||||
|
||||
def test_logout_closes_socket(anna):
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
anna.post("/api/auth/logout")
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_revoking_session_closes_its_socket_only(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
sessions = anna.get("/api/auth/sessions").json()
|
||||
phone_session = next(s for s in sessions if not s["current"])
|
||||
|
||||
with connect(anna) as laptop_ws:
|
||||
laptop_ws.receive_json()
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(phone) as phone_ws:
|
||||
phone_ws.receive_json()
|
||||
anna.delete(f"/api/auth/sessions/{phone_session['id']}")
|
||||
phone_ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
anna.post("/api/clips", json={"content": "still live"})
|
||||
assert laptop_ws.receive_json()["type"] == "clip.created"
|
||||
|
||||
|
||||
def test_revoke_other_sessions_closes_their_sockets(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
with connect(anna) as laptop_ws:
|
||||
laptop_ws.receive_json()
|
||||
with pytest.raises(WebSocketDisconnect), connect(phone) as phone_ws:
|
||||
phone_ws.receive_json()
|
||||
anna.delete("/api/auth/sessions")
|
||||
phone_ws.receive_json()
|
||||
|
||||
anna.post("/api/clips", json={"content": "still live"})
|
||||
assert laptop_ws.receive_json()["type"] == "clip.created"
|
||||
|
||||
|
||||
def test_password_change_closes_other_sockets(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(phone) as phone_ws:
|
||||
phone_ws.receive_json()
|
||||
anna.post(
|
||||
"/api/auth/password",
|
||||
json={"current_password": PASSWORD, "new_password": "brand new password"},
|
||||
)
|
||||
phone_ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "body"),
|
||||
[("patch", {"is_active": False}), ("patch", {"password": "reset by admin!"}), ("delete", None)],
|
||||
)
|
||||
def test_admin_actions_close_user_sockets(client, make_user, second_client, method, body):
|
||||
make_user("boss", Role.ADMIN)
|
||||
anna_id = make_user("anna").id
|
||||
login(client, "boss")
|
||||
anna = second_client("anna")
|
||||
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
if method == "patch":
|
||||
client.patch(f"/api/admin/users/{anna_id}", json=body)
|
||||
else:
|
||||
client.delete(f"/api/admin/users/{anna_id}")
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_heartbeat_and_revalidation(anna, db, monkeypatch):
|
||||
from app.models import UserSession
|
||||
|
||||
monkeypatch.setattr(ws_module, "PING_INTERVAL_SECONDS", 0.05)
|
||||
monkeypatch.setattr(ws_module, "REVALIDATE_INTERVAL_SECONDS", 0)
|
||||
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
assert ws.receive_json() == {"type": "ping"}
|
||||
# Session disappears behind the socket's back (e.g. CLI password reset)
|
||||
db.query(UserSession).delete()
|
||||
db.commit()
|
||||
while True:
|
||||
assert ws.receive_json() == {"type": "ping"}
|
||||
assert exc.value.code == 4401
|
||||
@@ -18,6 +18,7 @@ exec uvicorn app.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--workers 1 \
|
||||
--ws-max-size 65536 \
|
||||
--proxy-headers \
|
||||
--forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}" \
|
||||
--log-level "${LOG_LEVEL:-info}"
|
||||
@@ -1 +1,2 @@
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
@@ -5,7 +5,12 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="theme-color" content="#0f1115" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-title" content="Clipboard" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<title>LAN-Clipboard</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
"typecheck": "vue-tsc --build",
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --write src/",
|
||||
"format:check": "prettier --check src/"
|
||||
"format:check": "prettier --check src/",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"highlight.js": "^11.12.0",
|
||||
@@ -25,14 +26,18 @@
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"@vue/eslint-config-prettier": "^10.2.0",
|
||||
"@vue/eslint-config-typescript": "^14.9.0",
|
||||
"@vue/test-utils": "^2.5.1",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-plugin-vue": "^10.11.1",
|
||||
"jiti": "^2.7.0",
|
||||
"jsdom": "^29.1.1",
|
||||
"prettier": "^3.9.10",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.72.0",
|
||||
"vite": "^8.3.5",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.0.5",
|
||||
"vue-tsc": "^3.3.13"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect x="6" y="4" width="20" height="25" rx="3" fill="#1b1f27" stroke="#6ea8fe" stroke-width="2"/><rect x="11" y="2" width="10" height="5" rx="1.5" fill="#6ea8fe"/><path d="M11 14h10M11 19h10M11 24h6" stroke="#9aa4b2" stroke-width="2" stroke-linecap="round"/></svg>
|
||||
|
Before Width: | Height: | Size: 326 B |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="100%" height="100%">
|
||||
<!-- Full-bleed background; motif stays inside the central safe zone (80 %) -->
|
||||
<rect width="512" height="512" fill="#0f1115"/>
|
||||
<g transform="translate(256 256) scale(0.78) translate(-256 -248)">
|
||||
<rect x="128" y="104" width="256" height="320" rx="36" fill="#1b1f27" stroke="#6ea8fe" stroke-width="20"/>
|
||||
<rect x="196" y="72" width="120" height="64" rx="18" fill="#6ea8fe"/>
|
||||
<path d="M184 216h144M184 280h144M184 344h88" stroke="#9aa4b2" stroke-width="22" stroke-linecap="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 601 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="100%" height="100%">
|
||||
<rect width="512" height="512" rx="112" fill="#0f1115"/>
|
||||
<rect x="128" y="104" width="256" height="320" rx="36" fill="#1b1f27" stroke="#6ea8fe" stroke-width="20"/>
|
||||
<rect x="196" y="72" width="120" height="64" rx="18" fill="#6ea8fe"/>
|
||||
<path d="M184 216h144M184 280h144M184 344h88" stroke="#9aa4b2" stroke-width="22" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 445 B |
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Renders the PWA icons from the SVG sources with headless Chromium (Playwright image).
|
||||
# Usage (from frontend/): sh scripts/render-icons.sh
|
||||
set -eu
|
||||
|
||||
IMAGE=mcr.microsoft.com/playwright:v1.63.0-noble
|
||||
CHROME=/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-linux64/chrome-headless-shell
|
||||
|
||||
render() { # <svg> <size> <png>
|
||||
docker run --rm -v "$PWD/public/icons:/icons" "$IMAGE" "$CHROME" \
|
||||
--no-sandbox --hide-scrollbars --default-background-color=00000000 \
|
||||
--window-size="$2,$2" --screenshot="/icons/$3" "file:///icons/$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
render icon.svg 192 icon-192.png
|
||||
render icon.svg 512 icon-512.png
|
||||
render icon-maskable.svg 512 icon-maskable-512.png
|
||||
render icon-maskable.svg 180 apple-touch-icon.png
|
||||
echo "Icons rendered into public/icons/"
|
||||
@@ -1,13 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue'
|
||||
import { RouterView } from 'vue-router'
|
||||
|
||||
import AppHeader from '@/components/AppHeader.vue'
|
||||
import ToastHost from '@/components/ToastHost.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { useUploadsStore } from '@/stores/uploads'
|
||||
import { useSyncStore } from '@/stores/sync'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const clips = useClipsStore()
|
||||
const projects = useProjectsStore()
|
||||
const uploads = useUploadsStore()
|
||||
const sync = useSyncStore()
|
||||
|
||||
// Live sync runs while someone is logged in; local data is dropped on logout or user switch
|
||||
watch(
|
||||
() => auth.user?.id ?? null,
|
||||
(userId, previousId) => {
|
||||
if (previousId !== undefined && userId !== previousId) {
|
||||
sync.stop()
|
||||
clips.reset()
|
||||
projects.reset()
|
||||
uploads.reset()
|
||||
}
|
||||
if (userId !== null) {
|
||||
sync.start()
|
||||
void projects.load().catch(() => {})
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppHeader v-if="auth.user" />
|
||||
<RouterView />
|
||||
<ToastHost />
|
||||
</template>
|
||||
@@ -18,18 +18,23 @@ export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
|
||||
onUnauthorized = handler
|
||||
}
|
||||
|
||||
function readCookie(name: string): string | null {
|
||||
/** Report an expired or revoked session detected outside of fetch (e.g. WebSocket close). */
|
||||
export function notifyUnauthorized(): void {
|
||||
onUnauthorized?.()
|
||||
}
|
||||
|
||||
export function readCookie(name: string): string | null {
|
||||
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
|
||||
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
|
||||
}
|
||||
|
||||
function errorMessage(response: Response, data: unknown): string {
|
||||
export function errorMessage(status: number, statusText: string, data: unknown): string {
|
||||
if (data && typeof data === 'object' && 'detail' in data) {
|
||||
const detail = (data as { detail: unknown }).detail
|
||||
if (typeof detail === 'string') return detail
|
||||
if (Array.isArray(detail)) return 'Ungültige Eingabe.'
|
||||
}
|
||||
return `${response.status} ${response.statusText}`
|
||||
return `${status} ${statusText}`
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
@@ -50,7 +55,11 @@ export async function apiRequest<T>(method: string, path: string, body?: unknown
|
||||
if (!response.ok) {
|
||||
if (response.status === 401 && path !== '/auth/login') onUnauthorized?.()
|
||||
const data: unknown = await response.json().catch(() => null)
|
||||
throw new ApiError(response.status, errorMessage(response, data), data)
|
||||
throw new ApiError(
|
||||
response.status,
|
||||
errorMessage(response.status, response.statusText, data),
|
||||
data,
|
||||
)
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
return (await response.json()) as T
|
||||
|
||||
@@ -18,15 +18,39 @@ export interface SessionInfo {
|
||||
current: boolean
|
||||
}
|
||||
|
||||
export type ClipKind = 'text' | 'code'
|
||||
export type ClipKind = 'text' | 'code' | 'file'
|
||||
|
||||
export interface FileInfo {
|
||||
name: string
|
||||
content_type: string
|
||||
size: number
|
||||
/** Verified JPEG/PNG/GIF/WebP; only these may be shown inline */
|
||||
previewable: boolean
|
||||
expires_at: string | null
|
||||
}
|
||||
|
||||
export interface FileUsage {
|
||||
used_bytes: number
|
||||
quota_bytes: number
|
||||
max_file_bytes: number
|
||||
}
|
||||
|
||||
/** Allowed lifetimes of an upload in days; 0 keeps the file until it is deleted. */
|
||||
export type ExpiryDays = 0 | 1 | 7 | 30
|
||||
|
||||
export interface Clip {
|
||||
id: number
|
||||
/** Creator; differs from the current user for clips in shared projects */
|
||||
user_id: number
|
||||
owner_name: string
|
||||
kind: ClipKind
|
||||
title: string | null
|
||||
content: string
|
||||
language: string | null
|
||||
pinned: boolean
|
||||
project_id: number | null
|
||||
/** Set for clips of kind "file" */
|
||||
file: FileInfo | null
|
||||
version: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
@@ -37,4 +61,65 @@ export interface ClipList {
|
||||
total: number
|
||||
}
|
||||
|
||||
export type ClipInput = Partial<Pick<Clip, 'kind' | 'title' | 'content' | 'language' | 'pinned'>>
|
||||
export type ClipInput = Partial<
|
||||
Pick<Clip, 'kind' | 'title' | 'content' | 'language' | 'pinned' | 'project_id'>
|
||||
>
|
||||
|
||||
export type ProjectColor =
|
||||
'blue' | 'teal' | 'green' | 'amber' | 'orange' | 'red' | 'pink' | 'violet'
|
||||
|
||||
export type ProjectRole = 'owner' | 'edit' | 'read'
|
||||
|
||||
export interface Project {
|
||||
id: number
|
||||
name: string
|
||||
color: ProjectColor
|
||||
/** The current user's role in this project */
|
||||
role: ProjectRole
|
||||
owner_name: string
|
||||
/** Clips of all members */
|
||||
clip_count: number
|
||||
/** Users it is shared with, without the owner */
|
||||
member_count: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export type ProjectInput = Partial<Pick<Project, 'name' | 'color'>>
|
||||
|
||||
export interface Member {
|
||||
user_id: number
|
||||
username: string
|
||||
role: ProjectRole
|
||||
}
|
||||
|
||||
export interface UserName {
|
||||
id: number
|
||||
username: string
|
||||
}
|
||||
|
||||
export interface ApiToken {
|
||||
id: number
|
||||
name: string
|
||||
/** First characters, to tell tokens apart */
|
||||
prefix: string
|
||||
created_at: string
|
||||
last_used_at: string | null
|
||||
last_ip: string | null
|
||||
}
|
||||
|
||||
export interface CreatedApiToken extends ApiToken {
|
||||
/** The secret itself; only returned once */
|
||||
token: string
|
||||
}
|
||||
|
||||
export interface BackupStatus {
|
||||
enabled: boolean
|
||||
/** Local hour of the daily backup */
|
||||
hour: number
|
||||
latest: { name: string; size: number; created_at: string } | null
|
||||
count: number
|
||||
/** No backup within the last day */
|
||||
stale: boolean
|
||||
last_error: string | null
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { ApiError } from './client'
|
||||
import { uploadFile } from './upload'
|
||||
|
||||
class FakeXhr {
|
||||
static last: FakeXhr
|
||||
method = ''
|
||||
url = ''
|
||||
headers: Record<string, string> = {}
|
||||
body: unknown = null
|
||||
status = 0
|
||||
statusText = ''
|
||||
response: unknown = null
|
||||
responseType = ''
|
||||
upload: { onprogress: ((e: ProgressEvent) => void) | null } = { onprogress: null }
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
onabort: (() => void) | null = null
|
||||
|
||||
constructor() {
|
||||
FakeXhr.last = this
|
||||
}
|
||||
open(method: string, url: string) {
|
||||
this.method = method
|
||||
this.url = url
|
||||
}
|
||||
setRequestHeader(name: string, value: string) {
|
||||
this.headers[name] = value
|
||||
}
|
||||
send(body: unknown) {
|
||||
this.body = body
|
||||
}
|
||||
abort() {
|
||||
this.onabort?.()
|
||||
}
|
||||
respond(status: number, response: unknown) {
|
||||
this.status = status
|
||||
this.response = response
|
||||
this.onload?.()
|
||||
}
|
||||
}
|
||||
|
||||
describe('uploadFile', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('sends the raw file with metadata in the query string', async () => {
|
||||
vi.stubGlobal('XMLHttpRequest', FakeXhr)
|
||||
document.cookie = 'lc_csrf=token123'
|
||||
const file = new File(['abc'], 'Bericht März.pdf', { type: 'application/pdf' })
|
||||
const progress = vi.fn()
|
||||
|
||||
const handle = uploadFile(file, { expiresDays: 30, projectId: 4, onProgress: progress })
|
||||
const xhr = FakeXhr.last
|
||||
xhr.upload.onprogress?.({ lengthComputable: true, loaded: 2, total: 3 } as ProgressEvent)
|
||||
xhr.respond(201, { id: 9 })
|
||||
|
||||
expect(await handle.promise).toEqual({ id: 9 })
|
||||
const url = new URL(xhr.url, 'https://x')
|
||||
expect(xhr.method).toBe('POST')
|
||||
expect(url.pathname).toBe('/api/files')
|
||||
expect(Object.fromEntries(url.searchParams)).toEqual({
|
||||
name: 'Bericht März.pdf',
|
||||
expires_days: '30',
|
||||
project_id: '4',
|
||||
})
|
||||
expect(xhr.headers['Content-Type']).toBe('application/pdf')
|
||||
expect(xhr.headers['X-CSRF-Token']).toBe('token123')
|
||||
expect(xhr.body).toBe(file)
|
||||
expect(progress).toHaveBeenCalledWith(2, 3)
|
||||
})
|
||||
|
||||
it('reports the backend message, or a proxy 413 without JSON', async () => {
|
||||
vi.stubGlobal('XMLHttpRequest', FakeXhr)
|
||||
const file = new File(['abc'], 'a.txt')
|
||||
|
||||
const quota = uploadFile(file, { expiresDays: 7, projectId: null })
|
||||
FakeXhr.last.respond(413, { detail: 'Nicht genug Speicherplatz' })
|
||||
await expect(quota.promise).rejects.toThrow('Nicht genug Speicherplatz')
|
||||
|
||||
const proxy = uploadFile(file, { expiresDays: 7, projectId: null })
|
||||
FakeXhr.last.respond(413, null)
|
||||
const error = await proxy.promise.catch((e: unknown) => e)
|
||||
expect(error).toBeInstanceOf(ApiError)
|
||||
expect((error as ApiError).message).toBe('Die Datei ist zu groß für den Server.')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { ApiError, errorMessage, notifyUnauthorized, readCookie } from '@/api/client'
|
||||
import type { Clip, ExpiryDays } from '@/api/types'
|
||||
|
||||
export interface UploadOptions {
|
||||
expiresDays: ExpiryDays
|
||||
projectId: number | null
|
||||
onProgress?: (loaded: number, total: number) => void
|
||||
}
|
||||
|
||||
export interface UploadHandle {
|
||||
promise: Promise<Clip>
|
||||
abort: () => void
|
||||
}
|
||||
|
||||
export class UploadAborted extends Error {
|
||||
constructor() {
|
||||
super('Hochladen abgebrochen.')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload one file as raw request body. Uses XMLHttpRequest because fetch reports no
|
||||
* upload progress; the backend streams the body straight to disk.
|
||||
*/
|
||||
export function uploadFile(file: File, options: UploadOptions): UploadHandle {
|
||||
const xhr = new XMLHttpRequest()
|
||||
const params = new URLSearchParams({
|
||||
name: file.name || 'datei',
|
||||
expires_days: String(options.expiresDays),
|
||||
})
|
||||
if (options.projectId !== null) params.set('project_id', String(options.projectId))
|
||||
|
||||
const promise = new Promise<Clip>((resolve, reject) => {
|
||||
xhr.open('POST', `/api/files?${params}`)
|
||||
xhr.setRequestHeader('Accept', 'application/json')
|
||||
xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream')
|
||||
const csrf = readCookie('lc_csrf')
|
||||
if (csrf) xhr.setRequestHeader('X-CSRF-Token', csrf)
|
||||
xhr.responseType = 'json'
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) options.onProgress?.(event.loaded, event.total)
|
||||
}
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve(xhr.response as Clip)
|
||||
return
|
||||
}
|
||||
if (xhr.status === 401) notifyUnauthorized()
|
||||
// A proxy in front (e.g. nginx) answers 413 with HTML, not JSON
|
||||
const data: unknown = xhr.response
|
||||
const message =
|
||||
xhr.status === 413 && data === null
|
||||
? 'Die Datei ist zu groß für den Server.'
|
||||
: errorMessage(xhr.status, xhr.statusText, data)
|
||||
reject(new ApiError(xhr.status, message, data))
|
||||
}
|
||||
xhr.onerror = () => reject(new Error('Netzwerkfehler beim Hochladen.'))
|
||||
xhr.onabort = () => reject(new UploadAborted())
|
||||
xhr.send(file)
|
||||
})
|
||||
|
||||
return { promise, abort: () => xhr.abort() }
|
||||
}
|
||||
@@ -32,9 +32,18 @@ body {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
/* Top inset is handled by the sticky header (status bar overlays the app on iOS) */
|
||||
body {
|
||||
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom)
|
||||
env(safe-area-inset-left);
|
||||
padding: 0 env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
|
||||
}
|
||||
|
||||
button,
|
||||
a,
|
||||
select,
|
||||
input,
|
||||
textarea {
|
||||
/* No double-tap-to-zoom delay on touch devices */
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
/* --- Shared building blocks ------------------------------------------------ */
|
||||
@@ -65,6 +74,7 @@ body {
|
||||
|
||||
.form {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
@@ -215,3 +225,15 @@ code {
|
||||
background: var(--accent);
|
||||
color: var(--bg);
|
||||
}
|
||||
|
||||
.page.wide {
|
||||
max-width: 72rem;
|
||||
}
|
||||
|
||||
/* Touch devices: every control at least 44 px high */
|
||||
@media (pointer: coarse) {
|
||||
button.small,
|
||||
.button-link.small {
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,16 @@
|
||||
import { RouterLink, useRouter } from 'vue-router'
|
||||
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useSyncStore } from '@/stores/sync'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const sync = useSyncStore()
|
||||
|
||||
const STATUS_LABELS = {
|
||||
live: 'Live-Sync aktiv',
|
||||
connecting: 'Verbinde …',
|
||||
offline: 'Offline',
|
||||
} as const
|
||||
const router = useRouter()
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
@@ -14,7 +22,16 @@ async function logout(): Promise<void> {
|
||||
|
||||
<template>
|
||||
<header class="header">
|
||||
<RouterLink to="/" class="brand">LAN-Clipboard</RouterLink>
|
||||
<RouterLink to="/" class="brand">
|
||||
LAN-Clipboard
|
||||
<span
|
||||
class="sync-dot"
|
||||
:class="sync.status"
|
||||
role="status"
|
||||
:title="STATUS_LABELS[sync.status]"
|
||||
:aria-label="STATUS_LABELS[sync.status]"
|
||||
></span>
|
||||
</RouterLink>
|
||||
<nav class="nav">
|
||||
<RouterLink to="/account">Konto</RouterLink>
|
||||
<RouterLink v-if="auth.isAdmin" to="/admin/users">Benutzer</RouterLink>
|
||||
@@ -33,17 +50,43 @@ async function logout(): Promise<void> {
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
padding: calc(0.5rem + env(safe-area-inset-top)) 1rem 0.5rem;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text);
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sync-dot {
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.sync-dot.live {
|
||||
background: var(--ok);
|
||||
}
|
||||
|
||||
.sync-dot.connecting {
|
||||
background: var(--muted);
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { BackupStatus as Status } from '@/api/types'
|
||||
|
||||
import BackupStatus from './BackupStatus.vue'
|
||||
|
||||
const ok: Status = {
|
||||
enabled: true,
|
||||
hour: 3,
|
||||
latest: { name: 'app-2026-10-25.db.gz', size: 1536, created_at: '2026-10-25T02:00:00Z' },
|
||||
count: 5,
|
||||
stale: false,
|
||||
last_error: null,
|
||||
}
|
||||
|
||||
async function render(status: Status) {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response(JSON.stringify(status), { status: 200 })),
|
||||
)
|
||||
const wrapper = mount(BackupStatus)
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
describe('BackupStatus', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('shows the latest backup', async () => {
|
||||
const wrapper = await render(ok)
|
||||
expect(wrapper.text()).toContain('1,5 KB')
|
||||
expect(wrapper.text()).toContain('täglich 03:00 Uhr')
|
||||
expect(wrapper.text()).toContain('5 Sicherungen')
|
||||
expect(wrapper.classes()).not.toContain('problem')
|
||||
})
|
||||
|
||||
it('warns when no backup ran for a day', async () => {
|
||||
const wrapper = await render({ ...ok, stale: true })
|
||||
expect(wrapper.classes()).toContain('problem')
|
||||
expect(wrapper.find('[role=alert]').text()).toContain('Seit über einem Tag')
|
||||
})
|
||||
|
||||
it('shows the last error', async () => {
|
||||
const wrapper = await render({ ...ok, last_error: '25.10.2026 03:00: disk full' })
|
||||
expect(wrapper.find('[role=alert]').text()).toContain('disk full')
|
||||
})
|
||||
|
||||
it('a disabled backup is not a problem', async () => {
|
||||
const wrapper = await render({ ...ok, enabled: false, stale: true, latest: null, count: 0 })
|
||||
expect(wrapper.classes()).not.toContain('problem')
|
||||
expect(wrapper.text()).toContain('ausgeschaltet')
|
||||
expect(wrapper.find('[role=alert]').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import { api } from '@/api/client'
|
||||
import type { BackupStatus } from '@/api/types'
|
||||
import { formatBytes, formatDateTime } from '@/utils/format'
|
||||
|
||||
const status = ref<BackupStatus | null>(null)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Disabled is a choice, not a problem; a missing or failed backup while enabled is
|
||||
const problem = computed(
|
||||
() =>
|
||||
status.value !== null &&
|
||||
status.value.enabled &&
|
||||
(status.value.stale || !!status.value.last_error),
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
status.value = await api.get<BackupStatus>('/admin/backup')
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="card" :class="{ problem }">
|
||||
<h2>Datensicherung</h2>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<template v-else-if="status">
|
||||
<p v-if="!status.enabled" class="muted">
|
||||
Automatische Sicherung ist ausgeschaltet (<code>BACKUP_ENABLED=false</code>).
|
||||
</p>
|
||||
<dl>
|
||||
<dt>Letzte Sicherung</dt>
|
||||
<dd :class="{ error: status.enabled && status.stale }">
|
||||
<template v-if="status.latest">
|
||||
{{ formatDateTime(status.latest.created_at) }} · {{ formatBytes(status.latest.size) }}
|
||||
</template>
|
||||
<template v-else>noch keine</template>
|
||||
</dd>
|
||||
<dt>Zeitplan</dt>
|
||||
<dd>täglich {{ String(status.hour).padStart(2, '0') }}:00 Uhr</dd>
|
||||
<dt>Vorhanden</dt>
|
||||
<dd>{{ status.count }} {{ status.count === 1 ? 'Sicherung' : 'Sicherungen' }}</dd>
|
||||
</dl>
|
||||
<p v-if="status.last_error" class="error" role="alert">
|
||||
Letzter Versuch fehlgeschlagen: {{ status.last_error }}
|
||||
</p>
|
||||
<p v-else-if="status.enabled && status.stale" class="error" role="alert">
|
||||
Seit über einem Tag keine Sicherung. Log prüfen:
|
||||
<code>docker compose logs app | grep -i backup</code>
|
||||
</p>
|
||||
<p class="muted small">
|
||||
Ablage unter <code>data/backups/</code>. Manuell sichern:
|
||||
<code>docker exec -u app lan-clipboard lc-admin backup</code>
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.problem {
|
||||
border-color: var(--error);
|
||||
}
|
||||
|
||||
dl {
|
||||
display: grid;
|
||||
grid-template-columns: max-content 1fr;
|
||||
gap: 0.25rem 1rem;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
code {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
</style>
|
||||
@@ -4,11 +4,25 @@ import { RouterLink } from 'vue-router'
|
||||
|
||||
import type { Clip } from '@/api/types'
|
||||
import CopyButton from '@/components/CopyButton.vue'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import ProjectDot from '@/components/ProjectDot.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { formatBytes, formatDateTime, formatExpiry, formatRelative } from '@/utils/format'
|
||||
import { highlight, languageLabel } from '@/utils/highlight'
|
||||
import { now } from '@/utils/now'
|
||||
|
||||
const props = defineProps<{ clip: Clip }>()
|
||||
const emit = defineEmits<{ togglePin: []; remove: [] }>()
|
||||
const props = withDefaults(defineProps<{ clip: Clip; showProject?: boolean }>(), {
|
||||
showProject: true,
|
||||
})
|
||||
const emit = defineEmits<{ togglePin: []; remove: []; selectProject: [id: number] }>()
|
||||
|
||||
const projects = useProjectsStore()
|
||||
const auth = useAuthStore()
|
||||
const project = computed(() =>
|
||||
props.clip.project_id === null ? undefined : projects.byId.get(props.clip.project_id),
|
||||
)
|
||||
const canEdit = computed(() => projects.canEditClip(props.clip))
|
||||
const fromOther = computed(() => props.clip.user_id !== auth.user?.id)
|
||||
|
||||
const PREVIEW_LINES = 10
|
||||
const PREVIEW_CHARS = 2000
|
||||
@@ -24,6 +38,12 @@ const visibleText = computed(() =>
|
||||
? props.clip.content
|
||||
: lines.value.slice(0, PREVIEW_LINES).join('\n').slice(0, PREVIEW_CHARS),
|
||||
)
|
||||
const fileUrl = computed(() => `/api/files/${props.clip.id}`)
|
||||
const expired = computed(() => {
|
||||
const expires = props.clip.file?.expires_at
|
||||
return expires != null && new Date(expires).getTime() <= now.value
|
||||
})
|
||||
|
||||
// Highlight only what is visible; large clips stay cheap until expanded
|
||||
const html = computed(() =>
|
||||
props.clip.kind === 'code' ? highlight(visibleText.value, props.clip.language) : null,
|
||||
@@ -36,11 +56,45 @@ const html = computed(() =>
|
||||
<div class="clip-meta">
|
||||
<strong v-if="clip.title" class="clip-title">{{ clip.title }}</strong>
|
||||
<span v-if="clip.pinned" class="badge accent">angeheftet</span>
|
||||
<button
|
||||
v-if="showProject && project"
|
||||
type="button"
|
||||
class="badge project"
|
||||
:title="`Nur ${project.name} zeigen`"
|
||||
@click="emit('selectProject', project.id)"
|
||||
>
|
||||
<ProjectDot :color="project.color" />
|
||||
{{ project.name }}
|
||||
</button>
|
||||
<span v-if="clip.kind === 'code'" class="badge">{{ languageLabel(clip.language) }}</span>
|
||||
</div>
|
||||
<span class="muted small">{{ formatDateTime(clip.updated_at) }}</span>
|
||||
<span class="muted small when">
|
||||
<template v-if="fromOther">von {{ clip.owner_name }} · </template>
|
||||
<time :datetime="clip.updated_at" :title="formatDateTime(clip.updated_at)">
|
||||
{{ formatRelative(clip.updated_at, now) }}
|
||||
</time>
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div v-if="clip.file" class="file">
|
||||
<a
|
||||
v-if="clip.file.previewable && !expired"
|
||||
:href="`${fileUrl}?inline=1`"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="preview"
|
||||
>
|
||||
<img :src="`${fileUrl}?inline=1`" :alt="clip.file.name" loading="lazy" />
|
||||
</a>
|
||||
<div class="file-info">
|
||||
<span class="file-name">{{ clip.file.name }}</span>
|
||||
<span class="muted small" :class="{ error: expired }">
|
||||
{{ formatBytes(clip.file.size) }} · {{ formatExpiry(clip.file.expires_at, now) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -- highlight.js output is escaped -->
|
||||
<pre v-if="html !== null" class="content code"><code class="hljs" v-html="html"></code></pre>
|
||||
<pre v-else class="content text">{{ visibleText }}</pre>
|
||||
@@ -48,19 +102,32 @@ const html = computed(() =>
|
||||
<button v-if="isLong" type="button" class="link" @click="expanded = !expanded">
|
||||
{{ expanded ? 'weniger' : `mehr (${lines.length} Zeilen)` }}
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<footer class="actions">
|
||||
<CopyButton :text="clip.content" />
|
||||
<template v-if="clip.file">
|
||||
<a v-if="!expired" :href="fileUrl" download class="button-link small download">
|
||||
Herunterladen
|
||||
</a>
|
||||
</template>
|
||||
<CopyButton v-else :text="clip.content" />
|
||||
<template v-if="canEdit">
|
||||
<RouterLink :to="`/clips/${clip.id}`" class="button-link small">Bearbeiten</RouterLink>
|
||||
<button type="button" class="small" @click="emit('togglePin')">
|
||||
{{ clip.pinned ? 'Lösen' : 'Anheften' }}
|
||||
</button>
|
||||
<button type="button" class="small danger" @click="emit('remove')">Löschen</button>
|
||||
</template>
|
||||
</footer>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.clip {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.clip.pinned {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
@@ -81,6 +148,20 @@ const html = computed(() =>
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.badge.project {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
min-height: 0;
|
||||
max-width: 14rem;
|
||||
overflow: hidden;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-size: 0.8rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.clip-title {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -110,6 +191,45 @@ const html = computed(() =>
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.file {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.preview {
|
||||
display: block;
|
||||
justify-self: start;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.preview img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 16rem;
|
||||
border-radius: calc(var(--radius) - 4px);
|
||||
background: var(--bg);
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
padding: 0.75rem;
|
||||
border-radius: calc(var(--radius) - 4px);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.file-name {
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.download {
|
||||
background: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.link {
|
||||
min-height: 32px;
|
||||
padding: 0;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import type { ProjectColor } from '@/api/types'
|
||||
import { PROJECT_COLORS } from '@/utils/projects'
|
||||
|
||||
const model = defineModel<ProjectColor>({ required: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="colors" role="radiogroup" aria-label="Farbe">
|
||||
<button
|
||||
v-for="color in PROJECT_COLORS"
|
||||
:key="color.id"
|
||||
type="button"
|
||||
role="radio"
|
||||
class="swatch"
|
||||
:class="{ active: model === color.id }"
|
||||
:aria-checked="model === color.id"
|
||||
:aria-label="color.label"
|
||||
:title="color.label"
|
||||
:style="{ '--swatch': color.value }"
|
||||
@click="model = color.id"
|
||||
></button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.colors {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* 44px touch target around a smaller visible circle */
|
||||
.swatch {
|
||||
position: relative;
|
||||
width: 44px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.swatch::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 10px;
|
||||
border-radius: 50%;
|
||||
background: var(--swatch);
|
||||
}
|
||||
|
||||
.swatch.active::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 5px;
|
||||
border: 2px solid var(--text);
|
||||
border-radius: 50%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,111 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterLink } from 'vue-router'
|
||||
|
||||
import ProjectDot from '@/components/ProjectDot.vue'
|
||||
import SharedIcon from '@/components/SharedIcon.vue'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import type { ProjectFilter } from '@/utils/projects'
|
||||
|
||||
defineProps<{ active: ProjectFilter }>()
|
||||
const emit = defineEmits<{ select: [filter: ProjectFilter] }>()
|
||||
|
||||
const projects = useProjectsStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav class="project-bar" aria-label="Projekte">
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: active === null }"
|
||||
:aria-pressed="active === null"
|
||||
@click="emit('select', null)"
|
||||
>
|
||||
Alle
|
||||
</button>
|
||||
<button
|
||||
v-for="project in projects.items"
|
||||
:key="project.id"
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: active === project.id }"
|
||||
:aria-pressed="active === project.id"
|
||||
@click="emit('select', project.id)"
|
||||
>
|
||||
<ProjectDot :color="project.color" />
|
||||
<span class="name">{{ project.name }}</span>
|
||||
<SharedIcon
|
||||
v-if="project.role !== 'owner' || project.member_count > 0"
|
||||
:title="project.role === 'owner' ? 'Geteilt' : `Geteilt von ${project.owner_name}`"
|
||||
/>
|
||||
<span class="count">{{ project.clip_count }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="projects.items.length > 0"
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: active === 'none' }"
|
||||
:aria-pressed="active === 'none'"
|
||||
@click="emit('select', 'none')"
|
||||
>
|
||||
Ohne Projekt
|
||||
</button>
|
||||
<RouterLink to="/projects" class="chip manage">
|
||||
{{ projects.items.length > 0 ? 'Verwalten' : '+ Projekt' }}
|
||||
</RouterLink>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* One scrollable row; swipe sideways on narrow screens */
|
||||
.project-bar {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
overflow-x: auto;
|
||||
margin: 0 -1rem 1rem;
|
||||
padding: 0.125rem 1rem;
|
||||
scrollbar-width: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.project-bar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-height: 44px;
|
||||
padding: 0 0.9rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-size: 0.9rem;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chip.active {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.chip.manage {
|
||||
border-style: dashed;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.name {
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.count {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { colorValue } from '@/utils/projects'
|
||||
|
||||
const props = defineProps<{ color: string }>()
|
||||
const style = computed(() => ({ background: colorValue(props.color) }))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="dot" :style="style" aria-hidden="true"></span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dot {
|
||||
display: inline-block;
|
||||
flex: none;
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
border-radius: 50%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,181 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import { api } from '@/api/client'
|
||||
import type { Member, Project, ProjectRole, UserName } from '@/api/types'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
|
||||
const props = defineProps<{ project: Project }>()
|
||||
|
||||
const projects = useProjectsStore()
|
||||
const toast = useToastStore()
|
||||
|
||||
const ROLE_LABELS: Record<ProjectRole, string> = {
|
||||
owner: 'Besitzer',
|
||||
edit: 'Bearbeiten',
|
||||
read: 'Lesen',
|
||||
}
|
||||
|
||||
const members = ref<Member[]>([])
|
||||
const users = ref<UserName[]>([])
|
||||
const newUser = ref('')
|
||||
const newRole = ref<ProjectRole>('edit')
|
||||
const error = ref<string | null>(null)
|
||||
const busy = ref(false)
|
||||
|
||||
// Only users who are not in the project yet
|
||||
const candidates = computed(() => {
|
||||
const taken = new Set(members.value.map((m) => m.user_id))
|
||||
return users.value.filter((u) => !taken.has(u.id))
|
||||
})
|
||||
|
||||
async function run(action: () => Promise<Member[] | void>, message?: string): Promise<void> {
|
||||
busy.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const result = await action()
|
||||
if (result) members.value = result
|
||||
if (message) toast.show(message)
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function add(): Promise<void> {
|
||||
const username = newUser.value
|
||||
return run(async () => {
|
||||
const result = await projects.addMember(props.project.id, username, newRole.value)
|
||||
newUser.value = ''
|
||||
return result
|
||||
}, `Mit ${username} geteilt`)
|
||||
}
|
||||
|
||||
function setRole(member: Member, role: ProjectRole): Promise<void> {
|
||||
return run(() => projects.setMemberRole(props.project.id, member.user_id, role))
|
||||
}
|
||||
|
||||
function remove(member: Member): Promise<void> {
|
||||
const text =
|
||||
`${member.username} aus „${props.project.name}“ entfernen? ` +
|
||||
`Clips von ${member.username} in diesem Projekt landen bei ihr bzw. ihm unter „Ohne Projekt“.`
|
||||
if (!confirm(text)) return Promise.resolve()
|
||||
return run(async () => {
|
||||
await projects.removeMember(props.project.id, member.user_id)
|
||||
return projects.members(props.project.id)
|
||||
}, `${member.username} entfernt`)
|
||||
}
|
||||
|
||||
onMounted(() =>
|
||||
run(async () => {
|
||||
users.value = await api.get<UserName[]>('/users')
|
||||
return projects.members(props.project.id)
|
||||
}),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="members" aria-label="Mitglieder">
|
||||
<ul class="member-list">
|
||||
<li v-for="member in members" :key="member.user_id" class="member">
|
||||
<span class="member-name">{{ member.username }}</span>
|
||||
<span v-if="member.role === 'owner'" class="muted small">{{ ROLE_LABELS.owner }}</span>
|
||||
<div v-else class="controls">
|
||||
<select
|
||||
:value="member.role"
|
||||
:aria-label="`Rolle von ${member.username}`"
|
||||
:disabled="busy"
|
||||
class="role"
|
||||
@change="setRole(member, ($event.target as HTMLSelectElement).value as ProjectRole)"
|
||||
>
|
||||
<option value="edit">{{ ROLE_LABELS.edit }}</option>
|
||||
<option value="read">{{ ROLE_LABELS.read }}</option>
|
||||
</select>
|
||||
<button type="button" class="small danger" :disabled="busy" @click="remove(member)">
|
||||
Entfernen
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<form v-if="candidates.length > 0" class="add" @submit.prevent="add">
|
||||
<select v-model="newUser" aria-label="Benutzer" required class="user">
|
||||
<option value="" disabled>Benutzer wählen …</option>
|
||||
<option v-for="u in candidates" :key="u.id" :value="u.username">{{ u.username }}</option>
|
||||
</select>
|
||||
<select v-model="newRole" aria-label="Rolle" class="role">
|
||||
<option value="edit">{{ ROLE_LABELS.edit }}</option>
|
||||
<option value="read">{{ ROLE_LABELS.read }}</option>
|
||||
</select>
|
||||
<button type="submit" class="primary small" :disabled="busy || !newUser">Teilen</button>
|
||||
</form>
|
||||
<p v-else-if="users.length === 0" class="muted small">
|
||||
Es gibt keine anderen Benutzer. Ein Admin kann unter „Benutzer“ welche anlegen.
|
||||
</p>
|
||||
<p class="muted small hint">
|
||||
Bearbeiten: Clips und Dateien anlegen, ändern und löschen. Lesen: ansehen, kopieren,
|
||||
herunterladen.
|
||||
</p>
|
||||
<p v-if="error" class="error small" role="alert">{{ error }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.members {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.member-list {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.member,
|
||||
.add {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.member-name {
|
||||
flex: 1;
|
||||
min-width: 6rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.role {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
/* Role and remove button wrap together, below the name if needed */
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.user {
|
||||
flex: 1;
|
||||
width: auto;
|
||||
min-width: 10rem;
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.error {
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
|
||||
const model = defineModel<number | null>({ required: true })
|
||||
/** Also offer this project even without write access (the clip is already in it). */
|
||||
const props = defineProps<{ keep?: number | null }>()
|
||||
const projects = useProjectsStore()
|
||||
|
||||
const options = computed(() =>
|
||||
projects.items.filter((p) => projects.canWrite(p.role) || p.id === props.keep),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<select v-model="model" aria-label="Projekt" class="project-select">
|
||||
<option :value="null">Ohne Projekt</option>
|
||||
<option v-for="project in options" :key="project.id" :value="project.id">
|
||||
{{ project.role === 'owner' ? project.name : `${project.name} (von ${project.owner_name})` }}
|
||||
</option>
|
||||
</select>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.project-select {
|
||||
width: auto;
|
||||
min-width: 9rem;
|
||||
max-width: 100%;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
</style>
|
||||
@@ -1,17 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import type { ClipKind } from '@/api/types'
|
||||
import type { ClipKind, ExpiryDays } from '@/api/types'
|
||||
import ProjectSelect from '@/components/ProjectSelect.vue'
|
||||
import UploadList from '@/components/UploadList.vue'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { DEFAULT_EXPIRY, useUploadsStore } from '@/stores/uploads'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
import { readClipboardText } from '@/utils/clipboard'
|
||||
import { EXPIRY_OPTIONS } from '@/utils/expiry'
|
||||
import { detectLanguage, LANGUAGES } from '@/utils/highlight'
|
||||
|
||||
const store = useClipsStore()
|
||||
const projects = useProjectsStore()
|
||||
const uploads = useUploadsStore()
|
||||
const toast = useToastStore()
|
||||
|
||||
const content = ref('')
|
||||
const kind = ref<ClipKind>('text')
|
||||
const language = ref<string>('plaintext')
|
||||
const languageTouched = ref(false)
|
||||
const projectId = ref<number | null>(null)
|
||||
const expiresDays = ref<ExpiryDays>(DEFAULT_EXPIRY)
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const dragging = ref(false)
|
||||
const busy = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
@@ -23,6 +36,57 @@ watch([content, kind], () => {
|
||||
language.value = detectLanguage(content.value) ?? 'plaintext'
|
||||
})
|
||||
|
||||
// New clips go to the project currently shown
|
||||
watch(
|
||||
() => [store.filter.project, projects.writable] as const,
|
||||
([filter]) => {
|
||||
// Only projects we may put clips into; read-only shared projects fall back to none
|
||||
const writable = typeof filter === 'number' && projects.writable.some((p) => p.id === filter)
|
||||
projectId.value = writable ? filter : null
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// Content shared from another app (share target) arrives as a draft
|
||||
watch(
|
||||
() => store.draft,
|
||||
(draft) => {
|
||||
if (!draft) return
|
||||
content.value = draft
|
||||
store.draft = null
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function uploadFiles(files: FileList | File[] | null | undefined): void {
|
||||
if (!files || files.length === 0) return
|
||||
void uploads.add([...files], { expiresDays: expiresDays.value, projectId: projectId.value })
|
||||
}
|
||||
|
||||
function onFilesChosen(): void {
|
||||
uploadFiles(fileInput.value?.files)
|
||||
// Allow choosing the same file again
|
||||
if (fileInput.value) fileInput.value.value = ''
|
||||
}
|
||||
|
||||
function onDrop(event: DragEvent): void {
|
||||
dragging.value = false
|
||||
uploadFiles(event.dataTransfer?.files)
|
||||
}
|
||||
|
||||
function onDragOver(event: DragEvent): void {
|
||||
if (event.dataTransfer?.types.includes('Files')) dragging.value = true
|
||||
}
|
||||
|
||||
/** Pasting a screenshot or copied file uploads it; plain text pastes as usual. */
|
||||
function onPaste(event: ClipboardEvent): void {
|
||||
const files = event.clipboardData?.files
|
||||
if (files && files.length > 0) {
|
||||
event.preventDefault()
|
||||
uploadFiles(files)
|
||||
}
|
||||
}
|
||||
|
||||
async function paste(): Promise<void> {
|
||||
error.value = null
|
||||
try {
|
||||
@@ -43,10 +107,12 @@ async function save(): Promise<void> {
|
||||
content: content.value,
|
||||
kind: kind.value,
|
||||
language: kind.value === 'code' ? language.value : null,
|
||||
project_id: projectId.value,
|
||||
})
|
||||
content.value = ''
|
||||
kind.value = 'text'
|
||||
languageTouched.value = false
|
||||
toast.show('Gespeichert')
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e)
|
||||
} finally {
|
||||
@@ -56,7 +122,14 @@ async function save(): Promise<void> {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form class="card quick-add" @submit.prevent="save">
|
||||
<form
|
||||
class="card quick-add"
|
||||
:class="{ dragging }"
|
||||
@submit.prevent="save"
|
||||
@dragover.prevent="onDragOver"
|
||||
@dragleave.self="dragging = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<textarea
|
||||
v-model="content"
|
||||
:class="{ mono: kind === 'code' }"
|
||||
@@ -66,6 +139,7 @@ async function save(): Promise<void> {
|
||||
spellcheck="false"
|
||||
@keydown.enter.ctrl.prevent="save"
|
||||
@keydown.enter.meta.prevent="save"
|
||||
@paste="onPaste"
|
||||
></textarea>
|
||||
<div class="row">
|
||||
<div class="segmented" role="radiogroup" aria-label="Art">
|
||||
@@ -97,10 +171,24 @@ async function save(): Promise<void> {
|
||||
>
|
||||
<option v-for="l in LANGUAGES" :key="l.id" :value="l.id">{{ l.label }}</option>
|
||||
</select>
|
||||
<ProjectSelect v-if="projects.writable.length > 0" v-model="projectId" />
|
||||
<div class="spacer"></div>
|
||||
<div class="buttons">
|
||||
<button type="button" @click="paste">Einfügen</button>
|
||||
<button type="submit" class="primary" :disabled="!canSave">Speichern</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row files">
|
||||
<button type="button" @click="fileInput?.click()">Datei …</button>
|
||||
<select v-model="expiresDays" aria-label="Datei aufbewahren" class="expiry">
|
||||
<option v-for="o in EXPIRY_OPTIONS" :key="o.days" :value="o.days">
|
||||
{{ o.days === 0 ? 'Unbegrenzt behalten' : `${o.label} behalten` }}
|
||||
</option>
|
||||
</select>
|
||||
<span class="muted small hint">oder hierher ziehen</span>
|
||||
<input ref="fileInput" type="file" multiple hidden @change="onFilesChosen" />
|
||||
</div>
|
||||
<UploadList />
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
</form>
|
||||
</template>
|
||||
@@ -108,6 +196,8 @@ async function save(): Promise<void> {
|
||||
<style scoped>
|
||||
.quick-add {
|
||||
display: grid;
|
||||
/* Never wider than the card, even with a long project name in the select */
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
@@ -122,6 +212,33 @@ async function save(): Promise<void> {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Wrap together, never one by one */
|
||||
.buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.quick-add.dragging {
|
||||
border-color: var(--accent);
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.expiry {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* Drag and drop needs a mouse; no hint on touch screens */
|
||||
@media (pointer: coarse) {
|
||||
.hint {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.language {
|
||||
width: auto;
|
||||
min-width: 9rem;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<template>
|
||||
<!-- Two people: marks projects shared with others -->
|
||||
<svg class="shared-icon" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
|
||||
<circle cx="5.5" cy="5" r="2.5" fill="currentColor" />
|
||||
<circle cx="11" cy="5.5" r="2" fill="currentColor" opacity="0.7" />
|
||||
<path d="M1 13.5c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4z" fill="currentColor" />
|
||||
<path
|
||||
d="M10.5 13.5c0-1.6-.5-2.8-1.4-3.6.5-.2 1.1-.4 1.9-.4 2.2 0 4 1.3 4 4z"
|
||||
fill="currentColor"
|
||||
opacity="0.7"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.shared-icon {
|
||||
flex: none;
|
||||
color: var(--muted);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,70 @@
|
||||
<script setup lang="ts">
|
||||
import { applyUpdate, updateAvailable } from '@/pwa'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
|
||||
const toast = useToastStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="toast-host" aria-live="polite">
|
||||
<div v-if="updateAvailable" class="toast update" role="status">
|
||||
<span>Neue Version verfügbar</span>
|
||||
<button type="button" class="primary small" @click="applyUpdate">Neu laden</button>
|
||||
</div>
|
||||
<button
|
||||
v-for="t in toast.toasts"
|
||||
:key="t.id"
|
||||
type="button"
|
||||
class="toast"
|
||||
:class="t.kind"
|
||||
:role="t.kind === 'error' ? 'alert' : 'status'"
|
||||
@click="toast.dismiss(t.id)"
|
||||
>
|
||||
{{ t.text }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.toast-host {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: calc(1rem + env(safe-area-inset-bottom));
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: min(28rem, calc(100vw - 2rem));
|
||||
transform: translateX(-50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
min-height: 44px;
|
||||
padding: 0.5rem 1rem;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 4px 16px rgb(0 0 0 / 40%);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
text-align: center;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.toast.error {
|
||||
border-color: var(--error);
|
||||
color: var(--error);
|
||||
}
|
||||
|
||||
.toast.update {
|
||||
width: 100%;
|
||||
border-color: var(--accent);
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,89 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { ApiToken } from '@/api/types'
|
||||
|
||||
import TokenSection from './TokenSection.vue'
|
||||
|
||||
const existing: ApiToken = {
|
||||
id: 1,
|
||||
name: 'Desktop',
|
||||
prefix: 'lc_abcdefg',
|
||||
created_at: '2026-10-25T10:00:00Z',
|
||||
last_used_at: null,
|
||||
last_ip: null,
|
||||
}
|
||||
|
||||
function json(status: number, body: unknown): Response {
|
||||
return new Response(status === 204 ? null : JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('TokenSection', () => {
|
||||
let tokens: ApiToken[]
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
tokens = [existing]
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (url: string, init?: RequestInit) => {
|
||||
if (init?.method === 'POST') {
|
||||
const created = { ...existing, id: 2, name: 'Laptop', prefix: 'lc_secretx' }
|
||||
tokens = [...tokens, created]
|
||||
return json(201, { ...created, token: 'lc_secretxyz' })
|
||||
}
|
||||
if (init?.method === 'DELETE') {
|
||||
tokens = tokens.filter((t) => !url.endsWith(`/${t.id}`))
|
||||
return json(204, null)
|
||||
}
|
||||
return json(200, tokens)
|
||||
}),
|
||||
)
|
||||
vi.stubGlobal('confirm', () => true)
|
||||
})
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('lists tokens without their secret', async () => {
|
||||
const wrapper = mount(TokenSection)
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.text()).toContain('Desktop')
|
||||
expect(wrapper.text()).toContain('lc_abcdefg…')
|
||||
expect(wrapper.text()).toContain('noch nicht benutzt')
|
||||
})
|
||||
|
||||
it('shows a new token once and hides it when done', async () => {
|
||||
const wrapper = mount(TokenSection)
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('input').setValue('Laptop')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.token').text()).toBe('lc_secretxyz')
|
||||
expect(wrapper.findAll('.token-row')).toHaveLength(2)
|
||||
|
||||
const done = wrapper.findAll('button').find((b) => b.text() === 'Fertig')!
|
||||
await done.trigger('click')
|
||||
expect(wrapper.find('.token').exists()).toBe(false)
|
||||
expect(wrapper.text()).not.toContain('lc_secretxyz')
|
||||
})
|
||||
|
||||
it('revoking the new token also hides its secret', async () => {
|
||||
const wrapper = mount(TokenSection)
|
||||
await flushPromises()
|
||||
await wrapper.find('input').setValue('Laptop')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.findAll('.token-row')[1]!.find('button.danger').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.token').exists()).toBe(false)
|
||||
expect(wrapper.findAll('.token-row')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||