data-breach-detector 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """data_breach_detector — read-only breach-intelligence MCP server."""
2
+
3
+ from .server import mcp
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["mcp"]
@@ -0,0 +1,34 @@
1
+ """CLI entry point: stdio by default, streamable-HTTP with --http.
2
+
3
+ data-breach-detector # stdio (for local / MCP clients)
4
+ data-breach-detector --http # HTTP MCP on 127.0.0.1:8790/mcp
5
+ data-breach-detector --http --host 0.0.0.0 --port 8790
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+
12
+ from .server import mcp
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ ap = argparse.ArgumentParser(prog="data-breach-detector",
17
+ description="Read-only breach-intelligence MCP server")
18
+ ap.add_argument("--http", action="store_true",
19
+ help="serve over streamable-HTTP instead of stdio")
20
+ ap.add_argument("--host", default="127.0.0.1")
21
+ ap.add_argument("--port", type=int, default=8790)
22
+ args = ap.parse_args(argv)
23
+
24
+ if args.http:
25
+ mcp.settings.host = args.host
26
+ mcp.settings.port = args.port
27
+ mcp.run(transport="streamable-http")
28
+ else:
29
+ mcp.run()
30
+ return 0
31
+
32
+
33
+ if __name__ == "__main__":
34
+ raise SystemExit(main())
@@ -0,0 +1,89 @@
1
+ """Lightweight, dependency-free threat classifier.
2
+
3
+ Keyword-based triage of security text into threat categories with a severity
4
+ level and a recommended action. Stdlib only, so the whole package stays tiny.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ THREAT_CATEGORIES: dict[str, list[str]] = {
12
+ "data_breach": [
13
+ "data breach", "leaked database", "dump", "exposed data",
14
+ "data leak", "compromised accounts", "stolen data",
15
+ ],
16
+ "ransomware": [
17
+ "ransomware", "encrypted files", "ransom demand", "lockbit",
18
+ "blackcat", "cl0p", "play ransomware", "data extortion",
19
+ "double extortion",
20
+ ],
21
+ "credential_theft": [
22
+ "credential dump", "password leak", "login credentials", "combo list",
23
+ "stealer logs", "infostealer", "redline", "raccoon stealer", "vidar",
24
+ ],
25
+ "financial_fraud": [
26
+ "banking trojan", "payment fraud", "card skimmer", "atm malware",
27
+ "pos malware", "money mule", "business email compromise", "bec",
28
+ ],
29
+ "crypto_threat": [
30
+ "wallet drain", "exchange hack", "rug pull", "flash loan attack",
31
+ "bridge exploit", "smart contract exploit", "crypto scam", "ponzi",
32
+ "exit scam",
33
+ ],
34
+ "insider_threat": [
35
+ "insider trading", "insider threat", "data exfiltration",
36
+ "corporate espionage", "trade secret",
37
+ ],
38
+ "supply_chain": [
39
+ "supply chain attack", "dependency confusion", "malicious package",
40
+ "compromised update",
41
+ ],
42
+ "sanctions_evasion": [
43
+ "sanctions evasion", "money laundering", "kyc bypass", "mixer",
44
+ "tornado cash", "ofac",
45
+ ],
46
+ }
47
+
48
+ _TARGETS = re.compile(
49
+ r"\b(bank|credit union|exchange|brokerage|insurance|fintech|"
50
+ r"payment processor|clearing house|hedge fund|"
51
+ r"jpmorgan|goldman sachs|morgan stanley|citibank|wells fargo|"
52
+ r"binance|coinbase|kraken|bybit|okx|visa|mastercard|paypal|stripe)\b",
53
+ re.I,
54
+ )
55
+
56
+
57
+ def classify_threat(text: str) -> dict:
58
+ """Classify security text: threat level, categories, targets, action."""
59
+ low = (text or "").lower()
60
+ matched = {cat: [k for k in kws if k in low]
61
+ for cat, kws in THREAT_CATEGORIES.items()}
62
+ matched = {c: hits for c, hits in matched.items() if hits}
63
+ targets = sorted({t.lower() for t in _TARGETS.findall(text or "")})
64
+
65
+ n = len(matched)
66
+ has_target = bool(targets)
67
+ if n >= 3 or (n >= 2 and has_target):
68
+ level, conf = "critical", 0.9
69
+ elif n >= 2 or (n >= 1 and has_target):
70
+ level, conf = "high", 0.75
71
+ elif n >= 1:
72
+ level, conf = "medium", 0.6
73
+ else:
74
+ level, conf = "low", 0.3
75
+
76
+ action = {
77
+ "critical": "IMMEDIATE: alert security, check exposure to affected entities",
78
+ "high": "URGENT: review within the hour, assess exposure",
79
+ "medium": "MONITOR: track for escalation",
80
+ "low": "LOG: record for pattern analysis",
81
+ }[level]
82
+
83
+ return {
84
+ "threat_level": level,
85
+ "categories": matched,
86
+ "financial_targets": targets,
87
+ "confidence": conf,
88
+ "recommended_action": action,
89
+ }
@@ -0,0 +1,232 @@
1
+ """data_breach_detector — a read-only breach-intelligence MCP server.
2
+
3
+ DEFENSIVE ONLY. Answers "has X been breached / what's the recent breach news /
4
+ how severe is this threat text" from PUBLIC threat-intelligence disclosure
5
+ feeds. It reports INTELLIGENCE — the existence, timing, scale, category and
6
+ exposed data-TYPES of a breach — and never the breach CONTENTS. A redaction
7
+ pass strips emails, hashes, IPs, crypto addresses and credential-shaped tokens
8
+ from everything returned.
9
+
10
+ Live public sources (no key, no marketplace, no Tor):
11
+ - HaveIBeenPwned https://haveibeenpwned.com/api/v3/breaches
12
+ the public breach directory: domain, date, pwn count, and the CATEGORIES
13
+ of data exposed (e.g. "Email addresses, Passwords") — never the values.
14
+ - ransomwatch joshhighet/ransomwatch (public ransomware leak-site tracker)
15
+
16
+ It exposes no arbitrary fetch/crawl/proxy, no .onion access, no transactions,
17
+ and never returns the raw text of a dump, paste or leak.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import logging
24
+ import re
25
+ import time
26
+ from datetime import datetime, timezone
27
+
28
+ import httpx
29
+ from mcp.server.fastmcp import FastMCP
30
+
31
+ from .classifier import classify_threat
32
+
33
+ # httpx logs full request URLs at INFO; when the HTTP transport is fronted by a
34
+ # token nothing sensitive is in these URLs, but keep logs quiet regardless.
35
+ for _n in ("httpx", "httpcore"):
36
+ logging.getLogger(_n).setLevel(logging.WARNING)
37
+
38
+ mcp = FastMCP("data_breach_detector")
39
+
40
+ HIBP_BREACHES = "https://haveibeenpwned.com/api/v3/breaches"
41
+ RANSOMWATCH = "https://raw.githubusercontent.com/joshhighet/ransomwatch/main/posts.json"
42
+ _UA = "data-breach-detector/0.1 (+defensive threat-intel)"
43
+ _SEVERITY = ["low", "medium", "high", "critical"]
44
+
45
+ _REDACTIONS = [
46
+ (re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"), "[email]"),
47
+ (re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "[ip]"),
48
+ (re.compile(r"\b[a-fA-F0-9]{32,64}\b"), "[hash]"),
49
+ (re.compile(r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"), "[btc]"),
50
+ (re.compile(r"\b0x[a-fA-F0-9]{40}\b"), "[eth]"),
51
+ (re.compile(r"\S+:\S{4,}"), "[credential]"),
52
+ (re.compile(r"\b[A-Za-z0-9+/=_-]{24,}\b"), "[token]"),
53
+ ]
54
+
55
+
56
+ def _redact(text: str, cap: int = 320) -> str:
57
+ if not text:
58
+ return ""
59
+ out = text
60
+ for pattern, repl in _REDACTIONS:
61
+ out = pattern.sub(repl, out)
62
+ out = re.sub(r"<[^>]+>", " ", out)
63
+ out = re.sub(r"\s+", " ", out).strip()
64
+ return out[:cap]
65
+
66
+
67
+ def _sev_rank(level: str) -> int:
68
+ return _SEVERITY.index(level) if level in _SEVERITY else 0
69
+
70
+
71
+ _CACHE: dict = {"at": 0.0, "items": []}
72
+ _TTL_S = 900
73
+
74
+
75
+ async def _fetch_hibp(client: httpx.AsyncClient) -> list[dict]:
76
+ r = await client.get(HIBP_BREACHES)
77
+ r.raise_for_status()
78
+ out = []
79
+ for b in r.json():
80
+ data_types = b.get("DataClasses", []) or []
81
+ cls = classify_threat(f"{b.get('Title','')} {b.get('Description','')} {' '.join(data_types)}")
82
+ base = cls["threat_level"]
83
+ if any("password" in d.lower() or "credential" in d.lower() for d in data_types):
84
+ base = "critical" if b.get("IsStealerLog") else "high"
85
+ out.append({
86
+ "id": f"hibp:{b.get('Name')}",
87
+ "entity": b.get("Domain") or b.get("Name"),
88
+ "title": _redact(b.get("Title") or b.get("Name"), 120),
89
+ "summary": _redact(b.get("Description", "")),
90
+ "source": "HaveIBeenPwned",
91
+ "source_url": b.get("DisclosureUrl") or f"https://haveibeenpwned.com/PwnedWebsites#{b.get('Name')}",
92
+ "disclosed_at": (b.get("BreachDate") or "") + ("T00:00:00+00:00" if b.get("BreachDate") else ""),
93
+ "sort_date": b.get("AddedDate") or b.get("BreachDate", ""),
94
+ "pwn_count": b.get("PwnCount", 0),
95
+ "exposed_data_types": data_types,
96
+ "categories": list(cls["categories"].keys()) or ["data_breach"],
97
+ "threat_level": base,
98
+ "verified": bool(b.get("IsVerified")),
99
+ "stealer_log": bool(b.get("IsStealerLog")),
100
+ })
101
+ return out
102
+
103
+
104
+ async def _fetch_ransomwatch(client: httpx.AsyncClient) -> list[dict]:
105
+ r = await client.get(RANSOMWATCH)
106
+ r.raise_for_status()
107
+ posts = r.json()
108
+ posts.sort(key=lambda p: p.get("discovered", ""), reverse=True)
109
+ out = []
110
+ for p in posts[:120]:
111
+ title, group = p.get("post_title", ""), p.get("group_name", "")
112
+ cls = classify_threat(f"ransomware leak site {group} {title}")
113
+ out.append({
114
+ "id": f"ransomwatch:{group}:{title}"[:120],
115
+ "entity": _redact(title, 120),
116
+ "title": _redact(f"[{group}] {title}", 140),
117
+ "summary": _redact(f"Named on the {group} ransomware leak site."),
118
+ "source": "ransomwatch",
119
+ "source_url": "https://github.com/joshhighet/ransomwatch",
120
+ "disclosed_at": (p.get("discovered", "") or "").replace(" ", "T") + "+00:00" if p.get("discovered") else "",
121
+ "sort_date": p.get("discovered", ""),
122
+ "pwn_count": 0,
123
+ "exposed_data_types": [],
124
+ "categories": list(cls["categories"].keys()) or ["ransomware"],
125
+ "threat_level": "high",
126
+ "verified": True,
127
+ "stealer_log": False,
128
+ "actor": group,
129
+ })
130
+ return out
131
+
132
+
133
+ async def _feed() -> list[dict]:
134
+ now = time.time()
135
+ if _CACHE["items"] and now - _CACHE["at"] < _TTL_S:
136
+ return _CACHE["items"]
137
+ records: list[dict] = []
138
+ async with httpx.AsyncClient(timeout=25, headers={"User-Agent": _UA},
139
+ follow_redirects=True) as client:
140
+ results = await asyncio.gather(_fetch_hibp(client), _fetch_ransomwatch(client),
141
+ return_exceptions=True)
142
+ for res in results:
143
+ if isinstance(res, list):
144
+ records.extend(res)
145
+ records.sort(key=lambda r: r.get("sort_date", ""), reverse=True)
146
+ _CACHE.update(at=now, items=records)
147
+ return records
148
+
149
+
150
+ def _days_ago(iso: str | None) -> float:
151
+ if not iso:
152
+ return 1e9
153
+ try:
154
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
155
+ if dt.tzinfo is None:
156
+ dt = dt.replace(tzinfo=timezone.utc)
157
+ return (datetime.now(timezone.utc) - dt).total_seconds() / 86400
158
+ except (ValueError, TypeError):
159
+ return 1e9
160
+
161
+
162
+ @mcp.tool()
163
+ async def breach_news(since_days: int = 30, sector: str | None = None, limit: int = 25) -> dict:
164
+ """Recent breach and ransomware DISCLOSURES from public threat-intel feeds
165
+ (HaveIBeenPwned, ransomwatch). Metadata only — entity, date, scale, exposed
166
+ data TYPES, threat level — never the leaked data. Optional sector/keyword
167
+ filter (e.g. "bank", "health", "crypto")."""
168
+ feed = await _feed()
169
+ rows = [r for r in feed if _days_ago(r.get("sort_date")) <= since_days]
170
+ if sector:
171
+ s = sector.lower()
172
+ rows = [r for r in rows if s in (
173
+ r["title"] + " " + r["summary"] + " " + " ".join(r["categories"])
174
+ + " " + " ".join(r["exposed_data_types"])).lower()]
175
+ return {"count": len(rows), "since_days": since_days, "sector": sector,
176
+ "disclosures": rows[:limit],
177
+ "note": "Disclosure metadata only. No leaked records are served by this tool."}
178
+
179
+
180
+ @mcp.tool()
181
+ async def check_exposure(query: str, since_days: int = 100000) -> dict:
182
+ """Does a domain, company or brand appear in public breach or ransomware
183
+ DISCLOSURES? The HaveIBeenPwned model: yes/no plus metadata (when, scale,
184
+ which data types were exposed, severity, source) — never the exposed
185
+ records. Triage only; confirm through authorized channels."""
186
+ q = query.strip().lower()
187
+ if not q:
188
+ return {"error": "query is required (a domain, company or brand)"}
189
+ feed = await _feed()
190
+ hits = [r for r in feed if _days_ago(r.get("sort_date")) <= since_days and q in (
191
+ r["entity"] + " " + r["title"] + " " + r["summary"]).lower()]
192
+ worst = max((h["threat_level"] for h in hits), key=_sev_rank, default="none")
193
+ return {
194
+ "query": query, "exposed": bool(hits), "mentions": len(hits),
195
+ "worst_threat_level": worst if hits else "none",
196
+ "total_accounts_exposed": sum(h["pwn_count"] for h in hits),
197
+ "exposed_data_types": sorted({t for h in hits for t in h["exposed_data_types"]}),
198
+ "latest_disclosure": hits[0]["sort_date"] if hits else None,
199
+ "matches": hits[:15],
200
+ "note": ("Presence signal from public disclosure feeds: reports THAT an entity "
201
+ "appears in breach data, not the breached data. Confirm before acting."),
202
+ }
203
+
204
+
205
+ @mcp.tool()
206
+ async def assess_threat(text: str) -> dict:
207
+ """Triage a piece of security text (advisory, forum post, alert): classify
208
+ threat level, categories and recommended action. Pure analysis of text you
209
+ supply — collects nothing, reaches no network."""
210
+ if not text or not text.strip():
211
+ return {"error": "text is required"}
212
+ r = classify_threat(text)
213
+ return {"threat_level": r["threat_level"], "categories": list(r["categories"].keys()),
214
+ "financial_targets": r["financial_targets"], "confidence": r["confidence"],
215
+ "recommended_action": r["recommended_action"]}
216
+
217
+
218
+ @mcp.tool()
219
+ async def feed_sources() -> dict:
220
+ """List the public feeds this detector aggregates and how fresh the cache is."""
221
+ feed = await _feed()
222
+ by_source: dict[str, int] = {}
223
+ for r in feed:
224
+ by_source[r["source"]] = by_source.get(r["source"], 0) + 1
225
+ return {
226
+ "sources": ["HaveIBeenPwned — breach directory (domain, count, exposed data types)",
227
+ "ransomwatch — ransomware leak-site tracker (named victims)"],
228
+ "cached_disclosures": len(feed), "by_source": by_source,
229
+ "cache_age_seconds": int(time.time() - _CACHE["at"]) if _CACHE["at"] else None,
230
+ "scope": ("Public disclosure feeds only. No .onion access, no arbitrary "
231
+ "fetch/crawl, no credential or PII output."),
232
+ }
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: data-breach-detector
3
+ Version: 0.1.0
4
+ Summary: Read-only breach-intelligence MCP: reports THAT a domain was breached and which data types leaked, from public feeds (HaveIBeenPwned, ransomwatch). Never the leaked data.
5
+ Project-URL: Homepage, https://github.com/beepboop2025/data-breach-detector
6
+ Project-URL: Repository, https://github.com/beepboop2025/data-breach-detector
7
+ Author: beepboop2025
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: breach,haveibeenpwned,mcp,ransomware,security,threat-intelligence
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: httpx>=0.27
16
+ Requires-Dist: mcp>=1.2.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ <!-- mcp-name: io.github.beepboop2025/data-breach-detector -->
20
+
21
+ # data-breach-detector
22
+
23
+ A **read-only breach-intelligence MCP server**. It answers *"has this domain
24
+ been breached, what's the recent breach news, how severe is this threat text"*
25
+ from public threat-intelligence disclosure feeds — and reports **intelligence,
26
+ not contents**: the existence, timing, scale, category and exposed data-*types*
27
+ of a breach, never the leaked records themselves.
28
+
29
+ Built for defenders. Comparable in spirit to HaveIBeenPwned's own directory.
30
+
31
+ ## What it does not do
32
+
33
+ - No arbitrary URL fetch, no crawl, no proxy — no general scraping primitives.
34
+ - No `.onion` marketplace access, no transactions.
35
+ - Never returns the raw text of a dump, paste or leak. A redaction layer strips
36
+ emails, hashes, IPs, crypto addresses and credential-shaped tokens from every
37
+ string returned.
38
+
39
+ ## Sources (public, no key)
40
+
41
+ - **HaveIBeenPwned** `/api/v3/breaches` — the public breach directory: domain,
42
+ breach date, pwn count, and the *categories* of data exposed.
43
+ - **ransomwatch** (`joshhighet/ransomwatch`) — public ransomware leak-site tracker.
44
+
45
+ ## Tools
46
+
47
+ | tool | what it returns |
48
+ |------|-----------------|
49
+ | `breach_news(since_days, sector, limit)` | recent disclosures — entity, date, scale, exposed data types, severity |
50
+ | `check_exposure(query)` | does a domain/company appear in breach data — yes/no + metadata |
51
+ | `assess_threat(text)` | classify a piece of security text — level, categories, action (no network) |
52
+ | `feed_sources()` | which feeds are aggregated + cache freshness |
53
+
54
+ ## Run
55
+
56
+ ```bash
57
+ pip install data-breach-detector
58
+
59
+ data-breach-detector # stdio (for MCP clients)
60
+ data-breach-detector --http # streamable-HTTP on 127.0.0.1:8790/mcp
61
+ ```
62
+
63
+ Or point an MCP client at the config:
64
+
65
+ ```json
66
+ { "mcpServers": { "data_breach_detector": {
67
+ "command": "data-breach-detector"
68
+ } } }
69
+ ```
70
+
71
+ ## License
72
+
73
+ MIT. The breach data belongs to its sources (HaveIBeenPwned, ransomwatch);
74
+ this tool only aggregates their public disclosure metadata, with attribution.
@@ -0,0 +1,9 @@
1
+ data_breach_detector/__init__.py,sha256=mwpHbj3D5lF3PGovZtjjXIIH1LpNOJYQM9Duj1-BN0Y,139
2
+ data_breach_detector/__main__.py,sha256=bKtVnWpnO1aedNVi4L5Q81Ya1wp5lAcMDbCPb5TfTTc,1051
3
+ data_breach_detector/classifier.py,sha256=0v43pYEbS1vmeKjrnaKvIqZ0utQKGEhSIIBdL9HlZwY,3101
4
+ data_breach_detector/server.py,sha256=8ShiZK2bxqFmZlCZkBrft5CMghSkrG2pChUX2u5gIlA,10017
5
+ data_breach_detector-0.1.0.dist-info/METADATA,sha256=pZOApDsS3RITeyxpWs3w72c-g_TdJh3RrCyTxjVnN8o,2848
6
+ data_breach_detector-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
7
+ data_breach_detector-0.1.0.dist-info/entry_points.txt,sha256=WqYAIral8ZqQnphSgfozeBXyNuBLDHDYKc_F1dm_mqU,76
8
+ data_breach_detector-0.1.0.dist-info/licenses/LICENSE,sha256=AX5ap-fPhBF8ReW2DTTnh4Sz0KINCGqbn3Xs4HONjbc,1069
9
+ data_breach_detector-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ data-breach-detector = data_breach_detector.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 beepboop2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.