Skip to main content

Overview

Session Synchronization is the critical validation phase that ensures captured protocol tokens are active and ready for use. After Protocol Interception captures authentication tokens, APITHON must verify that the session is “hot” by triggering actual backend communication.

Why Synchronization Is Needed

Simply capturing tokens from network traffic is insufficient for two key reasons:
  1. Token Validation: The tokens may be stale, expired, or incomplete
  2. Backend Activation: The target service may require an initial “handshake” to establish streaming readiness
  3. Context Initialization: The internal context token needs to be confirmed as actively tracking conversation state
Without synchronization, attempting to use captured tokens would result in authentication failures or empty responses from the target service.

The Synchronization Function

The sincronizar_tunel function (lines 54-100 in apithon.py) orchestrates the entire synchronization process:
async def sincronizar_tunel(url_input):
    if not url_input.startswith("http"):
        url_input = "https://" + url_input
    SESS["target_url"] = url_input

    async with async_playwright() as p:
        print(f"\n[*] Estableciendo túnel en: {SESS['target_url']}")
        print("[*] Iniciando validación automatizada...")
        
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()

        async def protocol_sniffer(request):
            # ... [interception logic] ...

        page.on("request", protocol_sniffer)
        await page.goto(SESS["target_url"])

        try:
            input_selector = "div[contenteditable='true'], textarea, input"
            await page.wait_for_selector(input_selector, timeout=15000)
            print("[+] Interfaz detectada. Enviando validación ('.')")
            await page.fill(input_selector, ".")
            await page.keyboard.press("Enter")
        except Exception:
            print("[!] Advertencia: No se pudo automatizar el envío. Hágalo manualmente.")

        while not SESS["status_ready"]:
            await asyncio.sleep(0.5)
        
        print("[+] PROTOCOLO CAPTURADO: Estructura de sesión sincronizada.")
        await browser.close()

The Three Phases

Based on the README (lines 28-32), APITHON operates through three critical phases:
1

Phase 1: Interception (Sniffing)

Using Playwright, the system captures tokens and dynamic context from the target’s data flow.
page.on("request", protocol_sniffer)
await page.goto(SESS["target_url"])
2

Phase 2: Validation (Emulated)

The script automates sending a validation signal (”.” character) to immediately activate backend packet exchange.
await page.fill(input_selector, ".")
await page.keyboard.press("Enter")
This is the core synchronization mechanism.
3

Phase 3: Bridging (Gateway)

A Flask server translates standard REST requests to the captured internal protocol, enabling interoperability.See Gateway Mode for details on this phase.

Automated Validation Process

The validation process automatically triggers backend communication to capture active session tokens.

Input Detection

APItHON uses a flexible CSS selector to find the chat input field:
input_selector = "div[contenteditable='true'], textarea, input"
await page.wait_for_selector(input_selector, timeout=15000)
This selector matches:
  • Content-editable divs: Modern rich-text chat interfaces
  • Textareas: Traditional multi-line input fields
  • Input elements: Simple single-line text boxes
The 15-second timeout gives the page time to fully load and authenticate before attempting validation.

The Validation Message

APItHON sends a single period (.) as the validation message:
await page.fill(input_selector, ".")
await page.keyboard.press("Enter")
Why a period?
  • Minimal data payload
  • Universally accepted as valid input
  • Triggers backend processing without generating meaningful conversation
  • Easy to identify in logs or chat history

Fallback to Manual Input

If automation fails (due to CAPTCHA, unusual UI, or timing issues), the user is notified:
except Exception:
    print("[!] Advertencia: No se pudo automatizar el envío. Hágalo manualmente.")
The user can then manually type and send any message to trigger synchronization.

Session Monitoring Loop

After sending the validation message, APITHON enters a polling loop waiting for token capture:
while not SESS["status_ready"]:
    await asyncio.sleep(0.5)
This loop:
  • Checks the status_ready flag every 500ms
  • Continues until the protocol_sniffer successfully captures all tokens
  • Prevents the gateway from starting prematurely
The synchronization is complete when SESS["status_ready"] becomes True, which happens inside the protocol_sniffer function after all tokens are captured.
During synchronization, all browser cookies for the target domain are extracted:
cookies = await context.cookies()
SESS["auth_cookie"] = "; ".join([f"{c['name']}={c['value']}" for c in cookies])
This creates a cookie header string like:
__Secure-1PSID=xyz; __Secure-1PSIDTS=abc; NID=def

Context Persistence

The internal_context token is the most critical piece captured during synchronization:
ctx_match = re.search(r'(![a-zA-Z0-9_\-]{100,})', decoded)
if ctx_match:
    SESS["internal_context"] = ctx_match.group(1)
This token:
  • Starts with ! character
  • Is 100+ characters long
  • Contains alphanumeric characters, underscores, and hyphens
  • Persists conversation state across multiple requests

Session State Storage

All synchronized session data is stored in the global SESS dictionary:
SESS = {
    "auth_cookie": None,      # Full cookie string
    "internal_context": None, # Conversation context token
    "session_id": None,       # Session identifier
    "build_id": None,         # Frontend build version
    "status_ready": False,    # Synchronization flag
    "target_url": ""          # Target service URL
}

In-Memory Only

Session data is stored exclusively in RAM and never written to disk.

Process Lifetime

Tokens are valid only for the current process lifetime. They’re lost when APITHON terminates.

URL Normalization

Before synchronization begins, the input URL is normalized:
if not url_input.startswith("http"):
    url_input = "https://" + url_input
SESS["target_url"] = url_input
This allows users to input:
  • app.example.comhttps://app.example.com
  • https://app.example.comhttps://app.example.com (unchanged)
Always use HTTPS URLs. Many modern LLM services enforce HTTPS and will reject HTTP connections.

Error Handling

Input Selector Not Found

If the input field isn’t detected within 15 seconds:
except Exception:
    print("[!] Advertencia: No se pudo automatizar el envío. Hágalo manualmente.")
The synchronization doesn’t fail—it continues waiting for the user to manually trigger a message.

Synchronization Timeout

If tokens are never captured (due to network issues, incorrect URL, or authentication failure), the loop continues indefinitely:
while not SESS["status_ready"]:
    await asyncio.sleep(0.5)
The user must press Ctrl+C to abort and restart with corrections.

Synchronization Success

When synchronization completes successfully:
print("[+] PROTOCOLO CAPTURADO: Estructura de sesión sincronizada.")
await browser.close()
At this point:
  • All four tokens are captured and stored
  • The browser instance is closed (resources freed)
  • The status_ready flag is True
  • The system is ready to enter Gateway Mode

Diagram: Synchronization Flow

Next Steps

After successful synchronization, the captured tokens are ready to be used in Gateway Mode to translate external API requests into the target’s internal protocol.

Protocol Interception

Review how tokens are captured during synchronization

Gateway Mode

Learn how synchronized sessions power the API gateway

Build docs developers (and LLMs) love