#!/usr/bin/env python3
"""Audit menyeluruh DAS: cache, skrip sisipan lain, tautan judi, plugin asing, pengguna, sitemap."""
import base64, importlib.util, json, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
SITUS = f"https://{DOM}"
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36"}
UA_G = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}

SUNTIKAN = re.compile(r"livedashboardkit|35862e74a4a697bb6d998c471eade297|_b4a7b|_86b24", re.I)
JUDI = re.compile(r"casino|slot gacor|togel|maxwin|judi online|situs slot|kasyno|togel88", re.I)
RAGU = re.compile(r"eval\(|atob\(|fromCharCode|document\.write\(unescape|window\.location\.replace", re.I)


def ambil(url, kepala=UA):
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=kepala), timeout=45) as x:
            return x.status, x.read().decode("utf-8", "replace"), dict(x.headers)
    except urllib.error.HTTPError as e:
        return e.code, "", {}
    except Exception as e:
        return "GAGAL", str(e)[:50], {}


def rest(path):
    try:
        with urllib.request.urlopen(urllib.request.Request(f"{SITUS}{path}", headers=H), timeout=120) as x:
            return json.loads(x.read())
    except urllib.error.HTTPError as e:
        return {"err": e.code}
    except Exception as e:
        return {"err": str(e)[:50]}


print("=== 1. status cache beranda ===")
st, t, hdr = ambil(SITUS + "/?cek=" + str(int(time.time())))
st2, t2, hdr2 = ambil(SITUS + "/")
for label, tt, hh in (("URL biasa (cache)", t2, hdr2), ("URL tanpa cache", t, hdr)):
    print(f"   {label:<20} {len(tt):>7} char · cf-cache: {hh.get('cf-cache-status','-'):<8} · "
          f"skrip suntikan: {'ADA' if SUNTIKAN.search(tt) else 'tidak'}")
    time.sleep(1)

print("\n=== 2. skrip inline yang mencurigakan di beranda ===")
for s in re.findall(r"<script(?![^>]*src)[^>]*>(.*?)</script>", t, re.S):
    if RAGU.search(s):
        print("   ⚠", re.sub(r"\s+", " ", s)[:160])

print("\n=== 3. cloaking (pengunjung vs Googlebot) ===")
_, tg, hg = ambil(SITUS + "/?cek=" + str(int(time.time())), UA_G)
print(f"   pengunjung {len(t)} char · googlebot {len(tg)} char · beda {abs(len(t) - len(tg))}")

print("\n=== 4. plugin mencurigakan ===")
pl = rest("/wp-json/wp/v2/plugins?per_page=100&_fields=plugin,name,status")
if isinstance(pl, list):
    curiga = [x for x in pl if re.search(r"wp2p|protect-uploads|developer-toolkit|advanced-backup|starter-optimize|wpcode", x.get("plugin", ""), re.I)]
    print(f"   total plugin: {len(pl)}")
    for x in curiga:
        print(f"     [{'AKTIF' if x.get('status')=='active' else 'mati '}] {x.get('name')} · {x.get('plugin')}")
else:
    print("   gagal:", str(pl)[:70])

print("\n=== 5. pengguna ===")
us = rest("/wp-json/wp/v2/users?per_page=50&_fields=id,name")
if isinstance(us, list):
    for x in us:
        acak = bool(re.fullmatch(r"[0-9a-f]{8,}|wp2_[\w]+", str(x.get("name", "")), re.I))
        print(f"   #{x['id']:<4} {str(x.get('name'))[:28]}{'  ⚠' if acak else ''}")

print("\n=== 6. isi konten: kata judi & elemen tersembunyi ===")
hits = []
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            raw = x["content"]["raw"]
            kena = []
            if JUDI.search(raw):
                kena.append("kata judi")
            if re.search(r"position:\s*absolute;\s*left:\s*-\d+", raw, re.I):
                kena.append("elemen di luar layar")
            if re.search(r"overflow:\s*hidden;\s*height:\s*1(?:\.\d)?px", raw, re.I):
                kena.append("elemen tinggi 1px")
            if SUNTIKAN.search(raw):
                kena.append("skrip suntikan")
            if kena:
                hits.append((x["id"], jenis, kena))
        if len(d) < 100:
            break
        page += 1
        time.sleep(0.3)
print(f"   konten bermasalah: {len(hits)}")
for pid, jenis, kena in hits[:10]:
    print(f"     #{pid} {jenis} → {kena}")

print("\n=== 7. sitemap: jumlah entri ===")
st, sm, _ = ambil(f"{SITUS}/sitemap_index.xml")
if st == 200:
    subs = re.findall(r"<loc>([^<]+)</loc>", sm)
    print(f"   sub-sitemap: {len(subs)}")
    for s in subs:
        t2st, t2, _ = ambil(s)
        if t2st == 200:
            print(f"      {len(re.findall('<loc>', t2)):>4} entri · {s.split('/')[-1]}")
