1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
|
"""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())
|