Compare commits

...
38 Commits
Author SHA1 Message Date
bruno aa3df74fc1 fix(mfa): /mfa/webauthn/options enumeration-safe (200 totp fallback au lieu de 400) + test
CI / lint (push) Successful in 40s
CI / security (push) Successful in 27s
CI / test (push) Successful in 53s
CI / build (push) Successful in 23s
CI / e2e (push) Successful in 6m1s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
2026-09-08 00:48:20 -04:00
bruno f9d2c0d2d4 docs(roadmap): menage — aligne le roadmap sur le code reel (#59,63-66,71,74-77,78), resume efforts recalcule + CHANGELOG 2.1.0
CI / lint (push) Successful in 41s
CI / security (push) Successful in 28s
CI / test (push) Successful in 52s
CI / build (push) Successful in 1m10s
CI / e2e (push) Successful in 6m1s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
2026-09-08 00:12:28 -04:00
bruno c066b2c82a feat(desktop): #77 B5 port auto-increment si 17890 occupe (pick_free_port) + 3 tests Rust 2026-09-07 23:55:36 -04:00
bruno ab795ec9e0 feat(mfa): #64 WebAuthn complet — enregistrement/clé/verify login + gestion clés dans Sécurité (backend+frontend+i18n+tests) 2026-09-07 23:55:35 -04:00
bruno 7042307955 feat(pdf): #74 au complet — fix auth 500 stream + endpoint pdf/info + HTTP Range 206 + indexation incrementale PDF + config taille/timeout 2026-09-07 23:24:13 -04:00
bruno f37d5fda3c fix(version): ordre des imports (ruff I001)
CI / lint (push) Successful in 39s
CI / security (push) Successful in 28s
CI / test (push) Successful in 50s
CI / build (push) Successful in 23s
CI / e2e (push) Successful in 5m51s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
2026-09-07 22:15:39 -04:00
bruno c5b92eabe1 feat(version): version x.y.z propre et cohérente partout + bump script
CI / lint (push) Failing after 21s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 27s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Corrige l'incoherence d'affichage (page principale 0.0.0-dev vs a propos
v2.0.0-dev) et unifie la gestion de version sur une seule source de verite.

Backend:
- version.py: get_version() retourne toujours le tag x.y.z propre du dernier
  tag (plus de 0.0.0-dev / -N-gHASH dans l'UI). Ajout get_git_describe() et
  get_git_commit() pour le detail.
- main.py: /api/health expose git_describe + git_commit (nouveaux champs).

Frontend:
- modale A propos (populateAbout): version + commit lus depuis /api/health,
  suppression du hardcode v2.0.0-dev dans index.html.
- section config A propos (loadAbout): lit health.version, plus de state.
  APP_VERSION obsolete.
- badge header: fetch /api/health (fallback neutre '...').
- state.js: suppression de APP_VERSION (1.5.0) devenu mort; imports nettoyes.

Script:
- scripts/bump_version.sh: incrementation SemVer selon les commits
  (breaking->major, feat->minor, sinon patch), creer/pousser le tag vX.Y.Z.

Tests: 507 passed, frontend validators OK.
2026-09-07 22:13:54 -04:00
bruno 01453bce5f feat(admin): navigation par sections sticky + support complet des themes
CI / lint (push) Successful in 38s
CI / security (push) Successful in 26s
CI / test (push) Successful in 50s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 6m7s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Navigation/ergonomie:
- barre sticky de pilules (Stats, Audit, Backups, Utilisateurs) sous le header
- scrollspy (IntersectionObserver) + scroll fluide au clic dans admin.js
- ancres + scroll-margin-top sur chaque section, layout responsive <600px

Themes:
- admin.html importe et appelle initThemes() (themes.js) au boot: la page
  reprend le theme/mode sauvegarde dans l'app (localStorage meme-origine)
- script anti-FOUC en <head> applique vite le mode avant le CSS
2026-09-07 21:45:50 -04:00
bruno bd86ba36e2 fix(admin): scroll de la page admin bloqué par le CSS global de la SPA
CI / lint (push) Successful in 42s
CI / security (push) Successful in 28s
CI / test (push) Successful in 51s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 6m2s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
admin.html charge /static/style.css dont body{overflow:hidden;height:100vh}
(congu pour la SPA avec scroll interne). Sur la page admin autonome, ce bloc
desactivait le scroll de la page.

- frontend/admin.html: body.admin-page force overflow:auto + height:auto pour
  surcharger le CSS global (specificite body.admin-page > body).
2026-09-07 21:14:45 -04:00
bruno 88ab8db88d fix(admin): /admin.html retombait sur la page principale (ROADMAP #71)
CI / lint (push) Successful in 54s
CI / security (push) Successful in 26s
CI / test (push) Successful in 50s
CI / build (push) Successful in 23s
CI / e2e (push) Successful in 6m2s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Le menu Admin redirigeait vers /admin.html mais aucune route backend ne le
servait : le catch-all SPA /{full_path:path} renvoyait index.html, d'où le
retour à la page principale.

- backend/main.py: route GET /admin.html (gate require_admin) déclarée avant
  le catch-all SPA + correction des imports JS /frontend/js -> /static/js
- frontend/admin.html: chemins d'assets alignés sur le mount /static
- tests/test_admin.py: 3 tests de régression (page servie admin, refus 401/403)
2026-09-07 20:29:33 -04:00
bruno 11406034c9 fix(config): rétablir le bloc export à la colonne 0 (validation imports CI)
CI / lint (push) Successful in 38s
CI / security (push) Successful in 24s
CI / test (push) Successful in 49s
CI / build (push) Successful in 23s
CI / e2e (push) Successful in 6m1s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
2026-09-07 18:35:53 -04:00
bruno eef8671912 fix(config): corriger erreur de syntaxe config.js dans la section clés API IA
CI / lint (push) Failing after 33s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 25s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
2026-09-07 18:24:41 -04:00
bruno 72383b1634 feat(config): badges statut + suppression par provider dans Clés API IA
CI / lint (push) Failing after 33s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 24s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
- backend: ajout DELETE /api/config/ai-keys/{provider_env} pour supprimer une clé
- frontend: badge ✓ Configuré / Non configuré sur chaque ligne provider
- frontend: bouton × Supprimer avec confirmation sur les providers configurés
- testAIKeys met à jour les badges selon les résultats du test
2026-09-07 15:43:24 -04:00
bruno 2d70be0ae2 feat(ui): badge version visible + FAB AI flottant
CI / lint (push) Successful in 37s
CI / security (push) Successful in 25s
CI / test (push) Successful in 48s
CI / build (push) Successful in 21s
CI / e2e (push) Successful in 6m4s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
2026-09-07 14:37:37 -04:00
bruno 5350738c22 feat(bookslm): bouton toggle cacher/afficher la sidebar dans le header
CI / lint (push) Successful in 37s
CI / security (push) Successful in 24s
CI / test (push) Successful in 49s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 6m16s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Même mécanisme que le sidebar de navigation gauche :
- Bouton .bookslm-btn-toggle dans le header (icône panel-right-close/open)
- Toggle la classe .hidden sur le panel, persiste dans localStorage
- État restauré au prochain open()
- Le panel reste monté (pas de teardown), juste slid off-screen
- CSS : .bookslm-panel.open.hidden → translateX(100%)
- CSS : .bookslm-btn-toggle suit le pattern .sidebar-toggle-btn

i18n : bookslm.toggle_sidebar ajouté (fr + en)
Import safeCreateIcons ajouté pour rafraîchir l'icône Lucide au toggle.

Vérifié :
- pytest : 504 passed (zéro régression)
- ruff : All checks passed
- frontend unit : 7 passed
- validate-imports : 30 modules / 204 exports
- pane-manager JSDOM : 9/9
2026-09-07 13:59:00 -04:00
bruno 0d29dd00fd fix(bookslm): 422 + thème + picker zindex
CI / lint (push) Successful in 37s
CI / security (push) Successful in 25s
CI / test (push) Successful in 49s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 6m7s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
- Bug 1 (422): bookslm.js envoie maintenant {message, conversation_history}
  conformes au backend (au lieu de messages:[...])
- Bug 2 (thème BooksLM): style.css lignes 9015-9061 — suppression de
  tous les fallbacks hex (--bg, --muted, --text, --surface, --accent,
  --border) au profit des variables ObsiGate existantes (--bg-primary,
  --text-primary, --text-secondary, --surface, --surface2, --accent,
  --border). Ajout de color: var(--text-primary) sur .bookslm-panel
- Bug 3 (picker zindex/flex): bookslm-picker-host + ai-picker +
  .bookslm-header button obtiennent flex-shrink:0 + z-index:1 pour
  éviter que les selects compressent ou masquent les boutons
  header (Nouvelle conversation / Exporter / Plein écran / Fermer)
- Bug 4 (theme picker): ai.js — var(--bg-tertiary, transparent) →
  var(--surface), var(--border-color) → var(--border) sur tous les
  selects, menus et createSeparator. Plus de variables inexistantes.

Tests: pytest 504 passed, frontend unit 7/7, validate-imports 30 modules
204 exports, pane-manager 9/9, ruff All checks passed.
2026-09-07 13:53:49 -04:00
bruno d441481930 fix(xiaomi): URL MiMo + header api-key + fallback polling admin SSE
CI / lint (push) Successful in 37s
CI / security (push) Successful in 32s
CI / test (push) Successful in 48s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 6m1s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
1. **fix(xiaomi): la clé Xiaomi échouait avec 'Name or service not known'**
   - URL précédente api.xiaomi.com n'existe pas (DNS fail)
   - Vraie URL: https://api.xiaomimimo.com/v1/models
   - Xiaomi MiMo utilise un header custom 'api-key:' (PAS 'Authorization: Bearer')
   - Modèles par défaut mis à jour: mimo-v2.5-pro, mimo-v2.5, mimo-v2.5-asr, etc.
   - Le chat dans ai.py supporte maintenant un header custom via auth_header_name

2. **fix(admin): EventSource 503 → fallback polling**
   - Ajout d'un fallback: si EventSource ne reçoit jamais le premier event
     (cookie expiré, réseau bloqué, proxy timeout), on bascule sur du polling
     /api/admin/stats toutes les 5s. Le UI continue de se mettre à jour.
   - Cleanup correct du timer dans disconnectSSE

3. **fix(test_ai_models)**: 2 nouveaux tests de régression
   - test_xiaomi_uses_api_key_header_not_bearer: vérifie URL + header
   - test_xiaomi_test_endpoint_uses_real_url: vérifie /api/config/ai-keys/test
   - Patche backend.ai ET backend.main (import local)
   - Header case-insensitive (urllib normalise à 'Api-key', HTTP est insensible)

Vérifié :
- pytest : 504 passed (502 + 2 nouveaux Xiaomi)
- frontend unit : 7 passed
- validate-imports : 30 modules / 204 exports
- pane-manager JSDOM : 9/9
- ruff check backend/ : All checks passed
2026-09-07 12:47:24 -04:00
bruno 7ff9b854b6 fix(admin,ai): redirect admin.html + modèles fallback + picker provider/modèle par requête
CI / lint (push) Successful in 41s
CI / security (push) Successful in 28s
CI / test (push) Successful in 48s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 6m5s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Trois bugs corrigés + une amélioration demandée :

1. **fix(admin): /admin.html redirigeait toujours vers /**
   - admin.js _gateAdmin() lisait /api/auth/status qui ne contient PAS le rôle user
   - Remplacé par /api/auth/me (retourne username, role, vaults)
   - Le code distingue maintenant le cas 'auth désactivé' (admin anonyme) du
     cas 'auth requise non admin' (affiche écran forbidden)

2. **fix(ai): les modèles Nvidia/Xiaomi ne se chargeaient pas dans les dropdowns**
   - Xiaomi : l'endpoint public /v1/models est instable, échec réseau fréquent
   - Toutes les erreurs réseau/d'API renvoyaient models=[] → dropdown vide
   - Ajout d'un fallback curé : _FALLBACK_MODELS dict avec 4-8 modèles populaires
     par provider, TOUJOURS retourné si la clé manque OU si l'API distante échoue
   - Le frontend voit désormais 'fallback' vs 'live' comme hint pour l'utilisateur
   - Gemini parsing : strip du préfixe 'models/' retourné par l'API Gemini
   - 7 nouveaux tests pytest pour _FALLBACK_MODELS + endpoint /api/config/ai-models

3. **feat(ai): picker provider/model dans la toolbar AI + BooksLM**
   - Plusieurs providers peuvent maintenant être activés simultanément
   - Sélection provider+model par section (Forge, BooksLM, etc.) via dropdown
   - État persisté en localStorage (le choix suit l'utilisateur entre sections)
   - Chaque appel AI passe maintenant {provider, model} au backend
   - ai.js : aiAction() lit le picker et l'injecte dans le body
   - bookslm.js : envoie provider+model à /api/ai/bookslm/chat
   - ai_routes.py + bookslm_routes.py : AIRequest et BooksLMChatRequest
     acceptent provider+model, avec save/restore du modèle original
     pour ne pas affecter les autres requêtes concurrentes
   - 7 nouvelles clés i18n (ai.provider, ai.model, ai.model_loading, etc.)
   - 1 nouveau test bookslm vérifie que le schema accepte provider+model
   - validate-imports.mjs : fix faux positif sur 'export { X as Y }'

Vérifié :
- pytest : 502 passed, 5 skipped (494 baseline + 7 AI models + 1 BooksLM)
- frontend unit : 7 passed
- validate-imports : 30 modules / 204 exports / 0 erreur
- pane-manager JSDOM : 9/9
- ruff check backend/ : All checks passed
2026-09-07 12:00:05 -04:00
bruno 46be24f6a3 feat(admin): frontend dashboard complet pour #71
CI / lint (push) Successful in 36s
CI / security (push) Successful in 23s
CI / test (push) Successful in 46s
CI / build (push) Successful in 22s
CI / e2e (push) Successful in 5m43s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Page admin standalone + widgets temps réel + CRUD users via AdminPanel existant.

- frontend/admin.html : page admin (header + 4 sections : stats temps réel,
  audit logs, backups, gestion utilisateurs + footer)
- frontend/js/admin.js : module ES avec init(), connectSSE(), loadStatsOnce(),
  loadAuditLogs(), loadBackupStats(), renderStatsWidget(), renderAuditTable(),
  renderBackups() + helpers (formatBytes, formatUptime, severityColor)
- frontend/locales/{fr,en}.json : 36 clés admin.* identiques (diff vérifié)
- frontend/js/auth.js : adminRow.onclick redirige vers /admin.html (au lieu de
  AdminPanel.show() qui reste fonctionnel)
- tests/frontend/unit.test.mjs : 3 nouveaux tests (admin.js existe + exports + parse)
- tests/test_auth_api.py : 2 nouveaux tests smoke (PATCH + DELETE /api/auth/admin/users)

Vérifié :
- pytest : 494 passed, 5 skipped (492 baseline + 2 nouveaux)
- frontend unit : 7 passed (4 baseline + 3 admin)
- validate-imports : 30 modules validated (29 + admin.js)
- pane-manager JSDOM : 9/9 passed
- ruff check backend/ : All checks passed
2026-09-07 11:14:46 -04:00
bruno 3908e1601a fix(ci): contournement DNS flaky + retry pour le job Docker build
CI / lint (push) Successful in 37s
CI / security (push) Successful in 25s
CI / test (push) Successful in 46s
CI / build (push) Successful in 1m22s
CI / e2e (push) Successful in 5m48s
Le job 'CI / build' échouait avec :
  failed to fetch anonymous token: dial tcp: lookup auth.docker.io on
  127.0.0.11:53: server misbehaving

Le résolveur DNS embarqué du daemon Docker sur le runner GitHub Actions
est bogué de manière intermittente. Cette PR ajoute :

1. Étape 'Configure DNS' qui configure /etc/docker/daemon.json avec
   les DNS publics Google/Cloudflare/Quad9 (8.8.8.8, 1.1.1.1, 9.9.9.9)
   puis redémarre le daemon Docker
2. Retry jusqu'à 3 fois (10s, 20s d'attente) sur la commande
   docker build pour absorber les flakes réseau ponctuels

Aucun changement au Dockerfile lui-même — il fonctionne en local
et le bug est purement infrastructure.
2026-09-07 10:20:52 -04:00
bruno 1ef0a7ed82 chore(lint): combine nested if dans bookslm_routes (SIM102)
CI / lint (push) Successful in 36s
CI / security (push) Successful in 23s
CI / test (push) Successful in 48s
CI / build (push) Failing after 24s
CI / e2e (push) Skipped
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
Fix final pour atteindre 'All checks passed!' sur ruff check backend/.
Le commit précédent avait raté ce fichier (modifié par --unsafe-fixes
mais non inclus dans le commit).
2026-09-07 09:09:27 -04:00
bruno 43f5b4a078 chore(lint): fixe les 3 dernières erreurs ruff pré-existantes
CI / lint (push) Failing after 19s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 27s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
- bookslm.py: PERF402 — list(_cache) au lieu de la boucle d'append
- bookslm_routes.py: SIM102 — combine les conditions imbriquées (via --unsafe-fixes)
- export.py: DTZ005 — datetime.now(tz=timezone.utc) au lieu de naive now()
- watcher.py: SIM102 — combine les conditions imbriquées

Résultat : ruff check backend/ → All checks passed!
Vérifié : pytest full suite reste 492 passed, 5 skipped, 0 failed.
2026-09-07 09:06:11 -04:00
bruno 83355a25c8 chore(lint): ruff --fix sur le backend (cleanup pré-existant)
Réduit les erreurs ruff de 11 à 5 (toutes pré-existantes non auto-fixables) :
- F401 imports inutilisés dans auth/mfa.py
- I001 blocs d'imports non triés dans auth/router.py + main.py + pdf_reader.py

Les 5 restantes sont dans bookslm/export/watcher (code pré-existant, hors scope).

Vérifié : pytest full suite reste 492 passed, 5 skipped, 0 failed.
2026-09-07 09:01:40 -04:00
bruno ec56bc32f8 feat(pdf): tests pytest + fix bug NameError pour #74
CI / lint (push) Failing after 19s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 23s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
- tests/test_pdf.py : 13 tests (100% verts) couvrant :
  - extract_pdf_text/metadata/toc avec edge cases (corrupt, missing, truncation)
  - .pdf dans SUPPORTED_EXTENSIONS
  - _scan_vault() extrait le texte des PDFs (vérifié avec fixture reportlab)
  - parseur du filtre ext:pdf
- backend/pdf_reader.py : fix NameError quand pymupdf est installé
  (PdfReader n'était déclaré que dans la branche except ImportError)
- backend/requirements-test.txt : reportlab pour générer des PDFs de test (devDep only)
- README.md + README.fr.md : section 'PDF support' documentée
- docs/ROADMAP.md : #74 marqué 'pratiquement complet' avec détail honnête des items livrés vs non
- CHANGELOG.md : entrées pour #71 admin (déjà dans commit précédent), #75 I2 et #74
2026-09-07 08:54:55 -04:00
bruno 050c3d2515 test(pane-manager): tests JSDOM pour #75 I2
- tests/frontend/pane-manager.test.mjs : 9 tests d'intégration frontend via JSDOM 30
  Couvre factory, init, open/activate/close, isolation entre panes, drag/drop smoke
- tests/frontend/package.json + package-lock.json : jsdom en devDependency
- .gitea/workflows/ci.yml : nouvelle étape 'Frontend JSDOM tests (PaneManager)'
  qui installe jsdom au besoin puis lance pane-manager.test.mjs
2026-09-07 08:54:41 -04:00
bruno b649c6b301 feat(admin): backend dashboard pour #71
- backend/admin.py : module FastAPI avec 4 endpoints admin-gated
  - GET /api/admin/stats (CPU/RAM/Disk/Uptime via psutil)
  - GET /api/admin/audit (filtres user/action/limit/offset)
  - GET /api/admin/backup-stats (count + size + age par vault)
  - GET /api/admin/stream (Server-Sent Events 5s)
- backend/main.py : routeur monté + middleware gzip bypass pour SSE
- backend/requirements.txt : ajout psutil>=5.9
- tests/test_admin.py : 13 tests (auth + filtres + format SSE), 100% verts

Pas de frontend dans cette PR — page admin.html + admin.js restent à faire.
2026-09-07 08:54:25 -04:00
bruno 99c9acccb0 docs(roadmap): #76 BooksLM marqué FAIT + providers AI étendus
CI / lint (push) Failing after 17s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 21s
2026-09-06 19:43:07 -04:00
bruno 524e6da591 feat(bookslm): v2.2.0 - BooksLM chat AI contextuel par répertoire + 4 providers AI
CI / lint (push) Failing after 16s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 21s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
BooksLM (#76):
- Panneau chat slide-in 450px, clic-droit répertoire → 🧠 BooksLM
- Collecte récursive .md avec limites (200 fichiers, 200K chars)
- Cache SHA-256, redaction secrets, priorité README/index
- SSE streaming, badges sources cliquables, historique localStorage
- Commandes palette: BooksLM ouvrir/nouvelle conversation

Providers AI (4 nouveaux):
- NVIDIA (integrate.api.nvidia.com)
- QwenCloud (dashscope.aliyuncs.com)
- Xiaomi (api.xiaomi.com)
- Mistral (api.mistral.ai)
- Tous OpenAI-compatible, auto-listing modèles

Fix: dropdown config-select suit maintenant le thème (option bg/color)
27 tests BooksLM + 466 tests au total
2026-09-06 19:42:40 -04:00
bruno 6292bfd9cb docs(roadmap): #64 #65 #66 marqués FAIT
CI / lint (push) Failing after 17s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 20s
2026-09-06 18:43:57 -04:00
bruno 83063d3a18 feat(auth): v2.1.0 - MFA TOTP avec QR code, recovery codes
CI / lint (push) Failing after 16s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 21s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
- backend/auth/mfa.py: TOTP (pyotp), recovery codes SHA-256
- Login flow: mfa_required → totp/verify → token (ou recovery)
- 6 nouveaux endpoints /api/auth/mfa/*
- Frontend: QR code setup, 6-digit auto-submit, recovery codes
- Settings: section Sécurité avec enable/disable MFA
- CSS: mfa-challenge, setup-card, recovery-list, badges
- i18n: 36 nouvelles clés EN/FR
- pyotp ajouté aux dépendances
- 30 tests (TOTP, recovery, API endpoints, login flow)
- 439 tests passent au total
2026-09-06 18:42:32 -04:00
bruno 7b0dacabdd feat(export): v2.1.0 - export multi-formats HTML/MD-bundle/ePub
- backend/export.py: 3 exporters (HTML standalone, ZIP MD, ePub 3)
- HTML: CSS inliné, images base64, navigation wikilinks
- MD bundle: ZIP préserve structure répertoire
- ePub: zipfile + mistune, zero nouvelle dépendance
- 3 endpoints API: /api/export/{html,md-bundle,epub}
- UI: dropdown Export dans toolbar viewer (HTML/MD/ePub)
- 20 tests (validité, contenu, erreurs, API)
- 439 tests passent au total
2026-09-06 18:42:26 -04:00
bruno c8b861f0b6 feat(themes): v2.1.0 - themes personnalisés avec presets light/dark/high-contrast/sepia
- 4 modes: dark, light, high-contrast, sepia (40+ CSS vars chacun)
- Import/export thèmes personnalisés en JSON
- Grid swatches dans les paramètres avec preview
- toggleThemeMode() cycle through all 4 modes
- CustomEvent 'themechange' dispatché
- 18 tests unitaires (structure, generators, colors, i18n keys)
- 439 tests passent au total
2026-09-06 18:42:20 -04:00
bruno 09912509cb docs(roadmap): #77 Desktop marqué complet — D/E/F mis à jour
CI / lint (push) Failing after 16s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 21s
- D. Build et distribution: build local vérifié, CI existant
- E. UX: crash handler, preferences save, first-run defaults
- F. Tests: 16 tests Rust, build debug+release OK
- Items optionnels restants: wizard interactif, jumplist, signature code
2026-09-06 18:25:29 -04:00
bruno 3e0940da8c feat(desktop): v2.0.0 - tests unitaires Rust #77 complets
CI / lint (push) Failing after 17s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 21s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
- 16 tests Rust: config roundtrip, JSON parsing, vault dedup,
  dir remove, backend URL, paths, branding, edge cases
- Ajout tempfile dev-dependency pour tests avec tmpdir
- .gitignore: exclusions junction points backend/frontend
- Build debug + release vérifié et fonctionnel
- Compilation: rustc 1.94.1, tauri-cli 2.11.4
2026-09-06 18:24:45 -04:00
bruno d20e623f0c fix(docker): build sans fichier VERSION pre-genere (docker compose build direct)
CI / lint (push) Failing after 23s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 32s
backend/VERSION est gitignore (genere par build.sh/CI) donc le COPY
echouait sur un clone propre. Remplace par le COPY backend/ existant +
ARG VERSION avec RUN fallback ; docker-compose.yml injecte VERSION via
build args. docker compose build --no-cache fonctionne desormais sans
build.sh.
2026-09-02 08:41:45 -04:00
bruno ef7a3ff1ed fix(watcher): auto-polling sur mounts reseau (NFS/SMB) pour maj temps reel des recents
CI / lint (push) Failing after 25s
CI / test (push) Skipped
CI / build (push) Skipped
CI / e2e (push) Skipped
CI / security (push) Successful in 28s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
inotify ne voit pas les ecritures faites depuis d'autres clients NFS
(Obsidian sur Windows), donc index_updated n'etait jamais emis et la
section Recent du sidebar ne se rafraichissait pas. Detection du fstype
par vault via /proc/mounts -> PollingObserver (stat-based) sur mounts
reseau, Observer natif conserve sur les mounts locaux.
2026-09-02 08:16:21 -04:00
bruno 2115cb9085 chore: ignore desktop/checksums.txt (artefact regenere par publish_release.py)
CI / lint (push) Successful in 29s
CI / security (push) Successful in 26s
CI / test (push) Successful in 39s
CI / build (push) Successful in 13s
CI / e2e (push) Successful in 6m7s
2026-08-25 21:23:21 -04:00
bruno 5f981509ac fix(publish): user-agent navigateur pour contourner le blocage Cloudflare 1010 (writes Gitea)
CI / lint (push) Successful in 30s
CI / security (push) Successful in 22s
CI / test (push) Successful in 35s
CI / build (push) Successful in 13s
CI / e2e (push) Successful in 6m7s
2026-08-25 21:23:04 -04:00
62 changed files with 10383 additions and 425 deletions
+9
View File
@@ -33,6 +33,15 @@ OBSIGATE_ADMIN_PASSWORD=chab30
# Backup
# OBSIGATE_BACKUP_DIR=.obsigate-backup
# PDF (ROADMAP #74)
# OBSIGATE_PDF_MAX_SIZE_MB=50 # PDFs plus volumineux = texte non indexé
# OBSIGATE_PDF_EXTRACT_TIMEOUT=30 # secondes avant abandon de l'extraction
# WebAuthn / MFA (ROADMAP #64) — nécessaire hors localhost
# OBSIGATE_WEBAUTHN_RP_ID=obsigate.example.com
# OBSIGATE_WEBAUTHN_RP_NAME=ObsiGate
# OBSIGATE_WEBAUTHN_ORIGINS=https://obsigate.example.com
# ── AI Provider Configuration ──
# Définir au moins un provider pour activer les fonctionnalités AI dans l'éditeur
+39 -2
View File
@@ -38,6 +38,17 @@ jobs:
- name: Frontend unit tests
run: node tests/frontend/unit.test.mjs
- name: Frontend JSDOM tests (PaneManager)
run: |
cd tests/frontend
if [ -d node_modules ]; then
node pane-manager.test.mjs
else
echo "tests/frontend/node_modules missing — installing jsdom"
npm install --no-audit --no-fund --silent
node pane-manager.test.mjs
fi
# ── Tests ─────────────────────────────────────────────────────────
test:
needs: lint
@@ -54,6 +65,7 @@ jobs:
run: |
pip install pytest pytest-cov pytest-asyncio httpx
pip install -r backend/requirements.txt
pip install -r backend/requirements-test.txt || echo "test deps install failed (non-blocking — PDF tests will skip)"
- name: Run tests
run: pytest tests/ --cov=backend --cov-report=xml --cov-report=term -q
@@ -99,8 +111,33 @@ jobs:
VERSION=$(git describe --tags --dirty 2>/dev/null | sed 's/^v//' || echo "0.0.0-dev")
echo "$VERSION" > backend/VERSION
- name: Build Docker image
run: docker build -t obsigate:ci .
- name: Configure DNS (workaround flaky 127.0.0.11 resolver)
# GitHub Actions runners occasionally fail to resolve auth.docker.io via
# the embedded Docker DNS (127.0.0.11:53 → "server misbehaving").
# Force the daemon to use public DNS as a fallback.
run: |
sudo mkdir -p /etc/docker
if ! grep -q "dns" /etc/docker/daemon.json 2>/dev/null; then
echo '{"dns": ["8.8.8.8", "1.1.1.1", "9.9.9.9"]}' | sudo tee /etc/docker/daemon.json
sudo systemctl restart docker || sudo service docker restart || true
sleep 3
fi
- name: Build Docker image (retry on transient DNS/network errors)
run: |
for attempt in 1 2 3; do
echo "=== docker build attempt $attempt/3 ==="
if docker build -t obsigate:ci . ; then
echo "✓ Docker build succeeded"
exit 0
fi
echo "✗ Build failed (attempt $attempt)"
if [ $attempt -lt 3 ]; then
sleep $((attempt * 10))
fi
done
echo "✗ Docker build failed after 3 attempts"
exit 1
- name: Verify image
run: docker images obsigate:ci
+3
View File
@@ -26,5 +26,8 @@ playwright-report/
desktop/target/
desktop/python-embed/
desktop/frontend-static/
desktop/checksums.txt
desktop/backend/
desktop/frontend/
backend/VERSION
+38 -1
View File
@@ -6,7 +6,35 @@ Format basé sur [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/),
et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
> **En cours de développement** : les changements non publiés sont dans la section
> [2.0.0 — Unreleased](#200--unreleased). La dernière version publiée est **1.8.0**.
> [2.1.0](#210--2026-09-07). La dernière version publiée est **2.0.0**.
---
## [2.1.0] — 2026-09-07
### Ajouté
- **#74 Support PDF au complet** — `GET /api/file/{vault}/pdf/info` (métadonnées sans
contenu), streaming avec HTTP Range / 206 Partial Content (rendu progressif des gros PDF),
config `OBSIGATE_PDF_MAX_SIZE_MB` (50) + `OBSIGATE_PDF_EXTRACT_TIMEOUT` (30s).
16 tests supplémentaires (26 au total dans `test_pdf.py`).
- **#64 MFA — WebAuthn** (second facteur en plus du TOTP) : enregistrement de clés de
sécurité / biométrie (Windows Hello, Touch ID), assertion au login, gestion des clés dans
« Sécurité du compte », codes de récupération émis à l'activation. Nouveau module
`backend/auth/webauthn_mfa.py` (lib `webauthn==2.6.0`, challenges in-memory TTL 180s à
usage unique). 10 tests avec authentificateur virtuel (CBOR réel, ECDSA P-256).
i18n FR/EN (13 clés). Config : `OBSIGATE_WEBAUTHN_RP_ID` / `_RP_NAME` / `_ORIGINS`.
- **#77 Desktop — port auto-increment** : `pick_free_port()` scanne 17890..17899 si le port
est occupé (2 instances côte à côte possibles) + 3 tests Rust (19 au total côté desktop).
- Docs : sections PDF README FR/EN (Range, /pdf/info), variables env, guide WebAuthn.
### Corrigé
- **PDF stream 500** : `api_pdf_stream` plantait systématiquement (`NameError: current_user`
non injecté — endpoint jamais couvert par un test). Désormais authentifié + testé.
- **Indexation incrémentale des PDF** : le chemin watcher (`_index_single_file_sync`) lisait
les PDFs en `read_text()` → contenu garbage indexé. Utilise maintenant `extract_pdf_text()`
comme le scan complet.
---
@@ -18,6 +46,15 @@ et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
### Ajouté
- **Application bureau native (Tauri 2)** — Porte d'entrée desktop pour vaults Obsidian (`desktop/`)
- **Dashboard administrateur (#71, backend)** — 4 endpoints admin-gated pour monitoring serveur
- `GET /api/admin/stats` — CPU/RAM/Disk/Uptime via psutil
- `GET /api/admin/audit` — 500 dernières entrées d'audit avec filtres `user`/`action`/`limit`/`offset`
- `GET /api/admin/backup-stats` — compte + taille + age par vault
- `GET /api/admin/stream` — Server-Sent Events qui push les stats toutes les 5s
- Nouveau module `backend/admin.py` + 13 tests pytest
- **Tests JSDOM PaneManager (#75, sous-tâche I2)** — 9 tests d'intégration frontend via JSDOM 30
- Couvre : factory, init, open/activate/close, isolation entre panes, drag/drop smoke
- Wired dans le CI Gitea (`.gitea/workflows/ci.yml`)
- Shell Rust + Tauri 2 (tray icon, notifications OS, auto-update depuis Gitea)
- Backend Python embarqué (python-embed) avec health check, démarrage ~2s
- Sélecteur de dossiers natif, config persistante des vaults (type VAULT vs DIR)
+5 -2
View File
@@ -31,8 +31,11 @@ RUN apt-get update \
COPY backend/ ./backend/
COPY frontend/ ./frontend/
# Copy pre-generated VERSION file (generated by build.sh before docker build)
COPY backend/VERSION ./backend/VERSION
# Bake version: build.sh/CI pre-generate backend/VERSION (copied above);
# plain `docker compose build` has no such file (gitignored) — fall back
# to the VERSION build arg so the image always carries a version string.
ARG VERSION=0.0.0-dev
RUN test -f backend/VERSION || echo "$VERSION" > backend/VERSION
# Create non-root user for security + data directory for auth persistence
# Using explicit UID/GID 1000 to match common host user and docker-compose settings
+12
View File
@@ -272,6 +272,8 @@ Un compte **admin** connecté voit une icône 🛡️ dans le header : liste, cr
| `OBSIGATE_REFRESH_TOKEN_TTL` | Durée de vie refresh token (secondes) | `2592000` |
| `OBSIGATE_LOGIN_MAX_ATTEMPTS` | Tentatives de login max par IP | `10` |
| `OBSIGATE_LOGIN_WINDOW_SECONDS` | Fenêtre de rate limiting (secondes) | `900` |
| `OBSIGATE_PDF_MAX_SIZE_MB` | Taille max des PDF extraits (text indexation) | `50` |
| `OBSIGATE_PDF_EXTRACT_TIMEOUT` | Timeout extraction PDF (secondes) | `30` |
### Volume pour la persistance
@@ -611,6 +613,16 @@ curl "http://localhost:2020/api/file/Recettes?path=pizza.md"
Les opérateurs sont combinables : `tag:linux vault:IT ext:md serveur web`.
### Support PDF
Les fichiers PDF de vos vaults s'affichent en ligne dans le navigateur via le visualiseur PDF natif (iframe + `<embed>`).
Le visualiseur streame le fichier via HTTP Range (206 Partial Content) — les gros PDF se chargent progressivement.
Le texte est extrait à l'indexation (pypdf / pymupdf) — le contenu PDF est donc recherchable via la recherche full-text.
Filtrez avec `ext:pdf` pour restreindre les résultats aux PDF.
Les métadonnées (pages, titre, auteur) sont disponibles via `GET /api/file/{vault}/pdf/info` sans transférer le document.
**Limitations :** pas d'OCR (les PDF scannés ne sont pas recherchables), pas d'annotation, pas d'édition du PDF lui-même.
### Raccourcis clavier
| Raccourci | Action |
+13 -1
View File
@@ -310,6 +310,8 @@ When an **admin** account is logged in, a 🛡️ icon appears in the header. Cl
| `OBSIGATE_REFRESH_TOKEN_TTL` | Refresh token lifetime (seconds) | `2592000` |
| `OBSIGATE_LOGIN_MAX_ATTEMPTS` | Max login attempts per IP | `10` |
| `OBSIGATE_LOGIN_WINDOW_SECONDS` | Rate limiting window (seconds) | `900` |
| `OBSIGATE_PDF_MAX_SIZE_MB` | Max PDF size for text extraction | `50` |
| `OBSIGATE_PDF_EXTRACT_TIMEOUT` | PDF extraction timeout (seconds) | `30` |
>All these variables are documented in `.env.example`.
@@ -738,7 +740,17 @@ curl "http://localhost:2020/api/file/Recipes?path=pizza.md"
| `ext:<type>` | Filter by file type | `ext:md kubernetes` |
| `"exact phrase"` | Phrase search | `tag:"multiple words"` |
Extension filter examples: `ext:sh` for bash scripts, `ext:py` for Python scripts, `ext:md` for Markdown files.
Extension filter examples: `ext:sh` for bash scripts, `ext:py` for Python scripts, `ext:md` for Markdown files, `ext:pdf` for PDF documents (text-extracted content is indexed).
### PDF support
PDF files in your vaults are rendered inline in the browser via the native PDF viewer (iframe + `<embed>`).
The viewer streams the file over HTTP Range requests (206 Partial Content), so large PDFs load progressively.
Text is extracted on indexing (pypdf / pymupdf) so PDF content is searchable via the full-text search.
Filter with `ext:pdf` to restrict results to PDFs.
PDF metadata (pages, title, author) is available via `GET /api/file/{vault}/pdf/info` without transferring the document.
**Limitations:** no OCR (scanned PDFs aren't searchable), no annotation, no editing of the PDF itself.
Operators are combinable: `tag:linux vault:IT ext:md server web` searches for "server web" in Markdown files of the IT vault with the linux tag.
+262
View File
@@ -0,0 +1,262 @@
# backend/admin.py
# Admin Dashboard endpoints — system stats, audit logs, backup stats,
# and Server-Sent Events stream for real-time widgets.
#
# All endpoints protected with require_admin.
import asyncio
import json
import logging
import os
import shutil
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
from backend.audit import AUDIT_LOG_FILE, get_recent_entries
from backend.auth.middleware import require_admin
from backend.indexer import get_vault_data, index
logger = logging.getLogger("obsigate.admin")
router = APIRouter(prefix="/api/admin", tags=["admin"])
# Server start time — set at module import. Approximates uptime even
# if used before lifespan startup fully runs.
_SERVER_START_TIME = time.time()
def _server_uptime_seconds() -> float:
return time.time() - _SERVER_START_TIME
def _format_timestamp_for_stream(payload: dict) -> str:
"""Serialize a payload as an SSE-compatible data line."""
return json.dumps(payload, default=str, ensure_ascii=False)
def _get_disk_stats() -> tuple[float, float]:
"""Return (used_gb, total_gb) for the data volume or cwd fallback."""
# Prefer /data mount when present (production), else use cwd
target = "/data" if os.path.isdir("/data") else "."
try:
usage = shutil.disk_usage(target)
used_gb = round(usage.used / (1024 ** 3), 2)
total_gb = round(usage.total / (1024 ** 3), 2)
return used_gb, total_gb
except OSError as e:
logger.warning(f"disk_usage failed for {target}: {e}")
return 0.0, 0.0
def _count_active_sessions() -> int:
"""Count currently-revoked-free active sessions.
Best-effort estimate: we don't keep an in-memory session store, so we
fall back to 1 if the server is up. Useful for the dashboard tile.
"""
return 1
# ── /api/admin/stats ────────────────────────────────────────────────────
@router.get("/stats")
async def get_admin_stats(_admin=Depends(require_admin)):
"""Return real-time system stats for the admin dashboard."""
import psutil
try:
cpu_pct = psutil.cpu_percent(interval=None)
except Exception:
cpu_pct = 0.0
try:
vm = psutil.virtual_memory()
mem_used_mb = round(vm.used / (1024 ** 2), 1)
mem_total_mb = round(vm.total / (1024 ** 2), 1)
except Exception:
mem_used_mb, mem_total_mb = 0.0, 0.0
disk_used_gb, disk_total_gb = _get_disk_stats()
uptime_seconds = int(_server_uptime_seconds())
active_sessions = _count_active_sessions()
return {
"cpu_pct": cpu_pct,
"mem_used_mb": mem_used_mb,
"mem_total_mb": mem_total_mb,
"disk_used_gb": disk_used_gb,
"disk_total_gb": disk_total_gb,
"uptime_seconds": uptime_seconds,
"active_sessions": active_sessions,
}
# ── /api/admin/audit ───────────────────────────────────────────────────
@router.get("/audit")
async def get_admin_audit(
user: str | None = Query(None, description="Filter by username (substring)"),
action: str | None = Query(None, description="Filter by exact action"),
limit: int = Query(500, ge=1, le=2000, description="Max entries"),
offset: int = Query(0, ge=0, description="Skip first N entries"),
_admin=Depends(require_admin),
):
"""Return recent audit log entries with optional filters."""
entries = get_recent_entries(limit=offset + limit, action=action)
if user:
needle = user.lower()
entries = [e for e in entries if needle in str(e.get("username", "")).lower()]
if offset:
entries = entries[offset:]
return {
"entries": entries,
"total": len(entries),
"log_file": str(AUDIT_LOG_FILE),
}
# ── /api/admin/backup-stats ───────────────────────────────────────────
def _scan_backups() -> list[dict]:
"""Walk every vault's backup directory and return one row per .bak file."""
rows: list[dict] = []
for vault_name in list(index.keys()):
vd = get_vault_data(vault_name)
if not vd:
continue
vault_root = Path(vd["path"])
backup_root = Path(os.environ.get("OBSIGATE_BACKUP_DIR", ".obsigate-backup"))
if not backup_root.is_absolute():
backup_root = vault_root / backup_root
vault_backup_dir = backup_root / vault_name
if not vault_backup_dir.exists():
continue
try:
for fpath in vault_backup_dir.rglob("*.bak"):
if not fpath.is_file():
continue
try:
st = fpath.stat()
except OSError:
continue
# Backup filename: {orig}.{timestamp}.bak — split from the right
name = fpath.name
parts = name.rsplit(".", 2)
if len(parts) < 3 or not parts[-2].isdigit():
continue
try:
ts = int(parts[-2])
except ValueError:
continue
rows.append({
"vault": vault_name,
"filename": name,
"timestamp": ts,
"size": st.st_size,
})
except OSError as e:
logger.warning(f"Backup scan error in {vault_backup_dir}: {e}")
rows.sort(key=lambda r: r["timestamp"], reverse=True)
return rows
@router.get("/backup-stats")
async def get_admin_backup_stats(_admin=Depends(require_admin)):
"""Return backup statistics across all vaults."""
rows = _scan_backups()
now_ts = int(time.time())
total_size_mb = round(sum(r["size"] for r in rows) / (1024 ** 2), 2)
by_vault: dict[str, dict[str, Any]] = {}
for r in rows:
bucket = by_vault.setdefault(r["vault"], {"count": 0, "size_mb": 0.0})
bucket["count"] += 1
bucket["size_mb"] = round(bucket["size_mb"] + r["size"] / (1024 ** 2), 2)
if rows:
newest_ts = rows[0]["timestamp"]
oldest_ts = rows[-1]["timestamp"]
newest_age_days = round((now_ts - newest_ts) / 86400, 2)
oldest_age_days = round((now_ts - oldest_ts) / 86400, 2)
else:
newest_age_days = 0.0
oldest_age_days = 0.0
return {
"total_backups": len(rows),
"total_size_mb": total_size_mb,
"oldest_age_days": oldest_age_days,
"newest_age_days": newest_age_days,
"by_vault": by_vault,
}
# ── /api/admin/stream — Server-Sent Events ─────────────────────────────
async def _stats_event_generator():
"""Yield an SSE `stats` event with the current system stats."""
try:
import psutil
# Prime cpu_percent so the first real measurement isn't 0.0
psutil.cpu_percent(interval=None)
except Exception:
pass
last_keepalive = time.time()
KEEPALIVE_INTERVAL = 15.0
STATS_INTERVAL = 5.0
try:
while True:
now = time.time()
try:
data = await asyncio.to_thread(_build_stats_payload)
except Exception as e:
logger.warning(f"SSE stats build failed: {e}")
data = {"error": str(e)}
yield f"event: stats\ndata: {_format_timestamp_for_stream(data)}\n\n"
if now - last_keepalive >= KEEPALIVE_INTERVAL:
last_keepalive = now
yield ": keepalive\n\n"
await asyncio.sleep(STATS_INTERVAL)
except asyncio.CancelledError:
logger.info("SSE stats stream cancelled")
raise
def _build_stats_payload() -> dict:
"""Synchronous stats builder for the SSE generator."""
import psutil
cpu_pct = psutil.cpu_percent(interval=None)
vm = psutil.virtual_memory()
disk_used_gb, disk_total_gb = _get_disk_stats()
return {
"cpu_pct": cpu_pct,
"mem_used_mb": round(vm.used / (1024 ** 2), 1),
"mem_total_mb": round(vm.total / (1024 ** 2), 1),
"disk_used_gb": disk_used_gb,
"disk_total_gb": disk_total_gb,
"uptime_seconds": int(_server_uptime_seconds()),
"timestamp": datetime.now(timezone.utc).isoformat(),
}
@router.get("/stream")
async def stream_admin_stats(_admin=Depends(require_admin)):
"""Server-Sent Events stream of system metrics, every 5 seconds."""
return StreamingResponse(
_stats_event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
)
+43 -4
View File
@@ -1,6 +1,6 @@
"""ObsiGate AI — Multi-provider AI service for editor enhancement.
Supports: DeepSeek, OpenRouter, Google Gemini.
Supports: DeepSeek, OpenRouter, Google Gemini, Ollama, NVIDIA, QwenCloud, Xiaomi, Mistral.
Configured via environment variables.
"""
@@ -14,7 +14,7 @@ import httpx
logger = logging.getLogger("obsigate.ai")
ProviderName = Literal["deepseek", "openrouter", "gemini", "ollama"]
ProviderName = Literal["deepseek", "openrouter", "gemini", "ollama", "nvidia", "qwencloud", "xiaomi", "mistral"]
# Provider configurations — keys loaded from file or .env
AI_KEYS_FILE = Path("data/api_keys.json")
@@ -61,6 +61,34 @@ def _load_provider_keys():
"model": os.getenv("OLLAMA_MODEL", "qwen2.5-coder:1.5b"),
"auth_header": "Bearer {api_key}",
},
"nvidia": {
"api_key": get_ai_key("NVIDIA_API_KEY"),
"base_url": "https://integrate.api.nvidia.com/v1",
"model": os.getenv("NVIDIA_MODEL", "meta/llama-3.1-405b-instruct"),
"auth_header": "Bearer {api_key}",
},
"qwencloud": {
"api_key": get_ai_key("QWENCLOUD_API_KEY"),
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model": os.getenv("QWENCLOUD_MODEL", "qwen-max"),
"auth_header": "Bearer {api_key}",
},
"xiaomi": {
"api_key": get_ai_key("XIAOMI_API_KEY"),
"base_url": os.getenv("XIAOMI_BASE_URL", "https://api.xiaomimimo.com/v1"),
"model": os.getenv("XIAOMI_MODEL", "mimo-v2.5-pro"),
# Xiaomi MiMo uses a dedicated `api-key` header (NOT Authorization: Bearer).
# The `_call_deepseek_openrouter` helper substitutes {api_key} verbatim,
# so we just emit the raw key value here.
"auth_header": "{api_key}",
"auth_header_name": "api-key",
},
"mistral": {
"api_key": get_ai_key("MISTRAL_API_KEY"),
"base_url": "https://api.mistral.ai/v1",
"model": os.getenv("MISTRAL_MODEL", "mistral-large-latest"),
"auth_header": "Bearer {api_key}",
},
}
PROVIDERS = _load_provider_keys()
@@ -86,13 +114,23 @@ def _get_provider_config(provider: ProviderName | None = None) -> dict:
async def _call_deepseek_openrouter(prompt: str, system: str, provider: ProviderName | None = None,
temperature: float = 0.7, max_tokens: int = 2048) -> str:
"""Call OpenAI-compatible API (DeepSeek, OpenRouter)."""
"""Call OpenAI-compatible API (DeepSeek, OpenRouter, Xiaomi MiMo, etc.)."""
cfg = _get_provider_config(provider)
# Debug: log masked key to diagnose 401
key_preview = cfg["api_key"][:8] + "..." + cfg["api_key"][-4:] if len(cfg["api_key"]) > 12 else "***"
logger.info(f"AI call: provider={cfg['name']} model={cfg['model']} key={key_preview}")
# Most providers use "Authorization: Bearer KEY". Some (Xiaomi MiMo) use a
# dedicated header like "api-key: KEY". We support both via the
# `auth_header_name` key in PROVIDERS — defaults to "Authorization".
header_name = cfg.get("auth_header_name") or "Authorization"
header_value = cfg["auth_header"].format(api_key=cfg["api_key"])
# If the auth_header template doesn't include "Bearer " but the default
# header is Authorization, prepend it. This preserves backward compatibility
# for providers that store just the raw key.
if header_name == "Authorization" and not header_value.lower().startswith("bearer "):
header_value = "Bearer " + header_value
headers = {
"Authorization": cfg["auth_header"].format(api_key=cfg["api_key"]),
header_name: header_value,
"Content-Type": "application/json",
}
payload = {
@@ -139,6 +177,7 @@ async def ai_complete(prompt: str, provider: ProviderName | None = None) -> str:
cfg = _get_provider_config(provider)
if cfg["name"] == "gemini":
return await _call_gemini(prompt, "You are a helpful assistant.")
# All other providers use OpenAI-compatible format
return await _call_deepseek_openrouter(prompt, "You are a helpful assistant.", provider)
+15 -1
View File
@@ -42,6 +42,10 @@ async def api_status():
"deepseek": "DEEPSEEK_API_KEY",
"openrouter": "OPENROUTER_API_KEY",
"gemini": "GEMINI_API_KEY",
"nvidia": "NVIDIA_API_KEY",
"qwencloud": "QWENCLOUD_API_KEY",
"xiaomi": "XIAOMI_API_KEY",
"mistral": "MISTRAL_API_KEY",
}
providers = {}
for name, env_var in provider_keys.items():
@@ -97,7 +101,8 @@ class AIRequest(BaseModel):
instruction: str | None = Field(None, description="Custom instruction for rewrite")
target_lang: str | None = Field(None, description="Target language for translation")
tone: str | None = Field(None, description="Target tone (professional, casual, etc.)")
provider: str | None = Field(None, description="AI provider override")
provider: str | None = Field(None, description="AI provider override (e.g. 'deepseek', 'nvidia')")
model: str | None = Field(None, description="Model name override for this request")
class AIResponse(BaseModel):
@@ -107,6 +112,12 @@ class AIResponse(BaseModel):
async def _handle(action, request: AIRequest):
"""Wrapper with error handling."""
from backend.ai import PROVIDERS
# Apply per-request model override (saved/restored around the call)
original_model = None
if request.model and request.provider and request.provider in PROVIDERS:
original_model = PROVIDERS[request.provider].get("model")
PROVIDERS[request.provider]["model"] = request.model
try:
result = await action(request.text, request.provider)
return AIResponse(result=result, provider=request.provider or "default")
@@ -115,6 +126,9 @@ async def _handle(action, request: AIRequest):
except Exception as e:
logger.error(f"AI error: {e}")
raise HTTPException(status_code=500, detail=f"AI service error: {e!s}")
finally:
if original_model is not None and request.provider in PROVIDERS:
PROVIDERS[request.provider]["model"] = original_model
@router.post("/improve", response_model=AIResponse)
+63
View File
@@ -0,0 +1,63 @@
# backend/auth/mfa.py
# Multi-Factor Authentication: TOTP + recovery codes.
# TOTP via pyotp, recovery codes hashed with argon2 for single-use storage.
import hashlib
import logging
import secrets
import pyotp
logger = logging.getLogger("obsigate.auth.mfa")
TOTP_ISSUER = "ObsiGate"
def generate_secret() -> str:
"""Generate a new TOTP secret (base32-encoded, 160 bits)."""
return pyotp.random_base32()
def generate_qr_uri(secret: str, username: str, issuer: str = TOTP_ISSUER) -> str:
"""Generate an otpauth:// URI for QR code generation."""
totp = pyotp.TOTP(secret)
return totp.provisioning_uri(name=username, issuer_name=issuer)
def verify_totp(secret: str, code: str) -> bool:
"""Verify a TOTP code with a ±1 window tolerance."""
totp = pyotp.TOTP(secret)
return totp.verify(code, valid_window=1)
def generate_recovery_codes(n: int = 8) -> list[str]:
"""Generate n human-readable recovery codes (XXXX-XXXX format)."""
codes = []
for _ in range(n):
# 8 chars alphanumeric, grouped with dash for readability
raw = secrets.token_hex(4).upper()
code = f"{raw[:4]}-{raw[4:]}"
codes.append(code)
return codes
def hash_recovery_code(code: str) -> str:
"""Hash a recovery code for storage (SHA-256 for fast comparison).
We use SHA-256 instead of argon2 here because recovery codes are
high-entropy random strings, not user-chosen passwords.
"""
return hashlib.sha256(code.upper().encode("utf-8")).hexdigest()
def verify_recovery_code(code: str, hashed_codes: list[str]) -> int | None:
"""Verify a recovery code against stored hashes.
Returns the index of the matched code (for removal), or None if invalid.
Comparison is case-insensitive.
"""
code_hash = hash_recovery_code(code)
for i, stored_hash in enumerate(hashed_codes):
if secrets.compare_digest(code_hash, stored_hash):
return i
return None
+407 -11
View File
@@ -5,7 +5,7 @@
import logging
import re
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response
from pydantic import BaseModel, validator
from backend.ratelimit import is_rate_limited
@@ -20,6 +20,14 @@ from .jwt_handler import (
is_token_revoked,
revoke_token,
)
from .mfa import (
generate_qr_uri,
generate_recovery_codes,
generate_secret,
hash_recovery_code,
verify_recovery_code,
verify_totp,
)
from .middleware import is_auth_enabled, require_admin, require_auth
from .password import hash_password, verify_password
from .user_store import (
@@ -136,16 +144,32 @@ async def login(body: LoginRequest, response: Response, request: Request):
detail += f" ({remaining} tentative(s) restante(s))"
raise HTTPException(401, detail)
# Success — clear rate limits and generate tokens
record_login_success(body.username)
# Success — clear rate limits
rl_record_success(client_ip)
# If MFA is enabled, don't issue token yet — require second factor
if user.get("mfa_enabled"):
method = "totp" if user.get("mfa_secret") else _preferred_mfa_method(user)
logger.info(f"User '{body.username}' login deferred — MFA required ({method})")
return {
"mfa_required": True,
"mfa_method": method,
"username": body.username,
"remember_me": body.remember_me,
}
return _issue_tokens(user, body.username, body.remember_me, response)
def _issue_tokens(user: dict, username: str, remember_me: bool, response: Response) -> dict:
"""Issue JWT tokens after successful authentication (password or MFA verified)."""
record_login_success(username)
access_token = create_access_token(user)
refresh_token, refresh_jti = create_refresh_token(body.username)
refresh_token, refresh_jti = create_refresh_token(username)
# Set refresh token as HttpOnly cookie (path-restricted to /api/auth/refresh)
max_age = 2592000 if body.remember_me else 604800 # 30d or 7d
import os
max_age = 2592000 if remember_me else 604800 # 30d or 7d
secure = os.environ.get("OBSIGATE_SECURE_COOKIES", "false").lower() == "true"
response.set_cookie(
key="refresh_token",
@@ -156,10 +180,7 @@ async def login(body: LoginRequest, response: Response, request: Request):
secure=secure,
path="/api/auth/refresh",
)
logger.info(f"User '{body.username}' logged in")
# Set access token as cookie for same-origin requests (e.g. popout window)
logger.info(f"User '{username}' logged in")
response.set_cookie(
key="access_token",
value=access_token,
@@ -169,7 +190,6 @@ async def login(body: LoginRequest, response: Response, request: Request):
secure=secure,
path="/",
)
return {
"access_token": access_token,
"token_type": "bearer", # nosec B105 — OAuth2 token_type, pas un mot de passe
@@ -304,6 +324,382 @@ async def change_password(
return {"message": "Mot de passe mis à jour"}
# ── MFA endpoints ────────────────────────────────────────────────────
class MfaVerifyRequest(BaseModel):
username: str
code: str
remember_me: bool = False
class MfaRecoveryRequest(BaseModel):
username: str
recovery_code: str
class MfaDisableRequest(BaseModel):
password: str
code: str
class MfaEnableRequest(BaseModel):
code: str
@router.post("/mfa/totp/setup")
async def mfa_totp_setup(current_user=Depends(require_auth)):
"""Generate a TOTP secret and QR URI for MFA setup.
Returns the secret and otpauth URI — client displays QR code.
Does NOT enable MFA yet; call /mfa/totp/enable after first successful verify.
"""
from .user_store import update_user
secret = generate_secret()
qr_uri = generate_qr_uri(secret, current_user["username"])
# Store secret temporarily (not yet enabled)
update_user(current_user["username"], {
"mfa_secret_pending": secret,
})
return {
"secret": secret,
"qr_uri": qr_uri,
"otpauth_uri": qr_uri,
}
@router.post("/mfa/totp/enable")
async def mfa_totp_enable(
req: MfaEnableRequest,
current_user=Depends(require_auth),
):
"""Enable MFA after verifying the first TOTP code.
On success: generates recovery codes, enables MFA, returns recovery codes.
"""
from .user_store import get_user, update_user
user = get_user(current_user["username"])
secret = user.get("mfa_secret_pending")
if not secret:
raise HTTPException(400, "Aucune configuration MFA en cours. Commencez par /mfa/totp/setup")
if not verify_totp(secret, req.code):
raise HTTPException(400, "Code TOTP invalide")
# Generate recovery codes
recovery_codes = generate_recovery_codes()
hashed_codes = [hash_recovery_code(c) for c in recovery_codes]
# Enable MFA
update_user(current_user["username"], {
"mfa_enabled": True,
"mfa_secret": secret,
"mfa_method": "totp",
"mfa_recovery_codes": hashed_codes,
"mfa_secret_pending": None, # clear pending
})
logger.info(f"MFA enabled for user '{current_user['username']}'")
return {
"mfa_enabled": True,
"recovery_codes": recovery_codes, # shown once, client must display/save
}
@router.post("/mfa/totp/disable")
async def mfa_totp_disable(
req: MfaDisableRequest,
current_user=Depends(require_auth),
):
"""Disable MFA. Requires current password + valid TOTP code."""
from .user_store import get_user, update_user
user = get_user(current_user["username"])
if not user.get("mfa_enabled"):
raise HTTPException(400, "MFA non activé")
if not verify_password(req.password, user["password_hash"]):
raise HTTPException(400, "Mot de passe incorrect")
if not verify_totp(user["mfa_secret"], req.code):
raise HTTPException(400, "Code TOTP invalide")
update_user(current_user["username"], {
"mfa_enabled": False,
"mfa_secret": None,
"mfa_method": None,
"mfa_recovery_codes": [],
})
logger.info(f"MFA disabled for user '{current_user['username']}'")
return {"mfa_enabled": False}
# ── WebAuthn endpoints (ROADMAP #64) ─────────────────────────────────
def _preferred_mfa_method(user: dict) -> str:
"""Which second factor to offer at login: webauthn when keys exist, else totp."""
if user.get("webauthn_credentials"):
return "webauthn"
return "totp"
class WebauthnRegisterRequest(BaseModel):
credential: dict
label: str = ""
class WebauthnVerifyRequest(BaseModel):
username: str
credential: dict
remember_me: bool = False
class WebauthnRemoveRequest(BaseModel):
credential_id: str
password: str
@router.post("/mfa/webauthn/register/options")
async def mfa_webauthn_register_options(current_user=Depends(require_auth)):
"""Start WebAuthn key enrolment — returns publicKey creation options for the browser."""
from .webauthn_mfa import begin_registration
options = begin_registration(current_user["username"],
current_user.get("display_name", ""))
return {"options": options}
@router.post("/mfa/webauthn/register")
async def mfa_webauthn_register(
req: WebauthnRegisterRequest,
current_user=Depends(require_auth),
):
"""Verify the created credential, store it, and enable MFA if not already on.
Returns recovery codes when MFA is newly enabled (they were never issued).
"""
from datetime import datetime, timezone
from .user_store import get_user, update_user
from .webauthn_mfa import complete_registration
user = get_user(current_user["username"])
try:
record = complete_registration(current_user["username"], req.credential,
label=req.label)
except ValueError as e:
raise HTTPException(400, str(e))
except Exception as e:
logger.warning(f"WebAuthn registration failed for {current_user['username']}: {e}")
raise HTTPException(400, "Validation du credential WebAuthn échouée")
record["registered_at"] = datetime.now(timezone.utc).isoformat()
creds = list(user.get("webauthn_credentials", []))
creds = [c for c in creds if c.get("credential_id") != record["credential_id"]]
creds.append(record)
updates: dict = {"webauthn_credentials": creds}
issued_recovery: list[str] = []
if not user.get("mfa_enabled"):
issued_recovery = generate_recovery_codes()
updates.update({
"mfa_enabled": True,
"mfa_method": "webauthn",
"mfa_recovery_codes": [hash_recovery_code(c) for c in issued_recovery],
})
update_user(current_user["username"], updates)
logger.info(f"WebAuthn credential registered for user '{current_user['username']}' "
f"({record['label']})")
return {
"ok": True,
"credentials": user_credentials_response(creds),
"mfa_enabled": True,
"recovery_codes": issued_recovery,
}
def user_credentials_response(creds: list[dict]) -> list[dict]:
from .webauthn_mfa import credentials_for_api
return credentials_for_api(creds)
@router.get("/mfa/webauthn/credentials")
async def mfa_webauthn_list(current_user=Depends(require_auth)):
from .user_store import get_user
user = get_user(current_user["username"])
return {"credentials": user_credentials_response(user.get("webauthn_credentials", []))}
@router.post("/mfa/webauthn/credentials/remove")
async def mfa_webauthn_remove(
req: WebauthnRemoveRequest,
current_user=Depends(require_auth),
):
"""Remove a WebAuthn key. Requires password. Disables MFA if no second factor remains."""
from .user_store import get_user, update_user
from .webauthn_mfa import clear_pending
user = get_user(current_user["username"])
if not verify_password(req.password, user["password_hash"]):
raise HTTPException(400, "Mot de passe incorrect")
creds = [c for c in user.get("webauthn_credentials", [])
if c.get("credential_id") != req.credential_id]
if len(creds) == len(user.get("webauthn_credentials", [])):
raise HTTPException(404, "Credential inconnu")
updates: dict = {"webauthn_credentials": creds}
if not creds and not user.get("mfa_secret"):
updates.update({"mfa_enabled": False, "mfa_method": None, "mfa_recovery_codes": []})
elif not creds and user.get("mfa_secret"):
updates["mfa_method"] = "totp"
update_user(current_user["username"], updates)
clear_pending(current_user["username"])
return {"ok": True, "credentials": user_credentials_response(creds),
"mfa_enabled": bool(updates.get("mfa_enabled", user.get("mfa_enabled"))) and bool(creds or user.get("mfa_secret"))}
@router.post("/mfa/webauthn/options")
async def mfa_webauthn_login_options(body: dict = Body(...)):
"""Unauthenticated: begin the login assertion for a user with registered keys.
Enumeration-safe: always 200 — returns null options (caller falls back to
TOTP/recovery UI) when the user has no WebAuthn key or MFA is off.
"""
username = str(body.get("username", ""))
user = get_user(username)
creds = (user or {}).get("webauthn_credentials", [])
if not user or not user.get("mfa_enabled") or not creds:
return {"mfa_method": "totp", "options": None}
from .webauthn_mfa import begin_authentication
options = begin_authentication(username, creds)
if options is None:
return {"mfa_method": "totp", "options": None}
return {"mfa_method": "webauthn", "options": options}
@router.post("/mfa/webauthn/verify")
async def mfa_webauthn_verify(
body: WebauthnVerifyRequest,
response: Response,
request: Request,
):
"""Unauthenticated: verify the WebAuthn assertion and issue JWT tokens."""
from .user_store import get_user, update_user
from .webauthn_mfa import complete_authentication
user = get_user(body.username)
if not user:
hash_password("dummy_timing_protection")
raise HTTPException(401, "Identifiants invalides")
if not user.get("mfa_enabled"):
raise HTTPException(400, "MFA non activé pour cet utilisateur")
creds = user.get("webauthn_credentials", [])
try:
credential_id = body.credential.get("id", "")
stored = next((c for c in creds if c.get("credential_id") == credential_id), None)
if stored is None:
raise ValueError("Credential non enregistré")
new_count = complete_authentication(body.username, body.credential, stored)
except ValueError as e:
raise HTTPException(401, str(e))
except Exception as e:
logger.warning(f"WebAuthn verification failed for {body.username}: {e}")
raise HTTPException(401, "Vérification WebAuthn échouée")
updated = [dict(c) for c in creds]
for c in updated:
if c.get("credential_id") == body.credential.get("id"):
c["sign_count"] = new_count
update_user(body.username, {"webauthn_credentials": updated})
client_ip = request.client.host if request.client else "unknown"
rl_record_success(client_ip)
logger.info(f"User '{body.username}' logged in via WebAuthn")
return _issue_tokens(user, body.username, body.remember_me, response)
@router.get("/mfa/status")
async def mfa_status(current_user=Depends(require_auth)):
"""Return current user's MFA status."""
from .user_store import get_user
user = get_user(current_user["username"])
return {
"mfa_enabled": user.get("mfa_enabled", False),
"mfa_method": user.get("mfa_method"),
"totp_enabled": bool(user.get("mfa_secret")),
"webauthn_credentials": len(user.get("webauthn_credentials", [])),
}
@router.post("/mfa/totp/verify")
async def mfa_totp_verify(body: MfaVerifyRequest, response: Response, request: Request):
"""Verify TOTP code during login (second factor).
Called after login returns mfa_required=true.
On success: issues JWT tokens.
"""
from .user_store import get_user
user = get_user(body.username)
if not user:
# Timing-safe: simulate work
hash_password("dummy_timing_protection")
raise HTTPException(401, "Identifiants invalides")
if not user.get("mfa_enabled") or not user.get("mfa_secret"):
raise HTTPException(400, "MFA non activé pour cet utilisateur")
if not verify_totp(user["mfa_secret"], body.code):
raise HTTPException(401, "Code TOTP invalide")
# Clear IP rate limit on success
client_ip = request.client.host if request.client else "unknown"
rl_record_success(client_ip)
return _issue_tokens(user, body.username, body.remember_me, response)
@router.post("/mfa/recovery")
async def mfa_recovery_login(body: MfaRecoveryRequest, response: Response, request: Request):
"""Login with a recovery code (when TOTP device is unavailable).
Each recovery code is single-use.
"""
from .user_store import get_user, update_user
user = get_user(body.username)
if not user:
hash_password("dummy_timing_protection")
raise HTTPException(401, "Identifiants invalides")
if not user.get("mfa_enabled"):
raise HTTPException(400, "MFA non activé pour cet utilisateur")
hashed_codes = user.get("mfa_recovery_codes", [])
if not hashed_codes:
raise HTTPException(400, "Aucun code de récupération disponible")
idx = verify_recovery_code(body.recovery_code, hashed_codes)
if idx is None:
raise HTTPException(401, "Code de récupération invalide")
# Remove used recovery code (single-use)
hashed_codes.pop(idx)
update_user(body.username, {"mfa_recovery_codes": hashed_codes})
# Clear IP rate limit
client_ip = request.client.host if request.client else "unknown"
rl_record_success(client_ip)
logger.info(f"User '{body.username}' logged in via recovery code")
return _issue_tokens(user, body.username, False, response)
# ── Admin endpoints ───────────────────────────────────────────────────
@router.get("/admin/users")
+184
View File
@@ -0,0 +1,184 @@
# backend/auth/webauthn_mfa.py
# WebAuthn support for MFA (ROADMAP #64): security keys / platform biometrics.
# Thin wrapper over the `webauthn` library with an in-memory challenge store.
#
# Credentials are persisted in users.json under "webauthn_credentials":
# [{ "credential_id": <b64url>, "public_key": <b64url>, "sign_count": int,
# "transports": [...], "label": str, "registered_at": iso }]
from __future__ import annotations
import logging
import os
import secrets
import time
from typing import Any
from webauthn import (
generate_authentication_options,
generate_registration_options,
options_to_json,
verify_authentication_response,
verify_registration_response,
)
from webauthn.helpers import (
base64url_to_bytes,
bytes_to_base64url,
parse_authentication_credential_json,
parse_registration_credential_json,
)
from webauthn.helpers.structs import (
AuthenticatorSelectionCriteria,
ResidentKeyRequirement,
UserVerificationRequirement,
)
logger = logging.getLogger("obsigate.auth.webauthn")
# Challenge lifetime: clients have 3 minutes to complete the ceremony.
CHALLENGE_TTL_SECONDS = 180
# In-memory pending challenges: key -> (challenge_bytes, expires_at)
_pending: dict[str, tuple[bytes, float]] = {}
def rp_id() -> str:
return os.environ.get("OBSIGATE_WEBAUTHN_RP_ID", "localhost")
def rp_name() -> str:
return os.environ.get("OBSIGATE_WEBAUTHN_RP_NAME", "ObsiGate")
def expected_origins() -> list[str]:
raw = os.environ.get("OBSIGATE_WEBAUTHN_ORIGINS", "http://localhost")
return [o.strip() for o in raw.split(",") if o.strip()]
def _prune_expired() -> None:
now = time.time()
for key in [k for k, (_, exp) in _pending.items() if exp < now]:
_pending.pop(key, None)
def _store_challenge(key: str) -> bytes:
_prune_expired()
challenge = secrets.token_bytes(32)
_pending[key] = (challenge, time.time() + CHALLENGE_TTL_SECONDS)
return challenge
def _take_challenge(key: str) -> bytes | None:
"""Pop a challenge (single-use). Returns None if missing/expired."""
_prune_expired()
entry = _pending.pop(key, None)
return entry[0] if entry else None
def clear_pending(username: str) -> None:
"""Drop all pending challenges for a user (e.g. after enable/disable)."""
for key in [k for k in _pending if k.startswith(f"{username}:")]:
_pending.pop(key, None)
# ── Registration (enrol a key in settings) ─────────────────────────────
def begin_registration(username: str, display_name: str) -> dict:
options = generate_registration_options(
rp_id=rp_id(),
rp_name=rp_name(),
user_name=username,
user_display_name=display_name or username,
challenge=_store_challenge(f"{username}:register"),
authenticator_selection=AuthenticatorSelectionCriteria(
resident_key=ResidentKeyRequirement.PREFERRED,
user_verification=UserVerificationRequirement.PREFERRED,
),
)
return _finalize_options(options)
def complete_registration(username: str, credential_json: dict[str, Any],
label: str = "") -> dict:
challenge = _take_challenge(f"{username}:register")
if challenge is None:
raise ValueError("Session d'enregistrement expirée — recommencez")
credential = parse_registration_credential_json(credential_json)
verification = verify_registration_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=rp_id(),
expected_origin=expected_origins(),
)
transports = credential.response.transports or []
label = (label or str(credential_json.get("label") or "")).strip() or "Security key"
record = {
"credential_id": bytes_to_base64url(verification.credential_id),
"public_key": bytes_to_base64url(verification.credential_public_key),
"sign_count": int(verification.sign_count),
"transports": [str(t) for t in transports],
"label": label[:60],
}
return record
# ── Authentication (assertion at login) ────────────────────────────────
def begin_authentication(username: str, credentials: list[dict]) -> dict | None:
if not credentials:
return None
from webauthn.helpers.structs import PublicKeyCredentialDescriptor
allow = [
PublicKeyCredentialDescriptor(id=base64url_to_bytes(c["credential_id"]))
for c in credentials
]
options = generate_authentication_options(
rp_id=rp_id(),
challenge=_store_challenge(f"{username}:login"),
allow_credentials=allow,
)
return _finalize_options(options)
def complete_authentication(
username: str,
credential_json: dict[str, Any],
stored: dict,
) -> int:
"""Verify an assertion. Returns the new sign_count. Raises ValueError on failure."""
challenge = _take_challenge(f"{username}:login")
if challenge is None:
raise ValueError("Session expirée — rechargez la page")
credential = parse_authentication_credential_json(credential_json)
verification = verify_authentication_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=rp_id(),
expected_origin=expected_origins(),
credential_public_key=base64url_to_bytes(stored["public_key"]),
credential_current_sign_count=int(stored.get("sign_count", 0)),
)
return int(verification.new_sign_count)
def credentials_for_api(credentials: list[dict]) -> list[dict]:
"""Sanitized view for the settings UI (no public keys)."""
return [
{
"credential_id": c.get("credential_id"),
"label": c.get("label", "Security key"),
"transports": c.get("transports", []),
"registered_at": c.get("registered_at"),
}
for c in credentials
]
def _finalize_options(options) -> dict:
import json
return json.loads(options_to_json(options))
+256
View File
@@ -0,0 +1,256 @@
"""BooksLM — Context collection and caching for directory-scoped AI chat.
Collects markdown files from an Obsidian vault directory, applies secret
redaction, builds a system prompt with file contents, and caches results
for repeated queries.
"""
import hashlib
import json
import logging
import os
import time
from pathlib import Path
from typing import Any
from backend.secret_redactor import redact_file_content
logger = logging.getLogger("obsigate.bookslm")
# ── Configuration limits ──
BOOKSLM_MAX_FILES = int(os.getenv("BOOKSLM_MAX_FILES", "200"))
BOOKSLM_MAX_TOTAL_CHARS = int(os.getenv("BOOKSLM_MAX_TOTAL_CHARS", "200000"))
BOOKSLM_MAX_FILE_CHARS = int(os.getenv("BOOKSLM_MAX_FILE_CHARS", "30000"))
# ── Cache ──
_cache: dict[str, dict[str, Any]] = {}
_CACHE_TTL = 300 # seconds
def _cache_key(vault_path: Path, directory: str, file_mtimes: list[tuple[str, float]]) -> str:
"""Build a SHA-256 cache key from vault+directory+file modification times."""
raw = json.dumps({
"vault": str(vault_path),
"dir": directory,
"mtimes": sorted(file_mtimes),
}, sort_keys=True)
return hashlib.sha256(raw.encode()).hexdigest()
def _should_skip(name: str) -> bool:
"""Return True if this file/directory name should be skipped."""
skip_prefixes = (".",)
skip_names = {"_attachments", "node_modules", ".git", ".obsidian", "__pycache__"}
if name in skip_names:
return True
return bool(any(name.startswith(p) for p in skip_prefixes))
def _file_priority(path: Path) -> tuple[int, float]:
"""Sort key: README/index first, then by modification time descending.
Returns (priority_group, -mtime) so that:
- Group 0: README* and index* files (come first)
- Group 1: all other files (come after)
Within each group, newer files come first.
"""
name_lower = path.stem.lower()
if name_lower.startswith("readme") or name_lower.startswith("index"):
group = 0
else:
group = 1
try:
mtime = path.stat().st_mtime
except OSError:
mtime = 0.0
return (group, -mtime)
def collect_directory_context(vault_path: Path, directory: str) -> dict[str, Any]:
"""Walk a directory recursively, collect .md files with content.
Args:
vault_path: Absolute path to the vault root.
directory: Relative directory path within the vault (empty = root).
Returns:
Dict with keys: files, total_chars, file_count, directory_tree.
"""
target_dir = (vault_path / directory).resolve() if directory else vault_path.resolve()
vault_resolved = vault_path.resolve()
# Safety: ensure target is within vault
try:
target_dir.relative_to(vault_resolved)
except ValueError:
logger.warning(f"Directory outside vault: {target_dir}")
return {"files": [], "total_chars": 0, "file_count": 0, "directory_tree": ""}
if not target_dir.exists() or not target_dir.is_dir():
return {"files": [], "total_chars": 0, "file_count": 0, "directory_tree": ""}
# Check cache
file_mtimes: list[tuple[str, float]] = []
md_files: list[Path] = []
try:
for p in target_dir.rglob("*"):
# Skip hidden dirs/files and special dirs
parts = p.relative_to(target_dir).parts
if any(_should_skip(part) for part in parts):
continue
if p.is_file() and p.suffix.lower() == ".md":
md_files.append(p)
try:
file_mtimes.append((str(p.relative_to(target_dir)), p.stat().st_mtime))
except OSError:
file_mtimes.append((str(p.relative_to(target_dir)), 0.0))
except PermissionError:
logger.warning(f"Permission denied scanning {target_dir}")
return {"files": [], "total_chars": 0, "file_count": 0, "directory_tree": ""}
key = _cache_key(vault_resolved, directory, file_mtimes)
if key in _cache:
cached = _cache[key]
if time.time() - cached.get("_ts", 0) < _CACHE_TTL:
logger.debug(f"Cache hit for {directory}")
return {k: v for k, v in cached.items() if k != "_ts"}
# Sort by priority: README/index first, then by mtime descending
md_files.sort(key=_file_priority)
# Apply limits
collected: list[dict[str, Any]] = []
total_chars = 0
for p in md_files:
if len(collected) >= BOOKSLM_MAX_FILES:
break
if total_chars >= BOOKSLM_MAX_TOTAL_CHARS:
break
rel_path = str(p.relative_to(vault_resolved)).replace("\\", "/")
try:
content = p.read_text(encoding="utf-8", errors="replace")
except Exception as e:
logger.warning(f"Cannot read {rel_path}: {e}")
continue
# Redact secrets
content = redact_file_content(content, rel_path)
# Truncate if too long
if len(content) > BOOKSLM_MAX_FILE_CHARS:
content = content[:BOOKSLM_MAX_FILE_CHARS] + "\n\n[... tronqué]"
remaining = BOOKSLM_MAX_TOTAL_CHARS - total_chars
if len(content) > remaining:
content = content[:remaining] + "\n\n[... tronqué]"
title = p.stem.replace("-", " ").replace("_", " ").title()
file_type = "markdown"
collected.append({
"path": rel_path,
"title": title,
"content": content,
"type": file_type,
})
total_chars += len(content)
# Build directory tree
dir_tree = _build_directory_tree(target_dir, vault_resolved)
result = {
"files": collected,
"total_chars": total_chars,
"file_count": len(collected),
"directory_tree": dir_tree,
}
# Store in cache
_cache[key] = {**result, "_ts": time.time()}
logger.info(f"Collected {len(collected)} files ({total_chars} chars) from {directory or '/'}")
return result
def _build_directory_tree(target_dir: Path, vault_root: Path) -> str:
"""Build a text representation of the directory tree (dirs + .md files)."""
lines: list[str] = []
try:
for p in sorted(target_dir.rglob("*")):
parts = p.relative_to(target_dir).parts
if any(_should_skip(part) for part in parts):
continue
if p.is_dir():
depth = len(p.relative_to(target_dir).parts)
lines.append(f"{' ' * depth}{p.name}/")
elif p.is_file() and p.suffix.lower() == ".md":
depth = len(p.relative_to(target_dir).parts)
lines.append(f"{' ' * depth}{p.name}")
except PermissionError:
pass
return "\n".join(lines)
def build_system_prompt(context: dict[str, Any]) -> str:
"""Build a system prompt for directory-scoped AI chat.
Args:
context: Output of collect_directory_context().
Returns:
System prompt string with file contents.
"""
files = context.get("files", [])
file_count = context.get("file_count", 0)
total_chars = context.get("total_chars", 0)
# Rough token estimate (1 token ≈ 4 chars)
est_tokens = total_chars // 4
token_warning = ""
if est_tokens > 100_000:
token_warning = f"\n⚠️ Attention : le contexte est très volumineux (~{est_tokens:,} tokens estimés). Les réponses peuvent être moins précises.\n"
prompt = (
"Tu es un assistant de recherche documentaire. "
"Tu réponds UNIQUEMENT en te basant sur les documents fournis ci-dessous. "
"Cite tes sources avec le nom du fichier quand tu utilises une information. "
"Si l'information ne se trouve pas dans les documents, dis-le clairement."
f"\n\n📚 Contexte : {file_count} fichier(s) ({total_chars:,} caractères)"
f"{token_warning}\n"
)
# Directory tree
tree = context.get("directory_tree", "")
if tree:
prompt += f"\n📂 Arborescence du dossier :\n```\n{tree}\n```\n"
# File contents
prompt += "\n---\n"
for f in files:
prompt += f"\n## 📄 {f['title']} (`{f['path']}`)\n\n{f['content']}\n\n---\n"
prompt += "\nFin du contexte. Réponds à la question de l'utilisateur en te basant uniquement sur ces documents."
return prompt
def invalidate_cache(vault_path: Path | None = None, directory: str | None = None) -> int:
"""Invalidate cache entries.
Args:
vault_path: If provided, only invalidate entries for this vault.
directory: If provided, only invalidate entries for this directory.
Returns:
Number of cache entries removed.
"""
if vault_path is None and directory is None:
count = len(_cache)
_cache.clear()
return count
to_remove = list(_cache)
for k in to_remove:
del _cache[k]
return len(to_remove)
+172
View File
@@ -0,0 +1,172 @@
"""BooksLM API routes — directory-scoped AI chat for Obsidian vaults."""
import json
import logging
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from backend.auth.middleware import check_vault_access, require_auth
from backend.bookslm import build_system_prompt, collect_directory_context
from backend.indexer import get_vault_data
logger = logging.getLogger("obsigate.bookslm_routes")
router = APIRouter(prefix="/api/ai/bookslm", tags=["BooksLM"])
# ── Request models ──
class BooksLMContextRequest(BaseModel):
vault: str = Field(description="Vault name")
directory: str = Field(default="", description="Relative directory path within the vault")
class BooksLMChatRequest(BaseModel):
vault: str = Field(description="Vault name")
directory: str = Field(default="", description="Relative directory path within the vault")
message: str = Field(description="User message")
conversation_history: list[dict[str, str]] = Field(
default_factory=list,
description="Previous conversation turns [{role, content}]",
)
provider: str | None = Field(
default=None,
description="AI provider override (e.g. 'deepseek', 'openrouter', 'gemini', 'nvidia', 'xiaomi', 'mistral', 'qwencloud'). "
"If not set, uses DEFAULT_PROVIDER.",
)
model: str | None = Field(
default=None,
description="Model name to use for this request. If not set, uses the provider's default model.",
)
# ── Endpoints ──
@router.post("/context")
async def api_bookslm_context(
req: BooksLMContextRequest,
current_user=Depends(require_auth),
):
"""Collect directory context for BooksLM.
Returns file list, content, and metadata for the specified directory.
"""
if not check_vault_access(req.vault, current_user):
raise HTTPException(status_code=403, detail=f"Accès refusé à la vault '{req.vault}'")
vault_data = get_vault_data(req.vault)
if not vault_data:
raise HTTPException(status_code=404, detail=f"Vault '{req.vault}' not found")
vault_path = Path(vault_data["path"])
context = collect_directory_context(vault_path, req.directory)
return context
@router.post("/chat")
async def api_bookslm_chat(
req: BooksLMChatRequest,
current_user=Depends(require_auth),
):
"""Chat with AI about directory contents (BooksLM).
Builds context from the directory, then sends the user message
with a system prompt containing all file contents to the AI provider.
Returns an SSE stream with the response.
"""
if not check_vault_access(req.vault, current_user):
raise HTTPException(status_code=403, detail=f"Accès refusé à la vault '{req.vault}'")
vault_data = get_vault_data(req.vault)
if not vault_data:
raise HTTPException(status_code=404, detail=f"Vault '{req.vault}' not found")
vault_path = Path(vault_data["path"])
# Collect context
context = collect_directory_context(vault_path, req.directory)
if context["file_count"] == 0:
raise HTTPException(status_code=404, detail="Aucun fichier markdown trouvé dans ce dossier")
# Build system prompt
system_prompt = build_system_prompt(context)
# Call AI provider
from backend.ai import DEFAULT_PROVIDER, PROVIDERS, _call_deepseek_openrouter, _call_gemini
# Build messages with conversation history
messages_text = ""
if req.conversation_history:
for turn in req.conversation_history:
role = turn.get("role", "user")
content = turn.get("content", "")
if role == "user":
messages_text += f"\n\nUtilisateur : {content}"
elif role == "assistant":
messages_text += f"\n\nAssistant : {content}"
# Current message
user_prompt = req.message
if messages_text:
user_prompt = f"Historique de la conversation :{messages_text}\n\nQuestion actuelle : {req.message}"
async def generate_sse():
try:
# Resolve provider: explicit override wins, else default.
# Fall back to first available if the requested one isn't configured.
cfg_name = (req.provider or DEFAULT_PROVIDER).lower()
if cfg_name not in PROVIDERS or not PROVIDERS[cfg_name].get("api_key"):
# Try next available provider
for pname, pcfg in PROVIDERS.items():
if pcfg.get("api_key") and pname != "gemini":
cfg_name = pname
break
else:
# No provider available at all
err = "Aucun fournisseur AI configuré (clés API manquantes)"
error_data = json.dumps({"error": err}, ensure_ascii=False)
yield f"event: error\ndata: {error_data}\n\n"
return
# Optional per-request model override
original_model = None
if req.model and cfg_name in PROVIDERS:
original_model = PROVIDERS[cfg_name].get("model")
PROVIDERS[cfg_name]["model"] = req.model
try:
if cfg_name == "gemini":
response = await _call_gemini(user_prompt, system_prompt, temperature=0.3, max_tokens=4096)
else:
response = await _call_deepseek_openrouter(
user_prompt, system_prompt,
provider=cfg_name,
temperature=0.3,
max_tokens=4096,
)
finally:
# Restore the original model so other calls aren't affected
if original_model is not None and cfg_name in PROVIDERS:
PROVIDERS[cfg_name]["model"] = original_model
# Send the full response as a single SSE event
data = json.dumps({"token": response, "provider": cfg_name, "model": req.model or PROVIDERS.get(cfg_name, {}).get("model", "")}, ensure_ascii=False)
yield f"event: message\ndata: {data}\n\n"
yield "event: done\ndata: {}\n\n"
except Exception as e:
logger.error(f"BooksLM chat error: {e}")
error_data = json.dumps({"error": str(e)}, ensure_ascii=False)
yield f"event: error\ndata: {error_data}\n\n"
return StreamingResponse(
generate_sse(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
+431
View File
@@ -0,0 +1,431 @@
"""
Export utilities for ObsiGate — standalone HTML, Markdown bundle (.zip) and ePub.
Each function converts vault content (markdown notes) into a self-contained
downloadable artifact. Rendering reuses ``mistune`` (already a core dependency)
so no extra markdown engine is required. The ePub generator builds a minimal
but valid EPUB 3 container by hand (``zipfile`` only) so there is no hard
dependency on ``ebooklib``.
All functions raise :class:`ExportError` on any failure (missing file, binary
content, unreadable source, ...) so callers can translate to HTTP errors.
"""
from __future__ import annotations
import base64
import datetime
import html as html_mod
import io
import logging
import mimetypes
import re
import unicodedata
import zipfile
from pathlib import Path
import frontmatter
import mistune
logger = logging.getLogger("obsigate.export")
class ExportError(Exception):
"""Raised when an export operation cannot be completed."""
# Cached mistune renderer (singleton) — mirrors backend.main's configuration.
_markdown = mistune.create_markdown(
escape=False,
plugins=["table", "strikethrough", "footnotes", "task_lists"],
)
# File extensions considered "safe" text files for markdown-like exports.
_MARKDOWN_EXTS = {".md", ".markdown", ".mdown", ".mkd", ".txt"}
_HTML_CSS = """
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
max-width: 760px;
margin: 40px auto;
padding: 0 24px;
line-height: 1.7;
color: #1a1a2e;
font-size: 16px;
}
h1 { font-size: 28px; border-bottom: 2px solid #333; padding-bottom: 8px; margin-top: 0; }
h2 { font-size: 22px; margin-top: 28px; border-bottom: 1px solid #ddd; padding-bottom: 4px; }
h3 { font-size: 18px; margin-top: 24px; }
h4, h5, h6 { font-size: 16px; margin-top: 20px; }
p { margin: 10px 0; }
pre {
background: #f5f5f5;
border: 1px solid #e0e0e0;
border-radius: 6px;
padding: 12px 16px;
font-size: 14px;
overflow-x: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
code { font-size: 14px; background: #f5f5f5; padding: 2px 5px; border-radius: 3px; }
pre code { background: none; padding: 0; }
a { color: #4f46e5; text-decoration: none; }
a:hover { text-decoration: underline; }
img { max-width: 100%; border-radius: 4px; }
blockquote { border-left: 3px solid #ccc; padding-left: 14px; color: #555; margin: 12px 0; }
table { border-collapse: collapse; width: 100%; margin: 12px 0; }
th, td { border: 1px solid #ddd; padding: 6px 10px; text-align: left; font-size: 14px; }
th { background: #f0f0f0; font-weight: 600; }
ul, ol { margin: 8px 0; padding-left: 24px; }
li { margin: 2px 0; }
hr { border: none; border-top: 1px solid #ddd; margin: 20px 0; }
nav.export-nav {
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 14px 18px;
margin: 16px 0 28px;
background: #fafafa;
}
nav.export-nav h2 { border: none; margin: 0 0 8px; font-size: 15px; text-transform: uppercase; letter-spacing: .04em; }
nav.export-nav ul { margin: 0; padding-left: 20px; }
.wikilink-missing { color: #c0392b; }
"""
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _slugify(text: str) -> str:
"""URL-safe slug from arbitrary text (Unicode-aware)."""
text = html_mod.unescape(re.sub(r"<[^>]+>", "", text))
text = text.lower()
text = unicodedata.normalize("NFD", text)
text = "".join(ch for ch in text if not unicodedata.combining(ch))
cleaned = []
for ch in text:
if unicodedata.category(ch).startswith(("L", "N")) or ch in (" ", "-"):
cleaned.append(ch)
text = re.sub(r"\s+", "-", "".join(cleaned))
text = re.sub(r"-+", "-", text)
return text.strip("-") or "document"
def _resolve(vault_path: Path, file_path: Path | str) -> Path:
"""Resolve *file_path* against *vault_path*, accepting absolute or relative.
Returns an absolute :class:`Path`. Does not require the file to exist.
"""
file_path = Path(file_path)
if file_path.is_absolute():
return file_path
return (Path(vault_path) / file_path).resolve()
def _read_text(path: Path) -> str:
"""Read a text file, raising :class:`ExportError` on missing/binary content."""
if not path.exists() or not path.is_file():
raise ExportError(f"File not found: {path}")
try:
raw = path.read_bytes()
except OSError as e:
raise ExportError(f"Cannot read file {path}: {e}") from e
if b"\x00" in raw[:4096]:
raise ExportError(f"File appears to be binary: {path}")
return raw.decode("utf-8", errors="replace")
def _strip_frontmatter(text: str) -> tuple[str, dict]:
"""Split frontmatter from a markdown document.
Returns ``(body, metadata)``. Falls back gracefully when no frontmatter.
"""
try:
post = frontmatter.loads(text)
return post.content, dict(post.metadata or {})
except Exception:
return text, {}
def _safe_name(name: str) -> str:
"""ASCII-safe, filename-safe download name."""
cleaned = "".join(
c for c in name if c.isascii() and (c.isalnum() or c in " _-.")
).strip()
return cleaned or "document"
def _collect_markdown_files(vault_path: Path) -> list[Path]:
"""List all markdown files in the vault, sorted by relative path."""
vault_path = Path(vault_path)
results = []
if not vault_path.is_dir():
return results
for p in sorted(vault_path.rglob("*")):
if p.is_file() and p.suffix.lower() in _MARKDOWN_EXTS:
results.append(p)
return results
# ---------------------------------------------------------------------------
# Markdown → HTML (shared by HTML and ePub exporters)
# ---------------------------------------------------------------------------
def _inline_images(md: str, file_dir: Path, vault_path: Path) -> str:
"""Replace image references with base64 data URIs.
Supports standard markdown ``![alt](src)`` and Obsidian embeds
``![[image.png]]`` / ``![[image.png|300]]``. Sources are resolved relative
to the note's directory, then the vault root.
"""
candidates = [file_dir, vault_path]
def _to_data_uri(src: str) -> str:
src = src.strip().strip("<>")
if src.startswith(("http://", "https://", "data:")):
return src # leave remote/data URLs untouched
src_path = None
for base in candidates:
candidate = (base / src).resolve()
if candidate.is_file():
src_path = candidate
break
if src_path is None:
return src # unresolved — leave as-is
try:
data = src_path.read_bytes()
mime = mimetypes.guess_type(str(src_path))[0] or "application/octet-stream"
b64 = base64.b64encode(data).decode("ascii")
return f"data:{mime};base64,{b64}"
except OSError:
return src
# Obsidian embeds: ![[path]] or ![[path|size]]
def _embed(match):
inner = match.group(1).strip()
target = inner.split("|", 1)[0].strip()
return f"![{target}]({_to_data_uri(target)})"
md = re.sub(r"!\[\[([^\]]+)\]\]", _embed, md)
# Standard markdown images
def _img(match):
alt = match.group(1)
src = match.group(2)
return f"![{alt}]({_to_data_uri(src)})"
md = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", _img, md)
return md
def _convert_wikilinks(md: str, vault_path: Path, current: Path) -> str:
"""Convert ``[[Note]]`` / ``[[Note|display]]`` to cross-file HTML links."""
md_files = {p.stem.lower(): p for p in _collect_markdown_files(vault_path)}
def _replace(match):
target = match.group(1).strip()
display = (match.group(2) or target).strip()
# Same-document anchor
if target.startswith("#"):
return f'<a href="#{_slugify(target[1:])}">{html_mod.escape(display)}</a>'
# Resolve to another file — link to its exported .html sibling
key = Path(target).stem.lower()
if key in md_files:
href = f"{_slugify(md_files[key].stem)}.html"
return f'<a href="{href}">{html_mod.escape(display)}</a>'
return f'<span class="wikilink-missing">{html_mod.escape(display)}</span>'
return re.sub(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]", _replace, md)
def _render_body(md: str, file_dir: Path, vault_path: Path, current: Path) -> str:
"""Render raw markdown to an HTML fragment (images inlined, wikilinks resolved)."""
md = _inline_images(md, file_dir, vault_path)
md = _convert_wikilinks(md, vault_path, current)
return _markdown(md)
def _build_nav(vault_path: Path, current: Path) -> str:
"""Build a navigation block linking to every other markdown note in the vault."""
items = []
for p in _collect_markdown_files(vault_path):
if p.resolve() == Path(current).resolve():
continue
stem = p.stem
items.append(f'<li><a href="{_slugify(stem)}.html">{html_mod.escape(stem)}</a></li>')
if not items:
return ""
return (
'<nav class="export-nav"><h2>Notes</h2><ul>'
+ "".join(items)
+ "</ul></nav>"
)
# ---------------------------------------------------------------------------
# Public exporters
# ---------------------------------------------------------------------------
def export_html(vault_path: Path, file_path: Path) -> bytes:
"""Convert a markdown note into a standalone HTML document.
Images are inlined as base64 data URIs, wikilinks become cross-file links,
and a navigation block lists every other note in the vault.
Returns:
UTF-8 encoded HTML as bytes.
"""
vault_path = Path(vault_path)
path = _resolve(vault_path, file_path)
raw = _read_text(path)
body, metadata = _strip_frontmatter(raw)
title = str(metadata.get("title") or path.stem)
rendered = _render_body(body, path.parent, vault_path, path)
nav = _build_nav(vault_path, path)
html_doc = f"""<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="ObsiGate">
<title>{html_mod.escape(title)}</title>
<style>{_HTML_CSS}</style>
</head>
<body>
<header><h1>{html_mod.escape(title)}</h1></header>
{nav}
{rendered}
</body>
</html>"""
return html_doc.encode("utf-8")
def export_md_bundle(vault_path: Path, directory_path: Path) -> bytes:
"""Zip a directory (or single file) of markdown, preserving structure.
Returns:
ZIP archive as bytes.
"""
vault_path = Path(vault_path)
path = _resolve(vault_path, directory_path)
if not path.exists():
raise ExportError(f"Path not found: {path}")
buffer = io.BytesIO()
try:
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
if path.is_dir():
base = path
for p in sorted(path.rglob("*")):
if p.is_file():
arcname = p.relative_to(base).as_posix()
zf.write(p, arcname=arcname)
# Avoid emitting an empty (invalid) zip for an empty directory
if not any(p.is_file() for p in path.rglob("*")):
zf.writestr(".empty", "")
else:
zf.write(path, arcname=path.name)
except OSError as e:
raise ExportError(f"Cannot create bundle: {e}") from e
return buffer.getvalue()
def export_epub(vault_path: Path, file_path: Path) -> bytes:
"""Convert a markdown note into a minimal, valid EPUB 3 container.
Uses only ``zipfile`` + ``mistune`` (no ``ebooklib`` dependency). Images
are inlined as base64 so the ePub is fully self-contained.
Returns:
EPUB archive as bytes.
"""
vault_path = Path(vault_path)
path = _resolve(vault_path, file_path)
raw = _read_text(path)
body, metadata = _strip_frontmatter(raw)
title = str(metadata.get("title") or path.stem)
author = str(metadata.get("author") or "ObsiGate")
rendered = _render_body(body, path.parent, vault_path, path)
uid = f"obsigate-{_slugify(title)}-{int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())}"
xhtml = f"""<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<title>{html_mod.escape(title)}</title>
<style>{_HTML_CSS}</style>
</head>
<body>
<h1>{html_mod.escape(title)}</h1>
{rendered}
</body>
</html>"""
# EPUB requires a valid XHTML-ish body; strip our HTML5-only doctype is not
# needed since we emit XML directly above. Escape any bare ampersands in
# text nodes outside tags is delegated to mistune's own escaping.
content_opf = f"""<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="bookid">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:identifier id="bookid">{html_mod.escape(uid)}</dc:identifier>
<dc:title>{html_mod.escape(title)}</dc:title>
<dc:creator>{html_mod.escape(author)}</dc:creator>
<dc:language>fr</dc:language>
<meta property="dcterms:modified">{datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}</meta>
</metadata>
<manifest>
<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
<item id="chapter1" href="chapter1.xhtml" media-type="application/xhtml+xml"/>
</manifest>
<spine toc="ncx">
<itemref idref="chapter1"/>
</spine>
</package>"""
toc_ncx = f"""<?xml version="1.0" encoding="utf-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
<head>
<meta name="dtb:uid" content="{html_mod.escape(uid)}"/>
</head>
<docTitle><text>{html_mod.escape(title)}</text></docTitle>
<navMap>
<navPoint id="navpoint-1" playOrder="1">
<navLabel><text>{html_mod.escape(title)}</text></navLabel>
<content src="chapter1.xhtml"/>
</navPoint>
</navMap>
</ncx>"""
container_xml = """<?xml version="1.0" encoding="utf-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>"""
buffer = io.BytesIO()
try:
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
# `mimetype` must be the first entry, stored (uncompressed).
zf.writestr(
zipfile.ZipInfo("mimetype"),
"application/epub+zip",
compress_type=zipfile.ZIP_STORED,
)
zf.writestr("META-INF/container.xml", container_xml)
zf.writestr("OEBPS/content.opf", content_opf)
zf.writestr("OEBPS/toc.ncx", toc_ncx)
zf.writestr("OEBPS/chapter1.xhtml", xhtml)
except OSError as e:
raise ExportError(f"Cannot create ePub: {e}") from e
return buffer.getvalue()
+17 -9
View File
@@ -546,19 +546,27 @@ def _index_single_file_sync(vault_name: str, vault_path: str, file_path: str, va
stat = fpath.stat()
modified = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
raw = fpath.read_text(encoding="utf-8", errors="replace")
# PDF handling — binary, must go through pdf_reader (same as _scan_vault)
tags: list[str] = []
title = fpath.stem.replace("-", " ").replace("_", " ")
content_preview = raw[:200].strip()
if ext == ".pdf":
from backend.pdf_reader import extract_pdf_metadata, extract_pdf_text
raw = extract_pdf_text(fpath, max_chars=SEARCH_CONTENT_LIMIT)
pdf_meta = extract_pdf_metadata(fpath)
title = pdf_meta.get("title") or title
content_preview = raw[:200].strip()
else:
raw = fpath.read_text(encoding="utf-8", errors="replace")
content_preview = raw[:200].strip()
if ext == ".md":
post = parse_markdown_file(raw)
tags = _extract_tags(post)
inline_tags = _extract_inline_tags(post.content)
tags = list(set(tags) | set(inline_tags))
title = _extract_title(post, fpath)
content_preview = post.content[:200].strip()
if ext == ".md":
post = parse_markdown_file(raw)
tags = _extract_tags(post)
inline_tags = _extract_inline_tags(post.content)
tags = list(set(tags) | set(inline_tags))
title = _extract_title(post, fpath)
content_preview = post.content[:200].strip()
return {
"path": str(relative).replace("\\", "/"),
+388 -34
View File
@@ -19,7 +19,7 @@ from typing import Any
import frontmatter
import mistune
from fastapi import Body, Depends, FastAPI, HTTPException, Query
from fastapi import Body, Depends, FastAPI, HTTPException, Query, Request
from fastapi.responses import FileResponse, HTMLResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
@@ -287,9 +287,11 @@ class ReloadResponse(BaseModel):
class HealthResponse(BaseModel):
"""Application health status."""
status: str = Field(description="Health status ('ok' or 'error')")
version: str = Field(description="Application version")
version: str = Field(description="Application version (x.y.z — latest release tag)")
vaults: int = Field(description="Number of configured vaults")
total_files: int = Field(description="Total indexed files across all vaults")
git_describe: str = Field(default="", description="Full git describe string (commits beyond tag), empty if no git")
git_commit: str = Field(default="", description="Short HEAD commit hash, empty if no git")
class DirectoryCreateRequest(BaseModel):
@@ -645,7 +647,7 @@ async def lifespan(app: FastAPI):
_search_executor = None
from backend.version import get_version
from backend.version import get_git_commit, get_git_describe, get_version
app = FastAPI(title="ObsiGate", version=get_version(), lifespan=lifespan)
@@ -662,11 +664,11 @@ class SSESafeGZipMiddleware(GZipMiddleware):
We detect SSE endpoints by path and bypass compression entirely.
"""
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http" and scope.get("path") == "/api/events":
# Bypass GZip: passthrough directly to the inner app
await self.app(scope, receive, send)
else:
await super().__call__(scope, receive, send)
if scope["type"] == "http" and scope.get("path") in ("/api/events", "/api/admin/stream"):
# Bypass GZip: passthrough directly to the inner app
await self.app(scope, receive, send)
else:
await super().__call__(scope, receive, send)
app.add_middleware(SSESafeGZipMiddleware, minimum_size=1000)
@@ -686,12 +688,16 @@ from backend.secret_redactor import redact_file_content
# Lazy import: WeasyPrint PDF export (requires GTK, may not be available everywhere)
try:
from backend.pdf_export import build_pdf_html, generate_pdf
except OSError:
except Exception: # pragma: no cover - WeasyPrint/GTK missing
generate_pdf = None # type: ignore[assignment]
build_pdf_html = None # type: ignore[assignment]
import logging
logging.getLogger("obsigate").warning("PDF export unavailable (WeasyPrint/GTK not found)")
# Multi-format export (HTML / MD bundle / ePub) — pure Python, no heavy deps.
from backend.ai_routes import router as ai_router
from backend.bookslm_routes import router as bookslm_router
from backend.export import ExportError, export_epub, export_html, export_md_bundle
from backend.saved_searches import delete_saved, get_saved, save_search
from backend.share import (
create_share,
@@ -711,6 +717,15 @@ from backend.webhooks import (
app.include_router(auth_router)
app.include_router(ai_router)
app.include_router(bookslm_router)
# Admin Dashboard endpoints (system stats, audit logs, backups, stream)
try:
from backend.admin import router as admin_router
app.include_router(admin_router)
logger.info("Admin dashboard router mounted at /api/admin/*")
except ImportError as e:
logger.warning(f"Could not load admin dashboard router: {e}")
# Resolve frontend path relative to this file
FRONTEND_DIR = Path(__file__).resolve().parent.parent / "frontend"
@@ -1016,6 +1031,8 @@ async def api_health():
"version": app.version,
"vaults": len(index),
"total_files": total_files,
"git_describe": get_git_describe(),
"git_commit": get_git_commit(),
}
@@ -1445,6 +1462,93 @@ async def api_file_pdf(vault_name: str, path: str = Query(..., description="Rela
return Response(content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="{safe_name}.pdf"'})
# ---------------------------------------------------------------------------
# Multi-format export endpoints (HTML / Markdown bundle / ePub)
# ---------------------------------------------------------------------------
def _resolve_export_target(vault_name: str, path: str, current_user: dict) -> tuple[Path, Path]:
"""Resolve a vault + relative path into (vault_root, absolute file path).
Enforces auth (vault access) and path traversal protection.
"""
if not check_vault_access(vault_name, current_user):
raise HTTPException(status_code=403, detail=f"Accès refusé à la vault '{vault_name}'")
vault_data = get_vault_data(vault_name)
if not vault_data:
raise HTTPException(status_code=404, detail=f"Vault '{vault_name}' not found")
vault_root = Path(vault_data["path"])
target = _resolve_safe_path(vault_root, path)
return vault_root, target
@app.get("/api/export/html")
async def api_export_html(
vault: str = Query(..., description="Vault name"),
path: str = Query(..., description="Relative path to file"),
current_user=Depends(require_auth),
):
"""Export a markdown note as a standalone HTML file."""
try:
vault_root, target = _resolve_export_target(vault, path, current_user)
html_bytes = export_html(vault_root, target)
except ExportError as e:
raise HTTPException(status_code=400, detail=str(e))
record_open(current_user.get("username"), vault, path)
safe_name = _safe_export_name(target.stem)
return Response(
content=html_bytes,
media_type="text/html; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{safe_name}.html"'},
)
@app.get("/api/export/md-bundle")
async def api_export_md_bundle(
vault: str = Query(..., description="Vault name"),
path: str = Query(..., description="Relative path to directory or file"),
current_user=Depends(require_auth),
):
"""Export a directory (or single file) of markdown as a ZIP bundle."""
try:
vault_root, target = _resolve_export_target(vault, path, current_user)
zip_bytes = export_md_bundle(vault_root, target)
except ExportError as e:
raise HTTPException(status_code=400, detail=str(e))
safe_name = _safe_export_name(target.name)
return Response(
content=zip_bytes,
media_type="application/zip",
headers={"Content-Disposition": f'attachment; filename="{safe_name}.zip"'},
)
@app.get("/api/export/epub")
async def api_export_epub(
vault: str = Query(..., description="Vault name"),
path: str = Query(..., description="Relative path to file"),
current_user=Depends(require_auth),
):
"""Export a markdown note as an ePub document."""
try:
vault_root, target = _resolve_export_target(vault, path, current_user)
epub_bytes = export_epub(vault_root, target)
except ExportError as e:
raise HTTPException(status_code=400, detail=str(e))
record_open(current_user.get("username"), vault, path)
safe_name = _safe_export_name(target.stem)
return Response(
content=epub_bytes,
media_type="application/epub+zip",
headers={"Content-Disposition": f'attachment; filename="{safe_name}.epub"'},
)
def _safe_export_name(name: str) -> str:
"""ASCII-safe, filename-safe download name (falls back to 'document')."""
cleaned = "".join(c for c in name if c.isascii() and (c.isalnum() or c in " _-.")).strip()
return cleaned or "document"
@app.put("/api/file/{vault_name}/save", response_model=FileSaveResponse)
async def api_file_save(
vault_name: str,
@@ -2623,8 +2727,17 @@ async def api_file(vault_name: str, path: str = Query(..., description="Relative
@app.get("/api/file/{vault_name}/pdf/stream")
async def api_pdf_stream(vault_name: str, path: str = Query(...)):
"""Stream a PDF file with Content-Type: application/pdf for inline browser viewing."""
async def api_pdf_stream(
request: Request,
vault_name: str,
path: str = Query(...),
current_user=Depends(require_auth),
):
"""Stream a PDF file with Content-Type: application/pdf for inline browser viewing.
Supports HTTP Range requests (206 Partial Content) so browsers can
progressively render large PDFs in the native viewer.
"""
if not check_vault_access(vault_name, current_user):
raise HTTPException(status_code=403, detail=f"Accès refusé à la vault '{vault_name}'")
vault_data = get_vault_data(vault_name)
@@ -2636,9 +2749,100 @@ async def api_pdf_stream(vault_name: str, path: str = Query(...)):
raise HTTPException(status_code=404, detail=f"File not found: {path}")
if file_path.suffix.lower() != ".pdf":
raise HTTPException(status_code=400, detail="Not a PDF file")
from fastapi.responses import FileResponse
file_size = file_path.stat().st_size
range_header = request.headers.get("range")
if range_header:
# Parse "bytes=start-end" (single range only; multi-range is not used by viewers)
m = re.match(r"bytes=(\d*)-(\d*)", range_header)
if not m:
raise HTTPException(status_code=416,
headers={"Content-Range": f"bytes */{file_size}"})
start_s, end_s = m.group(1), m.group(2)
if start_s == "" and end_s == "":
raise HTTPException(status_code=416,
headers={"Content-Range": f"bytes */{file_size}"})
if start_s == "":
# suffix range: last N bytes
length = min(int(end_s), file_size)
start = file_size - length
end = file_size - 1
else:
start = int(start_s)
end = int(end_s) if end_s else file_size - 1
end = min(end, file_size - 1)
if start > end or start >= file_size:
raise HTTPException(status_code=416,
headers={"Content-Range": f"bytes */{file_size}"})
chunk_size = end - start + 1
async def _partial():
# Open + reads offloaded to threads (avoid blocking the event loop — ASYNC230)
f = await asyncio.to_thread(open, str(file_path), "rb")
try:
await asyncio.to_thread(f.seek, start)
remaining = chunk_size
while remaining > 0:
data = await asyncio.to_thread(f.read, min(64 * 1024, remaining))
if not data:
break
remaining -= len(data)
yield data
finally:
await asyncio.to_thread(f.close)
return StreamingResponse(
_partial(),
status_code=206,
media_type="application/pdf",
headers={
"Content-Range": f"bytes {start}-{end}/{file_size}",
"Accept-Ranges": "bytes",
"Content-Length": str(chunk_size),
"Content-Disposition": f'inline; filename="{file_path.name}"',
},
)
return FileResponse(str(file_path), media_type="application/pdf", headers={
"Content-Disposition": f"inline; filename=\"{file_path.name}\""})
"Accept-Ranges": "bytes",
"Content-Disposition": f'inline; filename="{file_path.name}"'})
@app.get("/api/file/{vault_name}/pdf/info")
async def api_pdf_info(
vault_name: str,
path: str = Query(..., description="Relative path to PDF file"),
current_user=Depends(require_auth),
):
"""Return PDF metadata (pages, title, author, size) without the document content.
Lets the UI display file info before loading a heavy PDF into the viewer.
"""
if not check_vault_access(vault_name, current_user):
raise HTTPException(status_code=403, detail=f"Accès refusé à la vault '{vault_name}'")
vault_data = get_vault_data(vault_name)
if not vault_data:
raise HTTPException(status_code=404, detail=f"Vault '{vault_name}' not found")
vault_root = Path(vault_data["path"])
file_path = _resolve_safe_path(vault_root, path)
if not file_path.exists() or not file_path.is_file():
raise HTTPException(status_code=404, detail=f"File not found: {path}")
if file_path.suffix.lower() != ".pdf":
raise HTTPException(status_code=400, detail="Not a PDF file")
from backend.pdf_reader import extract_pdf_metadata
meta = extract_pdf_metadata(file_path)
stat = file_path.stat()
return {
"vault": vault_name,
"path": path,
"pages": meta.get("pages", 0),
"title": meta.get("title") or file_path.name,
"author": meta.get("author", ""),
"size_bytes": stat.st_size,
}
@app.get("/api/search", response_model=SearchResponse)
@@ -3903,7 +4107,7 @@ async def api_get_ai_keys(current_user=Depends(require_admin)):
"""Return stored AI keys (values masked)."""
keys = _read_ai_keys()
masked = {}
for k in ["DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY"]:
for k in ["DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY", "NVIDIA_API_KEY", "QWENCLOUD_API_KEY", "XIAOMI_API_KEY", "MISTRAL_API_KEY"]:
val = keys.get(k, "") or os.environ.get(k, "")
if val:
masked[k] = val[:4] + "..." + val[-4:] if len(val) > 8 else "***"
@@ -3915,21 +4119,53 @@ async def api_get_ai_keys(current_user=Depends(require_admin)):
async def api_set_ai_keys(body: dict = Body(...), current_user=Depends(require_admin)):
"""Save AI keys. Pass {"DEEPSEEK_API_KEY":"sk-...","OPENROUTER_API_KEY":"...","GEMINI_API_KEY":"..."}"""
keys = _read_ai_keys()
for k in ["DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY"]:
for k in ["DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY", "NVIDIA_API_KEY", "QWENCLOUD_API_KEY", "XIAOMI_API_KEY", "MISTRAL_API_KEY"]:
if body.get(k):
keys[k] = body[k]
_write_ai_keys(keys)
logger.info("AI keys updated")
return {"status": "ok"}
@app.delete("/api/config/ai-keys/{provider_env}")
async def api_delete_ai_key(provider_env: str, current_user=Depends(require_admin)):
"""Delete a specific AI provider key from storage."""
allowed = {"DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY",
"NVIDIA_API_KEY", "QWENCLOUD_API_KEY", "XIAOMI_API_KEY", "MISTRAL_API_KEY"}
key_name = provider_env.upper()
if key_name not in allowed:
raise HTTPException(status_code=400, detail=f"Clé inconnue: {provider_env}")
keys = _read_ai_keys()
if key_name in keys:
del keys[key_name]
_write_ai_keys(keys)
# Also clear from env at runtime so get_ai_key() no longer finds it
os.environ.pop(key_name, None)
logger.info(f"AI key deleted: {key_name}")
return {"status": "deleted", "key": key_name}
@app.post("/api/config/ai-keys/test")
async def api_test_ai_keys(current_user=Depends(require_admin)):
"""Test which AI providers are configured."""
"""Test which AI providers are configured.
Each provider has a dedicated (URL, header-name) test pair.
- Most OpenAI-compatible APIs use `Authorization: Bearer KEY`
- Xiaomi MiMo uses `api-key: KEY`
- Gemini uses a query-string key
"""
results = {}
for key_name, label, test_url, test_header in [
("DEEPSEEK_API_KEY", "deepseek", "https://api.deepseek.com/v1/models", "Authorization"),
("OPENROUTER_API_KEY", "openrouter", "https://openrouter.ai/api/v1/models", "Authorization"),
("GEMINI_API_KEY", "gemini", "https://generativelanguage.googleapis.com/v1beta/models?key={key}", None),
for key_name, label, test_url_tmpl, header_name in [
# OpenAI-compatible — Authorization: Bearer
("DEEPSEEK_API_KEY", "deepseek", "https://api.deepseek.com/v1/models", "Authorization"),
("OPENROUTER_API_KEY","openrouter", "https://openrouter.ai/api/v1/models", "Authorization"),
("NVIDIA_API_KEY", "nvidia", "https://integrate.api.nvidia.com/v1/models", "Authorization"),
("QWENCLOUD_API_KEY", "qwencloud", "https://dashscope.aliyuncs.com/compatible-mode/v1/models", "Authorization"),
("MISTRAL_API_KEY", "mistral", "https://api.mistral.ai/v1/models", "Authorization"),
# Xiaomi MiMo — dedicated api-key header (NOT Authorization: Bearer)
("XIAOMI_API_KEY", "xiaomi", "https://api.xiaomimimo.com/v1/models", "api-key"),
# Gemini — key in query string
("GEMINI_API_KEY", "gemini", "https://generativelanguage.googleapis.com/v1beta/models?key={key}", None),
]:
key = get_ai_key(key_name)
if not key:
@@ -3937,13 +4173,15 @@ async def api_test_ai_keys(current_user=Depends(require_admin)):
continue
try:
import urllib.request
if test_header:
req = urllib.request.Request(test_url, headers={test_header: "Bearer " + key})
url = test_url_tmpl.replace("{key}", key) if "{key}" in test_url_tmpl else test_url_tmpl
if header_name:
req = urllib.request.Request(url, headers={header_name: key})
else:
req = urllib.request.Request(test_url.replace("{key}", key))
req = urllib.request.Request(url)
urllib.request.urlopen(req, timeout=5)
results[label] = "ok"
except Exception as e:
# Truncate the error to keep the response small.
results[label] = "erreur: " + str(e)[:80]
return results
@@ -3954,28 +4192,54 @@ async def api_test_ai_keys(current_user=Depends(require_admin)):
@app.get("/api/config/ai-models")
async def api_list_ai_models(provider: str = Query(...), current_user=Depends(require_admin)):
"""List available models for a given AI provider."""
"""List available models for a given AI provider.
Strategy:
1. Try the provider's public models endpoint (OpenAI-compatible /v1/models or Gemini).
2. If the network call fails (timeout, 4xx, 5xx, DNS, etc.), fall back to a
curated static list of known-good models for that provider.
3. Always return a non-empty list when the provider is known, so the UI
dropdown is never empty.
"""
provider = provider.lower()
if provider not in ("deepseek", "openrouter", "gemini"):
return {"models": [], "error": f"Unknown provider: {provider}"}
all_providers = ("deepseek", "openrouter", "gemini", "nvidia", "qwencloud", "xiaomi", "mistral")
if provider not in all_providers:
return {"models": [], "error": f"Unknown provider: {provider}", "source": "validation"}
key_name = f"{provider.upper()}_API_KEY"
key = get_ai_key(key_name)
if not key:
return {"models": [], "error": "API key not configured"}
# No key configured — return curated fallback list so the UI can
# still show what WOULD be available once a key is set.
return {"models": _FALLBACK_MODELS.get(provider, []), "source": "fallback",
"note": "API key not configured — showing default model list"}
# Build URL and request
# Build URL
if provider == "gemini":
url = f"https://generativelanguage.googleapis.com/v1beta/models?key={key}"
elif provider == "deepseek":
url = "https://api.deepseek.com/v1/models"
else: # openrouter
elif provider == "openrouter":
url = "https://openrouter.ai/api/v1/models"
elif provider == "nvidia":
url = "https://integrate.api.nvidia.com/v1/models"
elif provider == "qwencloud":
url = "https://dashscope.aliyuncs.com/compatible-mode/v1/models"
elif provider == "xiaomi":
# Xiaomi MiMo — dedicated api-key header (NOT Authorization: Bearer).
# Endpoint: https://api.xiaomimimo.com/v1/models
url = "https://api.xiaomimimo.com/v1/models"
models = [] # parsed below with the custom header
elif provider == "mistral":
url = "https://api.mistral.ai/v1/models"
try:
if provider == "gemini":
req = urllib.request.Request(url)
elif provider == "xiaomi":
# Xiaomi MiMo uses a dedicated api-key header.
req = urllib.request.Request(url, headers={"api-key": key})
else:
req = urllib.request.Request(url, headers={"Authorization": "Bearer " + key})
@@ -3983,13 +4247,90 @@ async def api_list_ai_models(provider: str = Query(...), current_user=Depends(re
data = _json.loads(resp.read().decode())
if provider == "gemini":
models = [m.get("name", "") for m in data.get("models", [])]
models = [m.get("name", "") for m in data.get("models", []) if m.get("name")]
# Gemini returns names like "models/gemini-1.5-flash" — strip prefix
models = [m.replace("models/", "") for m in models]
else:
models = [m.get("id", "") for m in data.get("data", [])]
models = [m.get("id", "") for m in data.get("data", []) if m.get("id")]
return {"models": models}
if models:
# Prepend the configured default if not already present
default = PROVIDERS.get(provider, {}).get("model")
if default and default not in models:
models = [default] + models
return {"models": models, "source": "live", "count": len(models)}
# Empty list from API — fall through to fallback
raise ValueError("empty model list from provider API")
except Exception as e:
return {"models": [], "error": str(e)}
# Network error, auth error, parsing error — use curated fallback
fallback = _FALLBACK_MODELS.get(provider, [])
return {"models": fallback, "source": "fallback", "error": str(e)[:200],
"note": "Could not reach provider API — showing default model list"}
# ── Curated fallback model lists ──────────────────────────────────────────
# Used when the provider API is unreachable or returns empty.
# Keep these short and focused on models known to work with the
# OpenAI-compatible chat completions interface (or Gemini's generateContent).
_FALLBACK_MODELS: dict[str, list[str]] = {
"deepseek": [
"deepseek-chat",
"deepseek-reasoner",
],
"openrouter": [
"openai/gpt-4o-mini",
"openai/gpt-4o",
"anthropic/claude-3.5-sonnet",
"anthropic/claude-3-haiku",
"google/gemini-2.0-flash-exp:free",
"meta-llama/llama-3.1-70b-instruct",
"meta-llama/llama-3.1-8b-instruct:free",
"mistralai/mistral-large-latest",
],
"gemini": [
"gemini-2.0-flash",
"gemini-2.0-flash-exp",
"gemini-1.5-pro",
"gemini-1.5-flash",
"gemini-1.5-flash-8b",
],
"nvidia": [
"meta/llama-3.1-405b-instruct",
"meta/llama-3.1-70b-instruct",
"meta/llama-3.1-8b-instruct",
"mistralai/mistral-large",
"google/gemma-2-27b-it",
"nvidia/llama-3.1-nemotron-70b-instruct",
],
"qwencloud": [
"qwen-max",
"qwen-plus",
"qwen-turbo",
"qwen-long",
"qwen-vl-max",
"qwen-vl-plus",
],
"xiaomi": [
# Xiaomi MiMo models — the public /v1/models endpoint requires the
# `api-key` custom header (NOT Authorization: Bearer), so the live
# call often fails with 401 even with the right key. We ship a
# known-good list as fallback. See https://mimo.mi.com/docs/
"mimo-v2.5-pro",
"mimo-v2.5",
"mimo-v2.5-asr",
"mimo-v2.5-tts",
"mimo-v2.5-tts-voiceclone",
"mimo-v2.5-tts-voicedesign",
],
"mistral": [
"mistral-large-latest",
"mistral-medium-latest",
"mistral-small-latest",
"open-mistral-7b",
"open-mixtral-8x7b",
"codestral-latest",
],
}
# ---------------------------------------------------------------------------
@@ -4438,6 +4779,19 @@ if FRONTEND_DIR.exists():
return HTMLResponse(content=poc_file.read_text(encoding="utf-8"))
raise HTTPException(status_code=404, detail="Editor POC not found")
@app.get("/admin.html", response_class=HTMLResponse)
async def serve_admin_page(_current_user=Depends(require_admin)):
"""Serve the admin dashboard page (ROADMAP #71) — admin-gated.
Must be declared BEFORE the SPA catch-all ``/{full_path:path}`` or the
admin page would be shadowed by ``index.html`` (the reported bug: the
Admin menu kept returning to the main page).
"""
admin_file = FRONTEND_DIR / "admin.html"
if admin_file.exists():
return HTMLResponse(content=admin_file.read_text(encoding="utf-8"))
raise HTTPException(status_code=404, detail="Admin page not found")
@app.get("/{full_path:path}")
async def serve_spa(full_path: str):
"""Serve the SPA index.html for all non-API routes."""
+49 -4
View File
@@ -2,11 +2,21 @@
from __future__ import annotations
import logging
import os
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as FuturesTimeout
from pathlib import Path
logger = logging.getLogger(__name__)
# Configurable limits (see ROADMAP #74 G3):
# OBSIGATE_PDF_MAX_SIZE_MB — PDFs larger than this are not text-extracted (default 50)
# OBSIGATE_PDF_EXTRACT_TIMEOUT — seconds before extraction is abandoned (default 30)
PDF_MAX_SIZE_MB: int = int(os.environ.get("OBSIGATE_PDF_MAX_SIZE_MB", "50"))
PDF_EXTRACT_TIMEOUT: float = float(os.environ.get("OBSIGATE_PDF_EXTRACT_TIMEOUT", "30"))
PDF_READER: str = "pypdf"
PdfReader = None # type: ignore
try:
import fitz # pymupdf
PDF_READER = "pymupdf"
@@ -16,19 +26,54 @@ except ImportError:
from pypdf import PdfReader # type: ignore
logger.info("PDF reader: pypdf (pure Python)")
except ImportError:
PdfReader = None # type: ignore
logger.warning("No PDF reader available — install pypdf or pymupdf")
def pdf_exceeds_size_limit(file_path: Path) -> bool:
"""True if the PDF is larger than OBSIGATE_PDF_MAX_SIZE_MB (skip text extraction)."""
try:
return file_path.stat().st_size > PDF_MAX_SIZE_MB * 1024 * 1024
except OSError:
return False
def _run_with_timeout(fn, *args, timeout: float):
"""Run a sync function in a worker thread with a hard timeout.
A timed-out extraction leaves its worker thread running (daemon-style pool
is abandoned), but the request itself is freed — acceptable trade-off for
pathological PDFs on a self-hosted single-user server.
"""
executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="pdf-extract")
try:
future = executor.submit(fn, *args)
return future.result(timeout=timeout)
finally:
executor.shutdown(wait=False)
def extract_pdf_text(file_path: Path, max_chars: int = 100000) -> str:
"""Extract text from a PDF file. Returns empty string on failure."""
"""Extract text from a PDF file. Returns empty string on failure.
Oversized PDFs (> OBSIGATE_PDF_MAX_SIZE_MB) and extractions exceeding
OBSIGATE_PDF_EXTRACT_TIMEOUT seconds return "" instead of blocking.
"""
if PdfReader is None and PDF_READER == "pypdf":
return ""
if pdf_exceeds_size_limit(file_path):
logger.info("PDF too large to index (> %d MB), skipping text extraction: %s",
PDF_MAX_SIZE_MB, file_path)
return ""
try:
if PDF_READER == "pymupdf":
return _extract_pymupdf(file_path, max_chars)
return _run_with_timeout(_extract_pymupdf, file_path, max_chars,
timeout=PDF_EXTRACT_TIMEOUT)
else:
return _extract_pypdf(file_path, max_chars)
return _run_with_timeout(_extract_pypdf, file_path, max_chars,
timeout=PDF_EXTRACT_TIMEOUT)
except FuturesTimeout:
logger.warning("PDF text extraction timed out (%ss): %s", PDF_EXTRACT_TIMEOUT, file_path)
return ""
except Exception as e:
logger.warning("Failed to extract PDF text from %s: %s", file_path, e)
return ""
+5
View File
@@ -0,0 +1,5 @@
# Additional dev/test-only dependencies for the test suite.
# These are NOT required for production runtime.
# Install with: pip install -r requirements-test.txt
reportlab>=4.0 # PDF fixture generation for test_pdf.py
+3
View File
@@ -13,3 +13,6 @@ snowballstemmer>=2.2.0
weasyprint>=60.0
httpx>=0.27.0
pypdf>=4.0
pyotp>=2.10.0
webauthn==2.6.0
psutil>=5.9
+64 -28
View File
@@ -1,13 +1,15 @@
"""
Version management for ObsiGate.
Uses git describe to generate a SemVer-compatible version string.
Format: MAJOR.MINOR.PATCH[-commits-since-tag-gHASH]
The canonical version is the numeric SemVer of the LATEST release tag
(MAJOR.MINOR.PATCH). get_version() always returns a clean "x.y.z" string so
the UI never shows "-dev", "0.0.0-dev" or a "-N-gHASH" suffix — the same
number appears in the header badge, the About modal and the API health.
Examples:
v1.7.0 (exact tag)
v1.7.0-3-gabc1234 (3 commits after v1.7.0)
v1.7.0-dev (fallback when Git unavailable)
tag v2.0.0 -> "2.0.0"
HEAD 31 commits after -> "2.0.0" (release version, no dev clutter)
no git / no VERSION -> "0.0.0"
"""
from __future__ import annotations
@@ -15,13 +17,14 @@ import subprocess
from pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent # ObsiGate repo root
_VERSION_FILE = Path(__file__).resolve().parent / "VERSION"
def get_version() -> str:
"""Get the current version from Git tags."""
def _run_git(args: list[str]) -> str:
"""Run a git command in the repo root; return stdout (stripped) or ''."""
try:
result = subprocess.run(
["git", "describe", "--tags", "--dirty=-dirty"],
["git", *args],
cwd=str(_ROOT),
capture_output=True,
text=True,
@@ -29,35 +32,68 @@ def get_version() -> str:
check=False,
)
if result.returncode == 0:
tag = result.stdout.strip()
# git describe returns v1.7.0 or v1.7.0-3-gabc1234
# Remove leading 'v' if present
tag = tag.removeprefix("v")
return tag
return result.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
pass
return ""
# Fallback: try reading from a VERSION file next to this module
version_file = Path(__file__).parent / "VERSION"
if version_file.exists():
return version_file.read_text().strip()
return "0.0.0-dev"
def _clean_base(raw: str) -> str:
"""Reduce a version string to its numeric MAJOR.MINOR.PATCH base.
Handles "v2.0.0", "2.0.0-31-gabc1234", "2.0.0-dev", "0.0.0-dev".
Returns "" if no numeric triplet can be parsed.
"""
s = (raw or "").strip().lstrip("vV")
base = s.split("-")[0] # strip -N-gHASH / -dev / -dirty suffixes
parts = base.split(".")
nums = []
for p in parts[:3]:
if not p.isdigit():
break
nums.append(str(int(p)))
if len(nums) != 3:
return ""
return ".".join(nums)
def get_git_describe() -> str:
"""Full `git describe` string (e.g. "2.0.0-31-gabc1234") or '' if no git."""
return _run_git(["describe", "--tags", "--dirty=-dirty"]).lstrip("v")
def get_git_commit() -> str:
"""Short HEAD commit hash (e.g. "abc1234") or '' if unavailable."""
return _run_git(["rev-parse", "--short", "HEAD"])
def get_version() -> str:
"""Return the clean release version x.y.z (latest tag) — never a -suffix.
Priority: latest git tag -> backend/VERSION file -> "0.0.0".
"""
# 1) Latest tag from git (works even with commits beyond the tag)
tag = _run_git(["describe", "--tags", "--abbrev=0"])
base = _clean_base(tag)
if base:
return base
# 2) backend/VERSION file (baked at build time by build.sh / CI / Docker)
if _VERSION_FILE.exists():
base = _clean_base(_VERSION_FILE.read_text(encoding="utf-8"))
if base:
return base
# 3) Nothing available
return "0.0.0"
def get_version_tuple() -> tuple[int, int, int]:
"""Return (major, minor, patch) tuple for programmatic use."""
raw = get_version()
# Strip -suffix for parsing
base = raw.split("-")[0]
try:
parts = base.split(".")
major = int(parts[0]) if len(parts) > 0 else 0
minor = int(parts[1]) if len(parts) > 1 else 0
patch = int(parts[2]) if len(parts) > 2 else 0
return (major, minor, patch)
except (ValueError, IndexError):
return (0, 0, 0)
base = _clean_base(raw) or "0.0.0"
major, minor, patch = (int(p) for p in base.split("."))
return (major, minor, patch)
if __name__ == "__main__":
+66 -5
View File
@@ -1,7 +1,8 @@
import asyncio
import logging
import os
import time
from collections.abc import Callable
from collections.abc import Callable, Iterable
from pathlib import Path
from watchdog.events import FileSystemEventHandler
@@ -12,6 +13,54 @@ from backend.indexer import IGNORED_DIRS, SUPPORTED_EXTENSIONS
logger = logging.getLogger("obsigate.watcher")
# Filesystem types where inotify does NOT fire for changes made by other
# clients (the edit happens on another machine — e.g. Obsidian on Windows
# writing to an NFS/SMB export). For those mounts watchdog's native
# Observer silently misses everything and polling is the only option.
NETWORK_FSTYPES = {
"nfs", "nfs4", "cifs", "smbfs", "smb2", "smb3",
"fuse", "fuse.sshfs", "glusterfs", "9p", "virtiofs", "lustre",
}
def find_mount_fstype(resolved_path: str, mount_lines: Iterable[str]) -> str:
"""Return the fstype of the longest /proc/mounts entry covering the path.
Pure function (mount_lines are text lines) so it can be unit-tested
without /proc. Returns "" when no mount matches.
"""
best_point = ""
best_fstype = ""
for line in mount_lines:
parts = line.split()
if len(parts) < 3:
continue
mount_point, fstype = parts[1], parts[2]
# /proc/mounts escapes special chars in octal
mount_point = mount_point.replace("\\040", " ").replace("\\011", "\t")
root = mount_point.rstrip("/") or "/"
if (resolved_path == root or resolved_path.startswith(root + "/")) and len(mount_point) > len(best_point):
best_point = mount_point
best_fstype = fstype
return best_fstype
def is_network_mount(path: str) -> bool:
"""True if *path* sits on a network/fuse filesystem (Linux only).
inotify events are local to the client that made the write, so vaults
shared over NFS/SMB never see Obsidian's edits. On those mounts we
must fall back to PollingObserver, which detects changes by stat().
"""
if os.name != "posix":
return False
try:
with open("/proc/mounts", "r", encoding="utf-8") as fh:
fstype = find_mount_fstype(os.path.realpath(path), fh)
except OSError:
return False
return fstype in NETWORK_FSTYPES
class VaultEventHandler(FileSystemEventHandler):
"""Gestionnaire d'événements filesystem pour une vault Obsidian.
@@ -114,7 +163,12 @@ class VaultWatcher:
vault_path: str,
loop: asyncio.AbstractEventLoop,
):
"""Créer et démarrer un observer pour une vault."""
"""Créer et démarrer un observer pour une vault.
Le mode (natif inotify vs polling) est choisi par vault :
les mounts réseau (NFS/SMB/fuse) sont surveillés en polling car
inotify ne voit pas les écritures faites depuis d'autres clients.
"""
path = Path(vault_path)
if not path.exists():
logger.warning(f"Vault '{vault_name}' path not found: {vault_path}")
@@ -122,16 +176,23 @@ class VaultWatcher:
handler = VaultEventHandler(vault_name, self.event_queue, loop)
ObserverClass = PollingObserver if self.use_polling else Observer
polling = self.use_polling or is_network_mount(vault_path)
if polling and not self.use_polling:
logger.info(
f"Vault '{vault_name}' is on a network mount — "
"using polling watcher (inotify cannot see remote edits)"
)
ObserverClass = PollingObserver if polling else Observer
try:
observer = ObserverClass(
timeout=self.polling_interval if self.use_polling else 1
timeout=self.polling_interval if polling else 1
)
observer.schedule(handler, str(path), recursive=True)
observer.daemon = True
observer.start()
self.observers[vault_name] = observer
mode = "polling" if self.use_polling else "native"
mode = "polling" if polling else "native"
logger.info(f"Watching ({mode}): {vault_name} -> {vault_path}")
except Exception as e:
logger.error(f"Failed to start watcher for '{vault_name}': {e}")
+1
View File
@@ -2644,6 +2644,7 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-store",
"tauri-plugin-updater",
"tempfile",
"tokio",
]
+3
View File
@@ -26,6 +26,9 @@ log = "0.4"
env_logger = "0.11"
chrono = "0.4"
[dev-dependencies]
tempfile = "3"
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
+231 -7
View File
@@ -9,11 +9,40 @@ use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU16, Ordering};
use std::sync::Mutex;
use std::time::Duration;
// ── Backend port (ROADMAP #77 B: auto-increment if 17890 is busy) ────
const DEFAULT_BACKEND_PORT: u16 = 17890;
const PORT_SCAN_ATTEMPTS: u16 = 10;
static BACKEND_PORT: AtomicU16 = AtomicU16::new(DEFAULT_BACKEND_PORT);
fn backend_url() -> String {
format!("http://127.0.0.1:{}", BACKEND_PORT.load(Ordering::Relaxed))
}
/// First free TCP port starting at DEFAULT_BACKEND_PORT.
fn pick_free_port() -> u16 {
for offset in 0..PORT_SCAN_ATTEMPTS {
let port = DEFAULT_BACKEND_PORT + offset;
if TcpListener::bind(("127.0.0.1", port)).is_ok() {
if offset > 0 {
info!("Port {} busy — using {} instead", DEFAULT_BACKEND_PORT, port);
}
return port;
}
}
warn!("No free port in {}..{}, falling back to default",
DEFAULT_BACKEND_PORT, DEFAULT_BACKEND_PORT + PORT_SCAN_ATTEMPTS - 1);
DEFAULT_BACKEND_PORT
}
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use tauri::Manager;
@@ -172,12 +201,15 @@ fn spawn_backend(exe_dir: &PathBuf) -> Result<Child, String> {
cmd.env(format!("DIR_{}_PATH", n), &dir.path);
}
let port = pick_free_port();
BACKEND_PORT.store(port, Ordering::Relaxed);
let child = cmd
.args([
"-m", "uvicorn",
"backend.main:app",
"--host", "127.0.0.1",
"--port", "17890",
"--port", &port.to_string(),
"--log-level", "info",
])
.stdout(Stdio::from(log.try_clone().map_err(|e| format!("{}", e))?))
@@ -191,10 +223,10 @@ fn spawn_backend(exe_dir: &PathBuf) -> Result<Child, String> {
async fn wait_for_backend() -> Result<(), String> {
let client = reqwest::Client::new();
let url = "http://127.0.0.1:17890/api/health";
let url = format!("{}/api/health", backend_url());
for i in 0..30 {
match client.get(url).timeout(Duration::from_secs(2)).send().await {
match client.get(&url).timeout(Duration::from_secs(2)).send().await {
Ok(resp) if resp.status().is_success() => {
info!("Backend ready (attempt {})", i + 1);
return Ok(());
@@ -235,7 +267,7 @@ fn kill_backend(child: &mut Child) {
#[tauri::command]
fn get_backend_url() -> String {
"http://127.0.0.1:17890".to_string()
backend_url()
}
#[tauri::command]
@@ -390,7 +422,7 @@ async fn check_backend_health(state: tauri::State<'_, BackendProcess>) -> Result
}
// Health check HTTP
match reqwest::get("http://127.0.0.1:17890/api/health").await {
match reqwest::get(format!("{}/api/health", backend_url())).await {
Ok(resp) if resp.status().is_success() => Ok("healthy".to_string()),
_ => Ok("unhealthy".to_string()),
}
@@ -570,7 +602,7 @@ fn main() {
let _ = window.eval(
r#"if (window.__setBootStatus) window.__setBootStatus("Backend prêt — chargement de l'interface…")"#,
);
match window.eval("window.location.href = 'http://127.0.0.1:17890'") {
match window.eval(&format!("window.location.href = '{}'", backend_url())) {
Ok(_) => info!("Redirect to backend OK"),
Err(e) => error!("Redirect eval failed: {}", e),
}
@@ -580,8 +612,9 @@ fn main() {
error!("Backend failed: {}", e);
if let Some(window) = handle.get_webview_window("main") {
let _ = window.eval(&format!(
r#"document.body.innerHTML = '<div style="padding:40px;text-align:center;font-family:sans-serif"><h2 style="color:#c0392b">ObsiGate n\'a pas pu démarrer</h2><p style="color:#666">{}</p><p><button onclick="location.reload()" style="padding:10px 20px;font-size:16px;cursor:pointer;background:#7C3AED;color:white;border:none;border-radius:6px">Réessayer</button></p><p style="margin-top:20px;font-size:12px;color:#999">Backend: http://127.0.0.1:17890 | Logs: {}</p></div>'"#,
r#"document.body.innerHTML = '<div style="padding:40px;text-align:center;font-family:sans-serif"><h2 style="color:#c0392b">ObsiGate n\'a pas pu démarrer</h2><p style="color:#666">{}</p><p><button onclick="location.reload()" style="padding:10px 20px;font-size:16px;cursor:pointer;background:#7C3AED;color:white;border:none;border-radius:6px">Réessayer</button></p><p style="margin-top:20px;font-size:12px;color:#999">Backend: {} | Logs: {}</p></div>'"#,
e.replace('\'', "\\'").replace('"', "\\\""),
backend_url(),
backend_log_path().display().to_string().replace('\\', "\\\\"),
));
}
@@ -832,3 +865,194 @@ fn build_tray_menu(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
// ── Tests ───────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
/// Helper: write config to a temp dir and read it back
fn roundtrip_config(config: &AppConfig) -> AppConfig {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("config.json");
let json = serde_json::to_string_pretty(config).unwrap();
fs::write(&path, &json).unwrap();
let raw = fs::read_to_string(&path).unwrap();
serde_json::from_str(&raw).unwrap()
}
#[test]
fn test_default_config() {
let c = AppConfig::default();
assert!(c.vault_path.is_none());
assert!(c.vaults.is_empty());
assert!(c.dirs.is_empty());
assert_eq!(c.window_width, Some(1200.0));
assert_eq!(c.window_height, Some(800.0));
}
#[test]
fn test_config_roundtrip() {
let c = AppConfig {
vault_path: Some("/test/vault".into()),
vaults: vec![
VaultConfig { name: "Personal".into(), path: "/v/personal".into() },
VaultConfig { name: "Work".into(), path: "/v/work".into() },
],
dirs: vec![DirConfig { name: "home".into(), path: "/home".into() }],
window_x: Some(100.0),
window_y: Some(200.0),
window_width: Some(1400.0),
window_height: Some(900.0),
};
let loaded = roundtrip_config(&c);
assert_eq!(loaded.vault_path, Some("/test/vault".into()));
assert_eq!(loaded.vaults.len(), 2);
assert_eq!(loaded.vaults[0].name, "Personal");
assert_eq!(loaded.vaults[1].path, "/v/work");
assert_eq!(loaded.dirs.len(), 1);
assert_eq!(loaded.window_x, Some(100.0));
}
#[test]
fn test_config_empty_json() {
// serde requires vaults/dirs fields — missing fields use unwrap_or_default
let c: AppConfig = serde_json::from_str("{}").unwrap_or_default();
assert!(c.vault_path.is_none());
assert!(c.vaults.is_empty());
}
#[test]
fn test_config_partial_json() {
// serde requires all fields — partial JSON uses unwrap_or_default
let c: AppConfig = serde_json::from_str(
r#"{"vaults":[{"name":"t","path":"/t"}]}"#
).unwrap_or_default();
// Will fall to default since dirs is missing
assert!(c.vaults.is_empty() || c.vaults.len() == 1);
}
#[test]
fn test_config_corrupted_json_fallback() {
let result: Result<AppConfig, _> = serde_json::from_str("not json");
assert!(result.is_err());
// Caller should use unwrap_or_default()
let c = result.unwrap_or_default();
assert!(c.vaults.is_empty());
}
#[test]
fn test_vault_dedup() {
let mut c = AppConfig::default();
c.vaults.retain(|v| v.name != "test");
c.vaults.push(VaultConfig { name: "test".into(), path: "/first".into() });
c.vaults.retain(|v| v.name != "test");
c.vaults.push(VaultConfig { name: "test".into(), path: "/second".into() });
assert_eq!(c.vaults.len(), 1);
assert_eq!(c.vaults[0].path, "/second");
}
#[test]
fn test_dir_remove() {
let mut c = AppConfig::default();
c.dirs.push(DirConfig { name: "a".into(), path: "/a".into() });
c.dirs.push(DirConfig { name: "b".into(), path: "/b".into() });
c.dirs.retain(|d| d.name != "a");
assert_eq!(c.dirs.len(), 1);
assert_eq!(c.dirs[0].name, "b");
}
#[test]
fn test_backend_url() {
let port = BACKEND_PORT.load(Ordering::Relaxed);
assert_eq!(get_backend_url(), format!("http://127.0.0.1:{}", port));
}
#[test]
fn test_pick_free_port_is_free() {
let port = pick_free_port();
assert!((DEFAULT_BACKEND_PORT..DEFAULT_BACKEND_PORT + PORT_SCAN_ATTEMPTS).contains(&port));
assert!(TcpListener::bind(("127.0.0.1", port)).is_ok());
}
#[test]
fn test_pick_free_port_skips_busy_port() {
let blocker = match TcpListener::bind(("127.0.0.1", DEFAULT_BACKEND_PORT)) {
Ok(l) => l,
Err(_) => return, // default port already busy on this machine — skip
};
let port = pick_free_port();
assert_ne!(port, DEFAULT_BACKEND_PORT);
assert!(port < DEFAULT_BACKEND_PORT + PORT_SCAN_ATTEMPTS);
drop(blocker);
}
#[test]
fn test_backend_url_reflects_port() {
let saved = BACKEND_PORT.load(Ordering::Relaxed);
BACKEND_PORT.store(17893, Ordering::Relaxed);
assert_eq!(backend_url(), "http://127.0.0.1:17893");
BACKEND_PORT.store(saved, Ordering::Relaxed);
}
#[test]
fn test_about_msg_contains_branding() {
assert!(ABOUT_MSG.contains("ObsiGate Desktop"));
assert!(ABOUT_MSG.contains("Bruno Charest"));
assert!(ABOUT_MSG.contains("Tauri"));
}
#[test]
fn test_app_data_dir_nonempty() {
let dir = app_data_dir();
assert!(!dir.to_string_lossy().is_empty());
}
#[test]
fn test_logs_dir_under_app_data() {
let logs = logs_dir();
assert!(logs.starts_with(app_data_dir()));
assert_eq!(logs.file_name().unwrap(), "logs");
}
#[test]
fn test_backend_log_path() {
let p = backend_log_path();
assert_eq!(p.file_name().unwrap(), "backend.log");
}
#[test]
fn test_json_format_keys() {
let c = AppConfig::default();
let json = serde_json::to_string(&c).unwrap();
assert!(json.contains("\"vaults\""));
assert!(json.contains("\"dirs\""));
assert!(json.contains("\"window_width\""));
}
#[test]
fn test_backend_health_check_url() {
// Verify the health check targets the correct endpoint
let url = "http://127.0.0.1:17890/api/health";
assert!(url.contains("17890"));
assert!(url.contains("/api/health"));
}
#[test]
fn test_vault_config_clone() {
let v = VaultConfig { name: "test".into(), path: "/t".into() };
let v2 = v.clone();
assert_eq!(v.name, v2.name);
assert_eq!(v.path, v2.path);
}
#[test]
fn test_dir_config_debug() {
let d = DirConfig { name: "x".into(), path: "/x".into() };
let dbg = format!("{:?}", d);
assert!(dbg.contains("x"));
}
}
+4
View File
@@ -11,6 +11,10 @@ services:
obsigate:
build:
context: .
args:
# VERSION est injecte par build.sh/CI via `git describe` ;
# sans variable d'env, l'image tombe sur 0.0.0-dev (fallback Dockerfile).
VERSION: ${VERSION:-0.0.0-dev}
image: obsigate:latest
container_name: obsigate
user: "1000:1000"
+209 -200
View File
@@ -1,6 +1,7 @@
# ObsiGate — Roadmap
> **Version :** 2.0.0-dev | **Dernière mise à jour :** 2026-06-18
> **Version :** 2.1.0-dev | **Dernière mise à jour :** 2026-09-07
> Revue de cohérence roadmap ↔ code : cases cochées selon l'état réel vérifié dans le dépôt (commit c066b2c).
> Voir aussi [CHANGELOG.md](./CHANGELOG.md), [AUDIT_TECHNIQUE.md](./docs/AUDIT_TECHNIQUE_2026-05-27.md)
---
@@ -119,7 +120,7 @@
---
## 🔵 En cours (P1)
## ✅ Complété (suite — v1.7 → v2.1)
### 58. Tests E2E Playwright ✅ FAIT
- **Effort :** 2-3 jours | **Impact :** 🔴
@@ -146,7 +147,7 @@
## ⚪ Backlog — Priorité 3 (P3)
### 59. Mode hors-ligne PWA complet ✅ FAIT
### 59. Mode hors-ligne PWA complet — ✅ TERMINÉ
- **Effort :** 3-4 jours | **Impact :** 🟡
- **Description :** Service worker avancé avec IndexedDB pour permettre la navigation et la recherche en mode hors-ligne, avec file de synchronisation au retour réseau.
- **Implémentation :** `offline-db.js` (377 lignes) + `offline.js` (209 lignes). IndexedDB 3 stores (files, content, pending). Badge hors-ligne dans le header. Modale résolution de conflits.
@@ -190,7 +191,7 @@
- [ ] Gestion des déconnexions : reconnexion automatique, merge state au retour
- [ ] Tests de charge : 5+ utilisateurs simultanés sur le même fichier
### 63. Internationalisation (i18n) — Multilingue
### 63. Internationalisation (i18n) — Multilingue — ✅ TERMINÉ
- **Effort :** 2-3 jours | **Impact :** 🟡 | **Statut :** ✅ Terminé
- **Description :** Support de l'anglais et du français via un système de clés de traduction.
- **Sous-tâches :**
@@ -207,111 +208,119 @@
- [x] Thèmes, palette de commandes, raccourcis, webhooks → EN/FR complet
- [x] Messages système : toasts, statuts, événements → EN/FR complet
### 64. MFA — Authentification multi-facteurs
- **Effort :** 2 jours | **Impact :** 🟡
### 64. MFA — Authentification multi-facteurs — ✅ TERMINÉ (TOTP + WebAuthn + recovery codes)
- **Effort :** 2 jours (réalisé) | **Impact :** 🟡
- **Description :** Ajout d'un second facteur d'authentification obligatoire pour les comptes administrateur. Deux méthodes sont proposées :
- **TOTP** (Time-based One-Time Password) : l'utilisateur scanne un QR code avec son app d'authentification (Google Authenticator, Authy, Bitwarden) qui génère un code à 6 chiffres renouvelé toutes les 30 secondes. Au login, après avoir saisi son mot de passe, l'utilisateur doit entrer le code affiché sur son téléphone. Même si le mot de passe est volé, le compte reste protégé car l'attaquant n'a pas le téléphone.
- **WebAuthn** (clés de sécurité physiques) : l'utilisateur enregistre une clé USB (YubiKey, SoloKey) ou utilise la biométrie de son appareil (empreinte digitale, Face ID, Windows Hello). Au login, le navigateur demande de toucher la clé physique ou de scanner le doigt. C'est le niveau de sécurité le plus élevé — résistant au phishing car la clé vérifie le domaine du site avant de répondre.
- **Codes de secours** : 8 codes à usage unique imprimables, à conserver en lieu sûr, qui permettent de se connecter même si on perd son téléphone ou sa clé. Chaque code ne fonctionne qu'une seule fois.
- **Pourquoi c'est important :** Le vol de mot de passe est la cause #1 de brèches de sécurité. Avec un vault Obsidian contenant des notes personnelles, projets sensibles, secrets et tokens API, l'authentification par simple mot de passe n'est plus suffisante. Le MFA empêche 99.9% des attaques de prise de compte automatisées (source : Microsoft Security).
- **Sous-tâches :**
- [ ] TOTP : génération de secret, QR code, vérification code 6 chiffres
- [ ] WebAuthn : enregistrement de clé, assertion, attestation
- [ ] UI : page « Sécurité du compte » avec activation/désactivation MFA
- [ ] Flow login : mot de passe → challenge TOTP si activé
- [ ] Recovery codes : 8 codes de backup à usage unique
- [ ] Stockage : `totp_secret` + `webauthn_credential_id` dans `users.json`
- [x] TOTP : génération de secret, QR code, vérification code 6 chiffres
- [x] WebAuthn : enregistrement de clé, assertion, attestation (`backend/auth/webauthn_mfa.py`, lib `webauthn==2.6.0`, challenges in-memory TTL 180s à usage unique) — FAIT en 2026-09 (commit ab795ec)
- [x] UI : page « Sécurité du compte » avec activation/désactivation MFA + gestion des clés WebAuthn (liste, ajout, retrait)
- [x] Flow login : mot de passe → challenge TOTP OU WebAuthn selon `mfa_method` retourné par /login
- [x] Recovery codes : 8 codes de backup à usage unique (générés à l'activation, hachés SHA-256)
- [x] Stockage : `mfa_secret` + `webauthn_credentials[]` dans `users.json`
- [x] Tests : `tests/test_mfa.py` (29) + `tests/test_webauthn.py` (10, authentificateur virtuel CBOR/EC P-256)
### 65. Thèmes personnalisés — CSS variables
- **Effort :** 1-2 jours | **Impact :** 🟢
### 65. Thèmes personnalisés — CSS variables — ✅ TERMINÉ
- **Effort :** 1-2 jours (réalisé) | **Impact :** 🟢
- **Description :** Exposition de variables CSS pour permettre aux utilisateurs de créer des thèmes personnalisés. Presets inclus : light, dark, high-contrast, sepia.
- **Sous-tâches :**
- [ ] Audit des variables CSS existantes → liste des 30+ variables
- [ ] Fichier `themes.json` avec presets (light, dark, high-contrast, sepia)
- [ ] UI : sélecteur de thème dans les paramètres (aperçu live)
- [ ] Import/export de thème personnalisé (JSON)
- [ ] Application dynamique sans rechargement (`document.documentElement.style.setProperty`)
- [x] Audit des variables CSS existantes → 40+ variables
- [x] Presets: light, dark, high-contrast, sepia (générés dynamiquement)
- [x] UI : sélecteur de thème dans les paramètres (swatches grid)
- [x] Import/export de thème personnalisé (JSON)
- [x] Application dynamique via document.documentElement.style.setProperty
### 66. Export multi-formats
- **Effort :** 1-2 jours | **Impact :** 🟢
### 66. Export multi-formats — ✅ TERMINÉ
- **Effort :** 1-2 jours (réalisé) | **Impact :** 🟢
- **Description :** Export de notes individuelles ou de vaults entiers en HTML standalone, bundle Markdown (.zip), et ePub pour liseuses.
- **Sous-tâches :**
- [ ] Export HTML standalone : CSS inliné, images en base64, navigation inter-fichiers
- [ ] Export MD bundle : ZIP du vault avec structure préservée
- [ ] Export ePub : conversion markdown → ePub via `markdown` + `ebooklib`
- [ ] UI : bouton « Exporter » dans le viewer (fichier unique) + dans le menu vault (export complet)
- [ ] Endpoints : `GET /api/export/html`, `GET /api/export/md-bundle`, `GET /api/export/epub`
- [x] Export HTML standalone : CSS inliné, images en base64, navigation inter-fichiers
- [x] Export MD bundle : ZIP du vault avec structure préservée
- [x] Export ePub : conversion markdown → ePub (zipfile + mistune, 0 nouvelle dep)
- [x] UI : dropdown Export dans toolbar viewer (HTML / MD bundle / ePub)
- [x] Endpoints : `GET /api/export/html`, `GET /api/export/md-bundle`, `GET /api/export/epub`
### 74. Support complet des documents PDF
- **Effort :** 4-5 jours | **Impact :** 🟡
- **Description :** Prise en charge native des fichiers PDF dans ObsiGate avec parité fonctionnelle complète avec les documents Markdown : apparition dans l'arborescence, indexation full-text, visualisation inline dans le navigateur, recherche TF-IDF, et téléchargement. Actuellement, les PDF sont traités comme des fichiers binaires non supportés (message « Ce fichier est binaire et ne peut pas être affiché » + bouton download).
- **Architecture actuelle :**
- `SUPPORTED_EXTENSIONS` (`backend/indexer.py:56`) : ne contient pas `.pdf` → les PDF sont ignorés par l'indexeur, le file watcher, et l'arborescence
- `api_file_view()` (`backend/main.py:2303`) : UnicodeDecodeError sur lecture → retourne `unsupported: true`
- `frontend/js/viewer.js:377` : si `data.unsupported` → affiche le message binaire + bouton download
- `pdf_export.py` : exporte du MD → PDF (WeasyPrint) — aucun rapport avec la lecture de PDF existants
- Icone PDF déjà présente dans `EXT_ICONS` frontend (`.pdf` → `file-text`) — inutilisée
### 74. Support complet des documents PDF — ✅ TERMINÉ
- **Effort :** 4-5 jours | **Impact :** 🟡 | **Statut :** ✅ COMPLET (2026-09-07 — C3 + Range 206 + config G3 + indexation incrémentale, commit 7042307)
- **Description :** Prise en charge native des fichiers PDF dans ObsiGate avec parité fonctionnelle complète avec les documents Markdown : apparition dans l'arborescence, indexation full-text, visualisation inline dans le navigateur, recherche TF-IDF, et téléchargement.
- **Implémentation réelle (vérifiée 2026-09-07) :**
- **Bugs corrigés (2026-09) :** `api_pdf_stream` crashait en 500 (`NameError: current_user` jamais injecté) ; l'indexation incrémentale du watcher faisait `read_text()` sur les PDFs (garbage) ; Range/206 et `pdf/info` absents malgré le texte ci-dessous.
- `GET /api/file/{vault}/pdf/info` — métadonnées seules sans transférer le document (C3)
- Stream avec `Accept-Ranges` + 206 Partial Content (single range, suffix-range, 416) (C2)
- `OBSIGATE_PDF_MAX_SIZE_MB` (50) + `OBSIGATE_PDF_EXTRACT_TIMEOUT` (30s via thread-pool) (B4/G3)
- Backend `backend/pdf_reader.py` (existant) — extraction pypdf + pymupdf (fallback), métadonnées, TOC
- `backend/indexer.py` — `.pdf` dans SUPPORTED_EXTENSIONS, extraction dans `index_document()`
- `backend/main.py` — flag `is_pdf: True` retourné par `api_file_view`, endpoint `GET /api/file/{vault}/pdf/stream` avec support Range/206
- `backend/search.py` — filtre `ext:pdf` (déjà implémenté avant cette PR)
- `frontend/js/viewer.js:451-480` — branche `if (data.is_pdf)` + iframe + toolbar + TOC + bouton download
- **Tests :** `tests/test_pdf.py` (26 tests verts) — text/metadata/TOC + indexation scan/incrémentale + filtre ext + stream 200/206/416 + /pdf/info + limite de taille
- **Bug fixé dans cette PR :** `PdfReader` NameError dans `pdf_reader.py` quand pymupdf est installé (la variable `PdfReader` n'était déclarée que dans la branche `except ImportError`)
- `backend/requirements-test.txt` (nouveau) — `reportlab` pour générer des PDFs de test
- **Sous-tâches :**
##### A. Backend — Extraction de texte PDF (1-1.5 jour)
- [ ] **A1. Dépendance** : Ajouter `pymupdf` (PyMuPDF/fitz) à `requirements.txt` — bibliothèque C performante avec extraction texte + métadonnées, déjà compatible avec l'image Docker (libs système GTK/Pango déjà présentes pour WeasyPrint). Alternative légère : `pypdf` (pure Python, pas de deps système) si pymupdf pose problème.
- [ ] **A2. Module `backend/pdf_reader.py`** : Créer un module dédié avec les fonctions :
- [x] **A1. Dépendance** : `pypdf>=4.0` retenu dans requirements (pure Python, simplicité Docker) ; PyMuPDF (`fitz`) utilisé automatiquement en priorité s'il est importable — l'inverse du plan initial, fonctionnellement équivalent.
- [x] **A2. Module `backend/pdf_reader.py`** : Créer un module dédié avec les fonctions :
- `extract_pdf_text(file_path: Path) -> str` : extrait tout le texte du PDF, page par page, avec séparateur `\f` entre pages. Gère les PDF encodés, protégés par mot de passe (retourne erreur explicite), et corrompus.
- `extract_pdf_metadata(file_path: Path) -> dict` : extrait titre, auteur, sujet, nombre de pages, taille.
- `extract_pdf_preview(file_path: Path, max_chars: int = 100000) -> str` : extrait les N premiers caractères pour l'indexation (limité par `SEARCH_CONTENT_LIMIT`).
- [ ] **A3. Fallback pypdf** : Si pymupdf non disponible (exception d'import), fallback automatique sur `pypdf` avec un log warning. Code structuré avec une interface abstraite (`PdfReader` protocol) pour swap transparent.
- [x] **A3. Fallback pypdf** : Si pymupdf non disponible (exception d'import), fallback automatique sur `pypdf` avec un log warning. Code structuré avec une interface abstraite (`PdfReader` protocol) pour swap transparent.
##### B. Backend — Indexation des PDF (1 jour)
- [ ] **B1. Ajout à `SUPPORTED_EXTENSIONS`** : Ajouter `.pdf` au set dans `backend/indexer.py:56`. Déclencher un rebuild complet de l'index (incrémental via le file watcher pour les nouveaux PDFs).
- [ ] **B2. Modification de `index_document()`** (`backend/indexer.py:524`) : Dans la fonction d'indexation, détecter l'extension `.pdf` et appeler `extract_pdf_text()` au lieu de `read_text()`. Le texte extrait alimente le pipeline TF-IDF existant — aucun changement nécessaire dans `search.py`.
- [ ] **B3. Métadonnées PDF dans le document info** : Enrichir la structure de retour de `index_document()` avec les champs spécifiques PDF : `page_count`, `pdf_title` (titre extrait des métadonnées, prioritaire sur le nom de fichier), `pdf_author`.
- [ ] **B4. Gestion d'erreur robuste** : PDF corrompu → log warning + skip (ne pas bloquer l'indexation). PDF volumineux (>50 Mo) → log info + extraction tronquée à `SEARCH_CONTENT_LIMIT`. Timeout d'extraction configurable (30s par défaut).
- [x] **B1. Ajout à `SUPPORTED_EXTENSIONS`** : Ajouter `.pdf` au set dans `backend/indexer.py:56`. Déclencher un rebuild complet de l'index (incrémental via le file watcher pour les nouveaux PDFs).
- [x] **B2. Lecture PDF dans les DEUX chemins d'indexation** (`_scan_vault` + `_index_single_file_sync`, utilisé par le watcher) : détection `.pdf` → `extract_pdf_text()`. Fix 2026-09 : seul le scan complet gérait les PDFs, l'incrémental indexait du garbage.
- [x] **B3. Métadonnées PDF (adapté)** : titre PDF prioritaire sur le nom de fichier dans l'index ; `pages`/`author` exposés via `api_file_view` + `/pdf/info` (non stockés dans l'entrée d'index).
- [x] **B4. Gestion d'erreur robuste** : PDF corrompu → log warning + skip (ne pas bloquer l'indexation). PDF volumineux (>50 Mo) → log info + extraction tronquée à `SEARCH_CONTENT_LIMIT`. Timeout d'extraction configurable (30s par défaut).
##### C. Backend — API endpoints PDF (0.5 jour)
- [ ] **C1. Modification de `api_file_view()`** (`backend/main.py:2270`) : Avant la tentative de `read_text()`, détecter `.pdf` par extension. Pour les PDF :
- [x] **C1. Modification de `api_file_view()`** (`backend/main.py:2270`) : Avant la tentative de `read_text()`, détecter `.pdf` par extension. Pour les PDF :
- Extraire le texte avec `extract_pdf_text()`
- Extraire les métadonnées (pages, auteur)
- Retourner une réponse structurée : `is_pdf: true`, `page_count`, `pdf_metadata`, `html` (aperçu texte formaté), `raw_length`
- Le champ `html` contient un rendu texte simple (pas de markdown) : texte paginé ou première page formatée
- [ ] **C2. Nouvel endpoint `GET /api/file/{vault}/pdf/stream`** : Sert le fichier PDF brut avec `Content-Type: application/pdf` et `Content-Disposition: inline` pour visualisation dans le navigateur. Supporte le `Range` header (HTTP 206 Partial Content) pour le streaming progressif des gros PDFs — essentiel pour la performance sur des documents volumineux.
- [ ] **C3. Nouvel endpoint `GET /api/file/{vault}/pdf/info`** : Retourne les métadonnées seules (pages, titre, auteur) sans le contenu — permet à l'UI d'afficher les infos avant de charger le PDF lourd.
- [ ] **C4. Endpoint download** : Déjà fonctionnel (`/api/file/{vault}/download`) — aucun changement nécessaire.
- [x] **C2. Nouvel endpoint `GET /api/file/{vault}/pdf/stream`** : Sert le fichier PDF brut avec `Content-Type: application/pdf` et `Content-Disposition: inline` pour visualisation dans le navigateur. Supporte le `Range` header (HTTP 206 Partial Content) pour le streaming progressif des gros PDFs — essentiel pour la performance sur des documents volumineux.
- [x] **C3. Nouvel endpoint `GET /api/file/{vault}/pdf/info`** : Retourne les métadonnées seules (pages, titre, auteur) sans le contenu — permet à l'UI d'afficher les infos avant de charger le PDF lourd.
- [x] **C4. Endpoint download** : Déjà fonctionnel (`/api/file/{vault}/download`) — aucun changement nécessaire.
##### D. Frontend — Arborescence de fichiers (0.5 jour)
- [ ] **D1. Icône et filtre** : L'icône PDF (`file-text` de Lucide) est déjà mappée dans `EXT_ICONS` (`frontend/js/utils.js:129`). Une fois `.pdf` dans `SUPPORTED_EXTENSIONS`, les PDFs apparaissent automatiquement dans l'arborescence via l'API `list_directory`. Aucun changement UI nécessaire.
- [ ] **D2. Distinction visuelle** (optionnel) : Sous-titre léger sous le nom du fichier dans l'arborescence indiquant le nombre de pages (ex: « 12 pages ») pour différencier rapidement les PDF des MD. Donnée disponible via l'API `pdf/info`.
- [ ] **D3. Drag & drop et upload** : Le mécanisme d'upload existant (`POST /api/file/{vault}/upload`) fonctionne déjà pour tout type de fichier. Vérifier que le MIME type `application/pdf` est correctement détecté et que le watcher réindexe automatiquement.
- [x] **D1. Icône et filtre** : L'icône PDF (`file-text` de Lucide) est déjà mappée dans `EXT_ICONS` (`frontend/js/utils.js:129`). Une fois `.pdf` dans `SUPPORTED_EXTENSIONS`, les PDFs apparaissent automatiquement dans l'arborescence via l'API `list_directory`. Aucun changement UI nécessaire.
- [x] **D2. Distinction visuelle** (optionnel) : Sous-titre léger sous le nom du fichier dans l'arborescence indiquant le nombre de pages (ex: « 12 pages ») pour différencier rapidement les PDF des MD. Donnée disponible via l'API `pdf/info`.
- [x] **D3. Drag & drop et upload** : Le mécanisme d'upload existant (`POST /api/file/{vault}/upload`) fonctionne déjà pour tout type de fichier. Vérifier que le MIME type `application/pdf` est correctement détecté et que le watcher réindexe automatiquement.
##### E. Frontend — Viewer PDF (1 jour)
- [ ] **E1. Rendu inline natif** : Utiliser le visualiseur PDF intégré du navigateur via `<iframe>` pointant sur `/api/file/{vault}/pdf/stream?path=...`. Approche optimale :
- [x] **E1. Rendu inline natif** : Utiliser le visualiseur PDF intégré du navigateur via `<iframe>` pointant sur `/api/file/{vault}/pdf/stream?path=...`. Approche optimale :
- Zéro dépendance JS supplémentaire
- Rendu identique à Chrome/Firefox/Safari natif
- Support natif du zoom, recherche dans le document, navigation par pages, rotation
- L'iframe s'adapte en hauteur (`height: 100%` du content-area)
- [ ] **E2. Détection dans le viewer** : Dans `frontend/js/viewer.js`, fonction `renderFileContent()` — ajouter une branche après la détection `data.unsupported` :
- [x] **E2. Détection dans le viewer** : Dans `frontend/js/viewer.js`, fonction `renderFileContent()` — ajouter une branche après la détection `data.unsupported` :
- Si `data.is_pdf === true` → render l'iframe PDF au lieu du viewer markdown
- Si le navigateur ne supporte pas le rendu PDF inline → fallback sur l'UI « binaire » avec bouton download + bouton « Ouvrir dans un nouvel onglet »
- [ ] **E3. Barre d'outils PDF** : Dans la barre d'outils du viewer (celle qui a déjà les boutons Copier, Source, .md, PDF, Éditer, pop-out), pour les fichiers PDF :
- [x] **E3. Barre d'outils PDF** : Dans la barre d'outils du viewer (celle qui a déjà les boutons Copier, Source, .md, PDF, Éditer, pop-out), pour les fichiers PDF :
- Remplacer « Copier » / « Source » / « Éditer » par des actions spécifiques PDF
- Bouton « Télécharger » (.pdf) — déjà existant, fonctionne
- Bouton « Plein écran » — ouvre le PDF dans un nouvel onglet en plein écran
- Badge « N pages » indiquant le nombre de pages
- Bouton « pop-out » — gardé, ouvre le viewer PDF dans une popup séparée
- [ ] **E4. Thème** : L'iframe PDF est en dehors du DOM applicatif donc pas affecté par le thème dark/light. Ajouter un message discret « Le PDF s'affiche avec le thème de votre navigateur » si `_currentTheme === 'dark'` (les PDFs en fond blanc dans un thème sombre peuvent surprendre).
- [ ] **E5. Responsive** : L'iframe s'adapte à la largeur du content-area. En mode mobile, hauteur ajustée à la viewport. La toolbar mobile existante fonctionne avec les actions PDF.
- [x] **E4. Thème (optionnel, non retenu)** : L'iframe PDF est en dehors du DOM applicatif donc pas affecté par le thème dark/light. Ajouter un message discret « Le PDF s'affiche avec le thème de votre navigateur » si `_currentTheme === 'dark'` (les PDFs en fond blanc dans un thème sombre peuvent surprendre).
- [x] **E5. Responsive** : L'iframe s'adapte à la largeur du content-area. En mode mobile, hauteur ajustée à la viewport. La toolbar mobile existante fonctionne avec les actions PDF.
##### F. Frontend — Recherche (0.5 jour)
- [ ] **F1. Résultats de recherche** : Les PDFs apparaissent dans les résultats via le TF-IDF existant (le texte extrait est indexé). Ajouter un badge visuel « PDF » à côté du titre dans les résultats de recherche pour distinguer les PDFs des MD — utiliser l'icône `file-text`.
- [ ] **F2. Snippets de recherche** : Les extraits de contexte montrent le texte extrait du PDF avec surlignage des termes recherchés — fonctionnement identique aux MD via le mécanisme de snippet existant dans `search.py`.
- [ ] **F3. Filtres de recherche avancés** : Ajouter `ext:pdf` comme filtre pour limiter la recherche aux PDFs uniquement (complément aux filtres `created:`, `modified:`, `size:` déjà prévus #34).
- [x] **F1. Résultats de recherche** : Les PDFs apparaissent dans les résultats via le TF-IDF existant (le texte extrait est indexé). Ajouter un badge visuel « PDF » à côté du titre dans les résultats de recherche pour distinguer les PDFs des MD — utiliser l'icône `file-text`.
- [x] **F2. Snippets de recherche** : Les extraits de contexte montrent le texte extrait du PDF avec surlignage des termes recherchés — fonctionnement identique aux MD via le mécanisme de snippet existant dans `search.py`.
- [x] **F3. Filtres de recherche avancés** : Ajouter `ext:pdf` comme filtre pour limiter la recherche aux PDFs uniquement (complément aux filtres `created:`, `modified:`, `size:` déjà prévus #34).
##### G. Docker & Dépendances (0.5 jour)
- [ ] **G1. requirements.txt** : Ajouter `pymupdf>=1.24.0` (sinon `pypdf>=4.0` en fallback).
- [ ] **G2. Dockerfile** : Vérifier que l'image `python:3.11-slim` dispose des libs système nécessaires pour pymupdf. Si besoin, ajouter `libmupdf-dev` ou utiliser `pypdf` (pure Python) pour éviter la complexité. Recommandation : pypdf pour la simplicité Docker, pymupdf en option pour la performance.
- [ ] **G3. Configuration** : Ajouter `OBSIGATE_PDF_MAX_SIZE_MB` (défaut 50) pour limiter la taille des PDFs indexés et `OBSIGATE_PDF_EXTRACT_TIMEOUT` (défaut 30s).
- [x] **G1. requirements.txt** : `pypdf>=4.0` retenu (pymupdf optionnel, utilisé s'il est importable).
- [x] **G2. Dockerfile** : Vérifier que l'image `python:3.11-slim` dispose des libs système nécessaires pour pymupdf. Si besoin, ajouter `libmupdf-dev` ou utiliser `pypdf` (pure Python) pour éviter la complexité. Recommandation : pypdf pour la simplicité Docker, pymupdf en option pour la performance.
- [x] **G3. Configuration** : `OBSIGATE_PDF_MAX_SIZE_MB` (50) + `OBSIGATE_PDF_EXTRACT_TIMEOUT` (30s) — documentés dans `.env.example` et README FR/EN.
##### H. Tests (1 jour)
- [ ] **H1. Tests unitaires backend** :
- [x] **H1. Tests unitaires backend** :
- `test_pdf_reader.py` : extraction texte PDF simple, PDF vide, PDF avec uniquement des images (OCR non requis — retourne chaîne vide), PDF protégé par mot de passe, PDF corrompu, extraction métadonnées
- Fixtures : créer un PDF de test minimal (2 pages, texte simple) via `reportlab` dans les fixtures de test
- `test_pdf_indexing.py` : vérifier qu'un PDF dans un vault est correctement indexé, que le texte est recherchable, que `index_document()` gère l'extension `.pdf`
@@ -320,12 +329,12 @@
- Test d'intégration : naviguer vers un fichier PDF → l'iframe est rendue
- Test : fichier PDF dans les résultats de recherche
- Test : téléchargement de PDF fonctionnel
- [ ] **H3. CI** : Ajouter la fixture PDF de test dans les artefacts de CI. Les tests PDF sont sautés si pymupdf/pypdf n'est pas disponible.
- [x] **H3. CI** : Ajouter la fixture PDF de test dans les artefacts de CI. Les tests PDF sont sautés si pymupdf/pypdf n'est pas disponible.
##### I. Documentation utilisateur (inclus dans l'effort)
- [ ] **I1.** Mettre à jour README.md : mentionner le support PDF dans les formats supportés
- [x] **I1.** Mettre à jour README.md : mentionner le support PDF dans les formats supportés
- [ ] **I2.** Ajouter une note dans la FAQ : « Comment visualiser un PDF dans ObsiGate ? »
- [ ] **I3.** Documenter les limitations : pas d'OCR (PDFs scannés non recherchables), pas d'annotation PDF, pas d'édition de PDF
- [x] **I3.** Documenter les limitations : pas d'OCR (PDFs scannés non recherchables), pas d'annotation PDF, pas d'édition de PDF
##### J. Points d'attention / Risques
- **Performance** : Un PDF de 500 pages peut générer beaucoup de texte → `SEARCH_CONTENT_LIMIT` (100 Ko) limite l'indexation au début du document. Pour les PDFs volumineux, envisager une extraction paginée avec `SEARCH_CONTENT_LIMIT` réparti sur les N premières pages.
@@ -336,7 +345,7 @@
---
### 75. Éditeur multi-panneaux (Split View) ✅ Complété
### 75. Éditeur multi-panneaux (Split View) — ✅ TERMINÉ (reste I3 : tests E2E split view)
- **Effort :** 5-7 jours (réalisé) | **Impact :** 🟡
- **Statut :** Fonctionnel — toutes les sous-tâches implémentées (reste tests I2/I3)
- **Fichiers clés :** `frontend/js/pane-manager.js` (1082 loc), `frontend/js/viewer.js` (modifié), `frontend/js/ui.js` (modifié), `frontend/js/dashboard.js` (modifié), `frontend/js/palette.js` (modifié), `frontend/style.css` (modifié), `tests/test_pane_manager.py` (22 tests)
@@ -406,13 +415,13 @@
- [x] **E3.** Rendu paresseux (mémoire) — contenu masqué via `display:none` sur panneaux inactifs
- [x] **E4.** Verrouillage éditeur multi-panneau — même fichier ouvert dans 2 panneaux → focus le panneau existant
- [x] **G3.** Bouton reset dans la palette de commandes (🔄 Réinitialiser les panneaux)
- [ ] **I2.** Tests d'intégration frontend (JSDOM ou similaire)
- [ ] **I2.** Tests d'intégration frontend (JSDOM ou similaire) — **FAIT** : `tests/frontend/pane-manager.test.mjs` (9 tests, 100% verts)
- [ ] **I3.** Tests E2E Playwright
---
### 76. BooksLM — Console AI contextuelle par répertoire (style NotebookLM)
- **Effort :** 5-6 jours | **Impact :** 🟡
### 76. BooksLM — Console AI contextuelle par répertoire (style NotebookLM) — ✅ TERMINÉ
- **Effort :** 5-6 jours (réalisé) | **Impact :** 🟡
- **Description :** Console de chat AI contextuelle accessible via le menu contextuel des répertoires dans l'arborescence. Au clic sur « BooksLM », un panneau de chat s'ouvre à droite du viewer et indexe automatiquement toutes les ressources markdown (et PDF via #74) du répertoire courant et de ses sous-répertoires récursivement comme contexte pour un assistant AI. L'assistant peut répondre à des questions, résumer, synthétiser, et croiser l'information à travers tous les documents du scope — exactement comme NotebookLM de Google, mais pour n'importe quel répertoire de votre vault Obsidian.
- **Fonctionnement général :**
- L'utilisateur fait un clic-droit sur un répertoire dans l'arborescence → option « BooksLM »
@@ -423,65 +432,65 @@
- L'historique de chat est optionnellement sauvegardé (localStorage ou fichier `.books-lm.json` dans le répertoire)
- **Sous-tâches :**
##### A. Backend — Collecte et préparation du contexte (1.5-2 jours)
- [ ] **A1. Nouvel endpoint `POST /api/ai/bookslm/context`** : Reçoit `{vault, directory}` → parcourt récursivement le répertoire → lit tous les fichiers supportés → retourne un objet `{files: [{path, title, content, type: "md"|"pdf"}], total_chars, file_count, directory_tree}`
- [ ] **A2. Limites configurables** : `BOOKSLM_MAX_FILES` (défaut 200), `BOOKSLM_MAX_TOTAL_CHARS` (défaut 200 000), `BOOKSLM_MAX_FILE_CHARS` (défaut 30 000 par fichier). Les fichiers au-delà sont tronqués avec un message `[... continue dans le fichier]`.
- [ ] **A3. Filtrage intelligent** : Ignorer les fichiers cachés (`.` préfixe), les dossiers `_attachments/`, les fichiers binaires non-supportés. Respecter `.gitignore` ou `.obsigate-ignore` si présent.
- [ ] **A4. Streaming du contexte** : Pour les très gros répertoires, l'endpoint supporte le streaming SSE pour informer l'UI de la progression (« Indexation de 45/127 fichiers... »).
##### A. Backend — Collecte et préparation du contexte (1.5-2 jours) — ✅ livré (backend/bookslm.py, bookslm_routes.py)
- [x] **A1. Nouvel endpoint `POST /api/ai/bookslm/context`** : Reçoit `{vault, directory}` → parcourt récursivement le répertoire → lit tous les fichiers supportés → retourne un objet `{files: [{path, title, content, type: "md"|"pdf"}], total_chars, file_count, directory_tree}`
- [x] **A2. Limites configurables** : `BOOKSLM_MAX_FILES` (défaut 200), `BOOKSLM_MAX_TOTAL_CHARS` (défaut 200 000), `BOOKSLM_MAX_FILE_CHARS` (défaut 30 000 par fichier). Les fichiers au-delà sont tronqués avec un message `[... continue dans le fichier]`.
- [x] **A3. Filtrage intelligent** : Ignorer les fichiers cachés (`.` préfixe), les dossiers `_attachments/`, les fichiers binaires non-supportés. Respecter `.gitignore` ou `.obsigate-ignore` si présent.
- [x] **A4. Streaming du contexte (non retenu — collecte rapide, indicateur simple côté UI)** : Pour les très gros répertoires, l'endpoint supporte le streaming SSE pour informer l'UI de la progression (« Indexation de 45/127 fichiers... »).
##### B. Backend — Endpoint chat BooksLM (1 jour)
- [ ] **B1. Endpoint `POST /api/ai/bookslm/chat`** : Reçoit `{vault, directory, message, conversation_history: [{role, content}]}` → construit le contexte système à partir des fichiers du répertoire → appelle le provider AI configuré → stream la réponse via SSE.
- [ ] **B2. Prompt système** : Template par défaut optimisé : « Tu es un assistant de recherche qui aide à comprendre et analyser les documents d'un répertoire. Voici le contenu de tous les documents disponibles. Réponds en te basant UNIQUEMENT sur ces documents. Cite tes sources avec le nom du fichier. Si l'information n'est pas dans les documents, dis-le clairement. »
- [ ] **B3. Mode « Sources »** : Chaque réponse inclut les fichiers référencés (détectés via mention de titre ou contenu). L'UI affiche des badges de source cliquables.
- [ ] **B4. Mise en cache du contexte** : Le contexte du répertoire est caché en mémoire (hash du contenu) pour éviter de re-parser tous les fichiers à chaque message. Invalidé si un fichier est modifié (watcher).
- [ ] **B5. Provider** : Utilise la même abstraction provider que l'AI Editor (#27) — DeepSeek, OpenRouter, Gemini. Ajouter `BOOKSLM_DEFAULT_MODEL` dans `.env` (défaut : `DEEPSEEK_MODEL`).
##### B. Backend — Endpoint chat BooksLM (1 jour) — ✅ livré
- [x] **B1. Endpoint `POST /api/ai/bookslm/chat`** : Reçoit `{vault, directory, message, conversation_history: [{role, content}]}` → construit le contexte système à partir des fichiers du répertoire → appelle le provider AI configuré → stream la réponse via SSE.
- [x] **B2. Prompt système** : Template par défaut optimisé : « Tu es un assistant de recherche qui aide à comprendre et analyser les documents d'un répertoire. Voici le contenu de tous les documents disponibles. Réponds en te basant UNIQUEMENT sur ces documents. Cite tes sources avec le nom du fichier. Si l'information n'est pas dans les documents, dis-le clairement. »
- [x] **B3. Mode « Sources »** : Chaque réponse inclut les fichiers référencés (détectés via mention de titre ou contenu). L'UI affiche des badges de source cliquables.
- [x] **B4. Mise en cache du contexte** : Le contexte du répertoire est caché en mémoire (hash du contenu) pour éviter de re-parser tous les fichiers à chaque message. Invalidé si un fichier est modifié (watcher).
- [x] **B5. Provider** : Utilise la même abstraction provider que l'AI Editor (#27) — DeepSeek, OpenRouter, Gemini. Ajouter `BOOKSLM_DEFAULT_MODEL` dans `.env` (défaut : `DEEPSEEK_MODEL`).
##### C. Frontend — Panneau de chat BooksLM (2 jours)
- [ ] **C1. Module `frontend/js/bookslm.js`** : Nouveau module ES avec la classe `BooksLM` :
##### C. Frontend — Panneau de chat BooksLM (2 jours) — ✅ livré (frontend/js/bookslm.js)
- [x] **C1. Module `frontend/js/bookslm.js`** : Nouveau module ES avec la classe `BooksLM` :
- Gère l'état : `_isOpen`, `_currentDirectory`, `_messages[]`, `_contextFiles[]`, `_isLoading`
- Crée le DOM du panneau : conteneur latéral `.bookslm-panel` (450px, redimensionnable via poignée)
- Header : titre « BooksLM », nom du répertoire courant, bouton fermer, bouton « Nouvelle conversation »
- Zone de messages : scrollable, bulles utilisateur (droite) et assistant (gauche) avec Markdown rendu
- Zone d'entrée : `textarea` avec Ctrl+Enter pour envoyer, bouton envoyer
- Barre d'état : nombre de fichiers indexés, nombre total de caractères
- [ ] **C2. Intégration au menu contextuel** : Dans `frontend/js/context-menu.js`, ajouter l'option « 🧠 BooksLM » pour les nœuds de type `directory` dans l'arborescence. Visible seulement si le vault est accessible.
- [ ] **C3. Rendu Markdown dans le chat** : Utiliser le renderer Markdown existant (ou un sous-ensemble simplifié) pour afficher les réponses de l'AI avec support du **gras**, *italique*, `code`, listes, et tableaux.
- [ ] **C4. Streaming des réponses** : Connexion SSE pour afficher la réponse de l'AI token par token (effet « typing » naturel).
- [ ] **C5. Badges de sources** : Après chaque réponse, afficher les fichiers sources mentionnés sous forme de badges cliquables qui ouvrent le fichier dans le viewer principal.
- [ ] **C6. Mode plein écran** : Bouton pour basculer en mode plein écran (cache la sidebar, le panneau prend tout l'espace). Utile pour les sessions de recherche intense.
- [x] **C2. Intégration au menu contextuel** : Dans `frontend/js/context-menu.js`, ajouter l'option « 🧠 BooksLM » pour les nœuds de type `directory` dans l'arborescence. Visible seulement si le vault est accessible.
- [x] **C3. Rendu Markdown dans le chat** : Utiliser le renderer Markdown existant (ou un sous-ensemble simplifié) pour afficher les réponses de l'AI avec support du **gras**, *italique*, `code`, listes, et tableaux.
- [x] **C4. Streaming des réponses** : Connexion SSE pour afficher la réponse de l'AI token par token (effet « typing » naturel).
- [x] **C5. Badges de sources** : Après chaque réponse, afficher les fichiers sources mentionnés sous forme de badges cliquables qui ouvrent le fichier dans le viewer principal.
- [x] **C6. Mode plein écran** : Bouton pour basculer en mode plein écran (cache la sidebar, le panneau prend tout l'espace). Utile pour les sessions de recherche intense.
##### D. Frontend — Actions et UX (0.5-1 jour)
- [ ] **D1. Copier la réponse** : Bouton copie sur chaque message assistant.
- [ ] **D2. Régénérer** : Bouton pour régénérer la dernière réponse (utile si la réponse est hors-sujet).
- [ ] **D3. Exporter la conversation** : Bouton pour exporter l'historique en Markdown → sauvegarder comme note dans le répertoire courant.
- [ ] **D4. Historique des conversations** : Stockage dans `localStorage` par clé `bookslm-history-{vault}-{directory}`. Liste déroulante dans le header pour charger une conversation précédente.
- [ ] **D5. Indicateur de contexte** : Barre de progression montrant l'utilisation du contexte (% de la limite `BOOKSLM_MAX_TOTAL_CHARS`). Si le répertoire est trop gros, suggérer de réduire le scope.
- [ ] **D6. Suggestions de questions** : Après l'indexation, afficher 3 questions suggérées basées sur les titres et métadonnées des fichiers (« Résume ce répertoire », « Quels sont les thèmes principaux ? », « Y a-t-il des contradictions entre ces documents ? »).
##### D. Frontend — Actions et UX (0.5-1 jour) — ✅ livré (D5 partiel)
- [x] **D1. Copier la réponse** : Bouton copie sur chaque message assistant.
- [x] **D2. Régénérer** : Bouton pour régénérer la dernière réponse (utile si la réponse est hors-sujet).
- [x] **D3. Exporter la conversation** : Bouton pour exporter l'historique en Markdown → sauvegarder comme note dans le répertoire courant.
- [x] **D4. Historique des conversations** : Stockage dans `localStorage` par clé `bookslm-history-{vault}-{directory}`. Liste déroulante dans le header pour charger une conversation précédente.
- [x] **D5. Indicateur de contexte (barre de progression %) — non retenu, compteur fichiers/caractères affiché)** : Barre de progression montrant l'utilisation du contexte (% de la limite `BOOKSLM_MAX_TOTAL_CHARS`). Si le répertoire est trop gros, suggérer de réduire le scope.
- [x] **D6. Suggestions de questions** : Après l'indexation, afficher 3 questions suggérées basées sur les titres et métadonnées des fichiers (« Résume ce répertoire », « Quels sont les thèmes principaux ? », « Y a-t-il des contradictions entre ces documents ? »).
##### E. CSS & Design (0.5 jour)
- [ ] **E1. Panneau latéral** : Animation slide-in depuis la droite (300ms ease-out). Ombre portée pour séparation visuelle.
- [ ] **E2. Poignée de redimensionnement** : Similaire à `.sidebar-resize-handle`, curseur `col-resize`, largeur min 350px, max 800px. Persistance dans localStorage.
- [ ] **E3. Bulles de chat** : Style cohérent avec le thème actuel. Messages utilisateur avec accent-color, messages assistant avec fond `var(--surface2)`.
- [ ] **E4. Responsive** : Sur mobile (<768px), le panneau passe en plein écran (pas de split view). Navigation par swipe pour revenir au viewer.
- [ ] **E5. Thème sombre/clair** : Toutes les variables CSS utilisent les customs properties existantes → compatibilité automatique.
##### E. CSS & Design (0.5 jour) — ✅ livré
- [x] **E1. Panneau latéral** : Animation slide-in depuis la droite (300ms ease-out). Ombre portée pour séparation visuelle.
- [x] **E2. Poignée de redimensionnement** : Similaire à `.sidebar-resize-handle`, curseur `col-resize`, largeur min 350px, max 800px. Persistance dans localStorage.
- [x] **E3. Bulles de chat** : Style cohérent avec le thème actuel. Messages utilisateur avec accent-color, messages assistant avec fond `var(--surface2)`.
- [x] **E4. Responsive** : Sur mobile (<768px), le panneau passe en plein écran (pas de split view). Navigation par swipe pour revenir au viewer.
- [x] **E5. Thème sombre/clair** : Toutes les variables CSS utilisent les customs properties existantes → compatibilité automatique.
##### F. Intégration et compatibilité (0.5 jour)
- [ ] **F1. Compatibilité Split View (#75)** : Si le split view est actif, BooksLM s'ouvre en remplacement du panneau le plus à droite (ou en 3e colonne). Le panneau BooksLM est traité comme un type spécial de pane dans le PaneManager.
- [ ] **F2. Compatibilité AI Editor (#26-29)** : BooksLM utilise le même système de provider AI. Les clés API configurées pour l'AI Editor fonctionnent pour BooksLM.
- [ ] **F3. Compatibilité PDF (#74)** : Si le support PDF est implémenté, les PDFs dans le répertoire sont inclus dans le contexte (texte extrait).
- [ ] **F4. Palette de commandes (#31)** : Ajouter les commandes « BooksLM: Ouvrir pour le répertoire courant » et « BooksLM: Nouvelle conversation ».
##### F. Intégration et compatibilité (0.5 jour) — ✅ livré (F1 adapté : panneau dédié, pas un pane du PaneManager)
- [ ] **F1. Compatibilité Split View (#75) (adapté : panneau latéral indépendant, cohabite avec le split view)** : Si le split view est actif, BooksLM s'ouvre en remplacement du panneau le plus à droite (ou en 3e colonne). Le panneau BooksLM est traité comme un type spécial de pane dans le PaneManager.
- [x] **F2. Compatibilité AI Editor (#26-29)** : BooksLM utilise le même système de provider AI. Les clés API configurées pour l'AI Editor fonctionnent pour BooksLM.
- [x] **F3. Compatibilité PDF (#74)** : Si le support PDF est implémenté, les PDFs dans le répertoire sont inclus dans le contexte (texte extrait).
- [x] **F4. Palette de commandes (#31)** : Ajouter les commandes « BooksLM: Ouvrir pour le répertoire courant » et « BooksLM: Nouvelle conversation ».
##### G. Tests (1 jour)
- [ ] **G1. Tests unitaires backend** :
##### G. Tests (1 jour) — ✅ G1 livré (28 tests), G2/G3 non retenus
- [x] **G1. Tests unitaires backend** :
- `test_bookslm_context.py` : collecte récursive, respect des limites, filtrage fichiers cachés, streaming SSE
- `test_bookslm_chat.py` : construction du prompt, caching du contexte, invalidation après modification
- [ ] **G2. Tests d'intégration frontend** :
- [ ] **G2. Tests d'intégration frontend (non retenus)** :
- Ouverture du panneau BooksLM depuis le menu contextuel
- Envoi d'un message et affichage de la réponse
- Badges de sources cliquables
- Export de conversation
- Redimensionnement du panneau
- [ ] **G3. Tests E2E (Playwright, #58)** :
- [ ] **G3. Tests E2E (Playwright) (non retenus à ce jour)** :
- Test : clic-droit sur répertoire → BooksLM → panneau visible
- Test : chat fonctionnel → message envoyé → réponse reçue
- Test : fermeture et réouverture → historique restauré
@@ -498,7 +507,7 @@
### 78. Éditeur Excalidraw — Ouverture et édition de fichiers .excalidraw
- **Effort :** 3-4 jours | **Impact :** 🟡 | **Statut :** ⚪ Prévu
- **Effort :** 3-4 jours | **Impact :** 🟡 | **Statut :** 🟡 ~90% livré (2026-09 — éditeur iframe complet, détection, création, autosave, support `.excalidraw.md`. Reste : B5 extraction texte pour recherche, C8 menu contextuel, F2/F3 tests, vérif BUG-002)
- **Description :** Prise en charge native des fichiers `.excalidraw` dans ObsiGate avec un éditeur visuel complet intégré. L'utilisateur peut ouvrir un fichier `.excalidraw` depuis l'arborescence et obtenir l'éditeur de diagrammes Excalidraw directement dans ObsiGate — dessiner, modifier, sauvegarder, comme dans l'app Excalidraw standalone, mais intégré au flux de travail du vault Obsidian.
@@ -532,8 +541,8 @@
- **Sous-tâches :**
##### A. Fichier `frontend/excalidraw-editor.html` — Éditeur autonome (1.5 jour)
- [ ] **A1. Structure HTML** : Page minimale avec un `<div id="excalidraw-container">` en plein écran. Pas de header ObsiGate — tout l'espace est pour le canvas.
- [ ] **A2. Import Excalidraw** :
- [x] **A1. Structure HTML** : Page minimale avec un `<div id="excalidraw-container">` en plein écran. Pas de header ObsiGate — tout l'espace est pour le canvas.
- [x] **A2. Import Excalidraw** :
```html
<script type="module">
import * as ExcalidrawLib from "https://esm.sh/@excalidraw/excalidraw@0.18.0";
@@ -541,7 +550,7 @@
</script>
```
Version épinglée (`@0.18.0`) pour la stabilité. Mise à jour manuelle testée.
- [ ] **A3. Configuration du chemin d'assets** : Définir `window.EXCALIDRAW_ASSET_PATH` pour pointer vers le CDN des fonts/polices d'Excalidraw (nécessaire pour le rendu des polices handwriting).
- [x] **A3. Configuration du chemin d'assets** : Définir `window.EXCALIDRAW_ASSET_PATH` pour pointer vers le CDN des fonts/polices d'Excalidraw (nécessaire pour le rendu des polices handwriting).
- [ ] **A4. Initialisation React** : Excalidraw nécessite React + ReactDOM. Les importer depuis esm.sh également :
```html
<script type="module">
@@ -551,37 +560,37 @@
window.ReactDOM = ReactDOM;
</script>
```
- [ ] **A5. Rendu du composant** : Monter `<ExcalidrawLib.Excalidraw>` dans le conteneur avec les `initialData` reçues. Configurer les callbacks `onChange` pour détecter les modifications.
- [ ] **A6. Barre d'outils minimaliste** (dans l'iframe, superposée en haut à droite) :
- [x] **A5. Rendu du composant** : Monter `<ExcalidrawLib.Excalidraw>` dans le conteneur avec les `initialData` reçues. Configurer les callbacks `onChange` pour détecter les modifications.
- [x] **A6. Barre d'outils minimaliste** (dans l'iframe, superposée en haut à droite) :
- Bouton « 💾 Sauvegarder » → envoie les données au parent
- Badge « Modifié » (disparaît après sauvegarde)
- Indicateur de thème 🌙/☀️
- Optionnel : bouton « Export PNG » et « Export SVG » (natif Excalidraw)
- [ ] **A7. Communication postMessage** :
- [x] **A7. Communication postMessage** :
- Réception : écouter `message` → si `type === "init"`, charger `data.elements` + `data.appState` + `data.files` dans l'état Excalidraw. Si `type === "theme"`, basculer `theme` (dark/light).
- Émission : `postMessage({type: "save", data: {elements, appState, files}}, "*")` quand l'utilisateur sauvegarde.
- Émission : `postMessage({type: "ready"}, "*")` au chargement pour signaler que l'iframe est prête.
- Émission : `postMessage({type: "modified", dirty: true/false}, "*")` pour l'indicateur de modification.
- [ ] **A8. Gestion des erreurs** : Si les données sont invalides (JSON corrompu, pas un fichier Excalidraw), afficher un message d'erreur stylisé dans l'iframe.
- [x] **A8. Gestion des erreurs** : Si les données sont invalides (JSON corrompu, pas un fichier Excalidraw), afficher un message d'erreur stylisé dans l'iframe.
##### B. Backend — Détection et API (0.5 jour)
- [ ] **B1. Ajout à `SUPPORTED_EXTENSIONS`** : Ajouter `.excalidraw` dans `backend/indexer.py:56` pour que les fichiers apparaissent dans l'arborescence et soient indexés.
- [ ] **B2. Icône** : Ajouter `.excalidraw` dans `EXT_ICONS` (`frontend/js/utils.js`) → icône `pen-tool` ou `edit-3` (Lucide).
- [ ] **B3. Détection dans `api_file_view()`** : Dans `backend/main.py`, pour les fichiers `.excalidraw` :
- [x] **B1. Ajout à `SUPPORTED_EXTENSIONS`** : Ajouter `.excalidraw` dans `backend/indexer.py:56` pour que les fichiers apparaissent dans l'arborescence et soient indexés.
- [x] **B2. Icône** : Ajouter `.excalidraw` dans `EXT_ICONS` (`frontend/js/utils.js`) → icône `pen-tool` ou `edit-3` (Lucide).
- [x] **B3. Détection dans `api_file_view()`** : Dans `backend/main.py`, pour les fichiers `.excalidraw` :
- Lire le JSON
- Vérifier `data.get("type") === "excalidraw"`
- Retourner `is_excalidraw: true` + les données parsées (`elements`, `appState`, `files`)
- Si le JSON est invalide ou n'est pas un fichier Excalidraw valide → fallback sur le viewer JSON standard
- [ ] **B4. Endpoint de sauvegarde** : Le endpoint existant `PUT /api/file/{vault}` fonctionne déjà pour écrire du contenu. L'iframe envoie le JSON modifié via postMessage → le parent appelle l'API existante. Aucun nouvel endpoint nécessaire.
- [ ] **B5. Indexation du contenu texte** : Extraire le texte des éléments Excalidraw (`element.text` pour les éléments de type `text`) pour l'indexation TF-IDF. Permet de rechercher du texte présent dans les diagrammes.
- [ ] **B6. Contenu initial pour nouveaux fichiers** : Définir le squelette JSON minimum pour un fichier `.excalidraw` vide :
- [x] **B4. Endpoint de sauvegarde** : Le endpoint existant `PUT /api/file/{vault}` fonctionne déjà pour écrire du contenu. L'iframe envoie le JSON modifié via postMessage → le parent appelle l'API existante. Aucun nouvel endpoint nécessaire.
- [ ] **B5. Indexation du contenu texte** (NON FAIT) : extraire `element.text` des éléments pour la recherche TF-IDF — les fichiers sont indexés comme JSON brut.
- [x] **B6. Contenu initial pour nouveaux fichiers** : Définir le squelette JSON minimum pour un fichier `.excalidraw` vide :
```json
{"type":"excalidraw","version":2,"elements":[],"appState":{"viewBackgroundColor":"#ffffff"},"files":{}}
```
Ce squelette est retourné par le backend quand on crée un fichier `.excalidraw` (utilisé par `POST /api/file/{vault}`).
##### C. Frontend — Intégration dans le viewer (1 jour)
- [ ] **C1. Module `frontend/js/excalidraw-viewer.js`** (nouveau) : Fonction `renderExcalidraw(container, data, vault, path)` :
- [x] **C1. Module `frontend/js/excalidraw-viewer.js`** (nouveau) : Fonction `renderExcalidraw(container, data, vault, path)` :
- Crée une `<iframe>` avec `src="/frontend/excalidraw-editor.html"` et `sandbox="allow-scripts allow-same-origin"`
- Stocke une référence à l'iframe pour la communication
- Attend le message `ready` de l'iframe
@@ -589,46 +598,46 @@
- Écoute les messages `save` → appelle `saveFile(vault, path, JSON.stringify(data))` via l'API existante
- Écoute les messages `modified` → met à jour l'indicateur dans la barre d'onglets
- Gère le thème : écoute `themeChanged` → envoie `postMessage({type: "theme", theme})` à l'iframe
- [ ] **C2. Dispatch dans `viewer.js`** : Dans `renderFileContent()` ou `renderFile()` :
- [x] **C2. Dispatch dans `viewer.js`** : Dans `renderFileContent()` ou `renderFile()` :
- Après la détection `data.is_json`, ajouter une branche : si `data.is_excalidraw === true` → appeler `renderExcalidraw(container, data, vaultName, filePath)`
- Ne PAS passer par le viewer markdown standard
- [ ] **C3. Barre d'outils contextuelle** : Dans la toolbar du viewer (celle avec Copier/Source/Éditer/PDF/pop-out) :
- [x] **C3. Barre d'outils contextuelle** : Dans la toolbar du viewer (celle avec Copier/Source/Éditer/PDF/pop-out) :
- Pour les fichiers `.excalidraw` : remplacer « Éditer (Forge) » par « Ouvrir dans Excalidraw.com » (lien externe, nouvel onglet)
- Garder « Télécharger » (.excalidraw) et « pop-out »
- Badge « Excalidraw » avec icône `pen-tool`
- [ ] **C4. Auto-save** : Débounce 2 secondes après la dernière modification dans l'iframe → sauvegarde automatique silencieuse (comme l'éditeur markdown #29). L'iframe émet `modified` → le parent démarre un timer → au bout de 2s sans nouvelle modification → `postMessage({type: "requestSave"})` → l'iframe répond avec `save` → le parent écrit via l'API.
- [ ] **C5. Raccourci Ctrl+S** : L'iframe intercepte Ctrl+S → envoie `save` au parent → le parent sauvegarde → confirmation visuelle (toast « Excalidraw sauvegardé »).
- [ ] **C6. Compatibilité Split View (#75)** : L'iframe s'affiche dans le content-area du panneau actif. Le `PaneTabManager` gère le cache : quand on switch d'onglet, l'état de l'iframe est préservé (elle reste dans le DOM, juste masquée). Plusieurs iframes Excalidraw peuvent coexister dans différents panneaux.
- [ ] **C7. Création via la modale « Nouveau fichier »** : Dans `frontend/js/ui.js`, fonction `showCreateFileModal()` :
- [x] **C4. Auto-save** : Débounce 2 secondes après la dernière modification dans l'iframe → sauvegarde automatique silencieuse (comme l'éditeur markdown #29). L'iframe émet `modified` → le parent démarre un timer → au bout de 2s sans nouvelle modification → `postMessage({type: "requestSave"})` → l'iframe répond avec `save` → le parent écrit via l'API.
- [x] **C5. Raccourci Ctrl+S** : L'iframe intercepte Ctrl+S → envoie `save` au parent → le parent sauvegarde → confirmation visuelle (toast « Excalidraw sauvegardé »).
- [x] **C6. Compatibilité Split View (#75)** : L'iframe s'affiche dans le content-area du panneau actif. Le `PaneTabManager` gère le cache : quand on switch d'onglet, l'état de l'iframe est préservé (elle reste dans le DOM, juste masquée). Plusieurs iframes Excalidraw peuvent coexister dans différents panneaux.
- [x] **C7. Création via la modale « Nouveau fichier »** : Dans `frontend/js/ui.js`, fonction `showCreateFileModal()` :
- Ajouter `<option value=".excalidraw">Excalidraw (.excalidraw)</option>` dans le `<select id="file-ext-select">` (après `.json`)
- Quand l'extension `.excalidraw` est sélectionnée, le backend crée le fichier avec le squelette JSON minimum (B6)
- Après création → `openFile(vault, path)` → le viewer détecte `is_excalidraw: true` → l'iframe s'ouvre avec le canvas vierge
- Fonctionne aussi via la palette de commandes `Ctrl+Alt+Space` → « Nouveau fichier » (action `create-file` existante)
- [ ] **C8. Création via le menu contextuel de l'arborescence** : Dans `frontend/js/context-menu.js`, ajouter une option « 🎨 Nouveau diagramme Excalidraw » dans le menu contextuel des répertoires → ouvre directement la modale avec `.excalidraw` pré-sélectionné.
- [ ] **C8. Création via le menu contextuel (NON FAIT — la modale « Nouveau fichier » suffit)** : Dans `frontend/js/context-menu.js`, ajouter une option « 🎨 Nouveau diagramme Excalidraw » dans le menu contextuel des répertoires → ouvre directement la modale avec `.excalidraw` pré-sélectionné.
##### D. CSS & Design (0.5 jour)
- [ ] **D1. Styles de l'iframe dans ObsiGate** : L'iframe occupe 100% du content-area (`width: 100%; height: 100%; border: none;`). Aucun padding ni marge.
- [x] **D1. Styles de l'iframe dans ObsiGate** : L'iframe occupe 100% du content-area (`width: 100%; height: 100%; border: none;`). Aucun padding ni marge.
- [ ] **D2. Thème dark/light** : L'iframe reçoit le thème courant → Excalidraw applique son thème interne (`theme="dark"` ou `theme="light"`). Les couleurs sont cohérentes avec ObsiGate grâce à la palette d'Excalidraw.
- [ ] **D3. Écran de chargement** : Pendant le chargement de l'iframe (React + Excalidraw ~2 Mo), afficher un spinner « Chargement de l'éditeur Excalidraw... » dans le content-area. L'iframe envoie `ready` → le spinner disparaît.
- [ ] **D4. Responsive** : L'iframe s'adapte à la largeur du panneau. En mode mobile (<768px), l'éditeur Excalidraw est utilisable (UI tactile native).
- [x] **D3. Écran de chargement** : Pendant le chargement de l'iframe (React + Excalidraw ~2 Mo), afficher un spinner « Chargement de l'éditeur Excalidraw... » dans le content-area. L'iframe envoie `ready` → le spinner disparaît.
- [x] **D4. Responsive** : L'iframe s'adapte à la largeur du panneau. En mode mobile (<768px), l'éditeur Excalidraw est utilisable (UI tactile native).
##### E. Gestion des conflits et edge cases (0.5 jour)
- [ ] **E1. Fichier modifié à l'extérieur** : Si le fichier est modifié par Syncthing/watcher pendant l'édition → détecter via le watcher → afficher un bandeau « Ce fichier a été modifié à l'extérieur. Recharger ? » avec boutons [Recharger] [Ignorer].
- [ ] **E2. Plusieurs onglets** : Deux onglets sur le même fichier `.excalidraw` → le second détecte que le fichier est déjà ouvert → focus l'onglet existant (comportement existant du `TabManager` #E4).
- [ ] **E3. Fichier vide ou nouveau** : Couvert par C7/C8 — la création d'un `.excalidraw` produit un canvas vierge avec le squelette JSON minimum (B6). L'iframe gère nativement le cas `elements: []`.
- [x] **E1. Fichier modifié à l'extérieur** : Si le fichier est modifié par Syncthing/watcher pendant l'édition → détecter via le watcher → afficher un bandeau « Ce fichier a été modifié à l'extérieur. Recharger ? » avec boutons [Recharger] [Ignorer].
- [x] **E2. Plusieurs onglets** : Deux onglets sur le même fichier `.excalidraw` → le second détecte que le fichier est déjà ouvert → focus l'onglet existant (comportement existant du `TabManager` #E4).
- [x] **E3. Fichier vide ou nouveau** : Couvert par C7/C8 — la création d'un `.excalidraw` produit un canvas vierge avec le squelette JSON minimum (B6). L'iframe gère nativement le cas `elements: []`.
- [ ] **E4. Fichier corrompu** : Si le JSON ne contient pas `type: "excalidraw"` ou est invalide → fallback sur le viewer JSON standard avec un message « Ce fichier .excalidraw semble corrompu ».
- [ ] **E5. Pop-out** : Le bouton pop-out fonctionne — il ouvre l'éditeur dans une popup séparée avec sa propre iframe. Utile pour éditer sur un deuxième écran.
- [ ] **E6. Annulation (Ctrl+Z)** : Natif dans Excalidraw — l'historique d'annulation est géré par l'état interne de l'iframe. Pas besoin d'interaction avec le parent.
- [x] **E5. Pop-out** : Le bouton pop-out fonctionne — il ouvre l'éditeur dans une popup séparée avec sa propre iframe. Utile pour éditer sur un deuxième écran.
- [x] **E6. Annulation (Ctrl+Z)** : Natif dans Excalidraw — l'historique d'annulation est géré par l'état interne de l'iframe. Pas besoin d'interaction avec le parent.
##### F. Tests (0.5 jour)
- [ ] **F1. Tests backend** :
##### F. Tests (0.5 jour) — F1 ✅ (6 tests test_excalidraw.py)
- [x] **F1. Tests backend** :
- `test_excalidraw_detection.py` : fichier `.excalidraw` valide → `is_excalidraw: true`, JSON invalide → fallback JSON, fichier sans `type: excalidraw` → fallback
- `test_excalidraw_search.py` : texte extrait des éléments → recherchable via TF-IDF
- [ ] **F2. Tests frontend** :
- [ ] **F2. Tests frontend (non retenus)** :
- Chargement de l'iframe avec des données de test
- Communication postMessage (init → ready → save)
- Changement de thème propagé à l'iframe
- [ ] **F3. Tests E2E (Playwright, #58)** :
- [ ] **F3. Tests E2E (Playwright) (NON FAITS)** :
- Ouvrir un fichier `.excalidraw` → l'iframe se charge → le canvas Excalidraw est visible
- Dessiner un rectangle → sauvegarder → recharger → le rectangle est toujours là
- Basculer thème sombre → l'iframe passe en dark mode
@@ -718,29 +727,23 @@
- [ ] UI : toggle « Recherche sémantique » dans la barre de recherche
- [ ] UI : score de similarité dans les résultats
### 71. Tableau de bord administrateur
- **Effort :** 2 jours | **Impact :** 🟢
### 71. Tableau de bord administrateur — Backend ✅, Frontend ✅
- **Effort :** 2 jours | **Impact :** 🟢 | **Statut :** ✅ Terminé (2026-08, commits 46be24f / 88ab8db / 01453bc)
- **Description :** Une page web dédiée accessible uniquement aux administrateurs qui centralise tout le monitoring et la gestion du serveur ObsiGate en un seul endroit. Un cockpit de pilotage pour le sysadmin.
- **Widgets temps réel** (rafraîchis via SSE) :
- **CPU / RAM / Disque** : jauges visuelles avec seuils d'alerte (vert < 70%, orange < 90%, rouge > 90%). Permet de voir en un coup d'œil si le serveur est en surcharge.
- **Requêtes par minute** : graphique sparkline des dernières 24h. Permet de détecter les pics d'activité anormaux (attaques, bots, bug qui spam l'API).
- **Utilisateurs actifs** : nombre de sessions connectées en ce moment, compteur de recherches en cours.
- **Gestion des utilisateurs** :
- Tableau triable/filtrable de tous les comptes (nom, rôle, date de création, dernière connexion, nombre de vaults).
- Création, édition, suppression d'utilisateurs. Attribution de rôles (admin/user/readonly).
- Réinitialisation de mot de passe administrateur.
- **Logs d'audit visuels** :
- Tableau chronologique des 500 dernières actions : qui a fait quoi, quand, depuis quelle IP.
- Filtres par utilisateur, type d'action (login, création fichier, suppression, modification settings), plage de dates.
- Export CSV pour analyse externe.
- **Statistiques backups** : graphique d'évolution du nombre et de la taille des backups par vault. Détection automatique des vaults sans backup récent.
- **Pourquoi c'est important :** Actuellement, administrer ObsiGate nécessite de se connecter en SSH au serveur et de lire des fichiers JSON. Le dashboard rend toutes ces opérations accessibles depuis l'interface web, avec des visuels qui permettent de diagnostiquer un problème en 10 secondes au lieu de 10 minutes de CLI.
- **Sous-tâches :**
- [ ] Widgets temps réel : CPU, mémoire, espace disque, requêtes/min (rafraîchissement SSE)
- [ ] Gestion utilisateurs : tableau triable, création/édition/suppression, filtre par rôle
- [ ] Logs d'audit : visualisation des 500 dernières entrées, filtre par utilisateur/action/date
- [ ] Backup stats : graphique d'évolution (taille totale, nombre par vault, âge moyen)
- [ ] Protection : accès restreint au rôle `admin` uniquement
- **Implémentation réelle (vérifiée) :**
- **Backend `backend/admin.py`** (nouveau, 261 lignes) — 4 endpoints admin-gated (`require_admin`) :
- `GET /api/admin/stats` — CPU/RAM/Disk/Uptime via psutil
- `GET /api/admin/audit` — 500 dernières entrées d'audit avec filtres `user`/`action`/`limit`/`offset`
- `GET /api/admin/backup-stats` — compte + taille + age par vault
- `GET /api/admin/stream` — Server-Sent Events qui push les stats toutes les 5s
- `backend/main.py` — routeur monté + middleware gzip bypass pour `/api/admin/stream`
- `backend/requirements.txt` — ajout `psutil>=5.9`
- **Tests :** `tests/test_admin.py` (13 tests, 100% verts) — couvrent auth + filtres + format SSE
- **Complété (2026-08) :**
- `frontend/admin.html` (472 l.) + `frontend/js/admin.js` (544 l.) — dashboard standalone avec navigation par sections sticky + thèmes
- Lien « Admin » dans le user menu (`#admin-menu-row`, gating `role === "admin"`)
- Widgets temps réel via EventSource `/api/admin/stream` + snapshot `/api/admin/stats`
- CRUD users + fix routing `/admin.html` + fix scroll
### 72. API publique documentée — OpenAPI 3.1
- **Effort :** 1-2 jours | **Impact :** 🟢
@@ -805,19 +808,19 @@
- **Sous-tâches :**
##### A. Initialisation du projet Tauri (1 jour)
- [ ] Installer Rust + toolchain Tauri : `cargo install tauri-cli`
- [ ] Initialiser `tauri init` dans `/desktop/` avec config Windows/Linux
- [ ] Configurer `tauri.conf.json` : fenêtre 1200×800, sans cadre, titre "ObsiGate"
- [ ] Configurer le build : cibles `.msi`/`.nsis` (Windows), `.deb`/`.AppImage` (Linux)
- [ ] Ajouter les icônes desktop (`.ico` Windows, `.png` Linux) dans `desktop/icons/`
##### A. Initialisation du projet Tauri (1 jour) — ✅ livré (vérifié 2026-09)
- [x] Toolchain : tauri-cli 2.11.4 / rustc 1.94.1
- [x] Projet Tauri v2 dans `desktop/` (Cargo.toml, build.rs)
- [x] `tauri.conf.json` : fenêtre 1200×800 (min 800×600), titre "ObsiGate"
- [x] Build : cibles `.msi`/`.nsis` (Windows), `.deb`/`.AppImage` (Linux)
- [x] Icônes desktop dans `desktop/icons/` (.ico, .icns, .png)
##### B. Intégration du backend Python (2-3 jours)
- [ ] Bundle Python : créer un dossier `python-embed/` avec `python3.11-embed` + `site-packages/` (requirements.txt gelés)
- [ ] Script `sidecar.py` : lance uvicorn sur `localhost:17890`, log dans `%APPDATA%/ObsiGate/logs/`
- [ ] Code Rust `main.rs` : spawn le sidecar comme processus fils, health check (boucle `GET /api/health` avec timeout 10s), kill propre au `SIGTERM`
- [ ] Menu tray : icône dans la barre des tâches avec options « Ouvrir ObsiGate », « Quitter »
- [ ] Gestion du port : détecter si 17890 est déjà utilisé → incrémenter (17891, 17892...)
##### B. Intégration du backend Python (2-3 jours) — ✅ livré (variante : uvicorn spawné directement, pas de sidecar.py)
- [x] Bundle Python : `desktop/python-embed/` (python3.11-embed + site-packages, validé par validate-structure.sh)
- [x] Lancement backend : `spawn_backend()` Rust lance `python-embed -m uvicorn backend.main:app` (équivalent sidecar), logs dans `%APPDATA%/ObsiGate/logs/backend.log`
- [x] `main.rs` : spawn processus fils, health check (`GET /api/health`, 30 essais × 2s), kill propre (SIGTERM→wait→kill)
- [x] Menu tray (voir section C ✅)
- [x] Gestion du port : `pick_free_port()` scan 17890..17899 si occupé (commit c066b2c, 3 tests Rust)
##### C. Fonctionnalités desktop natives (2-3 jours) — ✅ COMPLÉTÉ
- [x] **Sélecteur de dossier** : `pick_vault_folder` via `tauri_plugin_dialog` → ajoute le vault dans config.json
@@ -832,28 +835,32 @@
- [x] **Pas de terminal visible** : `#![windows_subsystem = "windows"]` + `CREATE_NO_WINDOW` sur le processus Python
- [x] **Persistance fenêtre** : position/taille sauvegardée dans `config.json`
##### D. Build et distribution (2 jours)
##### D. Build et distribution (2 jours) — ✅ COMPLÉTÉ
- [x] **CI/CD automatisé** : workflow Gitea Actions `.gitea/workflows/desktop-build.yml` — build Windows + Linux à chaque push sur `main` (si `desktop/` modifié), upload des artefacts `.msi`/`.AppImage`/`.deb` en release
- [ ] **Build Windows** : `tauri build --target x86_64-pc-windows-msvc` → `.msi` + `.exe` installer
- [ ] **Build Linux** : `tauri build --target x86_64-unknown-linux-gnu` → `.deb`, `.rpm`, `.AppImage`
- [x] **Auto-update** : `tauri-plugin-updater` → vérifie `https://git.dracodev.net/api/v1/repos/Projets/ObsiGate/releases/latest`
- [x] **Build Windows local** : `cargo build --release` vérifié (rustc 1.94.1) — `cargo tauri build --bundles msi` prêt
- [x] **Build Linux local** : workflow CI couvre `.deb`, `.rpm`, `.AppImage`
- [x] **Auto-update** : `tauri-plugin-updater` configuré → vérifie `https://git.dracodev.net/api/v1/repos/Projets/ObsiGate/releases/latest`
- [ ] **Signature de code** : configurer le certificat (optionnel mais recommandé pour Windows)
- [ ] **Page de release** : intégrer le build desktop dans les releases Gitea + README d'installation
- [x] **Page de release** : README desktop existe (`desktop/README.md`)
##### E. Expérience utilisateur (1 jour)
##### E. Expérience utilisateur (1 jour) — ✅ COMPLÉTÉ
- [x] Écran de chargement pendant le démarrage du backend (« ObsiGate démarre... » avec spinner) — splash inline `#boot-splash` dans `index.html`, retiré quand `app.js` signale le boot ; statut mis à jour depuis Rust
- [ ] Gestion des erreurs : backend crash → message explicite + bouton « Redémarrer »
- [ ] Sauvegarde des préférences desktop (taille fenêtre, position, dernier vault)
- [ ] Première expérience : wizard « Choisissez votre vault » au premier lancement
- [ ] Icône dans le menu Démarrer / dock Linux avec jumplist (vaults récents)
- [x] Gestion des erreurs : backend crash → `showBackendCrashBanner()` appelé par le monitor loop toutes les 5s
- [x] Sauvegarde des préférences desktop : position/taille fenêtre sauvées dans `%APPDATA%/ObsiGate/config.json` au close + restauration au startup
- [x] Première expérience : config par défaut auto-créée au premier lancement (vault `~/voute_obsidian`, dir `~USERPROFILE`)
- [ ] Wizard interactif « Choisissez votre vault » au premier lancement (optionnel — config auto suffisante)
- [ ] Jumplist vaults récents dans le menu Démarrer (optionnel)
##### F. Tests (1 jour)
- [ ] Test : installation → premier lancement → wizard vault → ouverture fichier
- [ ] Test : tray icon → réduire dans la barre → restaurer
- [ ] Test : notifications natives → fichier modifié → popup OS
- [ ] Test : association `.md` → double-clic → ouvre dans ObsiGate
- [ ] Test : auto-update → nouvelle version dispo → téléchargement → installation
- [ ] Test : cleanup → désinstallation propre (pas de fichiers résiduels)
##### F. Tests (1 jour) — ✅ COMPLÉTÉ
- [x] 16 tests Rust unitaires : config roundtrip, JSON parsing (empty/partial/corrupted), vault dedup, dir remove, backend URL, paths, branding, edge cases
- [x] Build debug + release vérifié (rustc 1.94.1, tauri-cli 2.11.4)
- [x] CI desktop workflow existant (desktop-build.yml)
- [ ] Test E2E : installation → premier lancement → wizard vault → ouverture fichier (manuel)
- [ ] Test E2E : tray icon → réduire → restaurer (manuel)
- [ ] Test E2E : notifications natives → fichier modifié → popup OS (manuel)
- [ ] Test E2E : association `.md` → double-clic → ouvre dans ObsiGate (manuel)
- [ ] Test E2E : auto-update → nouvelle version → install (manuel)
- [ ] Test E2E : désinstallation propre (manuel)
- **Prérequis techniques :**
- Rust ≥ 1.75 (stable) — installé via `rustup`
@@ -868,12 +875,13 @@
| Priorité | Items | Effort total estimé |
|---|---|---|
| ✅ Complété | #1 → #57 | ~65 jours |
| 🔵 P1 | ✅ #58 (Playwright E2E) | Terminé |
| 🔵 P2 | 🔨 #77 (Tauri Desktop) | 8-12 jours |
| ⚪ P3 | #59, #61-66, #74, #75, #76, #78 (11 items) | 35-46 jours |
| ⚪ P4 | #67 → #73 (7 items) | 18-23 jours |
| **Total restant** | **20 items** | **63-84 jours** |
| ✅ Complété | #1 → #59, #63-66, #71, #74, #75*, #76 (58 E2E, 59 offline, 63 i18n, 64 MFA TOTP+WebAuthn, 65 thèmes, 66 export, 71 admin, 74 PDF, 76 BooksLM) | ~75 jours réalisés |
| 🔵 P2 restant | #77 Desktop : signature code (optionnel), wizard 1er lancement (optionnel), 6 tests E2E **manuels** | ~1-2 jours |
| ⚪ P3 restant | #61 Plugins système (4-5j) · #62 Collaboration Yjs (5-7j) · #78 Excalidraw finitions (B5 recherche, C8, F3 E2E, BUG-002) (~1-1.5j) | ~10-13.5 jours |
| ⚪ P4 restant | #67 Push (2j) · #68 Health enrichi (1j) · #69 Mobile éditeur (2-3j) · #70 Sémantique (4-5j) · #72 OpenAPI (1-2j) · #73 Sync (6-8j) | 16-21 jours |
| **Total restant** | **9 items + finitions** | **~28-37 jours** |
\* #75 : 100% fonctionnel, il ne reste que les tests E2E Playwright de la sous-tâche I3.
---
@@ -882,4 +890,5 @@
- Les items P3/P4 ne sont pas ordonnés par priorité interne — à raffiner selon les retours utilisateurs.
- L'effort inclut le développement + tests unitaires + intégration CI, mais pas la documentation utilisateur.
- Les items marqués 🟢 (nice-to-have) sont de bons candidats pour des contributions externes.
- Le mode hors-ligne (#59) et l'i18n (#63) sont les P3 ayant le meilleur rapport effort/valeur.
- #59 (hors-ligne), #63 (i18n), #64 (MFA), #65-66, #71, #74, #75, #76 sont livrés — les P3 restants à plus fort rapport effort/valeur : #78 finitions (recherche texte Excalidraw) et #68 (health check, 1j).
- #78 a un bug ouvert référencé dans docs/ISSUES_TODOLIST.md (BUG-002, loading infini Excalidraw) — fixés par les commits a4ea322/185d603, à revalider sur poste client avant de cocher F3.
+472
View File
@@ -0,0 +1,472 @@
<!doctype html>
<html lang="fr" data-theme="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title data-i18n="admin.page_title">ObsiGate — Administration</title>
<meta name="robots" content="noindex" />
<link rel="icon" type="image/svg+xml" href="/static/icons/icon-72x72.svg" />
<!-- Anti-FOUC : applique vite le mode du thème sauvegardé avant le CSS -->
<script>
(function () {
var root = document.documentElement;
try {
var mode = localStorage.getItem("obsigate-theme-mode") || "dark";
root.setAttribute("data-theme", mode);
var light = mode === "light" || mode === "sepia";
root.style.setProperty("--bg-primary", light ? "#ffffff" : "#0f1117");
root.style.setProperty("--text-primary", light ? "#1a1a1a" : "#e6edf3");
} catch (e) { root.setAttribute("data-theme", "dark"); }
})();
</script>
<link rel="stylesheet" href="/static/style.css" />
<style>
/* ── Admin page — local styles (kept inline to limit impact on /static/style.css) ── */
:root {
--admin-card-bg: var(--bg-secondary, #161b22);
--admin-card-border: var(--border, #21262d);
--admin-success: var(--success, #3fb950);
--admin-warning: var(--warning, #f59e0b);
--admin-danger: var(--danger, #ff7b72);
}
body.admin-page {
margin: 0;
min-height: 100vh;
overflow: auto; /* override SPA style.css: body{overflow:hidden} */
height: auto; /* override SPA style.css: body{height:100vh} */
background: var(--bg-primary, #0f1117);
color: var(--text-primary, #e6edf3);
font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
}
/* ── Sticky section nav ── */
.admin-subnav {
position: sticky;
top: 0;
z-index: 50;
display: flex;
gap: 6px;
flex-wrap: nowrap;
overflow-x: auto;
padding: 8px 24px;
background: var(--bg-secondary, #161b22);
border-bottom: 1px solid var(--border, #21262d);
backdrop-filter: blur(4px);
scrollbar-width: thin;
}
.admin-subnav::-webkit-scrollbar { height: 6px; }
.admin-subnav a {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 500;
color: var(--text-secondary, #8b949e);
text-decoration: none;
border: 1px solid transparent;
transition: background 0.15s, color 0.15s, border-color 0.15s;
}
.admin-subnav a:hover {
background: var(--bg-hover, #1f2430);
color: var(--text-primary, #e6edf3);
}
.admin-subnav a.active {
background: var(--accent-bg, #1f2a3a);
color: var(--accent-text, #79c0ff);
border-color: var(--accent, #58a6ff);
}
.admin-section { scroll-margin-top: 64px; }
@media (max-width: 600px) {
.admin-subnav { padding: 8px 12px; }
.admin-subnav a { font-size: 0.8rem; padding: 6px 10px; }
}
.admin-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 24px;
background: var(--bg-secondary, #161b22);
border-bottom: 1px solid var(--admin-card-border);
}
.admin-header-left { display: flex; align-items: center; gap: 14px; }
.admin-header h1 {
font-size: 1.25rem;
font-weight: 600;
margin: 0;
color: var(--text-primary, #e6edf3);
}
.admin-header .admin-subtitle {
font-size: 0.85rem;
color: var(--text-secondary, #8b949e);
}
.admin-header-right { display: flex; align-items: center; gap: 12px; }
#admin-role-badge {
padding: 4px 10px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
background: var(--accent-bg, #1f2a3a);
color: var(--accent-text, #79c0ff);
border: 1px solid var(--accent, #58a6ff);
}
#admin-role-badge[data-role="admin"] {
background: var(--success-bg, #1a3d1f);
color: var(--success, #3fb950);
border-color: var(--success, #3fb950);
}
.admin-back-btn {
padding: 6px 14px;
background: var(--bg-hover, #1f2430);
color: var(--text-primary, #e6edf3);
border: 1px solid var(--admin-card-border);
border-radius: 6px;
font-size: 0.85rem;
cursor: pointer;
text-decoration: none;
transition: background 0.15s;
}
.admin-back-btn:hover { background: var(--bg-sidebar, #13161d); }
.admin-main {
max-width: 1400px;
margin: 0 auto;
padding: 24px;
display: grid;
gap: 24px;
}
.admin-section {
background: var(--admin-card-bg);
border: 1px solid var(--admin-card-border);
border-radius: 10px;
padding: 20px;
}
.admin-section h2 {
font-size: 1.05rem;
font-weight: 600;
margin: 0 0 16px 0;
color: var(--text-primary, #e6edf3);
display: flex;
align-items: center;
gap: 8px;
}
.admin-section h2::before {
content: "";
display: inline-block;
width: 4px;
height: 18px;
background: var(--accent, #58a6ff);
border-radius: 2px;
}
/* ── Stats grid ── */
#admin-stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 14px;
}
.admin-stat-card {
background: var(--bg-hover, #1f2430);
border: 1px solid var(--admin-card-border);
border-radius: 8px;
padding: 14px;
display: flex;
flex-direction: column;
gap: 8px;
}
.admin-stat-label {
font-size: 0.75rem;
color: var(--text-secondary, #8b949e);
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 600;
}
.admin-stat-value {
font-size: 1.6rem;
font-weight: 700;
color: var(--text-primary, #e6edf3);
}
.admin-stat-unit {
font-size: 0.85rem;
font-weight: 400;
color: var(--text-secondary, #8b949e);
}
.admin-stat-bar {
height: 6px;
background: var(--bg-primary, #0f1117);
border-radius: 3px;
overflow: hidden;
}
.admin-stat-bar-fill {
height: 100%;
border-radius: 3px;
transition: width 0.4s ease, background 0.4s ease;
}
/* ── Tables ── */
.admin-table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
.admin-table th, .admin-table td {
padding: 8px 12px;
text-align: left;
border-bottom: 1px solid var(--admin-card-border);
}
.admin-table th {
background: var(--bg-primary, #0f1117);
color: var(--text-secondary, #8b949e);
font-weight: 600;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.admin-table tbody tr:hover {
background: var(--bg-hover, #1f2430);
}
.admin-table code {
background: var(--bg-primary, #0f1117);
padding: 2px 6px;
border-radius: 4px;
font-size: 0.8rem;
color: var(--accent-text, #79c0ff);
}
/* ── Filters ── */
.admin-filters {
display: flex;
gap: 10px;
margin-bottom: 14px;
flex-wrap: wrap;
}
.admin-filters input, .admin-filters select {
padding: 6px 12px;
background: var(--bg-primary, #0f1117);
color: var(--text-primary, #e6edf3);
border: 1px solid var(--admin-card-border);
border-radius: 6px;
font-size: 0.85rem;
}
.admin-filters input:focus, .admin-filters select:focus {
outline: none;
border-color: var(--accent, #58a6ff);
}
.admin-btn {
padding: 6px 14px;
background: var(--accent, #58a6ff);
color: #fff;
border: none;
border-radius: 6px;
font-size: 0.85rem;
cursor: pointer;
font-weight: 600;
transition: opacity 0.15s;
}
.admin-btn:hover { opacity: 0.85; }
.admin-btn-secondary {
background: var(--bg-hover, #1f2430);
color: var(--text-primary, #e6edf3);
border: 1px solid var(--admin-card-border);
}
/* ── Backups ── */
#admin-backups-summary {
display: flex;
gap: 20px;
margin-bottom: 14px;
flex-wrap: wrap;
font-size: 0.85rem;
color: var(--text-secondary, #8b949e);
}
#admin-backups-summary > div {
padding: 8px 14px;
background: var(--bg-primary, #0f1117);
border-radius: 6px;
border: 1px solid var(--admin-card-border);
}
.admin-backup-bar {
height: 8px;
background: var(--bg-primary, #0f1117);
border-radius: 4px;
overflow: hidden;
min-width: 120px;
}
.admin-backup-bar-fill {
height: 100%;
background: linear-gradient(90deg, var(--accent, #58a6ff), var(--accent-text, #79c0ff));
transition: width 0.4s ease;
}
/* ── Users management ── */
#section-users .admin-users-hint {
color: var(--text-secondary, #8b949e);
font-size: 0.85rem;
margin-bottom: 14px;
}
/* ── Footer ── */
.admin-footer {
max-width: 1400px;
margin: 0 auto;
padding: 16px 24px;
font-size: 0.75rem;
color: var(--text-muted, #484f58);
display: flex;
justify-content: space-between;
border-top: 1px solid var(--admin-card-border);
}
#admin-stats-timestamp { color: var(--text-secondary, #8b949e); }
/* ── Forbidden screen ── */
#admin-forbidden {
display: none;
max-width: 500px;
margin: 100px auto;
padding: 40px;
text-align: center;
background: var(--admin-card-bg);
border: 1px solid var(--admin-danger);
border-radius: 10px;
}
#admin-forbidden h2 { color: var(--admin-danger); margin-top: 0; }
/* ── Loading state ── */
.admin-loading {
padding: 40px;
text-align: center;
color: var(--text-secondary, #8b949e);
font-size: 0.9rem;
}
</style>
</head>
<body class="admin-page">
<header class="admin-header">
<div class="admin-header-left">
<h1>ObsiGate — Admin</h1>
<span class="admin-subtitle" data-i18n="admin.header_subtitle">Tableau de bord administrateur</span>
</div>
<div class="admin-header-right">
<span id="admin-role-badge">…</span>
<a href="/" class="admin-back-btn" data-i18n="admin.back_btn">← Retour</a>
</div>
</header>
<nav class="admin-subnav" id="admin-subnav" aria-label="Sections admin">
<a href="#section-stats" class="active" data-section="stats">📊 <span data-i18n="admin.stats_title">Statistiques</span></a>
<a href="#section-audit" data-section="audit">🕒 <span data-i18n="admin.audit_title">Logs d'audit</span></a>
<a href="#section-backups" data-section="backups">💾 <span data-i18n="admin.backups_title">Backups</span></a>
<a href="#section-users" data-section="users">👥 <span data-i18n="admin.users_title">Utilisateurs</span></a>
</nav>
<main id="admin-main" class="admin-main">
<!-- Loading state shown until init() resolves -->
<div id="admin-loading" class="admin-loading" data-i18n="common.loading">Chargement…</div>
<!-- Section 1 — Stats temps réel -->
<section class="admin-section" id="section-stats">
<h2 data-i18n="admin.stats_title">Statistiques temps réel</h2>
<div id="admin-stats-grid" class="admin-loading">…</div>
</section>
<!-- Section 2 — Logs d'audit -->
<section class="admin-section" id="section-audit">
<h2 data-i18n="admin.audit_title">Logs d'audit</h2>
<div class="admin-filters">
<input type="text" id="admin-audit-user" data-i18n-placeholder="admin.audit_filter_user" placeholder="Filtrer par utilisateur" />
<select id="admin-audit-action">
<option value="" data-i18n="admin.audit_all_actions">Toutes les actions</option>
</select>
<button id="admin-audit-refresh" class="admin-btn admin-btn-secondary" data-i18n="admin.audit_refresh">Rafraîchir</button>
</div>
<div id="admin-audit-empty" class="admin-loading" style="display:none;" data-i18n="admin.audit_empty">Aucun log disponible</div>
<table class="admin-table">
<thead>
<tr>
<th>Date</th>
<th>Action</th>
<th>User</th>
<th>Vault</th>
<th>IP</th>
</tr>
</thead>
<tbody id="admin-audit-tbody"></tbody>
</table>
</section>
<!-- Section 3 — Statistiques backups -->
<section class="admin-section" id="section-backups">
<h2 data-i18n="admin.backups_title">Statistiques backups</h2>
<div id="admin-backups-summary"></div>
<div id="admin-backups-empty" class="admin-loading" style="display:none;" data-i18n="admin.backups_vault_empty">Aucun backup</div>
<table class="admin-table">
<thead>
<tr>
<th data-i18n="admin.backups_per_vault">Par vault</th>
<th>Count</th>
<th>Size</th>
<th>Distribution</th>
</tr>
</thead>
<tbody id="admin-backups-tbody"></tbody>
</table>
</section>
<!-- Section 4 — Gestion utilisateurs -->
<section class="admin-section" id="section-users">
<h2 data-i18n="admin.users_title">Gestion utilisateurs</h2>
<p class="admin-users-hint" data-i18n="admin.users_manage_hint">Ouvrir la modale de gestion des utilisateurs (CRUD complet)</p>
<button id="admin-users-manage-btn" class="admin-btn" data-i18n="admin.users_manage_btn">Gérer les utilisateurs</button>
</section>
</main>
<div id="admin-forbidden">
<h2 data-i18n="admin.forbidden_title">Accès refusé</h2>
<p data-i18n="admin.forbidden_msg">Vous devez être administrateur pour accéder à cette page.</p>
<a href="/" class="admin-back-btn" data-i18n="admin.back_btn">← Retour</a>
</div>
<footer class="admin-footer">
<span>ObsiGate Admin — ROADMAP #71</span>
<span id="admin-stats-timestamp">—</span>
</footer>
<script type="module">
// Theme: applique le thème/mode sauvegardé dans l'app principale
// (même origine => localStorage partagé). Fait AVANT le rendu pour
// éviter que la page admin n'utilise les vars CSS par défaut.
import { initThemes } from "/static/js/themes.js";
// We import admin.js which provides init() — but the i18n module
// is global (window.t), so we can use t() right away to translate
// static DOM. admin.js will then call init() after DOMContentLoaded.
import { initI18n } from "/static/js/i18n.js";
import * as Admin from "/static/js/admin.js";
initThemes();
await initI18n();
// Re-apply DOM translations now that locale strings are loaded
document.querySelectorAll("[data-i18n]").forEach((el) => {
el.textContent = window.t(el.getAttribute("data-i18n"));
});
document.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
el.setAttribute("placeholder", window.t(el.getAttribute("data-i18n-placeholder")));
});
// Remove loading hint now that i18n is ready
const loading = document.getElementById("admin-loading");
if (loading) loading.style.display = "none";
if (typeof Admin.init === "function") {
Admin.init();
} else {
console.error("admin.js did not export init()");
}
</script>
</body>
</html>
+107 -2
View File
@@ -1448,6 +1448,7 @@
<li><a href="#cfg-ai" class="help-nav-link" data-i18n="settings.ai"></a></li>
<li><a href="#cfg-themes" class="help-nav-link" data-i18n="settings.themes"></a></li>
<li><a href="#cfg-profile" class="help-nav-link" data-i18n="settings.profile"></a></li>
<li><a href="#cfg-security" class="help-nav-link" data-i18n="settings.security"></a></li>
<li><a href="#cfg-about" class="help-nav-link" data-i18n="settings.about"></a></li>
<li><a href="#cfg-webhooks" class="help-nav-link" data-i18n="config.section_webhooks"></a></li>
<li><a href="#cfg-partages-publics" class="help-nav-link" data-i18n="config.section_shares"></a></li>
@@ -2011,6 +2012,90 @@
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-nvidia-key"
>NVIDIA API Key</label
>
<input
type="password"
id="cfg-nvidia-key"
class="config-input"
placeholder="nvapi-..."
autocomplete="off"
/>
<select
id="cfg-nvidia-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-qwencloud-key"
>QwenCloud API Key</label
>
<input
type="password"
id="cfg-qwencloud-key"
class="config-input"
placeholder="sk-..."
autocomplete="off"
/>
<select
id="cfg-qwencloud-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-xiaomi-key"
>Xiaomi API Key</label
>
<input
type="password"
id="cfg-xiaomi-key"
class="config-input"
placeholder="xm-..."
autocomplete="off"
/>
<select
id="cfg-xiaomi-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-mistral-key"
>Mistral API Key</label
>
<input
type="password"
id="cfg-mistral-key"
class="config-input"
placeholder="sk-..."
autocomplete="off"
/>
<select
id="cfg-mistral-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div
class="config-actions-row"
style="margin-top: 16px"
@@ -2042,7 +2127,7 @@
<h2 data-i18n="auto.c14b5603">🎨 Thèmes</h2>
<p class="config-description" data-i18n="auto.caac40b9">
Choisissez un thème visuel. Chaque thème
offre un mode sombre et clair.
offre un mode sombre, clair, contraste élevé et sépia.
</p>
<div class="theme-grid" id="theme-grid">
<div class="config-diag-loading" data-i18n="common.loading">Chargement...</div>
@@ -2080,6 +2165,26 @@
</div>
</section>
<!-- Sécurité du compte (MFA) -->
<section
class="config-section help-section"
id="cfg-security"
>
<h2 data-i18n="settings.security">🔒 Sécurité du compte</h2>
<p class="config-description" data-i18n="settings.security_desc">
Activez l'authentification à deux facteurs (2FA) pour renforcer la sécurité de votre compte.
</p>
<div id="mfa-settings">
<div id="mfa-status" class="mfa-status-section">
<div class="mfa-status-row">
<span class="mfa-status-label" data-i18n="mfa.status_label">Authentification 2FA</span>
<span id="mfa-status-badge" class="mfa-badge mfa-badge-off" data-i18n="mfa.disabled">Désactivée</span>
</div>
<div id="mfa-setup-area"></div>
</div>
</div>
</section>
<!-- À propos -->
<section
class="config-section help-section"
@@ -4845,7 +4950,7 @@ curl -X POST https://votre-serveur.com/webhook \
</div>
<h1 class="about-title" data-i18n="header.logo">ObsiGate</h1>
<p class="about-tagline">Vos notes Obsidian,<br>simplement accessibles.</p>
<span class="about-version">v2.0.0-dev</span>
<span class="about-version">—</span>
</div>
<div class="about-body">
<div class="about-stats">
+544
View File
@@ -0,0 +1,544 @@
// frontend/js/admin.js — Admin Dashboard frontend module (ROADMAP #71)
//
// Standalone ES module loaded by frontend/admin.html.
// Public API:
// init() — DOMContentLoaded entry point. Verifies auth, fires initial loads.
// connectSSE() — Opens EventSource on /api/admin/stream; updates widgets on every "stats" event.
// loadStatsOnce() — Initial GET /api/admin/stats (snapshot before SSE delivers first frame).
// loadAuditLogs(filters) — GET /api/admin/audit with optional {user, action}.
// loadBackupStats() — GET /api/admin/backup-stats.
// renderStatsWidget(stats) — Paint CPU/RAM/Disk/Uptime/Sessions cards.
// renderAuditTable(entries) — Paint audit log table.
// renderBackups(byVault) — Paint per-vault backup bars.
// getAuthHeaders() — Read Bearer token from sessionStorage (same source as auth.js).
// formatBytes(mb) — Human-readable size formatter.
// formatUptime(seconds) — "Xd Yh Zm" formatter.
// severityColor(pct) — "success" | "warning" | "danger" based on thresholds.
import { api, AdminPanel } from "./auth.js";
import { state } from "./state.js";
import { escapeHtml, safeCreateIcons } from "./utils.js";
import { t, getLocale } from "./i18n.js";
// ── Module state ─────────────────────────────────────────────────────────
let _eventSource = null;
let _pollTimer = null;
let _auditFilters = { user: "", action: "" };
// ── Helpers ──────────────────────────────────────────────────────────────
/**
* Read the current Bearer token from sessionStorage (same key auth.js uses).
* Returns an `{Authorization: "Bearer ..."}` object or null.
*/
export function getAuthHeaders() {
try {
const token = sessionStorage.getItem("obsigate_access_token");
if (!token) return null;
return { Authorization: "Bearer " + token };
} catch {
return null;
}
}
/** Format a size in MB as a human-readable string. */
export function formatBytes(mb) {
if (mb == null || isNaN(mb)) return "—";
if (mb < 1) return `${Math.round(mb * 1024)} KB`;
if (mb < 1024) return `${mb.toFixed(1)} MB`;
return `${(mb / 1024).toFixed(2)} GB`;
}
/** Format an uptime in seconds as "Xd Yh Zm" (or "Xh Ym" / "Xm"). */
export function formatUptime(seconds) {
if (seconds == null || isNaN(seconds) || seconds < 0) return "—";
const s = Math.floor(seconds);
const d = Math.floor(s / 86400);
const h = Math.floor((s % 86400) / 3600);
const m = Math.floor((s % 3600) / 60);
if (d > 0) return `${d}d ${h}h ${m}m`;
if (h > 0) return `${h}h ${m}m`;
return `${m}m`;
}
/**
* Map a percentage to a CSS severity token.
* <70 → success (green)
* <90 → warning (orange)
* ≥90 → danger (red)
*/
export function severityColor(pct) {
if (pct == null || isNaN(pct)) return "success";
if (pct >= 90) return "danger";
if (pct >= 70) return "warning";
return "success";
}
/** Format an ISO timestamp with the user's locale. */
function formatDate(iso) {
if (!iso) return "—";
try {
return new Date(iso).toLocaleString(
getLocale() === "fr" ? "fr-FR" : "en-US"
);
} catch {
return iso;
}
}
/** Discreet error helper — never crashes the page. */
function _showInlineError(containerId, msg) {
const el = document.getElementById(containerId);
if (!el) return;
el.innerHTML = `<div class="admin-inline-error" style="color:var(--danger);padding:8px 12px;font-size:0.85rem;">${escapeHtml(msg)}</div>`;
}
// ── Stats widget ─────────────────────────────────────────────────────────
/**
* Paint the 5 stats cards.
* @param {object} stats {cpu_pct, mem_used_mb, mem_total_mb, disk_used_gb, disk_total_gb, uptime_seconds, active_sessions}
*/
export function renderStatsWidget(stats) {
if (!stats) return;
const grid = document.getElementById("admin-stats-grid");
if (!grid) return;
const cpuPct = stats.cpu_pct ?? 0;
const memPct = stats.mem_total_mb > 0 ? (stats.mem_used_mb / stats.mem_total_mb) * 100 : 0;
const diskPct = stats.disk_total_gb > 0 ? (stats.disk_used_gb / stats.disk_total_gb) * 100 : 0;
const cpuSev = severityColor(cpuPct);
const memSev = severityColor(memPct);
const diskSev = severityColor(diskPct);
const memTotal = stats.mem_total_mb ?? 0;
const diskTotal = stats.disk_total_gb ?? 0;
grid.innerHTML = `
<div class="admin-stat-card" data-sev="${cpuSev}">
<div class="admin-stat-label">${escapeHtml(t("admin.stats_cpu"))}</div>
<div class="admin-stat-value">${cpuPct.toFixed(1)}<span class="admin-stat-unit">%</span></div>
<div class="admin-stat-bar"><div class="admin-stat-bar-fill" style="width:${Math.min(cpuPct, 100).toFixed(1)}%;background:var(--${cpuSev});"></div></div>
</div>
<div class="admin-stat-card" data-sev="${memSev}">
<div class="admin-stat-label">${escapeHtml(t("admin.stats_memory"))}</div>
<div class="admin-stat-value">${stats.mem_used_mb?.toFixed(0) ?? "—"}<span class="admin-stat-unit"> / ${memTotal.toFixed(0)} MB</span></div>
<div class="admin-stat-bar"><div class="admin-stat-bar-fill" style="width:${Math.min(memPct, 100).toFixed(1)}%;background:var(--${memSev});"></div></div>
</div>
<div class="admin-stat-card" data-sev="${diskSev}">
<div class="admin-stat-label">${escapeHtml(t("admin.stats_disk"))}</div>
<div class="admin-stat-value">${stats.disk_used_gb?.toFixed(1) ?? "—"}<span class="admin-stat-unit"> / ${diskTotal.toFixed(1)} GB</span></div>
<div class="admin-stat-bar"><div class="admin-stat-bar-fill" style="width:${Math.min(diskPct, 100).toFixed(1)}%;background:var(--${diskSev});"></div></div>
</div>
<div class="admin-stat-card">
<div class="admin-stat-label">${escapeHtml(t("admin.stats_uptime"))}</div>
<div class="admin-stat-value" style="font-size:1.4rem;">${escapeHtml(formatUptime(stats.uptime_seconds))}</div>
</div>
<div class="admin-stat-card">
<div class="admin-stat-label">${escapeHtml(t("admin.stats_sessions"))}</div>
<div class="admin-stat-value">${stats.active_sessions ?? 0}</div>
</div>
`;
// Update footer timestamp
const ts = stats.timestamp ? new Date(stats.timestamp) : new Date();
const stamp = document.getElementById("admin-stats-timestamp");
if (stamp) {
stamp.textContent = t("admin.stats_refresh", { time: ts.toLocaleTimeString(getLocale() === "fr" ? "fr-FR" : "en-US") });
}
}
/** Fetch /api/admin/stats and paint. */
export async function loadStatsOnce() {
try {
const data = await api("/api/admin/stats");
renderStatsWidget(data);
} catch (err) {
_showInlineError("admin-stats-grid", err.message || "stats load failed");
}
}
/**
* Open a Server-Sent Events connection on /api/admin/stream.
* The endpoint emits `event: stats\ndata: {...}` every 5 seconds.
*
* The browser's EventSource doesn't support custom headers, so we rely on
* the httpOnly cookie (set by /api/auth/login with samesite=lax) to authenticate.
* `withCredentials: true` ensures the cookie is sent.
*
* If the connection fails to open (4xx/5xx or network), we fall back to
* periodic polling of /api/admin/stats every 5s so the UI keeps updating.
*/
export function connectSSE() {
if (_eventSource) {
try { _eventSource.close(); } catch { /* */ }
_eventSource = null;
}
if (_pollTimer) {
clearInterval(_pollTimer);
_pollTimer = null;
}
let sseReady = false;
try {
_eventSource = new EventSource("/api/admin/stream", { withCredentials: true });
_eventSource.addEventListener("stats", (ev) => {
sseReady = true;
try {
const data = JSON.parse(ev.data);
renderStatsWidget(data);
} catch (err) {
console.warn("admin SSE parse error", err);
}
});
_eventSource.onopen = () => {
sseReady = true;
// Stop the polling fallback once SSE works.
if (_pollTimer) { clearInterval(_pollTimer); _pollTimer = null; }
};
_eventSource.onerror = () => {
// EventSource auto-reconnects. Only start polling fallback if we
// never received the first event yet (e.g. 401/403/network blocked).
if (!sseReady) {
_startPollingFallback();
}
console.warn("admin SSE error (will retry)");
};
} catch (err) {
console.warn("admin SSE init failed", err);
_startPollingFallback();
}
// Kick off a single initial fetch right away so the UI doesn't show
// zeros for 5 seconds waiting for the first SSE event.
loadStatsOnce();
}
function _startPollingFallback() {
if (_pollTimer) return;
console.warn("admin: falling back to polling /api/admin/stats every 5s");
_pollTimer = setInterval(() => {
loadStatsOnce().catch(() => { /* ignore — error already shown */ });
}, 5000);
}
/** Close the SSE connection if any (useful before navigation). */
export function disconnectSSE() {
if (_eventSource) {
try { _eventSource.close(); } catch { /* */ }
_eventSource = null;
}
if (_pollTimer) {
clearInterval(_pollTimer);
_pollTimer = null;
}
}
// ── Audit log ────────────────────────────────────────────────────────────
/**
* Render the audit log table.
* @param {Array<object>} entries Array of audit entries (timestamp, action, username, vault, ip, ...).
*/
export function renderAuditTable(entries) {
const tbody = document.getElementById("admin-audit-tbody");
const empty = document.getElementById("admin-audit-empty");
if (!tbody) return;
if (!entries || !entries.length) {
tbody.innerHTML = "";
if (empty) empty.style.display = "";
return;
}
if (empty) empty.style.display = "none";
tbody.innerHTML = entries.map((e) => {
const ts = formatDate(e.timestamp);
const action = escapeHtml(e.action || "—");
const user = escapeHtml(e.username || e.user || "—");
const vault = escapeHtml(e.vault || "—");
const ip = escapeHtml(e.ip || "—");
return `<tr>
<td>${escapeHtml(ts)}</td>
<td><code>${action}</code></td>
<td>${user}</td>
<td>${vault}</td>
<td>${ip}</td>
</tr>`;
}).join("");
}
/**
* Fetch /api/admin/audit with optional filters.
* @param {{user?: string, action?: string}} filters
*/
export async function loadAuditLogs(filters = {}) {
if (filters.user !== undefined) _auditFilters.user = filters.user;
if (filters.action !== undefined) _auditFilters.action = filters.action;
const params = new URLSearchParams();
if (_auditFilters.user) params.set("user", _auditFilters.user);
if (_auditFilters.action) params.set("action", _auditFilters.action);
params.set("limit", "200");
const qs = params.toString();
try {
const data = await api(`/api/admin/audit?${qs}`);
renderAuditTable(data.entries || []);
} catch (err) {
_showInlineError("admin-audit-tbody", err.message || "audit load failed");
}
}
/** Populate the action <select> with the values we know about.
* The endpoint doesn't list all possible actions, so we hardcode the
* common ones and let the user pick "All". */
function _populateAuditActions() {
const select = document.getElementById("admin-audit-action");
if (!select) return;
const ACTIONS = [
"file_save", "file_delete", "file_view", "file_rename",
"share_create", "share_revoke", "auth_login", "auth_logout",
"auth_failed", "user_create", "user_update", "user_delete",
"backup_create", "config_update",
];
select.innerHTML =
`<option value="">${escapeHtml(t("admin.audit_all_actions"))}</option>` +
ACTIONS.map((a) => `<option value="${a}">${escapeHtml(a)}</option>`).join("");
}
// ── Backups ─────────────────────────────────────────────────────────────
/**
* Render per-vault backup bars.
* @param {object} byVault { vault: {count, size_mb} }
*/
export function renderBackups(byVault) {
const tbody = document.getElementById("admin-backups-tbody");
const empty = document.getElementById("admin-backups-empty");
if (!tbody) return;
const entries = byVault ? Object.entries(byVault) : [];
if (!entries.length) {
tbody.innerHTML = "";
if (empty) empty.style.display = "";
return;
}
if (empty) empty.style.display = "none";
// Largest vault for proportional bars
const maxSize = Math.max(...entries.map(([, v]) => v.size_mb || 0), 1);
tbody.innerHTML = entries
.sort((a, b) => (b[1].size_mb || 0) - (a[1].size_mb || 0))
.map(([vault, data]) => {
const count = data.count || 0;
const size = data.size_mb || 0;
const widthPct = Math.min((size / maxSize) * 100, 100).toFixed(1);
return `<tr>
<td>${escapeHtml(vault)}</td>
<td>${count}</td>
<td>${escapeHtml(formatBytes(size))}</td>
<td>
<div class="admin-backup-bar"><div class="admin-backup-bar-fill" style="width:${widthPct}%;"></div></div>
</td>
</tr>`;
})
.join("");
}
/** Fetch /api/admin/backup-stats and paint. */
export async function loadBackupStats() {
try {
const data = await api("/api/admin/backup-stats");
const summary = document.getElementById("admin-backups-summary");
if (summary) {
summary.innerHTML = `
<div>${escapeHtml(t("admin.backups_total", { count: data.total_backups ?? 0, size: formatBytes(data.total_size_mb) }))}</div>
<div>${escapeHtml(t("admin.backups_oldest", { days: (data.oldest_age_days ?? 0).toFixed(2) }))}</div>
<div>${escapeHtml(t("admin.backups_newest", { days: (data.newest_age_days ?? 0).toFixed(2) }))}</div>
`;
}
renderBackups(data.by_vault || {});
} catch (err) {
_showInlineError("admin-backups-tbody", err.message || "backups load failed");
}
}
// ── User management integration ─────────────────────────────────────────
/** Wire the "Manage users" button to open the existing AdminPanel modal. */
function _wireUserMgmt() {
const btn = document.getElementById("admin-users-manage-btn");
if (!btn) return;
btn.addEventListener("click", () => {
try {
AdminPanel.show();
} catch (err) {
console.error("AdminPanel.show failed", err);
}
});
}
// ── Filters wiring ──────────────────────────────────────────────────────
function _wireAuditFilters() {
const userInput = document.getElementById("admin-audit-user");
const actionSelect = document.getElementById("admin-audit-action");
const refreshBtn = document.getElementById("admin-audit-refresh");
if (refreshBtn) {
refreshBtn.addEventListener("click", () => loadAuditLogs());
}
if (userInput) {
userInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") loadAuditLogs();
});
}
if (actionSelect) {
actionSelect.addEventListener("change", () => loadAuditLogs());
}
}
// ── Section nav (scrollspy) ───────────────────────────────────────────
/**
* Wire the sticky section nav: smooth-scroll on click + highlight the section
* currently in view (IntersectionObserver). Falls back to default anchor jump
* if the observer is unavailable.
*/
function _wireSectionNav() {
const links = Array.from(document.querySelectorAll("#admin-subnav a"));
if (!links.length) return;
const targets = links
.map((a) => document.getElementById((a.getAttribute("href") || "#").slice(1)))
.filter(Boolean);
// Smooth scroll on click
links.forEach((a) => {
a.addEventListener("click", (e) => {
const href = a.getAttribute("href");
if (!href || !href.startsWith("#")) return;
const t = document.getElementById(href.slice(1));
if (!t) return;
e.preventDefault();
t.scrollIntoView({ behavior: "smooth", block: "start" });
});
});
// Scrollspy: mark the section currently at the top of the viewport
let active = null;
const setActive = (id) => {
if (active === id) return;
active = id;
links.forEach((l) => l.classList.toggle("active", l.getAttribute("href") === "#" + id));
};
if ("IntersectionObserver" in window) {
const io = new IntersectionObserver(
(entries) => {
entries.forEach((en) => {
if (en.isIntersecting) setActive(en.target.id);
});
},
{ rootMargin: "-64px 0px -70% 0px", threshold: 0 }
);
targets.forEach((t) => io.observe(t));
} else {
// Fallback: highlight the first section only (no scroll observation)
links[0] && links[0].classList.add("active");
}
}
// ── Auth gate ────────────────────────────────────────────────────────────
/**
* Verify the current session and admin role.
* Uses /api/auth/me (which returns the current user) and falls back to
* the cached user in sessionStorage if the request fails.
* Redirects to / if not authenticated or not admin.
* Returns the user object on success, null otherwise.
*/
async function _gateAdmin() {
const container = document.getElementById("admin-main");
const forbidden = document.getElementById("admin-forbidden");
// First check whether auth is even enabled (public endpoint).
let authEnabled = false;
try {
const statusRes = await fetch("/api/auth/status", { credentials: "include" });
if (statusRes.ok) {
const status = await statusRes.json();
authEnabled = !!status.auth_enabled;
}
} catch { /* network error — fall through */ }
if (!authEnabled) {
// Server is wide open, treat current visitor as allowed.
return { username: "anonymous", role: "admin" };
}
// Auth is enabled — try to load the current user.
try {
const meRes = await fetch("/api/auth/me", {
credentials: "include",
headers: getAuthHeaders(),
});
if (meRes.status === 401 || meRes.status === 403) {
window.location.href = "/";
return null;
}
if (!meRes.ok) throw new Error("HTTP " + meRes.status);
const user = await meRes.json();
// Cache for later fallback
try {
sessionStorage.setItem("obsigate_user", JSON.stringify(user));
} catch { /* */ }
if (user.role !== "admin") {
if (container) container.style.display = "none";
if (forbidden) forbidden.style.display = "";
return null;
}
return user;
} catch (err) {
// Network error — try to use cached sessionStorage user as fallback
try {
const cached = sessionStorage.getItem("obsigate_user");
if (cached) {
const u = JSON.parse(cached);
if (u.role === "admin") return u;
}
} catch { /* */ }
window.location.href = "/";
return null;
}
}
// ── Init ─────────────────────────────────────────────────────────────────
/**
* Page entry point. Called on DOMContentLoaded by admin.html.
* Verifies auth, populates the action select, wires events, kicks off loads.
*/
export async function init() {
const user = await _gateAdmin();
if (!user) return;
// Show role badge
const badge = document.getElementById("admin-role-badge");
if (badge) {
badge.textContent = user.role || "user";
badge.dataset.role = user.role || "user";
}
_populateAuditActions();
_wireAuditFilters();
_wireUserMgmt();
_wireSectionNav();
// Initial loads (in parallel — none depends on another)
loadStatsOnce();
loadAuditLogs();
loadBackupStats();
// Then start the live SSE stream for stats
connectSSE();
}
+79
View File
@@ -0,0 +1,79 @@
// ObsiGate — Floating Action Button (FAB) to open/close the BooksLM AI sidebar.
// Always visible in the bottom-right corner; hides while BooksLM is open.
import booksLM from './bookslm.js';
import { state } from './state.js';
import { showToast, TabManager } from './ui.js';
import { t } from './i18n.js';
import { safeCreateIcons } from './utils.js';
let _fab = null;
// Mirror palette.js getCurrentFile(): prefer the active tab, then fall back to state.
function getCurrentFile() {
const id = TabManager._activeTabId;
if (id) {
const tab = TabManager._tabs.find((x) => x.id === id);
if (tab) return { vault: tab.vault, path: tab.path };
}
if (state.currentVault && state.currentPath) return { vault: state.currentVault, path: state.currentPath };
return null;
}
// The BooksLM panel is considered visible when it has `.open` without `.hidden`
// (the header toggle collapses it off-screen via `.hidden`).
function isBooksLmVisible() {
const panel = document.querySelector('.bookslm-panel');
return !!(panel && panel.classList.contains('open') && !panel.classList.contains('hidden'));
}
function syncVisibility() {
if (!_fab) return;
const visible = isBooksLmVisible();
_fab.hidden = visible;
const label = visible ? t('fab.close') : t('fab.open');
_fab.title = label;
_fab.setAttribute('aria-label', label);
}
async function onClick() {
const f = getCurrentFile();
if (!f) {
showToast(t('toast.no_open_file'), 'error');
return;
}
const sameDir = booksLM._isOpen && booksLM._vault === f.vault && booksLM._directory === f.path;
if (sameDir) {
// Already open for this directory: re-show a collapsed panel, or close it.
const panel = document.querySelector('.bookslm-panel');
if (panel && panel.classList.contains('hidden')) {
booksLM._toggleSidebar();
} else {
booksLM.close();
}
return;
}
await booksLM.open(f.vault, f.path);
}
export function initAIFab() {
if (_fab) return;
const btn = document.createElement('button');
btn.type = 'button';
btn.id = 'ai-fab';
btn.className = 'ai-fab';
btn.innerHTML = '<i data-lucide="bot" style="width:24px;height:24px"></i>';
document.body.appendChild(btn);
_fab = btn;
btn.addEventListener('click', onClick);
document.addEventListener('bookslm:opened', syncVisibility);
document.addEventListener('bookslm:closed', syncVisibility);
if (typeof safeCreateIcons === 'function') safeCreateIcons();
syncVisibility();
}
export default initAIFab;
+199 -16
View File
@@ -13,7 +13,14 @@ import { t } from './i18n.js';
// ── API call helper ──
async function aiAction(endpoint, text, extra = {}) {
const body = { text, ...extra };
// Inject current provider + model from the per-section picker.
const pickerState = _readPicker();
const body = {
text,
...extra,
...(pickerState.provider ? { provider: pickerState.provider } : {}),
...(pickerState.model ? { model: pickerState.model } : {}),
};
const data = await api(`/api/ai/${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -22,6 +29,165 @@ async function aiAction(endpoint, text, extra = {}) {
return data.result;
}
// ── Per-section provider/model picker ───────────────────────────────────────
// State is stored in localStorage so the user choice persists across sections.
const PICKER_STORAGE_KEY = 'obsigate_ai_picker';
function _readPicker() {
try {
return JSON.parse(localStorage.getItem(PICKER_STORAGE_KEY) || '{}');
} catch { return {}; }
}
function _writePicker(state) {
try {
localStorage.setItem(PICKER_STORAGE_KEY, JSON.stringify(state));
} catch { /* */ }
}
/**
* Build a provider+model picker that appears in every section's AI toolbar
* (Forge editor, BooksLM, etc.). The picker reads /api/ai/status to discover
* available providers, then /api/config/ai-models?provider=X to list models.
*/
async function _buildPickerUI() {
const pickerState = _readPicker();
// Fetch configured providers
let availableProviders = {};
try {
const status = await api('/api/ai/status');
availableProviders = status.providers || {};
} catch { /* */ }
const providerNames = Object.keys(availableProviders).filter(
(p) => availableProviders[p]?.available
);
if (!providerNames.length) return null;
const wrap = document.createElement('div');
wrap.className = 'ai-picker';
Object.assign(wrap.style, {
display: 'inline-flex',
alignItems: 'center',
gap: '4px',
marginLeft: '8px',
paddingLeft: '8px',
borderLeft: '1px solid var(--border)',
fontSize: '0.7rem',
color: 'var(--text-muted)',
flexShrink: '0',
zIndex: '1',
});
// Provider select
const providerLabel = document.createElement('span');
providerLabel.textContent = t('ai.provider') + ':';
wrap.appendChild(providerLabel);
const providerSelect = document.createElement('select');
providerSelect.className = 'ai-picker-select';
Object.assign(providerSelect.style, {
fontSize: '0.7rem',
background: 'var(--surface)',
color: 'var(--text-primary)',
border: '1px solid var(--border)',
borderRadius: '4px',
padding: '2px 4px',
cursor: 'pointer',
});
const defaultOpt = document.createElement('option');
defaultOpt.value = '';
defaultOpt.textContent = t('ai.provider_default');
providerSelect.appendChild(defaultOpt);
providerNames.forEach((p) => {
const opt = document.createElement('option');
opt.value = p;
opt.textContent = p;
if (p === pickerState.provider) opt.selected = true;
providerSelect.appendChild(opt);
});
// Model select (sibling of provider)
const modelSelect = document.createElement('select');
modelSelect.className = 'ai-picker-model';
Object.assign(modelSelect.style, {
fontSize: '0.7rem',
background: 'var(--surface)',
color: 'var(--text-primary)',
border: '1px solid var(--border)',
borderRadius: '4px',
padding: '2px 4px',
cursor: 'pointer',
minWidth: '120px',
maxWidth: '220px',
});
const placeholderOpt = document.createElement('option');
placeholderOpt.value = '';
placeholderOpt.textContent = t('ai.model_default');
modelSelect.appendChild(placeholderOpt);
async function _loadModels(provider) {
modelSelect.innerHTML = '';
const ph = document.createElement('option');
ph.value = '';
ph.textContent = t('ai.model_loading');
modelSelect.appendChild(ph);
try {
const data = await api(`/api/config/ai-models?provider=${encodeURIComponent(provider)}`);
modelSelect.innerHTML = '';
const def = document.createElement('option');
def.value = '';
def.textContent = t('ai.model_default') + (data.source === 'fallback' ? ` (${t('ai.model_offline')})` : '');
modelSelect.appendChild(def);
(data.models || []).forEach((m) => {
const opt = document.createElement('option');
opt.value = m;
opt.textContent = m;
if (m === pickerState.model && provider === pickerState.provider) opt.selected = true;
modelSelect.appendChild(opt);
});
} catch (err) {
modelSelect.innerHTML = '';
const opt = document.createElement('option');
opt.value = '';
opt.textContent = t('ai.model_load_error');
modelSelect.appendChild(opt);
}
}
providerSelect.addEventListener('change', () => {
pickerState.provider = providerSelect.value || null;
// Reset model when provider changes
pickerState.model = null;
_writePicker(pickerState);
if (pickerState.provider) {
_loadModels(pickerState.provider);
} else {
modelSelect.innerHTML = '';
const ph = document.createElement('option');
ph.value = '';
ph.textContent = t('ai.model_default');
modelSelect.appendChild(ph);
}
});
modelSelect.addEventListener('change', () => {
pickerState.model = modelSelect.value || null;
_writePicker(pickerState);
});
// Load models for the initial provider selection
if (pickerState.provider && providerNames.includes(pickerState.provider)) {
_loadModels(pickerState.provider);
}
wrap.appendChild(providerSelect);
wrap.appendChild(modelSelect);
return wrap;
}
// ── Get selected text from CodeMirror ──
function getSelection(editorView) {
if (!editorView) return '';
@@ -80,12 +246,12 @@ function createMenu(items, parentEl) {
const menuLeft = rect.left;
Object.assign(menu.style, {
position: 'fixed',
top: menuTop + 'px',
left: menuLeft + 'px',
background: 'var(--bg-primary)',
border: '1px solid var(--border-color)',
borderRadius: '6px',
position: 'fixed',
top: menuTop + 'px',
left: menuLeft + 'px',
background: 'var(--bg-primary)',
border: '1px solid var(--border)',
borderRadius: '6px',
padding: '4px 0',
minWidth: '200px',
maxHeight: '60vh',
@@ -172,12 +338,12 @@ function createSubMenu(items, parentEl) {
const menu = document.createElement('div');
menu.className = 'ai-submenu';
Object.assign(menu.style, {
position: 'absolute',
left: '100%',
top: '0',
background: 'var(--bg-primary)',
border: '1px solid var(--border-color)',
borderRadius: '6px',
position: 'absolute',
left: '100%',
top: '0',
background: 'var(--bg-primary)',
border: '1px solid var(--border)',
borderRadius: '6px',
padding: '4px 0',
minWidth: '180px',
zIndex: '101',
@@ -220,7 +386,7 @@ export async function createAIToolbar(container, getEditorView) {
if (!aiConfigured) {
const hint = document.createElement('div');
hint.style.cssText = 'padding:6px 12px;font-size:0.7rem;color:var(--text-muted);border-bottom:1px solid var(--border-color)';
hint.style.cssText = 'padding:6px 12px;font-size:0.7rem;color:var(--text-muted);border-bottom:1px solid var(--border)';
hint.textContent = t('ai.not_configured');
container.appendChild(hint);
return;
@@ -233,7 +399,7 @@ export async function createAIToolbar(container, getEditorView) {
alignItems: 'center',
gap: '2px',
padding: '4px 8px',
borderBottom: '1px solid var(--border-color)',
borderBottom: '1px solid var(--border)',
background: 'var(--bg-secondary)',
flexWrap: 'wrap',
position: 'sticky',
@@ -357,6 +523,13 @@ export async function createAIToolbar(container, getEditorView) {
toolbar.appendChild(rewriteBtn);
toolbar.appendChild(toolboxBtn);
// Append the per-section provider/model picker on the right.
const picker = await _buildPickerUI();
if (picker) {
toolbar.appendChild(createSeparator());
toolbar.appendChild(picker);
}
container.insertBefore(toolbar, container.firstChild);
// ── Action helper ──
@@ -452,6 +625,16 @@ function createDropdownBtn(text, items, tooltip = '') {
function createSeparator() {
const sep = document.createElement('span');
sep.style.cssText = 'width:1px;height:16px;background:var(--border-color);margin:0 2px';
sep.style.cssText = 'width:1px;height:16px;background:var(--border);margin:0 2px';
return sep;
}
// ── Public exports ────────────────────────────────────────────────────────
// Other modules (e.g. BooksLM) can import the picker helpers to render the
// same per-section provider/model picker in their own toolbar.
export {
_readPicker,
_writePicker,
PICKER_STORAGE_KEY,
_buildPickerUI as buildAIPickerUI,
};
+8 -5
View File
@@ -5,6 +5,7 @@
import * as UI from './ui.js';
import * as Utils from './utils.js';
import { initI18n, t } from './i18n.js';
import { initAIFab } from './ai-fab.js';
// Wire up AI toolbar toast (avoids circular import in utils.js)
window._obsigateShowToast = UI.showToast;
@@ -99,6 +100,7 @@ async function init() {
initMermaid();
setupFocusMode();
Utils.safeCreateIcons();
initAIFab();
}
document.addEventListener("DOMContentLoaded", () => {
@@ -111,15 +113,16 @@ document.addEventListener("DOMContentLoaded", () => {
window.__OBSIGATE_BOOTED = true;
if (typeof window.__obsigateBootReady === "function") window.__obsigateBootReady();
}
// Show version in header
// Show version in header — always visible, fallback before the async fetch
const versionBadge = document.getElementById('version-badge');
if (versionBadge) {
versionBadge.textContent = window.__OBSIGATE_VERSION || '…';
}
fetch('/api/health')
.then(r => r.json())
.then(d => {
const badge = document.getElementById('version-badge');
if (badge && d.version) {
badge.textContent = d.version;
badge.style.display = 'inline-block';
}
if (badge && d.version) badge.textContent = d.version;
})
.catch(() => {});
});
+748 -31
View File
@@ -139,10 +139,122 @@ const AuthManager = {
throw new Error(err.detail || "Erreur de connexion");
}
const data = await response.json();
// If MFA is required, return the MFA challenge instead of saving token
if (data.mfa_required) {
return data;
}
this.saveToken(data);
return data.user;
},
async verifyMfa(username, code, rememberMe) {
const response = await fetch("/api/auth/mfa/totp/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username, code, remember_me: rememberMe || false }),
});
if (!response.ok) {
const err = await response.json();
throw new Error(err.detail || "Code invalide");
}
const data = await response.json();
this.saveToken(data);
return data.user;
},
async verifyRecovery(username, recoveryCode) {
const response = await fetch("/api/auth/mfa/recovery", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username, recovery_code: recoveryCode }),
});
if (!response.ok) {
const err = await response.json();
throw new Error(err.detail || "Code invalide");
}
const data = await response.json();
this.saveToken(data);
return data.user;
},
// ── WebAuthn (ROADMAP #64) ─────────────────────────────────────────
async webauthnLoginOptions(username) {
const resp = await fetch("/api/auth/mfa/webauthn/options", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username }),
});
if (!resp.ok) throw new Error((await resp.json()).detail || "WebAuthn indisponible");
return await resp.json();
},
async verifyWebauthn(username, credential, rememberMe) {
const response = await fetch("/api/auth/mfa/webauthn/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username, credential, remember_me: rememberMe || false }),
});
if (!response.ok) {
const err = await response.json();
throw new Error(err.detail || "Vérification WebAuthn échouée");
}
const data = await response.json();
this.saveToken(data);
return data.user;
},
async webauthnRegisterOptions() {
return await api("/api/auth/mfa/webauthn/register/options", { method: "POST" });
},
async webauthnRegister(credential, label) {
return await api("/api/auth/mfa/webauthn/register", {
method: "POST",
body: JSON.stringify({ credential, label }),
});
},
async webauthnCredentials() {
return await api("/api/auth/mfa/webauthn/credentials");
},
async webauthnRemove(credentialId, password) {
return await api("/api/auth/mfa/webauthn/credentials/remove", {
method: "POST",
body: JSON.stringify({ credential_id: credentialId, password }),
});
},
// ── MFA Setup API calls ──────────────────────────────────────────
async getMfaStatus() {
const resp = await api("/api/auth/mfa/status");
return resp;
},
async mfaSetup() {
return await api("/api/auth/mfa/totp/setup", { method: "POST" });
},
async mfaEnable(code) {
return await api("/api/auth/mfa/totp/enable", {
method: "POST",
body: JSON.stringify({ code }),
});
},
async mfaDisable(password, code) {
return await api("/api/auth/mfa/totp/disable", {
method: "POST",
body: JSON.stringify({ password, code }),
});
},
async logout() {
try {
const token = this.getToken();
@@ -216,7 +328,7 @@ const AuthManager = {
// Important: use an inline function to ensure we don't bind multiple identical listeners on rerenders, or clean up before
adminRow.onclick = () => {
closeHeaderMenu();
AdminPanel.show();
window.location.href = "/admin.html";
};
} else {
adminRow.classList.add("hidden");
@@ -278,6 +390,343 @@ const AuthManager = {
};
// ---------------------------------------------------------------------------
// Post-login setup (shared between normal login and MFA login)
// ---------------------------------------------------------------------------
async function _onLoginSuccess() {
AuthManager.showApp();
// Re-sync language from server now that we're authenticated
try {
const resp = await fetch('/api/auth/me', { credentials: 'include' });
if (resp.ok) {
const user = await resp.json();
if (user.language && user.language !== getLocale()) {
await setLocale(user.language);
}
}
} catch (e) { /* non-bloquant */ }
// Load app data after successful login
try {
const { loadVaults, loadTags } = await import('./sidebar.js');
await Promise.all([loadVaults(), loadTags()]);
const { IndexUpdateManager } = await import('./sync.js');
IndexUpdateManager.connect();
const { syncFileIndexFromServer } = await import('./offline.js');
syncFileIndexFromServer();
showWelcome();
} catch (err) {
console.error("Failed to load data after login:", err);
}
}
// ---------------------------------------------------------------------------
// MFA Challenge UI (TOTP code input during login)
// ---------------------------------------------------------------------------
// base64url <-> ArrayBuffer helpers for WebAuthn (ROADMAP #64)
function _b64urlToBuf(s) {
const pad = "=".repeat((4 - (s.length % 4)) % 4);
const b = (s + pad).replace(/-/g, "+").replace(/_/g, "/");
const raw = atob(b);
return Uint8Array.from(raw, (c) => c.charCodeAt(0));
}
function _bufToB64url(buf) {
const bytes = new Uint8Array(buf);
let s = "";
for (const c of bytes) s += String.fromCharCode(c);
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function runWebauthnCeremony(optionsJson) {
const pkOptions = {
challenge: _b64urlToBuf(optionsJson.challenge),
timeout: optionsJson.timeout || 60000,
rpId: optionsJson.rpId,
userVerification: optionsJson.userVerification || "preferred",
allowCredentials: (optionsJson.allowCredentials || []).map((c) => ({
type: c.type || "public-key",
id: _b64urlToBuf(c.id),
transports: c.transports,
})),
};
const cred = await navigator.credentials.get({ publicKey: pkOptions });
if (!cred) throw new Error(t("mfa.webauthn_cancelled"));
return {
id: cred.id,
rawId: _bufToB64url(cred.rawId),
type: cred.type,
response: {
clientDataJSON: _bufToB64url(cred.response.clientDataJSON),
authenticatorData: _bufToB64url(cred.response.authenticatorData),
signature: _bufToB64url(cred.response.signature),
userHandle: cred.response.userHandle ? _bufToB64url(cred.response.userHandle) : "",
},
};
}
async function runWebauthnRegistration() {
const resp = await AuthManager.webauthnRegisterOptions();
const o = resp.options;
const pkOptions = {
rp: { id: o.rpId || o.rp.id, name: o.rp.name },
challenge: _b64urlToBuf(o.challenge),
user: {
id: _b64urlToBuf(o.user.id),
name: o.user.name,
displayName: o.user.displayName,
},
pubKeyCredParams: o.pubKeyCredParams,
timeout: o.timeout || 60000,
authenticatorSelection: o.authenticatorSelection || undefined,
attestation: "none",
};
const cred = await navigator.credentials.create({ publicKey: pkOptions });
if (!cred) throw new Error(t("mfa.webauthn_cancelled"));
const credential = {
id: cred.id,
rawId: _bufToB64url(cred.rawId),
type: cred.type,
response: {
clientDataJSON: _bufToB64url(cred.response.clientDataJSON),
attestationObject: _bufToB64url(cred.response.attestationObject),
},
};
if (cred.response.getTransports) {
credential.response.transports = Array.from(cred.response.getTransports());
}
return credential;
}
function _startWebauthnLogin(mfaSection, username, rememberMe) {
const btn = mfaSection.querySelector("#mfa-webauthn-btn");
const errorEl = mfaSection.querySelector("#mfa-error");
if (btn) btn.disabled = true;
if (errorEl) errorEl.classList.add("hidden");
(async () => {
try {
const resp = await AuthManager.webauthnLoginOptions(username);
if (resp.mfa_method !== "webauthn" || !resp.options) {
throw new Error(t("mfa.webauthn_no_key"));
}
const credential = await runWebauthnCeremony(resp.options);
await AuthManager.verifyWebauthn(username, credential, rememberMe);
mfaSection.classList.add("hidden");
const loginForm = document.getElementById("login-form");
if (loginForm) loginForm.classList.remove("hidden");
await _onLoginSuccess();
} catch (err) {
if (errorEl) {
errorEl.textContent = err.message || String(err);
errorEl.classList.remove("hidden");
}
} finally {
if (btn) btn.disabled = false;
}
})();
}
function showMfaChallenge(username, rememberMe, loginBtn, loginErrorEl, mfaMethod) {
const loginBox = document.querySelector(".login-box");
if (!loginBox) return;
// Hide the normal login form
const loginForm = document.getElementById("login-form");
if (loginForm) loginForm.classList.add("hidden");
// Create MFA challenge UI
let mfaSection = document.getElementById("mfa-challenge");
if (!mfaSection) {
mfaSection = document.createElement("div");
mfaSection.id = "mfa-challenge";
mfaSection.className = "mfa-challenge";
loginBox.appendChild(mfaSection);
}
// WebAuthn second factor: key prompt instead of TOTP code input
if (mfaMethod === "webauthn") {
mfaSection.innerHTML = `
<div class="mfa-icon">🔑</div>
<h3>${t('mfa.title')}</h3>
<p class="mfa-subtitle">${t('mfa.webauthn_prompt')}</p>
<p class="mfa-error hidden" id="mfa-error"></p>
<button type="button" class="btn-login" id="mfa-webauthn-btn">
<span class="btn-text">${t('mfa.webauthn_btn')}</span>
</button>
<div class="mfa-actions">
<button type="button" class="mfa-link-btn" id="mfa-use-recovery">${t('mfa.use_recovery')}</button>
<button type="button" class="mfa-link-btn" id="mfa-back-login">${t('mfa.back_to_login')}</button>
</div>
`;
mfaSection.classList.remove("hidden");
document.getElementById("mfa-webauthn-btn").addEventListener("click", () => {
_startWebauthnLogin(mfaSection, username, rememberMe);
});
document.getElementById("mfa-use-recovery").addEventListener("click", () => {
showRecoveryChallenge(username, rememberMe, loginForm, mfaSection);
});
document.getElementById("mfa-back-login").addEventListener("click", () => {
mfaSection.classList.add("hidden");
if (loginForm) loginForm.classList.remove("hidden");
});
// Auto-start the ceremony — the browser shows its own dialog
_startWebauthnLogin(mfaSection, username, rememberMe);
return;
}
mfaSection.innerHTML = `
<div class="mfa-icon">🔐</div>
<h3>${t('mfa.title')}</h3>
<p class="mfa-subtitle">${t('mfa.subtitle')}</p>
<form id="mfa-form">
<div class="mfa-code-input-group">
<input type="text" id="mfa-code" class="mfa-code-input" maxlength="6"
pattern="[0-9]{6}" inputmode="numeric" autocomplete="one-time-code"
placeholder="000000" autofocus required>
</div>
<p class="mfa-error hidden" id="mfa-error"></p>
<button type="submit" class="btn-login" id="mfa-verify-btn">
<span class="btn-text">${t('mfa.verify')}</span>
<span class="btn-spinner hidden">⏳</span>
</button>
</form>
<div class="mfa-actions">
<button type="button" class="mfa-link-btn" id="mfa-use-recovery">${t('mfa.use_recovery')}</button>
<button type="button" class="mfa-link-btn" id="mfa-back-login">${t('mfa.back_to_login')}</button>
</div>
`;
mfaSection.classList.remove("hidden");
const codeInput = document.getElementById("mfa-code");
codeInput.focus();
// Auto-submit when 6 digits entered
codeInput.addEventListener("input", () => {
codeInput.value = codeInput.value.replace(/[^0-9]/g, "");
if (codeInput.value.length === 6) {
document.getElementById("mfa-verify-btn").click();
}
});
// Handle MFA form submit
document.getElementById("mfa-form").addEventListener("submit", async (e) => {
e.preventDefault();
const code = codeInput.value.trim();
if (code.length !== 6) return;
const btn = document.getElementById("mfa-verify-btn");
const errorEl = document.getElementById("mfa-error");
btn.disabled = true;
btn.querySelector(".btn-spinner").classList.remove("hidden");
btn.querySelector(".btn-text").textContent = t('mfa.verifying');
errorEl.classList.add("hidden");
try {
await AuthManager.verifyMfa(username, code, rememberMe);
mfaSection.classList.add("hidden");
if (loginForm) loginForm.classList.remove("hidden");
await _onLoginSuccess();
} catch (err) {
errorEl.textContent = err.message;
errorEl.classList.remove("hidden");
codeInput.value = "";
codeInput.focus();
} finally {
btn.disabled = false;
btn.querySelector(".btn-spinner").classList.add("hidden");
btn.querySelector(".btn-text").textContent = t('mfa.verify');
}
});
// Switch to recovery code input
document.getElementById("mfa-use-recovery").addEventListener("click", () => {
showRecoveryChallenge(username, rememberMe, loginForm, mfaSection);
});
// Back to login
document.getElementById("mfa-back-login").addEventListener("click", () => {
mfaSection.classList.add("hidden");
if (loginForm) loginForm.classList.remove("hidden");
});
}
function showRecoveryChallenge(username, rememberMe, loginForm, mfaSection) {
mfaSection.innerHTML = `
<div class="mfa-icon">🔑</div>
<h3>${t('mfa.recovery_title')}</h3>
<p class="mfa-subtitle">${t('mfa.recovery_subtitle')}</p>
<form id="recovery-form">
<div class="mfa-code-input-group">
<input type="text" id="recovery-code" class="mfa-code-input recovery-input" maxlength="9"
autocomplete="off" placeholder="XXXX-XXXX" autofocus required>
</div>
<p class="mfa-error hidden" id="recovery-error"></p>
<button type="submit" class="btn-login" id="recovery-verify-btn">
<span class="btn-text">${t('mfa.verify')}</span>
<span class="btn-spinner hidden">⏳</span>
</button>
</form>
<div class="mfa-actions">
<button type="button" class="mfa-link-btn" id="recovery-use-totp">${t('mfa.use_totp')}</button>
<button type="button" class="mfa-link-btn" id="recovery-back-login">${t('mfa.back_to_login')}</button>
</div>
`;
const codeInput = document.getElementById("recovery-code");
codeInput.focus();
// Auto-format: insert dash after 4 chars
codeInput.addEventListener("input", () => {
let v = codeInput.value.replace(/[^a-zA-Z0-9]/g, "").toUpperCase();
if (v.length > 4) v = v.slice(0, 4) + "-" + v.slice(4, 8);
codeInput.value = v;
});
document.getElementById("recovery-form").addEventListener("submit", async (e) => {
e.preventDefault();
const code = codeInput.value.trim();
const btn = document.getElementById("recovery-verify-btn");
const errorEl = document.getElementById("recovery-error");
btn.disabled = true;
btn.querySelector(".btn-spinner").classList.remove("hidden");
btn.querySelector(".btn-text").textContent = t('mfa.verifying');
errorEl.classList.add("hidden");
try {
await AuthManager.verifyRecovery(username, code);
mfaSection.classList.add("hidden");
if (loginForm) loginForm.classList.remove("hidden");
await _onLoginSuccess();
} catch (err) {
errorEl.textContent = err.message;
errorEl.classList.remove("hidden");
codeInput.value = "";
codeInput.focus();
} finally {
btn.disabled = false;
btn.querySelector(".btn-spinner").classList.add("hidden");
btn.querySelector(".btn-text").textContent = t('mfa.verify');
}
});
document.getElementById("recovery-use-totp").addEventListener("click", () => {
showMfaChallenge(username, rememberMe, null, null);
});
document.getElementById("recovery-back-login").addEventListener("click", () => {
mfaSection.classList.add("hidden");
if (loginForm) loginForm.classList.remove("hidden");
});
}
// ---------------------------------------------------------------------------
// Login form handler
// ---------------------------------------------------------------------------
@@ -300,36 +749,14 @@ function initLoginForm() {
errorEl.classList.add("hidden");
try {
await AuthManager.login(username, password, rememberMe);
AuthManager.showApp();
// Re-sync language from server now that we're authenticated
try {
const resp = await fetch('/api/auth/me', { credentials: 'include' });
if (resp.ok) {
const user = await resp.json();
if (user.language && user.language !== getLocale()) {
await setLocale(user.language);
}
}
} catch (e) { /* non-bloquant */ }
// Load app data after successful login
try {
// Dynamic imports to avoid circular dependency with sidebar.js
const { loadVaults, loadTags } = await import('./sidebar.js');
await Promise.all([loadVaults(), loadTags()]);
// Start SSE sync now that auth cookie is set (dynamic import to avoid circular dep)
const { IndexUpdateManager } = await import('./sync.js');
IndexUpdateManager.connect();
// Sync offline file index now that we're authenticated
const { syncFileIndexFromServer } = await import('./offline.js');
syncFileIndexFromServer();
// Show dashboard
showWelcome();
} catch (err) {
console.error("Failed to load data after login:", err);
const result = await AuthManager.login(username, password, rememberMe);
// Check if MFA is required
if (result && result.mfa_required) {
showMfaChallenge(result.username, rememberMe, btn, errorEl, result.mfa_method);
return;
}
// Normal login success
await _onLoginSuccess();
safeCreateIcons();
} catch (err) {
errorEl.textContent = err.message;
@@ -576,4 +1003,294 @@ const AdminPanel = {
};
export { api, AuthManager, initLoginForm, AdminPanel };
// ---------------------------------------------------------------------------
// MFA Settings — Setup/Disable UI in the settings panel
// ---------------------------------------------------------------------------
async function initMfaSettings() {
const area = document.getElementById("mfa-setup-area");
const badge = document.getElementById("mfa-status-badge");
if (!area || !badge) return;
// Check current MFA status
let mfaEnabled = false;
try {
const status = await AuthManager.getMfaStatus();
mfaEnabled = status.mfa_enabled;
} catch (e) {
// Not logged in or error
return;
}
if (mfaEnabled) {
badge.textContent = t("mfa.enabled");
badge.className = "mfa-badge mfa-badge-on";
area.innerHTML = `
<p class="mfa-info-text" data-i18n="mfa.enabled_desc">${t("mfa.enabled_desc")}</p>
<button class="config-btn-secondary" id="mfa-disable-btn">${t("mfa.disable_btn")}</button>
<div id="mfa-disable-form-area"></div>
`;
document.getElementById("mfa-disable-btn").addEventListener("click", () => {
_showDisableMfaForm();
});
} else {
badge.textContent = t("mfa.disabled");
badge.className = "mfa-badge mfa-badge-off";
area.innerHTML = `
<p class="mfa-info-text" data-i18n="mfa.setup_desc">${t("mfa.setup_desc")}</p>
<button class="config-btn-primary" id="mfa-enable-btn">${t("mfa.enable_btn")}</button>
<div id="mfa-setup-flow-area"></div>
`;
document.getElementById("mfa-enable-btn").addEventListener("click", () => {
_startMfaSetup();
});
}
// WebAuthn security keys section (ROADMAP #64)
_renderWebauthnSection(area);
}
async function _renderWebauthnSection(container) {
if (!container || !window.PublicKeyCredential) return;
let keys = [];
try {
const resp = await AuthManager.webauthnCredentials();
keys = resp.credentials || [];
} catch (e) {
return; // auth disabled or endpoint unreachable — hide section
}
let section = document.getElementById("webauthn-settings");
if (!section) {
section = document.createElement("div");
section.id = "webauthn-settings";
section.className = "webauthn-settings";
container.appendChild(section);
}
const listHtml = keys.length
? `<ul class="webauthn-key-list">${keys.map((k) => `
<li class="webauthn-key-item">
<span class="webauthn-key-label">🔑 ${k.label || "Security key"}</span>
<span class="webauthn-key-meta">${(k.transports || []).join(", ") || "—"}</span>
<button class="config-btn-secondary config-btn-sm webauthn-key-remove"
data-id="${k.credential_id}">${t("mfa.webauthn_remove")}</button>
</li>`).join("")}</ul>`
: `<p class="mfa-info-text">${t("mfa.webauthn_none")}</p>`;
section.innerHTML = `
<h4 class="webauthn-title">${t("mfa.webauthn_title")}</h4>
<p class="mfa-info-text">${t("mfa.webauthn_desc")}</p>
${listHtml}
<div class="mfa-recovery-actions">
<button class="config-btn-primary" id="webauthn-add-btn">${t("mfa.webauthn_add")}</button>
</div>
<p class="mfa-error hidden" id="webauthn-error"></p>
<div id="webauthn-flow-area"></div>
`;
const errEl = section.querySelector("#webauthn-error");
document.getElementById("webauthn-add-btn").addEventListener("click", async () => {
errEl.classList.add("hidden");
try {
const credential = await runWebauthnRegistration();
const label = prompt(t("mfa.webauthn_label_prompt"), "Ma clé");
const result = await AuthManager.webauthnRegister(credential, label || "Security key");
if (result.recovery_codes && result.recovery_codes.length) {
_showRecoveryCodes(result.recovery_codes);
} else {
showToast(t("mfa.webauthn_added"), "success");
}
initMfaSettings();
} catch (err) {
errEl.textContent = err.message || String(err);
errEl.classList.remove("hidden");
}
});
section.querySelectorAll(".webauthn-key-remove").forEach((btn) => {
btn.addEventListener("click", async () => {
const password = prompt(t("mfa.webauthn_remove_confirm"));
if (password === null) return;
try {
await AuthManager.webauthnRemove(btn.dataset.id, password);
showToast(t("mfa.webauthn_removed"), "success");
initMfaSettings();
} catch (err) {
errEl.textContent = err.message || String(err);
errEl.classList.remove("hidden");
}
});
});
}
async function _startMfaSetup() {
const flowArea = document.getElementById("mfa-setup-flow-area");
if (!flowArea) return;
try {
const data = await AuthManager.mfaSetup();
flowArea.innerHTML = `
<div class="mfa-setup-card">
<h4>${t("mfa.scan_qr")}</h4>
<div class="mfa-qr-container">
<img id="mfa-qr-img" alt="QR Code" class="mfa-qr-code"
src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(data.otpauth_uri)}">
</div>
<details class="mfa-secret-details">
<summary>${t("mfa.manual_entry")}</summary>
<code class="mfa-secret-code">${data.secret}</code>
</details>
<div class="mfa-verify-section">
<label>${t("mfa.enter_code")}</label>
<input type="text" id="mfa-enable-code" class="mfa-code-input" maxlength="6"
pattern="[0-9]{6}" inputmode="numeric" placeholder="000000" autocomplete="one-time-code">
<button class="config-btn-primary" id="mfa-confirm-btn">${t("mfa.confirm_enable")}</button>
<p class="mfa-error hidden" id="mfa-enable-error"></p>
</div>
</div>
`;
const codeInput = document.getElementById("mfa-enable-code");
codeInput.addEventListener("input", () => {
codeInput.value = codeInput.value.replace(/[^0-9]/g, "");
});
document.getElementById("mfa-confirm-btn").addEventListener("click", async () => {
const code = codeInput.value.trim();
if (code.length !== 6) return;
const btn = document.getElementById("mfa-confirm-btn");
const errorEl = document.getElementById("mfa-enable-error");
btn.disabled = true;
btn.textContent = t("mfa.verifying");
errorEl.classList.add("hidden");
try {
const result = await AuthManager.mfaEnable(code);
// Show recovery codes
_showRecoveryCodes(result.recovery_codes);
} catch (err) {
errorEl.textContent = err.message;
errorEl.classList.remove("hidden");
codeInput.value = "";
codeInput.focus();
} finally {
btn.disabled = false;
btn.textContent = t("mfa.confirm_enable");
}
});
} catch (err) {
flowArea.innerHTML = `<p class="mfa-error">${err.message}</p>`;
}
}
function _showRecoveryCodes(codes) {
const flowArea = document.getElementById("mfa-setup-flow-area");
const area = document.getElementById("mfa-setup-area");
if (!flowArea) return;
const codesHtml = codes.map(c => `<code class="mfa-recovery-code">${c}</code>`).join("\n");
flowArea.innerHTML = `
<div class="mfa-recovery-card">
<h4>🔑 ${t("mfa.recovery_codes_title")}</h4>
<p class="mfa-warning">${t("mfa.recovery_codes_warning")}</p>
<div class="mfa-recovery-list" id="mfa-recovery-list">
${codesHtml}
</div>
<div class="mfa-recovery-actions">
<button class="config-btn-secondary" id="mfa-copy-codes">${t("mfa.copy_codes")}</button>
<button class="config-btn-secondary" id="mfa-download-codes">${t("mfa.download_codes")}</button>
<button class="config-btn-primary" id="mfa-codes-done">${t("mfa.done")}</button>
</div>
</div>
`;
document.getElementById("mfa-copy-codes").addEventListener("click", () => {
navigator.clipboard.writeText(codes.join("\n")).then(() => {
showToast(t("mfa.codes_copied"), "success");
});
});
document.getElementById("mfa-download-codes").addEventListener("click", () => {
const blob = new Blob([codes.join("\n")], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "obsigate-recovery-codes.txt";
a.click();
URL.revokeObjectURL(url);
});
document.getElementById("mfa-codes-done").addEventListener("click", () => {
// Refresh MFA settings display
initMfaSettings();
});
}
function _showDisableMfaForm() {
const formArea = document.getElementById("mfa-disable-form-area");
if (!formArea) return;
formArea.innerHTML = `
<div class="mfa-disable-card">
<h4>${t("mfa.disable_confirm_title")}</h4>
<p>${t("mfa.disable_confirm_desc")}</p>
<div class="form-group">
<label>${t("mfa.password_label")}</label>
<input type="password" id="mfa-disable-password" class="config-input" placeholder="${t('mfa.password_placeholder')}">
</div>
<div class="form-group">
<label>${t("mfa.totp_code_label")}</label>
<input type="text" id="mfa-disable-code" class="mfa-code-input" maxlength="6"
pattern="[0-9]{6}" inputmode="numeric" placeholder="000000">
</div>
<div class="mfa-disable-actions">
<button class="config-btn-secondary" id="mfa-disable-cancel">${t("common.cancel")}</button>
<button class="config-btn-danger" id="mfa-disable-confirm">${t("mfa.disable_confirm_btn")}</button>
</div>
<p class="mfa-error hidden" id="mfa-disable-error"></p>
</div>
`;
document.getElementById("mfa-disable-cancel").addEventListener("click", () => {
formArea.innerHTML = "";
});
document.getElementById("mfa-disable-confirm").addEventListener("click", async () => {
const password = document.getElementById("mfa-disable-password").value;
const code = document.getElementById("mfa-disable-code").value.trim();
const errorEl = document.getElementById("mfa-disable-error");
const btn = document.getElementById("mfa-disable-confirm");
if (!password || code.length !== 6) {
errorEl.textContent = t("mfa.fill_all_fields");
errorEl.classList.remove("hidden");
return;
}
btn.disabled = true;
btn.textContent = t("mfa.verifying");
errorEl.classList.add("hidden");
try {
await AuthManager.mfaDisable(password, code);
showToast(t("mfa.disabled_success"), "success");
initMfaSettings();
} catch (err) {
errorEl.textContent = err.message;
errorEl.classList.remove("hidden");
} finally {
btn.disabled = false;
btn.textContent = t("mfa.disable_confirm_btn");
}
});
}
export { api, AuthManager, initLoginForm, AdminPanel, initMfaSettings };
+492
View File
@@ -0,0 +1,492 @@
// BooksLM — Directory-scoped AI chat panel (style NotebookLM)
import { t } from './i18n.js';
import { buildAIPickerUI } from './ai.js';
import { safeCreateIcons } from './utils.js';
class BooksLM {
constructor() {
this._isOpen = false;
this._vault = null;
this._directory = null;
this._messages = [];
this._contextFiles = [];
this._isLoading = false;
this._abortCtrl = null;
this._panel = null;
this._isFullscreen = false;
}
// ── Public API ──────────────────────────────────────────────────────
async open(vault, directory) {
if (this._isOpen && this._vault === vault && this._directory === directory) {
this.close();
return;
}
this._vault = vault;
this._directory = directory;
this._messages = [];
this._contextFiles = [];
this._isLoading = true;
// Restore history
this._loadHistory();
// Build panel if needed
if (!this._panel) {
this._panel = this._render();
document.body.appendChild(this._panel);
}
this._updateHeader();
this._updateStatus();
this._renderMessages();
// Open with animation
requestAnimationFrame(() => {
this._panel.classList.add('open');
let hidden = false;
// Apply persisted hidden state (user toggled off in a previous session)
try {
const savedHidden = localStorage.getItem('obsigate-bookslm-hidden');
if (savedHidden === 'true') {
this._panel.classList.add('hidden');
this._updateToggleIcon();
hidden = true;
}
} catch { /* */ }
document.dispatchEvent(new CustomEvent(hidden ? 'bookslm:closed' : 'bookslm:opened', { detail: { vault, directory } }));
});
this._isOpen = true;
// Load context
try {
const resp = await fetch('/api/ai/bookslm/context', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ vault, directory })
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json();
this._contextFiles = data.files || [];
this._updateStatus(data);
this._showSuggestions();
} catch (e) {
console.warn('BooksLM: context load failed', e);
this._contextFiles = [];
this._updateStatus({ error: e.message });
}
this._isLoading = false;
}
close() {
if (!this._panel || !this._isOpen) return;
this._panel.classList.remove('open');
this._isOpen = false;
document.dispatchEvent(new CustomEvent('bookslm:closed'));
// Abort any in-flight request
if (this._abortCtrl) {
this._abortCtrl.abort();
this._abortCtrl = null;
}
}
/**
* Toggle the BooksLM sidebar visibility (collapsed/hidden to the right edge
* while the panel stays mounted). The state is persisted in localStorage so
* the user choice survives page reloads — same UX as the left sidebar toggle.
*
* The panel stays in the DOM (no teardown); only a CSS transform is applied,
* which is what makes this fast and matches the right-sidebar pattern in
* ObsiGate.
*/
_toggleSidebar() {
if (!this._panel) return;
const isHidden = this._panel.classList.toggle('hidden');
try {
localStorage.setItem('obsigate-bookslm-hidden', isHidden ? 'true' : 'false');
} catch { /* */ }
this._updateToggleIcon();
document.dispatchEvent(new CustomEvent(isHidden ? 'bookslm:closed' : 'bookslm:opened'));
}
/**
* Swap the toggle icon between "panel-right-close" (visible) and
* "panel-right-open" (hidden) so the button visually reflects the state.
*/
_updateToggleIcon() {
if (!this._panel) return;
const btn = this._panel.querySelector('.bookslm-btn-toggle');
if (!btn) return;
const isHidden = this._panel.classList.contains('hidden');
const icon = btn.querySelector('i[data-lucide]');
if (!icon) return;
icon.setAttribute('data-lucide', isHidden ? 'panel-right-open' : 'panel-right-close');
if (typeof safeCreateIcons === 'function') safeCreateIcons();
}
newConversation() {
this._messages = [];
this._saveHistory();
if (this._panel) {
this._renderMessages();
this._showSuggestions();
}
if (!this._isOpen && this._vault && this._directory) {
this.open(this._vault, this._directory);
}
}
exportConversation() {
if (!this._messages.length) return;
let md = `# BooksLM — ${this._directory}\n\n`;
for (const msg of this._messages) {
const role = msg.role === 'user' ? '**You**' : '**AI**';
md += `### ${role}\n\n${msg.content}\n\n---\n\n`;
}
const blob = new Blob([md], { type: 'text/markdown' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `bookslm-${this._directory.replace(/\//g, '_')}.md`;
a.click();
URL.revokeObjectURL(a.href);
}
openFile(path) {
window.dispatchEvent(new CustomEvent('obsigate:open-file', {
detail: { vault: this._vault, path }
}));
}
// ── Rendering ───────────────────────────────────────────────────────
_render() {
const panel = document.createElement('div');
panel.className = 'bookslm-panel';
panel.innerHTML = `
<div class="bookslm-header">
<button class="bookslm-btn-toggle" title="${t('bookslm.toggle_sidebar')}" aria-label="${t('bookslm.toggle_sidebar')}">
<i data-lucide="panel-right-close" style="width:16px;height:16px"></i>
</button>
<span>📚</span>
<span class="bookslm-title"></span>
<span class="bookslm-picker-host" style="margin-left:auto"></span>
<button class="bookslm-btn-new" title="${t('bookslm.new_conversation')}">✨</button>
<button class="bookslm-btn-export" title="${t('bookslm.export')}">📥</button>
<button class="bookslm-btn-fullscreen" title="⛶">⛶</button>
<button class="bookslm-btn-close" title="✕">✕</button>
</div>
<div class="bookslm-status"></div>
<div class="bookslm-suggestions"></div>
<div class="bookslm-messages"></div>
<div class="bookslm-input-area">
<textarea placeholder="${t('bookslm.placeholder')}" rows="1"></textarea>
<button class="bookslm-btn-send">${t('bookslm.send')}</button>
</div>
`;
// Inject the provider/model picker asynchronously (depends on /api/ai/status)
const pickerHost = panel.querySelector('.bookslm-picker-host');
buildAIPickerUI().then((picker) => {
if (picker && pickerHost) pickerHost.replaceWith(picker);
}).catch(() => { /* ignore */ });
// Wire events
panel.querySelector('.bookslm-btn-close').addEventListener('click', () => this.close());
panel.querySelector('.bookslm-btn-new').addEventListener('click', () => this.newConversation());
panel.querySelector('.bookslm-btn-export').addEventListener('click', () => this.exportConversation());
panel.querySelector('.bookslm-btn-toggle').addEventListener('click', () => this._toggleSidebar());
panel.querySelector('.bookslm-btn-fullscreen').addEventListener('click', () => {
this._isFullscreen = !this._isFullscreen;
panel.classList.toggle('fullscreen', this._isFullscreen);
});
// Send button
panel.querySelector('.bookslm-btn-send').addEventListener('click', () => this._sendMessage());
// Textarea auto-grow + Ctrl+Enter
const textarea = panel.querySelector('textarea');
textarea.addEventListener('input', () => {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
});
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this._sendMessage();
}
});
return panel;
}
_updateHeader() {
if (!this._panel) return;
const title = this._panel.querySelector('.bookslm-title');
if (title) {
title.textContent = this._directory
? `📚 ${this._directory.split('/').pop() || this._vault}`
: t('bookslm.title');
}
}
_updateStatus(data) {
if (!this._panel) return;
const status = this._panel.querySelector('.bookslm-status');
if (!status) return;
if (data && data.error) {
status.innerHTML = `<span style="color:#f87171">⚠ ${t('bookslm.no_context')}</span>`;
return;
}
if (data && data.files) {
const count = data.files.length;
const chars = data.total_chars || 0;
const pct = Math.min(100, Math.round((chars / 100000) * 100));
status.innerHTML = `
<span>${t('bookslm.files_indexed', { count })}, ${t('bookslm.chars_loaded', { chars: Math.round(chars / 1000) + 'K' })}</span>
<div class="bookslm-context-bar"><div class="bookslm-context-fill" style="width:${pct}%"></div></div>
`;
} else if (this._isLoading) {
status.textContent = '⏳ ...';
}
}
_showSuggestions() {
if (!this._panel) return;
const sugEl = this._panel.querySelector('.bookslm-suggestions');
if (!sugEl) return;
sugEl.innerHTML = '';
if (!this._contextFiles.length && !this._isLoading) return;
const suggestions = [
t('bookslm.suggestion_summary'),
t('bookslm.suggestion_themes'),
t('bookslm.suggestion_contradictions')
];
for (const s of suggestions) {
const btn = document.createElement('button');
btn.className = 'bookslm-suggestion';
btn.textContent = s;
btn.addEventListener('click', () => {
const textarea = this._panel.querySelector('textarea');
if (textarea) {
textarea.value = s;
this._sendMessage();
}
});
sugEl.appendChild(btn);
}
}
_renderMessages() {
if (!this._panel) return;
const container = this._panel.querySelector('.bookslm-messages');
if (!container) return;
container.innerHTML = '';
for (const msg of this._messages) {
const bubble = document.createElement('div');
bubble.className = `bookslm-bubble ${msg.role}`;
if (msg.role === 'assistant') {
bubble.innerHTML = this._renderMarkdown(msg.content || '');
// Source badges
if (msg.sources && msg.sources.length) {
const sourcesDiv = document.createElement('div');
sourcesDiv.className = 'bookslm-sources';
for (const src of msg.sources) {
const badge = document.createElement('span');
badge.className = 'bookslm-source-badge';
badge.textContent = `📄 ${src.split('/').pop()}`;
badge.title = src;
badge.addEventListener('click', () => this.openFile(src));
sourcesDiv.appendChild(badge);
}
bubble.appendChild(sourcesDiv);
}
} else {
bubble.textContent = msg.content;
}
container.appendChild(bubble);
}
// Scroll to bottom
container.scrollTop = container.scrollHeight;
}
// ── Messaging ───────────────────────────────────────────────────────
async _sendMessage() {
const textarea = this._panel.querySelector('textarea');
const text = (textarea.value || '').trim();
if (!text || this._isLoading) return;
textarea.value = '';
textarea.style.height = 'auto';
// Hide suggestions
const sugEl = this._panel.querySelector('.bookslm-suggestions');
if (sugEl) sugEl.innerHTML = '';
// Add user message
this._messages.push({ role: 'user', content: text });
this._renderMessages();
// Add assistant placeholder
const assistantMsg = { role: 'assistant', content: '', sources: [] };
this._messages.push(assistantMsg);
this._renderMessages();
this._isLoading = true;
// Disable send button
const sendBtn = this._panel.querySelector('.bookslm-btn-send');
if (sendBtn) sendBtn.disabled = true;
this._abortCtrl = new AbortController();
try {
// Read provider/model from the picker (localStorage-backed)
let provider = null;
let model = null;
try {
const picker = JSON.parse(localStorage.getItem('obsigate_ai_picker') || '{}');
provider = picker.provider || null;
model = picker.model || null;
} catch { /* */ }
const resp = await fetch('/api/ai/bookslm/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
vault: this._vault,
directory: this._directory,
// The backend expects `message` + `conversation_history`,
// not a generic `messages` array. Convert before sending.
message: this._messages.length
? this._messages[this._messages.length - 1].content
: '',
conversation_history: this._messages
.slice(0, -1)
.filter((m) => m.content && m.content.trim())
.map((m) => ({ role: m.role, content: m.content })),
context_files: this._contextFiles.map((f) => f.path || f),
provider,
model,
}),
signal: this._abortCtrl.signal
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const payload = line.slice(6);
if (payload === '[DONE]') continue;
try {
const data = JSON.parse(payload);
if (data.content) {
assistantMsg.content += data.content;
}
if (data.sources) {
assistantMsg.sources = data.sources;
}
} catch {
// Raw text token
assistantMsg.content += payload;
}
this._renderMessages();
}
}
// Extract sources from context files if mentioned
if (!assistantMsg.sources.length) {
const contentLower = assistantMsg.content.toLowerCase();
assistantMsg.sources = this._contextFiles
.filter(f => {
const name = (f.path || f || '').split('/').pop().toLowerCase();
return name && contentLower.includes(name);
})
.map(f => f.path || f);
}
} catch (e) {
if (e.name !== 'AbortError') {
assistantMsg.content = `⚠ Error: ${e.message}`;
console.warn('BooksLM chat error:', e);
}
}
this._isLoading = false;
if (sendBtn) sendBtn.disabled = false;
this._abortCtrl = null;
this._renderMessages();
this._saveHistory();
}
// ── Markdown (lightweight) ──────────────────────────────────────────
_renderMarkdown(text) {
if (!text) return '';
let html = text
// Code blocks
.replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
// Inline code
.replace(/`([^`]+)`/g, '<code>$1</code>')
// Bold
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
// Italic
.replace(/\*(.+?)\*/g, '<em>$1</em>')
// Links
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
// Unordered lists
.replace(/^[*\-+] (.+)$/gm, '<li>$1</li>')
// Headers
.replace(/^### (.+)$/gm, '<h4>$1</h4>')
.replace(/^## (.+)$/gm, '<h3>$1</h3>')
// Paragraphs
.replace(/\n\n/g, '</p><p>')
.replace(/\n/g, '<br>');
return `<p>${html}</p>`;
}
// ── History persistence ─────────────────────────────────────────────
_historyKey() {
return `bookslm-history-${this._vault}-${this._directory}`;
}
_saveHistory() {
try {
localStorage.setItem(this._historyKey(), JSON.stringify(this._messages));
} catch {}
}
_loadHistory() {
try {
const data = localStorage.getItem(this._historyKey());
if (data) {
this._messages = JSON.parse(data);
}
} catch {
this._messages = [];
}
}
}
const booksLM = new BooksLM();
export default booksLM;
export { BooksLM };
+202 -39
View File
@@ -1,5 +1,5 @@
// config.js — extracted from app.js (3872-4865)
import { api, AuthManager } from './auth.js';
import { api, AuthManager, initMfaSettings } from './auth.js';
import { state } from './state.js';
import { el, icon, openFile } from './viewer.js';
import { syncVaultSelectors, setSelectedVaultContext, refreshSidebarForContext, loadVaults, loadVaultSettings, loadTags, TagFilterService, refreshSidebarTreePreservingState } from './sidebar.js';
@@ -663,6 +663,9 @@ function initConfigModal() {
// Init profile
initProfile();
// Init MFA settings (security tab)
initMfaSettings();
}
function closeConfigModal() {
@@ -920,8 +923,7 @@ function loadAbout() {
title: t("about.section_app"),
rows: [
[t("about.name"), "ObsiGate"],
[t("about.version"), state.APP_VERSION],
[t("about.api_version"), health.version || "—"],
[t("about.version"), health.version || "—"],
[t("about.status"), health.status || "—"],
],
},
@@ -1337,21 +1339,77 @@ function updateRegexPreview() {
// ── AI Keys management ──
const AI_KEY_MAP = {
"cfg-deepseek-key": "DEEPSEEK_API_KEY",
"cfg-openrouter-key": "OPENROUTER_API_KEY",
"cfg-gemini-key": "GEMINI_API_KEY",
"cfg-nvidia-key": "NVIDIA_API_KEY",
"cfg-qwencloud-key": "QWENCLOUD_API_KEY",
"cfg-xiaomi-key": "XIAOMI_API_KEY",
"cfg-mistral-key": "MISTRAL_API_KEY",
};
const AI_PROVIDER_NAMES = ["deepseek","openrouter","gemini","nvidia","qwencloud","xiaomi","mistral"];
function _ensureAIKeyUI() {
for (const [inputId] of Object.entries(AI_KEY_MAP)) {
const input = document.getElementById(inputId);
if (!input) continue;
const row = input.closest(".config-row");
if (!row || row.dataset.enhanced) continue;
row.dataset.enhanced = "1";
row.style.cssText += "display:flex;align-items:center;gap:8px;flex-wrap:wrap;";
const badge = document.createElement("span");
badge.id = inputId.replace("-key", "-badge");
badge.style.cssText = "font-size:11px;padding:2px 8px;border-radius:10px;white-space:nowrap;";
row.appendChild(badge);
const delBtn = document.createElement("button");
delBtn.type = "button";
delBtn.id = inputId.replace("-key", "-delete");
delBtn.className = "config-btn-secondary";
delBtn.style.cssText = "font-size:11px;padding:4px 10px;color:var(--danger,#e74c3c);border-color:var(--danger,#e74c3c);cursor:pointer;display:none;";
delBtn.textContent = "\u00d7 Supprimer";
delBtn.addEventListener("click", () => deleteAIKey(inputId));
row.appendChild(delBtn);
}
}
function _setAIKeyBadge(inputId, hasKey) {
const badge = document.getElementById(inputId.replace("-key", "-badge"));
const delBtn = document.getElementById(inputId.replace("-key", "-delete"));
if (badge) {
if (hasKey) {
badge.textContent = "\u2713 Configur\u00e9";
badge.style.background = "var(--success-bg, #27ae6022)";
badge.style.color = "var(--success, #27ae60)";
badge.style.border = "1px solid var(--success, #27ae60)";
} else {
badge.textContent = "Non configur\u00e9";
badge.style.background = "var(--muted-bg, #ffffff10)";
badge.style.color = "var(--text-muted, #888)";
badge.style.border = "1px solid var(--border, #444)";
}
}
if (delBtn) delBtn.style.display = hasKey ? "inline-block" : "none";
}
async function loadAIKeys() {
_ensureAIKeyUI();
try {
const data = await api("/api/config/ai-keys");
["DEEPSEEK_API_KEY","OPENROUTER_API_KEY","GEMINI_API_KEY"].forEach(k => {
const id = "cfg-" + k.toLowerCase().replace(/_api_key/g, "") + "-key";
const input = document.getElementById(id);
if (input && data[k]) input.placeholder = data[k];
});
for (const [inputId, envName] of Object.entries(AI_KEY_MAP)) {
const input = document.getElementById(inputId);
const val = data[envName] || "";
if (input) {
input.placeholder = val || (inputId.includes("gemini") ? "AIza..." : inputId.includes("openrouter") ? "sk-or-..." : "sk-...");
}
_setAIKeyBadge(inputId, !!val);
}
} catch(e) {}
}
async function saveAIKeys() {
const keys = {};
const map = { "cfg-deepseek-key": "DEEPSEEK_API_KEY", "cfg-openrouter-key": "OPENROUTER_API_KEY", "cfg-gemini-key": "GEMINI_API_KEY" };
for (const [id, name] of Object.entries(map)) {
for (const [id, name] of Object.entries(AI_KEY_MAP)) {
const input = document.getElementById(id);
if (input && input.value.trim()) keys[name] = input.value.trim();
}
@@ -1359,8 +1417,19 @@ async function saveAIKeys() {
try {
await api("/api/config/ai-keys", { method: "POST", body: JSON.stringify(keys) });
showToast(t("config.api_keys_saved"), "success");
// Clear inputs
Object.keys(map).forEach(id => { const el = document.getElementById(id); if (el) el.value = ""; });
Object.keys(AI_KEY_MAP).forEach(id => { const el = document.getElementById(id); if (el) el.value = ""; });
loadAIKeys();
} catch(e) { showToast("Erreur: " + e.message, "error"); }
}
async function deleteAIKey(inputId) {
const envName = AI_KEY_MAP[inputId];
if (!envName) return;
const provider = envName.replace("_API_KEY", "").replace(/_/g, " ");
if (!confirm("Supprimer la cl\u00e9 API " + provider + " ?\nLe fournisseur ne sera plus disponible.")) return;
try {
await api("/api/config/ai-keys/" + envName, { method: "DELETE" });
showToast("Cl\u00e9 " + provider + " supprim\u00e9e", "success");
loadAIKeys();
} catch(e) { showToast("Erreur: " + e.message, "error"); }
}
@@ -1369,12 +1438,18 @@ async function testAIKeys() {
const status = document.getElementById("cfg-ai-status");
if (status) status.textContent = "Test en cours...";
try {
// Test connectivity
const results = await api("/api/config/ai-keys/test", { method: "POST" });
var msg = Object.entries(results).map(([k,v]) => k + ": " + v).join(" | ");
if (status) status.textContent = msg;
// Fetch models for configured providers
for (const p of ["deepseek","openrouter","gemini"]) {
for (const p of AI_PROVIDER_NAMES) {
const inputId = "cfg-" + p + "-key";
if (results[p] === "ok") {
_setAIKeyBadge(inputId, true);
} else if (results[p] && results[p].includes("non")) {
_setAIKeyBadge(inputId, false);
}
}
for (const p of AI_PROVIDER_NAMES) {
if (results[p] === "ok") {
try {
const m = await api("/api/config/ai-models?provider=" + p);
@@ -1389,9 +1464,9 @@ async function testAIKeys() {
}
}
} catch(e) {
if (status) status.textContent = "Erreur: " + e.message;
if (status) status.textContent = "Erreur: " + e.message;
}
}
}
export {
@@ -1414,25 +1489,40 @@ export {
function initThemePicker() {
import('./themes.js').then(function(mod) {
var THEMES = mod.THEMES;
var AVAILABLE_MODES = mod.AVAILABLE_MODES;
var applyTheme = mod.applyTheme;
var getCurrentTheme = mod.getCurrentTheme;
var getCurrentMode = mod.getCurrentMode;
var exportAllThemes = mod.exportAllThemes;
var importTheme = mod.importTheme;
var deleteCustomTheme = mod.deleteCustomTheme;
var loadCustomThemes = mod.loadCustomThemes;
var grid = document.getElementById('theme-grid');
if (!grid) return;
var themeKeys = Object.keys(THEMES);
// Mode label map (uses i18n t() when available, fallback to English)
var modeLabels = {
'dark': function() { return t('theme.dark'); },
'light': function() { return t('theme.light'); },
'high-contrast': function() { return t('theme.high_contrast'); },
'sepia': function() { return t('theme.sepia'); }
};
function renderCards() {
var themeKeys = Object.keys(THEMES);
var current = getCurrentTheme();
var mode = getCurrentMode();
grid.innerHTML = '';
themeKeys.forEach(function(key) {
var t = THEMES[key];
var v = t.modes[mode];
var th = THEMES[key];
// Use dark mode for preview if mode not resolved yet
var v = th.modes[mode] || th.modes.dark || th.modes.light;
if (!v) return;
var card = document.createElement('div');
card.className = 'theme-card' + (key === current ? ' active' : '');
var isCustom = th.desc === 'Custom theme';
card.innerHTML =
'<div class="theme-card-preview">' +
'<div class="theme-card-preview-bar" style="background:' + (v['--bg-sidebar'] || v['--bg-primary']) + '"></div>' +
@@ -1440,33 +1530,101 @@ function initThemePicker() {
'<div class="theme-card-preview-btn" style="background:' + (v['--accent'] || '#58a6ff') + '"></div>' +
'</div>' +
'</div>' +
'<div class="theme-card-name">' + t.name + '</div>' +
'<div class="theme-card-desc">' + t.desc + '</div>';
'<div class="theme-card-name">' + th.name + (isCustom ? ' <span class="theme-custom-badge">✦</span>' : '') + '</div>' +
'<div class="theme-card-desc">' + th.desc + '</div>';
card.addEventListener('click', function() {
applyTheme(key, mode);
renderCards();
});
// Right-click to delete custom themes
if (isCustom) {
card.addEventListener('contextmenu', function(e) {
e.preventDefault();
if (confirm(t('theme.delete_confirm'))) {
deleteCustomTheme(key);
renderCards();
}
});
}
grid.appendChild(card);
});
// Mode toggle
// Mode toggle — 4 modes
var toggle = document.createElement('div');
toggle.className = 'theme-mode-toggle';
var dBtn = elBtn(t('theme.dark'), 'dark', mode);
var lBtn = elBtn(t('theme.light'), 'light', mode);
toggle.appendChild(dBtn);
toggle.appendChild(lBtn);
grid.appendChild(toggle);
}
function elBtn(label, m, currentMode) {
var btn = document.createElement('button');
btn.className = 'theme-mode-btn' + (m === currentMode ? ' active' : '');
btn.textContent = label;
btn.addEventListener('click', function() {
applyTheme(getCurrentTheme(), m);
renderCards();
AVAILABLE_MODES.forEach(function(m) {
var btn = document.createElement('button');
btn.className = 'theme-mode-btn' + (m === mode ? ' active' : '');
btn.textContent = (modeLabels[m] || function() { return m; })();
btn.addEventListener('click', function() {
applyTheme(getCurrentTheme(), m);
renderCards();
});
toggle.appendChild(btn);
});
return btn;
grid.appendChild(toggle);
// Import/Export buttons
var actions = document.createElement('div');
actions.className = 'theme-actions';
var exportBtn = document.createElement('button');
exportBtn.className = 'theme-action-btn';
exportBtn.textContent = t('theme.export_all');
exportBtn.addEventListener('click', function() {
var json = exportAllThemes();
var blob = new Blob([json], { type: 'application/json' });
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url; a.download = 'obsigate-themes.json'; a.click();
URL.revokeObjectURL(url);
});
var importBtn = document.createElement('button');
importBtn.className = 'theme-action-btn';
importBtn.textContent = t('theme.import');
importBtn.addEventListener('click', function() {
var input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.addEventListener('change', function(e) {
var file = e.target.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function(ev) {
var content = ev.target.result;
// Support single theme or all-themes format
try {
var data = JSON.parse(content);
if (data.themes) {
// Multi-theme export: import each
var count = 0;
Object.keys(data.themes).forEach(function(k) {
var res = importTheme(JSON.stringify(data.themes[k]));
if (res.ok) count++;
});
alert(t('theme.import_success', { count: count }));
} else {
var res = importTheme(content);
if (res.ok) {
alert(t('theme.import_success', { count: 1 }));
} else {
alert(t('theme.import_error') + ': ' + res.error);
}
}
} catch(ex) {
alert(t('theme.import_error') + ': ' + ex.message);
}
renderCards();
};
reader.readAsText(file);
});
input.click();
});
actions.appendChild(exportBtn);
actions.appendChild(importBtn);
grid.appendChild(actions);
}
renderCards();
@@ -1494,7 +1652,7 @@ function initAboutModal() {
document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && overlay.classList.contains('active')) overlay.classList.remove('active'); });
function populateAbout() {
// Live stats from health endpoint
// Live stats + version from health endpoint (single source of truth)
fetch('/api/health')
.then(function(r) { return r.json(); })
.then(function(d) {
@@ -1502,6 +1660,11 @@ function initAboutModal() {
var vEl = document.getElementById('about-stat-vaults');
if (fEl) fEl.textContent = d.total_files || '—';
if (vEl) vEl.textContent = d.vaults || '—';
// Clean x.y.z version (not hardcoded) + git detail
var versionEl = document.getElementById('about-version');
if (versionEl && d.version) versionEl.textContent = d.version;
var commitEl = document.getElementById('about-commit');
if (commitEl) commitEl.textContent = d.git_describe || d.git_commit || '—';
})
.catch(function() {});
+3
View File
@@ -58,6 +58,9 @@ function getCMDS() {
{ id:'focus-next', label:'→ Panneau suivant', desc:'Active le panneau suivant (Ctrl+Alt+→)', cat:'Panneaux', act:()=>{close();if(window.PaneManager&&window.PaneManager.isSplit()){const n=(window.PaneManager.activePaneId+1)%window.PaneManager.panes.length;window.PaneManager.setActivePane(n);}} },
{ id:'focus-prev', label:'← Panneau précédent', desc:'Active le panneau précédent (Ctrl+Alt+←)', cat:'Panneaux', act:()=>{close();if(window.PaneManager&&window.PaneManager.isSplit()){const n=(window.PaneManager.activePaneId-1+window.PaneManager.panes.length)%window.PaneManager.panes.length;window.PaneManager.setActivePane(n);}} },
{ id:'reset-panes', label:'🔄 Réinitialiser les panneaux', desc:'Ferme tous les panneaux et revient au mode single-pane', cat:'Panneaux', act:()=>{close();if(window.PaneManager){while(window.PaneManager.isSplit()){window.PaneManager.closePane(window.PaneManager.panes.length-1);}localStorage.removeItem('obsigate-panes');}} },
// BooksLM commands
{ id:'bookslm-open', label:t('palette.bookslm_open'), desc:'Open BooksLM AI chat for current directory', cat:'AI', act:async()=>{close();const f=getCurrentFile();if(f){const m=await import('./bookslm.js');m.default.open(f.vault,f.path);}else{showToast(t('toast.no_open_file'),'error');}} },
{ id:'bookslm-new', label:t('palette.bookslm_new'), desc:'Reset BooksLM conversation and open fresh', cat:'AI', act:async()=>{close();const f=getCurrentFile();if(f){const m=await import('./bookslm.js');m.default.newConversation();m.default.open(f.vault,f.path);}else{showToast(t('toast.no_open_file'),'error');}} },
];
return _cmdsCache;
}
-2
View File
@@ -2,8 +2,6 @@
Use state.xxx to read/write any value. ES module imports are read-only,
so we export a single mutable object instead of individual let bindings. */
export const state = {
APP_VERSION: "1.5.0",
// Core navigation
currentVault: null,
currentPath: null,
+180 -4
View File
@@ -526,26 +526,85 @@ var THEMES = {
var _currentTheme = 'defaut-obsigate';
var _currentMode = 'dark';
var AVAILABLE_MODES = ['dark', 'light', 'high-contrast', 'sepia'];
// ── Mode generators ─────────────────────────────────────────────────
// Generate a high-contrast variant from dark-mode CSS vars.
function _genHighContrast(darkVars) {
return {
'--bg-primary': '#000000', '--bg-secondary': '#0a0a0a', '--bg-sidebar': '#000000',
'--bg-hover': '#141414', '--border': '#444444', '--text-primary': '#ffffff',
'--text-secondary': '#cccccc', '--text-muted': '#888888', '--accent': darkVars['--accent'] || '#58a6ff',
'--accent-green': '#4cff6e', '--tag-bg': '#1a2a44', '--tag-text': '#7dc4ff',
'--code-bg': '#0a0a0a', '--search-bg': '#111111', '--scrollbar': '#444444',
'--resize-handle': '#444444', '--overlay-bg': 'rgba(0,0,0,0.85)',
'--danger': '#ff6b6b', '--danger-bg': '#4a0f0f', '--success': '#4cff6e', '--success-bg': '#0a3a14',
'--accent-card': darkVars['--accent'] || '#58a6ff', '--accent-bg': '#1a2a44', '--accent-text': '#7dc4ff',
'--green': '#4cff6e', '--green-bg': '#0a3a14', '--purple': '#c084fc', '--purple-bg': '#2a1a4a',
'--surface': '#0a0a0a', '--surface2': '#000000', '--surface3': '#000000',
'--border-md': '#444444', '--text': '#ffffff', '--text-2': '#cccccc', '--text-3': '#888888',
'--ok': '#4cff6e', '--warn': '#ffcc00', '--ai': '#c084fc', '--err': '#ff6b6b'
};
}
// Generate a sepia variant from light-mode CSS vars.
function _genSepia(lightVars) {
return {
'--bg-primary': '#f5ecd5', '--bg-secondary': '#eee3c8', '--bg-sidebar': '#e8dcc0',
'--bg-hover': '#e0d4b4', '--border': '#c8b890', '--text-primary': '#3d2e1a',
'--text-secondary': '#6b5a3e', '--text-muted': '#9a8a6a', '--accent': '#b8860b',
'--accent-green': '#5a8a32', '--tag-bg': '#e8dcc0', '--tag-text': '#8b6914',
'--code-bg': '#eee3c8', '--search-bg': '#f5ecd5', '--scrollbar': '#c8b890',
'--resize-handle': '#c8b890', '--overlay-bg': 'rgba(60,40,10,0.25)',
'--danger': '#b33a2a', '--danger-bg': '#f5e0dc', '--success': '#5a8a32', '--success-bg': '#e0edd0',
'--accent-card': '#b8860b', '--accent-bg': '#f0e4c4', '--accent-text': '#8b6914',
'--green': '#5a8a32', '--green-bg': '#e0edd0', '--purple': '#7a5a9a', '--purple-bg': '#e8ddf0',
'--surface': '#eee3c8', '--surface2': '#f5ecd5', '--surface3': '#e8dcc0',
'--border-md': '#c8b890', '--text': '#3d2e1a', '--text-2': '#6b5a3e', '--text-3': '#9a8a6a',
'--ok': '#5a8a32', '--warn': '#b8860b', '--ai': '#7a5a9a', '--err': '#b33a2a'
};
}
// Get CSS vars for a theme + mode (generating HC/sepia on demand).
function _getVars(themeKey, mode) {
var theme = THEMES[themeKey];
if (!theme) return null;
if (theme.modes[mode]) return theme.modes[mode];
// Generate high-contrast / sepia from dark / light
if (mode === 'high-contrast') return _genHighContrast(theme.modes.dark || {});
if (mode === 'sepia') return _genSepia(theme.modes.light || {});
return null;
}
function applyTheme(themeKey, mode) {
var theme = THEMES[themeKey];
if (!theme) return;
mode = mode || _currentMode || 'dark';
var vars = theme.modes[mode];
var vars = _getVars(themeKey, mode);
if (!vars) return;
var root = document.documentElement;
Object.keys(vars).forEach(function(key) {
root.style.setProperty(key, vars[key]);
});
// Store resolved vars on the theme for export/preview
if (!theme.modes[mode]) theme.modes[mode] = vars;
_currentTheme = themeKey;
_currentMode = mode;
try { localStorage.setItem('obsigate-theme', themeKey); } catch(e) {}
try { localStorage.setItem('obsigate-theme-mode', mode); } catch(e) {}
// Notify other components of theme change
try {
root.setAttribute('data-theme', mode);
document.dispatchEvent(new CustomEvent('themechange', { detail: { theme: themeKey, mode: mode } }));
} catch(e) {}
}
function toggleThemeMode() {
var newMode = _currentMode === 'dark' ? 'light' : 'dark';
var idx = AVAILABLE_MODES.indexOf(_currentMode);
var newMode = AVAILABLE_MODES[(idx + 1) % AVAILABLE_MODES.length];
applyTheme(_currentTheme, newMode);
return newMode;
}
@@ -553,14 +612,131 @@ function toggleThemeMode() {
function getCurrentTheme() { return _currentTheme; }
function getCurrentMode() { return _currentMode; }
// ── Public API ──────────────────────────────────────────────────────
function setTheme(name) {
if (THEMES[name]) {
applyTheme(name, _currentMode);
}
}
function getTheme() {
return _currentTheme;
}
function listThemes() {
return Object.keys(THEMES).map(function(key) {
return { id: key, name: THEMES[key].name, desc: THEMES[key].desc };
});
}
function listModes() {
return AVAILABLE_MODES.slice();
}
// ── Import / Export ─────────────────────────────────────────────────
function exportTheme(themeKey) {
themeKey = themeKey || _currentTheme;
var theme = THEMES[themeKey];
if (!theme) return null;
// Ensure HC/sepia are resolved for export
var modes = {};
AVAILABLE_MODES.forEach(function(m) {
modes[m] = _getVars(themeKey, m);
});
return JSON.stringify({
version: 1,
id: themeKey,
name: theme.name,
desc: theme.desc,
modes: modes
}, null, 2);
}
function exportAllThemes() {
var out = {};
Object.keys(THEMES).forEach(function(key) {
out[key] = {
name: THEMES[key].name,
desc: THEMES[key].desc,
modes: {}
};
AVAILABLE_MODES.forEach(function(m) {
out[key].modes[m] = _getVars(key, m);
});
});
return JSON.stringify({ version: 1, themes: out }, null, 2);
}
function importTheme(jsonStr) {
try {
var data = JSON.parse(jsonStr);
if (!data || !data.modes) return { ok: false, error: 'Invalid theme JSON: missing modes' };
var name = data.name || data.id || ('custom-' + Date.now());
var key = (data.id || name).toLowerCase().replace(/[^a-z0-9]+/g, '-');
var modes = {};
if (data.modes.dark && typeof data.modes.dark === 'object') modes.dark = data.modes.dark;
if (data.modes.light && typeof data.modes.light === 'object') modes.light = data.modes.light;
if (Object.keys(modes).length === 0) return { ok: false, error: 'Theme must define at least dark or light mode' };
THEMES[key] = { name: name, desc: data.desc || 'Custom theme', modes: modes };
try { localStorage.setItem('obsigate-custom-' + key, JSON.stringify(THEMES[key])); } catch(e) {}
return { ok: true, key: key };
} catch(e) {
return { ok: false, error: 'JSON parse error: ' + e.message };
}
}
function loadCustomThemes() {
var keys = [];
try {
for (var i = 0; i < localStorage.length; i++) {
var k = localStorage.key(i);
if (k && k.indexOf('obsigate-custom-') === 0) {
keys.push(k);
}
}
} catch(e) {}
keys.forEach(function(lsKey) {
try {
var data = JSON.parse(localStorage.getItem(lsKey));
if (data && data.modes) {
var key = lsKey.replace('obsigate-custom-', '');
THEMES[key] = data;
}
} catch(e) {}
});
}
function deleteCustomTheme(key) {
if (THEMES[key] && THEMES[key].desc === 'Custom theme') {
delete THEMES[key];
try { localStorage.removeItem('obsigate-custom-' + key); } catch(e) {}
return true;
}
return false;
}
function initThemes() {
// Load any custom themes from localStorage first
loadCustomThemes();
var saved = null;
var savedMode = null;
try { saved = localStorage.getItem('obsigate-theme'); } catch(e) {}
try { savedMode = localStorage.getItem('obsigate-theme-mode'); } catch(e) {}
if (saved && THEMES[saved]) _currentTheme = saved;
if (savedMode) _currentMode = savedMode;
if (savedMode && AVAILABLE_MODES.indexOf(savedMode) !== -1) _currentMode = savedMode;
applyTheme(_currentTheme, _currentMode);
}
export { THEMES, applyTheme, toggleThemeMode, getCurrentTheme, getCurrentMode, initThemes };
export {
THEMES, AVAILABLE_MODES,
applyTheme, toggleThemeMode,
getCurrentTheme, getCurrentMode,
getTheme,
setTheme, listThemes, listModes,
exportTheme, exportAllThemes, importTheme, deleteCustomTheme, loadCustomThemes,
initThemes
};
+6 -2
View File
@@ -177,14 +177,16 @@ export function toggleTheme() {
// Update the theme toggle label
const themeLabel = document.getElementById("theme-label");
if (themeLabel) {
themeLabel.textContent = newMode === "dark" ? t('theme.dark') : t('theme.light');
const modeLabelMap = { dark: 'theme.dark', light: 'theme.light', 'high-contrast': 'theme.high_contrast', sepia: 'theme.sepia' };
themeLabel.textContent = t(modeLabelMap[newMode] || 'theme.dark');
}
// Update the theme toggle icon
const themeBtn = document.getElementById("theme-toggle");
if (themeBtn) {
const icon = themeBtn.querySelector("i");
if (icon) {
icon.setAttribute("data-lucide", newMode === "dark" ? "moon" : "sun");
const isLight = newMode === "light" || newMode === "sepia";
icon.setAttribute("data-lucide", isLight ? "sun" : "moon");
}
}
safeCreateIcons();
@@ -1696,6 +1698,8 @@ export const ContextMenuManager = {
this._addSeparator();
this._addItem('bookmark-plus', 'Ajouter aux recherches sauvegardees', () => this._saveDirectorySearch(), false);
this._addSeparator();
this._addItem('brain', '🧠 BooksLM', () => { import('./bookslm.js').then(m => m.default.open(this._targetVault, this._targetPath)); }, false);
this._addSeparator();
this._addItem('edit', 'Renommer', () => this._renameItem(), isReadonly);
this._addItem('trash-2', 'Supprimer', () => this._deleteDirectory(), isReadonly);
} else if (type === 'file') {
+67 -2
View File
@@ -1,5 +1,5 @@
/* ObsiGate — Viewer module */
import { api } from './auth.js';
import { api, AuthManager } from './auth.js';
import { state } from './state.js';
import { escapeHtml, safeCreateIcons, safeHighlight, getFileIcon, openEditor, copyToClipboard } from './utils.js';
import { TabManager, closeMobileSidebar, ContextMenuManager, RightSidebarManager, showToast, buildFrontmatterCard } from './ui.js';
@@ -13,6 +13,41 @@ import { openShareDialog } from './config.js';
import { cacheViewedFile, getCachedFile } from './offline.js';
import { t } from './i18n.js';
// ── Multi-format export ────────────────────────────────────────────────────
// Downloads a file export (HTML / MD bundle / ePub) via the authenticated
// export endpoints, showing a loading toast while the request is in flight.
async function downloadExport(vault, path, format, fallbackName) {
showToast(t("viewer.export_start"), "info");
const url = `/api/export/${format}?vault=${encodeURIComponent(vault)}&path=${encodeURIComponent(path)}`;
try {
const headers = AuthManager.getAuthHeaders() || {};
const res = await fetch(url, { credentials: "include", headers });
if (!res.ok) {
let detail = "";
try { detail = (await res.json()).detail || ""; } catch (_) { /* ignore */ }
throw new Error(detail || "HTTP " + res.status);
}
const blob = await res.blob();
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = fallbackName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
showToast(t("viewer.export_done"), "success");
} catch (err) {
console.error("Export error:", err);
showToast(t("viewer.export_error") + " " + err.message, "error");
}
}
// Close any open export dropdown when clicking elsewhere.
document.addEventListener("click", function (e) {
if (e.target && e.target.closest && e.target.closest(".export-dropdown")) return;
document.querySelectorAll(".export-menu").forEach(function (m) { m.style.display = "none"; });
});
// Pane-aware content area helper — delegates to PaneManager when split
function getContentArea() {
// Override set by PaneTabManager._renderFileInPane for cross-module rendering
@@ -635,6 +670,36 @@ export function renderFile(data) {
window.open(pdfUrl, "_blank");
});
// Export dropdown button (HTML / MD bundle / ePub)
const exportWrap = el("div", { class: "export-dropdown", style: "position:relative;display:inline-block" });
const exportBtn = el("button", { class: "btn-action", title: t("viewer.export_title") }, [icon("download", 14), document.createTextNode(t("viewer.export"))]);
const exportMenu = el("div", { class: "export-menu", style: "display:none;position:absolute;right:0;top:100%;z-index:1000;min-width:200px;padding:4px;background:var(--bg,#fff);border:1px solid #ccc;border-radius:6px;box-shadow:0 6px 16px rgba(0,0,0,.18)" });
const exportOptions = [
{ format: "html", icon: "file-code", label: t("viewer.export_html"), ext: ".html" },
{ format: "md-bundle", icon: "archive", label: t("viewer.export_md_bundle"), ext: ".zip" },
{ format: "epub", icon: "book-open", label: t("viewer.export_epub"), ext: ".epub" },
];
exportOptions.forEach((opt) => {
const item = el("button", { class: "export-menu-item", style: "display:flex;align-items:center;gap:8px;width:100%;padding:8px 10px;border:none;background:none;cursor:pointer;border-radius:4px;text-align:left;font-size:13px" }, [
icon(opt.icon, 14),
document.createTextNode(opt.label),
]);
item.addEventListener("mouseenter", () => { item.style.background = "rgba(128,128,128,.15)"; });
item.addEventListener("mouseleave", () => { item.style.background = "none"; });
item.addEventListener("click", () => {
exportMenu.style.display = "none";
const baseName = data.path.split("/").pop().replace(/\.[^.]+$/, "") || "document";
downloadExport(data.vault, data.path, opt.format, baseName + opt.ext);
});
exportMenu.appendChild(item);
});
exportBtn.addEventListener("click", (e) => {
e.stopPropagation();
exportMenu.style.display = exportMenu.style.display === "block" ? "none" : "block";
});
exportWrap.appendChild(exportBtn);
exportWrap.appendChild(exportMenu);
const editBtn = el("button", { class: "btn-action", title: "Editer" }, [icon("edit", 14), document.createTextNode("Editer")]);
editBtn.addEventListener("click", () => {
openEditor(data.vault, data.path);
@@ -754,7 +819,7 @@ export function renderFile(data) {
// Assemble
area.innerHTML = "";
area.appendChild(breadcrumb);
area.appendChild(el("div", { class: "file-header" }, [el("div", { class: "file-title" }, [document.createTextNode(data.title)]), tagsDiv, el("div", { class: "file-actions" }, [copyBtn, sourceBtn, mdBtn, pdfBtn, editBtn, forgeBtn, openNewWindowBtn, tocBtn, shareBtn, bookmarkBtn])]));
area.appendChild(el("div", { class: "file-header" }, [el("div", { class: "file-title" }, [document.createTextNode(data.title)]), tagsDiv, el("div", { class: "file-actions" }, [copyBtn, sourceBtn, mdBtn, pdfBtn, exportWrap, editBtn, forgeBtn, openNewWindowBtn, tocBtn, shareBtn, bookmarkBtn])]));
if (fmSection) area.appendChild(fmSection);
area.appendChild(mdDiv);
area.appendChild(rawDiv);
+119 -1
View File
@@ -42,6 +42,19 @@
"about.tests": "Tests",
"about.vaults_configured": "Configured vaults",
"about.version": "Version",
"admin.audit_all_actions": "All actions",
"admin.audit_empty": "No log available",
"admin.audit_filter_action": "Action",
"admin.audit_filter_user": "Filter by user",
"admin.audit_refresh": "Refresh",
"admin.audit_title": "Audit logs",
"admin.back_btn": "← Back",
"admin.backups_newest": "Newest: {days} days",
"admin.backups_oldest": "Oldest: {days} days",
"admin.backups_per_vault": "Per vault",
"admin.backups_title": "Backup statistics",
"admin.backups_total": "Total: {count} backups ({size})",
"admin.backups_vault_empty": "No backup",
"admin.close": "Close",
"admin.col_actions": "Actions",
"admin.col_last_login": "Last login",
@@ -49,8 +62,22 @@
"admin.col_status": "Status",
"admin.col_user": "User",
"admin.col_vaults": "Vaults",
"admin.forbidden_msg": "You must be an administrator to access this page.",
"admin.forbidden_title": "Access denied",
"admin.header_subtitle": "Administrator dashboard",
"admin.new_user": "+ New user",
"admin.page_title": "ObsiGate — Administration",
"admin.stats_cpu": "CPU",
"admin.stats_disk": "Disk",
"admin.stats_memory": "Memory",
"admin.stats_refresh": "Last update: {time}",
"admin.stats_sessions": "Active sessions",
"admin.stats_title": "Real-time statistics",
"admin.stats_uptime": "Uptime",
"admin.title": "Administration — Users",
"admin.users_manage_btn": "Manage users",
"admin.users_manage_hint": "Open the user management modal (full CRUD)",
"admin.users_title": "User management",
"ai.casual": "Casual tone",
"ai.completion_added": "AI: completion added",
"ai.continue": "Continue",
@@ -75,6 +102,13 @@
"ai.not_configured": "⚠️ AI not configured — add DEEPSEEK_API_KEY, OPENROUTER_API_KEY or GEMINI_API_KEY in .env",
"ai.processing": "⏳ AI: processing...",
"ai.professional": "Professional tone",
"ai.provider": "Provider",
"ai.provider_default": "— default —",
"ai.model": "Model",
"ai.model_default": "— default —",
"ai.model_loading": "Loading…",
"ai.model_offline": "offline",
"ai.model_load_error": "Load error",
"ai.quota_exceeded": "AI: quota exceeded or payment required",
"ai.rewrite": "💬 Rewrite",
"ai.rewrite_done": "AI: text rewritten",
@@ -1377,7 +1411,14 @@
"theme.change": "Change theme",
"theme.dark": "Dark",
"theme.light": "Light",
"theme.high_contrast": "High Contrast",
"theme.sepia": "Sepia",
"theme.title": "Theme",
"theme.export_all": "Export Themes",
"theme.import": "Import Theme",
"theme.import_success": "{count} theme(s) imported",
"theme.import_error": "Import error",
"theme.delete_confirm": "Delete this custom theme?",
"themes.name_gradients": "Subtle gradients",
"themes.name_terminal": "Pure black & green",
"toast.ai_keys_saved": "API keys saved",
@@ -1465,6 +1506,14 @@
"viewer.download_pdf": "Download as PDF",
"viewer.edit": "Edit",
"viewer.error": "Loading error",
"viewer.export": "Export",
"viewer.export_done": "Export complete",
"viewer.export_epub": "Export as ePub",
"viewer.export_error": "Export error:",
"viewer.export_html": "Export as HTML",
"viewer.export_md_bundle": "Export as Markdown bundle (.zip)",
"viewer.export_start": "Exporting...",
"viewer.export_title": "Export document",
"viewer.forge_brand": "Forge",
"viewer.forge_title": "Forge (new editor)",
"viewer.index_start": "Starting index...",
@@ -1495,5 +1544,74 @@
"webhook.trigger_dir_create": "Directory creation via API",
"webhook.trigger_dir_delete": "Directory deletion via API",
"webhook.trigger_dir_rename": "Directory rename via API",
"webhook.trigger_rename": "Rename via API"
"webhook.trigger_rename": "Rename via API",
"settings.security": "🔒 Account Security",
"settings.security_desc": "Enable two-factor authentication (2FA) to strengthen your account security.",
"mfa.title": "Two-Factor Authentication",
"mfa.subtitle": "Enter the 6-digit code from your authenticator app.",
"mfa.verify": "Verify",
"mfa.verifying": "Verifying...",
"mfa.use_recovery": "Use a recovery code",
"mfa.back_to_login": "Back to login",
"mfa.recovery_title": "Recovery Code",
"mfa.recovery_subtitle": "Enter one of your recovery codes (format: XXXX-XXXX).",
"mfa.use_totp": "Use authenticator code",
"mfa.status_label": "Two-Factor Authentication",
"mfa.enabled": "Enabled",
"mfa.disabled": "Disabled",
"mfa.enabled_desc": "Your account is protected by two-factor authentication.",
"mfa.setup_desc": "Add an extra layer of security to your account with TOTP.",
"mfa.enable_btn": "Enable 2FA",
"mfa.disable_btn": "Disable 2FA",
"mfa.scan_qr": "Scan this QR code with your authenticator app",
"mfa.manual_entry": "Manual entry (if you can't scan)",
"mfa.enter_code": "Enter the 6-digit code to confirm",
"mfa.confirm_enable": "Confirm & Enable",
"mfa.recovery_codes_title": "Recovery Codes",
"mfa.recovery_codes_warning": "Save these codes in a secure place. Each code can only be used once.",
"mfa.copy_codes": "Copy",
"mfa.download_codes": "Download",
"mfa.done": "Done",
"mfa.codes_copied": "Recovery codes copied!",
"mfa.disable_confirm_title": "Disable 2FA",
"mfa.disable_confirm_desc": "Enter your password and a valid TOTP code to disable two-factor authentication.",
"mfa.password_label": "Password",
"mfa.password_placeholder": "Your current password",
"mfa.totp_code_label": "TOTP Code",
"mfa.disable_confirm_btn": "Disable 2FA",
"mfa.disabled_success": "2FA has been disabled.",
"mfa.fill_all_fields": "Please fill in all fields.",
"bookslm.title": "BooksLM",
"bookslm.files_indexed": "{count} files indexed",
"bookslm.chars_loaded": "{chars} chars loaded",
"bookslm.placeholder": "Ask a question about these documents...",
"bookslm.send": "Send",
"bookslm.new_conversation": "New conversation",
"bookslm.export": "Export conversation",
"bookslm.toggle_sidebar": "Hide/Show AI sidebar",
"bookslm.copy": "Copy",
"bookslm.regenerate": "Regenerate",
"bookslm.suggestion_summary": "Summarize this directory",
"bookslm.suggestion_themes": "What are the main themes?",
"bookslm.suggestion_contradictions": "Are there contradictions between these documents?",
"bookslm.no_context": "No files found in this directory",
"bookslm.context_too_large": "Directory too large — some files were truncated",
"bookslm.source": "Source",
"palette.bookslm_open": "BooksLM: Open for current directory",
"palette.bookslm_new": "BooksLM: New conversation",
"fab.open": "Open AI assistant",
"fab.close": "Close AI assistant",
"mfa.webauthn_title": "Security keys (WebAuthn)",
"mfa.webauthn_desc": "Authenticate with a physical key (YubiKey) or your device biometrics (Windows Hello, Touch ID).",
"mfa.webauthn_none": "No registered keys.",
"mfa.webauthn_add": "Add a security key",
"mfa.webauthn_label_prompt": "Key name (e.g. Pocket YubiKey)",
"mfa.webauthn_added": "Security key registered.",
"mfa.webauthn_removed": "Security key removed.",
"mfa.webauthn_remove": "Remove",
"mfa.webauthn_remove_confirm": "Enter your password to remove this key:",
"mfa.webauthn_prompt": "Present your security key or confirm with Windows Hello.",
"mfa.webauthn_btn": "Verify with my key",
"mfa.webauthn_cancelled": "WebAuthn ceremony cancelled.",
"mfa.webauthn_no_key": "No security key registered for this account."
}
+119 -1
View File
@@ -42,6 +42,19 @@
"about.tests": "Tests",
"about.vaults_configured": "Vaults configurés",
"about.version": "Version",
"admin.audit_all_actions": "Toutes les actions",
"admin.audit_empty": "Aucun log disponible",
"admin.audit_filter_action": "Action",
"admin.audit_filter_user": "Filtrer par utilisateur",
"admin.audit_refresh": "Rafraîchir",
"admin.audit_title": "Logs d'audit",
"admin.back_btn": "← Retour",
"admin.backups_newest": "Plus récent : {days} jours",
"admin.backups_oldest": "Plus ancien : {days} jours",
"admin.backups_per_vault": "Par vault",
"admin.backups_title": "Statistiques backups",
"admin.backups_total": "Total : {count} backups ({size})",
"admin.backups_vault_empty": "Aucun backup",
"admin.close": "Fermer",
"admin.col_actions": "Actions",
"admin.col_last_login": "Dernière connexion",
@@ -49,8 +62,22 @@
"admin.col_status": "Statut",
"admin.col_user": "Utilisateur",
"admin.col_vaults": "Vaults",
"admin.forbidden_msg": "Vous devez être administrateur pour accéder à cette page.",
"admin.forbidden_title": "Accès refusé",
"admin.header_subtitle": "Tableau de bord administrateur",
"admin.new_user": "+ Nouvel utilisateur",
"admin.page_title": "ObsiGate — Administration",
"admin.stats_cpu": "CPU",
"admin.stats_disk": "Disque",
"admin.stats_memory": "Mémoire",
"admin.stats_refresh": "Dernière mise à jour : {time}",
"admin.stats_sessions": "Sessions actives",
"admin.stats_title": "Statistiques temps réel",
"admin.stats_uptime": "Uptime",
"admin.title": "Administration — Utilisateurs",
"admin.users_manage_btn": "Gérer les utilisateurs",
"admin.users_manage_hint": "Ouvrir la modale de gestion des utilisateurs (CRUD complet)",
"admin.users_title": "Gestion utilisateurs",
"ai.casual": "Ton décontracté",
"ai.completion_added": "AI: complétion ajoutée",
"ai.continue": "Continuer",
@@ -75,6 +102,13 @@
"ai.not_configured": "⚠️ AI non configuré — ajouter DEEPSEEK_API_KEY, OPENROUTER_API_KEY ou GEMINI_API_KEY dans .env",
"ai.processing": "⏳ AI: traitement en cours...",
"ai.professional": "Ton professionnel",
"ai.provider": "Fournisseur",
"ai.provider_default": "— défaut —",
"ai.model": "Modèle",
"ai.model_default": "— défaut —",
"ai.model_loading": "Chargement…",
"ai.model_offline": "hors ligne",
"ai.model_load_error": "Erreur de chargement",
"ai.quota_exceeded": "AI: quota dépassé ou paiement requis",
"ai.rewrite": "💬 Réécrire",
"ai.rewrite_done": "AI: texte réécrit",
@@ -1377,7 +1411,14 @@
"theme.change": "Changer le thème",
"theme.dark": "Sombre",
"theme.light": "Clair",
"theme.high_contrast": "Contraste élevé",
"theme.sepia": "Sépia",
"theme.title": "Thème",
"theme.export_all": "Exporter les thèmes",
"theme.import": "Importer un thème",
"theme.import_success": "{count} thème(s) importé(s)",
"theme.import_error": "Erreur d'importation",
"theme.delete_confirm": "Supprimer ce thème personnalisé ?",
"themes.name_gradients": "Degrades subtils",
"themes.name_terminal": "Noir pur & vert",
"toast.ai_keys_saved": "Clés API sauvegardées",
@@ -1465,6 +1506,14 @@
"viewer.download_pdf": "Télécharger en PDF",
"viewer.edit": "Éditer",
"viewer.error": "Erreur de chargement",
"viewer.export": "Exporter",
"viewer.export_done": "Export terminé",
"viewer.export_epub": "Exporter en ePub",
"viewer.export_error": "Erreur d'export :",
"viewer.export_html": "Exporter en HTML",
"viewer.export_md_bundle": "Exporter en bundle Markdown (.zip)",
"viewer.export_start": "Export en cours...",
"viewer.export_title": "Exporter le document",
"viewer.forge_brand": "Forge",
"viewer.forge_title": "Forge (nouvel éditeur)",
"viewer.index_start": "Démarrage index.",
@@ -1495,5 +1544,74 @@
"webhook.trigger_dir_create": "Création de dossier via API",
"webhook.trigger_dir_delete": "Suppression de dossier via l'API",
"webhook.trigger_dir_rename": "Renommage de dossier via l'API",
"webhook.trigger_rename": "Renommage via l'API"
"webhook.trigger_rename": "Renommage via l'API",
"settings.security": "🔒 Sécurité du compte",
"settings.security_desc": "Activez l'authentification à deux facteurs (2FA) pour renforcer la sécurité de votre compte.",
"mfa.title": "Authentification à deux facteurs",
"mfa.subtitle": "Entrez le code à 6 chiffres de votre application d'authentification.",
"mfa.verify": "Vérifier",
"mfa.verifying": "Vérification...",
"mfa.use_recovery": "Utiliser un code de récupération",
"mfa.back_to_login": "Retour à la connexion",
"mfa.recovery_title": "Code de récupération",
"mfa.recovery_subtitle": "Entrez l'un de vos codes de récupération (format : XXXX-XXXX).",
"mfa.use_totp": "Utiliser le code authenticator",
"mfa.status_label": "Authentification à deux facteurs",
"mfa.enabled": "Activée",
"mfa.disabled": "Désactivée",
"mfa.enabled_desc": "Votre compte est protégé par l'authentification à deux facteurs.",
"mfa.setup_desc": "Ajoutez une couche de sécurité supplémentaire à votre compte avec le TOTP.",
"mfa.enable_btn": "Activer la 2FA",
"mfa.disable_btn": "Désactiver la 2FA",
"mfa.scan_qr": "Scannez ce QR code avec votre application d'authentification",
"mfa.manual_entry": "Saisie manuelle (si vous ne pouvez pas scanner)",
"mfa.enter_code": "Entrez le code à 6 chiffres pour confirmer",
"mfa.confirm_enable": "Confirmer et activer",
"mfa.recovery_codes_title": "Codes de récupération",
"mfa.recovery_codes_warning": "Enregistrez ces codes dans un endroit sûr. Chaque code ne peut être utilisé qu'une seule fois.",
"mfa.copy_codes": "Copier",
"mfa.download_codes": "Télécharger",
"mfa.done": "Terminé",
"mfa.codes_copied": "Codes de récupération copiés !",
"mfa.disable_confirm_title": "Désactiver la 2FA",
"mfa.disable_confirm_desc": "Entrez votre mot de passe et un code TOTP valide pour désactiver l'authentification à deux facteurs.",
"mfa.password_label": "Mot de passe",
"mfa.password_placeholder": "Votre mot de passe actuel",
"mfa.totp_code_label": "Code TOTP",
"mfa.disable_confirm_btn": "Désactiver la 2FA",
"mfa.disabled_success": "La 2FA a été désactivée.",
"mfa.fill_all_fields": "Veuillez remplir tous les champs.",
"bookslm.title": "BooksLM",
"bookslm.files_indexed": "{count} fichiers indexés",
"bookslm.chars_loaded": "{chars} caractères chargés",
"bookslm.placeholder": "Posez une question sur ces documents...",
"bookslm.send": "Envoyer",
"bookslm.new_conversation": "Nouvelle conversation",
"bookslm.export": "Exporter la conversation",
"bookslm.toggle_sidebar": "Masquer/Afficher la sidebar AI",
"bookslm.copy": "Copier",
"bookslm.regenerate": "Régénérer",
"bookslm.suggestion_summary": "Résume ce répertoire",
"bookslm.suggestion_themes": "Quels sont les thèmes principaux ?",
"bookslm.suggestion_contradictions": "Y a-t-il des contradictions entre ces documents ?",
"bookslm.no_context": "Aucun fichier trouvé dans ce répertoire",
"bookslm.context_too_large": "Répertoire trop volumineux — certains fichiers ont été tronqués",
"bookslm.source": "Source",
"palette.bookslm_open": "BooksLM: Ouvrir pour le répertoire courant",
"palette.bookslm_new": "BooksLM: Nouvelle conversation",
"fab.open": "Ouvrir l'assistant AI",
"fab.close": "Fermer l'assistant AI",
"mfa.webauthn_title": "Clés de sécurité (WebAuthn)",
"mfa.webauthn_desc": "Authentifiez-vous avec une clé physique (YubiKey) ou la biométrie de votre appareil (Windows Hello, Touch ID).",
"mfa.webauthn_none": "Aucune clé enregistrée.",
"mfa.webauthn_add": "Ajouter une clé de sécurité",
"mfa.webauthn_label_prompt": "Nom de la clé (ex : YubiKey de poche)",
"mfa.webauthn_added": "Clé de sécurité enregistrée.",
"mfa.webauthn_removed": "Clé de sécurité supprimée.",
"mfa.webauthn_remove": "Retirer",
"mfa.webauthn_remove_confirm": "Entrez votre mot de passe pour retirer cette clé :",
"mfa.webauthn_prompt": "Présentez votre clé de sécurité ou confirmez avec Windows Hello.",
"mfa.webauthn_btn": "Valider avec ma clé",
"mfa.webauthn_cancelled": "Cérémonie WebAuthn annulée.",
"mfa.webauthn_no_key": "Aucune clé de sécurité enregistrée pour ce compte."
}
+249 -7
View File
@@ -522,15 +522,16 @@ a:hover {
background: color-mix(in srgb, var(--accent) 10%, transparent);
}
/* Version badge in header */
/* Version badge in header — always visible */
.version-badge {
display: none;
font-size: 10px;
color: var(--text-muted);
padding: 2px 8px;
display: inline-block;
font-size: 11px;
color: var(--text-secondary);
font-weight: 500;
padding: 3px 10px;
border-radius: 10px;
background: color-mix(in srgb, var(--text-muted) 8%, transparent);
border: 1px solid color-mix(in srgb, var(--text-muted) 15%, transparent);
background: color-mix(in srgb, var(--text-secondary) 10%, transparent);
border: 1px solid color-mix(in srgb, var(--text-secondary) 20%, transparent);
font-family: var(--font-mono, monospace);
white-space: nowrap;
cursor: default;
@@ -2398,6 +2399,34 @@ select {
background: var(--accent);
color: #fff;
}
/* Theme import/export actions */
.theme-actions {
display: flex;
gap: 8px;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.theme-action-btn {
padding: 5px 14px;
font-size: 0.7rem;
font-weight: 600;
border: 1px solid var(--border);
background: var(--bg-secondary);
color: var(--text-secondary);
border-radius: 6px;
cursor: pointer;
transition: background 0.15s, color 0.15s;
}
.theme-action-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.theme-custom-badge {
font-size: 0.6rem;
color: var(--accent);
margin-left: 2px;
}
/* Profile section */
.profile-form { max-width: 420px; }
.profile-field { margin-bottom: 14px; }
@@ -3805,6 +3834,12 @@ body.resizing-v {
cursor: pointer;
}
.config-select option {
background: var(--bg-input, #1a1a2e);
color: var(--text-primary, #e0e0e0);
padding: 4px 8px;
}
.config-btn-add {
padding: 8px 16px;
border: 1px solid var(--accent);
@@ -8878,3 +8913,210 @@ body.popup-mode .content-area {
right: 4px;
}
}
/* ── MFA (Multi-Factor Authentication) ────────────────────────────────── */
.mfa-challenge {
margin-top: 20px;
padding: 24px;
border-radius: 12px;
background: var(--surface, #1a1a2e);
border: 1px solid var(--border, #333);
text-align: center;
}
.mfa-challenge .mfa-icon { font-size: 48px; margin-bottom: 12px; }
.mfa-challenge h3 { margin: 0 0 8px; color: var(--text, #fff); }
.mfa-challenge p { color: var(--muted, #999); margin: 0 0 16px; }
.mfa-code-input {
width: 180px;
font-size: 28px;
text-align: center;
letter-spacing: 12px;
padding: 12px;
border: 2px solid var(--border, #444);
border-radius: 8px;
background: var(--bg, #0d0d1a);
color: var(--text, #fff);
font-family: monospace;
outline: none;
}
.mfa-code-input:focus { border-color: var(--accent, #7C3AED); }
.mfa-code-input-group { display: flex; gap: 8px; justify-content: center; align-items: center; margin-bottom: 12px; }
.mfa-code-input-group span { color: var(--muted, #999); font-size: 24px; }
.mfa-link-btn {
background: none; border: none; color: var(--accent, #7C3AED);
cursor: pointer; font-size: 13px; text-decoration: underline;
}
.mfa-link-btn:hover { opacity: 0.8; }
.mfa-error { color: #e74c3c; font-size: 13px; margin-top: 8px; }
.mfa-recovery-input { width: 200px; font-size: 20px; letter-spacing: 4px; }
/* MFA Settings (Security tab) */
.mfa-status-section { padding: 16px 0; }
.mfa-status-row { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
.mfa-badge {
display: inline-flex; align-items: center; gap: 6px;
padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 600;
}
.mfa-badge-on { background: #1a3a2a; color: #4ade80; }
.mfa-badge-off { background: #3a2a1a; color: #f59e0b; }
.mfa-status-label { color: var(--text, #fff); font-weight: 500; }
/* MFA Setup card */
.mfa-setup-card {
padding: 20px; border-radius: 10px;
background: var(--surface2, #1e1e3a); border: 1px solid var(--border, #333);
}
.mfa-setup-card h4 { margin: 0 0 12px; color: var(--text, #fff); }
.mfa-qr-container { text-align: center; margin: 16px 0; }
.mfa-qr-code img, .mfa-qr-code canvas { max-width: 200px; border-radius: 8px; }
.mfa-secret-details { margin-top: 12px; }
.mfa-secret-code {
font-family: monospace; font-size: 14px; padding: 8px 12px;
background: var(--bg, #0d0d1a); border-radius: 6px;
color: var(--accent, #7C3AED); cursor: pointer; user-select: all;
display: inline-block;
}
.mfa-info-text { color: var(--muted, #999); font-size: 13px; margin: 8px 0; }
.mfa-subtitle { color: var(--muted, #999); font-size: 13px; margin: 0 0 16px; }
.mfa-verify-section { display: flex; gap: 8px; align-items: center; margin-top: 12px; }
.mfa-actions { margin-top: 16px; }
/* MFA Recovery codes display */
.mfa-recovery-card {
padding: 20px; border-radius: 10px;
background: var(--surface2, #1e1e3a); border: 1px solid var(--border, #333);
margin-top: 16px;
}
.mfa-recovery-card h4 { margin: 0 0 8px; color: var(--text, #fff); }
.mfa-recovery-list {
display: grid; grid-template-columns: 1fr 1fr; gap: 6px 24px;
margin: 12px 0; list-style: none; padding: 0;
}
.mfa-recovery-code {
font-family: monospace; font-size: 14px; padding: 4px 8px;
background: var(--bg, #0d0d1a); border-radius: 4px;
color: var(--text, #fff); letter-spacing: 1px;
}
.mfa-recovery-actions { display: flex; gap: 8px; margin-top: 12px; }
/* WebAuthn security keys (ROADMAP #64) */
.webauthn-settings { margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border, #333); }
.webauthn-title { margin: 0 0 6px; color: var(--text, #fff); font-size: 0.95rem; }
.webauthn-key-list { list-style: none; margin: 10px 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.webauthn-key-item {
display: flex; align-items: center; gap: 10px; padding: 8px 10px;
background: var(--surface2, #1a1a2e); border-radius: 6px;
}
.webauthn-key-label { flex: 1; font-size: 0.9rem; color: var(--text, #fff); }
.webauthn-key-meta { font-size: 0.75rem; color: var(--text-muted, #888); }
.config-btn-sm { padding: 4px 10px; font-size: 0.78rem; }
/* MFA Disable card */
.mfa-disable-card {
padding: 16px; border-radius: 10px;
background: var(--surface2, #1e1e3a); border: 1px solid #e74c3c33;
margin-top: 16px;
}
.mfa-disable-card h4 { margin: 0 0 8px; color: #e74c3c; }
.mfa-disable-actions { display: flex; gap: 8px; margin-top: 12px; }
.mfa-warning {
color: #f59e0b; font-size: 13px; padding: 8px 12px;
background: #3a2a1a; border-radius: 6px; margin-top: 8px;
}
/* ── BooksLM Panel ──────────────────────────────────── */
.bookslm-panel { position: fixed; right: 0; top: 0; bottom: 0; width: 450px;
background: var(--bg-primary); border-left: 1px solid var(--border);
z-index: 100; display: flex; flex-direction: column;
transform: translateX(100%); transition: transform 300ms ease-out;
box-shadow: -4px 0 20px rgba(0,0,0,0.3);
color: var(--text-primary); }
.bookslm-panel.open { transform: translateX(0); }
/* The `.hidden` class is applied by the header toggle button to collapse the
panel while keeping it mounted (so the toggle icon stays usable). When
hidden, the panel is slid fully off-screen and the open animation no
longer overrides the translateX. */
.bookslm-panel.open.hidden { transform: translateX(100%); }
.bookslm-btn-toggle {
display: flex; align-items: center; justify-content: center;
background: none; border: none; cursor: pointer;
color: var(--text-secondary); padding: 4px;
border-radius: 4px; flex-shrink: 0;
transition: color 200ms ease, background 200ms ease;
}
.bookslm-btn-toggle:hover { color: var(--accent); background: var(--surface2); }
.bookslm-header { display: flex; align-items: center; gap: 8px;
padding: 12px 16px; border-bottom: 1px solid var(--border);
font-size: 14px; font-weight: 600; }
.bookslm-header .bookslm-title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bookslm-header .bookslm-picker-host,
.bookslm-header .ai-picker,
.bookslm-header button { flex-shrink: 0; }
.bookslm-header .ai-picker { z-index: 1; }
.bookslm-header button { background: none; border: none; cursor: pointer;
color: var(--text-secondary); font-size: 16px; padding: 4px 8px; border-radius: 4px; }
.bookslm-header button:hover { background: var(--surface2); color: var(--text-primary); }
.bookslm-status { padding: 6px 16px; font-size: 12px; color: var(--text-secondary);
border-bottom: 1px solid var(--border); display: flex; gap: 12px; align-items: center; }
.bookslm-status .bookslm-context-bar { flex: 1; height: 4px; border-radius: 2px;
background: var(--surface2); overflow: hidden; }
.bookslm-status .bookslm-context-fill { height: 100%; border-radius: 2px; background: var(--accent); transition: width 0.3s; }
.bookslm-messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; }
.bookslm-bubble { max-width: 85%; padding: 10px 14px; border-radius: 12px; font-size: 14px; line-height: 1.5; word-wrap: break-word; }
.bookslm-bubble.user { align-self: flex-end; background: var(--accent); color: #fff; border-bottom-right-radius: 4px; }
.bookslm-bubble.assistant { align-self: flex-start; background: var(--surface2); color: var(--text-primary); border-bottom-left-radius: 4px; }
.bookslm-bubble.assistant code { background: rgba(0,0,0,0.2); padding: 1px 4px; border-radius: 3px; font-size: 0.9em; }
.bookslm-bubble.assistant pre { background: rgba(0,0,0,0.3); padding: 10px; border-radius: 6px; overflow-x: auto; margin: 8px 0; }
.bookslm-sources { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 8px; }
.bookslm-source-badge { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px;
background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
font-size: 11px; color: var(--accent); cursor: pointer; }
.bookslm-source-badge:hover { background: var(--surface2); }
.bookslm-input-area { display: flex; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--border); align-items: flex-end; }
.bookslm-input-area textarea { flex: 1; resize: none; min-height: 36px; max-height: 120px;
padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border);
background: var(--bg-primary); color: var(--text-primary); font-size: 14px; font-family: inherit; }
.bookslm-input-area textarea:focus { border-color: var(--accent); outline: none; }
.bookslm-input-area button { padding: 8px 16px; border-radius: 8px; border: none;
background: var(--accent); color: #fff; cursor: pointer; font-size: 14px; }
.bookslm-input-area button:hover { opacity: 0.9; }
.bookslm-input-area button:disabled { opacity: 0.5; cursor: not-allowed; }
.bookslm-suggestions { display: flex; flex-direction: column; gap: 6px; padding: 8px 16px 0; }
.bookslm-suggestion { padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border);
background: var(--surface); color: var(--text-secondary); cursor: pointer; font-size: 13px; text-align: left; }
.bookslm-suggestion:hover { background: var(--surface2); color: var(--text-primary); border-color: var(--accent); }
@media (max-width: 768px) {
.bookslm-panel { width: 100%; }
}
/* ── AI Floating Action Button ───────────────────────── */
.ai-fab {
position: fixed;
bottom: 24px;
right: 24px;
width: 52px;
height: 52px;
border-radius: 50%;
background: var(--accent);
color: #fff;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
z-index: 99;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
transition: transform 200ms ease, opacity 200ms ease;
padding: 0;
}
.ai-fab:hover {
transform: scale(1.08);
}
.ai-fab:active {
transform: scale(0.96);
}
.ai-fab[hidden] {
display: none;
}
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# ObsiGate — version bump helper (SemVer MAJOR.MINOR.PATCH)
#
# The canonical version is the latest release tag. This tool inspects the
# commits since that tag and decides the next version from their type
# (Conventional Commits), then creates and pushes the new tag:
#
# breaking change / `!:` / "BREAKING CHANGE" -> MAJOR bump (x.0.0)
# feat / feature -> MINOR bump (x.y.0)
# anything else (fix, perf, refactor, ...) -> PATCH bump (x.y.z)
#
# Usage:
# scripts/bump_version.sh [--major|--minor|--patch] [--dry-run] [--push]
#
# --dry-run : only print the computed next version, do not tag.
# --push : also `git push origin` the new tag (default: local only).
# --major|--minor|--patch : force the increment, overriding commit detection.
#
# Examples:
# scripts/bump_version.sh --dry-run # preview next version
# scripts/bump_version.sh # tag locally per commits
# scripts/bump_version.sh --patch --push # force patch + push
# -----------------------------------------------------------------------------
set -euo pipefail
cd "$(git rev-parse --show-toplevel)" # run from repo root regardless of cwd
BRANCH="$(git branch --show-current)"
# ── Parse args ────────────────────────────────────────────────────────────
FORCE=""; DRY_RUN=0; DO_PUSH=0
for a in "$@"; do
case "$a" in
--major) FORCE=major ;;
--minor) FORCE=minor ;;
--patch) FORCE=patch ;;
--dry-run) DRY_RUN=1 ;;
--push) DO_PUSH=1 ;;
*) echo "✗ Argument inconnu: $a"; exit 2 ;;
esac
done
# ── Current version = latest tag base ─────────────────────────────────────
CURRENT="$(git describe --tags --abbrev=0 2>/dev/null || echo "0.0.0")"
CURRENT="${CURRENT#v}"
IFS='.' read -r MAJ MIN PAT <<< "$CURRENT"
MAJ="${MAJ:-0}"; MIN="${MIN:-0}"; PAT="${PAT:-0}"
echo "Version actuelle : $CURRENT (branche: $BRANCH)"
# ── Detect bump type from commits since last tag ──────────────────────────
if [ -z "$FORCE" ]; then
# Use HEAD~1..HEAD when no tag exists yet (all commits "since" nothing).
RANGE="${CURRENT#0.0.0}" # if 0.0.0 fallback there may be no tag at all
if git rev-parse "v${CURRENT}" >/dev/null 2>&1; then
RANGE="v${CURRENT}..HEAD"
else
RANGE="HEAD~10..HEAD"
echo "⚠ Aucun tag v${CURRENT} trouvé — analyse des 10 derniers commits."
fi
LOG="$(git log --format='%s%n%b' "$RANGE" 2>/dev/null || true)"
BUMP="patch" # default
if echo "$LOG" | grep -qE '^[a-zA-Z]+\([^)]*\)!:|\!:\s|BREAKING CHANGE:'; then
BUMP="major"
elif echo "$LOG" | grep -qiE '^(feat|feature)(\(|:|\s)'; then
BUMP="minor"
fi
# If nothing meaningful in range, keep patch
echo "Détection (${RANGE}) : changement ${BUMP}"
else
BUMP="$FORCE"
echo "Incrément forcé : ${BUMP}"
fi
# ── Compute next version ──────────────────────────────────────────────────
case "$BUMP" in
major) MAJ=$((MAJ + 1)); MIN=0; PAT=0 ;;
minor) MIN=$((MIN + 1)); PAT=0 ;;
*) PAT=$((PAT + 1)) ;;
esac
NEXT="${MAJ}.${MIN}.${PAT}"
# ── Guard: tag already exists? ────────────────────────────────────────────
if git rev-parse "v${NEXT}" >/dev/null 2>&1; then
echo "✗ Le tag v${NEXT} existe déjà. Corrigez l'incrément ou retirez le tag."
exit 1
fi
if [ "$DRY_RUN" = "1" ]; then
echo "── DRY RUN ─────────────────────────────"
echo " Prochain tag : v${NEXT}"
echo " (aucun tag créé)"
exit 0
fi
# ── Create tag ────────────────────────────────────────────────────────────
git tag -a "v${NEXT}" -m "Release v${NEXT} (${BUMP} bump depuis v${CURRENT})"
echo "✓ Tag créé localement : v${NEXT}"
if [ "$DO_PUSH" = "1" ]; then
git push origin "v${NEXT}"
echo "✓ Tag poussé : v${NEXT}"
else
echo "ℹ Tag local uniquement. Poussez avec: git push origin v${NEXT}"
fi
echo "Done."
+7
View File
@@ -128,6 +128,13 @@ def make_gitea_request(
if content_type:
req.add_header("Content-Type", content_type)
req.add_header("Accept", "application/json")
# Cloudflare sur git.dracodev.net bloque les User-Agents "Python-urllib/*"
# (HTTP 403 Error 1010) pour les écritures ; on présente un UA navigateur.
req.add_header(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
)
try:
with urllib.request.urlopen(req, data=data) as resp:
+555
View File
@@ -0,0 +1,555 @@
{
"name": "frontend",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frontend",
"version": "1.0.0",
"license": "ISC",
"devDependencies": {
"jsdom": "^30.0.1"
}
},
"node_modules/@asamuzakjp/css-color": {
"version": "6.0.7",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-6.0.7.tgz",
"integrity": "sha512-vC/bk1Lz7Tn/EfU9/apOTBk80/8dyGyWMowPoV1tJ52muDGsDqt2HPT2klrFUiY60MQmQv9q8yIht15JnBgDGw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@csstools/css-calc": "^3.3.0",
"@csstools/css-color-parser": "^4.1.10",
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0",
"lru-cache": "^11.5.2"
},
"engines": {
"node": "^22.13.0 || >=24.0.0"
}
},
"node_modules/@asamuzakjp/dom-selector": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-8.3.2.tgz",
"integrity": "sha512-93Z1N+BQNXysodoicpOIyNh2drHfz/CTf9nnT0FEx72GJcIiwgydD7tGAr78j41LsYn3hlRn+LdGPuBLn1Bl8Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"bidi-js": "^1.0.3",
"css-tree": "^3.2.1",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.2"
},
"engines": {
"node": "^22.13.0 || >=24.0.0"
}
},
"node_modules/@bramus/specificity": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",
"integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",
"dev": true,
"license": "MIT",
"dependencies": {
"css-tree": "^3.0.0"
},
"bin": {
"specificity": "bin/cli.js"
}
},
"node_modules/@csstools/color-helpers": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",
"integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT-0",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/@csstools/css-calc": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz",
"integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0"
}
},
"node_modules/@csstools/css-color-parser": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.2.tgz",
"integrity": "sha512-3QKjR/vxyjcSXBLgb6lP0S3MGdvwbmqSsvLPbYdVORqPDc8FX1HAJ0Spk38bxaRXgvENTA47tlhhbb5Z2e8hEg==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"dependencies": {
"@csstools/color-helpers": "^6.1.1",
"@csstools/css-calc": "^3.3.0"
},
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0"
}
},
"node_modules/@csstools/css-parser-algorithms": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",
"integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-tokenizer": "^4.0.0"
}
},
"node_modules/@csstools/css-syntax-patches-for-csstree": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.12.tgz",
"integrity": "sha512-3vLQK+dXxhBMR2Wx99PTCifE+vHtW2ndZWyla8yK813ev6oGhyn8Lja8jCyGAWTJ+LEYZK7EVtJxrDj8ztevJw==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT-0",
"peerDependencies": {
"css-tree": "^3.2.1"
},
"peerDependenciesMeta": {
"css-tree": {
"optional": true
}
}
},
"node_modules/@csstools/css-tokenizer": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",
"integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/@exodus/bytes": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",
"integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
},
"peerDependencies": {
"@noble/hashes": "^1.8.0 || ^2.0.0"
},
"peerDependenciesMeta": {
"@noble/hashes": {
"optional": true
}
}
},
"node_modules/bidi-js": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",
"integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",
"dev": true,
"license": "MIT",
"dependencies": {
"require-from-string": "^2.0.2"
}
},
"node_modules/css-tree": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",
"integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",
"dev": true,
"license": "MIT",
"dependencies": {
"mdn-data": "2.27.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
}
},
"node_modules/data-urls": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
"integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",
"dev": true,
"license": "MIT",
"dependencies": {
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^16.0.0"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/data-urls/node_modules/whatwg-url": {
"version": "16.0.1",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",
"integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.11.0",
"tr46": "^6.0.0",
"webidl-conversions": "^8.0.1"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/decimal.js": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
"dev": true,
"license": "MIT"
},
"node_modules/entities": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
"integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/html-encoding-sniffer": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
"integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.6.0"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/is-potential-custom-element-name": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
"dev": true,
"license": "MIT"
},
"node_modules/jsdom": {
"version": "30.0.1",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.0.1.tgz",
"integrity": "sha512-52v7mUVUfNQVYYqE1lcdaymWL0njO7lTLUog6ZvW2U5KsbiLk/GnZlVJ+qx0xfNJZ6Gn+KSpPNE52vurbxZwrA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@asamuzakjp/css-color": "^6.0.5",
"@asamuzakjp/dom-selector": "^8.3.0",
"@bramus/specificity": "^2.4.2",
"@csstools/css-syntax-patches-for-csstree": "^1.1.7",
"@exodus/bytes": "^1.15.1",
"css-tree": "^3.2.1",
"data-urls": "^7.0.0",
"decimal.js": "^10.6.0",
"html-encoding-sniffer": "^6.0.0",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.2",
"parse5": "^8.0.1",
"saxes": "^6.0.0",
"symbol-tree": "^3.2.4",
"tough-cookie": "^6.0.2",
"undici": "^8.9.0",
"w3c-xmlserializer": "^5.0.0",
"webidl-conversions": "^8.0.1",
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^17.1.0",
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"peerDependencies": {
"canvas": "^3.2.3"
},
"peerDependenciesMeta": {
"canvas": {
"optional": true
}
}
},
"node_modules/lru-cache": {
"version": "11.5.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",
"integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/mdn-data": {
"version": "2.27.1",
"resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
"integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
"dev": true,
"license": "CC0-1.0"
},
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
"integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",
"dev": true,
"license": "MIT",
"dependencies": {
"entities": "^8.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
"dev": true,
"license": "ISC",
"dependencies": {
"xmlchars": "^2.2.0"
},
"engines": {
"node": ">=v12.22.7"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/symbol-tree": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
"integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
"dev": true,
"license": "MIT"
},
"node_modules/tldts": {
"version": "7.4.11",
"resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.11.tgz",
"integrity": "sha512-aBiNayCfTQxuIJBm06M+xR14cYaYlDlSXZbgsnKzKNxDKUVq7KFwTjwBSsb7m9Y5xO8WfPnBc63WaYFMTGlvqw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tldts-core": "^7.4.11"
},
"bin": {
"tldts": "bin/cli.js"
}
},
"node_modules/tldts-core": {
"version": "7.4.11",
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.11.tgz",
"integrity": "sha512-CW3WN2rIIE/Of21mulhgnGOwoDyEFNygyIBOONSdyAuSATgMMUCpLeUlB+E8sAwA5xRV9hYPl+kyZ9citHCaKg==",
"dev": true,
"license": "MIT"
},
"node_modules/tough-cookie": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
"integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"tldts": "^7.0.5"
},
"engines": {
"node": ">=16"
}
},
"node_modules/tr46": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",
"integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",
"dev": true,
"license": "MIT",
"dependencies": {
"punycode": "^2.3.1"
},
"engines": {
"node": ">=20"
}
},
"node_modules/undici": {
"version": "8.10.2",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.10.2.tgz",
"integrity": "sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
},
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
"integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
"dev": true,
"license": "MIT",
"dependencies": {
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/webidl-conversions": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
"integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=20"
}
},
"node_modules/whatwg-mimetype": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
"integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=20"
}
},
"node_modules/whatwg-url": {
"version": "17.1.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.1.0.tgz",
"integrity": "sha512-3GeworPmc2ZfEEHP7lEbUfBX/L75wdEsi0rLNhXcXxnoN5jyq0SL5gCy06SGW2cyTIZdTvWIDQNQoza++vKeaw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.15.1",
"tr46": "^6.0.0",
"webidl-conversions": "^8.0.1"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
},
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
"dev": true,
"license": "MIT"
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"jsdom": "^30.0.1"
}
}
+271
View File
@@ -0,0 +1,271 @@
#!/usr/bin/env node
/**
* ObsiGate — JSDOM integration tests for PaneManager (ROADMAP #75 I2).
*
* Loads the actual pane-manager.js ES module in a JSDOM environment and
* verifies DOM-level behavior: tab creation via open(), activation,
* removal via close(), pane isolation, drag/drop smoke.
*
* Usage: node tests/frontend/pane-manager.test.mjs
*/
import { strict as assert } from "node:assert";
import { JSDOM } from "jsdom";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const REPO_ROOT = path.resolve(__dirname, "..", "..");
// ── JSDOM bootstrap ─────────────────────────────────────────────────────────
const dom = new JSDOM(
`<!DOCTYPE html>
<html>
<body>
<div id="content-wrapper">
<div id="dashboard-home"></div>
<div id="tab-bar" class="tab-bar">
<div id="tab-list" class="tab-list"></div>
</div>
<div id="content-area"></div>
</div>
</body>
</html>`,
{ url: "http://localhost/", pretendToBeVisual: true }
);
const w = dom.window;
globalThis.window = w;
globalThis.document = w.document;
globalThis.HTMLElement = w.HTMLElement;
globalThis.Element = w.Element;
globalThis.Node = w.Node;
globalThis.Event = w.Event;
globalThis.CustomEvent = w.CustomEvent;
globalThis.DragEvent = w.DragEvent || w.Event;
globalThis.MouseEvent = w.MouseEvent || w.Event;
globalThis.localStorage = w.localStorage;
globalThis.sessionStorage = w.sessionStorage;
Object.defineProperty(globalThis, "navigator", {
value: w.navigator,
configurable: true,
writable: true,
});
// ── Helpers ─────────────────────────────────────────────────────────────────
function $$(sel) {
return Array.from(document.querySelectorAll(sel));
}
function resetBody(html) {
document.body.innerHTML = html;
}
// ── Dynamic import (after globals are set) ──────────────────────────────────
const pm = await import(
pathToFileURL(path.join(REPO_ROOT, "frontend", "js", "pane-manager.js")).href
);
const { createPaneTabManager, PaneManager, getActiveTabManager, getActiveContentArea } = pm;
let testCount = 0;
let passCount = 0;
async function test(name, fn) {
testCount++;
try {
await fn();
console.log(` ✓ ${name}`);
passCount++;
} catch (e) {
console.log(` ✗ ${name}`);
console.log(` ${e.message}`);
if (e.stack) console.log(` ${e.stack.split("\n").slice(1, 3).join("\n ")}`);
}
}
// ── Test suite ──────────────────────────────────────────────────────────────
console.log("\n── pane-manager.js JSDOM integration tests (#75 I2) ──\n");
await test("createPaneTabManager returns expected shape", () => {
resetBody(`
<div id="pane-t1"><div class="tab-bar"></div><div id="tl1" class="tab-list"></div><div class="content-area"></div></div>
`);
const tm = createPaneTabManager("t1");
assert.equal(tm.paneId, "t1");
assert.equal(typeof tm.open, "function");
assert.equal(typeof tm.activate, "function");
assert.equal(typeof tm.close, "function");
assert.equal(typeof tm.init, "function");
});
await test("init() binds tab bar / list / content area to provided DOM", () => {
resetBody(`
<div id="pane-t2">
<div class="tab-bar"></div>
<div id="tb2" class="tab-list"></div>
<div id="ca2" class="content-area"></div>
</div>
`);
const tm = createPaneTabManager("t2");
const bar = document.querySelector("#pane-t2 .tab-bar");
const list = document.querySelector("#tb2");
const area = document.querySelector("#ca2");
tm.init(bar, list, area);
assert.equal(tm.getTabBar(), bar);
assert.equal(tm.getTabList(), list);
assert.equal(tm.getContentArea(), area);
});
await test("open() appends a tab-item to the tab-list", async () => {
resetBody(`
<div id="pane-t3">
<div class="tab-bar"></div>
<div id="tl3" class="tab-list"></div>
<div class="content-area"></div>
</div>
`);
const tm = createPaneTabManager("t3");
tm.init(
document.querySelector("#pane-t3 .tab-bar"),
document.querySelector("#tl3"),
document.querySelector("#pane-t3 .content-area")
);
await tm.open("vault1", "/notes/foo.md");
const items = $$("#tl3 .tab-item");
assert.equal(items.length, 1, `expected 1 tab-item, got ${items.length}`);
assert.match(items[0].textContent, /foo/);
});
await test("activate() switches .active class between tabs", async () => {
resetBody(`
<div id="pane-t4">
<div class="tab-bar"></div>
<div id="tl4" class="tab-list"></div>
<div class="content-area"></div>
</div>
`);
const tm = createPaneTabManager("t4");
tm.init(
document.querySelector("#pane-t4 .tab-bar"),
document.querySelector("#tl4"),
document.querySelector("#pane-t4 .content-area")
);
await tm.open("vault1", "/notes/foo.md");
await tm.open("vault1", "/notes/bar.md");
// PaneTabManager.activate(tabId) is called inside open(), so the most
// recently opened tab is active by default.
let [t1, t2] = $$("#tl4 .tab-item");
assert.ok(!t1.classList.contains("active"), `t1 should NOT be active (it was opened first): ${t1.className}`);
assert.ok(t2.classList.contains("active"), `t2 should be active (most recent): ${t2.className}`);
// Now explicitly activate the first tab.
tm.activate("vault1::/notes/foo.md");
tm._renderTabs();
[t1, t2] = $$("#tl4 .tab-item");
assert.ok(t1.classList.contains("active"), "after explicit activate, t1 should be active");
assert.ok(!t2.classList.contains("active"), "t2 should no longer be active");
});
await test("close() removes the tab-item from DOM", async () => {
resetBody(`
<div id="pane-t5">
<div class="tab-bar"></div>
<div id="tl5" class="tab-list"></div>
<div class="content-area"></div>
</div>
`);
const tm = createPaneTabManager("t5");
tm.init(
document.querySelector("#pane-t5 .tab-bar"),
document.querySelector("#tl5"),
document.querySelector("#pane-t5 .content-area")
);
await tm.open("vault1", "/notes/foo.md");
await tm.open("vault1", "/notes/bar.md");
assert.equal($$("#tl5 .tab-item").length, 2);
await tm.close("vault1::/notes/foo.md");
assert.equal($$("#tl5 .tab-item").length, 1);
assert.match($$("#tl5 .tab-item")[0].textContent, /bar/);
});
await test("isolation: tabs in pane-A do not appear in pane-B", async () => {
resetBody(`
<div id="pane-A"><div class="tab-bar"></div><div id="tlA" class="tab-list"></div><div class="content-area"></div></div>
<div id="pane-B"><div class="tab-bar"></div><div id="tlB" class="tab-list"></div><div class="content-area"></div></div>
`);
const tmA = createPaneTabManager("A");
tmA.init(
document.querySelector("#pane-A .tab-bar"),
document.querySelector("#tlA"),
document.querySelector("#pane-A .content-area")
);
const tmB = createPaneTabManager("B");
tmB.init(
document.querySelector("#pane-B .tab-bar"),
document.querySelector("#tlB"),
document.querySelector("#pane-B .content-area")
);
await tmA.open("v1", "/only-in-a.md");
assert.equal($$("#tlA .tab-item").length, 1);
assert.equal($$("#tlB .tab-item").length, 0, "pane-B must be empty");
await tmB.open("v1", "/only-in-b.md");
assert.equal($$("#tlA .tab-item").length, 1, "pane-A unchanged");
assert.equal($$("#tlB .tab-item").length, 1);
});
await test("PaneManager singleton exposes expected methods", () => {
assert.equal(typeof PaneManager, "object");
assert.equal(PaneManager.isSplit(), false);
assert.deepEqual(PaneManager.panes, []);
assert.equal(typeof PaneManager.splitRight, "function");
assert.equal(typeof PaneManager.splitDown, "function");
assert.equal(typeof PaneManager.closePane, "function");
});
await test("DragEvent dispatch on tab-item does not crash", async () => {
resetBody(`
<div id="pane-d">
<div class="tab-bar"></div>
<div id="tld" class="tab-list"></div>
<div class="content-area"></div>
</div>
`);
const tm = createPaneTabManager("d");
tm.init(
document.querySelector("#pane-d .tab-bar"),
document.querySelector("#tld"),
document.querySelector("#pane-d .content-area")
);
await tm.open("v1", "/drag.md");
const tab = document.querySelector("#tld .tab-item");
assert.ok(tab, "tab should exist");
const dt = {
setData: () => {},
getData: () => "",
types: ["text/plain"],
};
const ds = new Event("dragstart", { bubbles: true, cancelable: true });
Object.defineProperty(ds, "dataTransfer", { value: dt });
tab.dispatchEvent(ds); // should not throw
const de = new Event("dragend", { bubbles: true });
Object.defineProperty(de, "dataTransfer", { value: dt });
tab.dispatchEvent(de); // should not throw
});
await test("getActiveTabManager / getActiveContentArea helpers exist", () => {
assert.equal(typeof getActiveTabManager, "function");
assert.equal(typeof getActiveContentArea, "function");
});
// ── Summary ─────────────────────────────────────────────────────────────────
console.log(`\n${passCount}/${testCount} pane-manager tests passed\n`);
process.exit(passCount === testCount ? 0 : 1);
+86 -2
View File
@@ -28,7 +28,7 @@ function testEscapeHtml() {
// ── Test state object structure ────────────────────────────────────────────
// Replicate state.js structure for testing
const expectedStateKeys = [
'APP_VERSION', 'currentVault', 'currentPath', 'allVaults', 'selectedContextVault',
'currentVault', 'currentPath', 'allVaults', 'selectedContextVault',
'searchTimeout', 'searchAbortController', 'advancedSearchOffset', 'advancedSearchTotal',
'advancedSearchSort', 'advancedSearchLastQuery', 'suggestAbortController',
'dropdownActiveIndex', 'dropdownItems', 'currentSearchId', 'selectedTags',
@@ -43,7 +43,7 @@ const expectedStateKeys = [
function testStateKeys() {
const state = {
APP_VERSION: "1.5.0", currentVault: null, currentPath: null, allVaults: [],
currentVault: null, currentPath: null, allVaults: [],
selectedContextVault: "all", searchTimeout: null, searchAbortController: null,
advancedSearchOffset: 0, advancedSearchTotal: 0, advancedSearchSort: "relevance",
advancedSearchLastQuery: "", suggestAbortController: null, dropdownActiveIndex: -1,
@@ -127,6 +127,85 @@ function testModulesHaveImports() {
console.log(' ✓ All modules have imports and exports (except state.js)');
}
// ── Test admin.js exports (ROADMAP #71) ─────────────────────────────────
// Static analysis of frontend/js/admin.js — confirms the ES module shape
// without depending on a DOM environment.
const ADMIN_PATH = join(JS_DIR, 'admin.js');
const ADMIN_REQUIRED_EXPORTS = [
'init',
'connectSSE',
'loadStatsOnce',
'loadAuditLogs',
'loadBackupStats',
'renderStatsWidget',
'renderAuditTable',
'renderBackups',
'getAuthHeaders',
'formatBytes',
'formatUptime',
'severityColor',
];
function _collectExportedNames(content) {
const names = new Set();
// Multi-line export { ... } blocks
for (const m of content.matchAll(/^export\s*\{([\s\S]*?)\}/gm)) {
for (const part of m[1].split(',')) {
const n = part.trim().split(/\s+as\s+/)[0].trim();
if (n) names.add(n);
}
}
// export function/const/let/class/async function NAME
for (const m of content.matchAll(/^export\s+(?:async\s+)?(?:function|const|let|class)\s+(\w+)/gm)) {
names.add(m[1]);
}
return names;
}
function testAdminModuleExists() {
const content = readFileSync(ADMIN_PATH, 'utf-8');
assert.ok(content.length > 0, 'admin.js must be a non-empty file');
// Sanity: it must import from auth.js, state.js, utils.js, i18n.js
assert.ok(/from\s+['"]\.\/auth\.js['"]/.test(content), 'admin.js must import from ./auth.js');
assert.ok(/from\s+['"]\.\/state\.js['"]/.test(content), 'admin.js must import from ./state.js');
assert.ok(/from\s+['"]\.\/utils\.js['"]/.test(content), 'admin.js must import from ./utils.js');
assert.ok(/from\s+['"]\.\/i18n\.js['"]/.test(content), 'admin.js must import from ./i18n.js');
console.log(' ✓ admin.js exists and imports the expected modules');
}
function testAdminModuleExports() {
const content = readFileSync(ADMIN_PATH, 'utf-8');
const exported = _collectExportedNames(content);
const missing = ADMIN_REQUIRED_EXPORTS.filter((name) => !exported.has(name));
assert.strictEqual(missing.length, 0, `admin.js missing exports: ${missing.join(', ')}`);
console.log(` ✓ admin.js exports all ${ADMIN_REQUIRED_EXPORTS.length} expected names`);
}
function testAdminModuleSyntax() {
// node --check verifies parseability without executing side effects.
execSync(`node --check "${ADMIN_PATH}"`, { stdio: 'pipe' });
console.log(' ✓ admin.js parses without syntax errors');
}
// ── Test ai-fab.js (FAB — Floating Action Button) ─────────────────────────
const AIFAB_PATH = join(JS_DIR, 'ai-fab.js');
function testAIFabModuleExists() {
const content = readFileSync(AIFAB_PATH, 'utf-8');
assert.ok(content.length > 0, 'ai-fab.js must be a non-empty file');
assert.ok(/from\s+['"]\.\/bookslm\.js['"]/.test(content), 'ai-fab.js must import from ./bookslm.js');
assert.ok(/from\s+['"]\.\/state\.js['"]/.test(content), 'ai-fab.js must import from ./state.js');
assert.ok(/from\s+['"]\.\/i18n\.js['"]/.test(content), 'ai-fab.js must import from ./i18n.js');
console.log(' ✓ ai-fab.js exists and imports the expected modules');
}
function testAIFabModuleExports() {
const content = readFileSync(AIFAB_PATH, 'utf-8');
const exported = _collectExportedNames(content);
assert.ok(exported.has('initAIFab'), 'ai-fab.js must export initAIFab');
console.log(' ✓ ai-fab.js exports initAIFab');
}
// ── Run all tests ──────────────────────────────────────────────────────────
async function main() {
let passed = 0, failed = 0;
@@ -136,6 +215,11 @@ async function main() {
['state keys', testStateKeys],
['module syntax', testAllModulesParse],
['module structure', testModulesHaveImports],
['admin module exists', testAdminModuleExists],
['admin module exports', testAdminModuleExports],
['admin module syntax', testAdminModuleSyntax],
['ai-fab module exists', testAIFabModuleExists],
['ai-fab module exports', testAIFabModuleExports],
];
for (const [name, fn] of tests) {
+9 -2
View File
@@ -38,8 +38,15 @@ function collectExports(filePath, modName) {
const m = exportBlockText.match(/^export\s*\{([^}]+)\}/);
if (m) {
for (const name of m[1].split(',')) {
const n = name.trim().replace(/\s+as\s+\w+.*/, '').trim();
if (n && n !== '') exports.add(n);
// Handle `original as exported` — export both names
const asMatch = name.trim().match(/^(\w+)\s+as\s+(\w+)$/);
if (asMatch) {
exports.add(asMatch[2]); // exported name
exports.add(asMatch[1]); // original name too (in case it's re-imported)
} else {
const n = name.trim().trim();
if (n && n !== '') exports.add(n);
}
}
}
exportBlockText = '';
+338
View File
@@ -0,0 +1,338 @@
# tests/test_admin.py — Integration tests for the Admin Dashboard endpoints
# (ROADMAP #71)
#
# These tests cover:
# - GET /api/admin/stats — CPU/RAM/Disk/Uptime snapshot
# - GET /api/admin/audit — recent audit log entries with filters
# - GET /api/admin/backup-stats — backup counts/sizes per vault
# - GET /api/admin/stream — Server-Sent Events stream
# All endpoints must require admin auth.
import os
import shutil
import tempfile
from pathlib import Path
import pytest
@pytest.fixture
def admin_client(tmp_path):
"""TestClient with auth enabled, isolated temp data, admin user provisioned."""
data_dir = tmp_path / "data"
data_dir.mkdir()
import json
from backend.auth.password import hash_password
pw_hash = hash_password("chab30")
users = {
"version": 1,
"users": {
"admin": {
"id": "admin-1",
"username": "admin",
"display_name": "admin",
"password_hash": pw_hash,
"role": "admin",
"vaults": ["*"],
"active": True,
"created_at": "2026-01-01T00:00:00",
},
"normaluser": {
"id": "user-1",
"username": "normaluser",
"display_name": "normal",
"password_hash": hash_password("normal123"),
"role": "user",
"vaults": ["TestVault"],
"active": True,
"created_at": "2026-01-01T00:00:00",
},
},
}
(data_dir / "users.json").write_text(json.dumps(users), encoding="utf-8")
src_secret = Path("data/secret.key")
if src_secret.exists():
shutil.copy2(str(src_secret), str(data_dir / "secret.key"))
orig_cwd = os.getcwd()
test_vault_path = os.path.abspath("test-vault")
os.chdir(str(tmp_path))
os.environ["VAULT_1_NAME"] = "TestVault"
os.environ["VAULT_1_PATH"] = test_vault_path
os.environ["OBSIGATE_AUTH_ENABLED"] = "true"
os.environ["OBSIGATE_ADMIN_USER"] = "admin"
os.environ["OBSIGATE_ADMIN_PASSWORD"] = "chab30"
os.environ["OBSIGATE_WATCHER_ENABLED"] = "false"
import backend.main
backend.main._load_config = lambda: {"watcher_enabled": False}
from backend.main import app
from backend.indexer import build_index, index
import asyncio
for key in list(index.keys()):
del index[key]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(build_index())
from backend.search import init_inverted_index
init_inverted_index()
from fastapi.testclient import TestClient
client = TestClient(app)
yield client
if hasattr(client, "close"):
client.close()
loop.run_until_complete(asyncio.sleep(0))
os.chdir(orig_cwd)
shutil.rmtree(str(tmp_path), ignore_errors=True)
for k in [
"VAULT_1_NAME", "VAULT_1_PATH", "OBSIGATE_AUTH_ENABLED",
"OBSIGATE_ADMIN_USER", "OBSIGATE_ADMIN_PASSWORD", "OBSIGATE_WATCHER_ENABLED",
]:
os.environ.pop(k, None)
def _login(client, username="admin", password="chab30"):
resp = client.post("/api/auth/login", json={"username": username, "password": password})
assert resp.status_code == 200, resp.text
return resp.json()["access_token"]
def _bearer(token):
return {"Authorization": f"Bearer {token}"}
# ═══════════════════════════════════════════════════════════════════
# /api/admin/stats
# ═══════════════════════════════════════════════════════════════════
class TestAdminStats:
EXPECTED_KEYS = {
"cpu_pct", "mem_used_mb", "mem_total_mb",
"disk_used_gb", "disk_total_gb",
"uptime_seconds", "active_sessions",
}
def test_stats_ok_as_admin(self, admin_client):
token = _login(admin_client)
resp = admin_client.get("/api/admin/stats", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
missing = self.EXPECTED_KEYS - set(data.keys())
assert not missing, f"Missing keys: {missing}"
# Numeric sanity (allow 0 for any metric — depending on platform)
for key in ("cpu_pct", "mem_used_mb", "mem_total_mb",
"disk_used_gb", "disk_total_gb", "uptime_seconds",
"active_sessions"):
assert isinstance(data[key], (int, float)), f"{key} not numeric"
assert data[key] >= 0, f"{key} is negative"
def test_stats_requires_auth(self, admin_client):
resp = admin_client.get("/api/admin/stats")
assert resp.status_code in (401, 403)
def test_stats_requires_admin_role(self, admin_client):
token = _login(admin_client, username="normaluser", password="normal123")
resp = admin_client.get("/api/admin/stats", headers=_bearer(token))
assert resp.status_code == 403
# ═══════════════════════════════════════════════════════════════════
# /api/admin/audit
# ═══════════════════════════════════════════════════════════════════
class TestAdminAudit:
def _seed_audit(self, tmp_path_factory=None):
"""Append a few entries to the audit log so filtering has data."""
from backend.audit import _write_entry
from datetime import datetime, timezone
entries = [
{"timestamp": datetime.now(timezone.utc).isoformat(),
"action": "file_save", "username": "alice", "vault": "TestVault",
"size": 100, "ip": "127.0.0.1"},
{"timestamp": datetime.now(timezone.utc).isoformat(),
"action": "file_delete", "username": "bob", "vault": "TestVault",
"ip": "127.0.0.1"},
{"timestamp": datetime.now(timezone.utc).isoformat(),
"action": "file_save", "username": "bob", "vault": "TestVault",
"size": 50, "ip": "127.0.0.1"},
]
for e in entries:
_write_entry(e)
def test_audit_ok(self, admin_client):
self._seed_audit()
token = _login(admin_client)
resp = admin_client.get("/api/admin/audit", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
assert "entries" in data
assert "total" in data
# We just seeded at least 3 entries
assert data["total"] >= 3
def test_audit_filter_by_user(self, admin_client):
self._seed_audit()
token = _login(admin_client)
resp = admin_client.get("/api/admin/audit?user=bob", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
assert all("bob" in str(e.get("username", "")).lower() for e in data["entries"])
def test_audit_filter_by_action(self, admin_client):
self._seed_audit()
token = _login(admin_client)
resp = admin_client.get("/api/admin/audit?action=file_delete", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
assert all(e.get("action") == "file_delete" for e in data["entries"])
def test_audit_limit_param(self, admin_client):
self._seed_audit()
token = _login(admin_client)
resp = admin_client.get("/api/admin/audit?limit=2", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
assert len(data["entries"]) <= 2
def test_audit_requires_admin(self, admin_client):
resp = admin_client.get("/api/admin/audit")
assert resp.status_code in (401, 403)
# ═══════════════════════════════════════════════════════════════════
# /api/admin/backup-stats
# ═══════════════════════════════════════════════════════════════════
class TestAdminBackupStats:
def _create_backup_files(self, tmp_path_factory=None):
"""Create a couple of fake .bak files in the default backup dir."""
from backend.indexer import vault_config
import time as _time
for vault_name, cfg in list(vault_config.items()):
vault_root = Path(cfg["path"])
backup_root = vault_root / ".obsigate-backup" / vault_name / "subdir"
backup_root.mkdir(parents=True, exist_ok=True)
ts1 = int(_time.time()) - 86400
ts2 = int(_time.time())
(backup_root / f"note.md.{ts1}.bak").write_text("old version")
(backup_root / f"note.md.{ts2}.bak").write_text("newer version with more content")
def test_backup_stats_ok(self, admin_client):
self._create_backup_files()
token = _login(admin_client)
resp = admin_client.get("/api/admin/backup-stats", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
for k in ("total_backups", "total_size_mb", "oldest_age_days",
"newest_age_days", "by_vault"):
assert k in data, f"missing key {k}"
assert data["total_backups"] >= 2
assert data["total_size_mb"] >= 0
# We created one set per vault — at least one vault entry
assert isinstance(data["by_vault"], dict)
def test_backup_stats_empty(self, admin_client):
"""Even with no backups, endpoint returns 200 with zero counts."""
token = _login(admin_client)
resp = admin_client.get("/api/admin/backup-stats", headers=_bearer(token))
assert resp.status_code == 200
data = resp.json()
assert data["total_backups"] >= 0
# If no backups exist, both age fields are 0
if data["total_backups"] == 0:
assert data["newest_age_days"] == 0.0
assert data["oldest_age_days"] == 0.0
def test_backup_stats_requires_admin(self, admin_client):
resp = admin_client.get("/api/admin/backup-stats")
assert resp.status_code in (401, 403)
# ═══════════════════════════════════════════════════════════════════
# /api/admin/stream
# ═══════════════════════════════════════════════════════════════════
class TestAdminStream:
def test_stream_content_type(self, admin_client):
"""Verify SSE endpoint returns text/event-stream with valid first frame.
The /api/admin/stream endpoint is an infinite generator (yields every 5s).
We can't easily consume a streaming response from a sync TestClient
(the context manager blocks on entry for infinite responses). Instead,
we verify the endpoint contract from two angles:
1. Without auth → 401/403 (proves the endpoint is mounted and gated)
2. Direct invocation of the underlying generator yields a valid SSE
frame on the first iteration (proves the format contract).
"""
# 1) Endpoint is gated behind admin auth.
resp = admin_client.get("/api/admin/stream")
assert resp.status_code in (401, 403), (
f"unauthenticated should be rejected, got {resp.status_code}"
)
# 2) Direct generator check — read the first frame, then close.
import asyncio
from backend.admin import _stats_event_generator
async def _first_frame():
gen = _stats_event_generator()
return await gen.__anext__()
first = asyncio.run(_first_frame())
assert isinstance(first, str), f"expected str, got {type(first).__name__}"
assert first.startswith("event: stats"), f"unexpected frame: {first[:100]!r}"
assert "data: " in first
# The data line should be parseable JSON.
import json
data_line = [ln for ln in first.splitlines() if ln.startswith("data: ")][0]
payload = json.loads(data_line[len("data: "):])
assert isinstance(payload, dict)
assert "cpu_pct" in payload or "error" in payload
def test_stream_requires_admin(self, admin_client):
resp = admin_client.get("/api/admin/stream")
assert resp.status_code in (401, 403)
# ═══════════════════════════════════════════════════════════════
# Admin dashboard PAGE (/admin.html)
# ═══════════════════════════════════════════════════════════════
class TestAdminPage:
"""Regression for ROADMAP #71 — Admin menu bounced back to the main page.
Root cause: /admin.html had no explicit route, so the SPA catch-all
``/{full_path:path}`` served index.html. Guard the fix.
"""
def test_page_served_as_admin(self, admin_client):
token = _login(admin_client)
resp = admin_client.get("/admin.html", headers=_bearer(token))
assert resp.status_code == 200
body = resp.text
# Real admin page markers (NOT the main SPA index.html)
assert "admin-main" in body or "ObsiGate — Admin" in body or "admin.js" in body
# The regression: index.html markers must be absent
assert "boot-splash" not in body
# Asset paths must point to the actual static mount (/static), not /frontend
assert "/static/js/admin.js" in body
assert "/frontend/js/admin.js" not in body
def test_page_requires_auth(self, admin_client):
resp = admin_client.get("/admin.html")
assert resp.status_code in (401, 403)
def test_page_requires_admin_role(self, admin_client):
token = _login(admin_client, username="normaluser", password="normal123")
resp = admin_client.get("/admin.html", headers=_bearer(token))
assert resp.status_code == 403
+310
View File
@@ -0,0 +1,310 @@
"""Tests for the AI models listing endpoint + curated fallback lists (ROADMAP #74/#71).
Covers:
- GET /api/config/ai-models always returns a non-empty list for known providers,
even when the live API call fails (network, auth, etc.).
- The fallback list is curated with at least one model per provider.
- Gemini parsing strips the "models/" prefix.
- The default model is prepended if not already in the list.
"""
from __future__ import annotations
import pytest
from fastapi.testclient import TestClient
from backend.main import _FALLBACK_MODELS, app
@pytest.fixture
def admin_client(tmp_path):
"""Minimal admin client for the /api/config/ai-models endpoint."""
from backend.auth.password import hash_password
import json
import os
from pathlib import Path
data_dir = tmp_path / "data"
data_dir.mkdir()
users = {
"version": 1,
"users": {
"admin": {
"id": "admin-1",
"username": "admin",
"display_name": "admin",
"password_hash": hash_password("chab30"),
"role": "admin",
"vaults": ["*"],
"active": True,
"created_at": "2026-01-01T00:00:00",
},
},
}
(data_dir / "users.json").write_text(json.dumps(users), encoding="utf-8")
src_secret = Path("data/secret.key")
if src_secret.exists():
import shutil
shutil.copy2(str(src_secret), str(data_dir / "secret.key"))
orig_cwd = os.getcwd()
os.chdir(str(tmp_path))
os.environ["VAULT_1_NAME"] = "TestVault"
os.environ["VAULT_1_PATH"] = str(Path("test-vault").resolve())
os.environ["OBSIGATE_AUTH_ENABLED"] = "true"
os.environ["OBSIGATE_ADMIN_USER"] = "admin"
os.environ["OBSIGATE_ADMIN_PASSWORD"] = "chab30"
os.environ["OBSIGATE_WATCHER_ENABLED"] = "false"
import backend.main
backend.main._load_config = lambda: {"watcher_enabled": False}
from backend.indexer import build_index, index
import asyncio
for key in list(index.keys()):
del index[key]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(build_index())
client = TestClient(app)
yield client
client.close()
os.chdir(orig_cwd)
for k in ["VAULT_1_NAME", "VAULT_1_PATH", "OBSIGATE_AUTH_ENABLED",
"OBSIGATE_ADMIN_USER", "OBSIGATE_ADMIN_PASSWORD", "OBSIGATE_WATCHER_ENABLED"]:
os.environ.pop(k, None)
def _login_admin(client):
resp = client.post("/api/auth/login",
json={"username": "admin", "password": "chab30"})
assert resp.status_code == 200, resp.text
return resp.json()["access_token"]
# ── Unit tests for the fallback table itself ─────────────────────────────
class TestFallbackTable:
def test_every_known_provider_has_fallback_list(self):
"""Every provider in the dropdown must have a non-empty fallback list."""
expected_providers = {
"deepseek", "openrouter", "gemini", "nvidia",
"qwencloud", "xiaomi", "mistral",
}
assert set(_FALLBACK_MODELS.keys()) >= expected_providers
for p in expected_providers:
assert _FALLBACK_MODELS[p], f"fallback list for {p!r} is empty"
assert all(isinstance(m, str) and m.strip() for m in _FALLBACK_MODELS[p]), \
f"fallback list for {p!r} contains invalid entries: {_FALLBACK_MODELS[p]}"
def test_fallback_lists_are_short_and_focused(self):
"""Fallbacks should be short (≤10 models) and well-known."""
for p, models in _FALLBACK_MODELS.items():
assert len(models) <= 10, f"too many fallbacks for {p}: {len(models)}"
def test_xiaomi_fallback_contains_mimo_models(self):
"""Xiaomi's MiMo models must be in the fallback list."""
mimos = [m for m in _FALLBACK_MODELS["xiaomi"] if "mimo" in m.lower()]
assert mimos, "no MiMo model in xiaomi fallback"
# ── Endpoint integration tests ────────────────────────────────────────────
class TestListModelsEndpoint:
"""Verify /api/config/ai-models?provider=X always returns a usable list."""
def test_unknown_provider_returns_empty(self, admin_client):
token = _login_admin(admin_client)
resp = admin_client.get(
"/api/config/ai-models",
params={"provider": "nonexistent-provider"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
data = resp.json()
assert data["models"] == []
assert "error" in data or "source" in data
def test_provider_without_key_returns_fallback(self, admin_client, monkeypatch):
"""When the provider has no API key configured, return the curated fallback list."""
# Force every provider key to be empty so the endpoint hits its
# 'no key configured' branch.
from backend import ai
monkeypatch.setattr(ai, "get_ai_key", lambda name: None)
token = _login_admin(admin_client)
for provider in ("xiaomi", "nvidia", "deepseek", "mistral"):
resp = admin_client.get(
"/api/config/ai-models",
params={"provider": provider},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200, f"{provider}: {resp.status_code}"
data = resp.json()
assert data["models"], f"{provider}: fallback list is empty"
assert data.get("source") == "fallback", (
f"{provider}: expected source=fallback, got {data.get('source')!r}"
)
def test_provider_with_unreachable_api_returns_fallback(
self, admin_client, monkeypatch,
):
"""When the live API call fails (network/DNS), the fallback list is used.
This test patches both the key lookup AND the urlopen call so we
deterministically hit the network-failure branch.
"""
from backend import ai as aimod
# Fake key so we don't take the 'no key' short-circuit.
monkeypatch.setattr(aimod, "get_ai_key", lambda name: "fake-key-for-test")
# Patch urllib.request.urlopen to always raise — simulating network down.
# NOTE: main.py imports urllib.request at module load, so we patch the
# symbol it actually uses (urllib.request.urlopen).
import urllib.request
def _boom(*args, **kwargs):
raise OSError("simulated network down")
monkeypatch.setattr(urllib.request, "urlopen", _boom)
token = _login_admin(admin_client)
# Pick a non-Gemini provider so we hit the network code path.
resp = admin_client.get(
"/api/config/ai-models",
params={"provider": "nvidia"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
data = resp.json()
# The response should be a usable list — either via fallback after
# network failure, or the 'no key' shortcut. Both are acceptable as
# long as models is non-empty.
assert data["models"], "model list should be non-empty"
assert data.get("source") in ("fallback",), (
f"unexpected source: {data.get('source')!r}"
)
def test_response_includes_source_field(self, admin_client, monkeypatch):
"""All successful responses must include a 'source' field for UI hinting."""
from backend import ai as aimod
monkeypatch.setattr(aimod, "get_ai_key", lambda name: "fake-key")
token = _login_admin(admin_client)
resp = admin_client.get(
"/api/config/ai-models",
params={"provider": "gemini"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
data = resp.json()
assert "source" in data
assert data["source"] in ("live", "fallback")
def test_xiaomi_uses_api_key_header_not_bearer(self, admin_client, monkeypatch):
"""Regression test: Xiaomi MiMo must use `api-key` header, NOT Authorization.
Without this, the live call always fails with 401 even with a valid key.
"""
# Fake key — patch BOTH the source module AND the imported reference
# in backend.main (which does `from backend.ai import ... get_ai_key`).
import backend.ai as aimod
import backend.main as bmain
monkeypatch.setattr(aimod, "get_ai_key", lambda name: "fake-xiaomi-key")
if hasattr(bmain, "get_ai_key"):
monkeypatch.setattr(bmain, "get_ai_key", lambda name: "fake-xiaomi-key")
captured = {}
def fake_Request(url, *args, **kwargs):
captured["url"] = url
captured["headers"] = dict(kwargs.get("headers") or {})
class FakeResp:
def __enter__(self): return self
def __exit__(self, *a): pass
def read(self):
return b'{"object":"list","data":[{"id":"mimo-v2.5-pro","object":"model","owned_by":"xiaomi"}]}'
captured["response"] = FakeResp()
return captured["response"]
def fake_urlopen(req, timeout=None):
return req
# Patch urllib.request at the point where backend.main imported it.
import urllib.request as global_urllib_mod
monkeypatch.setattr(global_urllib_mod, "Request", fake_Request, raising=True)
monkeypatch.setattr(global_urllib_mod, "urlopen", fake_urlopen, raising=True)
token = _login_admin(admin_client)
resp = admin_client.get(
"/api/config/ai-models",
params={"provider": "xiaomi"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200, f"resp: {resp.text[:300]}"
# Verify the URL + headers used.
assert captured.get("url"), f"Request was not called (captured={captured!r})"
assert captured["url"].startswith("https://api.xiaomimimo.com/v1/models"), (
f"unexpected URL: {captured.get('url')!r}"
)
hdrs = {k.lower(): v for k, v in captured.get("headers", {}).items()}
assert "api-key" in hdrs, f"missing api-key header in {hdrs!r}"
assert hdrs["api-key"] == "fake-xiaomi-key"
assert "authorization" not in hdrs, f"Authorization leaked: {hdrs!r}"
def test_xiaomi_test_endpoint_uses_real_url(self, admin_client, monkeypatch):
"""The /api/config/ai-keys/test endpoint must also use api.xiaomimimo.com.
Regression: it previously used api.xiaomi.com which doesn't exist
(DNS error Name or service not known).
"""
# Patch BOTH the source module AND the imported reference in backend.main
import backend.ai as aimod
import backend.main as bmain
monkeypatch.setattr(aimod, "get_ai_key", lambda name: "fake-key")
if hasattr(bmain, "get_ai_key"):
monkeypatch.setattr(bmain, "get_ai_key", lambda name: "fake-key")
import urllib.request as global_urllib_mod
captured_urls = []
captured_headers = []
def fake_urlopen(req, timeout=None):
captured_urls.append(req.full_url)
captured_headers.append(dict(req.headers))
raise OSError("simulated network error")
monkeypatch.setattr(global_urllib_mod, "urlopen", fake_urlopen, raising=True)
token = _login_admin(admin_client)
admin_client.post(
"/api/config/ai-keys/test",
headers={"Authorization": f"Bearer {token}"},
)
# Find the xiaomi URL among the captured calls.
xiaomi_idx = next(
(i for i, u in enumerate(captured_urls) if "xiaomi" in u.lower()),
None,
)
assert xiaomi_idx is not None, (
f"xiaomi URL not found in captured URLs: {captured_urls!r}"
)
xiaomi_url = captured_urls[xiaomi_idx]
# Must use the real MiMo endpoint, NOT the dead api.xiaomi.com.
assert "api.xiaomimimo.com" in xiaomi_url, (
f"xiaomi test URL is wrong: {xiaomi_url!r}"
)
# Must use api-key header, not Authorization. urllib.request
# normalizes header names to title-case ("Api-key"), but HTTP
# headers are case-insensitive on the wire — both forms are valid.
xiaomi_hdrs = {k.lower(): v for k, v in captured_headers[xiaomi_idx].items()}
assert "api-key" in xiaomi_hdrs, (
f"xiaomi api-key header missing: {xiaomi_hdrs!r}"
)
assert xiaomi_hdrs["api-key"] == "fake-key"
# Bearer prefix must NOT be in the api-key value
assert "Bearer" not in xiaomi_hdrs["api-key"]
+46
View File
@@ -221,6 +221,52 @@ class TestAdmin:
data = resp.json()
assert data["username"] == "testuser"
def test_patch_user(self, auth_client):
"""PATCH /api/auth/admin/users/{username} updates fields."""
token = self._login_admin(auth_client)
# Create a user first, then patch it.
auth_client.post("/api/auth/admin/users", headers={
"Authorization": f"Bearer {token}",
}, json={
"username": "patchuser",
"password": "origpass",
"role": "user",
"vaults": ["TestVault"],
})
resp = auth_client.patch("/api/auth/admin/users/patchuser", headers={
"Authorization": f"Bearer {token}",
}, json={
"display_name": "Patched User",
"active": False,
})
assert resp.status_code == 200
data = resp.json()
assert data["display_name"] == "Patched User"
assert data["active"] is False
def test_delete_user(self, auth_client):
"""DELETE /api/auth/admin/users/{username} removes the user."""
token = self._login_admin(auth_client)
# Create a throwaway user, then delete it.
auth_client.post("/api/auth/admin/users", headers={
"Authorization": f"Bearer {token}",
}, json={
"username": "deleteuser",
"password": "delpass",
"role": "user",
"vaults": ["TestVault"],
})
resp = auth_client.delete("/api/auth/admin/users/deleteuser", headers={
"Authorization": f"Bearer {token}",
})
assert resp.status_code == 200
# Confirm it's gone via list.
list_resp = auth_client.get("/api/auth/admin/users", headers={
"Authorization": f"Bearer {token}",
})
usernames = [u["username"] for u in list_resp.json()]
assert "deleteuser" not in usernames
def test_logout(self, auth_client):
token = self._login_admin(auth_client)
resp = auth_client.post("/api/auth/logout", headers={
+576
View File
@@ -0,0 +1,576 @@
"""Tests for BooksLM — directory context collection, caching, and API routes."""
import asyncio
import json
import os
import shutil
import tempfile
from pathlib import Path
import pytest
# ── Unit tests: collect_directory_context ──────────────────────────────
class TestCollectDirectoryContext:
"""Tests for collect_directory_context()."""
def test_basic_collection(self, tmp_path):
"""Collect .md files from a simple directory."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
vault.mkdir()
(vault / "note1.md").write_text("# Note 1\nHello world", encoding="utf-8")
(vault / "note2.md").write_text("# Note 2\nGoodbye world", encoding="utf-8")
(vault / "notemd.txt").write_text("Not markdown", encoding="utf-8")
result = collect_directory_context(vault, "")
assert result["file_count"] == 2
assert result["total_chars"] > 0
paths = [f["path"] for f in result["files"]]
assert "note1.md" in paths
assert "note2.md" in paths
assert "notemd.txt" not in paths
def test_subdirectory_collection(self, tmp_path):
"""Collect files recursively from subdirectories."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
subdir = vault / "projects" / "code"
subdir.mkdir(parents=True)
(subdir / "readme.md").write_text("# Code project", encoding="utf-8")
(vault / "root.md").write_text("# Root", encoding="utf-8")
result = collect_directory_context(vault, "projects")
assert result["file_count"] == 1
assert result["files"][0]["path"] == "projects/code/readme.md"
def test_hidden_files_skipped(self, tmp_path):
"""Hidden files and special directories are skipped."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
vault.mkdir()
(vault / ".hidden.md").write_text("Hidden", encoding="utf-8")
(vault / ".obsidian").mkdir()
(vault / ".obsidian" / "config.md").write_text("Config", encoding="utf-8")
(vault / "visible.md").write_text("Visible", encoding="utf-8")
result = collect_directory_context(vault, "")
assert result["file_count"] == 1
assert result["files"][0]["path"] == "visible.md"
def test_attachments_skipped(self, tmp_path):
"""_attachments/ directory is skipped."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
attach = vault / "_attachments"
attach.mkdir(parents=True)
(attach / "image.md").write_text("Image doc", encoding="utf-8")
(vault / "real.md").write_text("Real content", encoding="utf-8")
result = collect_directory_context(vault, "")
assert result["file_count"] == 1
assert result["files"][0]["path"] == "real.md"
def test_max_files_limit(self, tmp_path):
"""Respects BOOKSLM_MAX_FILES limit."""
from backend.bookslm import collect_directory_context
import backend.bookslm as bookslm_mod
vault = tmp_path / "vault"
vault.mkdir()
old_max = bookslm_mod.BOOKSLM_MAX_FILES
bookslm_mod.BOOKSLM_MAX_FILES = 3
try:
for i in range(10):
(vault / f"note{i}.md").write_text(f"Content {i}", encoding="utf-8")
result = collect_directory_context(vault, "")
assert result["file_count"] == 3
finally:
bookslm_mod.BOOKSLM_MAX_FILES = old_max
def test_max_file_chars_truncation(self, tmp_path):
"""Files exceeding max chars are truncated with marker."""
from backend.bookslm import collect_directory_context
import backend.bookslm as bookslm_mod
vault = tmp_path / "vault"
vault.mkdir()
old_max = bookslm_mod.BOOKSLM_MAX_FILE_CHARS
bookslm_mod.BOOKSLM_MAX_FILE_CHARS = 50
try:
long_content = "x" * 200
(vault / "long.md").write_text(long_content, encoding="utf-8")
result = collect_directory_context(vault, "")
assert result["file_count"] == 1
assert "[... tronqué]" in result["files"][0]["content"]
assert len(result["files"][0]["content"]) <= 50 + 50 # truncated + marker
finally:
bookslm_mod.BOOKSLM_MAX_FILE_CHARS = old_max
def test_max_total_chars_limit(self, tmp_path):
"""Stops collecting when total chars limit is reached."""
from backend.bookslm import collect_directory_context
import backend.bookslm as bookslm_mod
vault = tmp_path / "vault"
vault.mkdir()
old_total = bookslm_mod.BOOKSLM_MAX_TOTAL_CHARS
old_file = bookslm_mod.BOOKSLM_MAX_FILE_CHARS
bookslm_mod.BOOKSLM_MAX_TOTAL_CHARS = 100
bookslm_mod.BOOKSLM_MAX_FILE_CHARS = 10000
try:
for i in range(10):
(vault / f"f{i}.md").write_text("a" * 50, encoding="utf-8")
result = collect_directory_context(vault, "")
# Should not collect all 10 files (10 * 50 = 500 > 100)
assert result["total_chars"] <= 100 + 50 # some margin for truncation marker
finally:
bookslm_mod.BOOKSLM_MAX_TOTAL_CHARS = old_total
bookslm_mod.BOOKSLM_MAX_FILE_CHARS = old_file
def test_readme_index_priority(self, tmp_path):
"""README and index files come first in results."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
vault.mkdir()
(vault / "aaa.md").write_text("# AAA", encoding="utf-8")
(vault / "README.md").write_text("# README", encoding="utf-8")
(vault / "index.md").write_text("# Index", encoding="utf-8")
(vault / "zzz.md").write_text("# ZZZ", encoding="utf-8")
result = collect_directory_context(vault, "")
paths = [f["path"] for f in result["files"]]
# README and index should be before other files
readme_idx = paths.index("README.md")
index_idx = paths.index("index.md")
aaa_idx = paths.index("aaa.md")
assert readme_idx < aaa_idx
assert index_idx < aaa_idx
def test_empty_directory(self, tmp_path):
"""Empty directory returns empty result."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
vault.mkdir()
result = collect_directory_context(vault, "")
assert result["file_count"] == 0
assert result["total_chars"] == 0
assert result["files"] == []
def test_nonexistent_directory(self, tmp_path):
"""Nonexistent directory returns empty result."""
from backend.bookslm import collect_directory_context
result = collect_directory_context(tmp_path, "nonexistent")
assert result["file_count"] == 0
def test_title_generation(self, tmp_path):
"""File titles are derived from stem with proper casing."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
vault.mkdir()
(vault / "my-cool-note.md").write_text("Content", encoding="utf-8")
result = collect_directory_context(vault, "")
assert result["files"][0]["title"] == "My Cool Note"
def test_directory_tree(self, tmp_path):
"""Directory tree is included in result."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
(vault / "sub").mkdir(parents=True)
(vault / "sub" / "file.md").write_text("Content", encoding="utf-8")
(vault / "root.md").write_text("Root", encoding="utf-8")
result = collect_directory_context(vault, "")
tree = result["directory_tree"]
assert "root.md" in tree
assert "sub/" in tree
assert "file.md" in tree
# ── Unit tests: build_system_prompt ────────────────────────────────────
class TestBuildSystemPrompt:
"""Tests for build_system_prompt()."""
def test_basic_prompt(self):
"""Prompt contains expected sections."""
from backend.bookslm import build_system_prompt
context = {
"files": [
{"path": "note.md", "title": "My Note", "content": "# Hello", "type": "markdown"},
],
"total_chars": 7,
"file_count": 1,
"directory_tree": "note.md",
}
prompt = build_system_prompt(context)
assert "assistant de recherche" in prompt
assert "note.md" in prompt
assert "My Note" in prompt
assert "# Hello" in prompt
assert "Cite tes sources" in prompt
def test_empty_context(self):
"""Empty context still produces valid prompt."""
from backend.bookslm import build_system_prompt
context = {"files": [], "total_chars": 0, "file_count": 0, "directory_tree": ""}
prompt = build_system_prompt(context)
assert "0 fichier" in prompt
def test_token_warning(self):
"""Large context triggers token warning."""
from backend.bookslm import build_system_prompt
context = {
"files": [
{"path": "big.md", "title": "Big", "content": "x" * 500000, "type": "markdown"},
],
"total_chars": 500000,
"file_count": 1,
"directory_tree": "big.md",
}
prompt = build_system_prompt(context)
assert "⚠️" in prompt or "volumineux" in prompt
# ── Unit tests: caching ────────────────────────────────────────────────
class TestCaching:
"""Tests for cache behavior."""
def test_cache_hit(self, tmp_path):
"""Second call with same data returns cached result."""
from backend.bookslm import collect_directory_context, _cache
_cache.clear()
vault = tmp_path / "vault"
vault.mkdir()
(vault / "note.md").write_text("Content", encoding="utf-8")
result1 = collect_directory_context(vault, "")
result2 = collect_directory_context(vault, "")
assert result1["file_count"] == result2["file_count"]
assert result1["total_chars"] == result2["total_chars"]
def test_cache_invalidation_on_change(self, tmp_path):
"""Cache is invalidated when file content changes."""
from backend.bookslm import collect_directory_context, _cache
_cache.clear()
vault = tmp_path / "vault"
vault.mkdir()
(vault / "note.md").write_text("Original", encoding="utf-8")
result1 = collect_directory_context(vault, "")
assert result1["file_count"] == 1
# Modify file (change mtime)
import time
time.sleep(0.1)
(vault / "note.md").write_text("Modified content", encoding="utf-8")
result2 = collect_directory_context(vault, "")
assert result2["files"][0]["content"] == "Modified content"
def test_invalidate_cache(self, tmp_path):
"""invalidate_cache clears the cache."""
from backend.bookslm import collect_directory_context, invalidate_cache, _cache
_cache.clear()
vault = tmp_path / "vault"
vault.mkdir()
(vault / "note.md").write_text("Content", encoding="utf-8")
collect_directory_context(vault, "")
assert len(_cache) > 0
count = invalidate_cache()
assert count > 0
assert len(_cache) == 0
# ── Unit tests: secret redaction ──────────────────────────────────────
class TestRedaction:
"""Verify that secrets are redacted in collected content."""
def test_secrets_are_redacted(self, tmp_path):
"""API keys in file content are redacted."""
from backend.bookslm import collect_directory_context
vault = tmp_path / "vault"
vault.mkdir()
# The secret redactor looks for patterns like sk-..., AKIA..., etc.
(vault / "secrets.md").write_text(
"Config: api_key=AKIA1234567890ABCDEF and sk-abcdefghijklmnopqrstuvwxyz01234567890",
encoding="utf-8",
)
result = collect_directory_context(vault, "")
# The redactor should have processed this file
content = result["files"][0]["content"]
# At minimum the file should be collected (redaction is best-effort)
assert result["file_count"] == 1
# ── Integration tests: API endpoints ──────────────────────────────────
@pytest.fixture
def bookslm_client():
"""Create a TestClient with auth enabled, isolated temp data."""
tmp = Path(tempfile.mkdtemp())
data_dir = tmp / "data"
data_dir.mkdir()
# Create a test vault with some files
test_vault = tmp / "test-vault"
test_vault.mkdir()
(test_vault / "README.md").write_text("# Test Vault\nWelcome to the test vault.", encoding="utf-8")
(test_vault / "notes").mkdir()
(test_vault / "notes" / "note1.md").write_text("# Note 1\nFirst note content.", encoding="utf-8")
(test_vault / "notes" / "note2.md").write_text("# Note 2\nSecond note content.", encoding="utf-8")
from backend.auth.password import hash_password
pw_hash = hash_password("TestPass123!")
users = {
"version": 1,
"users": {
"testuser": {
"id": "testuser-1",
"username": "testuser",
"display_name": "Test User",
"password_hash": pw_hash,
"role": "admin",
"vaults": ["*"],
"active": True,
"created_at": "2026-01-01T00:00:00",
}
}
}
(data_dir / "users.json").write_text(json.dumps(users), encoding="utf-8")
src_secret = Path("data/secret.key")
if src_secret.exists():
shutil.copy2(str(src_secret), str(data_dir / "secret.key"))
orig_cwd = os.getcwd()
os.chdir(str(tmp))
os.environ["VAULT_1_NAME"] = "TestVault"
os.environ["VAULT_1_PATH"] = str(test_vault)
os.environ["OBSIGATE_AUTH_ENABLED"] = "true"
os.environ["OBSIGATE_ADMIN_USER"] = "testuser"
os.environ["OBSIGATE_ADMIN_PASSWORD"] = "TestPass123!"
os.environ["OBSIGATE_WATCHER_ENABLED"] = "false"
import backend.main
backend.main._load_config = lambda: {"watcher_enabled": False}
from backend.main import app
from backend.indexer import build_index, index
for key in list(index.keys()):
del index[key]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(build_index())
from backend.search import init_inverted_index
init_inverted_index()
from fastapi.testclient import TestClient
client = TestClient(app)
yield client
if hasattr(client, 'close'):
client.close()
loop.run_until_complete(asyncio.sleep(0))
os.chdir(orig_cwd)
shutil.rmtree(str(tmp), ignore_errors=True)
for k in ["VAULT_1_NAME", "VAULT_1_PATH", "OBSIGATE_AUTH_ENABLED",
"OBSIGATE_ADMIN_USER", "OBSIGATE_ADMIN_PASSWORD", "OBSIGATE_WATCHER_ENABLED"]:
os.environ.pop(k, None)
def _login_bookslm(client, username="testuser", password="TestPass123!"):
resp = client.post("/api/auth/login", json={"username": username, "password": password})
return resp.json().get("access_token"), resp
class TestBooksLMContextEndpoint:
"""Tests for POST /api/ai/bookslm/context."""
def test_context_returns_files(self, bookslm_client):
"""Context endpoint returns files from the directory."""
token, _ = _login_bookslm(bookslm_client)
resp = bookslm_client.post(
"/api/ai/bookslm/context",
json={"vault": "TestVault", "directory": "notes"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
data = resp.json()
assert data["file_count"] == 2
paths = [f["path"] for f in data["files"]]
assert "notes/note1.md" in paths
assert "notes/note2.md" in paths
def test_context_root_directory(self, bookslm_client):
"""Context endpoint works for root directory."""
token, _ = _login_bookslm(bookslm_client)
resp = bookslm_client.post(
"/api/ai/bookslm/context",
json={"vault": "TestVault", "directory": ""},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
data = resp.json()
assert data["file_count"] >= 1 # At least README.md
def test_context_requires_auth(self, bookslm_client):
"""Context endpoint requires authentication."""
resp = bookslm_client.post(
"/api/ai/bookslm/context",
json={"vault": "TestVault", "directory": ""},
)
assert resp.status_code == 401
def test_context_vault_not_found(self, bookslm_client):
"""Context endpoint returns 404 for unknown vault."""
token, _ = _login_bookslm(bookslm_client)
resp = bookslm_client.post(
"/api/ai/bookslm/context",
json={"vault": "NonExistent", "directory": ""},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 404
def test_context_nonexistent_directory(self, bookslm_client):
"""Context endpoint returns empty for nonexistent directory."""
token, _ = _login_bookslm(bookslm_client)
resp = bookslm_client.post(
"/api/ai/bookslm/context",
json={"vault": "TestVault", "directory": "nonexistent"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
data = resp.json()
assert data["file_count"] == 0
class TestBooksLMChatEndpoint:
"""Tests for POST /api/ai/chat."""
def test_chat_requires_auth(self, bookslm_client):
"""Chat endpoint requires authentication."""
resp = bookslm_client.post(
"/api/ai/bookslm/chat",
json={"vault": "TestVault", "directory": "", "message": "Hello"},
)
assert resp.status_code == 401
def test_chat_vault_not_found(self, bookslm_client):
"""Chat endpoint returns 404 for unknown vault."""
token, _ = _login_bookslm(bookslm_client)
resp = bookslm_client.post(
"/api/ai/bookslm/chat",
json={"vault": "NonExistent", "directory": "", "message": "Hello"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 404
def test_chat_empty_directory(self, bookslm_client):
"""Chat endpoint returns 404 for empty directory."""
token, _ = _login_bookslm(bookslm_client)
resp = bookslm_client.post(
"/api/ai/bookslm/chat",
json={"vault": "TestVault", "directory": "nonexistent", "message": "Hello"},
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 404
def test_chat_request_accepts_provider_and_model(self, bookslm_client):
"""The chat endpoint schema accepts provider + model fields without rejecting.
We don't actually call the AI (would need a live key) — we just verify
the request schema is wired correctly so a missing key is the only
failure mode, not a 422 validation error.
"""
token, _ = _login_bookslm(bookslm_client)
# Build a tiny valid directory so the chat endpoint doesn't 404.
from pathlib import Path
vault_dir = Path(os.environ.get("VAULT_1_PATH", "test-vault"))
sub = vault_dir / "for_chat_test"
sub.mkdir(exist_ok=True)
(sub / "note.md").write_text("# hello\n", encoding="utf-8")
try:
resp = bookslm_client.post(
"/api/ai/bookslm/chat",
json={
"vault": "TestVault",
"directory": "for_chat_test",
"message": "ping",
"provider": "deepseek",
"model": "deepseek-chat",
},
headers={"Authorization": f"Bearer {token}"},
)
# Either 200 (if a real key is configured) or 500 (no key / quota).
# Must NOT be 422 — the schema must accept the fields.
assert resp.status_code in (200, 500), (
f"unexpected status {resp.status_code}: {resp.text[:200]}"
)
assert resp.status_code != 422, (
f"schema rejected provider/model fields: {resp.text[:300]}"
)
finally:
import shutil
shutil.rmtree(sub, ignore_errors=True)
+172
View File
@@ -0,0 +1,172 @@
# tests/test_export.py — Tests for multi-format export (HTML / MD bundle / ePub)
import io
import zipfile
from pathlib import Path
import pytest
from backend.export import (
ExportError,
export_epub,
export_html,
export_md_bundle,
)
# ═══════════════════════════════════════════════════════════════════
# export_html
# ═══════════════════════════════════════════════════════════════════
class TestExportHtml:
def test_valid_html(self, test_vault_dir):
vault = Path(test_vault_dir)
html = export_html(vault, vault / "note1.md")
assert isinstance(html, bytes)
text = html.decode("utf-8")
assert text.startswith("<!DOCTYPE html>")
assert "<html" in text
assert "</html>" in text
assert "<style>" in text # inlined CSS
def test_renders_content(self, test_vault_dir):
vault = Path(test_vault_dir)
html = export_html(vault, vault / "note1.md").decode("utf-8")
assert "Introduction" in html
assert "Python" in html
def test_uses_frontmatter_title(self, test_vault_dir):
vault = Path(test_vault_dir)
html = export_html(vault, vault / "note1.md").decode("utf-8")
assert "<title>Introduction à Python</title>" in html
def test_navigation_lists_other_notes(self, test_vault_dir):
vault = Path(test_vault_dir)
html = export_html(vault, vault / "note1.md").decode("utf-8")
assert "class=\"export-nav\"" in html
# note2 should appear as a sibling link
assert "note2.html" in html or "note2" in html
def test_wikilink_becomes_link(self, test_vault_dir):
vault = Path(test_vault_dir)
html = export_html(vault, vault / "note2.md").decode("utf-8")
assert "href=" in html
def test_missing_file_raises(self, test_vault_dir):
vault = Path(test_vault_dir)
with pytest.raises(ExportError):
export_html(vault, vault / "does_not_exist.md")
# ═══════════════════════════════════════════════════════════════════
# export_md_bundle
# ═══════════════════════════════════════════════════════════════════
class TestExportMdBundle:
def test_zip_contains_files(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_md_bundle(vault, vault)
assert isinstance(data, bytes)
zf = zipfile.ZipFile(io.BytesIO(data))
names = zf.namelist()
assert "note1.md" in names
assert "note2.md" in names
assert "config.json" in names
# Subdirectory preserved
assert any("Projets/projet.md" in n for n in names)
def test_zip_preserves_structure(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_md_bundle(vault, vault / "Projets")
zf = zipfile.ZipFile(io.BytesIO(data))
names = zf.namelist()
assert "projet.md" in names
def test_single_file_bundle(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_md_bundle(vault, vault / "note1.md")
zf = zipfile.ZipFile(io.BytesIO(data))
assert "note1.md" in zf.namelist()
def test_missing_path_raises(self, test_vault_dir):
vault = Path(test_vault_dir)
with pytest.raises(ExportError):
export_md_bundle(vault, vault / "nope")
# ═══════════════════════════════════════════════════════════════════
# export_epub
# ═══════════════════════════════════════════════════════════════════
class TestExportEpub:
def test_epub_is_valid_zip(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_epub(vault, vault / "note1.md")
assert isinstance(data, bytes)
zf = zipfile.ZipFile(io.BytesIO(data))
assert zf.testzip() is None # archive is intact
def test_epub_mimetype_first(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_epub(vault, vault / "note1.md")
zf = zipfile.ZipFile(io.BytesIO(data))
names = zf.namelist()
assert names[0] == "mimetype"
assert zf.read("mimetype") == b"application/epub+zip"
def test_epub_required_files(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_epub(vault, vault / "note1.md")
zf = zipfile.ZipFile(io.BytesIO(data))
names = set(zf.namelist())
assert "META-INF/container.xml" in names
assert "OEBPS/content.opf" in names
assert "OEBPS/toc.ncx" in names
assert "OEBPS/chapter1.xhtml" in names
def test_epub_content_rendered(self, test_vault_dir):
vault = Path(test_vault_dir)
data = export_epub(vault, vault / "note1.md")
zf = zipfile.ZipFile(io.BytesIO(data))
xhtml = zf.read("OEBPS/chapter1.xhtml").decode("utf-8")
assert "Introduction" in xhtml
assert "Python" in xhtml
def test_epub_missing_file_raises(self, test_vault_dir):
vault = Path(test_vault_dir)
with pytest.raises(ExportError):
export_epub(vault, vault / "nope.md")
# ═══════════════════════════════════════════════════════════════════
# API endpoints
# ═══════════════════════════════════════════════════════════════════
class TestExportApi:
def test_export_html_endpoint(self, client):
resp = client.get("/api/export/html", params={"vault": "TestVault", "path": "note1.md"})
assert resp.status_code == 200
assert "text/html" in resp.headers["content-type"]
assert "attachment" in resp.headers["content-disposition"]
assert resp.content.startswith(b"<!DOCTYPE html>")
def test_export_md_bundle_endpoint(self, client):
resp = client.get("/api/export/md-bundle", params={"vault": "TestVault", "path": ""})
assert resp.status_code == 200
assert resp.headers["content-type"] == "application/zip"
zf = zipfile.ZipFile(io.BytesIO(resp.content))
assert "note1.md" in zf.namelist()
def test_export_epub_endpoint(self, client):
resp = client.get("/api/export/epub", params={"vault": "TestVault", "path": "note1.md"})
assert resp.status_code == 200
assert "epub" in resp.headers["content-type"]
zf = zipfile.ZipFile(io.BytesIO(resp.content))
assert zf.namelist()[0] == "mimetype"
def test_export_missing_file_returns_400(self, client):
resp = client.get("/api/export/html", params={"vault": "TestVault", "path": "nope.md"})
assert resp.status_code == 400
def test_export_unknown_vault_returns_404(self, client):
resp = client.get("/api/export/html", params={"vault": "NoVault", "path": "x.md"})
assert resp.status_code == 404
+353
View File
@@ -0,0 +1,353 @@
"""Tests for MFA (Multi-Factor Authentication) — TOTP + recovery codes."""
import asyncio
import json
import os
import shutil
import tempfile
import time
from pathlib import Path
import pyotp
import pytest
from backend.auth.mfa import (
TOTP_ISSUER,
generate_qr_uri,
generate_recovery_codes,
generate_secret,
hash_recovery_code,
verify_recovery_code,
verify_totp,
)
# ── Unit tests: TOTP ───────────────────────────────────────────────────
class TestTotpGeneration:
def test_generate_secret_returns_base32(self):
secret = generate_secret()
assert isinstance(secret, str)
assert len(secret) >= 16
import base64
base64.b32decode(secret, casefold=True)
def test_generate_secret_unique(self):
secrets = {generate_secret() for _ in range(100)}
assert len(secrets) == 100
def test_generate_qr_uri_format(self):
secret = generate_secret()
uri = generate_qr_uri(secret, "testuser")
assert uri.startswith("otpauth://totp/")
assert "ObsiGate" in uri
assert "testuser" in uri
assert "secret=" in uri
def test_generate_qr_uri_custom_issuer(self):
secret = generate_secret()
uri = generate_qr_uri(secret, "testuser", issuer="CustomIssuer")
assert "CustomIssuer" in uri
def test_verify_totp_valid(self):
secret = generate_secret()
totp = pyotp.TOTP(secret)
code = totp.now()
assert verify_totp(secret, code) is True
def test_verify_totp_invalid(self):
secret = generate_secret()
assert verify_totp(secret, "000000") is False
def test_verify_totp_wrong_secret(self):
secret1 = generate_secret()
secret2 = generate_secret()
totp1 = pyotp.TOTP(secret1)
code = totp1.now()
assert verify_totp(secret2, code) is False
def test_verify_totp_window_tolerance(self):
secret = generate_secret()
totp = pyotp.TOTP(secret)
current_time = time.time()
code = totp.at(int(current_time))
assert verify_totp(secret, str(code).zfill(6)) is True
# ── Unit tests: Recovery codes ─────────────────────────────────────────
class TestRecoveryCodes:
def test_generate_count(self):
codes = generate_recovery_codes()
assert len(codes) == 8
def test_generate_custom_count(self):
codes = generate_recovery_codes(n=12)
assert len(codes) == 12
def test_code_format(self):
codes = generate_recovery_codes()
for code in codes:
assert len(code) == 9 # XXXX-XXXX
assert code[4] == "-"
assert code[:4].isalnum()
assert code[5:].isalnum()
def test_codes_unique(self):
codes = generate_recovery_codes(n=20)
assert len(set(codes)) == 20
def test_codes_uppercase(self):
codes = generate_recovery_codes()
for code in codes:
assert code == code.upper()
def test_hash_recovery_code_deterministic(self):
code = "ABCD-1234"
h1 = hash_recovery_code(code)
h2 = hash_recovery_code(code)
assert h1 == h2
def test_hash_case_insensitive(self):
h1 = hash_recovery_code("abcd-1234")
h2 = hash_recovery_code("ABCD-1234")
assert h1 == h2
def test_hash_different_for_different_codes(self):
h1 = hash_recovery_code("AAAA-AAAA")
h2 = hash_recovery_code("BBBB-BBBB")
assert h1 != h2
def test_verify_recovery_code_match(self):
codes = generate_recovery_codes()
hashed = [hash_recovery_code(c) for c in codes]
for i, code in enumerate(codes):
idx = verify_recovery_code(code, hashed)
assert idx == i
def test_verify_recovery_code_case_insensitive(self):
codes = ["ABCD-1234"]
hashed = [hash_recovery_code(c) for c in codes]
assert verify_recovery_code("abcd-1234", hashed) == 0
def test_verify_recovery_code_invalid(self):
codes = generate_recovery_codes()
hashed = [hash_recovery_code(c) for c in codes]
assert verify_recovery_code("ZZZZ-ZZZZ", hashed) is None
def test_verify_recovery_code_empty_list(self):
assert verify_recovery_code("AAAA-AAAA", []) is None
def test_recovery_code_single_use(self):
codes = generate_recovery_codes(n=3)
hashed = [hash_recovery_code(c) for c in codes]
idx = verify_recovery_code(codes[0], hashed)
assert idx == 0
hashed.pop(idx)
assert verify_recovery_code(codes[0], hashed) is None
idx2 = verify_recovery_code(codes[1], hashed)
assert idx2 == 0
# ── Integration tests: MFA API endpoints ───────────────────────────────
@pytest.fixture
def mfa_client():
"""Create a TestClient with auth enabled, isolated temp data."""
tmp = Path(tempfile.mkdtemp())
data_dir = tmp / "data"
data_dir.mkdir()
from backend.auth.password import hash_password
pw_hash = hash_password("TestPass123!")
users = {
"version": 1,
"users": {
"testuser": {
"id": "testuser-1",
"username": "testuser",
"display_name": "Test User",
"password_hash": pw_hash,
"role": "admin",
"vaults": ["*"],
"active": True,
"created_at": "2026-01-01T00:00:00",
}
}
}
(data_dir / "users.json").write_text(json.dumps(users), encoding="utf-8")
src_secret = Path("data/secret.key")
if src_secret.exists():
shutil.copy2(str(src_secret), str(data_dir / "secret.key"))
orig_cwd = os.getcwd()
test_vault_path = os.path.abspath("test-vault")
os.chdir(str(tmp))
os.environ["VAULT_1_NAME"] = "TestVault"
os.environ["VAULT_1_PATH"] = test_vault_path
os.environ["OBSIGATE_AUTH_ENABLED"] = "true"
os.environ["OBSIGATE_ADMIN_USER"] = "testuser"
os.environ["OBSIGATE_ADMIN_PASSWORD"] = "TestPass123!"
os.environ["OBSIGATE_WATCHER_ENABLED"] = "false"
import backend.main
backend.main._load_config = lambda: {"watcher_enabled": False}
from backend.main import app
from backend.indexer import build_index, index
for key in list(index.keys()):
del index[key]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(build_index())
from backend.search import init_inverted_index
init_inverted_index()
from fastapi.testclient import TestClient
client = TestClient(app)
yield client
if hasattr(client, 'close'):
client.close()
loop.run_until_complete(asyncio.sleep(0))
os.chdir(orig_cwd)
shutil.rmtree(str(tmp), ignore_errors=True)
for k in ["VAULT_1_NAME", "VAULT_1_PATH", "OBSIGATE_AUTH_ENABLED",
"OBSIGATE_ADMIN_USER", "OBSIGATE_ADMIN_PASSWORD", "OBSIGATE_WATCHER_ENABLED"]:
os.environ.pop(k, None)
def _login(client, username="testuser", password="TestPass123!"):
resp = client.post("/api/auth/login", json={"username": username, "password": password})
return resp.json().get("access_token"), resp
def _auth_headers(token):
return {"Authorization": f"Bearer {token}"}
class TestMfaApiEndpoints:
def test_mfa_status_initially_disabled(self, mfa_client):
token, _ = _login(mfa_client)
resp = mfa_client.get("/api/auth/mfa/status", headers=_auth_headers(token))
assert resp.status_code == 200
assert resp.json()["mfa_enabled"] is False
def test_mfa_setup_generates_secret(self, mfa_client):
token, _ = _login(mfa_client)
resp = mfa_client.post("/api/auth/mfa/totp/setup", headers=_auth_headers(token))
assert resp.status_code == 200
data = resp.json()
assert "secret" in data
assert "otpauth_uri" in data
assert "otpauth://totp/" in data["otpauth_uri"]
assert len(data["secret"]) >= 16
def test_mfa_enable_flow(self, mfa_client):
token, _ = _login(mfa_client)
headers = _auth_headers(token)
# Setup
setup_resp = mfa_client.post("/api/auth/mfa/totp/setup", headers=headers)
secret = setup_resp.json()["secret"]
totp = pyotp.TOTP(secret)
# Enable
enable_resp = mfa_client.post("/api/auth/mfa/totp/enable", headers=headers, json={
"code": totp.now(),
})
assert enable_resp.status_code == 200
data = enable_resp.json()
assert "recovery_codes" in data
assert len(data["recovery_codes"]) == 8
assert data["mfa_enabled"] is True
def test_mfa_enable_invalid_code(self, mfa_client):
token, _ = _login(mfa_client)
headers = _auth_headers(token)
mfa_client.post("/api/auth/mfa/totp/setup", headers=headers)
resp = mfa_client.post("/api/auth/mfa/totp/enable", headers=headers, json={
"code": "000000",
})
assert resp.status_code in (400, 401)
def test_mfa_login_defers_to_totp(self, mfa_client):
token, _ = _login(mfa_client)
headers = _auth_headers(token)
# Enable MFA
setup_resp = mfa_client.post("/api/auth/mfa/totp/setup", headers=headers)
secret = setup_resp.json()["secret"]
totp = pyotp.TOTP(secret)
mfa_client.post("/api/auth/mfa/totp/enable", headers=headers, json={"code": totp.now()})
# Login again — should require MFA
login_resp = mfa_client.post("/api/auth/login", json={
"username": "testuser", "password": "TestPass123!",
})
assert login_resp.status_code == 200
data = login_resp.json()
assert data.get("mfa_required") is True
assert data.get("mfa_method") == "totp"
assert "access_token" not in data
def test_mfa_verify_issues_token(self, mfa_client):
token, _ = _login(mfa_client)
headers = _auth_headers(token)
setup_resp = mfa_client.post("/api/auth/mfa/totp/setup", headers=headers)
secret = setup_resp.json()["secret"]
totp = pyotp.TOTP(secret)
mfa_client.post("/api/auth/mfa/totp/enable", headers=headers, json={"code": totp.now()})
# Login → MFA challenge
mfa_client.post("/api/auth/login", json={"username": "testuser", "password": "TestPass123!"})
# Verify TOTP
verify_resp = mfa_client.post("/api/auth/mfa/totp/verify", json={
"username": "testuser", "code": totp.now(),
})
assert verify_resp.status_code == 200
data = verify_resp.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
def test_mfa_recovery_login(self, mfa_client):
token, _ = _login(mfa_client)
headers = _auth_headers(token)
setup_resp = mfa_client.post("/api/auth/mfa/totp/setup", headers=headers)
secret = setup_resp.json()["secret"]
totp = pyotp.TOTP(secret)
enable_resp = mfa_client.post("/api/auth/mfa/totp/enable", headers=headers, json={"code": totp.now()})
recovery_codes = enable_resp.json()["recovery_codes"]
# Login → MFA challenge
mfa_client.post("/api/auth/login", json={"username": "testuser", "password": "TestPass123!"})
# Use recovery code
recover_resp = mfa_client.post("/api/auth/mfa/recovery", json={
"username": "testuser", "recovery_code": recovery_codes[0],
})
assert recover_resp.status_code == 200
assert "access_token" in recover_resp.json()
def test_mfa_disable_flow(self, mfa_client):
token, _ = _login(mfa_client)
headers = _auth_headers(token)
setup_resp = mfa_client.post("/api/auth/mfa/totp/setup", headers=headers)
secret = setup_resp.json()["secret"]
totp = pyotp.TOTP(secret)
mfa_client.post("/api/auth/mfa/totp/enable", headers=headers, json={"code": totp.now()})
# Disable
disable_resp = mfa_client.post("/api/auth/mfa/totp/disable", headers=headers, json={
"password": "TestPass123!", "code": totp.now(),
})
assert disable_resp.status_code == 200
# Verify disabled
status_resp = mfa_client.get("/api/auth/mfa/status", headers=headers)
assert status_resp.json()["mfa_enabled"] is False
def test_login_without_mfa_still_works(self, mfa_client):
login_resp = mfa_client.post("/api/auth/login", json={
"username": "testuser", "password": "TestPass123!",
})
assert login_resp.status_code == 200
data = login_resp.json()
assert "access_token" in data
assert data.get("mfa_required") is None
+329
View File
@@ -0,0 +1,329 @@
"""Tests for PDF support in ObsiGate (ROADMAP #74).
Covers:
- backend/pdf_reader.py: text/metadata/TOC extraction with pypdf + pymupdf
- backend/main.py: api_pdf_stream endpoint, is_pdf detection in api_file_view
- backend/indexer.py: .pdf in SUPPORTED_EXTENSIONS, index_document handles PDFs
- backend/search.py: filter `ext:pdf` returns only PDFs (already implemented)
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
from pathlib import Path
import pytest
# Skip the whole module if neither PDF library is available.
try:
import pypdf # noqa: F401
HAS_PDF_LIB = True
except ImportError:
try:
import fitz # noqa: F401 # pymupdf
HAS_PDF_LIB = True
except ImportError:
HAS_PDF_LIB = False
pytestmark = pytest.mark.skipif(
not HAS_PDF_LIB, reason="Neither pypdf nor pymupdf is installed"
)
# ── Fixtures: generate a real PDF on disk ──────────────────────────────────
def make_simple_pdf(path: Path, *, pages: int = 2, title: str = "", author: str = "") -> Path:
"""Create a PDF with `pages` pages, each page containing a unique sentence."""
try:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
except ImportError:
pytest.skip("reportlab not available — cannot generate test PDF fixture")
c = canvas.Canvas(str(path), pagesize=letter)
if title:
c.setTitle(title)
if author:
c.setAuthor(author)
for i in range(pages):
c.drawString(72, 720, f"ObsiGate test PDF — page {i + 1} uniqueword{i}")
c.showPage()
c.save()
return path
@pytest.fixture
def pdf_dir(tmp_path: Path) -> Path:
"""A temp directory with a few PDFs of different shapes."""
d = tmp_path / "pdfs"
d.mkdir()
make_simple_pdf(d / "simple.pdf", pages=2, title="Simple Test", author="Bruno")
make_simple_pdf(d / "long.pdf", pages=3)
make_simple_pdf(d / "single.pdf", pages=1)
return d
# ── backend/pdf_reader.py ──────────────────────────────────────────────────
class TestPdfReader:
def test_extract_text_returns_text_with_keywords(self, pdf_dir: Path):
from backend.pdf_reader import extract_pdf_text
text = extract_pdf_text(pdf_dir / "simple.pdf")
assert "ObsiGate test PDF" in text
assert "uniqueword0" in text
assert "uniqueword1" in text
def test_extract_text_truncates_at_max_chars(self, pdf_dir: Path):
from backend.pdf_reader import extract_pdf_text
# tight max_chars truncates after the first page
text = extract_pdf_text(pdf_dir / "long.pdf", max_chars=10)
assert len(text) <= 50 # allow some slack; first page may have ~30 chars
def test_extract_text_missing_file_returns_empty(self, tmp_path: Path):
from backend.pdf_reader import extract_pdf_text
result = extract_pdf_text(tmp_path / "does-not-exist.pdf")
assert result == ""
def test_extract_text_corrupt_file_returns_empty(self, tmp_path: Path):
from backend.pdf_reader import extract_pdf_text
junk = tmp_path / "junk.pdf"
junk.write_bytes(b"not a real pdf, just some bytes %PDF-1.4 but no xref")
result = extract_pdf_text(junk)
# Should not raise; returns "" on failure
assert isinstance(result, str)
def test_extract_metadata_returns_pages_title_author(self, pdf_dir: Path):
from backend.pdf_reader import extract_pdf_metadata
info = extract_pdf_metadata(pdf_dir / "simple.pdf")
assert info["pages"] == 2
assert info["title"] in ("Simple Test", "") # metadata may be empty on some readers
assert isinstance(info["author"], str)
def test_extract_metadata_missing_file_returns_zeros(self, tmp_path: Path):
from backend.pdf_reader import extract_pdf_metadata
info = extract_pdf_metadata(tmp_path / "missing.pdf")
assert info == {"pages": 0, "title": "", "author": ""}
def test_extract_toc_returns_list(self, pdf_dir: Path):
from backend.pdf_reader import extract_pdf_toc
# simple PDFs (no outline) → empty list, no exception
toc = extract_pdf_toc(pdf_dir / "simple.pdf")
assert isinstance(toc, list)
class TestPdfIncrementalIndexing:
"""_index_single_file_sync (watcher/update path) must handle binary PDFs.
Regression: it used to read_text() every file, producing garbage for PDFs.
"""
def test_index_single_file_sync_extracts_pdf_text(self, pdf_dir: Path):
from backend.indexer import _index_single_file_sync
info = _index_single_file_sync("v", str(pdf_dir), str(pdf_dir / "simple.pdf"))
assert info is not None
assert info["extension"] == ".pdf"
assert "ObsiGate test PDF" in info["content"]
assert "uniqueword0" in info["content"]
def test_index_single_file_sync_pdf_title_from_metadata(self, pdf_dir: Path):
from backend.indexer import _index_single_file_sync
info = _index_single_file_sync("v", str(pdf_dir), str(pdf_dir / "simple.pdf"))
# title metadata was set at generation time
assert info["title"] == "Simple Test"
class TestPdfSizeLimit:
def test_oversized_pdf_skips_text_extraction(self, pdf_dir: Path, monkeypatch):
import backend.pdf_reader as pr
monkeypatch.setattr(pr, "PDF_MAX_SIZE_MB", 0) # everything is "too large"
text = pr.extract_pdf_text(pdf_dir / "simple.pdf")
assert text == ""
def test_normal_pdf_within_limit_extracts(self, pdf_dir: Path, monkeypatch):
import backend.pdf_reader as pr
monkeypatch.setattr(pr, "PDF_MAX_SIZE_MB", 50)
text = pr.extract_pdf_text(pdf_dir / "simple.pdf")
assert "ObsiGate test PDF" in text
# ── API: /pdf/stream (206 Range) + /pdf/info ───────────────────────────────
@pytest.fixture
def pdf_client():
"""TestClient (auth disabled) over a vault containing one generated PDF."""
tmp = Path(tempfile.mkdtemp())
vault = tmp / "PdfVault"
vault.mkdir()
make_simple_pdf(vault / "doc.pdf", pages=2, title="Doc Test", author="Bruno")
os.environ["VAULT_1_NAME"] = "PdfVault"
os.environ["VAULT_1_PATH"] = str(vault)
os.environ["OBSIGATE_AUTH_ENABLED"] = "false"
os.environ["OBSIGATE_WATCHER_ENABLED"] = "false"
import backend.main
backend.main._load_config = lambda: {"watcher_enabled": False}
from backend.indexer import build_index, index
for key in list(index.keys()):
del index[key]
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(build_index())
from fastapi.testclient import TestClient
client = TestClient(backend.main.app)
yield client
client.close()
shutil.rmtree(str(tmp), ignore_errors=True)
for k in ["VAULT_1_NAME", "VAULT_1_PATH", "OBSIGATE_AUTH_ENABLED", "OBSIGATE_WATCHER_ENABLED"]:
os.environ.pop(k, None)
class TestPdfStreamApi:
def test_stream_returns_200_application_pdf(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf")
assert r.status_code == 200
assert r.headers["content-type"] == "application/pdf"
assert r.headers.get("accept-ranges") == "bytes"
assert r.content[:4] == b"%PDF"
def test_stream_full_range_returns_whole_file(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf",
headers={"Range": "bytes=0-99999999"})
assert r.status_code == 206
assert r.headers["content-range"].startswith("bytes 0-")
assert r.content[:4] == b"%PDF"
def test_stream_partial_range(self, pdf_client):
full = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf").content
r = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf",
headers={"Range": "bytes=10-19"})
assert r.status_code == 206
assert r.content == full[10:20]
assert len(r.content) == 10
def test_stream_open_ended_range(self, pdf_client):
full = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf").content
r = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf",
headers={"Range": "bytes=100-"})
assert r.status_code == 206
assert r.content == full[100:]
def test_stream_bad_range_returns_416(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.pdf",
headers={"Range": "bytes=999999999-"})
assert r.status_code == 416
assert "bytes */" in r.headers.get("content-range", "")
def test_stream_rejects_non_pdf(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/stream?path=doc.md")
assert r.status_code == 404 or r.status_code == 400
class TestPdfInfoApi:
def test_info_returns_metadata_without_content(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/info?path=doc.pdf")
assert r.status_code == 200
body = r.json()
assert body["pages"] == 2
assert body["title"] in ("Doc Test", "doc.pdf")
assert body["size_bytes"] > 0
assert "path" in body and body["vault"] == "PdfVault"
# no heavy content in the payload
assert "html" not in body
def test_info_missing_file_404(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/info?path=nope.pdf")
assert r.status_code == 404
def test_info_missing_non_pdf_404(self, pdf_client):
r = pdf_client.get("/api/file/PdfVault/pdf/info?path=readme.txt")
assert r.status_code == 404 # missing file checked before extension
# ── backend/indexer.py ─────────────────────────────────────────────────────
class TestPdfIndexing:
def test_pdf_in_supported_extensions(self):
from backend.indexer import SUPPORTED_EXTENSIONS
assert ".pdf" in SUPPORTED_EXTENSIONS
def test_scan_vault_picks_up_pdf_files(self, pdf_dir: Path, tmp_path: Path):
"""When a vault directory is scanned with .pdf files, they appear in files list.
Uses the public _scan_vault() helper directly — no global state needed.
"""
from backend.indexer import _scan_vault
vault_root = tmp_path / "vault"
vault_root.mkdir()
shutil.copy2(pdf_dir / "simple.pdf", vault_root / "a.pdf")
shutil.copy2(pdf_dir / "single.pdf", vault_root / "b.pdf")
result = _scan_vault("test-vault", str(vault_root), {"name": "test-vault", "path": str(vault_root)})
names = {f["path"] for f in result["files"]}
assert "a.pdf" in names
assert "b.pdf" in names
# The PDF content should have been extracted.
a_file = next(f for f in result["files"] if f["path"] == "a.pdf")
assert "ObsiGate test PDF" in (a_file.get("content") or "")
assert "uniqueword0" in (a_file.get("content") or "")
# ── Search filter `ext:` ───────────────────────────────────────────────────
class TestExtFilter:
"""The `ext:` filter is parsed in backend/search.py and applied in the
search pipeline. These tests verify the parsing + filter logic in isolation
so we don't depend on the full index state.
"""
def test_parse_ext_token(self):
from backend.search import _parse_advanced_query
parsed = _parse_advanced_query("hello ext:pdf world")
assert parsed["ext"] == "pdf"
assert "hello" in parsed["terms"]
assert "world" in parsed["terms"]
def test_parse_ext_token_with_dot(self):
from backend.search import _parse_advanced_query
parsed = _parse_advanced_query("ext:.md")
assert parsed["ext"] == "md"
def test_parse_no_ext_token(self):
from backend.search import _parse_advanced_query
parsed = _parse_advanced_query("hello world")
# ext key is initialized to None and stays None if no ext: token.
assert parsed.get("ext") in (None, "")
def test_parse_ext_token_lowercased(self):
from backend.search import _parse_advanced_query
parsed = _parse_advanced_query("ext:PDF")
assert parsed["ext"] == "pdf"
+208
View File
@@ -0,0 +1,208 @@
"""Tests for the Custom Themes feature (#65).
Validates:
- Theme JSON structure validity
- All 15 built-in themes have required keys and valid CSS colors
- High-contrast and sepia mode generators produce valid CSS vars
- Import/export round-trip
- AVAILABLE_MODES includes all 4 modes
"""
import json
import re
import pytest
# ── CSS color validation ─────────────────────────────────────────────
_CSS_COLOR_RE = re.compile(
r"^("
r"#[0-9a-fA-F]{3,8}" # hex
r"|rgba?\([^)]+\)" # rgb/rgba
r"|hsla?\([^)]+\)" # hsl/hsla
r"|[a-zA-Z]+" # named color
r")$"
)
REQUIRED_VARS = [
'--bg-primary', '--bg-secondary', '--bg-sidebar', '--bg-hover', '--border',
'--text-primary', '--text-secondary', '--text-muted', '--accent',
'--accent-green', '--tag-bg', '--tag-text', '--code-bg', '--search-bg',
'--scrollbar', '--resize-handle', '--overlay-bg',
'--danger', '--danger-bg', '--success', '--success-bg',
'--accent-card', '--accent-bg', '--accent-text',
'--green', '--green-bg', '--purple', '--purple-bg',
'--surface', '--surface2', '--surface3',
'--border-md', '--text', '--text-2', '--text-3',
'--ok', '--warn', '--ai', '--err',
]
AVAILABLE_MODES = ['dark', 'light', 'high-contrast', 'sepia']
# ── Theme data extracted from themes.js ──────────────────────────────
# We parse the JS file to extract theme definitions for validation.
def _parse_themes_from_js():
"""Read themes.js and build a dict of theme definitions using regex."""
import os
js_path = os.path.join(os.path.dirname(__file__), '..', 'frontend', 'js', 'themes.js')
with open(js_path, encoding='utf-8') as f:
content = f.read()
return content
def _extract_theme_names(content):
"""Extract top-level theme keys from THEMES dict."""
return re.findall(r"'([a-z0-9-]+)':\s*\{", content.split('var THEMES')[1].split('// ── Theme Engine')[0])
def _count_css_vars_in_block(content, keyword, section_start):
"""Count CSS variable assignments starting from a position."""
return len(re.findall(r"'--[a-z]", content[section_start:section_start + 2000]))
class TestThemeStructure:
"""Validate theme data from themes.js."""
@pytest.fixture(autouse=True)
def load_js(self):
self.content = _parse_themes_from_js()
def test_themes_file_exists(self):
"""themes.js should exist and be readable."""
assert len(self.content) > 1000
def test_has_available_modes(self):
"""AVAILABLE_MODES should define all 4 modes."""
assert "AVAILABLE_MODES = ['dark', 'light', 'high-contrast', 'sepia']" in self.content
def test_has_mode_generators(self):
"""Mode generators for high-contrast and sepia should exist."""
assert '_genHighContrast' in self.content
assert '_genSepia' in self.content
def test_theme_count(self):
"""Should have 15 built-in themes."""
names = _extract_theme_names(self.content)
assert len(names) == 15, f"Expected 15 themes, found {len(names)}: {names}"
def test_required_export_functions(self):
"""All required functions should be exported."""
required_exports = [
'THEMES', 'AVAILABLE_MODES',
'applyTheme', 'toggleThemeMode',
'getCurrentTheme', 'getCurrentMode',
'setTheme', 'listThemes', 'listModes',
'exportTheme', 'exportAllThemes', 'importTheme',
'deleteCustomTheme', 'loadCustomThemes',
'initThemes',
]
export_block = self.content.split('export {')[1].split('}')[0]
for fn in required_exports:
assert fn in export_block, f"Missing export: {fn}"
def test_high_contrast_vars_count(self):
"""High-contrast generator should define 30+ CSS vars."""
hc_start = self.content.index('_genHighContrast')
hc_section = self.content[hc_start:hc_start + 2000]
var_count = len(re.findall(r"'--[a-z]", hc_section))
assert var_count >= 30, f"High-contrast defines {var_count} vars, expected >= 30"
def test_sepia_vars_count(self):
"""Sepia generator should define 30+ CSS vars."""
sepia_start = self.content.index('_genSepia')
sepia_section = self.content[sepia_start:sepia_start + 2000]
var_count = len(re.findall(r"'--[a-z]", sepia_section))
assert var_count >= 30, f"Sepia defines {var_count} vars, expected >= 30"
def test_high_contrast_colors_valid(self):
"""High-contrast mode should use valid CSS colors."""
hc_start = self.content.index('_genHighContrast')
hc_section = self.content[hc_start:hc_start + 2000]
colors = re.findall(r":\s*'([^']+)'", hc_section)
for color in colors:
assert _CSS_COLOR_RE.match(color), f"Invalid CSS color in high-contrast: {color}"
def test_sepia_colors_valid(self):
"""Sepia mode should use valid CSS colors."""
sepia_start = self.content.index('_genSepia')
sepia_section = self.content[sepia_start:sepia_start + 2000]
colors = re.findall(r":\s*'([^']+)'", sepia_section)
for color in colors:
assert _CSS_COLOR_RE.match(color), f"Invalid CSS color in sepia: {color}"
def test_getvars_handles_all_modes(self):
"""_getVars should handle dark, light, high-contrast, and sepia."""
assert "mode === 'high-contrast'" in self.content
assert "mode === 'sepia'" in self.content
def test_import_theme_validates_input(self):
"""importTheme should validate JSON structure."""
assert "missing modes" in self.content
assert "at least dark or light" in self.content
def test_localstorage_keys(self):
"""Custom themes should use proper localStorage key prefix."""
assert "obsigate-custom-" in self.content
assert "obsigate-theme" in self.content
assert "obsigate-theme-mode" in self.content
def test_each_theme_has_dark_and_light(self):
"""Each built-in theme should define dark and light modes."""
names = _extract_theme_names(self.content)
for name in names:
pattern = re.compile(
rf"'{re.escape(name)}':\s*\{{.*?modes:\s*\{{.*?dark:\s*\{{",
re.DOTALL
)
assert pattern.search(self.content), f"Theme '{name}' missing dark mode"
def test_toggle_cycles_all_modes(self):
"""toggleThemeMode should cycle through all 4 modes."""
assert '% AVAILABLE_MODES.length' in self.content
class TestI18nKeys:
"""Validate that all theme i18n keys exist in both locales."""
@pytest.fixture(autouse=True)
def load_locales(self):
import os
base = os.path.join(os.path.dirname(__file__), '..', 'frontend', 'locales')
with open(os.path.join(base, 'en.json'), encoding='utf-8') as f:
self.en = json.load(f)
with open(os.path.join(base, 'fr.json'), encoding='utf-8') as f:
self.fr = json.load(f)
def test_theme_keys_en(self):
"""English locale should have all theme keys."""
required = [
'theme.dark', 'theme.light', 'theme.high_contrast', 'theme.sepia',
'theme.title', 'theme.change',
'theme.export_all', 'theme.import',
'theme.import_success', 'theme.import_error',
'theme.delete_confirm',
]
for key in required:
assert key in self.en, f"Missing EN key: {key}"
def test_theme_keys_fr(self):
"""French locale should have all theme keys."""
required = [
'theme.dark', 'theme.light', 'theme.high_contrast', 'theme.sepia',
'theme.title', 'theme.change',
'theme.export_all', 'theme.import',
'theme.import_success', 'theme.import_error',
'theme.delete_confirm',
]
for key in required:
assert key in self.fr, f"Missing FR key: {key}"
def test_import_success_has_placeholder(self):
"""import_success key should accept a {count} parameter."""
assert '{count}' in self.en['theme.import_success']
assert '{count}' in self.fr['theme.import_success']
def test_key_parity(self):
"""EN and FR should have the same set of theme.* keys."""
en_theme = {k for k in self.en if k.startswith('theme.')}
fr_theme = {k for k in self.fr if k.startswith('theme.')}
assert en_theme == fr_theme, f"Key mismatch: EN-only={en_theme - fr_theme}, FR-only={fr_theme - en_theme}"
+74
View File
@@ -74,6 +74,80 @@ class TestIsRelevant:
assert handler._is_relevant("/vault/Makefile") is True
# ═══════════════════════════════════════════════════════════════════
# Network-mount detection (NFS/SMB → polling watcher required)
# ═══════════════════════════════════════════════════════════════════
class TestNetworkMountDetection:
MOUNTS = [
"overlay / overlay rw 0 0",
"server:/export/NFS/OBSIDIAN_DOC /vaults/Obsidian_IT nfs4 rw 0 0",
"server:/export/home/bruno /vaults/bruno nfs4 rw 0 0",
"dev/sda1 /data ext4 rw 0 0",
"srv:/share /mnt/smb cifs rw 0 0",
]
def test_nfs_mount_detected(self):
from backend.watcher import find_mount_fstype
ft = find_mount_fstype("/vaults/Obsidian_IT/note.md", self.MOUNTS)
assert ft == "nfs4"
def test_nested_nfs_mount(self):
from backend.watcher import find_mount_fstype
ft = find_mount_fstype("/vaults/bruno/sub/dir", self.MOUNTS)
assert ft == "nfs4"
def test_smb_mount_detected(self):
from backend.watcher import find_mount_fstype
ft = find_mount_fstype("/mnt/smb/file.md", self.MOUNTS)
assert ft == "cifs"
def test_local_fs_not_network(self):
from backend.watcher import find_mount_fstype
ft = find_mount_fstype("/data/file.md", self.MOUNTS)
assert ft == "ext4"
def test_unmatched_path_returns_empty(self):
from backend.watcher import find_mount_fstype
assert find_mount_fstype("/nowhere/file.md", self.MOUNTS) == ""
def test_longest_prefix_wins(self):
from backend.watcher import find_mount_fstype
lines = self.MOUNTS + ["tmpfs /vaults/Obsidian_IT/tmp tmpfs rw 0 0"]
assert find_mount_fstype("/vaults/Obsidian_IT/tmp/x", lines) == "tmpfs"
assert find_mount_fstype("/vaults/Obsidian_IT/other", lines) == "nfs4"
def test_escaped_space_in_mount_point(self):
from backend.watcher import find_mount_fstype
lines = ["srv:/x /vaults/My\\040Vault nfs rw 0 0"]
assert find_mount_fstype("/vaults/My Vault/a.md", lines) == "nfs"
def test_is_network_mount_false_on_windows(self, monkeypatch):
import backend.watcher as w
monkeypatch.setattr(w.os, "name", "nt")
assert w.is_network_mount("/vaults/x") is False
def test_watch_vault_uses_polling_for_network_mount(self, monkeypatch):
"""_watch_vault must pick PollingObserver when is_network_mount is True."""
import asyncio
from unittest.mock import MagicMock
import backend.watcher as w
watcher = w.VaultWatcher(on_file_change=MagicMock())
monkeypatch.setattr(w, "is_network_mount", lambda p: True)
mock_poll = MagicMock()
monkeypatch.setattr(w, "PollingObserver", mock_poll)
with tempfile.TemporaryDirectory() as tmpdir:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
watcher._watch_vault("NetVault", tmpdir, loop)
)
mock_poll.assert_called_once()
assert "NetVault" in watcher.observers
# ═══════════════════════════════════════════════════════════════════
# VaultWatcher (unit tests with mocks)
# ═══════════════════════════════════════════════════════════════════
+339
View File
@@ -0,0 +1,339 @@
# tests/test_webauthn.py
# WebAuthn MFA tests (ROADMAP #64).
# Uses a virtual authenticator (EC P-256, packed-free 'none' attestation, raw
# CBOR via cbor2) to exercise the real verification path end-to-end.
from __future__ import annotations
import hashlib
import json
import os
import shutil
import struct
import tempfile
from pathlib import Path
import cbor2
import pytest
from cryptography.hazmat.primitives.asymmetric import ec
from webauthn.helpers import bytes_to_base64url
def _b64url(data: bytes) -> str:
return bytes_to_base64url(data)
class VirtualAuthenticator:
"""Minimal WebAuthn authenticator: generates a P-256 key, produces
'none'-attestation registration responses and ES256 assertion responses."""
RP_ID = "localhost"
ORIGIN = "http://localhost"
def __init__(self):
self.key = ec.generate_private_key(ec.SECP256R1())
self.credential_id = os.urandom(32)
self.sign_count = 0
# ── COSE public key (ES256) ──
def _cose_key(self) -> bytes:
pub = self.key.public_key().public_numbers()
x = pub.x.to_bytes(32, "big")
y = pub.y.to_bytes(32, "big")
return cbor2.dumps({1: 2, 3: -7, -1: 1, -2: x, -3: y}, canonical=True)
def _rp_id_hash(self) -> bytes:
return hashlib.sha256(self.RP_ID.encode()).digest()
def _client_data(self, typ: str, challenge_b64: str) -> bytes:
return json.dumps({
"type": typ,
"challenge": challenge_b64,
"origin": self.ORIGIN,
"crossOrigin": False,
}).encode()
def make_registration(self, options: dict) -> dict:
challenge = options["challenge"]
auth_data = bytearray(self._rp_id_hash())
auth_data += bytes([0x41]) # UP + AT
auth_data += struct.pack(">I", 0)
aaguid = b"\x00" * 16
auth_data += aaguid
auth_data += struct.pack(">H", len(self.credential_id))
auth_data += self.credential_id
auth_data += self._cose_key()
attestation_object = cbor2.dumps(
{"fmt": "none", "attStmt": {}, "authData": bytes(auth_data)},
canonical=True,
)
client_data = self._client_data("webauthn.create", challenge)
return {
"id": _b64url(self.credential_id),
"rawId": _b64url(self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": _b64url(client_data),
"attestationObject": _b64url(attestation_object),
},
}
def make_assertion(self, options: dict) -> dict:
challenge = options["challenge"]
auth_data = bytearray(self._rp_id_hash())
auth_data += bytes([0x01]) # UP
self.sign_count += 1
auth_data += struct.pack(">I", self.sign_count)
client_data = self._client_data("webauthn.get", challenge)
signed = bytes(auth_data) + hashlib.sha256(client_data).digest()
# WebAuthn spec: ECDSA signatures are ASN.1 DER (not raw r||s like U2F)
der_sig = self.key.sign(signed, ec.ECDSA(hashes.SHA256()))
return {
"id": _b64url(self.credential_id),
"rawId": _b64url(self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": _b64url(client_data),
"authenticatorData": _b64url(bytes(auth_data)),
"signature": _b64url(der_sig),
"userHandle": "",
},
}
from cryptography.hazmat.primitives import hashes # noqa: E402 (used above)
# ── Unit tests: webauthn_mfa module ──────────────────────────────────
class TestWebauthnModule:
def test_rp_config_defaults(self, monkeypatch):
import backend.auth.webauthn_mfa as w
monkeypatch.delenv("OBSIGATE_WEBAUTHN_RP_ID", raising=False)
assert w.rp_id() == "localhost"
monkeypatch.setenv("OBSIGATE_WEBAUTHN_RP_ID", "obs.example.com")
assert w.rp_id() == "obs.example.com"
def test_challenge_is_single_use(self):
import backend.auth.webauthn_mfa as w
w._pending.clear()
ch = w._store_challenge("u1:register")
assert isinstance(ch, bytes) and len(ch) == 32
assert w._take_challenge("u1:register") == ch
assert w._take_challenge("u1:register") is None # popped
def test_take_challenge_expired(self):
import time as _t
import backend.auth.webauthn_mfa as w
w._pending.clear()
w._store_challenge("u2:register")
key = "u2:register"
ch, _ = w._pending[key]
w._pending[key] = (ch, _t.time() - 1)
assert w._take_challenge(key) is None
def test_full_registration_and_authentication_roundtrip(self):
from webauthn import (
generate_authentication_options,
generate_registration_options,
options_to_json,
)
import backend.auth.webauthn_mfa as w
w._pending.clear()
auth = VirtualAuthenticator()
reg_opts = generate_registration_options(
rp_id="localhost", rp_name="ObsiGate",
user_name="alice", user_id=b"1", user_display_name="Alice",
challenge=w._store_challenge("alice:register"),
)
cred = auth.make_registration(json.loads(options_to_json(reg_opts)))
verified = w.complete_registration("alice", cred)
assert verified["credential_id"] == cred["id"]
assert verified["public_key"]
auth_opts = generate_authentication_options(
rp_id="localhost",
challenge=w._store_challenge("alice:login"),
)
assertion = auth.make_assertion(json.loads(options_to_json(auth_opts)))
new_count = w.complete_authentication(
"alice", assertion,
{"public_key": verified["public_key"], "sign_count": 0})
assert new_count == 1
# ── Integration: API endpoints ───────────────────────────────────────
@pytest.fixture
def wa_client(monkeypatch):
"""Auth-enabled client with a user, WebAuthn RP configured for localhost."""
tmp = Path(tempfile.mkdtemp())
data_dir = tmp / "data"
data_dir.mkdir()
from backend.auth.password import hash_password
users = {"version": 1, "users": {"testuser": {
"id": "t-1", "username": "testuser", "display_name": "Test",
"password_hash": hash_password("TestPass123!"), "role": "admin",
"vaults": ["*"], "active": True,
}}}
(data_dir / "users.json").write_text(json.dumps(users), encoding="utf-8")
monkeypatch.setattr("backend.auth.user_store.USERS_FILE", data_dir / "users.json")
monkeypatch.setenv("OBSIGATE_WEBAUTHN_RP_ID", "localhost")
monkeypatch.setenv("OBSIGATE_WEBAUTHN_ORIGINS", "http://localhost")
os.environ["VAULT_1_NAME"] = "TestVault"
os.environ["VAULT_1_PATH"] = os.path.abspath("test-vault")
os.environ["OBSIGATE_AUTH_ENABLED"] = "true"
os.environ["OBSIGATE_WATCHER_ENABLED"] = "false"
import backend.main
backend.main._load_config = lambda: {"watcher_enabled": False}
from fastapi.testclient import TestClient
client = TestClient(backend.main.app)
yield client
client.close()
shutil.rmtree(str(tmp), ignore_errors=True)
for k in ["VAULT_1_NAME", "VAULT_1_PATH", "OBSIGATE_AUTH_ENABLED",
"OBSIGATE_WATCHER_ENABLED"]:
os.environ.pop(k, None)
def _login_headers(client):
r = client.post("/api/auth/login",
json={"username": "testuser", "password": "TestPass123!"})
token = r.json()["access_token"]
return {"Authorization": f"Bearer {token}"}
class TestWebauthnApi:
def test_register_requires_auth(self, wa_client):
r = wa_client.post("/api/auth/mfa/webauthn/register/options")
assert r.status_code == 401
def test_registration_flow_enables_mfa(self, wa_client):
headers = _login_headers(wa_client)
r = wa_client.post("/api/auth/mfa/webauthn/register/options", headers=headers)
assert r.status_code == 200
options = r.json()["options"]
auth = VirtualAuthenticator()
cred = auth.make_registration(options)
r2 = wa_client.post("/api/auth/mfa/webauthn/register", headers=headers,
json={"credential": cred, "label": "YubiKey 5"})
assert r2.status_code == 200, r2.text
body = r2.json()
assert body["mfa_enabled"] is True
assert len(body["recovery_codes"]) == 8
assert body["credentials"][0]["label"] == "YubiKey 5"
# status reflects webauthn
r3 = wa_client.get("/api/auth/mfa/status", headers=headers)
st = r3.json()
assert st["mfa_enabled"] is True
assert st["webauthn_credentials"] == 1
assert st["totp_enabled"] is False
def test_login_with_webauthn_assertion(self, wa_client):
headers = _login_headers(wa_client)
options = wa_client.post("/api/auth/mfa/webauthn/register/options",
headers=headers).json()["options"]
auth = VirtualAuthenticator()
cred = auth.make_registration(options)
wa_client.post("/api/auth/mfa/webauthn/register", headers=headers,
json={"credential": cred, "label": "Key"})
# Fresh login → MFA required via webauthn
r = wa_client.post("/api/auth/login",
json={"username": "testuser", "password": "TestPass123!"})
body = r.json()
assert body["mfa_required"] is True
assert body["mfa_method"] == "webauthn"
opts_r = wa_client.post("/api/auth/mfa/webauthn/options",
json={"username": "testuser"})
assert opts_r.status_code == 200
assertion = auth.make_assertion(opts_r.json()["options"])
v = wa_client.post("/api/auth/mfa/webauthn/verify",
json={"username": "testuser", "credential": assertion})
assert v.status_code == 200, v.text
assert "access_token" in v.json()
def test_login_with_wrong_credential_rejected(self, wa_client):
headers = _login_headers(wa_client)
options = wa_client.post("/api/auth/mfa/webauthn/register/options",
headers=headers).json()["options"]
auth = VirtualAuthenticator()
cred = auth.make_registration(options)
wa_client.post("/api/auth/mfa/webauthn/register", headers=headers,
json={"credential": cred, "label": "Key"})
opts_r = wa_client.post("/api/auth/mfa/webauthn/options",
json={"username": "testuser"})
# Impostor key signs the challenge
impostor = VirtualAuthenticator()
bad = impostor.make_assertion(opts_r.json()["options"])
v = wa_client.post("/api/auth/mfa/webauthn/verify",
json={"username": "testuser", "credential": bad})
assert v.status_code == 401
def test_challenge_single_use(self, wa_client):
headers = _login_headers(wa_client)
options = wa_client.post("/api/auth/mfa/webauthn/register/options",
headers=headers).json()["options"]
auth = VirtualAuthenticator()
cred = auth.make_registration(options)
wa_client.post("/api/auth/mfa/webauthn/register", headers=headers,
json={"credential": cred, "label": "K"})
opts_r = wa_client.post("/api/auth/mfa/webauthn/options",
json={"username": "testuser"})
assertion = auth.make_assertion(opts_r.json()["options"])
v1 = wa_client.post("/api/auth/mfa/webauthn/verify",
json={"username": "testuser", "credential": assertion})
assert v1.status_code == 200
# replay the same credential → challenge already consumed
v2 = wa_client.post("/api/auth/mfa/webauthn/verify",
json={"username": "testuser", "credential": assertion})
assert v2.status_code == 401
def test_login_options_enumeration_safe(self, wa_client):
# Unknown user / no MFA -> always 200 with totp fallback, no 404/400 leak
r = wa_client.post("/api/auth/mfa/webauthn/options",
json={"username": "ghost-user"})
assert r.status_code == 200
assert r.json() == {"mfa_method": "totp", "options": None}
def test_remove_key_disables_mfa(self, wa_client):
headers = _login_headers(wa_client)
options = wa_client.post("/api/auth/mfa/webauthn/register/options",
headers=headers).json()["options"]
auth = VirtualAuthenticator()
cred = auth.make_registration(options)
wa_client.post("/api/auth/mfa/webauthn/register", headers=headers,
json={"credential": cred, "label": "K"})
cred_id = cred["id"]
r = wa_client.post("/api/auth/mfa/webauthn/credentials/remove",
headers=headers,
json={"credential_id": cred_id, "password": "wrong"})
assert r.status_code == 400
r2 = wa_client.post("/api/auth/mfa/webauthn/credentials/remove",
headers=headers,
json={"credential_id": cred_id, "password": "TestPass123!"})
assert r2.status_code == 200
st = wa_client.get("/api/auth/mfa/status", headers=headers).json()
assert st["mfa_enabled"] is False