Exploit database

GH-de79f9bc167cd9df0000aa805acd65ba

rakib-nyc/nullorigin

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2021-42574

11 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files6
rakib-nyc/nulloriginRevision c2d68bb79550

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

nullorigin/cli.py

Suggested starting filePython · 30,834 bytes
"""
NullOrigin command-line interface.

Author: Muhammad Rakibul Islam <[email protected]>
License: Apache-2.0
"""

import asyncio
import json
import sys
from pathlib import Path

import click

from nullorigin import __version__
from nullorigin.config import load_config

IMAGE_EXTENSIONS = {
    ".png", ".jpg", ".jpeg", ".jfif", ".webp", ".tif", ".tiff",
    ".bmp", ".gif", ".ico", ".avif", ".jp2", ".j2k", ".ppm", ".pgm", ".tga",
}
AUDIO_EXTENSIONS = {".wav", ".wave"}
# All three OOXML dialects share the same ZIP-of-XML structure.
OOXML_EXTENSIONS = {".docx", ".docm", ".dotx", ".pptx", ".pptm", ".xlsx", ".xlsm"}
PDF_EXTENSIONS = {".pdf"}

from nullorigin.engines.code import CODE_EXTENSIONS  # noqa: E402

# Formats we cannot safely round-trip. Each carries a specific reason so the
# refusal tells the user what to do instead of just saying "no".
UNSUPPORTED_BINARY = {
    ".doc": "legacy Word (OLE2) predates OOXML; re-save as .docx",
    ".ppt": "legacy PowerPoint (OLE2); re-save as .pptx",
    ".xls": "legacy Excel (OLE2); re-save as .xlsx",
    ".rtf": "RTF is not a ZIP container; re-save as .docx",
    ".odt": "OpenDocument; re-save as .docx",
    ".odp": "OpenDocument; re-save as .pptx",
    ".ods": "OpenDocument; re-save as .xlsx",
    ".pages": "Apple Pages; export as .docx",
    ".key": "Apple Keynote; export as .pptx",
    ".numbers": "Apple Numbers; export as .xlsx",
    ".mp3": "compressed audio; convert to .wav (ffmpeg -i in.mp3 out.wav)",
    ".m4a": "compressed audio; convert to .wav",
    ".aac": "compressed audio; convert to .wav",
    ".ogg": "compressed audio; convert to .wav",
    ".opus": "compressed audio; convert to .wav",
    ".flac": "lossless compressed audio; convert to .wav",
    ".aiff": "AIFF; convert to .wav",
    ".mp4": "video is not supported",
    ".mov": "video is not supported",
    ".mkv": "video is not supported",
    ".avi": "video is not supported",
    ".webm": "video is not supported",
    ".heic": "HEIC needs pillow-heif; convert to .png or .jpg",
    ".heif": "HEIF needs pillow-heif; convert to .png or .jpg",
    ".zip": "archives are not supported; extract and sanitize the contents",
    ".tar": "archives are not supported; extract and sanitize the contents",
    ".gz": "archives are not supported; extract and sanitize the contents",
}

# Byte-order marks and their encodings, longest first so UTF-32 is not mistaken
# for UTF-16.
# The BOM-aware codec names ("utf-16", not "utf-16-le") are used deliberately:
# they strip the BOM on read and re-emit one on write, so the mark does not end
# up as a stray U+FEFF inside the text. Byte order may normalize to the
# platform default on round-trip; the file stays valid either way.
_BOMS = (
    (b"\x00\x00\xfe\xff", "utf-32"),
    (b"\xff\xfe\x00\x00", "utf-32"),
    (b"\xef\xbb\xbf", "utf-8-sig"),
    (b"\xfe\xff", "utf-16"),
    (b"\xff\xfe", "utf-16"),
)

_MIME_BY_EXT = {
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".webp": "image/webp",
    ".tiff": "image/tiff",
    ".bmp": "image/bmp",
    ".gif": "image/gif",
}


@click.group()
@click.version_option(__version__, prog_name="nullorigin")
def main():
    """NullOrigin: Universal AI Provenance & Watermark Sanitization Suite."""


@main.command()
@click.option("--host", default=None, help="Host to bind the proxy server to.")
@click.option("--port", default=None, type=int, help="Port to run the proxy server on.")
@click.option("--config", default=None, help="Path to the configuration file.")
@click.option("--reload", is_flag=True, help="Enable auto-reload (development only).")
@click.option("--log-level", default="info", help="Uvicorn log level.")
@click.option(
    "--allow-public-bind",
    is_flag=True,
    help="Acknowledge binding a non-loopback interface without a telemetry token.",
)
def run(host, port, config, reload, log_level, allow_public_bind):
    """Start the NullOrigin reverse proxy server."""
    import uvicorn

    cfg = load_config(config, strict=config is not None)
    bind_host = host or cfg.proxy.host
    bind_port = port or cfg.proxy.port

    # This proxy relays upstream API keys and exposes a telemetry reset. Binding
    # beyond loopback without a token is almost never intended, so it must be
    # stated explicitly rather than happening by default.
    public = bind_host not in ("127.0.0.1", "localhost", "::1")
    if public and not cfg.proxy.telemetry_token and not allow_public_bind:
        raise click.ClickException(
            f"Refusing to bind {bind_host} without a telemetry token.\n\n"
            "This proxy forwards upstream API credentials and exposes "
            "/telemetry/reset. On a non-loopback interface those are reachable "
            "by anyone who can route to this host.\n\n"
            "Choose one:\n"
            "  - bind loopback:    nullorigin run --host 127.0.0.1\n"
            "  - set a token:      export NULLORIGIN_TELEMETRY_TOKEN=$(openssl rand -hex 32)\n"
            "  - accept the risk:  nullorigin run --host "
            f"{bind_host} --allow-public-bind\n\n"
            "There is still no TLS: run behind a reverse proxy that terminates HTTPS."
        )

    from nullorigin.proxy.server import app, set_config

    set_config(cfg)

    click.echo(f"NullOrigin {__version__} — proxy listening on {bind_host}:{bind_port}")
    click.echo(f"  providers:   {', '.join(sorted(cfg.proxy.upstream_map))}")
    click.echo(f"  text engine: unicode={cfg.text.clean_unicode} backend={cfg.text.paraphraser.backend}")
    click.echo(f"  media:       metadata={cfg.media.purge_metadata} stego={cfg.media.disrupt_stego}")
    click.echo(f"  telemetry:   {'token required' if cfg.proxy.telemetry_token else 'open (loopback)'}")
    click.echo(f"  health:      http://{bind_host}:{bind_port}/health")
    if public:
        click.secho(
            "  WARNING:     bound to a non-loopback interface over plain HTTP; "
            "terminate TLS upstream.",
            fg="yellow",
        )

    uvicorn.run(app, host=bind_host, port=bind_port, reload=reload, log_level=log_level)


@main.command()
@click.argument("input_file", type=click.Path(exists=True, dir_okay=False))
@click.option("--output", "-o", required=True, help="Path to save the sanitized output file.")
@click.option("--config", default=None, help="Path to the configuration file.")
@click.option(
    "--no-paraphrase", is_flag=True, help="Skip semantic restructuring for text inputs."
)
@click.option(
    "--flatten-typography",
    is_flag=True,
    help="Also convert em dashes, curly quotes, and ellipses to ASCII. Off by "
         "default: these are ordinary typography, not provenance markers.",
)
@click.option(
    "--strip-annotations",
    is_flag=True,
    help="PDF only: also remove annotations. Off by default because these "
         "include links and form fields, not only comments.",
)
@click.option(
    "--fold-homoglyphs-in-code",
    is_flag=True,
    help="Source code only: also fold confusable characters. Off by default "
         "because folding merges identifiers the compiler treats as distinct.",
)
@click.option("--verify", is_flag=True, help="Report before/after watermark measurements.")
def purge(
    input_file, output, config, no_paraphrase, flatten_typography, strip_annotations,
    fold_homoglyphs_in_code, verify,
):
    """Purge AI watermarks, C2PA/EXIF metadata, and hidden tokens from a file."""
    cfg = load_config(config, strict=config is not None)
    src = Path(input_file)
    dst = Path(output)
    dst.parent.mkdir(parents=True, exist_ok=True)
    ext = src.suffix.lower()

    if ext in IMAGE_EXTENSIONS:
        _purge_image(src, dst, cfg, verify)
    elif ext in AUDIO_EXTENSIONS:
        _purge_audio(src, dst, cfg, verify)
    elif ext in OOXML_EXTENSIONS:
        _purge_docx(src, dst, cfg, flatten_typography, verify)
    elif ext in PDF_EXTENSIONS:
        _purge_pdf(src, dst, cfg, strip_annotations, verify)
    elif ext in CODE_EXTENSIONS:
        _purge_code(src, dst, cfg, fold_homoglyphs_in_code, verify)
    elif ext in UNSUPPORTED_BINARY:
        raise click.ClickException(
            f"{src.suffix} is not supported: {UNSUPPORTED_BINARY[ext]}.\n\n"
            "Reading it as text would corrupt it, so NullOrigin refuses rather "
            "than producing a damaged file."
        )
    else:
        _purge_text(src, dst, cfg, no_paraphrase, flatten_typography, verify)


def read_text_any_encoding(src: Path) -> tuple[str, str]:
    """Decode a text file, honoring BOMs and falling back sensibly.

    UTF-16 and Latin-1 files are perfectly ordinary text; refusing them because
    they are not UTF-8 would be wrong. Genuinely binary input still fails, and
    the caller turns that into a clean refusal.
    """
    raw = src.read_bytes()
    if not raw:
        return "", "utf-8"

    for bom, encoding in _BOMS:
        if raw.startswith(bom):
            return raw.decode(encoding), encoding

    # A NUL byte in the first block means binary, not text in an odd encoding.
    if b"\x00" in raw[:8192] and not raw[:4].startswith((b"\xff", b"\xfe")):
        raise click.ClickException(
            f"{src.name} appears to be binary (NUL byte found), not text.\n\n"
            "Supported inputs: text, images (.png/.jpg/.webp/.gif/.tiff/...), "
            "audio (.wav), and Office documents (.docx/.pptx/.xlsx)."
        )

    # Order matters. Bare UTF-16 is deliberately NOT tried here: it decodes any
    # even-length byte string into garbage, so it would swallow every Latin-1
    # file with an even byte count. UTF-16 is only honored via its BOM above,
    # and NUL-heavy input has already been rejected as binary.
    for encoding in ("utf-8", "cp1252", "latin-1"):
        try:
            return raw.decode(encoding), encoding
        except (UnicodeDecodeError, UnicodeError):
            continue

    raise click.ClickException(
        f"{src.name} could not be decoded as text in any common encoding.\n\n"
        "Supported inputs: text, images, audio (.wav), and Office documents."
    )


def _purge_code(src: Path, dst: Path, cfg, fold_homoglyphs: bool, verify: bool) -> None:
    from nullorigin.engines.code import purge_code

    click.echo(f"Scanning source file {src}...")
    content, encoding = read_text_any_encoding(src)

    # Deliberately not the plain-text path: no NFKC (it rewrites string literal
    # values) and no paraphrasing (it produces code that does not run).
    cleaned, report = purge_code(
        content, fold_homoglyphs=fold_homoglyphs, path=str(src)
    )
    dst.write_text(cleaned, encoding=encoding)

    click.echo(f"  bidi controls removed:   {report.bidi_controls}")
    click.echo(f"  invisible chars removed: {report.invisible_characters}")
    click.echo(
        f"  homoglyphs in identifiers: {report.homoglyph_identifiers} "
        f"({'folded' if fold_homoglyphs else 'reported only'})"
    )
    click.echo(f"Saved clean source to {dst}")

    if report.trojan_source:
        click.secho(
            f"\n  TROJAN SOURCE DETECTED (CVE-2021-42574): {report.bidi_controls} "
            "bidirectional control character(s).\n"
            "  This file rendered differently than it compiled. Review the diff.",
            fg="red",
            bold=True,
            err=True,
        )

    if report.homoglyph_identifiers and not fold_homoglyphs:
        click.secho(
            f"\n  WARNING: {report.homoglyph_identifiers} confusable character(s) in "
            "identifiers were left in place.\n"
            "  Folding them would merge names the compiler currently treats as "
            "distinct, which\n  changes behavior. Review them, then re-run with "
            "--fold-homoglyphs-in-code if correct.",
            fg="yellow",
            err=True,
        )

    if verify and report.findings:
        click.echo("\nFindings:")
        for finding in report.sorted_findings():
            click.echo(f"  {finding}")
            click.echo(f"      {finding.line_text.strip()[:88]}")


def _purge_pdf(src: Path, dst: Path, cfg, strip_annotations: bool, verify: bool) -> None:
    from nullorigin.engines.document import (
        PdfEncrypted,
        PdfSupportMissing,
        inspect_pdf,
        purge_pdf,
    )

    click.echo(f"Sanitizing PDF {src}...")
    try:
        before = inspect_pdf(src) if verify else None
        clean, report = purge_pdf(
            src,
            strip_metadata=cfg.media.purge_metadata,
            strip_annotations=strip_annotations,
        )
    except PdfSupportMissing as exc:
        raise click.ClickException(str(exc)) from None
    except PdfEncrypted as exc:
        raise click.ClickException(str(exc)) from None
    except ValueError as exc:
        raise click.ClickException(f"{src.name}: {exc}") from None

    dst.write_bytes(clean)
    click.echo(f"  pages preserved:        {report.pages}")
    click.echo(f"  metadata fields cleared: {len(report.info_fields_cleared)}")
    click.echo(f"  XMP packet removed:      {report.xmp_removed}")
    if report.embedded_files or report.javascript_actions:
        click.echo(
            f"  attachments/JavaScript removed: "
            f"{report.embedded_files}/{report.javascript_actions}"
        )
    click.echo(f"Saved clean PDF to {dst} ({src.stat().st_size} -> {len(clean)} bytes)")

    # Invisible characters inside content streams are detected, not removed.
    # Saying so matters: silence here would read as "there were none".
    if report.invisible_characters or report.homoglyph_confusables:
        click.secho(
            f"\n  NOTE: {report.invisible_characters} invisible character(s) and "
            f"{report.homoglyph_confusables} homoglyph(s) remain in the page text.\n"
            "  PDF draws text glyph by glyph through a font-specific encoding, so "
            "these\n  cannot be rewritten in place without corrupting the layout. To "
            "remove them,\n  extract the text, run `nullorigin purge` on it, and "
            "regenerate the PDF.",
            fg="yellow",
        )

    if verify:
        after = inspect_pdf(clean)
        click.echo("\nVerification:")
        click.echo(f"  /Info fields: {len(before.info_fields)} -> {len(after.info_fields)}")
        click.echo(f"  XMP present:  {before.had_xmp} -> {after.had_xmp}")
        click.echo(f"  pages:        {before.pages} -> {after.pages}")
        click.echo(f"  attachments:  {before.embedded_files} -> {after.embedded_files}")
        click.echo(f"  JavaScript:   {before.javascript_actions} -> {after.javascript_actions}")
        if before.info_fields:
            click.echo(f"  cleared: {', '.join(sorted(before.info_fields))}")
        if not before.found_anything:
            click.secho(
                "\n  No provenance indicators were present in the original.",
                fg="green",
            )


def _purge_docx(src: Path, dst: Path, cfg, flatten_typography: bool, verify: bool) -> None:
    from nullorigin.engines.document import inspect_docx, purge_docx

    click.echo(f"Sanitizing Word document {src}...")
    before = inspect_docx(src) if verify else None

    clean, report = purge_docx(
        src,
        fold_homoglyphs=cfg.text.fold_homoglyphs,
        flatten_typography=flatten_typography,
        strip_metadata=cfg.media.purge_metadata,
    )
    dst.write_bytes(clean)

    click.echo(f"  invisible characters removed: {report.invisible_removed}")
    click.echo(f"  homoglyph confusables folded: {report.homoglyphs_folded}")
    if flatten_typography:
        click.echo(f"  typography flattened:         {report.typography_flattened}")
    click.echo(f"  metadata fields cleared:      {len(report.metadata_fields_cleared)}")
    click.echo(f"Saved clean document to {dst}")

    if verify:
        after = inspect_docx(clean)
        click.echo("\nVerification:")
        click.echo(f"  invisible chars: {before.invisible_removed} -> {after.invisible_removed}")
        click.echo(f"  confusables:     {before.homoglyphs_folded} -> {after.homoglyphs_folded}")
        click.echo(f"  metadata fields: {len(before.metadata)} -> {len(after.metadata)}")
        if report.metadata_fields_cleared:
            click.echo(f"  cleared: {', '.join(report.metadata_fields_cleared)}")
        if not before.found_anything:
            click.secho(
                "\n  No provenance indicators were present in the original. "
                "Nothing was removed because there was nothing to remove.",
                fg="green",
            )


def _image_error(src: Path, exc: Exception) -> str:
    return (
        f"{src.name} could not be decoded as an image "
        f"({type(exc).__name__}: {exc}).\n\n"
        "The file may be truncated, corrupt, or in a format this Pillow build "
        "does not support."
    )


def _stego_options(cfg) -> dict:
    return {
        "crop_ratio": cfg.media.crop_ratio,
        "crop_mode": cfg.media.crop_mode,
        "dwt_threshold": cfg.media.dwt_threshold,
        "fourier_strength": cfg.media.fourier_strength,
        "dither_sigma": cfg.media.dither_sigma,
    }


def _purge_image(src: Path, dst: Path, cfg, verify: bool) -> None:
    from PIL import UnidentifiedImageError

    from nullorigin.engines.media.c2pa_remover import inspect_metadata, purge_c2pa_metadata

    raw = src.read_bytes()
    click.echo(f"Purging provenance metadata and steganography from {src}...")
    out_mime = _MIME_BY_EXT.get(dst.suffix.lower())

    try:
        before = inspect_metadata(raw) if verify else None
        clean = purge_c2pa_metadata(
            raw,
            mime_type=out_mime,
            disrupt_stego=cfg.media.disrupt_stego,
            stego_options=_stego_options(cfg),
        )
    except (UnidentifiedImageError, OSError, ValueError) as exc:
        raise click.ClickException(_image_error(src, exc)) from None

    dst.write_bytes(clean)
    click.echo(f"Saved clean image to {dst} ({len(raw)} -> {len(clean)} bytes)")

    if verify:
        from nullorigin.evaluation.metrics import (
            align_for_comparison,
            calculate_psnr,
            calculate_ssim,
            image_arrays,
        )

        after = inspect_metadata(clean)
        click.echo("\nVerification:")
        click.echo(
            f"  metadata before: {sorted(set(before['text_chunks']) | set(before['info_keys']))}"
        )
        click.echo(
            f"  metadata after:  {sorted(set(after['text_chunks']) | set(after['info_keys']))}"
        )
        click.echo(f"  EXIF before/after: {bool(before['exif'])} -> {bool(after['exif'])}")
        click.echo(
            f"  C2PA marker before/after: "
            f"{before['has_c2pa_marker']} -> {after['has_c2pa_marker']}"
        )
        try:
            a, b = align_for_comparison(image_arrays(raw), image_arrays(clean))
            click.echo(f"  SSIM: {calculate_ssim(a, b):.4f}   PSNR: {calculate_psnr(a, b):.2f} dB")
        except (ValueError, OSError) as exc:
            click.echo(f"  (quality metrics unavailable: {exc})")


def _purge_audio(src: Path, dst: Path, cfg, verify: bool) -> None:
    from nullorigin.engines.audio.audio_cleaner import audio_snr_db, disrupt_audio_watermarks

    click.echo(f"Neutralizing acoustic watermarks in {src}...")
    raw = src.read_bytes()
    clean = disrupt_audio_watermarks(
        raw,
        low_cut_hz=cfg.audio.low_cut_hz,
        max_shift_rad=cfg.audio.max_shift_rad,
        notch_bands=cfg.audio.notch_bands,
    )
    dst.write_bytes(clean)
    click.echo(f"Saved clean audio to {dst}")

    if verify:
        snr = audio_snr_db(raw, clean)
        click.echo("\nVerification:")
        click.echo(f"  SNR vs original: {snr:.2f} dB" if snr is not None else "  SNR: unavailable")


def _purge_text(
    src: Path, dst: Path, cfg, no_paraphrase: bool, flatten_typography: bool, verify: bool
) -> None:
    from nullorigin.engines.text.kgw_detector import KGWStatisticalDetector
    from nullorigin.engines.text.paraphraser import StatisticalTextNeutralizer
    from nullorigin.engines.text.unicode_cleaner import clean_unicode_artifacts

    click.echo(f"Cleaning text structure and token transitions in {src}...")
    content, encoding = read_text_any_encoding(src)
    if encoding not in ("utf-8", "utf-8-sig"):
        click.echo(f"  detected encoding: {encoding}")
    detector = KGWStatisticalDetector(
        gamma=cfg.text.kgw.gamma,
        hash_key=cfg.text.kgw.hash_key,
        threshold=cfg.text.kgw.detection_threshold,
    )
    before = detector.detect(content) if verify else None

    cleaned, report = clean_unicode_artifacts(
        content,
        fold_homoglyphs=cfg.text.fold_homoglyphs,
        flatten_typography=flatten_typography,
    )
    click.echo(
        f"  removed {report.invisible_removed} invisible characters, "
        f"folded {report.homoglyphs_folded} homoglyphs"
    )

    if not no_paraphrase:
        neutralizer = StatisticalTextNeutralizer.from_settings(cfg)
        if neutralizer.enabled:
            click.echo(
                f"  applying semantic restructuring via {neutralizer.backend.name} backend..."
            )
            result = asyncio.run(neutralizer.neutralize(cleaned))
            if result.ok:
                cleaned = result.text
                click.echo("  restructuring complete")
            else:
                # Surfacing this matters: a silent fallback looks identical to a
                # successful rewrite but leaves the statistical watermark intact.
                click.secho(
                    f"  WARNING: {neutralizer.backend.name} backend unavailable "
                    f"({result.error}). Statistical watermark NOT neutralized; "
                    f"only unicode artifacts were removed.",
                    fg="yellow",
                    err=True,
                )
        else:
            click.echo("  paraphrase backend disabled; unicode cleaning only")

    # Write back in the encoding it arrived in, so a UTF-16 file stays UTF-16.
    dst.write_text(cleaned, encoding=encoding)
    click.echo(f"Saved clean text to {dst}")

    if verify:
        after = detector.detect(cleaned)
        click.echo("\nVerification (KGW statistical detector):")
        click.echo(f"  z-score before: {before.z_score:+.4f}  (p={before.p_value:.3g})")
        click.echo(f"  z-score after:  {after.z_score:+.4f}  (p={after.p_value:.3g})")
        click.echo(f"  detected before/after (z>{detector.threshold}): "
                   f"{before.is_watermarked} -> {after.is_watermarked}")


@main.command()
@click.argument("input_file", type=click.Path(exists=True, dir_okay=False))
@click.option("--config", default=None, help="Path to the configuration file.")
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON.")
def inspect(input_file, config, as_json):
    """Report provenance indicators in a file without modifying it."""
    cfg = load_config(config, strict=config is not None)
    src = Path(input_file)
    ext = src.suffix.lower()

    if ext in IMAGE_EXTENSIONS:
        from PIL import UnidentifiedImageError

        from nullorigin.engines.media.c2pa_remover import inspect_metadata

        try:
            result = inspect_metadata(src.read_bytes())
        except (UnidentifiedImageError, OSError, ValueError) as exc:
            raise click.ClickException(_image_error(src, exc)) from None
        result["size"] = list(result.get("size", ()))
    elif ext in AUDIO_EXTENSIONS:
        result = {"type": "audio", "bytes": src.stat().st_size,
                  "note": "No public acoustic watermark detector is implemented."}
    elif ext in OOXML_EXTENSIONS:
        from nullorigin.engines.document import inspect_docx

        report = inspect_docx(src)
        result = {
            "type": "ooxml_document",
            "words": report.word_count,
            "characters": report.character_count,
            "invisible_characters": report.invisible_removed,
            "invisible_detail": report.invisible_detail,
            "homoglyph_confusables": report.homoglyphs_folded,
            "homoglyph_detail": report.homoglyph_detail,
            "typography_characters": report.typography_flattened,
            "metadata": report.metadata,
            "provenance_found": report.found_anything,
            "note": (
                "Typography (em dashes, curly quotes) is counted separately and is "
                "not a provenance indicator."
            ),
        }
    elif ext in CODE_EXTENSIONS:
        from nullorigin.engines.code import scan_code

        content, encoding = read_text_any_encoding(src)
        report = scan_code(content, path=str(src))
        result = {
            "type": "source_code",
            "encoding": encoding,
            "lines": report.lines,
            "trojan_source": report.trojan_source,
            "bidi_controls": report.bidi_controls,
            "invisible_characters": report.invisible_characters,
            "homoglyphs_in_identifiers": report.homoglyph_identifiers,
            "homoglyphs_elsewhere": report.homoglyph_other,
            "worst_severity": report.worst_severity,
            "findings": [
                {
                    "severity": f.severity,
                    "kind": f.kind,
                    "codepoint": f.codepoint,
                    "name": f.name,
                    "line": f.line,
                    "column": f.column,
                    "detail": f.detail,
                }
                for f in report.sorted_findings()
            ],
            "note": (
                "No provider watermarks generated source code, and no public "
                "detector exists. This scan reports invisible and deceptive "
                "characters, which is a security concern rather than a "
                "provenance one."
            ),
        }
    elif ext in PDF_EXTENSIONS:
        from nullorigin.engines.document import PdfEncrypted, PdfSupportMissing, inspect_pdf

        try:
            report = inspect_pdf(src)
        except (PdfSupportMissing, PdfEncrypted) as exc:
            raise click.ClickException(str(exc)) from None
        except ValueError as exc:
            raise click.ClickException(f"{src.name}: {exc}") from None
        result = {
            "type": "pdf",
            "pages": report.pages,
            "words": report.word_count,
            "characters": report.character_count,
            "text_extractable": report.text_extractable,
            "info_fields": report.info_fields,
            "xmp_present": report.had_xmp,
            "embedded_files": report.embedded_files,
            "javascript_actions": report.javascript_actions,
            "annotations": report.annotations,
            "invisible_characters": report.invisible_characters,
            "invisible_detail": report.invisible_detail,
            "homoglyph_confusables": report.homoglyph_confusables,
            "typography_characters": report.typography_characters,
            "provenance_found": report.found_anything,
            "note": (
                "Invisible characters in page content streams are detected but not "
                "removed by `purge`; PDF text is font-encoded and cannot be rewritten "
                "in place safely."
            ),
        }
    elif ext in UNSUPPORTED_BINARY:
        raise click.ClickException(
            f"{src.suffix} is not supported: {UNSUPPORTED_BINARY[ext]}."
        )
    else:
        from nullorigin.engines.text.kgw_detector import KGWStatisticalDetector
        from nullorigin.engines.text.unicode_cleaner import count_invisible_tokens

        content, encoding = read_text_any_encoding(src)
        detector = KGWStatisticalDetector(
            gamma=cfg.text.kgw.gamma,
            hash_key=cfg.text.kgw.hash_key,
            threshold=cfg.text.kgw.detection_threshold,
        )
        detection = detector.detect(content)
        result = {
            "type": "text",
            "encoding": encoding,
            "characters": len(content),
            "invisible_characters": count_invisible_tokens(content),
            "kgw_z_score": round(detection.z_score, 4),
            "kgw_p_value": detection.p_value,
            "kgw_green_fraction": round(detection.green_fraction, 4),
            "kgw_detected": detection.is_watermarked,
            "note": (
                "KGW scoring uses NullOrigin's own key and tokenizer; it detects "
                "watermarks embedded by this suite, not a vendor's production watermark."
            ),
        }

    if as_json:
        click.echo(json.dumps(result, indent=2, default=str))
    else:
        for key, value in result.items():
            click.echo(f"{key}: {value}")


@main.command()
@click.option("--dataset", default=None, help="Path to the dataset root directory.")
@click.option("--config", default=None, help="Path to the configuration file.")
@click.option("--output", "-o", default=None, help="Write the full report as JSON to this path.")
@click.option(
    "--section",
    "sections",
    multiple=True,
    type=click.Choice(["text", "media", "audio"]),
    help="Limit the run to specific sections (repeatable).",
)
def benchmark(dataset, config, output, sections):
    """Measure sanitization effectiveness and quality against the fixtures."""
    from nullorigin.evaluation.runner import run_benchmarks

    report = run_benchmarks(
        dataset_path=dataset,
        config_path=config,
        output_json=output,
        sections=list(sections) if sections else None,
    )
    sys.exit(0 if report.verdicts.get("overall_pass") else 1)


@main.command("build-datasets")
@click.option("--root", default="datasets", help="Directory to write fixtures into.")
def build_datasets(root):
    """Regenerate the synthetic evaluation fixtures."""
    from nullorigin.evaluation.datasets import (
        build_audio_dataset,
        build_image_dataset,
        build_text_dataset,
    )

    click.echo(f"Building evaluation fixtures under {root}/ ...")
    click.echo(f"  {build_text_dataset(Path(root))}")
    for path in build_image_dataset(Path(root)):
        click.echo(f"  {path}")
    try:
        for path in build_audio_dataset(Path(root)):
            click.echo(f"  {path}")
    except ImportError:
        click.secho("  (skipped audio fixtures: scipy not installed)", fg="yellow")
    click.echo("Done.")


@main.command()
@click.argument("pytest_args", nargs=-1, type=click.UNPROCESSED)
def test(pytest_args):
    """Run the automated unit and integration test suite."""
    import subprocess

    click.echo("Running NullOrigin test suite...")
    result = subprocess.run([sys.executable, "-m", "pytest", *pytest_args])
    sys.exit(result.returncode)


if __name__ == "__main__":
    main()