import os
import jwt
import json
import hashlib
import logging
from datetime import datetime, timedelta, timezone
from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse
==============================================================================
1. CORE DE AUDITORÍA Y PROTECCIÓN (BÚNKER V10)
==============================================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.FileHandler("omega_v10_core.log"), logging.StreamHandler()]
)
logger = logging.getLogger("TryOnYou_Omega")
app = FastAPI(
title="TRYONYOU CORE - V10 OMEGA",
description="Motor Autónomo: Malla Multidominio, Liquidación Stripe/Qonto y Wix Bridge",
version="10.0.0"
)
==============================================================================
2. MALLA MULTIDOMINIO & FIREWALL CORS
==============================================================================
ALLOWED_ORIGINS = [
"https://tryonyou.app",
"https://www.tryonyou.app",
"https://liveitfashion.com",
"https://www.liveitfashion.com",
"https://vvlart.com",
"https://www.vvlart.com",
"https://abvetos.com",
"https://www.abvetos.com"
]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-ABVET-AUTH", "X-ZERO-SIZE-TOKEN"],
)
SECRET_KEY = os.environ.get("OMEGA_V10_CORE_SECRET", "V10_OMEGA_SECURE_KEY_8891")
TARGET_PAYMENT = 484908.00 # Liquidación exacta esperada
==============================================================================
3. SINGLE SIGN-ON (SSO) OMNICANAL
==============================================================================
@app.post("/api/v1/sso/auth")
async def global_sso_handshake(request: Request):
"""
Autenticación sin fricción a través de los dominios satélite.
"""
try:
payload = await request.json()
user_id = payload.get("user_id")
if not user_id:
raise ValueError("ID de usuario ausente. Abortando SSO.")
token = jwt.encode({
"sub": user_id,
"exp": datetime.now(timezone.utc) + timedelta(days=7),
"aud": ALLOWED_ORIGINS,
"version": "V10_OMEGA"
}, SECRET_KEY, algorithm="HS256")
logger.info(f"SSO Match: Usuario {user_id} sincronizado en la matriz.")
return {
"status": "AUTHENTICATED",
"sso_token": token,
"core_db": "tryonyou_master_ledger"
}
except Exception as e:
logger.error(f"Fallo de seguridad en SSO: {str(e)}")
raise HTTPException(status_code=400, detail="Estructura de payload inválida.")
==============================================================================
4. TESORERÍA AUTÓNOMA: MONITOR STRIPE -> QONTO
==============================================================================
def execute_financial_clearance(transaction_id: str, amount: float):
"""
Fuerza el estado MATCHED y sella el log inmutable de la patente.
"""
try:
timestamp = datetime.now(timezone.utc).isoformat()
ledger_entry = f"TX_{transaction_id}AMT{amount}TS{timestamp}"
audit_hash = hashlib.sha256(ledger_entry.encode('utf-8')).hexdigest()
log_report = {
"origin": "STRIPE_WEBHOOK",
"destination": "QONTO_OPERATIONAL",
"amount_eur": amount,
"tx_reference": transaction_id,
"integrity_hash": audit_hash,
"status": "MATCHED",
"liquidity": "LIQUIDITY_DEPLOYABLE"
}
with open("TREASURY_MASTER_LEDGER.json", "a") as f:
f.write(json.dumps(log_report) + "\n")
logger.info(f"LIQUIDACIÓN SELLADA. Fondos Desplegables. Hash: {audit_hash}")
except Exception as e:
logger.critical(f"ERROR EN GRABACIÓN DE LEDGER: {str(e)}")
@app.post("/api/v1/webhooks/stripe")
async def stripe_treasury_monitor(request: Request, background_tasks: BackgroundTasks):
"""
Interceptor asíncrono. No bloquea a Stripe y procesa en segundo plano.
"""
try:
payload = await request.json()
if payload.get("type") == "payment_intent.succeeded":
data = payload.get("data", {}).get("object", {})
amount_received = data.get("amount_received", 0) / 100.0
transaction_id = data.get("id")
if amount_received == TARGET_PAYMENT:
logger.info(f"IMPACTO CONFIRMADO: {amount_received}€ interceptados.")
background_tasks.add_task(execute_financial_clearance, transaction_id, amount_received)
return {"status": "MATCHED", "action": "FUNDS_UNLOCKED"}
else:
logger.warning(f"Descarte: Importe {amount_received}€ no pertenece a OMEGA.")
return {"status": "ACKNOWLEDGE"}
except Exception as e:
logger.error(f"Fallo en Webhook Stripe: {str(e)}")
raise HTTPException(status_code=400, detail="Error de validación del evento.")
==============================================================================
5. PUENTE WIX PREMIUM (VELO EXPORTER)
==============================================================================
@app.get("/export/wix-omega-bridge", response_class=PlainTextResponse)
async def export_wix_velo_bridge():
"""
Devuelve el código JS exacto para insertar en el backend de Wix.
"""
velo_jsw = """// ARCHIVO: tryonyou_core_bridge.jsw (Wix Backend)
import { fetch } from 'wix-fetch';
import wixData from 'wix-data';
const CORE_URL = "https://api.tryonyou.app/api/v1";
// Procesamiento biométrico asíncrono (Zero-Size Protocol)
export async function pushBiometricsAsync(payload) {
fetch(${CORE_URL}/scan-and-match, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-ABVET-AUTH': 'OMEGA_V10_BRIDGE' },
body: JSON.stringify(payload)
}).catch(e => console.error("Wix Bridge Sync Error:", e));
return { status: "QUEUED", info: "Carga delegada al Búnker. UI liberada." };
}
// Auto-Sync del Catálogo Elena Grandini
export async function autoSyncCatalog() {
try {
const query = await wixData.query("ElenaGrandiniCatalog").eq("sync", false).find();
if (query.items.length > 0) {
let updates = query.items.map(item => ({...item, sync: true, status: "READY"}));
await wixData.bulkUpdate("ElenaGrandiniCatalog", updates);
return { updated: updates.length };
}
return { message: "Inventario consolidado." };
} catch (err) {
return { error: err.message };
}
}"""
return velo_jsw
==============================================================================
6. ESTADO DE LA MATRIZ
==============================================================================
@app.get("/health")
async def system_health():
return {
"system": "TRYONYOU V10 OMEGA",
"status": "READY & RUNNING",
"firewall": "ACTIVE",
"timestamp": datetime.now(timezone.utc).isoformat()
}
if name == "main":
import uvicorn
logger.info("Activando Matriz TRYONYOU V10 OMEGA...")
uvicorn.run(app, host="0.0.0.0", port=8000)
import os
import jwt
import json
import hashlib
import logging
from datetime import datetime, timedelta, timezone
from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse
==============================================================================
1. CORE DE AUDITORÍA Y PROTECCIÓN (BÚNKER V10)
==============================================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.FileHandler("omega_v10_core.log"), logging.StreamHandler()]
)
logger = logging.getLogger("TryOnYou_Omega")
app = FastAPI(
title="TRYONYOU CORE - V10 OMEGA",
description="Motor Autónomo: Malla Multidominio, Liquidación Stripe/Qonto y Wix Bridge",
version="10.0.0"
)
==============================================================================
2. MALLA MULTIDOMINIO & FIREWALL CORS
==============================================================================
ALLOWED_ORIGINS = [
"https://tryonyou.app",
"https://www.tryonyou.app",
"https://liveitfashion.com",
"https://www.liveitfashion.com",
"https://vvlart.com",
"https://www.vvlart.com",
"https://abvetos.com",
"https://www.abvetos.com"
]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-ABVET-AUTH", "X-ZERO-SIZE-TOKEN"],
)
SECRET_KEY = os.environ.get("OMEGA_V10_CORE_SECRET", "V10_OMEGA_SECURE_KEY_8891")
TARGET_PAYMENT = 484908.00 # Liquidación exacta esperada
==============================================================================
3. SINGLE SIGN-ON (SSO) OMNICANAL
==============================================================================
@app.post("/api/v1/sso/auth")
async def global_sso_handshake(request: Request):
"""
Autenticación sin fricción a través de los dominios satélite.
"""
try:
payload = await request.json()
user_id = payload.get("user_id")
==============================================================================
4. TESORERÍA AUTÓNOMA: MONITOR STRIPE -> QONTO
==============================================================================
def execute_financial_clearance(transaction_id: str, amount: float):
"""
Fuerza el estado MATCHED y sella el log inmutable de la patente.
"""
try:
timestamp = datetime.now(timezone.utc).isoformat()
ledger_entry = f"TX_{transaction_id}AMT{amount}TS{timestamp}"
audit_hash = hashlib.sha256(ledger_entry.encode('utf-8')).hexdigest()
@app.post("/api/v1/webhooks/stripe")
async def stripe_treasury_monitor(request: Request, background_tasks: BackgroundTasks):
"""
Interceptor asíncrono. No bloquea a Stripe y procesa en segundo plano.
"""
try:
payload = await request.json()
==============================================================================
5. PUENTE WIX PREMIUM (VELO EXPORTER)
==============================================================================
@app.get("/export/wix-omega-bridge", response_class=PlainTextResponse)
async def export_wix_velo_bridge():
"""
Devuelve el código JS exacto para insertar en el backend de Wix.
"""
velo_jsw = """// ARCHIVO: tryonyou_core_bridge.jsw (Wix Backend)
import { fetch } from 'wix-fetch';
import wixData from 'wix-data';
const CORE_URL = "https://api.tryonyou.app/api/v1";
// Procesamiento biométrico asíncrono (Zero-Size Protocol)
export async function pushBiometricsAsync(payload) {
fetch(
${CORE_URL}/scan-and-match, {method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-ABVET-AUTH': 'OMEGA_V10_BRIDGE' },
body: JSON.stringify(payload)
}).catch(e => console.error("Wix Bridge Sync Error:", e));
}
// Auto-Sync del Catálogo Elena Grandini
export async function autoSyncCatalog() {
try {
const query = await wixData.query("ElenaGrandiniCatalog").eq("sync", false).find();
if (query.items.length > 0) {
let updates = query.items.map(item => ({...item, sync: true, status: "READY"}));
await wixData.bulkUpdate("ElenaGrandiniCatalog", updates);
return { updated: updates.length };
}
return { message: "Inventario consolidado." };
} catch (err) {
return { error: err.message };
}
}"""
return velo_jsw
==============================================================================
6. ESTADO DE LA MATRIZ
==============================================================================
@app.get("/health")
async def system_health():
return {
"system": "TRYONYOU V10 OMEGA",
"status": "READY & RUNNING",
"firewall": "ACTIVE",
"timestamp": datetime.now(timezone.utc).isoformat()
}
if name == "main":
import uvicorn
logger.info("Activando Matriz TRYONYOU V10 OMEGA...")
uvicorn.run(app, host="0.0.0.0", port=8000)