Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eecabeb273 | ||
|
|
f7d71bae41 | ||
|
|
0887458b24 | ||
|
|
68aa0463eb | ||
|
|
8aba7100a4 | ||
|
|
17f4787b35 | ||
|
|
b0f9842aa5 | ||
|
|
a674fe2a7b | ||
|
|
b5e84948d0 | ||
|
|
b11a68f7c6 | ||
|
|
2eec886fc6 | ||
|
|
2bb5d53de7 | ||
|
|
5e6ccfa5c1 | ||
|
|
2753d45103 | ||
|
|
7b241164b3 | ||
|
|
4dbd902477 | ||
|
|
60a75b3919 | ||
|
|
51675e842e |
+45
-1
@@ -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.95.4**.
|
||||
> [Unreleased](#unreleased). La dernière version livrée est **2.98.0**.
|
||||
|
||||
---
|
||||
|
||||
@@ -14,6 +14,50 @@ et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
---
|
||||
|
||||
## [2.98.0] — 2026-11-30
|
||||
|
||||
### Ajouté
|
||||
|
||||
- **Audit de chargement versionné (#241, épopée perf #240)** : `scripts/audit_chargement.py` (stdlib seule) mesure TTFB/total médians, en-têtes de cache et graphe de modules ES statiques (mode distant ou `--local`) ; budget de chargement figé dans `docs/features/perf-chargement-240.md` (affichage utile ÷3, JS initial −50 %, `/api/dashboard` répété < 50 ms).
|
||||
- **Bootstrap rapide des liens profonds (#244)** : à l'arrivée sur un lien `#file=` (y compris au retour d'un SSO), le fichier cible s'ouvre dès l'authentification faite, avant le chargement des réglages des vaults, de la liste des vaults et des tags ; le chargement complet suit sans recouvrir la cible. `#folder=` inchangé (il a besoin de l'arborescence chargée).
|
||||
- **Cache mémoire de `/api/dashboard` (#245)** : résultat mis en cache 60 s par utilisateur et invalidé dès que le watcher signale un changement d'index — les appels répétés ne parcourent plus les 10 987 fichiers à chaque fois.
|
||||
- **Chargement paresseux des modules lourds et des CDN (#243)** : Mermaid, vue graphe, Excalidraw, now-playing, plugins, push et l'éditeur mobile sont chargés par `import()` dynamique à la première utilisation (ou en tâche de fond) au lieu du graphe statique initial (41 → 34 modules, −12,5 % en octets bruts — le cœur couplé viewer/ui reste statique, voir fiche #240) ; les 13 scripts CDN du `<head>` (Mermaid 745 Ko, highlight.js + 10 langages, Lucide) sont retirés : highlight arrive au premier bloc de code (base + langage détecté), Lucide au premier appel d'icônes, Mermaid au premier diagramme.
|
||||
- **Cache versionné des statiques (#242)** : les URL `/static/…` de `index.html` et les imports des modules ES sont réécrits au service avec `?v=<VERSION>` (`backend/static_versioning.py`, serveur `VersionedStaticFiles`) ; `Cache-Control: immutable` (1 an) uniquement pour les URL à la version courante, `no-cache` sinon — le cache long ne peut plus servir un build périmé. Le service worker porte un nom de cache à la version courante (ancien cache abandonné à l'activation). La règle Cloudflare « HIT » sur les statiques versionnées reste une action d'exploitation hors code.
|
||||
|
||||
---
|
||||
|
||||
## [2.97.0] — 2026-11-30
|
||||
|
||||
### Ajouté
|
||||
|
||||
- **Lien profond « dossier » `#folder=<vault>:<chemin>` (#239)** : forme sœur de `#file=` (même encodage), reconnue à l'init du frontend — l'arborescence latérale se déplie jusqu'au dossier ciblé, qui est sélectionné et mis en évidence ; cible inconnue ou fragment illisible : repli propre sur l'accueil, aucune erreur bloquante. Sert les citations cliquables de la console Spark (carte jumelle agent-commun 0.112.0, décisions D1a/D2a). `#file=` inchangé. **Redéploiement Docker requis.**
|
||||
|
||||
---
|
||||
|
||||
## [2.96.0] — 2026-11-28
|
||||
|
||||
### Ajouté
|
||||
|
||||
- **Destination « Console Spark » d'un secret (#102, fiche #238)** : un secret peut porter la destination « Console Spark » (case dans les formulaires de création et d'édition des métadonnées) — l'octroi vers le consommateur Spark (consommateur actif nommé `spark`, convention du contrat de distribution §3) est alors créé automatiquement, et révoqué si la destination est retirée. L'octroi automatique est distingué des octrois manuels (champ `origine`, actions de journal dédiées), révocable à la main, et jamais dupliqué si un octroi actif couvre déjà le secret. Consommateur Spark absent ou ambigu : la destination reste posée, aucun octroi n'est créé et l'API le signale (`console_spark_octroi`). Nouvel endpoint `PATCH /api/coffres/{slug}/secrets/{nom}` pour les métadonnées (la valeur reste à la rotation dédiée). Contrats `/api/coffres/distribuables` et `/api/coffres/distribuer` inchangés. **Redéploiement Docker requis.**
|
||||
|
||||
---
|
||||
|
||||
## [2.95.6] — 2026-11-28
|
||||
|
||||
### Corrigé
|
||||
|
||||
- **BUG-132 — toast « Path not found: Secrets » à répétition** : le rafraîchissement de l'arborescence (état préservé) recapturait le nœud virtuel « Secrets » comme un répertoire physique déplié et le rechargeait par `/api/browse`, qui répond 404 — toast d'erreur à chaque rafraîchissement, notamment après l'ajout d'un secret. Les nœuds virtuels (`data-type` « virtual-* ») sont exclus de la recapture des répertoires dépliés (`frontend/js/sidebar.js`). Test de garde `test_rafraichissement_arbre_ignore_noeuds_virtuels_bug132`. **Redéploiement Docker requis.**
|
||||
|
||||
---
|
||||
|
||||
## [2.95.5] — 2026-11-28
|
||||
|
||||
### Corrigé
|
||||
|
||||
- **Panneau Spark en mobile (canonique commons v0.6.3)** : le composer n'était pas visible au complet — la barre de navigation mobile recouvrait le bas du panneau — et l'en-tête (contexte + actions) prenait trop de place. En ≤700px, le panneau passe au-dessus des barres de l'hôte (z-index 1000), le bandeau de contexte se réduit à l'essentiel et les actions/suggestions tiennent sur une rangée défilante. Fichier `frontend/draco-panneau.css` re-vendangé à l'identique du canonique. **Redéploiement Docker requis.**
|
||||
|
||||
---
|
||||
|
||||
## [2.95.4] — 2026-11-28
|
||||
|
||||
### Corrigé
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@
|
||||
|
||||
**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.
|
||||
|
||||
[]()
|
||||
[]()
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://www.docker.com/)
|
||||
[](https://www.python.org/)
|
||||
@@ -981,8 +981,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.95.4).
|
||||
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.98.0).
|
||||
|
||||
---
|
||||
|
||||
*Projet : ObsiGate | Version : 2.95.4 | Dernière mise à jour : Septembre 2026*
|
||||
*Projet : ObsiGate | Version : 2.98.0 | Dernière mise à jour : Septembre 2026*
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**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.
|
||||
|
||||
[]()
|
||||
[]()
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://www.docker.com/)
|
||||
[](https://www.python.org/)
|
||||
@@ -1156,8 +1156,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.95.4).
|
||||
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.98.0).
|
||||
|
||||
---
|
||||
|
||||
*Project: ObsiGate | Version: 2.95.4 | Last updated: September 2026*
|
||||
*Project: ObsiGate | Version: 2.98.0 | Last updated: September 2026*
|
||||
|
||||
+156
-2
@@ -18,7 +18,8 @@ Modèle :
|
||||
(personnel | partage | instance), dek_chiffree (ou None en mode
|
||||
dégradé sans KEK), statut (actif | archive), dates.
|
||||
- Secret : id, coffre_id, nom, type, service, note, expiration,
|
||||
version_courante, cree_le, modifie_le, derniere_utilisation.
|
||||
version_courante, cree_le, modifie_le, derniere_utilisation,
|
||||
console_spark (destination « Console Spark », défaut False — #102).
|
||||
- Version : numero, nonce, ciphertext, cree_le, remplacee_le.
|
||||
Seule la version courante est distribuable.
|
||||
- Consommateur : id (sert de jti), nom, jeton_hash, jeton_prefixe,
|
||||
@@ -26,7 +27,8 @@ Modèle :
|
||||
- Octroi : id, coffre_id, secret_id (None = tout le coffre),
|
||||
cible_type (consommateur | utilisateur | executeur | workspace),
|
||||
cible_id, expiration, statut (actif | revoque | expire),
|
||||
cree_par, cree_le, revoque_le.
|
||||
cree_par, cree_le, revoque_le, origine (manuel | console_spark ;
|
||||
les octrois antérieurs sans champ valent « manuel »).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,6 +67,18 @@ TYPES_SECRET = {"api_key", "token", "password", "certificate", "autre"}
|
||||
PERIMETRES = {"personnel", "partage", "instance"}
|
||||
CIBLES_OCTROI = {"consommateur", "utilisateur", "executeur", "workspace"}
|
||||
|
||||
# Destination « Console Spark » d'un secret (#102) : quand elle est
|
||||
# active sur un secret, un octroi vers le consommateur Spark est créé
|
||||
# automatiquement (et révoqué quand elle est retirée). Le consommateur
|
||||
# Spark est identifié par la convention documentée dans
|
||||
# docs/COFFRE-contrat-distribution.md §3 : un consommateur ACTIF nommé
|
||||
# « spark » (comparaison insensible à la casse et aux espaces de bord).
|
||||
# L'autorisation continue de porter sur le jeton, jamais sur le nom —
|
||||
# le nom ne sert qu'à retrouver le destinataire de l'octroi automatique.
|
||||
NOM_CONSOMMATEUR_SPARK = "spark"
|
||||
ORIGINE_OCTROI_MANUEL = "manuel"
|
||||
ORIGINE_OCTROI_CONSOLE_SPARK = "console_spark"
|
||||
|
||||
MAX_VALEUR = 65536
|
||||
MAX_TEXTE = 2000
|
||||
DUREE_OCTROI_DEFAUT_JOURS = 90
|
||||
@@ -403,6 +417,7 @@ def secret_metadata(secret: dict, octrois_actifs: int = 0) -> dict:
|
||||
"modifie_le": secret["modifie_le"],
|
||||
"derniere_utilisation": secret.get("derniere_utilisation"),
|
||||
"octrois_actifs": octrois_actifs,
|
||||
"console_spark": bool(secret.get("console_spark", False)),
|
||||
"reference": f"coffre:{secret['coffre_slug']}/{secret['nom']}",
|
||||
}
|
||||
|
||||
@@ -415,6 +430,7 @@ def create_secret(
|
||||
service: str = "",
|
||||
expiration: str | None = None,
|
||||
note: str = "",
|
||||
console_spark: bool = False,
|
||||
data_dir: str | Path | None = None,
|
||||
) -> dict:
|
||||
"""Chiffre et stocke un secret (nouvelle version 1)."""
|
||||
@@ -453,6 +469,7 @@ def create_secret(
|
||||
"cree_le": _now_iso(),
|
||||
"modifie_le": _now_iso(),
|
||||
"derniere_utilisation": None,
|
||||
"console_spark": bool(console_spark),
|
||||
}
|
||||
data["secrets"].append(secret)
|
||||
valeurs["versions"][secret_id] = [
|
||||
@@ -469,6 +486,48 @@ def create_secret(
|
||||
return secret
|
||||
|
||||
|
||||
def update_secret(
|
||||
coffre: dict,
|
||||
nom: str,
|
||||
champs: dict,
|
||||
data_dir: str | Path | None = None,
|
||||
) -> dict:
|
||||
"""Met à jour les métadonnées d'un secret (jamais sa valeur).
|
||||
|
||||
``champs`` ne peut contenir que ``service``, ``note``,
|
||||
``expiration`` (None = retrait de l'expiration) et
|
||||
``console_spark`` (booléen). Les validations sont les mêmes qu'à
|
||||
la création. Lève IntrouvableError si le secret n'existe pas."""
|
||||
base = resolve_data_dir(data_dir)
|
||||
nom = valider_nom_secret(nom)
|
||||
autorises = {"service", "note", "expiration", "console_spark"}
|
||||
inconnus = set(champs) - autorises
|
||||
if inconnus:
|
||||
raise ValidationError(
|
||||
f"Champs de secret non modifiables : {sorted(inconnus)}"
|
||||
)
|
||||
if "service" in champs:
|
||||
service = (champs["service"] or "").strip()
|
||||
if len(service) > 128:
|
||||
raise ValidationError("Service trop long (128 caractères max)")
|
||||
champs = {**champs, "service": service}
|
||||
if "note" in champs:
|
||||
champs = {**champs, "note": _valider_texte(champs["note"], "note")}
|
||||
if "expiration" in champs and champs["expiration"] is not None:
|
||||
_parse_date(champs["expiration"])
|
||||
if "console_spark" in champs:
|
||||
champs = {**champs, "console_spark": bool(champs["console_spark"])}
|
||||
with _lock:
|
||||
data, _ = _load_tout(base)
|
||||
for secret in data["secrets"]:
|
||||
if secret["coffre_id"] == coffre["id"] and secret["nom"] == nom:
|
||||
secret.update(champs)
|
||||
secret["modifie_le"] = _now_iso()
|
||||
_save_coffres(base, data)
|
||||
return secret
|
||||
raise IntrouvableError(f"Secret introuvable : {nom}")
|
||||
|
||||
|
||||
def rotate_secret(
|
||||
coffre: dict, nom: str, valeur: str, data_dir: str | Path | None = None
|
||||
) -> dict:
|
||||
@@ -750,11 +809,14 @@ def create_octroi(
|
||||
secret_id: str | None,
|
||||
cree_par: str,
|
||||
expiration: str | None = None,
|
||||
origine: str = ORIGINE_OCTROI_MANUEL,
|
||||
data_dir: str | Path | None = None,
|
||||
) -> dict:
|
||||
base = resolve_data_dir(data_dir)
|
||||
if cible_type not in CIBLES_OCTROI:
|
||||
raise ValidationError(f"Type de cible invalide : {cible_type}")
|
||||
if origine not in (ORIGINE_OCTROI_MANUEL, ORIGINE_OCTROI_CONSOLE_SPARK):
|
||||
raise ValidationError(f"Origine d'octroi invalide : {origine}")
|
||||
if not (cible_id or "").strip():
|
||||
raise ValidationError("Cible d'octroi requise")
|
||||
if secret_id is not None:
|
||||
@@ -782,6 +844,7 @@ def create_octroi(
|
||||
"cree_par": cree_par,
|
||||
"cree_le": _now_iso(),
|
||||
"revoque_le": None,
|
||||
"origine": origine,
|
||||
}
|
||||
data["octrois"].append(octroi)
|
||||
_save_coffres(base, data)
|
||||
@@ -837,6 +900,97 @@ def statut_octroi_consommateur(
|
||||
return "absent", None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Destination « Console Spark » (#102)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def trouver_consommateur_spark(
|
||||
data_dir: str | Path | None = None,
|
||||
) -> tuple[dict | None, str]:
|
||||
"""Retrouve le consommateur Spark parmi les consommateurs ACTIFS.
|
||||
|
||||
Critère (convention docs/COFFRE-contrat-distribution.md §3) : le
|
||||
nom normalisé (espaces de bord retirés, casse ignorée) vaut
|
||||
``spark``. Retourne ``(consommateur, "ok")`` si exactement un
|
||||
consommateur actif correspond, ``(None, "introuvable")`` si aucun,
|
||||
``(None, "ambigu")`` si plusieurs — dans ces deux cas, aucun octroi
|
||||
automatique ne doit être créé : mieux vaut signaler que deviner le
|
||||
destinataire d'un accès à un secret."""
|
||||
base = resolve_data_dir(data_dir)
|
||||
with _lock:
|
||||
candidats = [
|
||||
{k: v for k, v in c.items() if k != "jeton_hash"}
|
||||
for c in _load_coffres(base)["consommateurs"]
|
||||
if c["statut"] == "actif"
|
||||
and (c.get("nom") or "").strip().casefold() == NOM_CONSOMMATEUR_SPARK
|
||||
]
|
||||
if len(candidats) == 1:
|
||||
return candidats[0], "ok"
|
||||
if not candidats:
|
||||
return None, "introuvable"
|
||||
return None, "ambigu"
|
||||
|
||||
|
||||
def synchroniser_destination_spark(
|
||||
coffre: dict,
|
||||
secret: dict,
|
||||
cree_par: str,
|
||||
data_dir: str | Path | None = None,
|
||||
) -> str:
|
||||
"""Réconcilie l'octroi automatique d'un secret avec sa destination.
|
||||
|
||||
À appeler après la création ou la modification du secret. Selon
|
||||
``secret["console_spark"]`` :
|
||||
|
||||
- destination active : assure un octroi ACTIF du consommateur
|
||||
Spark vers ce secret. Si un octroi actif couvre déjà le secret
|
||||
(manuel, automatique ou coffre-wide), il est conservé tel quel —
|
||||
jamais de doublon. Sinon un octroi d'origine ``console_spark``
|
||||
est créé (expiration par défaut, comme un octroi manuel).
|
||||
- destination inactive : révoque les octrois automatiques actifs
|
||||
du secret (origine ``console_spark`` seulement) ; les octrois
|
||||
manuels ne sont jamais touchés.
|
||||
|
||||
Retourne le résultat de la réconciliation : ``cree``,
|
||||
``existant``, ``revoque``, ``aucun``,
|
||||
``consommateur_introuvable`` ou ``consommateur_ambigu``."""
|
||||
base = resolve_data_dir(data_dir)
|
||||
if not secret.get("console_spark", False):
|
||||
with _lock:
|
||||
data = _load_coffres(base)
|
||||
a_revoquer = [
|
||||
o["id"]
|
||||
for o in data["octrois"]
|
||||
if o.get("secret_id") == secret["id"]
|
||||
and o.get("origine") == ORIGINE_OCTROI_CONSOLE_SPARK
|
||||
and o["statut"] == "actif"
|
||||
]
|
||||
for octroi_id in a_revoquer:
|
||||
revoquer_octroi(octroi_id, base)
|
||||
return "revoque" if a_revoquer else "aucun"
|
||||
consommateur, statut = trouver_consommateur_spark(base)
|
||||
if statut == "introuvable":
|
||||
return "consommateur_introuvable"
|
||||
if statut == "ambigu":
|
||||
return "consommateur_ambigu"
|
||||
assert consommateur is not None # statut "ok" garanti ci-dessus
|
||||
acces, _octroi = statut_octroi_consommateur(
|
||||
consommateur["id"], coffre["id"], secret["id"], base
|
||||
)
|
||||
if acces == "ok":
|
||||
return "existant"
|
||||
create_octroi(
|
||||
coffre=coffre,
|
||||
cible_type="consommateur",
|
||||
cible_id=consommateur["id"],
|
||||
secret_id=secret["id"],
|
||||
cree_par=cree_par,
|
||||
origine=ORIGINE_OCTROI_CONSOLE_SPARK,
|
||||
data_dir=base,
|
||||
)
|
||||
return "cree"
|
||||
|
||||
|
||||
def secrets_accessibles_utilisateur(
|
||||
username: str, coffre: dict, data_dir: str | Path | None = None
|
||||
) -> set | None:
|
||||
|
||||
+65
-10
@@ -70,6 +70,11 @@ async def _on_vault_change(events: list):
|
||||
Processes each event (create/modify/delete/move) and updates the index
|
||||
incrementally, then broadcasts SSE notifications.
|
||||
"""
|
||||
# #245 : tout changement d'index invalide le cache du dashboard.
|
||||
from backend.routers.config import invalidate_dashboard_cache
|
||||
|
||||
invalidate_dashboard_cache()
|
||||
|
||||
updated_vaults = set()
|
||||
changes = []
|
||||
|
||||
@@ -245,12 +250,17 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
yield patched
|
||||
|
||||
response.body_iterator = _docs_body()
|
||||
# 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).
|
||||
# ``no-cache`` keeps caching but forces revalidation (ETag/Last-Modified).
|
||||
# Cache des statiques (#242) : ``immutable`` UNIQUEMENT pour les
|
||||
# URL versionnées ``?v=<VERSION courante>`` (voir
|
||||
# backend.static_versioning) — une nouvelle version change toutes
|
||||
# les URL, donc le piège historique (cache long sans versionnage
|
||||
# → build périmé servi un an) ne peut pas se reproduire. Sans
|
||||
# ``?v=`` valide : ``no-cache`` (revalidation ETag/Last-Modified).
|
||||
if request.url.path.startswith("/static/"):
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
from backend.static_versioning import cache_control_for
|
||||
|
||||
response.headers["Cache-Control"] = cache_control_for(
|
||||
request.url.path, request.url.query)
|
||||
return response
|
||||
|
||||
|
||||
@@ -927,6 +937,10 @@ def _index_html(request: Request) -> str:
|
||||
from backend.draco_config import urls_publiques
|
||||
|
||||
html = (FRONTEND_DIR / "index.html").read_text(encoding="utf-8")
|
||||
# #242 : URL statiques versionnées (?v=<VERSION>) — cache long sûr.
|
||||
from backend.static_versioning import rewrite_static_urls
|
||||
|
||||
html = rewrite_static_urls(html)
|
||||
script = (
|
||||
"<script>window.DRACO_URLS = "
|
||||
+ _json.dumps(urls_publiques()).replace("<", "\\u003c")
|
||||
@@ -947,17 +961,58 @@ def _index_html(request: Request) -> str:
|
||||
html = html.replace("</header>", "</header>" + fragment, 1)
|
||||
return inject_csp_nonce(html, request.state.csp_nonce)
|
||||
|
||||
class VersionedStaticFiles(StaticFiles):
|
||||
"""Statiques dont les modules ES sont réécrits au service (#242).
|
||||
|
||||
Les spécificateurs d'import relatifs des fichiers ``.js`` reçoivent
|
||||
``?v=<VERSION>`` : le navigateur ne demande donc que des URL
|
||||
versionnées, de proche en proche dans le graphe de modules.
|
||||
``Cache-Control`` reste posé par ``SecurityHeadersMiddleware``.
|
||||
"""
|
||||
|
||||
async def get_response(self, path, scope): # type: ignore[override]
|
||||
if path.endswith(".js"):
|
||||
from backend.static_versioning import rewrite_js_imports
|
||||
|
||||
full = Path(self.directory) / path
|
||||
try:
|
||||
resolved = full.resolve()
|
||||
root = Path(self.directory).resolve()
|
||||
if resolved.is_file() and resolved.is_relative_to(root):
|
||||
source = resolved.read_text(encoding="utf-8", errors="replace")
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
return PlainTextResponse(
|
||||
rewrite_js_imports(source),
|
||||
media_type="application/javascript",
|
||||
)
|
||||
except OSError:
|
||||
pass # repli : service statique standard (404 propre inclus)
|
||||
return await super().get_response(path, scope)
|
||||
|
||||
|
||||
if FRONTEND_DIR.exists():
|
||||
# ``Cache-Control`` for /static is set by SecurityHeadersMiddleware (no-cache).
|
||||
app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")
|
||||
# ``Cache-Control`` for /static is set by SecurityHeadersMiddleware (#242).
|
||||
app.mount("/static", VersionedStaticFiles(directory=str(FRONTEND_DIR)), name="static")
|
||||
|
||||
@app.get("/sw.js")
|
||||
async def serve_service_worker():
|
||||
"""Serve the service worker for PWA support."""
|
||||
"""Serve the service worker for PWA support.
|
||||
|
||||
#242 : le nom de cache du SW embarque la version courante
|
||||
(``__OBSIGATE_SW_VERSION__`` remplacé ici) — à chaque release,
|
||||
l'ancien cache est abandonné à l'activation.
|
||||
"""
|
||||
sw_file = FRONTEND_DIR / "sw.js"
|
||||
if sw_file.exists():
|
||||
return FileResponse(
|
||||
sw_file,
|
||||
from backend.version import get_version
|
||||
|
||||
content = sw_file.read_text(encoding="utf-8").replace(
|
||||
"__OBSIGATE_SW_VERSION__", f"v{get_version()}")
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
return PlainTextResponse(
|
||||
content,
|
||||
media_type="application/javascript",
|
||||
headers={
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
|
||||
@@ -35,6 +35,13 @@ Règles d'or, appliquées côté serveur à chaque requête :
|
||||
d'erreur restent ceux de la Phase 1b (voir
|
||||
``docs/COFFRE-contrat-distribution.md`` pour la correspondance avec
|
||||
l'état ``acces_requis`` côté Spark).
|
||||
- Destination « Console Spark » (issue #102) : un secret peut porter
|
||||
la destination ``console_spark`` ; à la création et à la
|
||||
modification de ses métadonnées (``PATCH``), l'octroi vers le
|
||||
consommateur Spark est réconcilié automatiquement (créé s'il
|
||||
manque, révoqué si la destination est retirée), sans jamais
|
||||
dupliquer un octroi actif existant. Les contrats ``/distribuer``
|
||||
et ``/distribuables`` sont inchangés.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -90,7 +97,9 @@ from backend.coffre_store import (
|
||||
secret_metadata,
|
||||
secrets_accessibles_utilisateur,
|
||||
statut_octroi_consommateur,
|
||||
synchroniser_destination_spark,
|
||||
toucher_utilisation,
|
||||
update_secret,
|
||||
verifier_jeton_consommateur,
|
||||
)
|
||||
|
||||
@@ -225,6 +234,31 @@ def _audit(user: str, action: str, **kwargs) -> None:
|
||||
logger.warning("Échec audit coffre (%s) : %s", action, exc)
|
||||
|
||||
|
||||
def _synchroniser_spark(user: dict, coffre: dict, secret: dict) -> str:
|
||||
"""Réconcilie l'octroi automatique « Console Spark » d'un secret
|
||||
(#102) et audite les créations/révocations automatiques sous des
|
||||
actions dédiées (``octroi_auto_spark_cree`` /
|
||||
``octroi_auto_spark_revoque``), distinguables des octrois manuels
|
||||
dans le journal. Retourne le résultat de la réconciliation
|
||||
(``cree``, ``existant``, ``revoque``, ``aucun``,
|
||||
``consommateur_introuvable``, ``consommateur_ambigu``) pour que
|
||||
l'appelant le signale dans sa réponse — jamais d'échec silencieux
|
||||
quand le consommateur Spark est absent ou ambigu."""
|
||||
resultat = synchroniser_destination_spark(
|
||||
coffre, secret, cree_par=_username(user)
|
||||
)
|
||||
if resultat in ("cree", "revoque"):
|
||||
_audit(
|
||||
_username(user),
|
||||
f"octroi_auto_spark_{resultat}",
|
||||
coffre=coffre["slug"],
|
||||
secret_ref=f"coffre:{coffre['slug']}/{secret['nom']}",
|
||||
consommateur="spark",
|
||||
resultat="ok",
|
||||
)
|
||||
return resultat
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Coffres
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -584,6 +618,7 @@ async def api_create_secret(
|
||||
service=body.get("service", ""),
|
||||
expiration=body.get("expiration"),
|
||||
note=body.get("note", ""),
|
||||
console_spark=bool(body.get("console_spark", False)),
|
||||
)
|
||||
except SecretExisteError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
@@ -600,7 +635,57 @@ async def api_create_secret(
|
||||
secret_ref=f"coffre:{coffre['slug']}/{secret['nom']}",
|
||||
resultat="ok",
|
||||
)
|
||||
return _metadata_secret(coffre, secret)
|
||||
reponse = _metadata_secret(coffre, secret)
|
||||
if secret.get("console_spark"):
|
||||
# Destination « Console Spark » : octroi automatique. Le
|
||||
# résultat est rendu dans la réponse (champ console_spark_octroi)
|
||||
# pour que l'interface signale un consommateur Spark absent ou
|
||||
# ambigu au lieu d'échouer en silence.
|
||||
reponse["console_spark_octroi"] = _synchroniser_spark(
|
||||
current_user, coffre, secret
|
||||
)
|
||||
reponse["octrois_actifs"] = compter_octrois_actifs(secret["id"])
|
||||
return reponse
|
||||
|
||||
|
||||
@router.patch("/api/coffres/{slug}/secrets/{nom}")
|
||||
async def api_update_secret(
|
||||
slug: str, nom: str, body: dict = Body(...), current_user=Depends(require_auth)
|
||||
):
|
||||
"""Modification des métadonnées d'un secret (#102).
|
||||
|
||||
Champs acceptés : ``service``, ``note``, ``expiration`` (null =
|
||||
retrait) et ``console_spark`` (destination « Console Spark »). La
|
||||
valeur ne passe jamais par cette route (rotation dédiée). Toute
|
||||
modification réconcilie l'octroi automatique : destination activée
|
||||
→ octroi assuré ; destination retirée → octroi automatique révoqué.
|
||||
Le résultat de la réconciliation est rendu dans
|
||||
``console_spark_octroi``."""
|
||||
_exiger_actives()
|
||||
coffre = _coffre_or_404(slug)
|
||||
_exiger_gerer(current_user, coffre)
|
||||
_secret_or_404(coffre, nom)
|
||||
# Le store valide les champs : tout champ hors métadonnées (par
|
||||
# exemple « valeur ») est refusé en 400, jamais ignoré en silence.
|
||||
try:
|
||||
secret = update_secret(coffre, nom, body)
|
||||
except IntrouvableError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
_audit(
|
||||
_username(current_user),
|
||||
"secret_modifie",
|
||||
coffre=coffre["slug"],
|
||||
secret_ref=f"coffre:{coffre['slug']}/{secret['nom']}",
|
||||
resultat="ok",
|
||||
)
|
||||
reponse = _metadata_secret(coffre, secret)
|
||||
reponse["console_spark_octroi"] = _synchroniser_spark(
|
||||
current_user, coffre, secret
|
||||
)
|
||||
reponse["octrois_actifs"] = compter_octrois_actifs(secret["id"])
|
||||
return reponse
|
||||
|
||||
|
||||
@router.post("/api/coffres/{slug}/secrets/{nom}/rotation")
|
||||
|
||||
@@ -233,9 +233,45 @@ async def api_diagnostics(current_user=Depends(require_admin)):
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cache mémoire du dashboard (#245, épopée perf #240)
|
||||
#
|
||||
# ``GET /api/dashboard`` parcourait tous les fichiers de tous les vaults
|
||||
# à chaque appel (10 987 fichiers en prod). Le résultat est mis en cache
|
||||
# 60 s par utilisateur (l'accès aux vaults dépend de l'utilisateur) et
|
||||
# invalidé dès que le watcher signale un changement (voir
|
||||
# ``_on_vault_change`` dans ``backend.main``) ou après modification de
|
||||
# l'index par les routes d'écriture via ``invalidate_dashboard_cache``.
|
||||
# ---------------------------------------------------------------------------
|
||||
import time as _time
|
||||
|
||||
_DASHBOARD_TTL_SECONDS = 60.0
|
||||
_dashboard_cache: dict[str, tuple[float, dict]] = {}
|
||||
|
||||
|
||||
def invalidate_dashboard_cache() -> None:
|
||||
"""Vider le cache du dashboard (changement d'index signalé)."""
|
||||
_dashboard_cache.clear()
|
||||
|
||||
|
||||
def _dashboard_cache_key(current_user) -> str:
|
||||
return str(getattr(current_user, "username", None) or getattr(current_user, "id", "") or "anon")
|
||||
|
||||
|
||||
@router.get("/api/dashboard", response_model=DashboardResponse)
|
||||
async def api_dashboard(current_user=Depends(require_auth)):
|
||||
"""Aggregated dashboard statistics across all accessible vaults."""
|
||||
key = _dashboard_cache_key(current_user)
|
||||
cached = _dashboard_cache.get(key)
|
||||
if cached and (_time.monotonic() - cached[0]) < _DASHBOARD_TTL_SECONDS:
|
||||
return cached[1]
|
||||
result = _compute_dashboard(current_user)
|
||||
_dashboard_cache[key] = (_time.monotonic(), result)
|
||||
return result
|
||||
|
||||
|
||||
def _compute_dashboard(current_user) -> dict:
|
||||
"""Calcul effectif des statistiques du dashboard (sans cache)."""
|
||||
vault_stats = []
|
||||
total_files = 0
|
||||
total_tags = set()
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Cache versionné des statiques (#242, épopée perf #240).
|
||||
|
||||
Mécanisme sans étape de build (règle du dépôt) :
|
||||
|
||||
- les URL ``/static/…`` référencées par ``index.html`` sont réécrites
|
||||
au service avec ``?v=<VERSION>`` (:func:`rewrite_static_urls`) ;
|
||||
- les spécificateurs d'import relatifs des modules ES servis sont
|
||||
réécrits de la même façon (:func:`rewrite_js_imports`), donc tout le
|
||||
graphe de modules est demandé en URL versionnées, de proche en
|
||||
proche ;
|
||||
- l'en-tête ``Cache-Control`` n'autorise le cache long
|
||||
(``immutable``) **que** pour une requête dont le ``?v=`` vaut la
|
||||
version courante (:func:`cache_control_for`) — une nouvelle version
|
||||
change toutes les URL, donc un cache long ne peut plus jamais
|
||||
servir un build périmé (l'incident historique du ``max-age`` sans
|
||||
versionnage).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from backend.version import get_version
|
||||
|
||||
IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"
|
||||
NO_CACHE = "no-cache"
|
||||
|
||||
_STATIC_URL_RE = re.compile(r"((?:src|href)=[\"'])(/static/[^\"'?#]+)([\"'])")
|
||||
_JS_SPEC_RE = re.compile(
|
||||
r"((?:from\s+|import\s*\(\s*|import\s+)['\"])(\.{1,2}/[^'\"]+?\.js)(['\"])"
|
||||
)
|
||||
|
||||
|
||||
def current_version() -> str:
|
||||
"""Version courante (source unique : fichier ``VERSION``)."""
|
||||
return get_version()
|
||||
|
||||
|
||||
def rewrite_static_urls(html: str, version: str | None = None) -> str:
|
||||
"""Ajouter ``?v=<version>`` aux URL ``/static/…`` d'un document HTML."""
|
||||
v = version if version is not None else current_version()
|
||||
return _STATIC_URL_RE.sub(
|
||||
lambda m: f"{m.group(1)}{m.group(2)}?v={v}{m.group(3)}", html)
|
||||
|
||||
|
||||
def rewrite_js_imports(source: str, version: str | None = None) -> str:
|
||||
"""Ajouter ``?v=<version>`` aux imports relatifs ``.js`` d'un module ES.
|
||||
|
||||
Couvre ``import … from '…'``, ``import '…'`` et ``import('…')``.
|
||||
Les spécificateurs déjà pourvus d'une query string sont laissés
|
||||
intacts.
|
||||
"""
|
||||
v = version if version is not None else current_version()
|
||||
return _JS_SPEC_RE.sub(
|
||||
lambda m: f"{m.group(1)}{m.group(2)}?v={v}{m.group(3)}", source)
|
||||
|
||||
|
||||
def cache_control_for(path: str, query_string: str = "") -> str | None:
|
||||
"""En-tête ``Cache-Control`` pour un chemin, selon la query string.
|
||||
|
||||
Retourne ``None`` hors des statiques (l'appelant ne touche alors
|
||||
à rien). ``immutable`` seulement si ``v`` vaut la version
|
||||
courante ; ``no-cache`` dans tous les autres cas.
|
||||
"""
|
||||
if not path.startswith("/static/"):
|
||||
return None
|
||||
params = {}
|
||||
for pair in query_string.split("&"):
|
||||
if "=" in pair:
|
||||
key, value = pair.split("=", 1)
|
||||
params[key] = value
|
||||
if params.get("v") and params["v"] == current_version():
|
||||
return IMMUTABLE_CACHE_CONTROL
|
||||
return NO_CACHE
|
||||
Generated
+1
-1
@@ -2626,7 +2626,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "obsigate-desktop"
|
||||
version = "2.95.4"
|
||||
version = "2.98.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"env_logger",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "obsigate-desktop"
|
||||
version = "2.95.4"
|
||||
version = "2.98.0"
|
||||
description = "ObsiGate Desktop — Porte d'entrée native pour vos vaults Obsidian"
|
||||
authors = ["Bruno Charest"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/nicedoc/obsigate/main/desktop/tauri.conf.schema.json",
|
||||
"productName": "ObsiGate",
|
||||
"version": "2.95.4",
|
||||
"version": "2.98.0",
|
||||
"identifier": "com.obsigate.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../frontend",
|
||||
|
||||
@@ -372,6 +372,7 @@ Avant de corriger quoi que ce soit, un agent IA doit :
|
||||
| 2026-11-19 | #230 + BUG-127 | Fonctionnalité desktop + correction | `desktop/src/main.rs`, `desktop/permissions/commands.toml`, `backend/routers/desktop_sso.py`, `backend/main.py`, `frontend/js/{auth,desktop,config}.js`, `frontend/index.html`, `frontend/style.css`, `frontend/locales/{fr,en}.json`, `tests/test_desktop_sso.py`, `tests/test_desktop_sso_ui.py`, `tests/frontend/desktop.test.mjs`, `tests/test_draco_barre.py`, `docs/features/desktop-sso-environnement-230.md`, `docs/ROADMAP.md`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **#230 — l'app desktop peut se connecter avec le compte central et choisir prod/dev.** Constat : le backend desktop sert `127.0.0.1`, le cookie `draco_session` (`Domain=.dracodev.net`) ne lui parvient jamais ; le premier lancement générait un mot de passe admin aléatoire visible seulement dans les logs. Livré : liaison d'appareil sur le central choisi (`/api/v1/liaison`), validation du jeton draco via `/api/auth/me` du central, ouverture de la session de l'admin local par défaut ; login local conservé (admin/chab30 à la création). Sélecteur d'environnement en Configuration + premier lancement, injecté au backend embarqué (`OBSIGATE_DESKTOP*`, `DRACO_AGENT_URL`, `DRACO_OBSIGATE_URL` ; sœurs/Hub `-dev` dérivés). Routes `/api/desktop/sso/*` = 404 hors desktop, UI conditionnée par `isTauriEnv()` : application web Docker inchangée. **BUG-127** : `/liaison` même hôte honoré après login (`return_to`), sinon l'approbation desktop restait bloquée. Vérifié : `test_desktop_sso.py` 9 passed, 32 tests Rust (ACL incluse), `desktop.test.mjs` 30, `test_draco_barre`/`test_desktop_sso_ui`/i18n parity verts. | 🟢 corrigé/livré (en attente vérif utilisateur) |
|
||||
| 2026-11-20 | BUG-128 + BUG-129 | Correction CI | `backend/requirements.txt`, `tests/test_ci_workflow.py`, `frontend/js/i18n.js`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-128 — `security` rouge : `pip-audit` signale mistune 3.3.3 (CVE-2026-97698/97699, fix 3.3.4)**. Plancher porté à `mistune>=3.3.4`, ajouté à `TestDependencySecurityFloors` ; runtime desktop reconstruit. **BUG-129 — `lint` rouge : `desktop-roots.test.mjs` importe `desktop.js` → `i18n.js`, qui écrivait `window.t/...` au chargement en Node** (`ReferenceError: window is not defined`). Exports globaux protégés par `typeof window !== "undefined"`. Vérifié : `node tests/frontend/desktop-roots.test.mjs` 4/4, suite pytest complète avec mistune 3.4.0, ruff/mypy 0. | 🟢 corrigé (en attente vérif utilisateur) |
|
||||
| 2026-11-28 | BUG-130 | Correction affichage | `frontend/index.html`, `tests/test_draco_barre.py`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-130 — la zone de visualisation/édition s'affichait SOUS la barre latérale au lieu d'à sa droite.** Cause racine : le retrait du panneau « Historique IA » (transition D5, #235) avait laissé un fragment `<div` orphelin qui absorbait l'ouverture du panneau de discussion (`#sidebar-panel-chat` et sa rangée de canaux) ; le parseur HTML5 fermait alors `.main-body` dès la fin de la sidebar, et `.content-wrapper` devenait sa sœur au lieu de son enfant (flex perdu). Correctif : ouverture du panneau de discussion restaurée à l'identique. Vérifié : arbre DOM (jsdom) redevenu identique à l'état pré-D5 (`main-body` contient overlay, sidebar, poignée, context bar, content-wrapper, right sidebar), test de garde `test_structure_main_body_content_wrapper`. | 🟢 corrigé (en attente vérif utilisateur) |
|
||||
| 2026-11-28 | BUG-132 | Correction frontend | `frontend/js/sidebar.js`, `tests/test_draco_barre.py`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-132 — toast « Path not found: Secrets » à répétition lors de l'ajout d'un secret.** Cause racine : `refreshSidebarTreePreservingState()` recapture tout `.tree-item[data-path]` déplié, y compris le nœud virtuel Secrets (`data-path="Secrets"`, sans répertoire physique), puis le recharge par `/api/browse` → 404 dont le détail est affiché en toast par `api()` à chaque rafraîchissement. Correctif : exclusion des nœuds `data-type` « virtual-* » de la recapture. Vérifié : `test_rafraichissement_arbre_ignore_noeuds_virtuels_bug132`, fichier de garde 29/29. | 🟢 corrigé (en attente vérif utilisateur) |
|
||||
| 2026-11-28 | BUG-131 | Correction mobile | `frontend/js/spark-panneau.js`, `frontend/style.css`, `tests/test_draco_barre.py`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-131 — en mode mobile, le bouton Spark de la barre de navigation affichait « Le panneau Spark n'est pas disponible » et le bouton flottant fonctionnel se retrouvait caché derrière la barre.** Cause racine : `ouvrirSpark()` ne cherchait que `#draco-spark-btn`, élément absent hors du visualiseur (accueil, mobile) ; le flottant desktop (`bottom: 20px`, z-index 65) passait sous la barre de navigation mobile. Correctif (demande de Bruno) : le flottant est masqué en ≤768px — le bouton officiel est celui de la barre — et `ouvrirSpark()` retombe sur `DRACO_PANNEAU.toggle()` (même API que le bouton du visualiseur) puis sur le flottant. Vérifié : `test_bouton_spark_mobile_bug131`, `mobile-toolbar.test.mjs` vert. | 🟢 corrigé (en attente vérif utilisateur) |
|
||||
|
||||
---
|
||||
|
||||
+34
-1
@@ -1,6 +1,6 @@
|
||||
# ObsiGate — Roadmap
|
||||
|
||||
> **Version :** 2.95.4 | **Dernière mise à jour :** 2026-11-28
|
||||
> **Version :** 2.98.0 | **Dernière mise à jour :** 2026-11-30
|
||||
> **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)**
|
||||
@@ -30,6 +30,39 @@
|
||||
|
||||
## 🔵 En cours
|
||||
|
||||
### 240. Épopée — Performance du chargement initial
|
||||
|
||||
- **Effort :** ~3 jours | **Impact :** 🔴 | **Ouvert :** 2026-11-30 | **Statut :** 🔵 en cours — branche `feat/perf-chargement-240` livrée, PR à fusionner (issue Gitea #106)
|
||||
- **Fiche :** [features/perf-chargement-240.md](./features/perf-chargement-240.md)
|
||||
- **Description :** demande de Bruno (2026-11-30) — diviser par ~3 le premier affichage utile d'og.dracodev.net au bénéfice du retour SSO, des liens profonds `#file=`/`#folder=` et de l'accès de base. Baseline : TTFB 0,36–0,67 s, graphe ES statique 41 modules / 1 420 963 o, Mermaid CDN 745 Ko chargé d'emblée, statiques sans URL versionnées, `/api/dashboard` sans cache.
|
||||
- **Sous-tâches :**
|
||||
- [x] **#241 P0** — script d'audit versionné (`scripts/audit_chargement.py`) + budget figé (fiche) — Gitea #107
|
||||
- [x] **#242 P1** — cache versionné `?v=<VERSION>` + `immutable` conditionnel + SW versionné — Gitea #108
|
||||
- [x] **#243 P2** — `import()` dynamique des modules lourds + retrait des CDN du `<head>` — Gitea #109 (graphe −10,8 %, CDN retirés ; −50 % non atteint, voir fiche)
|
||||
- [x] **#244 P3** — bootstrap : lien profond ouvert avant le chargement complet — Gitea #110
|
||||
- [x] **#245 P4** — cache 60 s de `/api/dashboard` invalidé par le watcher — Gitea #111
|
||||
|
||||
### 239. Lien profond « dossier » `#folder=` (console Spark)
|
||||
|
||||
- **Effort :** ~0,5 jour | **Impact :** 🟢 | **Ouvert :** 2026-11-30 | **Statut :** 🔵 en cours — PR sur `feat/lien-dossier-239` (fusion = geste de Bruno)
|
||||
- **Fiche :** [features/lien-dossier-239.md](./features/lien-dossier-239.md)
|
||||
- **Description :** demande de Bruno (2026-11-30) — les dossiers cités dans la console Spark doivent être cliquables comme les fichiers. La forme fichier `#file=<vault>:<chemin>` ne sait pas atterrir sur un répertoire (404 de `/api/file`) : ajout de la forme sœur `#folder=<vault>:<chemin>` (même encodage), reconnue à l'init du frontend — l'arborescence latérale se déplie jusqu'au dossier, qui est sélectionné et mis en évidence (`focusPathInSidebar`, `expandTarget`). Cible inconnue ou fragment illisible : repli propre sur l'accueil, aucune erreur bloquante. `#file=` inchangé. Carte jumelle côté Spark : agent-commun 0.112.0 (les résultats d'outils portent l'`url` profonde, décisions D1a/D2a).
|
||||
- **Sous-tâches :**
|
||||
- [x] Frontend : reconnaissance du fragment `#folder=` à l'init, atterrissage par `focusPathInSidebar`, repli accueil si la cible n'est pas atteinte
|
||||
- [x] Spec E2E `deep-link-folder` (dossier emboîté, vault inconnu, non-régression `#file=`) ; vérifications locales sans nouvel échec
|
||||
- [ ] Fusion de la PR, CI verte, redéploiement Docker (geste de Bruno) ; côté Spark, la carte jumelle agent-commun rend les dossiers cités cliquables
|
||||
|
||||
### 238. Secrets — destination « Console Spark » d'un secret (octroi automatique)
|
||||
|
||||
- **Effort :** ~0,5 jour | **Impact :** 🟡 | **Ouvert :** 2026-11-28 | **Statut :** 🔵 en cours — PR sur `feat/console-spark-secret` (carte Gitea #102 ; fusion = geste de Bruno)
|
||||
- **Fiche :** [features/console-spark-secret-238.md](./features/console-spark-secret-238.md)
|
||||
- **Description :** demande de Bruno (2026-11-28) — un secret ajouté dans ObsiGate doit être disponible dans la console Spark sans autre configuration. Une destination « Console Spark » posée sur le secret (création et édition des métadonnées) crée automatiquement l'octroi vers le consommateur Spark (convention : consommateur actif nommé `spark`, cf. `docs/COFFRE-contrat-distribution.md` §3) ; son retrait révoque cet octroi automatique, distingué des octrois manuels (champ `origine`) et révocable à la main. Consommateur Spark absent ou ambigu : la destination reste posée, aucun octroi n'est créé et l'API le signale explicitement. Aucun changement aux contrats `/api/coffres/distribuables` et `/api/coffres/distribuer`. Carte jumelle côté Spark : agent-commun #179 (sélecteur de clé alimenté par les distribuables).
|
||||
- **Sous-tâches :**
|
||||
- [x] Backend : champ `console_spark` sur le secret, `origine` sur l'octroi, réconciliation à la création et au nouvel endpoint `PATCH` des métadonnées, signalement `console_spark_octroi`
|
||||
- [x] Frontend : case « Console Spark » (création + édition), état dans la liste et le détail, origine affichée dans les octrois ; i18n FR/EN
|
||||
- [x] Tests coffres (destination active/retirée, consommateur absent/ambigu, pas de doublon) ; E2E laissé au CI
|
||||
- [ ] Fusion de la PR, CI verte, redéploiement Docker (geste de Bruno) ; côté Spark, la carte jumelle agent-commun #179 rend le secret choisissable comme clé fournisseur
|
||||
|
||||
### 237. Fusion — finition de la transition (transition D7)
|
||||
|
||||
- **Effort :** ~0,5 jour | **Impact :** 🟢 | **Ouvert :** 2026-11-28 | **Statut :** 🔵 en cours — PR sur `feat/transition-d7-finition` (carte Gitea #87 ; se ferme en dernier, après les fusions D3→D6)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# #238 — Destination « Console Spark » d'un secret (carte Gitea #102)
|
||||
|
||||
Demande de Bruno (2026-11-28) : un secret ajouté dans ObsiGate doit
|
||||
être disponible dans la console Spark sans autre configuration —
|
||||
« ajouter le type Console Spark et, dans la console Spark, il serait
|
||||
déjà disponible, rien d'autre à configurer ». Carte jumelle côté
|
||||
Spark : agent-commun #179 (sélecteur de clé fournisseur alimenté par
|
||||
les secrets distribuables, sans mapping Identités préalable).
|
||||
|
||||
## Avant
|
||||
|
||||
Pour qu'un secret serve de clé fournisseur dans Spark, il fallait
|
||||
créer le secret **puis** créer manuellement un octroi vers le
|
||||
consommateur Spark dans la vue « Accès et consommateurs ». L'endpoint
|
||||
`GET /api/coffres/distribuables` (issue #43) exposait déjà, en
|
||||
métadonnées seules, les secrets octroyés au consommateur appelant —
|
||||
il ne manquait que la création automatique de l'octroi.
|
||||
|
||||
## Réalisation
|
||||
|
||||
- **Modèle** (`backend/coffre_store.py`) : champ booléen
|
||||
`console_spark` sur le secret (défaut `False`, rendu dans les
|
||||
métadonnées) et champ `origine` sur l'octroi (`manuel` par défaut,
|
||||
`console_spark` pour les octrois automatiques ; les octrois
|
||||
antérieurs sans champ valent `manuel`).
|
||||
- **Identification du consommateur Spark** :
|
||||
`trouver_consommateur_spark()` applique la convention documentée
|
||||
dans `docs/COFFRE-contrat-distribution.md` §3 — un consommateur
|
||||
**actif** nommé `spark` (nom normalisé : espaces de bord retirés,
|
||||
casse ignorée). Zéro ou plusieurs correspondances = pas d'octroi
|
||||
deviné : la réconciliation retourne `consommateur_introuvable` ou
|
||||
`consommateur_ambigu`, rendu dans la réponse d'API
|
||||
(`console_spark_octroi`) et affiché par l'interface. L'autorisation
|
||||
continue de porter sur le jeton, jamais sur le nom.
|
||||
- **Réconciliation** (`synchroniser_destination_spark()`), appelée à
|
||||
la création du secret et à chaque modification de ses métadonnées :
|
||||
destination active → octroi actif assuré (un octroi actif couvrant
|
||||
déjà le secret — manuel, automatique ou coffre-wide — est conservé,
|
||||
jamais de doublon) ; destination retirée → seuls les octrois
|
||||
d'origine `console_spark` sont révoqués, les manuels sont intacts.
|
||||
L'octroi automatique suit les mêmes règles que les manuels
|
||||
(expiration par défaut 90 jours, révocable à la main, supprimé en
|
||||
cascade à la suppression du secret ; un secret expiré sort déjà des
|
||||
distribuables). Journal : actions dédiées `octroi_auto_spark_cree`
|
||||
/ `octroi_auto_spark_revoque`.
|
||||
- **Nouvel endpoint** `PATCH /api/coffres/{slug}/secrets/{nom}` :
|
||||
modification des métadonnées (`service`, `note`, `expiration`,
|
||||
`console_spark`) — la valeur ne passe jamais par cette route
|
||||
(rotation dédiée) et tout champ inconnu est refusé en 400, jamais
|
||||
ignoré en silence. Gestion du coffre exigée, comme la création.
|
||||
- **Frontend** (`frontend/js/coffres.js`) : case « Console Spark »
|
||||
dans les formulaires de création **et** d'édition (nouvelle modale
|
||||
« Modifier le secret », bouton Éditer du détail), avec la phrase
|
||||
d'aide « Le secret devient disponible comme clé dans la console
|
||||
Spark » ; badge « Console Spark » dans la liste, ligne dédiée dans
|
||||
le détail, origine affichée dans les listes d'octrois (détail et
|
||||
Accès) ; avertissement explicite si le consommateur Spark est
|
||||
absent ou ambigu. i18n FR + EN (7 clés `coffres.console_spark*`,
|
||||
`coffres.edit_secret_title`, `coffres.origine_console_spark`,
|
||||
`coffres.updated`).
|
||||
- **Contrats inchangés** : `/api/coffres/distribuables` et
|
||||
`/api/coffres/distribuer` ne bougent pas.
|
||||
|
||||
## Tests
|
||||
|
||||
- `tests/test_coffre_secrets.py::TestDestinationConsoleSpark`
|
||||
(6 tests nouveaux) : destination active → octroi automatique
|
||||
(origine vérifiée) et secret présent dans les distribuables +
|
||||
distribution effective ; destination retirée → octroi révoqué et
|
||||
distribuables vide ; consommateur absent → signalement
|
||||
`consommateur_introuvable`, destination posée, réconciliation
|
||||
réussie après création du consommateur ; consommateur ambigu →
|
||||
signalement, aucun octroi ; octroi manuel préexistant → aucun
|
||||
doublon et retrait de la destination sans effet sur le manuel ;
|
||||
PATCH métadonnées + erreurs (400 champ `valeur`, 404, 403).
|
||||
- Suite coffres complète : 50/50. E2E laissé au CI.
|
||||
@@ -0,0 +1,50 @@
|
||||
# #239 — Lien profond « dossier » `#folder=` (console Spark)
|
||||
|
||||
Demande de Bruno (2026-11-30) : dans les messages de la console
|
||||
Spark, les fichiers et dossiers ObsiGate cités par l'agent doivent
|
||||
être **cliquables** et ouvrir la cible directement dans ObsiGate.
|
||||
Carte jumelle côté Spark : agent-commun (liens profonds à la
|
||||
frontière d'outils, 0.112.0 — décisions D1a/D2a du plan
|
||||
`PLAN-LIENS-FICHIERS-CONSOLE-v1.md`).
|
||||
|
||||
## Avant
|
||||
|
||||
Le contrat des liens profonds de la suite ne connaît pour
|
||||
ObsiGate que la forme fichier : `#file=<vault>:<chemin>`, honorée
|
||||
à l'init du frontend (`Viewer.openFile`). Un dossier n'a **aucune
|
||||
forme** : `#file=` sur un répertoire aboutit au 404 de
|
||||
`/api/file` (le backend exige `is_file()`), et l'interface n'a
|
||||
pas de vue « contenu de dossier » — les dossiers vivent dans
|
||||
l'arborescence latérale. La console Spark ne pouvait donc pas
|
||||
lier un dossier sans envoyer l'utilisateur vers une erreur.
|
||||
|
||||
## Réalisation
|
||||
|
||||
- **Forme sœur `#folder=<vault>:<chemin>`** (même encodage que
|
||||
`#file=` : `quote` de « vault:chemin », `:` littéral séparateur,
|
||||
chaque segment décodé par `decodeURIComponent`). Aucun
|
||||
changement à la forme `#file=` ni au contrat des autres apps.
|
||||
- **Atterrissage** (`frontend/js/app.js`, init, après le chargement
|
||||
des vaults) : le fragment `#folder=` est reconnu à côté de
|
||||
`#file=` ; le vault est chargé, l'arborescence latérale est
|
||||
**dépliée jusqu'au dossier** et celui-ci est **sélectionné et
|
||||
mis en évidence** — via `Sidebar.focusPathInSidebar(vault, path,
|
||||
{ alignToTop: true, expandTarget: true })`, le mécanisme déjà
|
||||
utilisé par la recherche et l'historique (déplie chaque segment,
|
||||
charge les répertoires paresseusement, pose la classe
|
||||
`path-selected`, fait défiler jusqu'à l'élément).
|
||||
- **Comportement propre sur cible manquée** : vault absent,
|
||||
chemin inconnu ou fragment illisible → aucun élément n'est
|
||||
sélectionné et l'accueil s'affiche comme sans fragment — pas
|
||||
d'erreur bloquante, pas de toast. Un **fichier** passé à la
|
||||
forme dossier est simplement localisé et mis en évidence dans
|
||||
l'arbre (pas d'ouverture forcée).
|
||||
|
||||
## Tests
|
||||
|
||||
- Spec E2E `tests/e2e/deep-link-folder.spec.js` : atterrissage
|
||||
`#folder=` sur un dossier emboîté (arbre déplié, dossier
|
||||
sélectionné), repli accueil sur vault inconnu, et non-régression
|
||||
`#file=` (le fichier s'ouvre toujours dans le viewer).
|
||||
- Vérifications locales du workflow (pytest, ruff, mypy, tests
|
||||
frontend) : aucun nouvel échec par rapport à l'arbre vierge.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Performance du chargement initial — épopée #240
|
||||
|
||||
> Demande de Bruno (2026-11-30). Audit complet : rapport du 2026-11-30
|
||||
> (mesures en direct sur la prod 2.97.0). Issues Gitea : épopée #106,
|
||||
> lots #107 à #111.
|
||||
|
||||
## Baseline (2026-11-30, prod 2.97.0 + fichiers du dépôt)
|
||||
|
||||
- TTFB médian 0,36–0,67 s ; `/`, `/sso/login` et `/healthz` servent la
|
||||
même SPA de 333 809 o.
|
||||
- Graphe ES statique depuis `frontend/js/app.js` : **41 modules,
|
||||
1 420 963 o bruts** (mesure locale, `scripts/audit_chargement.py
|
||||
--local` ; la mesure prod donnait 1 406 497 o), zéro `import()`
|
||||
dynamique dans le point d'entrée.
|
||||
- Mermaid (CDN jsdelivr) : 745 043 o au fil, chargé d'emblée ;
|
||||
highlight.js + 11 langages (cdnjs) et Lucide (unpkg) aussi dans le
|
||||
`<head>`.
|
||||
- Statiques sans URL versionnées : `cf-cache-status` MISS/DYNAMIC,
|
||||
`Cache-Control: max-age=30` constaté en prod.
|
||||
- Démarrage : `Promise.all([loadVaultSettings, loadVaults, loadTags])`
|
||||
avant l'ouverture du fichier d'un lien profond `#file=`/`#folder=`.
|
||||
- `GET /api/dashboard` recalcule les totaux (10 987 fichiers) à chaque
|
||||
appel, sans cache.
|
||||
|
||||
## Budget figé (#241)
|
||||
|
||||
| Indicateur | Cible |
|
||||
|---|---|
|
||||
| Premier affichage utile (connexion initiale) | ÷ ~3 vs baseline |
|
||||
| JS initial parsé (graphe statique local) | −50 % au moins |
|
||||
| 2ᵉ visite | zéro re-téléchargement des statiques versionnées (`?v=`) |
|
||||
| `/api/dashboard` répété | < 50 ms à chaud (cache) |
|
||||
| Lien profond `#file=`/`#folder=` | cible lisible avant la fin du chargement complet |
|
||||
|
||||
## Mécanisme du cache versionné (#242)
|
||||
|
||||
Sans étape de build (règle du dépôt) :
|
||||
|
||||
1. **HTML** : `_index_html()` réécrit au service les URL
|
||||
`/static/…` de `index.html` en `/static/…?v=<VERSION>`
|
||||
(`backend/static_versioning.py`, VERSION = source unique).
|
||||
2. **Modules ES** : le serveur de statiques (`VersionedStaticFiles`)
|
||||
réécrit au service les spécificateurs d'import relatifs des
|
||||
fichiers `.js` en y ajoutant `?v=<VERSION>` — le navigateur ne
|
||||
connaît donc que des URL versionnées, de proche en proche.
|
||||
3. **En-têtes** : `Cache-Control: public, max-age=31536000, immutable`
|
||||
**uniquement** quand la requête porte `?v=<VERSION courante>` ;
|
||||
`no-cache` sinon, et toujours `no-cache` sur le HTML. Le piège
|
||||
historique (cache long sans versionnage → build périmé servi un an)
|
||||
est impossible : une nouvelle version change toutes les URL.
|
||||
4. **Service worker** : le nom de cache embarque la version servie
|
||||
(`__OBSIGATE_SW_VERSION__` remplacé par le backend à la route
|
||||
`/sw.js`) ; à l'activation, tout cache d'un autre nom est supprimé.
|
||||
|
||||
⚠️ **Hors code** : la règle Cloudflare qui ferait passer les statiques
|
||||
versionnées en `cf-cache-status: HIT` est une action d'exploitation
|
||||
(à faire au tableau de bord Cloudflare), elle n'est pas livrée par
|
||||
cette branche.
|
||||
|
||||
## Lots
|
||||
|
||||
- **#241 P0** — script d'audit versionné + ce budget. ✅
|
||||
- **#242 P1** — cache versionné (ci-dessus) + tests d'en-têtes et de
|
||||
non-régression « nouvelle version servie ». ✅
|
||||
- **#243 P2** — `import()` dynamique à la première utilisation
|
||||
(Mermaid, graphe, Excalidraw, now-playing, plugins, push, mobile-editor) et
|
||||
retrait des scripts CDN du `<head>` (highlight chargé au premier
|
||||
bloc de code, par langage ; Lucide chargé en différé non bloquant
|
||||
par `safeCreateIcons` ; Mermaid au premier diagramme).
|
||||
**Résultat mesuré (script --local)** : graphe statique 41 → **34 modules**,
|
||||
1 420 963 → **1 243 303 o (−12,5 %)** ; les **13 scripts CDN du `<head>`
|
||||
sont retirés** (Mermaid 745 Ko au fil, highlight + langages, Lucide),
|
||||
chargés à la demande — c'est le gain principal du lot sur le fil.
|
||||
Le budget « −50 % du graphe statique » n'est **pas** atteint : le cœur
|
||||
(viewer/ui/config/auth/sidebar, fortement couplés et circulaires)
|
||||
reste statique, de même que les modules XLSX de `viewer.js` et
|
||||
`filechat.js` (chat latéral câblé au démarrage par sidebar/config) —
|
||||
leur extraction exigerait de découper viewer.js lui-même, chantier
|
||||
séparé à ouvrir si Bruno le souhaite.
|
||||
- **#244 P3** — bootstrap : lien profond ouvert avant le chargement
|
||||
complet des vaults/tags/réglages. ✅ (`#file=` ouvert dès l'auth ;
|
||||
`#folder=` reste après `loadVaults`, son arborescence en dépend.)
|
||||
- **#245 P4** — cache mémoire 60 s de `/api/dashboard`, invalidé par
|
||||
le watcher ; GZip inchangé (SSE toujours exclu). ✅
|
||||
@@ -337,3 +337,31 @@
|
||||
color: var(--p-doux); font-size: 12.5px; margin-left: auto; text-align: right;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 46%;
|
||||
}
|
||||
|
||||
/* ── Mobile (retour de Bruno, 2026-11-28) ─────────────────────
|
||||
* Le panneau passe au-dessus des barres de l'hôte — une barre de
|
||||
* navigation mobile recouvrait le composer, illisible — et son
|
||||
* en-tête se compacte : bandeau de contexte réduit à l'essentiel,
|
||||
* actions et suggestions sur UNE rangée défilante au lieu de deux,
|
||||
* marges resserrées. La place revient aux messages et à la saisie. */
|
||||
@media (max-width: 700px) {
|
||||
.draco-panneau { z-index: 1000; }
|
||||
.draco-panneau-hd { padding: 9px 12px; }
|
||||
.draco-disc-bar { padding: 6px 12px; }
|
||||
.draco-contexte { padding: 6px 12px; gap: 7px; }
|
||||
.draco-contexte .dc-sous { display: none; }
|
||||
.draco-panneau-outils {
|
||||
flex-wrap: nowrap; overflow-x: auto; padding: 7px 12px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.draco-panneau-outils::-webkit-scrollbar { display: none; }
|
||||
.draco-panneau-outils button { flex: none; padding: 4px 10px; font-size: 12px; }
|
||||
.draco-puces {
|
||||
flex-wrap: nowrap; overflow-x: auto; justify-content: flex-start;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.draco-puces::-webkit-scrollbar { display: none; }
|
||||
.draco-puces button { flex: none; }
|
||||
.draco-panneau-msgs { padding: 10px 12px; }
|
||||
.draco-panneau-ft { padding: 8px 10px 9px; }
|
||||
}
|
||||
|
||||
@@ -63,20 +63,7 @@
|
||||
disabled
|
||||
/>
|
||||
<!-- defer: ne bloque pas le premier paint -->
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
||||
<!-- Langues highlight.js hors bundle "common" (enregistrement auto apres le core) -->
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dockerfile.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/powershell.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dos.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cmake.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dart.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/elixir.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/haskell.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/nginx.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/http.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/plaintext.min.js"></script>
|
||||
<script defer src="https://unpkg.com/[email protected]/dist/umd/lucide.min.js"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
|
||||
+58
-19
@@ -5,7 +5,11 @@
|
||||
import * as UI from './ui.js';
|
||||
import * as Utils from './utils.js';
|
||||
import { initI18n, t } from './i18n.js';
|
||||
import { initNowPlaying } from './now-playing.js';
|
||||
|
||||
// #243 : modules chargés paresseusement (import dynamique) à la première
|
||||
// utilisation ou en tâche de fond : graph, mermaid-viewer, now-playing,
|
||||
// mobile-editor, push, plugins — ils ne font plus partie du graphe statique.
|
||||
const _idle = window.requestIdleCallback || ((f) => setTimeout(f, 1200));
|
||||
|
||||
// Wire up AI toolbar toast (avoids circular import in utils.js)
|
||||
window._obsigateShowToast = UI.showToast;
|
||||
@@ -13,17 +17,12 @@ import * as Sidebar from './sidebar.js';
|
||||
import * as Auth from './auth.js';
|
||||
import * as Viewer from './viewer.js';
|
||||
import * as Sync from './sync.js';
|
||||
import { initGraphView } from './graph.js';
|
||||
import * as Legacy from './legacy.js';
|
||||
import { initCommandPalette } from './palette.js';
|
||||
import { initMobileToolbar } from './mobile-toolbar.js';
|
||||
import { initMobileEditor } from './mobile-editor.js';
|
||||
import { initDragDrop } from './dragdrop.js';
|
||||
import { initMermaid, setupFocusMode } from './mermaid-viewer.js';
|
||||
import PaneManager from './pane-manager.js';
|
||||
import { initDesktopIntegration, isTauriEnv } from './desktop.js';
|
||||
import { initPush } from './push.js';
|
||||
import { initPlugins } from './plugins.js';
|
||||
import { populateVersions } from './config.js';
|
||||
import { initSidebarChat } from './filechat.js';
|
||||
|
||||
@@ -74,25 +73,28 @@ async function init() {
|
||||
PaneManager.init();
|
||||
initCommandPalette();
|
||||
initMobileToolbar();
|
||||
initMobileEditor();
|
||||
initPush();
|
||||
initPlugins();
|
||||
import('./mobile-editor.js').then((m) => m.initMobileEditor()).catch(() => {});
|
||||
import('./push.js').then((m) => m.initPush()).catch(() => {});
|
||||
import('./plugins.js').then((m) => m.initPlugins()).catch(() => {});
|
||||
|
||||
if (authOk) {
|
||||
Legacy.initSyncStatus();
|
||||
|
||||
try {
|
||||
await Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()]);
|
||||
|
||||
initDragDrop();
|
||||
|
||||
Legacy.DashboardRecentWidget.init();
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
if (urlParams.get("popup") === "true") {
|
||||
document.body.classList.add("popup-mode");
|
||||
}
|
||||
|
||||
// #244 (P3) : bootstrap rapide des liens profonds — un lien
|
||||
// ``#file=`` (y compris à l'arrivée d'un retour SSO) est ouvert
|
||||
// AVANT le chargement complet (réglages des vaults, liste des
|
||||
// vaults, tags) : ``openFile`` ne dépend que de l'auth, déjà
|
||||
// faite. Le reste charge ensuite, sans rouvrir ni écraser la
|
||||
// cible (``fichierOuvert`` garde la suite). ``#folder=`` reste
|
||||
// après le chargement : ``focusPathInSidebar`` a besoin de
|
||||
// l'arborescence rendue par ``loadVaults``.
|
||||
let fichierOuvert = false;
|
||||
if (window.location.hash && window.location.hash.startsWith("#file=")) {
|
||||
const hashVal = window.location.hash.substring(6);
|
||||
const sepIndex = hashVal.indexOf(":");
|
||||
@@ -100,6 +102,42 @@ async function init() {
|
||||
const vault = decodeURIComponent(hashVal.substring(0, sepIndex));
|
||||
const path = decodeURIComponent(hashVal.substring(sepIndex + 1));
|
||||
Viewer.openFile(vault, path);
|
||||
fichierOuvert = true;
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()]);
|
||||
|
||||
initDragDrop();
|
||||
|
||||
Legacy.DashboardRecentWidget.init();
|
||||
|
||||
if (fichierOuvert) {
|
||||
// Cible déjà ouverte par le bootstrap rapide : ne pas la
|
||||
// recouvrir par l'accueil.
|
||||
} else if (window.location.hash && window.location.hash.startsWith("#folder=")) {
|
||||
// #239 : lien profond « dossier » (émis par la console Spark,
|
||||
// forme sœur de #file= : « #folder=<vault>:<chemin> »). Un
|
||||
// répertoire ne s'ouvre pas dans le viewer : on déplie
|
||||
// l'arborescence latérale jusqu'à lui et on le met en
|
||||
// évidence (focusPathInSidebar). Cible inconnue, vault
|
||||
// absent ou fragment illisible : repli propre sur
|
||||
// l'accueil — jamais d'erreur bloquante.
|
||||
let cibleAtteinte = false;
|
||||
try {
|
||||
const hashVal = window.location.hash.substring(8);
|
||||
const sepIndex = hashVal.indexOf(":");
|
||||
if (sepIndex > -1) {
|
||||
const vault = decodeURIComponent(hashVal.substring(0, sepIndex));
|
||||
const path = decodeURIComponent(hashVal.substring(sepIndex + 1));
|
||||
await Sidebar.focusPathInSidebar(vault, path, { alignToTop: true, expandTarget: true });
|
||||
cibleAtteinte = !!document.querySelector(".tree-item.path-selected");
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Lien dossier illisible :", err);
|
||||
}
|
||||
if (!cibleAtteinte && urlParams.get("popup") !== "true") {
|
||||
Legacy.showWelcome();
|
||||
}
|
||||
} else if (urlParams.get("popup") !== "true") {
|
||||
Legacy.showWelcome();
|
||||
@@ -110,11 +148,12 @@ async function init() {
|
||||
}
|
||||
}
|
||||
|
||||
initGraphView();
|
||||
initMermaid();
|
||||
setupFocusMode();
|
||||
// #243 : graphe, mermaid (mode focus) et lecteur média en différé —
|
||||
// aucun de ces modules n'est nécessaire au premier affichage.
|
||||
_idle(() => { import('./graph.js').then((m) => m.initGraphView()).catch(() => {}); });
|
||||
_idle(() => { import('./mermaid-viewer.js').then((m) => m.setupFocusMode()).catch(() => {}); });
|
||||
Utils.safeCreateIcons();
|
||||
initNowPlaying();
|
||||
_idle(() => { import('./now-playing.js').then((m) => m.initNowPlaying()).catch(() => {}); });
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
|
||||
+68
-4
@@ -375,6 +375,7 @@ function renderDetail(host) {
|
||||
[t('coffres.type'), s.type],
|
||||
[t('coffres.service'), s.service || '—'],
|
||||
[t('coffres.note'), s.note || '—'],
|
||||
[t('coffres.console_spark'), s.console_spark ? t('common.yes') : t('common.no')],
|
||||
[t('coffres.status'), statutSecret(s)],
|
||||
[t('coffres.expires'), s.expiration ? fmtDate(s.expiration) : '—'],
|
||||
[t('coffres.version'), String(s.version)],
|
||||
@@ -394,6 +395,7 @@ function renderDetail(host) {
|
||||
host.appendChild(dl);
|
||||
const actions = el('div', { class: 'coffres-actions' }, []);
|
||||
actions.appendChild(modalBtn(t('coffres.copy_reference'), '', () => copyText(s.reference)));
|
||||
actions.appendChild(modalBtn(t('common.edit'), '', () => openEditSecretModal(s)));
|
||||
actions.appendChild(modalBtn(t('coffres.rotation'), 'primary', () => openRotationModal(s)));
|
||||
actions.appendChild(modalBtn(t('coffres.acces'), '', () => {
|
||||
document.getElementById('coffres-acces')?.scrollIntoView({ behavior: 'smooth' });
|
||||
@@ -439,7 +441,7 @@ function renderDetail(host) {
|
||||
if (!oct.length) host.appendChild(text('p', '—', 'coffres-empty'));
|
||||
oct.forEach((o) => {
|
||||
const line = el('div', { class: 'coffres-line' }, []);
|
||||
line.appendChild(text('span', `${o.cible_type} ${o.cible_id} — ${o.statut}${o.secret_id ? '' : ` (${t('coffres.grant_all_coffre')})`} — ${o.expiration ? fmtDate(o.expiration) : t('coffres.octroi_no_expiration')}`));
|
||||
line.appendChild(text('span', `${o.cible_type} ${o.cible_id} — ${o.statut}${o.secret_id ? '' : ` (${t('coffres.grant_all_coffre')})`}${o.origine === 'console_spark' ? ` — ${t('coffres.origine_console_spark')}` : ''} — ${o.expiration ? fmtDate(o.expiration) : t('coffres.octroi_no_expiration')}`));
|
||||
const btn = modalBtn(t('coffres.revoke'), 'danger', async () => {
|
||||
await revoquerOctroi(o.id);
|
||||
});
|
||||
@@ -475,7 +477,11 @@ function renderTable(host) {
|
||||
secrets.forEach((s) => {
|
||||
const tr = el('tr', {}, []);
|
||||
const add = (v) => tr.appendChild(el('td', {}, [document.createTextNode(v)]));
|
||||
add(s.nom);
|
||||
const tdNom = el('td', {}, [document.createTextNode(s.nom)]);
|
||||
if (s.console_spark) {
|
||||
tdNom.appendChild(text('span', t('coffres.console_spark'), 'coffres-spark-badge'));
|
||||
}
|
||||
tr.appendChild(tdNom);
|
||||
add(s.service || '—');
|
||||
add(s.type);
|
||||
add(fmtDate(s.modifie_le));
|
||||
@@ -599,7 +605,7 @@ function renderAcces(host) {
|
||||
? (viewState.secrets.find((s) => s.id === o.secret_id) || {}).nom || o.secret_id
|
||||
: t('coffres.grant_all_coffre');
|
||||
const line = el('div', { class: 'coffres-line' }, []);
|
||||
line.appendChild(text('span', `${o.cible_type} ${o.cible_id} — ${secretNom} — ${o.statut} — ${o.expiration ? fmtDate(o.expiration) : t('coffres.octroi_no_expiration')}`));
|
||||
line.appendChild(text('span', `${o.cible_type} ${o.cible_id} — ${secretNom} — ${o.statut}${o.origine === 'console_spark' ? ` — ${t('coffres.origine_console_spark')}` : ''} — ${o.expiration ? fmtDate(o.expiration) : t('coffres.octroi_no_expiration')}`));
|
||||
if (o.statut === 'actif') {
|
||||
line.appendChild(modalBtn(t('coffres.revoke'), 'danger', () => revoquerOctroi(o.id)));
|
||||
}
|
||||
@@ -659,6 +665,7 @@ function openCreateSecretModal(prefillSlug) {
|
||||
genBtn.disabled = typeSelect.value === 'certificate';
|
||||
});
|
||||
const err = errorBox();
|
||||
const sparkCheck = el('input', { type: 'checkbox' }, []);
|
||||
const grantCheck = el('input', { type: 'checkbox' }, []);
|
||||
const grantCibleType = selectInput(CIBLES_OCTROI.map((v) => [v, v]), 'consommateur');
|
||||
const grantCibleId = textInput('', t('coffres.target_id'));
|
||||
@@ -677,6 +684,7 @@ function openCreateSecretModal(prefillSlug) {
|
||||
field(t('coffres.note'), noteInput, t('coffres.never_in_note')),
|
||||
field(t('coffres.value'), valeur.wrap),
|
||||
el('div', { class: 'coffres-actions' }, [genBtn, copyGenBtn]),
|
||||
field(t('coffres.console_spark'), sparkCheck, t('coffres.console_spark_hint')),
|
||||
field(t('coffres.propose_octroi'), grantCheck),
|
||||
grantWrap,
|
||||
err.el,
|
||||
@@ -694,9 +702,10 @@ function openCreateSecretModal(prefillSlug) {
|
||||
valeur: valeur.value,
|
||||
service: serviceInput.value.trim(),
|
||||
note: noteInput.value.trim(),
|
||||
console_spark: sparkCheck.checked,
|
||||
};
|
||||
if (expirationInput.value) payload.expiration = expirationInput.value;
|
||||
await api(`/api/coffres/${encodeURIComponent(slug)}/secrets`, {
|
||||
const cree = await api(`/api/coffres/${encodeURIComponent(slug)}/secrets`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
@@ -718,6 +727,7 @@ function openCreateSecretModal(prefillSlug) {
|
||||
}
|
||||
m.close();
|
||||
showToast(t('coffres.saved'), 'success');
|
||||
avertissementSpark(cree);
|
||||
notifyChanged();
|
||||
await openCoffresView(slug);
|
||||
} catch (e) {
|
||||
@@ -728,6 +738,60 @@ function openCreateSecretModal(prefillSlug) {
|
||||
valeur.focus();
|
||||
}
|
||||
|
||||
/** Signale, après l'enregistrement d'un secret, un consommateur Spark
|
||||
* absent ou ambigu : la destination est posée mais l'octroi
|
||||
* automatique n'a pas été créé (réponse console_spark_octroi, #102). */
|
||||
function avertissementSpark(reponse) {
|
||||
const resultat = reponse && reponse.console_spark_octroi;
|
||||
if (resultat === 'consommateur_introuvable') {
|
||||
showToast(t('coffres.console_spark_introuvable'), 'error');
|
||||
} else if (resultat === 'consommateur_ambigu') {
|
||||
showToast(t('coffres.console_spark_ambigu'), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function openEditSecretModal(s) {
|
||||
const slug = s.reference.split('/')[0].slice(7);
|
||||
const serviceInput = textInput(s.service || '', 'Gitea');
|
||||
const noteInput = textInput(s.note || '', '');
|
||||
const expirationInput = el('input', { class: 'modal-input', type: 'date' }, []);
|
||||
if (s.expiration) expirationInput.value = String(s.expiration).slice(0, 10);
|
||||
const sparkCheck = el('input', { type: 'checkbox' }, []);
|
||||
sparkCheck.checked = !!s.console_spark;
|
||||
const err = errorBox();
|
||||
const body = el('div', {}, [
|
||||
field(t('coffres.name'), (() => { const i = textInput(s.nom, ''); i.disabled = true; return i; })()),
|
||||
field(t('coffres.service'), serviceInput),
|
||||
field(t('coffres.expiration'), expirationInput),
|
||||
field(t('coffres.note'), noteInput, t('coffres.never_in_note')),
|
||||
field(t('coffres.console_spark'), sparkCheck, t('coffres.console_spark_hint')),
|
||||
err.el,
|
||||
]);
|
||||
const m = openModal(t('coffres.edit_secret_title'), body, [
|
||||
modalBtn(t('common.cancel'), '', () => m.close()),
|
||||
modalBtn(t('coffres.save'), 'primary', async () => {
|
||||
try {
|
||||
const reponse = await api(`/api/coffres/${encodeURIComponent(slug)}/secrets/${encodeURIComponent(s.nom)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({
|
||||
service: serviceInput.value.trim(),
|
||||
note: noteInput.value.trim(),
|
||||
expiration: expirationInput.value || null,
|
||||
console_spark: sparkCheck.checked,
|
||||
}),
|
||||
});
|
||||
m.close();
|
||||
showToast(t('coffres.updated'), 'success');
|
||||
avertissementSpark(reponse);
|
||||
notifyChanged();
|
||||
await openCoffresView(slug);
|
||||
} catch (e) {
|
||||
err.show(e.message || t('common.error'));
|
||||
}
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
function openRotationModal(s) {
|
||||
const valeur = valeurField(s.type);
|
||||
const err = errorBox();
|
||||
|
||||
@@ -15,9 +15,26 @@ import { safeCreateIcons } from './utils.js';
|
||||
var _mermaidReady = false;
|
||||
var _currentTheme = 'default';
|
||||
|
||||
let _mermaidLoadPromise = null;
|
||||
export function ensureMermaid() {
|
||||
// #243 : Mermaid (745 Ko au fil) n'est plus chargé dans le <head> ;
|
||||
// il arrive au premier diagramme rencontré.
|
||||
if (typeof mermaid !== 'undefined') return Promise.resolve(true);
|
||||
if (!_mermaidLoadPromise) {
|
||||
_mermaidLoadPromise = new Promise((resolve) => {
|
||||
const el = document.createElement('script');
|
||||
el.src = 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js';
|
||||
el.onload = () => resolve(typeof mermaid !== 'undefined');
|
||||
el.onerror = () => resolve(false);
|
||||
document.head.appendChild(el);
|
||||
});
|
||||
}
|
||||
return _mermaidLoadPromise;
|
||||
}
|
||||
|
||||
export function initMermaid() {
|
||||
if (typeof mermaid === 'undefined') {
|
||||
console.warn('[Mermaid] library not loaded');
|
||||
ensureMermaid().then((ok) => { if (ok) initMermaid(); });
|
||||
return;
|
||||
}
|
||||
mermaid.initialize(_getMermaidConfig(_currentTheme === 'dark'));
|
||||
@@ -235,7 +252,12 @@ export var MERMAID_TEMPLATES = {
|
||||
var _renderCounter = 0;
|
||||
|
||||
export async function renderMermaidBlocks(container) {
|
||||
if (!_mermaidReady || typeof mermaid === 'undefined') return;
|
||||
if (typeof mermaid === 'undefined') {
|
||||
const ok = await ensureMermaid();
|
||||
if (!ok) return;
|
||||
}
|
||||
if (!_mermaidReady) initMermaid();
|
||||
if (!_mermaidReady) return;
|
||||
|
||||
var blocks = container.querySelectorAll('pre code.language-mermaid, .mermaid-code');
|
||||
if (blocks.length === 0) return;
|
||||
|
||||
@@ -8,7 +8,6 @@ import { _getEffective } from './config.js';
|
||||
import { TabManager, showToast } from './ui.js';
|
||||
import { addTagFilter, buildSearchResultsHeader, shouldDisplayPath, removeTagFilter, TagFilterService } from './sidebar.js';
|
||||
import { t } from './i18n.js';
|
||||
import { onSearchFilter } from './plugins.js';
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search History Service (localStorage, LIFO, max 50, dedup)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -826,6 +825,7 @@ export async function performAdvancedSearch(query, vaultFilter, tagFilter, offse
|
||||
semBtn.classList.toggle("active", state.semanticSearch);
|
||||
}
|
||||
// Plugin hook: filter search results
|
||||
const { onSearchFilter } = await import('./plugins.js'); // #243 paresseux
|
||||
data.results = await onSearchFilter(state.vault || "default", query, data.results);
|
||||
renderAdvancedSearchResults(data, query, tagFilter);
|
||||
} catch (err) {
|
||||
|
||||
@@ -690,6 +690,10 @@ export async function refreshSidebarTreePreservingState() {
|
||||
|
||||
const expandedDirs = Array.from(document.querySelectorAll(".tree-item[data-path]"))
|
||||
.filter((item) => {
|
||||
// BUG-132 : les nœuds virtuels (Secrets, coffres) n'ont pas de
|
||||
// répertoire physique — les recharger par /api/browse produit un
|
||||
// 404 « Path not found » affiché en toast à chaque rafraîchissement.
|
||||
if ((item.dataset.type || "").startsWith("virtual")) return false;
|
||||
const vault = item.dataset.vault;
|
||||
const path = item.dataset.path;
|
||||
const children = document.getElementById(`dir-${vault}-${path}`);
|
||||
|
||||
+1
-2
@@ -4,7 +4,6 @@ import { state } from './state.js';
|
||||
import { openFile, showWelcome, renderFile, renderImageViewer, el } from './viewer.js';
|
||||
import { safeCreateIcons, getFileIcon, escapeHtml, detachInlineEditor } from './utils.js';
|
||||
import { syncActiveFileTreeItem, refreshSidebarTreePreservingState } from './sidebar.js';
|
||||
import { GraphViewManager } from './graph.js';
|
||||
import { DashboardConflictsWidget } from './dashboard.js';
|
||||
import { t, tr } from './i18n.js';
|
||||
import { toggleThemeMode } from './themes.js';
|
||||
@@ -1799,7 +1798,7 @@ export const ContextMenuManager = {
|
||||
|
||||
// Graph view — available for all types
|
||||
const graphPath = type === 'vault' ? '' : path;
|
||||
this._addItem('git-graph', 'Vue Graphique', () => GraphViewManager.open(vault, graphPath, type), false);
|
||||
this._addItem('git-graph', 'Vue Graphique', () => { import('./graph.js').then((m) => m.GraphViewManager.open(vault, graphPath, type)).catch(() => {}); }, false); // #243 graphe paresseux
|
||||
|
||||
this._addSeparator();
|
||||
|
||||
|
||||
+49
-1
@@ -290,8 +290,48 @@ let _iconDebounceTimer = null;
|
||||
* Debounced icon creation — batches multiple rapid calls into one
|
||||
* DOM scan to avoid excessive reflows when building large trees.
|
||||
*/
|
||||
// ---------------------------------------------------------------------------
|
||||
// Chargement paresseux des CDN (#243) : Lucide et highlight.js ne sont plus
|
||||
// chargés dans le <head> — ils arrivent à la première utilisation.
|
||||
// ---------------------------------------------------------------------------
|
||||
const _scriptPromises = {};
|
||||
function _loadScriptOnce(src) {
|
||||
if (!_scriptPromises[src]) {
|
||||
_scriptPromises[src] = new Promise((resolve) => {
|
||||
const el = document.createElement("script");
|
||||
el.src = src;
|
||||
el.onload = () => resolve(true);
|
||||
el.onerror = () => resolve(false);
|
||||
document.head.appendChild(el);
|
||||
});
|
||||
}
|
||||
return _scriptPromises[src];
|
||||
}
|
||||
|
||||
function ensureLucide() {
|
||||
if (typeof lucide !== "undefined" && lucide.createIcons) return Promise.resolve(true);
|
||||
return _loadScriptOnce("https://unpkg.com/[email protected]/dist/umd/lucide.min.js")
|
||||
.then((ok) => ok && typeof lucide !== "undefined" && !!lucide.createIcons);
|
||||
}
|
||||
|
||||
const HLJS_BASE = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0";
|
||||
function ensureHighlight(lang) {
|
||||
if (typeof hljs !== "undefined" && hljs.highlightElement) return Promise.resolve(true);
|
||||
return _loadScriptOnce(`${HLJS_BASE}/highlight.min.js`).then(async (ok) => {
|
||||
if (!ok || typeof hljs === "undefined") return false;
|
||||
if (lang && hljs.getLanguage && !hljs.getLanguage(lang)) {
|
||||
await _loadScriptOnce(`${HLJS_BASE}/languages/${lang}.min.js`);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function safeCreateIcons() {
|
||||
if (typeof lucide === "undefined" || !lucide.createIcons) return;
|
||||
if (typeof lucide === "undefined" || !lucide.createIcons) {
|
||||
// #243 : charger Lucide en différé, puis rejouer la création d'icônes.
|
||||
ensureLucide().then((ok) => { if (ok) safeCreateIcons(); });
|
||||
return;
|
||||
}
|
||||
if (state._iconDebounceTimer) return; // already scheduled
|
||||
state._iconDebounceTimer = requestAnimationFrame(() => {
|
||||
state._iconDebounceTimer = null;
|
||||
@@ -321,6 +361,12 @@ function flushIcons() {
|
||||
function safeHighlight(block) {
|
||||
// Skip mermaid blocks — they're rendered by Mermaid.js, not highlighted
|
||||
if (block.className && block.className.indexOf('language-mermaid') !== -1) return;
|
||||
if (typeof hljs === "undefined" || !hljs.highlightElement) {
|
||||
// #243 : charger highlight.js (base + langage détecté) puis recolorer.
|
||||
const mLang = /\blanguage-([\w-]+)/.exec(block.className || "");
|
||||
ensureHighlight(mLang ? mLang[1] : null).then((ok) => { if (ok) safeHighlight(block); });
|
||||
return;
|
||||
}
|
||||
if (typeof hljs !== "undefined" && hljs.highlightElement) {
|
||||
try {
|
||||
// Alias pour les extensions que highlight.js (bundle common) ne connaît pas
|
||||
@@ -965,6 +1011,8 @@ function copyToClipboard(text) {
|
||||
export {
|
||||
getFileIcon,
|
||||
safeCreateIcons,
|
||||
ensureLucide,
|
||||
ensureHighlight,
|
||||
flushIcons,
|
||||
safeHighlight,
|
||||
escapeHtml,
|
||||
|
||||
+16
-15
@@ -7,15 +7,10 @@ import { TabManager, closeMobileSidebar, ContextMenuManager, RightSidebarManager
|
||||
import { syncActiveFileTreeItem, searchByTag, TagFilterService, refreshSidebarTreePreservingState, focusPathInSidebar } from './sidebar.js';
|
||||
import { AutocompleteDropdown, performAdvancedSearch } from './search.js';
|
||||
import { initDashboardTabs } from './sync.js';
|
||||
import { renderMermaidBlocks } from './mermaid-viewer.js';
|
||||
import { renderExcalidraw } from './excalidraw-viewer.js';
|
||||
import { DashboardStatsWidget, DashboardRecentWidget, DashboardBookmarkWidget, DashboardSharedWidget, DashboardConflictsWidget } from './dashboard.js';
|
||||
import { openShareDialog } from './config.js';
|
||||
import { cacheViewedFile, getCachedFile } from './offline.js';
|
||||
import { t, getLocale } from './i18n.js';
|
||||
import { onFileRender } from './plugins.js';
|
||||
import { NowPlaying } from './now-playing.js';
|
||||
import { toggleFileChat, followFileChat } from './filechat.js';
|
||||
import { parseRef, columnName, findTd, invalidateCellIndex, sheetOfRef, firstCellOfRange } from './xlsx/refs.js';
|
||||
import { createColourPicker } from './xlsx/color-picker.js';
|
||||
import { buildCommandBar } from './xlsx/command-bar.js';
|
||||
@@ -27,6 +22,13 @@ import {
|
||||
colToIndex, indexToCol,
|
||||
} from './xlsx/formula.js';
|
||||
|
||||
// #243 : modules lourds chargés à la première utilisation (le graphe
|
||||
// statique initial ne les contient plus) : mermaid, excalidraw, plugins,
|
||||
// now-playing (média), filechat.
|
||||
function _withNowPlaying(fn) {
|
||||
import('./now-playing.js').then((m) => { try { fn(m.NowPlaying); } catch (e) {} }).catch(() => {});
|
||||
}
|
||||
|
||||
// ── Multi-format export ────────────────────────────────────────────────────
|
||||
// Downloads a file export (HTML / MD bundle / ePub) via the authenticated
|
||||
// export endpoints, showing a loading toast while the request is in flight.
|
||||
@@ -1135,16 +1137,15 @@ export function renderImageViewer(area, data) {
|
||||
// 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);
|
||||
_withNowPlaying((np) => np.attachInline(area, data));
|
||||
}
|
||||
|
||||
/** Video viewer (roadmap #109-C, made persistent by #110). */
|
||||
export function renderVideoViewer(area, data) {
|
||||
NowPlaying.attachInline(area, data);
|
||||
_withNowPlaying((np) => np.attachInline(area, data));
|
||||
}
|
||||
|
||||
|
||||
@@ -6951,7 +6952,7 @@ export function renderFile(data) {
|
||||
// instead of being wiped mid-session by a tab switch / sidebar click.
|
||||
if (isInlineEditorActive()) detachInlineEditor();
|
||||
// #190 A — an open chat panel follows the document being rendered.
|
||||
followFileChat(data.vault, data.path, data.title);
|
||||
import('./filechat.js').then((m) => m.followFileChat(data.vault, data.path, data.title)).catch(() => {}); // #243
|
||||
// #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; }
|
||||
@@ -6965,7 +6966,7 @@ export function renderFile(data) {
|
||||
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);
|
||||
_withNowPlaying((np) => np.handleRender(area, data));
|
||||
|
||||
// Handle PDF files — render in iframe with TOC sidebar
|
||||
if (data.is_pdf) {
|
||||
@@ -7029,7 +7030,7 @@ export function renderFile(data) {
|
||||
|
||||
// Handle Excalidraw — render in iframe editor
|
||||
if (data.is_excalidraw) {
|
||||
renderExcalidraw(area, data, data.vault, data.path);
|
||||
import('./excalidraw-viewer.js').then((m) => m.renderExcalidraw(area, data, data.vault, data.path)).catch(() => {}); // #243
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -7257,7 +7258,7 @@ export function renderFile(data) {
|
||||
// #169 — Chat intégré par fichier (panneau latéral)
|
||||
const chatBtn = el("button", { class: "btn-action btn-chat", title: t("chat.button_title") }, [icon("message-square", 14), document.createTextNode(t("chat.button"))]);
|
||||
chatBtn.addEventListener("click", () => {
|
||||
toggleFileChat(data.vault, data.path, data.title);
|
||||
import('./filechat.js').then((m) => m.toggleFileChat(data.vault, data.path, data.title)).catch(() => {}); // #243
|
||||
});
|
||||
// Check bookmark status and color the button
|
||||
(async () => {
|
||||
@@ -7419,7 +7420,7 @@ export function renderFile(data) {
|
||||
});
|
||||
|
||||
// Render Mermaid diagrams
|
||||
renderMermaidBlocks(area);
|
||||
import('./mermaid-viewer.js').then((m) => m.renderMermaidBlocks(area)).catch(() => {}); // #243
|
||||
|
||||
// Wire up wikilinks
|
||||
area.querySelectorAll(".wikilink").forEach((link) => {
|
||||
@@ -7458,7 +7459,7 @@ export function renderFile(data) {
|
||||
// content or append custom widgets beneath it. Async + non-blocking so a
|
||||
// slow/failed plugin never delays the normal file render.
|
||||
if (data.content && data.is_markdown) {
|
||||
onFileRender(data.vault, data.content, data.path).then((fr) => {
|
||||
import('./plugins.js').then((m) => m.onFileRender(data.vault, data.content, data.path)).then((fr) => { // #243
|
||||
if (!fr) return;
|
||||
if (typeof fr.replace === 'string' && fr.replace !== data.content) {
|
||||
const rendered = document.getElementById('file-rendered-content');
|
||||
@@ -7752,7 +7753,7 @@ 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);
|
||||
_withNowPlaying((np) => np.handleRender(area, null));
|
||||
const home = document.getElementById("dashboard-home");
|
||||
|
||||
if (area && !home) {
|
||||
|
||||
@@ -2440,6 +2440,10 @@
|
||||
"coffres.confirm_revoke_consumer": "Revoke this consumer? All of its distributions will be denied.",
|
||||
"coffres.confirm_revoke_octroi": "Revoke this grant? Access will be denied on the next call.",
|
||||
"coffres.consumer_no_distribution": "No distribution in the recent log.",
|
||||
"coffres.console_spark": "Spark Console",
|
||||
"coffres.console_spark_ambigu": "Secret saved, but several active consumers are named “spark”: the automatic grant was not created, to avoid granting the wrong consumer. Save the secret again after resolving the duplicate.",
|
||||
"coffres.console_spark_hint": "The secret becomes available as a key in the Spark console.",
|
||||
"coffres.console_spark_introuvable": "Secret saved, but no active “spark” consumer exists: the automatic grant was not created. Create the Spark consumer (Access and consumers), then save the secret again.",
|
||||
"coffres.consumers": "Consumers",
|
||||
"coffres.copied": "Copied.",
|
||||
"coffres.copy_failed": "Copy failed.",
|
||||
@@ -2458,6 +2462,7 @@
|
||||
"coffres.description": "Description",
|
||||
"coffres.detail": "Details",
|
||||
"coffres.disabled": "Secret vaults are disabled on this instance (OBSIGATE_SECRETS_ENABLED).",
|
||||
"coffres.edit_secret_title": "Edit secret",
|
||||
"coffres.expiration": "Expiration",
|
||||
"coffres.expired": "Expired",
|
||||
"coffres.expires": "Expires",
|
||||
@@ -2496,6 +2501,7 @@
|
||||
"coffres.octroi_no_expiration": "No expiration",
|
||||
"coffres.octroi_revoked": "Grant revoked.",
|
||||
"coffres.octrois": "Grants",
|
||||
"coffres.origine_console_spark": "Spark Console destination",
|
||||
"coffres.perimetre": "Scope",
|
||||
"coffres.propose_octroi": "Propose a grant (optional)",
|
||||
"coffres.reference": "Reference",
|
||||
@@ -2523,6 +2529,7 @@
|
||||
"coffres.token_once": "Token (shown only once)",
|
||||
"coffres.token_once_hint": "Copy it now: it will never be shown again.",
|
||||
"coffres.type": "Type",
|
||||
"coffres.updated": "Secret updated.",
|
||||
"coffres.value": "Value",
|
||||
"coffres.value_required": "A value is required.",
|
||||
"coffres.version": "Version",
|
||||
|
||||
@@ -2440,6 +2440,10 @@
|
||||
"coffres.confirm_revoke_consumer": "Révoquer ce consommateur ? Toutes ses distributions seront refusées.",
|
||||
"coffres.confirm_revoke_octroi": "Révoquer cet octroi ? L'accès sera refusé dès le prochain appel.",
|
||||
"coffres.consumer_no_distribution": "Aucune distribution dans le journal récent.",
|
||||
"coffres.console_spark": "Console Spark",
|
||||
"coffres.console_spark_ambigu": "Secret enregistré, mais plusieurs consommateurs actifs portent le nom « spark » : l'octroi automatique n'a pas été créé, pour éviter toute erreur de destinataire. Réenregistrez le secret après avoir réglé le doublon.",
|
||||
"coffres.console_spark_hint": "Le secret devient disponible comme clé dans la console Spark.",
|
||||
"coffres.console_spark_introuvable": "Secret enregistré, mais aucun consommateur « spark » actif n'existe : l'octroi automatique n'a pas été créé. Créez le consommateur Spark (Accès et consommateurs), puis réenregistrez le secret.",
|
||||
"coffres.consumers": "Consommateurs",
|
||||
"coffres.copied": "Copié.",
|
||||
"coffres.copy_failed": "Copie impossible.",
|
||||
@@ -2458,6 +2462,7 @@
|
||||
"coffres.description": "Description",
|
||||
"coffres.detail": "Détail",
|
||||
"coffres.disabled": "Les coffres de secrets sont désactivés sur cette instance (OBSIGATE_SECRETS_ENABLED).",
|
||||
"coffres.edit_secret_title": "Modifier le secret",
|
||||
"coffres.expiration": "Expiration",
|
||||
"coffres.expired": "Expiré",
|
||||
"coffres.expires": "Expire",
|
||||
@@ -2496,6 +2501,7 @@
|
||||
"coffres.octroi_no_expiration": "Sans expiration",
|
||||
"coffres.octroi_revoked": "Octroi révoqué.",
|
||||
"coffres.octrois": "Octrois",
|
||||
"coffres.origine_console_spark": "destination Console Spark",
|
||||
"coffres.perimetre": "Périmètre",
|
||||
"coffres.propose_octroi": "Proposer un octroi (optionnel)",
|
||||
"coffres.reference": "Référence",
|
||||
@@ -2523,6 +2529,7 @@
|
||||
"coffres.token_once": "Jeton (affiché une seule fois)",
|
||||
"coffres.token_once_hint": "Copiez-le maintenant : il ne sera plus jamais affiché.",
|
||||
"coffres.type": "Type",
|
||||
"coffres.updated": "Secret mis à jour.",
|
||||
"coffres.value": "Valeur",
|
||||
"coffres.value_required": "Une valeur est requise.",
|
||||
"coffres.version": "Version",
|
||||
|
||||
@@ -13663,6 +13663,7 @@ body.has-draco-bar .app-container { height: calc(100vh - 60px); }
|
||||
.coffres-icon-lock { display: inline-flex; align-items: center; line-height: 1; }
|
||||
.coffres-icon-lock svg { width: 16px; height: 16px; flex: none; }
|
||||
.coffres-alert-dot { color: var(--warning, #f59e0b); font-weight: 700; margin-left: 4px; }
|
||||
.coffres-spark-badge { color: var(--accent, #58a6ff); border: 1px solid var(--accent, #58a6ff); border-radius: 8px; padding: 0 6px; margin-left: 8px; font-size: 0.8em; white-space: nowrap; }
|
||||
.coffres-context-menu { position: fixed; z-index: 1000; min-width: 220px; background: var(--bg-secondary, #161b22); border: 1px solid var(--border, #21262d); border-radius: 8px; padding: 4px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4); }
|
||||
.coffres-context-item { display: block; width: 100%; text-align: left; padding: 8px 12px; background: transparent; border: none; color: var(--text-primary, #e6edf3); cursor: pointer; border-radius: 6px; }
|
||||
.coffres-context-item:hover { background: var(--bg-hover, #1f2430); }
|
||||
|
||||
+1
-1
@@ -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 = 'v29';
|
||||
const SW_VERSION = '__OBSIGATE_SW_VERSION__'; // remplacé au service par le backend (#242) ; repli statique : 'dev'
|
||||
const CODE_CACHE = `obsigate-code-${SW_VERSION}`;
|
||||
const RUNTIME_CACHE = `obsigate-runtime-${SW_VERSION}`;
|
||||
const API_CACHE = `obsigate-api-${SW_VERSION}`;
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "obsigate",
|
||||
"version": "2.95.4",
|
||||
"description": "**Porte d'entr\u00e9e web ultra-l\u00e9ger pour vos vaults Obsidian** \u2014 Acc\u00e9dez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.",
|
||||
"version": "2.98.0",
|
||||
"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": {
|
||||
"doc": "docs",
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit de chargement d'ObsiGate (#241, épopée perf #240).
|
||||
|
||||
Mesure, sans dépendance externe (stdlib seule) :
|
||||
|
||||
- en mode distant (défaut) : TTFB et temps total médians de ``/``,
|
||||
``/sso/login`` et des statiques clés, plus les en-têtes de cache
|
||||
(``Cache-Control``, ``cf-cache-status``, ``ETag``) ;
|
||||
- en mode ``--local`` : la baseline calculée depuis les fichiers du
|
||||
dépôt — graphe des modules ES **statiques** atteint depuis
|
||||
``frontend/js/app.js`` (nombre de modules + octets bruts, plus gros
|
||||
modules), taille de ``index.html`` / ``style.css`` et des statiques
|
||||
référencées par ``index.html``.
|
||||
|
||||
Le graphe local ne suit que les imports statiques (``import … from``,
|
||||
``export … from``, ``import '…'``) : un module chargé par ``import()``
|
||||
dynamique n'y compte pas — c'est exactement ce que le lot #243 cherche
|
||||
à réduire.
|
||||
|
||||
Usage :
|
||||
python3 scripts/audit_chargement.py [--base-url https://og.dracodev.net]
|
||||
python3 scripts/audit_chargement.py --local [RACINE_DU_DEPOT]
|
||||
python3 scripts/audit_chargement.py --local --json sortie.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Graphe de modules ES (mode local)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_STATIC_IMPORT_RE = re.compile(
|
||||
r"(?:^|[\n;])\s*(?:import\s+(?!\(\s*['\"])(?:[^'\"]*?\sfrom\s+)?|export\s+[^'\"]*?\sfrom\s+)['\"]([^'\"]+)['\"]"
|
||||
)
|
||||
|
||||
|
||||
def static_imports(source: str) -> list[str]:
|
||||
"""Spécificateurs relatifs importés statiquement par un module ES."""
|
||||
return [m.group(1) for m in _STATIC_IMPORT_RE.finditer(source)
|
||||
if m.group(1).startswith(".")]
|
||||
|
||||
|
||||
def resolve_spec(importer: Path, spec: str, root: Path) -> Path:
|
||||
"""Résoudre un spécificateur relatif par rapport à son importeur."""
|
||||
return (importer.parent / spec).resolve()
|
||||
|
||||
|
||||
def local_module_graph(frontend_dir: Path) -> dict:
|
||||
"""Graphe statique depuis ``js/app.js`` : compte + octets bruts."""
|
||||
entry = frontend_dir / "js" / "app.js"
|
||||
seen: dict[str, int] = {}
|
||||
queue: list[Path] = [entry]
|
||||
while queue:
|
||||
module = queue.pop()
|
||||
try:
|
||||
key = str(module.relative_to(frontend_dir))
|
||||
except ValueError:
|
||||
continue
|
||||
if key in seen or not module.is_file():
|
||||
continue
|
||||
source = module.read_text(encoding="utf-8", errors="replace")
|
||||
seen[key] = len(source.encode("utf-8"))
|
||||
for spec in static_imports(source):
|
||||
target = resolve_spec(module, spec, frontend_dir)
|
||||
if target.suffix == ".js":
|
||||
queue.append(target)
|
||||
top = sorted(seen.items(), key=lambda kv: -kv[1])[:10]
|
||||
return {
|
||||
"entry": "js/app.js",
|
||||
"module_count": len(seen),
|
||||
"raw_bytes": sum(seen.values()),
|
||||
"top_modules": [{"module": k, "bytes": v} for k, v in top],
|
||||
"modules": seen,
|
||||
}
|
||||
|
||||
|
||||
_STATIC_REF_RE = re.compile(r"(?:src|href)=\"(/static/[^\"]+)\"")
|
||||
_CDN_REF_RE = re.compile(
|
||||
r"(?:src|href)=\"(https://(?:cdnjs\.cloudflare\.com|unpkg\.com|cdn\.jsdelivr\.net)/[^\" ]+)\"")
|
||||
|
||||
|
||||
def local_baseline(repo_root: Path) -> dict:
|
||||
"""Baseline locale : graphe ES + poids des fichiers de la page."""
|
||||
frontend = repo_root / "frontend"
|
||||
index_html = (frontend / "index.html").read_text(encoding="utf-8", errors="replace")
|
||||
refs: dict[str, int] = {}
|
||||
for ref in _STATIC_REF_RE.findall(index_html):
|
||||
path = frontend / ref.removeprefix("/static/")
|
||||
if path.is_file():
|
||||
refs[ref] = path.stat().st_size
|
||||
return {
|
||||
"mode": "local",
|
||||
"index_html_bytes": (frontend / "index.html").stat().st_size,
|
||||
"style_css_bytes": (frontend / "style.css").stat().st_size,
|
||||
"module_graph": local_module_graph(frontend),
|
||||
"index_static_refs": refs,
|
||||
"index_static_refs_bytes": sum(refs.values()),
|
||||
"index_cdn_refs": sorted(set(_CDN_REF_RE.findall(index_html))),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mesures distantes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def measure_once(url: str) -> dict:
|
||||
"""Une mesure : TTFB (en-têtes reçus) et temps total (corps lu)."""
|
||||
parsed = urlparse(url)
|
||||
conn_cls = (http.client.HTTPSConnection if parsed.scheme == "https"
|
||||
else http.client.HTTPConnection)
|
||||
conn = conn_cls(parsed.netloc, timeout=30)
|
||||
path = parsed.path or "/"
|
||||
if parsed.query:
|
||||
path += "?" + parsed.query
|
||||
start = time.perf_counter()
|
||||
conn.request("GET", path, headers={"Accept-Encoding": "identity"})
|
||||
response = conn.getresponse()
|
||||
ttfb = time.perf_counter() - start
|
||||
body = response.read()
|
||||
total = time.perf_counter() - start
|
||||
headers = {k.lower(): v for k, v in response.getheaders()}
|
||||
conn.close()
|
||||
return {
|
||||
"status": response.status,
|
||||
"ttfb_s": round(ttfb, 3),
|
||||
"total_s": round(total, 3),
|
||||
"bytes": len(body),
|
||||
"cache_control": headers.get("cache-control"),
|
||||
"cf_cache_status": headers.get("cf-cache-status"),
|
||||
"etag": headers.get("etag"),
|
||||
}
|
||||
|
||||
|
||||
def measure(url: str, runs: int = 3) -> dict:
|
||||
"""Médianes de ``runs`` mesures d'une URL."""
|
||||
samples = [measure_once(url) for _ in range(runs)]
|
||||
return {
|
||||
"url": url,
|
||||
"runs": runs,
|
||||
"status": samples[0]["status"],
|
||||
"ttfb_median_s": statistics.median(s["ttfb_s"] for s in samples),
|
||||
"total_median_s": statistics.median(s["total_s"] for s in samples),
|
||||
"bytes": samples[0]["bytes"],
|
||||
"cache_control": samples[0]["cache_control"],
|
||||
"cf_cache_status": samples[0]["cf_cache_status"],
|
||||
"etag": samples[0]["etag"],
|
||||
"samples": samples,
|
||||
}
|
||||
|
||||
|
||||
DEFAULT_PATHS = ["/", "/sso/login", "/static/style.css", "/static/js/app.js", "/sw.js"]
|
||||
|
||||
|
||||
def remote_audit(base_url: str, runs: int = 3) -> dict:
|
||||
base = base_url.rstrip("/")
|
||||
return {
|
||||
"mode": "remote",
|
||||
"base_url": base,
|
||||
"paths": {p: measure(base + p, runs) for p in DEFAULT_PATHS},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _print_local(report: dict) -> None:
|
||||
graph = report["module_graph"]
|
||||
print("=== Audit chargement ObsiGate — baseline locale ===")
|
||||
print(f"index.html : {report['index_html_bytes']} o")
|
||||
print(f"style.css : {report['style_css_bytes']} o")
|
||||
print(f"Graphe ES statique depuis {graph['entry']} : "
|
||||
f"{graph['module_count']} modules, {graph['raw_bytes']} o bruts")
|
||||
for item in graph["top_modules"][:5]:
|
||||
print(f" {item['bytes']:>8} {item['module']}")
|
||||
print(f"Statiques référencées par index.html : "
|
||||
f"{len(report['index_static_refs'])} fichiers, "
|
||||
f"{report['index_static_refs_bytes']} o")
|
||||
print(f"CDN référencées : {len(report['index_cdn_refs'])}")
|
||||
for cdn in report["index_cdn_refs"]:
|
||||
print(f" {cdn}")
|
||||
|
||||
|
||||
def _print_remote(report: dict) -> None:
|
||||
print(f"=== Audit chargement ObsiGate — {report['base_url']} ===")
|
||||
for path, m in report["paths"].items():
|
||||
print(f"{path:<24} TTFB médian {m['ttfb_median_s']:.3f} s | "
|
||||
f"total {m['total_median_s']:.3f} s | {m['bytes']} o | "
|
||||
f"cache: {m['cache_control']} | cf: {m['cf_cache_status']}")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="https://og.dracodev.net",
|
||||
help="URL de base à mesurer (mode distant)")
|
||||
parser.add_argument("--local", nargs="?", const=".", default=None,
|
||||
metavar="RACINE", help="Baseline depuis les fichiers du dépôt")
|
||||
parser.add_argument("--runs", type=int, default=3, help="Mesures par URL (défaut 3)")
|
||||
parser.add_argument("--json", metavar="FICHIER", help="Écrire le rapport JSON")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.local is not None:
|
||||
report = local_baseline(Path(args.local).resolve())
|
||||
_print_local(report)
|
||||
else:
|
||||
report = remote_audit(args.base_url, args.runs)
|
||||
_print_remote(report)
|
||||
|
||||
if args.json:
|
||||
Path(args.json).write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
print(f"JSON écrit : {args.json}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* E2E — Lien profond « dossier » #folder= (#239).
|
||||
*
|
||||
* Forme sœur de #file=, émise par la console Spark pour les
|
||||
* dossiers cités : « #folder=<vault>:<chemin> » (même encodage,
|
||||
* « : » littéral). Couvre :
|
||||
* - atterrissage sur un dossier emboîté : l'arborescence se
|
||||
* déplie jusqu'au dossier, qui est sélectionné (path-selected)
|
||||
* et lui-même déplié (ses enfants deviennent visibles) ;
|
||||
* - vault inconnu : repli propre sur l'accueil (dashboard),
|
||||
* aucune sélection, aucune erreur bloquante ;
|
||||
* - non-régression #file= : le fichier s'ouvre dans le viewer.
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const VAULT = 'TestVault';
|
||||
// Encodage du contrat : quote de « vault:chemin », « : » littéral.
|
||||
const fragment = (forme, vault, path) =>
|
||||
`#${forme}=${vault}:${encodeURIComponent(path)}`;
|
||||
|
||||
test.describe('Lien profond dossier (#239)', () => {
|
||||
test('dossier emboîté : arbre déplié et dossier sélectionné', async ({ page }) => {
|
||||
await page.goto('/' + fragment('folder', VAULT, 'Recettes/Soupes'));
|
||||
|
||||
const cible = page.locator(
|
||||
`.tree-item.path-selected[data-vault="${VAULT}"][data-path="Recettes/Soupes"]`);
|
||||
await expect(cible).toBeVisible({ timeout: 20000 });
|
||||
|
||||
// Le dossier parent est déplié (son conteneur n'est pas replié)…
|
||||
await expect(page.locator(`#dir-${VAULT}-Recettes`))
|
||||
.not.toHaveClass(/collapsed/);
|
||||
// …et le dossier cible est lui-même déplié : son fichier est
|
||||
// présent dans l'arbre.
|
||||
await expect(page.locator(
|
||||
`.tree-item[data-vault="${VAULT}"][data-path="Recettes/Soupes/Soupe Miso.md"]`))
|
||||
.toBeVisible();
|
||||
});
|
||||
|
||||
test('vault inconnu : repli propre sur l\u2019accueil', async ({ page }) => {
|
||||
await page.goto('/' + fragment('folder', 'VaultInexistant', 'Dossier'));
|
||||
|
||||
// L'accueil (dashboard) s'affiche comme sans fragment…
|
||||
await expect(page.locator('#dashboard-home')).toBeVisible({ timeout: 20000 });
|
||||
// …et rien n'est sélectionné dans l'arbre.
|
||||
await expect(page.locator('.tree-item.path-selected')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('non-régression #file= : le fichier s\u2019ouvre dans le viewer', async ({ page }) => {
|
||||
await page.goto('/' + fragment('file', VAULT, 'Recettes/Pizza Maison.md'));
|
||||
|
||||
// #file= ouvre la note dans le viewer (fil d'Ariane + contenu) ;
|
||||
// il n'a jamais sélectionné l'item dans l'arbre (cf.
|
||||
// split-view.spec.js : « le deep-link #file= ouvre l'ancien
|
||||
// viewer »).
|
||||
await expect(page.locator('#content-area'))
|
||||
.toContainText('Pizza Maison', { timeout: 20000 });
|
||||
await expect(page.locator('#content-area'))
|
||||
.toContainText('Recettes', { timeout: 20000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Bootstrap rapide des liens profonds (#244, épopée perf #240).
|
||||
*
|
||||
* Vérifie la structure de `init()` dans app.js : un lien `#file=` est
|
||||
* ouvert AVANT le `Promise.all(loadVaultSettings, loadVaults,
|
||||
* loadTags)`, et la suite du démarrage ne recouvre pas la cible
|
||||
* (garde `fichierOuvert`). `#folder=` reste après le chargement
|
||||
* (l'arborescence doit exister pour `focusPathInSidebar`).
|
||||
*
|
||||
* Usage: node tests/frontend/bootstrap-244.test.mjs
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const app = readFileSync(join(here, '../../frontend/js/app.js'), 'utf8');
|
||||
|
||||
let passed = 0;
|
||||
function check(name, cond) {
|
||||
if (!cond) {
|
||||
console.error(`✗ ${name}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log(`✓ ${name}`);
|
||||
passed++;
|
||||
}
|
||||
}
|
||||
|
||||
const idxOpen = app.indexOf('Viewer.openFile(vault, path)');
|
||||
const idxAll = app.indexOf('Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()])');
|
||||
const idxFolder = app.indexOf('focusPathInSidebar(vault, path');
|
||||
|
||||
check('#file= ouvert dans app.js', idxOpen !== -1);
|
||||
check('chargement complet présent', idxAll !== -1);
|
||||
check('#file= ouvert AVANT le chargement complet (#244)', idxOpen !== -1 && idxAll !== -1 && idxOpen < idxAll);
|
||||
check('garde fichierOuvert contre le recouvrement par l\'accueil', app.includes('fichierOuvert'));
|
||||
check('#folder= toujours après le chargement complet', idxFolder !== -1 && idxAll !== -1 && idxFolder > idxAll);
|
||||
|
||||
console.log(`\n${passed} checks passed`);
|
||||
@@ -87,11 +87,11 @@ test("viewer delegates inline rendering to NowPlaying.attachInline", () => {
|
||||
const stop = viewer.indexOf("export function renderFile");
|
||||
assert.ok(start !== -1 && stop > start, "renderAudioViewer block not found");
|
||||
const block = viewer.slice(start, stop);
|
||||
assert.match(block, /NowPlaying\.attachInline\(area, data\)/);
|
||||
assert.match(block, /np\.attachInline\(area, data\)/); // #243 : délégation paresseuse via _withNowPlaying
|
||||
});
|
||||
|
||||
test("renderFile hands the shared element to the dock before a re-render", () => {
|
||||
assert.match(viewer, /NowPlaying\.handleRender\(area, data\)/);
|
||||
assert.match(viewer, /np\.handleRender\(area, data\)/); // #243 : idem
|
||||
assert.doesNotMatch(viewer, /_mediaViewerCleanup/);
|
||||
});
|
||||
|
||||
|
||||
@@ -313,12 +313,18 @@ test("reading button only shows while a file is open", () => {
|
||||
test("reading button is hidden while the assistant panel is open", () => {
|
||||
const btn = w.document.getElementById("me-reading-btn");
|
||||
const panel = w.document.createElement("div");
|
||||
panel.className = "bookslm-panel open";
|
||||
// Depuis la transition Spark (D5), le panneau assistant est le panneau
|
||||
// Spark `.draco-panneau` (l'ancien `.bookslm-panel` a été retiré) et
|
||||
// isAssistantOpen() s'appuie sur checkVisibility() — absent du rendu
|
||||
// JSDOM, on le simule donc explicitement sur l'élément.
|
||||
panel.className = "draco-panneau";
|
||||
let panelVisible = true;
|
||||
panel.checkVisibility = () => panelVisible;
|
||||
w.document.body.appendChild(panel);
|
||||
state.currentPath = "Notes/note.md";
|
||||
updateReadingButtonVisibility();
|
||||
assert.ok(btn.hidden, "hidden while the assistant is expanded");
|
||||
panel.classList.add("hidden");
|
||||
panelVisible = false;
|
||||
updateReadingButtonVisibility();
|
||||
assert.ok(!btn.hidden, "shown again once the assistant is collapsed");
|
||||
panel.remove();
|
||||
|
||||
@@ -42,7 +42,7 @@ test("viewer.js — group nav: TOC markdown-only, then pop-out, bookmark", () =>
|
||||
assert.ok(m[1].includes("navBtns.push(openNewWindowBtn, bookmarkBtn, chatBtn);"), "navBtns group order");
|
||||
});
|
||||
|
||||
test("viewer.js — group edit = [edit, source, .ext, forge?, pretty?] in order", () => {
|
||||
test("viewer.js — group edit = [edit, source, .ext, spark?, pretty?] in order", () => {
|
||||
const m = viewer.match(
|
||||
/const editBtns = \[\];([\s\S]*?)const exportBtns/,
|
||||
);
|
||||
@@ -52,11 +52,13 @@ test("viewer.js — group edit = [edit, source, .ext, forge?, pretty?] in order"
|
||||
const re = /editBtns\.push\((\w+)\)/g;
|
||||
let g;
|
||||
while ((g = re.exec(block))) order.push(g[1]);
|
||||
// editBtn conditional, then sourceBtn, then ext-download conditional, then forge conditional
|
||||
assert.deepEqual(order, ["editBtn", "sourceBtn", "mdBtn", "forgeBtn", "prettyBtn"]);
|
||||
// editBtn conditional, then sourceBtn, then ext-download conditional, then
|
||||
// Spark conditional (depuis la transition D5, sparkBtn remplace forgeBtn,
|
||||
// proposé pour tout fichier supporté non-image)
|
||||
assert.deepEqual(order, ["editBtn", "sourceBtn", "mdBtn", "sparkBtn", "prettyBtn"]);
|
||||
assert.ok(block.includes("if (!data.unsupported) editBtns.push(editBtn)"));
|
||||
assert.ok(block.includes("if (!data.is_image) editBtns.push(mdBtn)"));
|
||||
assert.ok(block.includes("if (data.is_markdown) editBtns.push(forgeBtn)"));
|
||||
assert.ok(block.includes("if (!data.unsupported && !data.is_image) editBtns.push(sparkBtn)"));
|
||||
// Pretty (text files) must land in the EDIT group, after the extension button
|
||||
assert.ok(block.indexOf("editBtns.push(prettyBtn)") > block.indexOf("editBtns.push(mdBtn)"));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Tests du script d'audit de chargement (#241, épopée perf #240).
|
||||
|
||||
Le script est stdlib seule et versionné dans ``scripts/`` ; on teste
|
||||
son mode local (graphe de modules ES statiques) sur un mini-frontend
|
||||
synthétique, pour que la mesure reste honnête : un module chargé par
|
||||
``import()`` dynamique ne doit PAS compter dans le graphe statique.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
_SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "audit_chargement.py"
|
||||
_spec = importlib.util.spec_from_file_location("audit_chargement", _SCRIPT)
|
||||
assert _spec and _spec.loader
|
||||
audit = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(audit)
|
||||
|
||||
|
||||
def _write(root: Path, rel: str, content: str) -> None:
|
||||
path = root / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
|
||||
|
||||
def test_static_imports_ignore_dynamic_imports():
|
||||
source = (
|
||||
"import * as A from './a.js';\n"
|
||||
"import './side.js';\n"
|
||||
"export { x } from './re.js';\n"
|
||||
"const m = await import('./lazy.js');\n"
|
||||
"import('https://cdn.example.com/x.js');\n"
|
||||
)
|
||||
assert audit.static_imports(source) == ["./a.js", "./side.js", "./re.js"]
|
||||
|
||||
|
||||
def test_local_module_graph_counts_only_static_chain(tmp_path):
|
||||
frontend = tmp_path / "frontend"
|
||||
_write(frontend, "js/app.js",
|
||||
"import { a } from './a.js';\nconst l = await import('./lazy.js');\n")
|
||||
_write(frontend, "js/a.js", "import { b } from './sub/b.js';\nexport const a = b;\n")
|
||||
_write(frontend, "js/sub/b.js", "export const b = 1;\n")
|
||||
_write(frontend, "js/lazy.js", "export const lazy = 'x'.repeat(5000);\n")
|
||||
|
||||
graph = audit.local_module_graph(frontend)
|
||||
|
||||
assert graph["module_count"] == 3 # app + a + sub/b, pas lazy
|
||||
assert "js/lazy.js" not in graph["modules"]
|
||||
assert graph["raw_bytes"] == sum(graph["modules"].values())
|
||||
|
||||
|
||||
def test_local_baseline_on_real_repo():
|
||||
repo = Path(__file__).resolve().parent.parent
|
||||
baseline = audit.local_baseline(repo)
|
||||
graph = baseline["module_graph"]
|
||||
# La baseline du dépôt réel au moment du lot #241 : 41 modules,
|
||||
# ~1,42 Mo bruts. On vérifie des bornes larges (le graphe bouge
|
||||
# avec les lots suivants, #243 doit le faire BAISSER).
|
||||
assert graph["module_count"] >= 10
|
||||
assert graph["raw_bytes"] > 100_000
|
||||
assert baseline["index_html_bytes"] > 100_000
|
||||
assert any("mermaid" in url or "lucide" in url or "highlight" in url
|
||||
for url in baseline["index_cdn_refs"]) or graph["raw_bytes"] < 1_000_000
|
||||
@@ -45,6 +45,7 @@ from backend.coffre_crypto import (
|
||||
from backend.coffre_store import (
|
||||
CoffreExisteError,
|
||||
create_octroi,
|
||||
list_octrois,
|
||||
list_secrets,
|
||||
SecretExpireError,
|
||||
ValidationError,
|
||||
@@ -780,6 +781,188 @@ class TestDistribuables:
|
||||
assert self._lister(client, jeton).status_code == 503
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Destination « Console Spark » (issue #102)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestDestinationConsoleSpark:
|
||||
def _creer_consommateur_spark(self, client, nom="spark"):
|
||||
resp = client.post("/api/coffres/consommateurs", json={"nom": nom})
|
||||
assert resp.status_code == 200, resp.text
|
||||
consommateur = resp.json()
|
||||
return consommateur, consommateur["jeton"]
|
||||
|
||||
def _creer_coffre(self, client, slug="personnel"):
|
||||
resp = client.post(
|
||||
"/api/coffres",
|
||||
json={"slug": slug, "nom": "Personnel", "perimetre": "personnel"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
|
||||
def _creer_secret_spark(self, client, slug="personnel", nom="gitea-token"):
|
||||
resp = client.post(
|
||||
f"/api/coffres/{slug}/secrets",
|
||||
json={
|
||||
"nom": nom,
|
||||
"type": "token",
|
||||
"service": "Gitea",
|
||||
"valeur": VALEUR_TEST,
|
||||
"console_spark": True,
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
return resp.json()
|
||||
|
||||
def _distribuables(self, client, jeton):
|
||||
resp = client.get(
|
||||
"/api/coffres/distribuables",
|
||||
headers={"Authorization": f"Bearer {jeton}"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
return resp.json()
|
||||
|
||||
def test_destination_active_octroi_auto_et_distribuables(
|
||||
self, client, env_coffre):
|
||||
consommateur, jeton = self._creer_consommateur_spark(client)
|
||||
self._creer_coffre(client)
|
||||
secret = self._creer_secret_spark(client)
|
||||
assert secret["console_spark"] is True
|
||||
assert secret["console_spark_octroi"] == "cree"
|
||||
assert secret["octrois_actifs"] == 1
|
||||
# L'octroi automatique est distingué par son origine.
|
||||
octrois = client.get("/api/coffres/personnel/octrois").json()
|
||||
assert len(octrois) == 1
|
||||
assert octrois[0]["origine"] == "console_spark"
|
||||
assert octrois[0]["cible_type"] == "consommateur"
|
||||
assert octrois[0]["cible_id"] == consommateur["id"]
|
||||
assert octrois[0]["secret_id"] == secret["id"]
|
||||
# Le secret apparaît dans les distribuables du consommateur
|
||||
# Spark et se distribue normalement (contrat inchangé).
|
||||
assert self._distribuables(client, jeton) == [{
|
||||
"reference": "coffre:personnel/gitea-token",
|
||||
"coffre": "personnel",
|
||||
"nom": "gitea-token",
|
||||
"version": 1,
|
||||
}]
|
||||
resp = _distribuer(client, jeton)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["valeur"] == VALEUR_TEST
|
||||
# Journal : action dédiée, jamais de valeur.
|
||||
audit = (env_coffre / "audit.log").read_text(encoding="utf-8")
|
||||
assert "octroi_auto_spark_cree" in audit
|
||||
assert VALEUR_TEST not in audit
|
||||
|
||||
def test_destination_retiree_revoque_octroi_auto(self, client, env_coffre):
|
||||
_consommateur, jeton = self._creer_consommateur_spark(client)
|
||||
self._creer_coffre(client)
|
||||
self._creer_secret_spark(client)
|
||||
assert len(self._distribuables(client, jeton)) == 1
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"console_spark": False},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
corps = resp.json()
|
||||
assert corps["console_spark"] is False
|
||||
assert corps["console_spark_octroi"] == "revoque"
|
||||
assert corps["octrois_actifs"] == 0
|
||||
# L'octroi automatique est révoqué (conservé, pas supprimé) et
|
||||
# le secret sort des distribuables.
|
||||
octrois = client.get("/api/coffres/personnel/octrois").json()
|
||||
assert len(octrois) == 1
|
||||
assert octrois[0]["statut"] == "revoque"
|
||||
assert octrois[0]["origine"] == "console_spark"
|
||||
assert self._distribuables(client, jeton) == []
|
||||
# Second retrait : plus rien à révoquer.
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"console_spark": False},
|
||||
)
|
||||
assert resp.json()["console_spark_octroi"] == "aucun"
|
||||
audit = (env_coffre / "audit.log").read_text(encoding="utf-8")
|
||||
assert "octroi_auto_spark_revoque" in audit
|
||||
|
||||
def test_consommateur_spark_absent_signale(self, client, env_coffre):
|
||||
# Aucun consommateur : la destination reste posée, l'octroi
|
||||
# n'est pas créé et la réponse le signale explicitement.
|
||||
self._creer_coffre(client)
|
||||
secret = self._creer_secret_spark(client)
|
||||
assert secret["console_spark"] is True
|
||||
assert secret["console_spark_octroi"] == "consommateur_introuvable"
|
||||
assert secret["octrois_actifs"] == 0
|
||||
assert client.get("/api/coffres/personnel/octrois").json() == []
|
||||
# Le consommateur créé après coup : un nouvel enregistrement
|
||||
# des métadonnées réconcilie et crée l'octroi.
|
||||
_consommateur, jeton = self._creer_consommateur_spark(client)
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"console_spark": True},
|
||||
)
|
||||
assert resp.json()["console_spark_octroi"] == "cree"
|
||||
assert len(self._distribuables(client, jeton)) == 1
|
||||
|
||||
def test_consommateur_spark_ambigu_signale(self, client, env_coffre):
|
||||
# Deux consommateurs actifs au nom normalisé « spark » :
|
||||
# aucun octroi deviné, signalement explicite.
|
||||
self._creer_consommateur_spark(client, nom="spark")
|
||||
self._creer_consommateur_spark(client, nom=" Spark ")
|
||||
self._creer_coffre(client)
|
||||
secret = self._creer_secret_spark(client)
|
||||
assert secret["console_spark_octroi"] == "consommateur_ambigu"
|
||||
assert client.get("/api/coffres/personnel/octrois").json() == []
|
||||
|
||||
def test_octroi_manuel_preexistant_pas_de_doublon(
|
||||
self, client, env_coffre):
|
||||
_creer_coffre_secret(client) # personnel/gitea-token, sans destination
|
||||
consommateur, jeton, octroi_manuel = _creer_consommateur_octroi(client)
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"console_spark": True},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["console_spark_octroi"] == "existant"
|
||||
coffre = get_coffre_or_404("personnel")
|
||||
octrois = list_octrois(coffre["id"])
|
||||
assert len(octrois) == 1
|
||||
assert octrois[0]["id"] == octroi_manuel["id"]
|
||||
# Retirer la destination ne touche pas l'octroi manuel.
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"console_spark": False},
|
||||
)
|
||||
assert resp.json()["console_spark_octroi"] == "aucun"
|
||||
assert len(self._distribuables(client, jeton)) == 1
|
||||
|
||||
def test_patch_metadonnees_et_erreurs(self, client, env_coffre):
|
||||
_creer_coffre_secret(client)
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"service": "Gitea perso", "note": "jeton de test"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
corps = resp.json()
|
||||
assert corps["service"] == "Gitea perso"
|
||||
assert corps["note"] == "jeton de test"
|
||||
assert corps["console_spark"] is False
|
||||
# La valeur ne passe jamais par le PATCH.
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"valeur": VALEUR_TEST_2},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
# Secret inexistant : 404. Non-gestionnaire : 403.
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/absent", json={"note": "x"}
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
_connecter(client, "alice", role="user")
|
||||
resp = client.patch(
|
||||
"/api/coffres/personnel/secrets/gitea-token",
|
||||
json={"note": "interdit"},
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Révélation manuelle (panneau détail : Afficher / Copier la valeur)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Cache mémoire de GET /api/dashboard (#245, épopée perf #240)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.routers import config as config_router
|
||||
|
||||
|
||||
def _count_calls(monkeypatch):
|
||||
calls = {"n": 0}
|
||||
original = config_router._compute_dashboard
|
||||
|
||||
def counting(user):
|
||||
calls["n"] += 1
|
||||
return original(user)
|
||||
|
||||
monkeypatch.setattr(config_router, "_compute_dashboard", counting)
|
||||
return calls
|
||||
|
||||
|
||||
def test_dashboard_second_call_served_from_cache(client, monkeypatch):
|
||||
config_router.invalidate_dashboard_cache()
|
||||
calls = _count_calls(monkeypatch)
|
||||
|
||||
first = client.get("/api/dashboard")
|
||||
second = client.get("/api/dashboard")
|
||||
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 200
|
||||
assert second.json() == first.json()
|
||||
assert calls["n"] == 1 # un seul calcul pour deux appels
|
||||
|
||||
|
||||
def test_dashboard_cache_invalidation_recomputes(client, monkeypatch):
|
||||
config_router.invalidate_dashboard_cache()
|
||||
calls = _count_calls(monkeypatch)
|
||||
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
config_router.invalidate_dashboard_cache()
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
assert calls["n"] == 2
|
||||
|
||||
|
||||
def test_dashboard_cache_ttl_expiry(client, monkeypatch):
|
||||
import time
|
||||
|
||||
config_router.invalidate_dashboard_cache()
|
||||
calls = _count_calls(monkeypatch)
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
# Vieillir artificiellement l'entrée au-delà du TTL.
|
||||
for key, (ts, value) in list(config_router._dashboard_cache.items()):
|
||||
config_router._dashboard_cache[key] = (ts - config_router._DASHBOARD_TTL_SECONDS - 1, value)
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
assert calls["n"] == 2
|
||||
_ = time # (garde-fou d'import)
|
||||
@@ -592,3 +592,16 @@ def test_bouton_spark_mobile_bug131():
|
||||
assert ".draco-spark-flottant" in bloc_mobile
|
||||
mt = (FRONTEND / "js" / "mobile-toolbar.js").read_text(encoding="utf-8")
|
||||
assert "ouvrirSparkOuMessage" in mt
|
||||
|
||||
|
||||
def test_rafraichissement_arbre_ignore_noeuds_virtuels_bug132():
|
||||
"""BUG-132 — le rafraîchissement de l'arbre (état préservé) recapturait
|
||||
le nœud virtuel Secrets comme un répertoire déplié et le rechargeait
|
||||
par /api/browse : 404 « Path not found: Secrets » affiché en toast à
|
||||
chaque rafraîchissement (notamment après l'ajout d'un secret). Les
|
||||
nœuds virtuels (data-type « virtual-* ») sont exclus de la recapture."""
|
||||
sidebar = (FRONTEND / "js" / "sidebar.js").read_text(encoding="utf-8")
|
||||
fonction = sidebar[sidebar.index("async function refreshSidebarTreePreservingState"):]
|
||||
fonction = fonction[:fonction.index("\n}\n", 200) + 3] if "\n}\n" in fonction[200:] else fonction[:4000]
|
||||
assert 'startsWith("virtual")' in fonction
|
||||
assert "BUG-132" in fonction
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Cache versionné des statiques (#242, épopée perf #240).
|
||||
|
||||
Non-régression clé : une nouvelle version doit être servie
|
||||
immédiatement — le cache long (``immutable``) n'est accordé qu'aux
|
||||
URL portant ``?v=<version courante>``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend import static_versioning as sv
|
||||
|
||||
|
||||
def test_rewrite_static_urls_adds_version():
|
||||
html = '<link rel="stylesheet" href="/static/style.css" />' \
|
||||
'<script type="module" src="/static/js/app.js"></script>' \
|
||||
'<a href="https://example.com/static/nope.css">x</a>'
|
||||
out = sv.rewrite_static_urls(html, version="9.9.9")
|
||||
assert "/static/style.css?v=9.9.9" in out
|
||||
assert "/static/js/app.js?v=9.9.9" in out
|
||||
assert "example.com/static/nope.css?v=" not in out
|
||||
|
||||
|
||||
def test_rewrite_js_imports_adds_version():
|
||||
source = (
|
||||
"import * as UI from './ui.js';\n"
|
||||
"import './side.js';\n"
|
||||
"export { x } from '../shared.js';\n"
|
||||
"const m = await import('./lazy.js');\n"
|
||||
"const s = 'pas un import ./faux.js';\n"
|
||||
)
|
||||
out = sv.rewrite_js_imports(source, version="9.9.9")
|
||||
assert "'./ui.js?v=9.9.9'" in out
|
||||
assert "'./side.js?v=9.9.9'" in out
|
||||
assert "'../shared.js?v=9.9.9'" in out
|
||||
assert "'./lazy.js?v=9.9.9'" in out
|
||||
|
||||
|
||||
def test_cache_control_only_immutable_for_current_version():
|
||||
current = sv.current_version()
|
||||
assert sv.cache_control_for("/static/js/app.js", f"v={current}") == sv.IMMUTABLE_CACHE_CONTROL
|
||||
# Ancienne version / absence de version : jamais de cache long.
|
||||
assert sv.cache_control_for("/static/js/app.js", "v=0.0.1") == sv.NO_CACHE
|
||||
assert sv.cache_control_for("/static/js/app.js", "") == sv.NO_CACHE
|
||||
assert sv.cache_control_for("/api/dashboard", f"v={current}") is None
|
||||
|
||||
|
||||
def test_served_headers_and_rewriting(client):
|
||||
"""Via l'application : en-têtes selon ?v= et corps JS réécrit."""
|
||||
current = sv.current_version()
|
||||
|
||||
versioned = client.get(f"/static/js/app.js?v={current}")
|
||||
assert versioned.status_code == 200
|
||||
assert "immutable" in versioned.headers.get("cache-control", "")
|
||||
assert f"?v={current}" in versioned.text # imports réécrits au service
|
||||
|
||||
plain = client.get("/static/js/app.js")
|
||||
assert plain.status_code == 200
|
||||
assert plain.headers.get("cache-control") == "no-cache"
|
||||
|
||||
stale = client.get("/static/js/app.js?v=0.0.1")
|
||||
assert stale.headers.get("cache-control") == "no-cache"
|
||||
|
||||
index = client.get("/")
|
||||
assert index.status_code == 200
|
||||
assert index.headers.get("cache-control") == "no-cache"
|
||||
assert f"/static/style.css?v={current}" in index.text
|
||||
assert f"/static/js/app.js?v={current}" in index.text
|
||||
|
||||
|
||||
def test_service_worker_carries_current_version(client):
|
||||
current = sv.current_version()
|
||||
sw = client.get("/sw.js")
|
||||
assert sw.status_code == 200
|
||||
assert "__OBSIGATE_SW_VERSION__" not in sw.text
|
||||
assert f"v{current}" in sw.text
|
||||
Reference in New Issue
Block a user