"""Deterministic GitHub issue spam and malware filter. Used by: - .github/workflows/issue-spam-filter.yml (automatic triage on issue opened/edited/reopened) Standard library only; never checks out or executes untrusted code. Evaluates issues from untrusted accounts using generic malware, scam, phishing, and flood heuristics (no game titles or publisher/company names). When triggered, neutralizes the issue body, closes it as not_planned, locks it as spam, and applies the `spam` label. """ from __future__ import annotations import argparse import json import os import re import sys import urllib.error import urllib.parse import urllib.request from dataclasses import dataclass from datetime import datetime, timedelta, timezone from typing import Any TRUSTED_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"}) SPAM_LABEL = "spam" SPAM_THRESHOLD = 6 ORG_BLOCK_SCORE_THRESHOLD = 10 NEUTRALIZED_BODY = ( "Removed automatically (suspected spam/malware).\n\n" "If this was closed in error, please contact a maintainer." ) NEUTRALIZED_TITLE = "[removed]" # Duplicate-title and rapid-burst flood windows. DUPLICATE_WINDOW_HOURS = 24 DUPLICATE_TITLE_MIN_MATCHES = 2 AUTHOR_BURST_WINDOW_MINUTES = 30 AUTHOR_BURST_MIN_ISSUES = 3 URL_RE = re.compile(r"https?://[^\s<>()\[\]\"']+", re.I) # Bracketed promotional/piracy-bait prefixes in titles, e.g. "[GUIDE] ... Download & Guide". BAIT_TAG_RE = re.compile( r"[\[\(【]\s*(?:guide|free|crack(?:ed)?|download|leak(?:ed)?|mod|cheat|hack|" r"full|activator|keygen|repack|torrent|installer|setup|updated|working|new|" r"release|unlocked|bypass|loader|spoofer)\s*[\]\)】]", re.I, ) BAIT_TITLE_ACTION_RE = re.compile( r"\b(?:download(?:\s*&\s*guide)?|free\s+download|full\s+version|crack(?:ed)?|" r"keygen|activator|repack|torrent|installer|setup|patch\s+download|mod\s+menu|" r"cheat\s+engine|aimbot|wallhack|spoofer|license\s+key|serial\s+key|product\s+key|" r"unlock(?:ed)?\s+all|pc\s+download)\b", re.I, ) # Standalone high-confidence piracy/malware/scam phrases in title. EXPLICIT_SCAM_TITLE_RE = re.compile( r"\b(?:free\s+download|full\s+version\s+download|crack\s+download|keygen|" r"license\s+key\s+generator|serial\s+key\s+generator|hwid\s+spoofer|" r"wallet\s+drainer|crypto\s+drainer|seed\s+phrase|stealer\s+builder|" r"rat\s+tool|crypter\s+fud|fud\s+crypter|aimbot\s+free|mod\s+menu\s+download|" r"download\s*&\s*guide|download\s+and\s+guide|free\s+pc\s+download|" r"repack\s+download|torrent\s+download|activator\s+download)\b", re.I, ) # Classic malware-drop instructions in issue body: password-protected archive or AV disable. ARCHIVE_PASSWORD_RE = re.compile( r"(?:\b(?:zip|rar|7z|archive|file|extract(?:ion)?)\s+password\b|" r"\bpass(?:word)?\s*[:=\-]\s*[`\"']?[a-z0-9@#$%^&*_.\-]{3,24}[`\"']?)", re.I, ) AV_DISABLE_RE = re.compile( r"\b(?:disable|turn\s+off|pause|deactivate|exclude\s+from)\s+" r"(?:your\s+)?(?:antivirus|anti-virus|windows\s+defender|defender|smartscreen|" r"real[- ]time\s+protection|firewall)\b", re.I, ) # Download-and-execute shell/PowerShell one-liners commonly pasted by malware bots. MALICIOUS_ONELINER_RE = re.compile( r"(?:\b(?:irm|iwr|invoke-webrequest|invoke-restmethod)\b[^\n]{0,200}\|\s*(?:iex|invoke-expression)\b|" r"\bpowershell(?:\.exe)?\b[^\n]{0,120}\s-(?:enc|encodedcommand|e)\s+[A-Za-z0-9+/=]{20,}|" r"\b(?:curl|wget)\b[^\n]{0,200}\|\s*(?:ba)?sh\b|" r"\bmshta(?:\.exe)?\s+https?://|" r"\bcertutil(?:\.exe)?\s+-urlcache\b)", re.I, ) # Download / install CTA phrases common in scam bodies. DOWNLOAD_CTA_RE = re.compile( r"\b(?:download\s+now|click\s+here\s+to\s+download|direct\s+download|" r"download\s+link|mirror\s+link|backup\s+link|extract\s+the\s+archive|" r"run\s+as\s+administrator|installation\s+guide|step[- ]by[- ]step\s+guide|" r"how\s+to\s+download|no\s+survey|100%\s+working|verified\s+safe|" r"virus\s+free|no\s+virus|password\s+protected|setup\.exe|installer\.exe)\b", re.I, ) # Crypto, phishing, support-scam, and SEO spam phrases. PHISHING_SCAM_RE = re.compile( r"\b(?:crypto\s+recovery|recover\s+stolen|wallet\s+recovery|seed\s+phrase|" r"airdrop\s+claim|claim\s+airdrop|usdt\s+generator|free\s+crypto|" r"customer\s+support\s+number|toll[- ]free\s+number|helpline\s+number|" r"whatsapp\s*(?:\+?\d|us|me)|online\s+casino|sports\s+betting|" r"essay\s+writing\s+service|assignment\s+help)\b", re.I, ) # Clickbait badge buttons in markdown. DOWNLOAD_BADGE_RE = re.compile( r"\[!\[[^\]]*(?:download|free|install|get\s+now|click\s+here)[^\]]*\]\([^)]+\)\]\([^)]+\)", re.I, ) # Promotional emoji cluster often used by spam bots. PROMO_EMOJI_RE = re.compile(r"[🎮🔥🚀✅💎⬇️📥⚡🆓💰🎁🔓💥⭐👉👇🔗]") # Legitimate XCL report / technical signals (reduce false-positive risk on additive rules). XCL_LEGIT_SIGNAL_RE = re.compile( r"(?:###\s+Game\s+and\s+package\s+version|###\s+What\s+happens|" r"###\s+XCL\s+version|###\s+GPU\s+and\s+driver\s+version|" r"\breport\.json\b|\bxcl\.log\b|\bMicrosoftGame\.config\b|" r"\bxcl\s+run\b|\bD3D12\b|\bDXIL\b|\bRDNA2?\b|\bkernelx\b|\bPSO\b)", re.I, ) # URL shorteners and file-drop/redirect hosts frequently abused for malware delivery. SUSPICIOUS_HOSTS = frozenset({ # URL shorteners "bit.ly", "tinyurl.com", "t.co", "cutt.ly", "rb.gy", "shorturl.at", "is.gd", "rebrand.ly", "tiny.cc", "ow.ly", "goo.su", "clck.ru", "surl.li", "short.gy", "v.gd", "x.gd", # File-drop / paste / redirect hubs "mediafire.com", "mega.nz", "gofile.io", "pixeldrain.com", "workupload.com", "sendspace.com", "krakenfiles.com", "1fichier.com", "filebin.net", "anonfiles.com", "uploadhaven.com", "telegra.ph", "t.me", "linktr.ee", "beacons.ai", "bit.do", }) # Hosts trusted for normal bug reports / logs / docs. SAFE_LINK_HOSTS = frozenset({ "github.com", "raw.githubusercontent.com", "user-images.githubusercontent.com", "gist.github.com", "learn.microsoft.com", "docs.microsoft.com", "msdn.microsoft.com", "gpuopen.com", "developer.nvidia.com", "vulkan.lunarg.com", }) BINARY_EXT_RE = re.compile( r"\.(?:exe|msi|scr|bat|cmd|vbs|ps1|zip|rar|7z|iso|dmg|pkg|apk)(?:[?#]|$)", re.I, ) @dataclass(frozen=True) class SpamVerdict: is_spam: bool score: int reasons: tuple[str, ...] hard_trigger: bool = False def normalize_title(title: str) -> str: """Normalize an issue title for duplicate-flood comparison.""" cleaned = re.sub(r"[^a-z0-9]+", " ", (title or "").lower()).strip() return cleaned def extract_urls(text: str) -> list[str]: return [m.group(0).rstrip(".,;:!?)") for m in URL_RE.finditer(text or "")] def _host_matches(host: str, domain_set: frozenset[str]) -> bool: host = host.lower().strip(".") if host.startswith("www."): host = host[4:] if host in domain_set: return True return any(host.endswith("." + d) for d in domain_set) def _is_google_sites_redirect(parsed: urllib.parse.ParseResult) -> bool: host = (parsed.hostname or "").lower() return host == "sites.google.com" and parsed.path.lower().startswith("/view/") def parse_iso_utc(ts: str | None) -> datetime | None: if not ts: return None try: return datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone(timezone.utc) except ValueError: return None def analyze_issue( issue: dict[str, Any], recent_issues: list[dict[str, Any]] | None = None, *, now: datetime | None = None, ) -> SpamVerdict: """Score an issue and return a deterministic SpamVerdict.""" if issue.get("pull_request"): return SpamVerdict(False, 0, ("is_pull_request",)) assoc = (issue.get("author_association") or "NONE").upper() if assoc in TRUSTED_ASSOCIATIONS: return SpamVerdict(False, 0, ("trusted_author",)) title = (issue.get("title") or "").strip() body = (issue.get("body") or "").strip() combined = f"{title}\n{body}" score = 0 reasons: list[str] = [] hard_trigger = False # 1. High-confidence malware / scam rules (cannot be discounted away). if EXPLICIT_SCAM_TITLE_RE.search(title): score += 6 reasons.append("explicit_scam_title") hard_trigger = True elif BAIT_TAG_RE.search(title) and BAIT_TITLE_ACTION_RE.search(title): score += 6 reasons.append("bait_tag_and_download_title") hard_trigger = True if MALICIOUS_ONELINER_RE.search(combined): score += 8 reasons.append("malicious_download_oneliner") hard_trigger = True has_archive_pw = bool(ARCHIVE_PASSWORD_RE.search(body)) has_av_disable = bool(AV_DISABLE_RE.search(body)) if has_archive_pw and has_av_disable: score += 8 reasons.append("archive_password_and_av_disable") hard_trigger = True elif has_archive_pw: score += 5 reasons.append("archive_password_instruction") elif has_av_disable: score += 4 reasons.append("av_disable_instruction") # 2. URL & link analysis. urls = extract_urls(combined) external_urls: list[str] = [] has_suspicious_host = False has_external_binary = False for u in urls: parsed = urllib.parse.urlparse(u) host = (parsed.hostname or "").lower() if not host: continue if _host_matches(host, SUSPICIOUS_HOSTS) or _is_google_sites_redirect(parsed): has_suspicious_host = True external_urls.append(u) elif not _host_matches(host, SAFE_LINK_HOSTS): external_urls.append(u) if BINARY_EXT_RE.search(parsed.path or ""): has_external_binary = True if has_suspicious_host: score += 3 reasons.append("suspicious_link_host") if has_external_binary: score += 4 reasons.append("external_binary_or_archive_link") # 3. Body scam / spam patterns. cta_matches = DOWNLOAD_CTA_RE.findall(body) if len(cta_matches) >= 2: score += 3 reasons.append("repeated_download_cta") elif len(cta_matches) == 1: score += 2 reasons.append("download_cta") if DOWNLOAD_BADGE_RE.search(body): score += 3 reasons.append("download_badge_button") if PHISHING_SCAM_RE.search(combined): score += 5 reasons.append("phishing_or_seo_scam") promo_emojis = PROMO_EMOJI_RE.findall(combined) if len(promo_emojis) >= 5 or len(set(promo_emojis)) >= 3: score += 2 reasons.append("promo_emoji_spam") # Trivial / stub title (e.g. "-") combined with external links or empty/tiny body. alnum_title = re.sub(r"[^a-z0-9]", "", title.lower()) if len(alnum_title) <= 1: if external_urls: score += 4 reasons.append("stub_title_with_external_link") elif len(body) <= 20: score += 3 reasons.append("stub_empty_issue") # 4. Duplicate-title and rapid-burst flood detection across recent issues. if recent_issues: ref_time = now or parse_iso_utc(issue.get("created_at")) or datetime.now(timezone.utc) issue_num = issue.get("number") issue_author = ((issue.get("user") or {}).get("login") or "").lower() norm_title = normalize_title(title) dup_cutoff = ref_time - timedelta(hours=DUPLICATE_WINDOW_HOURS) burst_cutoff = ref_time - timedelta(minutes=AUTHOR_BURST_WINDOW_MINUTES) dup_count = 0 author_burst_count = 0 for other in recent_issues: if other.get("pull_request"): continue if issue_num is not None and other.get("number") == issue_num: continue other_created = parse_iso_utc(other.get("created_at")) if other_created is None: continue other_assoc = (other.get("author_association") or "NONE").upper() if other_assoc in TRUSTED_ASSOCIATIONS: continue if norm_title and len(norm_title) >= 6 and other_created >= dup_cutoff: if normalize_title(other.get("title") or "") == norm_title: dup_count += 1 other_author = ((other.get("user") or {}).get("login") or "").lower() if issue_author and other_author == issue_author and other_created >= burst_cutoff: author_burst_count += 1 if dup_count >= DUPLICATE_TITLE_MIN_MATCHES: score += 6 reasons.append(f"duplicate_title_flood({dup_count})") hard_trigger = True if author_burst_count >= AUTHOR_BURST_MIN_ISSUES: score += 6 reasons.append(f"author_rapid_burst({author_burst_count})") hard_trigger = True # 5. Discount additive-only score when legitimate XCL bug-report signals are present. if not hard_trigger and XCL_LEGIT_SIGNAL_RE.search(combined): score = max(0, score - 4) reasons.append("xcl_technical_signal_discount") is_spam = hard_trigger or score >= SPAM_THRESHOLD return SpamVerdict( is_spam=is_spam, score=score, reasons=tuple(reasons), hard_trigger=hard_trigger, ) def should_org_block(issue: dict[str, Any], verdict: SpamVerdict) -> bool: """Return True only when an issue is high-confidence spam from a non-bot untrusted account.""" if not verdict.is_spam: return False if not (verdict.hard_trigger or verdict.score >= ORG_BLOCK_SCORE_THRESHOLD): return False assoc = (issue.get("author_association") or "NONE").upper() if assoc in TRUSTED_ASSOCIATIONS: return False user = issue.get("user") or {} login = (user.get("login") or "").strip() if not login or login.lower().endswith("[bot]") or (user.get("type") or "").lower() == "bot": return False return True def _is_already_neutralized(issue: dict[str, Any]) -> bool: return ( issue.get("state") == "closed" and bool(issue.get("locked")) and (issue.get("body") or "").strip() == NEUTRALIZED_BODY.strip() ) def _has_spam_label(issue: dict[str, Any]) -> bool: for lbl in issue.get("labels") or []: name = lbl.get("name") if isinstance(lbl, dict) else str(lbl) if (name or "").lower() == SPAM_LABEL: return True return False class GitHubClient: """Minimal stdlib GitHub REST client.""" def __init__(self, token: str, api_base: str = "https://api.github.com") -> None: self.token = token self.api_base = api_base.rstrip("/") def request( self, method: str, path: str, payload: dict[str, Any] | None = None, ) -> Any: url = f"{self.api_base}{path}" if payload is not None: data: bytes | None = json.dumps(payload).encode("utf-8") elif method.upper() in ("PUT", "POST", "PATCH"): data = b"" else: data = None req = urllib.request.Request(url, data=data, method=method) req.add_header("Accept", "application/vnd.github+json") req.add_header("X-GitHub-Api-Version", "2022-11-28") req.add_header("User-Agent", "xcl-issue-spam-filter") if self.token: req.add_header("Authorization", f"Bearer {self.token}") if payload is not None: req.add_header("Content-Type", "application/json") with urllib.request.urlopen(req, timeout=30) as resp: raw = resp.read() if not raw: return None return json.loads(raw.decode("utf-8")) def get_issue(self, repo: str, number: int) -> dict[str, Any]: return self.request("GET", f"/repos/{repo}/issues/{number}") def list_recent_issues( self, repo: str, since: datetime, per_page: int = 50, max_pages: int = 1, ) -> list[dict[str, Any]]: since_iso = since.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") items: list[dict[str, Any]] = [] for page in range(1, max_pages + 1): qs = urllib.parse.urlencode({ "state": "all", "sort": "created", "direction": "desc", "since": since_iso, "per_page": per_page, "page": page, }) result = self.request("GET", f"/repos/{repo}/issues?{qs}") if not isinstance(result, list) or not result: break items.extend(result) if len(result) < per_page: break return items def neutralize_and_close_issue( self, repo: str, number: int, *, clear_title: bool = False, ) -> None: payload: dict[str, Any] = { "body": NEUTRALIZED_BODY, "state": "closed", "state_reason": "not_planned", } if clear_title: payload["title"] = NEUTRALIZED_TITLE self.request("PATCH", f"/repos/{repo}/issues/{number}", payload) def lock_issue_as_spam(self, repo: str, number: int) -> None: self.request( "PUT", f"/repos/{repo}/issues/{number}/lock", {"lock_reason": "spam"}, ) def add_spam_label(self, repo: str, number: int) -> None: self.request( "POST", f"/repos/{repo}/issues/{number}/labels", {"labels": [SPAM_LABEL]}, ) def block_org_user(self, org: str, username: str) -> bool: encoded_user = urllib.parse.quote(username, safe="") try: self.request("PUT", f"/orgs/{org}/blocks/{encoded_user}") return True except urllib.error.HTTPError as exc: if exc.code == 422: # Already blocked or cannot be blocked (e.g. org member). return True raise def _neutralize_issue(client: GitHubClient, repo: str, issue: dict[str, Any]) -> None: number = int(issue["number"]) if _is_already_neutralized(issue): return title_has_url = bool(URL_RE.search(issue.get("title") or "")) client.neutralize_and_close_issue(repo, number, clear_title=title_has_url) try: client.lock_issue_as_spam(repo, number) except urllib.error.HTTPError as exc: print(f"#{number}: warning: failed to lock issue ({exc.code})", file=sys.stderr) try: client.add_spam_label(repo, number) except urllib.error.HTTPError as exc: print(f"#{number}: warning: failed to add label ({exc.code})", file=sys.stderr) def _try_org_block( org_block_client: GitHubClient | None, repo: str, username: str, context: str, ) -> bool: if org_block_client is None: return False org = repo.split("/", 1)[0] try: org_block_client.block_org_user(org, username) print(f"{context}: blocked @{username} from org {org}") return True except urllib.error.HTTPError as exc: print( f"{context}: warning: failed to block @{username} from org {org} ({exc.code})", file=sys.stderr, ) return False def process_issue( client: GitHubClient, repo: str, number: int, *, org_block_client: GitHubClient | None = None, dry_run: bool = False, ) -> SpamVerdict: """Fetch, evaluate, and (if spam) neutralize, close, lock, label, and optionally org-block.""" issue = client.get_issue(repo, number) if issue.get("pull_request"): print(f"#{number}: skipping pull request") return SpamVerdict(False, 0, ("is_pull_request",)) if _is_already_neutralized(issue): print(f"#{number}: already neutralized and locked") return SpamVerdict(False, 0, ("already_neutralized",)) now = datetime.now(timezone.utc) recent_issues = client.list_recent_issues( repo, since=now - timedelta(hours=DUPLICATE_WINDOW_HOURS) ) verdict = analyze_issue(issue, recent_issues, now=now) print( f"#{number}: is_spam={verdict.is_spam} score={verdict.score} " f"hard_trigger={verdict.hard_trigger} reasons={list(verdict.reasons)}" ) if not verdict.is_spam or dry_run: return verdict _neutralize_issue(client, repo, issue) if should_org_block(issue, verdict): username = (issue.get("user") or {}).get("login") or "" _try_org_block(org_block_client, repo, username, f"#{number}") return verdict def backfill_recent_spam( client: GitHubClient, repo: str, hours: int, *, org_block_client: GitHubClient | None = None, dry_run: bool = False, ) -> list[str]: """Scan recent issues, neutralize any missed spam, and org-block high-confidence spammers.""" now = datetime.now(timezone.utc) since = now - timedelta(hours=max(1, hours)) recent = client.list_recent_issues(repo, since=since, per_page=100, max_pages=3) issues_only = [i for i in recent if not i.get("pull_request")] print(f"backfill: scanning {len(issues_only)} issues from the last {hours}h") to_block: set[str] = set() for issue in issues_only: number = int(issue["number"]) assoc = (issue.get("author_association") or "NONE").upper() if assoc in TRUSTED_ASSOCIATIONS: continue verdict = analyze_issue(issue, issues_only, now=now) if not verdict.is_spam and _has_spam_label(issue): verdict = SpamVerdict(True, ORG_BLOCK_SCORE_THRESHOLD, ("existing_spam_label",), True) if not verdict.is_spam: continue username = ((issue.get("user") or {}).get("login") or "").strip() print( f"backfill #{number} (@{username}): score={verdict.score} " f"hard_trigger={verdict.hard_trigger} reasons={list(verdict.reasons)}" ) if not dry_run: _neutralize_issue(client, repo, issue) if should_org_block(issue, verdict): to_block.add(username) blocked: list[str] = [] for username in sorted(to_block, key=str.lower): if dry_run: print(f"backfill: [dry-run] would block @{username}") blocked.append(username) elif _try_org_block(org_block_client, repo, username, "backfill"): blocked.append(username) print(f"backfill: done ({len(blocked)} accounts blocked)") return blocked def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Filter spam and malware GitHub issues.") parser.add_argument("--repo", required=True, help="owner/repo") target = parser.add_mutually_exclusive_group(required=True) target.add_argument("--issue", type=int, help="Issue number") target.add_argument( "--backfill-hours", type=int, help="Scan recent issues from the last N hours and org-block spammers", ) target.add_argument( "--block-users", help="Comma-separated GitHub usernames to org-block directly", ) parser.add_argument( "--dry-run", action="store_true", help="Evaluate and log verdict without modifying issues or blocking users", ) args = parser.parse_args(argv) token = os.environ.get("GITHUB_TOKEN", "") if not token and not args.dry_run and not args.block_users: print("GITHUB_TOKEN is required unless --dry-run is set", file=sys.stderr) return 2 org_block_token = os.environ.get("SPAM_ORG_BLOCK_TOKEN", "").strip() client = GitHubClient(token) org_block_client = GitHubClient(org_block_token) if org_block_token else None if args.block_users is not None: users = [ u.strip().lstrip("@") for u in args.block_users.split(",") if u.strip() and not u.strip().lower().endswith("[bot]") ] if not org_block_client and not args.dry_run: print("SPAM_ORG_BLOCK_TOKEN is required for --block-users", file=sys.stderr) return 2 blocked = 0 for username in users: if args.dry_run: print(f"block-users: [dry-run] would block @{username}") blocked += 1 elif _try_org_block(org_block_client, args.repo, username, "block-users"): blocked += 1 print(f"block-users: done ({blocked}/{len(users)} accounts blocked)") return 0 if blocked == len(users) else 1 if args.backfill_hours is not None: backfill_recent_spam( client, args.repo, args.backfill_hours, org_block_client=org_block_client, dry_run=args.dry_run, ) else: process_issue( client, args.repo, args.issue, org_block_client=org_block_client, dry_run=args.dry_run, ) return 0 if __name__ == "__main__": raise SystemExit(main())