Buckets:

download
raw
23.9 kB
"""CLI commands for crawling and scanning skills from ClawHub."""
from __future__ import annotations
import asyncio
import sys
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path
from typing import Annotated
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
app = typer.Typer(help="Crawl and scan skills from ClawHub registry.")
console = Console()
class CrawlFormat(StrEnum):
CONSOLE = "console"
JSON = "json"
SARIF = "sarif"
def _format_and_output(result, fmt: CrawlFormat, output: Path | None) -> None:
"""Format a scan result and write to output or stdout."""
if fmt == CrawlFormat.CONSOLE:
from malwar.cli.formatters.console import format_scan_result
format_scan_result(result)
elif fmt == CrawlFormat.JSON:
from malwar.cli.formatters.json_fmt import format_json
text = format_json(result)
_write(text, output)
elif fmt == CrawlFormat.SARIF:
from malwar.cli.formatters.sarif import format_sarif
text = format_sarif(result)
_write(text, output)
def _write(text: str, output: Path | None) -> None:
if output:
output.write_text(text)
typer.echo(f"Output written to {output}")
else:
sys.stdout.write(text + "\n")
@app.command(name="scan")
def crawl_scan(
slug: Annotated[str, typer.Argument(help="Skill slug on ClawHub")],
version: Annotated[
str | None,
typer.Option("--version", "-v", help="Specific skill version"),
] = None,
fmt: Annotated[
CrawlFormat,
typer.Option("--format", "-f", help="Output format"),
] = CrawlFormat.CONSOLE,
output: Annotated[
Path | None,
typer.Option("--output", "-o", help="Output file path"),
] = None,
no_llm: Annotated[
bool, typer.Option("--no-llm", help="Skip LLM analysis layer")
] = False,
no_urls: Annotated[
bool, typer.Option("--no-urls", help="Skip URL crawling layer")
] = False,
layers: Annotated[
str | None,
typer.Option("--layers", help="Comma-separated layers to run"),
] = None,
) -> None:
"""Fetch a skill from ClawHub and scan its SKILL.md for threats."""
exit_code = asyncio.run(
_async_crawl_scan(slug, version, fmt, output, no_llm, no_urls, layers)
)
raise typer.Exit(exit_code)
async def _async_crawl_scan(
slug: str,
version: str | None,
fmt: CrawlFormat,
output: Path | None,
no_llm: bool,
no_urls: bool,
layers_str: str | None,
) -> int:
from malwar.crawl.client import ClawHubClient, ClawHubError
from malwar.sdk import scan
client = ClawHubClient()
try:
console.print(f"Fetching SKILL.md for [bold]{slug}[/bold]...", style="dim")
content = await client.get_skill_file(slug, version=version)
except ClawHubError as exc:
console.print(f"[red]Error:[/red] {exc}")
return 1
layer_list: list[str] | None = None
if layers_str:
layer_list = [layer.strip() for layer in layers_str.split(",")]
result = await scan(
content,
file_name=f"clawhub:{slug}/SKILL.md",
use_llm=not no_llm,
use_urls=not no_urls,
layers=layer_list,
)
_format_and_output(result, fmt, output)
return 1 if result.risk_score >= 40 else 0
@app.command(name="search")
def crawl_search(
query: Annotated[str, typer.Argument(help="Search query")],
limit: Annotated[
int, typer.Option("--limit", "-n", help="Maximum results")
] = 20,
) -> None:
"""Search for skills on ClawHub."""
asyncio.run(_async_search(query, limit))
async def _async_search(query: str, limit: int) -> None:
from malwar.crawl.client import ClawHubClient, ClawHubError
client = ClawHubClient()
try:
results = await client.search(query, limit=limit)
except ClawHubError as exc:
console.print(f"[red]Error:[/red] {exc}")
raise typer.Exit(1) from None
if not results:
console.print(f"No skills found for [bold]{query}[/bold]")
return
table = Table(title=f"Search results for '{query}'")
table.add_column("Slug", style="cyan", no_wrap=True)
table.add_column("Name", style="bold")
table.add_column("Summary")
table.add_column("Version", justify="right")
table.add_column("Score", justify="right", style="dim")
for r in results:
table.add_row(
r.slug,
r.display_name,
r.summary[:60] + ("..." if len(r.summary) > 60 else ""),
r.version or "-",
f"{r.score:.1f}",
)
console.print(table)
console.print(
"\n Scan a skill: [bold]malwar crawl scan <slug>[/bold]",
style="dim",
)
@app.command(name="list")
def crawl_list(
limit: Annotated[
int, typer.Option("--limit", "-n", help="Number of skills to list")
] = 20,
cursor: Annotated[
str | None,
typer.Option("--cursor", help="Pagination cursor from previous request"),
] = None,
) -> None:
"""List skills from the ClawHub registry."""
asyncio.run(_async_list(limit, cursor))
async def _async_list(limit: int, cursor: str | None) -> None:
from malwar.crawl.client import ClawHubClient, ClawHubError
client = ClawHubClient()
try:
skills, next_cursor = await client.list_skills(limit=limit, cursor=cursor)
except ClawHubError as exc:
console.print(f"[red]Error:[/red] {exc}")
raise typer.Exit(1) from None
# The ClawHub /skills endpoint currently returns empty results;
# fall back to a broad search so users can still browse skills.
if not skills:
try:
results = await client.search("a", limit=limit)
except ClawHubError:
results = []
if not results:
console.print("No skills found.")
return
table = Table(title="ClawHub Skills")
table.add_column("Slug", style="cyan", no_wrap=True)
table.add_column("Name", style="bold")
table.add_column("Summary")
table.add_column("Score", justify="right", style="dim")
for r in results:
table.add_row(
r.slug,
r.display_name,
r.summary[:60] + ("..." if len(r.summary) > 60 else ""),
f"{r.score:.1f}",
)
console.print(table)
console.print(
"\n Scan a skill: [bold]malwar crawl scan <slug>[/bold]",
style="dim",
)
return
table = Table(title="ClawHub Skills")
table.add_column("Slug", style="cyan", no_wrap=True)
table.add_column("Name", style="bold")
table.add_column("Summary")
table.add_column("Version", justify="right")
table.add_column("Downloads", justify="right", style="dim")
for s in skills:
version = s.latest_version.version if s.latest_version else "-"
table.add_row(
s.slug,
s.display_name,
s.summary[:60] + ("..." if len(s.summary) > 60 else ""),
version,
str(s.stats.downloads),
)
console.print(table)
if next_cursor:
console.print(
f"\n Next page: [bold]malwar crawl list --cursor {next_cursor[:20]}...[/bold]",
style="dim",
)
@app.command(name="info")
def crawl_info(
slug: Annotated[str, typer.Argument(help="Skill slug on ClawHub")],
) -> None:
"""Show details and moderation status for a ClawHub skill."""
asyncio.run(_async_info(slug))
async def _async_info(slug: str) -> None:
from malwar.crawl.client import ClawHubClient, ClawHubError
client = ClawHubClient()
try:
detail = await client.get_skill(slug)
except ClawHubError as exc:
console.print(f"[red]Error:[/red] {exc}")
raise typer.Exit(1) from None
# Header panel
lines = [
f"Slug: {detail.slug}",
f"Name: {detail.display_name}",
f"Summary: {detail.summary}",
]
if detail.owner:
lines.append(f"Author: {detail.owner.username}")
if detail.latest_version:
lines.append(f"Version: {detail.latest_version.version}")
if detail.stats:
lines.append(
f"Stats: {detail.stats.downloads} downloads, "
f"{detail.stats.stars} stars, "
f"{detail.stats.versions} versions"
)
if detail.created_at:
created = datetime.fromtimestamp(detail.created_at / 1000, tz=UTC)
lines.append(f"Created: {created.strftime('%Y-%m-%d')}")
if detail.tags:
lines.append(f"Tags: {', '.join(f'{k}={v}' for k, v in detail.tags.items())}")
console.print(Panel("\n".join(lines), title=f"Skill: {detail.slug}"))
# Moderation status
if detail.moderation:
mod = detail.moderation
mod_lines = []
if mod.is_malware_blocked:
mod_lines.append("[bold red]BLOCKED: Malware detected by VirusTotal[/bold red]")
if mod.is_suspicious:
mod_lines.append("[yellow]SUSPICIOUS: Flagged for review[/yellow]")
if mod.is_pending_scan:
mod_lines.append("[cyan]PENDING: Awaiting security scan[/cyan]")
if mod.is_hidden_by_mod:
mod_lines.append("[red]HIDDEN: Hidden by moderator[/red]")
if mod.is_removed:
mod_lines.append("[red]REMOVED: Removed from registry[/red]")
if mod.reason:
mod_lines.append(f"Reason: {mod.reason}")
if mod_lines:
console.print(Panel(
"\n".join(mod_lines),
title="Moderation Status",
style="yellow",
))
else:
console.print("[bold green]Moderation: No flags[/bold green]")
else:
console.print("[dim]Moderation: No data available[/dim]")
console.print(
f"\n Scan this skill: [bold]malwar crawl scan {detail.slug}[/bold]",
style="dim",
)
@app.command(name="url")
def crawl_url(
url: Annotated[str, typer.Argument(help="URL to a SKILL.md file")],
fmt: Annotated[
CrawlFormat,
typer.Option("--format", "-f", help="Output format"),
] = CrawlFormat.CONSOLE,
output: Annotated[
Path | None,
typer.Option("--output", "-o", help="Output file path"),
] = None,
no_llm: Annotated[
bool, typer.Option("--no-llm", help="Skip LLM analysis layer")
] = False,
no_urls: Annotated[
bool, typer.Option("--no-urls", help="Skip URL crawling layer")
] = False,
layers: Annotated[
str | None,
typer.Option("--layers", help="Comma-separated layers to run"),
] = None,
) -> None:
"""Fetch a SKILL.md from any URL and scan it for threats."""
exit_code = asyncio.run(
_async_crawl_url(url, fmt, output, no_llm, no_urls, layers)
)
raise typer.Exit(exit_code)
async def _async_crawl_url(
url: str,
fmt: CrawlFormat,
output: Path | None,
no_llm: bool,
no_urls: bool,
layers_str: str | None,
) -> int:
from malwar.crawl.client import ClawHubError, fetch_url
from malwar.sdk import scan
try:
console.print(f"Fetching [bold]{url}[/bold]...", style="dim")
content = await fetch_url(url)
except ClawHubError as exc:
console.print(f"[red]Error:[/red] {exc}")
return 1
except Exception as exc:
console.print(f"[red]Error fetching URL:[/red] {exc}")
return 1
# Derive a file name from the URL
file_name = url.rsplit("/", 1)[-1] or "SKILL.md"
layer_list: list[str] | None = None
if layers_str:
layer_list = [layer.strip() for layer in layers_str.split(",")]
result = await scan(
content,
file_name=file_name,
use_llm=not no_llm,
use_urls=not no_urls,
layers=layer_list,
)
_format_and_output(result, fmt, output)
return 1 if result.risk_score >= 40 else 0
# ---------------------------------------------------------------------------
# Continuous registry monitoring
# ---------------------------------------------------------------------------
_DEFAULT_SNAPSHOT_DIR = "data/registry-snapshots"
def _render_diff_console(diff, snapshot) -> None:
"""Print a human-readable summary of a snapshot diff."""
summary = (
f"Skills scanned: [bold]{snapshot.skill_count}[/bold] "
f"Flagged: [bold]{snapshot.flagged_count}[/bold] "
f"Scan errors: [dim]{len(snapshot.errors)}[/dim]"
)
console.print(Panel(summary, title="Registry Snapshot"))
if diff.is_first_run:
console.print(
"[dim]First run — no previous snapshot to diff against. "
"Baseline saved.[/dim]"
)
if diff.newly_malicious:
table = Table(title="⚠ Newly flagged skills", style="red")
table.add_column("Slug", style="cyan", no_wrap=True)
table.add_column("Verdict", style="bold")
table.add_column("Risk", justify="right")
table.add_column("Installs", justify="right", style="dim")
table.add_column("Rules")
for r in diff.newly_malicious:
table.add_row(
r.slug,
r.verdict,
str(r.risk_score),
f"{r.installs:,}",
", ".join(r.finding_rule_ids[:4]),
)
console.print(table)
if diff.verdict_changed:
table = Table(title="Verdict changes")
table.add_column("Slug", style="cyan", no_wrap=True)
table.add_column("Change")
for c in diff.verdict_changed:
table.add_row(c.slug, c.detail)
console.print(table)
if diff.modified:
table = Table(title="Modified skills")
table.add_column("Slug", style="cyan", no_wrap=True)
table.add_column("Change")
for c in diff.modified:
table.add_row(c.slug, c.detail)
console.print(table)
counts = (
f"[green]+{len(diff.added)} added[/green] "
f"[red]-{len(diff.removed)} removed[/red] "
f"{len(diff.modified)} modified "
f"{len(diff.verdict_changed)} verdict changes"
)
console.print(counts)
@app.command(name="monitor")
def crawl_monitor(
snapshot_dir: Annotated[
Path,
typer.Option("--snapshot-dir", help="Directory holding snapshot history"),
] = Path(_DEFAULT_SNAPSHOT_DIR),
max_skills: Annotated[
int | None,
typer.Option("--max", help="Cap the number of skills scanned (testing)"),
] = None,
no_escalate: Annotated[
bool,
typer.Option("--no-escalate", help="Disable escalation (shorthand for --escalate-backend none)"),
] = False,
escalate_backend: Annotated[
str,
typer.Option(
"--escalate-backend",
help="Second-opinion backend for the ambiguous band: "
"none | hf (free local classifier) | anthropic (LLM) | "
"tiered (hf triage -> anthropic on hits)",
),
] = "anthropic",
escalate_budget: Annotated[
int | None,
typer.Option(
"--escalate-budget",
help="Cap how many skills are escalated per run (most-suspicious first)",
),
] = None,
concurrency: Annotated[
int, typer.Option("--concurrency", help="Skills scanned in parallel")
] = 8,
fmt: Annotated[
CrawlFormat, typer.Option("--format", "-f", help="Output format")
] = CrawlFormat.CONSOLE,
output: Annotated[
Path | None,
typer.Option("--output", "-o", help="Write the JSON diff to this file"),
] = None,
no_save: Annotated[
bool,
typer.Option("--no-save", help="Do not persist the new snapshot"),
] = False,
digest: Annotated[
bool,
typer.Option(
"--digest",
help="Also print a shareable digest + draft post (for review before publishing)",
),
] = False,
publish: Annotated[
bool,
typer.Option(
"--publish",
help="Post the digest to X when skills newly turn malicious (requires X API creds)",
),
] = False,
fail_on_malicious: Annotated[
bool,
typer.Option(
"--fail-on-malicious",
help="Exit non-zero when newly-flagged skills are found",
),
] = False,
full: Annotated[
bool,
typer.Option(
"--full",
help="Re-scan every skill instead of only changed ones "
"(defends against silent same-version content swaps)",
),
] = False,
max_scans: Annotated[
int | None,
typer.Option(
"--max-scans",
help="Cap skills scanned per run; the overflow is deferred and "
"picked up next run. Lets a large registry build up over runs "
"instead of timing out.",
),
] = None,
page_size: Annotated[
int,
typer.Option(
"--page-size",
help="Skills requested per registry listing page. Larger pages mean "
"fewer requests to enumerate the whole registry (the API returns its "
"own maximum if this exceeds it).",
),
] = 100,
no_enrich: Annotated[
bool,
typer.Option(
"--no-enrich",
help="Skip fetching publisher and platform moderation state for "
"flagged skills (saves one request each, loses attribution).",
),
] = False,
enrich_backfill: Annotated[
int,
typer.Option(
"--enrich-backfill",
help="Per-run cap on attributing already-flagged skills from earlier "
"snapshots, so the existing flagged tail is covered over a bounded "
"number of runs rather than whenever the rescan rotation reaches it.",
),
] = 500,
) -> None:
"""Scan the registry incrementally and diff against the last snapshot.
Designed to run on a schedule (e.g. daily): it crawls the whole registry
but only re-fetches and re-scans skills whose version changed since the last
snapshot (escalating flagged ones to the LLM), diffs the result, and reports
what changed — with a headline list of skills that newly turned malicious.
The first run scans everything. Pass ``--full`` on a periodic cadence (e.g.
weekly) to re-scan every skill and catch silent same-version tampering.
"""
exit_code = asyncio.run(
_async_monitor(
snapshot_dir=snapshot_dir,
max_skills=max_skills,
escalate_backend="none" if no_escalate else escalate_backend,
escalate_budget=escalate_budget,
concurrency=concurrency,
fmt=fmt,
output=output,
save=not no_save,
digest=digest,
publish=publish,
fail_on_malicious=fail_on_malicious,
full=full,
max_scans=max_scans,
page_size=page_size,
enrich_flagged=not no_enrich,
enrich_backfill=enrich_backfill,
)
)
raise typer.Exit(exit_code)
async def _async_monitor(
*,
snapshot_dir: Path,
max_skills: int | None,
escalate_backend: str,
escalate_budget: int | None,
concurrency: int,
fmt: CrawlFormat,
output: Path | None,
save: bool,
digest: bool,
publish: bool,
fail_on_malicious: bool,
full: bool = False,
max_scans: int | None = None,
page_size: int = 100,
enrich_flagged: bool = True,
enrich_backfill: int = 500,
) -> int:
from rich.progress import BarColumn, Progress, TextColumn
from malwar.monitor import (
EscalationPolicy,
SnapshotStore,
build_snapshot,
diff_snapshots,
make_backend,
)
store = SnapshotStore(snapshot_dir)
previous = store.load_latest()
try:
backend = make_backend(escalate_backend)
except ValueError as exc:
console.print(f"[red]{exc}[/red]")
return 2
policy = EscalationPolicy(budget=escalate_budget)
mode = "full re-scan" if full else ("incremental" if previous else "first run")
scope = f" (max {max_skills})" if max_skills else ""
console.print(f"Crawling ClawHub registry{scope} [{mode}]...", style="dim")
with Progress(
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("{task.completed}/{task.total}"),
console=console,
transient=True,
) as progress:
task_id = progress.add_task("Scanning skills", total=None)
def _on_progress(done: int, total: int, slug: str) -> None:
progress.update(
task_id, total=total, completed=done, description=f"Scanning {slug}"
)
snapshot = await build_snapshot(
previous=previous,
force_rescan=full,
max_skills=max_skills,
scan_budget=max_scans,
escalation=backend,
escalation_policy=policy,
concurrency=concurrency,
page_size=page_size,
enrich_flagged=enrich_flagged,
enrich_backfill_limit=enrich_backfill,
on_progress=_on_progress,
)
if snapshot.skill_count == 0:
console.print("[yellow]No skills found in the registry.[/yellow]")
return 0
summary = (
f"[dim]Scanned {snapshot.scanned_count} changed/new, "
f"reused {snapshot.reused_count} unchanged"
)
if snapshot.pending_count:
summary += f", deferred {snapshot.pending_count} to next run"
if snapshot.escalated_count:
summary += f", escalated {snapshot.escalated_count} to '{backend.name}'"
if snapshot.attributed_count:
summary += (
f", attributed {snapshot.attributed_count} flagged "
f"({snapshot.unblocked_malicious_count} malicious unblocked upstream)"
)
console.print(summary + ".[/dim]")
diff = diff_snapshots(previous, snapshot)
if save:
archive = store.save(snapshot)
console.print(f"[dim]Snapshot saved to {archive}[/dim]")
if fmt == CrawlFormat.JSON:
import json
payload = json.dumps(diff.model_dump(), indent=2, sort_keys=True)
_write(payload, output)
else:
_render_diff_console(diff, snapshot)
if digest or publish:
from malwar.monitor import render_digest, render_tweet
console.print(Panel(render_digest(diff, snapshot), title="Shareable digest"))
tweet = render_tweet(diff, snapshot)
console.print(
Panel(tweet, title="Draft post (review before publishing)", style="dim")
)
if publish:
await _publish_to_x(diff, snapshot)
if fail_on_malicious and diff.newly_malicious:
return 1
return 0
async def _publish_to_x(diff, snapshot) -> None:
"""Post the digest to X — only when something newly turned malicious."""
from malwar.monitor import render_tweet
from malwar.notifications.x_channel import XPublisher
if not diff.newly_malicious:
console.print("[dim]Nothing newly flagged — skipping X post.[/dim]")
return
publisher = XPublisher.from_settings()
if not publisher.is_configured():
console.print(
"[yellow]--publish set but X API credentials are missing "
"(set MALWAR_X_API_KEY / _API_SECRET / _ACCESS_TOKEN / "
"_ACCESS_TOKEN_SECRET); skipping post.[/yellow]"
)
return
ok = await publisher.post(render_tweet(diff, snapshot))
if ok:
console.print("[green]Posted threat digest to X.[/green]")
else:
console.print("[red]Failed to post to X (see logs).[/red]")

Xet Storage Details

Size:
23.9 kB
·
Xet hash:
7102bffafaea02611b8a97b43c1a4f8fd721b400b18333ec15f0d0f46d21f0b3

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.