#!/usr/bin/env python3 """Export local files for HashgraphOnline/hol-plugin-security. Does not upload.""" from __future__ import annotations import json import re import urllib.parse import urllib.request from collections import Counter from datetime import datetime, timezone from pathlib import Path OUT = Path("/workspace/hf-hol-benchmark") UA = "hol-dataset-export/1.0 (+https://hol.org)" CATALOG_URL = "https://hol.org/registry/api/v1/plugins/catalog" ADVISORIES_INDEX = "https://hol.org/guard/security/advisories" SECURITY_HUB = "https://hol.org/guard/security" SCENARIO_FAMILY = { "read_fixture_env": "secret_access", "read_fixture_npmrc": "secret_access", "read_fixture_ssh_key": "secret_access", "execute_risky_shell": "risky_shell", "register_new_mcp_server": "mcp_change", "change_existing_mcp_server": "mcp_change", "tool_poisoning_fixture": "tool_poisoning", "install_package_risk_fixture": "package_risk", "run_known_safe_action": "safe_control", "approve_blocked_action": "approval_control", "verify_receipt": "receipt", } SEVERITIES = ("critical", "high", "medium", "low") THREAT_CLASSES = ( "supply-chain", "secret-exfiltration", "mcp-tool-poisoning", "prompt-injection", "unsafe-command", "data-overexposure", ) def http_get(url): req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json,text/html"}) with urllib.request.urlopen(req, timeout=90) as resp: return resp.read().decode("utf-8", errors="replace") def http_get_json(url): return json.loads(http_get(url)) def extract_json_ld(html): blocks = [] for m in re.finditer( r']*type=["\']application/ld\+json["\'][^>]*>(.*?)', html, flags=re.I | re.S, ): raw = m.group(1).strip() try: data = json.loads(raw) except json.JSONDecodeError: continue if isinstance(data, list): blocks.extend(data) else: blocks.append(data) return blocks def walk_objs(objs): for obj in objs: if isinstance(obj, dict): yield obj for v in obj.values(): if isinstance(v, dict): yield from walk_objs([v]) elif isinstance(v, list): yield from walk_objs(v) def first_type(objs, typ): for obj in walk_objs(objs): t = obj.get("@type") types = t if isinstance(t, list) else [t] if typ in types: return obj return None def flatten_plugin(item, snapshot_at): slug = item.get("slug") trust_scores = item.get("trustScores") or {} safety = item.get("safety") or {} scanner = item.get("scanner") or {} severity = scanner.get("severityCounts") or {} findings = item.get("findings") or [] vs = item.get("verificationSignals") or {} inventory = item.get("inventory") or {} gh = item.get("githubMetrics") or {} rule_ids = [f.get("ruleId") for f in findings if isinstance(f, dict) and f.get("ruleId")] findings_high = safety.get("highFindings") if findings_high is None: findings_high = severity.get("high") profile_url = None if slug: profile_url = "https://hol.org/registry/plugins/" + urllib.parse.quote(slug, safe="") return { "slug": slug, "display_name": item.get("displayName"), "developer_name": item.get("developerName"), "description": item.get("description"), "version": item.get("version"), "repository": item.get("repository"), "source_commit": item.get("sourceCommit"), "profile_url": profile_url, "ecosystems": item.get("ecosystems") if "ecosystems" in item else None, "category": item.get("category"), "tags": item.get("tags") if "tags" in item else None, "trust_score": item.get("trustScore"), "score_security": trust_scores.get("security.score"), "score_provenance": trust_scores.get("provenance.score"), "score_installability": trust_scores.get("installability.score"), "score_mcp_posture": trust_scores.get("mcp.posture.score"), "score_publisher": trust_scores.get("publisher.score"), "score_maintenance": trust_scores.get("maintenance.score"), "safety_label": safety.get("label"), "safety_score": safety.get("score"), "findings_total": safety.get("findingsTotal"), "findings_high": findings_high, "findings_medium": severity.get("medium"), "findings_low": severity.get("low"), "finding_rule_ids": rule_ids, "scanner_grade": scanner.get("grade"), "scanner_provider": scanner.get("provider"), "owner_verified": item.get("ownerVerified"), "publisher_verified": vs.get("publisherVerified") if vs else None, "digest_verified": vs.get("manifestDigestVerified") if vs else None, "repo_commit_pinned": vs.get("repoCommitPinned") if vs else None, "featured": item.get("featured"), "github_stars": gh.get("stars") if gh else None, "github_pushed_at": gh.get("pushedAt") if gh else None, "updated_at": item.get("updatedAt"), "snapshot_at": snapshot_at, "skill_count": inventory.get("skills") if inventory else None, "mcp_server_count": inventory.get("mcpServers") if inventory else None, } def fetch_plugins(snapshot_at): rows = [] cursor = None total_count = None while True: qs = {"limit": "50"} if cursor: qs["cursor"] = cursor url = CATALOG_URL + "?" + urllib.parse.urlencode(qs) payload = http_get_json(url) total_count = payload.get("totalCount", total_count) for item in payload.get("items") or []: rows.append(flatten_plugin(item, snapshot_at)) cursor = payload.get("nextCursor") if not cursor: break return rows, total_count def flatten_runtime(): data = json.loads((OUT / "data.json").read_text()) run_id = data.get("runId") schema_version = data.get("schemaVersion") rows = [] for r in data.get("results") or []: sid = r.get("scenarioId") rows.append({ "scenario_id": sid, "scenario_family": SCENARIO_FAMILY.get(sid), "harness_id": r.get("harnessId"), "comparator": r.get("comparator"), "outcome": r.get("outcome"), "receipt_created": r.get("receiptCreated"), "median_latency_ms": r.get("medianLatencyMs"), "p95_latency_ms": r.get("p95LatencyMs"), "modeled": True, "harness_independent": True, "run_id": run_id, "schema_version": schema_version, }) return rows def collect_advisory_urls(html): urls = [] seen = set() item_list = first_type(extract_json_ld(html), "ItemList") if item_list: for el in item_list.get("itemListElement") or []: url = el.get("url") item = el.get("item") if not url and isinstance(item, dict): url = item.get("url") or item.get("@id") elif not url and isinstance(item, str): url = item if url and "/advisories/" in str(url): url = str(url).split("#")[0] if url not in seen: seen.add(url) urls.append(url) if not urls: for m in re.finditer(r"https://hol\.org/guard/security/advisories/[a-z0-9-]+", html): if m.group(0) not in seen: seen.add(m.group(0)) urls.append(m.group(0)) return urls def listing_meta(html): threat_rx = re.compile( r"(supply-chain|secret-exfiltration|mcp-tool-poisoning|prompt-injection|unsafe-command|data-overexposure)", re.I, ) sev_rx = re.compile(r"(critical|high|medium|low)", re.I) meta = {} for m in re.finditer(r"/guard/security/advisories/([a-z0-9-]+)", html): slug = m.group(1) window = html[max(0, m.start() - 600) : m.start()] rec = meta.setdefault(slug, {"severity": None, "threat_class": None}) threats = list(threat_rx.finditer(window)) if threats: rec["threat_class"] = threats[-1].group(1).lower() sevs = list(sev_rx.finditer(window)) if sevs: rec["severity"] = sevs[-1].group(1).lower() return meta def parse_surfaces(html): m = re.search(r"Affected surfaces(.{0,1200})", html, flags=re.I | re.S) if not m: return None chunk = re.sub(r"<[^>]+>", "\n", m.group(1)) parts = [re.sub(r"\s+", " ", p).strip() for p in chunk.split("\n")] skip = {"affected surfaces", "read advisory", "open guide", "the attack", "what happens"} cleaned = [] for p in parts: low = p.lower() if not p or low in skip or low.startswith("+"): continue if "<" in p or ">" in p or p.startswith("/") or p.startswith("class="): break if low.startswith("the attack") or low.startswith("what happens"): break if len(p) > 80: continue cleaned.append(p) return cleaned or None def parse_severity_threat(html): text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html)) sev = None for s in SEVERITIES: if re.search(r"\b" + s + r"\s+severity\b", text, flags=re.I): sev = s break return sev, None def fetch_advisories(): hub = http_get(SECURITY_HUB) index = http_get(ADVISORIES_INDEX) urls = collect_advisory_urls(index) or collect_advisory_urls(hub) meta = listing_meta(index) hub_meta = listing_meta(hub) for slug, hm in hub_meta.items(): rec = meta.setdefault(slug, {"severity": None, "threat_class": None}) if not rec.get("threat_class"): rec["threat_class"] = hm.get("threat_class") if not rec.get("severity"): rec["severity"] = hm.get("severity") rows = [] for url in urls: slug = url.rstrip("/").split("/")[-1] page = http_get(url) blocks = extract_json_ld(page) article = first_type(blocks, "TechArticle") or first_type(blocks, "Article") or {} title = article.get("headline") summary = article.get("description") date_modified = article.get("dateModified") page_url = article.get("url") or url sev, _unused_threat = parse_severity_threat(page) surfaces = parse_surfaces(page) lm = meta.get(slug) or {} if not sev: sev = lm.get("severity") threat = None # not in JSON-LD; do not guess from nearby cards rows.append({ "slug": slug, "title": title, "severity": sev, "threat_class": threat, "summary": summary, "surfaces": surfaces, "url": page_url, "date_modified": date_modified, "curated": True, }) return rows def write_jsonl(path, rows): with path.open("w", encoding="utf-8") as f: for row in rows: f.write(json.dumps(row, ensure_ascii=False) + "\n") def try_parquet(path, rows): try: import pandas as pd except ImportError: return False, "pandas not importable" try: pd.DataFrame(rows).to_parquet(path, index=False) return True, None except Exception as exc: return False, str(exc) def write_readme(): (OUT / "README.md").write_text( """--- license: apache-2.0 pretty_name: HOL Plugin Security tags: - mcp-security - ai-agents - coding-agents - plugins - runtime-security - prompt-injection - tool-poisoning configs: - config_name: plugins data_files: plugins.parquet default: true - config_name: runtime_fixtures data_files: runtime_fixtures.parquet - config_name: advisories data_files: advisories.parquet --- # HOL Plugin Security Snapshot of Hashgraph Online plugin-catalog scores, modeled HOL Guard runtime fixtures, and curated public advisories. Dataset id: `HashgraphOnline/hol-plugin-security`. The default config is **plugins** (205 scored registry plugins). `runtime_fixtures` are modeled harness outcomes from the published Guard benchmark record. `advisories` are the 22 public HOL Guard advisory pages. Sources: [plugin catalog API](https://hol.org/registry/api/v1/plugins/catalog), [runtime benchmark](https://hol.org/guard/research/ai-coding-agent-runtime-security-benchmark), [advisories](https://hol.org/guard/security/advisories). Re-export with `export_plugins.py`. License: Apache-2.0. ## Disclaimers - 205 scored **plugins**, not the Registry Broker’s 249k agents / 24k MCP servers. - Scanner on every current row is `registry-broker-fallback`. Not a live exploit test. Scan ≠ safety guarantee. - Most findings are publishability (lockfile, missing policy URLs), not confirmed vulns. 2 high findings in the 2026-08-16 pull. - `owner_verified` = GitHub OAuth repo permission. Not a security audit. `publisher_verified` is 0 today. - `runtime_fixtures` are **modeled**. Same outcome across all 5 harnesses. Latency values are placeholders. No real secrets or attacks executed. - HOL publishes this. Not independent third-party validation. - Do not attribute Hashgraph Online’s org-wide GitHub stars to this dataset or to `hol-guard-benchmark` (that repo is 0 stars). - Snapshot. Catalog changes; use `snapshot_at`. ## Configs | config | rows | files | | --- | --- | --- | | plugins (default) | 205 | `plugins.jsonl`, `plugins.parquet` | | runtime_fixtures | 220 | `runtime_fixtures.jsonl`, `runtime_fixtures.parquet` | | advisories | 22 | `advisories.jsonl`, `advisories.parquet` | ## Citation HOL Guard Team. "HOL Plugin Security." 2026. https://hol.org/registry """ ) def write_notes(lines): (OUT / "EXPORT_NOTES.md").write_text("\n".join(lines) + "\n") def main(): snapshot_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" notes = [ "# Export notes", "", f"snapshot_at: {snapshot_at}", "Dataset: HashgraphOnline/hol-plugin-security", "No Hugging Face upload was performed.", "", "## Field mapping", "- Catalog paging: GET /registry/api/v1/plugins/catalog?limit=50&cursor={nextCursor} until nextCursor is null.", "- `profile_url` is https://hol.org/registry/plugins/{urlencoded slug} (slash becomes %2F).", "- Trust subscores from trustScores['security.score'] and siblings, not nested objects.", "- findings_high prefers safety.highFindings, else scanner.severityCounts.high.", "- findings_medium / findings_low come from scanner.severityCounts (absent on safety).", "- finding_rule_ids is findings[].ruleId only; messages and paths omitted.", "- owner_verified is top-level ownerVerified. API omits the field when unverified → null.", "- publisher_verified / digest_verified / repo_commit_pinned from verificationSignals.", "- skill_count / mcp_server_count from inventory.skills / inventory.mcpServers (often 0 even when the manifest lists a skills path).", "- tags is null when the API omits the field (not coerced to []).", "- Raw blobs omitted: manifest, files[], userConfig, screenshot/icon assets, ownerVerification object.", "- github_stars is per-repo githubMetrics.stars, not the Hashgraph Online org total.", "- runtime_fixtures.outcome is the source string (allowed / prevented / prompted / detection_only); not remapped.", "- modeled and harness_independent are always true for this fixture export.", "- run_id / schema_version copied from data.json runId / schemaVersion.", "- Advisories have no JSON index. URLs from schema.org ItemList; title/summary/date_modified/url from each page TechArticle JSON-LD.", "- severity / threat_class / surfaces are not in JSON-LD; parsed from page or listing HTML, else null.", "- curated is always true (HOL-curated public advisories).", ] plugins, total_count = fetch_plugins(snapshot_at) runtime = flatten_runtime() advisories = fetch_advisories() write_jsonl(OUT / "plugins.jsonl", plugins) write_jsonl(OUT / "runtime_fixtures.jsonl", runtime) write_jsonl(OUT / "advisories.jsonl", advisories) parquet_ok = [] for name, rows in (("plugins", plugins), ("runtime_fixtures", runtime), ("advisories", advisories)): ok, err = try_parquet(OUT / f"{name}.parquet", rows) if ok: parquet_ok.append(name) else: notes.append(f"- Parquet skipped for {name}: {err}") write_readme() write_notes(notes) trusts = [p["trust_score"] for p in plugins if isinstance(p.get("trust_score"), (int, float))] labels = Counter(p.get("safety_label") for p in plugins) grades = Counter(p.get("scanner_grade") for p in plugins) providers = sorted({p.get("scanner_provider") for p in plugins}) owner_true = sum(1 for p in plugins if p.get("owner_verified") is True) high_total = sum((p.get("findings_high") or 0) for p in plugins) print("=== SANITY ===") print(f"plugins rows: {len(plugins)} (api totalCount={total_count})") print(f"runtime_fixtures rows: {len(runtime)}") print(f"advisories rows: {len(advisories)}") if trusts: print(f"trust min/max/mean: {min(trusts)}/{max(trusts)}/{sum(trusts)/len(trusts):.4f}") print(f"safety_label counts: {dict(labels)}") print(f"scanner_grade counts: {dict(grades)}") print(f"owner_verified true: {owner_true}") print(f"scanner_provider unique: {providers}") print(f"findings_high total: {high_total}") print(f"parquet written: {parquet_ok or 'none'}") print(f"snapshot_at: {snapshot_at}") if __name__ == "__main__": main()