Compare commits

...
15 Commits
Author SHA1 Message Date
bruno 8264e7ffae fix: conserver plein ecran et panneau metadonnees dans la visionneuse d'images (sidebar droite) + lanceur E2E Windows BUG-072
CI / lint (push) Successful in 2m1s
CI / security (push) Successful in 1m23s
CI / test (push) Successful in 4m27s
CI / build (push) Successful in 1m19s
CI / e2e (push) Successful in 17m45s
2026-09-23 13:43:47 -04:00
bruno 80852374a8 fix: positionnement lecteur media (mobile/desktop) et drag libre de la mini-video #110
CI / lint (push) Successful in 2m0s
CI / security (push) Successful in 1m22s
CI / test (push) Successful in 4m36s
CI / build (push) Successful in 1m18s
CI / e2e (push) Successful in 13m7s
2026-09-23 11:42:23 -04:00
bruno e3c6789776 feat: lecteur média persistant Now Playing (dock audio, mini-vidéo PiP, Media Session, mobile) #110
CI / lint (push) Successful in 2m5s
CI / security (push) Successful in 1m23s
CI / test (push) Successful in 3m57s
CI / build (push) Successful in 1m18s
CI / e2e (push) Successful in 13m18s
2026-09-23 10:41:15 -04:00
bruno e2417cb5ab feat: support audio & vidéo — lecteurs HTML5 intégrés #109
CI / lint (push) Successful in 1m58s
CI / security (push) Successful in 1m22s
CI / test (push) Successful in 4m32s
CI / build (push) Successful in 2m6s
CI / e2e (push) Successful in 12m57s
2026-09-23 09:14:34 -04:00
bruno eccbf7474e feat: support complet des images — arborescence, visionneuse, indexation #108
CI / lint (push) Successful in 1m57s
CI / security (push) Successful in 1m22s
CI / test (push) Successful in 4m32s
CI / build (push) Failing after 1m16s
CI / e2e (push) Skipped
2026-09-23 07:47:04 -04:00
bruno 69cee4d93a docs(roadmap): add #108 image support and #109 audio/video players
CI / lint (push) Successful in 1m55s
CI / security (push) Successful in 1m25s
CI / test (push) Successful in 4m33s
CI / build (push) Successful in 1m15s
CI / e2e (push) Successful in 11m59s
- #108: images parity — tree + indexing (never read bytes into TF-IDF),
  fix broken standalone viewer (img src points to JSON /raw instead of
  /api/image), zoom/pan viewer, thumbnails, SVG sandbox hardening
- #109: audio/video — HTML5 players, shared media streaming endpoint
  with Range/206 (extract helper from existing pdf/stream), codec
  fallback UI, PWA/mobile notes
- Update effort summary (8 items, ~28-43 days)
2026-09-22 23:28:55 -04:00
bruno 705f755b6b docs: guides d'utilisation, capture reelle et README ameliores
CI / lint (push) Successful in 2m2s
CI / security (push) Successful in 1m25s
CI / test (push) Successful in 4m13s
CI / build (push) Successful in 1m16s
CI / e2e (push) Successful in 11m56s
2026-09-22 22:40:51 -04:00
bruno 8ad8eaac71 test: spec E2E mobile pour la page Configurations BUG-071
CI / lint (push) Successful in 1m54s
CI / security (push) Successful in 1m21s
CI / test (push) Successful in 3m58s
CI / build (push) Failing after 1m22s
CI / e2e (push) Skipped
2026-09-22 22:03:42 -04:00
bruno dd9224e685 fix: page Configurations inutilisable en mode mobile BUG-071
CI / lint (push) Successful in 1m57s
CI / security (push) Successful in 1m20s
CI / test (push) Successful in 4m20s
CI / build (push) Successful in 1m20s
CI / e2e (push) Successful in 11m51s
2026-09-22 21:24:56 -04:00
bruno aeb7516445 fix: activation WebAuthn impossible BUG-070 (rp_id/origines derives requete, challenges multiples)
CI / lint (push) Successful in 1m59s
CI / security (push) Successful in 1m35s
CI / test (push) Successful in 4m7s
CI / build (push) Successful in 1m16s
CI / e2e (push) Successful in 12m12s
2026-09-22 20:54:01 -04:00
bruno bca0fdd941 fix: login 2FA bloque sans erreur BUG-069 (challenge montait dans .login-box inexistant -> .login-card + erreur visible)
CI / lint (push) Successful in 1m56s
CI / security (push) Successful in 1m20s
CI / test (push) Successful in 4m17s
CI / build (push) Successful in 1m16s
CI / e2e (push) Successful in 12m35s
2026-09-22 20:38:37 -04:00
bruno 60da957f13 fix: section Securite du compte incomplete BUG-068 (boutons theme, QR local, mot de passe, recovery WebAuthn)
CI / lint (push) Successful in 2m25s
CI / security (push) Successful in 1m20s
CI / test (push) Successful in 3m43s
CI / build (push) Successful in 2m9s
CI / e2e (push) Successful in 12m7s
2026-09-22 20:07:25 -04:00
bruno f621620593 feat: optimisation globale des performances #86 (scan differentiel, excalidraw differe, garde-fou replace; inverted index/PDF lazy/caps regex deja livres via BUG-033/040/025)
CI / lint (push) Successful in 1m54s
CI / security (push) Successful in 1m22s
CI / test (push) Successful in 4m23s
CI / build (push) Successful in 1m17s
CI / e2e (push) Successful in 12m9s
2026-09-22 19:04:26 -04:00
bruno eff74cabe0 feat: #107 configuration - gestion des clés API & MCP (création/révocation, expiration 1j/1mois/6mois/1an/sans fin, une clé pour API REST + serveur MCP, dernière utilisation, store sans secret persisté; fix révocation longue durée) + script token MCP
CI / lint (push) Successful in 1m58s
CI / security (push) Successful in 1m32s
CI / test (push) Successful in 4m0s
CI / build (push) Successful in 1m15s
CI / e2e (push) Successful in 12m9s
2026-09-22 14:48:51 -04:00
bruno 6f0a6f7fd8 chore(fixtures): enrichit les vaults de test (frontmatter complet, types fichiers pour vues/aper/us, dossiers avec accents+espaces, scripts dupliques, images/logs) + purge residus e2e-diagram
CI / lint (push) Successful in 1m55s
CI / security (push) Successful in 1m20s
CI / test (push) Successful in 3m43s
CI / build (push) Successful in 1m16s
CI / e2e (push) Successful in 11m44s
2026-09-22 13:42:49 -04:00
113 changed files with 10590 additions and 2468 deletions
+5 -2
View File
@@ -16,7 +16,7 @@ OBSIGATE_ADMIN_PASSWORD=chab30
# OBSIGATE_SECURE_COOKIES=false
# Tokens TTL en secondes
# OBSIGATE_ACCESS_TOKEN_TTL=900
# OBSIGATE_ACCESS_TOKEN_TTL=31536000000 # 1000 ans
# OBSIGATE_REFRESH_TOKEN_TTL=604800
# Rate limiting
@@ -51,7 +51,10 @@ OBSIGATE_ADMIN_PASSWORD=chab30
# 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
# WebAuthn / MFA (ROADMAP #64) — par défaut rp_id/origines sont dérivés de la
# requête (hôte exact, port inclus) : rien à configurer en accès direct.
# À renseigner uniquement pour un accès via reverse-proxy sous un autre nom
# (avec OBSIGATE_TRUST_PROXY=true pour X-Forwarded-Host/Proto) :
# OBSIGATE_WEBAUTHN_RP_ID=obsigate.example.com
# OBSIGATE_WEBAUTHN_RP_NAME=ObsiGate
# OBSIGATE_WEBAUTHN_ORIGINS=https://obsigate.example.com
+1
View File
@@ -40,6 +40,7 @@ jobs:
node tests/frontend/unit.test.mjs
node tests/frontend/pdf-viewer.test.mjs
node tests/frontend/forge-completion.test.mjs
node tests/frontend/config-mobile.test.mjs
- name: Frontend JSDOM tests (PaneManager + Excalidraw + Plugins + AI + SW + Collab + Mobile + Semantic + Desktop + Inline edition)
run: |
+6 -1
View File
@@ -44,9 +44,13 @@ node tests/frontend/unit.test.mjs
# Tests JSDOM : node_modules dans tests/frontend/ (npm install là-bas si absent), ex :
node tests/frontend/pane-manager.test.mjs
# E2E (si UI touchée, ~5 min) : reproduit le job CI e2e (port 2029, auth désactivée)
# E2E (si UI touchée, ~10 min) : reproduit le job CI e2e (port 2029, auth désactivée)
npm run test:e2e # prérequis : uv, Node >= 20, npx playwright install chromium
bash scripts/run-e2e-local.sh -g "nom du test" # filtre / --headed
# Windows sans bash exploitable (WSL HS, git-bash bloqué par App Control) :
npm run test:e2e:ps # équivalent PowerShell, mêmes conditions que le CI
pwsh -File scripts/run-e2e-local.ps1 -PlaywrightArgs @('-g','nom du test')
```
- Un seul test backend : `.\.venv\Scripts\python.exe -m pytest tests/test_search.py -q`.
@@ -91,6 +95,7 @@ bash scripts/run-e2e-local.sh -g "nom du test" # filtre / --headed
| Travail à venir + index | `docs/ROADMAP.md` |
| Historique des versions | `CHANGELOG.md` |
| Conception par feature | `docs/features/<slug>.md` |
| Guides d'utilisation | `docs/GUIDES/` |
| Archive du complété | `docs/archive/COMPLETED_v1-v2.md` |
| Bugs / TODO | `docs/ISSUES_TODOLIST.md` |
| Build & releases | `docs/DEVELOPMENT_AND_RELEASES.md` |
+278 -1
View File
@@ -6,7 +6,7 @@ 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 à venir sont listés dans la section
> [Unreleased](#unreleased). La dernière version livrée est **2.14.0**.
> [Unreleased](#unreleased). La dernière version livrée est **2.19.2**.
---
@@ -14,6 +14,283 @@ et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [2.19.2] — 2026-09-23
### Ajouté
- **Lanceur E2E Windows/PowerShell** : `scripts/run-e2e-local.ps1` (+ script npm
`test:e2e:ps`) reproduit localement le job CI `e2e` (uvicorn natif, auth
désactivée, fixtures TestVault/TestDir, port 2029, projet `chromium-desktop`)
sans dépendre de `bash` — indispensable sur les postes Windows où WSL ne
démarre pas et où git-bash est bloqué par une politique de contrôle
d'application. Le script `bash` reste la référence pour la CI/Linux.
### Corrigé
- **BUG-072 — visionneuse d'images** : le plein écran (lightbox) et le panneau
« Métadonnées » sont désormais **conservés lors de la navigation** entre images
(flèches ←/→ et clic sur la pellicule) ; auparavant chaque changement d'image
recréait la visionneuse et perdait ces états. Le panneau de métadonnées s'affiche
maintenant en **barre latérale à droite de l'image** (au lieu d'une bande sous la
pellicule) et reste visible en plein écran.
---
## [2.19.1] — 2026-09-23
### Corrigé
- **#110 — lisibilité et positionnement du lecteur média** : en mode mobile, la
barre audio passe en grille (barre de progression pleine largeur sur sa propre
ligne) et les actions secondaires (précédent/suivant/agrandir/volume) sont
masquées pour éviter tout chevauchement ; le volume est aussi masqué sur les
écrans intermédiaires en desktop, et `overflow: hidden` empêche le débordement
hors de la pilule. La mini-fenêtre vidéo n'est plus ré-aimantée sur les bords :
elle se déplace et se redimensionne **librement** (position absolue mémorisée,
centre autorisé), le glisser fonctionnant désormais depuis n'importe quel point
de la fenêtre (boutons/curseurs/poignée exclus, seuil de 4 px pour préserver
les contrôles natifs de la vidéo).
---
## [2.19.0] — 2026-09-23
### Ajouté
- **#110 — Lecteur média persistant « Now Playing »** : les fichiers audio et
vidéo continuent de jouer pendant la navigation grâce à un contrôleur global
`frontend/js/now-playing.js` qui possède **un seul** élément `<audio>`/`<video>`
téléporté entre la vue inline (onglet/panneau) et un dock flottant
(`<body>`), sans interruption de lecture. Dock desktop : pilule verre dépoli
(artwork, titre, voûte, play/pause, précédent/suivant, barre de progression,
volume, retour au média, agrandir, fermer). Mini-fenêtre vidéo flottante
déplaçable/redimensionnable avec aimantation aux coins et bouton
Picture-in-Picture natif. Mode mobile : mini-player fixé au-dessus de la barre
d'outils (safe-area `viewport-fit=cover`). Intégration **Media Session** (écran
verrouillé, touches matérielles, Windows SMTC), panneau étendu façon « Now
Playing », lecture auto du média suivant/précédent du dossier, reprise après
rechargement, notification quand l'onglet est fermé pendant la lecture. Fiche :
[docs/features/media-viewers-109.md](docs/features/media-viewers-109.md) (§ Now
Playing, #110).
---
## [2.18.0] — 2026-09-23
### Ajouté
- **#109 — Support audio & vidéo (lecteurs HTML5 intégrés)** : les fichiers audio
(`.mp3 .m4a .aac .wav .ogg .oga .opus .flac`) et vidéo (`.mp4 .webm .mov .m4v`)
apparaissent désormais dans l'arborescence et l'index (nom/taille/date
uniquement, contenu jamais lu, intégrés à `SUPPORTED_EXTENSIONS` via
`media_types.py`). Nouvel endpoint `GET /api/media/{vault}?path=…` avec support
HTTP `Range` / `206 Partial Content` (`Content-Range`, `Accept-Ranges`, `416`
sur plage invalide, `413` au-delà de `OBSIGATE_MEDIA_MAX_INLINE_MB`, défaut
500 Mo) — le helper Range de `pdf/stream` a été extrait en
`_stream_file_with_range()` et est partagé. `api_file_view()` expose
`is_audio`/`is_video`/`stream_url`/`media_mime` avant toute lecture texte.
Frontend : lecteur audio dédié (artwork, durée via `loadedmetadata`) et lecteur
vidéo (`playsinline`, scène noire letterboxée), icônes Lucide `audio-lines` /
`video`, pause à la réinitialisation de la vue, repli téléchargement si le codec
n'est pas lisible ou le fichier trop volumineux. Les médias sont exclus du
contexte textuel BooksLM et du cache hors-ligne du service worker. Fiche :
[docs/features/media-viewers-109.md](docs/features/media-viewers-109.md).
---
## [2.17.0] — 2026-09-23
### Ajouté
- **#108 — Support complet des images (arborescence, visionneuse, indexation)** :
les images (`.png .jpg .jpeg .gif .svg .webp .bmp .ico`) apparaissent désormais
dans l'arborescence et l'index comme les autres fichiers — nom/taille/date
uniquement, jamais les octets (contenu indexé vide, TF-IDF préservé). Nouveau
module partagé `backend/media_types.py` (extensions + MIME, socle réutilisé par
#109). Visionneuse dédiée : zoom molette 0,1×–8×, pan au glisser, double-clic
pour réinitialiser, boutons +/−/reset et badge de zoom, navigation ←/→ entre
les images du dossier avec pellicule de miniatures, panneau métadonnées
(dimensions, taille, type, chemin, date), lightbox plein écran, « Ouvrir
l'original » et téléchargement. Endpoint `GET /api/media/{vault}/thumb`
(miniature WebP 256 px, cache disque invalidé par mtime, repli sur l'original
pour le SVG, `pillow>=10.0`). Filtre `ext:png`/`ext:jpg` opérationnel ;
compteurs d'images séparés dans `/api/dashboard` (`image_count`/`total_images`).
Fiche : [docs/features/image-support.md](docs/features/image-support.md).
### Corrigé
- **#108-B1 — Affichage isolé d'une image** : le `<img>` généré par
`api_file_view()` pointait vers `/api/file/{vault}/raw` (qui renvoie du JSON)
au lieu de `/api/image/{vault}` (octets + MIME correct). Corrigé côté backend
et dans `viewer.js` (bouton Plein écran), avec encodage d'URL des chemins.
- **#108-B3 — XSS via SVG** : `/api/image` (et le repli miniatures) pose
`Content-Security-Policy: sandbox` sur les SVG ouverts directement, pour
empêcher l'exécution du JavaScript embarqué ; le middleware n'écrase plus une
politique stricte posée par une route.
---
## [2.16.6] — 2026-09-22
### Ajouté
- **Guides d'utilisation `docs/GUIDES/`** : nouvel index + 10 guides FR
(prise en main, recherche/PDF/Excalidraw, assistant IA & Forge,
collaboration temps réel, PWA & hors-ligne, API REST, serveur MCP,
authentification & sécurité, déploiement Docker, desktop Tauri). Le guide MCP
est déplacé dans `docs/GUIDES/MCP.md` ; `docs/MCP_GUIDE.md` devient une page
de redirection.
### Modifié
- **README.md / README.fr.md** : capture d'écran réelle de l'application en tête
(remplace l'illustration ASCII) ; un emoji sur chaque entrée de la table des
matières ; nouvelle section « Guides » avec liens vers `docs/GUIDES/` ;
renvois vers les guides depuis les sections API, Recherche, Sécurité, Desktop
et Collaboration.
---
## [2.16.5] — 2026-09-22
### Corrigé
- **BUG-071 (complément) - spec E2E mobile de la page Configurations** :
`tests/e2e/config-mobile.spec.js` (nouveau, projet `chromium-mobile`,
ignoré en `chromium-desktop` comme `mobile-editor.spec.js`) : le hamburger
révèle le sommaire, le choix d'une section y défile + lien actif + repli
auto, aucun débordement horizontal à 393px. Vérifié en local contre
l'instance de test (port 2029, auth désactivée) : 3/3.
---
## [2.16.4] — 2026-09-22
### Corrigé
- **BUG-071 - Page « Configurations » inutilisable en mode mobile** : trois
causes. (1) Le sommaire (`#config-nav`) partageait la règle `.help-nav`
qui le masque sous 768px, mais — contrairement au Guide — la modale
n'avait aucun bouton pour l'afficher : aucun moyen d'atteindre une section.
Nouvel hamburger `#config-hamburger` dans l'en-tête (même traitement
`.help-hamburger` que le Guide, libellé traduit `config.toc_toggle`
FR/EN). (2) Les liens du sommaire étaient des ancres brutes sans JS :
`config.js` les intercepte désormais (défilement doux vers la section dans
la modale, lien actif, repli automatique du sommaire sur mobile, réinit à
l'ouverture). (3) Les grilles 2 colonnes (fournisseur/modèle IA, clé/modèle
par fournisseur), les rangées d'ajout à largeurs fixes (jetons, webhooks)
et les lignes webhook/jeton/partage en flex une ligne débordaient en
360px : bloc CSS mobile scopé `#config-modal` (1 colonne, wrap, largeurs
inline neutralisées, cibles tactiles 44px, sommaire plafonné à 46vh).
`data-i18n-attr` accepte désormais plusieurs paires `attr:clé` séparées
par `;` (titre + aria-label traduits). Tests :
`tests/frontend/config-mobile.test.mjs` (nouveau, 11 — hamburger, i18n,
câblage JS, CSS mobile, garde-fou ancres mortes façon BUG-067),
enregistré dans le CI.
---
## [2.16.3] — 2026-09-22
### Corrigé
- **BUG-070 - Activation clé physique WebAuthn impossible (« Validation du
credential WebAuthn échouée »)** : deux causes. (1) Les valeurs par défaut
(`rp_id localhost`, origines `http://localhost` sans port) rejetaient toute
URL réelle — logs : `Unexpected client data origin "http://localhost:2020",
expected one of ['http://localhost']`. `rp_id`/origines sont désormais
dérivés de la requête (hôte exact, port inclus ; `X-Forwarded-Host/Proto`
si `OBSIGATE_TRUST_PROXY=true`), la config explicite restant prioritaire
(`backend/auth/webauthn_mfa.py::resolve_relying_party`, appliqué aux 4
endpoints d'enregistrement et de login). (2) Challenge à usage unique
fragile au double-clic/retry (`challenge was not expected`) : les 5
derniers challenges sont conservés et la vérification accepte le challenge
correspondant à la cérémonie en cours. `.env.example` documente le nouveau
comportement. Vérifié au navigateur avec authentificateur virtuel
(Playwright CDP, instance Docker) : enregistrement 200 + clé listée, puis
clé de test retirée. Tests : `tests/test_webauthn.py` (+8 : résolution RP,
forwarded, retry, roundtrip sans config).
---
## [2.16.2] — 2026-09-22
### Corrigé
- **BUG-069 - Login 2FA bloqué sans erreur** : après user+mot de passe corrects
sur un compte avec 2FA, la page de login restait affichée sans erreur et le
challenge MFA n'apparaissait jamais. Cause : `showMfaChallenge`
(`frontend/js/auth.js`) montait le challenge dans `.login-box`, inexistant
dans `index.html` (marquage réel : `#login-screen > .login-card`) →
`return` silencieux. Correctif : montage dans `.login-card` (repli
`#login-screen`) + erreur visible (`mfa.challenge_unavailable`, FR/EN) au
lieu d'un retour silencieux si le point de montage manque. Vérifié de bout
en bout au navigateur (Playwright, instance Docker) : challenge affiché,
code erroné → erreur, code valide → connecté. Tests :
`tests/frontend/mfa-settings.test.mjs` (+2 contrôles d'ancrage DOM).
---
## [2.16.1] — 2026-09-22
### Corrigé
- **BUG-068 - Configuration : section « 🔒 Sécurité du compte » inachevée** :
boutons `config-btn-primary` / `config-btn-danger` définis depuis les
variables du thème (`frontend/style.css`) ; QR code TOTP généré en local par
le backend (`POST /api/auth/mfa/totp/setup` → `qr_data_url`, SVG `data:`
via `segno`, `backend/requirements.txt`) au lieu de l'image tierce bloquée
par la CSP (`img-src 'self' data: blob:`, secret TOTP exposé) ; codes de
récupération affichés aussi à la première activation WebAuthn ; carte
« Mot de passe » (changement via `POST /api/auth/change-password`) et
échappement des libellés de clés WebAuthn. Tests :
`tests/test_mfa.py::test_mfa_setup_returns_local_qr_data_url`,
`tests/frontend/mfa-settings.test.mjs` (nouveau, 9 contrôles).
---
## [2.16.0] — 2026-09-22
### Modifié
- **#86 - Optimisation globale des performances (phase 3)** : ferme les deux derniers
points de la phase 3 (recherche via inverted index, PDF lazy et caps regex déjà livrés
via BUG-033/BUG-040/BUG-025). Scan **différentiel** : `_scan_vault` réutilise les
entrées inchangées (`size` + `modified`) d'un snapshot précédent — seuls `os.walk` +
`stat` tournent à chaque rebuild (`build_index`, `reload_single_vault`). Extraction
**excalidraw différée** : le scan ne lit plus les `.excalidraw` / `.excalidraw.md`
(flag `excalidraw_text_pending`), `enrich_pdf_texts()` extrait leur texte après index
comme pour les PDF. Garde-fou `MAX_REPLACE_FILE_BYTES` (5 Mio) sur `replace_in_files`.
Tests : `tests/test_perf_phase3.py` (9). Voir
[docs/features/perf-phase3-86.md](./docs/features/perf-phase3-86.md).
---
## [2.15.0] — 2026-09-22
### Ajouté
- **#107 - Configuration : gestion des clés API & MCP** — nouvelle section
« 🔑 Clés API & MCP » dans le panneau de configuration : création, liste
(créée / expire / dernière utilisation) et révocation de jetons longue
durée utilisables aussi bien sur l'API REST que sur le serveur MCP
(`/mcp`) — un seul et même jeton Bearer pour les deux. Choix
d'expiration à la création : 1 jour, 1 mois, 6 mois, 1 an, sans fin.
Le secret n'est affiché qu'une fois (jamais persisté en clair,
`data/api_tokens.json` ne contient que les métadonnées) ; révocation
immédiate des deux côtés, plafond 50 clés par utilisateur, isolation
par utilisateur, audit `config_change`. Corrigé au passage : le store
de révocation (`revoked_tokens.json`) bornait toute entrée à 7 jours —
un jeton longue durée révoqué « reprenait vie » après purge ; il est
désormais calé sur l'expiration réelle du jeton. Voir
[docs/features/api-mcp-tokens-107.md](./docs/features/api-mcp-tokens-107.md).
---
## [2.14.1] — 2026-09-22
---
## [2.14.0] — 2026-09-19
### Ajouté
+88 -40
View File
@@ -1,61 +1,75 @@
# ObsiGate
> **Version française** — ce document est le miroir synchronisé de [README.md](README.md) (référence complète). Dernière synchronisation : juin 2026.
> **Version française** — ce document est le miroir synchronisé de [README.md](README.md) (référence complète). Dernière synchronisation : septembre 2026.
**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.
[![Version](https://img.shields.io/badge/Version-2.14.0-blue.svg)]()
[![Version](https://img.shields.io/badge/Version-2.19.2-blue.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![Python](https://img.shields.io/badge/Python-3.11+-green.svg)](https://www.python.org/)
[![CI/CD](https://img.shields.io/badge/CI%2FCD-Gitea_Actions-green.svg)](https://git.dracodev.net/Projets/ObsiGate/actions)
```
┌─────────────────────────────────────────────────────────┐
│ [🔍 Recherche...] [☀/🌙 Thème] ObsiGate │
├──────────────┬──────────────────────────────────────────┤
│ SIDEBAR │ CONTENT AREA │
│ ▼ Recettes │ 📄 Titre du fichier │
│ 📁 Soupes │ Tags: #recette #rapide │
│ 📄 Pizza │ [Contenu Markdown rendu] │
│ ▼ IT │ │
│ 📁 Docker │ │
│ Tags Cloud │ │
└──────────────┴──────────────────────────────────────────┘
```
![Interface ObsiGate — tableau de bord Statistiques avec vaults, tags et raccourcis clavier](docs/images/obsigate-home.png)
> Interface web d'ObsiGate : sidebar multi-vault, recherche globale, statistiques et raccourcis.
---
## 📚 Guides
Les **guides d'utilisation** pas à pas se trouvent dans [`docs/GUIDES/`](docs/GUIDES/) :
| Guide | Contenu |
|---|---|
| 🚀 [Prise en main](docs/GUIDES/PRISE_EN_MAIN.md) | Premier lancement, interface, navigation, vaults, raccourcis |
| 🔍 [Recherche, PDF & Excalidraw](docs/GUIDES/RECHERCHE_PDF_EXCALIDRAW.md) | Syntaxe de requête, recherche sémantique, lecteur PDF, diagrammes |
| 🤖 [Assistant IA & Forge](docs/GUIDES/ASSISTANT_IA_FORGE.md) | Fournisseurs, éditeur IA, BooksLM, Forge, commandes `@` / `/` |
| 📝 [Édition & collaboration](docs/GUIDES/COLLABORATION.md) | Édition simultanée, curseurs distants, persistance |
| 📱 [PWA & hors-ligne](docs/GUIDES/PWA_HORS_LIGNE.md) | Installation, cache hors-ligne, file de synchro, notifications |
| 🔌 [API REST](docs/GUIDES/API_REST.md) | Authentification, clés API, endpoints, exemples `curl`, SSE |
| 🧩 [Serveur MCP](docs/GUIDES/MCP.md) | Brancher Claude Desktop, Cursor, Cline… sur vos vaults |
| 🔒 [Authentification & sécurité](docs/GUIDES/AUTHENTIFICATION_SECURITE.md) | Utilisateurs, MFA, permissions par vault, durcissement |
| 🐳 [Déploiement Docker](docs/GUIDES/DEPLOIEMENT_DOCKER.md) | `docker-compose`, volumes, reverse proxy, mises à jour |
| 🖥️ [Desktop (Tauri)](docs/GUIDES/DESKTOP.md) | Installation, premier lancement, build depuis les sources, dépannage |
> Index complet : [`docs/GUIDES/README.md`](docs/GUIDES/README.md).
---
## 📋 Table des matières
- [Fonctionnalités](#fonctionnalites)
- [Prérequis](#prerequis)
- [Installation rapide](#installation-rapide)
- [Configuration détaillée](#configuration-detaillee)
- [Variables d'environnement](#variables-denvironnement)
- [🔒 Authentification](#authentification)
- [Ajouter une nouvelle vault](#ajouter-une-nouvelle-vault)
- [Build & déploiement avec build.sh](#build-deploiement-avec-buildsh)
- [Rendu d'images Obsidian](#rendu-dimages-obsidian)
- [Desktop (Tauri) — Application native](#desktop-tauri-application-native)
- [Utilisation](#utilisation)
- [API](#api)
- [Recherche avancée](#recherche-avancee)
- [Dépannage](#depannage)
- [Performance](#performance)
- [Sécurité](#securite)
- [Stack technique](#stack-technique)
- [Architecture](#architecture)
- [Développement](#developpement)
- [Licence](#licence)
- [Changelog](#changelog)
- ✨ [Fonctionnalités](#fonctionnalites)
- 📚 [Guides](#guides)
- 🚀 [Prérequis](#prerequis)
- ⚡ [Installation rapide](#installation-rapide)
- ⚙️ [Configuration détaillée](#configuration-detaillee)
- 🌍 [Variables d'environnement](#variables-denvironnement)
- 🔒 [Authentification](#authentification)
- ➕ [Ajouter une nouvelle vault](#ajouter-une-nouvelle-vault)
- 🔨 [Build & déploiement avec build.sh](#build-deploiement-avec-buildsh)
- 🖼️ [Rendu d'images Obsidian](#rendu-dimages-obsidian)
- 🖥️ [Desktop (Tauri) — Application native](#desktop-tauri-application-native)
- 📖 [Utilisation](#utilisation)
- 👥 [Collaboration temps réel](#collaboration-temps-reel)
- 🔌 [API](#api)
- 🔍 [Recherche avancée](#recherche-avancee)
- 🔧 [Dépannage](#depannage)
- ⚡ [Performance](#performance)
- 🛡️ [Sécurité](#securite)
- 🏗️ [Stack technique](#stack-technique)
- 🏠 [Architecture](#architecture)
- 📝 [Développement](#developpement)
- 📄 [Licence](#licence)
- 🤝 [Support](#support)
- 📝 [Changelog](#changelog)
---
## ✨ Fonctionnalités
- **🤖 AI Editor intégré** — Éditeur CodeMirror 6 avec toolbar IA : amélioration, correction, traduction, génération, réécriture personnalisée, toolbox (liste, tableau, frontmatter, canvas) — multi-provider DeepSeek/OpenRouter/Gemini
- **🧩 Serveur MCP & agent IA** — Serveur Model Context Protocol intégré (`/mcp`) et assistant avec function calling : lisez, cherchez et modifiez vos vaults depuis Claude Desktop, Cursor… avec confirmations two-step, permissions par vault, rate limiting et redaction des secrets ([guide](docs/MCP_GUIDE.md))
- **🧩 Serveur MCP & agent IA** — Serveur Model Context Protocol intégré (`/mcp`) et assistant avec function calling : lisez, cherchez et modifiez vos vaults depuis Claude Desktop, Cursor… avec confirmations two-step, permissions par vault, rate limiting et redaction des secrets ([guide](docs/GUIDES/MCP.md))
- **👥 Collaboration temps réel** — Édition simultanée d'un même document (Yjs/CRDT) : curseurs distants colorés, indicateur de présence, fusion sans conflit, reconnexion automatique et persistance serveur ([détail](docs/features/collaboration.md))
- **📖 Guide d'utilisation intégré** — Aide complète en FR/EN accessible depuis le menu Options : interface, navigation, recherche, fichiers, IA, sécurité, API & intégrations (OpenAPI, MCP), hors-ligne, collaboration, desktop, plus une section **Architecture** avec diagramme Mermaid ; téléchargeable en **Markdown** et **PDF** dans la langue courante ([détail](docs/features/guide-coverage-105.md))
- **📱 Éditeur mobile natif** — Édition optimisée pour le tactile : barre d'outils Markdown flottante (gras/italique/code/liste/lien), bouton « Coller » persistant (contournement iOS), zoom par pincement et hauteur ajustable, raccourcis swipe (liens entrants / table des matières) et mode lecture plein écran avec navigation entre fichiers ([détail](docs/features/mobile-editor.md))
@@ -69,6 +83,7 @@
- **🏷️ Tag cloud** : Filtrage par tags extraits des frontmatters YAML
- **🔗 Wikilinks** : Les `[[liens internes]]` Obsidian sont cliquables
- **🖼️ Images Obsidian** : Support complet des syntaxes d'images Obsidian avec résolution intelligente
- **🎬 Audio & vidéo** : Lecteurs HTML5 intégrés (`.mp3 .wav .flac .mp4 .webm`…) avec streaming HTTP Range (lecture, déplacement, plein écran) et **lecture persistante** (mini-lecteur flottant / mini-fenêtre vidéo, retour au média ou arrêt à tout moment, contrôles écran verrouillé via Media Session), repli téléchargement si le format n'est pas lisible par le navigateur
- **🎨 Diagrammes Excalidraw** : Visualiseur/éditeur natif des fichiers `.excalidraw` et `.excalidraw.md` (iframe sandboxée, auto-save, thème clair/sombre, texte des diagrammes indexé pour la recherche)
- **🎨 Syntax highlight** : Coloration syntaxique des blocs de code
- **🌓 Thème clair/sombre** : Toggle persisté en localStorage
@@ -282,6 +297,7 @@ Un compte **admin** connecté voit une icône 🛡️ dans le header : liste, cr
| `OBSIGATE_WEBHOOK_ALLOW_HTTP` | Autoriser les webhooks non HTTPS | `false` |
| `OBSIGATE_WEBHOOK_ALLOW_PRIVATE` | Autoriser les webhooks vers des adresses privées/boucle | `false` |
| `OBSIGATE_PDF_MAX_SIZE_MB` | Taille max des PDF extraits (text indexation) | `50` |
| `OBSIGATE_MEDIA_MAX_INLINE_MB` | Taille max pour la lecture audio/vidéo intégrée (au-delà : téléchargement) | `500` |
| `OBSIGATE_PDF_EXTRACT_TIMEOUT` | Timeout extraction PDF (secondes) | `30` |
| `OBSIGATE_TAVILY_API_KEY` / `OBSIGATE_BRAVE_API_KEY` / `OBSIGATE_SERPAPI_API_KEY` / `OBSIGATE_EXA_API_KEY` | Fournisseurs de recherche web à clé (essayés avant SearXNG) | — |
| `OBSIGATE_WEB_PROVIDERS` | Ordre des fournisseurs de recherche (ex. `brave,searxng`) | — |
@@ -392,6 +408,18 @@ ObsiGate supporte **toutes les syntaxes d'images Obsidian** avec résolution int
6. Index de démarrage (match le plus proche)
7. Fallback : placeholder stylisé `[image not found: filename.ext]`
### Visionneuse & arborescence
Les images sont de plein droit des fichiers du vault : elles apparaissent dans
l'arborescence, sont indexées (nom + métadonnées, **jamais les octets**) et
s'ouvrent dans une **visionneuse dédiée** — zoom molette 0,1×–8×, pan au
glisser, double-clic pour réinitialiser, navigation ←/→ entre les images du
dossier (avec pellicule de miniatures WebP), panneau de métadonnées, lightbox
plein écran, ouverture de l'original et téléchargement. Le filtre de recherche
`ext:png`/`ext:jpg` est disponible. Formats décodables : PNG, JPEG, GIF, WebP,
BMP, ICO, SVG (SVG servi avec une politique CSP `sandbox`). **HEIC/HEIF**
(iPhone) n'est pas décodable par les navigateurs et n'est pas pris en charge.
### Configuration
```yaml
@@ -412,6 +440,8 @@ curl -X POST http://localhost:2020/api/attachments/rescan/MonVault
## 🖥️ Desktop (Tauri) — Application native
> 📖 Guide complet : [Desktop (Tauri)](docs/GUIDES/DESKTOP.md)
ObsiGate Desktop est une application native construite avec [Tauri](https://tauri.app/) (Rust + webview système). Elle embarque le backend Python et le frontend dans un exécutable standalone — zéro Docker, zéro ligne de commande.
> 🚧 **Version 2.0.0 — binaires en cours de stabilisation.** Pour l'instant, le build depuis les sources est recommandé.
@@ -571,6 +601,8 @@ Cycle de vie : Tauri spawn le backend Python → health check → splash de dém
## 👥 Collaboration temps réel
> 📖 Guide complet : [Édition & collaboration](docs/GUIDES/COLLABORATION.md)
Plusieurs utilisateurs peuvent éditer le même document markdown simultanément (façon Google Docs) :
- **Fusion sans conflit** grâce à Yjs (CRDT) : deux personnes peuvent taper au même endroit, aucune
@@ -590,6 +622,8 @@ fenêtres) pour voir la collaboration en action.
## 🔌 API
> 📖 Guide complet : [API REST](docs/GUIDES/API_REST.md) · [Serveur MCP](docs/GUIDES/MCP.md)
ObsiGate expose une API REST complète :
| Endpoint | Description | Méthode | Auth |
@@ -617,6 +651,7 @@ ObsiGate expose une API REST complète :
| `/api/events` | Flux SSE temps réel | GET | Oui |
| `/api/vaults/add` / `/api/vaults/{name}` | Gestion dynamique des vaults | POST/DELETE | Admin |
| `/api/image/{vault}?path=` | Servir une image | GET | Oui |
| `/api/media/{vault}/thumb?path=&size=` | Miniature WebP (cache disque) | GET | Oui |
| `/api/config` | Lire / écrire la configuration | GET/POST | Oui/Admin |
| `/api/diagnostics` | Statistiques index et mémoire | GET | Admin |
@@ -637,6 +672,8 @@ curl "http://localhost:2020/api/file/Recettes?path=pizza.md"
## 🔍 Recherche avancée
> 📖 Guide complet : [Recherche, PDF & Excalidraw](docs/GUIDES/RECHERCHE_PDF_EXCALIDRAW.md)
### Syntaxe de requête
| Opérateur | Description | Exemple |
@@ -758,6 +795,8 @@ Configurables via l'interface (Settings) ou l'API `/api/config`.
## 🛡️ Sécurité
> 📖 Guide complet : [Authentification & sécurité](docs/GUIDES/AUTHENTIFICATION_SECURITE.md)
- **Path traversal** : tous les endpoints fichier valident que le chemin résolu reste dans la vault
- **Rate limiting** : 10 tentatives de login max par IP sur 15 minutes + lockout par compte (5 tentatives)
- **Audit log** : écritures/suppressions/config journalisées dans `data/audit.log` (JSON lines, rotation 10 MB)
@@ -833,7 +872,7 @@ Configurables via l'interface (Settings) ou l'API `/api/config`.
| Validation des imports frontend | `node tests/frontend/validate-imports.mjs` | `lint` |
| Tests unitaires frontend | `node tests/frontend/unit.test.mjs` | `lint` |
| Tests backend | `pytest tests/ -q` | `test` |
| **E2E Playwright** | `npm run test:e2e` (~5 min) | `e2e` |
| **E2E Playwright** | `npm run test:e2e` (~10 min) | `e2e` |
#### Tests E2E locaux (`npm run test:e2e`)
@@ -856,6 +895,15 @@ bash scripts/run-e2e-local.sh --headed # navigateur visible
bash scripts/run-e2e-local.sh -g "reset panes" # filtre sur un test
```
Sous Windows, si `bash` n'est pas exploitable (WSL indisponible, git-bash
bloqué par une politique de contrôle d'application), utiliser le lanceur
PowerShell équivalent :
```powershell
npm run test:e2e:ps
pwsh -File scripts/run-e2e-local.ps1 -PlaywrightArgs @('-g','reset panes')
```
La suite doit se terminer sur **tous les tests passant** (60 actuellement),
sans échec ni dépendance aux retries. En cas d'échec : corriger et relancer
localement jusqu'à 100 %, puis seulement commiter.
@@ -927,8 +975,8 @@ Ce projet est sous licence **MIT** — voir le fichier [LICENSE](LICENSE) pour l
## 📝 Changelog
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.14.0).
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.19.2).
---
*Projet : ObsiGate | Version : 2.14.0 | Dernière mise à jour : Juin 2026*
*Projet : ObsiGate | Version : 2.19.2 | Dernière mise à jour : Septembre 2026*
+89 -35
View File
@@ -2,53 +2,73 @@
**Ultra-light web gateway for your Obsidian vaults** — Access, browse, and search all your Obsidian notes from any device via a modern, responsive web interface.
[![Version](https://img.shields.io/badge/Version-2.14.0-blue.svg)]()
[![Version](https://img.shields.io/badge/Version-2.19.2-blue.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![Python](https://img.shields.io/badge/Python-3.11+-green.svg)](https://www.python.org/)
[![CI/CD](https://img.shields.io/badge/CI%2FCD-Gitea_Actions-green.svg)](https://git.dracodev.net/Projets/ObsiGate/actions)
```
┌─────────────────────────────────────────────────────────┐
│ [🔍 Search...] [☀/🌙 Theme] ObsiGate │
├──────────────┬──────────────────────────────────────────┤
│ SIDEBAR │ CONTENT AREA │
│ ▼ Recipes │ 📄 File Title │
│ 📁 Soups │ Tags: #recipe #quick │
│ 📄 Pizza │ [Rendered Markdown Content] │
│ ▼ IT │ │
│ 📁 Docker │ │
│ Tags Cloud │ │
└──────────────┴──────────────────────────────────────────┘
```
![ObsiGate interface — statistics dashboard with vaults, tags and keyboard shortcuts](docs/images/obsigate-home.png)
> ObsiGate web interface: multi-vault sidebar, global search, dashboard stats and shortcuts.
---
## 📚 Guides
Step-by-step **user guides** live in [`docs/GUIDES/`](docs/GUIDES/):
| Guide | What it covers |
|---|---|
| 🚀 [Getting Started](docs/GUIDES/PRISE_EN_MAIN.md) | First run, interface, navigation, vaults, shortcuts |
| 🔍 [Search, PDF & Excalidraw](docs/GUIDES/RECHERCHE_PDF_EXCALIDRAW.md) | Query syntax, semantic search, PDF viewer, diagrams |
| 🤖 [AI Assistant & Forge](docs/GUIDES/ASSISTANT_IA_FORGE.md) | Providers, AI editor, BooksLM, Forge, `@` / `/` commands |
| 📝 [Editing & Collaboration](docs/GUIDES/COLLABORATION.md) | Simultaneous editing, remote cursors, persistence |
| 📱 [PWA & Offline](docs/GUIDES/PWA_HORS_LIGNE.md) | Install as an app, offline cache, sync queue, push |
| 🔌 [REST API](docs/GUIDES/API_REST.md) | Authentication, API keys, endpoints, `curl` examples, SSE |
| 🧩 [MCP Server](docs/GUIDES/MCP.md) | Connect Claude Desktop, Cursor, Cline… to your vaults |
| 🔒 [Auth & Security](docs/GUIDES/AUTHENTIFICATION_SECURITE.md) | Users, MFA, per-vault permissions, hardening |
| 🐳 [Docker Deployment](docs/GUIDES/DEPLOIEMENT_DOCKER.md) | `docker-compose`, volumes, reverse proxy, updates |
| 🖥️ [Desktop (Tauri)](docs/GUIDES/DESKTOP.md) | Install, first run, build from source, troubleshooting |
> All guides are currently written in **French**. See the full index:
> [`docs/GUIDES/README.md`](docs/GUIDES/README.md).
---
## 📋 Table of Contents
- [Features](#features)
- [Architecture](#architecture)
- [Prerequisites](#prerequisites)
- [Quick Installation](#quick-installation)
- [Detailed Configuration](#detailed-configuration)
- [Environment Variables](#environment-variables)
- [🔒 Authentication](#authentication)
- [Adding a New Vault](#adding-a-new-vault)
- [Build & Deployment with build.sh](#build--deployment-with-buildsh)
- [Desktop (Tauri) — Native Application](#desktop-tauri--native-application)
- [Usage](#usage)
- [API](#api)
- [Performance](#performance)
- [Troubleshooting](#troubleshooting)
- [Tech Stack](#tech-stack)
- [Changelog](#changelog)
- ✨ [Features](#features)
- 📚 [Guides](#guides)
- 🚀 [Prerequisites](#prerequisites)
- ⚡ [Quick Installation](#quick-installation)
- ⚙️ [Detailed Configuration](#detailed-configuration)
- 🌍 [Environment Variables](#environment-variables)
- 🔒 [Authentication](#authentication)
- ➕ [Adding a New Vault](#adding-a-new-vault)
- 🔨 [Build & Deployment with build.sh](#build--deployment-with-buildsh)
- 🖼️ [Obsidian Image Rendering](#obsidian-image-rendering)
- 🖥️ [Desktop (Tauri) — Native Application](#desktop-tauri--native-application)
- 📖 [Usage](#usage)
- 👥 [Real-time Collaboration](#real-time-collaboration)
- 🔌 [API](#api)
- 🔍 [Advanced Search](#advanced-search)
- 🛡️ [Security](#security)
- ⚡ [Performance](#performance)
- 🔧 [Troubleshooting](#troubleshooting)
- 🏗️ [Tech Stack](#tech-stack)
- 🏠 [Architecture](#architecture)
- 📝 [Development](#development)
- 📄 [License](#license)
- 🤝 [Support](#support)
- 📝 [Changelog](#changelog)
---
## ✨ Features
- **🤖 Integrated AI Editor** — CodeMirror 6 editor with AI toolbar: improve, correct, translate, generate, custom rewrite, toolbox (list, table, frontmatter, canvas) — multi-provider DeepSeek/OpenRouter/Gemini
- **🧩 MCP Server & AI Agent** — Built-in Model Context Protocol server (`/mcp`) and tool-calling assistant: read, search and edit your vaults from Claude Desktop, Cursor… with two-step confirmations, per-vault permissions, rate limiting and secret redaction ([guide](docs/MCP_GUIDE.md))
- **🧩 MCP Server & AI Agent** — Built-in Model Context Protocol server (`/mcp`) and tool-calling assistant: read, search and edit your vaults from Claude Desktop, Cursor… with two-step confirmations, per-vault permissions, rate limiting and secret redaction ([guide](docs/GUIDES/MCP.md))
- **👥 Real-time Collaboration** — Simultaneous editing of the same document (Yjs/CRDT): colored remote cursors, presence indicator, conflict-free merge, automatic reconnection and server-side persistence ([details](docs/features/collaboration.md))
- **📖 Built-in User Guide** — Complete FR/EN help from the Options menu: interface, navigation, search, files, AI, security, API & integrations (OpenAPI, MCP), offline, collaboration, desktop, plus an **Architecture** section with a Mermaid diagram; downloadable as **Markdown** and **PDF** in the current language ([details](docs/features/guide-coverage-105.md))
- **📱 Native Mobile Editor** — Touch-optimised editing: floating Markdown toolbar (bold/italic/code/list/link), persistent Paste button (iOS workaround), pinch-zoom font & adjustable height, swipe shortcuts (backlinks / table of contents) and a full-screen reading mode with page navigation ([details](docs/features/mobile-editor.md))
@@ -62,6 +82,7 @@
- **🏷️ Tag Cloud** : Filtering by tags extracted from YAML frontmatters
- **🔗 Wikilinks** : `[[internal links]]` from Obsidian are clickable
- **🖼️ Obsidian Images** : Full support for all Obsidian image syntaxes with intelligent resolution
- **🎬 Audio & video** : Built-in HTML5 players (`.mp3 .wav .flac .mp4 .webm`…) with HTTP Range streaming (play, seek, fullscreen) and **persistent playback** (floating mini-player / mini video window, return to media or stop anytime, lock-screen controls via Media Session), falling back to download when the format is not playable in the browser
- **🎨 Excalidraw Diagrams** : Native viewer/editor for `.excalidraw` and `.excalidraw.md` files (sandboxed iframe, autosave, dark/light theme, diagram text indexed for search)
- **🎨 Syntax Highlight** : Syntax highlighting for code blocks
- **🌓 Light/Dark Theme** : Toggle persisted in localStorage
@@ -320,6 +341,7 @@ When an **admin** account is logged in, a 🛡️ icon appears in the header. Cl
| `OBSIGATE_WEBHOOK_ALLOW_HTTP` | Allow non-HTTPS webhook targets | `false` |
| `OBSIGATE_WEBHOOK_ALLOW_PRIVATE` | Allow webhooks to private/loopback addresses | `false` |
| `OBSIGATE_PDF_MAX_SIZE_MB` | Max PDF size for text extraction | `50` |
| `OBSIGATE_MEDIA_MAX_INLINE_MB` | Max size for inline audio/video playback (above: download) | `500` |
| `OBSIGATE_PDF_EXTRACT_TIMEOUT` | PDF extraction timeout (seconds) | `30` |
| `OBSIGATE_TAVILY_API_KEY` / `OBSIGATE_BRAVE_API_KEY` / `OBSIGATE_SERPAPI_API_KEY` / `OBSIGATE_EXA_API_KEY` | Keyed web-search providers (tried before SearXNG) | — |
| `OBSIGATE_WEB_PROVIDERS` | Search provider order (e.g. `brave,searxng`) | — |
@@ -496,6 +518,17 @@ ObsiGate uses 7 resolution strategies in order of priority:
6. **Startup index (closest match)** : If multiple files have the same name
7. **Fallback** : Display a styled placeholder `[image not found: filename.ext]`
### Viewer & file tree
Images are first-class vault files: they appear in the tree, are indexed (name +
metadata, **never the bytes**) and open in a **dedicated viewer** — wheel zoom
0.1×–8×, drag pan, double-click to reset, ←/→ navigation between images in the
same folder (WebP thumbnail filmstrip), metadata panel, full-screen lightbox,
open original and download. The `ext:png`/`ext:jpg` search filter is available.
Decodable formats: PNG, JPEG, GIF, WebP, BMP, ICO, SVG (SVG served with a
`sandbox` CSP). **HEIC/HEIF** (iPhone) is not decodable by browsers and is not
supported.
### Configuration
To optimize resolution, configure the attachments folder for each vault:
@@ -520,6 +553,8 @@ curl -X POST http://localhost:2020/api/attachments/rescan/MyVault
## 🖥️ Desktop (Tauri) — Native Application
> 📖 Full guide: [Desktop (Tauri)](docs/GUIDES/DESKTOP.md)
ObsiGate Desktop is a native application built with [Tauri](https://tauri.app/) (Rust + system webview). It embeds the Python backend and frontend in a standalone executable — zero Docker, zero command line.
> 🚧 **Version 2.0.0 — binaries are being stabilized.** For now, building from source is recommended.
@@ -687,6 +722,8 @@ Lifecycle: Tauri spawns the Python backend → health check → opens the webvie
## 👥 Real-time Collaboration
> 📖 Full guide: [Editing & Collaboration](docs/GUIDES/COLLABORATION.md)
Multiple users can edit the same markdown document simultaneously (Google Docs style):
- **Conflict-free merge** via Yjs (CRDT): two people can type in the same place, no change is lost.
@@ -703,6 +740,8 @@ No configuration is required: open the same file in two browsers (or two windows
## 🔌 API
> 📖 Full guide: [REST API](docs/GUIDES/API_REST.md) · [MCP Server](docs/GUIDES/MCP.md)
ObsiGate exposes a complete REST API :
| Endpoint | Description | Method | Auth |
@@ -730,6 +769,7 @@ ObsiGate exposes a complete REST API :
| `/api/events` | Real-time SSE stream | GET | Yes |
| `/api/vaults/add` / `/api/vaults/{name}` | Dynamic vault management | POST/DELETE | Admin |
| `/api/image/{vault}?path=` | Serve an image | GET | Yes |
| `/api/media/{vault}/thumb?path=&size=` | WebP thumbnail (disk cache) | GET | Yes |
| `/api/config` | Read / write configuration | GET/POST | Yes/Admin |
| `/api/diagnostics` | Index and memory statistics | GET | Admin |
@@ -763,6 +803,8 @@ curl "http://localhost:2020/api/file/Recipes?path=pizza.md"
## 🔍 Advanced Search
> 📖 Full guide: [Search, PDF & Excalidraw](docs/GUIDES/RECHERCHE_PDF_EXCALIDRAW.md)
### Query Syntax
| Operator | Description | Example |
@@ -915,6 +957,8 @@ These parameters are configurable via the interface (Settings) or the `/api/conf
## 🛡️ Security
> 📖 Full guide: [Auth & Security](docs/GUIDES/AUTHENTIFICATION_SECURITE.md)
- **Path traversal** : All file endpoints validate that the resolved path stays within the vault
- **Rate limiting** : 10 login attempts max per IP over 15 minutes + per-account lockout (5 attempts)
- **Audit log** : All writes, deletions, and config changes are logged in `data/audit.log` (JSON lines, 10 MB rotation)
@@ -998,7 +1042,7 @@ These parameters are configurable via the interface (Settings) or the `/api/conf
| Frontend import validation | `node tests/frontend/validate-imports.mjs` | `lint` |
| Frontend unit tests | `node tests/frontend/unit.test.mjs` | `lint` |
| Backend tests | `pytest tests/ -q` | `test` |
| **E2E Playwright** | `npm run test:e2e` (~5 min) | `e2e` |
| **E2E Playwright** | `npm run test:e2e` (~10 min) | `e2e` |
#### Local E2E Tests (`npm run test:e2e`)
@@ -1021,6 +1065,14 @@ bash scripts/run-e2e-local.sh --headed # visible browser
bash scripts/run-e2e-local.sh -g "reset panes" # filter on a test
```
On Windows, when `bash` is unusable (WSL unavailable, git-bash blocked by an
Application Control policy), use the equivalent PowerShell launcher:
```powershell
npm run test:e2e:ps
pwsh -File scripts/run-e2e-local.ps1 -PlaywrightArgs @('-g','reset panes')
```
The suite must end with **all tests passing** (60 currently), with no failure
or reliance on retries. In case of failure: fix and re-run locally until 100 %,
then only commit.
@@ -1070,7 +1122,9 @@ ObsiGate/
├── Dockerfile # Multi-stage, healthcheck, non-root
├── docker-compose.yml # Deployment with healthcheck and auth env vars
├── build.sh # Automated build & deployment (docker compose build + up)
└── docs/CONTRIBUTING.md # Contribution guide
└── docs/
├── GUIDES/ # User guides (getting started, API, MCP, desktop…)
└── CONTRIBUTING.md # Contribution guide
```
### Contributing
@@ -1096,8 +1150,8 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
## 📝 Changelog
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.14.0).
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.19.2).
---
*Project: ObsiGate | Version: 2.14.0 | Last updated: May 2026*
*Project: ObsiGate | Version: 2.19.2 | Last updated: September 2026*
+1 -1
View File
@@ -1 +1 @@
2.14.0
2.19.2
+2 -3
View File
@@ -4,10 +4,9 @@ import threading
from pathlib import Path
from typing import Any
logger = logging.getLogger("obsigate.attachment_indexer")
from backend.media_types import IMAGE_EXTENSIONS
# Image file extensions to index
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".ico"}
logger = logging.getLogger("obsigate.attachment_indexer")
# Global attachment index: {vault_name: {filename_lower: [absolute_path, ...]}}
attachment_index: dict[str, dict[str, list[Path]]] = {}
+175 -16
View File
@@ -7,6 +7,7 @@ import json
import logging
import os
import secrets
import threading
import time
import uuid
from pathlib import Path
@@ -23,6 +24,22 @@ ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_SECONDS = int(os.environ.get("OBSIGATE_ACCESS_TOKEN_TTL", "3600")) # default 1 hour
REFRESH_TOKEN_EXPIRE_SECONDS = int(os.environ.get("OBSIGATE_REFRESH_TOKEN_TTL", "604800")) # default 7 days
#: Persistent API/MCP access tokens (user-managed, shown in the config panel).
API_TOKENS_FILE = Path("data/api_tokens.json")
#: Accepted values for the expiry selector in the UI (1 day, 1 month, 6 months,
#: 1 year, never). "never" → no ``exp`` claim → token valid until revoked.
API_TOKEN_EXPIRY_CHOICES = {
"1d": 24 * 3600,
"30d": 30 * 24 * 3600,
"180d": 180 * 24 * 3600,
"365d": 365 * 24 * 3600,
"never": None,
}
#: Max active tokens per user (anti hoarding; revoking frees a slot).
API_TOKEN_MAX_PER_USER = 50
#: AES-GCM key derived once from the JWT secret to encrypt stored tokens.
_API_TOKEN_KEY: bytes | None = None
# In-memory revoked token set (loaded from disk on startup)
_revoked_jtis: set = set()
_revoked_loaded = False
@@ -92,43 +109,61 @@ def decode_token(token: str) -> dict | None:
# ---------------------------------------------------------------------------
# Token revocation
# ---------------------------------------------------------------------------
# The store is a dict {jti: valid_until}: the revocation record may be dropped
# once the underlying token's own expiry has passed (by then the JWT is dead
# anyway). Long-lived API/MCP tokens (see create_api_token) must therefore be
# revoked with their real expiry — a 1-year token revoked last week must not
# silently come back to life when a 7-day cleanup purges the record (BUG in
# the previous set-based store, fixed with feature #107).
_revoked_map: dict[str, int] = {}
_revoked_loaded = False
def _load_revoked():
"""Load revoked token JTIs from disk into memory (once)."""
global _revoked_loaded, _revoked_jtis
global _revoked_loaded, _revoked_map
if _revoked_loaded:
return
if REVOKED_TOKENS_FILE.exists():
try:
data = json.loads(REVOKED_TOKENS_FILE.read_text())
# Clean expired entries (older than 7 days)
# Drop entries whose underlying token has itself expired.
now = int(time.time())
_revoked_jtis = {
jti for jti, exp in data.items()
if exp > now
_revoked_map = {
jti: int(exp) for jti, exp in data.items()
if int(exp) > now
}
except Exception as e:
logger.warning(f"Failed to load revoked tokens: {e}")
_revoked_jtis = set()
_revoked_map = {}
_revoked_loaded = True
def _save_revoked():
"""Persist revoked JTIs to disk."""
"""Persist revoked JTIs to disk with their per-token expiry."""
REVOKED_TOKENS_FILE.parent.mkdir(parents=True, exist_ok=True)
# Store with expiry timestamp for cleanup
now = int(time.time())
# Keep entries for 7 days max
data = {jti: now + REFRESH_TOKEN_EXPIRE_SECONDS for jti in _revoked_jtis}
tmp = REVOKED_TOKENS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(data))
tmp.write_text(json.dumps(_revoked_map))
tmp.replace(REVOKED_TOKENS_FILE)
def revoke_token(jti: str):
"""Add a token JTI to the revocation list."""
def revoke_token(jti: str, expires_at: int | None = None):
"""Add a token JTI to the revocation list.
``expires_at`` is the revoked token's own ``exp`` (unix seconds) — the
record is kept at least that long so a long-lived API token cannot
outlive its revocation. ``None`` means the token never expires (API/MCP
"sans fin") → the record is kept forever (capped at ~100 years, the JWT
store's practical infinity). Default keeps 7 days (session tokens).
"""
_load_revoked()
_revoked_jtis.add(jti)
now = int(time.time())
if expires_at is None:
until = now + 100 * 365 * 24 * 3600
else:
until = max(int(expires_at), now + REFRESH_TOKEN_EXPIRE_SECONDS)
_revoked_map[jti] = until
_save_revoked()
logger.debug(f"Revoked token JTI: {jti[:8]}...")
@@ -136,4 +171,128 @@ def revoke_token(jti: str):
def is_token_revoked(jti: str) -> bool:
"""Check if a token JTI has been revoked."""
_load_revoked()
return jti in _revoked_jtis
return jti in _revoked_map
# ---------------------------------------------------------------------------
# API / MCP tokens (feature #107)
# ---------------------------------------------------------------------------
# Long-lived access tokens the user creates from the config panel. They are
# plain HS256 access-type JWTs (``api: true`` claim), so they authenticate
# against BOTH the REST API and the MCP endpoint (/mcp) — which share
# ``get_current_user``. The raw token is shown exactly once at creation; the
# store keeps metadata only (name, owner, expiry, last use) — no secret
# material is written to disk.
#
# File: data/api_tokens.json
# {"version": 1, "tokens": {jti: {name, username, created_at, expires_at, last_used_at}}}
_api_tokens_lock = threading.RLock()
_touch_last_write: dict[str, float] = {}
def _load_api_tokens() -> dict:
if not API_TOKENS_FILE.exists():
return {"version": 1, "tokens": {}}
try:
return json.loads(API_TOKENS_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as e:
logger.error(f"Failed to read api_tokens.json: {e}")
return {"version": 1, "tokens": {}}
def _save_api_tokens(data: dict):
API_TOKENS_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = API_TOKENS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
tmp.replace(API_TOKENS_FILE)
def create_api_token(user: dict, name: str, expiry_key: str) -> tuple[dict, str]:
"""Create a persistent API/MCP token. Returns (record, jwt_string).
``expiry_key`` must be one of API_TOKEN_EXPIRY_CHOICES; "never" omits the
``exp`` claim (valid until explicitly revoked).
"""
if expiry_key not in API_TOKEN_EXPIRY_CHOICES:
raise ValueError("Expiration invalide")
seconds = API_TOKEN_EXPIRY_CHOICES[expiry_key]
with _api_tokens_lock:
data = _load_api_tokens()
tokens = data["tokens"]
mine = sum(1 for t in tokens.values() if t["username"] == user["username"])
if mine >= API_TOKEN_MAX_PER_USER:
raise ValueError(f"Maximum {API_TOKEN_MAX_PER_USER} tokens par utilisateur")
now = int(time.time())
jti = str(uuid.uuid4())
payload = {
"sub": user["username"],
"role": user.get("role", "user"),
"vaults": user.get("vaults", []),
"jti": jti,
"iat": now,
"type": "access",
"api": True,
}
if seconds is not None:
payload["exp"] = now + seconds
token = jwt.encode(payload, get_secret_key(), algorithm=ALGORITHM)
record = {
"jti": jti,
"name": name[:64] or "API token",
"username": user["username"],
"created_at": now,
"expires_at": payload.get("exp"),
"expiry_key": expiry_key,
"last_used_at": None,
}
tokens[jti] = record
_save_api_tokens(data)
return record, token
def list_api_tokens(username: str) -> list[dict]:
"""Token metadata for one user, newest first."""
data = _load_api_tokens()
now = int(time.time())
items = [
{**t, "expired": t.get("expires_at") is not None and t["expires_at"] < now}
for t in data["tokens"].values()
if t["username"] == username
]
return sorted(items, key=lambda t: t["created_at"], reverse=True)
def delete_api_token(jti: str, username: str) -> dict:
"""Revoke and remove an API token. Raises KeyError when unknown/not owned."""
with _api_tokens_lock:
data = _load_api_tokens()
record = data["tokens"].get(jti)
if not record or record["username"] != username:
raise KeyError(jti)
# Revoke by jti so the presented JWT stops working even though it is
# stateless — kept until its natural expiry (no-expiry → forever).
revoke_token(jti, record.get("expires_at"))
del data["tokens"][jti]
_save_api_tokens(data)
return record
def maybe_touch_api_token(jti: str | None, created_or_expires: bool = False):
"""Record last usage of an API token, throttled to one disk write/hour."""
if not jti:
return
now = time.time()
if now - _touch_last_write.get(jti, 0) < 3600:
return
_touch_last_write[jti] = now
try:
with _api_tokens_lock:
data = _load_api_tokens()
record = data["tokens"].get(jti)
if record is None:
return
record["last_used_at"] = int(now)
_save_api_tokens(data)
except Exception as e: # never fail an authenticated request over stats
logger.debug(f"api_token touch failed: {e}")
+5 -1
View File
@@ -11,7 +11,7 @@ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from backend.services.net import get_client_ip
from .jwt_handler import decode_token, is_token_revoked
from .jwt_handler import decode_token, is_token_revoked, maybe_touch_api_token
from .user_store import get_user
logger = logging.getLogger("obsigate.auth.middleware")
@@ -115,6 +115,10 @@ def get_current_user(
user["_token_vaults"] = payload.get("vaults", [])
# Attach the token id for per-token rate limiting (AI tool layer).
user["_token_jti"] = payload.get("jti")
# Feature #107: track last usage of user-managed API/MCP tokens
# (throttled write — this dependency runs on both REST and /mcp paths).
if payload.get("api"):
maybe_touch_api_token(payload.get("jti"))
# BUG-030: expose the real client IP to the audit log.
user["_request_ip"] = get_client_ip(request)
return user
+97 -11
View File
@@ -17,10 +17,14 @@ from backend.services.net import get_client_ip
from .jwt_handler import (
ACCESS_TOKEN_EXPIRE_SECONDS,
API_TOKEN_EXPIRY_CHOICES,
create_access_token,
create_api_token,
create_refresh_token,
decode_token,
delete_api_token,
is_token_revoked,
list_api_tokens,
revoke_token,
)
from .mfa import (
@@ -444,7 +448,9 @@ class MfaEnableRequest(BaseModel):
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.
Returns the secret, the otpauth URI and a ready-to-display QR code
(`qr_data_url`, SVG `data:` URI — no third-party service, CSP-safe).
Does NOT enable MFA yet; call /mfa/totp/enable after first successful verify.
"""
from .user_store import update_user
@@ -454,10 +460,21 @@ async def mfa_totp_setup(current_user=Depends(require_auth)):
update_user(current_user["username"], {
"mfa_secret_pending": secret,
})
# BUG-068: the QR code is generated locally (segno, stdlib-free SVG data
# URI). The previous client-side https://api.qrserver.com image was blocked
# by the CSP (img-src 'self' data: blob:) and leaked the otpauth URI —
# including the TOTP secret — to a third party.
qr_data_url: str | None = None
try:
import segno
qr_data_url = segno.make(qr_uri).svg_data_uri(scale=5)
except Exception:
qr_data_url = None
return {
"secret": secret,
"qr_uri": qr_uri,
"otpauth_uri": qr_uri,
"qr_data_url": qr_data_url,
}
@@ -559,18 +576,25 @@ class WebauthnRemoveRequest(BaseModel):
@router.post("/mfa/webauthn/register/options")
async def mfa_webauthn_register_options(current_user=Depends(require_auth)):
async def mfa_webauthn_register_options(request: Request,
current_user=Depends(require_auth)):
"""Start WebAuthn key enrolment — returns publicKey creation options for the browser."""
from .webauthn_mfa import begin_registration
from .webauthn_mfa import begin_registration, resolve_relying_party
# BUG-070: rp_id/origins derive from the request (exact host incl. port)
# unless explicitly configured — the old localhost defaults rejected
# every real access URL ("Unexpected client data origin").
rp, _ = resolve_relying_party(request)
options = begin_registration(current_user["username"],
current_user.get("display_name", ""))
current_user.get("display_name", ""),
rp_id_override=rp)
return {"options": options}
@router.post("/mfa/webauthn/register")
async def mfa_webauthn_register(
req: WebauthnRegisterRequest,
request: Request,
current_user=Depends(require_auth),
):
"""Verify the created credential, store it, and enable MFA if not already on.
@@ -580,14 +604,17 @@ async def mfa_webauthn_register(
from datetime import datetime, timezone
from .user_store import get_user, update_user
from .webauthn_mfa import complete_registration
from .webauthn_mfa import complete_registration, resolve_relying_party
user = get_user(current_user["username"])
if user is None:
raise HTTPException(404, "Utilisateur introuvable")
rp, origins = resolve_relying_party(request)
try:
record = complete_registration(current_user["username"], req.credential,
label=req.label)
label=req.label,
rp_id_override=rp,
origins_override=origins)
except ValueError as e:
raise HTTPException(400, str(e))
except Exception as e:
@@ -666,7 +693,7 @@ async def mfa_webauthn_remove(
@router.post("/mfa/webauthn/options")
async def mfa_webauthn_login_options(body: dict = Body(...)):
async def mfa_webauthn_login_options(request: Request, 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
@@ -678,8 +705,9 @@ async def mfa_webauthn_login_options(body: dict = Body(...)):
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)
from .webauthn_mfa import begin_authentication, resolve_relying_party
rp, _ = resolve_relying_party(request)
options = begin_authentication(username, creds, rp_id_override=rp)
if options is None:
return {"mfa_method": "totp", "options": None}
return {"mfa_method": "webauthn", "options": options}
@@ -693,7 +721,7 @@ async def mfa_webauthn_verify(
):
"""Unauthenticated: verify the WebAuthn assertion and issue JWT tokens."""
from .user_store import get_user, update_user
from .webauthn_mfa import complete_authentication
from .webauthn_mfa import complete_authentication, resolve_relying_party
client_ip = _enforce_mfa_rate_limit(request, body.username)
@@ -704,13 +732,16 @@ async def mfa_webauthn_verify(
if not user.get("mfa_enabled"):
raise HTTPException(400, "MFA non activé pour cet utilisateur")
rp, origins = resolve_relying_party(request)
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)
new_count = complete_authentication(body.username, body.credential, stored,
rp_id_override=rp,
origins_override=origins)
except ValueError as e:
_record_mfa_failure(client_ip, body.username)
raise HTTPException(401, str(e))
@@ -861,3 +892,58 @@ async def delete_user_endpoint(
return {"message": f"Utilisateur '{username}' supprimé"}
except ValueError as e:
raise HTTPException(404, str(e))
# ── API / MCP tokens (feature #107) ──────────────────────────────────
# One long-lived token authenticates BOTH the REST API and the MCP
# endpoint (/mcp): the MCP server resolves the caller through the same
# get_current_user() dependency, so the same Bearer JWT works everywhere.
class CreateApiTokenRequest(BaseModel):
name: str
expiry: str # 1d | 30d | 180d | 365d | never
@router.get("/tokens")
async def list_user_tokens(current_user=Depends(require_auth)):
"""List the caller's API/MCP tokens (metadata only — the secret is never stored)."""
return {
"tokens": list_api_tokens(current_user["username"]),
"expiry_choices": list(API_TOKEN_EXPIRY_CHOICES.keys()),
}
@router.post("/tokens")
async def create_user_token(
req: CreateApiTokenRequest,
request: Request,
current_user=Depends(require_auth),
):
"""Create a long-lived API/MCP token. The raw JWT is returned ONCE."""
try:
record, token = create_api_token(current_user, req.name.strip(), req.expiry)
except ValueError as e:
raise HTTPException(400, str(e))
from backend.audit import log_config_change
log_config_change(current_user["username"],
{"action": "api_token_create", "name": record["name"],
"expiry": record["expiry_key"]}, ip=get_client_ip(request))
return {"token": token, **record}
@router.delete("/tokens/{jti}")
async def delete_user_token(
jti: str,
request: Request,
current_user=Depends(require_auth),
):
"""Revoke + delete an API/MCP token (immediate effect on API and MCP)."""
try:
record = delete_api_token(jti, current_user["username"])
except KeyError:
raise HTTPException(404, "Token introuvable")
from backend.audit import log_config_change
log_config_change(current_user["username"],
{"action": "api_token_revoke", "name": record["name"]},
ip=get_client_ip(request))
return {"message": f"Token '{record['name']}' révoqué"}
+157 -36
View File
@@ -38,8 +38,16 @@ 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]] = {}
# How many outstanding challenges to keep per key. BUG-070: a single slot made
# the flow fragile — a double-click on "add key" (or any retry) overwrote the
# pending challenge and the in-flight ceremony failed with
# "Client data challenge was not expected challenge". The verifier now accepts
# any recent challenge for the key.
MAX_PENDING_PER_KEY = 5
# In-memory pending challenges: key -> [(challenge_bytes, expires_at), ...]
# (newest last)
_pending: dict[str, list[tuple[bytes, float]]] = {}
def rp_id() -> str:
@@ -55,24 +63,100 @@ def expected_origins() -> list[str]:
return [o.strip() for o in raw.split(",") if o.strip()]
def resolve_relying_party(request: Any = None) -> tuple[str, list[str]]:
"""Resolve the WebAuthn (rp_id, expected_origins) for a ceremony.
BUG-070: the previous defaults (rp_id ``localhost``, origins
``http://localhost``) rejected every real-world access URL — any port
(``http://localhost:2020``), ``127.0.0.1``, a LAN host or a public domain
failed verification with "Unexpected client data origin".
Explicit configuration still wins: when ``OBSIGATE_WEBAUTHN_RP_ID`` /
``OBSIGATE_WEBAUTHN_ORIGINS`` are set they are used unchanged. Otherwise
the values are derived from the incoming request (exact ``Host``, port
included, since the browser origin carries non-default ports).
Behind a reverse proxy the external host/proto come from
``X-Forwarded-Host`` / ``X-Forwarded-Proto``, honored only when
``OBSIGATE_TRUST_PROXY=true`` (same rule as ``get_client_ip``).
"""
env_rp = os.environ.get("OBSIGATE_WEBAUTHN_RP_ID")
env_raw = os.environ.get("OBSIGATE_WEBAUTHN_ORIGINS")
if request is None:
return (env_rp or "localhost",
[o.strip() for o in env_raw.split(",") if o.strip()]
if env_raw else ["http://localhost"])
from backend.services.net import is_trusted_proxy
if is_trusted_proxy():
fwd_host = request.headers.get("x-forwarded-host", "")
host = fwd_host.split(",")[0].strip() or request.headers.get("host", "")
fwd_proto = request.headers.get("x-forwarded-proto", "")
scheme = fwd_proto.split(",")[0].strip() or request.url.scheme
else:
host = request.headers.get("host", "")
scheme = request.url.scheme
if not host:
url = request.url
host = url.netloc or url.hostname or ""
scheme = scheme or url.scheme or "http"
rp = env_rp or _hostname_only(host) or "localhost"
if env_raw:
origins = [o.strip() for o in env_raw.split(",") if o.strip()]
else:
origins = [f"{scheme or 'http'}://{host}"] if host else ["http://localhost"]
return rp, origins
def _hostname_only(host: str) -> str:
"""Strip the port (and IPv6 brackets) from a Host header value."""
host = host.strip()
if host.startswith("["): # [::1]:8080 or [::1]
end = host.find("]")
return host[1:end] if end > 0 else host
if host.count(":") == 1:
name, _, port = host.partition(":")
return name if port.isdigit() else host
return host
def _prune_expired() -> None:
now = time.time()
for key in [k for k, (_, exp) in _pending.items() if exp < now]:
_pending.pop(key, None)
for key in list(_pending):
remaining = [(c, exp) for c, exp in _pending[key] if exp >= now]
if remaining:
_pending[key] = remaining
else:
_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)
slot = _pending.setdefault(key, [])
slot.append((challenge, time.time() + CHALLENGE_TTL_SECONDS))
del slot[:-MAX_PENDING_PER_KEY] # keep only the most recent ones
return challenge
def _take_challenge(key: str) -> bytes | None:
"""Pop a challenge (single-use). Returns None if missing/expired."""
"""Pop the newest challenge (single-use). Returns None if missing/expired."""
_prune_expired()
entry = _pending.pop(key, None)
return entry[0] if entry else None
slot = _pending.get(key)
if not slot:
return None
challenge, _ = slot.pop()
if not slot:
_pending.pop(key, None)
return challenge
def _take_all_challenges(key: str) -> list[bytes]:
"""Pop every outstanding challenge for *key* (newest last)."""
_prune_expired()
slot = _pending.pop(key, None)
return [c for c, _ in slot] if slot else []
def clear_pending(username: str) -> None:
@@ -83,9 +167,12 @@ def clear_pending(username: str) -> None:
# ── Registration (enrol a key in settings) ─────────────────────────────
def begin_registration(username: str, display_name: str) -> dict:
def begin_registration(username: str, display_name: str,
rp_id_override: str | None = None,
origins_override: list[str] | None = None) -> dict:
_ = origins_override # origins only matter at verification time
options = generate_registration_options(
rp_id=rp_id(),
rp_id=rp_id_override or rp_id(),
rp_name=rp_name(),
user_name=username,
user_display_name=display_name or username,
@@ -98,19 +185,44 @@ def begin_registration(username: str, display_name: str) -> dict:
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")
def _verify_with_any_challenge(key: str, verify_one: Any, empty_message: str) -> Any:
"""Run *verify_one(challenge)* against every outstanding challenge.
Returns the first success; re-raises the last error when all fail.
BUG-070: lets an in-flight ceremony survive a re-requested options call
(double-click / retry) that stored a newer challenge afterwards.
"""
challenges = _take_all_challenges(key)
if not challenges:
raise ValueError(empty_message)
last_error: Exception | None = None
for challenge in challenges:
try:
return verify_one(challenge)
except Exception as e: # try the next candidate challenge
last_error = e
assert last_error is not None
raise last_error
def complete_registration(username: str, credential_json: dict[str, Any],
label: str = "", rp_id_override: str | None = None,
origins_override: list[str] | None = None) -> dict:
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(),
)
effective_rp = rp_id_override or rp_id()
effective_origins = origins_override or expected_origins()
def _verify(challenge: bytes) -> Any:
return verify_registration_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=effective_rp,
expected_origin=effective_origins,
)
verification = _verify_with_any_challenge(
f"{username}:register", _verify,
"Session d'enregistrement expirée — recommencez")
transports = credential.response.transports or []
label = (label or str(credential_json.get("label") or "")).strip() or "Security key"
@@ -126,9 +238,12 @@ def complete_registration(username: str, credential_json: dict[str, Any],
# ── Authentication (assertion at login) ────────────────────────────────
def begin_authentication(username: str, credentials: list[dict]) -> dict | None:
def begin_authentication(username: str, credentials: list[dict],
rp_id_override: str | None = None,
origins_override: list[str] | None = None) -> dict | None:
if not credentials:
return None
_ = origins_override # origins only matter at verification time
from webauthn.helpers.structs import PublicKeyCredentialDescriptor
allow = [
@@ -136,7 +251,7 @@ def begin_authentication(username: str, credentials: list[dict]) -> dict | None:
for c in credentials
]
options = generate_authentication_options(
rp_id=rp_id(),
rp_id=rp_id_override or rp_id(),
challenge=_store_challenge(f"{username}:login"),
allow_credentials=allow,
)
@@ -147,21 +262,27 @@ def complete_authentication(
username: str,
credential_json: dict[str, Any],
stored: dict,
rp_id_override: str | None = None,
origins_override: list[str] | None = None,
) -> 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")
"""Verify an assertion. Returns the new sign_count. Raises on failure."""
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)),
)
effective_rp = rp_id_override or rp_id()
effective_origins = origins_override or expected_origins()
def _verify(challenge: bytes) -> Any:
return verify_authentication_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=effective_rp,
expected_origin=effective_origins,
credential_public_key=base64url_to_bytes(stored["public_key"]),
credential_current_sign_count=int(stored.get("sign_count", 0)),
)
verification = _verify_with_any_challenge(
f"{username}:login", _verify,
"Session expirée — rechargez la page")
return int(verification.new_sign_count)
+5
View File
@@ -15,6 +15,7 @@ import time
from pathlib import Path
from typing import Any
from backend.media_types import is_media
from backend.secret_redactor import redact_file_content
logger = logging.getLogger("obsigate.bookslm")
@@ -185,6 +186,10 @@ def collect_directory_context(vault_path: Path, directory: str) -> dict[str, Any
def _file_entry(target: Path, rel_path: str, remaining: int) -> dict[str, Any] | None:
"""Read, redact and truncate a single file into a context entry."""
suffix = target.suffix.lower()
# #109-D3 — audio/video (and images) carry no extractable text; never feed
# raw bytes to the model. Images are handled separately via vision data URLs.
if is_media(suffix):
return None
try:
if suffix == ".pdf":
from backend.pdf_reader import extract_pdf_text
+146 -31
View File
@@ -11,6 +11,8 @@ from typing import Any
import frontmatter
from backend.media_types import AUDIO_EXTENSIONS, IMAGE_EXTENSIONS, VIDEO_EXTENSIONS, is_media
logger = logging.getLogger("obsigate.indexer")
# Global in-memory index
@@ -69,7 +71,7 @@ SUPPORTED_EXTENSIONS = {
".dockerfile", ".makefile", ".cmake",
".excalidraw",
".excalidraw.md",
}
} | set(IMAGE_EXTENSIONS) | set(AUDIO_EXTENSIONS) | set(VIDEO_EXTENSIONS)
# Ignored directories (configurable via OBSIGATE_IGNORED_DIRS env var)
@@ -397,31 +399,52 @@ def parse_markdown_file(raw: str) -> frontmatter.Post:
return frontmatter.Post(content)
def _scan_vault(vault_name: str, vault_path: str, vault_cfg: dict[str, Any] | None = None) -> dict[str, Any]:
def _scan_vault(
vault_name: str,
vault_path: str,
vault_cfg: dict[str, Any] | None = None,
previous_files: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Synchronously scan a single vault directory and build file index.
Walks the vault tree, reads supported files, extracts metadata
(tags, title, content preview) and stores a capped content snapshot
for in-memory full-text search.
All files and directories are indexed, including hidden files (starting with '.').
Differential scan (#86): when ``previous_files`` maps a relative path to
its previous ``file_info`` dict, entries whose ``size`` and ``modified``
timestamp are unchanged are reused verbatim (no disk read, no re-parse).
Only the cheap ``os.walk`` + ``stat`` runs on every pass; heavy content
extraction (PDF metadata excepted — always cheap) is skipped for
unchanged files. This replaces the full ``rglob`` re-read on rebuilds.
Excalidraw diagrams (#86, like PDFs since BUG-040) are deferred: the scan
only records the title and sets ``excalidraw_text_pending``; the expensive
JSON/lz-string text extraction runs in ``enrich_pdf_texts()`` after the
index is queryable.
Args:
vault_name: Display name of the vault.
vault_path: Absolute filesystem path to the vault root.
vault_cfg: Optional vault configuration dict (unused for indexing, kept for compatibility).
previous_files: Optional ``{relative_path: file_info}`` snapshot from a
previous scan used for differential reuse.
Returns:
Dict with keys ``files`` (list), ``tags`` (counter dict), ``path`` (str), ``paths`` (list).
Dict with keys ``files`` (list), ``tags`` (counter dict), ``path`` (str),
``paths`` (list) and ``reused`` (int, differential hits).
"""
vault_root = Path(vault_path)
files: list[dict[str, Any]] = []
tag_counts: dict[str, int] = {}
paths: list[dict[str, str]] = []
reused = 0
if not vault_root.exists():
logger.warning(f"Vault path does not exist: {vault_path}")
return {"files": [], "tags": {}, "path": vault_path, "paths": []}
return {"files": [], "tags": {}, "path": vault_path, "paths": [], "reused": 0}
root_resolved = vault_root.resolve(strict=False)
@@ -479,9 +502,37 @@ def _scan_vault(vault_name: str, vault_path: str, vault_cfg: dict[str, Any] | No
stat = fpath.stat()
modified = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
# #86 differential scan: reuse the previous entry when neither
# size nor mtime changed — skips the disk read + parse below.
if previous_files:
prev = previous_files.get(rel_path_str)
if (
prev is not None
and prev.get("size") == stat.st_size
and prev.get("modified") == modified
):
file_info = {**prev, "tags": list(prev.get("tags", []))}
files.append(file_info)
for tag in file_info.get("tags", []):
tag_counts[tag] = tag_counts.get(tag, 0) + 1
reused += 1
# The global backlink index is rebuilt on every scan,
# so re-register this file's wikilinks from its
# (cached) content instead of re-reading the disk.
if file_info.get("extension") == ".md" and file_info.get("content"):
try:
_extract_wikilinks_for_backlinks(
vault_name, file_info["path"],
file_info.get("title", ""), file_info["content"],
)
except Exception:
pass
continue
# PDF handling — special path (binary, uses pdf_reader)
tags: list[str] = []
pdf_text_pending = False
excalidraw_text_pending = False
if ext == ".pdf":
from backend.pdf_reader import extract_pdf_metadata
# BUG-040: only the (cheap) metadata is read during the
@@ -494,10 +545,20 @@ def _scan_vault(vault_name: str, vault_path: str, vault_cfg: dict[str, Any] | No
content_preview = ""
pdf_text_pending = True
elif ext == ".excalidraw" or fpath.name.lower().endswith(".excalidraw.md"):
raw = fpath.read_text(encoding="utf-8", errors="replace")
raw = extract_excalidraw_indexable(raw)
# #86: defer the expensive JSON/lz-string text extraction
# (read + decompress + element walk) to ``enrich_pdf_texts``
# so the scan stays cheap; title comes from the filename.
raw = ""
title = fpath.stem.replace(".excalidraw", "").replace("-", " ").replace("_", " ")
content_preview = raw[:200].strip()
content_preview = ""
excalidraw_text_pending = True
elif is_media(ext):
# #108 — images (and future media, #109) are binary: index
# name/size/mtime only and never read the bytes. ``content``
# stays empty so the TF-IDF index remains clean.
raw = ""
title = fpath.stem.replace("-", " ").replace("_", " ")
content_preview = ""
else:
raw = fpath.read_text(encoding="utf-8", errors="replace")
title = fpath.stem.replace("-", " ").replace("_", " ")
@@ -528,6 +589,8 @@ def _scan_vault(vault_name: str, vault_path: str, vault_cfg: dict[str, Any] | No
}
if pdf_text_pending:
file_info["pdf_text_pending"] = True
if excalidraw_text_pending:
file_info["excalidraw_text_pending"] = True
files.append(file_info)
for tag in tags:
@@ -540,28 +603,49 @@ def _scan_vault(vault_name: str, vault_path: str, vault_cfg: dict[str, Any] | No
logger.error(f"Error indexing {fpath}: {e}")
continue
logger.info(f"Vault '{vault_name}': indexed {len(files)} files, {len(paths)} paths, {len(tag_counts)} unique tags")
return {"files": files, "tags": tag_counts, "path": vault_path, "paths": paths, "config": {}}
logger.info(
f"Vault '{vault_name}': indexed {len(files)} files "
f"({reused} reused), {len(paths)} paths, {len(tag_counts)} unique tags"
)
return {"files": files, "tags": tag_counts, "path": vault_path, "paths": paths, "config": {}, "reused": reused}
def _read_excalidraw_indexable_text(file_path: Path) -> str:
"""Read an excalidraw file and return its indexable text (blocking helper).
Runs inside an executor via ``enrich_pdf_texts`` so the lz-string
decompression of large diagrams never blocks the event loop.
"""
try:
raw = file_path.read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
try:
return extract_excalidraw_indexable(raw)
except Exception: # pragma: no cover - defensive
return ""
async def enrich_pdf_texts(vault_name: str | None = None) -> int:
"""Extract text from PDFs whose extraction was deferred during the scan (BUG-040).
"""Extract text deferred during the scan: PDFs (BUG-040) + excalidraw (#86).
``_scan_vault`` only reads PDF metadata so a vault with many or large PDFs
starts serving immediately. This coroutine runs *after* the index (and the
inverted index) is ready, extracts the missing text off the event loop and
updates the in-memory entry plus the incremental index hooks.
``_scan_vault`` only reads PDF metadata and excalidraw filenames so a vault
with many or large heavy files starts serving immediately. This coroutine
runs *after* the index (and the inverted index) is ready, extracts the
missing text off the event loop and updates the in-memory entry plus the
incremental index hooks.
Args:
vault_name: Restrict the pass to a single vault; ``None`` covers every
indexed vault.
Returns:
Number of deferred PDFs whose text extraction was attempted.
Number of deferred files (PDF + excalidraw) whose text extraction was
attempted.
"""
from backend.pdf_reader import extract_pdf_text
pending: list[tuple[str, dict[str, Any], Path]] = []
pending: list[tuple[str, dict[str, Any], Path, str]] = []
with _index_lock:
for name, vault_data in index.items():
if vault_name is not None and name != vault_name:
@@ -569,32 +653,38 @@ async def enrich_pdf_texts(vault_name: str | None = None) -> int:
vault_root = Path(vault_data.get("path", ""))
for file_info in vault_data.get("files", []):
if file_info.get("pdf_text_pending"):
pending.append((name, file_info, vault_root / file_info["path"]))
pending.append((name, file_info, vault_root / file_info["path"], "pdf"))
elif file_info.get("excalidraw_text_pending"):
pending.append((name, file_info, vault_root / file_info["path"], "excalidraw"))
if not pending:
return 0
loop = asyncio.get_running_loop()
enriched = 0
for name, file_info, file_path in pending:
for name, file_info, file_path, kind in pending:
try:
raw = await loop.run_in_executor(None, extract_pdf_text, file_path, 100000)
if kind == "pdf":
raw = await loop.run_in_executor(None, extract_pdf_text, file_path, 100000)
else:
raw = await loop.run_in_executor(None, _read_excalidraw_indexable_text, file_path)
except Exception as exc: # pragma: no cover - defensive
logger.warning("PDF enrichment failed for %s: %s", file_path, exc)
logger.warning("Deferred text enrichment failed for %s: %s", file_path, exc)
raw = ""
file_info["content"] = raw[:SEARCH_CONTENT_LIMIT]
file_info["content_preview"] = raw[:200].strip()
file_info.pop("pdf_text_pending", None)
file_info.pop("excalidraw_text_pending", None)
enriched += 1
if _on_index_change:
try:
_on_index_change("add", name, file_info["path"], file_info)
except Exception as exc: # pragma: no cover - defensive
logger.warning(
"Index hook failed after PDF enrichment for %s: %s", file_path, exc
"Index hook failed after deferred enrichment for %s: %s", file_path, exc
)
logger.info("PDF enrichment: extracted text for %d deferred PDF(s)", enriched)
logger.info("Deferred text enrichment: extracted text for %d file(s)", enriched)
return enriched
@@ -603,16 +693,24 @@ async def build_index(progress_callback=None) -> None:
Runs vault scans concurrently, inserting them incrementally into the global index.
Notifies progress via the provided callback.
#86 differential rebuild: the previous per-vault ``{path: file_info}``
snapshots are captured before the clear and handed to ``_scan_vault`` so
unchanged files (same size + mtime) are reused without disk re-reads.
"""
global index, vault_config
vault_config.clear()
vault_config.update(load_vault_config())
# Note: vault_settings are now only used for UI display preferences (hideHiddenFiles)
# Indexing always includes all files regardless of settings
global _index_generation
with _index_lock:
previous_snapshot: dict[str, dict[str, dict[str, Any]]] = {
name: {f["path"]: f for f in vdata.get("files", [])}
for name, vdata in index.items()
}
index.clear()
_file_lookup.clear()
path_index.clear()
@@ -631,8 +729,13 @@ async def build_index(progress_callback=None) -> None:
loop = asyncio.get_event_loop()
async def _process_vault(name: str, config: dict[str, Any]):
import functools
vault_path = config["path"]
vault_data = await loop.run_in_executor(None, _scan_vault, name, vault_path, config)
scan = functools.partial(
_scan_vault, name, vault_path, config, previous_snapshot.get(name)
)
vault_data = await loop.run_in_executor(None, scan)
vault_data["config"] = config
# Build lookup entries for the new vault
@@ -695,7 +798,7 @@ async def reload_index() -> dict[str, Any]:
Dict mapping vault names to their file/tag counts.
"""
await build_index()
# BUG-040: complete the deferred PDF extraction for the rebuilt index.
# BUG-040/#86: complete the deferred PDF + excalidraw extraction.
await enrich_pdf_texts()
stats = {}
for name, data in index.items():
@@ -724,14 +827,22 @@ async def reload_single_vault(vault_name: str) -> dict[str, Any]:
raise ValueError(f"Vault '{vault_name}' not found in configuration")
config = vault_config[vault_name]
# #86 differential rescan: snapshot this vault's entries before removal so
# unchanged files are reused without disk re-reads.
with _index_lock:
_previous = {f["path"]: f for f in index.get(vault_name, {}).get("files", [])}
# Remove old vault data from index structures
await remove_vault_from_index(vault_name)
# Re-add the vault with updated configuration
import functools
vault_path = config["path"]
loop = asyncio.get_event_loop()
vault_data = await loop.run_in_executor(None, _scan_vault, vault_name, vault_path, config)
scan = functools.partial(_scan_vault, vault_name, vault_path, config, _previous)
vault_data = await loop.run_in_executor(None, scan)
vault_data["config"] = config
# Build lookup entries for the vault
@@ -761,7 +872,7 @@ async def reload_single_vault(vault_name: str) -> dict[str, Any]:
from backend.attachment_indexer import build_attachment_index
await build_attachment_index({vault_name: config})
# BUG-040: complete the deferred PDF extraction for this vault.
# BUG-040/#86: complete the deferred PDF + excalidraw extraction.
await enrich_pdf_texts(vault_name)
stats = {"file_count": len(vault_data["files"]), "tag_count": len(vault_data["tags"])}
@@ -832,6 +943,10 @@ def _index_single_file_sync(vault_name: str, vault_path: str, file_path: str, va
raw = extract_excalidraw_indexable(raw)
title = fpath.stem.replace(".excalidraw", "").replace("-", " ").replace("_", " ")
content_preview = raw[:200].strip()
elif is_media(ext):
# #108 — binary media: metadata only, never read the bytes.
raw = ""
content_preview = ""
else:
raw = fpath.read_text(encoding="utf-8", errors="replace")
content_preview = raw[:200].strip()
+262 -60
View File
@@ -2,7 +2,6 @@ import asyncio
import html as html_mod
import json as _json
import logging
import mimetypes
import os
import re
import secrets
@@ -16,6 +15,7 @@ from datetime import datetime, timezone
from functools import partial
from pathlib import Path
from typing import Any
from urllib.parse import quote
import frontmatter
import mistune
@@ -52,6 +52,8 @@ from backend.indexer import (
remove_vault_from_index,
update_single_file,
)
from backend.media_thumbs import generate_thumbnail, is_decodable
from backend.media_types import IMAGE_EXTENSIONS, is_audio, is_image, is_video, media_mime_type
from backend.openapi_docs import (
API_DESCRIPTION,
TAGS_METADATA,
@@ -203,6 +205,11 @@ class FileContentResponse(BaseModel):
size_bytes: int | None = Field(default=None, description="File size in bytes (for unsupported files)")
is_pdf: bool | None = Field(default=None, description="True for PDF files")
is_image: bool | None = Field(default=None, description="True for image files")
is_audio: bool | None = Field(default=None, description="True for audio files (HTML5 <audio>, roadmap #109)")
is_video: bool | None = Field(default=None, description="True for video files (HTML5 <video>, roadmap #109)")
media_too_large: bool | None = Field(default=None, description="True when audio/video exceeds the inline streaming limit")
stream_url: str | None = Field(default=None, description="Byte-range streaming URL under /api/media (audio/video)")
media_mime: str | None = Field(default=None, description="MIME type for audio/video files")
is_csv: bool | None = Field(default=None, description="True for CSV files")
is_json: bool | None = Field(default=None, description="True for JSON files")
is_excalidraw: bool | None = Field(default=None, description="True for Excalidraw diagram files")
@@ -699,20 +706,23 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' blob: https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://cdn.jsdelivr.net https://static.cloudflareinsights.com; "
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com https://cdn.jsdelivr.net https://esm.sh; "
"img-src 'self' data: blob:; "
"connect-src 'self' blob: https://esm.sh https://unpkg.com https://cdnjs.cloudflare.com https://fonts.googleapis.com https://fonts.gstatic.com https://cdn.jsdelivr.net; "
"font-src 'self' data: https://fonts.gstatic.com https://esm.sh; "
"worker-src 'self' blob:; "
"frame-src 'self' blob:; "
"object-src 'none'; "
"base-uri 'self'; "
"form-action 'self'; "
"frame-ancestors 'self';"
)
# A route may set a stricter per-response policy (e.g. ``sandbox`` for
# standalone SVG, #108-B3); keep it instead of overwriting it.
if "Content-Security-Policy" not in response.headers:
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' blob: https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://cdn.jsdelivr.net https://static.cloudflareinsights.com; "
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com https://cdn.jsdelivr.net https://esm.sh; "
"img-src 'self' data: blob:; "
"connect-src 'self' blob: https://esm.sh https://unpkg.com https://cdnjs.cloudflare.com https://fonts.googleapis.com https://fonts.gstatic.com https://cdn.jsdelivr.net; "
"font-src 'self' data: https://fonts.gstatic.com https://esm.sh; "
"worker-src 'self' blob:; "
"frame-src 'self' blob:; "
"object-src 'none'; "
"base-uri 'self'; "
"form-action 'self'; "
"frame-ancestors 'self';"
)
# Static assets are NOT content-hashed, so they must revalidate:
# ``immutable``/long max-age made Cloudflare and mobile browsers serve
# a stale build for a year (the service worker cache compounded it).
@@ -1032,6 +1042,27 @@ def _content_disposition(disposition: str, filename: str) -> str:
return f"{disposition}; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(filename)}"
def _media_max_inline_bytes() -> int:
"""Maximum size (bytes) for inline audio/video playback (roadmap #109-A3).
Configurable via ``OBSIGATE_MEDIA_MAX_INLINE_MB`` (default 500 MB). Files
above the limit are not streamed in the viewer (the UI falls back to the
download button), which keeps a single uvicorn worker from being pinned by
multi-gigabyte media. Invalid or non-positive values fall back to default.
"""
default_mb = 500
raw = os.environ.get("OBSIGATE_MEDIA_MAX_INLINE_MB", "").strip()
if not raw:
return default_mb * 1024 * 1024
try:
mb = float(raw)
except ValueError:
return default_mb * 1024 * 1024
if mb <= 0:
return default_mb * 1024 * 1024
return int(mb * 1024 * 1024)
def _resolve_safe_path(vault_root: Path, relative_path: str | None) -> Path:
"""Resolve a relative path safely within the vault root.
@@ -2409,19 +2440,18 @@ async def api_file(vault_name: str, path: str = Query(..., description="Relative
raise HTTPException(status_code=500, detail=f"Error reading PDF: {e!s}")
# === Images: return as viewable image ===
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".ico"}
if ext in IMAGE_EXTENSIONS:
if is_image(ext):
size = file_path.stat().st_size
mime_map = {
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
".gif": "image/gif", ".svg": "image/svg+xml", ".webp": "image/webp",
".bmp": "image/bmp", ".ico": "image/x-icon",
}
mime = mime_map.get(ext, "application/octet-stream")
mime = media_mime_type(str(file_path))
# #108-B1 — the raw endpoint returns JSON (FileRawResponse), so the
# standalone <img> must point to /api/image, which serves the bytes
# with the right MIME type. Paths are URL-encoded (accents, spaces).
img_url = f"/api/image/{quote(vault_name, safe='')}?path={quote(path, safe='')}"
html = (
f'<div class="image-viewer">'
f'<img src="/api/file/{vault_name}/raw?path={path}" '
f'alt="{file_path.name}" style="max-width:100%;max-height:80vh;object-fit:contain" />'
f'<img src="{img_url}" '
f'alt="{html_mod.escape(file_path.name, quote=True)}" '
f'style="max-width:100%;max-height:80vh;object-fit:contain" />'
f'</div>'
)
return {
@@ -2439,6 +2469,61 @@ async def api_file(vault_name: str, path: str = Query(..., description="Relative
"size_bytes": size,
}
# === Audio / Video: HTML5 players streamed from /api/media (roadmap #109) ===
if is_audio(ext) or is_video(ext):
size = file_path.stat().st_size
mime = media_mime_type(str(file_path))
media_kind = "audio" if is_audio(ext) else "video"
# #109-A3 — beyond the inline limit the viewer falls back to download
# (a single uvicorn worker must not be pinned by multi-GB media).
if size > _media_max_inline_bytes():
return {
"vault": vault_name,
"path": path,
"title": file_path.name,
"tags": [],
"frontmatter": {},
"html": "",
"raw_length": size,
"extension": ext,
"is_markdown": False,
"unsupported": True,
"media_too_large": True,
"size_bytes": size,
}
# #109-A2 — byte-range endpoint: enables scrub and is required by Safari.
stream_url = f"/api/media/{quote(vault_name, safe='')}?path={quote(path, safe='')}"
if media_kind == "audio":
html = (
f'<div class="audio-viewer">'
f'<audio controls preload="metadata" src="{stream_url}"></audio>'
f'</div>'
)
else:
html = (
f'<div class="video-viewer">'
f'<video controls playsinline preload="metadata" src="{stream_url}"></video>'
f'</div>'
)
return {
"vault": vault_name,
"path": path,
"title": file_path.name,
"tags": [],
"frontmatter": {},
"html": html,
"raw_length": size,
"extension": ext,
"is_markdown": False,
"is_audio": media_kind == "audio",
"is_video": media_kind == "video",
"media_mime": mime,
"stream_url": stream_url,
"size_bytes": size,
}
try:
raw = file_path.read_text(encoding="utf-8", errors="replace")
except PermissionError as e:
@@ -2614,32 +2699,21 @@ async def api_file(vault_name: str, path: str = Query(..., description="Relative
}
@app.get("/api/file/{vault_name}/pdf/stream", response_class=FileResponse)
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.
def _stream_file_with_range(file_path: Path, request: Request, media_type: str):
"""Return a file response honouring the HTTP ``Range`` header (roadmap #109).
Supports HTTP Range requests (206 Partial Content) so browsers can
progressively render large PDFs in the native viewer.
Shared by ``pdf/stream`` and ``/api/media``: a plain :class:`FileResponse`
with ``Accept-Ranges: bytes`` when no range is requested, or a
:class:`StreamingResponse` (206 Partial Content, 64 KiB chunks) for a valid
single range. An unsatisfiable range yields ``416`` with a
``Content-Range: bytes */size`` header.
Reads are offloaded to threads so the event loop is never blocked
(ASYNC230), matching the previous inline implementation.
"""
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")
file_size = file_path.stat().st_size
range_header = request.headers.get("range")
disposition = _content_disposition("inline", file_path.name)
if range_header:
# Parse "bytes=start-end" (single range only; multi-range is not used by viewers)
@@ -2667,7 +2741,6 @@ async def api_pdf_stream(
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)
@@ -2684,18 +2757,45 @@ async def api_pdf_stream(
return StreamingResponse(
_partial(),
status_code=206,
media_type="application/pdf",
media_type=media_type,
headers={
"Content-Range": f"bytes {start}-{end}/{file_size}",
"Accept-Ranges": "bytes",
"Content-Length": str(chunk_size),
"Content-Disposition": _content_disposition("inline", file_path.name),
"Content-Disposition": disposition,
},
)
return FileResponse(str(file_path), media_type="application/pdf", headers={
return FileResponse(str(file_path), media_type=media_type, headers={
"Accept-Ranges": "bytes",
"Content-Disposition": _content_disposition("inline", file_path.name)})
"Content-Disposition": disposition})
@app.get("/api/file/{vault_name}/pdf/stream", response_class=FileResponse)
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)
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")
return _stream_file_with_range(file_path, request, "application/pdf")
@app.get("/api/file/{vault_name}/pdf/info", response_model=PdfInfoResponse)
@@ -3183,16 +3283,19 @@ async def api_image(vault_name: str, path: str = Query(..., description="Relativ
if not file_path.exists() or not file_path.is_file():
raise HTTPException(status_code=404, detail=f"Image not found: {path}")
# Determine MIME type
mime_type, _ = mimetypes.guess_type(str(file_path))
if not mime_type:
# Default to octet-stream if unknown
mime_type = "application/octet-stream"
mime_type = media_mime_type(str(file_path))
# #108-B3 — a standalone SVG opened in a tab executes its embedded JS
# (same-origin XSS). ``sandbox`` forces a unique opaque origin with no
# script execution; inside an <img> tag the header is irrelevant.
headers = {"X-Content-Type-Options": "nosniff"}
if file_path.suffix.lower() == ".svg":
headers["Content-Security-Policy"] = "sandbox"
try:
# Read and return the image file
content = file_path.read_bytes()
return Response(content=content, media_type=mime_type)
return Response(content=content, media_type=mime_type, headers=headers)
except PermissionError:
raise HTTPException(status_code=403, detail="Permission denied")
except Exception as e:
@@ -3200,6 +3303,91 @@ async def api_image(vault_name: str, path: str = Query(..., description="Relativ
raise HTTPException(status_code=500, detail=f"Error serving image: {e!s}")
@app.get("/api/media/{vault_name}", response_class=FileResponse)
async def api_media_stream(
request: Request,
vault_name: str,
path: str = Query(..., description="Relative path to audio/video file"),
current_user=Depends(require_auth),
):
"""Stream an audio/video file with HTTP Range support (roadmap #109-A2).
Serves the bytes with the correct MIME type and honours ``Range`` requests
(``206 Partial Content`` + ``Content-Range``/``Accept-Ranges``), which is
what enables scrubbing in ``<audio>``/``<video>`` and is required by Safari
for MP4. Files above ``OBSIGATE_MEDIA_MAX_INLINE_MB`` (default 500 MB) are
refused with ``413`` — the viewer falls back to the download button.
"""
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"Media not found: {path}")
ext = file_path.suffix.lower()
if not (is_audio(ext) or is_video(ext)):
raise HTTPException(status_code=400, detail="Not an audio/video file")
if file_path.stat().st_size > _media_max_inline_bytes():
raise HTTPException(status_code=413, detail="Media too large for inline streaming")
return _stream_file_with_range(file_path, request, media_mime_type(str(file_path)))
@app.get("/api/media/{vault_name}/thumb", response_class=FileResponse)
async def api_media_thumb(
vault_name: str,
path: str = Query(..., description="Relative path to image"),
size: int = Query(256, ge=32, le=1024, description="Max thumbnail edge in pixels"),
current_user=Depends(require_auth),
):
"""Serve a cached WebP thumbnail of an image (roadmap #108-C).
SVG (and any format Pillow cannot decode) falls back to the original
bytes. Generation runs in a thread and is capped at 2 s; on timeout or
failure the original is served so the UI never breaks.
"""
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"Image not found: {path}")
if not is_image(file_path.suffix.lower()):
raise HTTPException(status_code=400, detail="Not an image file")
mime_type = media_mime_type(str(file_path))
if not is_decodable(file_path):
# SVG: never let a standalone navigation execute embedded JS (#108-B3).
svg_headers = {"X-Content-Type-Options": "nosniff"}
if file_path.suffix.lower() == ".svg":
svg_headers["Content-Security-Policy"] = "sandbox"
return FileResponse(str(file_path), media_type=mime_type, headers=svg_headers)
loop = asyncio.get_running_loop()
thumb: Path | None = None
try:
thumb = await asyncio.wait_for(
loop.run_in_executor(None, generate_thumbnail, file_path, size),
timeout=2.0,
)
except Exception:
thumb = None
if thumb is not None and thumb.exists():
return FileResponse(str(thumb), media_type="image/webp")
return FileResponse(str(file_path), media_type=mime_type)
@app.post("/api/attachments/rescan/{vault_name}", response_model=AttachmentRescanResponse)
async def api_rescan_attachments(vault_name: str, current_user=Depends(require_admin)):
"""Rescan attachments for a specific vault.
@@ -4092,6 +4280,7 @@ async def api_dashboard(current_user=Depends(require_auth)):
total_files = 0
total_tags = set()
total_size = 0
total_images = 0
for vname, vdata in index.items():
if "*" not in user_vaults and vname not in user_vaults:
continue
@@ -4100,13 +4289,26 @@ async def api_dashboard(current_user=Depends(require_auth)):
total_files += fc
vtags = set()
vsize = 0
vimages = 0
for f in files:
vtags.update(f.get("tags", []))
vsize += f.get("size", 0)
if (f.get("extension") or "").lower() in IMAGE_EXTENSIONS:
vimages += 1
total_tags.update(vtags)
total_size += vsize
vault_stats.append({"name": vname, "file_count": fc, "tag_count": len(vtags), "total_size_bytes": vsize})
return {"vaults": vault_stats, "total_files": total_files, "total_tags": len(total_tags), "total_size_bytes": total_size}
total_images += vimages
vault_stats.append({
"name": vname, "file_count": fc, "tag_count": len(vtags),
"total_size_bytes": vsize, "image_count": vimages,
})
return {
"vaults": vault_stats,
"total_files": total_files,
"total_tags": len(total_tags),
"total_size_bytes": total_size,
"total_images": total_images,
}
# ---------------------------------------------------------------------------
+74
View File
@@ -0,0 +1,74 @@
"""Image thumbnail generation and disk cache (roadmap #108-C).
Thumbnails are generated on demand with Pillow and cached under
``<OBSIGATE_DATA_DIR>/.obsigate-cache/thumbs/<sha1>.webp``. The cache key
embeds the source path, mtime (ns) and size, so an edited image naturally
invalidates its stale thumbnail without any explicit cleanup.
"""
from __future__ import annotations
import hashlib
import os
from pathlib import Path
DEFAULT_THUMB_SIZE = 256
# Extensions Pillow cannot decode without extra native libraries: served as-is.
_UNDECODABLE = {".svg"}
def thumbs_cache_dir() -> Path:
"""Return (and create) the thumbnail cache directory."""
base = Path(os.environ.get("OBSIGATE_DATA_DIR", "data")) / ".obsigate-cache" / "thumbs"
base.mkdir(parents=True, exist_ok=True)
return base
def thumb_cache_path(file_path: Path, size: int) -> Path:
"""Compute the deterministic cache path for *file_path* at *size*."""
try:
st = file_path.stat()
stamp = f"{st.st_mtime_ns}:{st.st_size}"
except OSError:
stamp = "0:0"
key = hashlib.sha1(f"{file_path}:{stamp}:{size}".encode()).hexdigest()
return thumbs_cache_dir() / f"{key}.webp"
def is_decodable(file_path: Path) -> bool:
"""True when Pillow can be expected to decode *file_path*."""
return file_path.suffix.lower() not in _UNDECODABLE
def generate_thumbnail(file_path: Path, size: int = DEFAULT_THUMB_SIZE) -> Path | None:
"""Generate (or reuse) a WebP thumbnail and return its path.
Returns ``None`` when the file cannot be decoded (e.g. SVG) or Pillow is
unavailable, so the caller can fall back to serving the original.
"""
cache_path = thumb_cache_path(file_path, size)
if cache_path.exists():
return cache_path
try:
from PIL import Image, ImageOps
except Exception: # pragma: no cover - Pillow is an optional runtime dep
return None
try:
with Image.open(file_path) as opened:
# Animated formats: keep only the first frame.
if getattr(opened, "is_animated", False):
opened.seek(0)
img = ImageOps.exif_transpose(opened) or opened
if img.mode not in ("RGB", "RGBA"):
img = img.convert("RGBA")
img.thumbnail((size, size))
tmp = cache_path.with_suffix(".tmp")
img.save(tmp, "WEBP", quality=80)
os.replace(tmp, cache_path)
return cache_path
except Exception:
return None
+76
View File
@@ -0,0 +1,76 @@
"""Shared media type constants and helpers.
Single source of truth for the file extensions and MIME types handled by the
image support (roadmap #108) and reused by the audio/video players (#109).
Keeping these sets here avoids the previous duplication (``indexer.py``,
``attachment_indexer.py`` and ``main.py`` each carried their own copy).
"""
from __future__ import annotations
import mimetypes
# Image extensions viewable in the browser (HEIC/HEIF deliberately excluded —
# no browser decodes them natively; see roadmap #108).
IMAGE_EXTENSIONS: frozenset[str] = frozenset({
".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".ico",
})
# Audio extensions (socle for #109, not wired into the index yet).
AUDIO_EXTENSIONS: frozenset[str] = frozenset({
".mp3", ".m4a", ".aac", ".wav", ".ogg", ".oga", ".opus", ".flac",
})
# Video extensions (socle for #109, not wired into the index yet).
VIDEO_EXTENSIONS: frozenset[str] = frozenset({
".mp4", ".webm", ".mov", ".m4v",
})
MEDIA_EXTENSIONS: frozenset[str] = IMAGE_EXTENSIONS | AUDIO_EXTENSIONS | VIDEO_EXTENSIONS
# Explicit MIME types for extensions ``mimetypes`` gets wrong or does not know.
_MIME_OVERRIDES: dict[str, str] = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".webp": "image/webp",
".m4a": "audio/mp4",
".oga": "audio/ogg",
".opus": "audio/ogg",
".mov": "video/quicktime",
".m4v": "video/mp4",
}
def is_image(ext: str) -> bool:
"""Return True when *ext* (with leading dot, any case) is an image."""
return ext.lower() in IMAGE_EXTENSIONS
def is_audio(ext: str) -> bool:
"""Return True when *ext* is an audio extension."""
return ext.lower() in AUDIO_EXTENSIONS
def is_video(ext: str) -> bool:
"""Return True when *ext* is a video extension."""
return ext.lower() in VIDEO_EXTENSIONS
def is_media(ext: str) -> bool:
"""Return True when *ext* is any supported image/audio/video extension."""
return ext.lower() in MEDIA_EXTENSIONS
def media_mime_type(path: str) -> str:
"""Return the best MIME type for *path* (extension based).
Falls back to ``application/octet-stream`` when the type is unknown.
"""
lower = path.lower()
for ext, mime in _MIME_OVERRIDES.items():
if lower.endswith(ext):
return mime
guessed, _ = mimetypes.guess_type(path)
return guessed or "application/octet-stream"
+2
View File
@@ -15,6 +15,7 @@ weasyprint>=60.0
httpx>=0.27.0
pypdf>=4.0
pyotp>=2.10.0
segno>=1.5.0
webauthn==2.6.0
psutil>=5.9
pywebpush>=2.3.0
@@ -23,3 +24,4 @@ sse-starlette==2.1.3
openpyxl>=3.1
python-docx>=1.1
reportlab>=4.0
pillow>=10.0
+2
View File
@@ -395,6 +395,7 @@ class DashboardVaultStat(BaseModel):
file_count: int
tag_count: int
total_size_bytes: int
image_count: int = 0
class DashboardResponse(BaseModel):
@@ -404,6 +405,7 @@ class DashboardResponse(BaseModel):
total_files: int
total_tags: int
total_size_bytes: int
total_images: int = 0
# ---------------------------------------------------------------------------
+15
View File
@@ -26,6 +26,11 @@ from backend.services.vaults import get_vault_root
logger = logging.getLogger("obsigate.services.mutations")
# #86: per-file size cap for find/replace passes (CPU guard — complements the
# BUG-025 regex caps). Files larger than this are skipped instead of being
# read fully into memory and scanned with a user-supplied pattern.
MAX_REPLACE_FILE_BYTES = 5_000_000
# Skeleton injected into empty ``.excalidraw`` files (mirrors the route logic).
_EXCALIDRAW_SKELETON = (
'{"type":"excalidraw","version":2,"elements":[],'
@@ -509,6 +514,16 @@ def replace_in_files(
continue
if not file_path.exists() or not file_path.is_file():
continue
# #86 CPU guard: skip files too large to scan safely in one pass.
try:
if file_path.stat().st_size > MAX_REPLACE_FILE_BYTES:
logger.warning(
"replace_in_files: skipping oversized file %s/%s (%d bytes)",
result_vault, result["path"], file_path.stat().st_size,
)
continue
except OSError:
continue
try:
original = file_path.read_text(encoding="utf-8", errors="replace")
except OSError:
+1 -1
View File
@@ -2626,7 +2626,7 @@ dependencies = [
[[package]]
name = "obsigate-desktop"
version = "2.14.0"
version = "2.19.2"
dependencies = [
"chrono",
"env_logger",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "obsigate-desktop"
version = "2.14.0"
version = "2.19.2"
description = "ObsiGate Desktop — Porte d'entrée native pour vos vaults Obsidian"
authors = ["Bruno Charest"]
edition = "2021"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/nicedoc/obsigate/main/desktop/tauri.conf.schema.json",
"productName": "ObsiGate",
"version": "2.14.0",
"version": "2.19.2",
"identifier": "com.obsigate.desktop",
"build": {
"frontendDist": "../frontend",
+2 -2
View File
@@ -347,7 +347,7 @@ Pour répondre au besoin de cibler un fournisseur/modèle sans dépendre uniquem
| **0 — Fondations** | `backend/tools/` (registry, context, service, audit) + extraction des services métier + tests unitaires | Couche d'outils testable sans IA |
| **1 — Function calling in-app** | Abstraction tool-calling multi-provider, agent loop, confirmations UI, SSE réel, outils de navigation | Assistant qui lit/cherche/lit/ouvre/modifie avec confirmation |
| **2 — Serveur MCP** | `backend/mcp/server.py` (tools + resources + prompts), **Streamable HTTP** (`/mcp`, auth JWT), confirmation two-step | ObsiGate accessible comme serveur MCP (local + distant, multi-utilisateur) |
| **3 — Durcissement** ✅ | Rate limiting (`backend/tools/ratelimit.py`), quotas `BOOKSLM_MAX_*`, redaction systématique des résultats (`backend/tools/redaction.py`), doc OpenAPI (tag/path MCP) + [guide MCP](./MCP_GUIDE.md), tests E2E | Observabilité et sécurité complètes |
| **3 — Durcissement** ✅ | Rate limiting (`backend/tools/ratelimit.py`), quotas `BOOKSLM_MAX_*`, redaction systématique des résultats (`backend/tools/redaction.py`), doc OpenAPI (tag/path MCP) + [guide MCP](./GUIDES/MCP.md), tests E2E | Observabilité et sécurité complètes |
Voir `docs/ROADMAP.md` (item dédié) pour le détail des activités.
@@ -380,7 +380,7 @@ Voir `docs/ROADMAP.md` (item dédié) pour le détail des activités.
- `backend/mcp/confirmations.py` — jetons de confirmation signés (two-step, anti-rejeu)
- `backend/tools/ratelimit.py` — rate limiting par jeton/outil (phase F)
- `backend/tools/redaction.py` — redaction récursive des résultats d'outils (phase F)
- `docs/MCP_GUIDE.md` — guide d'installation et d'utilisation des clients MCP
- `docs/GUIDES/MCP.md` — guide d'installation et d'utilisation des clients MCP
- `backend/bookslm.py`, `backend/bookslm_routes.py` — assistant contextuel (+ endpoint `/agent`)
- `frontend/js/ai.js`, `frontend/js/bookslm.js` — UI IA
- `backend/auth/middleware.py` — permissions
+326
View File
@@ -0,0 +1,326 @@
# 🔌 Guide de l'API REST
ObsiGate expose une **API REST complète** couvrant toute l'application :
vaults, fichiers, recherche, sauvegardes, exports, IA, partage, webhooks et
administration. Ce guide explique l'authentification, la création de clés et
donne des exemples prêts à l'emploi.
> **Public :** développeurs, intégrateurs, scripts d'automatisation
> **Doc interactive :** `/docs` (Swagger UI) · `/redoc` (ReDoc) · `/openapi.json`
> **Voir aussi :** [Serveur MCP](./MCP.md) · [Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md)
---
## 1. Base et conventions
| Élément | Valeur |
|---|---|
| URL de base | `http://<hôte>:2020` (Docker) ou `http://127.0.0.1:17890` (desktop) |
| Préfixe API | `/api` |
| Format | JSON (`application/json`) |
| Version | suit la version d'ObsiGate (header `X-…`, `/api/health`) |
| Erreurs | `{"detail": "..."}` + code HTTP (`400`, `401`, `403`, `404`, `409`, `422`, `500`) |
Quand l'authentification est **désactivée** (`OBSIGATE_AUTH_ENABLED=false`), tous
les endpoints sont accessibles sans jeton (utilisateur anonyme avec accès à tous
les vaults).
---
## 2. Authentification
### 2.1 Jeton de session (JWT)
Obtenu via `POST /api/auth/login`. Le jeton d'accès a une durée de vie courte
(`OBSIGATE_ACCESS_TOKEN_TTL`, défaut 3600 s) et un refresh token longue durée est
posé en cookie HTTP-only.
```bash
curl -s -X POST http://localhost:2020/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"votre_mot_de_passe"}'
```
Réponse (extrait) :
```json
{
"access_token": "eyJ...",
"token_type": "bearer",
"expires_in": 3600,
"user": { "username": "admin", "role": "admin", "vaults": ["*"] }
}
```
Deux façons de présenter le jeton :
```http
Authorization: Bearer <access_token>
```
ou, pour un client navigateur, le cookie HTTP-only avec
`credentials: "include"` (le login pose aussi un cookie `access_token`).
### 2.2 Clés API longue durée (recommandé pour scripts & MCP)
Une **seule clé** authentifie **l'API REST et le serveur MCP**. Créez-la depuis
l'interface (Configurations → **🔑 Clés API & MCP**) ou par API :
```bash
# 1. Se connecter, récupérer le token (section 2.1)
# 2. Créer une clé valable 30 jours
curl -s -X POST http://localhost:2020/api/auth/tokens \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"Script backup","expiry":"30d"}'
```
Réponse (`token` affiché **une seule fois**) :
```json
{
"token": "eyJ...",
"jti": "…",
"name": "Script backup",
"created_at": 1790000000,
"expires_at": 1792592000,
"expiry_key": "30d"
}
```
| `expiry` | Durée |
|---|---|
| `1d` | 1 jour |
| `30d` | 1 mois |
| `180d` | 6 mois |
| `365d` | 1 an |
| `never` | sans expiration |
Gestion :
| Endpoint | Rôle |
|---|---|
| `GET /api/auth/tokens` | Lister vos clés (`last_used_at`, statut) |
| `POST /api/auth/tokens` | Créer (`{name, expiry}`) |
| `DELETE /api/auth/tokens/{jti}` | Révoquer immédiatement (API **et** MCP) |
> Le JWT brut n'est **jamais persisté** : copiez-le à la création. Plafond :
> 50 clés actives par utilisateur.
---
## 3. Référence des endpoints
> Liste non exhaustive — la référence faisant foi est `/openapi.json`. Les
> colonnes **Auth** indiquent le niveau requis (`—`, `Oui`, `Admin`).
### 3.1 Système
| Endpoint | Description | Méthode | Auth |
|---|---|---|---|
| `/api/health` | Santé (statut, version, stats) | GET | — |
| `/api/health/detailed` | Santé détaillée | GET | — |
| `/api/config` | Lire / écrire la configuration | GET/POST | Oui/Admin |
| `/api/diagnostics` | Statistiques index & mémoire | GET | Admin |
| `/api/dashboard` | Statistiques du tableau de bord | GET | Oui |
| `/api/events` | Flux SSE temps réel | GET | Oui |
### 3.2 Vaults
| Endpoint | Description | Méthode | Auth |
|---|---|---|---|
| `/api/vaults` | Liste (filtrée par permissions) | GET | Oui |
| `/api/vaults/status` | Statut de toutes les vaults | GET | Oui |
| `/api/vaults/add` | Ajouter une vault (volume déjà monté) | POST | Admin |
| `/api/vaults/{name}` | Supprimer une vault | DELETE | Admin |
| `/api/index/reload` | Réindexation complète | GET | Admin |
| `/api/index/reload/{vault}` | Réindexer une vault | GET | Oui |
| `/api/vaults/{vault}/settings` | Lire / écrire les réglages | GET/POST | Oui |
| `/api/attachments/rescan/{vault}` | Rescanner les attachements | POST | Oui |
### 3.3 Fichiers
| Endpoint | Description | Méthode | Auth |
|---|---|---|---|
| `/api/browse/{vault}?path=` | Naviguer dans les dossiers | GET | Oui |
| `/api/file/{vault}?path=` | Contenu rendu (Markdown) | GET | Oui |
| `/api/file/{vault}/raw?path=` | Contenu brut | GET | Oui |
| `/api/file/{vault}/download?path=` | Télécharger | GET | Oui |
| `/api/file/{vault}/save?path=` | Enregistrer | PUT | Oui |
| `/api/file/{vault}` | Créer | POST | Oui |
| `/api/file/{vault}` | Renommer | PATCH | Oui |
| `/api/file/{vault}` | Supprimer | DELETE | Oui |
| `/api/directory/{vault}` | Créer / renommer / supprimer un dossier | POST/PATCH/DELETE | Oui |
| `/api/move/{vault}` | Déplacer un fichier/dossier | POST | Oui |
| `/api/vault/{vault}/batch-upload` | Upload multiple (multipart) | POST | Oui |
| `/api/image/{vault}?path=` | Servir une image | GET | Oui |
### 3.4 Recherche & graphe
| Endpoint | Description | Méthode | Auth |
|---|---|---|---|
| `/api/search` | Recherche simple (legacy) | GET | Oui |
| `/api/search/advanced` | Recherche TF-IDF avancée (facettes, tri, pagination, `semantic=`) | GET | Oui |
| `/api/search/replace` | Recherche/remplacement multi-fichiers | POST | Oui |
| `/api/tags?vault=` | Tags uniques avec compteurs | GET | Oui |
| `/api/suggest?q=` | Autocomplétion de titres | GET | Oui |
| `/api/tags/suggest?q=` | Autocomplétion de tags | GET | Oui |
| `/api/tree-search` | Recherche de fichiers/dossiers | GET | Oui |
| `/api/vault/{vault}/paths` | Liste de chemins | GET | Oui |
| `/api/graph/{vault}` | Graphe de liens | GET | Oui |
### 3.5 Sauvegardes
| Endpoint | Description | Méthode | Auth |
|---|---|---|---|
| `/api/file/{vault}/backups` | Backups d'un fichier | GET | Oui |
| `/api/file/{vault}/diff` | Diff avec une version | GET | Oui |
| `/api/file/{vault}/restore` | Restaurer une version | POST | Oui |
| `/api/backups` | Lister les backups | GET | Oui |
| `/api/backups/content` | Contenu d'un backup | GET | Oui |
| `/api/backups/delete` / `/purge` / `/compress` / `/auto` | Gestion & purge | POST | Oui |
### 3.6 Exports
| Endpoint | Description | Méthode |
|---|---|---|
| `/api/export/html` | Exporter en HTML | GET |
| `/api/export/md-bundle` | Exporter en bundle Markdown (ZIP) | GET |
| `/api/export/epub` | Exporter en ePub | GET |
| `/api/guide/download?format=md\|pdf&lang=fr\|en` | Télécharger le guide intégré | GET |
### 3.7 PDF
| Endpoint | Description | Méthode |
|---|---|---|
| `/api/file/{vault}/pdf/info` | Métadonnées sans transfert | GET |
| `/api/file/{vault}/pdf/stream` | Streaming (HTTP Range, 206) | GET |
### 3.8 IA
| Endpoint | Description | Méthode |
|---|---|---|
| `/api/ai/status` | Statut des fournisseurs | GET |
| `/api/ai/improve`, `/fix-spelling`, `/summarize`, `/translate`, `/rewrite`, `/to-list`, `/to-table`, `/frontmatter`, `/inline-complete`, `/to-canvas`… | Actions éditeur IA | POST |
| `/api/ai/model-capabilities?provider=&model=` | Capacités d'un modèle | GET |
| `/api/ai/bookslm/*` | Console IA par répertoire | POST/GET |
| `/api/ai/skills` | Lister / créer / supprimer des skills | GET/POST/DELETE |
| `/api/config/ai-keys` · `/api/config/tool-keys` | Clés fournisseurs & sources | GET/POST/DELETE |
### 3.9 Authentification & administration
| Endpoint | Description | Méthode | Auth |
|---|---|---|---|
| `/api/auth/status` | Statut de l'auth | GET | — |
| `/api/auth/login` · `/refresh` · `/logout` | Cycle de session | POST | — / Cookie / Oui |
| `/api/auth/me` | Profil courant | GET/PATCH | Oui |
| `/api/auth/change-password` | Changer le mot de passe | POST | Oui |
| `/api/auth/mfa/*` | TOTP, WebAuthn, recovery | POST/GET | Oui |
| `/api/auth/tokens` | Clés API (voir §2.2) | GET/POST/DELETE | Oui |
| `/api/auth/admin/users` | Lister / créer des utilisateurs | GET/POST | Admin |
| `/api/auth/admin/users/{u}` | Modifier / supprimer | PATCH/DELETE | Admin |
| `/api/admin/stats` · `/audit` · `/backup-stats` · `/stream` | Monitoring admin | GET | Admin |
### 3.10 Partage, webhooks, conflits, plugins, push
| Endpoint | Description | Méthode |
|---|---|---|
| `/api/share/{vault}` | Créer un lien de partage public | POST |
| `/api/shares` | Lister / supprimer les partages | GET/DELETE |
| `/api/webhooks` | CRUD webhooks (HMAC-SHA256) | GET/POST/PATCH/DELETE |
| `/api/conflicts` · `/api/conflicts/resolve` | Conflits Syncthing | GET/POST |
| `/api/plugins` | Installer / activer / désactiver | GET/POST/DELETE |
| `/api/push/*` | Abonnement Web Push (VAPID) | GET/POST/DELETE |
---
## 4. Exemples `curl`
```bash
BASE=http://localhost:2020
TOKEN=$(curl -s -X POST $BASE/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"secret"}' | jq -r .access_token)
# Santé
curl -s $BASE/api/health
# Lister les vaults
curl -s $BASE/api/vaults -H "Authorization: Bearer $TOKEN"
# Naviguer
curl -s "$BASE/api/browse/Recettes?path=" -H "Authorization: Bearer $TOKEN"
# Lire un fichier (rendu Markdown)
curl -s "$BASE/api/file/Recettes?path=pizza.md" -H "Authorization: Bearer $TOKEN"
# Lire en brut
curl -s "$BASE/api/file/Recettes/raw?path=pizza.md" -H "Authorization: Bearer $TOKEN"
# Sauvegarder
curl -s -X PUT "$BASE/api/file/Recettes/save?path=pizza.md" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"content":"# Pizza\n\nNouvelle recette."}'
# Recherche avancée
curl -s "$BASE/api/search/advanced?q=tag:cuisine%20pizza&vault=all&limit=20&offset=0&sort=relevance" \
-H "Authorization: Bearer $TOKEN"
# Autocomplétion
curl -s "$BASE/api/suggest?q=piz&vault=all" -H "Authorization: Bearer $TOKEN"
# Forcer une réindexation
curl -s $BASE/api/index/reload -H "Authorization: Bearer $TOKEN"
```
> Le mot de passe peut aussi être fourni par une clé API dans `Authorization`.
> Quand l'auth est désactivée, omettez l'en-tête.
---
## 5. Temps réel
### 5.1 SSE — `/api/events`
Flux d'événements de changement d'index (fichiers créés/supprimés/modifiés), avec
reconnexion automatique côté client.
```bash
curl -N "$BASE/api/events"
```
### 5.2 WebSocket — collaboration
`ws(s)://<hôte>/ws/collab/{vault}/{path}` transporte les mises à jour
Yjs/CRDT et la présence (curseurs distants). Authentification par cookie
`access_token` ou paramètre `?token=`, avec contrôle d'accès par vault.
Voir [Édition & collaboration](./COLLABORATION.md).
---
## 6. Limites et bonnes pratiques
- **Rate limiting** : les endpoints de login et les outils IA sont limités ;
respectez `retry_after` en cas de `429`.
- **Permissions** : chaque endpoint fichier vérifie l'accès au vault et rejette
les chemins hors vault (path traversal).
- **Clés API** : préférez-les aux mots de passe pour les scripts ; révoquez-les
dès qu'elles ne servent plus.
- **Gros volumes** : utilisez la pagination (`limit`/`offset`) et le streaming
HTTP Range pour les PDF.
- **Exports** : `md-bundle` et `epub` renvoient un fichier binaire — utilisez
`-o` avec `curl`.
---
## 7. Dépannage
| Code | Cause probable |
|---|---|
| `401` | Jeton absent, expiré ou révoqué |
| `403` | Compte sans accès à cette vault / réservé admin |
| `404` | Vault, fichier ou chemin inexistant |
| `409` | Conflit (fichier déjà existant, etc.) |
| `422` | Corps de requête invalide (schéma Pydantic) |
| `429` | Rate limit dépassé — voir `retry_after` |
| `501` | Export PDF indisponible (WeasyPrint/GTK absent) |
+217
View File
@@ -0,0 +1,217 @@
# 🤖 Guide Assistant IA & Forge
ObsiGate intègre un **assistant IA** capable de lire, rechercher et modifier vos
notes, ainsi qu'un **éditeur IA** (CodeMirror + toolbar) et une console
contextuelle par répertoire (**BooksLM**). Ce guide explique comment les
configurer et les utiliser.
> **Fiches techniques :** [`ai-tools-mcp.md`](../features/ai-tools-mcp.md) ·
> [`ai-assistant-commands.md`](../features/ai-assistant-commands.md) ·
> [`ai-quick-actions.md`](../features/ai-quick-actions.md) ·
> [`forge-assistant.md`](../features/forge-assistant.md) ·
> [`bookslm.md`](../features/bookslm.md) ·
> [`ai-tools-roadmap.md`](../features/ai-tools-roadmap.md)
> **Voir aussi :** [Serveur MCP](./MCP.md) · [API REST](./API_REST.md)
---
## 1. Vue d'ensemble
L'IA d'ObsiGate se compose de plusieurs surfaces complémentaires :
| Surface | Rôle |
|---|---|
| **Éditeur IA** | Toolbar d'actions sur le document ouvert (CodeMirror) |
| **Assistant IA** | Panneau de discussion avec *function calling* sur vos vaults |
| **BooksLM** | Console IA contextuelle sur un **répertoire** (style NotebookLM) |
| **Forge** | Éditeur avancé avec assistant IA intégré |
| **Outils (tools)** | Lecture, recherche, écriture, opérations destructives (two-step) |
| **MCP** | Exposition des mêmes outils à Claude Desktop, Cursor, Cline… |
---
## 2. Configurer un fournisseur
### 2.1 Fournisseurs supportés
ObsiGate est **multi-fournisseur** :
- **DeepSeek**
- **OpenRouter**
- **Google Gemini**
Chaque fournisseur se configure au choix :
1. **Depuis l'interface** — menu → Configurations → **Clés API IA**. La clé saisie
est stockée dans `data/api_keys.json` et **prime** sur la variable
d'environnement.
2. **Par variable d'environnement** — voir `.env.example`.
### 2.2 Modèle et capacités
L'interface affiche les **capacités** de chaque modèle (8 indicateurs : vision,
tool calling, contexte long, etc.), via
`GET /api/ai/model-capabilities?provider=&model=`. Le picker de l'assistant
propose une recherche de modèle et une bulle d'information ⓘ.
Vous pouvez définir un **modèle par défaut** et un fournisseur par défaut dans la
configuration. Le fournisseur/modèle est **partagé** entre l'assistant et Forge.
### 2.3 Tester la configuration
`POST /api/config/ai-keys/test` vérifie qu'une clé fonctionne. En cas d'échec,
un message explicite s'affiche.
---
## 3. Éditeur IA (toolbar)
Quand un document Markdown est ouvert dans l'éditeur, une **toolbar IA** propose
des actions qui remplacent ou insèrent du contenu. Actions principales :
| Action | Effet |
|---|---|
| **Améliorer** | Relecture et amélioration générale |
| **Corriger** | Correction orthographique et grammaticale |
| **Raccourcir / Allonger** | Ajuste la longueur du texte |
| **Simplifier** | Vulgarise le contenu |
| **Ton** | Adapte le registre (formel, neutre…) |
| **Traduire** | Traduit la sélection ou le document |
| **Expliquer** | Explique un passage |
| **Résumer** | Produit un résumé |
| **Continuer** | Prolonge le texte |
| **Réécrire** | Réécriture personnalisée libre |
| **En liste / En tableau** | Convertit en liste à puces ou tableau Markdown |
| **Frontmatter** | Génère ou met à jour le frontmatter YAML |
| **Complétion inline** | `Ctrl + J` — complétion directement dans l'éditeur |
| **En canvas** | Transforme en diagramme canvas |
> Les actions sont exposées par `backend/ai_routes.py` (préfixe `/api/ai`). Le
> contexte ad-hoc (fichiers ouverts, répertoire, recherche, récents) est injecté
> automatiquement.
---
## 4. Forge et Editer
- **Editer** ouvre le document dans l'éditeur CodeMirror classique.
- **Forge** ouvre l'**éditeur avancé** : mêmes capacités d'édition, mais avec
l'**assistant IA partagé** intégré (bouton AI Panel), insertion rapide
(`Alt + I`), aide (`F1`) et mode plein écran.
Dans les deux cas, `Editer` et `Forge` **remplacent** la vue lecture ; revenez en
lecture avec `✓` / `×` ou `Échap`. Le panneau de l'assistant reste accessible à
côté.
---
## 5. Assistant IA & BooksLM
### 5.1 Discussion avec outils
L'assistant (panneau latéral) discute et **appelle des outils** pour agir sur
vos vaults : `list_vaults`, `read_file`, `search_fulltext`, `get_backlinks`,
`list_tags`, etc. Les opérations d'écriture passent par une **confirmation en
deux temps** (aperçu + jeton, puis application).
### 5.2 Contexte `@`
Tapez `@` pour attacher :
- un **fichier** (chip de contexte) ;
- un **répertoire** (chip de contexte) ;
- une **image** (pièce jointe, si le modèle gère la vision).
Le menu est alimenté par `/api/tree-search` (repli sur la liste des fichiers du
vault). Les chips sont retirables et rechargent le contexte.
### 5.3 Commandes `/` et skills
Tapez `/` pour ouvrir le **menu de commandes** (navigation `↑`/`↓`/`Entrée`/`Échap`).
**30 skills intégrés**, répartis par familles :
| Famille | Exemples |
|---|---|
| Base | `/research`, `/resume`, `/reformuler`, `/correction`, `/brainstorm`, `/plan`, `/ask`, `/meeting-note`, `/livrable` |
| Extraction & structuration | `/extract`, `/timeline`, `/glossary`, `/tag` |
| Transformation & adaptation | `/translate`, `/adapt`, `/clean`, `/summary-progressive` |
| Analyse critique & décision | `/critique`, `/compare`, `/prioritize`, `/swot`, `/debate` |
| Apprentissage & mémorisation | `/quiz`, `/reading-note`, `/qa-generator` |
| Méta-gestion & confidentialité | `/link`, `/anonymize`, `/estimate` |
Chaque skill applique un bloc de règles commun (français, notes traitées comme
données, anti-hallucination, conservation des noms/dates/chiffres).
**Skills utilisateur** : `/create-new-skill` ouvre une modale et persiste le
skill dans `data/skills.json` (par utilisateur). Ils sont listés par
`GET /api/ai/skills` et supprimables.
**Commandes admin** (exécutées localement, sans LLM) : `/help`, `/providers`,
`/provider <nom>`, `/model <nom>`, `/keys`.
### 5.4 Actions rapides
Un catalogue de **25 actions** en 6 catégories est proposé sous forme de boutons
contextuels (« Résumer en 3 points », « Checklist d'actions », « Générer le
frontmatter », « Expliquer le code », « Fusionner », « Traduire »…). Un tiroir
**« Toutes les actions »** permet de rechercher dans le catalogue.
### 5.5 Deep Research
Le mode **Deep Research** enchaîne recherche web et synthèse. Il est activé via
le panneau **« + »** de l'assistant (fichiers, contextes, skills, Deep Research).
### 5.6 Historique
Les conversations sont **persistées côté backend** et accessibles depuis la
sidebar « Historique IA », avec filtre de recherche.
---
## 6. Outils (function calling)
Les outils sont définis dans `backend/tools/` — **source unique de vérité**,
partagée par l'assistant in-app et le serveur MCP.
| Catégorie | Outils |
|---|---|
| Vaults / navigation | `list_vaults`, `list_directory`, `list_all_files` |
| Lecture | `read_file`, `read_file_raw`, `get_backlinks`, `list_backups`, `diff_backup`, `get_graph` |
| Recherche | `search_fulltext`, `search_advanced`, `search_paths`, `list_tags`, `suggest_tags`, `list_recent` |
| Écriture (propose/apply) | `create_file`, `create_directory`, `edit_file`, `append_to_file`, `restore_backup` |
| Destructif (propose/apply) | `rename_file`, `rename_directory`, `move_path`, `replace_in_files`, `delete_file`, `delete_directory` |
| Web / sources connectées | `web_search`, `fetch_url`, sources Gitea/GitHub… |
Les mutations suivent un flux **two-step** : `propose_<tool>` renvoie un aperçu
et un **jeton signé à usage unique**, puis `apply_<tool>` exécute.
---
## 7. Sécurité
- **Permissions par vault** appliquées à chaque outil.
- **Anti path-traversal** via `resolve_safe_path`.
- **Confirmation two-step** pour toute mutation.
- **Toggle `aiDestructiveTools`** par vault : le désactiver bloque
rename/move/replace/delete, sans bloquer create/edit/append.
- **Backup automatique** avant chaque opération destructive.
- **Rate limiting** par identité et par outil.
- **Redaction des secrets** dans tous les retours d'outils.
- **Audit** de chaque appel (`data/audit.log`, action `ai_tool_call`).
Détails : [Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md) et
[`MCP.md`](./MCP.md) §5.
---
## 8. Dépannage
| Symptôme | Piste |
|---|---|
| « Aucun fournisseur configuré » | Saisir une clé API (Configurations → Clés API IA) et la tester |
| L'IA n'a pas accès à un fichier | Vérifier `list_vaults` et les permissions du compte |
| L'image est refusée | Le modèle ne supporte pas la vision (400) — choisir un modèle multimodal |
| Une mutation reste bloquée | Vérifier `aiDestructiveTools` et le flux `propose_` → `apply_` |
| Quota d'outils atteint | Respecter `OBSIGATE_TOOL_RATE_LIMIT` / `retry_after` |
| Réponse tronquée | Ajuster `BOOKSLM_MAX_TOOL_READ_BYTES` / le modèle |
+229
View File
@@ -0,0 +1,229 @@
# 🔒 Guide Authentification & sécurité
ObsiGate embarque un système d'authentification optionnel **JWT + Argon2id**,
un contrôle d'accès **par vault**, du MFA (TOTP, WebAuthn, codes de secours) et
des mécanismes de durcissement. Ce guide couvre l'activation, la gestion des
comptes et les bonnes pratiques.
> **Public :** administrateurs · **Voir aussi :**
> [`features/api-mcp-tokens-107.md`](../features/api-mcp-tokens-107.md) ·
> [API REST](./API_REST.md) · [MCP](./MCP.md) · [Déploiement Docker](./DEPLOIEMENT_DOCKER.md)
---
## 1. Vue d'ensemble
- **Désactivée par défaut** (`OBSIGATE_AUTH_ENABLED=false`) — compatible avec
toutes les installations existantes.
- Quand elle est activée, l'écran de connexion s'affiche et chaque endpoint
vérifie l'utilisateur et ses permissions.
- Les données d'auth (`users.json`, `secret.key`, `api_tokens.json`) vivent dans
`/app/data` — **montez ce dossier en volume** pour les persister.
---
## 2. Activer l'authentification
### 2.1 Fichier `.env`
```bash
cp .env.example .env
```
```bash
OBSIGATE_AUTH_ENABLED=true
OBSIGATE_ADMIN_USER=admin
OBSIGATE_ADMIN_PASSWORD=votre_mot_de_passe # vide = auto-généré (voir logs)
# OBSIGATE_SECURE_COOKIES=false # true si derrière HTTPS
```
### 2.2 `docker-compose.yml`
```yaml
env_file:
- .env
```
> **Ne mettez jamais de mot de passe dans `docker-compose.yml` !** Utilisez
> toujours `.env` (non committé).
### 2.3 Premier démarrage
Si aucun utilisateur n'existe, ObsiGate crée un compte admin et affiche le mot de
passe **une seule fois dans les logs** :
```bash
docker compose logs obsigate | grep -A4 "FIRST"
```
```
============================================================
FIRST STARTUP — Admin account created automatically
Username : admin
Password : xK9mQ3pLr7wN2jT5
CHANGE THIS PASSWORD on first login!
============================================================
```
Changez-le immédiatement (menu profil → *Changer le mot de passe*).
---
## 3. Gestion des utilisateurs
### 3.1 Interface d'administration
Un compte **admin** voit une icône 🛡️ dans le header. Le panneau permet de :
- lister tous les utilisateurs ;
- créer / modifier / supprimer des comptes ;
- assigner les vaults accessibles par utilisateur ;
- activer / désactiver des comptes.
### 3.2 Ligne de commande
```bash
# Créer un utilisateur
docker exec obsigate python backend/create_admin.py create alice MotDePasse --role user --vaults Recettes IT
# Créer un admin avec accès total
docker exec obsigate python backend/create_admin.py create bob SecretPass --role admin --vaults "*"
# Lister
docker exec obsigate python backend/create_admin.py list
# Supprimer
docker exec obsigate python backend/create_admin.py delete alice
```
### 3.3 Contrôle d'accès par vault
| Valeur `vaults` | Accès |
|---|---|
| `["*"]` | Toutes les vaults (y compris futures) — défaut admin |
| `["Recettes", "IT"]` | Uniquement ces vaults |
| `[]` | Aucun accès |
Les permissions sont revérifiées à chaque requête (et à chaque connexion
WebSocket de collaboration).
---
## 4. MFA (authentification multifacteur)
ObsiGate propose trois secondes facteurs, configurables par l'utilisateur.
### 4.1 TOTP (application d'authentification)
1. Menu profil → **Sécurité** → *Configurer TOTP* (`POST /api/auth/mfa/totp/setup`).
2. Scannez le QR code avec Google Authenticator, Authy, etc.
3. Validez le code (`POST /api/auth/mfa/totp/enable`).
4. Désactivation : `POST /api/auth/mfa/totp/disable` (mot de passe requis).
### 4.2 Clés de sécurité & biométrie (WebAuthn)
- Enregistrement : `POST /api/auth/mfa/webauthn/register/options` puis
`POST /api/auth/mfa/webauthn/register`.
- Connexion : `POST /api/auth/mfa/webauthn/options` puis `/verify`.
- Gestion des clés : `GET /api/auth/mfa/webauthn/credentials`,
`POST /api/auth/mfa/webauthn/credentials/remove`.
> Le *relying party* (domaine) est **dérivé de la requête** (hôte exact, port
> inclus) ; derrière un reverse proxy, activez `OBSIGATE_TRUST_PROXY=true` pour
> que `X-Forwarded-Host/Proto` soient pris en compte.
### 4.3 Codes de secours
À l'activation du MFA, des **codes de récupération** sont générés. Utilisez-en un
via `POST /api/auth/mfa/recovery` si vous perdez votre second facteur. Conservez-
les hors ligne.
### 4.4 Statut
`GET /api/auth/mfa/status` indique les facteurs actifs pour le compte courant.
---
## 5. Clés API & MCP
Pour les scripts et les clients externes, créez une **clé API longue durée**
(1 j, 1 mois, 6 mois, 1 an, sans fin) depuis Configurations → 🔑 **Clés API &
MCP**. Une seule clé authentifie l'API REST **et** le serveur MCP.
- Le secret n'est **affiché qu'une fois** (pattern GitHub) et n'est jamais persisté.
- La révocation est **immédiate** des deux côtés.
- Une colonne « dernière utilisation » (throttlée) aide à repérer les clés
dormantes.
Détails : [API REST §2.2](./API_REST.md#22-clés-api-longue-durée-recommandé-pour-scripts--mcp)
et [`features/api-mcp-tokens-107.md`](../features/api-mcp-tokens-107.md).
---
## 6. Mécanismes de durcissement
| Mécanisme | Détail |
|---|---|
| **Path traversal** | Chaque endpoint fichier valide que le chemin résolu reste dans la vault |
| **Rate limiting** | 10 tentatives de login max par IP / 15 min + lockout par compte |
| **Rate limiting MFA** | Appliqué aux endpoints TOTP/WebAuthn/recovery |
| **Audit log** | Écritures, suppressions, config dans `data/audit.log` (JSON lines, rotation 10 Mo) |
| **Backup automatique** | Avant chaque modification/suppression dans `.obsigate-backup/` |
| **Redaction** | Masquage des JWT, clés API, tokens dans les aperçus et retours d'outils |
| **CSP** | `object-src`, `base-uri`, `form-action`, `frame-ancestors` restreints |
| **Cookie HttpOnly** | Jeton retiré de `sessionStorage`, porté par cookie HTTP-only |
| **Utilisateur non-root** | Conteneur sous `obsigate` (UID 1000) |
| **Volumes read-only** | Vaults montées `:ro` par défaut |
| **Atomic writes** | `users.json`, `shares.json`, `webhooks.json` écrits en tmp+replace |
| **Symlinks ignorés** | L'index n'indexe pas les liens symboliques |
### Politique de mot de passe
Une politique minimale est validée à la création d'un compte. Choisissez des mots
de passe longs et uniques ; activez le MFA pour les comptes admin.
---
## 7. Variables d'environnement
| Variable | Description | Défaut |
|---|---|---|
| `OBSIGATE_AUTH_ENABLED` | Activer l'authentification | `false` |
| `OBSIGATE_ADMIN_USER` | Nom de l'admin auto-créé | `admin` |
| `OBSIGATE_ADMIN_PASSWORD` | Mot de passe admin (vide = auto-généré) | *(auto)* |
| `OBSIGATE_SECURE_COOKIES` | Cookie `Secure` (HTTPS uniquement) | `false` |
| `OBSIGATE_ACCESS_TOKEN_TTL` | Durée de vie du token d'accès (s) | `3600` |
| `OBSIGATE_REFRESH_TOKEN_TTL` | Durée de vie du refresh token (s) | `2592000` |
| `OBSIGATE_LOGIN_MAX_ATTEMPTS` | Tentatives de login max par IP | `10` |
| `OBSIGATE_ACCOUNT_MAX_ATTEMPTS` | Tentatives de login max par compte | `10` |
| `OBSIGATE_LOGIN_WINDOW_SECONDS` | Fenêtre de rate limiting (s) | `900` |
| `OBSIGATE_TRUST_PROXY` | Faire confiance à `X-Forwarded-For` / `Host` | `false` |
Toutes ces variables sont documentées dans `.env.example`.
---
## 8. Déploiement sécurisé (checklist)
- [ ] `OBSIGATE_AUTH_ENABLED=true` sur toute instance exposée.
- [ ] Mot de passe admin fort, changé après le premier démarrage.
- [ ] MFA activé pour les comptes admin.
- [ ] HTTPS via reverse proxy + `OBSIGATE_SECURE_COOKIES=true`.
- [ ] `OBSIGATE_TRUST_PROXY=true` **uniquement** derrière un proxy de confiance.
- [ ] Volume `./data:/app/data` monté et **sauvegardé**.
- [ ] Vaults montées en `:ro` (lecture seule) sauf besoin d'écriture.
- [ ] Clés API révoquées dès qu'elles ne servent plus.
- [ ] Accès réseau restreint (VPN / pare-feu) si possible.
---
## 9. Dépannage
| Symptôme | Piste |
|---|---|
| Login bloqué `429` | Rate limit : attendre la fenêtre (`OBSIGATE_LOGIN_WINDOW_SECONDS`) |
| WebAuthn refuse l'enregistrement | Domaine/port non dérivés — activer `OBSIGATE_TRUST_PROXY` derrière un proxy |
| TOTP « challenge inattendu » | Relancer la cérémonie ; les 5 derniers challenges sont acceptés |
| Perte du second facteur | Utiliser un code de secours (`/api/auth/mfa/recovery`) |
| Sessions perdues au redémarrage | Le volume `./data` n'est pas monté |
| Clé API `401` | Clé expirée ou révoquée — en créer une nouvelle |
+86
View File
@@ -0,0 +1,86 @@
# 📝 Guide Édition & collaboration temps réel
Plusieurs utilisateurs peuvent éditer le **même document Markdown
simultanément**, façon Google Docs, grâce à Yjs (CRDT) et à un canal WebSocket.
Ce guide explique le fonctionnement et l'utilisation.
> **Public :** tous les utilisateurs · **Fiche technique :**
> [`features/collaboration.md`](../features/collaboration.md)
> **Voir aussi :** [Prise en main](./PRISE_EN_MAIN.md) · [API REST](./API_REST.md)
---
## 1. Ce que fait la collaboration
- **Fusion sans conflit** via **Yjs (CRDT)** : deux personnes peuvent taper au
même endroit, aucune modification n'est perdue.
- **Curseurs distants colorés** et sélections visibles dans CodeMirror, étiquetés
avec le nom de chaque utilisateur.
- **Indicateur de présence** dans l'en-tête de l'éditeur (avatars + statut de
connexion).
- **Reconnexion automatique** (backoff exponentiel) : l'état est fusionné au retour.
- **Persistance serveur** : le document est écrit sur disque **2 s** après la
dernière modification.
---
## 2. Utilisation
Aucune configuration n'est nécessaire :
1. Ouvrez le même fichier dans **deux navigateurs** (ou deux fenêtres).
2. Passez en mode **Editer** (ou **Forge**) dans les deux.
3. Tapez : les modifications apparaissent en temps réel des deux côtés, avec les
curseurs de chacun.
> L'édition collaborative nécessite que la vault soit **accessible en écriture**
> (le volume Docker doit être monté **sans** `:ro` pour les vaults modifiables).
---
## 3. Transport & protocole
| Élément | Valeur |
|---|---|
| Endpoint | `ws(s)://<hôte>/ws/collab/{vault}/{chemin}` |
| Authentification | Cookie `access_token` (ou paramètre `?token=`) |
| Autorisation | Contrôle d'accès **par vault** appliqué à chaque connexion |
| Protocole | Yjs / CRDT — updates + awareness (curseurs) |
| Persistance | Écriture disque débouncée (2 s) côté serveur |
Le canal est mis à niveau à partir de la même origine que l'application. Derrière
un reverse proxy, autorisez les **upgrades WebSocket** et augmentez
`proxy_read_timeout` (voir [Déploiement Docker](./DEPLOIEMENT_DOCKER.md)).
---
## 4. Sécurité
- L'accès au document est **revérifié à la connexion** (permissions du compte).
- Un utilisateur sans droit sur la vault ne peut pas rejoindre la session.
- Les échanges passent par le même domaine que l'application (pas de serveur
tiers).
---
## 5. Limitations & bonnes pratiques
- La collaboration vise les fichiers **Markdown**.
- Évitez d'éditer le même fichier simultanément depuis ObsiGate **et** une
application de synchronisation externe (risque de conflits au niveau fichier).
- Le document est écrit après un court délai ; attendez la fin de la sauvegarde
avant de fermer brutalement l'onglet.
- En cas de conflit de synchronisation externe (Syncthing), l'écran
**Conflits** (`/api/conflicts`) aide à résoudre.
---
## 6. Dépannage
| Symptôme | Piste |
|---|---|
| Les curseurs des autres n'apparaissent pas | Vérifier le WebSocket (proxy sans support `Upgrade`) |
| Reconnecté sans cesse | Réseau instable ou timeout proxy trop court |
| Modifications non persistées | Vault montée en lecture seule (`:ro`) ? |
| `401` à la connexion | Session expirée — se reconnecter |
| Accès refusé | Le compte n'a pas la permission sur cette vault |
+221
View File
@@ -0,0 +1,221 @@
# 🐳 Guide de déploiement Docker
Ce guide couvre l'installation, la configuration et l'exploitation d'ObsiGate
avec Docker / Docker Compose, y compris le reverse proxy HTTPS et les mises à jour.
> **Public :** administrateurs, ops
> **Voir aussi :** [Prise en main](./PRISE_EN_MAIN.md) ·
> [Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md) ·
> [`DEVELOPMENT_AND_RELEASES.md`](../DEVELOPMENT_AND_RELEASES.md)
---
## 1. Prérequis
| Composant | Version minimale |
|---|---|
| Docker | ≥ 20.10 |
| docker-compose | ≥ 2.0 |
| Espace disque | ~200 Mo pour l'image |
Systèmes supportés : Linux (Ubuntu, Debian…), macOS (Intel & Apple Silicon),
Windows (Docker Desktop), NAS compatibles Docker (Synology, QNAP…).
---
## 2. Configuration de `docker-compose.yml`
```yaml
services:
obsigate:
build:
context: .
image: obsigate:latest
container_name: obsigate
restart: unless-stopped
ports:
- "2020:8080" # port local 2020 → conteneur 8080
volumes:
- /home/user/Documents/Obsidian-Recettes:/vaults/Recettes:ro
- /home/user/Documents/Obsidian-IT:/vaults/IT:ro
- ./data:/app/data # persistance auth/config/backups
environment:
- VAULT_1_NAME=Recettes
- VAULT_1_PATH=/vaults/Recettes
- VAULT_2_NAME=IT
- VAULT_2_PATH=/vaults/IT
- OBSIGATE_AUTH_ENABLED=true
- OBSIGATE_ADMIN_USER=admin
env_file:
- .env # secrets (mot de passe admin…)
```
> **Important :** les chemins de vaults doivent être **absolus** et montés en
> **lecture seule** (`:ro`) sauf si vous voulez autoriser l'édition depuis
> ObsiGate. Le dossier `./data` doit être **persistant**.
### Variables de vault
| Variable | Description | Exemple |
|---|---|---|
| `VAULT_N_NAME` | Nom affiché | `Recettes` |
| `VAULT_N_PATH` | Chemin dans le conteneur | `/vaults/Recettes` |
| `VAULT_N_ATTACHMENTS_PATH` | Dossier d'attachements (optionnel) | `Assets/Images` |
| `VAULT_N_SCAN_ATTACHMENTS` | Scanner les images au démarrage | `true` |
**Nommage :** lettres, chiffres et tirets uniquement ; le nom doit correspondre au
chemin interne.
---
## 3. Construire et lancer
### 3.1 Script `build.sh` (recommandé)
```bash
chmod +x build.sh # une seule fois
./build.sh
```
Le script :
1. vérifie Docker et Docker Compose (versions) ;
2. valide `docker-compose.yml` (présence + syntaxe) ;
3. contrôle chaque volume monté (avertit si la source n'existe pas) ;
4. construit l'image (multi-stage, ~180 Mo) ;
5. démarre le conteneur ;
6. affiche le statut puis les logs en temps réel.
| Option | Description |
|---|---|
| `--help`, `-h` | Aide complète |
| `--build-only` | Construire sans démarrer |
| `--no-cache` | Rebuild complet sans cache **(défaut)** |
| `--cache` | Utiliser le cache Docker (plus rapide) |
| `--progress=plain` / `--progress=tty` | Sortie verbeuse / interactive |
### 3.2 Alternative manuelle
```bash
docker compose build --no-cache
docker compose up -d
```
### 3.3 Exploitation
```bash
docker compose down # arrêter
docker compose up -d # redémarrer sans rebuild
docker compose logs -f # logs temps réel
docker compose logs --tail=100 obsigate
```
> **Compatibilité Docker :** l'image utilise une variante `uvicorn` minimale et
> `fastapi 0.110.3` pour éviter des dépendances natives optionnelles
> (`watchfiles`, `uvloop`, `httptools`, `fastapi-cli`…) qui échouent sur Alpine,
> ARM ou i386.
---
## 4. Reverse proxy & HTTPS
ObsiGate sert du HTTP en clair ; placez un reverse proxy devant pour TLS.
### 4.1 Nginx (exemple)
```nginx
server {
listen 443 ssl http2;
server_name obsigate.example.com;
ssl_certificate /etc/letsencrypt/live/obsigate.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/obsigate.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:2020;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade; # WebSocket collab
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # SSE / WebSocket
}
}
```
### 4.2 Variables à activer derrière un proxy
```bash
OBSIGATE_SECURE_COOKIES=true # cookie Secure (HTTPS uniquement)
OBSIGATE_TRUST_PROXY=true # confiance à X-Forwarded-For / Host
```
> N'activez `OBSIGATE_TRUST_PROXY` **que** derrière un proxy de confiance, sinon
> l'adresse IP client peut être usurpée (rate limiting, audit).
Cloudflare Tunnel, Caddy et Traefik fonctionnent de la même façon (pensez au
support WebSocket et aux longs timeouts pour le SSE).
---
## 5. Healthcheck & supervision
L'image intègre un healthcheck sur `/api/health` (statut, version, stats). Vous
pouvez aussi l'interroger depuis l'hôte :
```bash
curl -s http://localhost:2020/api/health
curl -s http://localhost:2020/api/health/detailed # admin
```
`/api/admin/stream` fournit un flux d'administration (admin uniquement).
---
## 6. Mises à jour
```bash
git pull
./build.sh # reconstruit et redémarre
```
Vos données (`./data`) et vos vaults (volumes `:ro`) sont conservées. Pour un
rebuild propre sans cache : `./build.sh --no-cache`.
> **Version :** le fichier `VERSION` à la racine est la source unique de vérité ;
> l'image et l'UI affichent la même version. Voir
> [`DEVELOPMENT_AND_RELEASES.md`](../DEVELOPMENT_AND_RELEASES.md).
---
## 7. Sauvegardes
- **Données applicatives** : sauvegardez `./data` (utilisateurs, clés, partages,
webhooks, jetons).
- **Vos notes** : ObsiGate n'écrit dans les vaults que si elles sont montées en
écriture. Un backup automatique interne est créé dans `.obsigate-backup/` avant
chaque modification (rotation 10 Mo d'audit).
- **Backups desktop** : voir [Desktop](./DESKTOP.md).
---
## 8. Multi-plateforme
L'image est publiée pour `linux/amd64`, `linux/arm64`, `linux/arm/v7` et
`linux/386`. Sur un NAS ou un Raspberry Pi, choisissez la variante correspondante
(Buildx / `platform:` dans le compose).
---
## 9. Dépannage
| Symptôme | Piste |
|---|---|
| Port déjà utilisé | `sudo netstat -tulpn \| grep 2020` puis changer `ports: "2021:8080"` |
| Vault introuvable | Chemin absolu, permissions de lecture, redémarrer après modif |
| Build qui échoue | `docker system prune -f` puis `./build.sh --progress=plain` |
| Logs | `docker compose logs -f obsigate` |
| Widgets temps réel inopérants derrière un proxy | Autoriser les upgrades WebSocket et augmenter `proxy_read_timeout` |
| Login « insecure cookie » | Passer en HTTPS ou retirer `OBSIGATE_SECURE_COOKIES` |
+201
View File
@@ -0,0 +1,201 @@
# 🖥️ Guide de l'application desktop (Tauri)
ObsiGate Desktop est une application native construite avec
[Tauri](https://tauri.app/) (Rust + webview système). Elle embarque le backend
Python et le frontend dans un exécutable autonome — **zéro Docker, zéro ligne de
commande**.
> **Public :** tous les utilisateurs · **Statut :** version 2.x, binaires en
> cours de stabilisation (build depuis les sources recommandé)
> **Fiche technique :** [`features/desktop-tauri.md`](../features/desktop-tauri.md) ·
> **Checklist E2E :** [`DESKTOP_E2E_CHECKLIST.md`](../DESKTOP_E2E_CHECKLIST.md)
---
## 1. Fonctionnalités natives
| Fonctionnalité | Web | Desktop |
|---|---|---|
| Accès fichiers local | Via upload | Natif (sélecteur de dossier) |
| Thème système | Manuel | Auto (suit l'OS clair/sombre) |
| Notifications | Service Worker | Natif OS |
| Association `.md` | ❌ | ✅ « Ouvrir avec ObsiGate » |
| Icône de barre des tâches (tray) | ❌ | ✅ |
| Auto-update | ❌ | ✅ (vérifie les releases Gitea) |
| Mode hors-ligne | Limité | Complet (backend local) |
---
## 2. Téléchargement des binaires
Les releases sont publiées sur
[Gitea](https://git.dracodev.net/Projets/ObsiGate/releases) :
| Plateforme | Formats |
|---|---|
| **Linux** | `.deb` + `.AppImage` |
| **Windows** | `.msi` + `.exe` (NSIS) |
### Linux
```bash
# .deb (Debian / Ubuntu / Deepin)
sudo dpkg -i obsigate_2.0.0_amd64.deb
# Lancer : ObsiGate depuis le menu applications, ou `obsigate-desktop`
# .AppImage (toute distribution)
chmod +x ObsiGate_2.0.0_amd64.AppImage
./ObsiGate_2.0.0_amd64.AppImage
```
### Windows
```cmd
:: Double-cliquer sur ObsiGate_2.0.0_x64.msi (ou le setup NSIS)
:: Ou lancer ObsiGate depuis le menu Démarrer
```
---
## 3. Démarrage
1. **Lancez l'application** depuis le menu ou la ligne de commande.
2. Le backend Python démarre automatiquement sur `127.0.0.1:17890`
(splash « Démarrage… » pendant le boot).
3. La fenêtre s'ouvre et charge l'interface ObsiGate.
4. **Premier lancement** : sélectionnez le dossier de vos vaults Obsidian via le
sélecteur natif.
5. Pour fermer : icône tray → **Quitter** (arrêt propre du backend).
---
## 4. Construire depuis les sources
Guide détaillé : [`desktop/README.md`](../../desktop/README.md).
### 4.1 Prérequis communs
| Outil | Version | Installation |
|---|---|---|
| Rust (cargo) | ≥ 1.75 | `rustup` |
| Tauri CLI | ≥ 2.0 | `cargo install tauri-cli` |
| Git | — | — |
| Dépendances système Linux | — | `sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev` |
> **Important — staging :** `tauri.conf.json` embarque `backend/**` et
> `frontend/**` **depuis le dossier `desktop/`**. Les scripts de build copient
> automatiquement `../backend` et `../frontend` dans `desktop/` avant
> `cargo tauri build`. Sans ce staging, le build échoue avec
> « glob pattern backend/**/* path not found ».
### 4.2 Windows — `build-windows.bat`
```cmd
REM Prérequis (via Scoop) : rustup, curl, git
scoop install rustup curl git
rustup default stable
cargo install tauri-cli
cd desktop
build-windows.bat
```
Étapes du script :
1. Tue les processus Python résiduels (`taskkill /F /IM python.exe`).
2. Télécharge **Python 3.11 embed** (python.org) → `desktop\python-embed\` +
active pip (`python311._pth`).
3. `pip install -r ..\backend\requirements.txt` dans l'embed.
4. **Staging** : copie `..\backend` et `..\frontend` dans `desktop\`.
5. `cargo tauri build --target x86_64-pc-windows-msvc --bundles nsis`.
6. Copie `python-embed` à côté de l'exécutable pour le mode dev local.
7. Nettoie les dossiers stagés.
→ **Artefact :** `desktop\target\x86_64-pc-windows-msvc\release\bundle\nsis\ObsiGate_2.0.0_x64-setup.exe`
### 4.3 Linux — `build-linux.sh`
```bash
cd desktop
chmod +x build-linux.sh
./build-linux.sh
```
Étapes du script :
1. Vérifie Rust + Tauri CLI, installe les dépendances système (apt).
2. Crée un venv `desktop/python-embed/venv` + `pip install -r ../backend/requirements.txt`.
3. **Staging** : copie `../backend` et `../frontend` dans `desktop/`.
4. `cargo tauri build --target x86_64-unknown-linux-gnu --bundles deb,appimage`.
5. Copie le runtime (`python-embed/`, `backend/`, `frontend/`) à côté de l'exécutable.
→ **Artefacts :**
- `desktop/target/x86_64-unknown-linux-gnu/release/bundle/deb/obsigate_2.0.0_amd64.deb`
- `desktop/target/x86_64-unknown-linux-gnu/release/bundle/appimage/ObsiGate_2.0.0_amd64.AppImage`
---
## 5. Builds CI/CD automatiques
Le workflow [`.gitea/workflows/desktop-build.yml`](../../.gitea/workflows/desktop-build.yml)
construit les binaires desktop à chaque push sur `main` touchant `desktop/**`,
`frontend/**` ou `backend/**` (et manuellement via `workflow_dispatch`), sur des
**runners self-hosted** :
| Job | Runner | Artefacts (30 jours) |
|---|---|---|
| `build-windows` | `[self-hosted, windows, desktop]` | `desktop/target/release/bundle/msi/*.msi` |
| `build-linux` | `[self-hosted, linux, desktop]` | `*.AppImage` + `*.deb` |
Les artefacts sont téléchargeables depuis la page **Actions** du run Gitea ; la
publication en **Gitea Release** est prévue sur les tags `v*`.
---
## 6. Architecture desktop
```
┌────────────────────────────────────────────┐
│ Tauri (Rust) │
│ ├─ Webview (webview système) │
│ │ └─ Frontend (HTML/JS/CSS) │
│ └─ Sidecar Python │
│ └─ uvicorn backend.main:app │
│ └─ port 127.0.0.1:17890 │
└────────────────────────────────────────────┘
```
Cycle de vie : Tauri spawn le backend Python → health check → splash → webview.
À la fermeture : arrêt propre du backend (SIGTERM / kill).
---
## 7. Mises à jour
L'application vérifie les **releases Gitea** et propose la mise à jour (updater
Tauri signé). Le manifeste `latest.json` est généré automatiquement.
> La **signature de code Windows** n'est pas retenue (pas de certificat) : le
> binaire peut déclencher un avertissement SmartScreen. Alternatives possibles :
> SignPath.io (OSS gratuit), Certum OSS, Azure Trusted Signing, certificat EV.
---
## 8. Logs & dépannage
Les logs du backend sont écrits dans :
- **Windows** : `%APPDATA%\ObsiGate\logs\backend.log`
- **Linux** : `~/.config/obsigate/logs/backend.log`
| Symptôme | Piste |
|---|---|
| « Backend ne répond pas » | Vérifier le port `17890` (conflit) et relancer |
| Build « glob pattern backend/**/* not found » | Le staging n'a pas été fait — utiliser les scripts fournis |
| Le sélecteur de dossier ne s'ouvre pas | Permissions système / dialogue natif bloqué |
| Fenêtre blanche | Consulter `backend.log` ; le backend a peut-être échoué au boot |
| Mise à jour non proposée | Vérifier la connectivité aux releases Gitea |
Voir aussi [Prise en main](./PRISE_EN_MAIN.md) et
[Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md).
+191
View File
@@ -0,0 +1,191 @@
# 🧩 Guide MCP (Model Context Protocol)
ObsiGate expose ses vaults à des **clients MCP externes** (Claude Desktop, Cursor,
Cline, tout client compatible MCP) via un serveur **Streamable HTTP** monté sur
`/mcp`. Les outils sont les **mêmes** que ceux de l'assistant in-app : la couche
`backend/tools/` est la source unique de vérité.
> **Statut :** livré (#79 phase E + F) · **Dernière mise à jour :** 2026-09
> **Voir aussi :** [`features/ai-tools-mcp.md`](../features/ai-tools-mcp.md) ·
> [`AI_ARCHITECTURE_GUIDE.md`](../AI_ARCHITECTURE_GUIDE.md) ·
> [API REST](./API_REST.md) · [Assistant IA & Forge](./ASSISTANT_IA_FORGE.md)
---
## 1. Prérequis
1. Une instance ObsiGate accessible (locale ou distante).
2. Une **clé API** (recommandé) ou un **jeton JWT** valide
(`Authorization: Bearer <token>`). Une seule clé fonctionne pour l'API REST
**et** le MCP. Créez-la depuis l'interface (Configurations → 🔑 Clés API & MCP)
ou via `POST /api/auth/tokens` — voir [API REST §2.2](./API_REST.md#22-clés-api-longue-durée-recommandé-pour-scripts--mcp).
3. Si l'authentification est désactivée (`OBSIGATE_AUTH_ENABLED=false`), le
serveur MCP accepte un utilisateur anonyme disposant de tous les vaults.
> Le transport `stdio` n'est pas encore supporté ; utilisez le transport HTTP
> (un pont local type `mcp-remote` si votre client ne gère pas nativement le
> Streamable HTTP distant).
---
## 2. Endpoint & protocole
| Élément | Valeur |
|---|---|
| URL | `https://<obsigate>/mcp` |
| Transport | Streamable HTTP (`POST` JSON-RPC 2.0, `Accept: application/json, text/event-stream`) |
| Auth | `Authorization: Bearer <JWT>` |
| Protocole MCP | `2025-03-26` (négocié à l'`initialize`) |
| Réponses | JSON (`json_response=True`) |
Handshake minimal :
```bash
curl -sS https://obsigate.example/mcp \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: application/json, text/event-stream" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{
"protocolVersion":"2025-03-26","capabilities":{},
"clientInfo":{"name":"curl","version":"1.0"}}}'
```
La réponse contient l'en-tête `Mcp-Session-Id` à réutiliser pour les appels
suivants (`tools/list`, `tools/call`, `resources/read`, …).
---
## 3. Configuration des clients
### Claude Desktop (via pont `mcp-remote`)
```json
{
"mcpServers": {
"obsigate": {
"command": "npx",
"args": [
"-y", "mcp-remote",
"https://obsigate.example/mcp",
"--header", "Authorization: Bearer ${OBSIGATE_TOKEN}"
],
"env": { "OBSIGATE_TOKEN": "eyJ..." }
}
}
}
```
### Cursor
`.cursor/mcp.json` :
```json
{
"mcpServers": {
"obsigate": {
"url": "https://obsigate.example/mcp",
"headers": { "Authorization": "Bearer eyJ..." }
}
}
}
```
### Client générique (config raccourcie)
```json
{"mcpServers": {"obsigate": {
"url": "http://localhost:2020/mcp",
"headers": {"Authorization": "Bearer <clé API>"}
}}}
```
---
## 4. Primitives exposées
### 4.1 Tools
Les outils de **lecture/recherche** sont exposés directement. Les outils
**d'écriture/destructifs** sont exposés via une paire **two-step** :
`propose_<tool>` (aperçu + jeton de confirmation, aucune modification) puis
`apply_<tool>` (consomme le jeton et exécute).
| Catégorie | Outils |
|---|---|
| Vaults / navigation | `list_vaults`, `list_directory`, `list_all_files` |
| Lecture | `read_file`, `read_file_raw`, `get_backlinks`, `list_backups`, `diff_backup`, `get_graph` |
| Recherche | `search_fulltext`, `search_advanced`, `search_paths`, `list_tags`, `suggest_tags`, `list_recent` |
| Écriture (propose/apply) | `create_file`, `create_directory`, `edit_file`, `append_to_file`, `restore_backup` |
| Destructif (propose/apply) | `rename_file`, `rename_directory`, `move_path`, `replace_in_files`, `delete_file`, `delete_directory` |
Flux d'une mutation :
```text
1. tools/call { name: "propose_edit_file",
arguments: { vault, path, content } }
→ { tool, arguments, diff, confirmation_token, expires_in }
2. (l'utilisateur / l'agent valide)
3. tools/call { name: "apply_edit_file",
arguments: { confirmation_token } }
→ { ok: true, data: { ... } }
```
Le jeton est **signé (JWT), à usage unique et à durée de vie limitée**
(`OBSIGATE_MCP_CONFIRMATION_TTL`, défaut 300 s). Un rejeu renvoie `token_reused`.
### 4.2 Resources
| URI | Contenu |
|---|---|
| `vault://<name>` | Vault accessible (métadonnées, nombre de fichiers) |
| `vault://<name>/<path>` | Contenu d'un fichier (lecture seule, **secrets redactés**) |
### 4.3 Prompts
`summarize-directory`, `generate-note`, `find-related`.
---
## 5. Sécurité
- **Permissions par vault** : `check_vault_access` est appliqué à chaque outil
et chaque resource ; un utilisateur ne voit que ses vaults.
- **Anti path-traversal** : `resolve_safe_path` rejette tout chemin hors du vault.
- **Confirmation two-step** pour toute mutation (jeton signé, usage unique).
- **Toggle par vault** `aiDestructiveTools` (défaut : activé) : le désactiver
bloque rename/move/replace/delete tout en laissant create/edit/append.
- **Backup automatique** avant chaque opération destructive.
- **Rate limiting** : par jeton et par outil
(`OBSIGATE_TOOL_RATE_LIMIT`, `OBSIGATE_TOOL_RATE_LIMIT_PER_TOOL`,
`OBSIGATE_TOOL_RATE_WINDOW`). Une limite dépassée renvoie le code `rate_limited`.
- **Redaction des secrets** : les résultats d'outils (lectures, diffs, extraits
de recherche) sont nettoyés avant tout retour au client.
- **Audit** : chaque appel est journalisé (`data/audit.log`, action
`ai_tool_call`) avec arguments sensibles résumés.
### Variables d'environnement
| Variable | Défaut | Rôle |
|---|---|---|
| `OBSIGATE_MCP_CONFIRMATION_TTL` | `300` | Durée de vie (s) des jetons de confirmation |
| `OBSIGATE_TOOL_RATE_LIMIT` | `60` | Appels d'outils max par identité et par fenêtre |
| `OBSIGATE_TOOL_RATE_LIMIT_PER_TOOL` | = global | Appels max par outil et par fenêtre |
| `OBSIGATE_TOOL_RATE_WINDOW` | `60` | Longueur de la fenêtre (s) |
| `BOOKSLM_MAX_TOOL_CALLS` | `25` | Quota d'appels d'outils par run d'agent |
| `BOOKSLM_MAX_TOOL_READ_BYTES` | `200000` | Taille max renvoyée par `read_file` |
---
## 6. Dépannage
| Symptôme | Cause probable / remède |
|---|---|
| `401 Authentification requise` | En-tête `Authorization: Bearer` absent ou jeton expiré |
| `vault_access_denied` | Le jeton n'a pas accès à ce vault (`vaults` / `_token_vaults`) |
| `destructive_tools_disabled` | `aiDestructiveTools=false` pour ce vault |
| `confirmation_required` | Appeler d'abord `propose_<tool>` puis `apply_<tool>` |
| `token_reused` / `invalid_confirmation` | Jeton déjà consommé ou expiré → refaire un `propose_` |
| `rate_limited` | Quota dépassé ; respecter `retry_after` |
| Le client ne se connecte pas | Vérifier le transport Streamable HTTP / le pont `mcp-remote` |
+236
View File
@@ -0,0 +1,236 @@
# 🚀 Guide de prise en main
Ce guide vous fait passer d'une installation fraîche à une utilisation courante
d'ObsiGate : première connexion, découverte de l'interface, navigation dans vos
vaults Obsidian et raccourcis essentiels.
> **Public :** tous les utilisateurs · **Durée de lecture :** ~10 min
> **Voir aussi :** [Déploiement Docker](./DEPLOIEMENT_DOCKER.md) ·
> [Recherche, PDF & Excalidraw](./RECHERCHE_PDF_EXCALIDRAW.md) ·
> [API REST](./API_REST.md)
---
## 1. Qu'est-ce qu'ObsiGate ?
ObsiGate est une **porte d'entrée web ultra-légère** vers vos vaults Obsidian.
Il indexe vos notes en mémoire, les rend accessibles depuis n'importe quel
navigateur (ordinateur, tablette, téléphone) et ajoute une couche moderne :
recherche avancée, lecture Markdown, liens `[[wikilinks]]`, images, PDF,
Excalidraw, Mermaid, assistant IA, collaboration temps réel.
Points clés :
- **Aucune modification de vos vaults** : les volumes sont montés en lecture seule (`:ro`) par défaut.
- **Pas de base de données** : tout l'état tient dans des fichiers JSON sous `data/`.
- **Temps réel** : un watcher surveille le système de fichiers et met l'index à jour à chaud.
- **Multi-vault** : plusieurs vaults peuvent être affichés et recherchés simultanément.
---
## 2. Prérequis
| Composant | Version | Remarque |
|---|---|---|
| Docker | ≥ 20.10 | ou Node/`uv` pour un lancement manuel |
| docker-compose | ≥ 2.0 | inclus avec Docker Desktop |
| Navigateur | récent | Chrome, Edge, Firefox, Safari |
Vous aurez aussi besoin du **chemin absolu** de chaque vault Obsidian sur la
machine qui héberge Docker.
---
## 3. Lancer ObsiGate en 3 étapes
> La procédure complète (reverse proxy, HTTPS, mises à jour) est détaillée dans le
> [Guide de déploiement Docker](./DEPLOIEMENT_DOCKER.md).
### 3.1 Cloner le dépôt
```bash
git clone https://git.dracodev.net/Projets/ObsiGate.git
cd ObsiGate
```
### 3.2 Déclarer vos vaults
Éditez `docker-compose.yml` pour monter vos dossiers (chemins absolus, lecture seule) :
```yaml
volumes:
- /home/user/Documents/Obsidian-Recettes:/vaults/Recettes:ro
- /home/user/Documents/Obsidian-IT:/vaults/IT:ro
- ./data:/app/data # persistance auth/config
environment:
- VAULT_1_NAME=Recettes
- VAULT_1_PATH=/vaults/Recettes
- VAULT_2_NAME=IT
- VAULT_2_PATH=/vaults/IT
```
Créez le fichier de secrets à partir du modèle :
```bash
cp .env.example .env
# Éditez .env (mot de passe admin, options d'auth…)
```
### 3.3 Construire et démarrer
```bash
chmod +x build.sh # une seule fois
./build.sh
```
`build.sh` vérifie Docker, valide les volumes, construit l'image et démarre le
conteneur. Ouvrez ensuite **http://localhost:2020**.
> Options utiles : `./build.sh --help`, `./build.sh --cache` (rebuild rapide),
> `./build.sh --build-only` (construire sans démarrer).
---
## 4. Premier accès
### 4.1 Si l'authentification est désactivée (défaut)
Vous arrivez directement sur l'interface. Toutes les fonctionnalités sont
accessibles sans compte — **à réserver à un usage sur réseau de confiance**.
### 4.2 Si l'authentification est activée
L'écran de connexion s'affiche. Au **tout premier démarrage**, ObsiGate crée un
compte admin et affiche le mot de passe **une seule fois dans les logs** :
```bash
docker compose logs obsigate | grep -A4 "FIRST"
```
Changez ce mot de passe dès la première connexion (menu → profil →
*Changer le mot de passe*). La gestion complète des comptes, du MFA et des
permissions est décrite dans le
[Guide Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md).
---
## 5. Découvrir l'interface
L'interface se compose de trois zones principales.
### 5.1 L'en-tête (header)
| Élément | Rôle |
|---|---|
| 🔍 **Barre de recherche globale** | Recherche dans toutes les vaults autorisées |
| Filtre | Restreint la recherche (type, tag, vault…) |
| Sélecteur de vault | Bascule l'arborescence sur une vault ou « Toutes les vaults » |
| Utilisateur | Nom du compte connecté (si auth activée) |
| Version | Version courante d'ObsiGate |
| ⚙️ **Options** | Configuration, thème, guide d'utilisation, administration |
### 5.2 La barre latérale (sidebar)
Elle regroupe les vues principales via des icônes :
- **Arborescence** — parcourt les dossiers et fichiers de la vault sélectionnée.
- **Graphe** — vue force-directed des liens entre notes.
- **Récents** — derniers fichiers ouverts.
- **Signets** — vos fichiers et recherches enregistrés.
- **Partagés** — liens de partage public que vous avez créés.
Un champ **« Filtrer fichiers… »** restreint l'arborescence en temps réel, et le
bouton **Aa** ajuste l'affichage des libellés.
### 5.3 La zone de contenu
Elle affiche l'onglet actif : tableau de bord **Statistiques**, **Bookmarks**,
**Récents**, **Partagés**, ou le document ouvert. Les documents s'ouvrent dans
des **onglets** (avec possibilité de vue multi-panneaux / split view).
---
## 6. Navigation et lecture
1. **Déployez une vault** dans la sidebar (clic sur son nom).
2. **Cliquez sur un dossier** pour l'ouvrir, sur un **fichier** pour l'afficher.
3. Le **breadcrumb** en haut du document permet de remonter rapidement.
4. Les **wikilinks** `[[note]]` sont cliquables ; les images et diagrammes
s'affichent automatiquement.
5. Utilisez **Ctrl + clic** sur un lien pour l'ouvrir en aperçu rapide selon le
contexte, ou ouvrir le graphe centré sur un nœud.
### Créer et modifier
- **Bouton « Editer »** : ouvre le document dans l'éditeur Markdown (CodeMirror).
- **Bouton « Forge »** (éditeur avancé) : ouvre la version enrichie avec
assistant IA intégré. Voir [Assistant IA & Forge](./ASSISTANT_IA_FORGE.md).
- **Nouveau fichier / dossier** : depuis les actions de la sidebar ou la palette
de commandes.
- **Sauvegarde** : `Ctrl + S` (et auto-sauvegarde dans l'éditeur IA).
> Selon le mode, la lecture et l'édition se remplacent : `Editer` et `Forge`
> prennent la place de la vue lecture ; revenez avec `✓` / `×` ou `Échap`.
---
## 7. Rechercher
La recherche est un point fort d'ObsiGate : index inversé TF-IDF, stemming
français, normalisation des accents, facettes et pagination. La syntaxe complète
(`tag:`, `#`, `vault:`, `title:`, `path:`, `ext:`, phrases exactes) est décrite
dans le [Guide Recherche, PDF & Excalidraw](./RECHERCHE_PDF_EXCALIDRAW.md).
Démarrage rapide :
- Tapez dans la barre de recherche, `Ctrl + K` pour y revenir.
- `/` focalise la recherche hors champ de saisie.
- `/` + `↑`/`↓` navigue dans les suggestions.
---
## 8. Apparence et confort
- **Thème clair/sombre** : bascule persistée en `localStorage` ; le desktop suit
aussi le thème du système.
- **Thèmes** : clair, sombre, contraste élevé, sépia — import/export possible.
- **Responsive** : l'interface s'adapte au mobile (éditeur tactile, barre
d'outils flottante).
- **PWA** : installable comme application native, mode hors-ligne partiel.
Voir [PWA & mode hors-ligne](./PWA_HORS_LIGNE.md).
---
## 9. Raccourcis clavier essentiels
| Action | Raccourci |
|---|---|
| Palette de commandes | `Ctrl + Shift + Space` |
| Palette de fichiers (navigation rapide) | `Ctrl + Alt + Space` |
| Focus barre de recherche | `Ctrl + K` |
| Recherche rapide (hors champ texte) | `/` |
| Sauvegarder le fichier ouvert | `Ctrl + S` |
| Rechercher dans le document | `Ctrl + F` |
| Completion IA inline (éditeur) | `Ctrl + J` |
| Insertion rapide (éditeur Forge) | `Alt + I` |
| Fermer l'éditeur / modale | `Échap` |
| Aide de l'éditeur Forge | `F1` |
| Naviguer dans les suggestions | `↑` / `↓` |
| Lancer la recherche / valider | `Entrée` |
> Le panneau **Raccourcis & Astuces** du tableau de bord Statistiques récapitule
> ces raccourcis directement dans l'application.
---
## 10. Et ensuite ?
| Objectif | Guide |
|---|---|
| Mieux chercher, lire PDF et Excalidraw | [Recherche, PDF & Excalidraw](./RECHERCHE_PDF_EXCALIDRAW.md) |
| Utiliser l'IA intégrée | [Assistant IA & Forge](./ASSISTANT_IA_FORGE.md) |
| Éditer à plusieurs | [Édition & collaboration](./COLLABORATION.md) |
| Sécuriser l'accès | [Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md) |
| Automatiser via API/MCP | [API REST](./API_REST.md) · [MCP](./MCP.md) |
| Installer l'application native | [Desktop (Tauri)](./DESKTOP.md) |
+136
View File
@@ -0,0 +1,136 @@
# 📱 Guide PWA & mode hors-ligne
ObsiGate est une **Progressive Web App (PWA)** : installez-la comme une
application native, consultez vos notes **hors-ligne**, recevez des
notifications et synchronisez vos modifications à la reconnexion.
> **Public :** tous les utilisateurs · **Guides techniques :**
> [`PWA_GUIDE.md`](../PWA_GUIDE.md) · [`INSTALLATION_PWA.md`](../INSTALLATION_PWA.md)
> **Voir aussi :** [Prise en main](./PRISE_EN_MAIN.md) · [Édition & collaboration](./COLLABORATION.md)
---
## 1. Qu'est-ce que la PWA d'ObsiGate ?
Une PWA combine le meilleur du web et du natif :
- **Installation** sur l'écran d'accueil, sans store.
- **Mode hors-ligne** : interface et dernières données consultées mises en cache.
- **Notifications** : alertes de mise à jour et Web Push.
- **Performance** : chargement rapide via cache intelligent.
- **Multi-plateforme** : desktop, mobile, tablette.
---
## 2. Installer la PWA
### Desktop (Chrome, Edge, Brave)
1. Ouvrez ObsiGate dans le navigateur.
2. Cliquez sur l'icône d'installation dans la barre d'adresse (➕ / ⬇️).
3. Cliquez sur **Installer** dans la popup.
4. ObsiGate apparaît dans vos applications.
*Alternative :* menu ⋮ → **Installer ObsiGate…**
### Android (Chrome)
1. Ouvrez ObsiGate dans Chrome.
2. Menu ⋮ → **Ajouter à l'écran d'accueil**.
3. Confirmez.
### iOS / iPadOS (Safari)
1. Ouvrez ObsiGate dans Safari.
2. Bouton Partager 📤 → **Sur l'écran d'accueil**.
3. Nommez l'application puis **Ajouter**.
---
## 3. Mode hors-ligne
Le **Service Worker** (`frontend/sw.js`) met en cache :
- l'interface (HTML, CSS, JavaScript, manifeste) ;
- les ressources statiques (icônes, polices) ;
- les dernières données API consultées.
### Stratégies de cache
| Ressource | Stratégie |
|---|---|
| Code (HTML/JS/CSS/manifest) | **Network-first** (cache en secours hors-ligne) |
| API | **Network-first** (+ cache hors-ligne) |
| Autres assets (images, polices) | **Stale-while-revalidate** |
| Nettoyage | Purge des caches d'une version antérieure à l'activation |
> Le choix **network-first** est délibéré : les assets ne sont pas fingerprintés,
> un cache-first servirait indéfiniment un ancien build sur mobile.
### File de synchronisation & conflits
- Les modifications faites hors-ligne sont stockées (IndexedDB) et rejouées à la
reconnexion.
- Les conflits éventuels sont détectés et peuvent être résolus (écran
**Conflits**, `GET /api/conflicts`).
### Tester hors-ligne
1. DevTools (F12) → onglet **Network**.
2. Cochez **Offline**.
3. Rechargez : l'application doit fonctionner avec le cache.
---
## 4. Notifications (Web Push)
- Abonnement à partir de l'interface (permission navigateur requise).
- Endpoints : `GET /api/push/vapid-public-key`,
`POST /api/push/subscribe`, `DELETE /api/push/subscribe`,
`GET /api/push/subscriptions`.
- Les notifications sont signées **VAPID** et peuvent prévenir de changements
(collaboration, mises à jour).
---
## 5. Mises à jour
- Vérification régulière des mises à jour.
- Notification quand une nouvelle version est disponible.
- Mise à jour en un clic, **sans perte de données**.
- Le numéro `SW_VERSION` invalide l'ancien cache à chaque livraison.
### Forcer une mise à jour (console)
```javascript
navigator.serviceWorker.getRegistration().then(reg => reg.update());
```
---
## 6. Débogage
### Vérifier l'installation
Chrome DevTools → onglet **Application** :
- **Manifest** : métadonnées ;
- **Service Workers** : enregistrement ;
- **Cache Storage** : contenu du cache.
### Désinstaller le Service Worker
```javascript
navigator.serviceWorker.getRegistrations().then(regs => regs.forEach(r => r.unregister()));
```
---
## 7. Limites
- Le hors-ligne dépend des données déjà mises en cache.
- Les actions d'écriture hors-ligne s'appliquent à la reconnexion (pas en temps
réel).
- iOS applique des contraintes spécifiques (persistance, notifications).
Voir [Édition & collaboration](./COLLABORATION.md) pour le temps réel.
+54
View File
@@ -0,0 +1,54 @@
# 📚 Guides d'utilisation ObsiGate
Bienvenue dans le répertoire des **guides utilisateur** d'ObsiGate. Chaque guide est
autonome, écrit en français et illustré d'exemples concrets (commandes, configuration,
captures conceptuelles).
> **Vous découvrez ObsiGate ?** Commencez par le **[Guide de prise en main](./PRISE_EN_MAIN.md)**.
> Une aide rapide est aussi intégrée directement dans l'application (menu Options →
> **Guide d'utilisation**, FR/EN, téléchargeable en Markdown et PDF).
---
## 🗂️ Sommaire des guides
| Guide | Public | Contenu |
|---|---|---|
| 🚀 [Prise en main](./PRISE_EN_MAIN.md) | Tous | Premier lancement, interface, navigation, vaults, raccourcis |
| 🔍 [Recherche, PDF & Excalidraw](./RECHERCHE_PDF_EXCALIDRAW.md) | Tous | Syntaxe de requête, recherche sémantique, lecteur PDF, diagrammes |
| 🤖 [Assistant IA & Forge](./ASSISTANT_IA_FORGE.md) | Tous | Fournisseurs, éditeur IA, BooksLM, Forge, commandes `@` / `/` |
| 📝 [Édition & collaboration](./COLLABORATION.md) | Tous | Édition simultanée, curseurs distants, persistance |
| 📱 [PWA & mode hors-ligne](./PWA_HORS_LIGNE.md) | Tous | Installation PWA, cache, file de synchronisation, notifications |
| 🔌 [API REST](./API_REST.md) | Développeurs | Authentification, clés API, endpoints, exemples `curl`, SSE |
| 🧩 [Serveur MCP](./MCP.md) | Développeurs / IA | Brancher Claude Desktop, Cursor, Cline… sur vos vaults |
| 🔒 [Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md) | Admin | Utilisateurs, MFA, permissions par vault, bonnes pratiques |
| 🐳 [Déploiement Docker](./DEPLOIEMENT_DOCKER.md) | Admin / Ops | `docker-compose`, volumes, reverse proxy, mises à jour |
| 🖥️ [Application desktop (Tauri)](./DESKTOP.md) | Tous | Installation, premier lancement, build depuis les sources |
---
## 🧭 Par où commencer ?
- **Je veux juste utiliser l'application** → [Prise en main](./PRISE_EN_MAIN.md)
- **Je veux sécuriser mon instance** → [Authentification & sécurité](./AUTHENTIFICATION_SECURITE.md)
- **Je veux brancher une IA** → [Assistant IA & Forge](./ASSISTANT_IA_FORGE.md) puis [MCP](./MCP.md)
- **Je veux scripter/automatiser** → [API REST](./API_REST.md)
- **Je veux héberger sur un serveur** → [Déploiement Docker](./DEPLOIEMENT_DOCKER.md)
---
## 📖 Documentation associée
| Type | Où |
|---|---|
| Vue d'ensemble produit | [`README.fr.md`](../../README.fr.md) · [`README.md`](../../README.md) |
| Conception détaillée par fonctionnalité | [`docs/features/`](../features/) |
| Standards de code | [`docs/CONTRIBUTING.md`](../CONTRIBUTING.md) |
| Méthode de livraison (Definition of Done) | [`docs/DELIVERY_WORKFLOW.md`](../DELIVERY_WORKFLOW.md) |
| Roadmap / travail à venir | [`docs/ROADMAP.md`](../ROADMAP.md) |
| Historique des versions | [`CHANGELOG.md`](../../CHANGELOG.md) |
| API interactive (Swagger / ReDoc) | `/docs` · `/redoc` (instance ObsiGate) |
> **Convention :** ce répertoire est la **porte d'entrée utilisateur**. Le *comment*
> (utilisation) vit ici ; le *pourquoi* (conception technique) vit dans
> [`docs/features/`](../features/). Ne jamais dupliquer le détail technique des fiches.
+193
View File
@@ -0,0 +1,193 @@
# 🔍 Guide Recherche, PDF & Excalidraw
ObsiGate va au-delà de la simple lecture : recherche puissante, rendu des
documents riches (PDF, diagrammes) et indexation de leur contenu pour que tout
soit retrouvable.
> **Public :** tous les utilisateurs
> **Fiches techniques :** [`features/semantic-search.md`](../features/semantic-search.md) ·
> [`features/pdf.md`](../features/pdf.md) · [`features/excalidraw.md`](../features/excalidraw.md)
---
## 1. Recherche plein texte (TF-IDF)
Le moteur d'ObsiGate s'appuie sur un **index inversé** et un scoring **TF-IDF**
avec :
- **Boost titre** — une correspondance dans le titre pèse 3× plus.
- **Normalisation des accents** — `resume` trouve `résumé`, `elephant` trouve `éléphant`.
- **Stemming français** — les variantes des mots sont rapprochées.
- **Snippets surlignés** — les termes trouvés sont mis en `<mark>` dans l'extrait.
- **Facettes** — compteurs par vault et par tag sur les résultats.
- **Pagination** — 50 résultats par page.
- **Tri** — par pertinence (TF-IDF) ou par date de modification.
- **Chips de filtres** — les filtres actifs apparaissent sous forme de puces retirables.
- **Historique** — les 50 dernières recherches sont conservées en `localStorage`.
La recherche s'effectue **sans I/O disque** : le contenu est déjà en mémoire.
---
## 2. Syntaxe de requête
| Opérateur | Description | Exemple |
|---|---|---|
| `tag:<nom>` | Filtre par tag | `tag:recette docker` |
| `#<nom>` | Raccourci de tag | `#linux serveur` |
| `vault:<nom>` | Filtre par vault | `vault:IT kubernetes` |
| `title:<texte>` | Filtre par titre | `title:pizza` |
| `path:<texte>` | Filtre par chemin | `path:recettes/soupes` |
| `ext:<type>` | Filtre par type de fichier | `ext:md kubernetes` |
| `"phrase exacte"` | Recherche d'une phrase | `tag:"multi mots"` |
Les opérateurs sont **combinables** :
```text
tag:linux vault:IT ext:md serveur web
```
Cette requête cherche « serveur web » dans les fichiers Markdown de la vault
`IT` portant le tag `linux`.
### Filtres par extension
| Extension | Contenu |
|---|---|
| `ext:md` | Notes Markdown |
| `ext:py`, `ext:sh`, `ext:js` | Scripts et code |
| `ext:pdf` | Documents PDF (texte extrait) |
| `ext:excalidraw` | Diagrammes Excalidraw (texte extrait) |
---
## 3. Autocomplétion et suggestions
- **`/api/suggest`** — suggère des titres de fichiers.
- **`/api/tags/suggest`** — suggère des tags.
- Navigation clavier : `↑` / `↓` puis `Entrée` ; `Échap` ferme les suggestions.
### Raccourcis de recherche
| Raccourci | Action |
|---|---|
| `Ctrl + K` / `Cmd + K` | Focaliser la barre de recherche |
| `/` | Focaliser la recherche (hors champ texte) |
| `↑` / `↓` | Naviguer dans les suggestions |
| `Entrée` | Sélectionner la suggestion active ou lancer la recherche |
| `Échap` | Fermer les suggestions / quitter la recherche |
Recherches sauvegardées et signets sont disponibles via l'API
(`/api/saved-searches`, `/api/bookmarks`).
---
## 4. Recherche sémantique (optionnelle)
Au classement TF-IDF peut s'ajouter un classement **par embeddings**, fusionné
via la méthode **RRF** (Reciprocal Rank Fusion). Activation : touche `~`
(ou `Alt + S`) dans la recherche.
Deux modes :
1. **Sans dépendance** — un *embedder* par hachage fournit une base utilisable
immédiatement.
2. **Embeddings réels** — installez `backend/requirements-semantic.txt` et/ou
renseignez les variables `OBSIGATE_EMBEDDING_*` pour utiliser
`all-MiniLM-L6-v2`.
Détails et configuration :
[`features/semantic-search.md`](../features/semantic-search.md).
---
## 5. Support PDF
### Lecture
Les fichiers PDF de vos vaults s'affichent **en ligne** dans le navigateur via le
visualiseur PDF natif (iframe + `<embed>`). Le fichier est **streamé** en HTTP
Range (`206 Partial Content`) : les gros PDF se chargent progressivement.
### Recherche
Le texte est **extrait à l'indexation** (`pypdf` / `pymupdf`), donc le contenu
des PDF est recherchable via la recherche plein texte. Utilisez `ext:pdf` pour
limiter les résultats aux PDF.
### Métadonnées
`GET /api/file/{vault}/pdf/info` renvoie les métadonnées (pages, titre, auteur)
**sans transférer** le document.
```bash
curl "http://localhost:2020/api/file/Recettes/pdf/info?path=menu.pdf"
```
### Limites
- **Pas d'OCR** : les PDF scannés (images) ne sont pas recherchables.
- Pas d'annotation ni d'édition du PDF lui-même.
---
## 6. Diagrammes Excalidraw
Les fichiers `.excalidraw` et `.excalidraw.md` (dont le format compressé du
**plugin Obsidian Excalidraw**) s'ouvrent dans un **éditeur visuel Excalidraw
complet**, dans une iframe sandboxée.
- **Dessin et édition** sans quitter ObsiGate.
- **Sauvegarde automatique** (débounce 2 s) ou `Ctrl + S`.
- **Thème** clair/sombre suivi automatiquement.
- **Texte indexé** : le texte des éléments du diagramme est extrait à
l'indexation et donc recherchable (`ext:excalidraw`).
Fiche technique : [`features/excalidraw.md`](../features/excalidraw.md).
---
## 7. Autres contenus riches
### Mermaid
Les blocs de code ` ```mermaid ` sont rendus en diagrammes interactifs (live
preview, thèmes, zoom, plein écran, pré-processeur compatible syntaxe Obsidian).
### Images Obsidian
Toutes les syntaxes d'images sont supportées avec résolution intelligente en
7 stratégies :
1. chemin absolu ;
2. dossier d'attachements configuré (`VAULT_N_ATTACHMENTS_PATH`) ;
3. index de démarrage (correspondance unique) ;
4. même répertoire que la note ;
5. racine de la vault ;
6. index de démarrage (correspondance la plus proche) ;
7. repli : `[image not found: fichier.ext]`.
Rescan manuel des attachements :
```bash
curl -X POST "http://localhost:2020/api/attachments/rescan/Recettes"
```
### Graphe et backlinks
- **Graphe** : vue force-directed (Barnes-Hut), filtres (tag, type), profondeur,
mode focus, export PNG, aperçu au survol (`Ctrl + clic`).
- **Backlinks** : `GET /api/file/{vault}/backlinks?path=…` liste les notes
pointant vers un document.
---
## 8. Dépannage
| Symptôme | Piste |
|---|---|
| Un PDF ne s'affiche pas | Vérifier la taille (`OBSIGATE_PDF_MAX_SIZE_MB`, défaut 50 Mo) |
| Le texte d'un PDF scanné n'est pas trouvé | Pas d'OCR : normal |
| Une image reste introuvable | Configurer `VAULT_N_ATTACHMENTS_PATH`, puis rescan |
| La recherche sémantique ne s'active pas | Vérifier le toggle `~` et `OBSIGATE_EMBEDDING_*` |
| Résultats obsolètes | Forcer une réindexation : `GET /api/index/reload` |
+11
View File
@@ -176,6 +176,11 @@ Avant de corriger quoi que ce soit, un agent IA doit :
| *BUG-065* | [🟡 IMPORTANT] Éditeur Excalidraw : l'auto-save recharge la page en pleine édition | 🟢 corrigé | P1 | 📱 frontend | IA | `frontend/js/excalidraw-viewer.js`, `frontend/js/utils.js`, `frontend/excalidraw-editor.html`, `tests/frontend/excalidraw-viewer.test.mjs` | Ouvrir un `.excalidraw` puis modifier un élément : au bout de 2 s la vue se recharge | Chaque modification déclenchait un `PUT save` 2 s plus tard → SSE `index_updated` → `reloadExternalWrite` → `openFile` → **recréation de l'iframe** (refresh visible). Auto-save supprimée : sauvegarde explicite (bouton 💾 / Ctrl+S). `reloadExternalWrite` ignore le fichier si un iframe Excalidraw est ouvert (`iframe[data-excalidraw-vault/path]`). Le badge « Modified » ne réagit plus aux changements d'`appState` (resize/zoom) mais à la signature des éléments. | Vérifié Playwright : plus de refresh, badge stable après bascule plein écran. Test statique (absence de `requestSave`/`saveTimer`). |
| *BUG-066* | [🔵 MINEUR] Configuration : icônes manquantes dans la table des matières (« Fichiers cachés », « Partages publics ») | 🟢 corrigé | P3 | 📱 frontend | IA | `frontend/locales/{fr,en}.json` | Ouvrir Configuration → observer le sommaire : les entrées « Fichiers cachés » et « Partages publics » n'ont pas d'icône | `config.section_hidden` → « 🗂️ Fichiers cachés » / « 🗂️ Hidden files », `config.section_shares` → « 📤 Partages publics » (EN avait déjà l'icône). Test : `tests/frontend/unit.test.mjs` (+1 : toutes les entrées du sommaire portent une icône FR/EN) | Les libellés du sommaire utilisent des clés i18n distinctes des titres de section (`auto.f8ba6127`, `config.section_partages-publics`) qui, elles, avaient l'icône |
| *BUG-067* | [🔵 MINEUR] Guide d'utilisation : l'entrée « 📱 Mobile » du sommaire ne fait rien (section absente) | 🟢 corrigé | P3 | 📱 frontend | IA | `frontend/index.html` | Ouvrir le Guide → cliquer « 📱 Mobile » dans le sommaire : rien ne se passe | L'ancre `#help-mobile-editor` était présente dans la TOC mais aucune section `id="help-mobile-editor"` n'existait (l'édition mobile n'était qu'un h3 de `help-edition`). Fix #105 : section dédiée créée avec ancre + entrée de nav cohérente. | Vérifié par test statique `tests/test_guide.py::test_nav_anchors_resolve` |
| *BUG-068* | Configuration — section « 🔒 Sécurité du compte » inachevée : boutons hors thème, QR code invisible, fiabilité des fonctions à valider | 🟢 corrigé | P1 | 📱 frontend + ⚙️ backend | IA | `frontend/js/auth.js`, `frontend/style.css`, `backend/auth/router.py` | Configuration → 🔒 Sécurité du compte | `frontend/style.css` (+`config-btn-primary`/`danger` thème), `backend/auth/router.py` (`qr_data_url` segno local), `frontend/js/auth.js` (QR local + fallback, recovery WebAuthn, carte mot de passe, escapeHtml labels), locales FR/EN, `backend/requirements.txt` (+segno) ; tests `tests/test_mfa.py` (+1) + `tests/frontend/mfa-settings.test.mjs` (nouveau, 9) | pytest 1241 passed / 6 skipped, ruff 0, mypy 0, frontend unit + validate-imports verts |
| *BUG-069* | Login 2FA bloqué sans erreur : après user+pwd corrects, la page de login reste affichée et le challenge MFA n'apparaît jamais | 🟢 corrigé | P0 | 📱 frontend | IA | `frontend/js/auth.js`, `frontend/index.html` | Activer 2FA → logout → login (bon user+pwd) | `frontend/js/auth.js` (`showMfaChallenge` → `.login-card` + erreur `mfa.challenge_unavailable` si montage impossible), locales FR/EN ; tests `tests/frontend/mfa-settings.test.mjs` (+2) | Reproduit au navigateur avant correctif (challenge jamais affiché), vérifié après : challenge affiché, code erroné → erreur, code valide (200) → app ; frontend mfa-settings 11/11, unit + validate-imports verts |
| *BUG-070* | Activation clé physique WebAuthn impossible : « Validation du credential WebAuthn échouée » à chaque tentative | 🟢 corrigé | P0 | ⚙️ backend | IA | `backend/auth/webauthn_mfa.py`, `backend/auth/router.py` | Config → Sécurité → Ajouter une clé → cérémonie navigateur → 400 | `resolve_relying_party()` (rp_id/origines dérivés de la requête, config explicite prioritaire, forwarded si TRUST_PROXY) sur les 4 endpoints ; challenges multiples (5 derniers) acceptés ; `.env.example` ; tests `tests/test_webauthn.py` (+8) | Logs : origin `http://localhost:2020` rejetée + challenge mismatch au retry. Vérifié navigateur (authentificateur virtuel CDP) : register 200 + clé listée, clé de test retirée (admin de nouveau TOTP seul) ; pytest 1249 passed, ruff/mypy 0 |
| *BUG-071* | Configuration « Configurations » inutilisable en mode mobile : sommaire masqué sans bouton d'accès, navigation par ancre sans JS, grilles 2 colonnes et rangées d'ajout qui débordent (≤768px) | 🟢 corrigé | P1 | 📱 frontend | IA | `frontend/index.html`, `frontend/js/config.js`, `frontend/js/i18n.js`, `frontend/style.css`, `frontend/locales/{fr,en}.json` | Mobile (≤768px) : ouvrir Configurations → aucun sommaire ni moyen d'atteindre une section ; champs « Clés IA » / jetons / webhooks débordent | `index.html` (+`#config-hamburger` `.help-hamburger`, `config.toc_toggle` FR/EN) ; `config.js` (toggle, scroll doux + actif + repli auto mobile, reset à l'ouverture) ; `i18n.js` (`data-i18n-attr` multi-paires `;`) ; `style.css` (bloc mobile `#config-modal` : sommaire haut 46vh, grilles 1fr, add-rows wrap + `!important`, items wrap, 44px) ; tests `tests/frontend/config-mobile.test.mjs` (nouveau, 11) + CI ; E2E `tests/e2e/config-mobile.spec.js` (nouveau, 3/3 projet chromium-mobile, ignoré en desktop) | pytest 1249 passed / 6 skipped, ruff 0, mypy 0, validate-imports 39 modules, unit 10/10, JSDOM ai 93/93 + sidebar 6/6 + mobile 35/35 + ai-keys 7/7 |
| *BUG-072* | Visionneuse d'images : le plein écran et le panneau « Métadonnées » ne sont pas conservés lors de la navigation ←/→, et le panneau s'affiche sous la pellicule au lieu d'une barre latérale | 🟢 corrigé | P2 | 📱 frontend | IA | `frontend/js/viewer.js`, `frontend/style.css` | Ouvrir une image, activer le plein écran (ou Métadonnées), puis naviguer avec les flèches précédent/suivant | État persistant `_imageViewerState { lightbox, meta }` + drapeau `_imageViewerNavPending` posé par `go()`/pellicule : `renderFile` ne réinitialise que hors navigation image→image. Panneau reconstruit dans `.image-viewer-body` (sidebar droite, `border-left`, `width:280px; max-width:40%`) ; la règle lightbox ne masque plus que la pellicule. Boutons `image-btn-lightbox`/`image-btn-metadata` (+ `aria-pressed`), `Escape` resynchronisé. Tests : `tests/frontend/image-viewer.test.mjs` (+2), E2E `tests/e2e/image-viewer.spec.js` (+1). | Navigation → `openFile` → `renderImageViewer` recréait le conteneur : les états `lightbox`/`metaPanel` étaient perdus. Le panneau était rendu en bas (colonne) au lieu d'une sidebar droite |
| | | | | | | | | | | |
### TODOs techniques (améliorations / nouvelles tâches)
@@ -249,6 +254,12 @@ Avant de corriger quoi que ce soit, un agent IA doit :
| 2026-09-18 | BUG-066 | Correction | `frontend/locales/fr.json`, `frontend/locales/en.json`, `tests/frontend/unit.test.mjs`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-066** : la table des matières de la page de configuration n'affichait aucune icône pour « Fichiers cachés » et « Partages publics ». Les libellés du sommaire proviennent de clés i18n (`config.section_hidden`, `config.section_shares`) distinctes des titres de section qui, eux, portaient déjà l'icône. Alignement : 🗂️ / 📤 en FR **et** EN. Test de non-régression : `unit.test.mjs` vérifie que **toutes** les entrées `.help-nav-link` du sommaire portent une icône dans les deux langues (17/17). Vérifié : `unit.test.mjs` 10/10, `validate-imports` 38 modules. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-18 | #105, BUG-067 | Documentation + correction | `frontend/index.html`, `frontend/js/config.js`, `frontend/style.css`, `frontend/locales/{fr,en}.json`, `backend/guide_export.py`, `backend/main.py`, `tests/test_guide.py`, `docs/features/guide-coverage-105.md`, `CHANGELOG.md`, `docs/ROADMAP.md`, `docs/ISSUES_TODOLIST.md` | **#105** : audit complet de couverture du Guide d'utilisation — 8 nouvelles sections (Architecture + diagramme Mermaid, API & intégrations, Diagrammes Mermaid & Excalidraw, Hors-ligne & synchronisation, Collaboration temps réel, Application desktop, Bibliothèque & signets, Multilingue) et compléments (recherche sémantique, MFA/WebAuthn, notifications push, exports HTML/ePub/ZIP, PDF, vue multi-panneaux, admin). Téléchargement du guide en Markdown et PDF (`GET /api/guide/download?format=md|pdf`, FR/EN, rendu par le moteur d'export existant). Guide plus large en desktop. **BUG-067** : ancre morte `#help-mobile-editor` → section dédiée créée. | 🟢 corrigé (en attente vérif utilisateur)
| 2026-09-18 | #105 (ajustements) | Amélioration | `frontend/index.html`, `frontend/js/config.js`, `frontend/sw.js`, `frontend/locales/{fr,en}.json`, `backend/guide_export.py`, `backend/pdf_export.py`, `Dockerfile`, `scripts/build_guide_diagrams.py`, `scripts/render_guide_diagram.mjs`, `scripts/guide_content.py`, `backend/assets/guide_diagrams/df7366a40db6a5a2.png`, `tests/test_guide.py`, `docs/features/guide-coverage-105.md`, `CHANGELOG.md` | **#105 (retour utilisateur)** : 1) boutons de téléchargement du guide passés en icônes seules (tooltips i18n conservés) ; 2) le diagramme Mermaid de la section Architecture est désormais rendu en **vraie image** dans le PDF (pipeline de pré-rendu PNG Chromium+mermaid v11, PNG commité sous `backend/assets/guide_diagrams/<sha1>.png`, résolu par `diagram_png_for()` ; le Markdown garde le fenced mermaid) ; 3) emoji du PDF rendus **en couleur** au lieu de rectangles : `fonts-noto-color-emoji` ajouté au Dockerfile + `"Noto Color Emoji"` en fin de pile de polices PDF. Vérifié : pytest 1218 (test_guide ×13), ruff/mypy 0, validate-imports 38, unit 10/10 ; PDF live conteneur 2020 : 24 pages, 0 glyphes tofu, diagramme 3568x1174 embarqué. | 🟢 livré
| 2026-09-22 | BUG-068 | Correction | `backend/auth/router.py`, `backend/requirements.txt`, `frontend/js/auth.js`, `frontend/style.css`, `frontend/locales/{fr,en}.json`, `tests/test_mfa.py`, `tests/frontend/mfa-settings.test.mjs` (nouveau), `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-068** : section « 🔒 Sécurité du compte » finalisée. (1) Boutons hors thème : `config-btn-primary`/`config-btn-danger` n'existaient pas en CSS → définis depuis les variables du thème (+ états disabled). (2) QR invisible : l'image tierce était bloquée par la CSP (`img-src 'self' data: blob:`) et exposait le secret TOTP → QR SVG `data:` généré en local par le backend (`qr_data_url`, segno) avec repli saisie manuelle. (3) Codes de récupération perdus à la 1re activation WebAuthn → `_showRecoveryCodes(codes, targetId)` avec repli `webauthn-flow-area`. (4) Carte « Mot de passe » ajoutée (endpoint `change-password` existant, jusque-là sans UI) + échappement des libellés de clés WebAuthn. Vérifié : pytest 1241 passed / 6 skipped, ruff 0, mypy 0 (78 fichiers), `mfa-settings.test.mjs` 9/9, unit 10/10, validate-imports 39 modules. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-23 | BUG-069 | Correction | `frontend/js/auth.js`, `frontend/locales/{fr,en}.json`, `tests/frontend/mfa-settings.test.mjs`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-069** : login 2FA bloqué sans erreur — après user+pwd corrects, `showMfaChallenge` cherchait `.login-box` (inexistant dans `index.html`, marquage réel `#login-screen > .login-card`) et faisait un `return` silencieux : page de login figée, aucune erreur. Correctif : montage dans `.login-card` (repli `#login-screen`) + erreur visible `mfa.challenge_unavailable` (FR/EN) si le point de montage manque. **Reproduit au navigateur** (Playwright, instance Docker `obsigate-test`, compte jetable avec TOTP) : avant → challenge jamais affiché ; après → challenge affiché, code erroné → erreur, code valide (verify 200) → app. Tests : `mfa-settings.test.mjs` 11/11 (+2 ancrage DOM), unit 10/10, validate-imports 39 modules. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-23 | BUG-070 | Correction | `backend/auth/webauthn_mfa.py`, `backend/auth/router.py`, `.env.example`, `tests/test_webauthn.py`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-070** : activation WebAuthn rejetée en 400. (1) Défauts `localhost` sans port → `resolve_relying_party()` dérive rp_id/origines de la requête (config explicite prioritaire, forwarded sous TRUST_PROXY), appliqué aux endpoints register + login. (2) Challenge single-use → 5 derniers conservés, vérification contre le challenge de la cérémonie en cours. **Vérifié au navigateur** (authentificateur virtuel CDP, instance Docker) : register 200, clé listée, clé de test retirée. Tests : `test_webauthn.py` 19/19 (+8), suite complète 1249 passed / 6 skipped, ruff/mypy 0. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-23 | BUG-071 | Correction | `frontend/index.html`, `frontend/js/config.js`, `frontend/js/i18n.js`, `frontend/style.css`, `frontend/locales/{fr,en}.json`, `tests/frontend/config-mobile.test.mjs` (nouveau), `.gitea/workflows/ci.yml`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-071** : page « Configurations » inutilisable en mobile. (1) `#config-nav` masquée sous 768px sans toggle → hamburger `#config-hamburger` ajouté à l'en-tête (`.help-hamburger`, libellé `config.toc_toggle` FR/EN). (2) Ancres brutes sans JS → interception en `config.js` (scroll doux, lien actif, repli auto mobile, reset à l'ouverture). (3) Débordements 360px → bloc CSS mobile `#config-modal` (sommaire haut 46vh, grilles 1fr, add-rows wrap + largeurs inline neutralisées, items wrap, cibles 44px). `data-i18n-attr` multi-paires (`;`). Vérifié : `config-mobile.test.mjs` 11/11 (nouveau, au CI), pytest 1249 passed / 6 skipped, ruff/mypy 0, validate-imports 39 modules, unit 10/10, JSDOM ai 93/93 + ai-sidebar 6/6 + sidebar-filters 8/8 + mobile-editor 35/35 + config-ai-keys 7/7. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-23 | BUG-071 (complément E2E) | Test | `tests/e2e/config-mobile.spec.js` (nouveau), `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-071 (complément E2E)** : spec Playwright mobile (convention `mobile-editor.spec.js` : `test.skip` hors viewport ≤768px, donc inactive sur le projet `chromium-desktop` du CI). Vérifié en local sur l'instance de test (port 2029, auth désactivée) : hamburger → sommaire, sélection → scroll + actif + repli, 0 débordement horizontal à 393px (3/3 `chromium-mobile`, 3 ignorés en desktop) ; suite `mobile-editor.spec.js` intacte (3/3). | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-23 | BUG-072 | Correction | `frontend/js/viewer.js`, `frontend/style.css`, `tests/frontend/image-viewer.test.mjs`, `tests/e2e/image-viewer.spec.js`, `scripts/run-e2e-local.ps1` (nouveau), `package.json`, `AGENTS.md`, `README.md`, `README.fr.md`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-072** : dans la visionneuse d'images (#108-D), le plein écran (lightbox) et le panneau « Métadonnées » étaient perdus dès qu'on changeait d'image avec ←/→ (ou la pellicule), car `openFile` → `renderFile` recrée entièrement `renderImageViewer`. (1) **Persistance** : état module `_imageViewerState { lightbox, meta }` restauré à chaque rendu ; un drapeau `_imageViewerNavPending` posé par `go()` et le clic de vignette indique à `renderFile` que le rendu suivant est une navigation image→image (pas de réinitialisation) — toute autre ouverture repart à zéro. (2) **Panneau latéral** : `.image-meta-panel` déplacé dans un nouveau `.image-viewer-body` en flex row, à droite de `.image-stage` (`border-left`, `width:280px; max-width:40%`, défilement vertical) au lieu d'une bande sous la pellicule ; la règle lightbox ne masque plus que la pellicule. Boutons stables `image-btn-lightbox`/`image-btn-metadata` + `aria-pressed`, `Escape` resynchronise l'état. Tests statiques `image-viewer.test.mjs` (+2) et E2E Playwright (+1). **Diagnostic E2E** : `npm run test:e2e` bloquait car `bash` résout vers WSL (HS, Ubuntu `Stopped`, `HCS_E_CONNECTION_TIMEOUT`) et git-bash est bloqué par App Control → lanceur PowerShell ajouté. Vérifié : `image-viewer.spec.js` 4/4, **suite `chromium-desktop` complète 103 passed / 6 skipped (10,3 min)** via `scripts/run-e2e-local.ps1`, `image-viewer.test.mjs` 12/12, unit 10/10, validate-imports 40 modules. | 🟢 corrigé (en attente vérif utilisateur) |
---
+7 -179
View File
@@ -1,182 +1,10 @@
# ObsiGate — Guide MCP (Model Context Protocol)
# Guide MCP — déplacé
> **Statut :** livré (#79 phase E + F) · **Dernière mise à jour :** 2026-09-11
> **Voir aussi :** [AI_ARCHITECTURE_GUIDE.md](./AI_ARCHITECTURE_GUIDE.md) ·
> [features/ai-tools-mcp.md](./features/ai-tools-mcp.md) · [ROADMAP.md](./ROADMAP.md)
> Ce guide a été déplacé dans le répertoire des guides utilisateur :
> **[docs/GUIDES/MCP.md](./GUIDES/MCP.md)**.
ObsiGate expose ses vaults à des **clients MCP externes** (Claude Desktop, Cursor,
tout client compatible MCP) via un serveur **Streamable HTTP** monté sur `/mcp`.
Les outils sont les **mêmes** que ceux de l'assistant in-app : la couche
`backend/tools/` est la source unique de vérité.
Le serveur MCP d'ObsiGate (`/mcp`) expose les mêmes outils que l'assistant IA à
Claude Desktop, Cursor, Cline et tout client compatible MCP. Configuration,
outils, resources/prompts, sécurité et dépannage s'y trouvent désormais.
---
## 1. Prérequis
1. Une instance ObsiGate accessible (locale ou distante).
2. Un **jeton JWT** valide (`Authorization: Bearer <token>`), obtenu via
`POST /api/auth/login` (ou une clé API). Le jeton porte les permissions par
vault de l'utilisateur — l'autorisation MCP réutilise `get_current_user`.
3. Si l'authentification est désactivée (`OBSIGATE_AUTH_ENABLED=false`), le
serveur MCP accepte un utilisateur anonyme disposant de tous les vaults.
> Le transport `stdio` n'est **pas** encore supporté ; utilisez le transport
> HTTP (un pont local type `mcp-remote` si votre client ne gère pas nativement
> le Streamable HTTP distant).
---
## 2. Endpoint & protocole
| Élément | Valeur |
|---|---|
| URL | `https://<obsigate>/mcp` |
| Transport | Streamable HTTP (`POST` JSON-RPC 2.0, `Accept: application/json, text/event-stream`) |
| Auth | `Authorization: Bearer <JWT>` |
| Protocole MCP | `2025-03-26` (négocié à l'`initialize`) |
| Réponses | JSON (`json_response=True`) |
Handshake minimal :
```bash
curl -sS https://obsigate.example/mcp \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: application/json, text/event-stream" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{
"protocolVersion":"2025-03-26","capabilities":{},
"clientInfo":{"name":"curl","version":"1.0"}}}'
```
La réponse contient l'en-tête `Mcp-Session-Id` à réutiliser pour les appels
suivants (`tools/list`, `tools/call`, `resources/read`, …).
---
## 3. Configuration des clients
### Claude Desktop (via pont `mcp-remote`)
```json
{
"mcpServers": {
"obsigate": {
"command": "npx",
"args": [
"-y", "mcp-remote",
"https://obsigate.example/mcp",
"--header", "Authorization: Bearer ${OBSIGATE_TOKEN}"
],
"env": { "OBSIGATE_TOKEN": "eyJ..." }
}
}
}
```
### Cursor
`.cursor/mcp.json` :
```json
{
"mcpServers": {
"obsigate": {
"url": "https://obsigate.example/mcp",
"headers": { "Authorization": "Bearer eyJ..." }
}
}
}
```
---
## 4. Primitives exposées
### 4.1 Tools
Les outils de **lecture/recherche** sont exposés directement. Les outils
**d'écriture/destructifs** sont exposés via une paire **two-step** :
`propose_<tool>` (aperçu + jeton de confirmation, aucune modification) puis
`apply_<tool>` (consomme le jeton et exécute).
| Catégorie | Outils |
|---|---|
| Vaults / navigation | `list_vaults`, `list_directory`, `list_all_files` |
| Lecture | `read_file`, `read_file_raw`, `get_backlinks`, `list_backups`, `diff_backup`, `get_graph` |
| Recherche | `search_fulltext`, `search_advanced`, `search_paths`, `list_tags`, `suggest_tags`, `list_recent` |
| Écriture (propose/apply) | `create_file`, `create_directory`, `edit_file`, `append_to_file`, `restore_backup` |
| Destructif (propose/apply) | `rename_file`, `rename_directory`, `move_path`, `replace_in_files`, `delete_file`, `delete_directory` |
Flux d'une mutation :
```text
1. tools/call { name: "propose_edit_file",
arguments: { vault, path, content } }
→ { tool, arguments, diff, confirmation_token, expires_in }
2. (l'utilisateur / l'agent valide)
3. tools/call { name: "apply_edit_file",
arguments: { confirmation_token } }
→ { ok: true, data: { ... } }
```
Le jeton est **signé (JWT), à usage unique et à durée de vie limitée**
(`OBSIGATE_MCP_CONFIRMATION_TTL`, défaut 300 s). Un rejeu renvoie
`token_reused`.
### 4.2 Resources
| URI | Contenu |
|---|---|
| `vault://<name>` | Vault accessible (métadonnées, nombre de fichiers) |
| `vault://<name>/<path>` | Contenu d'un fichier (lecture seule, **secrets redactés**) |
### 4.3 Prompts
`summarize-directory`, `generate-note`, `find-related`.
---
## 5. Sécurité
- **Permissions par vault** : `check_vault_access` est appliqué à chaque outil
et chaque resource ; un utilisateur ne voit que ses vaults.
- **Anti path-traversal** : `resolve_safe_path` rejette tout chemin hors du vault.
- **Confirmation two-step** pour toute mutation (jeton signé, usage unique).
- **Toggle par vault** `aiDestructiveTools` (défaut : activé) : le désactiver
bloque rename/move/replace/delete tout en laissant create/edit/append.
- **Backup automatique** avant chaque opération destructive.
- **Rate limiting** : par jeton et par outil
(`OBSIGATE_TOOL_RATE_LIMIT`, `OBSIGATE_TOOL_RATE_LIMIT_PER_TOOL`,
`OBSIGATE_TOOL_RATE_WINDOW`). Une limite dépassée renvoie le code
`rate_limited`.
- **Redaction des secrets** : les résultats d'outils (lectures, diffs,
extraits de recherche) sont nettoyés avant tout retour au client.
- **Audit** : chaque appel est journalisé (`data/audit.log`, action
`ai_tool_call`) avec arguments sensibles résumés.
### Variables d'environnement
| Variable | Défaut | Rôle |
|---|---|---|
| `OBSIGATE_MCP_CONFIRMATION_TTL` | `300` | Durée de vie (s) des jetons de confirmation |
| `OBSIGATE_TOOL_RATE_LIMIT` | `60` | Appels d'outils max par identité et par fenêtre |
| `OBSIGATE_TOOL_RATE_LIMIT_PER_TOOL` | = global | Appels max par outil et par fenêtre |
| `OBSIGATE_TOOL_RATE_WINDOW` | `60` | Longueur de la fenêtre (s) |
| `BOOKSLM_MAX_TOOL_CALLS` | `25` | Quota d'appels d'outils par run d'agent |
| `BOOKSLM_MAX_TOOL_READ_BYTES` | `200000` | Taille max renvoyée par `read_file` |
---
## 6. Dépannage
| Symptôme | Cause probable / remède |
|---|---|
| `401 Authentification requise` | En-tête `Authorization: Bearer` absent ou jeton expiré |
| `vault_access_denied` | Le jeton n'a pas accès à ce vault (`vaults` / `_token_vaults`) |
| `destructive_tools_disabled` | `aiDestructiveTools=false` pour ce vault |
| `confirmation_required` | Appeler d'abord `propose_<tool>` puis `apply_<tool>` |
| `token_reused` / `invalid_confirmation` | Jeton déjà consommé ou expiré → refaire un `propose_` |
| `rate_limited` | Quota dépassé ; respecter `retry_after` |
| Le client ne se connecte pas | Vérifier le transport Streamable HTTP / le pont `mcp-remote` |
Sommaire des guides : [docs/GUIDES/README.md](./GUIDES/README.md).
+9 -13
View File
@@ -1,6 +1,6 @@
# ObsiGate — Roadmap
> **Version :** 2.14.0 | **Dernière mise à jour :** 2026-09-19
> **Version :** 2.19.2 | **Dernière mise à jour :** 2026-09-23
> **Ce fichier ne contient que le travail à venir** (🔵 En cours + ⚪ Backlog) et un index compact
> vers les fonctionnalités livrées.
> - **Méthode de livraison à appliquer pour toute tâche : [DELIVERY_WORKFLOW.md](./DELIVERY_WORKFLOW.md)**
@@ -107,15 +107,6 @@
- [ ] Persister index, JTI révoqués et compteurs de rate-limit (SQLite/Redis)
- [ ] Verrous asyncio autour de l'index global et des stores JSON ; service de partage public (expiration, révocation, quotas)
### 86. Optimisation globale des performances (phase 3)
- **Effort :** 4-6 jours | **Impact :** 🟡 | **Zone :** backend (`search.py`, `indexer.py`, `mutations.py`)
- **Description :** brancher l'inverted index (déjà construit) sur la recherche simple et le tool IA `search_fulltext`, indexation incrémentale, extraction PDF lazy.
- **Sous-tâches :**
- [ ] Recherche simple + tool IA via l'inverted index (suppression du balayage O(N) en mémoire)
- [ ] Indexation incrémentale + scan différentiel au démarrage (remplace le `rglob` complet)
- [ ] Extraction PDF/excalidraw différée (hors scan) ; caps CPU sur les opérations regex
### 87. Amélioration continue — tests, CI/CD, revues de sécurité (phase 4)
- **Effort :** 3-5 jours | **Impact :** 🟡 | **Zone :** `.gitea/workflows/`, `tests/`
@@ -189,6 +180,11 @@
| 104 | Configuration — Redesign UI de la section « Clés API IA » : recherche fournisseurs, carte défaut 2 colonnes + badges de capacités, cartes dépliables, footer d'actions sticky | 2.12.0 | [features/ai-keys-ui.md](./features/ai-keys-ui.md) |
| 105 | Guide d'utilisation — audit de couverture complet, téléchargement Markdown/PDF, guide desktop élargi, section Architecture (Mermaid) + BUG-067 | 2.13.0 | [features/guide-coverage-105.md](./features/guide-coverage-105.md) |
| 106 | Assistant IA — Actions instantanées contextuelles, catalogue « Toutes les actions » & frontmatter complet | 2.14.0 | [features/ai-quick-actions.md](./features/ai-quick-actions.md) |
| 107 | Configuration — Gestion des clés API & MCP : création/révocation de jetons longue durée (1 j, 1 mois, 6 mois, 1 an, sans fin), une seule clé pour l'API REST et le serveur MCP, « dernière utilisation », store `data/api_tokens.json` sans secret persisté | 2.15.0 | [features/api-mcp-tokens-107.md](./features/api-mcp-tokens-107.md) |
| 86 | Optimisation globale des performances (phase 3) — scan différentiel, excalidraw différé, garde-fou `replace` (inverted index / PDF lazy / caps regex déjà livrés via BUG-033/040/025) | 2.16.0 | [features/perf-phase3-86.md](./features/perf-phase3-86.md) |
| 108 | Support complet des images — arborescence, visionneuse (zoom/pan/navigation/miniatures), indexation nom+métadonnées, `media_types.py`, filtre `ext:`, SVG sandbox | 2.17.0 | [features/image-support.md](./features/image-support.md) |
| 109 | Support audio & vidéo — lecteurs HTML5 intégrés, streaming HTTP Range (`/api/media`), fallback codec/taille | 2.18.0 | [features/media-viewers-109.md](./features/media-viewers-109.md) |
| 110 | Lecteur média persistant « Now Playing » — élément partagé téléporté (inline ⇄ dock), Media Session, mini-vidéo PiP, mobile, reprise | 2.19.0 | [features/media-viewers-109.md](./features/media-viewers-109.md) |
---
@@ -196,11 +192,11 @@
| Priorité | Items | Effort total estimé |
|---|---|---|
| ✅ Complété | #1 → #59, #61–72, #74–76, #78–84, #88–93, #94–100, #102–106, #92 | ~115 jours réalisés |
| ✅ Complété | #1 → #59, #61–72, #74–76, #78–84, #86, #88–93, #94–100, #102–110, #92 | ~130 jours réalisés |
| 🔵 P2 restant | #77 Desktop : signature de code (non retenue), 6 tests E2E **manuels** ([protocole](./DESKTOP_E2E_CHECKLIST.md)) | ~0,5-1 jour |
| ⚪ P4 restant | #73 Sync (6-8j) | 6-8 jours |
| ⚪ P0/P1 restant | #85-87 Refonte architecturale, performance, CI/CD (BUG-035 → BUG-040 corrigés) | ~15-23 jours |
| **Total restant** | **7 items + finitions** | **~27-42 jours** |
| ⚪ P0/P1 restant | #85, #87 Refonte architecturale, CI/CD (BUG-035 → BUG-040 corrigés, #86 livré) | ~11-17 jours |
| **Total restant** | **6 items + finitions** | **~23-38 jours** |
---
+1 -1
View File
@@ -67,7 +67,7 @@
`call_tool` (couvre les diffs, extraits de recherche et lectures non pré-redactées).
- [x] **F3.** Documentation OpenAPI + guide MCP — `backend/openapi_docs.py` : tag `MCP`,
règle `/mcp`, injection du path `/mcp` (Streamable HTTP, JSON-RPC) dans le schéma ;
nouveau [`docs/MCP_GUIDE.md`](../MCP_GUIDE.md) (endpoint, auth, config Claude Desktop /
nouveau [`docs/GUIDES/MCP.md`](../GUIDES/MCP.md) (endpoint, auth, config Claude Desktop /
Cursor, tools/resources/prompts, sécurité, variables, dépannage).
- [x] **F4.** Tests E2E de bout en bout — `tests/test_ai_e2e.py` : agent in-app
read→confirmation→write, quota d'outils, rate limiting, redaction, et flux MCP complet
+95
View File
@@ -0,0 +1,95 @@
# #107 — Clés API & MCP (panneau de configuration)
**Version : 2.15.0 — statut : complété (septembre 2026)**
## Problème
Pour brancher un client MCP externe (Claude Desktop, Cursor…) ou scripter
l'API REST, il fallait soit se connecter et voler le JWT de session de 1 h
dans le navigateur, soit générer un token à la main via `docker exec`
(`generer_access_token.sh`) — sans expiration maîtrisable ni révocation.
## Décision : une seule clé pour l'API ET le MCP
Le serveur MCP (`/mcp`, `backend/mcp/server.py::_authenticate`) résout
l'appelant via la même dépendance `get_current_user()` que l'API REST.
Un jeton HS256 `type=access` authentifie donc **les deux surfaces** — il
n'y a pas de famille de clés séparée à exposer dans l'UI. C'est dit
explicitement dans la section (« la même clé fonctionne pour les deux »)
et verrouillé par tests (REST 200 + MCP initialize 200 avec la même clé ;
révocation → 401 des deux côtés).
## Conception
### Store — `data/api_tokens.json`
```json
{"version": 1, "tokens": {"<jti>": {
"name": "Claude Desktop", "username": "admin",
"created_at": 1790000000, "expires_at": 1792592000,
"expiry_key": "30d", "last_used_at": null
}}}
```
Le JWT brut n'est **jamais persisté** : affiché une seule fois à la
création, sinon perdu (pattern GitHub). La révocation fonctionne par
`jti` : le JWT présenté est rejeté par `is_token_revoked` même s'il est
encore valide dans sa signature.
### Expirations (choix UI)
| Clé | Durée | `exp` dans le JWT |
|---|---|---|
| `1d` | 1 jour | iat + 86 400 |
| `30d` | 1 mois | iat + 2 592 000 |
| `180d` | 6 mois | iat + 15 552 000 |
| `365d` | 1 an | iat + 31 536 000 |
| `never` | sans fin | **aucun claim exp** |
Plafond : 50 tokens actifs par utilisateur (`API_TOKEN_MAX_PER_USER`).
### Correction induite — révocation longue durée
L'ancien `revoked_tokens.json` bornait toute entrée à 7 jours ; une clé
1 an révoquée aurait « repris vie » au nettoyage suivant. Le store devient
un dict `{jti: valid_until}` calé sur l'expiration réelle du jeton
(« sans fin » → 100 ans). Session tokens inchangés (7 j).
### « Dernière utilisation »
`get_current_user` appelle `maybe_touch_api_token(jti)` pour les jetons
`api: true` — écriture disque throttlée à 1 h par jti, silencieuse si le
dossier est en lecture seule ; ne fait jamais échouer une requête.
## Endpoints (`/api/auth`, auth requise, périmètre = l'appelant)
- `GET /api/auth/tokens` → `{tokens: [...], expiry_choices: [...]}`
- `POST /api/auth/tokens` `{name, expiry}` → `{token, ...record}` (secret unique)
- `DELETE /api/auth/tokens/{jti}` → révocation immédiate API + MCP
- Audit : `config_change` / `api_token_create|revoke`.
## UI — panneau Configuration
Nouvelle section `#cfg-tokens` « 🔑 Clés API & MCP » (après Sécurité) :
liste (badge Active/Expirée, créée/expire/dernière utilisation), champ
nom + sélecteur d'expiration + Créer, zone secrète en tirets avec Copier,
bloc « Utilisation » : header `Authorization: Bearer <clé>` + exemple de
config MCP avec headers sur `<base>/mcp`. 28 clés i18n FR/EN, SW v24.
## Tests — `tests/test_api_tokens.py` (13)
Création/liste (secret jamais restitué), les 5 durées dont l'absence
d'`exp` pour `never`, expiration invalide → 400, clé identique acceptée
par REST **et** `/mcp`, refus MCP anonyme, isolation par utilisateur,
révocation → 401 immédiat des deux côtés, survie de la révocation
longue durée après reload disque, drapeau `expired`, migration de format
`revoked_tokens.json`. Suite auth + MCP complète verte (77).
## Config MCP externe (exemple)
```json
{"mcpServers": {"obsigate": {
"url": "http://localhost:2020/mcp",
"headers": {"Authorization": "***"}
}}}
```
+96
View File
@@ -0,0 +1,96 @@
# #108 — Support complet des images (arborescence, visionneuse, indexation)
> **Version livrée :** 2.17.0 · **Statut :** ✅ · **Impact :** 🟡
> **Zone :** backend (`indexer`, `main`, `media_types`, `media_thumbs`) + frontend
> (`viewer.js`, `utils.js`, `style.css`).
## Contexte
Seul l'affichage *inline* dans un document markdown (`![[image.png]]`) fonctionnait.
L'image isolée était **invisible dans l'arborescence** (filtrée par
`SUPPORTED_EXTENSIONS`) et son **affichage standalone était cassé** : le `<img>`
généré par `api_file_view()` pointait vers `/api/file/{vault}/raw`, un endpoint qui
renvoie du **JSON** (`FileRawResponse`) et non des octets d'image.
## Ce qui a été livré
### A. Arborescence & indexation
- **`backend/media_types.py`** (nouveau) : source unique des extensions
`IMAGE_EXTENSIONS`, `AUDIO_EXTENSIONS`, `VIDEO_EXTENSIONS` (+ helpers
`is_image`/`is_audio`/`is_video`/`is_media`/`media_mime_type`). Socle réutilisé
par #109. `attachment_indexer.py` et `api_file_view()` ne dupliquent plus la
liste.
- Les extensions image sont intégrées à `SUPPORTED_EXTENSIONS`
(`indexer.py`) **avec une branche binaire** : `_scan_vault` et
`_index_single_file_sync` indexent **nom / taille / mtime** et ne lisent
**jamais** les octets (`content: ""`, `content_preview: ""`). Le TF-IDF reste
donc propre et aucune `UnicodeDecodeError` ne pollue les logs.
- Le reindex **watchdog** suit automatiquement (même filtre d'extensions).
- Le filtre `ext:png` / `ext:jpg` de la recherche avancée est opérationnel dès
lors que les images entrent dans l'index.
- `/api/dashboard` expose `image_count` (par vault) et `total_images` (global),
séparés du `file_count` général.
### B. Affichage standalone (correctif)
- `api_file_view()` génère désormais
`src="/api/image/{vault}?path=…"` (chemin URL-encodé) au lieu de `/raw`.
- `viewer.js` utilise le même endpoint (plus de bouton « Plein écran » cassé).
- **Sécurité SVG** : `/api/image` (et le repli de `/api/media/.../thumb`) ajoute
`Content-Security-Policy: sandbox` pour les `.svg`, ce qui empêche
l'exécution du JavaScript embarqué quand le fichier est ouvert directement
dans un onglet (XSS same-origin). Dans une balise `<img>`, l'en-tête est sans
effet. Le middleware de sécurité ne remplace plus une politique stricte posée
par une route.
### C. Miniatures
- `GET /api/media/{vault}/thumb?path=…&size=…` : miniature **WebP** générée
avec `pillow>=10.0`, mise en cache sous
`<OBSIGATE_DATA_DIR>/.obsigate-cache/thumbs/{sha1}.webp`. La clé de cache
embarque **mtime + taille**, donc toute édition invalide naturellement la
vignette.
- Génération dans un thread (`run_in_executor`) avec **timeout 2 s** ; repli sur
l'original en cas d'échec. SVG : l'original est servi tel quel (Pillow ne
décode pas le SVG) ; GIF/WebP animés : première frame.
### D. Visionneuse
`renderImageViewer()` (`frontend/js/viewer.js`) remplace l'ancien rendu minimal :
- image centrée `object-fit: contain` ; **zoom molette 0,1×–8×**, **pan au
glisser** (Pointer Events), **double-clic = réinitialisation**, raccourcis
`+` / `-` / `0` ;
- boutons +/−/reset et **badge de zoom** ;
- **navigation ←/→** entre les images du même dossier (via `/api/browse`) et
**pellicule de miniatures** (`/api/media/.../thumb`, `loading="lazy"`) ;
- barre d'outils : « Ouvrir l'original » (nouvel onglet `/api/image`),
téléchargement, **panneau métadonnées** repliable (dimensions via
`naturalWidth/Height`, taille, type MIME, chemin, date), **lightbox** plein
écran (fond `rgba(0,0,0,.9)`, `Échap` pour quitter) ;
- `EXT_ICONS` : extensions image → icône Lucide `image` ;
- compatible Split View (#75) : rendu dans `getContentArea()` du panneau actif.
### E. Tests
- `tests/test_image_api.py` : octets + MIME sur `/api/image`, en-tête `sandbox`
des SVG, URL `/api/image` dans le HTML de `api_file_view`, encodage des
chemins accentués, miniatures WebP + repli SVG + refus non-image.
- `tests/test_image_indexing.py` : image présente dans `list_directory` et
`path_index`, indexée avec `content == ""`, pertinence watchdog, compteurs
dashboard, filtre `ext:png`.
- `tests/frontend/image-viewer.test.mjs` : helpers purs (`clampImageZoom`,
`isImagePath`, `buildImageUrl`) + vérifications statiques (zoom/pan/nav,
absence de `/raw` dans la visionneuse, CSS, icônes).
- `tests/e2e/image-viewer.spec.js` : ouverture d'une image depuis
l'arborescence, réponse `/api/image` en `image/png`, zoom molette, navigation
par la pellicule (fixtures `test_vault/sample-image.png` +
`sample-vector.svg`).
## Limitations connues
- **HEIC/HEIF** (iPhone) : non décodables par les navigateurs → hors scope ;
`pillow-heif` envisagé en v2.
- Le SVG passe par l'original (pas de rendu bitmap côté serveur) : les
miniatures de dossiers SVG ne sont pas générées.
+187
View File
@@ -0,0 +1,187 @@
# #109 — Support audio & vidéo (lecteurs HTML5 intégrés)
> **Version livrée :** 2.18.0 · **Statut :** ✅ · **Impact :** 🟡
> **Zone :** backend (`main`, `indexer`, `media_types`, `bookslm`) + frontend
> (`viewer.js`, `utils.js`, `style.css`, `sw.js`).
## Contexte
Le socle média de #108 (`backend/media_types.py`) exposait déjà
`AUDIO_EXTENSIONS` / `VIDEO_EXTENSIONS`, mais ces fichiers n'étaient ni indexés
ni affichables : ils tombaient dans le chemin binaire « Ce fichier est binaire
et ne peut pas être affiché » + bouton download.
## Ce qui a été livré
### A. Backend
- **Indexation** : `AUDIO_EXTENSIONS` et `VIDEO_EXTENSIONS` sont intégrées à
`SUPPORTED_EXTENSIONS` (`indexer.py`). La branche `is_media(ext)` existante
indexe **nom / taille / mtime** sans jamais lire les octets (`content: ""`),
donc le TF-IDF et les logs restent propres. Le watcher et le filtre `ext:`
suivent automatiquement.
- **Streaming** : le helper Range de `pdf/stream` a été extrait en
`_stream_file_with_range(file_path, request, media_type)` (206 +
`Content-Range` + `Accept-Ranges`, `416` sur plage invalide, `FileResponse`
simple sinon, lectures offloadées via `asyncio.to_thread`). `pdf/stream`
l'utilise désormais aussi (comportement inchangé, tests de régression).
- **Nouvel endpoint `GET /api/media/{vault}?path=…`** : sert audio/vidéo avec le
MIME `media_types.media_mime_type` (surcharges `.m4a→audio/mp4`,
`.opus/.oga→audio/ogg`, `.mov→video/quicktime`, `.m4v→video/mp4`).
- **Gardes-fous** : `_resolve_safe_path`, `check_vault_access`, et
`OBSIGATE_MEDIA_MAX_INLINE_MB` (défaut **500 Mo**) — au-delà, l'endpoint
renvoie `413` et la vue fichier bascule sur l'UI de téléchargement.
- **`api_file_view()`** renvoie, avant tout `read_text()`, `is_audio` /
`is_video` / `stream_url` / `media_mime` / `size_bytes`. Au-delà de la limite :
`unsupported: true` + `media_too_large: true`.
### B/C. Frontend — lecteurs
- `viewer.js` dispatche `data.is_audio` → `renderAudioViewer()` et
`data.is_video` → `renderVideoViewer()`.
- **Audio** : `<audio controls preload="metadata">` pleine largeur, artwork
placeholder (icône Lucide `audio-lines`), durée lue via `loadedmetadata`,
toolbar (titre, voûte + taille, badge durée, ouvrir l'original, télécharger).
- **Vidéo** : `<video controls playsinline preload="metadata">` centrée sur une
scène noire letterboxée (`max-height: calc(100vh - 180px)`), même toolbar
avec durée + résolution.
- `renderMediaFallback()` : sur l'événement `error` de l'élément média (codec
hors web-natif : `.mkv`, `.avi`, HEVC…) ou si le fichier est trop volumineux,
remplace le lecteur par l'UI binaire + message
`viewer.media_unsupported` / `viewer.media_too_large` + **Télécharger** /
**Ouvrir dans un nouvel onglet**.
- **Pause** au changement de vue : `_mediaViewerCleanup` met en pause et détache
la source quand `renderFile()` re-rend la zone (changement d'onglet, navigation)
— pas de lecture persistante en v1 (cohérence #75).
- `EXT_ICONS` (`utils.js`) : audio → `audio-lines`, vidéo → `video`.
- i18n FR/EN (`viewer.media_unsupported`, `viewer.media_too_large`).
### D. Recherche & intégrations
- Filtres `ext:mp3`, `ext:mp4`, etc. opérationnels (les médias entrent dans
l'index).
- Récents / dashboards : previews vides (aucun texte extrait) — comportement
naturel de la branche binaire.
- **BooksLM** : `_file_entry()` ignore désormais tout média (`is_media`) — les
octets ne sont jamais envoyés au modèle ; les images restent gérées à part via
`load_vault_image_data_url` (vision).
- **Hors scope v1** (porte notée) : transcription audio via Whisper.
### E. Mobile & PWA
- Le service worker ne met **jamais** en cache le flux média
(`/api/media/{vault}`), tout en conservant le cache des miniatures
(`/api/media/{vault}/thumb`) et la stratégie Network First pour le reste. Les
requêtes `Range` étaient déjà exclues.
### F. Tests
- `tests/test_media_stream.py` : 206 + `Content-Range` + 1024 octets, `416` hors
borne, `200` + `Accept-Ranges` sans Range, suffix range, `413` au-delà de la
limite, `403` path traversal, `403` vault sans accès, `400` non-média, MIME
`.mov`, régression `pdf/stream`.
- `tests/test_media_indexing.py` : `.mp3`/`.mp4`/`.flac` dans l'arborescence et
l'index, `content == ""`, watcher pertinent, filtre `ext:mp3`.
- `tests/frontend/media-viewer.test.mjs` : helpers purs (`formatMediaDuration`,
`buildMediaUrl`) + vérifications statiques (dispatch, `<audio>`/`<video>`,
fallback, CSS, icônes, i18n, service worker, endpoints backend).
- `tests/e2e/media-viewer.spec.js` : lecture `<audio>` et `<video>` via
`/api/media` + réponse `206` sur requête `Range`. Fixtures :
`test_vault/sample-audio.mp3` (sine 1 s) et `test_vault/sample-video.webm`
(VP8 64×64).
## Limitations connues
- Formats hors web-natifs (`.mkv`, `.avi`, HEVC, AC-4) : non lisibles sans
transcodage (ffmpeg hors scope) → repli téléchargement / lecteur de l'OS.
- HLS, sous-titres `<track src=".vtt">` et vignettes vidéo : hors scope v1.
- Gros médias (> 500 Mo par défaut) : pas de lecture intégrée (protège le worker
uvicorn unique) ; ajustable via `OBSIGATE_MEDIA_MAX_INLINE_MB`.
---
## #110 — Lecteur média persistant « Now Playing »
> **Version livrée :** 2.19.0 · **Statut :** ✅ · **Impact :** 🟡
> **Zone :** frontend (`now-playing.js`, `viewer.js`, `ui.js`, `pane-manager.js`,
> `app.js`, `style.css`, `index.html`, locales).
### Principe : un seul média, téléporté
`frontend/js/now-playing.js` est un contrôleur singleton qui possède **l'unique
élément `<audio>`/`<video>`** de l'application. Il est déplacé par `appendChild`
(sans recréation, donc sans couper la lecture) entre :
- la **vue inline** — l'onglet/panneau du média, via la surface
`NowPlaying.attachInline(area, data)` (appelée par `renderAudioViewer` /
`renderVideoViewer` de `viewer.js`) ; et
- le **dock global** — un enfant direct de `<body>` (`#now-playing-host`), monté
hors de `.content-wrapper` pour survivre à `renderFile()`, aux onglets, aux
panneaux et à la reconstruction de la grille split.
`renderFile()` appelle `NowPlaying.handleRender(area, data)` : si la zone qui va
être réécrite contient l'élément média, celui-ci est renvoyé au dock. Les autres
points qui vident le contenu (dashboard `_showDashboard`, `showWelcome`,
`PaneManager._buildGrid` / `_collapseToSingle`) appellent le même hook via le
global `window.NowPlaying`.
### Surfaces et ergonomie
- **Dock audio (desktop)** : pilule flottante verre dépoli centrée en bas
(`.np-dock--audio`) — artwork, titre, voûte, durée, play/pause,
précédent/suivant, barre de progression (seek), volume, **revenir au média**,
agrandir, fermer.
- **Panneau étendu** : carte centrale (bottom-sheet sur mobile) avec artwork,
scrub large, volume, vitesse 0,5–2×, précédent/suivant et actions
ouvrir/télécharger/fermer.
- **Mini-vidéo flottante** (`.np-dock--video`) : déplaçable **librement** depuis
n'importe quel point de la fenêtre (position absolue mémorisée, centre autorisé
— aucune aimantation aux bords) et redimensionnable, géométrie persistée ; sur
mobile elle se fixe au-dessus de la barre d'outils.
- **Mobile** : mini-player au-dessus de la barre 64 px
(`bottom: calc(64px + env(safe-area-inset-bottom))`), `viewport-fit=cover`
ajouté, et `body.np-active` ajoute le décalage du contenu. La barre audio passe
en grille (progression sur sa propre ligne) et masque les actions secondaires
pour éviter tout chevauchement.
### Comportements
- Naviguer (onglet, panneau, dashboard, split) **ne coupe pas** la lecture ; le
dock apparaît.
- **Revenir au média** : `NowPlaying.focus()` rouvre/focalise l'onglet
`vault::path` (`window.getActiveTabManager().open`).
- **Fermer** : `NowPlaying.stop()` met en pause, libère l'élément et masque le
dock.
- **Fermer l'onglet** du média en cours : la lecture continue et un toast
`player.continues` le signale.
- **Media Session** : métadonnées (`MediaMetadata`) + actions
play/pause/stop/seek/nexttrack/previoustrack → écran verrouillé, casque
Bluetooth, touches média, **Windows SMTC** (WebView2).
- **Picture-in-Picture** natif pour la vidéo (`requestPictureInPicture`), bouton
masqué si non supporté.
- **Reprise après rechargement** : état (fichier, position, pause, préférences
volume/vitesse) persisté en `localStorage` (`obsigate-now-playing`,
`obsigate-player-prefs`, `obsigate-player-pos`).
### Fichiers modifiés / ajoutés
- Nouveau : `frontend/js/now-playing.js` (contrôleur, dock, session, PiP,
persistance), `tests/e2e/media-viewer.spec.js` (dock/retour/fermeture/mini-vidéo).
- Modifiés : `viewer.js` (délégation inline + `handleRender`), `ui.js`
(dashboard + toast de fermeture d'onglet), `pane-manager.js` (grille/collapse),
`app.js` (`initNowPlaying`), `style.css` (dock/étendu/vidéo/mobile, et
correction des variables `--surface1`/`--text-dim` non définies),
`index.html` (`viewport-fit=cover`), locales FR/EN (`player.*`).
### Correctifs annexes
- Les variables CSS `--surface1` et `--text-dim`, utilisées mais **jamais
définies** depuis #108/#109, sont remplacées par `--surface` et
`--text-secondary` (+ `--text-dim` dans toute la feuille).
### Hors scope (porte notée)
- Fenêtre vidéo détachée **native** Tauri (`WebviewWindowBuilder` +
`always_on_top`) : non implémentée, à faire dans une itération dédiée (Rust,
capabilities, route `/player`).
+69
View File
@@ -0,0 +1,69 @@
# #86 — Optimisation globale des performances (phase 3)
> **Statut :** ✅ livré | **Zone :** backend (`indexer.py`, `mutations.py`)
> **Prérequis déjà livrés :** BUG-033 (recherche via inverted index), BUG-040 (PDF lazy),
> BUG-025 (caps regex).
## Contexte
La roadmap #86 demandait : recherche simple + tool IA via l'inverted index, indexation
incrémentale + scan différentiel au démarrage, extraction PDF/excalidraw différée et caps
CPU sur les opérations regex. Trois de ces cinq points étaient déjà couverts par des
correctifs antérieurs ; cette livraison ferme les deux points restants.
## Ce qui était déjà livré (rappel)
| Point #86 | Livré par | État |
|---|---|---|
| Recherche simple + `search_fulltext` via inverted index | BUG-033 | `search()` récupère ses candidats via l'inverted index (intersection + expansion de préfixes), repli scan pendant la construction |
| Extraction PDF différée | BUG-040 | `_scan_vault` ne lit que les métadonnées ; `enrich_pdf_texts()` extrait après index |
| Caps CPU regex | BUG-025 | `validate_regex` (longueur ≤ 500, rejet quantificateurs imbriqués), contenu tronqué à 200 kio, matchs plafonnés à 1 000 |
## Livré ici
### 1. Scan différentiel au démarrage (`backend/indexer.py`)
- `_scan_vault(..., previous_files)` : quand un snapshot `{relative_path: file_info}` est
fourni, toute entrée dont `size` **et** `modified` sont inchangés est réutilisée sans
lecture disque ni re-parse (copie du dict, tags recomptés, wikilinks ré-enregistrés
depuis le contenu caché pour reconstruire l'index de backlinks).
- `build_index()` capture le snapshot précédent avant le `clear()` et le transmet à
chaque scan de vault (via `functools.partial` pour l'executor) ; `reload_single_vault()`
fait de même pour son vault. Seuls le `os.walk` + `stat` (bon marché) tournent à
chaque passe ; le retour inclut `reused` (hits différentiels, loggé par vault).
- Premier démarrage (aucun snapshot) : comportement identique à avant.
### 2. Extraction excalidraw différée (`backend/indexer.py`)
- Le scan ne lit plus les `.excalidraw` / `.excalidraw.md` : titre dérivé du nom de
fichier, `content` vide, flag `excalidraw_text_pending` (plus de décompression
lz-string pendant le scan).
- `enrich_pdf_texts()` traite désormais les deux flags (`pdf` + `excalidraw`) via
`_read_excalidraw_indexable_text()` exécuté dans l'executor, avec notification du hook
d'index incrémental comme pour les PDF. Nom conservé pour compatibilité (tests,
`main.py`, `reload_index`, `reload_single_vault` inchangés côté appel).
- Le chemin incrémental fichier-à-fichier (`_index_single_file_sync`, watcher) reste
immédiat : un seul fichier ne justifie pas le différé.
### 3. Garde-fou taille sur `replace_in_files` (`backend/services/mutations.py`)
- Nouvelle constante `MAX_REPLACE_FILE_BYTES` (5 Mio) : tout fichier dépassant le plafond
est sauté (warning loggé) au lieu d'être lu intégralement puis balayé par le pattern
utilisateur. Complète les caps BUG-025 (qui couvrent la recherche, pas le remplacement
qui opère sur le contenu disque complet par nature).
## Tests
`tests/test_perf_phase3.py` (9 tests) : différé excalidraw au scan (`.excalidraw` +
`.excalidraw.md`), remplissage par l'enrichissement, `reused == 0` au premier scan,
réutilisation à l'identique, re-parse du fichier modifié, ajout/suppression, skip
`replace` sur fichier surdimensionné + cas passant nominal.
## Limites connues
- Pas de persistance disque de l'index : le différentiel joue sur les rebuilds dans le
même processus (`reload_index`, `reload_single_vault`), pas entre deux redémarrages
(persistance = #85, phase 2).
- La comparaison `size + mtime` ne détecte pas une modification qui conserverait taille
et mtime à la milliseconde près (cas pathologique, le watcher temps réel couvre les
modifications en cours d'exécution).
Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

+54 -1
View File
@@ -2,7 +2,7 @@
<html lang="fr" data-theme="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title data-i18n="header.logo">ObsiGate</title>
<!-- PWA Meta Tags -->
@@ -1486,6 +1486,18 @@
<div class="editor-modal" id="config-modal">
<div class="editor-container">
<div class="editor-header">
<button
class="help-hamburger"
id="config-hamburger"
data-i18n-attr="title:config.toc_toggle;aria-label:config.toc_toggle"
title="Afficher le sommaire"
aria-label="Afficher le sommaire"
>
<i
data-lucide="menu"
style="width: 18px; height: 18px"
></i>
</button>
<div class="editor-title" data-i18n="header.menu_config">Configurations</div>
<div class="editor-actions">
<button
@@ -1547,6 +1559,7 @@
<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-tokens" class="help-nav-link" data-i18n="config.nav_tokens">🔑 Clés API & MCP</a></li>
<li><a href="#cfg-push" class="help-nav-link" data-i18n="config.section_push">Notifications push</a></li>
<li><a href="#cfg-plugins" class="help-nav-link" data-i18n="config.section_plugins">🧩 Plugins</a></li>
<li><a href="#cfg-about" class="help-nav-link" data-i18n="settings.about"></a></li>
@@ -2335,6 +2348,46 @@
</div>
</section>
<!-- Clés API / MCP (#107) -->
<section id="cfg-tokens" class="config-section help-section">
<h2 data-i18n="config.section_tokens">🔑 Clés API &amp; MCP</h2>
<p class="config-description" data-i18n="config.tokens_desc">
Jetons longue durée pour l'API REST et le serveur MCP.
La même clé fonctionne pour les deux (en-tête Authorization: Bearer).
</p>
<div id="tokens-list"></div>
<div class="config-add-row" id="tokens-create-row">
<input
type="text"
id="token-name-input"
data-i18n-placeholder="config.token_name_placeholder"
placeholder="Nom (ex: Claude Desktop)"
class="config-input"
style="width: 180px"
/>
<select id="token-expiry-select" class="config-input" style="width: 140px">
<option value="1d" data-i18n="config.token_expiry_1d">1 jour</option>
<option value="30d" selected data-i18n="config.token_expiry_30d">1 mois</option>
<option value="180d" data-i18n="config.token_expiry_180d">6 mois</option>
<option value="365d" data-i18n="config.token_expiry_365d">1 an</option>
<option value="never" data-i18n="config.token_expiry_never">Sans fin</option>
</select>
<button class="config-btn-add" id="token-create-btn" data-i18n="config.token_create">Créer une clé</button>
</div>
<div id="token-secret-area" class="token-secret-area hidden">
<p class="config-description" data-i18n="config.token_secret_warning">Copiez cette clé maintenant — elle ne sera plus jamais affichée.</p>
<textarea id="token-secret-value" class="config-input token-secret-text" rows="3" readonly></textarea>
<div class="config-add-row">
<button class="config-btn-add" id="token-copy-btn" data-i18n="config.token_copy">Copier</button>
<button class="config-btn-add" id="token-dismiss-btn" data-i18n="config.token_done">Terminé</button>
</div>
</div>
<div class="qh-tip" style="margin-top:10px">
<strong data-i18n="config.token_usage">Utilisation</strong>
<span data-i18n="config.token_usage_detail">: en-tête `Authorization: Bearer ` sur l'API, et config MCP (`claude_desktop_config.json`) : `{"mcpServers":{"obsigate":{"url":"<base>/mcp","headers":{"Authorization":"Bearer "}}}}`.</span>
</div>
</section>
<!-- Notifications push -->
<section
class="config-section help-section"
+2
View File
@@ -6,6 +6,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';
import { initNowPlaying } from './now-playing.js';
// Wire up AI toolbar toast (avoids circular import in utils.js)
window._obsigateShowToast = UI.showToast;
@@ -113,6 +114,7 @@ async function init() {
setupFocusMode();
Utils.safeCreateIcons();
initAIFab();
initNowPlaying();
}
document.addEventListener("DOMContentLoaded", async () => {
+123 -15
View File
@@ -1,6 +1,6 @@
/* ObsiGate — Authentication: API helper, AuthManager, login form, AdminPanel */
import { state } from './state.js';
import { safeCreateIcons } from './utils.js';
import { safeCreateIcons, escapeHtml } from './utils.js';
import { showToast, closeHeaderMenu } from './ui.js';
import { t, getLocale, setLocale } from './i18n.js';
import { showWelcome } from './viewer.js';
@@ -266,6 +266,13 @@ const AuthManager = {
});
},
async changePassword(currentPassword, newPassword) {
return await api("/api/auth/change-password", {
method: "POST",
body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
});
},
async logout() {
try {
const token = this.getToken();
@@ -545,8 +552,22 @@ function _startWebauthnLogin(mfaSection, username, rememberMe) {
function showMfaChallenge(username, rememberMe, loginBtn, loginErrorEl, mfaMethod) {
const loginBox = document.querySelector(".login-box");
if (!loginBox) return;
// BUG-069: the challenge used to mount into `.login-box`, which does not
// exist in index.html (the login markup is `#login-screen > .login-card >
// #login-form`) — querySelector returned null and the function silently
// returned, leaving the user stuck on the login page with no error after
// entering correct credentials. Mount into the real card, and never fail
// silently: surface the problem in the login error box instead.
const loginBox = document.querySelector(".login-card")
|| document.getElementById("login-screen");
if (!loginBox) {
const fallback = loginErrorEl || document.getElementById("login-error");
if (fallback) {
fallback.textContent = t("mfa.challenge_unavailable");
fallback.classList.remove("hidden");
}
return;
}
// Hide the normal login form
const loginForm = document.getElementById("login-form");
@@ -1058,11 +1079,79 @@ async function initMfaSettings() {
});
}
// Password change (BUG-068: the "Sécurité du compte" section had no way to
// change the password although POST /api/auth/change-password exists).
_renderPasswordSection(area);
// WebAuthn security keys section (ROADMAP #64)
_renderWebauthnSection(area);
}
function _renderPasswordSection(container) {
if (!container || document.getElementById("password-settings")) return;
const section = document.createElement("div");
section.id = "password-settings";
section.className = "password-settings";
section.innerHTML = `
<h4 class="webauthn-title">${t("mfa.password_change_title")}</h4>
<p class="mfa-info-text">${t("mfa.password_change_desc")}</p>
<div class="form-group">
<label>${t("mfa.current_password_label")}</label>
<input type="password" id="pwd-current" class="config-input"
placeholder="${t('mfa.current_password_placeholder')}" autocomplete="current-password">
</div>
<div class="form-group">
<label>${t("mfa.new_password_label")}</label>
<input type="password" id="pwd-new" class="config-input"
placeholder="${t('mfa.new_password_placeholder')}" autocomplete="new-password">
</div>
<div class="form-group">
<label>${t("mfa.new_password_confirm_label")}</label>
<input type="password" id="pwd-confirm" class="config-input"
placeholder="${t('mfa.new_password_confirm_placeholder')}" autocomplete="new-password">
</div>
<div class="mfa-recovery-actions">
<button class="config-btn-primary" id="pwd-change-btn">${t("mfa.password_change_btn")}</button>
</div>
<p class="mfa-error hidden" id="pwd-change-error"></p>
`;
container.appendChild(section);
section.querySelector("#pwd-change-btn").addEventListener("click", async () => {
const errEl = section.querySelector("#pwd-change-error");
const current = section.querySelector("#pwd-current").value;
const next = section.querySelector("#pwd-new").value;
const confirm = section.querySelector("#pwd-confirm").value;
const btn = section.querySelector("#pwd-change-btn");
errEl.classList.add("hidden");
if (!current || !next || !confirm) {
errEl.textContent = t("mfa.fill_all_fields");
errEl.classList.remove("hidden");
return;
}
if (next !== confirm) {
errEl.textContent = t("mfa.password_mismatch");
errEl.classList.remove("hidden");
return;
}
btn.disabled = true;
try {
await AuthManager.changePassword(current, next);
showToast(t("mfa.password_changed"), "success");
section.querySelector("#pwd-current").value = "";
section.querySelector("#pwd-new").value = "";
section.querySelector("#pwd-confirm").value = "";
} catch (err) {
errEl.textContent = err.message || String(err);
errEl.classList.remove("hidden");
} finally {
btn.disabled = false;
}
});
}
async function _renderWebauthnSection(container) {
if (!container || !window.PublicKeyCredential) return;
@@ -1085,10 +1174,10 @@ async function _renderWebauthnSection(container) {
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>
<span class="webauthn-key-label">🔑 ${escapeHtml(k.label || "Security key")}</span>
<span class="webauthn-key-meta">${escapeHtml((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>
data-id="${escapeHtml(k.credential_id)}">${t("mfa.webauthn_remove")}</button>
</li>`).join("")}</ul>`
: `<p class="mfa-info-text">${t("mfa.webauthn_none")}</p>`;
@@ -1111,7 +1200,10 @@ async function _renderWebauthnSection(container) {
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);
// BUG-068: first-time WebAuthn enable issues recovery codes. There is
// no #mfa-setup-flow-area in the "already enabled" view, so render
// them into the WebAuthn flow area instead of losing them.
_showRecoveryCodes(result.recovery_codes, "webauthn-flow-area");
} else {
showToast(t("mfa.webauthn_added"), "success");
}
@@ -1145,16 +1237,28 @@ async function _startMfaSetup() {
try {
const data = await AuthManager.mfaSetup();
// BUG-068: the QR code comes from the backend as a local SVG data: URI
// (see POST /api/auth/mfa/totp/setup → qr_data_url). The previous
// third-party QR image was blocked by the CSP
// (img-src 'self' data: blob:) so it never displayed — and it leaked the
// otpauth URI (TOTP secret) to a third party. Fall back to the manual
// secret when the backend has no QR generator available.
const qrImg = data.qr_data_url
? `<img id="mfa-qr-img" alt="QR Code" class="mfa-qr-code-img"
src="${data.qr_data_url}"
onerror="this.style.display='none';document.getElementById('mfa-qr-fallback').style.display='block';">`
: "";
const fallbackStyle = data.qr_data_url ? "display:none" : "";
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)}">
${qrImg}
<p class="mfa-info-text" id="mfa-qr-fallback" style="${fallbackStyle}">${t("mfa.qr_unavailable")}</p>
</div>
<details class="mfa-secret-details">
<details class="mfa-secret-details" ${data.qr_data_url ? "" : "open"}>
<summary>${t("mfa.manual_entry")}</summary>
<code class="mfa-secret-code">${data.secret}</code>
<code class="mfa-secret-code">${escapeHtml(data.secret)}</code>
</details>
<div class="mfa-verify-section">
<label>${t("mfa.enter_code")}</label>
@@ -1201,12 +1305,16 @@ async function _startMfaSetup() {
}
function _showRecoveryCodes(codes) {
const flowArea = document.getElementById("mfa-setup-flow-area");
const area = document.getElementById("mfa-setup-area");
function _showRecoveryCodes(codes, targetId) {
// BUG-068: the recovery codes must be visible wherever the enable flow ran.
// The TOTP flow owns #mfa-setup-flow-area, but the WebAuthn first-enable
// path (#webauthn-flow-area) has none — previously those codes were lost.
const flowArea = document.getElementById(targetId || "mfa-setup-flow-area")
|| document.getElementById("webauthn-flow-area")
|| document.getElementById("mfa-setup-area");
if (!flowArea) return;
const codesHtml = codes.map(c => `<code class="mfa-recovery-code">${c}</code>`).join("\n");
const codesHtml = codes.map(c => `<code class="mfa-recovery-code">${escapeHtml(c)}</code>`).join("\n");
flowArea.innerHTML = `
<div class="mfa-recovery-card">
<h4>🔑 ${t("mfa.recovery_codes_title")}</h4>
+146
View File
@@ -767,12 +767,17 @@ function initConfigModal() {
openBtn.addEventListener("click", async () => {
modal.classList.add("active");
closeHeaderMenu();
// BUG-071: reset the TOC to the CSS default (mobile: hidden, desktop:
// visible) like the help modal does on open.
var configNavOnOpen = document.getElementById("config-nav");
if (configNavOnOpen) configNavOnOpen.style.display = '';
renderConfigFilters();
loadConfigFields();
loadDiagnostics();
loadAbout();
await loadHiddenFilesSettings();
loadWebhooksUI();
loadTokensUI();
loadSharesUI();
loadToolKeys();
safeCreateIcons();
@@ -885,6 +890,44 @@ function initConfigModal() {
});
}
// BUG-071: mobile table of contents. #config-nav shares the .help-nav
// rule that hides it below 768px, but — unlike the help modal — the config
// modal had no toggle to reveal it, leaving mobile users with no way to
// reach a section. The header hamburger opens it as a top block; picking
// a section smooth-scrolls inside the modal and collapses it on mobile.
var configNav = document.getElementById("config-nav");
var configHamburger = document.getElementById("config-hamburger");
function _isConfigMobile() { return window.innerWidth <= 768; }
function _setConfigNav(open) {
if (!configNav) return;
configNav.style.display = open ? "flex" : "none";
if (configHamburger) configHamburger.classList.toggle("active", !!open);
}
if (configHamburger) {
configHamburger.addEventListener("click", function(e) {
e.stopPropagation();
var hidden = !configNav || configNav.style.display === "none" || configNav.style.display === "";
_setConfigNav(hidden);
});
}
if (configNav) {
configNav.querySelectorAll(".help-nav-link").forEach(function(a) {
a.addEventListener("click", function(e) {
var hash = a.getAttribute("href");
if (!hash || hash.charAt(0) !== "#") return;
var target = document.getElementById(hash.slice(1));
if (!target) return;
e.preventDefault();
configNav.querySelectorAll(".help-nav-link").forEach(function(o) { o.classList.remove("active"); });
a.classList.add("active");
if (typeof target.scrollIntoView === "function") {
target.scrollIntoView({ behavior: "smooth", block: "start" });
}
if (_isConfigMobile()) _setConfigNav(false);
});
});
}
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && modal.classList.contains("active")) {
closeConfigModal();
@@ -1346,6 +1389,109 @@ document.addEventListener("click", function(e) {
}
});
// ── API / MCP tokens UI (#107) ──
let _tokensBound = false;
async function loadTokensUI() {
const list = document.getElementById("tokens-list");
if (!list) return;
try {
const data = await api("/api/auth/tokens");
renderTokensUI(data.tokens || []);
bindTokenEvents();
} catch (err) {
list.innerHTML = '<div class="config-description">' + escapeHtml(t("config.error_prefix") + ": " + (err.message || "")) + "</div>";
}
}
function _formatTokenDate(unixSec) {
if (!unixSec) return "";
return new Date(unixSec * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
}
function _tokenExpiryLabel(tok) {
if (!tok.expires_at) return t("config.token_expiry_never");
const map = { "1d": "config.token_expiry_1d", "30d": "config.token_expiry_30d", "180d": "config.token_expiry_180d", "365d": "config.token_expiry_365d" };
return map[tok.expiry_key] ? t(map[tok.expiry_key]) : _formatTokenDate(tok.expires_at);
}
function renderTokensUI(tokens) {
const list = document.getElementById("tokens-list");
if (!list) return;
if (!tokens.length) {
list.innerHTML = '<div class="config-description">' + escapeHtml(t("config.tokens_empty")) + "</div>";
return;
}
list.innerHTML = tokens.map(tok => {
const expired = tok.expired || (tok.expires_at && tok.expires_at * 1000 < Date.now());
const status = expired
? '<span class="token-badge token-badge-expired">' + escapeHtml(t("config.token_status_expired")) + "</span>"
: '<span class="token-badge token-badge-active">' + escapeHtml(t("config.token_status_active")) + "</span>";
const meta = [
t("config.token_created") + " " + _formatTokenDate(tok.created_at),
t("config.token_expires") + " " + _tokenExpiryLabel(tok),
tok.last_used_at ? t("config.token_last_used") + " " + _formatTokenDate(tok.last_used_at) : t("config.token_never_used")
].join(" · ");
return '<div class="token-item" data-jti="' + escapeHtml(tok.jti) + '">' +
'<span class="token-name">' + escapeHtml(tok.name) + "</span>" +
status +
'<span class="token-meta">' + escapeHtml(meta) + "</span>" +
'<button class="token-delete" data-jti="' + escapeHtml(tok.jti) + '" data-name="' + escapeHtml(tok.name) + '" title="' + escapeHtml(t("config.token_revoke")) + '">✕</button>' +
"</div>";
}).join("");
list.querySelectorAll(".token-delete").forEach(btn => btn.addEventListener("click", async () => {
const name = btn.dataset.name;
if (!confirm(t("config.token_revoke_confirm") + " \"" + name + "\" ?")) return;
try {
await api("/api/auth/tokens/" + btn.dataset.jti, { method: "DELETE" });
showToast(t("config.token_revoked_toast"), "success");
loadTokensUI();
} catch (err) {
showToast(err.message || t("config.error_unknown"), "error");
}
}));
}
function bindTokenEvents() {
if (_tokensBound) return;
_tokensBound = true;
const createBtn = document.getElementById("token-create-btn");
if (!createBtn) return;
createBtn.addEventListener("click", async () => {
const name = document.getElementById("token-name-input").value.trim();
const expiry = document.getElementById("token-expiry-select").value;
if (!name) { showToast(t("config.token_name_required"), "error"); return; }
createBtn.disabled = true;
try {
const res = await api("/api/auth/tokens", { method: "POST", body: JSON.stringify({ name, expiry }) });
const area = document.getElementById("token-secret-area");
const ta = document.getElementById("token-secret-value");
ta.value = res.token;
area.classList.remove("hidden");
ta.select();
document.getElementById("token-name-input").value = "";
showToast(t("config.token_created_toast"), "success");
loadTokensUI();
} catch (err) {
showToast(err.message || t("config.error_unknown"), "error");
} finally {
createBtn.disabled = false;
}
});
const copyBtn = document.getElementById("token-copy-btn");
if (copyBtn) copyBtn.addEventListener("click", async () => {
const ta = document.getElementById("token-secret-value");
try { await navigator.clipboard.writeText(ta.value); }
catch { ta.select(); document.execCommand("copy"); }
showToast(t("config.token_copied"), "success");
});
const dismissBtn = document.getElementById("token-dismiss-btn");
if (dismissBtn) dismissBtn.addEventListener("click", () => {
document.getElementById("token-secret-area").classList.add("hidden");
document.getElementById("token-secret-value").value = "";
});
}
// ── Shares UI ──
async function loadSharesUI() {
const list = document.getElementById("shares-list");
+13 -6
View File
@@ -5,6 +5,7 @@
* Static DOM: data-i18n="key" → textContent
* data-i18n-placeholder="key" → placeholder
* data-i18n-attr:title="key" → title attribute
* data-i18n-attr="a:k1;b:k2" → several attributes (";"-separated)
* data-i18n-html="key" → innerHTML (use sparingly)
* Dynamic JS: import { t } from './i18n.js'; t('key', {param: 'val'})
* Live reload: setLocale('en') updates every data-i18n element instantly.
@@ -183,13 +184,19 @@ function _applyDOM() {
el.innerHTML = t(key);
});
// data-i18n-attr:TITLE → sets any attribute
// data-i18n-attr:ATTR:key[;ATTR:key…] → sets any attribute(s).
// Single-pair form (data-i18n-attr="title:key") is preserved; multiple
// pairs are separated with ";" (BUG-071: the config TOC toggle needs both
// title and aria-label translated).
document.querySelectorAll('[data-i18n-attr]').forEach(function (el) {
const raw = el.getAttribute('data-i18n-attr');
const colon = raw.indexOf(':');
if (colon === -1) return;
const attr = raw.substring(0, colon);
const key = raw.substring(colon + 1);
el.setAttribute(attr, t(key));
raw.split(';').forEach(function (pair) {
const colon = pair.indexOf(':');
if (colon === -1) return;
const attr = pair.substring(0, colon).trim();
const key = pair.substring(colon + 1).trim();
if (!attr || !key) return;
el.setAttribute(attr, t(key));
});
});
}
File diff suppressed because it is too large Load Diff
+8
View File
@@ -197,9 +197,13 @@ function createPaneTabManager(paneId) {
close(tabId) {
const idx = this._tabs.findIndex(t => t.id === tabId);
if (idx === -1) return;
const closingTab = this._tabs[idx];
this._tabs.splice(idx, 1);
delete this._tabCache[tabId];
this._dirtyTabs.delete(tabId);
if (window.NowPlaying && closingTab) {
window.NowPlaying.notifyTabClosed(closingTab.vault, closingTab.path);
}
if (this._tabs.length === 0) {
this._activeTabId = null;
// If this pane has no more tabs and isn't the last pane, close it
@@ -826,6 +830,8 @@ const PaneManager = {
grid.className = 'pane-grid';
this._applyGridTemplate(grid, n);
// #110 — keep playing media alive across a pane-grid rebuild.
if (window.NowPlaying) window.NowPlaying.handleRender(wrapper, null);
wrapper.innerHTML = '';
wrapper.appendChild(grid);
this.panes = [];
@@ -1216,6 +1222,8 @@ const PaneManager = {
if (!grid) return;
const wrapper = grid.parentElement;
const pane0 = this.panes[0];
// #110 — keep playing media alive across a pane collapse.
if (window.NowPlaying) window.NowPlaying.handleRender(wrapper, null);
wrapper.innerHTML = '';
let tabBar = null, content = null;
if (pane0 && pane0.element) {
+7
View File
@@ -2080,11 +2080,16 @@ export const TabManager = {
}
const idx = this._tabs.findIndex(t => t.id === tabId);
if (idx === -1) return;
const closingTab = this._tabs[idx];
this._tabs.splice(idx, 1);
delete this._tabCache[tabId];
this._dirtyTabs.delete(tabId);
if (window.NowPlaying && closingTab) {
window.NowPlaying.notifyTabClosed(closingTab.vault, closingTab.path);
}
if (this._tabs.length === 0) {
this._activeTabId = null;
this._showDashboard();
@@ -2207,6 +2212,8 @@ export const TabManager = {
_showDashboard() {
const area = document.getElementById("content-area");
// #110 — move any playing media to the persistent dock before wiping.
if (window.NowPlaying && area) window.NowPlaying.handleRender(area, null);
// Save dashboard DOM before clearing (it may have been removed from DOM by renderFile)
let dashboard = document.getElementById("dashboard-home");
if (!dashboard) {
+31 -29
View File
@@ -201,37 +201,39 @@ const EXT_ICONS = {
".tex": "file-text",
".latex": "file-text",
// Image files
".png": "file-image",
".jpg": "file-image",
".jpeg": "file-image",
".gif": "file-image",
".svg": "file-image",
".webp": "file-image",
".bmp": "file-image",
".ico": "file-image",
".tiff": "file-image",
".tif": "file-image",
// Image files (roadmap #108-D1)
".png": "image",
".jpg": "image",
".jpeg": "image",
".gif": "image",
".svg": "image",
".webp": "image",
".bmp": "image",
".ico": "image",
".tiff": "image",
".tif": "image",
// Audio files
".mp3": "file-music",
".wav": "file-music",
".flac": "file-music",
".aac": "file-music",
".ogg": "file-music",
".m4a": "file-music",
".wma": "file-music",
// Audio files (roadmap #109-B2)
".mp3": "audio-lines",
".wav": "audio-lines",
".flac": "audio-lines",
".aac": "audio-lines",
".ogg": "audio-lines",
".oga": "audio-lines",
".opus": "audio-lines",
".m4a": "audio-lines",
".wma": "audio-lines",
// Video files
".mp4": "play",
".avi": "play",
".mov": "play",
".wmv": "play",
".flv": "play",
".webm": "play",
".mkv": "play",
".m4v": "play",
".3gp": "play",
// Video files (roadmap #109-B2)
".mp4": "video",
".avi": "video",
".mov": "video",
".wmv": "video",
".flv": "video",
".webm": "video",
".mkv": "video",
".m4v": "video",
".3gp": "video",
// Archive files
".zip": "file-archive",
+315 -19
View File
@@ -14,6 +14,7 @@ import { openShareDialog } from './config.js';
import { cacheViewedFile, getCachedFile } from './offline.js';
import { t } from './i18n.js';
import { onFileRender } from './plugins.js';
import { NowPlaying } from './now-playing.js';
// ── Multi-format export ────────────────────────────────────────────────────
// Downloads a file export (HTML / MD bundle / ePub) via the authenticated
@@ -540,13 +541,312 @@ export function navigatePdfToPage(area, page) {
iframe.src = `${base}${sep}_pdfpage=${Date.now()}#page=${page}`;
}
// ---------------------------------------------------------------------------
// Image viewer (roadmap #108-D)
// ---------------------------------------------------------------------------
const IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".ico"]);
const IMAGE_ZOOM_MIN = 0.1;
const IMAGE_ZOOM_MAX = 8;
let _imageViewerCleanup = null;
// BUG-072 — the lightbox and metadata panel states must survive the re-render
// triggered by ←/→ navigation (openFile → renderFile → renderImageViewer).
// Reset as soon as a non-image file is rendered.
const _imageViewerState = { lightbox: false, meta: false };
// Set right before an image→image navigation (←/→ / filmstrip click) so
// renderFile knows the state above must be carried over instead of reset.
let _imageViewerNavPending = false;
/** Clamp a zoom factor into the supported [0.1, 8] range. */
export function clampImageZoom(value) {
if (!Number.isFinite(value)) return 1;
return Math.min(IMAGE_ZOOM_MAX, Math.max(IMAGE_ZOOM_MIN, value));
}
/** True when *p* has a viewable image extension. */
export function isImagePath(p) {
const lower = (p || "").toLowerCase();
const dot = lower.lastIndexOf(".");
return dot !== -1 && IMAGE_EXTS.has(lower.slice(dot));
}
/** Build the byte-serving URL used by <img> / thumbnails. */
export function buildImageUrl(vault, path) {
return `/api/image/${encodeURIComponent(vault)}?path=${encodeURIComponent(path)}`;
}
function buildThumbUrl(vault, path, size) {
return `/api/media/${encodeURIComponent(vault)}/thumb?path=${encodeURIComponent(path)}&size=${size}`;
}
function formatBytes(n) {
if (!n && n !== 0) return "";
if (n < 1024) return `${n} o`;
if (n < 1048576) return `${(n / 1024).toFixed(1)} Ko`;
return `${(n / 1048576).toFixed(1)} Mo`;
}
/**
* Render a full image viewer: centered image, wheel zoom (0.1×–8×), drag pan,
* double-click reset, ←/→ navigation between siblings, thumbnail filmstrip,
* collapsible metadata panel and a full-viewport lightbox.
*/
export function renderImageViewer(area, data) {
const vault = data.vault;
const path = data.path;
const fileName = (path || "").split("/").pop();
const imgUrl = buildImageUrl(vault, path);
area.innerHTML = "";
const container = el("div", { class: "image-viewer-container", tabindex: "0" });
// ── Toolbar ────────────────────────────────────────────────────────────
const toolbar = el("div", { class: "image-toolbar" });
toolbar.appendChild(el("span", { class: "image-title", title: path }, [
document.createTextNode(data.title || fileName),
]));
toolbar.appendChild(el("div", { class: "image-toolbar-spacer" }));
const zoomBadge = el("span", { class: "image-zoom-badge" }, [document.createTextNode("100%")]);
toolbar.appendChild(zoomBadge);
const mkBtn = (iconName, label, cls) => {
const b = el("button", { class: `btn-action${cls ? " " + cls : ""}`, type: "button", title: label, "aria-label": label }, [icon(iconName, 14)]);
return b;
};
const zoomOutBtn = mkBtn("zoom-out", t("viewer.image_zoom_out"));
const zoomInBtn = mkBtn("zoom-in", t("viewer.image_zoom_in"));
const zoomResetBtn = mkBtn("rotate-ccw", t("viewer.image_zoom_reset"));
const prevBtn = mkBtn("chevron-left", t("viewer.image_prev"));
const nextBtn = mkBtn("chevron-right", t("viewer.image_next"));
const originalBtn = mkBtn("external-link", t("viewer.image_open_original"));
const downloadBtn = mkBtn("download", t("viewer.download"));
const metaBtn = mkBtn("info", t("viewer.image_metadata"), "image-btn-metadata");
const lightboxBtn = mkBtn("maximize", t("viewer.image_fullscreen"), "image-btn-lightbox");
[prevBtn, nextBtn, zoomOutBtn, zoomInBtn, zoomResetBtn, metaBtn, originalBtn, downloadBtn, lightboxBtn]
.forEach((b) => toolbar.appendChild(b));
container.appendChild(toolbar);
// ── Body: image stage + metadata sidebar (right) ───────────────────────
const body = el("div", { class: "image-viewer-body" });
const stage = el("div", { class: "image-stage" });
const img = el("img", { class: "image-main", src: imgUrl, alt: data.title || fileName, draggable: "false" });
stage.appendChild(img);
body.appendChild(stage);
// ── Metadata sidebar (kept open across ←/→ navigation) ─────────────────
const metaPanel = el("div", { class: "image-meta-panel" });
metaPanel.hidden = !_imageViewerState.meta;
body.appendChild(metaPanel);
container.appendChild(body);
// ── Thumbnail filmstrip (navigation) ───────────────────────────────────
const strip = el("div", { class: "image-nav-strip", hidden: true });
container.appendChild(strip);
let scale = 1;
let tx = 0;
let ty = 0;
const applyTransform = () => {
img.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`;
zoomBadge.textContent = `${Math.round(scale * 100)}%`;
};
const resetView = () => { scale = 1; tx = 0; ty = 0; applyTransform(); };
const setZoom = (next) => {
scale = clampImageZoom(next);
if (scale === 1) { tx = 0; ty = 0; }
applyTransform();
};
const renderMeta = () => {
const rows = [
[t("viewer.image_type"), data.image_mime || ""],
[t("viewer.image_dimensions"), img.naturalWidth ? `${img.naturalWidth} × ${img.naturalHeight}` : ""],
[t("viewer.metadata_size"), formatBytes(data.size_bytes)],
[t("viewer.metadata_path"), path],
];
if (data.modified) rows.push([t("viewer.metadata_modified"), data.modified]);
metaPanel.innerHTML = "";
const dl = el("dl", {});
rows.forEach(([k, v]) => {
dl.appendChild(el("dt", {}, [document.createTextNode(k)]));
dl.appendChild(el("dd", {}, [document.createTextNode(v || "—")]));
});
metaPanel.appendChild(dl);
};
// ── Sibling navigation ─────────────────────────────────────────────────
let siblings = [];
let currentIndex = -1;
const go = (delta) => {
if (siblings.length < 2 || currentIndex < 0) return;
const next = (currentIndex + delta + siblings.length) % siblings.length;
_imageViewerNavPending = true;
openFile(vault, siblings[next].path);
};
const renderStrip = () => {
if (siblings.length < 2) { strip.hidden = true; return; }
strip.hidden = false;
strip.innerHTML = "";
siblings.forEach((s, i) => {
const thumb = el("img", {
class: `image-thumb${i === currentIndex ? " active" : ""}`,
src: buildThumbUrl(vault, s.path, 96),
alt: s.name,
title: s.name,
loading: "lazy",
});
thumb.addEventListener("click", () => {
if (s.path === path) return;
_imageViewerNavPending = true;
openFile(vault, s.path);
});
strip.appendChild(thumb);
});
};
(async () => {
try {
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
const res = await api(`/api/browse/${encodeURIComponent(vault)}?path=${encodeURIComponent(dir)}`);
siblings = (res.items || []).filter((it) => it.type === "file" && isImagePath(it.path));
currentIndex = siblings.findIndex((it) => it.path === path);
prevBtn.disabled = nextBtn.disabled = siblings.length < 2;
renderStrip();
} catch (_) { /* navigation is best-effort */ }
})();
// ── Interactions ───────────────────────────────────────────────────────
stage.addEventListener("wheel", (e) => {
e.preventDefault();
const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
setZoom(scale * factor);
}, { passive: false });
let dragging = false;
let startX = 0;
let startY = 0;
let startTx = 0;
let startTy = 0;
stage.addEventListener("pointerdown", (e) => {
if (e.button !== 0) return;
dragging = true;
startX = e.clientX; startY = e.clientY; startTx = tx; startTy = ty;
stage.classList.add("panning");
if (stage.setPointerCapture) stage.setPointerCapture(e.pointerId);
});
stage.addEventListener("pointermove", (e) => {
if (!dragging) return;
tx = startTx + (e.clientX - startX);
ty = startTy + (e.clientY - startY);
applyTransform();
});
const endDrag = (e) => {
dragging = false;
stage.classList.remove("panning");
if (stage.releasePointerCapture && e.pointerId != null) {
try { stage.releasePointerCapture(e.pointerId); } catch (_) { /* already released */ }
}
};
stage.addEventListener("pointerup", endDrag);
stage.addEventListener("pointercancel", endDrag);
stage.addEventListener("dblclick", resetView);
zoomInBtn.addEventListener("click", () => setZoom(scale * 1.25));
zoomOutBtn.addEventListener("click", () => setZoom(scale / 1.25));
zoomResetBtn.addEventListener("click", resetView);
prevBtn.addEventListener("click", () => go(-1));
nextBtn.addEventListener("click", () => go(1));
originalBtn.addEventListener("click", () => window.open(imgUrl, "_blank"));
downloadBtn.addEventListener("click", () => {
const dlUrl = `/api/file/${encodeURIComponent(vault)}/download?path=${encodeURIComponent(path)}`;
window.open(dlUrl, "_blank");
});
metaBtn.setAttribute("aria-pressed", _imageViewerState.meta ? "true" : "false");
metaBtn.addEventListener("click", () => {
_imageViewerState.meta = !_imageViewerState.meta;
metaPanel.hidden = !_imageViewerState.meta;
metaBtn.setAttribute("aria-pressed", _imageViewerState.meta ? "true" : "false");
if (_imageViewerState.meta) renderMeta();
});
const syncLightbox = () => {
container.classList.toggle("lightbox", _imageViewerState.lightbox);
lightboxBtn.setAttribute("aria-pressed", _imageViewerState.lightbox ? "true" : "false");
};
syncLightbox();
lightboxBtn.addEventListener("click", () => {
_imageViewerState.lightbox = !_imageViewerState.lightbox;
syncLightbox();
});
img.addEventListener("load", () => { if (!metaPanel.hidden) renderMeta(); });
img.addEventListener("error", () => {
stage.innerHTML = "";
stage.appendChild(el("div", { class: "image-error" }, [document.createTextNode(t("viewer.image_error"))]));
});
const onKey = (e) => {
if (e.key === "ArrowLeft") { e.preventDefault(); go(-1); }
else if (e.key === "ArrowRight") { e.preventDefault(); go(1); }
else if (e.key === "+" || e.key === "=") { e.preventDefault(); setZoom(scale * 1.25); }
else if (e.key === "-") { e.preventDefault(); setZoom(scale / 1.25); }
else if (e.key === "0") { e.preventDefault(); resetView(); }
else if (e.key === "Escape") {
_imageViewerState.lightbox = false;
syncLightbox();
}
};
document.addEventListener("keydown", onKey);
_imageViewerCleanup = () => document.removeEventListener("keydown", onKey);
area.appendChild(container);
safeCreateIcons();
applyTransform();
if (_imageViewerState.meta) renderMeta();
try { container.focus({ preventScroll: true }); } catch (_) { /* non-fatal */ }
}
// #110 — Audio/video are handled by the global Now Playing controller
// (frontend/js/now-playing.js): a single shared media element is teleported
// between this inline view and a body-level dock, so playback survives tab,
// pane and page navigation. The inline branches below just hand over the
// surface; the legacy "stop on re-render" cleanup no longer applies.
export { formatMediaDuration, buildMediaUrl, renderFallback as renderMediaFallback } from "./now-playing.js";
/** Audio viewer (roadmap #109-B, made persistent by #110). */
export function renderAudioViewer(area, data) {
NowPlaying.attachInline(area, data);
}
/** Video viewer (roadmap #109-C, made persistent by #110). */
export function renderVideoViewer(area, data) {
NowPlaying.attachInline(area, data);
}
export function renderFile(data) {
// #93 — An inline edition session (#editor-container mounted in the content
// area) is destroyed by this very re-render: release it first so the editor
// state (CodeMirror view, Forge iframe, Yjs session) is torn down cleanly
// instead of being wiped mid-session by a tab switch / sidebar click.
if (isInlineEditorActive()) detachInlineEditor();
// #108 — release the image viewer's document-level shortcuts before swapping
// the content area (otherwise they leak on every re-render).
if (_imageViewerCleanup) { _imageViewerCleanup(); _imageViewerCleanup = null; }
// BUG-072 — carry the lightbox / metadata-panel state over an image→image
// navigation; any other render starts from a clean viewer.
if (!data.is_image || !_imageViewerNavPending) {
_imageViewerState.lightbox = false;
_imageViewerState.meta = false;
}
_imageViewerNavPending = false;
const area = getContentArea();
// #110 — if this render is about to replace the surface that currently hosts
// the shared media element, hand it back to the persistent dock first.
NowPlaying.handleRender(area, data);
// Handle PDF files — render in iframe with TOC sidebar
if (data.is_pdf) {
@@ -596,25 +896,19 @@ export function renderFile(data) {
return;
}
// Handle images
// Handle images — dedicated zoom/pan viewer (roadmap #108-D)
if (data.is_image) {
const imgUrl = `/api/file/${encodeURIComponent(data.vault)}/raw?path=${encodeURIComponent(data.path)}`;
area.innerHTML = `
<div class="image-viewer-container">
<div class="file-toolbar">
<span class="file-info">${escapeHtml(data.title)}</span>
<button class="btn-action" onclick="window.open('${imgUrl}', '_blank')">
<i data-lucide="maximize" style="width:14px;height:14px"></i> Plein écran
</button>
<button class="btn-action" onclick="window.open('/api/file/${encodeURIComponent(data.vault)}/download?path=${encodeURIComponent(data.path)}', '_blank')">
<i data-lucide="download" style="width:14px;height:14px"></i> Télécharger
</button>
</div>
<div class="image-viewer-body">
${data.html}
</div>
</div>`;
lucide.createIcons();
renderImageViewer(area, data);
return;
}
// Handle audio / video — native HTML5 players (roadmap #109)
if (data.is_audio) {
renderAudioViewer(area, data);
return;
}
if (data.is_video) {
renderVideoViewer(area, data);
return;
}
@@ -629,7 +923,7 @@ export function renderFile(data) {
<div class="unsupported-file">
<i data-lucide="file" style="width:48px;height:48px"></i>
<div class="filename">${escapeHtml(data.path.split("/").pop())}</div>
<div>Ce fichier est binaire et ne peut pas être affiché.</div>
<div>${data.media_too_large ? escapeHtml(t("viewer.media_too_large")) : "Ce fichier est binaire et ne peut pas être affiché."}</div>
${sizeStr ? `<div style="font-size:0.85rem;margin-top:4px">Taille : ${sizeStr}</div>` : ""}
<button class="btn-action" id="unsupported-download-btn">
<i data-lucide="download" style="width:14px;height:14px"></i> Télécharger
@@ -1294,6 +1588,8 @@ export function showWelcome() {
// Restore or rebuild the dashboard with tabbed sections
const area = getContentArea();
// #110 — keep playing media alive if the dashboard replaces its surface.
NowPlaying.handleRender(area, null);
const home = document.getElementById("dashboard-home");
if (area && !home) {
+73 -1
View File
@@ -569,9 +569,38 @@
"config.test": "Test",
"config.timeout_label": "Search timeout (ms)",
"config.title": "Settings",
"config.toc_toggle": "Show contents",
"config.title_boost": "Title boost",
"config.title_boost_hint": "Relevance multiplier for title matches",
"config.title_boost_label": "Title boost",
"config.nav_tokens": "🔑 API & MCP keys",
"config.section_tokens": "🔑 API & MCP keys",
"config.tokens_desc": "Long-lived tokens for the REST API and the MCP server — the same key works for both (Authorization: Bearer header).",
"config.tokens_empty": "No API keys created.",
"config.token_name_placeholder": "Name (e.g. Claude Desktop)",
"config.token_name_required": "A name is required",
"config.token_expiry_1d": "1 day",
"config.token_expiry_30d": "1 month",
"config.token_expiry_180d": "6 months",
"config.token_expiry_365d": "1 year",
"config.token_expiry_never": "Never",
"config.token_create": "Create key",
"config.token_secret_warning": "Copy this key now — it will never be shown again.",
"config.token_copy": "Copy",
"config.token_copied": "Key copied to clipboard",
"config.token_done": "Done",
"config.token_usage": "Usage",
"config.token_usage_detail": ": \"Authorization: Bearer <key>\" header on the API; for MCP, declare it in the headers of the /mcp URL.",
"config.token_created": "Created",
"config.token_expires": "Expires",
"config.token_last_used": "Last used",
"config.token_never_used": "Never used",
"config.token_status_active": "Active",
"config.token_status_expired": "Expired",
"config.token_revoke": "Revoke",
"config.token_revoke_confirm": "Revoke key",
"config.token_revoked_toast": "Key revoked (immediate effect on API + MCP)",
"config.token_created_toast": "Key created",
"config.url_required": "URL required",
"config.watcher_debounce_label": "Debounce (s)",
"config.watcher_enabled_label": "Enable watcher",
@@ -1794,11 +1823,24 @@
"viewer.export_title": "Export document",
"viewer.forge_brand": "Forge",
"viewer.forge_title": "Forge (new editor)",
"viewer.image_dimensions": "Dimensions",
"viewer.image_error": "Unable to load the image",
"viewer.image_fullscreen": "Full screen (lightbox)",
"viewer.image_metadata": "Metadata",
"viewer.image_next": "Next image",
"viewer.image_open_original": "Open original",
"viewer.image_prev": "Previous image",
"viewer.image_type": "Type",
"viewer.image_zoom_in": "Zoom in",
"viewer.image_zoom_out": "Zoom out",
"viewer.image_zoom_reset": "Reset zoom",
"viewer.index_start": "Starting index...",
"viewer.index_updated": "Updated",
"viewer.loaded_from_cache": "File loaded from offline cache",
"viewer.loading": "Loading file...",
"viewer.markdown": "Markdown",
"viewer.media_too_large": "File too large for inline playback. Download it to watch.",
"viewer.media_unsupported": "This format cannot be played in your browser.",
"viewer.metadata_created": "Created",
"viewer.metadata_modified": "Modified",
"viewer.metadata_path": "Path",
@@ -1859,6 +1901,19 @@
"mfa.disable_confirm_btn": "Disable 2FA",
"mfa.disabled_success": "2FA has been disabled.",
"mfa.fill_all_fields": "Please fill in all fields.",
"mfa.qr_unavailable": "QR code unavailable — use manual entry below.",
"mfa.password_change_title": "Password",
"mfa.password_change_desc": "Change your account password (min. 8 characters). All other sessions are invalidated.",
"mfa.current_password_label": "Current password",
"mfa.current_password_placeholder": "Your current password",
"mfa.new_password_label": "New password",
"mfa.new_password_placeholder": "Min. 8 characters",
"mfa.new_password_confirm_label": "Confirm new password",
"mfa.new_password_confirm_placeholder": "Repeat the new password",
"mfa.password_change_btn": "Change password",
"mfa.password_mismatch": "The two passwords do not match.",
"mfa.password_changed": "Password updated.",
"mfa.challenge_unavailable": "Verification screen unavailable — please reload the page.",
"bookslm.title": "BooksLM",
"bookslm.files_indexed": "{count} files indexed",
"bookslm.chars_loaded": "{chars} chars loaded",
@@ -1973,6 +2028,23 @@
"mfa.webauthn_btn": "Verify with my key",
"mfa.webauthn_cancelled": "WebAuthn ceremony cancelled.",
"mfa.webauthn_no_key": "No security key registered for this account.",
"player.now_playing": "Now playing",
"player.play": "Play",
"player.pause": "Pause",
"player.previous": "Previous",
"player.next": "Next",
"player.seek": "Seek",
"player.volume": "Volume",
"player.speed": "Playback speed",
"player.expand": "Expand player",
"player.minimize": "Minimize player",
"player.close": "Stop and close player",
"player.continues": "Playback continues — use the player to stop it.",
"player.reopen_tab": "Return to media",
"player.pip": "Picture in picture",
"player.move": "Move",
"player.resize": "Resize",
"player.resume": "Resuming last playback",
"plugins.title": "🧩 Plugins",
"plugins.description": "Extend ObsiGate with custom renderers, search filters, and editor actions.",
"plugins.install": "Install Plugin",
@@ -2074,7 +2146,7 @@
"guide105.lib_h3_conflicts": "Sync conflicts",
"guide105.lib_conflicts": "If you sync the vault with Syncthing, ObsiGate detects conflict files (\"sync-conflict\" copies) and offers to compare then resolve them from a dedicated page in the Options menu.",
"guide105.lib_h3_attach": "Attachments & media",
"guide105.lib_attach": "Inline <code>![[image.png]]</code> images, attachments and media (audio, video, embedded PDFs) are rendered in the viewer and indexed for search; the \"Rescan attachments\" button in Configuration rebuilds the attachment index.",
"guide105.lib_attach": "Inline <code>![[image.png]]</code> images, attachments and media (audio, video, embedded PDFs) are rendered in the viewer and indexed for search. Images also appear in the file tree and open in a dedicated viewer (wheel zoom, pan, navigation between images in the folder, thumbnails, metadata, lightbox); audio (.mp3, .wav, .flac…) and video (.mp4, .webm…) files open in a built-in HTML5 player (play, seek, speed, fullscreen), falling back to download when the format is not playable in the browser; playback continues while you navigate thanks to a floating mini-player (audio) or a mini video window, letting you return to the media or stop it at any time. The \"Rescan attachments\" button in Configuration rebuilds the attachment index.",
"guide105.off_pwa": "ObsiGate is a PWA: install it (install icon in the address bar) to open it like an app. The service worker caches the UI and your recently viewed documents.",
"guide105.off_edit": "Offline you can read cached documents and even edit them: changes are queued in IndexedDB.",
"guide105.off_sync": "When back online the queue replays automatically (sync badge in the header). If the server version diverged meanwhile, the file is flagged as conflict and the server copy is kept as a backup.",
+73 -1
View File
@@ -569,9 +569,38 @@
"config.test": "Tester",
"config.timeout_label": "Timeout recherche (ms)",
"config.title": "Configuration",
"config.toc_toggle": "Afficher le sommaire",
"config.title_boost": "Boost titre",
"config.title_boost_hint": "Multiplicateur de pertinence pour les correspondances dans le titre",
"config.title_boost_label": "Boost titre",
"config.nav_tokens": "🔑 Clés API & MCP",
"config.section_tokens": "🔑 Clés API & MCP",
"config.tokens_desc": "Jetons longue durée pour l'API REST et le serveur MCP — la même clé fonctionne pour les deux (en-tête Authorization: Bearer).",
"config.tokens_empty": "Aucune clé API créée.",
"config.token_name_placeholder": "Nom (ex: Claude Desktop)",
"config.token_name_required": "Un nom est requis",
"config.token_expiry_1d": "1 jour",
"config.token_expiry_30d": "1 mois",
"config.token_expiry_180d": "6 mois",
"config.token_expiry_365d": "1 an",
"config.token_expiry_never": "Sans fin",
"config.token_create": "Créer une clé",
"config.token_secret_warning": "Copiez cette clé maintenant — elle ne sera plus jamais affichée.",
"config.token_copy": "Copier",
"config.token_copied": "Clé copiée dans le presse-papiers",
"config.token_done": "Terminé",
"config.token_usage": "Utilisation",
"config.token_usage_detail": ": en-tête « Authorization: Bearer <clé> » sur l'API ; pour MCP, déclarez-la dans les headers de l'URL /mcp.",
"config.token_created": "Créée le",
"config.token_expires": "Expire",
"config.token_last_used": "Dernière utilisation",
"config.token_never_used": "Jamais utilisée",
"config.token_status_active": "Active",
"config.token_status_expired": "Expirée",
"config.token_revoke": "Révoquer",
"config.token_revoke_confirm": "Révoquer la clé",
"config.token_revoked_toast": "Clé révoquée (effet immédiat API + MCP)",
"config.token_created_toast": "Clé créée",
"config.url_required": "URL requise",
"config.watcher_debounce_label": "Debounce (s)",
"config.watcher_enabled_label": "Activer la surveillance",
@@ -1794,11 +1823,24 @@
"viewer.export_title": "Exporter le document",
"viewer.forge_brand": "Forge",
"viewer.forge_title": "Forge (nouvel éditeur)",
"viewer.image_dimensions": "Dimensions",
"viewer.image_error": "Impossible de charger l'image",
"viewer.image_fullscreen": "Plein écran (lightbox)",
"viewer.image_metadata": "Métadonnées",
"viewer.image_next": "Image suivante",
"viewer.image_open_original": "Ouvrir l'original",
"viewer.image_prev": "Image précédente",
"viewer.image_type": "Type",
"viewer.image_zoom_in": "Zoom avant",
"viewer.image_zoom_out": "Zoom arrière",
"viewer.image_zoom_reset": "Réinitialiser le zoom",
"viewer.index_start": "Démarrage index.",
"viewer.index_updated": "Mise à jour",
"viewer.loaded_from_cache": "Fichier chargé depuis le cache hors-ligne",
"viewer.loading": "Chargement du fichier...",
"viewer.markdown": "Markdown",
"viewer.media_too_large": "Fichier trop volumineux pour la lecture intégrée. Téléchargez-le pour le lire.",
"viewer.media_unsupported": "Ce format ne peut pas être lu dans votre navigateur.",
"viewer.metadata_created": "Créé",
"viewer.metadata_modified": "Modifié",
"viewer.metadata_path": "Chemin",
@@ -1859,6 +1901,19 @@
"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.",
"mfa.qr_unavailable": "QR code indisponible — utilisez la saisie manuelle ci-dessous.",
"mfa.password_change_title": "Mot de passe",
"mfa.password_change_desc": "Modifiez le mot de passe de votre compte (min. 8 caractères). Toutes les autres sessions sont invalidées.",
"mfa.current_password_label": "Mot de passe actuel",
"mfa.current_password_placeholder": "Votre mot de passe actuel",
"mfa.new_password_label": "Nouveau mot de passe",
"mfa.new_password_placeholder": "Min. 8 caractères",
"mfa.new_password_confirm_label": "Confirmer le nouveau mot de passe",
"mfa.new_password_confirm_placeholder": "Répétez le nouveau mot de passe",
"mfa.password_change_btn": "Changer le mot de passe",
"mfa.password_mismatch": "Les deux mots de passe ne correspondent pas.",
"mfa.password_changed": "Mot de passe mis à jour.",
"mfa.challenge_unavailable": "Écran de vérification indisponible — veuillez recharger la page.",
"bookslm.title": "BooksLM",
"bookslm.files_indexed": "{count} fichiers indexés",
"bookslm.chars_loaded": "{chars} caractères chargés",
@@ -1973,6 +2028,23 @@
"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.",
"player.now_playing": "Lecture en cours",
"player.play": "Lecture",
"player.pause": "Pause",
"player.previous": "Précédent",
"player.next": "Suivant",
"player.seek": "Position de lecture",
"player.volume": "Volume",
"player.speed": "Vitesse de lecture",
"player.expand": "Agrandir le lecteur",
"player.minimize": "Réduire le lecteur",
"player.close": "Arrêter et fermer le lecteur",
"player.continues": "Lecture en cours — utilisez le lecteur pour l'arrêter.",
"player.reopen_tab": "Revenir au média",
"player.pip": "Image dans l'image",
"player.move": "Déplacer",
"player.resize": "Redimensionner",
"player.resume": "Reprise de la dernière lecture",
"plugins.title": "🧩 Plugins",
"plugins.description": "Étendez ObsiGate avec des renderers personnalisés, filtres de recherche et actions d'éditeur.",
"plugins.install": "Installer le plugin",
@@ -2074,7 +2146,7 @@
"guide105.lib_h3_conflicts": "Conflits de synchronisation",
"guide105.lib_conflicts": "Si vous synchronisez le vault avec Syncthing, ObsiGate détecte les fichiers de conflit (copies « sync-conflict ») et propose de les comparer puis résoudre depuis la page dédiée du menu Options.",
"guide105.lib_h3_attach": "Fichiers joints & médias",
"guide105.lib_attach": "Les images <code>![[image.png]]</code>, pièces jointes et médias (audio, vidéo, PDF intégrés) dans les notes sont rendus dans le viewer et indexés pour la recherche ; le bouton « Rescan attachments » de la configuration recrée l'index des pièces jointes.",
"guide105.lib_attach": "Les images <code>![[image.png]]</code>, pièces jointes et médias (audio, vidéo, PDF intégrés) dans les notes sont rendus dans le viewer et indexés pour la recherche. Les images apparaissent aussi dans l'arborescence et s'ouvrent dans une visionneuse dédiée (zoom molette, pan, navigation entre images du dossier, miniatures, métadonnées, lightbox) ; les fichiers audio (.mp3, .wav, .flac…) et vidéo (.mp4, .webm…) s'ouvrent dans un lecteur HTML5 intégré (lecture, déplacement, vitesse, plein écran), avec repli sur le téléchargement si le format n'est pas lisible par le navigateur ; la lecture continue pendant la navigation grâce à un mini-lecteur flottant (audio) ou une mini-fenêtre vidéo, qui permet à tout moment de revenir au média ou de l'arrêter. Le bouton « Rescan attachments » de la configuration recrée l'index des pièces jointes.",
"guide105.off_pwa": "ObsiGate est une PWA : installez-la (icône d'installation de la barre d'adresse) pour l'ouvrir comme une application. Le service worker met en cache l'interface et vos derniers documents consultés.",
"guide105.off_edit": "Hors-ligne, vous pouvez lire les documents en cache et même les éditer : les modifications sont mises en file d'attente dans IndexedDB.",
"guide105.off_sync": "Au retour en ligne, la file se rejoue automatiquement (badge de synchronisation dans l'en-tête). Si la version serveur a divergé entre-temps, le fichier est marqué en conflit et la version serveur est préservée en backup.",
+833 -10
View File
@@ -4347,6 +4347,76 @@ body.resizing-v {
background: var(--bg-hover);
}
/* BUG-068: .config-btn-primary / .config-btn-danger were used by the account
security section (frontend/js/auth.js) but never defined — the buttons fell
back to the browser default and ignored the theme. Defined here with the
same conventions as .config-btn-save / .config-btn-secondary. */
.config-btn-primary {
padding: 8px 16px;
border: 1px solid var(--accent);
border-radius: 6px;
background: var(--accent);
color: #fff;
font-family: "JetBrains Mono", monospace;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
transition: opacity 150ms;
}
.config-btn-primary:hover {
opacity: 0.9;
}
.config-btn-primary:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.config-btn-danger {
padding: 8px 16px;
border: 1px solid var(--danger, #e74c3c);
border-radius: 6px;
background: var(--danger-bg, #3d1a18);
color: var(--danger, #ff7b72);
font-family: "JetBrains Mono", monospace;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
transition: opacity 150ms;
}
.config-btn-danger:hover {
opacity: 0.9;
}
.config-btn-danger:disabled {
opacity: 0.55;
cursor: not-allowed;
}
/* BUG-068: local QR code (backend SVG data: URI) + password section share the
security-tab card conventions. */
.mfa-qr-code-img {
max-width: 200px;
border-radius: 8px;
background: #fff;
padding: 8px;
}
.password-settings {
margin-top: 20px;
padding-top: 16px;
border-top: 1px solid var(--border, #333);
}
.password-settings .form-group {
margin: 8px 0;
}
.password-settings .form-group label {
display: block;
font-size: 0.78rem;
color: var(--text-secondary, #aaa);
margin-bottom: 4px;
}
.password-settings .config-input {
width: 100%;
max-width: 320px;
}
/* --- AI keys section: accordion redesign (#104) --- */
.ai-keys-header {
display: flex;
@@ -4653,6 +4723,82 @@ body.resizing-v {
}
}
/* BUG-071: Configurations modal — mobile usability (viewport ≤ 768px).
#config-nav shares the .help-nav rule that hides it, but the config modal
had no toggle (unlike the help modal): the header hamburger
(#config-hamburger, same .help-hamburger treatment) reveals it as a
collapsible top block. Two-column grids and fixed-width add-rows are
stacked/wrapped so nothing overflows a 360px viewport. */
@media (max-width: 768px) {
/* TOC as a collapsible top block (JS toggles inline display flex/none,
which wins over the hiding rule); the list scrolls within a capped nav. */
#config-modal #config-nav {
width: 100%;
min-width: 0;
max-width: 100%;
border-right: none;
border-bottom: 1px solid var(--border);
max-height: 46vh;
}
/* Two-column grids → single column. */
#config-modal .ai-default-grid,
#config-modal .ai-provider-fields {
grid-template-columns: 1fr;
}
/* Add-rows (tokens, webhooks, tag filters) wrap instead of overflowing. */
#config-modal .config-add-row,
#config-modal .config-add-pattern {
flex-wrap: wrap;
}
#config-modal .config-add-row .config-input,
#config-modal .config-add-pattern .config-input,
#config-modal .config-add-row .config-select {
flex: 1 1 140px;
width: auto !important; /* override fixed inline widths (180/140/100px) */
min-width: 0;
}
#config-modal .config-add-row .config-btn-add,
#config-modal .config-add-pattern .config-btn-add {
flex: 1 1 auto;
min-height: 44px;
}
/* Webhook / token / share rows wrap; long URLs and meta take their own
line instead of squeezing the delete control off-screen. */
#config-modal .webhook-item,
#config-modal .token-item,
#config-modal .share-item {
flex-wrap: wrap;
}
#config-modal .webhook-url,
#config-modal .token-meta,
#config-modal .share-url {
flex: 1 1 100%;
min-width: 0;
white-space: normal;
overflow-wrap: anywhere;
}
#config-modal .webhook-delete,
#config-modal .token-delete,
#config-modal .share-revoke {
min-width: 44px;
min-height: 44px;
}
/* Sticky AI-keys footer: full-width touch-friendly buttons. */
#config-modal .ai-keys-footer .config-btn-save,
#config-modal .ai-keys-footer .config-btn-secondary {
flex: 1 1 100%;
min-height: 44px;
}
/* Long inline code in tips (ex. MCP usage snippet) must wrap. */
#config-modal .qh-tip {
flex-wrap: wrap;
}
#config-modal .qh-tip span {
min-width: 0;
overflow-wrap: anywhere;
}
}
/* --- Toast notifications --- */
.toast-container {
position: fixed;
@@ -7607,6 +7753,27 @@ body.popup-mode .content-area {
.config-add-row { display: flex; gap: 8px; margin-top: 8px; }
.config-btn-add { padding: 6px 14px; background: var(--accent); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 0.8rem; }
/* ── API/MCP tokens UI (#107) ── */
.token-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
background: var(--bg-card, var(--bg-secondary));
border-radius: 6px;
margin-bottom: 6px;
font-size: 0.8rem;
}
.token-name { font-weight: 500; min-width: 90px; }
.token-badge { font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; white-space: nowrap; }
.token-badge-active { background: color-mix(in srgb, var(--success, #2e7d32) 18%, transparent); color: var(--success, #2e7d32); }
.token-badge-expired { background: color-mix(in srgb, var(--text-error, #c62828) 15%, transparent); color: var(--text-error, #c62828); }
.token-meta { color: var(--text-muted); font-size: 0.7rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
.token-delete { background: none; border: none; color: var(--text-error); cursor: pointer; font-size: 1rem; padding: 2px 6px; }
.token-secret-area { margin-top: 10px; padding: 10px; border: 1px dashed var(--accent); border-radius: 8px; }
.token-secret-area.hidden { display: none; }
.token-secret-text { width: 100%; font-family: monospace; font-size: 0.7rem; word-break: break-all; resize: none; }
/* ── Shares UI ── */
.share-item {
display: flex;
@@ -9402,14 +9569,14 @@ body.desktop-mode .editor-container {
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--surface1);
background: var(--surface);
border-bottom: 1px solid var(--border);
font-size: 0.85rem;
flex-shrink: 0;
}
.pdf-info {
flex: 1;
color: var(--text-dim);
color: var(--text-secondary);
}
.pdf-iframe {
flex: 1;
@@ -9434,7 +9601,7 @@ body.desktop-mode .editor-container {
.pdf-toc h3 {
margin: 0 0 8px 0;
font-size: 0.9rem;
color: var(--text-dim);
color: var(--text-secondary);
}
.pdf-toc ul {
list-style: none;
@@ -9453,7 +9620,7 @@ body.desktop-mode .editor-container {
text-decoration: underline;
}
.toc-page {
color: var(--text-dim);
color: var(--text-secondary);
font-size: 0.75rem;
margin-left: 4px;
}
@@ -9464,7 +9631,7 @@ body.desktop-mode .editor-container {
align-items: center;
justify-content: center;
min-height: 200px;
background: var(--surface1);
background: var(--surface);
padding: 20px;
}
.image-viewer-body img {
@@ -9472,6 +9639,662 @@ body.desktop-mode .editor-container {
box-shadow: 0 2px 12px rgba(0,0,0,0.15);
}
/* #108-D — dedicated image viewer: zoom, pan, filmstrip, metadata, lightbox */
.image-viewer-container {
display: flex;
flex-direction: column;
height: 100%;
outline: none;
}
.image-toolbar {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
background: var(--surface);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.image-toolbar .image-title {
color: var(--text);
font-size: 0.85rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 40%;
}
.image-toolbar-spacer {
flex: 1;
}
.image-zoom-badge {
font-variant-numeric: tabular-nums;
font-size: 0.75rem;
color: var(--text-secondary);
min-width: 46px;
text-align: center;
}
.image-viewer-body {
flex: 1;
display: flex;
min-height: 0;
}
.image-stage {
flex: 1;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
background: var(--surface2);
cursor: grab;
touch-action: none;
}
.image-stage.panning {
cursor: grabbing;
}
.image-main {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transform-origin: center center;
user-select: none;
-webkit-user-drag: none;
will-change: transform;
}
.image-error {
color: var(--text-secondary);
font-size: 0.9rem;
}
.image-nav-strip {
display: flex;
gap: 6px;
padding: 8px;
overflow-x: auto;
background: var(--surface);
border-top: 1px solid var(--border);
flex-shrink: 0;
}
.image-nav-strip[hidden] {
display: none;
}
.image-thumb {
width: 72px;
height: 72px;
object-fit: cover;
border-radius: 4px;
border: 2px solid transparent;
cursor: pointer;
opacity: 0.65;
flex-shrink: 0;
}
.image-thumb:hover {
opacity: 1;
}
.image-thumb.active {
border-color: var(--accent);
opacity: 1;
}
.image-meta-panel {
width: 280px;
max-width: 40%;
overflow-y: auto;
padding: 10px 16px;
background: var(--surface);
border-left: 1px solid var(--border);
font-size: 0.8rem;
color: var(--text-secondary);
flex-shrink: 0;
}
.image-meta-panel[hidden] {
display: none;
}
.image-meta-panel dl {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 12px;
margin: 0;
}
.image-meta-panel dt {
color: var(--text-secondary);
}
.image-meta-panel dd {
margin: 0;
color: var(--text);
overflow-wrap: anywhere;
}
.image-viewer-container.lightbox {
position: fixed;
inset: 0;
z-index: 2000;
background: rgba(0, 0, 0, 0.9);
}
.image-viewer-container.lightbox .image-nav-strip {
display: none;
}
/* ── Audio / Video viewers (roadmap #109) ── */
.audio-viewer-container,
.video-viewer-container {
display: flex;
flex-direction: column;
height: 100%;
}
.media-toolbar {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
background: var(--surface);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.media-toolbar .media-title {
color: var(--text);
font-size: 0.85rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 40%;
}
.media-toolbar-spacer {
flex: 1;
}
.media-duration-badge {
font-variant-numeric: tabular-nums;
font-size: 0.75rem;
color: var(--text-secondary);
min-width: 46px;
text-align: center;
}
.media-meta {
font-size: 0.75rem;
color: var(--text-secondary);
}
.audio-stage {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 20px;
padding: 32px 24px;
min-height: 50vh;
background: var(--surface2);
}
.audio-artwork {
display: flex;
align-items: center;
justify-content: center;
width: 140px;
height: 140px;
border-radius: 12px;
background: var(--surface);
border: 1px solid var(--border);
color: var(--accent);
}
.audio-player {
width: min(560px, 100%);
}
.video-stage {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: #000;
overflow: hidden;
min-height: 60vh;
}
.video-player {
max-width: 100%;
max-height: calc(100vh - 180px);
object-fit: contain;
}
.media-fallback-actions {
display: flex;
gap: 8px;
margin-top: 12px;
}
/* ── Now Playing — persistent media dock (roadmap #110) ── */
.np-inline-slot {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
}
.np-inline-slot .np-media--audio {
width: min(560px, 100%);
}
.np-media--video {
max-width: 100%;
max-height: calc(100vh - 180px);
}
.np-host {
position: fixed;
inset: 0;
z-index: 950;
pointer-events: none;
}
.np-dock {
pointer-events: auto;
}
.np-ctrl {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
padding: 0;
border: none;
border-radius: 50%;
background: transparent;
color: var(--text);
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease;
}
.np-ctrl:hover {
background: color-mix(in srgb, var(--accent) 18%, transparent);
color: var(--accent);
}
.np-ctrl:disabled {
opacity: 0.35;
cursor: default;
}
.np-ctrl:disabled:hover {
background: transparent;
color: var(--text);
}
.np-dock--audio {
position: fixed;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 10px;
width: min(720px, calc(100vw - 32px));
padding: 8px 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
backdrop-filter: blur(12px);
overflow: hidden;
}
.np-dock--audio .np-media {
display: none;
}
.np-dock-art {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--surface2);
color: var(--accent);
cursor: pointer;
}
.np-dock-info {
flex: 1 1 120px;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
cursor: pointer;
}
.np-dock-title {
color: var(--text);
font-size: 0.85rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.np-dock-sub {
color: var(--text-secondary);
font-size: 0.72rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.np-dock-controls {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 2px;
}
.np-dock-progress {
flex: 1 1 160px;
min-width: 0;
display: flex;
align-items: center;
gap: 8px;
}
.np-time {
color: var(--text-secondary);
font-size: 0.7rem;
font-variant-numeric: tabular-nums;
min-width: 34px;
text-align: center;
}
.np-seek {
flex: 1;
-webkit-appearance: none;
appearance: none;
height: 4px;
border-radius: 2px;
background: var(--border);
cursor: pointer;
}
.np-seek::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 12px;
height: 12px;
border-radius: 50%;
background: var(--accent);
}
.np-seek::-moz-range-thumb {
width: 12px;
height: 12px;
border: none;
border-radius: 50%;
background: var(--accent);
}
.np-dock-actions {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 2px;
}
.np-volume {
display: flex;
align-items: center;
gap: 4px;
color: var(--text-secondary);
padding: 0 4px;
}
.np-volume-range {
width: 70px;
-webkit-appearance: none;
appearance: none;
height: 4px;
border-radius: 2px;
background: var(--border);
cursor: pointer;
}
.np-volume-range::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 11px;
height: 11px;
border-radius: 50%;
background: var(--accent);
}
.np-volume-range::-moz-range-thumb {
width: 11px;
height: 11px;
border: none;
border-radius: 50%;
background: var(--accent);
}
/* Video dock — floating, draggable, resizable mini-window */
.np-dock--video {
position: fixed;
background: #000;
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.5);
}
.np-dock-video-frame {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
}
.np-dock-video-slot {
flex: 1;
display: flex;
min-height: 0;
background: #000;
overflow: hidden;
}
.np-dock-video-slot .np-media--video {
width: 100%;
height: 100%;
object-fit: contain;
max-height: none;
}
.np-dock-video-bar {
display: flex;
align-items: center;
gap: 4px;
padding: 4px 6px;
background: rgba(0, 0, 0, 0.62);
}
.np-dock-video-bar .np-ctrl,
.np-dock-video-bar .np-time {
color: #f5f5f5;
}
.np-dock-video-bar .np-seek {
background: rgba(255, 255, 255, 0.28);
}
.np-dock-video-bar .np-ctrl:hover {
background: rgba(255, 255, 255, 0.16);
color: #fff;
}
.np-video-grip {
display: inline-flex;
align-items: center;
color: rgba(255, 255, 255, 0.7);
cursor: grab;
touch-action: none;
}
.np-video-grip:active {
cursor: grabbing;
}
.np-video-resize {
position: absolute;
right: 0;
bottom: 0;
width: 18px;
height: 18px;
cursor: nwse-resize;
touch-action: none;
}
.np-video-resize::after {
content: "";
position: absolute;
right: 3px;
bottom: 3px;
width: 9px;
height: 9px;
border-right: 2px solid rgba(255, 255, 255, 0.55);
border-bottom: 2px solid rgba(255, 255, 255, 0.55);
}
.np-dock--error .np-dock-error-msg {
color: #fff;
font-size: 0.8rem;
padding: 24px 16px;
text-align: center;
}
/* Expanded audio panel (bottom sheet on mobile) */
.np-expanded {
position: fixed;
inset: 0;
z-index: 960;
pointer-events: auto;
}
.np-expanded[hidden] {
display: none;
}
.np-expanded-backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.35);
}
.np-exp-card {
position: absolute;
left: 50%;
bottom: 96px;
transform: translateX(-50%);
width: min(460px, calc(100vw - 32px));
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 22px 20px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 18px;
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.5);
}
.np-exp-art {
display: flex;
align-items: center;
justify-content: center;
width: 120px;
height: 120px;
border-radius: 14px;
background: var(--surface2);
border: 1px solid var(--border);
color: var(--accent);
}
.np-exp-title {
color: var(--text);
font-size: 1rem;
text-align: center;
overflow-wrap: anywhere;
}
.np-exp-sub {
color: var(--text-secondary);
font-size: 0.78rem;
}
.np-exp-seek {
width: 100%;
}
.np-exp-times {
width: 100%;
display: flex;
justify-content: space-between;
}
.np-exp-controls {
display: flex;
align-items: center;
gap: 14px;
}
.np-exp-controls .np-ctrl {
width: 44px;
height: 44px;
}
.np-exp-play {
background: var(--accent);
color: #fff;
}
.np-exp-play:hover {
background: var(--accent);
color: #fff;
filter: brightness(1.08);
}
.np-exp-extra {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: center;
}
.np-rate {
background: var(--surface2);
color: var(--text);
border: 1px solid var(--border);
border-radius: 8px;
padding: 4px 6px;
font-size: 0.75rem;
}
/* Mid-size screens: drop the volume slider before the row gets cramped. */
@media (max-width: 1100px) {
.np-dock--audio .np-volume {
display: none;
}
}
@media (max-width: 768px) {
.np-dock--audio {
left: 8px;
right: 8px;
bottom: calc(64px + env(safe-area-inset-bottom, 0px) + 8px);
transform: none;
width: auto;
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto auto;
grid-template-areas:
"progress progress progress progress"
"art info controls actions";
align-items: center;
gap: 6px 8px;
padding: 8px 10px;
border-radius: 12px;
}
.np-dock--audio .np-dock-art {
grid-area: art;
width: 38px;
height: 38px;
}
.np-dock--audio .np-dock-info {
grid-area: info;
}
.np-dock--audio .np-dock-controls {
grid-area: controls;
}
.np-dock--audio .np-dock-progress {
grid-area: progress;
width: 100%;
min-width: 0;
}
.np-dock--audio .np-dock-actions {
grid-area: actions;
}
/* Compact mobile: keep play / return / close; expand via the artwork. */
.np-dock--audio [data-np="prev"],
.np-dock--audio [data-np="next"],
.np-dock--audio [data-np="expand"] {
display: none;
}
.np-dock--video {
left: 8px !important;
right: 8px;
top: auto !important;
bottom: calc(64px + env(safe-area-inset-bottom, 0px) + 8px) !important;
width: auto !important;
height: 200px !important;
border-radius: 12px;
}
.np-video-resize {
display: none;
}
.np-exp-card {
bottom: calc(64px + env(safe-area-inset-bottom, 0px) + 12px);
}
body.np-active .content-area {
padding-bottom: calc(64px + env(safe-area-inset-bottom, 0px) + 76px);
}
}
@media (prefers-reduced-motion: reduce) {
.np-ctrl,
.np-dock,
.np-exp-card {
transition: none;
}
}
/* ── Text / CSV Viewer ── */
.text-viewer-container {
display: flex;
@@ -9483,14 +10306,14 @@ body.desktop-mode .editor-container {
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--surface1);
background: var(--surface);
border-bottom: 1px solid var(--border);
font-size: 0.85rem;
flex-shrink: 0;
}
.file-info {
flex: 1;
color: var(--text-dim);
color: var(--text-secondary);
}
.text-viewer-body {
flex: 1;
@@ -9520,8 +10343,8 @@ body.desktop-mode .editor-container {
font-size: 0.85rem;
}
.csv-table th {
background: var(--surface1);
color: var(--text-dim);
background: var(--surface);
color: var(--text-secondary);
font-weight: 600;
padding: 8px 12px;
text-align: left;
@@ -9534,7 +10357,7 @@ body.desktop-mode .editor-container {
border-bottom: 1px solid var(--border-light, var(--border));
}
.csv-table tr:hover td {
background: var(--surface1);
background: var(--surface);
}
/* ── JSON Viewer ── */
+8 -1
View File
@@ -11,7 +11,7 @@
* cache or Cloudflare does NOT clear the Service Worker Cache Storage, which is
* a separate store. Bumping SW_VERSION invalidates it on every release.
*/
const SW_VERSION = 'v23';
const SW_VERSION = 'v24';
const CODE_CACHE = `obsigate-code-${SW_VERSION}`;
const RUNTIME_CACHE = `obsigate-runtime-${SW_VERSION}`;
const API_CACHE = `obsigate-api-${SW_VERSION}`;
@@ -109,6 +109,13 @@ self.addEventListener('fetch', (event) => {
// Let the browser handle range requests (PDF/streamed media) directly.
if (request.headers.has('range')) return;
// Streamed audio/video is large and range-driven — never cache it
// (roadmap #109-E2). Image thumbnails (/api/media/{vault}/thumb) stay cached.
if (url.pathname.startsWith('/api/media/') && !url.pathname.endsWith('/thumb')) {
event.respondWith(fetch(request));
return;
}
if (url.pathname.startsWith('/api/')) {
event.respondWith(networkFirst(request, API_CACHE, () =>
new Response(JSON.stringify({ error: 'Offline' }), {
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Génère un token d'accès ObsiGate longue durée pour le client MCP
# Conteneur de test local: obsigate-test (adapter le nom selon l'instance)
docker exec -i obsigate-test python - <<'PYEOF'
import time, uuid, json
from jose import jwt
key = open("data/secret.key").read().strip()
u = json.load(open("data/users.json"))["users"]["admin"]
now = int(time.time())
tok = jwt.encode({
"sub": "admin",
"role": u["role"],
"vaults": u["vaults"],
"jti": str(uuid.uuid4()),
"iat": now,
"exp": now + 31536000, # 1 an
"type": "access",
}, key, algorithm="HS256")
print(tok)
PYEOF
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "obsigate",
"version": "2.14.0",
"version": "2.19.2",
"description": "**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.",
"main": "patch.js",
"directories": {
@@ -9,7 +9,8 @@
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test:e2e": "bash scripts/run-e2e-local.sh"
"test:e2e": "bash scripts/run-e2e-local.sh",
"test:e2e:ps": "pwsh -NoProfile -File scripts/run-e2e-local.ps1"
},
"repository": {
"type": "git",
+120
View File
@@ -0,0 +1,120 @@
<#
.SYNOPSIS
ObsiGate — E2E locaux (Playwright) sous Windows/PowerShell.
.DESCRIPTION
Équivalent PowerShell de `scripts/run-e2e-local.sh`, pour les postes Windows
où `bash` n'est pas utilisable (WSL indisponible, git-bash bloqué par une
politique de contrôle d'application). Démarre le backend nativement via
uvicorn (auth désactivée, fixtures TestVault/TestDir, port 2029 — mêmes
conditions que le job CI `e2e`), lance la suite Playwright puis nettoie.
.PARAMETER PlaywrightArgs
Arguments transmis à `npx playwright test`, ex. `-g "image viewer"`,
`--headed`.
.EXAMPLE
./scripts/run-e2e-local.ps1
./scripts/run-e2e-local.ps1 -g "BUG-072"
./scripts/run-e2e-local.ps1 --headed
#>
[CmdletBinding()]
param(
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$PlaywrightArgs
)
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
Set-Location -LiteralPath $Root
$Port = if ($env:E2E_PORT) { $env:E2E_PORT } else { "2029" }
$BaseUrl = "http://127.0.0.1:$Port"
$ServerLog = "data/e2e-server.log"
$ServerErrLog = "data/e2e-server.err.log"
function Assert-Command([string]$Name, [string]$Hint) {
if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
throw "[ERR] $Name introuvable. $Hint"
}
}
Assert-Command "uv" "Installez-le : https://docs.astral.sh/uv/"
Assert-Command "npx" "Installez Node.js (>= 20)."
# ----- Venv Python 3.11 (créé une seule fois) -----
$Python = ".venv-e2e/Scripts/python.exe"
if (-not (Test-Path -LiteralPath $Python)) {
Write-Host "[INFO] Création du venv .venv-e2e (Python 3.11)..."
uv venv .venv-e2e --python 3.11
uv pip install --python $Python -r backend/requirements.txt
}
# ----- Port déjà occupé ? -----
try {
Invoke-WebRequest -Uri "$BaseUrl/api/health" -TimeoutSec 2 -UseBasicParsing | Out-Null
Write-Host "[ERR] Quelque chose répond déjà sur $BaseUrl."
Write-Host " Arrêtez-le ou choisissez un autre port : `$env:E2E_PORT=2030; ./scripts/run-e2e-local.ps1"
exit 1
} catch {
# port libre
}
# ----- Démarrage du serveur (mêmes conditions que le CI e2e) -----
Write-Host "[INFO] Démarrage d'ObsiGate sur $BaseUrl (auth désactivée)..."
New-Item -ItemType Directory -Force -Path "data" | Out-Null
$env:OBSIGATE_AUTH_ENABLED = "false"
$env:VAULT_1_NAME = "TestVault"
$env:VAULT_1_PATH = (Resolve-Path -LiteralPath "test_vault").Path
$env:DIR_1_NAME = "TestDir"
$env:DIR_1_PATH = (Resolve-Path -LiteralPath "test_dir").Path
$server = Start-Process -FilePath $Python `
-ArgumentList "-m", "uvicorn", "backend.main:app", "--host", "127.0.0.1", "--port", $Port `
-RedirectStandardOutput $ServerLog -RedirectStandardError $ServerErrLog `
-PassThru -WindowStyle Hidden
$exitCode = 1
try {
# ----- Attente du health check (30 s max, comme le CI) -----
$ready = $false
for ($i = 0; $i -lt 30; $i++) {
try {
Invoke-WebRequest -Uri "$BaseUrl/api/health" -TimeoutSec 2 -UseBasicParsing | Out-Null
$ready = $true
break
} catch {
if ($server.HasExited) {
Write-Host "[ERR] Le serveur a quitté prématurément. Log :"
Get-Content -LiteralPath $ServerErrLog -Tail 30 -ErrorAction SilentlyContinue
exit 1
}
Start-Sleep -Seconds 1
}
}
if (-not $ready) {
Write-Host "[ERR] Serveur injoignable sur $BaseUrl. Log :"
Get-Content -LiteralPath $ServerErrLog -Tail 30 -ErrorAction SilentlyContinue
exit 1
}
Write-Host "[OK] Serveur prêt."
# ----- Browsers Playwright (no-op s'ils sont déjà installés) -----
npx playwright install chromium
# ----- Exécution de la suite (projet CI : chromium-desktop) -----
Write-Host "[INFO] BASE_URL=$BaseUrl npx playwright test --project=chromium-desktop $($PlaywrightArgs -join ' ')"
$env:BASE_URL = $BaseUrl
& npx playwright test --project=chromium-desktop @PlaywrightArgs
$exitCode = $LASTEXITCODE
} finally {
Write-Host "[INFO] Arrêt du serveur (PID $($server.Id))..."
if (-not $server.HasExited) { Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue }
# uvicorn (via uv) peut lancer un interpréteur enfant : tuer le groupe resté sur le port.
Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }
}
exit $exitCode
File diff suppressed because it is too large Load Diff
+68
View File
@@ -0,0 +1,68 @@
Voici les trois niveaux de résumé pour le document **"Agents IA — Panorama Complet 2026"** :
---
---
### **1. En une phrase**
Ce document est **un panorama exhaustif et structuré des 72 agents IA disponibles en 2026**, classés par catégories, avec leurs descriptions, statuts, installations, utilisations et comparatifs techniques.
---
---
### **2. En un paragraphe**
Le document **"Agents IA — Panorama Complet 2026"** est une **référence complète** pour comprendre, installer et utiliser les agents IA du marché. Il recense **72 agents** répartis en **16 catégories** (ex. : agents locaux, poids lourds open source, trésors open source, local-first, propriétaires, etc.). Chaque agent est détaillé avec sa **description**, ses **liens officiels** (page principale et documentation), son **statut** (actif, stagnant ou fermé), ses **étapes d'installation** (commandes précises) et son **mode d'utilisation** (exemples de commandes). Le document inclut également un **tableau récapitulatif comparatif** (stars GitHub, type, compatibilité locale, etc.), des **recommandations**, une **matrice de décision**, ainsi que des sections dédiées aux **benchmarks**, **coûts**, **sécurité** et **glossaire**. Les sources sont vérifiées et mises à jour en **août 2026**.
---
---
### **3. En une page**
---
#### **Contexte**
Le document **"Agents IA — Panorama Complet 2026"**, rédigé par **Bruno Charest**, est une **ressource de référence** pour les développeurs, chercheurs et utilisateurs souhaitant explorer l’écosystème des agents IA. Il s’appuie sur des sources officielles (GitHub, arXiv, blogs spécialisés) et est **mis à jour au 12 août 2026**. L’objectif est de fournir une **vue d’ensemble structurée** des agents disponibles, leurs fonctionnalités, et leurs spécificités techniques.
---
#### **Structure et contenu**
Le document est organisé en **23 sections**, dont :
- **Tableau récapitulatif comparatif** : Une vue synthétique des 72 agents, avec des colonnes pour le **nom**, la **catégorie**, le **type** (OSS, propriétaire, etc.), le **nombre d’étoiles GitHub**, le **statut** (🟢 actif, 🟡 stagnant, 🔴 fermé), la **compatibilité locale** (✅/~/❌), et les **méthodes d’installation**.
- **Catégories d’agents** :
- **Agents installés localement** (ex. : Claude Code, Hermes Agent, Atomic Agent, Pi, Tiny Agents, NemoClaw).
- **Prime Agent** : Agent open-source basé sur le modèle **RLM** (Recursive Language Model), avec des fonctionnalités avancées comme la mémoire persistante et l’auto-amélioration.
- **Poids lourds open source** (ex. : OpenCode, Claw Code, Gemini CLI, Codex CLI, OpenHands, Goose, Aider).
- **Trésors open source** : Agents optimisés pour des cas d’usage spécifiques (ex. : jcode en Rust, agentty en C++26, NullClaw en Zig).
- **Agents local-first** : Solutions conçues pour fonctionner **100 % localement** (ex. : openyak, Kun, iPolloWork).
- **Écosystème OpenClaw** : Une famille d’agents légers et sécurisés (ex. : OpenClaw, ZeroClaw, NanoClaw).
- **Agents propriétaires** : Outils fermés mais populaires (ex. : Cursor CLI, Warp, GitHub Copilot CLI, Devin).
- **Sections transverses** :
- **Orchestrateurs & harnesses** : Outils pour gérer des workflows multi-agents.
- **Infrastructure & outils** : Solutions pour déployer et superviser des agents.
- **Benchmarks & évaluation** : Méthodes pour tester les performances des agents.
- **Coût & modèles** : Analyse des coûts associés (abonnements, inférence locale, etc.).
- **Sécurité & gouvernance** : Bonnes pratiques pour un usage sécurisé.
- **Glossaire** : Définitions des termes techniques (ex. : RLM, MCP, LSP).
---
#### **Points clés**
- **Diversité des agents** : Le document couvre des agents **génériques** (ex. : Claude Code, OpenCode) et **spécialisés** (ex. : SWE-agent pour résoudre des issues GitHub, Plandex pour le "plan-first").
- **Statuts variés** : Certains projets sont **actifs** (ex. : Prime Agent, OpenCode), tandis que d’autres sont **fermés** (ex. : Claw Code, transformé en musée) ou **stagnants** (ex. : Plandex, Groq Code CLI).
- **Installation et utilisation** : Chaque agent est accompagné de **commandes précises** pour son installation (ex. : `npm install -g @anthropic-ai/claude-code` pour Claude Code) et son utilisation (ex. : `claude "explique ce repo"`).
- **Approches techniques** :
- **Local-first** : Agents conçus pour fonctionner **hors ligne** (ex. : Atomic Agent, NullClaw).
- **Multi-modèles** : Compatibilité avec plusieurs fournisseurs de LLM (ex. : Hermes Agent supporte 300+ providers).
- **Sandboxing** : Solutions pour exécuter du code en toute sécurité (ex. : NemoClaw avec des politiques réseau strictes).
- **Comparatifs** : Le tableau récapitulatif permet de **filtrer rapidement** les agents en fonction de critères comme la compatibilité locale ou le nombre d’étoiles GitHub.
---
#### **Conclusions**
Ce document est une **mine d’informations** pour :
- **Choisir un agent** en fonction de ses besoins (ex. : développement local, collaboration en équipe, résolution de bugs).
- **Comprendre les tendances** du marché (ex. : montée en puissance des agents **local-first**, adoption croissante des modèles **open-source**).
- **Installer et configurer** un agent rapidement grâce aux **instructions pas-à-pas**.
- **Comparer les solutions** via des critères objectifs (statut, stars GitHub, compatibilité locale).
Il s’adresse aussi bien aux **débutants** qu’aux **experts**, avec des sections adaptées à chaque niveau de connaissance. Les **sources citées** (GitHub, arXiv, blogs) garantissent la **fiabilité** des informations.
+26
View File
@@ -0,0 +1,26 @@
# Beloeil et ses Villains
Plongez dans un univers où les légendes locales sortent de l’ombre pour hanter les vivants. Entre les ruelles pavées, usées par des siècles de secrets, et les forêts mystérieuses, dont les arbres semblent murmurer des avertissements aux voyageurs égarés, **Beloeil** est une ville où chaque pierre, chaque souffle de vent, porte le poids d’un passé maudit.
---
### Les Gardiens de l’Obscurité
Les méchants de Beloeil ne sont pas de simples antagonistes. Ils sont les **gardiens d’un héritage sombre**, tissé de magie ancienne, de rivalités familiales et de serments brisés. Leur présence imprègne la ville d’une atmosphère où la frontière entre le bien et le mal s’estompe, où chaque choix semble mener à une nouvelle malédiction.
- **Le Comte Déchu** : Son armure rouillée grince encore entre les murs de son château en ruines. Ses anciens sujets, transformés en spectres, murmurent des prières pour une rédemption qui ne viendra jamais. Son règne, autrefis glorieux, n’est plus qu’un écho de trahisons et de regrets.
- **La Sorcière des Marais** : Ses potions ne se contentent pas d’empoisonner les corps, elles **corrompent les âmes**. Les villageois qui osent s’aventurer près de son repaire reviennent transformés, assoiffés de vengeance, hantés par des voix qu’ils ne reconnaissent plus.
- **Les Frères Jumeaux** : Autrefois unis par un pacte de sang, l’un a trahi l’autre par ambition. Leur malédiction les lie désormais dans une **danse macabre**, condamnés à se combattre pour l’éternité, leurs lames s’entrechoquant dans un ballet sans fin.
---
### Une Ville de Secrets et de Retournements
Beloeil est un lieu où **les apparences trompent**. Le héros tant admiré pourrait cacher un passé taché de crimes. La malédiction qui pèse sur la ville pourrait trouver son origine dans un **amour interdit** entre une fée et un mortel. Chaque recoin cache une intrigue, chaque murmure un avertissement.
Le surnaturel y est omniprésent : sorts oubliés, artefacts maudits, créatures légendaires. **La magie et l’horreur s’y mêlent**, plongeant les lecteurs dans un monde où chaque page révèle un nouveau mystère, une nouvelle terreur.
---
### Une Histoire à Écrire
Beloeil est une toile de fond parfaite pour une narration **riche en intrigues complexes et en retournements inattendus**. Que ce soit à travers des quêtes désespérées, des alliances fragiles ou des trahisons imprévisibles, cette ville offre un terrain fertile pour explorer **l’obscurité de l’âme humaine et la puissance des légendes**.
File diff suppressed because one or more lines are too long
-2
View File
@@ -1,2 +0,0 @@
# Nouveau fichier dans Dir
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
# PostgreSQL backup script for HabitForge
set -e
# Configuration
BACKUP_DIR="/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/habitforge_backup_${TIMESTAMP}.sql.gz"
RETENTION_DAYS=7
# Database settings (from environment)
DB_HOST="${POSTGRES_HOST:-db}"
DB_PORT="${POSTGRES_PORT:-5432}"
DB_NAME="${POSTGRES_DB:-habitforge}"
DB_USER="${POSTGRES_USER:-habitforge}"
# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"
echo "Starting backup at $(date)"
# Perform backup
PGPASSWORD="${POSTGRES_PASSWORD}" pg_dump \
-h "${DB_HOST}" \
-p "${DB_PORT}" \
-U "${DB_USER}" \
-d "${DB_NAME}" \
--format=plain \
--no-owner \
--no-acl | gzip > "${BACKUP_FILE}"
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "Backup completed successfully: ${BACKUP_FILE}"
# Get file size
SIZE=$(du -h "${BACKUP_FILE}" | cut -f1)
echo "Backup size: ${SIZE}"
# Remove old backups (older than RETENTION_DAYS)
echo "Removing backups older than ${RETENTION_DAYS} days..."
find "${BACKUP_DIR}" -name "habitforge_backup_*.sql.gz" -type f -mtime +${RETENTION_DAYS} -delete
# List remaining backups
echo "Current backups:"
ls -lh "${BACKUP_DIR}"/habitforge_backup_*.sql.gz 2>/dev/null || echo "No backups found"
else
echo "Backup failed!"
exit 1
fi
echo "Backup finished at $(date)"
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""
Script to import Zepp health data from export-zepp directory into HabitForge database.
Usage: python scripts/import_zepp_data.py [--user-id USER_ID]
"""
import sys
import os
import argparse
# Add parent directory to path to import backend modules
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from backend.integrations.import_zepp import main as import_main, USER_ID as DEFAULT_USER_ID
from backend.integrations import import_zepp
def run_import(user_id: int = None):
"""Run the Zepp data import."""
if user_id:
# Override the default user ID
import_zepp.USER_ID = user_id
print(f"Importing data for user ID: {user_id}")
else:
print(f"Importing data for default user ID: {DEFAULT_USER_ID}")
import_main()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Import Zepp health data into HabitForge")
parser.add_argument(
"--user-id",
type=int,
help="User ID to import data for (default: 1)",
default=None
)
args = parser.parse_args()
run_import(args.user_id)
+162
View File
@@ -0,0 +1,162 @@
"""
Migration script from SQLite to PostgreSQL.
This script migrates data from the existing SQLite database to PostgreSQL.
Usage:
python scripts/migrate_to_postgres.py
Prerequisites:
- PostgreSQL database must be running
- DATABASE_URL environment variable must point to PostgreSQL
- SQLite database must exist at data/habitforge.db
"""
import os
import sys
from datetime import datetime
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from backend import models
from backend.database import Base, SessionLocal as SQLiteSessionLocal
# PostgreSQL connection
POSTGRES_URL = os.getenv("DATABASE_URL", "postgresql://habitforge:habitforge@localhost:5432/habitforge")
def migrate_data():
"""Migrate data from SQLite to PostgreSQL."""
print("Starting migration from SQLite to PostgreSQL...")
# Create PostgreSQL engine
postgres_engine = create_engine(POSTGRES_URL)
PostgresSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=postgres_engine)
# Create tables in PostgreSQL
print("Creating tables in PostgreSQL...")
Base.metadata.create_all(bind=postgres_engine)
# Get SQLite session
sqlite_session = SQLiteSessionLocal()
# Get PostgreSQL session
postgres_session = PostgresSessionLocal()
try:
# Migrate Users
print("Migrating Users...")
users = sqlite_session.query(models.User).all()
for user in users:
new_user = models.User(
id=user.id,
username=user.username,
hashed_password=user.hashed_password
)
postgres_session.add(new_user)
postgres_session.commit()
print(f"Migrated {len(users)} users")
# Migrate Challenges
print("Migrating Challenges...")
challenges = sqlite_session.query(models.Challenge).all()
for challenge in challenges:
new_challenge = models.Challenge(
id=challenge.id,
name=challenge.name,
period_type=challenge.period_type,
daily_target=challenge.daily_target,
start_date=challenge.start_date,
end_date=challenge.end_date,
display_order=challenge.display_order,
user_id=challenge.user_id,
icon=challenge.icon,
image_url=challenge.image_url,
description=challenge.description,
unit_type=challenge.unit_type,
rest_days=challenge.rest_days,
frequency=challenge.frequency
)
postgres_session.add(new_challenge)
postgres_session.commit()
print(f"Migrated {len(challenges)} challenges")
# Migrate Tracking
print("Migrating Tracking...")
trackings = sqlite_session.query(models.Tracking).all()
for tracking in trackings:
new_tracking = models.Tracking(
id=tracking.id,
challenge_id=tracking.challenge_id,
date=tracking.date,
reps=tracking.reps,
completed=tracking.completed,
notes=tracking.notes
)
postgres_session.add(new_tracking)
postgres_session.commit()
print(f"Migrated {len(trackings)} trackings")
# Migrate DailyHealthMetrics
print("Migrating DailyHealthMetrics...")
metrics = sqlite_session.query(models.DailyHealthMetrics).all()
for metric in metrics:
new_metric = models.DailyHealthMetrics(
id=metric.id,
user_id=metric.user_id,
date=metric.date,
step_count=metric.step_count,
calories_burned=metric.calories_burned,
distance_meters=metric.distance_meters,
sleep_duration_minutes=metric.sleep_duration_minutes,
deep_sleep_minutes=metric.deep_sleep_minutes,
light_sleep_minutes=metric.light_sleep_minutes,
rem_sleep_minutes=metric.rem_sleep_minutes,
awake_duration_minutes=metric.awake_duration_minutes,
avg_heart_rate=metric.avg_heart_rate,
min_heart_rate=metric.min_heart_rate,
max_heart_rate=metric.max_heart_rate,
avg_spo2=metric.avg_spo2,
pai_score=metric.pai_score,
weight=metric.weight,
resting_heart_rate=metric.resting_heart_rate,
hrv=metric.hrv
)
postgres_session.add(new_metric)
postgres_session.commit()
print(f"Migrated {len(metrics)} daily health metrics")
print("\nMigration completed successfully!")
print(f"Total records migrated:")
print(f" - Users: {len(users)}")
print(f" - Challenges: {len(challenges)}")
print(f" - Trackings: {len(trackings)}")
print(f" - DailyHealthMetrics: {len(metrics)}")
except Exception as e:
print(f"\nError during migration: {e}")
postgres_session.rollback()
raise
finally:
sqlite_session.close()
postgres_session.close()
postgres_engine.dispose()
if __name__ == "__main__":
# Check if SQLite database exists
if not os.path.exists("data/habitforge.db"):
print("Error: SQLite database not found at data/habitforge.db")
sys.exit(1)
# Confirm migration
print("This will migrate data from SQLite to PostgreSQL.")
print(f"PostgreSQL URL: {POSTGRES_URL}")
response = input("Do you want to continue? (yes/no): ")
if response.lower() != "yes":
print("Migration cancelled.")
sys.exit(0)
migrate_data()
+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
# Production startup script for HabitForge
set -e
echo "Starting HabitForge in production mode..."
# Wait for database to be ready
echo "Waiting for database..."
while ! pg_isready -h ${POSTGRES_HOST:-db} -U ${POSTGRES_USER:-habitforge} -d ${POSTGRES_DB:-habitforge} > /dev/null 2>&1; do
echo "Database is unavailable - sleeping"
sleep 1
done
echo "Database is ready!"
# Run migrations
echo "Running database migrations..."
alembic upgrade head
# Start Gunicorn
echo "Starting Gunicorn..."
exec gunicorn backend.main:app \
--workers ${GUNICORN_WORKERS:-4} \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--access-logfile - \
--error-logfile - \
--log-level ${LOG_LEVEL:-info}
+281
View File
@@ -0,0 +1,281 @@
{
"type": "excalidraw",
"version": 2,
"elements": [
{
"id": "E_M7axF81tmVRs3_iSNTB",
"type": "rectangle",
"x": 474,
"y": 146.33334350585938,
"width": 415.3333740234375,
"height": 216.66665649414062,
"angle": 0,
"strokeColor": "#e03131",
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": "solid",
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": null,
"index": "a0",
"roundness": {
"type": 3
},
"seed": 975148614,
"version": 75,
"versionNonce": 1779287411,
"isDeleted": false,
"boundElements": [
{
"id": "9M-JFwSrjH6KSHIaBvvTI",
"type": "arrow"
}
],
"updated": 1789701383205,
"created": 1789695569357,
"link": null,
"locked": false
},
{
"id": "r0qk76e8Zwvzg03cCJTet",
"type": "diamond",
"x": 602,
"y": 154.33334350585938,
"width": 195.3333740234375,
"height": 202,
"angle": 0,
"strokeColor": "#f08c00",
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": "solid",
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": null,
"index": "a1",
"roundness": {
"type": 2
},
"seed": 1824592326,
"version": 88,
"versionNonce": 1410387869,
"isDeleted": false,
"boundElements": [],
"updated": 1789701386097,
"created": 1789695572009,
"link": null,
"locked": false
},
{
"id": "9KK6ZVdnduPeYFFFCFAsy",
"type": "ellipse",
"x": 980.6668701171875,
"y": 170.0000457763672,
"width": 162.66668701171875,
"height": 141.3333740234375,
"angle": 0,
"strokeColor": "#1e1e1e",
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": "solid",
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": null,
"index": "a2",
"roundness": {
"type": 2
},
"seed": 1669693053,
"version": 190,
"versionNonce": 1391288573,
"isDeleted": false,
"boundElements": [
{
"id": "9M-JFwSrjH6KSHIaBvvTI",
"type": "arrow"
}
],
"updated": 1789701376494,
"link": null,
"locked": false
},
{
"id": "9M-JFwSrjH6KSHIaBvvTI",
"type": "arrow",
"x": 895.3334350585938,
"y": 248.66673278808594,
"width": 82.66668701171875,
"height": 3.333343505859375,
"angle": 0,
"strokeColor": "#e03131",
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": "solid",
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": null,
"index": "a3",
"roundness": {
"type": 2
},
"seed": 1977221331,
"version": 35,
"versionNonce": 23426611,
"isDeleted": false,
"boundElements": null,
"updated": 1789701380015,
"link": null,
"locked": false,
"points": [
[
0,
0
],
[
82.66668701171875,
-3.333343505859375
]
],
"lastCommittedPoint": null,
"startBinding": {
"elementId": "E_M7axF81tmVRs3_iSNTB",
"focus": 0.022412363413033574,
"gap": 6.00006103515625
},
"endBinding": {
"elementId": "9KK6ZVdnduPeYFFFCFAsy",
"focus": -0.017303733989364446,
"gap": 2.836434396181596
},
"startArrowhead": null,
"endArrowhead": "arrow",
"elbowed": false
}
],
"appState": {
"showWelcomeScreen": false,
"theme": "dark",
"collaborators": {},
"currentChartType": "bar",
"currentItemBackgroundColor": "transparent",
"currentItemEndArrowhead": "arrow",
"currentItemFillStyle": "solid",
"currentItemFontFamily": 5,
"currentItemFontSize": 20,
"currentItemOpacity": 100,
"currentItemRoughness": 1,
"currentItemStartArrowhead": null,
"currentItemStrokeColor": "#f08c00",
"currentItemRoundness": "round",
"currentItemArrowType": "round",
"currentItemStrokeStyle": "solid",
"currentItemStrokeWidth": 2,
"currentItemTextAlign": "left",
"currentHoveredFontFamily": null,
"cursorButton": "up",
"activeEmbeddable": null,
"newElement": null,
"editingTextElement": null,
"editingGroupId": null,
"editingLinearElement": null,
"activeTool": {
"type": "selection",
"customType": null,
"locked": false,
"lastActiveTool": {
"type": "selection",
"customType": null,
"locked": false,
"lastActiveTool": null
}
},
"penMode": false,
"penDetected": false,
"errorMessage": null,
"exportBackground": true,
"exportScale": 1,
"exportEmbedScene": false,
"exportWithDarkMode": false,
"fileHandle": null,
"gridSize": 20,
"gridStep": 5,
"gridModeEnabled": false,
"isBindingEnabled": true,
"defaultSidebarDockedPreference": false,
"isLoading": false,
"isResizing": false,
"isRotating": false,
"lastPointerDownWith": "mouse",
"multiElement": null,
"name": "Untitled-2026-09-17-2148",
"contextMenu": null,
"openMenu": null,
"openPopup": null,
"openSidebar": null,
"openDialog": null,
"pasteDialog": {
"shown": false,
"data": null
},
"previousSelectedElementIds": {
"E_M7axF81tmVRs3_iSNTB": true
},
"resizingElement": null,
"scrolledOutside": false,
"scrollX": -23.33343505859375,
"scrollY": 101.99995422363281,
"selectedElementIds": {
"r0qk76e8Zwvzg03cCJTet": true
},
"hoveredElementIds": {},
"selectedGroupIds": {},
"selectedElementsAreBeingDragged": false,
"selectionElement": null,
"shouldCacheIgnoreZoom": false,
"stats": {
"open": false,
"panels": 3
},
"startBoundElement": null,
"suggestedBindings": [],
"frameRendering": {
"enabled": true,
"clip": true,
"name": true,
"outline": true
},
"frameToHighlight": null,
"editingFrame": null,
"elementsToHighlight": null,
"toast": null,
"viewBackgroundColor": "#ffffff",
"zenModeEnabled": false,
"zoom": {
"value": 1
},
"viewModeEnabled": false,
"pendingImageElementId": null,
"showHyperlinkPopup": false,
"selectedLinearElement": null,
"snapLines": [],
"originSnapOffset": null,
"objectsSnapModeEnabled": false,
"userToFollow": null,
"followedBy": {},
"isCropping": false,
"croppingElementId": null,
"searchMatches": [],
"offsetLeft": 0,
"offsetTop": 0,
"width": 1280,
"height": 800
},
"files": {}
}
+30 -1
View File
@@ -1,3 +1,32 @@
---
titre: ObsiGate — Analyse complète & Recommandations V1.1
auteur: Hermes-Claw
tags:
- analyse
- obsigate
- recommandations
- sécurité
- roadmap
- audit
- v1.1
aliases:
- ObsiGate Analyse
- Audit ObsiGate V1.1
catégorie: Analyse Technique
NomDeVoute: TestVault
Description: Analyse complète et recommandations pour ObsiGate, incluant fonctionnalités, forces, points d'amélioration, roadmap et checklist de professionnalisation.
creation_date: 2026-05-25T00:00:00+02:00
modification_date: 2026-10-07T12:00:00+02:00
status: finalisé
publish: true
favoris: true
template: false
task: false
archive: false
draft: false
private: false
---
# ObsiGate — Analyse complète & Recommandations V1.1
> **Date :** 2026-05-25 | **Analyste :** Hermes-Claw + Audit Code Source | **Version testée :** 1.4.0 (backend) / 1.5.0 (frontend) — http://openclaw1.dev.home:2020
@@ -381,4 +410,4 @@ TOTP ou WebAuthn pour l'accès admin.
---
*Analyse réalisée le 2026-05-25 — Révisée V1.1 après audit complet du code source*
*Document : ANALYSE_REVIEW.md*
*Document : ANALYSE_REVIEW.md*
Binary file not shown.
+24 -8
View File
@@ -7,16 +7,32 @@ publish: true
date: 2025-01-15
---
# Bienvenue dans le vault de test
# 📌 **Bienvenue dans TestVault**
Ceci est un document de test pour [[ObsiGate]].
**TestVault** est votre espace centralisé pour organiser, structurer et optimiser la gestion de vos notes et connaissances. Conçue pour allier **efficacité** et **simplicité**, cette voute vous permet de travailler de manière intuitive tout en bénéficiant d'outils puissants.
## Sections
---
- [[Projets/Projet Alpha]] - Un projet en cours
- [[Notes/Configuration serveur]] - Documentation technique
- [[Recettes/Pâtes carbonara]] - Une recette
## 🚀 **Fonctionnalités clés**
## Tags
✅ **Gestion intelligente des notes**
- Créez, modifiez et organisez vos notes en toute simplicité.
- Accédez rapidement à vos informations grâce à une structure claire.
✅ **Organisation avancée**
- Utilisez des **tags** et des **catégories** pour classer vos notes de manière logique.
- Retrouvez vos informations en un clin d'œil.
✅ **Recherche rapide et efficace**
- Trouvez ce dont vous avez besoin en quelques secondes.
✅ **Synchronisation multi-appareils**
- Accédez à vos notes où que vous soyez, sur tous vos appareils.
---
## 📂 **Structure de la voute**
Cette voute est conçue pour être **modulaire** et **évolutive**. Vous pouvez l'adapter selon vos besoins pour une expérience personnalisée.
---
#accueil #important #test
+214 -13
View File
@@ -10,6 +10,35 @@ title: Docker Guide
# Docker Guide
## Installation de Docker
### Sur Linux (Debian/Ubuntu)
```bash
# Mettre à jour les paquets
sudo apt update
# Installer les dépendances
sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release
# Ajouter la clé GPG officielle de Docker
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
# Ajouter le dépôt Docker
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# Installer Docker Engine
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io
# Vérifier l'installation
sudo docker run hello-world
```
### Sur macOS/Windows
- Télécharger [Docker Desktop](https://www.docker.com/products/docker-desktop/) et suivre les instructions.
---
## Commandes essentielles
```bash
@@ -20,36 +49,208 @@ docker ps -a
docker build -t myapp:latest .
# Lancer un conteneur
docker run -d -p 8080:80 myapp:latest
docker run -d -p 8080:80 --name my_container myapp:latest
# Voir les logs
docker logs -f container_name
docker logs -f my_container
# Arrêter un conteneur
docker stop my_container
# Supprimer un conteneur
docker rm my_container
# Supprimer une image
docker rmi myapp:latest
```
## Docker Compose
---
```yaml
version: "3.9"
services:
web:
image: nginx:alpine
ports:
- "80:80"
## Réseaux Docker
Docker propose plusieurs types de réseaux pour isoler ou connecter vos conteneurs :
| Type | Description | Exemple d'utilisation |
|------------|--------------------------------------|-------------------------------------|
| **bridge** | Réseau par défaut pour les conteneurs | `docker run -p 8080:80 myapp` |
| **host** | Conteneur utilise l'IP de l'hôte | `docker run --network host myapp` |
| **overlay**| Pour les swarms multi-hôtes | Utilisé avec `docker stack deploy` |
**Exemple : Créer un réseau personnalisé**
```bash
docker network create my_network
docker run -d --network my_network --name db redis
```
---
## Volumes
Les volumes permettent de persister les données :
- **Named volumes** : gérés par Docker
```bash
docker volume create my_volume
docker run -v my_volume:/data myapp
```
- **Bind mounts** : montage direct depuis l'hôte
```bash
docker run -v /chemin/absolu:/data myapp
```
- **tmpfs** : stockage en mémoire
```bash
docker run --tmpfs /data myapp
```
Voir aussi : [[Proxmox Setup]]
---
## Docker Compose
Exemple de fichier `docker-compose.yml` avec variables d'environnement et dépendances :
```yaml
version: "3.9"
services:
web:
image: nginx:alpine
ports:
- "80:80"
environment:
- NGINX_ENV=production
depends_on:
- redis
networks:
- frontend
redis:
image: redis:alpine
volumes:
- redis_data:/data
networks:
- frontend
volumes:
redis_data:
networks:
frontend:
driver: bridge
```
**Commandes utiles**
```bash
# Démarrer les services
docker-compose up -d
# Arrêter les services
docker-compose down
# Voir les logs
docker-compose logs -f
```
---
## Dockerfile : Exemple commenté
Voici un exemple de `Dockerfile` pour une application Python (FastAPI) :
```dockerfile
# Utiliser une image officielle Python comme base
FROM python:3.9-slim
# Définir le répertoire de travail
WORKDIR /app
# Copier les fichiers de dépendances
COPY requirements.txt .
# Installer les dépendances
RUN pip install --no-cache-dir -r requirements.txt
# Copier le reste du code source
COPY . .
# Exposer le port 8000
EXPOSE 8000
# Commande pour lancer l'application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
**Bonnes pratiques pour un Dockerfile** :
- Utiliser des images `slim` ou `alpine` pour réduire la taille.
- Multi-stage builds pour les applications compilées (Go, Rust, etc.).
- Toujours inclure un fichier `.dockerignore`.
---
## Sécurité
### Bonnes pratiques
- **Éviter de lancer des conteneurs en tant que `root`** :
```bash
docker run --user 1000:1000 myapp
```
- **Rendre le système de fichiers en lecture seule** :
```bash
docker run --read-only myapp
```
- **Limiter les capacités du conteneur** :
```bash
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE myapp
```
- **Scanner les images pour des vulnérabilités** :
Utiliser des outils comme [Trivy](https://github.com/aquasecurity/trivy) ou [Clair](https://github.com/quay/clair).
---
## Nettoyage des ressources
Pour libérer de l'espace, supprimez les ressources inutilisées :
```bash
# Supprimer les conteneurs arrêtés
docker container prune
# Supprimer les images inutilisées
docker image prune -a
# Supprimer les volumes inutilisés
docker volume prune
# Supprimer les réseaux inutilisés
docker network prune
# Nettoyer TOUT (attention, irréversible !)
docker system prune -a --volumes
```
---
## Bonnes pratiques
- [ ] Utiliser des images Alpine
- [ ] Multi-stage builds
- [x] Utiliser des images Alpine ou `slim`
- [x] Multi-stage builds pour les applications compilées
- [x] Fichier `.dockerignore`
- [x] Un processus par conteneur
- [x] Un processus par conteneur
- [x] Limiter les ressources (CPU/mémoire) avec `--memory` et `--cpus`
- [x] Utiliser des secrets pour les variables sensibles (ex: `--env-file` ou `docker secret`)
---
## Ressources utiles
- [Documentation officielle Docker](https://docs.docker.com/)
- [Docker Curriculum](https://docker-curriculum.com/)
- [Awesome Docker](https://github.com/veggiemonk/awesome-docker)
- [Tutoriel Docker Compose](https://docs.docker.com/compose/)
Voir aussi : [[Proxmox Setup]]
+10
View File
@@ -0,0 +1,10 @@
// Démonstration JavaScript pour le vault de test ObsiGate
const API_URL = "http://localhost:2020/api";
async function fetchVaults() {
const res = await fetch(`${API_URL}/vaults`);
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}
fetchVaults().then((v) => console.log("vaults:", v));
+12
View File
@@ -0,0 +1,12 @@
// Démonstration TypeScript pour le vault de test ObsiGate
interface Vault {
name: string;
files: number;
}
function summarize(vaults: Vault[]): string {
const total = vaults.reduce((acc, v) => acc + v.files, 0);
return `${vaults.length} vaults, ${total} fichiers`;
}
export default summarize;
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Script de démonstration pour le vault de test ObsiGate."""
import os
import sys
import json
from pathlib import Path
def main(argv):
print("hello from ObsiGate test vault") # commentaire
data = {"vaults": ["IT", "Perso"], "count": 2}
print(json.dumps(data, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+13
View File
@@ -0,0 +1,13 @@
import unittest
class TestDemo(unittest.TestCase):
def test_true_is_true(self):
self.assertTrue(True) # trivial test
def test_number(self):
self.assertEqual(2 + 2, 4)
if __name__ == "__main__":
unittest.main()
+16 -1
View File
@@ -1,7 +1,22 @@
---
title: Pizza Maison
tags: [recette, pizza, rapide]
tags: [recette, pizza, rapide, cuisine maison]
date: 2025-03-15
modification_date: 2025-10-31T14:30:00+01:00
aliases: [pizza maison, recette pizza]
catégorie: Recettes
NomDeVoute: TestVault
Description: Recette détaillée pour préparer une pizza maison avec pâte, sauce tomate et garnitures variées.
auteur: Inconnu
creation_date: 2025-03-15
status: publié
publish: true
favoris: false
template: recette
task: []
archive: false
draft: false
private: false
---
# Pizza Maison 2
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
# PostgreSQL backup script for HabitForge
set -e
# Configuration
BACKUP_DIR="/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/habitforge_backup_${TIMESTAMP}.sql.gz"
RETENTION_DAYS=7
# Database settings (from environment)
DB_HOST="${POSTGRES_HOST:-db}"
DB_PORT="${POSTGRES_PORT:-5432}"
DB_NAME="${POSTGRES_DB:-habitforge}"
DB_USER="${POSTGRES_USER:-habitforge}"
# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"
echo "Starting backup at $(date)"
# Perform backup
PGPASSWORD="${POSTGRES_PASSWORD}" pg_dump \
-h "${DB_HOST}" \
-p "${DB_PORT}" \
-U "${DB_USER}" \
-d "${DB_NAME}" \
--format=plain \
--no-owner \
--no-acl | gzip > "${BACKUP_FILE}"
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "Backup completed successfully: ${BACKUP_FILE}"
# Get file size
SIZE=$(du -h "${BACKUP_FILE}" | cut -f1)
echo "Backup size: ${SIZE}"
# Remove old backups (older than RETENTION_DAYS)
echo "Removing backups older than ${RETENTION_DAYS} days..."
find "${BACKUP_DIR}" -name "habitforge_backup_*.sql.gz" -type f -mtime +${RETENTION_DAYS} -delete
# List remaining backups
echo "Current backups:"
ls -lh "${BACKUP_DIR}"/habitforge_backup_*.sql.gz 2>/dev/null || echo "No backups found"
else
echo "Backup failed!"
exit 1
fi
echo "Backup finished at $(date)"
+7
View File
@@ -0,0 +1,7 @@
2026-09-14 08:12:01 INFO Starting ObsiGate test service on port 2020
2026-09-14 08:12:02 DEBUG Loaded 2 vaults: "IT", "Perso"
2026-09-14 08:12:05 WARN Disk usage at 82% on /var/data
2026-09-14 08:13:11 ERROR Failed to open "/var/db/index.sqlite"
2026-09-14 08:13:12 INFO Retrying in 5 seconds...
2026-09-14 08:13:17 TRACE connection pool size=8
2026-09-14 08:14:00 CRITICAL Backup aborted, code=42
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

@@ -0,0 +1,91 @@
# Vaccin Zona 2024 : Analyse Shingrix® vs Zostavax®
#médecine #vaccin #zona #2024 #santé
---
## 🔍 **Contexte 2024 : Shingrix® devient la référence**
- **Nom** : **Shingrix®** (GSK) – Vaccin **sous-unitaire recombinant** (non vivant).
- **Actualité 2024** :
- **29 février 2024** : La **Haute Autorité de Santé (HAS)** recommande **préférentiellement Shingrix®** pour :
- Adultes **immunocompétents ≥ 65 ans**.
- Personnes **immunodéprimées ≥ 18 ans** (ex. chimiothérapie, VIH).
- Personnes ayant **déjà eu un zona** ou vaccinées avec Zostavax® (délai d’1 an).
- **Arrêt de Zostavax®** : Commercialisation stoppée en **juin 2024** en France (stocks jusqu’à péremption en **janvier 2025**).
**Sources** : [MesVaccins](https://www.mesvaccins.net/web/vaccines/161-zostavax), [HAS](https://www.has-sante.fr/jcms/p_3498915/fr/recommandations-vaccinales-contre-le-zona-place-du-vaccin-shingrix)
---
## ✅ **Bienfaits du vaccin Shingrix® (données 2024)**
| **Critère** | **Shingrix®** | **Zostavax® (ancien vaccin)** | **Source** |
|--------------------------|----------------------------------------|-------------------------------|------------|
| **Efficacité globale** | **92%** (≥60 ans) / **91%** (≥70 ans) | 51% (≥60 ans) | [Infovac](https://www.infovac.ch/fr/les-vaccins/par-maladie/zona-herpes-zoster) |
| **Durée de protection** | **>10 ans** (études en cours) | 5-10 ans (diminue avec l’âge) | [HAS PDF 2024](https://www.has-sante.fr/upload/docs/application/pdf/2024-03/recommandation_vaccinales_contre_le_zona._place_du_vaccin_shingrix_2024-03-04_11-26-41_450.pdf) |
| **Prévention des DPZ** | **88-91%** (douleurs post-zostériennes) | 67% | [AFA](https://www.afa.asso.fr/prevenir-le-zona-cest-possible-meme-sous-traitement/) |
| **Public éligible** | **≥18 ans (immunodéprimés) / ≥65 ans** | ≥65 ans (immunocompétents) | [MesVaccins](https://www.mesvaccins.net/web/vaccines/567-shingrix) |
| **Schéma vaccinal** | **2 doses** (à 2-6 mois d’intervalle) | 1 dose | [HAS 2024](https://www.has-sante.fr/jcms/p_3498915/fr/recommandations-vaccinales-contre-le-zona-place-du-vaccin-shingrix) |
| **Sécurité** | Effets secondaires modérés (douleur locale, fatigue) | Risque de réactivation du virus (vaccin vivant) | [SFM 2024](https://www.sfm-microbiologie.org/2024/03/24/un-nouveau-vaccin-contre-le-zona-recommande-par-la-haute-autorite-de-sante-has/) |
---
## 🎯 **Pourquoi Shingrix® est-il une avancée majeure en 2024 ?**
1. **Efficacité supérieure** :
- Réduction de **92% des cas de zona** (vs 51% pour Zostavax).
- **Prévention des douleurs chroniques (DPZ)** dans **88-91% des cas** (vs 67%).
2. **Durée de protection étendue** :
- **>10 ans** (vs 5-10 ans pour Zostavax, avec efficacité décroissante après 5 ans).
3. **Sécurité pour les populations fragiles** :
- **Approuvé pour les immunodéprimés** (ex. patients sous traitement immunosuppresseur, VIH).
4. **Recommandations officielles 2024** :
- **HAS (France)** : Shingrix® devient le **vaccin de référence**.
- **Arrêt de Zostavax®** : Plus commercialisé en France depuis **juin 2024**.
---
## ⚠️ **Limites et points de vigilance**
- **Effets secondaires** :
- **Fréquents mais bénins** : Douleur locale (78%), fatigue (45%), maux de tête (38%), fièvre (21%).
- **Rares** : Réactions allergiques graves.
- **Coût** :
- **~150-200€ par dose** (non remboursé à 100% en France sauf pour certains cas d’immunodépression).
- **Schéma à 2 doses** (espacées de 2 à 6 mois).
- **Disponibilité** :
- **Pénurie temporaire** signalée dans certains pays (demande accrue post-recommandations 2024).
---
## 📌 **Recommandations pratiques (2024)**
- **Pour qui ?**
- Adultes **≥65 ans** (même sans antécédent de zona).
- **Immunodéprimés ≥18 ans** (ex. cancer, VIH, greffés).
- Personnes ayant **déjà eu un zona** (après guérison).
- **Quand ?**
- **2 doses** à 2-6 mois d’intervalle.
- **Pas de rappel recommandé** pour l’instant.
- **Où ?**
- Pharmacies, médecins, centres de vaccination (sur ordonnance en France).
---
## 🔗 **Sources officielles (2024)**
1. **Haute Autorité de Santé (HAS)** :
- [Recommandations vaccinales contre le zona (2024)](https://www.has-sante.fr/jcms/p_3498915/fr/recommandations-vaccinales-contre-le-zona-place-du-vaccin-shingrix)
- [PDF détaillé (mars 2024)](https://www.has-sante.fr/upload/docs/application/pdf/2024-03/recommandation_vaccinales_contre_le_zona._place_du_vaccin_shingrix_2024-03-04_11-26-41_450.pdf)
2. **MesVaccins.net** :
- [Fiche Shingrix®](https://www.mesvaccins.net/web/vaccines/567-shingrix)
- [Fiche Zona](https://www.mesvaccins.net/web/diseases/33-zona)
3. **Infovac (Suisse)** :
- [Comparatif Shingrix vs Zostavax](https://www.infovac.ch/fr/les-vaccins/par-maladie/zona-herpes-zoster)
4. **Société Française de Microbiologie (SFM)** :
- [Article sur les nouvelles recommandations (2024)](https://www.sfm-microbiologie.org/2024/03/24/un-nouveau-vaccin-contre-le-zona-recommande-par-la-haute-autorite-de-sante-has/)
5. **Vaccination Info Service (France)** :
- [Page Zona](https://www.vaccination-info-service.fr/Les-maladies-et-leurs-vaccins/Zona)
---
*Dernière mise à jour : 2024*
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
# PostgreSQL backup script for HabitForge
set -e
# Configuration
BACKUP_DIR="/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/habitforge_backup_${TIMESTAMP}.sql.gz"
RETENTION_DAYS=7
# Database settings (from environment)
DB_HOST="${POSTGRES_HOST:-db}"
DB_PORT="${POSTGRES_PORT:-5432}"
DB_NAME="${POSTGRES_DB:-habitforge}"
DB_USER="${POSTGRES_USER:-habitforge}"
# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"
echo "Starting backup at $(date)"
# Perform backup
PGPASSWORD="${POSTGRES_PASSWORD}" pg_dump \
-h "${DB_HOST}" \
-p "${DB_PORT}" \
-U "${DB_USER}" \
-d "${DB_NAME}" \
--format=plain \
--no-owner \
--no-acl | gzip > "${BACKUP_FILE}"
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "Backup completed successfully: ${BACKUP_FILE}"
# Get file size
SIZE=$(du -h "${BACKUP_FILE}" | cut -f1)
echo "Backup size: ${SIZE}"
# Remove old backups (older than RETENTION_DAYS)
echo "Removing backups older than ${RETENTION_DAYS} days..."
find "${BACKUP_DIR}" -name "habitforge_backup_*.sql.gz" -type f -mtime +${RETENTION_DAYS} -delete
# List remaining backups
echo "Current backups:"
ls -lh "${BACKUP_DIR}"/habitforge_backup_*.sql.gz 2>/dev/null || echo "No backups found"
else
echo "Backup failed!"
exit 1
fi
echo "Backup finished at $(date)"
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""
Script to import Zepp health data from export-zepp directory into HabitForge database.
Usage: python scripts/import_zepp_data.py [--user-id USER_ID]
"""
import sys
import os
import argparse
# Add parent directory to path to import backend modules
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from backend.integrations.import_zepp import main as import_main, USER_ID as DEFAULT_USER_ID
from backend.integrations import import_zepp
def run_import(user_id: int = None):
"""Run the Zepp data import."""
if user_id:
# Override the default user ID
import_zepp.USER_ID = user_id
print(f"Importing data for user ID: {user_id}")
else:
print(f"Importing data for default user ID: {DEFAULT_USER_ID}")
import_main()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Import Zepp health data into HabitForge")
parser.add_argument(
"--user-id",
type=int,
help="User ID to import data for (default: 1)",
default=None
)
args = parser.parse_args()
run_import(args.user_id)
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 488 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="64" viewBox="0 0 96 64">
<rect width="96" height="64" fill="#2a7de1" />
<circle cx="48" cy="32" r="20" fill="#ffc828" />
</svg>

After

Width:  |  Height:  |  Size: 191 B

Binary file not shown.
@@ -0,0 +1,156 @@
# Saison 2026-2027 - Canadiens de Montréal (NHL)
Voici le calendrier complet des **84 matchs** de la saison régulière et des **matchs de pré-saison** des Canadiens de Montréal pour la saison 2026-2027.
---
## 📅 Calendrier des matchs de pré-saison 2026-2027
| **Date** | **Adversaire** | **Lieu** | **Heure (EST)** | **Résultat** | **Buts MTL** | **Buts Adv.** | **Gardien MTL** | **Notes** |
|----------------|-------------------------|------------------------|-----------------|--------------|--------------|---------------|-----------------|--------------------|
| 24 sept. 2026 | Sénateurs d'Ottawa | Centre Bell | 19:00 | | | | | |
| 26 sept. 2026 | Maple Leafs de Toronto | Scotiabank Arena | 19:00 | | | | | |
| 28 sept. 2026 | Bruins de Boston | Centre Bell | 19:00 | | | | | |
| 30 sept. 2026 | Sabres de Buffalo | KeyBank Center | 19:00 | | | | | |
| 2 oct. 2026 | Red Wings de Détroit | Centre Bell | 19:00 | | | | | |
| 4 oct. 2026 | Lightning de Tampa Bay | Amalie Arena | 19:00 | | | | | |
---
## 📅 Calendrier des matchs de saison régulière
| **Date** | **Adversaire** | **Lieu** | **Heure (EST)** | **Résultat** | **Buts MTL** | **Buts Adv.** | **Gardien MTL** | **Notes** |
|----------------|-------------------------|----------------|-----------------|--------------|--------------|---------------|-----------------|--------------------|
| 12 oct. 2026 | Maple Leafs de Toronto | Centre Bell | 19:00 | | | | | Ouverture |
| 14 oct. 2026 | Sénateurs d'Ottawa | Centre Bell | 19:00 | | | | | |
| 16 oct. 2026 | Bruins de Boston | TD Garden | 19:00 | | | | | |
| 18 oct. 2026 | Sabres de Buffalo | KeyBank Center | 19:00 | | | | | |
| 21 oct. 2026 | Red Wings de Détroit | Little Caesars | 19:30 | | | | | |
| 23 oct. 2026 | Panthers de la Floride | Centre Bell | 19:00 | | | | | |
| 25 oct. 2026 | Lightning de Tampa Bay | Amalie Arena | 19:00 | | | | | |
| 28 oct. 2026 | Capitals de Washington | Capital One | 19:00 | | | | | |
| 30 oct. 2026 | Hurricanes de la Caroline | PNC Arena | 19:00 | | | | | |
| 1 nov. 2026 | Devils du New Jersey | Prudential | 19:00 | | | | | |
| 3 nov. 2026 | Islanders de New York | UBS Arena | 19:00 | | | | | |
| 5 nov. 2026 | Rangers de New York | Madison Square | 19:00 | | | | | |
| 7 nov. 2026 | Flyers de Philadelphie | Wells Fargo | 19:00 | | | | | |
| 9 nov. 2026 | Penguins de Pittsburgh | PPG Paints | 19:00 | | | | | |
| 11 nov. 2026 | Blue Jackets de Columbus | Nationwide | 19:00 | | | | | |
| 13 nov. 2026 | Predators de Nashville | Bridgestone | 20:00 | | | | | |
| 15 nov. 2026 | Stars de Dallas | American Airlines | 20:30 | | | | | |
| 17 nov. 2026 | Wild du Minnesota | Xcel Energy | 20:00 | | | | | |
| 19 nov. 2026 | Jets de Winnipeg | Canada Life | 20:00 | | | | | |
| 21 nov. 2026 | Avalanche du Colorado | Ball Arena | 21:00 | | | | | |
| 23 nov. 2026 | Coyotes de l'Arizona | Mullett Arena | 22:00 | | | | | |
| 25 nov. 2026 | Golden Knights de Vegas | T-Mobile Arena | 22:00 | | | | | |
| 27 nov. 2026 | Ducks d'Anaheim | Honda Center | 22:00 | | | | | |
| 29 nov. 2026 | Kings de Los Angeles | Crypto.com | 22:30 | | | | | |
| 1 déc. 2026 | Sharks de San José | SAP Center | 22:30 | | | | | |
| 3 déc. 2026 | Canucks de Vancouver | Rogers Arena | 22:00 | | | | | |
| 5 déc. 2026 | Oilers d'Edmonton | Rogers Place | 21:00 | | | | | |
| 7 déc. 2026 | Flames de Calgary | Scotiabank Saddledome | 21:00 | | | | | |
| 10 déc. 2026 | Bruins de Boston | Centre Bell | 19:00 | | | | | |
| 12 déc. 2026 | Sabres de Buffalo | Centre Bell | 19:00 | | | | | |
| 14 déc. 2026 | Red Wings de Détroit | Centre Bell | 19:00 | | | | | |
| 16 déc. 2026 | Panthers de la Floride | FLA Live Arena | 19:00 | | | | | |
| 18 déc. 2026 | Lightning de Tampa Bay | Centre Bell | 19:00 | | | | | |
| 20 déc. 2026 | Capitals de Washington | Centre Bell | 19:00 | | | | | |
| 22 déc. 2026 | Hurricanes de la Caroline | Centre Bell | 19:00 | | | | | |
| 27 déc. 2026 | Devils du New Jersey | Centre Bell | 19:00 | | | | | |
| 29 déc. 2026 | Islanders de New York | Centre Bell | 19:00 | | | | | |
| 31 déc. 2026 | Rangers de New York | Centre Bell | 19:00 | | | | | |
| 2 janv. 2027 | Flyers de Philadelphie | Centre Bell | 19:00 | | | | | |
| 4 janv. 2027 | Penguins de Pittsburgh | Centre Bell | 19:00 | | | | | |
| 6 janv. 2027 | Blue Jackets de Columbus | Centre Bell | 19:00 | | | | | |
| 8 janv. 2027 | Predators de Nashville | Centre Bell | 19:00 | | | | | |
| 10 janv. 2027 | Stars de Dallas | Centre Bell | 19:00 | | | | | |
| 12 janv. 2027 | Wild du Minnesota | Centre Bell | 19:00 | | | | | |
| 14 janv. 2027 | Jets de Winnipeg | Centre Bell | 19:00 | | | | | |
| 16 janv. 2027 | Avalanche du Colorado | Centre Bell | 19:00 | | | | | |
| 18 janv. 2027 | Coyotes de l'Arizona | Centre Bell | 19:00 | | | | | |
| 20 janv. 2027 | Golden Knights de Vegas | Centre Bell | 19:00 | | | | | |
| 22 janv. 2027 | Ducks d'Anaheim | Centre Bell | 19:00 | | | | | |
| 24 janv. 2027 | Kings de Los Angeles | Centre Bell | 19:00 | | | | | |
| 26 janv. 2027 | Sharks de San José | Centre Bell | 19:00 | | | | | |
| 28 janv. 2027 | Canucks de Vancouver | Centre Bell | 19:00 | | | | | |
| 30 janv. 2027 | Oilers d'Edmonton | Centre Bell | 19:00 | | | | | |
| 1 fév. 2027 | Flames de Calgary | Centre Bell | 19:00 | | | | | |
| 3 fév. 2027 | Maple Leafs de Toronto | Scotiabank Arena | 19:00 | | | | | |
| 5 fév. 2027 | Sénateurs d'Ottawa | Canadian Tire | 19:00 | | | | | |
| 7 fév. 2027 | Bruins de Boston | Centre Bell | 19:00 | | | | | |
| 9 fév. 2027 | Sabres de Buffalo | Centre Bell | 19:00 | | | | | |
| 11 fév. 2027 | Red Wings de Détroit | Centre Bell | 19:00 | | | | | |
| 13 fév. 2027 | Panthers de la Floride | Centre Bell | 19:00 | | | | | |
| 15 fév. 2027 | Lightning de Tampa Bay | Amalie Arena | 19:00 | | | | | |
| 17 fév. 2027 | Capitals de Washington | Centre Bell | 19:00 | | | | | |
| 19 fév. 2027 | Hurricanes de la Caroline | Centre Bell | 19:00 | | | | | |
| 21 fév. 2027 | Devils du New Jersey | Prudential | 19:00 | | | | | |
| 23 fév. 2027 | Islanders de New York | UBS Arena | 19:00 | | | | | |
| 25 fév. 2027 | Rangers de New York | Madison Square | 19:00 | | | | | |
| 27 fév. 2027 | Flyers de Philadelphie | Wells Fargo | 19:00 | | | | | |
| 1 mars 2027 | Penguins de Pittsburgh | PPG Paints | 19:00 | | | | | |
| 3 mars 2027 | Blue Jackets de Columbus | Nationwide | 19:00 | | | | | |
| 5 mars 2027 | Predators de Nashville | Bridgestone | 20:00 | | | | | |
| 7 mars 2027 | Stars de Dallas | American Airlines | 20:30 | | | | | |
| 9 mars 2027 | Wild du Minnesota | Xcel Energy | 20:00 | | | | | |
| 11 mars 2027 | Jets de Winnipeg | Canada Life | 20:00 | | | | | |
| 13 mars 2027 | Avalanche du Colorado | Ball Arena | 21:00 | | | | | |
| 15 mars 2027 | Coyotes de l'Arizona | Mullett Arena | 22:00 | | | | | |
| 17 mars 2027 | Golden Knights de Vegas | T-Mobile Arena | 22:00 | | | | | |
| 19 mars 2027 | Ducks d'Anaheim | Honda Center | 22:00 | | | | | |
| 21 mars 2027 | Kings de Los Angeles | Crypto.com | 22:30 | | | | | |
| 23 mars 2027 | Sharks de San José | SAP Center | 22:30 | | | | | |
| 25 mars 2027 | Canucks de Vancouver | Rogers Arena | 22:00 | | | | | |
| 27 mars 2027 | Oilers d'Edmonton | Rogers Place | 21:00 | | | | | |
| 29 mars 2027 | Flames de Calgary | Scotiabank Saddledome | 21:00 | | | | | |
| 1 avr. 2027 | Maple Leafs de Toronto | Centre Bell | 19:00 | | | | | |
| 3 avr. 2027 | Sénateurs d'Ottawa | Centre Bell | 19:00 | | | | | |
| 5 avr. 2027 | Bruins de Boston | TD Garden | 19:00 | | | | | |
| 7 avr. 2027 | Sabres de Buffalo | KeyBank Center | 19:00 | | | | | |
---
## 📊 Statistiques de la saison
### Classement de l'équipe
- **Victoires** :
- **Défaites** :
- **Défaites en prolongation** :
- **Défaites en fusillade** :
- **Points** :
- **Buts pour** :
- **Buts contre** :
- **Différentiel** :
### Meilleurs buteurs
| **Joueur** | **Buts** | **Passes** | **Points** | **±** | **Tirs** | **Temps de jeu** |
|---------------------|----------|------------|------------|-------|----------|------------------|
| | | | | | | |
| | | | | | | |
| | | | | | | |
### Meilleurs gardiens
| **Joueur** | **Victoires** | **Défaites** | **Moyenne de buts alloués** | **% Arrêts** | **Blanchissages** |
|---------------------|---------------|--------------|--------------------------------|--------------|-------------------|
| | | | | | |
| | | | | | |
---
## 🏆 Matchs importants
- **Match d'ouverture** : 12 octobre 2026 contre les Maple Leafs de Toronto.
- **Classique hivernale** : À confirmer.
- **Match des étoiles** : À confirmer.
- **Date limite des transactions** : À confirmer.
---
## 📝 Notes supplémentaires
- **Blessures** :
- **Transactions** :
- **Performances remarquables** :
---
*Dernière mise à jour : [Date]*
*Source : [NHL.com](https://www.nhl.com)*
@@ -0,0 +1,137 @@
%PDF-1.4
%“Œ‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R /F2 3 0 R /F3 4 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
>>
endobj
4 0 obj
<<
/BaseFont /ZapfDingbats /Name /F3 /Subtype /Type1 /Type /Font
>>
endobj
5 0 obj
<<
/Contents 12 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 11 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
6 0 obj
<<
/Contents 13 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 11 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
7 0 obj
<<
/Contents 14 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 11 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
8 0 obj
<<
/Contents 15 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 11 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
9 0 obj
<<
/PageMode /UseNone /Pages 11 0 R /Type /Catalog
>>
endobj
10 0 obj
<<
/Author (\(anonymous\)) /CreationDate (D:20260917170226+00'00') /Creator (\(unspecified\)) /Keywords () /ModDate (D:20260917170226+00'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (\(unspecified\)) /Title (Calendrier 2026-2027 - Canadiens de Montr\351al \(NHL\)) /Trapped /False
>>
endobj
11 0 obj
<<
/Count 4 /Kids [ 5 0 R 6 0 R 7 0 R 8 0 R ] /Type /Pages
>>
endobj
12 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 1120
>>
stream
Gb!Sk966RV&AI=/m&c:\E0(X7hVpYdR6!p/0^Zgq`E!UT%'C.Y1ZKS7'n5.EfZ)/^Ad4>t'&Tk+Dc\8nj$h,f?j+i9i8g%$Tb'?g@3#PL%kaTO?UnWbdLX,@@4)>t!,%t@/e.C9#j7AiEn#_TKPOF-JR474]b5HK[MK'[O+u"Bj,$<^1):M$9g&l&5$2dD;a-./R_qt;Fd=N1G?i"K@u,S!e-=p]N]gaEhn$A`ooJ8oMhGu'Yk]XXq,b5/kj9\m23[46%396Lb<#VsJ3DLA!iF]Q'/g#Q]5!\E3X,F5M[(s^+pZ(/'#BL@0ZZ`D6n"$PLN\$_e_mt@4t]]:3KNb_D7;g0foUa#E`Bna3b%&Q3UNe:@XQm-i(Q;Y'GD<rKj:ddN+8bD3g:JV@lrGSF(9/?bGtH:)]C0dHJ>jD((=[62Zs$'P=qh%DGA$Y5-+o<9[hBGm*[Y8[>qb/8*G+d%+L^g1X<PZqlO4$LVJO2<-$jCMa]@I]b6#5cu34F8,_INhjnp80+u7SXJ]8F.BfN'C(j\9kk9UEmIhn[26U%MhIK7>X.qQWJK"4#_T)G@=DPZQ*SW0L%?l4/ehT4m$e7_%KgpJF^T"po5T/WlX?%Y'ENeg'VPctR66_g^ga^;CE9oe&QlcHQ7?V&:KHG%MT8T`c\S!0HF%LH6?5<8na.s#)_&l;b7[_2ZQ>)ZiR>UeB:Og6\'IhoY5P'm0G7^YaIo+,APsmg[`SE(HQoPWaHB";.^[email protected]^SS/Nq[2Vdac1bkV5*c$[edQXI5SdLLYlag5lc0Yj]LA^;oJ:M>UUW?HFa!LP=LiN!a^?jpGZ7jLt?Q=euD;j>\6@3HY'))GWdbM+'4T46H+oYbhc8l>*lh(ff\a5gVHih6WihG$q?AK8)i[W41TDpJJN$B+uq?[T!3sQYoETntMq*[email protected]/C+2lNH66rJbt69p#a/qGH\9cP$&jS"m%@-!E3B=j6h-2^6*!SQHQtG,M6Q+W&9D2)eGm4&'5"=qKH>)!,s.F\?E=hji/ESa,CNTBTsM?A`$eVp+)k8'.R&7=WHo>#rbq`ja^g@6#P!1FL4!nAE^*ftp."JaamfInrW*hRG]3~>endstream
endobj
13 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 1374
>>
stream
GatUt?$#!`'Sc)P'tR&mRAQ;Jh)c`$D3e_cKJr3kDhP50'd4m/SK2nEj*P<MW+"4Z9>aGj5m`!fEh9%-`[H?RmX>ojKI.*!dhP?>TZ%S]d<UB\1N^/E]o;I[2q&23EIOKjGm8aQqK0(YiV018;:$oYC'7n%hld1?^"H[;kcR7r284E),X\SFc4L@RK&4k=54aMd)O1^odX&lDeL5]F5T_:>A'H9QcZ&l)&A\2?l[-#6)_HLmm%7#q_plhiF(bJ+kje]$C<[,9=a(+&!k23^"8!P$hb>-=EGS!<o$eNt,H5#,aY29s2g'&d*W(e5R',,n5jPjhZJeXV.D.H"'L'W+.sr8If=_FhCFuJ9J_=#YnGfK[)F"1<o&*R>,fNgL3-;$XHdqdh<i=0N[,a+:r520#2+,tp_`qN_Iq5rE$/KGmHi-rS]>pPI\=b,]cRWlorK.D"V(8Prjk;T1C24HlgR@m3k=eo.Qb,?;9iE]L?*2>fr#3g/QVHl"4b6Vc3:d]iDsTm!%,K9>c'n&9VFn4bAR!(#*Gr<LT6]Z\/E=r(D4J+/Mu2)N2(NC9p'/=>LC#5"s%G7&.osRK5OakE#_-=62ic\d`I34X)S0FnTL)IRp[Nu\iua8k2H.@SZp4&8hp*<Ioo4g?^:<Y#,8[0oppXK0WbP4qs!X7"Q]gTJgLD=%HYc\@b2(UeI<TW':&bLcr0^Pj7$+dOBZ?[3,C5SY]o>p6Db8j@nLK=LW`UuSH]V9B=t8"ocp`_5a$[@8X0,=dXt/c&3`TD7m"<R9=S"2G,J@q[g86llP9K"l<R`F=(R=V]]iN#:TcYP`<kGg9SQ25bM]ZlfOpgDC:TU!SfHV((28*[]2*ddn-!`7>0e$$mB_4ZQ%q6$MHA7j"StrRQ#70a'Tk=`+:l%,`R;u*rp:4&`L"cI6i86^7_osTDR.qrcnujae`F6'UW*X]G%ku4G<,IrGkMpikliY<BX.j%`'8)@e@0l;T"aV/CN+u]]epGpn9rBTS,HIR_n]AX<[email protected]_*gpQ5_,oa1a_2>gS'3SVeT!g)1)Y)>K$b9$kh#/5E1CW&D\nLI/hFBh@D)3iFS5/(J8$%?TAF.S2dHdbsm1-MlU:4AkeN]FA-VViM-0q4Zc0UfL&Ylldf<Z'6m6Y4.YKl%oc/aW4S#-)!imNK1R<=_Vp"DEqNq[72\'Gg_@J9*t<J]ZDo,SB>HO5PGHkh641GB7L5n0nc`3a!1fqXL@-D,P#Her%euf,a@3A^k-Hq.3u+!?h&,J2&.J[S*Gj0p?,p,n;5[s*-n@:'4:e.iKt.*AG$]OO7[cSkUhk:I*d^M=r_e*hu">Ip41A>I<UuMPHV3'polS7d@>lpY<O?Q7ZKt<!9PAbec~>endstream
endobj
14 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 1246
>>
stream
GatUt>uTcA'Sc)J.s+;9$Yi94ls15>=r,cW-8!]7hAg"DejbsWCr=WQ+(*^Hd`&BC7[hQ:3.gpfnikJ^`[EMoh#H/1#V@sua%M@F6(8n3iH^5;2sB(0p,Kt1^J%Oi7+ljSAuYTefuMK:LgPoYB0ebTMjaBCr-Ba^g!t&.TYCm!md]*LoDWBa:ZmN:,XGeaV0HF[7QEi:Opf@!30]r$JL-M>An]#60NU72.1"/df@Tb1o,2Cokbp^@n7Z8Wa-e`/pm-<HAC5EXYk+`k+'Ms7T&_l:OiLVa9HLqp?\k#ACY8&Xe'ft8BWHosp1'.>C1U0bBD-GSlC-h]W$*p?:mXs_#g^0%$+?!ee=#)s^-Q*b0OS7<&E(1SU".GU]%`'3HJW_*UV'%)>Y8%t#!AlAe]^!l2\V8%]KQPshGEeG.m0L-X-?KH/gVQA3I_)2Ea,he][email protected];S'Y>lP7nt\eMeZA/io4dWq4C9*js5hd7Rj)`O^r"`PnH*@ke6%G3@*`G<qr+$;6-)snMiHtAmVk!]g4iO9.1[]4INJ)b:n#3P)R&$cXkKWo8Tct>S^!ecc$AMX.*PWmNrg^\Lp2:Hh'$bFKOgmBS8Oj'<@U2jR+?4]*WK`MTN<[>u^^>ZmU*/FYfi]DUOZ:+1UMB_m=Q4V.??s-T//4).JZu'(*7YHs=o`2/It>&-_86:[GkH-;E=8Ugraq31)2\L;C$*h^I<_H'eH2C,e>+gnVDlrP!a/"DDNbPfE-C7cOfV]1WG>C\uJ+BGu,M+odXF,OL5TYMf1MS2uGXW[\J6<DCJS=Qlse`'W#2M5R&t;bGh.bpFqO%sgeEU>>3%Gh+D[>=GB>LStkb5I%jO&;LAPU)RmTif,$CafN4>`1t,=#eL/kPfM'PJD#+1k.,+H6kZQ$,k<@*-aMTNop.FMhsWF!*<7[agF;;##h/`6m5-)o>"Y_`Yrg?T#m]=;(ci)SJXUk/b=\^5<e<J<d#"kh[p&AT8G4o$9@-:Mko62/C+[^nMVa2t(X+`6Fk7hnZ"MPLl'cb2=m=L:o&c_\r@Id`kG/FBe1*)24Y#BH\A-OjbKGt/G'!Fal+MBBf>ZGqpGfTbMaNO<G[g%f0GXJ<qplaj[>Fq[Yltf4/'qQpFm9r5X1OaD'Z1T.XcFFi:$?A7$+`s9#pNE(ET!NEWk-5?s7O`Y[CS,+!gfdDF\:'.jX'F]d&6[-U!jCoDs@;`_;cOm>fl0s%/[g;B_E6qV26r~>endstream
endobj
15 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 914
>>
stream
GatUr?#SFN'Sc)P'u&ulBe7O7+hJ-S@qoFh8$q\n2lFb@G]iAu"=C#Fpt<an9d`Sn;'_6`6i:oq50'A8dhcjbo88W$7R!>@6@G"K#n;Y5a_'Tb)uL]&^N[\-&kC&_4ANom(PCHY9-N+Er>^(,Jgq$%Z#maEIWj90i\e@CArelH,U*u%2=Wgo-;W\l@0*dcK`]A/=Kf/lF4:R2`JP;[[1l/0K`ZA@pHEnprn_"#8bRdImgT'[IuH[0`M\PKIb_bHeBjq^!p?f=Q*`lsEY'L-MDKg!1.>'[email protected])(5>#Btr1nspa*9n-%@K#G8S)b-r%1E6c31.ff0On7k=8*O7?8[+F@nX]QWQ2;^XMQ9&PHDuJq*pDN%NEl4f29P-u_Ze3p>fD3/Ds9VY=$2V1M%&bj,f\_G9uILK7JHJ\.ti/*g1&A;s=8q+7U=DqU5t2d4nG5*5YiaF1+d,L9Xog@b))ncB!*'!,?GZ2'8gj(n@;0(0ZJ7s`KrBf("BP]eoIh;f(bqBQf[6<<?n-Rj/a%iOiR*0%(H7O*+?rN;_n9U&8HB6$^E;'JNZm]"o'eoI/$l?U9S58L#V<R<.9(Y%m\\laN0B]p7YP$cB)pE63-T&+RXhLdno$6&a.K).,'"joe.k?AH6\_/m:?Y##i-DuMeeEU\6\GPN7rOg\cRY17nXJhrAL]2l$L-puLk@'`[]aSCp0E&&?k8^LF*);'OTQVY+\Z?\(K6Ybr.12)hXSUtt<^jpiL_H#g<Xo)Vcf%`^]c"\mq$WTiVXl-'3oLFf"SHJ>Al0Z>aJrki\Eb#S^_b![!B"b`aB[=Sr.60(IB/q_4m$&E3VPpYQtUe/Om=pcfdXH3AWEY%^n+QL@!p2QD5Yd#YM+A"2TmCc'94Tu9h`(kA$EduJP$,r!*eRhbQ~>endstream
endobj
xref
0 16
0000000000 65535 f
0000000061 00000 n
0000000112 00000 n
0000000219 00000 n
0000000331 00000 n
0000000414 00000 n
0000000619 00000 n
0000000824 00000 n
0000001029 00000 n
0000001234 00000 n
0000001303 00000 n
0000001626 00000 n
0000001704 00000 n
0000002916 00000 n
0000004382 00000 n
0000005720 00000 n
trailer
<<
/ID
[<aba93085604206a813b8865dbf736fe6><aba93085604206a813b8865dbf736fe6>]
% ReportLab generated PDF document -- digest (opensource)
/Info 10 0 R
/Root 9 0 R
/Size 16
>>
startxref
6725
%%EOF
+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
# Production startup script for HabitForge
set -e
echo "Starting HabitForge in production mode..."
# Wait for database to be ready
echo "Waiting for database..."
while ! pg_isready -h ${POSTGRES_HOST:-db} -U ${POSTGRES_USER:-habitforge} -d ${POSTGRES_DB:-habitforge} > /dev/null 2>&1; do
echo "Database is unavailable - sleeping"
sleep 1
done
echo "Database is ready!"
# Run migrations
echo "Running database migrations..."
alembic upgrade head
# Start Gunicorn
echo "Starting Gunicorn..."
exec gunicorn backend.main:app \
--workers ${GUNICORN_WORKERS:-4} \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--access-logfile - \
--error-logfile - \
--log-level ${LOG_LEVEL:-info}
+22
View File
@@ -94,6 +94,28 @@ def test_vault_dir(tmp_path: Path) -> str:
# Non-markdown file
(vault / "config.json").write_text('{"key": "value"}', encoding="utf-8")
# Image attachments (roadmap #108) — indexed as metadata-only binaries and
# listed in the tree / browse endpoint.
import base64
(vault / "chatScreenshot.png").write_bytes(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAen63NgAAAAASUVORK5CYII="
))
(vault / "vector-icon.svg").write_text(
'<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"></svg>',
encoding="utf-8",
)
# Audio/video media (roadmap #109) — indexed as metadata-only binaries,
# streamed via /api/media. Prefer the committed E2E fixture when present.
repo_media = Path(__file__).resolve().parent.parent / "test_vault" / "sample-audio.mp3"
if repo_media.exists():
(vault / "sample-audio.mp3").write_bytes(repo_media.read_bytes())
else:
(vault / "sample-audio.mp3").write_bytes(
b"ID3\x03\x00\x00\x00\x00\x00\x00" + bytes(range(256)) * 16
)
# File with accents in title
(vault / "café_crème.md").write_text(
"---\ntitle: Café Crème\n---\n# Café Crème\nUn bon café.\n",
+94
View File
@@ -0,0 +1,94 @@
/**
* E2E tests for the Configurations modal on mobile (BUG-071).
*
* Runs only under the `chromium-mobile` Playwright project (viewport ≤ 768px);
* skipped on the desktop project that the CI job executes — same convention
* as mobile-editor.spec.js.
*
* Covered:
* - the TOC hamburger (#config-hamburger) is visible and reveals #config-nav,
* which is hidden by default on mobile;
* - picking a TOC entry scrolls to the section, marks the link active and
* collapses the nav;
* - the modal content does not overflow horizontally at 393px.
*
* Run:
* npx playwright test tests/e2e/config-mobile.spec.js --project=chromium-mobile
* (ObsiGate listening on http://localhost:2029, auth disabled)
*/
import { test, expect } from '@playwright/test';
const MOBILE_MAX_WIDTH = 768;
async function boot(page) {
await page.goto('/');
await page.waitForSelector('#app:not(.hidden)', { timeout: 15000 });
await expect(page.locator('#header-menu-btn')).toBeVisible({ timeout: 15000 });
}
async function openConfigModal(page) {
await page.locator('#header-menu-btn').click();
await page.locator('#config-open-btn').click();
await expect(page.locator('#config-modal.active')).toBeVisible();
}
test.describe('Configurations modal on mobile (BUG-071)', () => {
test('hamburger reveals the table of contents', async ({ page, viewport }) => {
test.skip((viewport?.width ?? 0) > MOBILE_MAX_WIDTH, 'Mobile viewport required');
await boot(page);
await openConfigModal(page);
// TOC hidden by default on mobile, hamburger visible.
await expect(page.locator('#config-hamburger')).toBeVisible();
await expect(page.locator('#config-nav')).toBeHidden();
await page.locator('#config-hamburger').click();
await expect(page.locator('#config-nav')).toBeVisible();
});
test('picking a section scrolls to it and collapses the nav', async ({ page, viewport }) => {
test.skip((viewport?.width ?? 0) > MOBILE_MAX_WIDTH, 'Mobile viewport required');
await boot(page);
await openConfigModal(page);
await page.locator('#config-hamburger').click();
const link = page.locator('#config-nav a[href="#cfg-tokens"]');
await expect(link).toBeVisible();
await link.click();
// Nav collapses on mobile after selection…
await expect(page.locator('#config-nav')).toBeHidden();
// …the link is marked active…
await expect(link).toHaveClass(/active/);
// …and the section scrolls into view inside the modal (smooth scroll:
// poll for the settled position instead of racing the animation).
await expect
.poll(
async () => {
const box = await page.locator('#cfg-tokens').boundingBox();
const modalBox = await page.locator('#config-modal').boundingBox();
if (!box || !modalBox) return Number.POSITIVE_INFINITY;
return box.y - (modalBox.y + modalBox.height);
},
{ timeout: 8000 },
)
.toBeLessThanOrEqual(0);
});
test('no horizontal overflow at 393px', async ({ page, viewport }) => {
test.skip((viewport?.width ?? 0) > MOBILE_MAX_WIDTH, 'Mobile viewport required');
await boot(page);
await openConfigModal(page);
for (const section of ['#cfg-ai', '#cfg-tokens', '#cfg-webhooks', '#cfg-partages-publics']) {
await page.locator('#config-hamburger').click();
await page.locator(`#config-nav a[href="${section}"]`).click();
}
const overflow = await page.evaluate(() => {
const scroller = document.getElementById('config-scroll');
return scroller.scrollWidth - scroller.clientWidth;
});
expect(overflow).toBeLessThanOrEqual(1);
});
});
+126
View File
@@ -0,0 +1,126 @@
/**
* E2E tests for the ObsiGate image viewer (roadmap #108).
*
* Fixtures : `test_vault/sample-image.png` (96x64) + `test_vault/sample-vector.svg`.
*
* Run (local):
* BASE_URL=http://localhost:2029 npx playwright test tests/e2e/image-viewer.spec.js
* BASE_URL=http://localhost:2029 npx playwright test tests/e2e/image-viewer.spec.js --headed
*/
import { test, expect } from '@playwright/test';
const BASE = process.env.BASE_URL || 'http://localhost:2029';
const CREDS = {
username: process.env.OBSIGATE_USER || 'admin',
password: process.env.OBSIGATE_PASS || 'test123',
};
async function login(page) {
await page.goto(BASE);
const loginForm = page.locator('#login-screen');
await expect(loginForm).toBeVisible({ timeout: 5000 }).catch(() => {});
if (await loginForm.isVisible()) {
await page.fill('#login-username', CREDS.username);
await page.fill('#login-password', CREDS.password);
await page.click('#login-btn');
}
await page.waitForFunction(() => window.__OBSIGATE_BOOTED === true, { timeout: 20000 });
}
async function openFile(page, vault, filePath) {
const treeItem = page.locator(`.tree-item[data-vault="${vault}"][data-path="${filePath}"]`);
if (!(await treeItem.count())) {
await page.locator(`.tree-item.vault-item[data-vault="${vault}"]`).first().click();
await treeItem.waitFor({ state: 'attached', timeout: 8000 });
}
await treeItem.dblclick({ timeout: 5000 });
}
test.describe('Image viewer — zoom / pan / navigation (#108)', () => {
test('affiche l\'image dans la visionneuse dédiée (URL /api/image)', async ({ page }) => {
// #108-B1 — l'image isolée doit pointer vers /api/image (octets), pas /raw (JSON).
const imageResponsePromise = page.waitForResponse(
(r) => r.url().includes('/api/image/') && r.status() === 200,
{ timeout: 15000 },
);
await login(page);
await openFile(page, 'TestVault', 'sample-image.png');
const main = page.locator('#content-area .image-viewer-container img.image-main');
await expect(main).toBeVisible({ timeout: 10000 });
await expect(main).toHaveAttribute('src', /\/api\/image\/TestVault\?path=/);
const resp = await imageResponsePromise;
expect(resp.headers()['content-type']).toContain('image/png');
// Le badge de zoom démarre à 100 %.
await expect(page.locator('#content-area .image-zoom-badge')).toHaveText('100%');
});
test('le zoom molette et le reset modifient la transform', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-image.png');
await expect(page.locator('#content-area .image-stage')).toBeVisible({ timeout: 10000 });
const badge = page.locator('#content-area .image-zoom-badge');
await expect(badge).toHaveText('100%');
await page.locator('#content-area .image-stage').hover();
await page.mouse.wheel(0, -240);
await expect(badge).not.toHaveText('100%', { timeout: 5000 });
const transform = await page.locator('#content-area img.image-main').evaluate(
(el) => getComputedStyle(el).transform,
);
expect(transform).not.toBe('none');
// Double-clic = réinitialisation.
await page.locator('#content-area .image-stage').dblclick();
await expect(badge).toHaveText('100%');
});
test('navigue entre les images du dossier via la pellicule', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-image.png');
const strip = page.locator('#content-area .image-nav-strip');
await expect(strip).toBeVisible({ timeout: 10000 });
// sample-image.png et sample-vector.svg partagent le dossier racine.
await expect(strip.locator('img.image-thumb')).toHaveCount(2);
await page.locator('#content-area .image-nav-strip img.image-thumb').first().click();
await expect(page.locator('#content-area .image-title')).toBeVisible();
});
test('conserve le plein écran et le panneau métadonnées à la navigation (#BUG-072)', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-image.png');
const container = page.locator('#content-area .image-viewer-container');
const metaPanel = page.locator('#content-area .image-meta-panel');
const title = page.locator('#content-area .image-title');
await expect(container).toBeVisible({ timeout: 10000 });
// Métadonnées : barre latérale à droite de l'image (pas sous la pellicule).
await page.locator('#content-area .image-btn-metadata').click();
await expect(metaPanel).toBeVisible();
const stageBox = await page.locator('#content-area .image-stage').boundingBox();
const metaBox = await metaPanel.boundingBox();
expect(metaBox.x).toBeGreaterThanOrEqual(stageBox.x + stageBox.width - 1);
// Plein écran activé.
await page.locator('#content-area .image-btn-lightbox').click();
await expect(container).toHaveClass(/lightbox/);
// Naviguer (flèche droite) : les deux états doivent survivre au re-render.
const titleBefore = await title.innerText();
await page.keyboard.press('ArrowRight');
await expect(container).toHaveClass(/lightbox/);
await expect(metaPanel).toBeVisible();
await expect(title).not.toHaveText(titleBefore);
});
});
+163
View File
@@ -0,0 +1,163 @@
/**
* E2E tests for the ObsiGate media viewers & persistent player (roadmap #109/#110).
*
* Fixtures : `test_vault/sample-audio.mp3` (1 s sine) + `test_vault/sample-video.webm`.
*
* Run (local):
* BASE_URL=http://localhost:2029 npx playwright test tests/e2e/media-viewer.spec.js
*/
import { test, expect } from '@playwright/test';
const BASE = process.env.BASE_URL || 'http://localhost:2029';
const CREDS = {
username: process.env.OBSIGATE_USER || 'admin',
password: process.env.OBSIGATE_PASS || 'test123',
};
async function login(page) {
await page.goto(BASE);
const loginForm = page.locator('#login-screen');
await expect(loginForm).toBeVisible({ timeout: 5000 }).catch(() => {});
if (await loginForm.isVisible()) {
await page.fill('#login-username', CREDS.username);
await page.fill('#login-password', CREDS.password);
await page.click('#login-btn');
}
await page.waitForFunction(() => window.__OBSIGATE_BOOTED === true, { timeout: 20000 });
}
async function openFile(page, vault, filePath) {
const treeItem = page.locator(`.tree-item[data-vault="${vault}"][data-path="${filePath}"]`);
if (!(await treeItem.count())) {
await page.locator(`.tree-item.vault-item[data-vault="${vault}"]`).first().click();
await treeItem.waitFor({ state: 'attached', timeout: 8000 });
}
await treeItem.dblclick({ timeout: 5000 });
}
test.describe('Media viewers — HTML5 audio/video (#109)', () => {
test('rend un lecteur audio natif branché sur /api/media', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-audio.mp3');
const audio = page.locator('#content-area .audio-viewer-container audio.np-media--audio');
await expect(audio).toBeVisible({ timeout: 10000 });
await expect(audio).toHaveAttribute('src', /\/api\/media\/TestVault\?path=/);
await expect(audio).toHaveAttribute('controls', '');
await expect(page.locator('#content-area .media-duration-badge')).not.toHaveText('--:--', { timeout: 10000 });
});
test('rend un lecteur vidéo natif branché sur /api/media', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-video.webm');
const video = page.locator('#content-area .video-viewer-container video.np-media--video');
await expect(video).toBeVisible({ timeout: 10000 });
await expect(video).toHaveAttribute('src', /\/api\/media\/TestVault\?path=/);
await expect(video).toHaveAttribute('playsinline', '');
});
test('le streaming média honore les requêtes Range (206)', async ({ page }) => {
await login(page);
const resp = await page.request.get(
`${BASE}/api/media/TestVault?path=${encodeURIComponent('sample-video.webm')}`,
{ headers: { Range: 'bytes=0-99' } },
);
expect(resp.status()).toBe(206);
expect(resp.headers()['content-range']).toMatch(/^bytes 0-99\/\d+$/);
expect(resp.headers()['accept-ranges']).toBe('bytes');
});
});
test.describe('Now Playing — lecture persistante (#110)', () => {
test('affiche le dock et continue la lecture quand on navigue ailleurs', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-audio.mp3');
await expect(page.locator('#content-area audio.np-media--audio')).toBeVisible({ timeout: 10000 });
// Naviguer vers une note : le média doit passer dans le dock.
await openFile(page, 'TestVault', 'note1.md');
const dock = page.locator('#now-playing-host .np-dock--audio');
await expect(dock).toBeVisible({ timeout: 10000 });
await expect(dock.locator('.np-dock-title')).toHaveText('sample-audio.mp3');
// S'assurer de la lecture (l'autoplay peut être bloqué sans geste).
const media = page.locator('#now-playing-host audio.np-media--audio');
if (await media.evaluate((el) => el.paused)) {
await dock.locator('[data-np="play"]').click();
}
await expect.poll(() => media.evaluate((el) => !el.paused), { timeout: 5000 }).toBe(true);
// Naviguer encore : toujours en lecture.
await openFile(page, 'TestVault', 'Accueil.md');
await expect(dock).toBeVisible();
expect(await media.evaluate((el) => !el.paused)).toBe(true);
});
test('revient sur le média depuis le dock', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-audio.mp3');
await expect(page.locator('#content-area audio.np-media--audio')).toBeVisible({ timeout: 10000 });
await openFile(page, 'TestVault', 'note1.md');
const dock = page.locator('#now-playing-host .np-dock--audio');
await expect(dock).toBeVisible({ timeout: 10000 });
await dock.locator('[data-np="reopen"]').click();
await expect(page.locator('#content-area .audio-viewer-container audio.np-media--audio')).toBeVisible({ timeout: 10000 });
await expect(dock).toBeHidden();
});
test('ferme la lecture depuis le dock', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-audio.mp3');
await expect(page.locator('#content-area audio.np-media--audio')).toBeVisible({ timeout: 10000 });
await openFile(page, 'TestVault', 'note1.md');
const dock = page.locator('#now-playing-host .np-dock--audio');
await expect(dock).toBeVisible({ timeout: 10000 });
await dock.locator('[data-np="close"]').click();
await expect(page.locator('#now-playing-host .np-dock--audio')).toBeHidden();
});
test('le mini-player vidéo flotte et reste visible en naviguant', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-video.webm');
await expect(page.locator('#content-area video.np-media--video')).toBeVisible({ timeout: 10000 });
await openFile(page, 'TestVault', 'note1.md');
const mini = page.locator('#now-playing-host .np-dock--video');
await expect(mini).toBeVisible({ timeout: 10000 });
await expect(mini.locator('video.np-media--video')).toBeVisible();
});
test('la mini-fenêtre vidéo peut être déplacée librement (centre)', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-video.webm');
await expect(page.locator('#content-area video.np-media--video')).toBeVisible({ timeout: 10000 });
await openFile(page, 'TestVault', 'note1.md');
const mini = page.locator('#now-playing-host .np-dock--video');
await expect(mini).toBeVisible({ timeout: 10000 });
const before = await mini.evaluate((el) => ({ left: parseFloat(el.style.left), top: parseFloat(el.style.top) }));
const box = await mini.boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 12);
await page.mouse.down();
await page.mouse.move(640, 360, { steps: 12 });
await page.mouse.up();
const after = await mini.evaluate((el) => ({ left: parseFloat(el.style.left), top: parseFloat(el.style.top) }));
expect(after.left).not.toBe(before.left);
expect(after.top).not.toBe(before.top);
// Doit pouvoir rester au centre (pas de re-aimantation sur les bords).
expect(after.left).toBeGreaterThan(50);
expect(after.left).toBeLessThan(900);
expect(after.top).toBeGreaterThan(20);
expect(after.top).toBeLessThan(600);
});
});
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env node
/**
* ObsiGate — Configurations modal mobile usability non-regression tests (BUG-071).
*
* Static checks (no jsdom needed — runs in the "Frontend unit tests" CI step):
* - BUG-071a: #config-nav shared the .help-nav rule that hides it below
* 768px, but the config modal had no toggle (the help modal has
* #help-hamburger) → the table of contents was unreachable on mobile.
* The header must carry #config-hamburger (same .help-hamburger
* treatment: hidden on desktop, visible on mobile) wired in config.js.
* - BUG-071b: the TOC links were bare anchors with no JS — no active state,
* no auto-collapse on mobile, unreliable scrolling inside the modal.
* config.js must smooth-scroll to the section, mark it active and collapse
* the nav on mobile, and reset the nav on open.
* - BUG-071c: two-column grids (.ai-default-grid, .ai-provider-fields),
* fixed-width add-rows (.config-add-row, 180/140/100px inline widths) and
* single-line webhook/token/share items overflowed a 360px viewport.
* style.css must stack/wrap them below 768px with 44px touch targets.
* - BUG-071d: every #config-nav link target must exist (dead-anchor guard,
* same class of bug as BUG-067 for the help modal).
* - BUG-071e: data-i18n-attr supports several "attr:key" pairs (";"-
* separated) so the toggle carries translated title AND aria-label.
*
* Usage: node tests/frontend/config-mobile.test.mjs
*/
import { strict as assert } from "node:assert";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(__dirname, "..", "..");
const indexHtml = readFileSync(path.join(ROOT, "frontend", "index.html"), "utf8");
const configJs = readFileSync(path.join(ROOT, "frontend", "js", "config.js"), "utf8");
const i18nJs = readFileSync(path.join(ROOT, "frontend", "js", "i18n.js"), "utf8");
const css = readFileSync(path.join(ROOT, "frontend", "style.css"), "utf8");
const fr = JSON.parse(readFileSync(path.join(ROOT, "frontend", "locales", "fr.json"), "utf8"));
const en = JSON.parse(readFileSync(path.join(ROOT, "frontend", "locales", "en.json"), "utf8"));
function test(label, fn) {
try {
fn();
console.log(" ✓ " + label);
} catch (err) {
console.error(" ✗ " + label + "\n " + err.message);
process.exitCode = 1;
}
}
// ── BUG-071a: header TOC toggle ─────────────────────────────────────────────
test("index.html — #config-hamburger exists in the config modal header", () => {
const modal = indexHtml.match(/<div class="editor-modal" id="config-modal">([\s\S]*?)<div class="editor-body help-body" id="config-body">/);
assert.ok(modal, "#config-modal with #config-body not found");
const header = modal[1].match(/<div class="editor-header">([\s\S]*?)<\/div>\s*<\/div>/);
assert.ok(header, "config modal .editor-header not found");
assert.match(header[1], /id="config-hamburger"/, "no #config-hamburger in the config header — TOC unreachable on mobile");
assert.match(header[1], /help-hamburger/, "the toggle must reuse .help-hamburger (desktop-hidden, mobile-visible)");
assert.match(header[1], /aria-label/, "the toggle needs an accessible label");
assert.match(header[1], /config\.toc_toggle/, "the toggle label must use the i18n key config.toc_toggle");
});
test("i18n — config.toc_toggle exists in FR and EN", () => {
assert.ok(fr["config.toc_toggle"], "fr.json missing config.toc_toggle");
assert.ok(en["config.toc_toggle"], "en.json missing config.toc_toggle");
assert.notEqual(fr["config.toc_toggle"], "config.toc_toggle", "FR value must be translated");
assert.notEqual(en["config.toc_toggle"], "config.toc_toggle", "EN value must be translated");
});
// ── BUG-071b: TOC behaviour in config.js ────────────────────────────────────
test("config.js — hamburger toggles #config-nav", () => {
assert.match(configJs, /getElementById\("config-hamburger"\)/, "no binding on #config-hamburger");
assert.match(configJs, /_setConfigNav\(/, "TOC open/close helper missing");
});
test("config.js — TOC links smooth-scroll, mark active, collapse on mobile", () => {
assert.match(configJs, /#config-nav[\s\S]{0,400}?help-nav-link/, "no handler on the #config-nav links");
assert.match(configJs, /scrollIntoView/, "section scroll must use scrollIntoView inside the modal");
assert.match(configJs, /innerWidth <= 768/, "the nav must auto-collapse on mobile viewports only");
});
test("config.js — TOC display reset when the modal opens", () => {
assert.match(configJs, /configNavOnOpen[\s\S]{0,120}?style\.display = ''/, "stale inline display would stick across sessions");
});
// ── BUG-071c: mobile CSS ────────────────────────────────────────────────────
test("style.css — config TOC becomes a capped top block on mobile", () => {
assert.match(css, /#config-modal #config-nav/, "no mobile rule scoped to #config-modal #config-nav");
assert.match(css, /#config-modal #config-nav[\s\S]{0,400}?max-height/, "the opened TOC must be height-capped so content stays reachable");
});
test("style.css — two-column config grids stack on mobile", () => {
assert.match(css, /#config-modal \.ai-default-grid/, ".ai-default-grid still 2 columns on mobile");
assert.match(css, /#config-modal \.ai-provider-fields/, ".ai-provider-fields still 3fr/2fr on mobile");
assert.match(css, /grid-template-columns: 1fr;/, "mobile grids must collapse to a single column");
});
test("style.css — add-rows wrap and fixed inline widths are neutralised", () => {
assert.match(css, /#config-modal \.config-add-row/, "no mobile rule for .config-add-row (token/webhook rows overflow)");
assert.match(css, /width: auto !important/, "fixed inline widths (180/140/100px) must be overridden on mobile");
assert.match(css, /min-height: 44px/, "mobile action controls need 44px touch targets");
});
test("style.css — webhook/token/share rows wrap on mobile", () => {
for (const cls of ["webhook-item", "token-item", "share-item"]) {
assert.match(css, new RegExp("#config-modal \\." + cls), `.${cls} has no mobile wrap rule`);
}
});
// ── BUG-071d: dead-anchor guard ─────────────────────────────────────────────
test("index.html — every #config-nav link resolves to an element id", () => {
const nav = indexHtml.match(/<nav class="help-nav" id="config-nav">([\s\S]*?)<\/nav>/);
assert.ok(nav, "#config-nav not found");
const hrefs = [...nav[1].matchAll(/href="(#[^"]+)"/g)].map((m) => m[1].slice(1));
assert.ok(hrefs.length > 0, "no links in #config-nav");
const missing = hrefs.filter((id) => !indexHtml.includes(`id="${id}"`));
assert.deepEqual(missing, [], `dead TOC anchors (cf. BUG-067): ${missing.join(", ")}`);
});
// ── BUG-071e: multi-pair data-i18n-attr ─────────────────────────────────────
test("i18n.js — data-i18n-attr supports several attr:key pairs", () => {
assert.match(i18nJs, /split\(['"];/, "pairs must be split on ';'");
assert.match(i18nJs, /el\.setAttribute\(attr, t\(key\)\)/, "each pair must set its attribute");
});
if (process.exitCode) {
console.error("\nConfig mobile tests FAILED");
} else {
console.log("\nAll config mobile tests passed.");
}

Some files were not shown because too many files have changed in this diff Show More