Compare commits
4
Commits
a444f28681
...
4c5d910f54
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c5d910f54 | ||
|
|
56b58243af | ||
|
|
e20af699dc | ||
|
|
0d89399090 |
No files matched your search
@@ -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.
|
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 4 – Live-Sync zwischen den Geräten eines Benutzers, Clips (Text und Code mit Syntax-Highlighting), Benutzer, Login, Admin-Verwaltung.
|
||||||
|
|
||||||
## Aufbau
|
## Aufbau
|
||||||
|
|
||||||
@@ -88,9 +88,18 @@ 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).
|
- „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.
|
- 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.
|
||||||
|
|
||||||
|
## 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` und `clip.deleted` an alle Geräte desselben Benutzers.
|
||||||
|
- 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.
|
||||||
|
|
||||||
## Reverse Proxy (Nginx Proxy Manager)
|
## 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.
|
- SSL im NPM terminieren. Die App spricht intern nur HTTP.
|
||||||
- `FORWARDED_ALLOW_IPS` auf die IP setzen, mit der NPM die App erreicht. Sie steht nach einem Aufruf über NPM im Log:
|
- `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.
|
`docker compose logs app | grep "GET /api/health"` → erste Spalte ist die Absender-IP.
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
from fastapi import APIRouter, HTTPException, status
|
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||||
|
|
||||||
from app.api.deps import AdminUser, DbSession
|
from app.api.deps import AdminUser, DbSession
|
||||||
from app.models import User
|
from app.models import User
|
||||||
from app.schemas.auth import UserOut
|
from app.schemas.auth import UserOut
|
||||||
from app.schemas.users import UserCreate, UserUpdate
|
from app.schemas.users import UserCreate, UserUpdate
|
||||||
from app.services import users as user_service
|
from app.services import users as user_service
|
||||||
|
from app.ws.hub import hub
|
||||||
|
|
||||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||||
|
|
||||||
@@ -32,13 +33,19 @@ def get_user(user_id: int, _admin: AdminUser, db: DbSession):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/users/{user_id}", response_model=UserOut)
|
@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)
|
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
|
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)
|
@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))
|
user_service.delete_user(db, admin, _get_user_or_404(db, user_id))
|
||||||
|
background.add_task(hub.close_user, user_id)
|
||||||
+23
-5
@@ -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 (
|
from app.api.deps import (
|
||||||
SESSION_COOKIE,
|
SESSION_COOKIE,
|
||||||
@@ -20,6 +20,7 @@ from app.security import verify_password
|
|||||||
from app.services import sessions as session_service
|
from app.services import sessions as session_service
|
||||||
from app.services.auth import LoginBlocked, authenticate
|
from app.services.auth import LoginBlocked, authenticate
|
||||||
from app.services.users import set_password
|
from app.services.users import set_password
|
||||||
|
from app.ws.hub import hub
|
||||||
|
|
||||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
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)
|
@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)
|
session_service.revoke_session(db, session.user_id, session.id)
|
||||||
clear_session_cookies(response)
|
clear_session_cookies(response)
|
||||||
|
background.add_task(hub.close_session, session.id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/me", response_model=UserOut)
|
@router.get("/me", response_model=UserOut)
|
||||||
@@ -60,10 +64,16 @@ def me(user: CurrentUser):
|
|||||||
|
|
||||||
|
|
||||||
@router.post("/password", status_code=status.HTTP_204_NO_CONTENT)
|
@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):
|
if not verify_password(session.user.password_hash, body.current_password):
|
||||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Das aktuelle Passwort ist falsch.")
|
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)
|
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])
|
@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)
|
@router.delete("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
def revoke_session(
|
def revoke_session(
|
||||||
session_id: int, session: CurrentSession, response: Response, db: DbSession
|
session_id: int,
|
||||||
|
session: CurrentSession,
|
||||||
|
response: Response,
|
||||||
|
db: DbSession,
|
||||||
|
background: BackgroundTasks,
|
||||||
) -> None:
|
) -> None:
|
||||||
if not session_service.revoke_session(db, session.user_id, session_id):
|
if not session_service.revoke_session(db, session.user_id, session_id):
|
||||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Sitzung nicht gefunden.")
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Sitzung nicht gefunden.")
|
||||||
if session_id == session.id:
|
if session_id == session.id:
|
||||||
clear_session_cookies(response)
|
clear_session_cookies(response)
|
||||||
|
background.add_task(hub.close_session, session_id)
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/sessions", response_model=RevokedResponse)
|
@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)
|
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)
|
return RevokedResponse(revoked=revoked)
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
from typing import Annotated
|
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 fastapi.responses import JSONResponse
|
||||||
|
|
||||||
from app.api.deps import CurrentUser, DbSession
|
from app.api.deps import CurrentUser, DbSession
|
||||||
from app.models import Clip
|
from app.models import Clip
|
||||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||||
from app.services import clips as clip_service
|
from app.services import clips as clip_service
|
||||||
|
from app.ws.hub import hub
|
||||||
|
|
||||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||||
|
|
||||||
@@ -14,6 +15,15 @@ router = APIRouter(prefix="/clips", tags=["clips"])
|
|||||||
_NULLABLE_FIELDS = {"title", "language"}
|
_NULLABLE_FIELDS = {"title", "language"}
|
||||||
|
|
||||||
|
|
||||||
|
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||||
|
"""Tell all devices of the user about a change, after the response is sent."""
|
||||||
|
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||||
|
|
||||||
|
|
||||||
|
def _clip_data(clip: Clip) -> dict:
|
||||||
|
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||||
|
|
||||||
|
|
||||||
def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
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
|
# Foreign and missing clips look the same, so ids of other users are not revealed
|
||||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||||
@@ -34,8 +44,10 @@ def list_clips(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession):
|
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks):
|
||||||
return clip_service.create_clip(db, user.id, **body.model_dump())
|
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||||
|
_notify(background, user.id, "clip.created", _clip_data(clip))
|
||||||
|
return clip
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{clip_id}", response_model=ClipOut)
|
@router.get("/{clip_id}", response_model=ClipOut)
|
||||||
@@ -44,7 +56,13 @@ def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||||
def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession):
|
def update_clip(
|
||||||
|
clip_id: int,
|
||||||
|
body: ClipUpdate,
|
||||||
|
user: CurrentUser,
|
||||||
|
db: DbSession,
|
||||||
|
background: BackgroundTasks,
|
||||||
|
):
|
||||||
clip = _get_own_clip(db, user, clip_id)
|
clip = _get_own_clip(db, user, clip_id)
|
||||||
changes = {
|
changes = {
|
||||||
field: getattr(body, field)
|
field: getattr(body, field)
|
||||||
@@ -52,18 +70,23 @@ def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession
|
|||||||
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
||||||
}
|
}
|
||||||
try:
|
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:
|
except clip_service.ClipConflict as exc:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
status_code=status.HTTP_409_CONFLICT,
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
content={
|
content={
|
||||||
"detail": "Der Clip wurde inzwischen auf einem anderen Gerät geändert.",
|
"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),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
_notify(background, user.id, "clip.updated", _clip_data(clip))
|
||||||
|
return clip
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None:
|
def delete_clip(
|
||||||
|
clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||||
|
) -> None:
|
||||||
if not clip_service.delete_clip(db, user.id, clip_id):
|
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||||
|
_notify(background, user.id, "clip.deleted", {"id": clip_id})
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
|
||||||
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||||
|
from fastapi.concurrency import run_in_threadpool
|
||||||
|
|
||||||
|
from app.api.deps import SESSION_COOKIE
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.db import _session_factory
|
||||||
|
from app.services.sessions import is_session_valid, resolve_session
|
||||||
|
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(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 _still_valid(session_id: int) -> bool:
|
||||||
|
with _session_factory()() as db:
|
||||||
|
return is_session_valid(db, 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.session_id):
|
||||||
|
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:
|
||||||
|
# Origin check protects the cookie-authenticated socket against cross-site hijacking
|
||||||
|
origin = (websocket.headers.get("origin") or "").rstrip("/")
|
||||||
|
if origin not in get_settings().allowed_origin_list:
|
||||||
|
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
|
||||||
|
ids = await run_in_threadpool(_resolve, websocket.cookies.get(SESSION_COOKIE))
|
||||||
|
if ids is None:
|
||||||
|
await websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||||
|
return
|
||||||
|
session_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, session_id=session_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)
|
||||||
+3
-2
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
|||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse
|
||||||
|
|
||||||
from app import __version__
|
from app import __version__
|
||||||
from app.api import admin, auth, clips, health
|
from app.api import admin, auth, clips, health, ws
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.db import _session_factory
|
from app.db import _session_factory
|
||||||
from app.middleware import (
|
from app.middleware import (
|
||||||
@@ -106,11 +106,12 @@ def create_app() -> FastAPI:
|
|||||||
# Last added runs first: security headers wrap every response, including rejections
|
# Last added runs first: security headers wrap every response, including rejections
|
||||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||||
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
||||||
app.add_middleware(SecurityHeadersMiddleware)
|
app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||||
app.include_router(health.router, prefix="/api")
|
app.include_router(health.router, prefix="/api")
|
||||||
app.include_router(auth.router, prefix="/api")
|
app.include_router(auth.router, prefix="/api")
|
||||||
app.include_router(admin.router, prefix="/api")
|
app.include_router(admin.router, prefix="/api")
|
||||||
app.include_router(clips.router, prefix="/api")
|
app.include_router(clips.router, prefix="/api")
|
||||||
|
app.include_router(ws.router, prefix="/api")
|
||||||
|
|
||||||
@app.exception_handler(UserError)
|
@app.exception_handler(UserError)
|
||||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||||
|
|||||||
@@ -26,21 +26,26 @@ class OriginCheckMiddleware:
|
|||||||
await self.app(scope, receive, send)
|
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'",
|
"default-src 'self'",
|
||||||
"script-src 'self'",
|
"script-src 'self'",
|
||||||
"style-src 'self'",
|
"style-src 'self'",
|
||||||
"img-src 'self' data:",
|
"img-src 'self' data:",
|
||||||
"connect-src 'self'",
|
" ".join(["connect-src 'self'", *ws_origins]),
|
||||||
"frame-ancestors 'none'",
|
"frame-ancestors 'none'",
|
||||||
"base-uri 'self'",
|
"base-uri 'self'",
|
||||||
"form-action 'self'",
|
"form-action 'self'",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
SECURITY_HEADERS = [
|
SECURITY_HEADERS = [
|
||||||
(b"content-security-policy", CONTENT_SECURITY_POLICY.encode()),
|
|
||||||
(b"x-content-type-options", b"nosniff"),
|
(b"x-content-type-options", b"nosniff"),
|
||||||
(b"referrer-policy", b"same-origin"),
|
(b"referrer-policy", b"same-origin"),
|
||||||
(b"x-frame-options", b"DENY"),
|
(b"x-frame-options", b"DENY"),
|
||||||
@@ -54,15 +59,16 @@ HSTS_HEADER = (b"strict-transport-security", b"max-age=31536000")
|
|||||||
class SecurityHeadersMiddleware:
|
class SecurityHeadersMiddleware:
|
||||||
"""Add security headers to every HTTP response; HSTS only for HTTPS requests."""
|
"""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.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:
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
if scope["type"] != "http":
|
if scope["type"] != "http":
|
||||||
await self.app(scope, receive, send)
|
await self.app(scope, receive, send)
|
||||||
return
|
return
|
||||||
|
|
||||||
extra = list(SECURITY_HEADERS)
|
extra = [self.csp_header, *SECURITY_HEADERS]
|
||||||
if scope.get("scheme") == "https":
|
if scope.get("scheme") == "https":
|
||||||
extra.append(HSTS_HEADER)
|
extra.append(HSTS_HEADER)
|
||||||
|
|
||||||
|
|||||||
@@ -32,11 +32,8 @@ def create_session(
|
|||||||
return session, token
|
return session, token
|
||||||
|
|
||||||
|
|
||||||
def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
def _validate(db: Session, session: UserSession | None, touch: bool) -> UserSession | None:
|
||||||
"""Return the valid session for a raw token; expired sessions are deleted."""
|
"""Return the session if still valid; expired ones are deleted."""
|
||||||
if not token:
|
|
||||||
return None
|
|
||||||
session = db.scalar(select(UserSession).where(UserSession.token_hash == hash_token(token)))
|
|
||||||
if session is None:
|
if session is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -47,12 +44,25 @@ def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
|||||||
db.commit()
|
db.commit()
|
||||||
return None
|
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
|
session.last_seen_at = now
|
||||||
db.commit()
|
db.commit()
|
||||||
return session
|
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]:
|
def list_sessions(db: Session, user_id: int) -> list[UserSession]:
|
||||||
return list(
|
return list(
|
||||||
db.scalars(
|
db.scalars(
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,79 @@
|
|||||||
|
"""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
|
||||||
|
session_id: int
|
||||||
|
|
||||||
|
|
||||||
|
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_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()
|
||||||
@@ -82,3 +82,8 @@ def test_oversized_chunked_request_is_rejected(client):
|
|||||||
def test_normal_requests_pass_size_limit(client):
|
def test_normal_requests_pass_size_limit(client):
|
||||||
response = client.post("/api/auth/login", json={"username": "x", "password": "y"})
|
response = client.post("/api/auth/login", json={"username": "x", "password": "y"})
|
||||||
assert response.status_code == 401
|
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,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 \
|
--host 0.0.0.0 \
|
||||||
--port 8000 \
|
--port 8000 \
|
||||||
--workers 1 \
|
--workers 1 \
|
||||||
|
--ws-max-size 65536 \
|
||||||
--proxy-headers \
|
--proxy-headers \
|
||||||
--forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}" \
|
--forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}" \
|
||||||
--log-level "${LOG_LEVEL:-info}"
|
--log-level "${LOG_LEVEL:-info}"
|
||||||
@@ -1,10 +1,28 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { watch } from 'vue'
|
||||||
import { RouterView } from 'vue-router'
|
import { RouterView } from 'vue-router'
|
||||||
|
|
||||||
import AppHeader from '@/components/AppHeader.vue'
|
import AppHeader from '@/components/AppHeader.vue'
|
||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useClipsStore } from '@/stores/clips'
|
||||||
|
import { useSyncStore } from '@/stores/sync'
|
||||||
|
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
|
const clips = useClipsStore()
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
if (userId !== null) sync.start()
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
|
|||||||
onUnauthorized = handler
|
onUnauthorized = handler
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Report an expired or revoked session detected outside of fetch (e.g. WebSocket close). */
|
||||||
|
export function notifyUnauthorized(): void {
|
||||||
|
onUnauthorized?.()
|
||||||
|
}
|
||||||
|
|
||||||
function readCookie(name: string): string | null {
|
function readCookie(name: string): string | null {
|
||||||
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
|
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
|
||||||
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
|
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
|
||||||
|
|||||||
@@ -2,8 +2,16 @@
|
|||||||
import { RouterLink, useRouter } from 'vue-router'
|
import { RouterLink, useRouter } from 'vue-router'
|
||||||
|
|
||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useSyncStore } from '@/stores/sync'
|
||||||
|
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
|
const sync = useSyncStore()
|
||||||
|
|
||||||
|
const STATUS_LABELS = {
|
||||||
|
live: 'Live-Sync aktiv',
|
||||||
|
connecting: 'Verbinde …',
|
||||||
|
offline: 'Offline',
|
||||||
|
} as const
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
async function logout(): Promise<void> {
|
async function logout(): Promise<void> {
|
||||||
@@ -14,7 +22,16 @@ async function logout(): Promise<void> {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<header class="header">
|
<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">
|
<nav class="nav">
|
||||||
<RouterLink to="/account">Konto</RouterLink>
|
<RouterLink to="/account">Konto</RouterLink>
|
||||||
<RouterLink v-if="auth.isAdmin" to="/admin/users">Benutzer</RouterLink>
|
<RouterLink v-if="auth.isAdmin" to="/admin/users">Benutzer</RouterLink>
|
||||||
@@ -39,11 +56,37 @@ async function logout(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.brand {
|
.brand {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
text-decoration: none;
|
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 {
|
.nav {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -24,19 +24,33 @@ export const useClipsStore = defineStore('clips', () => {
|
|||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const error = ref<string | null>(null)
|
const error = ref<string | null>(null)
|
||||||
|
const loaded = ref(false)
|
||||||
|
|
||||||
/** Insert or replace a clip locally (also the entry point for live sync later). */
|
/**
|
||||||
|
* Insert or replace a clip locally. Used for API responses and live-sync events;
|
||||||
|
* an older version never overwrites a newer one, whatever arrives first.
|
||||||
|
*/
|
||||||
function upsert(clip: Clip): void {
|
function upsert(clip: Clip): void {
|
||||||
const index = items.value.findIndex((c) => c.id === clip.id)
|
const index = items.value.findIndex((c) => c.id === clip.id)
|
||||||
if (index === -1) {
|
if (index === -1) {
|
||||||
items.value.push(clip)
|
items.value.push(clip)
|
||||||
total.value += 1
|
total.value += 1
|
||||||
} else {
|
} else if (items.value[index]!.version <= clip.version) {
|
||||||
items.value[index] = clip
|
items.value[index] = clip
|
||||||
|
} else {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
items.value.sort(compareClips)
|
items.value.sort(compareClips)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Forget everything, e.g. on logout so the next user on this device sees nothing. */
|
||||||
|
function reset(): void {
|
||||||
|
items.value = []
|
||||||
|
total.value = 0
|
||||||
|
error.value = null
|
||||||
|
loaded.value = false
|
||||||
|
}
|
||||||
|
|
||||||
function removeLocal(id: number): void {
|
function removeLocal(id: number): void {
|
||||||
const before = items.value.length
|
const before = items.value.length
|
||||||
items.value = items.value.filter((c) => c.id !== id)
|
items.value = items.value.filter((c) => c.id !== id)
|
||||||
@@ -50,6 +64,7 @@ export const useClipsStore = defineStore('clips', () => {
|
|||||||
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=0`)
|
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=0`)
|
||||||
items.value = page.items
|
items.value = page.items
|
||||||
total.value = page.total
|
total.value = page.total
|
||||||
|
loaded.value = true
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error.value = e instanceof Error ? e.message : String(e)
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -101,8 +116,10 @@ export const useClipsStore = defineStore('clips', () => {
|
|||||||
total,
|
total,
|
||||||
loading,
|
loading,
|
||||||
error,
|
error,
|
||||||
|
loaded,
|
||||||
upsert,
|
upsert,
|
||||||
removeLocal,
|
removeLocal,
|
||||||
|
reset,
|
||||||
load,
|
load,
|
||||||
loadMore,
|
loadMore,
|
||||||
fetchOne,
|
fetchOne,
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
import { notifyUnauthorized } from '@/api/client'
|
||||||
|
import type { Clip } from '@/api/types'
|
||||||
|
import { useClipsStore } from '@/stores/clips'
|
||||||
|
|
||||||
|
export type SyncStatus = 'offline' | 'connecting' | 'live'
|
||||||
|
|
||||||
|
type ServerMessage =
|
||||||
|
| { type: 'hello' }
|
||||||
|
| { type: 'ping' }
|
||||||
|
| { type: 'clip.created' | 'clip.updated'; data: Clip }
|
||||||
|
| { type: 'clip.deleted'; data: { id: number } }
|
||||||
|
|
||||||
|
const MIN_RETRY_MS = 1_000
|
||||||
|
const MAX_RETRY_MS = 30_000
|
||||||
|
// Server pings every 30 s; silence beyond this means the connection is dead
|
||||||
|
const WATCHDOG_MS = 75_000
|
||||||
|
const CLOSE_UNAUTHORIZED = 4401
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Live sync: receives change events over a WebSocket and applies them to the clip store.
|
||||||
|
* Writes always go through the REST API; the socket is read-only.
|
||||||
|
*/
|
||||||
|
export const useSyncStore = defineStore('sync', () => {
|
||||||
|
const status = ref<SyncStatus>('offline')
|
||||||
|
|
||||||
|
let socket: WebSocket | null = null
|
||||||
|
let wanted = false
|
||||||
|
let retryDelay = MIN_RETRY_MS
|
||||||
|
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
let watchdogTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
let listenersAdded = false
|
||||||
|
|
||||||
|
function handle(message: ServerMessage): void {
|
||||||
|
const clips = useClipsStore()
|
||||||
|
switch (message.type) {
|
||||||
|
case 'hello':
|
||||||
|
status.value = 'live'
|
||||||
|
retryDelay = MIN_RETRY_MS
|
||||||
|
// Events may have been missed while disconnected
|
||||||
|
if (clips.loaded) void clips.load()
|
||||||
|
break
|
||||||
|
case 'clip.created':
|
||||||
|
case 'clip.updated':
|
||||||
|
clips.upsert(message.data)
|
||||||
|
break
|
||||||
|
case 'clip.deleted':
|
||||||
|
clips.removeLocal(message.data.id)
|
||||||
|
break
|
||||||
|
case 'ping':
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetWatchdog(ws: WebSocket): void {
|
||||||
|
clearTimeout(watchdogTimer)
|
||||||
|
watchdogTimer = setTimeout(() => drop(ws), WATCHDOG_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Abandon a (possibly half-dead) socket and reconnect. */
|
||||||
|
function drop(ws: WebSocket): void {
|
||||||
|
if (socket !== ws) return
|
||||||
|
ws.onclose = ws.onmessage = ws.onerror = null
|
||||||
|
ws.close()
|
||||||
|
socket = null
|
||||||
|
scheduleReconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect(): void {
|
||||||
|
if (!wanted || socket) return
|
||||||
|
clearTimeout(retryTimer)
|
||||||
|
status.value = 'connecting'
|
||||||
|
|
||||||
|
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
|
||||||
|
const ws = new WebSocket(`${scheme}://${location.host}/api/ws`)
|
||||||
|
socket = ws
|
||||||
|
resetWatchdog(ws)
|
||||||
|
|
||||||
|
ws.onmessage = (event: MessageEvent<string>) => {
|
||||||
|
resetWatchdog(ws)
|
||||||
|
try {
|
||||||
|
handle(JSON.parse(event.data) as ServerMessage)
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Ignoring invalid sync message', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ws.onclose = (event: CloseEvent) => {
|
||||||
|
if (socket !== ws) return
|
||||||
|
socket = null
|
||||||
|
clearTimeout(watchdogTimer)
|
||||||
|
if (event.code === CLOSE_UNAUTHORIZED) {
|
||||||
|
stop()
|
||||||
|
notifyUnauthorized()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scheduleReconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleReconnect(): void {
|
||||||
|
clearTimeout(watchdogTimer)
|
||||||
|
status.value = wanted ? 'connecting' : 'offline'
|
||||||
|
if (!wanted) return
|
||||||
|
const jitter = 0.5 + Math.random()
|
||||||
|
retryTimer = setTimeout(connect, retryDelay * jitter)
|
||||||
|
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reconnect right away, e.g. when an iPhone brings the app back to the foreground. */
|
||||||
|
function reconnectNow(): void {
|
||||||
|
if (!wanted || document.visibilityState !== 'visible') return
|
||||||
|
if (socket && socket.readyState === WebSocket.OPEN) return
|
||||||
|
if (socket) drop(socket)
|
||||||
|
clearTimeout(retryTimer)
|
||||||
|
retryDelay = MIN_RETRY_MS
|
||||||
|
connect()
|
||||||
|
}
|
||||||
|
|
||||||
|
function start(): void {
|
||||||
|
wanted = true
|
||||||
|
if (!listenersAdded) {
|
||||||
|
document.addEventListener('visibilitychange', reconnectNow)
|
||||||
|
window.addEventListener('online', reconnectNow)
|
||||||
|
listenersAdded = true
|
||||||
|
}
|
||||||
|
connect()
|
||||||
|
}
|
||||||
|
|
||||||
|
function stop(): void {
|
||||||
|
wanted = false
|
||||||
|
clearTimeout(retryTimer)
|
||||||
|
clearTimeout(watchdogTimer)
|
||||||
|
if (socket) {
|
||||||
|
socket.onclose = socket.onmessage = socket.onerror = null
|
||||||
|
socket.close(1000)
|
||||||
|
socket = null
|
||||||
|
}
|
||||||
|
status.value = 'offline'
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status, start, stop }
|
||||||
|
})
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
import { onBeforeRouteLeave, useRouter } from 'vue-router'
|
import { onBeforeRouteLeave, useRouter } from 'vue-router'
|
||||||
|
|
||||||
import { ApiError } from '@/api/client'
|
import { ApiError } from '@/api/client'
|
||||||
@@ -19,6 +19,10 @@ const notFound = ref(false)
|
|||||||
const error = ref<string | null>(null)
|
const error = ref<string | null>(null)
|
||||||
const busy = ref(false)
|
const busy = ref(false)
|
||||||
const conflict = ref<Clip | null>(null)
|
const conflict = ref<Clip | null>(null)
|
||||||
|
// Live-sync notices: newer version from another device, or deleted there
|
||||||
|
const remoteChange = ref<Clip | null>(null)
|
||||||
|
const remoteDeleted = ref(false)
|
||||||
|
let leaving = false
|
||||||
|
|
||||||
// Form state
|
// Form state
|
||||||
const title = ref('')
|
const title = ref('')
|
||||||
@@ -34,6 +38,7 @@ function fillForm(source: Clip): void {
|
|||||||
kind.value = source.kind
|
kind.value = source.kind
|
||||||
language.value = source.language ?? detectLanguage(source.content) ?? 'plaintext'
|
language.value = source.language ?? detectLanguage(source.content) ?? 'plaintext'
|
||||||
baseVersion.value = source.version
|
baseVersion.value = source.version
|
||||||
|
remoteChange.value = null
|
||||||
}
|
}
|
||||||
|
|
||||||
const dirty = computed(() => {
|
const dirty = computed(() => {
|
||||||
@@ -51,6 +56,21 @@ const previewHtml = computed(() =>
|
|||||||
kind.value === 'code' ? highlight(content.value, language.value) : null,
|
kind.value === 'code' ? highlight(content.value, language.value) : null,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// React to live-sync updates of the clip being edited
|
||||||
|
watch(
|
||||||
|
() => store.items.find((c) => c.id === clip.value?.id),
|
||||||
|
(remote) => {
|
||||||
|
if (!clip.value || leaving) return
|
||||||
|
if (!remote) {
|
||||||
|
remoteDeleted.value = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (remote.version <= baseVersion.value) return
|
||||||
|
if (dirty.value) remoteChange.value = remote
|
||||||
|
else fillForm(remote)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
async function save(version = baseVersion.value): Promise<void> {
|
async function save(version = baseVersion.value): Promise<void> {
|
||||||
if (!clip.value) return
|
if (!clip.value) return
|
||||||
busy.value = true
|
busy.value = true
|
||||||
@@ -67,6 +87,7 @@ async function save(version = baseVersion.value): Promise<void> {
|
|||||||
version,
|
version,
|
||||||
)
|
)
|
||||||
conflict.value = null
|
conflict.value = null
|
||||||
|
leaving = true
|
||||||
clip.value = null // nothing left to lose; skip the leave guard
|
clip.value = null // nothing left to lose; skip the leave guard
|
||||||
await router.push('/')
|
await router.push('/')
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -81,17 +102,20 @@ async function save(version = baseVersion.value): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function takeTheirs(): void {
|
function takeTheirs(): void {
|
||||||
if (conflict.value) fillForm(conflict.value)
|
const theirs = conflict.value ?? remoteChange.value
|
||||||
|
if (theirs) fillForm(theirs)
|
||||||
conflict.value = null
|
conflict.value = null
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remove(): Promise<void> {
|
async function remove(): Promise<void> {
|
||||||
if (!clip.value || !confirm('Diesen Clip endgültig löschen?')) return
|
if (!clip.value || !confirm('Diesen Clip endgültig löschen?')) return
|
||||||
|
leaving = true
|
||||||
try {
|
try {
|
||||||
await store.remove(clip.value.id)
|
await store.remove(clip.value.id)
|
||||||
clip.value = null
|
clip.value = null
|
||||||
await router.push('/')
|
await router.push('/')
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
leaving = false
|
||||||
error.value = e instanceof Error ? e.message : String(e)
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,6 +141,23 @@ onMounted(async () => {
|
|||||||
</p>
|
</p>
|
||||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||||
|
|
||||||
|
<section v-if="remoteDeleted" class="card conflict" role="alert">
|
||||||
|
<p>
|
||||||
|
Dieser Clip wurde auf einem anderen Gerät gelöscht. Du kannst den Inhalt noch kopieren;
|
||||||
|
speichern ist nicht mehr möglich.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section v-else-if="remoteChange && !conflict" class="card notice" role="status">
|
||||||
|
<p>
|
||||||
|
Auf einem anderen Gerät geändert ({{ formatDateTime(remoteChange.updated_at) }}). Deine
|
||||||
|
Änderungen sind noch nicht gespeichert.
|
||||||
|
</p>
|
||||||
|
<div class="actions">
|
||||||
|
<button type="button" @click="takeTheirs">Andere Version laden</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section v-if="conflict" class="card conflict" role="alert">
|
<section v-if="conflict" class="card conflict" role="alert">
|
||||||
<h2>Konflikt</h2>
|
<h2>Konflikt</h2>
|
||||||
<p>
|
<p>
|
||||||
@@ -180,7 +221,9 @@ onMounted(async () => {
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button type="submit" class="primary" :disabled="busy || !content.trim()">Speichern</button>
|
<button type="submit" class="primary" :disabled="busy || remoteDeleted || !content.trim()">
|
||||||
|
Speichern
|
||||||
|
</button>
|
||||||
<CopyButton :text="content" />
|
<CopyButton :text="content" />
|
||||||
<RouterLink to="/" class="button-link">Abbrechen</RouterLink>
|
<RouterLink to="/" class="button-link">Abbrechen</RouterLink>
|
||||||
<div class="spacer"></div>
|
<div class="spacer"></div>
|
||||||
@@ -220,6 +263,15 @@ onMounted(async () => {
|
|||||||
border-color: var(--error);
|
border-color: var(--error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.notice {
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.conflict p,
|
||||||
|
.notice p {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.preview {
|
.preview {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0.75rem;
|
padding: 0.75rem;
|
||||||
|
|||||||
Reference in new issue
Block a user