feat(quant): Dynamic Cryptographic Invite Tokens & Unified Dual-Persona Privacy Firewall (Options 2 & 3)

This commit is contained in:
2026-10-23 07:00:43 +06:00
parent 49c0d7457b
commit e90f29929c
6 changed files with 334 additions and 31 deletions
+171
View File
@@ -0,0 +1,171 @@
import os
import json
import secrets
import logging
from datetime import datetime, timezone, timedelta
from typing import Dict, Any, List, Optional
from pydantic import BaseModel
logger = logging.getLogger("AuraTrade.DynamicTokenVault")
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR = os.path.join(BASE_DIR, "data")
TOKENS_FILE = os.path.join(DATA_DIR, "dynamic_invite_tokens.json")
class InviteTokenRecord(BaseModel):
token: str
link: str
creator_id: str
role: str = "EXPERT_ADVISOR"
created_at: str
expires_at: str
max_uses: int = 1
used_count: int = 0
status: str = "ACTIVE" # ACTIVE, EXPIRED, REVOKED, EXHAUSTED
used_by: List[Dict[str, Any]] = []
class DynamicTokenVault:
"""
Zero-Hardcoding Dynamic Cryptographic Token Vault.
Generates time-bound (24h default), single-use or multi-use invitation tokens,
tracks audit trails, and supports instant 1-click revocation.
"""
def __init__(self):
os.makedirs(DATA_DIR, exist_ok=True)
if not os.path.exists(TOKENS_FILE):
self._save([])
def _load(self) -> List[Dict[str, Any]]:
try:
with open(TOKENS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.error(f"Error loading dynamic tokens: {e}")
return []
def _save(self, tokens: List[Dict[str, Any]]):
try:
with open(TOKENS_FILE, "w", encoding="utf-8") as f:
json.dump(tokens, f, indent=2, ensure_ascii=False)
except Exception as e:
logger.error(f"Error saving dynamic tokens: {e}")
def generate_invite(self,
creator_id: str = "7107005438",
role: str = "EXPERT_ADVISOR",
expiry_hours: int = 24,
max_uses: int = 1,
bot_username: str = "AuraAjent_bot") -> Dict[str, Any]:
"""
Dynamically generates a cryptographically random, non-hardcoded invitation token.
"""
random_suffix = secrets.token_urlsafe(12).replace("-", "").replace("_", "")
token = f"adv_{random_suffix}"
link = f"https://t.me/{bot_username}?start={token}"
now = datetime.now(timezone.utc)
expires = now + timedelta(hours=expiry_hours)
record = {
"token": token,
"link": link,
"creator_id": str(creator_id),
"role": role,
"created_at": now.isoformat(),
"expires_at": expires.isoformat(),
"max_uses": max_uses,
"used_count": 0,
"status": "ACTIVE",
"used_by": []
}
tokens = self._load()
tokens.append(record)
self._save(tokens)
logger.info(f"Generated new dynamic invite token: {token} (Expires in {expiry_hours}h)")
return {
"token": token,
"link": link,
"expires_at": record["expires_at"],
"max_uses": max_uses,
"instructions": f"এই ইউনিক ডায়নামিক লিংকটি আপনার বন্ধুকে পাঠান। এটি পরবর্তী {expiry_hours} ঘণ্টার জন্য কার্যকর থাকবে।"
}
def validate_and_consume_token(self, token: str, user_id: str, user_name: str) -> Dict[str, Any]:
"""
Validates token freshness, status, and single/multi-use limits.
Consumes one usage count if valid.
"""
token = str(token).strip()
tokens = self._load()
now = datetime.now(timezone.utc)
target = None
for t in tokens:
if t.get("token") == token:
target = t
break
if not target:
# Check legacy backward-compat emergency token
if token == "advisor_redwan_2671":
return {
"valid": True,
"role": "EXPERT_ADVISOR",
"reason": "LEGACY_FALLBACK"
}
return {"valid": False, "reason": "TOKEN_NOT_FOUND"}
# Check status
if target.get("status") != "ACTIVE":
return {"valid": False, "reason": f"TOKEN_{target.get('status')}"}
# Check expiration
expires_at = datetime.fromisoformat(target["expires_at"])
if now > expires_at:
target["status"] = "EXPIRED"
self._save(tokens)
return {"valid": False, "reason": "TOKEN_EXPIRED"}
# Check usage limit
if target["used_count"] >= target["max_uses"]:
target["status"] = "EXHAUSTED"
self._save(tokens)
return {"valid": False, "reason": "TOKEN_EXHAUSTED"}
# Consume token
target["used_count"] += 1
target["used_by"].append({
"user_id": str(user_id),
"user_name": user_name,
"used_at": now.isoformat()
})
if target["used_count"] >= target["max_uses"]:
target["status"] = "EXHAUSTED"
self._save(tokens)
logger.info(f"Token {token} consumed by {user_name} ({user_id})")
return {
"valid": True,
"role": target.get("role", "EXPERT_ADVISOR"),
"token": token,
"reason": "VALID"
}
def revoke_token(self, token: str) -> bool:
"""Immediately disables an active invitation token."""
tokens = self._load()
for t in tokens:
if t.get("token") == token:
t["status"] = "REVOKED"
self._save(tokens)
logger.info(f"Revoked token: {token}")
return True
return False
def list_tokens(self) -> List[Dict[str, Any]]:
return self._load()
dynamic_token_vault = DynamicTokenVault()