Compare commits

..
18 Commits
Author SHA1 Message Date
ietm64 3f0766ccbe Passage à la 1.6.2
Tests unitaires / Brain (Python · pytest + couverture) (push) Successful in 25s
Tests unitaires / Web (Angular · vitest + couverture) (push) Successful in 28s
Tests unitaires / Core (Java · mvn test + JaCoCo) (push) Successful in 4m21s
E2E Tests / e2e (push) Failing after 4m36s
Build & Push Images / build (brain) (push) Successful in 1m19s
Build & Push Images / build (web) (push) Successful in 2m44s
Build & Push Images / build-switcher (push) Successful in 43s
Build & Push Images / build (core) (push) Successful in 4m42s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 57s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 43s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 55s
2026-10-29 10:35:50 +01:00
ietm64 b9020cb46f README : politique de signature du code (SignPath)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 45s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m6s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m54s
Section « Code signing policy » demandée par SignPath Foundation pour la
signature gratuite des installeurs Windows :
- signature fournie par SignPath.io, certificat de SignPath Foundation ;
- ce qui est signé : les .msi et le lanceur DM Loremind.exe, construits par
  GitHub Actions à partir de ce dépôt ;
- rôles de l'équipe (auteurs, relecteurs, approbateurs) et approbation
  manuelle de chaque signature ;
- confidentialité : aucune transmission sans demande explicite, sauf la
  vérification des mises à jour (désactivable), avec le lien vers la
  politique de confidentialité de la documentation.

En français (README.fr.md) et en anglais (README.md).
2026-10-29 10:28:15 +01:00
ietm64 10574ba0c5 Installeurs bureau : une seule release par version, avec les deux installeurs
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 48s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m3s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 38s
Build & Push Images / build (brain) (push) Successful in 1m40s
Build & Push Images / build (web) (push) Successful in 2m11s
Build & Push Images / build-switcher (push) Successful in 23s
Build & Push Images / build (core) (push) Successful in 3m52s
Les jobs windows et linux publiaient chacun leur installeur sur la release
GitHub. Ils tournent en parallèle : pour la v1.6.2-beta, chacun a créé sa
propre release pour le même tag. L'une a été publiée avec le .msi, l'autre
est restée en brouillon avec l'AppImage, et le job linux a échoué sur
« already_exists ».

- windows et linux construisent seulement, et passent leur installeur en
  artefact du run (gardé 7 jours).
- Un nouveau job `publish`, qui attend les deux, crée la release une seule
  fois et y attache le .msi et l'AppImage. Une bêta est publiée en
  pré-release.
- Si l'un des deux builds échoue, rien n'est publié : une release a
  toujours ses deux installeurs.
- Relancer le workflow pour une version déjà publiée met la release à jour
  et remplace les fichiers de même nom : pas besoin de la supprimer.

Vérifié : structure du workflow (dépendances des jobs, sorties tag et
isbeta du job windows, artefacts installer-*). Pas encore exécuté sur
GitHub.
2026-10-29 10:20:19 +01:00
ietm64 ace2e486fc Bureau : retrait des comportements qui déclenchaient des antivirus
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 47s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m5s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 30s
Build & Push Images / build (brain) (push) Successful in 1m33s
Build & Push Images / build (web) (push) Successful in 2m4s
Build & Push Images / build (core) (push) Successful in 3m41s
Build & Push Images / build-switcher (push) Successful in 16s
Un utilisateur a signalé une alerte Avast « IDP.Generic » sur l'appli de
bureau. Cette détection est heuristique : elle vise les programmes peu
connus et non signés qui se comportent comme des logiciels malveillants.
Deux comportements de DM Loremind correspondaient à ce profil.

Ouverture du navigateur (à chaque démarrage, et depuis l'icône de la barre
des tâches) :
- Avant : `rundll32 url.dll,FileProtocolHandler <url>`, un outil Windows
  très détourné par les logiciels malveillants.
- Maintenant : l'API standard de Java (`Desktop.browse`, ShellExecute sous
  Windows). Si elle n'est pas disponible, repli sur `cmd /c start`.

Vérification du réseau et du pare-feu (accès depuis une tablette) :
- Avant : PowerShell lancé avec un script encodé en base64
  (`-EncodedCommand`) et `-ExecutionPolicy Bypass`, la signature typique
  d'un script malveillant qui cherche à se cacher.
- Maintenant : script en clair, sur une ligne (`-Command`). Le contournement
  de la politique d'exécution est retiré : il ne sert qu'aux fichiers .ps1,
  il était donc inutile. La ligne de commande Windows est en UTF-16 : les
  accents (chemins, noms de réseau) passent tels quels.
- Un garde-fou refuse tout script sur plusieurs lignes ou contenant un
  guillemet double, qui serait mal transmis.

Bouton « Autoriser dans le pare-feu » : comportement inchangé. Seul le
script relancé en administrateur reste encodé, car `Start-Process
-ArgumentList` ne sait pas transmettre un script avec espaces et
guillemets ; il ne s'exécute qu'après un clic et la confirmation UAC de
Windows.

Vérifié :
- core clean verify (1299 tests) ;
- nouveaux tests : commande sans `-EncodedCommand` ni `Bypass`, scripts sur
  une ligne, script administrateur décodé à l'identique ;
- lecture réelle du réseau sur Windows avec la nouvelle commande (réseau
  privé, règles du pare-feu, pare-feu tiers avec accents) ;
- la JVM se ferme normalement après initialisation de `Desktop`, donc la
  relance d'une seconde instance n'est pas bloquée.

Non vérifié : l'ouverture du navigateur depuis l'appli installée, et
l'absence d'alerte Avast. La signature de l'installeur reste le remède
durable contre ce type d'alerte.
À redéployer : core (appli de bureau).
2026-10-29 09:56:22 +01:00
ietm64 c008c22e09 Passage à la 1.6.2-beta
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 1m14s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m55s
Build & Push Images / build (brain) (push) Successful in 1m19s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m28s
Build & Push Images / build (web) (push) Successful in 2m12s
Build & Push Images / build-switcher (push) Successful in 20s
Build & Push Images / build (core) (push) Successful in 4m28s
2026-10-29 09:45:24 +01:00
ietm64 bf606c23d1 suppression de la partie patreon 2026-10-29 09:28:48 +01:00
ietm64 1898e8b1ae Passage 1.6.1-beta
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 47s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 58s
Build & Push Images / build (brain) (push) Successful in 1m29s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m4s
Build & Push Images / build (web) (push) Successful in 2m20s
Build & Push Images / build-switcher (push) Successful in 24s
Build & Push Images / build (core) (push) Successful in 4m30s
2026-10-18 01:33:49 +02:00
ietm64 e77ad85be9 Import de règles : compteur d'attente et message de nouvel essai
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 35s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m2s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m48s
Après une erreur passagère du fournisseur IA, « nouvel essai dans 3s »
restait affiché pendant tout l'essai suivant, qui peut durer plusieurs
minutes : l'import paraissait bloqué alors qu'il avançait.
- Brain : un message annonce le lancement de l'essai suivant
  (« Nouvel essai en cours (tentative 2/3)… »).
- Écran du système de jeu : au-delà de 15 s sans nouvelle, un compteur
  indique depuis combien de temps l'IA travaille sur le morceau.

Vérifié : brain (234 tests), vitest, build, lint sans erreur.
À redéployer : web + brain.
2026-10-18 01:33:02 +02:00
ietm64 11939fe39e Import PDF : le résultat final ne dépasse plus la limite de 256 Ko
L'évènement de fin d'import porte tout le résultat : les règles d'un livre
entier, désormais en deux langues, ou l'arbre complet d'une campagne. La
limite par défaut de WebClient (256 Ko par évènement) faisait échouer
l'import au tout dernier moment, après toute l'analyse
(DataBufferLimitException). Les clients d'import acceptent maintenant
jusqu'à 64 Mo par évènement.

Vérifié : test avec un vrai serveur HTTP local et un évènement d'environ
1,8 Mo (échoue avec l'ancienne limite, passe avec la nouvelle) ; core
clean verify (1300 tests).
À redéployer : core.
2026-10-18 01:33:01 +02:00
ietm64 8958822545 Méthodes guidées : l'IA part de l'idée du MJ et suit la méthode étape par étape
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 55s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m3s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 55s
Build & Push Images / build (brain) (push) Successful in 2m30s
Build & Push Images / build (core) (push) Successful in 4m8s
Build & Push Images / build-switcher (push) Successful in 16s
Build & Push Images / build (web) (push) Successful in 2m46s
- L'idée de départ est obligatoire : les boutons « Proposer » restent
  inactifs tant qu'elle est vide, avec un message qui l'explique. Le champ
  est plus grand et invite à raconter son idée (lieu, adversaire, envies).
- L'IA reçoit la méthode telle que le MJ la suit à la main : le principe,
  puis le rôle de chaque étape (le « pourquoi » affiché dans l'assistant).
  Avant, elle ne voyait que les libellés des champs. Les exemples ne sont
  pas transmis, pour qu'elle ne les recopie pas.
- Prompt : garder le ton et le sujet de l'idée, et faire jouer à chaque
  réponse le rôle de son étape.

Vérifié : brain (233 tests), vitest (867), build, lint sans erreur, core
clean test-compile. Pas essayé avec un vrai modèle.
À redéployer : web + brain.
2026-10-18 00:43:46 +02:00
ietm64 007bcce8a7 Règles des systèmes en deux langues ; import de campagne dans la langue de l'UI
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 35s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 50s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m26s
- Règles d'un système de jeu stockées en français et en anglais (migration
  V28, rules_markdown_en). L'import d'un PDF garde l'extraction fidèle dans
  la langue du livre (détectée) et traduit section par section vers l'autre
  langue, noms propres conservés ; la progression de la traduction s'affiche.
  Un échec de traduction n'annule pas l'import.
- Éditeur du système : onglets Français / English ; l'import remplit les
  deux. Règles en séance et contexte de l'IA : version de la langue de
  l'interface, avec repli sur l'autre si elle est vide.
- Import de campagne : textes rédigés (ou traduits) dans la langue de
  l'interface ; titres et noms propres conservés tels quels ; arc par défaut
  nommé dans la bonne langue.
- Les règles anglaises suivent l'export/import de sauvegarde.

Vérifié : brain (détection, découpe, traduction, flux d'import, langue de
l'import de campagne), core clean verify (1299 tests), web build + vitest +
lint. Traduction non essayée avec un vrai modèle.
2026-10-18 00:37:01 +02:00
ietm64 a985bbd018 Méthodes guidées : propositions de l'IA à partir d'une idée de départ
- Champ « Ton idée de départ » dans l'assistant, avec « Proposer toute
  l'aventure » et « Proposer pour cette étape ».
- L'IA ne remplit que les champs vides, ou restés à leur valeur d'office et
  jamais modifiés : elle ne touche jamais à ce que le MJ a écrit, qui lui
  est transmis comme contexte. « Annuler la proposition » restaure l'état.
- Questions à choix : seule une valeur proposée est acceptée.
- Core : POST /api/campaigns/{id}/guided-assist (contexte de la campagne,
  filtrage des réponses, 502 si l'IA est indisponible).
- Brain : POST /generate/guided-answers, réponses dans la langue de
  l'interface.

Vérifié : brain (prompt, nettoyage), core (service, contrôleur), vitest
(champs libres, fusion, étape), parcours dans le navigateur (réponse
simulée, champ du MJ préservé, annulation, message d'erreur sans IA).
2026-10-18 00:37:00 +02:00
ietm64 1c9ac524db IA : la langue de l'interface suit les traitements de fond
La langue (en-tête X-User-Language, gardée dans un ThreadLocal) était perdue
dans l'exécuteur des flux SSE : imports de PDF (règles, campagne), ateliers
et chat partaient toujours en français, même avec l'interface en anglais.
Un TaskDecorator relaie désormais la langue du thread de la requête vers la
tâche de fond, puis la restaure (pas de fuite entre tâches du pool).

Vérifié : core (exécuteur applicationTaskExecutor en anglais, restauration).
2026-10-18 00:37:00 +02:00
ietm64 abf66733fe Paramètres : page vide dès qu'un appareil tablette est appairé
La date des appareils appairés était formatée avec `translate.currentLang`,
qui est un signal en ngx-translate 18 : converti en texte, il donnait une
locale invalide, et toLocaleString levait une RangeError qui interrompait
l'affichage de toute la page Paramètres (titres et libellés vides).
Utilise getCurrentLang() avec une locale explicite, et un repli sûr.

Vérifié : reproduit avec la version installée sur une base de test avec un
appareil appairé (RangeError en console, titres vides), puis corrigé (date
affichée, plus d'erreur). Web build + vitest + lint sans erreur.
2026-10-18 00:36:59 +02:00
ietm64 763219412b Mode plat : seulement quand l'arc et le chapitre uniques sont vides
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 38s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m4s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m52s
Une méthode guidée lancée dans une campagne vide crée un arc et un chapitre
qui portent le contenu écrit (titre, accroche, enjeux, vérité cachée ou plan
du méchant en notes MJ). Le mode plat les masquait : ce contenu devenait
introuvable derrière le nœud « Scènes ».

- Règle commune (flat-structure.ts) : un seul arc linéaire, un seul
  chapitre, et aucun contenu d'écriture dans l'un ou l'autre (les noms ne
  comptent pas, « Arc principal » / « Chapitre 1 » étant créés d'office).
- Appliquée au volet de gauche, à la page de la campagne (cartes d'arc
  visibles dès qu'il y a du contenu) et au livret PDF (en-têtes d'arc et de
  chapitre conservés ; un arc HUB n'est plus jamais mis à plat).

Vérifié : core clean verify (1289 tests, dont livret plat / non plat),
web build + 860 vitest (règle du mode plat), lint sans erreur.
À redéployer : core + web (aucune migration).
2026-10-17 23:53:23 +02:00
ietm64 cccf2b85db Correction test PDF
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 37s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m25s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 58s
Build & Push Images / build (brain) (push) Successful in 1m51s
Build & Push Images / build (web) (push) Successful in 2m21s
Build & Push Images / build (core) (push) Successful in 4m16s
Build & Push Images / build-switcher (push) Successful in 16s
2026-10-17 19:17:37 +02:00
ietm64 6ae9238fee passage v1.5.0-beta
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 49s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 52s
Build & Push Images / build (brain) (push) Successful in 1m24s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m6s
Build & Push Images / build (web) (push) Successful in 2m36s
Build & Push Images / build (core) (push) Successful in 4m19s
Build & Push Images / build-switcher (push) Successful in 22s
2026-10-17 19:05:52 +02:00
ietm64 0ef1380265 Améliore la navigation et la mise en page des exports PDF
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 37s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m37s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m1s
- Ajoute les fils d’Ariane, les favoris et l’historique de navigation
- Étend la recherche aux arcs, chapitres, scènes et quêtes
- Regroupe les actions de campagne dans le menu Gérer
- Améliore la navigation au clavier et sur mobile
- Refonte de l’export A4 : deux colonnes, couverture illustrée et encadrés
- Ajoute des motifs décoratifs en pied de page et une variante pour l’impression
- Vérifie la pagination, les renvois et la confidentialité de l’édition joueurs
2026-10-17 19:05:15 +02:00
170 changed files with 4283 additions and 2775 deletions
+3 -3
View File
@@ -47,7 +47,7 @@ jobs:
# Detection du canal : # Detection du canal :
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics) # - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR prives # - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR publics
# loremind-beta-<component> ; backup Gitea avec :version) # loremind-beta-<component> ; backup Gitea avec :version)
- name: Extract version & channel - name: Extract version & channel
id: meta id: meta
@@ -74,8 +74,8 @@ jobs:
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }} ${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
# Build & push canal BETA # Build & push canal BETA
# GHCR : repos prives loremind-beta-<component> (gated par PAT distribue # GHCR : repos PUBLICS loremind-beta-<component> (canal beta libre ;
# via le relais Patreon aux tiers Compagnon). # le switcher bascule IMAGE_NAMESPACE vers ce prefixe).
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne # Gitea : backup prive avec :version uniquement (pas de :latest pour ne
# pas faire upgrader les installs branchees sur Gitea). # pas faire upgrader les installs branchees sur Gitea).
- name: Build & push ${{ matrix.component }} (beta) - name: Build & push ${{ matrix.component }} (beta)
+48 -40
View File
@@ -12,12 +12,10 @@ name: Desktop installers
# inclus) pour que le tag declenche ce workflow. # inclus) pour que le tag declenche ce workflow.
# #
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache. # Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en # Tag beta vX.Y.Z-beta* -> GitHub Release PUBLIQUE marquee « pre-release » : le
# ARTEFACT PRIVE du run (telechargeable seulement par # canal beta est libre. /releases/latest l'ignore, donc
# toi via l'onglet Actions) ; tu le joins ensuite a un # seules les installations beta en sont prevenues
# post Patreon reserve a un palier. Patreon = la # (cf. DesktopUpdateService).
# barriere d'acces (equivalent du registry prive +
# relais pour les images Docker beta).
on: on:
push: push:
@@ -106,6 +104,10 @@ jobs:
windows: windows:
needs: tests needs: tests
runs-on: windows-latest runs-on: windows-latest
# Reprises par le job `publish` (tag de la release, statut pre-release).
outputs:
tag: ${{ steps.ver.outputs.tag }}
isbeta: ${{ steps.ver.outputs.isbeta }}
steps: steps:
# En declenchement manuel, on checkout le TAG correspondant a la version # En declenchement manuel, on checkout le TAG correspondant a la version
# saisie (sinon checkout prendrait la branche par defaut). En push de tag, # saisie (sinon checkout prendrait la branche par defaut). En push de tag,
@@ -169,33 +171,20 @@ jobs:
shell: pwsh shell: pwsh
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }} run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
# STABLE uniquement : Release GitHub publique avec le .msi. # Le .msi est passe au job `publish`, seul a creer la release.
# tag_name explicite : en declenchement manuel, github.ref est une branche, - name: Keep installer for the release
# donc on cible le tag derive (la release est attachee au bon tag).
- name: Publish installer to GitHub Release (stable)
if: ${{ steps.ver.outputs.isbeta == 'false' }}
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ver.outputs.tag }}
files: core/target/dist-out/*.msi
fail_on_unmatched_files: true
generate_release_notes: true
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
- name: Upload installer as private artifact (beta)
if: ${{ steps.ver.outputs.isbeta == 'true' }}
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: loremind-beta-${{ steps.ver.outputs.version }}-msi name: installer-windows
path: core/target/dist-out/*.msi path: core/target/dist-out/*.msi
retention-days: 90 if-no-files-found: error
retention-days: 7
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release. # LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux). # Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux # Brain empaquete via python-build-standalone (pas de Python embeddable Linux
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de # officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
# publication que windows : stable -> release publique ; beta -> artefact prive. # publication que windows : stable -> release publique ; beta -> pre-release.
linux: linux:
needs: tests needs: tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -242,21 +231,40 @@ jobs:
GITHUB_TOKEN: ${{ github.token }} GITHUB_TOKEN: ${{ github.token }}
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }} run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
# STABLE uniquement : attache l'AppImage a la release publique (meme tag que # L'AppImage est passee au job `publish`, seul a creer la release.
# le .msi -> les deux installeurs sur la meme release). - name: Keep AppImage for the release
- name: Publish AppImage to GitHub Release (stable)
if: ${{ steps.ver.outputs.isbeta == 'false' }}
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ver.outputs.tag }}
files: core/target/dist-out/DM_Loremind*.AppImage
fail_on_unmatched_files: true
# BETA uniquement : artefact PRIVE (pas de release publique).
- name: Upload AppImage as private artifact (beta)
if: ${{ steps.ver.outputs.isbeta == 'true' }}
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: loremind-beta-${{ steps.ver.outputs.version }}-appimage name: installer-linux
path: core/target/dist-out/DM_Loremind*.AppImage path: core/target/dist-out/DM_Loremind*.AppImage
retention-days: 90 if-no-files-found: error
retention-days: 7
# PUBLICATION : un seul job cree la release et y attache les deux installeurs.
# Quand windows et linux publiaient chacun de leur cote, ils tournaient en
# parallele et creaient DEUX releases pour le meme tag (une publiee, une en
# brouillon), l'un echouant sur « already_exists ». Rien n'est publie si l'un
# des deux builds echoue : une release a toujours ses deux installeurs.
# Relancer le workflow pour une version deja publiee met la release a jour et
# remplace les fichiers de meme nom (pas besoin de la supprimer).
publish:
needs: [windows, linux]
runs-on: ubuntu-latest
steps:
- name: Get installers
uses: actions/download-artifact@v4
with:
pattern: installer-*
path: dist
merge-multiple: true
# tag_name explicite : en declenchement manuel, github.ref est une branche.
# Une beta est publiee en pre-release (ignoree par /releases/latest).
- name: Publish GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.windows.outputs.tag }}
files: dist/*
fail_on_unmatched_files: true
generate_release_notes: true
prerelease: ${{ needs.windows.outputs.isbeta == 'true' }}
-5
View File
@@ -7,11 +7,6 @@
brain/data/settings.json brain/data/settings.json
*.key *.key
*.pem *.pem
# Exception : la cle PUBLIQUE JWT du relais Patreon est destinee a etre
# embarquee dans le binaire. Pas de risque a la committer (c'est une cle
# publique par construction). Sans cette exception, le module licensing
# est silencieusement desactive dans les builds CI.
!core/src/main/resources/licensing/jwt-public-key.pem
# ============================================================================ # ============================================================================
# Java / Spring Boot / Maven # Java / Spring Boot / Maven
+12 -2
View File
@@ -7,7 +7,6 @@
[![Licence: AGPL v3](https://img.shields.io/badge/Licence-AGPL%20v3-blue.svg)](LICENSE) [![Licence: AGPL v3](https://img.shields.io/badge/Licence-AGPL%20v3-blue.svg)](LICENSE)
[![Documentation](https://img.shields.io/badge/docs-loremind--docs-green)](https://loremind-docs.igmlcreation.fr/) [![Documentation](https://img.shields.io/badge/docs-loremind--docs-green)](https://loremind-docs.igmlcreation.fr/)
[![Démo](https://img.shields.io/badge/d%C3%A9mo-en%20ligne-orange)](https://loremind-demo.igmlcreation.fr/) [![Démo](https://img.shields.io/badge/d%C3%A9mo-en%20ligne-orange)](https://loremind-demo.igmlcreation.fr/)
[![Patreon](https://img.shields.io/badge/Patreon-soutenir-red)](https://www.patreon.com/c/IGMLCreation)
[![Discord](https://img.shields.io/badge/Discord-rejoindre-5865F2)](https://discord.gg/cPpFzCjEzQ) [![Discord](https://img.shields.io/badge/Discord-rejoindre-5865F2)](https://discord.gg/cPpFzCjEzQ)
## Découvrir DM Loremind en vidéo ## Découvrir DM Loremind en vidéo
@@ -67,9 +66,20 @@ Quelques limites à connaître :
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien : DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs - **Canal bêta** — les nouveautés en avant-première, gratuites pour tous : bascule depuis les Paramètres (Docker) ou pré-version GitHub (bureau)
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs - **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
## Politique de signature du code (Code signing policy)
Signature de code gratuite fournie par [SignPath.io](https://about.signpath.io), certificat de [SignPath Foundation](https://signpath.org).
- **Signé** : les installeurs Windows (`.msi`) et le lanceur `DM Loremind.exe`, construits par GitHub Actions à partir de ce dépôt.
- **Auteurs et relecteurs** : [IGMLcreation](https://github.com/IGMLcreation)
- **Approbateurs** : [IGMLcreation](https://github.com/IGMLcreation) — chaque demande de signature est approuvée manuellement.
- **Confidentialité** : DM Loremind ne transmet aucune information à d'autres systèmes en réseau, sauf à la demande explicite de la personne qui l'utilise, l'installe ou l'exploite, et sauf la vérification des mises à jour, qui peut être désactivée. Voir la [politique de confidentialité](https://loremind-docs.igmlcreation.fr/docs/confidentialite).
Politique complète : [Politique de signature du code](https://loremind-docs.igmlcreation.fr/docs/signature-du-code).
## Licence ## Licence
DM Loremind est distribué sous licence **[GNU AGPL v3](LICENSE)**. DM Loremind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
+12 -2
View File
@@ -7,7 +7,6 @@
[![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](LICENSE) [![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](LICENSE)
[![Documentation](https://img.shields.io/badge/docs-loremind--docs-green)](https://loremind-docs.igmlcreation.fr/en/) [![Documentation](https://img.shields.io/badge/docs-loremind--docs-green)](https://loremind-docs.igmlcreation.fr/en/)
[![Demo](https://img.shields.io/badge/demo-online-orange)](https://loremind-demo.igmlcreation.fr/) [![Demo](https://img.shields.io/badge/demo-online-orange)](https://loremind-demo.igmlcreation.fr/)
[![Patreon](https://img.shields.io/badge/Patreon-support-red)](https://www.patreon.com/c/IGMLCreation)
[![Discord](https://img.shields.io/badge/Discord-join-5865F2)](https://discord.gg/cPpFzCjEzQ) [![Discord](https://img.shields.io/badge/Discord-join-5865F2)](https://discord.gg/cPpFzCjEzQ)
## See DM Loremind in action ## See DM Loremind in action
@@ -67,9 +66,20 @@ A few limitations to be aware of:
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support: DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs - **Beta channel** — new features ahead of time, free for everyone: switch from Settings (Docker) or install a GitHub pre-release (desktop)
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback - **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
## Code signing policy
Free code signing provided by [SignPath.io](https://about.signpath.io), certificate by [SignPath Foundation](https://signpath.org).
- **Signed**: the Windows installers (`.msi`) and the `DM Loremind.exe` launcher, built by GitHub Actions from this repository.
- **Committers and reviewers**: [IGMLcreation](https://github.com/IGMLcreation)
- **Approvers**: [IGMLcreation](https://github.com/IGMLcreation) — each signing request is approved manually.
- **Privacy**: DM Loremind does not transfer any information to other networked systems unless specifically requested by the person using, installing or operating it, except for the update check, which can be turned off. See the [privacy policy](https://loremind-docs.igmlcreation.fr/en/docs/confidentialite).
Full policy: [Code signing policy](https://loremind-docs.igmlcreation.fr/en/docs/signature-du-code).
## License ## License
DM Loremind is distributed under the **[GNU AGPL v3](LICENSE)** license. DM Loremind is distributed under the **[GNU AGPL v3](LICENSE)** license.
+80
View File
@@ -9,6 +9,7 @@ from app.application.generate_page import GeneratePageUseCase
from app.application.llm_json import load_json_object from app.application.llm_json import load_json_object
from app.application.llm_retry import generate_with_retry from app.application.llm_retry import generate_with_retry
from app.application.prompts import conversation_title as title_prompts from app.application.prompts import conversation_title as title_prompts
from app.application.prompts import guided_answers as guided_answers_prompts
from app.application.prompts import narrative_fields as narrative_fields_prompts from app.application.prompts import narrative_fields as narrative_fields_prompts
from app.application.prompts import scene_drafts as scene_drafts_prompts from app.application.prompts import scene_drafts as scene_drafts_prompts
from app.application.prompts import session_recap as session_recap_prompts from app.application.prompts import session_recap as session_recap_prompts
@@ -290,3 +291,82 @@ async def generate_session_recap(
if not recap: if not recap:
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.") raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
return SessionRecapResponseDTO(recap=recap) return SessionRecapResponseDTO(recap=recap)
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
class GuidedOptionDTO(BaseModel):
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
value: str
label: str = Field(default="")
class GuidedFieldDTO(BaseModel):
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
key: str
label: str = Field(default="")
hint: str = Field(default="")
step: str = Field(default="")
options: list[GuidedOptionDTO] = Field(default_factory=list)
class GuidedAnswersRequestDTO(BaseModel):
method_name: str = Field(default="")
method_principle: str = Field(default="")
idea: str = Field(default="")
context: str = Field(default="")
fields: list[GuidedFieldDTO] = Field(default_factory=list)
existing: dict[str, str] = Field(default_factory=dict)
class GuidedAnswersResponseDTO(BaseModel):
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
answers: dict[str, str]
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
async def generate_guided_answers(
body: GuidedAnswersRequestDTO,
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
language: Annotated[str, Depends(get_user_language)],
) -> GuidedAnswersResponseDTO:
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
"""
by_key = {f.key: f for f in body.fields if f.key}
prompt = guided_answers_prompts.guided_answers_prompt(
body.method_name, body.method_principle, body.idea, body.context,
[f.model_dump() for f in body.fields], body.existing, language)
try:
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
except LLMProviderError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
parsed, _ = load_json_object(raw)
if not isinstance(parsed, dict):
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
out: dict[str, str] = {}
if not isinstance(raw, dict):
return out
for key, value in raw.items():
field = by_key.get(str(key))
if field is None or not isinstance(value, (str, int, float)):
continue
text = str(value).strip()
if not text:
continue
if field.options and text not in {o.value for o in field.options}:
continue
out[field.key] = text
return out
+7 -1
View File
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
sections: dict[str, str] sections: dict[str, str]
page_count: int page_count: int
ocr_page_count: int ocr_page_count: int
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
sections_by_language: dict[str, dict[str, str]] = {}
source_language: str = ""
@router.post("/import/rules", response_model=RulesImportResponseDTO) @router.post("/import/rules", response_model=RulesImportResponseDTO)
@@ -70,6 +73,8 @@ async def import_rules(
sections=result.sections, sections=result.sections,
page_count=result.page_count, page_count=result.page_count,
ocr_page_count=result.ocr_page_count, ocr_page_count=result.ocr_page_count,
sections_by_language=result.sections_by_language,
source_language=result.source_language,
) )
@@ -115,6 +120,7 @@ async def import_rules_stream(
@router.post("/import/campaign/stream") @router.post("/import/campaign/stream")
async def import_campaign_stream( async def import_campaign_stream(
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)], use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
language: Annotated[str, Depends(get_user_language)],
file: UploadFile = File(...), file: UploadFile = File(...),
) -> StreamingResponse: ) -> StreamingResponse:
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE). """Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
@@ -131,7 +137,7 @@ async def import_campaign_stream(
yield sse_event("error", {"message": upload_error}) yield sse_event("error", {"message": upload_error})
return return
try: try:
async for ev in use_case.stream(content): async for ev in use_case.stream(content, language=language):
event_type = ev.pop("type") event_type = ev.pop("type")
yield sse_event(event_type, ev) yield sse_event(event_type, ev)
except PdfExtractionError as exc: except PdfExtractionError as exc:
+14 -12
View File
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
# des appels LLM est divisé d'autant. 1 = comportement séquentiel. # des appels LLM est divisé d'autant. 1 = comportement séquentiel.
self._map_concurrency = max(1, map_concurrency) self._map_concurrency = max(1, map_concurrency)
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult: async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
"""Variante non-streamée : traite tout puis renvoie l'arbre complet.""" """Variante non-streamée : traite tout puis renvoie l'arbre complet."""
doc = self._extractor.extract(pdf_bytes) doc = self._extractor.extract(pdf_bytes)
chunks = chunk_text(doc.full_text, self._chunk_target_tokens) chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
@@ -371,7 +371,7 @@ class ImportCampaignUseCase:
for start in range(0, total, self._map_concurrency): for start in range(0, total, self._map_concurrency):
wave = list(enumerate(chunks))[start:start + self._map_concurrency] wave = list(enumerate(chunks))[start:start + self._map_concurrency]
results = await asyncio.gather(*( results = await asyncio.gather(*(
self._map_chunk(c, index=i, total=total, toc_block=toc_block) self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
for i, c in wave for i, c in wave
)) ))
for res in results: for res in results:
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
npcs=merger.npcs(), npcs=merger.npcs(),
) )
async def stream(self, pdf_bytes: bytes): async def stream(self, pdf_bytes: bytes, language: str = "fr"):
"""Variante streamée : yield des évènements d'avancement. """Variante streamée : yield des évènements d'avancement.
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count, {"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
@@ -432,7 +432,7 @@ class ImportCampaignUseCase:
for start in range(0, total, self._map_concurrency): for start in range(0, total, self._map_concurrency):
wave = list(enumerate(chunks))[start:start + self._map_concurrency] wave = list(enumerate(chunks))[start:start + self._map_concurrency]
gathered = asyncio.gather( gathered = asyncio.gather(
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block) *(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
for i, c in wave), for i, c in wave),
return_exceptions=True, return_exceptions=True,
) )
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
# --- MAP : un morceau → sous-arbre --------------------------------------- # --- MAP : un morceau → sous-arbre ---------------------------------------
async def _map_chunk( async def _map_chunk(
self, chunk: str, *, index: int, total: int, toc_block: str = "" self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
) -> dict: ) -> dict:
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}.""" """Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
return await self._extract_payload( return await self._extract_payload(
chunk, index=index, total=total, depth=0, toc_block=toc_block) chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
async def _extract_payload( async def _extract_payload(
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "" self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
language: str = "fr",
) -> dict: ) -> dict:
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée, """Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé).""" dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else "" toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
prompt = ( prompt = (
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME) prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
+ prompts.language_block(language)
+ toc_section + toc_section
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n" + f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
"Renvoie maintenant le JSON de l'arborescence." "Renvoie maintenant le JSON de l'arborescence."
@@ -591,9 +593,9 @@ class ImportCampaignUseCase:
f"Le modèle est trop lent sur le morceau {index + 1} : " f"Le modèle est trop lent sur le morceau {index + 1} : "
"re-découpage en 2 moitiés plus digestes…") "re-découpage en 2 moitiés plus digestes…")
a = await self._extract_payload( a = await self._extract_payload(
left, index=index, total=total, depth=depth + 1, toc_block=toc_block) left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
b = await self._extract_payload( b = await self._extract_payload(
right, index=index, total=total, depth=depth + 1, toc_block=toc_block) right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]} return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
payload, truncated = self._parse_payload(raw, index=index) payload, truncated = self._parse_payload(raw, index=index)
@@ -607,9 +609,9 @@ class ImportCampaignUseCase:
f"Réponse du modèle coupée sur le morceau {index + 1} : " f"Réponse du modèle coupée sur le morceau {index + 1} : "
"re-découpage en 2 moitiés plus digestes…") "re-découpage en 2 moitiés plus digestes…")
a = await self._extract_payload( a = await self._extract_payload(
left, index=index, total=total, depth=depth + 1, toc_block=toc_block) left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
b = await self._extract_payload( b = await self._extract_payload(
right, index=index, total=total, depth=depth + 1, toc_block=toc_block) right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]} return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
if truncated: if truncated:
logger.warning( logger.warning(
+63 -1
View File
@@ -26,6 +26,7 @@ from app.application.import_status import (
from app.application.llm_json import load_json_object, looks_like_truncated_json from app.application.llm_json import load_json_object, looks_like_truncated_json
from app.application.llm_retry import generate_with_retry from app.application.llm_retry import generate_with_retry
from app.application.prompts import import_rules as prompts from app.application.prompts import import_rules as prompts
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
from app.application.streaming import with_heartbeat from app.application.streaming import with_heartbeat
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
@@ -90,6 +91,9 @@ _ANCHORS_SCHEMA: dict = {
} }
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
_DETECT_CHARS = 20_000
class _SectionMerger: class _SectionMerger:
"""Fusionne les sections issues des différents morceaux, ordre préservé. """Fusionne les sections issues des différents morceaux, ordre préservé.
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
merger = _SectionMerger() merger = _SectionMerger()
for i, chunk in enumerate(chunks): for i, chunk in enumerate(chunks):
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language)) merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
sections = merger.result()
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
by_language = {source: sections}
translator = RulesTranslator(self._llm)
for target in other_languages(source):
try:
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
by_language[target] = {
titles.get(title, title): await translator.translate_content(content, source, target)
for title, content in sections.items()
}
except LLMProviderError as exc:
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
return RulesImportResult( return RulesImportResult(
sections=merger.result(), sections=sections,
page_count=doc.page_count, page_count=doc.page_count,
ocr_page_count=doc.ocr_page_count, ocr_page_count=doc.ocr_page_count,
sections_by_language=by_language,
source_language=source,
) )
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG): async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
@@ -344,14 +363,57 @@ class ImportRulesUseCase:
"de contexte (num_ctx) ou essayez un autre modèle."} "de contexte (num_ctx) ou essayez un autre modèle."}
return return
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
# langue de l'application. Un échec de traduction n'annule pas l'import.
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
by_language: dict[str, dict[str, str]] = {source: sections}
for target in other_languages(source):
try:
async for ev in self._translate_events(sections, source, target):
if ev["type"] == "_translated":
by_language[target] = ev["sections"]
else:
yield ev
except LLMProviderError as exc:
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
yield {"type": "status",
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
yield { yield {
"type": "done", "type": "done",
"sections": sections, "sections": sections,
"sections_by_language": by_language,
"source_language": source,
"page_count": doc.page_count, "page_count": doc.page_count,
"ocr_page_count": doc.ocr_page_count, "ocr_page_count": doc.ocr_page_count,
"skipped": skipped, "skipped": skipped,
} }
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
"""Évènements d'avancement de la traduction ; le dernier est
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
translator = RulesTranslator(self._llm)
titles = list(sections)
total = len(titles)
label = language_name(target)
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
mapping: dict[str, str] = {}
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
if kind == "heartbeat":
yield {"type": "heartbeat", "current": 0, "total": total}
elif kind == "result":
mapping = unique_titles(payload)
out: dict[str, str] = {}
for i, title in enumerate(titles):
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
"current": i + 1, "total": total}
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
if kind == "heartbeat":
yield {"type": "heartbeat", "current": i + 1, "total": total}
elif kind == "result":
out[mapping.get(title, title)] = payload
yield {"type": "_translated", "sections": out}
# --- MAP : un morceau → sections ----------------------------------------- # --- MAP : un morceau → sections -----------------------------------------
async def _map_chunk(self, chunk: str, *, index: int, total: int, async def _map_chunk(self, chunk: str, *, index: int, total: int,
+3
View File
@@ -113,5 +113,8 @@ async def generate_with_retry(
+ str(exc)[:160] + str(exc)[:160]
) )
await asyncio.sleep(wait) await asyncio.sleep(wait)
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
# l'essai suivant est lancé (il peut durer plusieurs minutes).
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
assert last_error is not None assert last_error is not None
raise last_error raise last_error
@@ -0,0 +1,71 @@
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
Plan du méchant…).
Générique : le front décrit la méthode (nom ; principe suivi du rôle de chaque étape, comme
dans l'assistant manuel) et ses questions (clé, libellé,
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
"""
from app.core.language import language_name
def _field_line(field: dict) -> str:
key = str(field.get("key") or "").strip()
label = str(field.get("label") or key).strip()
hint = str(field.get("hint") or "").strip()
step = str(field.get("step") or "").strip()
line = f'- "{key}"'
if step:
line += f" [{step}]"
line += f" : {label}"
if hint:
line += f" — {hint}"
options = field.get("options") or []
if options:
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
line += f" — UNE valeur parmi : {values}"
return line
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
fields: list[dict], existing: dict[str, str], language: str) -> str:
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
existing_lines = "\n".join(
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
existing_block = (
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
f"{existing_lines}\n" if existing_lines else ""
)
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
guide = method_principle.strip() if method_principle else ""
guide_block = (
"\nLa méthode, telle que le MJ la suit à la main (principe, puis rôle de chaque étape) :\n"
f"{guide}\n" if guide else ""
)
return (
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
f"avec la méthode « {method_name.strip() or 'guidée'} ».\n"
f"{guide_block}\n"
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
f"{context_block}{existing_block}\n"
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
f"{fields_list}\n\n"
"Règles IMPÉRATIVES :\n"
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
"valeurs proposées.\n"
"- Pars de l'idée du MJ et développe-la : garde son ton, ses lieux, ses personnages ; n'en change "
"pas le sujet.\n"
"- Respecte la méthode : chaque réponse remplit le rôle de SON étape, tel que décrit ci-dessus "
"(ex. une épreuve qui ne se règle pas par un combat, des pistes qui se recoupent). Ne mélange pas "
"les étapes.\n"
"- Toutes les réponses forment UNE aventure cohérente, concrète et jouable "
"(noms, lieux, motivations précises ; pas de généralités).\n"
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
f"- Rédige les réponses en {language_name(language)}.\n"
"Renvoie maintenant le JSON."
)
@@ -1,7 +1,29 @@
"""Prompts de l'import de campagne PDF (cf. import_campaign.py).""" """Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
from app.core.language import language_name
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties. # Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
DEFAULT_ARC_NAME = "Aventure principale" DEFAULT_ARC_NAME = "Aventure principale"
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
def default_arc_name(language: str) -> str:
"""Nom de l'arc unique, dans la langue de l'interface."""
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
def language_block(language: str) -> str:
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
name = language_name(language)
return (
"\n\nLANGUE DE SORTIE :\n"
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
"fidèlement, sans les résumer davantage.\n"
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
)
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle. MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page). On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
+136
View File
@@ -0,0 +1,136 @@
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
pour rester sous les limites de sortie des modèles.
"""
from __future__ import annotations
import re
from app.application.llm_json import load_json_object
from app.application.llm_retry import generate_with_retry
from app.core.language import language_name
from app.domain.ports import LLMProvider
LANGUAGES = ("fr", "en")
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
CHUNK_CHARS = 6000
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
def detect_language(text: str, default: str = "fr") -> str:
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
fr = sum(1 for w in words if w in _FR_WORDS)
en = sum(1 for w in words if w in _EN_WORDS)
if fr == en:
return default if default in LANGUAGES else "fr"
return "fr" if fr > en else "en"
def other_languages(source: str) -> list[str]:
return [lang for lang in LANGUAGES if lang != source]
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
if len(text) <= max_chars:
return [text]
chunks: list[str] = []
current = ""
for para in re.split(r"(\n\s*\n)", text):
if len(current) + len(para) <= max_chars:
current += para
continue
if current.strip():
chunks.append(current)
current = ""
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
cut = para.rfind("\n", 0, max_chars)
cut = cut if cut > 0 else max_chars
chunks.append(para[:cut])
para = para[cut:]
current = para
if current.strip():
chunks.append(current)
return chunks
def content_prompt(text: str, source: str, target: str) -> str:
return (
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
f"vers la langue « {language_name(target)} ».\n\n"
"Règles IMPÉRATIVES :\n"
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
"objets nommés.\n"
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
"Extrait :\n"
f"{text}"
)
def titles_prompt(titles: list[str], source: str, target: str) -> str:
listing = "\n".join(f"- {t}" for t in titles)
return (
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
"Garde les noms propres tels quels.\n"
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
f"{listing}"
)
class RulesTranslator:
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
def __init__(self, llm: LLMProvider) -> None:
self._llm = llm
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
if not titles:
return {}
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
output_format="json", temperature=0.2)
parsed, _ = load_json_object(raw)
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
out: dict[str, str] = {}
for title in titles:
value = mapping.get(title) if isinstance(mapping, dict) else None
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
return out
async def translate_content(self, text: str, source: str, target: str) -> str:
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
if not text or not text.strip():
return text
parts = []
for chunk in split_markdown(text):
if not chunk.strip():
parts.append(chunk)
continue
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
temperature=0.2)
parts.append(translated.strip())
return "\n\n".join(p for p in parts if p.strip())
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
seen: dict[str, int] = {}
out: dict[str, str] = {}
for original, translated in titles.items():
count = seen.get(translated, 0)
seen[translated] = count + 1
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
return out
+4
View File
@@ -367,6 +367,10 @@ class RulesImportResult:
sections: dict[str, str] sections: dict[str, str]
page_count: int page_count: int
ocr_page_count: int ocr_page_count: int
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
source_language: str = ""
def to_markdown(self) -> str: def to_markdown(self) -> str:
"""Assemble les sections en un markdown monolithique (## titre + contenu). """Assemble les sections en un markdown monolithique (## titre + contenu).
+1 -1
View File
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
app = FastAPI( app = FastAPI(
title="LoreMind Brain", title="LoreMind Brain",
description="Backend IA pour la génération de contenu narratif.", description="Backend IA pour la génération de contenu narratif.",
version="1.4.0-beta", version="1.6.2",
) )
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+62
View File
@@ -0,0 +1,62 @@
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
from __future__ import annotations
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
from app.application.prompts.guided_answers import guided_answers_prompt
def _fields() -> dict[str, GuidedFieldDTO]:
return {
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
}
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
prompt = guided_answers_prompt(
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
{"truth": "Le notaire est coupable", "empty": " "}, "en")
assert "Une tour qui se rallume" in prompt
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
assert "Le notaire est coupable" in prompt
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
assert "Campagne : Valfroide" in prompt
assert "anglais" in prompt
def test_prompt_lists_the_method_steps_and_asks_to_follow_them():
guide = ("Cinq temps dans un même lieu.\n\n"
"- Salle 2 : l'épreuve : ici, l'épée ne suffit pas.\n"
"- Salle 3 : le revers : les choses se compliquent.")
p = guided_answers_prompt("Donjon en 5 salles", guide, "Une crypte", "", [{"key": "room2.name"}], {}, "fr")
assert "telle que le MJ la suit à la main" in p
assert "- Salle 2 : l'épreuve : ici, l'épée ne suffit pas." in p
assert "rôle de SON étape" in p
assert "Idée de départ du MJ : Une crypte" in p
def test_prompt_without_idea_asks_for_an_original_adventure():
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
assert "propose une aventure originale" in prompt
assert "français" in prompt
def test_clean_keeps_requested_keys_and_valid_choices_only():
out = _clean_guided_answers({
"title": " L'héritage empoisonné ",
"node1.nature": "npc",
"unknown": "ignorée",
"empty": "",
}, _fields())
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
def test_clean_rejects_an_invalid_choice_and_non_text_values():
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
assert out == {}
assert _clean_guided_answers("pas un objet", _fields()) == {}
+52
View File
@@ -100,6 +100,8 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
monkeypatch.setattr("app.application.import_rules.chunk_text", monkeypatch.setattr("app.application.import_rules.chunk_text",
lambda *a, **k: ["AAA premier", "BBB second"]) lambda *a, **k: ["AAA premier", "BBB second"])
llm = ContentLLM([ llm = ContentLLM([
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
("Traduis cet extrait", "spells"),
("AAA premier", LLMProviderError("HTTP 503 saturé")), ("AAA premier", LLMProviderError("HTTP 503 saturé")),
("BBB second", '{"Magie":"sorts"}'), ("BBB second", '{"Magie":"sorts"}'),
]) ])
@@ -111,6 +113,25 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
assert done["type"] == "done" assert done["type"] == "done"
assert done["sections"] == {"Magie": "sorts"} assert done["sections"] == {"Magie": "sorts"}
assert done["skipped"] == 1 assert done["skipped"] == 1
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
assert done["source_language"] == "fr"
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
llm = ContentLLM([
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
])
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
events = [e async for e in uc.stream(b"pdf")]
done = events[-1]
assert done["type"] == "done"
assert done["source_language"] == "en"
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep): async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
@@ -155,3 +176,34 @@ async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc())) uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
events = [e async for e in uc.stream(b"pdf")] events = [e async for e in uc.stream(b"pdf")]
assert events[-1]["type"] == "error" assert events[-1]["type"] == "error"
class _RecordingLLM(ScriptedLLM):
"""ScriptedLLM qui garde les prompts reçus."""
def __init__(self, responses: list) -> None:
super().__init__(responses)
self.prompts: list[str] = []
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
self.prompts.append(prompt)
return await super().generate(prompt, output_format=output_format, temperature=temperature)
async def test_campaign_import_writes_in_the_interface_language_and_keeps_names():
llm = _RecordingLLM([_TREE])
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
events = [e async for e in uc.stream(b"pdf", language="en")]
assert events[-1]["type"] == "done"
prompt = llm.prompts[0]
assert "LANGUE DE SORTIE" in prompt
assert "en anglais" in prompt
assert "noms propres" in prompt
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
async def test_campaign_import_defaults_to_french():
llm = _RecordingLLM([_TREE])
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
assert "en français" in llm.prompts[0]
assert '"Aventure principale"' in llm.prompts[0]
+18
View File
@@ -110,3 +110,21 @@ async def test_rate_limit_respects_suggested_retry_after(slept):
assert await generate_with_retry(llm, "p") == "ok" assert await generate_with_retry(llm, "p") == "ok"
# min(8 + 2, 60) = 10 # min(8 + 2, 60) = 10
assert slept == [10.0] assert slept == [10.0]
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
import asyncio
from app.application.import_status import reset_status_queue, set_status_queue
queue: asyncio.Queue = asyncio.Queue()
token = set_status_queue(queue)
try:
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
assert await generate_with_retry(llm, "p") == "ok"
finally:
reset_status_queue(token)
messages = [queue.get_nowait() for _ in range(queue.qsize())]
assert "nouvel essai dans 3s" in messages[0]
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
+60
View File
@@ -0,0 +1,60 @@
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
from __future__ import annotations
from app.application.rules_translation import (
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
)
class EchoLLM:
"""Traduit « en majuscules » et garde trace des prompts reçus."""
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
self.prompts: list[str] = []
self._titles_json = titles_json
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
self.prompts.append(prompt)
if "Traduis ces titres" in prompt:
return self._titles_json
return prompt.split("Extrait :\n", 1)[1].upper()
def test_detect_language():
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
assert detect_language("", default="en") == "en"
assert other_languages("fr") == ["en"]
assert other_languages("en") == ["fr"]
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
assert split_markdown("court") == ["court"]
text = "\n\n".join(["a" * 40] * 10)
chunks = split_markdown(text, max_chars=100)
assert all(len(c) <= 100 for c in chunks)
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
def test_split_markdown_cuts_a_giant_paragraph():
chunks = split_markdown("x" * 250, max_chars=100)
assert [len(c) for c in chunks] == [100, 100, 50]
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
llm = EchoLLM()
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
assert out == "## COMBAT\n\nCHAQUE ROUND."
assert "noms propres" in llm.prompts[0]
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
async def test_translate_titles_falls_back_to_the_original_title():
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
assert out == {"Combat": "Fighting", "Magie": "Magie"}
def test_unique_titles_avoids_collisions():
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
+1 -26
View File
@@ -14,7 +14,7 @@
<groupId>com.loremind</groupId> <groupId>com.loremind</groupId>
<artifactId>loremind-core</artifactId> <artifactId>loremind-core</artifactId>
<version>1.4.0-beta</version> <version>1.6.2</version>
<name>LoreMind Core</name> <name>LoreMind Core</name>
<description>Backend Core - Architecture Hexagonale</description> <description>Backend Core - Architecture Hexagonale</description>
@@ -137,31 +137,6 @@
<version>5.1.0</version> <version>5.1.0</version>
</dependency> </dependency>
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle.
>= 10.0.2 : corrige CVE-2025-53864 (DoS par JSON profondement imbrique
dans le claim set — surface critique : JWT colle par l'utilisateur). -->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>10.9.1</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.84</version>
</dependency>
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify().
>= 1.15 : embarque un protobuf-java corrige (CVE-2024-7254). -->
<dependency>
<groupId>com.google.crypto.tink</groupId>
<artifactId>tink</artifactId>
<version>1.21.0</version>
</dependency>
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif : <!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
compatible distribution bureau locale via jpackage). Sert l'export PDF compatible distribution bureau locale via jpackage). Sert l'export PDF
d'une campagne (livret). --> d'une campagne (livret). -->
@@ -0,0 +1,20 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CampaignContentSearchService {
private final CampaignContentSearchRepository repository;
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
this.repository = repository;
}
public List<CampaignContentHit> search(String query) {
String value = query == null ? "" : query.strip();
return value.length() < 2 ? List.of() : repository.searchByName(value);
}
}
@@ -0,0 +1,86 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* IA des méthodes guidées (Mentor d'écriture) : propose des réponses aux questions d'une
* méthode à partir de l'idée de départ du MJ et de la campagne. Rien n'est enregistré : le
* front remplit les champs vides et le MJ relit, corrige ou relance.
*
* <p>Garde-fous : nombre de questions et longueur des textes bornés (le prompt reste
* raisonnable) ; en retour, seules les clés demandées sont gardées, et une question à choix
* n'accepte qu'une des valeurs proposées.</p>
*/
@Service
public class GuidedAssistService {
static final int MAX_QUESTIONS = 80;
static final int MAX_TEXT = 4_000;
private final GuidedMethodAssistant assistant;
private final CampaignContextFormatter contextFormatter;
public GuidedAssistService(GuidedMethodAssistant assistant, CampaignContextFormatter contextFormatter) {
this.assistant = assistant;
this.contextFormatter = contextFormatter;
}
/** Demande à proposer des réponses. @throws IllegalArgumentException aucune question valide */
public Map<String, String> suggest(String campaignId, String methodName, String principle, String idea,
List<Question> questions, Map<String, String> existing) {
List<Question> valid = questions == null ? List.of() : questions.stream()
.filter(Objects::nonNull)
.filter(q -> q.key() != null && !q.key().isBlank())
.limit(MAX_QUESTIONS)
.toList();
if (valid.isEmpty()) {
throw new IllegalArgumentException("Aucune question à laquelle répondre.");
}
Map<String, String> answers = assistant.answer(cap(methodName), cap(principle), cap(idea),
contextFormatter.format(campaignId), valid, capAll(existing));
return keepValid(answers, valid);
}
/** Clés demandées uniquement, valeurs non vides ; choix limités aux valeurs proposées. */
static Map<String, String> keepValid(Map<String, String> answers, List<Question> questions) {
Map<String, String> out = new LinkedHashMap<>();
if (answers == null) return out;
Map<String, Question> byKey = questions.stream()
.collect(Collectors.toMap(Question::key, q -> q, (a, b) -> a, LinkedHashMap::new));
for (Map.Entry<String, String> e : answers.entrySet()) {
Question q = byKey.get(e.getKey());
String value = e.getValue() == null ? "" : e.getValue().trim();
if (q == null || value.isEmpty()) continue;
if (q.options() != null && !q.options().isEmpty()) {
Set<String> allowed = q.options().stream().map(Choice::value).collect(Collectors.toSet());
if (!allowed.contains(value)) continue;
}
out.put(q.key(), cap(value));
}
return out;
}
private static Map<String, String> capAll(Map<String, String> existing) {
Map<String, String> out = new LinkedHashMap<>();
if (existing == null) return out;
existing.forEach((k, v) -> {
if (k != null && v != null && !v.isBlank()) out.put(k, cap(v.trim()));
});
return out;
}
private static String cap(String s) {
if (s == null) return "";
return s.length() > MAX_TEXT ? s.substring(0, MAX_TEXT) : s;
}
}
@@ -1,4 +1,4 @@
package com.loremind.application.licensing; package com.loremind.application.channel;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@@ -1,6 +1,7 @@
package com.loremind.application.gamesystemcontext; package com.loremind.application.gamesystemcontext;
import com.loremind.domain.gamesystemcontext.GameSystem; import com.loremind.domain.gamesystemcontext.GameSystem;
import com.loremind.domain.shared.ports.CurrentLanguage;
import com.loremind.domain.gamesystemcontext.GenerationIntent; import com.loremind.domain.gamesystemcontext.GenerationIntent;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository; import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import com.loremind.domain.generationcontext.GameSystemContext; import com.loremind.domain.generationcontext.GameSystemContext;
@@ -36,9 +37,11 @@ public class GameSystemContextBuilder {
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$"); private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
private final GameSystemRepository gameSystemRepository; private final GameSystemRepository gameSystemRepository;
private final CurrentLanguage currentLanguage;
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) { public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
this.gameSystemRepository = gameSystemRepository; this.gameSystemRepository = gameSystemRepository;
this.currentLanguage = currentLanguage;
} }
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) { public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
} }
private GameSystemContext build(GameSystem gs, GenerationIntent intent) { private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown()); // Règles dans la langue de l'interface (repli sur l'autre version si celle-ci est vide).
Map<String, String> allSections = parseH2Sections(gs.rulesFor(currentLanguage.get()));
Map<String, String> filtered = filterByIntent(allSections, intent); Map<String, String> filtered = filterByIntent(allSections, intent);
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered); return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
} }
@@ -59,6 +59,7 @@ public class GameSystemService {
String name, String name,
String description, String description,
String rulesMarkdown, String rulesMarkdown,
String rulesMarkdownEn,
List<TemplateField> characterTemplate, List<TemplateField> characterTemplate,
List<TemplateField> npcTemplate, List<TemplateField> npcTemplate,
List<TemplateField> enemyTemplate, List<TemplateField> enemyTemplate,
@@ -72,6 +73,7 @@ public class GameSystemService {
.name(data.name()) .name(data.name())
.description(data.description()) .description(data.description())
.rulesMarkdown(data.rulesMarkdown()) .rulesMarkdown(data.rulesMarkdown())
.rulesMarkdownEn(data.rulesMarkdownEn())
.foundryActorType(normalize(data.foundryActorType())) .foundryActorType(normalize(data.foundryActorType()))
.author(normalize(data.author())) .author(normalize(data.author()))
.isPublic(data.isPublic()) .isPublic(data.isPublic())
@@ -96,6 +98,7 @@ public class GameSystemService {
existing.setName(data.name()); existing.setName(data.name());
existing.setDescription(data.description()); existing.setDescription(data.description());
existing.setRulesMarkdown(data.rulesMarkdown()); existing.setRulesMarkdown(data.rulesMarkdown());
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
existing.replaceCharacterTemplate(data.characterTemplate()); existing.replaceCharacterTemplate(data.characterTemplate());
existing.replaceNpcTemplate(data.npcTemplate()); existing.replaceNpcTemplate(data.npcTemplate());
existing.replaceEnemyTemplate(data.enemyTemplate()); existing.replaceEnemyTemplate(data.enemyTemplate());
@@ -1,266 +0,0 @@
package com.loremind.application.licensing;
import com.loremind.domain.licensing.License;
import com.loremind.domain.licensing.LicenseClaims;
import com.loremind.domain.licensing.LicenseSnapshot;
import com.loremind.domain.licensing.LicenseStatus;
import com.loremind.domain.licensing.RegistryCredentials;
import com.loremind.domain.licensing.ports.JwtVerifier;
import com.loremind.domain.licensing.ports.LicenseRelay;
import com.loremind.domain.licensing.ports.LicenseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
/**
* Service application pour la gestion de la licence Patreon.
* <p>
* Responsabilites :
* <ul>
* <li>Installer un nouveau JWT recu du relais (apres OAuth utilisateur)</li>
* <li>Calculer le {@link LicenseStatus} courant en respectant la grace period</li>
* <li>Renouveler le JWT avant expiration en appelant le relais</li>
* <li>Activer/desactiver le toggle "canal beta" cote utilisateur</li>
* <li>Distribuer les credentials registry pour le pull beta</li>
* </ul>
*/
@Service
public class LicenseService {
private static final Logger log = LoggerFactory.getLogger(LicenseService.class);
private final LicenseRepository repository;
private final JwtVerifier jwtVerifier;
private final LicenseRelay relay;
private final long gracePeriodSeconds;
private final long refreshBeforeExpirySeconds;
private final boolean licensingEnabled;
public LicenseService(
LicenseRepository repository,
JwtVerifier jwtVerifier,
LicenseRelay relay,
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays,
@Value("${licensing.enabled:true}") boolean licensingEnabled) {
this.repository = repository;
this.jwtVerifier = jwtVerifier;
this.relay = relay;
this.gracePeriodSeconds = gracePeriodDays * 86_400L;
this.refreshBeforeExpirySeconds = refreshBeforeExpiryDays * 86_400L;
this.licensingEnabled = licensingEnabled;
}
/**
* @return true si le licensing Patreon est actif : il faut a la fois que la
* feature soit activee ({@code licensing.enabled}, faux en mode
* bureau/local ou le gating par image Docker n'a aucun sens) ET que
* le verifier soit configure (cle publique presente). Faux => l'UI
* masque toute la section Patreon, le daemon de refresh est no-op,
* et le canal beta est desactive.
*/
public boolean isLicensingEnabled() {
return licensingEnabled && jwtVerifier.isConfigured();
}
/**
* Genere ou retourne l'instance_id stable de cette installation.
* Stocke dans la licence elle-meme. Si pas de licence, en cree un volatil
* (sera persiste a la prochaine connexion).
*/
public String getOrCreateInstanceId() {
return repository.findCurrent()
.map(License::getInstanceId)
.orElseGet(() -> "li-" + UUID.randomUUID());
}
/**
* Construit l'URL OAuth pour ouvrir dans le navigateur de l'utilisateur.
*/
public String buildConnectUrl() {
return relay.buildConnectUrl(getOrCreateInstanceId());
}
/**
* Installe un JWT recu du relais (l'utilisateur l'a colle dans l'UI ou
* recu via deep-link). Verifie la signature, extrait les claims, persiste.
*/
public LicenseSnapshot installToken(String rawJwt) throws InstallException {
if (!jwtVerifier.isConfigured()) {
throw new InstallException("Licensing feature not enabled (no public key configured)");
}
LicenseClaims claims;
try {
claims = jwtVerifier.verify(rawJwt);
} catch (JwtVerifier.JwtVerificationException e) {
throw new InstallException("Invalid JWT: " + e.getMessage());
}
Instant now = Instant.now();
if (claims.expiresAt().isBefore(now)) {
throw new InstallException("JWT already expired");
}
Optional<License> existing = repository.findCurrent();
License toSave = License.builder()
.id("current")
.rawJwt(rawJwt)
.patreonUserId(claims.subject())
.tierId(claims.tierId())
.instanceId(claims.instanceId())
.issuedAt(claims.issuedAt())
.expiresAt(claims.expiresAt())
.lastRefreshAttemptAt(now)
.lastRefreshSucceeded(true)
// Au premier install, on active le canal beta par defaut.
// Sur reinstall apres deconnexion, on respecte la valeur precedente.
.betaChannelEnabled(existing.map(License::isBetaChannelEnabled).orElse(true))
.createdAt(existing.map(License::getCreatedAt).orElse(now))
.build();
License saved = repository.save(toSave);
log.info("Patreon license installed for user={} tier={} expires={}",
saved.getPatreonUserId(), saved.getTierId(), saved.getExpiresAt());
return snapshotOf(saved, now);
}
/**
* Etat courant de la licence pour exposition UI / decision technique.
*/
public LicenseSnapshot getCurrentSnapshot() {
return repository.findCurrent()
.map(l -> snapshotOf(l, Instant.now()))
.orElseGet(LicenseSnapshot::none);
}
/**
* Supprime la licence (deconnexion volontaire de Patreon par l'utilisateur).
*/
public void disconnect() {
repository.deleteCurrent();
log.info("Patreon license removed (user disconnect)");
}
/**
* Active ou desactive le canal beta. Necessite une licence valide ou en grace.
*/
public LicenseSnapshot setBetaChannelEnabled(boolean enabled) {
License current = repository.findCurrent()
.orElseThrow(() -> new IllegalStateException("No license installed"));
current.setBetaChannelEnabled(enabled);
License saved = repository.save(current);
return snapshotOf(saved, Instant.now());
}
/**
* Tente un refresh si la licence est proche de l'expiration. Idempotent.
* Appele par le daemon planifie + manuellement via l'UI ("Reessayer").
*/
public void refreshIfNeeded() {
Optional<License> opt = repository.findCurrent();
if (opt.isEmpty()) return;
License current = opt.get();
Instant now = Instant.now();
long secondsUntilExpiry = Duration.between(now, current.getExpiresAt()).getSeconds();
if (secondsUntilExpiry > refreshBeforeExpirySeconds) {
return;
}
doRefresh(current, now);
}
/**
* Force un refresh immediat (bouton UI "Reessayer maintenant").
*/
public void forceRefresh() {
repository.findCurrent().ifPresent(license -> doRefresh(license, Instant.now()));
}
/**
* Tente le refresh aupres du relais et persiste le resultat (succes ou echec) sur
* la licence. Le succes/echec est lu depuis {@code lastRefreshSucceeded}, pas
* depuis un retour de methode : le tentative est deja actee cote persistance.
*/
private void doRefresh(License current, Instant now) {
log.info("Refreshing Patreon license (current expires {})", current.getExpiresAt());
try {
String newJwt = relay.refreshToken(current.getRawJwt());
LicenseClaims claims = jwtVerifier.verify(newJwt);
current.setRawJwt(newJwt);
current.setIssuedAt(claims.issuedAt());
current.setExpiresAt(claims.expiresAt());
current.setTierId(claims.tierId());
current.setLastRefreshAttemptAt(now);
current.setLastRefreshSucceeded(true);
repository.save(current);
log.info("License refreshed successfully (new expiry {})", claims.expiresAt());
} catch (LicenseRelay.RelayException e) {
current.setLastRefreshAttemptAt(now);
current.setLastRefreshSucceeded(false);
repository.save(current);
if (e.getKind() == LicenseRelay.RelayErrorKind.REJECTED) {
log.warn("Relay rejected refresh ({}): tier may have been cancelled", e.getMessage());
} else {
log.warn("Relay refresh transient failure ({}): {}", e.getKind(), e.getMessage());
}
} catch (JwtVerifier.JwtVerificationException e) {
current.setLastRefreshAttemptAt(now);
current.setLastRefreshSucceeded(false);
repository.save(current);
log.error("Relay returned a JWT that fails verification: {}", e.getMessage());
}
}
/**
* Recupere les credentials registry pour pull du canal beta.
* @return empty si pas de licence valide ou relais en echec
*/
public Optional<RegistryCredentials> fetchRegistryCredentials() {
LicenseSnapshot snap = getCurrentSnapshot();
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
return Optional.empty();
}
License current = repository.findCurrent().orElse(null);
if (current == null) return Optional.empty();
try {
return Optional.of(relay.fetchRegistryCredentials(current.getRawJwt()));
} catch (LicenseRelay.RelayException e) {
log.warn("Cannot fetch registry credentials ({}): {}", e.getKind(), e.getMessage());
return Optional.empty();
}
}
private LicenseSnapshot snapshotOf(License l, Instant now) {
LicenseStatus status = computeStatus(l, now);
return new LicenseSnapshot(
status,
l.getPatreonUserId(),
l.getTierId(),
l.getInstanceId(),
l.getExpiresAt(),
l.getLastRefreshAttemptAt(),
l.isLastRefreshSucceeded(),
l.isBetaChannelEnabled()
);
}
private LicenseStatus computeStatus(License l, Instant now) {
if (l.getExpiresAt() == null) return LicenseStatus.NONE;
if (now.isBefore(l.getExpiresAt())) return LicenseStatus.VALID;
long secondsPastExpiry = Duration.between(l.getExpiresAt(), now).getSeconds();
if (secondsPastExpiry <= gracePeriodSeconds) return LicenseStatus.GRACE;
return LicenseStatus.EXPIRED;
}
public static class InstallException extends Exception {
public InstallException(String message) {
super(message);
}
}
}
@@ -0,0 +1,6 @@
package com.loremind.domain.campaigncontext;
/** Lightweight search projection with the ancestors needed to open a result. */
public record CampaignContentHit(String kind, String id, String name,
String campaignId, String campaignName, String arcId, String arcName,
String chapterId, String chapterName) {}
@@ -0,0 +1,8 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import java.util.List;
public interface CampaignContentSearchRepository {
List<CampaignContentHit> searchByName(String query);
}
@@ -0,0 +1,38 @@
package com.loremind.domain.campaigncontext.ports;
import java.util.List;
import java.util.Map;
/**
* Port de sortie (Mentor d'écriture) : demande à l'IA de proposer des réponses aux
* questions d'une méthode guidée à partir de l'idée de départ du MJ. Implémenté par un
* client du Brain. One-shot ; rien n'est enregistré (le MJ relit et corrige dans l'assistant).
*/
public interface GuidedMethodAssistant {
/** Choix possible d'une question à choix : valeur technique + libellé lisible. */
record Choice(String value, String label) {}
/**
* Une question de la méthode, décrite par le front (libellés dans la langue du MJ).
*
* @param key clé de réponse (ex. {@code node1.name})
* @param label libellé de la question
* @param hint aide (exemple de réponse attendue), optionnelle
* @param step titre de l'étape, optionnel
* @param options choix possibles (vide pour une question libre)
*/
record Question(String key, String label, String hint, String step, List<Choice> options) {}
/**
* @param methodName nom de la méthode (« Enquête en nœuds »…)
* @param principle principe de la méthode, suivi du rôle de chaque étape (comme dans l'assistant manuel)
* @param idea idée de départ du MJ (peut être vide)
* @param context contexte de la campagne (nom, description, système)
* @param questions questions auxquelles répondre
* @param existing réponses déjà écrites par le MJ (à respecter)
* @return une réponse proposée par clé (clés demandées uniquement)
*/
Map<String, String> answer(String methodName, String principle, String idea, String context,
List<Question> questions, Map<String, String> existing);
}
@@ -35,6 +35,9 @@ public class GameSystem {
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */ /** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
private String rulesMarkdown; private String rulesMarkdown;
/** Version anglaise des règles ({@code rulesMarkdown} = version française). Nullable. */
private String rulesMarkdownEn;
/** /**
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur. * Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après * Hors champs universels hard-codés (nom, portrait, header). Jamais null après
@@ -161,4 +164,15 @@ public class GameSystem {
if (a == null || b == null) return a == null && b == null; if (a == null || b == null) return a == null && b == null;
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT)); return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
} }
/**
* Règles dans la langue demandée ({@code en} → anglais, sinon français), avec repli sur
* l'autre version si celle-ci est vide : un système importé dans une seule langue reste lisible.
*/
public String rulesFor(String language) {
boolean english = "en".equalsIgnoreCase(language);
String preferred = english ? rulesMarkdownEn : rulesMarkdown;
String fallback = english ? rulesMarkdown : rulesMarkdownEn;
return preferred != null && !preferred.isBlank() ? preferred : fallback;
}
} }
@@ -16,5 +16,14 @@ import java.util.Map;
public record RulesImportResult( public record RulesImportResult(
Map<String, String> sections, Map<String, String> sections,
int pageCount, int pageCount,
int ocrPageCount) { int ocrPageCount,
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
Map<String, Map<String, String>> sectionsByLanguage,
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
String sourceLanguage) {
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
this(sections, pageCount, ocrPageCount, Map.of(), null);
}
} }
@@ -1,48 +0,0 @@
package com.loremind.domain.licensing;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
/**
* Licence Patreon installee dans cette instance LoreMind.
* <p>
* Singleton (une seule licence par instance, identifiee logiquement par
* {@code id = "current"}). Contient le JWT brut emis par le relais OAuth
* + les claims extraits a la verification, plus l'etat operationnel
* (derniere tentative de refresh, succes/echec).
* <p>
* <b>Note securite :</b> {@link #rawJwt} est stocke tel quel ; sa signature
* Ed25519 est verifiee a chaque lecture. Pas besoin de chiffrement au repos
* supplementaire — un attaquant qui a acces a la base a deja l'instance,
* et le JWT ne donne aucun pouvoir au-dela du canal beta de cette instance.
*/
@Data
@Builder
public class License {
private String id;
private String rawJwt;
private String patreonUserId;
private String tierId;
private String instanceId;
private Instant issuedAt;
private Instant expiresAt;
private Instant lastRefreshAttemptAt;
private boolean lastRefreshSucceeded;
private boolean betaChannelEnabled;
private Instant createdAt;
private Instant updatedAt;
}
@@ -1,15 +0,0 @@
package com.loremind.domain.licensing;
import java.time.Instant;
/**
* Claims extraits d'un JWT licence apres verification de signature.
* Immuable.
*/
public record LicenseClaims(
String subject,
String tierId,
String instanceId,
Instant issuedAt,
Instant expiresAt
) {}
@@ -1,23 +0,0 @@
package com.loremind.domain.licensing;
import java.time.Instant;
/**
* Vue immuable de la licence pour exposition vers les couches superieures.
* Decouple le domaine du DTO web et permet de calculer le {@link LicenseStatus}
* a un instant donne sans muter l'entite.
*/
public record LicenseSnapshot(
LicenseStatus status,
String patreonUserId,
String tierId,
String instanceId,
Instant expiresAt,
Instant lastRefreshAttemptAt,
boolean lastRefreshSucceeded,
boolean betaChannelEnabled
) {
public static LicenseSnapshot none() {
return new LicenseSnapshot(LicenseStatus.NONE, null, null, null, null, null, false, false);
}
}
@@ -1,23 +0,0 @@
package com.loremind.domain.licensing;
/**
* Etat operationnel de la licence vis-a-vis de l'acces beta.
* <p>
* Calcule a partir de la presence de licence + son JWT exp + grace period.
* <ul>
* <li>{@link #NONE} : aucune licence installee</li>
* <li>{@link #VALID} : JWT non expire, acces beta autorise</li>
* <li>{@link #GRACE} : JWT expire mais dans la periode de tolerance ;
* acces beta toujours autorise, l'UI doit avertir</li>
* <li>{@link #EXPIRED} : au-dela de la grace period, acces beta refuse</li>
* <li>{@link #UNVERIFIABLE} : JWT impossible a verifier (cle publique manquante,
* signature invalide, claims malformes) — traite comme NONE pour la securite</li>
* </ul>
*/
public enum LicenseStatus {
NONE,
VALID,
GRACE,
EXPIRED,
UNVERIFIABLE
}
@@ -1,18 +0,0 @@
package com.loremind.domain.licensing;
import java.time.Instant;
/**
* Credentials de pull pour un registry Docker, distribues par le relais
* apres verification d'un JWT licence valide.
* <p>
* {@code expiresAt} peut etre {@code null} si le credential est statique
* (cas du PAT GHCR partage en MVP) ; sinon, l'instance doit re-demander
* de nouveaux credentials avant cette date.
*/
public record RegistryCredentials(
String registry,
String username,
String password,
Instant expiresAt
) {}
@@ -1,34 +0,0 @@
package com.loremind.domain.licensing.ports;
import com.loremind.domain.licensing.RegistryCredentials;
import java.io.IOException;
/**
* Port de sortie : ecriture du docker config.json partage avec Watchtower.
* <p>
* Le fichier sert a Watchtower pour s'authentifier au registry prive (GHCR)
* lors du pull des images du canal beta. Volume Docker {@code docker-config}
* monte sur Core (en ecriture) et sur Watchtower (en lecture, via la variable
* {@code DOCKER_CONFIG}).
*/
public interface DockerConfigWriter {
/**
* Ecrit ou met a jour les credentials pour le registry indique.
* Cree le fichier s'il n'existe pas, conserve les autres registries deja
* presents (en theorie : aucun, mais defensif).
*/
void writeCredentials(RegistryCredentials credentials) throws IOException;
/**
* Supprime le fichier de credentials. Appele quand la licence est invalidee
* ou que le toggle beta passe a OFF.
*/
void clear() throws IOException;
/**
* @return true si le fichier de creds existe actuellement.
*/
boolean isPresent();
}
@@ -1,34 +0,0 @@
package com.loremind.domain.licensing.ports;
import com.loremind.domain.licensing.LicenseClaims;
/**
* Port de sortie : verification de signature et extraction des claims
* d'un JWT emis par le relais.
* <p>
* Implemente cote infrastructure avec la cle publique Ed25519 embarquee
* (SPKI PEM via configuration {@code licensing.jwt.public-key}).
*/
public interface JwtVerifier {
/**
* Verifie la signature, l'issuer, l'audience et l'expiration du JWT.
* @throws JwtVerificationException si la signature est invalide ou les claims malformes
*/
LicenseClaims verify(String rawJwt) throws JwtVerificationException;
/**
* @return true si la cle publique est configuree et utilisable.
* Permet a l'application de masquer la feature licensing si pas configuree.
*/
boolean isConfigured();
class JwtVerificationException extends Exception {
public JwtVerificationException(String message) {
super(message);
}
public JwtVerificationException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -1,59 +0,0 @@
package com.loremind.domain.licensing.ports;
import com.loremind.domain.licensing.RegistryCredentials;
/**
* Port de sortie vers le service relais OAuth Patreon.
* Encapsule les appels HTTP : refresh JWT et fetch registry credentials.
*/
public interface LicenseRelay {
/**
* Demande au relais l'URL OAuth a ouvrir pour connecter le compte Patreon.
*/
String buildConnectUrl(String instanceId);
/**
* Demande au relais de renouveler un JWT existant. Le relais re-verifie
* le tier Patreon de l'utilisateur ; renvoie un nouveau JWT si toujours
* actif, ou leve {@link RelayException} sinon.
*/
String refreshToken(String currentJwt) throws RelayException;
/**
* Demande au relais les credentials de pull du registry beta.
*/
RegistryCredentials fetchRegistryCredentials(String currentJwt) throws RelayException;
/**
* Erreurs distinctes emises par le relais. Permet au service application
* de differencier "tier expire" (action utilisateur) de "relais down"
* (action transitoire, garde la grace period).
*/
class RelayException extends Exception {
private final RelayErrorKind kind;
public RelayException(RelayErrorKind kind, String message) {
super(message);
this.kind = kind;
}
public RelayException(RelayErrorKind kind, String message, Throwable cause) {
super(message, cause);
this.kind = kind;
}
public RelayErrorKind getKind() {
return kind;
}
}
enum RelayErrorKind {
/** Le relais est joignable mais refuse : tier non actif, JWT trop ancien, etc. */
REJECTED,
/** Le relais a renvoye un JWT mais il est invalide / non parsable. */
BAD_RESPONSE,
/** Le relais est injoignable / 5xx / timeout. */
TRANSIENT
}
}
@@ -1,19 +0,0 @@
package com.loremind.domain.licensing.ports;
import com.loremind.domain.licensing.License;
import java.util.Optional;
/**
* Port de sortie pour la persistance de la licence installee.
* <p>
* Une seule licence par instance ({@code id = "current"} par convention).
*/
public interface LicenseRepository {
Optional<License> findCurrent();
License save(License license);
void deleteCurrent();
}
@@ -0,0 +1,11 @@
package com.loremind.domain.shared.ports;
/**
* Port : langue de l'interface de l'utilisateur courant ({@code fr} ou {@code en}), pour les
* contenus qui existent en deux langues (règles d'un système de jeu). Implémenté côté web.
*/
public interface CurrentLanguage {
/** Code court de la langue courante ({@code fr} par défaut). */
String get();
}
@@ -53,7 +53,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
@Value("${brain.base-url}") String baseUrl, @Value("${brain.base-url}") String baseUrl,
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds, @Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
@Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) { @Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
this.webClient = webClientBuilder.baseUrl(baseUrl).build(); this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
this.sse = new BrainSseImportSupport(objectMapper); this.sse = new BrainSseImportSupport(objectMapper);
this.importTimeoutSeconds = importTimeoutSeconds; this.importTimeoutSeconds = importTimeoutSeconds;
this.importCampaignStreamPath = importCampaignStreamPath; this.importCampaignStreamPath = importCampaignStreamPath;
@@ -0,0 +1,102 @@
package com.loremind.infrastructure.ai;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Adapter de sortie : propositions de réponses aux méthodes guidées via le Brain
* ({@code POST /generate/guided-answers}, one-shot). La langue de l'interface est relayée par
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
*/
@Component
public class BrainGuidedAnswersClient implements GuidedMethodAssistant {
private static final String PATH = "/generate/guided-answers";
private final RestTemplate restTemplate;
private final String baseUrl;
public BrainGuidedAnswersClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
this.restTemplate = restTemplate;
this.baseUrl = baseUrl;
}
@Override
public Map<String, String> answer(String methodName, String principle, String idea, String context,
List<Question> questions, Map<String, String> existing) {
Map<String, Object> req = new LinkedHashMap<>();
req.put("method_name", nz(methodName));
req.put("method_principle", nz(principle));
req.put("idea", nz(idea));
req.put("context", nz(context));
req.put("fields", toPayload(questions));
req.put("existing", existing == null ? Map.of() : existing);
return parse(call(req));
}
static List<Map<String, Object>> toPayload(List<Question> questions) {
List<Map<String, Object>> out = new ArrayList<>();
for (Question q : questions) {
Map<String, Object> f = new LinkedHashMap<>();
f.put("key", q.key());
f.put("label", nz(q.label()).isEmpty() ? q.key() : q.label());
f.put("hint", nz(q.hint()));
f.put("step", nz(q.step()));
List<Map<String, String>> options = new ArrayList<>();
if (q.options() != null) {
for (Choice c : q.options()) {
if (c != null && c.value() != null) options.add(Map.of("value", c.value(), "label", nz(c.label())));
}
}
f.put("options", options);
out.add(f);
}
return out;
}
@SuppressWarnings("unchecked")
private Map<String, Object> call(Map<String, Object> req) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> resp;
try {
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
} catch (ResourceAccessException e) {
throw new NarrativeAssistException("Le Brain est injoignable (timeout ou arrêté).", e);
} catch (RestClientResponseException e) {
throw new NarrativeAssistException(
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
} catch (Exception e) {
throw new NarrativeAssistException("Erreur inattendue lors de l'appel au Brain.", e);
}
if (resp == null) throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
return resp;
}
private static Map<String, String> parse(Map<String, Object> resp) {
Map<String, String> out = new LinkedHashMap<>();
if (resp.get("answers") instanceof Map<?, ?> m) {
m.forEach((k, v) -> {
if (k != null && v != null) out.put(k.toString(), v.toString());
});
}
return out;
}
private static String nz(String s) {
return s == null ? "" : s;
}
}
@@ -70,7 +70,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
@Value("${brain.paths.import-rules:/import/rules}") String importRulesPath, @Value("${brain.paths.import-rules:/import/rules}") String importRulesPath,
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) { @Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
this.restTemplate = restTemplate; this.restTemplate = restTemplate;
this.webClient = webClientBuilder.baseUrl(baseUrl).build(); this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
this.sse = new BrainSseImportSupport(objectMapper); this.sse = new BrainSseImportSupport(objectMapper);
this.baseUrl = baseUrl; this.baseUrl = baseUrl;
this.importTimeoutSeconds = importTimeoutSeconds; this.importTimeoutSeconds = importTimeoutSeconds;
@@ -106,7 +106,9 @@ public class BrainRulesImportClient implements RulesPdfImporter {
return new RulesImportResult( return new RulesImportResult(
Map.copyOf(response.getSections()), Map.copyOf(response.getSections()),
response.getPageCount(), response.getPageCount(),
response.getOcrPageCount()); response.getOcrPageCount(),
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
response.getSourceLanguage());
} catch (ResourceAccessException e) { } catch (ResourceAccessException e) {
throw new RulesImportException( throw new RulesImportException(
"Le Brain est injoignable (timeout ou service arrêté).", e); "Le Brain est injoignable (timeout ou service arrêté).", e);
@@ -218,12 +220,23 @@ public class BrainRulesImportClient implements RulesPdfImporter {
callbacks.onDone().accept(new RulesImportResult( callbacks.onDone().accept(new RulesImportResult(
toStringMap(node.path("sections")), toStringMap(node.path("sections")),
node.path("page_count").asInt(), node.path("page_count").asInt(),
node.path("ocr_page_count").asInt())); node.path("ocr_page_count").asInt(),
toLanguageMap(node.path("sections_by_language")),
node.path("source_language").asText(null)));
} }
} }
// --- Helpers ------------------------------------------------------------- // --- Helpers -------------------------------------------------------------
/** {code langue → sections} : règles en deux langues (vide si le Brain ne les fournit pas). */
private Map<String, Map<String, String>> toLanguageMap(JsonNode node) {
Map<String, Map<String, String>> out = new java.util.LinkedHashMap<>();
if (node != null && node.isObject()) {
node.fields().forEachRemaining(e -> out.put(e.getKey(), toStringMap(e.getValue())));
}
return out;
}
private List<String> toStringList(JsonNode array) { private List<String> toStringList(JsonNode array) {
List<String> out = new ArrayList<>(); List<String> out = new ArrayList<>();
if (array != null && array.isArray()) { if (array != null && array.isArray()) {
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
@JsonProperty("ocr_page_count") @JsonProperty("ocr_page_count")
private int ocrPageCount; private int ocrPageCount;
/** Règles en deux langues : {code langue → sections} (absent d'un Brain antérieur). */
@JsonProperty("sections_by_language")
private Map<String, Map<String, String>> sectionsByLanguage;
@JsonProperty("source_language")
private String sourceLanguage;
} }
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.codec.ServerSentEvent; import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import java.time.Duration; import java.time.Duration;
@@ -25,6 +26,21 @@ final class BrainSseImportSupport {
/** Champ JSON standard des events SSE du Brain portant un message lisible. */ /** Champ JSON standard des events SSE du Brain portant un message lisible. */
private static final String MESSAGE_FIELD = "message"; private static final String MESSAGE_FIELD = "message";
/**
* Taille max d'UN évènement SSE. L'évènement {@code done} porte tout le résultat de
* l'import (règles d'un livre entier, en deux langues ; arbre complet d'une campagne) :
* la limite par défaut de WebClient (256 Ko) faisait échouer l'import au tout dernier
* moment (DataBufferLimitException), après des minutes d'analyse.
*/
static final int MAX_EVENT_BYTES = 64 * 1024 * 1024;
/** WebClient d'import : évènements volumineux acceptés (voir {@link #MAX_EVENT_BYTES}). */
static WebClient importWebClient(WebClient.Builder builder, String baseUrl) {
return builder.baseUrl(baseUrl)
.codecs(c -> c.defaultCodecs().maxInMemorySize(MAX_EVENT_BYTES))
.build();
}
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
BrainSseImportSupport(ObjectMapper objectMapper) { BrainSseImportSupport(ObjectMapper objectMapper) {
@@ -3,7 +3,9 @@ package com.loremind.infrastructure.desktop;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.awt.Desktop;
import java.io.IOException; import java.io.IOException;
import java.net.URI;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.channels.FileLock; import java.nio.channels.FileLock;
import java.nio.file.Files; import java.nio.file.Files;
@@ -102,14 +104,20 @@ public final class DesktopSingleInstance {
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/"); openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
} }
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */ /**
* Ouvre le navigateur par defaut sur une URL quelconque : API standard de Java
* (ShellExecute sous Windows), sinon commande du systeme. Plus de {@code rundll32
* url.dll} : outil Windows tres detourne par les logiciels malveillants, que des
* antivirus signalaient (Avast « IDP.Generic ») quand un programme peu connu le lance.
*/
public static void openUrl(String url) { public static void openUrl(String url) {
if (browseWithJava(url)) return;
try { try {
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase(); String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
ProcessBuilder pb; ProcessBuilder pb;
if (os.contains("win")) { if (os.contains("win")) {
// rundll32 : ouverture d'URL fiable sans dependance graphique Java. // « start » de cmd ; le "" est le titre de fenetre attendu avant l'URL.
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url); pb = new ProcessBuilder("cmd", "/c", "start", "", url);
} else if (os.contains("mac")) { } else if (os.contains("mac")) {
pb = new ProcessBuilder("open", url); pb = new ProcessBuilder("open", url);
} else { } else {
@@ -122,6 +130,20 @@ public final class DesktopSingleInstance {
} }
} }
/** {@link Desktop#browse} si disponible (jamais en headless) ; false = repli sur une commande. */
private static boolean browseWithJava(String url) {
try {
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
return false;
}
Desktop.getDesktop().browse(URI.create(url));
return true;
} catch (IOException | RuntimeException e) {
log.debug("[Desktop] Ouverture via Desktop.browse impossible ({}), repli sur une commande.", e.getMessage());
return false;
}
}
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */ /** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
public static void openFolder(Path dir) { public static void openFolder(Path dir) {
try { try {
@@ -31,6 +31,9 @@ import java.util.Optional;
* <p> * <p>
* {@code /releases/latest} ne renvoie que les releases stables (pas les * {@code /releases/latest} ne renvoie que les releases stables (pas les
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas. * prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
* Une version BETA (le canal beta est libre : chaque beta est publiee en
* prerelease GitHub) interroge la liste complete des releases, pour etre
* prevenue de la beta suivante comme de la version stable qui la remplace.
*/ */
@Service @Service
@Profile("local") @Profile("local")
@@ -73,17 +76,18 @@ public class DesktopUpdateService {
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop"); headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json"); headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
boolean beta = isPrerelease(currentVersion);
ResponseEntity<JsonNode> resp = http.exchange( ResponseEntity<JsonNode> resp = http.exchange(
releasesApiUrl, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class); beta ? allReleasesUrl(releasesApiUrl) : releasesApiUrl,
JsonNode body = resp.getBody(); HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
if (body == null || body.path("tag_name").isMissingNode()) { JsonNode release = beta ? newestRelease(resp.getBody()) : resp.getBody();
if (release == null || release.path("tag_name").isMissingNode()) {
return Optional.empty(); return Optional.empty();
} }
String tag = body.path("tag_name").asText(""); // ex: "v0.15.0" String latest = version(release); // ex: "0.15.0"
String releaseUrl = body.path("html_url").asText(null); // page de la release String releaseUrl = release.path("html_url").asText(null); // page de la release
String latest = tag.startsWith("v") ? tag.substring(1) : tag;
if (!latest.isBlank() && compareSemver(currentVersion, latest) < 0) { if (!latest.isBlank() && (beta ? compareVersions(currentVersion, latest) : compareSemver(currentVersion, latest)) < 0) {
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion); log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl)); return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
} }
@@ -99,6 +103,66 @@ public class DesktopUpdateService {
/** Infos d'une mise a jour disponible. */ /** Infos d'une mise a jour disponible. */
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {} public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
static boolean isPrerelease(String version) {
return version.split("\\+", 2)[0].contains("-");
}
/** {@code .../releases/latest} -> {@code .../releases?per_page=30} (prereleases incluses). */
static String allReleasesUrl(String latestUrl) {
String base = latestUrl.endsWith("/latest") ? latestUrl.substring(0, latestUrl.length() - "/latest".length()) : latestUrl;
return base + "?per_page=30";
}
private static String version(JsonNode release) {
String tag = release.path("tag_name").asText("");
return tag.startsWith("v") ? tag.substring(1) : tag;
}
/** Release publiee la plus recente (stable ou beta), brouillons exclus. */
@Nullable
static JsonNode newestRelease(@Nullable JsonNode releases) {
if (releases == null || !releases.isArray()) return null;
JsonNode best = null;
for (JsonNode r : releases) {
if (r.path("draft").asBoolean(false) || version(r).isBlank()) continue;
if (best == null || compareVersions(version(best), version(r)) < 0) best = r;
}
return best;
}
/**
* Comme {@link #compareSemver} mais tient compte du suffixe : a version egale,
* la stable passe devant la beta (1.5.0-beta &lt; 1.5.0), et deux betas se
* comparent par leur numero (1.5.0-beta &lt; 1.5.0-beta.2 &lt; 1.5.0-beta.10).
*/
static int compareVersions(String a, String b) {
int cmp = compareSemver(a, b);
if (cmp != 0) return cmp;
String sa = suffix(a);
String sb = suffix(b);
if (sa.isEmpty() || sb.isEmpty()) return Boolean.compare(sa.isEmpty(), sb.isEmpty());
return compareSuffixes(sa, sb);
}
private static String suffix(String version) {
String noBuild = version.split("\\+", 2)[0];
int dash = noBuild.indexOf('-');
return dash < 0 ? "" : noBuild.substring(dash + 1);
}
/** Compare des suffixes en traitant les nombres comme des nombres (beta.10 &gt; beta.2). */
private static int compareSuffixes(String a, String b) {
String[] pa = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
String[] pb = b.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
for (int i = 0; i < Math.min(pa.length, pb.length); i++) {
boolean na = Character.isDigit(pa[i].charAt(0));
boolean nb = Character.isDigit(pb[i].charAt(0));
int cmp = na && nb ? Long.compare(Long.parseLong(pa[i]), Long.parseLong(pb[i])) : pa[i].compareTo(pb[i]);
if (cmp != 0) return cmp;
}
return Integer.compare(pa.length, pb.length);
}
/** /**
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore). * Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
* @return &lt;0 si a&lt;b, 0 si egales, &gt;0 si a&gt;b. * @return &lt;0 si a&lt;b, 0 si egales, &gt;0 si a&gt;b.
@@ -26,9 +26,16 @@ import java.util.concurrent.TimeUnit;
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur * qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
* (réglage système, jamais modifié par l'application). * (réglage système, jamais modifié par l'application).
* <p> * <p>
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de * Les scripts sont passés EN CLAIR ({@code -Command}, une ligne) : un script encodé
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable, * ({@code -EncodedCommand}) accompagné de {@code -ExecutionPolicy Bypass} est la signature
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell. * typique des logiciels malveillants, et faisait réagir des antivirus (Avast « IDP.Generic »).
* La politique d'exécution ne concerne que les fichiers .ps1 : inutile de la contourner.
* La ligne de commande Windows est en UTF-16 : accents et noms de réseau passent tels quels.
* Seule exception : le script relancé EN ADMINISTRATEUR (bouton « Autoriser »), encodé car
* {@code Start-Process -ArgumentList} ne sait pas transmettre un script avec espaces et
* guillemets ; il ne s'exécute que sur clic de l'utilisateur, derrière la confirmation UAC.
* Le seul paramètre variable est le chemin de l'exécutable, fourni par le système (pas par
* l'utilisateur), et échappé pour une chaîne PowerShell.
* <p> * <p>
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows. * Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
*/ */
@@ -69,14 +76,8 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
public FirewallFixOutcome allowThroughFirewall() { public FirewallFixOutcome allowThroughFirewall() {
String program = currentProgram(); String program = currentProgram();
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED; if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
String outer = "try {\n"
+ " $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
+ "-ArgumentList @('-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','"
+ encode(allowScript(program)) + "')\n"
+ " exit $p.ExitCode\n"
+ "} catch { exit " + EXIT_CANCELLED + " }\n";
try { try {
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode(); int exit = runPowerShell(elevationScript(program), ELEVATION_TIMEOUT_S).exitCode();
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED; : exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
log.info("Accès distant : autorisation pare-feu → {}", outcome); log.info("Accès distant : autorisation pare-feu → {}", outcome);
@@ -103,24 +104,37 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
// --- Scripts -------------------------------------------------------------------------- // --- Scripts --------------------------------------------------------------------------
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */ /**
* Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris).
* Une seule ligne d'instructions séparées par « ; » : elle est passée telle quelle à {@code -Command}.
*/
static String inspectScript(String program) { static String inspectScript(String program) {
return "$ErrorActionPreference = 'SilentlyContinue'\n" return "$ErrorActionPreference = 'SilentlyContinue'; "
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués. // Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n" + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
+ "$p = '" + psQuote(program) + "'\n" + "$p = '" + psQuote(program) + "'; "
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; " + "$nets = @(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n" + "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } }); "
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and " + "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | " + "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ " + "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n" + "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } }); "
// Pare-feu TIERS déclarés au Centre de sécurité (le pare-feu Windows n'y figure pas) : // Pare-feu TIERS déclarés au Centre de sécurité (le pare-feu Windows n'y figure pas) :
// ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire. // ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire.
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | " + "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' })\n" + "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' }); "
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | " + "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
+ "ConvertTo-Json -Depth 4 -Compress\n"; + "ConvertTo-Json -Depth 4 -Compress";
}
/**
* Relance PowerShell EN ADMINISTRATEUR (confirmation UAC) avec {@link #allowScript}, et
* renvoie son code de sortie ; refus de l'UAC → {@value #EXIT_CANCELLED}. Une seule ligne.
*/
static String elevationScript(String program) {
return "try { $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
+ "-ArgumentList @('-NoProfile','-NonInteractive','-EncodedCommand','"
+ encode(allowScript(program)) + "'); exit $p.ExitCode } catch { exit " + EXIT_CANCELLED + " }";
} }
/** /**
@@ -183,9 +197,9 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
private record Result(int exitCode, String output) {} private record Result(int exitCode, String output) {}
/** {@code script} : une ligne, sans guillemet double (chaînes PowerShell entre apostrophes). */
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException { private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", Process process = new ProcessBuilder(command(script))
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
.redirectError(ProcessBuilder.Redirect.DISCARD) .redirectError(ProcessBuilder.Redirect.DISCARD)
.start(); .start();
process.getOutputStream().close(); process.getOutputStream().close();
@@ -204,6 +218,14 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
return new Result(process.exitValue(), output.join()); return new Result(process.exitValue(), output.join());
} }
/** Ligne de commande PowerShell : script en clair, ni encodage ni contournement de politique. */
static List<String> command(String script) {
if (script.indexOf('"') >= 0 || script.indexOf('\n') >= 0) {
throw new IllegalArgumentException("Script PowerShell : une ligne, sans guillemet double");
}
return List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script);
}
private static boolean isWindows() { private static boolean isWindows() {
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows"); return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
} }
@@ -1,114 +0,0 @@
package com.loremind.infrastructure.licensing;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.loremind.domain.licensing.RegistryCredentials;
import com.loremind.domain.licensing.ports.DockerConfigWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Base64;
/**
* Implementation : ecriture du fichier {@code config.json} au format Docker
* standard, dans un volume partage avec Watchtower.
* <p>
* Format produit :
* <pre>{@code
* {
* "auths": {
* "ghcr.io": {
* "auth": "<base64(username:password)>"
* }
* }
* }
* }</pre>
*/
@Component
public class FileDockerConfigWriter implements DockerConfigWriter {
private static final Logger log = LoggerFactory.getLogger(FileDockerConfigWriter.class);
/** Cle racine du config.json Docker portant les registres authentifies. */
private static final String AUTHS_KEY = "auths";
private final Path configPath;
private final ObjectMapper mapper = new ObjectMapper();
public FileDockerConfigWriter(
@Value("${licensing.docker-config-path:/shared/docker/config.json}") String pathStr) {
this.configPath = Path.of(pathStr);
}
@Override
public void writeCredentials(RegistryCredentials credentials) throws IOException {
ensureParentDirectory();
ObjectNode root;
if (Files.exists(configPath)) {
try {
JsonNode existing = mapper.readTree(configPath.toFile());
root = existing.isObject() ? (ObjectNode) existing : mapper.createObjectNode();
} catch (IOException e) {
log.warn("Existing docker config unreadable, overwriting: {}", e.getMessage());
root = mapper.createObjectNode();
}
} else {
root = mapper.createObjectNode();
}
ObjectNode auths = root.has(AUTHS_KEY) && root.get(AUTHS_KEY).isObject()
? (ObjectNode) root.get(AUTHS_KEY)
: root.putObject(AUTHS_KEY);
String b64 = Base64.getEncoder().encodeToString(
(credentials.username() + ":" + credentials.password()).getBytes(StandardCharsets.UTF_8));
ObjectNode entry = mapper.createObjectNode();
entry.put("auth", b64);
auths.set(credentials.registry(), entry);
Files.writeString(configPath, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root),
StandardCharsets.UTF_8);
applyRestrictivePermissions();
log.info("Docker config written at {} for registry {}", configPath, credentials.registry());
}
@Override
public void clear() throws IOException {
if (Files.exists(configPath)) {
Files.delete(configPath);
log.info("Docker config cleared at {}", configPath);
}
}
@Override
public boolean isPresent() {
return Files.exists(configPath);
}
private void ensureParentDirectory() throws IOException {
Path parent = configPath.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
}
/** 0600 sur POSIX. Sur Windows (dev), no-op silencieux. */
private void applyRestrictivePermissions() {
try {
Files.setPosixFilePermissions(configPath, PosixFilePermissions.fromString("rw-------"));
} catch (UnsupportedOperationException | IOException e) {
// Windows / FS qui ne supporte pas POSIX => ignore (le conteneur tourne sous Linux en prod)
}
}
}
@@ -1,146 +0,0 @@
package com.loremind.infrastructure.licensing;
import com.fasterxml.jackson.databind.JsonNode;
import com.loremind.domain.licensing.RegistryCredentials;
import com.loremind.domain.licensing.ports.LicenseRelay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
/**
* Client HTTP du relais OAuth Patreon (deploye sur Cloudflare Workers).
* Voir {@code relay/} pour le code du relais.
*/
@Component
public class HttpLicenseRelay implements LicenseRelay {
private static final Logger log = LoggerFactory.getLogger(HttpLicenseRelay.class);
private final RestTemplate http;
private final String baseUrl;
public HttpLicenseRelay(
RestTemplateBuilder builder,
@Value("${licensing.relay.base-url:}") String baseUrl) {
this.http = builder
.connectTimeout(Duration.ofSeconds(5))
.readTimeout(Duration.ofSeconds(15))
.build();
this.baseUrl = stripTrailingSlash(baseUrl);
}
@Override
public String buildConnectUrl(String instanceId) {
if (baseUrl.isBlank()) {
throw new IllegalStateException("Licensing relay base URL not configured");
}
String encoded = URLEncoder.encode(instanceId, StandardCharsets.UTF_8);
return baseUrl + "/oauth/start?instance_id=" + encoded;
}
@Override
public String refreshToken(String currentJwt) throws RelayException {
if (baseUrl.isBlank()) {
throw new RelayException(RelayErrorKind.TRANSIENT, "relay not configured");
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> body = Map.of("jwt", currentJwt);
ResponseEntity<JsonNode> resp;
try {
resp = http.exchange(
baseUrl + "/token/refresh",
HttpMethod.POST,
new HttpEntity<>(body, headers),
JsonNode.class);
} catch (HttpClientErrorException e) {
throw new RelayException(RelayErrorKind.REJECTED,
"relay rejected refresh: " + e.getStatusCode() + " " + e.getStatusText());
} catch (HttpServerErrorException e) {
throw new RelayException(RelayErrorKind.TRANSIENT,
"relay 5xx: " + e.getStatusCode());
} catch (RestClientException e) {
throw new RelayException(RelayErrorKind.TRANSIENT, "relay unreachable: " + e.getMessage(), e);
}
JsonNode payload = resp.getBody();
if (payload == null || !payload.hasNonNull("jwt")) {
throw new RelayException(RelayErrorKind.BAD_RESPONSE, "missing jwt in refresh response");
}
return payload.get("jwt").asText();
}
@Override
public RegistryCredentials fetchRegistryCredentials(String currentJwt) throws RelayException {
if (baseUrl.isBlank()) {
throw new RelayException(RelayErrorKind.TRANSIENT, "relay not configured");
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> body = Map.of("jwt", currentJwt);
ResponseEntity<JsonNode> resp;
try {
resp = http.exchange(
baseUrl + "/registry/credentials",
HttpMethod.POST,
new HttpEntity<>(body, headers),
JsonNode.class);
} catch (HttpClientErrorException e) {
throw new RelayException(RelayErrorKind.REJECTED,
"relay rejected creds: " + e.getStatusCode() + " " + e.getStatusText());
} catch (HttpServerErrorException e) {
throw new RelayException(RelayErrorKind.TRANSIENT,
"relay 5xx: " + e.getStatusCode());
} catch (RestClientException e) {
throw new RelayException(RelayErrorKind.TRANSIENT, "relay unreachable: " + e.getMessage(), e);
}
JsonNode payload = resp.getBody();
if (payload == null
|| !payload.hasNonNull("registry")
|| !payload.hasNonNull("username")
|| !payload.hasNonNull("password")) {
throw new RelayException(RelayErrorKind.BAD_RESPONSE, "incomplete credentials response");
}
Instant expiresAt = null;
if (payload.hasNonNull("expires_at")) {
try {
expiresAt = Instant.parse(payload.get("expires_at").asText());
} catch (Exception e) {
log.warn("Cannot parse expires_at from relay creds response: {}", e.getMessage());
}
}
return new RegistryCredentials(
payload.get("registry").asText(),
payload.get("username").asText(),
payload.get("password").asText(),
expiresAt
);
}
private static String stripTrailingSlash(String s) {
if (s == null) return "";
String v = s.trim();
if (v.endsWith("/")) v = v.substring(0, v.length() - 1);
return v;
}
}
@@ -1,96 +0,0 @@
package com.loremind.infrastructure.licensing;
import com.loremind.application.licensing.LicenseService;
import com.loremind.domain.licensing.LicenseSnapshot;
import com.loremind.domain.licensing.LicenseStatus;
import com.loremind.domain.licensing.RegistryCredentials;
import com.loremind.domain.licensing.ports.DockerConfigWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Optional;
/**
* Daemon planifie qui :
* <ul>
* <li>renouvelle le JWT licence via le relais avant expiration (J-2)</li>
* <li>met a jour les credentials registry GHCR pour Watchtower
* (volume partage docker-config) tant que le canal beta est ON</li>
* <li>nettoie les credentials si la licence est invalidee ou le toggle OFF</li>
* </ul>
* Idempotent : peut tourner toutes les 6h sans risque, fait du no-op
* la plupart du temps.
*/
@Component
// Desactivable (ex: tests) : sans cette propriete (prod), le daemon tourne.
@ConditionalOnProperty(name = "licensing.refresh.enabled", matchIfMissing = true)
public class LicenseRefreshDaemon {
private static final Logger log = LoggerFactory.getLogger(LicenseRefreshDaemon.class);
/** 6 heures entre chaque cycle. Suffisant pour rattraper un J-2 sans surcharger. */
private static final long FIXED_DELAY_MS = 6L * 60L * 60L * 1000L;
/** Premier run apres 30s pour laisser le contexte Spring se stabiliser. */
private static final long INITIAL_DELAY_MS = 30_000L;
private final LicenseService licenseService;
private final DockerConfigWriter dockerConfigWriter;
public LicenseRefreshDaemon(LicenseService licenseService,
DockerConfigWriter dockerConfigWriter) {
this.licenseService = licenseService;
this.dockerConfigWriter = dockerConfigWriter;
}
@Scheduled(initialDelay = INITIAL_DELAY_MS, fixedDelay = FIXED_DELAY_MS)
public void tick() {
if (!licenseService.isLicensingEnabled()) {
return;
}
try {
licenseService.refreshIfNeeded();
syncDockerConfig();
} catch (Exception e) {
log.error("LicenseRefreshDaemon tick failed: {}", e.getMessage(), e);
}
}
/**
* Aligne le fichier docker config avec l'etat de la licence et le toggle :
* <ul>
* <li>VALID/GRACE + beta ON -> ecrit/refresh les creds</li>
* <li>tout autre cas -> efface le fichier</li>
* </ul>
*/
private void syncDockerConfig() {
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
boolean shouldHaveCreds = snap.betaChannelEnabled()
&& (snap.status() == LicenseStatus.VALID || snap.status() == LicenseStatus.GRACE);
if (!shouldHaveCreds) {
try {
if (dockerConfigWriter.isPresent()) {
dockerConfigWriter.clear();
}
} catch (IOException e) {
log.warn("Cannot clear docker config: {}", e.getMessage());
}
return;
}
Optional<RegistryCredentials> creds = licenseService.fetchRegistryCredentials();
if (creds.isEmpty()) {
log.warn("Beta enabled but cannot fetch registry credentials (relay down or rejected)");
return;
}
try {
dockerConfigWriter.writeCredentials(creds.get());
} catch (IOException e) {
log.error("Cannot write docker config: {}", e.getMessage());
}
}
}
@@ -1,217 +0,0 @@
package com.loremind.infrastructure.licensing;
import com.loremind.domain.licensing.LicenseClaims;
import com.loremind.domain.licensing.ports.JwtVerifier;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.Ed25519Verifier;
import com.nimbusds.jose.jwk.OctetKeyPair;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.time.Instant;
import java.util.Base64;
/**
* Verifie les JWT EdDSA/Ed25519 emis par le relais Patreon.
* <p>
* La cle publique est fournie en PEM SPKI via la propriete
* {@code licensing.jwt.public-key} (env {@code LICENSING_JWT_PUBLIC_KEY}).
* Si la cle est absente ou invalide, {@link #isConfigured()} retourne false
* et {@link #verify} echoue systematiquement — la feature licensing est
* desactivee silencieusement.
*/
@Component
public class NimbusJwtVerifier implements JwtVerifier {
private static final Logger log = LoggerFactory.getLogger(NimbusJwtVerifier.class);
private final String expectedIssuer;
private final String expectedAudience;
private final OctetKeyPair publicKey;
public NimbusJwtVerifier(
@Value("${licensing.jwt.public-key:}") String publicKeyPemFromEnv,
@Value("${licensing.jwt.expected-issuer:loremind-auth}") String expectedIssuer,
@Value("${licensing.jwt.expected-audience:loremind-instance}") String expectedAudience) {
this.expectedIssuer = expectedIssuer;
this.expectedAudience = expectedAudience;
// Strategie : env var en priorite (rotation possible sans rebuild),
// sinon ressource classpath embarquee dans le binaire.
String pem = (publicKeyPemFromEnv != null && !publicKeyPemFromEnv.isBlank())
? publicKeyPemFromEnv
: loadEmbeddedKey();
this.publicKey = parsePemSpki(pem);
if (publicKey == null) {
log.info("Licensing JWT verifier disabled (no public key found)");
} else {
String source = (publicKeyPemFromEnv != null && !publicKeyPemFromEnv.isBlank()) ? "env" : "embedded";
log.info("Licensing JWT verifier enabled (issuer={}, audience={}, key source={})",
expectedIssuer, expectedAudience, source);
}
}
/**
* Charge la cle publique embarquee dans le binaire (resource classpath).
* Le fichier est un PEM SPKI standard, fourni a la build pour chaque
* release. Si absent, la feature licensing est desactivee.
*/
private static String loadEmbeddedKey() {
ClassPathResource resource = new ClassPathResource("licensing/jwt-public-key.pem");
if (!resource.exists()) {
return null;
}
try (InputStream in = resource.getInputStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.warn("Cannot read embedded JWT public key: {}", e.getMessage());
return null;
}
}
@Override
public boolean isConfigured() {
return publicKey != null;
}
@Override
public LicenseClaims verify(String rawJwt) throws JwtVerificationException {
ensureConfigured();
ensureNotBlank(rawJwt);
SignedJWT signed = parseJwt(rawJwt);
ensureExpectedAlgorithm(signed);
verifySignature(signed);
JWTClaimsSet claims = parseClaims(signed);
ensureExpectedIssuer(claims);
ensureExpectedAudience(claims);
return toLicenseClaims(claims);
}
private void ensureConfigured() throws JwtVerificationException {
if (publicKey == null) {
throw new JwtVerificationException("JWT verifier not configured");
}
}
private static void ensureNotBlank(String rawJwt) throws JwtVerificationException {
if (rawJwt == null || rawJwt.isBlank()) {
throw new JwtVerificationException("JWT is empty");
}
}
private static SignedJWT parseJwt(String rawJwt) throws JwtVerificationException {
try {
return SignedJWT.parse(rawJwt);
} catch (ParseException e) {
throw new JwtVerificationException("JWT parse error: " + e.getMessage(), e);
}
}
private static void ensureExpectedAlgorithm(SignedJWT signed) throws JwtVerificationException {
JWSAlgorithm alg = signed.getHeader().getAlgorithm();
if (!JWSAlgorithm.EdDSA.equals(alg)) {
throw new JwtVerificationException("Unexpected JWT algorithm: " + alg);
}
}
private void verifySignature(SignedJWT signed) throws JwtVerificationException {
try {
JWSVerifier verifier = new Ed25519Verifier(publicKey);
if (!signed.verify(verifier)) {
throw new JwtVerificationException("JWT signature invalid");
}
} catch (Exception e) {
throw new JwtVerificationException("JWT signature verification failed: " + e.getMessage(), e);
}
}
private static JWTClaimsSet parseClaims(SignedJWT signed) throws JwtVerificationException {
try {
return signed.getJWTClaimsSet();
} catch (ParseException e) {
throw new JwtVerificationException("JWT claims parse error", e);
}
}
private void ensureExpectedIssuer(JWTClaimsSet claims) throws JwtVerificationException {
if (!expectedIssuer.equals(claims.getIssuer())) {
throw new JwtVerificationException("JWT issuer mismatch: " + claims.getIssuer());
}
}
private void ensureExpectedAudience(JWTClaimsSet claims) throws JwtVerificationException {
if (claims.getAudience() == null || !claims.getAudience().contains(expectedAudience)) {
throw new JwtVerificationException("JWT audience mismatch");
}
}
/**
* Construit les LicenseClaims depuis les claims validés (issuer/audience/signature).
* Note : on ne refuse pas un JWT expiré ici. C'est au LicenseService de decider ce
* qu'il fait d'un JWT expire (grace period, refresh, etc.). La verification de
* signature reste valide tant que la cle existe.
*/
private static LicenseClaims toLicenseClaims(JWTClaimsSet claims) throws JwtVerificationException {
// Nimbus n'expose exp/iat qu'en java.util.Date : converti en Instant SANS variable
// Date intermediaire (aucune reference au type legacy dans cette classe).
String sub = claims.getSubject();
if (claims.getExpirationTime() == null || claims.getIssueTime() == null || sub == null) {
throw new JwtVerificationException("JWT missing required claims");
}
Instant exp = claims.getExpirationTime().toInstant();
Instant iat = claims.getIssueTime().toInstant();
String tierId;
String instanceId;
try {
tierId = claims.getStringClaim("tier_id");
instanceId = claims.getStringClaim("instance_id");
} catch (ParseException e) {
throw new JwtVerificationException("JWT custom claim parse error", e);
}
if (tierId == null || tierId.isBlank() || instanceId == null || instanceId.isBlank()) {
throw new JwtVerificationException("JWT missing tier_id or instance_id");
}
return new LicenseClaims(sub, tierId, instanceId, iat, exp);
}
/**
* Parse une cle publique Ed25519 au format PEM SPKI vers un Nimbus
* {@link OctetKeyPair} (forme JWK utilisee pour la verification).
*/
private static OctetKeyPair parsePemSpki(String pem) {
if (pem == null || pem.isBlank()) return null;
try {
String base64 = pem
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s+", "");
byte[] der = Base64.getDecoder().decode(base64);
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(der));
byte[] keyBytes = spki.getPublicKeyData().getOctets();
String x = Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
return new OctetKeyPair.Builder(com.nimbusds.jose.jwk.Curve.Ed25519, com.nimbusds.jose.util.Base64URL.from(x))
.build();
} catch (IOException | IllegalArgumentException e) {
log.warn("Cannot parse licensing JWT public key: {}", e.getMessage());
return null;
}
}
}
@@ -37,6 +37,9 @@ public class GameSystemJpaEntity {
@Column(name = "rules_markdown", columnDefinition = "TEXT") @Column(name = "rules_markdown", columnDefinition = "TEXT")
private String rulesMarkdown; private String rulesMarkdown;
@Column(name = "rules_markdown_en", columnDefinition = "TEXT")
private String rulesMarkdownEn;
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */ /** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
@Convert(converter = TemplateFieldListJsonConverter.class) @Convert(converter = TemplateFieldListJsonConverter.class)
@Column(name = "character_template", columnDefinition = "TEXT") @Column(name = "character_template", columnDefinition = "TEXT")
@@ -1,72 +0,0 @@
package com.loremind.infrastructure.persistence.entity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
/**
* Entite JPA pour la licence Patreon installee.
* <p>
* Singleton : une seule ligne par instance (id = "current"). Ce design permet
* de ne jamais avoir de licence "fantome" en base et de simplifier les queries.
*/
@Entity
@Table(name = "licenses")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LicenseJpaEntity {
@Id
private String id;
@Column(name = "raw_jwt", columnDefinition = "TEXT", nullable = false)
private String rawJwt;
@Column(name = "patreon_user_id", nullable = false)
private String patreonUserId;
@Column(name = "tier_id", nullable = false)
private String tierId;
@Column(name = "instance_id", nullable = false)
private String instanceId;
@Column(name = "issued_at", nullable = false)
private Instant issuedAt;
@Column(name = "expires_at", nullable = false)
private Instant expiresAt;
@Column(name = "last_refresh_attempt_at")
private Instant lastRefreshAttemptAt;
@Column(name = "last_refresh_succeeded", nullable = false)
private boolean lastRefreshSucceeded;
@Column(name = "beta_channel_enabled", nullable = false)
private boolean betaChannelEnabled;
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt;
@Column(name = "updated_at", nullable = false)
private Instant updatedAt;
@PrePersist
protected void onCreate() {
Instant now = Instant.now();
if (createdAt == null) createdAt = now;
updatedAt = now;
}
@PreUpdate
protected void onUpdate() {
updatedAt = Instant.now();
}
}
@@ -1,9 +0,0 @@
package com.loremind.infrastructure.persistence.jpa;
import com.loremind.infrastructure.persistence.entity.LicenseJpaEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LicenseJpaRepository extends JpaRepository<LicenseJpaEntity, String> {
}
@@ -0,0 +1,57 @@
package com.loremind.infrastructure.persistence.postgres;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/** One bounded query; never loads complete scenes or one tree per campaign. */
@Repository
public class PostgresCampaignContentSearchRepository implements CampaignContentSearchRepository {
private final NamedParameterJdbcTemplate jdbc;
public PostgresCampaignContentSearchRepository(NamedParameterJdbcTemplate jdbc) {
this.jdbc = jdbc;
}
private static final String SQL = """
SELECT * FROM (
SELECT 'arc' AS kind, a.id, a.name, c.id AS campaign_id, c.name AS campaign_name,
a.id AS arc_id, a.name AS arc_name, CAST(NULL AS BIGINT) AS chapter_id,
CAST(NULL AS VARCHAR) AS chapter_name
FROM arcs a JOIN campaigns c ON c.id = a.campaign_id
WHERE a.type <> 'SYSTEM' AND LOWER(a.name) LIKE :query ESCAPE '!'
UNION ALL
SELECT 'chapter', ch.id, ch.name, c.id, c.name, a.id, a.name, ch.id, ch.name
FROM chapters ch JOIN arcs a ON a.id = ch.arc_id JOIN campaigns c ON c.id = a.campaign_id
WHERE a.type <> 'SYSTEM' AND LOWER(ch.name) LIKE :query ESCAPE '!'
UNION ALL
SELECT 'scene', s.id, s.name, c.id, c.name, a.id,
CASE WHEN a.type = 'SYSTEM' THEN NULL ELSE a.name END, ch.id, ch.name
FROM scenes s JOIN chapters ch ON ch.id = s.chapter_id
JOIN arcs a ON a.id = ch.arc_id JOIN campaigns c ON c.id = a.campaign_id
WHERE LOWER(s.name) LIKE :query ESCAPE '!'
UNION ALL
SELECT 'quest', q.id, q.name, c.id, c.name, a.id, a.name, NULL, NULL
FROM quests q JOIN campaigns c ON c.id = q.campaign_id
LEFT JOIN arcs a ON a.id = q.arc_id AND a.campaign_id = c.id
WHERE LOWER(q.name) LIKE :query ESCAPE '!'
) hits
ORDER BY LOWER(name), campaign_id, kind, id
LIMIT 80
""";
@Override
public List<CampaignContentHit> searchByName(String query) {
String pattern = "%" + query.toLowerCase(Locale.ROOT)
.replace("!", "!!").replace("%", "!%").replace("_", "!_") + "%";
return jdbc.query(SQL, Map.of("query", pattern), (rs, row) -> new CampaignContentHit(
rs.getString("kind"), rs.getString("id"), rs.getString("name"),
rs.getString("campaign_id"), rs.getString("campaign_name"),
rs.getString("arc_id"), rs.getString("arc_name"),
rs.getString("chapter_id"), rs.getString("chapter_name")));
}
}
@@ -60,6 +60,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
.name(e.getName()) .name(e.getName())
.description(e.getDescription()) .description(e.getDescription())
.rulesMarkdown(e.getRulesMarkdown()) .rulesMarkdown(e.getRulesMarkdown())
.rulesMarkdownEn(e.getRulesMarkdownEn())
.characterTemplate(e.getCharacterTemplate() != null .characterTemplate(e.getCharacterTemplate() != null
? new java.util.ArrayList<>(e.getCharacterTemplate()) ? new java.util.ArrayList<>(e.getCharacterTemplate())
: new java.util.ArrayList<>()) : new java.util.ArrayList<>())
@@ -84,6 +85,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
.name(g.getName()) .name(g.getName())
.description(g.getDescription()) .description(g.getDescription())
.rulesMarkdown(g.getRulesMarkdown()) .rulesMarkdown(g.getRulesMarkdown())
.rulesMarkdownEn(g.getRulesMarkdownEn())
.characterTemplate(g.getCharacterTemplate() != null .characterTemplate(g.getCharacterTemplate() != null
? new java.util.ArrayList<>(g.getCharacterTemplate()) ? new java.util.ArrayList<>(g.getCharacterTemplate())
: new java.util.ArrayList<>()) : new java.util.ArrayList<>())
@@ -1,76 +0,0 @@
package com.loremind.infrastructure.persistence.postgres;
import com.loremind.domain.licensing.License;
import com.loremind.domain.licensing.ports.LicenseRepository;
import com.loremind.infrastructure.persistence.entity.LicenseJpaEntity;
import com.loremind.infrastructure.persistence.jpa.LicenseJpaRepository;
import org.springframework.stereotype.Repository;
import java.time.Instant;
import java.util.Optional;
@Repository
public class PostgresLicenseRepository implements LicenseRepository {
static final String CURRENT_ID = "current";
private final LicenseJpaRepository jpa;
public PostgresLicenseRepository(LicenseJpaRepository jpa) {
this.jpa = jpa;
}
@Override
public Optional<License> findCurrent() {
return jpa.findById(CURRENT_ID).map(this::toDomain);
}
@Override
public License save(License license) {
LicenseJpaEntity entity = toEntity(license);
if (entity.getCreatedAt() == null) {
entity.setCreatedAt(Instant.now());
}
LicenseJpaEntity saved = jpa.save(entity);
return toDomain(saved);
}
@Override
public void deleteCurrent() {
jpa.deleteById(CURRENT_ID);
}
private License toDomain(LicenseJpaEntity e) {
return License.builder()
.id(e.getId())
.rawJwt(e.getRawJwt())
.patreonUserId(e.getPatreonUserId())
.tierId(e.getTierId())
.instanceId(e.getInstanceId())
.issuedAt(e.getIssuedAt())
.expiresAt(e.getExpiresAt())
.lastRefreshAttemptAt(e.getLastRefreshAttemptAt())
.lastRefreshSucceeded(e.isLastRefreshSucceeded())
.betaChannelEnabled(e.isBetaChannelEnabled())
.createdAt(e.getCreatedAt())
.updatedAt(e.getUpdatedAt())
.build();
}
private LicenseJpaEntity toEntity(License l) {
return LicenseJpaEntity.builder()
.id(CURRENT_ID)
.rawJwt(l.getRawJwt())
.patreonUserId(l.getPatreonUserId())
.tierId(l.getTierId())
.instanceId(l.getInstanceId())
.issuedAt(l.getIssuedAt())
.expiresAt(l.getExpiresAt())
.lastRefreshAttemptAt(l.getLastRefreshAttemptAt())
.lastRefreshSucceeded(l.isLastRefreshSucceeded())
.betaChannelEnabled(l.isBetaChannelEnabled())
.createdAt(l.getCreatedAt())
.updatedAt(l.getUpdatedAt())
.build();
}
}
@@ -577,7 +577,8 @@ public class ExportService {
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) { private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(), return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(), e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic()); e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic(),
e.getRulesMarkdownEn());
} }
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) { private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
@@ -49,6 +49,7 @@ class LoreContentInserter {
e.setName(d.name()); e.setName(d.name());
e.setDescription(d.description()); e.setDescription(d.description());
e.setRulesMarkdown(d.rulesMarkdown()); e.setRulesMarkdown(d.rulesMarkdown());
e.setRulesMarkdownEn(d.rulesMarkdownEn());
e.setCharacterTemplate(d.characterTemplate()); e.setCharacterTemplate(d.characterTemplate());
e.setNpcTemplate(d.npcTemplate()); e.setNpcTemplate(d.npcTemplate());
e.setEnemyTemplate(d.enemyTemplate()); e.setEnemyTemplate(d.enemyTemplate());
@@ -77,7 +77,9 @@ public record ContentExport(
List<TemplateField> enemyTemplate, List<TemplateField> enemyTemplate,
String foundryActorType, String foundryActorType,
String author, String author,
boolean isPublic boolean isPublic,
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
String rulesMarkdownEn
) {} ) {}
public record LoreDto( public record LoreDto(
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory;
import com.loremind.domain.campaigncontext.quest.NodeType; import com.loremind.domain.campaigncontext.quest.NodeType;
import com.loremind.domain.campaigncontext.quest.Prerequisite; import com.loremind.domain.campaigncontext.quest.Prerequisite;
import com.loremind.domain.campaigncontext.quest.QuestNodeRef; import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.structure.Room; import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.RoomBranch; import com.loremind.domain.campaigncontext.structure.RoomBranch;
import com.loremind.domain.campaigncontext.structure.SceneBranch; import com.loremind.domain.campaigncontext.structure.SceneBranch;
@@ -116,6 +117,7 @@ public class PdfExportService {
/** Construit le PDF de la campagne selon les options. @throws NoSuchElementException si absente. */ /** Construit le PDF de la campagne selon les options. @throws NoSuchElementException si absente. */
public byte[] export(String campaignId, PdfExportOptions options) { public byte[] export(String campaignId, PdfExportOptions options) {
options = options != null ? options : PdfExportOptions.defaults();
String xhtml = xhtml(campaignId, options); String xhtml = xhtml(campaignId, options);
try { try {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -124,7 +126,12 @@ public class PdfExportService {
registerFonts(builder); registerFonts(builder);
builder.withHtmlContent(xhtml, null); builder.withHtmlContent(xhtml, null);
builder.toStream(out); builder.toStream(out);
builder.run(); try (var renderer = builder.buildPdfRenderer(); var document = renderer.getPdfDocument()) {
renderer.layout();
renderer.createPDFWithoutClosing();
PdfPageOrnaments.draw(document, options);
document.save(out);
}
return out.toByteArray(); return out.toByteArray();
} catch (IOException e) { } catch (IOException e) {
throw new UncheckedIOException("Echec de la generation du PDF", e); throw new UncheckedIOException("Echec de la generation du PDF", e);
@@ -194,6 +201,7 @@ public class PdfExportService {
int enemies; int enemies;
int randomTables; int randomTables;
int lorePages; int lorePages;
private boolean columns;
Ctx(PdfExportOptions opt) { Ctx(PdfExportOptions opt) {
this.opt = opt; this.opt = opt;
@@ -205,7 +213,19 @@ public class PdfExportService {
} }
double contentWidthCm() { double contentWidthCm() {
return opt.format().contentWidthCm(); double width = opt.format().contentWidthCm();
return columns ? (width - 0.8) / 2 : width;
}
/** Le petit format garde une colonne ; les tables et cartes restent hors du flux. */
void beginColumns() {
columns = opt.format() == PdfExportOptions.PageFormat.A4;
if (columns) body.append("<div class=\"editorial-flow\">");
}
void endColumns() {
if (columns) body.append(DIV_CLOSE);
columns = false;
} }
/** Champ reserve au MJ : absent de la version joueurs. */ /** Champ reserve au MJ : absent de la version joueurs. */
@@ -317,6 +337,10 @@ public class PdfExportService {
private void cover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub) { private void cover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub) {
boolean published = pub.hasContent(); boolean published = pub.hasContent();
PdfImage art = imageEncoder.image(pub.coverImageId(), PdfImageEncoder.ILLUSTRATION_MAX); PdfImage art = imageEncoder.image(pub.coverImageId(), PdfImageEncoder.ILLUSTRATION_MAX);
if (art != null && ctx.opt.format() == PdfExportOptions.PageFormat.A4 && !ctx.opt.printFriendly()) {
illustratedCover(b, ctx, c, pub, art);
return;
}
b.append("<div class=\"cover").append(art != null ? " has-art" : "").append("\">"); b.append("<div class=\"cover").append(art != null ? " has-art" : "").append("\">");
String kicker = coverKicker(ctx, pub); String kicker = coverKicker(ctx, pub);
if (kicker != null) b.append("<div class=\"cover-kicker\">").append(esc(kicker)).append(DIV_CLOSE); if (kicker != null) b.append("<div class=\"cover-kicker\">").append(esc(kicker)).append(DIV_CLOSE);
@@ -350,6 +374,32 @@ public class PdfExportService {
b.append(DIV_CLOSE); b.append(DIV_CLOSE);
} }
/** Couverture A4 illustree : image a fond perdu et cartouche contraste, sans etirer l'image. */
private static void illustratedCover(StringBuilder b, Ctx ctx, CampaignJpaEntity c,
CampaignPublication pub, PdfImage art) {
double scale = Math.max(21.0 / art.w(), 29.7 / art.h());
double width = art.w() * scale, height = art.h() * scale;
b.append("<div class=\"cover cover-illustrated\"><img class=\"cover-background\" style=\"width:")
.append(cm(width)).append(";height:").append(cm(height))
.append(";left:").append(cm((21.0 - width) / 2))
.append(";top:").append(cm((29.7 - height) / 2))
.append("\" src=\"").append(art.uri()).append("\"/>")
.append("<div class=\"cover-caption\">");
String kicker = coverKicker(ctx, pub);
if (kicker != null) b.append("<div class=\"cover-kicker\">").append(esc(kicker)).append(DIV_CLOSE);
int titleSize = c.getName().length() > 100 ? 20 : c.getName().length() > 60 ? 26 : 32;
b.append("<h1 class=\"cover-title\" style=\"font-size:").append(titleSize).append("pt\">")
.append(esc(c.getName())).append("</h1>");
if (notBlank(pub.subtitle())) b.append("<div class=\"cover-subtitle\">").append(esc(pub.subtitle())).append(DIV_CLOSE);
b.append("<div class=\"cover-rule\"></div>");
String meta = technicalLine(pub);
if (!meta.isEmpty()) b.append("<div class=\"cover-meta\">").append(esc(meta)).append(DIV_CLOSE);
if (!ctx.gm) b.append("<div class=\"cover-edition\">Édition joueurs</div>");
if (notBlank(pub.author())) b.append("<div class=\"cover-author\">").append(esc(pub.author())).append(DIV_CLOSE);
if (notBlank(pub.version())) b.append("<div class=\"cover-version\">Version ").append(esc(pub.version())).append(DIV_CLOSE);
b.append("</div></div>");
}
/** Surtitre : le systeme de jeu s'il est renseigne ; sinon l'intitule historique du livret. */ /** Surtitre : le systeme de jeu s'il est renseigne ; sinon l'intitule historique du livret. */
private static String coverKicker(Ctx ctx, CampaignPublication pub) { private static String coverKicker(Ctx ctx, CampaignPublication pub) {
if (notBlank(pub.system())) return pub.system(); if (notBlank(pub.system())) return pub.system();
@@ -399,14 +449,17 @@ public class PdfExportService {
ctx.addToc(0, "Introduction", "part-intro"); ctx.addToc(0, "Introduction", "part-intro");
ctx.bookmarks.append(bookmark("Introduction", "part-intro", "")); ctx.bookmarks.append(bookmark("Introduction", "part-intro", ""));
ctx.beginColumns();
technicalTable(b, pub); technicalTable(b, pub);
String pitch = notBlank(pub.pitch()) ? pub.pitch() : c.getDescription(); String pitch = notBlank(pub.pitch()) ? pub.pitch() : c.getDescription();
introSection(b, "L'aventure en bref", pitch); introSection(b, "L'aventure en bref", pitch);
box(b, "warning", "Avertissements de contenu", pub.contentWarnings()); box(b, "warning", "Avertissements de contenu", pub.contentWarnings());
if (!ctx.gm) return; if (ctx.gm) {
introSection(b, "Contexte pour le MJ", pub.gmBackground()); introSection(b, "Contexte pour le MJ", pub.gmBackground());
introSection(b, "Accroches", pub.hooks()); introSection(b, "Accroches", pub.hooks());
if (ctx.opt.includes(Section.NARRATIVE)) introSection(b, "Structure de l'aventure", structureOutline(st)); if (ctx.opt.includes(Section.NARRATIVE)) introSection(b, "Structure de l'aventure", structureOutline(st));
}
ctx.endColumns();
} }
/** Tableau « Système / Niveaux / Joueurs / Durée » de la page technique. */ /** Tableau « Système / Niveaux / Joueurs / Durée » de la page technique. */
@@ -488,11 +541,12 @@ public class PdfExportService {
List<ArcJpaEntity> arcs = st.visibleArcs; List<ArcJpaEntity> arcs = st.visibleArcs;
if (arcs.isEmpty()) return; if (arcs.isEmpty()) return;
// Mode plat (miroir de l'UI Niveau 0) : 1 arc d'UN SEUL chapitre → on masque les // Mode plat (miroir de l'UI Niveau 0) : 1 arc linéaire d'UN SEUL chapitre, tous deux
// niveaux Arc/Chapitre et on présente les scènes À PLAT (cohérent avec la sidebar). // VIDES (créés d'office) → on masque les niveaux Arc/Chapitre et on présente les
if (arcs.size() == 1) { // scènes À PLAT. Un arc ou un chapitre écrit (méthode guidée…) garde ses en-têtes.
if (arcs.size() == 1 && arcs.get(0).getType() != ArcType.HUB) {
List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId()); List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId());
if (only.size() == 1) { if (only.size() == 1 && isBare(arcs.get(0)) && isBare(only.get(0))) {
narrativeFlat(ctx, st, arcs.get(0), only.get(0)); narrativeFlat(ctx, st, arcs.get(0), only.get(0));
return; return;
} }
@@ -502,9 +556,33 @@ public class PdfExportService {
ctx.addToc(0, "Structure narrative", ANCHOR_PART_NARRATIVE); ctx.addToc(0, "Structure narrative", ANCHOR_PART_NARRATIVE);
narrativeBookmarks(ctx, st, arcs); narrativeBookmarks(ctx, st, arcs);
ctx.beginColumns();
for (ArcJpaEntity arc : arcs) { for (ArcJpaEntity arc : arcs) {
arcSection(ctx, st, arc); arcSection(ctx, st, arc);
} }
ctx.endColumns();
}
/** Aucun contenu d'ecriture dans l'arc (son nom ne compte pas : « Arc principal » est cree d'office). */
static boolean isBare(ArcJpaEntity arc) {
return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(),
arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks())
&& isEmpty(arc.getIllustrationImageIds());
}
/** Aucun contenu d'ecriture dans le chapitre (son nom ne compte pas : « Chapitre 1 » est cree d'office). */
static boolean isBare(ChapterJpaEntity ch) {
return allBlank(ch.getDescription(), ch.getPlayerObjectives(), ch.getNarrativeStakes(), ch.getGmNotes())
&& isEmpty(ch.getIllustrationImageIds());
}
private static boolean allBlank(String... values) {
for (String v : values) if (notBlank(v)) return false;
return true;
}
private static boolean isEmpty(List<String> list) {
return list == null || list.isEmpty();
} }
/** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */ /** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */
@@ -606,6 +684,7 @@ public class PdfExportService {
b.append("<h1 class=\"part\" id=\"part-narrative\">Scènes</h1>"); b.append("<h1 class=\"part\" id=\"part-narrative\">Scènes</h1>");
ctx.addToc(0, "Scènes", ANCHOR_PART_NARRATIVE); ctx.addToc(0, "Scènes", ANCHOR_PART_NARRATIVE);
ctx.beginColumns();
arcFields(ctx, arc); arcFields(ctx, arc);
chapterFields(ctx, ch, st.questByContainerChapter.get(ch.getId()), st); chapterFields(ctx, ch, st.questByContainerChapter.get(ch.getId()), st);
@@ -617,6 +696,7 @@ public class PdfExportService {
ctx.scenes++; ctx.scenes++;
} }
ctx.bookmarks.append(bookmark("Scènes", ANCHOR_PART_NARRATIVE, scBms.toString())); ctx.bookmarks.append(bookmark("Scènes", ANCHOR_PART_NARRATIVE, scBms.toString()));
ctx.endColumns();
} }
/** /**
@@ -791,7 +871,10 @@ public class PdfExportService {
} }
if (!notBlank(difficulty) && enemies.isEmpty() && !notBlank(freeText) && !notBlank(tactics)) return; if (!notBlank(difficulty) && enemies.isEmpty() && !notBlank(freeText) && !notBlank(tactics)) return;
StringBuilder b = ctx.body; StringBuilder b = ctx.body;
b.append("<div class=\"box combat\"><div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE); String boxText = Objects.toString(difficulty, "") + "\n" + String.join("\n", enemies)
+ "\n" + Objects.toString(freeText, "") + "\n" + Objects.toString(tactics, "");
b.append("<div class=\"box combat").append(isLongBox(boxText) ? " flow" : "")
.append("\"><div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
prose(b, difficulty); prose(b, difficulty);
if (!enemies.isEmpty()) { if (!enemies.isEmpty()) {
b.append("<ul class=\"prose-list\">"); b.append("<ul class=\"prose-list\">");
@@ -816,10 +899,12 @@ public class PdfExportService {
for (QuestJpaEntity q : quests) qBms.append(bookmark(q.getName(), "quest-" + q.getId(), "")); for (QuestJpaEntity q : quests) qBms.append(bookmark(q.getName(), "quest-" + q.getId(), ""));
ctx.bookmarks.append(bookmark("Quêtes", "part-quests", qBms.toString())); ctx.bookmarks.append(bookmark("Quêtes", "part-quests", qBms.toString()));
ctx.beginColumns();
for (QuestJpaEntity q : quests) { for (QuestJpaEntity q : quests) {
ctx.addToc(1, q.getName(), "quest-" + q.getId()); ctx.addToc(1, q.getName(), "quest-" + q.getId());
standaloneQuest(ctx, q, st); standaloneQuest(ctx, q, st);
} }
ctx.endColumns();
} }
/** Une quete libre/transversale : ses champs + les scenes de ses conteneurs (arc SYSTEM masque). */ /** Une quete libre/transversale : ses champs + les scenes de ses conteneurs (arc SYSTEM masque). */
@@ -1377,7 +1462,9 @@ public class PdfExportService {
StringBuilder b = ctx.body; StringBuilder b = ctx.body;
// Hauteur bornee proportionnellement au format (A5 : environ 7,8 cm). // Hauteur bornee proportionnellement au format (A5 : environ 7,8 cm).
double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * ctx.opt.format().widthCm / PdfExportOptions.PageFormat.A4.widthCm; double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * ctx.opt.format().widthCm / PdfExportOptions.PageFormat.A4.widthCm;
double widthCm = Math.min(ctx.contentWidthCm(), maxHeight * img.w() / img.h()); // Reserve les retraits des encadres et pieces imbriques, y compris en deux colonnes.
double maxWidth = ctx.contentWidthCm() - (ctx.columns ? 1.2 : 0);
double widthCm = Math.min(maxWidth, maxHeight * img.w() / img.h());
b.append("<div class=\"illus\"><img style=\"width:").append(cm(widthCm)) b.append("<div class=\"illus\"><img style=\"width:").append(cm(widthCm))
.append("\" src=\"").append(img.uri()).append("\"/>"); .append("\" src=\"").append(img.uri()).append("\"/>");
if (caption != null) { if (caption != null) {
@@ -1422,6 +1509,9 @@ public class PdfExportService {
.replace("__PAGE_MARGIN__", margins) .replace("__PAGE_MARGIN__", margins)
.replace("__BODY_PT__", String.format(Locale.ROOT, "%.1fpt", f.bodyPt)); .replace("__BODY_PT__", String.format(Locale.ROOT, "%.1fpt", f.bodyPt));
if (f == PdfExportOptions.PageFormat.A5) css += A5_CSS; if (f == PdfExportOptions.PageFormat.A5) css += A5_CSS;
if (f == PdfExportOptions.PageFormat.A4) {
css += EDITORIAL_CSS.replace("__HEADER__", esc(header.replace("\\", "\\\\").replace("'", "\\'")));
}
return opt.printFriendly() ? css + PRINT_CSS : css; return opt.printFriendly() ? css + PRINT_CSS : css;
} }
@@ -1437,6 +1527,7 @@ public class PdfExportService {
private static final String PRINT_CSS = loadCss("/pdf/export-print.css"); private static final String PRINT_CSS = loadCss("/pdf/export-print.css");
/** Surcharges A5 : couverture et titres resserres pour une page etroite. */ /** Surcharges A5 : couverture et titres resserres pour une page etroite. */
private static final String A5_CSS = loadCss("/pdf/export-a5.css"); private static final String A5_CSS = loadCss("/pdf/export-a5.css");
private static final String EDITORIAL_CSS = loadCss("/pdf/export-editorial.css");
private static String loadCss(String resource) { private static String loadCss(String resource) {
try (InputStream in = PdfExportService.class.getResourceAsStream(resource)) { try (InputStream in = PdfExportService.class.getResourceAsStream(resource)) {
@@ -88,7 +88,8 @@ final class PdfHtml {
*/ */
static void box(StringBuilder b, String cssClass, String label, String value) { static void box(StringBuilder b, String cssClass, String label, String value) {
if (!notBlank(value)) return; if (!notBlank(value)) return;
b.append("<div class=\"box ").append(cssClass).append("\">"); boolean longText = isLongBox(value);
b.append("<div class=\"box ").append(cssClass).append(longText ? " flow" : "").append("\">");
b.append("<div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE); b.append("<div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
List<TextBlock> blocks = parseBlocks(value); List<TextBlock> blocks = parseBlocks(value);
for (int i = 0; i < blocks.size(); i++) { for (int i = 0; i < blocks.size(); i++) {
@@ -106,6 +107,11 @@ final class PdfHtml {
b.append(DIV_CLOSE); b.append(DIV_CLOSE);
} }
/** Borne conservative des encadres qui peuvent rester entiers dans une colonne A4. */
static boolean isLongBox(String text) {
return text.length() > 900 || text.lines().count() > 12;
}
/** /**
* Bloc "libelle en tete de ligne + valeur" si la valeur est non vide. Le libelle est * Bloc "libelle en tete de ligne + valeur" si la valeur est non vide. Le libelle est
* rendu EN LIGNE devant le premier paragraphe (style stat-block : compact et balayable), * rendu EN LIGNE devant le premier paragraphe (style stat-block : compact et balayable),
@@ -0,0 +1,110 @@
package com.loremind.infrastructure.transfer.pdf;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.util.Matrix;
import java.awt.Color;
import java.io.IOException;
/** Motifs vectoriels originaux, confines aux 49 points de marge inferieure des pages A4.
* Les dessiner apres la pagination conserve les renvois, le texte et la mise en page. */
final class PdfPageOrnaments {
private static final Color INK = new Color(0x34594f);
private static final Color SAGE = new Color(0xa8bbae);
private static final Color PALE = new Color(0xe6ece3);
private static final Color GOLD = new Color(0xb5a278);
private static final Color PRINT = new Color(0x999999);
private PdfPageOrnaments() {}
static void draw(PDDocument document, PdfExportOptions options) throws IOException {
if (options.format() != PdfExportOptions.PageFormat.A4) return;
// Pas de decoration sur la couverture, ni sur les annexes cartographiques paysage.
for (int i = 1; i < document.getNumberOfPages(); i++) {
var page = document.getPage(i);
var bounds = page.getMediaBox();
if (bounds.getWidth() > bounds.getHeight()) continue;
try (var canvas = new PDPageContentStream(document, page,
PDPageContentStream.AppendMode.PREPEND, true, true)) {
canvas.saveGraphicsState();
canvas.addRect(0, 0, bounds.getWidth(), 49);
canvas.clip();
// Le coin exterieur est plus ample ; alternance pour les pages en vis-a-vis.
corner(canvas, 0, false, i % 2 == 1 ? 1f : .72f, options.printFriendly());
corner(canvas, bounds.getWidth(), true, i % 2 == 0 ? 1f : .72f, options.printFriendly());
folio(canvas, bounds.getWidth() / 2, options.printFriendly());
canvas.restoreGraphicsState();
}
}
}
private static void corner(PDPageContentStream c, float x, boolean mirror, float scale,
boolean print) throws IOException {
c.saveGraphicsState();
c.transform(new Matrix(mirror ? -scale : scale, 0, 0, scale, x, 0));
if (!print) {
c.setNonStrokingColor(PALE);
c.moveTo(0, 49);
c.curveTo(35, 18, 94, 9, 184, 0);
c.lineTo(0, 0);
c.closePath();
c.fill();
c.setNonStrokingColor(SAGE);
c.moveTo(0, 35);
c.curveTo(40, 8, 81, 8, 150, 0);
c.lineTo(0, 0);
c.closePath();
c.fill();
c.setNonStrokingColor(INK);
c.moveTo(0, 21);
c.curveTo(22, 9, 63, 3, 110, 0);
c.lineTo(0, 0);
c.closePath();
c.fill();
c.setNonStrokingColor(SAGE);
for (int col = 0; col < 17; col++) {
float dx = 14 + col * 8;
for (int row = 0; row < 4; row++) {
float dy = 43 - col * 1.6f - row * 6;
if (dy > 13) dot(c, dx + (row % 2) * 3, dy, .35f + row * .12f);
}
}
}
c.setStrokingColor(print ? PRINT : GOLD);
c.setLineWidth(.45f);
c.moveTo(0, 43);
c.curveTo(32, 16, 85, 7, 170, 3);
c.stroke();
c.restoreGraphicsState();
}
private static void folio(PDPageContentStream c, float center, boolean print) throws IOException {
c.setStrokingColor(print ? PRINT : GOLD);
c.setNonStrokingColor(print ? PRINT : GOLD);
c.setLineWidth(.4f);
for (int side : new int[]{-1, 1}) {
c.moveTo(center + side * 18, 27);
c.lineTo(center + side * 37, 27);
c.stroke();
float x = center + side * 43;
c.moveTo(x, 29);
c.lineTo(x + 2, 27);
c.lineTo(x, 25);
c.lineTo(x - 2, 27);
c.closePath();
if (print) c.stroke(); else c.fill();
}
}
private static void dot(PDPageContentStream c, float x, float y, float r) throws IOException {
float k = r * .552285f;
c.moveTo(x + r, y);
c.curveTo(x + r, y + k, x + k, y + r, x, y + r);
c.curveTo(x - k, y + r, x - r, y + k, x - r, y);
c.curveTo(x - r, y - k, x - k, y - r, x, y - r);
c.curveTo(x + k, y - r, x + r, y - k, x + r, y);
c.closePath();
c.fill();
}
}
@@ -0,0 +1,57 @@
package com.loremind.infrastructure.updates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Retire les identifiants GHCR laisses par l'ancien canal beta Patreon.
*
* <p>Jusqu'a la 1.5, le Core ecrivait un {@code config.json} Docker (jeton GHCR recu
* du relais Patreon) dans un volume partage avec Watchtower et le switcher. Le canal
* beta est desormais libre et ses images publiques : ce jeton ne sert plus, et une
* fois revoque il ferait ECHOUER les telechargements (un registry refuse des
* identifiants invalides, meme pour une image publique). Le fichier n'a jamais
* contenu que ces identifiants : on le supprime au demarrage.
*
* <p>No-op sur les installations recentes : le docker-compose.yml ne monte plus ce
* volume ni ne definit {@code LICENSING_DOCKER_CONFIG_PATH}.
*/
@Component
public class LegacyRegistryCredentialsCleanup implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(LegacyRegistryCredentialsCleanup.class);
private final String configPath;
public LegacyRegistryCredentialsCleanup(@Value("${LICENSING_DOCKER_CONFIG_PATH:}") String configPath) {
this.configPath = configPath;
}
@Override
public void run(ApplicationArguments args) {
cleanup();
}
/** @return true si un ancien fichier d'identifiants a ete supprime */
boolean cleanup() {
if (configPath == null || configPath.isBlank()) return false;
Path file = Path.of(configPath);
try {
if (Files.deleteIfExists(file)) {
log.info("[Updates] Anciens identifiants GHCR du canal beta supprimes ({}).", file);
return true;
}
} catch (IOException | SecurityException e) {
log.warn("[Updates] Impossible de supprimer les anciens identifiants GHCR ({}) : {}", file, e.getMessage());
}
return false;
}
}
@@ -1,9 +1,7 @@
package com.loremind.infrastructure.updates; package com.loremind.infrastructure.updates;
import com.loremind.application.licensing.LicenseService; import com.loremind.application.channel.ChannelSwitcherService;
import com.loremind.domain.licensing.LicenseSnapshot; import com.loremind.application.channel.ChannelSwitcherService.Channel;
import com.loremind.domain.licensing.LicenseStatus;
import com.loremind.domain.licensing.RegistryCredentials;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@@ -24,10 +22,8 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
/** /**
* Detection des mises a jour disponibles + declenchement via Watchtower. * Detection des mises a jour disponibles + declenchement via Watchtower.
@@ -59,8 +55,9 @@ public class UpdateCheckService {
private final List<String> images; private final List<String> images;
private final String watchtowerUrl; private final String watchtowerUrl;
private final String watchtowerToken; private final String watchtowerToken;
private final String betaRegistry;
private final List<String> betaImages; private final List<String> betaImages;
private final LicenseService licenseService; private final ChannelSwitcherService channels;
/** Version semver courante du binaire (ex: "0.8.0"). Source de verite. */ /** Version semver courante du binaire (ex: "0.8.0"). Source de verite. */
private final String currentVersion; private final String currentVersion;
@@ -70,8 +67,9 @@ public class UpdateCheckService {
@Value("${update-check.images:}") String imagesCsv, @Value("${update-check.images:}") String imagesCsv,
@Value("${update-check.watchtower-url:http://watchtower:8080}") String watchtowerUrl, @Value("${update-check.watchtower-url:http://watchtower:8080}") String watchtowerUrl,
@Value("${update-check.watchtower-token:}") String watchtowerToken, @Value("${update-check.watchtower-token:}") String watchtowerToken,
@Value("${licensing.beta.images:}") String betaImagesCsv, @Value("${update-check.beta-registry:ghcr.io}") String betaRegistry,
LicenseService licenseService, @Value("${update-check.beta-images:}") String betaImagesCsv,
ChannelSwitcherService channels,
@Nullable BuildProperties buildProperties) { @Nullable BuildProperties buildProperties) {
this.http = builder this.http = builder
.connectTimeout(Duration.ofSeconds(5)) .connectTimeout(Duration.ofSeconds(5))
@@ -81,8 +79,9 @@ public class UpdateCheckService {
this.images = parseImages(imagesCsv); this.images = parseImages(imagesCsv);
this.watchtowerUrl = watchtowerUrl; this.watchtowerUrl = watchtowerUrl;
this.watchtowerToken = watchtowerToken; this.watchtowerToken = watchtowerToken;
this.betaRegistry = normalizeRegistry(betaRegistry);
this.betaImages = parseImages(betaImagesCsv); this.betaImages = parseImages(betaImagesCsv);
this.licenseService = licenseService; this.channels = channels;
this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null; this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null;
log.info("Update check init - registry={} images={} currentVersion={}", log.info("Update check init - registry={} images={} currentVersion={}",
this.registry, this.images, this.currentVersion); this.registry, this.images, this.currentVersion);
@@ -119,33 +118,17 @@ public class UpdateCheckService {
} }
/** /**
* Verifie l'etat du canal beta (images privees GHCR) avec auth basique. * Verifie l'etat du canal beta quand l'instance y tourne. Les images beta sont
* publiques (canal libre, plus de licence) : lecture anonyme du registry.
*/ */
public BetaStatus checkBeta() { public BetaStatus checkBeta() {
if (!licenseService.isLicensingEnabled()) { if (channels.getCurrentChannel() != Channel.BETA) {
return BetaStatus.disabled("licensing-not-configured"); return BetaStatus.disabled("not-on-beta-channel");
} }
LicenseSnapshot snap = licenseService.getCurrentSnapshot(); if (betaImages.isEmpty() || betaRegistry.isEmpty()) {
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
return BetaStatus.disabled("license-" + snap.status().name().toLowerCase());
}
if (!snap.betaChannelEnabled()) {
return BetaStatus.disabled("beta-toggle-off");
}
if (betaImages.isEmpty()) {
return BetaStatus.disabled("no-beta-images-configured"); return BetaStatus.disabled("no-beta-images-configured");
} }
ImagesEvaluation ev = evaluateImages(betaImages, betaRegistry, null);
Optional<RegistryCredentials> creds = licenseService.fetchRegistryCredentials();
if (creds.isEmpty()) {
return new BetaStatus(true, false, true, List.of(), Instant.now(), "relay-unavailable");
}
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(
(creds.get().username() + ":" + creds.get().password()).getBytes(StandardCharsets.UTF_8));
String betaRegistry = normalizeRegistry(creds.get().registry());
ImagesEvaluation ev = evaluateImages(betaImages, betaRegistry, basicAuth);
return new BetaStatus(true, ev.anyUpdate(), ev.anyUnknown(), return new BetaStatus(true, ev.anyUpdate(), ev.anyUnknown(),
ev.statuses(), Instant.now(), null); ev.statuses(), Instant.now(), null);
} }
@@ -31,7 +31,7 @@ import java.util.Map;
* </ul> * </ul>
* *
* <p>Important : ne court-circuite PAS les try/catch locaux des controllers * <p>Important : ne court-circuite PAS les try/catch locaux des controllers
* (ex: LicenseController.install catche InstallException -> 400 lui-meme). * (ex: UpdatesController.switchChannel catche IOException -> 500 lui-meme).
* Ce handler n'attrape QUE ce qui a echappe au catch local. * Ce handler n'attrape QUE ce qui a echappe au catch local.
*/ */
@RestControllerAdvice @RestControllerAdvice
@@ -32,7 +32,7 @@ public class RemoteAccessFilter extends OncePerRequestFilter {
private static final List<String> PUBLIC_PATHS = List.of( private static final List<String> PUBLIC_PATHS = List.of(
"/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session"); "/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session");
private static final List<String> LOCAL_ONLY_PREFIXES = List.of( private static final List<String> LOCAL_ONLY_PREFIXES = List.of(
"/api/settings", "/api/admin", "/api/license"); "/api/settings", "/api/admin");
private final RemoteAccessService remoteAccessService; private final RemoteAccessService remoteAccessService;
@@ -85,7 +85,6 @@ public class SecurityConfig {
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers("/api/settings/**").hasRole(ROLE_ADMIN) .requestMatchers("/api/settings/**").hasRole(ROLE_ADMIN)
.requestMatchers("/api/admin/**").hasRole(ROLE_ADMIN) .requestMatchers("/api/admin/**").hasRole(ROLE_ADMIN)
.requestMatchers("/api/license/**").hasRole(ROLE_ADMIN)
.anyRequest().permitAll() .anyRequest().permitAll()
) )
.httpBasic(basic -> {}); .httpBasic(basic -> {});
@@ -0,0 +1,18 @@
package com.loremind.infrastructure.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
/**
* Langue de l'utilisateur dans les tâches de fond : Spring Boot applique ce décorateur unique
* à l'exécuteur auto-configuré ({@code applicationTaskExecutor}) utilisé par les flux SSE.
*/
@Configuration
public class UserLanguageConfig {
@Bean
public TaskDecorator userLanguageTaskDecorator() {
return new UserLanguageTaskDecorator();
}
}
@@ -0,0 +1,14 @@
package com.loremind.infrastructure.web.config;
import com.loremind.domain.shared.ports.CurrentLanguage;
import org.springframework.stereotype.Component;
/** Langue courante lue dans {@link UserLanguageHolder} (requête HTTP, ou tâche de fond décorée). */
@Component
public class UserLanguageCurrentLanguage implements CurrentLanguage {
@Override
public String get() {
return UserLanguageHolder.get();
}
}
@@ -0,0 +1,30 @@
package com.loremind.infrastructure.web.config;
import org.springframework.core.task.TaskDecorator;
/**
* Relaie la langue de l'utilisateur ({@link UserLanguageHolder}, un ThreadLocal) du thread
* de la requête HTTP vers le thread de fond qui exécute la tâche.
* <p>
* Sans lui, les traitements longs lancés dans {@code applicationTaskExecutor} (imports de PDF,
* ateliers, chat IA en streaming…) lisaient la valeur par défaut du ThreadLocal sur leur
* propre thread : le Brain rédigeait toujours en français, même avec l'interface en anglais.
* Spring Boot associe automatiquement ce décorateur à l'exécuteur auto-configuré.
*/
public class UserLanguageTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
String language = UserLanguageHolder.get(); // lu sur le thread de la requête
return () -> {
String previous = UserLanguageHolder.get();
UserLanguageHolder.set(language);
try {
runnable.run();
} finally {
// Threads réutilisés par le pool : on ne laisse pas la langue fuir vers la tâche suivante.
UserLanguageHolder.set(previous);
}
};
}
}
@@ -0,0 +1,21 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.campaigncontext.CampaignContentSearchService;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/campaigns/search-content")
public class CampaignContentSearchController {
private final CampaignContentSearchService service;
public CampaignContentSearchController(CampaignContentSearchService service) {
this.service = service;
}
@GetMapping
public List<CampaignContentHit> search(@RequestParam("q") String query) {
return service.search(query);
}
}
@@ -257,6 +257,7 @@ public class GameSystemController {
dto.getName(), dto.getName(),
dto.getDescription(), dto.getDescription(),
dto.getRulesMarkdown(), dto.getRulesMarkdown(),
dto.getRulesMarkdownEn(),
templateFieldMapper.toDomainList(dto.getCharacterTemplate()), templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
templateFieldMapper.toDomainList(dto.getNpcTemplate()), templateFieldMapper.toDomainList(dto.getNpcTemplate()),
templateFieldMapper.toDomainList(dto.getEnemyTemplate()), templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
@@ -0,0 +1,52 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.campaigncontext.GuidedAssistService;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Map;
/**
* IA des méthodes guidées : propose des réponses aux questions d'une méthode à partir de
* l'idée de départ du MJ. Rien n'est enregistré.
*
* <p>{@code POST /api/campaigns/{campaignId}/guided-assist} → {@code {answers: {cle: valeur}}} ;
* 400 sans question, 404 campagne inconnue, 502 si l'IA est indisponible.</p>
*/
@RestController
@RequestMapping("/api/campaigns/{campaignId}/guided-assist")
public class GuidedAssistController {
/** Corps : la méthode (nom, principe), l'idée, les questions et les réponses déjà écrites. */
public record SuggestRequest(String methodName, String principle, String idea,
List<Question> questions, Map<String, String> existing) {}
public record SuggestResponse(Map<String, String> answers) {}
private final GuidedAssistService service;
private final CampaignRepository campaignRepository;
public GuidedAssistController(GuidedAssistService service, CampaignRepository campaignRepository) {
this.service = service;
this.campaignRepository = campaignRepository;
}
@PostMapping
public ResponseEntity<SuggestResponse> suggest(@PathVariable String campaignId, @RequestBody SuggestRequest body) {
if (!campaignRepository.existsById(campaignId)) {
return ResponseEntity.notFound().build();
}
try {
return ResponseEntity.ok(new SuggestResponse(service.suggest(campaignId, body.methodName(),
body.principle(), body.idea(), body.questions(), body.existing())));
} catch (NarrativeAssistException e) {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
}
}
}
@@ -1,160 +0,0 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.licensing.ChannelSwitcherService;
import com.loremind.application.licensing.LicenseService;
import com.loremind.application.licensing.LicenseService.InstallException;
import com.loremind.domain.licensing.LicenseSnapshot;
import com.loremind.infrastructure.web.dto.licensing.ChannelStatusDTO;
import com.loremind.infrastructure.web.dto.licensing.LicenseStatusDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
/**
* Endpoints de gestion de la licence Patreon.
*
* <ul>
* <li>{@code GET /api/license} : etat courant (status, tier, expiration...)</li>
* <li>{@code GET /api/license/connect-url} : URL OAuth a ouvrir dans le navigateur</li>
* <li>{@code POST /api/license/install} : colle un JWT recu du relais</li>
* <li>{@code DELETE /api/license} : deconnecte Patreon (efface la licence)</li>
* <li>{@code POST /api/license/refresh} : force un refresh manuel</li>
* <li>{@code PUT /api/license/beta-channel} : active/desactive le canal beta</li>
* </ul>
*/
@RestController
@RequestMapping("/api/license")
public class LicenseController {
/** Clé du message d'erreur dans le body JSON — contrat lu par le frontend. */
private static final String ERROR_KEY = "error";
private final LicenseService licenseService;
private final ChannelSwitcherService channelSwitcher;
public LicenseController(LicenseService licenseService, ChannelSwitcherService channelSwitcher) {
this.licenseService = licenseService;
this.channelSwitcher = channelSwitcher;
}
@GetMapping
public LicenseStatusDTO getStatus() {
boolean enabled = licenseService.isLicensingEnabled();
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
return LicenseStatusDTO.from(enabled, snap);
}
@GetMapping("/connect-url")
public Map<String, String> getConnectUrl() {
return Map.of("url", licenseService.buildConnectUrl());
}
@PostMapping("/install")
public ResponseEntity<Object> install(@RequestBody InstallRequest request) {
if (request == null || request.jwt() == null || request.jwt().isBlank()) {
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing jwt"));
}
try {
LicenseSnapshot snap = licenseService.installToken(request.jwt());
return ResponseEntity.ok(LicenseStatusDTO.from(true, snap));
} catch (InstallException e) {
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, e.getMessage()));
}
}
@DeleteMapping
public ResponseEntity<Void> disconnect() {
licenseService.disconnect();
return ResponseEntity.noContent().build();
}
@PostMapping("/refresh")
public ResponseEntity<LicenseStatusDTO> refresh() {
licenseService.forceRefresh();
boolean enabled = licenseService.isLicensingEnabled();
return ResponseEntity.ok(LicenseStatusDTO.from(enabled, licenseService.getCurrentSnapshot()));
}
@PutMapping("/beta-channel")
public ResponseEntity<Object> setBetaChannel(@RequestBody BetaChannelRequest request) {
if (request == null) {
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing body"));
}
try {
LicenseSnapshot snap = licenseService.setBetaChannelEnabled(request.enabled());
return ResponseEntity.ok(LicenseStatusDTO.from(true, snap));
} catch (IllegalStateException e) {
return ResponseEntity.status(409).body(Map.of(ERROR_KEY, e.getMessage()));
}
}
// ─── Bascule de canal (stable <-> beta) via sidecar switcher ────────────
//
// Le flux :
// 1. UI POST /api/license/channel/switch { channel: "beta" }
// 2. Core valide la licence (refus si target=beta sans Patreon actif)
// 3. Core depose une commande dans le volume partage
// 4. Sidecar `switcher` la traite (sed .env, docker compose up -d)
// 5. UI poll GET /api/license/channel pour suivre le status
/** Etat courant : canal actuel + dispo du sidecar + dernier resultat. */
// S125 : faux positif — le flux numerote ci-dessus est de la prose explicative, pas du code mort.
@SuppressWarnings("java:S125")
@GetMapping("/channel")
public ChannelStatusDTO getChannel() {
return ChannelStatusDTO.from(channelSwitcher);
}
/** Declenche un switch de canal. Renvoie l'ID de la commande pour le polling. */
@PostMapping("/channel/switch")
public ResponseEntity<Object> switchChannel(@RequestBody ChannelSwitchRequest request) {
if (request == null || request.channel() == null) {
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing channel"));
}
ChannelSwitcherService.Channel target;
try {
target = ChannelSwitcherService.Channel.valueOf(request.channel().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(Map.of(
ERROR_KEY, "invalid channel (allowed: stable, beta)"));
}
// Garde : pas de switch vers beta sans licence Patreon valide.
// Le switcher ferait le boulot quoi qu'il arrive (il valide juste le
// format), donc c'est ici qu'on doit refuser cote metier.
// VALID + GRACE autorisent l'acces beta (cf. javadoc de LicenseStatus).
if (target == ChannelSwitcherService.Channel.BETA) {
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
com.loremind.domain.licensing.LicenseStatus s = (snap != null) ? snap.status() : null;
boolean allowed = s == com.loremind.domain.licensing.LicenseStatus.VALID
|| s == com.loremind.domain.licensing.LicenseStatus.GRACE;
if (!allowed) {
return ResponseEntity.status(403).body(Map.of(
ERROR_KEY, "Aucune licence Patreon active — impossible de basculer sur le canal beta."));
}
}
if (!channelSwitcher.isSwitcherAvailable()) {
return ResponseEntity.status(503).body(Map.of(
ERROR_KEY, "Sidecar switcher non disponible (mise a jour requise du docker-compose.yml)."));
}
try {
String id = channelSwitcher.requestSwitch(target);
return ResponseEntity.accepted().body(Map.of(
"id", id,
"channel", target.name().toLowerCase(Locale.ROOT)));
} catch (IOException e) {
return ResponseEntity.status(500).body(Map.of(
ERROR_KEY, "Impossible d'ecrire la commande de switch: " + e.getMessage()));
}
}
public record InstallRequest(String jwt) {}
public record BetaChannelRequest(boolean enabled) {}
public record ChannelSwitchRequest(String channel) {}
}
@@ -1,5 +1,6 @@
package com.loremind.infrastructure.web.controller; package com.loremind.infrastructure.web.controller;
import com.loremind.application.channel.ChannelSwitcherService;
import com.loremind.infrastructure.updates.UpdateCheckService; import com.loremind.infrastructure.updates.UpdateCheckService;
import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus; import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus;
import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus; import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
@@ -10,10 +11,14 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
import com.loremind.infrastructure.web.dto.updates.ChannelStatusDTO;
import java.io.IOException;
import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
@@ -30,12 +35,18 @@ public class UpdatesController {
private static final Logger log = LoggerFactory.getLogger(UpdatesController.class); private static final Logger log = LoggerFactory.getLogger(UpdatesController.class);
/** Clé du message d'erreur dans le body JSON — contrat lu par le frontend. */
private static final String ERROR_KEY = "error";
private final UpdateCheckService updates; private final UpdateCheckService updates;
private final ChannelSwitcherService channels;
private final boolean demoMode; private final boolean demoMode;
public UpdatesController(UpdateCheckService updates, public UpdatesController(UpdateCheckService updates,
ChannelSwitcherService channels,
@Value("${app.demo-mode:false}") boolean demoMode) { @Value("${app.demo-mode:false}") boolean demoMode) {
this.updates = updates; this.updates = updates;
this.channels = channels;
this.demoMode = demoMode; this.demoMode = demoMode;
} }
@@ -70,6 +81,50 @@ public class UpdatesController {
} }
} }
// --- Bascule de canal stable <-> beta via le sidecar `switcher` ----------
//
// Le canal beta est libre : toute instance Docker peut y passer et en revenir.
// L'UI depose une commande (POST /channel/switch), le sidecar l'applique
// (IMAGE_NAMESPACE du .env + docker compose pull/up), l'UI suit le resultat
// via GET /channel.
/** Etat courant : canal actuel + dispo du sidecar + dernier resultat. */
@GetMapping("/channel")
public ChannelStatusDTO channel() {
guardDemoMode();
return ChannelStatusDTO.from(channels);
}
/** Declenche un switch de canal. Renvoie l'ID de la commande pour le polling. */
@PostMapping("/channel/switch")
public ResponseEntity<Object> switchChannel(@RequestBody ChannelSwitchRequest request) {
guardDemoMode();
if (request == null || request.channel() == null) {
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing channel"));
}
ChannelSwitcherService.Channel target;
try {
target = ChannelSwitcherService.Channel.valueOf(request.channel().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "invalid channel (allowed: stable, beta)"));
}
if (!channels.isSwitcherAvailable()) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(Map.of(
ERROR_KEY, "Sidecar switcher non disponible (mise a jour requise du docker-compose.yml)."));
}
try {
String id = channels.requestSwitch(target);
return ResponseEntity.accepted().body(Map.of(
"id", id,
"channel", target.name().toLowerCase(Locale.ROOT)));
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of(
ERROR_KEY, "Impossible d'ecrire la commande de switch: " + e.getMessage()));
}
}
public record ChannelSwitchRequest(String channel) {}
/** /**
* En mode demo, les instances ne doivent pas se mettre a jour ni meme * En mode demo, les instances ne doivent pas se mettre a jour ni meme
* exposer leur statut (pas de surface d'attaque, et pas de redemarrage * exposer leur statut (pas de surface d'attaque, et pas de redemarrage
@@ -17,6 +17,8 @@ public class GameSystemDTO {
private String name; private String name;
private String description; private String description;
private String rulesMarkdown; private String rulesMarkdown;
/** Version anglaise des règles (rulesMarkdown = version française). */
private String rulesMarkdownEn;
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>(); private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>(); private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>(); private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
@@ -1,35 +0,0 @@
package com.loremind.infrastructure.web.dto.licensing;
import com.loremind.domain.licensing.LicenseSnapshot;
import java.time.Instant;
/**
* Vue serialisee de l'etat de la licence pour le frontend.
* Le {@code rawJwt} n'est volontairement JAMAIS expose.
*/
public record LicenseStatusDTO(
boolean enabled,
String status,
String patreonUserId,
String tierId,
String instanceId,
Instant expiresAt,
Instant lastRefreshAttemptAt,
Boolean lastRefreshSucceeded,
boolean betaChannelEnabled
) {
public static LicenseStatusDTO from(boolean enabled, LicenseSnapshot snap) {
return new LicenseStatusDTO(
enabled,
snap.status().name(),
snap.patreonUserId(),
snap.tierId(),
snap.instanceId(),
snap.expiresAt(),
snap.lastRefreshAttemptAt(),
snap.lastRefreshAttemptAt() != null ? snap.lastRefreshSucceeded() : null,
snap.betaChannelEnabled()
);
}
}
@@ -1,7 +1,7 @@
package com.loremind.infrastructure.web.dto.licensing; package com.loremind.infrastructure.web.dto.updates;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.loremind.application.licensing.ChannelSwitcherService; import com.loremind.application.channel.ChannelSwitcherService;
/** /**
* Etat du canal courant + dernier resultat de switch. * Etat du canal courant + dernier resultat de switch.
@@ -20,6 +20,7 @@ public class GameSystemMapper {
dto.setName(g.getName()); dto.setName(g.getName());
dto.setDescription(g.getDescription()); dto.setDescription(g.getDescription());
dto.setRulesMarkdown(g.getRulesMarkdown()); dto.setRulesMarkdown(g.getRulesMarkdown());
dto.setRulesMarkdownEn(g.getRulesMarkdownEn());
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate())); dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate())); dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate())); dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
@@ -36,6 +37,7 @@ public class GameSystemMapper {
.name(dto.getName()) .name(dto.getName())
.description(dto.getDescription()) .description(dto.getDescription())
.rulesMarkdown(dto.getRulesMarkdown()) .rulesMarkdown(dto.getRulesMarkdown())
.rulesMarkdownEn(dto.getRulesMarkdownEn())
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate())) .characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate())) .npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
.enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate())) .enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate()))
@@ -8,7 +8,7 @@
# vivent sous loremind.home (defaut : ~/.loremind). # vivent sous loremind.home (defaut : ~/.loremind).
# #
# Surcharge UNIQUEMENT ce qui differe du profil par defaut (application.properties) : # Surcharge UNIQUEMENT ce qui differe du profil par defaut (application.properties) :
# le reste (timeouts, multipart, licensing...) est herite tel quel. # le reste (timeouts, multipart...) est herite tel quel.
# --- Config utilisateur editable (port + identifiants admin) ---------------- # --- Config utilisateur editable (port + identifiants admin) ----------------
# Charge ~/.loremind/loremind.properties s'il existe (cree au 1er lancement par # Charge ~/.loremind/loremind.properties s'il existe (cree au 1er lancement par
@@ -105,14 +105,6 @@ loremind.upload.max-file-size=2GB
loremind.upload.max-request-size=2GB loremind.upload.max-request-size=2GB
server.tomcat.max-swallow-size=-1 server.tomcat.max-swallow-size=-1
# --- Licensing / Patreon : desactive en mode bureau ------------------------
# Le gating par IMAGE Docker (canal beta tire d'un registry prive) n'a aucun
# sens hors Docker. On coupe toute la machinerie : daemon de refresh no-op,
# /api/license/* renvoie enabled=false, et l'UI masque la section Patreon.
# La distribution beta desktop se fait par installeur beta via Patreon, pas
# par une connexion in-app.
licensing.enabled=false
# --- Verification des mises a jour (bureau) -------------------------------- # --- Verification des mises a jour (bureau) --------------------------------
# Interroge l'API GitHub Releases (derniere release STABLE) au demarrage ; si # Interroge l'API GitHub Releases (derniere release STABLE) au demarrage ; si
# une version plus recente existe, l'icone systray le signale (bulle + item # une version plus recente existe, l'icone systray le signale (bulle + item
+4 -33
View File
@@ -104,36 +104,7 @@ update-check.images=${UPDATE_CHECK_IMAGES:}
update-check.watchtower-url=${WATCHTOWER_URL:http://watchtower:8080} update-check.watchtower-url=${WATCHTOWER_URL:http://watchtower:8080}
update-check.watchtower-token=${WATCHTOWER_TOKEN:} update-check.watchtower-token=${WATCHTOWER_TOKEN:}
# ============================================================================ # Canal beta (libre) : images publiques verifiees quand l'instance tourne en beta.
# Licensing (canal beta gate par Patreon) # LICENSING_BETA_IMAGES reste lu pour les .env d'avant la suppression de Patreon.
# ============================================================================ update-check.beta-registry=${UPDATE_CHECK_BETA_REGISTRY:ghcr.io}
# URL du relais OAuth Patreon (Cloudflare Workers). En prod : valeur par defaut. update-check.beta-images=${UPDATE_CHECK_BETA_IMAGES:${LICENSING_BETA_IMAGES:igmlcreation/loremind-beta-core,igmlcreation/loremind-beta-brain,igmlcreation/loremind-beta-web}}
licensing.relay.base-url=${LICENSING_RELAY_BASE_URL:https://loremind-auth.igmlcreation.fr}
# Cle publique Ed25519 (PEM SPKI) qui verifie les JWT emis par le relais.
# En prod : chargee automatiquement depuis classpath:licensing/jwt-public-key.pem
# (embarquee dans le binaire). Cette propriete sert UNIQUEMENT a la rotation
# de cle ou aux tests : si LICENSING_JWT_PUBLIC_KEY est defini, il prevaut
# sur le fichier embarque.
licensing.jwt.public-key=${LICENSING_JWT_PUBLIC_KEY:}
licensing.jwt.expected-issuer=loremind-auth
licensing.jwt.expected-audience=loremind-instance
# Periode de tolerance apres expiration du JWT pendant laquelle l'instance
# garde l'acces beta meme si le relais est indisponible pour le refresh.
licensing.grace-period-days=14
# Avant J-N de l'expiration, le daemon tente un refresh.
licensing.refresh-before-expiry-days=2
# Identifiant stable de l'instance (UUID genere a la premiere connexion Patreon
# et conserve en base). Utilise dans le state OAuth + dans le JWT.
licensing.instance-id-file=${LICENSING_INSTANCE_ID_FILE:}
# Image beta : si la licence est valide ET le toggle canal beta active,
# UpdateCheckService check ces images en plus du canal stable.
licensing.beta.images=${LICENSING_BETA_IMAGES:igmlcreation/loremind-beta-core,igmlcreation/loremind-beta-brain,igmlcreation/loremind-beta-web}
# Chemin de sortie pour le docker config.json partage avec Watchtower.
# Volume Docker `docker-config` monte sur ce chemin dans Core, et sur
# `/shared/docker` dans Watchtower (DOCKER_CONFIG=/shared/docker).
licensing.docker-config-path=${LICENSING_DOCKER_CONFIG_PATH:/shared/docker/config.json}
@@ -0,0 +1,3 @@
-- Règles d'un système de jeu en deux langues : rules_markdown = version française,
-- rules_markdown_en = version anglaise (remplie à l'import d'un PDF par traduction).
ALTER TABLE game_systems ADD COLUMN rules_markdown_en TEXT;
@@ -0,0 +1,2 @@
-- Le canal beta est libre : plus de licence Patreon, la table des licences ne sert plus.
DROP TABLE IF EXISTS licenses;
@@ -1,29 +0,0 @@
# Cle publique JWT du relais OAuth Patreon
Le fichier `jwt-public-key.pem` contient la **cle publique Ed25519** qui sert
a verifier la signature des JWT licence emis par le relais
(`loremind-auth.igmlcreation.fr`).
## Pourquoi ici ?
- C'est une **cle publique** : par nature non-secrete, elle peut etre committee
dans le repo public et embarquee dans le binaire distribue.
- Cela evite a chaque utilisateur final de devoir renseigner manuellement la
cle dans son `.env` au moment de l'installation.
- L'env `LICENSING_JWT_PUBLIC_KEY` peut surcharger cette valeur (utile pour
la rotation de cle sans rebuild ou pour les tests).
## Si le fichier est absent
La feature licensing est **desactivee silencieusement** : `LicenseService.isLicensingEnabled()`
renvoie `false`, et l'UI masque toute la section Patreon.
## Rotation de cle
1. Generer une nouvelle paire dans le relais : `npm run keys:generate`
2. Pousser la nouvelle cle privee : `wrangler secret put JWT_PRIVATE_KEY`
3. Remplacer `jwt-public-key.pem` ici avec la nouvelle cle publique
4. Rebuild + redeployer LoreMind (les anciens JWT seront refuses au prochain
refresh, l'utilisateur sera invite a reconnecter Patreon)
5. Optionnel : pendant la transition, supporter les deux cles en parallele
(pas implemente en MVP, peut etre ajoute si besoin operationnel)
@@ -1,3 +0,0 @@
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEArbfaqBq54HJR1pKqliTShKrNIab32gpBwSTDw90I4wg=
-----END PUBLIC KEY-----
@@ -0,0 +1,93 @@
/* Edition A4 : narration en colonnes, palette encre et sauge.
CSS pagine OpenHTMLtoPDF ; les tableaux detailles et cartes restent pleine largeur. */
@page {
@top-center { content: '__HEADER__'; font-family: 'DejaVu Sans', sans-serif; font-size: 7pt;
color: #34594f; letter-spacing: .12em; border-bottom: .5pt solid #b3bfb4; padding-bottom: 6pt; }
@bottom-center { content: counter(page); font-size: 9pt; color: #34594f; font-family: 'DejaVu Serif', serif; }
}
@page:first { @top-center { content: none; border: 0; } }
body { margin: 0; color: #292c29; line-height: 1.42; word-wrap: break-word; }
.editorial-flow { column-count: 2; column-gap: .8cm; }
.editorial-flow p, .editorial-flow .field, .editorial-flow .box { orphans: 3; widows: 3; }
.editorial-flow .prose { text-align: left; }
/* Un bloc en ligne est deplace entier par le moteur de colonnes. Les encadres longs
restent fluides, sans fond ni bordure susceptibles de deborder sur la colonne suivante. */
.editorial-flow .box, .editorial-flow .illus { display: inline-block; width: 100%; box-sizing: border-box; }
.editorial-flow .box.flow { display: block; background: none; border: 0; padding: .1cm 0; }
.editorial-flow .box.flow .box-label { border-top: 1pt solid #9a8351; padding-top: .12cm; }
.editorial-flow .arc-head, .editorial-flow .chapter-head, .editorial-flow .scene-head,
.editorial-flow .section-head { display: inline-block; width: 100%; box-sizing: border-box; }
.cover { padding-top: 3cm; }
.cover.has-art { padding-top: .3cm; }
.cover-title { font-family: 'DejaVu Serif', serif; font-size: 32pt; line-height: 1.12;
letter-spacing: -.03em; color: #193c34; }
.cover-kicker { color: #456656; font-size: 9pt; letter-spacing: .18em; }
.cover-subtitle { font-family: 'DejaVu Serif', serif; color: #545b50; font-style: italic; font-size: 13pt; }
.cover-rule { width: 5cm; border-bottom: 1.5pt solid #9a8351; }
.cover-art { margin: .35cm 0 .5cm; }
.cover-art img { border: 0; }
.cover-meta { color: #34594f; font-size: 9pt; }
.cover-author { color: #193c34; margin-top: .6cm; }
.cover-version { color: #67746a; }
@page illustrated-cover { size: A4; margin: 0;
@top-center { content: none; border: 0; }
@bottom-center { content: none; }
}
.cover-illustrated { page: illustrated-cover; position: relative; width: 21cm; height: 29.65cm;
padding: 0; margin: 0; overflow: hidden; background: #193c34; }
.cover-background { position: absolute; }
.cover-caption { position: absolute; bottom: 1.2cm; left: 1.3cm; right: 1.3cm;
background: #193c34; padding: .7cm .7cm .6cm; }
.cover-caption .cover-title { color: #fffdf4; }
.cover-caption .cover-kicker, .cover-caption .cover-meta, .cover-caption .cover-version { color: #d4dfce; }
.cover-caption .cover-subtitle, .cover-caption .cover-author { color: #fffdf4; }
.cover-caption .cover-rule { border-color: #c9b47e; }
.cover-caption .cover-edition { color: #e1ca8e; }
.credits-title, .credits-subtitle { color: #34594f; }
.legal { border-color: #b3bfb4; }
h1.part, h1.toc-title { font-family: 'DejaVu Serif', serif; font-size: 25pt; line-height: 1.15;
letter-spacing: -.02em; text-transform: none; color: #193c34; border-bottom: 1.5pt solid #9a8351;
padding-bottom: .22cm; margin-bottom: .5cm; }
.toc tr.lvl0 td { color: #193c34; border-bottom-color: #b3bfb4; }
.toc td { border-bottom-color: #d4d9d0; }
.arc { margin: 0 0 .4cm; }
.arc-head { background: none; padding: .12cm 0 .18cm; border-radius: 0;
border-top: 2pt solid #34594f; border-bottom: .5pt solid #9a8351;
color: #193c34; font-family: 'DejaVu Serif', serif; font-size: 19pt; line-height: 1.18; }
.chapter-head { background: none; border: 0; border-bottom: 1pt solid #b3bfb4;
padding: 0 0 .12cm; font-family: 'DejaVu Serif', serif; font-size: 15pt; line-height: 1.2; color: #34594f; }
.eyebrow, .eyebrow-light { color: #637767; font-size: 6.5pt; margin-bottom: .08cm; }
.scene { border: 0; border-radius: 0; background: none; padding: 0; margin: .4cm 0 .3cm; }
.scene-head { color: #193c34; font-size: 11pt; text-transform: uppercase; letter-spacing: .03em;
border-bottom: .5pt solid #b3bfb4; padding-bottom: .08cm; }
.scene-meta { color: #687365; font-size: 8.5pt; }
.room { background: none; border: 0;
padding: 0 0 0 .22cm; margin: .3cm 0; }
.room-head { color: #695a36; border-left: 1pt solid #9a8351; padding-left: .18cm; }
h2.section-head { font-family: 'DejaVu Serif', serif; font-size: 14pt; color: #34594f; border-bottom-color: #b3bfb4; }
h3.folder { color: #456656; border-bottom-color: #b3bfb4; }
.field { margin: .2cm 0; }
.field-label { color: #34594f; font-size: 7.5pt; letter-spacing: .02em; }
.box { padding: .25cm .3cm; margin: .25cm 0; border-radius: 0; }
.box-label { letter-spacing: .06em; }
.box ul { padding-left: .4cm; margin: .12cm 0; }
.readaloud { background: #edf1e7; border: .75pt solid #456656; font-style: normal; color: #234438; }
.readaloud .box-label { color: #34594f; }
.secret { background: #f5f1e7; border: 0; border-left: 2pt solid #9a8351; }
.secret .box-label { color: #79683e; }
.combat { background: #f8eeea; border-left-color: #9b5547; }
.card { background: #fafbf7; border-color: #c5cec1; border-radius: 0; }
.persona-name { font-family: 'DejaVu Serif', serif; color: #193c34; font-size: 14pt; }
.level, .illus .caption { color: #637767; }
.illus { margin: .35cm 0; }
.illus img { border: 0; border-radius: 0; }
.illus .caption { font-size: 7pt; letter-spacing: .04em; }
.tech-table { width: 100%; }
.stats-table thead th, .stat-array th { background: #e7ede2; color: #34594f; border-color: #b3bfb4; }
.stats-table tbody th { background: #f0f3eb; }
.stats-table tr.alt td { background: #f0f3eb; }
.stats-table td, .stats-table th, .stat-array td { border-color: #d4d9d0; }
.stats-table .roll-col, a.xref { color: #34594f; }
a.xref { border-bottom-color: #b3bfb4; }
a.pref:after, .annex-kind { color: #637767; }
.map-title { color: #193c34; }
@@ -0,0 +1,61 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** IA des méthodes guidées : questions validées, contexte de campagne transmis, réponses filtrées. */
@ExtendWith(MockitoExtension.class)
class GuidedAssistServiceTest {
@Mock private GuidedMethodAssistant assistant;
@Mock private CampaignContextFormatter contextFormatter;
@InjectMocks private GuidedAssistService service;
private static final Question TITLE = new Question("title", "Nom de l'enquête", "Ex. : L'héritage", "Le mystère", List.of());
private static final Question NATURE = new Question("node1.nature", "Genre de scène", null, "Première piste",
List.of(new Choice("location", "Un lieu"), new Choice("npc", "Une personne")));
@Test
void suggest_sendsCampaignContextAndExistingAnswers_andFiltersTheResult() {
when(contextFormatter.format("c1")).thenReturn("Campagne : Valfroide");
when(assistant.answer(eq("Enquête en nœuds"), any(), eq("Une tour se rallume"), eq("Campagne : Valfroide"),
anyList(), anyMap())).thenReturn(Map.of(
"title", " L'héritage empoisonné ",
"node1.nature", "dragon", // choix invalide -> écarté
"invented", "clé inventée", // clé non demandée -> écartée
"node1.name", ""));
Map<String, String> out = service.suggest("c1", "Enquête en nœuds", "Trois pistes",
"Une tour se rallume", List.of(TITLE, NATURE), Map.of("truth", " Le notaire ", "blank", " "));
assertEquals(Map.of("title", "L'héritage empoisonné"), out);
verify(assistant).answer(any(), any(), any(), any(), eq(List.of(TITLE, NATURE)), eq(Map.of("truth", "Le notaire")));
}
@Test
void suggest_keepsAValidChoice() {
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap())).thenReturn(Map.of("node1.nature", "npc"));
assertEquals(Map.of("node1.nature", "npc"), service.suggest("c1", "M", "", "", List.of(NATURE), null));
}
@Test
void suggest_withoutAnyValidQuestion_isRejected() {
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée", List.of(), Map.of()));
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée",
java.util.Arrays.asList(null, new Question(" ", "x", null, null, null)), Map.of()));
}
}
@@ -23,6 +23,9 @@ class GameSystemContextBuilderTest {
@Mock @Mock
private GameSystemRepository gameSystemRepository; private GameSystemRepository gameSystemRepository;
@Mock
private com.loremind.domain.shared.ports.CurrentLanguage currentLanguage;
@InjectMocks @InjectMocks
private GameSystemContextBuilder builder; private GameSystemContextBuilder builder;
@@ -71,4 +74,24 @@ class GameSystemContextBuilderTest {
assertEquals("Règles de combat.", sections.get("Combat")); assertEquals("Règles de combat.", sections.get("Combat"));
} }
@Test
void build_usesTheRulesOfTheInterfaceLanguage_withFallback() {
com.loremind.domain.gamesystemcontext.GameSystem gs = com.loremind.domain.gamesystemcontext.GameSystem.builder()
.id("gs").name("Nimble").rulesMarkdown("## Combat\nJet de d20").rulesMarkdownEn("## Fighting\nRoll a d20").build();
org.mockito.Mockito.when(gameSystemRepository.findById("gs")).thenReturn(java.util.Optional.of(gs));
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
.orElseThrow().toString().contains("Roll a d20"));
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("fr");
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
.orElseThrow().toString().contains("Jet de d20"));
gs.setRulesMarkdownEn(null); // pas de version anglaise : repli sur le français
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
.orElseThrow().toString().contains("Jet de d20"));
}
} }
@@ -347,4 +347,65 @@ class BrainRulesImportClientTest {
assertTrue(c.done.get().sections().isEmpty()); assertTrue(c.done.get().sections().isEmpty());
assertNull(c.error.get()); assertNull(c.error.get());
} }
@Test
void streaming_done_carriesBothLanguages() {
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"d20\"},\"page_count\":2,\"ocr_page_count\":0,"
+ "\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\"d20\"},"
+ "\"en\":{\"Fighting\":\"d20 roll\"}}}\n\n";
Collector c = new Collector();
ExchangeFunction ef = req -> Mono.just(
ClientResponse.create(HttpStatus.OK)
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
.body(sse)
.build());
client(ef).importRulesStreaming(
new byte[]{1}, "r.pdf",
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
c.done::set, c.error::set);
assertNotNull(c.done.get());
assertEquals("fr", c.done.get().sourceLanguage());
assertEquals(java.util.Map.of("Fighting", "d20 roll"), c.done.get().sectionsByLanguage().get("en"));
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
}
/**
* Livre entier en deux langues : l'évènement {@code done} dépasse largement les 256 Ko
* par défaut de WebClient. Vrai serveur HTTP local (une ExchangeFunction simulée ne
* passe pas par les codecs du client, donc ne verrait pas la limite).
*/
@Test
void streaming_acceptsAVeryLargeDoneEvent() throws Exception {
String big = "x".repeat(600_000);
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"" + big + "\"},\"page_count\":300,"
+ "\"ocr_page_count\":0,\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\""
+ big + "\"},\"en\":{\"Fighting\":\"" + big + "\"}}}\n\n";
byte[] payload = sse.getBytes(java.nio.charset.StandardCharsets.UTF_8);
com.sun.net.httpserver.HttpServer server =
com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/import/rules/stream", exchange -> {
exchange.getRequestBody().readAllBytes();
exchange.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE);
exchange.sendResponseHeaders(200, payload.length);
try (var out = exchange.getResponseBody()) {
out.write(payload);
}
});
server.start();
try {
String url = "http://127.0.0.1:" + server.getAddress().getPort();
BrainRulesImportClient real = new BrainRulesImportClient(restTemplate, WebClient.builder(), objectMapper,
url, 30, "/import/rules", "/import/rules/stream");
Collector c = new Collector();
real.importRulesStreaming(new byte[]{1}, "r.pdf",
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add, c.done::set, c.error::set);
assertNull(c.error.get());
assertNotNull(c.done.get());
assertEquals(600_000, c.done.get().sectionsByLanguage().get("en").get("Fighting").length());
} finally {
server.stop(0);
}
}
} }
@@ -0,0 +1,101 @@
package com.loremind.infrastructure.desktop;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.info.BuildProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestTemplate;
import java.util.Optional;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Mises a jour du bureau : la version stable suit {@code /releases/latest} ; une version
* beta (canal libre, publie en prerelease GitHub) suit la liste complete des releases.
*/
class DesktopUpdateServiceTest {
private static final String LATEST = "https://api.github.com/repos/IGMLcreation/LoreMind/releases/latest";
private static final String ALL = "https://api.github.com/repos/IGMLcreation/LoreMind/releases?per_page=30";
private static final ObjectMapper JSON = new ObjectMapper();
private static DesktopUpdateService service(String currentVersion, RestTemplate http) {
Properties p = new Properties();
p.setProperty("version", currentVersion);
DesktopUpdateService svc = new DesktopUpdateService(new RestTemplateBuilder(), true, LATEST, new BuildProperties(p));
ReflectionTestUtils.setField(svc, "http", http);
return svc;
}
private static void reply(RestTemplate http, String url, String json) throws Exception {
JsonNode body = JSON.readTree(json);
when(http.exchange(eq(url), eq(HttpMethod.GET), any(), eq(JsonNode.class)))
.thenReturn(ResponseEntity.ok(body));
}
@Test
void stableVersion_followsTheLatestStableRelease() throws Exception {
RestTemplate http = mock(RestTemplate.class);
reply(http, LATEST, "{\"tag_name\":\"v1.6.0\",\"html_url\":\"https://x/1.6.0\"}");
Optional<DesktopUpdateService.UpdateInfo> info = service("1.5.0", http).checkForUpdate();
assertTrue(info.isPresent());
assertEquals("1.6.0", info.get().latestVersion());
}
@Test
void betaVersion_isToldAboutTheNextBeta() throws Exception {
RestTemplate http = mock(RestTemplate.class);
reply(http, ALL, "[{\"tag_name\":\"v1.5.0-beta.2\",\"prerelease\":true,\"html_url\":\"https://x/b2\"},"
+ "{\"tag_name\":\"v1.6.0-beta\",\"draft\":true},"
+ "{\"tag_name\":\"v1.4.0\",\"html_url\":\"https://x/1.4.0\"}]");
Optional<DesktopUpdateService.UpdateInfo> info = service("1.5.0-beta", http).checkForUpdate();
assertTrue(info.isPresent(), "beta.2 > beta ; le brouillon 1.6.0-beta est ignore");
assertEquals("1.5.0-beta.2", info.get().latestVersion());
assertEquals("https://x/b2", info.get().releaseUrl());
}
@Test
void betaVersion_isToldWhenTheStableReleaseReplacesIt() throws Exception {
RestTemplate http = mock(RestTemplate.class);
reply(http, ALL, "[{\"tag_name\":\"v1.5.0\",\"html_url\":\"https://x/1.5.0\"},"
+ "{\"tag_name\":\"v1.5.0-beta\",\"prerelease\":true}]");
Optional<DesktopUpdateService.UpdateInfo> info = service("1.5.0-beta", http).checkForUpdate();
assertTrue(info.isPresent());
assertEquals("1.5.0", info.get().latestVersion());
}
@Test
void betaVersion_upToDate() throws Exception {
RestTemplate http = mock(RestTemplate.class);
reply(http, ALL, "[{\"tag_name\":\"v1.5.0-beta\",\"prerelease\":true},{\"tag_name\":\"v1.4.0\"}]");
assertFalse(service("1.5.0-beta", http).checkForUpdate().isPresent());
}
@Test
void compareVersions_ordersStableAfterBetaAndBetasByNumber() {
assertTrue(DesktopUpdateService.compareVersions("1.5.0-beta", "1.5.0") < 0);
assertTrue(DesktopUpdateService.compareVersions("1.5.0-beta", "1.5.0-beta.2") < 0);
assertTrue(DesktopUpdateService.compareVersions("1.5.0-beta.2", "1.5.0-beta.10") < 0);
assertTrue(DesktopUpdateService.compareVersions("1.6.0-beta", "1.5.0") > 0);
assertEquals(0, DesktopUpdateService.compareVersions("1.5.0", "1.5.0"));
}
}
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.condition.OS;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Base64; import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -70,6 +71,37 @@ class WindowsHostNetworkAccessTest {
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("SecurityCenter2")); assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("SecurityCenter2"));
} }
@Test
void command_passesTheScriptInClear_withoutAntivirusRedFlags() {
String script = WindowsHostNetworkAccess.inspectScript("C:\\Users\\Jérôme\\DM Loremind.exe");
List<String> cmd = WindowsHostNetworkAccess.command(script);
assertEquals(List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script), cmd);
assertFalse(String.join(" ", cmd).contains("EncodedCommand"), "script lisible, pas encodé");
assertFalse(String.join(" ", cmd).contains("Bypass"), "la politique d'exécution ne concerne que les .ps1");
assertTrue(script.contains("'C:\\Users\\Jérôme\\DM Loremind.exe'"), "accents gardés tels quels (ligne de commande UTF-16)");
}
@Test
void command_refusesMultilineOrDoubleQuotedScripts() {
assertThrows(IllegalArgumentException.class, () -> WindowsHostNetworkAccess.command("a\nb"));
assertThrows(IllegalArgumentException.class, () -> WindowsHostNetworkAccess.command("Write-Host \"x\""));
}
@Test
void elevation_runsTheAllowScriptAsAdmin_inOneLine() {
String path = "C:\\Users\\l'MJ\\DM Loremind.exe";
String elevation = WindowsHostNetworkAccess.elevationScript(path);
WindowsHostNetworkAccess.command(elevation); // une ligne, sans guillemet double
assertTrue(elevation.contains("-Verb RunAs"));
assertFalse(elevation.contains("Bypass"));
assertTrue(elevation.contains("catch { exit 1223 }"), "refus de l'UAC = annulation");
String encoded = elevation.replaceAll(".*'-EncodedCommand','([^']+)'.*", "$1");
assertEquals(WindowsHostNetworkAccess.allowScript(path),
new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_16LE));
}
@Test @Test
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() { void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
String encoded = WindowsHostNetworkAccess.encode("é"); String encoded = WindowsHostNetworkAccess.encode("é");
@@ -0,0 +1,101 @@
package com.loremind.infrastructure.persistence.postgres;
import com.loremind.application.campaigncontext.CampaignContentSearchService;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.infrastructure.web.controller.CampaignContentSearchController;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** Isolated SQL/API tests: never connects to the user's database. */
class PostgresCampaignContentSearchRepositoryTest {
private EmbeddedDatabase database;
private JdbcTemplate jdbc;
private CampaignContentSearchService service;
@BeforeEach
void setup() {
database = new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.H2).build();
jdbc = new JdbcTemplate(database);
jdbc.execute("SET MODE PostgreSQL");
jdbc.execute("CREATE TABLE campaigns (id BIGINT PRIMARY KEY, name VARCHAR NOT NULL)");
jdbc.execute("CREATE TABLE arcs (id BIGINT PRIMARY KEY, name VARCHAR, campaign_id BIGINT, type VARCHAR)");
jdbc.execute("CREATE TABLE chapters (id BIGINT PRIMARY KEY, name VARCHAR, arc_id BIGINT)");
jdbc.execute("CREATE TABLE scenes (id BIGINT PRIMARY KEY, name VARCHAR, chapter_id BIGINT)");
jdbc.execute("CREATE TABLE quests (id BIGINT PRIMARY KEY, name VARCHAR, campaign_id BIGINT, arc_id BIGINT)");
jdbc.update("INSERT INTO campaigns VALUES (1, 'Les Ombres'), (2, 'Autre campagne')");
jdbc.update("INSERT INTO arcs VALUES (10, 'Port sombre', 1, 'LINEAR'), (11, 'Technique', 1, 'SYSTEM')");
jdbc.update("INSERT INTO chapters VALUES (20, 'Nuit sombre', 10), (21, 'Le témoin', 11)");
jdbc.update("INSERT INTO scenes VALUES (30, 'Taverne sombre', 20), (31, 'Rencontre sombre', 21)");
jdbc.update("INSERT INTO quests VALUES (40, 'Secret sombre', 1, NULL), (41, 'Secret sombre', 2, NULL)");
service = new CampaignContentSearchService(new PostgresCampaignContentSearchRepository(new NamedParameterJdbcTemplate(database)));
}
@AfterEach
void cleanup() { database.shutdown(); }
@Test
void findsEveryKindWithCorrectAncestorsAndCampaignNames() {
List<CampaignContentHit> hits = service.search(" SOMBRE ");
assertEquals(6, hits.size());
assertEquals(4, hits.stream().map(CampaignContentHit::kind).distinct().count());
CampaignContentHit scene = hits.stream().filter(h -> h.id().equals("30")).findFirst().orElseThrow();
assertEquals("1", scene.campaignId());
assertEquals("Les Ombres", scene.campaignName());
assertEquals("10", scene.arcId());
assertEquals("20", scene.chapterId());
assertEquals("Nuit sombre", scene.chapterName());
assertTrue(hits.stream().anyMatch(h -> h.id().equals("41") && h.campaignName().equals("Autre campagne")));
}
@Test
void hidesSystemContainersButKeepsTheirScenesNavigable() {
assertTrue(service.search("Technique").isEmpty());
assertTrue(service.search("témoin").isEmpty());
CampaignContentHit hit = service.search("Rencontre").get(0);
assertEquals("11", hit.arcId());
assertNull(hit.arcName());
assertEquals("21", hit.chapterId());
}
@Test
void treatsSqlWildcardsAndQuotesAsLiteralUserText() {
jdbc.update("INSERT INTO scenes VALUES (32, ?, 20)", "100%_! d'ombre");
assertEquals(1, service.search("%_").size());
assertEquals(1, service.search("_!").size());
assertEquals(1, service.search("d'ombre").size());
assertTrue(service.search("' OR 1=1 --").isEmpty());
assertTrue(service.search(" ").isEmpty());
assertTrue(service.search("s").isEmpty());
assertTrue(service.search(null).isEmpty());
}
@Test
void excludesOrphansAndBoundsResults() {
jdbc.update("INSERT INTO scenes VALUES (33, 'Orpheline', 999)");
assertTrue(service.search("Orpheline").isEmpty());
for (int i = 100; i < 200; i++) jdbc.update("INSERT INTO quests VALUES (?, ?, 1, NULL)", i, "Recherche " + i);
assertEquals(80, service.search("Recherche").size());
}
@Test
void exposesSearchProjectionAtTheFrontendEndpoint() throws Exception {
MockMvcBuilders.standaloneSetup(new CampaignContentSearchController(service)).build()
.perform(get("/api/campaigns/search-content").param("q", "Taverne"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].kind").value("scene"))
.andExpect(jsonPath("$[0].chapterId").value("20"))
.andExpect(jsonPath("$[0].campaignName").value("Les Ombres"));
}
}
@@ -0,0 +1,119 @@
package com.loremind.infrastructure.transfer.pdf;
import com.loremind.infrastructure.persistence.entity.*;
import com.loremind.infrastructure.persistence.jpa.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/** Verifie le PDF rendu, sans Spring ni connexion a une base de donnees. */
class PdfEditorialLayoutTest {
private static final String PROSE = "Le chemin traverse la foret et rejoint les portes du village. "
+ "Les voyageurs observent les traces sur le sol et interrogent les gardiens. ";
private PdfExportService service(List<SceneJpaEntity> scenes) {
var campaign = CampaignJpaEntity.builder().id(1L).name("Le chemin des brumes").build();
var campaigns = mock(CampaignJpaRepository.class);
when(campaigns.findById(1L)).thenReturn(Optional.of(campaign));
var st = new Structure();
st.visibleArcs = List.of(ArcJpaEntity.builder().id(2L).name("Arc").build());
st.chaptersByArc.put(2L, List.of(ChapterJpaEntity.builder().id(3L).name("Chapitre").build()));
st.scenesByChapter.put(3L, scenes);
var loader = mock(PdfStructureLoader.class);
when(loader.load(campaign)).thenReturn(st);
return new PdfExportService(campaigns, mock(NpcJpaRepository.class), mock(EnemyJpaRepository.class),
mock(RandomTableJpaRepository.class), mock(GameSystemJpaRepository.class),
mock(LoreNodeJpaRepository.class), mock(PageJpaRepository.class), mock(TemplateJpaRepository.class),
loader, mock(PdfImageEncoder.class));
}
@Test
void longNarrationFlowsThroughBothColumnsWithoutLostOrDuplicatedParagraphs() throws Exception {
String text = IntStream.range(0, 45).mapToObj(i -> "Repere%03d ".formatted(i) + PROSE.repeat(3))
.reduce((a, b) -> a + "\n\n" + b).orElseThrow();
var service = service(List.of(SceneJpaEntity.builder().id(4L).name("La route")
.playerNarration(text).gmSecretNotes("CONFIDENTIEL").build()));
try (var pdf = PDDocument.load(service.export("1"))) {
var reader = new Positions();
String extracted = reader.getText(pdf);
for (int i = 0; i < 45; i++) assertEquals(1, count(extracted, "Repere%03d".formatted(i)));
var markers = reader.lines.stream().filter(l -> l.text.startsWith("Repere")).toList();
assertTrue(markers.stream().anyMatch(l -> l.x < 150));
assertTrue(markers.stream().anyMatch(l -> l.x > 300));
assertTrue(pdf.getNumberOfPages() > 3);
assertBounds(reader, pdf);
}
}
@Test
void shortReadAloudBoxesStayTogetherAtColumnAndPageBreaks() throws Exception {
List<SceneJpaEntity> scenes = IntStream.range(0, 14).mapToObj(i -> SceneJpaEntity.builder()
.id((long) i + 4).name("Etape " + i)
.playerNarration("Debut%02d ".formatted(i) + PROSE.repeat(4) + " Fin%02d".formatted(i)).build()).toList();
try (var pdf = PDDocument.load(service(scenes).export("1"))) {
var reader = new Positions();
reader.getText(pdf);
for (int i = 0; i < 14; i++) {
String start = "Debut%02d".formatted(i), end = "Fin%02d".formatted(i);
Line first = reader.lines.stream().filter(l -> l.text.contains(start)).findFirst().orElseThrow();
Line last = reader.lines.stream().filter(l -> l.text.contains(end)).findFirst().orElseThrow();
assertEquals(first.page, last.page, "Encadre coupe entre deux pages");
assertEquals(first.x < 300, last.x < 300, "Encadre coupe entre deux colonnes");
}
assertBounds(reader, pdf);
}
}
@Test
void playerEditionStillOmitsSecretsAndSmallFormatKeepsOneColumn() throws Exception {
var service = service(List.of(SceneJpaEntity.builder().id(4L).name("La route")
.playerNarration(PROSE.repeat(8)).gmSecretNotes("CONFIDENTIEL").build()));
for (String format : List.of("A4", "A5", "LETTER")) {
var options = PdfExportOptions.parse("player", format, true, "NARRATIVE", null);
try (var pdf = PDDocument.load(service.export("1", options))) {
String text = new PDFTextStripper().getText(pdf);
assertFalse(text.contains("CONFIDENTIEL"));
assertTrue(text.contains("voyageurs"));
assertEquals(format.equals("A4"), service.xhtml("1", options).contains("<div class=\"editorial-flow\">"));
}
}
}
private static int count(String text, String needle) {
return (text.length() - text.replace(needle, "").length()) / needle.length();
}
private static void assertBounds(Positions reader, PDDocument pdf) {
for (Line line : reader.lines) {
var bounds = pdf.getPage(line.page - 1).getMediaBox();
assertTrue(line.x >= 0 && line.right <= bounds.getWidth() + 1, line.toString());
assertTrue(line.y >= 0 && line.y <= bounds.getHeight(), line.toString());
}
}
private record Line(String text, int page, float x, float right, float y) {}
private static class Positions extends PDFTextStripper {
final List<Line> lines = new ArrayList<>();
Positions() throws IOException { super(); }
@Override
protected void writeString(String text, List<TextPosition> positions) throws IOException {
if (!positions.isEmpty()) {
TextPosition first = positions.get(0), last = positions.get(positions.size() - 1);
lines.add(new Line(text, getCurrentPageNo(), first.getXDirAdj(),
last.getXDirAdj() + last.getWidthDirAdj(), first.getYDirAdj()));
}
super.writeString(text, positions);
}
}
}
@@ -0,0 +1,49 @@
package com.loremind.infrastructure.transfer.pdf;
import com.loremind.infrastructure.persistence.entity.*;
import com.loremind.infrastructure.persistence.jpa.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.*;
/**
* Mode plat du livret : un seul arc d'un seul chapitre n'est présenté « à plat » que si
* ces deux conteneurs sont vides. Un chapitre écrit (méthode guidée…) garde ses en-têtes.
*/
@SpringBootTest
@Transactional
class PdfExportFlatModeTest {
@Autowired private PdfExportService service;
@Autowired private CampaignJpaRepository campaignRepo;
@Autowired private ArcJpaRepository arcRepo;
@Autowired private ChapterJpaRepository chapterRepo;
@Autowired private SceneJpaRepository sceneRepo;
private String campaign(String chapterGmNotes) {
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("C").arcsCount(1).build());
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Arc principal").campaignId(camp.getId()).order(0).build());
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("L'héritage empoisonné")
.arcId(arc.getId()).order(0).gmNotes(chapterGmNotes).build());
sceneRepo.save(SceneJpaEntity.builder().name("L'arrestation").chapterId(ch.getId()).order(0).build());
return String.valueOf(camp.getId());
}
@Test
void bareArcAndChapter_areFlattened() {
String x = service.xhtml(campaign(null), PdfExportOptions.defaults());
assertTrue(x.contains("id=\"part-narrative\">Scènes</h1>"));
assertFalse(x.contains("L'héritage empoisonné</div>"), "en-tête de chapitre masqué");
}
@Test
void writtenChapter_keepsItsHeaders() {
String x = service.xhtml(campaign("Le notaire est coupable."), PdfExportOptions.defaults());
assertTrue(x.contains("id=\"part-narrative\">Structure narrative</h1>"));
assertTrue(x.contains("L'héritage empoisonné"), "le chapitre de la méthode guidée reste visible");
assertTrue(x.contains("Le notaire est coupable."));
}
}
@@ -402,6 +402,9 @@ class PdfExportPreviewTest {
Path outPlayer = Path.of("target", "campaign-preview-joueurs-a5.pdf"); Path outPlayer = Path.of("target", "campaign-preview-joueurs-a5.pdf");
Files.write(outPlayer, player); Files.write(outPlayer, player);
System.out.println("[preview] PDF écrit : " + outPlayer.toAbsolutePath()); System.out.println("[preview] PDF écrit : " + outPlayer.toAbsolutePath());
Files.write(Path.of("target", "campaign-preview-impression-a4.pdf"),
service.export("1", PdfExportOptions.parse("gm", "A4", true, null, null)));
} }
/** Image placeholder deterministe : portrait carre ou battlemap avec grille. */ /** Image placeholder deterministe : portrait carre ou battlemap avec grille. */
@@ -11,14 +11,18 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -146,17 +150,29 @@ class PdfExportPublicationTest {
assertFalse(x.contains("Structure de l'aventure")); assertFalse(x.contains("Structure de l'aventure"));
} }
@Test @ParameterizedTest
void formatAndPrintMode_shapeTheStylesheet() { @EnumSource(PageFormat.class)
String a5 = service.xhtml(campaignId, new PdfExportOptions(true, PageFormat.A5, true, void formatAndPrintMode_shapeTheStylesheet(PageFormat format) throws Exception {
EnumSet.allOf(Section.class), LoreScope.ALL)); String printCss;
assertTrue(a5.contains("size: A5")); try (var in = PdfExportService.class.getResourceAsStream("/pdf/export-print.css")) {
assertTrue(a5.contains("font-size: 9.0pt")); assertNotNull(in, "feuille impression disponible");
assertTrue(a5.contains(".arc-head { background: none"), "feuille impression ajoutée"); printCss = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
String a4 = service.xhtml(campaignId, PdfExportOptions.defaults()); for (boolean print : new boolean[]{false, true}) {
assertTrue(a4.contains("size: A4")); String x = service.xhtml(campaignId, new PdfExportOptions(true, format, print,
assertFalse(a4.contains(".arc-head { background: none")); EnumSet.allOf(Section.class), LoreScope.ALL));
String css = x.substring(x.indexOf("<style>") + "<style>".length(), x.indexOf("</style>"));
assertTrue(css.contains("size: " + format.cssSize + ";"), "format " + format);
assertTrue(css.contains(String.format(Locale.ROOT, "font-size: %.1fpt", format.bodyPt)),
"corps du texte pour " + format);
// Le style A4 couleur peut aussi avoir des titres sans fond. Verifier la feuille
// complete et son ordre de cascade, plutot qu'une declaration CSS partagee.
if (print) {
assertTrue(css.endsWith(printCss), "surcharges impression appliquees en dernier : " + format);
} else {
assertFalse(css.contains(printCss), "aucune feuille impression en couleur : " + format);
}
}
} }
@Test @Test
@@ -0,0 +1,28 @@
package com.loremind.infrastructure.updates;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LegacyRegistryCredentialsCleanupTest {
@Test
void removesTheOldGhcrCredentials(@TempDir Path dir) throws Exception {
Path config = dir.resolve("config.json");
Files.writeString(config, "{\"auths\":{\"ghcr.io\":{\"auth\":\"dXNlcjpwYXQ=\"}}}");
assertTrue(new LegacyRegistryCredentialsCleanup(config.toString()).cleanup());
assertFalse(Files.exists(config));
}
@Test
void doesNothingOnRecentInstalls(@TempDir Path dir) {
assertFalse(new LegacyRegistryCredentialsCleanup("").cleanup());
assertFalse(new LegacyRegistryCredentialsCleanup(dir.resolve("config.json").toString()).cleanup());
}
}

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