feat(treblo): validation durcie, usage unique, 5 outils, code 6 chiffres et tests (ticket nyora-2026-10-216-c)

This commit is contained in:
bolbol committed 2026-11-02 12:02:35 +01:00
1 parent 1d6c3a157d
commit a4cbda385c
4 files changed
+490 -31

No files matched your search

+167 -25
View File
@@ -3,6 +3,7 @@ import os
import json
import hmac
import uuid
import secrets
import logging
import hashlib
import datetime
@@ -46,6 +47,14 @@ def get_validations_path() -> str:
return local
return path
def get_envois_path() -> str:
path = "/app/data/envois.jsonl"
if not os.path.exists(os.path.dirname(path)):
local = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "envois.jsonl")
os.makedirs(os.path.dirname(local), exist_ok=True)
return local
return path
def get_musique_dir(sphere: str) -> str:
path = f"/app/musique/{sphere}"
if not os.path.exists("/app/musique"):
@@ -76,10 +85,17 @@ def get_bot_token(sphere: str) -> str:
def validate_sphere_access(requested_sphere: str) -> str:
req = requested_sphere.lower().strip()
auth = current_sphere_var.get()
if req != auth:
if auth and req != auth:
raise ValueError(f"Refus explicite : le jeton de la sphère {auth} ne peut pas agir sur la sphère {req}")
return req
def compute_empreinte(sphere: str, tags: Optional[List[str]], prompt: Optional[str], paroles: Optional[str]) -> str:
s_tags = sorted([str(t).strip() for t in (tags or []) if str(t).strip()])
p_prompt = (str(prompt).strip() if prompt else "")
p_paroles = (str(paroles).strip() if paroles else "")
canonical = f"{sphere.lower().strip()}|{','.join(s_tags)}|{p_prompt}|{p_paroles}"
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def treblo_balance(sphere: str) -> Dict[str, Any]:
key = get_api_key(sphere)
req = urllib.request.Request("https://api.treblo.com/v1/credits/balance", headers={"Authorization": f"Bearer {key}"})
@@ -156,6 +172,50 @@ def get_journal_entry(task_id: str) -> Optional[Dict[str, Any]]:
pass
return None
def log_envoi(task_id: str, sphere: str, message_id: int):
path = get_envois_path()
entry = {
"type": "apercu_mp3",
"task_id": task_id,
"sphere": sphere,
"message_id": int(message_id),
"date": datetime.datetime.now(datetime.timezone.utc).isoformat()
}
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
def consume_approved_validation(sphere: str, empreinte: str, val_id: Optional[str] = None) -> bool:
v_path = get_validations_path()
if not os.path.exists(v_path):
return False
try:
with open(v_path, "r", encoding="utf-8") as f:
data = json.load(f)
now_dt = datetime.datetime.now(TUNIS_TZ)
updated = False
consumed = False
for item in data.get("validations", []):
if item.get("sphere") == sphere and item.get("status") == "APPROVED":
match = (val_id and item.get("id") == val_id) or (not val_id and item.get("empreinte") == empreinte)
if match:
exp = datetime.datetime.fromisoformat(item.get("expires_at"))
if exp > now_dt:
item["status"] = "USED"
item["used_at"] = now_dt.isoformat()
consumed = True
updated = True
break
else:
item["status"] = "EXPIRED"
updated = True
if updated:
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
return consumed
except Exception as e:
logger.warning("Erreur lecture validations.json: %s", e)
return False
def is_validation_approved(sphere: str, empreinte: str, val_id: Optional[str] = None) -> bool:
v_path = get_validations_path()
if not os.path.exists(v_path):
@@ -166,19 +226,16 @@ def is_validation_approved(sphere: str, empreinte: str, val_id: Optional[str] =
now_dt = datetime.datetime.now(TUNIS_TZ)
for item in data.get("validations", []):
if item.get("sphere") == sphere and item.get("status") == "APPROVED":
if val_id and item.get("id") == val_id:
match = (val_id and item.get("id") == val_id) or (not val_id and item.get("empreinte") == empreinte)
if match:
exp = datetime.datetime.fromisoformat(item.get("expires_at"))
if exp > now_dt:
return True
elif item.get("empreinte") == empreinte:
exp = datetime.datetime.fromisoformat(item.get("expires_at"))
if exp > now_dt:
return True
except Exception as e:
logger.warning("Erreur lecture validations.json: %s", e)
except Exception:
pass
return False
def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_iso: str, details: dict):
def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_iso: str = "", details: dict = None, code: Optional[str] = None):
v_path = get_validations_path()
data = {"validations": []}
if os.path.exists(v_path):
@@ -188,20 +245,25 @@ def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_
except Exception:
data = {"validations": []}
if not code:
code = f"{secrets.randbelow(1000000):06d}"
data.setdefault("validations", []).append({
"id": val_id,
"sphere": sphere,
"empreinte": empreinte,
"code": code,
"status": "PENDING",
"attempts": 0,
"created_at": datetime.datetime.now(TUNIS_TZ).isoformat(),
"expires_at": expires_iso,
"details": details
"details": details or {}
})
data["validations"] = data["validations"][-50:]
with open(v_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def send_telegram_validation_request(sphere: str, val_id: str, tags: list, prompt: str, paroles: str, expires_str: str):
def send_telegram_validation_request(sphere: str, val_id: str, code: str, tags: list, prompt: str, paroles: str, expires_str: str):
bot_token = get_bot_token(sphere)
chat_id = os.environ.get("TELEGRAM_CHAT_ID", "2084513684").strip()
if not bot_token or not chat_id:
@@ -218,8 +280,9 @@ def send_telegram_validation_request(sphere: str, val_id: str, tags: list, promp
f"• Tags : {tags_str}\n"
f"• Prompt : {prompt_str}\n"
f"• Paroles : {paroles_str}\n"
f"• Réf : #{val_id}\n\n"
f"Répondre OUI pour valider ou NON pour refuser (expiration : {expires_str})"
f"• Réf : #{val_id}\n"
f"• Code : {code}\n\n"
f"Transmettre ce code à l'assistant pour autoriser la génération (expiration : {expires_str})"
)
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
@@ -233,11 +296,11 @@ def send_telegram_validation_request(sphere: str, val_id: str, tags: list, promp
except Exception as e:
logger.warning("Échec envoi notification Telegram: %s", e)
def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str):
def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str) -> Optional[int]:
bot_token = get_bot_token(sphere)
chat_id = os.environ.get("TELEGRAM_CHAT_ID", "2084513684").strip()
if not bot_token or not chat_id or not os.path.exists(mp3_path):
return
return None
boundary = f"----TrebloBoundary{uuid.uuid4().hex}"
with open(mp3_path, "rb") as f:
@@ -259,9 +322,14 @@ def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str):
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.loads(resp.read().decode("utf-8"))
if data.get("ok"):
logger.info("Aperçu MP3 envoyé à Telegram (message_id=%s)", data.get("result", {}).get("message_id"))
msg_id = data.get("result", {}).get("message_id")
logger.info("Aperçu MP3 envoyé à Telegram (message_id=%s)", msg_id)
if isinstance(msg_id, int):
log_envoi(task_id, sphere, msg_id)
return msg_id
except Exception as e:
logger.warning("Échec envoi aperçu MP3 Telegram: %s", e)
return None
@mcp.tool()
def solde(sphere: str) -> dict:
@@ -269,6 +337,77 @@ def solde(sphere: str) -> dict:
sp = validate_sphere_access(sphere)
return treblo_balance(sp)
@mcp.tool()
def valider(val_id: str, code: str) -> dict:
"""Valide une demande d'approbation préalable à la génération musicale à l'aide du code à 6 chiffres transmis à Nabil.
Approuve seulement si le code est exact, la demande non expirée (15 minutes) et non utilisée (3 essais max par demande)."""
val_id_clean = str(val_id).strip().lstrip("#")
code_input = str(code).strip()
v_path = get_validations_path()
if not os.path.exists(v_path):
raise ValueError("Aucune demande de validation trouvée")
with open(v_path, "r", encoding="utf-8") as f:
data = json.load(f)
target = None
for item in data.get("validations", []):
if item.get("id") == val_id_clean:
target = item
break
if not target:
raise ValueError(f"Demande de validation #{val_id_clean} introuvable")
st = target.get("status", "PENDING")
if st == "USED":
raise ValueError(f"Demande #{val_id_clean} déjà utilisée (consommée)")
if st in ("CANCELLED", "REJECTED"):
raise ValueError(f"Demande #{val_id_clean} déjà annulée ou rejetée")
if st == "EXPIRED":
raise ValueError(f"Demande #{val_id_clean} expirée")
now_dt = datetime.datetime.now(TUNIS_TZ)
exp = datetime.datetime.fromisoformat(target.get("expires_at"))
if now_dt >= exp:
target["status"] = "EXPIRED"
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Demande #{val_id_clean} expirée (délai de 15 minutes dépassé)")
attempts = target.get("attempts", 0)
if attempts >= 3:
target["status"] = "CANCELLED"
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Limite de 3 essais atteinte : la demande #{val_id_clean} est annulée.")
stored_code = str(target.get("code", "")).strip()
if not hmac.compare_digest(code_input, stored_code):
attempts += 1
target["attempts"] = attempts
if attempts >= 3:
target["status"] = "CANCELLED"
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Code incorrect. Limite de 3 essais atteinte : la demande #{val_id_clean} est annulée.")
else:
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Code incorrect pour la demande #{val_id_clean} ({3 - attempts} essai(s) restant(s)).")
target["status"] = "APPROVED"
target["approved_at"] = now_dt.isoformat()
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
return {
"status": "APPROVED",
"val_id": val_id_clean,
"sphere": target.get("sphere"),
"message": f"Demande #{val_id_clean} approuvée avec succès. Vous pouvez maintenant appeler generer."
}
@mcp.tool()
def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str] = None, prompt: Optional[str] = None, validation_id: Optional[str] = None) -> dict:
"""Lance une génération musicale auprès de Treblo.
@@ -294,12 +433,13 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
if not has_tags and not has_prompt:
raise ValueError("Refus : un prompt ou des étiquettes (tags) doivent être fournis")
txt = str(prompt) if has_prompt else (str(paroles) if has_paroles else "")
empreinte = hashlib.sha256(txt.encode("utf-8")).hexdigest()
empreinte = compute_empreinte(sp, tag_list, prompt, paroles)
# Contrôle de la validation humaine obligatoire (T2)
if not is_validation_approved(sp, empreinte, validation_id):
# Contrôle de la validation humaine obligatoire (usage unique)
clean_val_id = str(validation_id).strip().lstrip("#") if validation_id else None
if not consume_approved_validation(sp, empreinte, clean_val_id):
val_id = uuid.uuid4().hex[:8]
code = f"{secrets.randbelow(1000000):06d}"
now_tunis = datetime.datetime.now(TUNIS_TZ)
exp_dt = now_tunis + datetime.timedelta(minutes=15)
expires_iso = exp_dt.isoformat()
@@ -308,6 +448,7 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
send_telegram_validation_request(
sphere=sp,
val_id=val_id,
code=code,
tags=tag_list or [],
prompt=prompt or "",
paroles=paroles or "",
@@ -317,13 +458,14 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
sphere=sp,
val_id=val_id,
empreinte=empreinte,
code=code,
expires_iso=expires_iso,
details={"tags": tag_list or [], "prompt": prompt or "", "paroles": paroles or ""}
)
raise ValueError(
f"Refus : validation humaine requise par Telegram (demande non validée ou étiquette invalide). "
f"Refus : validation humaine requise par Telegram (demande non validée ou code non saisi). "
f"Une demande d'approbation #{val_id} a été envoyée à Nabil sur Telegram pour la sphère {sp} (expiration à {expires_str}). "
f"Tant que Nabil n'a pas validé, la génération est refusée sans débit."
f"Veuillez demander le code de validation à Nabil et utiliser l'outil valider(val_id='{val_id}', code=...) avant de relancer generer."
)
bal_avant = treblo_balance(sp)
@@ -537,7 +679,7 @@ def recuperer(task_id: str, sphere: str) -> dict:
with open(json_meta_path, "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2, ensure_ascii=False)
# Relecture du solde réel après fin de tâche (T4)
# Relecture du solde réel après fin de tâche
credits_real = None
try:
bal = treblo_balance(sp)
@@ -547,7 +689,7 @@ def recuperer(task_id: str, sphere: str) -> dict:
update_journal_task(task_id, "SUCCESS", credits_apres=credits_real)
# Envoi de l'aperçu MP3 à Telegram (T3)
# Envoi de l'aperçu MP3 à Telegram et traçage dans envois.jsonl
if os.path.exists(mp3_file):
send_telegram_preview_mp3(sp, mp3_file, task_id)
@@ -598,7 +740,7 @@ class AuthAndSessionMiddleware(BaseHTTPMiddleware):
current_sphere_var.reset(token_cv)
async def health(request):
return JSONResponse({"status": "ok", "service": "treblo-mcp", "tools": 4})
return JSONResponse({"status": "ok", "service": "treblo-mcp", "tools": 5})
@asynccontextmanager
async def lifespan(app_instance):