diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..4093add
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,9 @@
+.git
+.github
+tests
+__pycache__
+*.pyc
+.DS_Store
+*.db
+*.zip
+*.json.tmp
diff --git a/.github/workflows/pathscope.yml b/.github/workflows/pathscope.yml
new file mode 100644
index 0000000..918836f
--- /dev/null
+++ b/.github/workflows/pathscope.yml
@@ -0,0 +1,108 @@
+# Example CI pipeline for PathScope.
+#
+# It does three things, in order:
+# 1. runs the unit test suite (no network, no dependencies),
+# 2. runs the built-in self-test,
+# 3. if a capture was attached to the run (artifact "pathscope-input"),
+# analyses it with a policy gate and publishes JUnit + an HTML report.
+#
+# PathScope is passive: this workflow never contacts the targets in the
+# capture. Replace the artifact step with wherever your capture comes from
+# (proxy export, browser HAR, Postman collection, ...).
+name: pathscope
+
+on:
+ push:
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: Unit tests and self-test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Run the unit tests
+ run: python3 -m unittest discover -s tests -v
+ - name: Run the built-in self-test
+ run: python3 path_detector.py --no-banner --self-test
+ - name: Check the environment
+ run: python3 path_detector.py --no-banner --doctor
+
+ install:
+ name: Installer smoke test
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest]
+ steps:
+ - uses: actions/checkout@v4
+ - name: Install into a throwaway prefix
+ run: |
+ ./install.sh --dry-run --no-path
+ PREFIX="$RUNNER_TEMP/pathscope" ./install.sh --no-path
+ - name: Run the installed launcher
+ run: |
+ "$RUNNER_TEMP/pathscope/bin/pathscope" --version
+ "$RUNNER_TEMP/pathscope/bin/pathscope" --no-banner --self-test
+ echo 'https://a.test/?file=../../etc/passwd' \
+ | "$RUNNER_TEMP/pathscope/bin/pathscope" --no-banner -q --format json \
+ | grep -q '"candidates": 1'
+ - name: Uninstall
+ run: PREFIX="$RUNNER_TEMP/pathscope" ./install.sh --uninstall
+
+ triage:
+ name: Triage a capture (optional)
+ needs: test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Download the capture artifact
+ id: capture
+ uses: actions/download-artifact@v4
+ continue-on-error: true
+ with:
+ name: pathscope-input
+ path: input
+ - name: Analyse with a policy gate
+ if: steps.capture.outcome == 'success'
+ id: triage
+ # Reports are produced first, then the gate decides the job's outcome.
+ run: |
+ set +e
+ python3 path_detector.py \
+ -i input/capture.har \
+ --preset balanced \
+ --policy .pathscope/policy.json \
+ --output-format junit > pathscope-junit.xml
+ echo "gate=$?" >> "$GITHUB_OUTPUT"
+ python3 path_detector.py \
+ -i input/capture.har \
+ --preset balanced \
+ --policy .pathscope/policy.json \
+ --save-report pathscope-report.html --interactive \
+ --github-annotations
+ echo "annotations=$?" >> "$GITHUB_OUTPUT"
+ - name: Upload reports
+ if: steps.capture.outcome == 'success'
+ uses: actions/upload-artifact@v4
+ with:
+ name: pathscope-reports
+ path: |
+ pathscope-junit.xml
+ pathscope-report.html
+ - name: Enforce the policy gate
+ if: steps.capture.outcome == 'success' && steps.triage.outputs.gate != '0'
+ run: |
+ echo "PathScope policy gate failed (exit ${{ steps.triage.outputs.gate }})." >&2
+ exit 1
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ad03bc7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+__pycache__/
+*.pyc
+.venv/
+venv/
diff --git a/.pathscope/policy.json b/.pathscope/policy.json
new file mode 100644
index 0000000..7aae98a
--- /dev/null
+++ b/.pathscope/policy.json
@@ -0,0 +1,10 @@
+{
+ "description": "Example gate: no new high-confidence candidates, at most 10 medium, 25 total",
+ "max_high": 0,
+ "max_medium": 10,
+ "max_total": 25,
+ "min_score": 0,
+ "fail_on_known": false,
+ "ignore_rules": [],
+ "ignore_hosts": []
+}
diff --git a/.pre-commit-config.example.yaml b/.pre-commit-config.example.yaml
new file mode 100644
index 0000000..ca360ee
--- /dev/null
+++ b/.pre-commit-config.example.yaml
@@ -0,0 +1,7 @@
+# Copy to .pre-commit-config.yaml in your project and run `pre-commit install`.
+repos:
+ - repo: https://github.com/mrdineshpathro/pathscope
+ rev: v2.2.0
+ hooks:
+ - id: pathscope-selftest
+ - id: pathscope-no-new-high
diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml
new file mode 100644
index 0000000..2414805
--- /dev/null
+++ b/.pre-commit-hooks.yaml
@@ -0,0 +1,28 @@
+# Pre-commit hook definitions (https://pre-commit.com).
+#
+# repos:
+# - repo: https://github.com/mrdineshpathro/pathscope
+# rev: v2.2.0
+# hooks:
+# - id: pathscope-selftest
+# - id: pathscope-no-new-high
+#
+# Both hooks are offline and read only the files listed by pre-commit.
+- id: pathscope-selftest
+ name: PathScope self-test
+ description: Verify the PathScope installation (parsing, scoring, escaping).
+ entry: python3 path_detector.py --no-banner --self-test
+ language: python
+ pass_filenames: false
+ always_run: true
+
+- id: pathscope-no-new-high
+ name: PathScope (no new high-confidence candidates)
+ description: >
+ Analyse the given captures and fail when a new high-confidence candidate
+ appears. Uses a reviewed ledger when one is provided, so a stable file does
+ not fail repeatedly.
+ entry: python3 path_detector.py --no-banner -q --policy '{"max_high": 0}' --top 5
+ language: python
+ files: \.(har|json|txt|xml|jsonl)$
+ types: [file]
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..e529c85
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,45 @@
+# PathScope container image.
+#
+# docker build -t pathscope .
+# cat requests.txt | docker run --rm -i pathscope --stream --format text
+# docker run --rm -v "$PWD:/data:ro" pathscope -i /data/requests.txt --format json
+#
+# The image contains nothing but PathScope and a Python runtime: no scanners,
+# no networking tools, no third-party packages.
+
+FROM python:3.12-slim AS base
+
+LABEL org.opencontainers.image.title="PathScope" \
+ org.opencontainers.image.description="Passive, offline triage of path-like request parameters" \
+ org.opencontainers.image.source="https://github.com/mrdineshpathro/pathscope" \
+ org.opencontainers.image.licenses="MIT"
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PYTHONHASHSEED=0
+
+# Unprivileged user: nothing in PathScope needs root.
+RUN groupadd --system --gid 10001 pathscope \
+ && useradd --system --uid 10001 --gid pathscope --create-home pathscope
+
+WORKDIR /opt/pathscope
+COPY path_detector.py ./
+COPY pathscope ./pathscope
+COPY assets ./assets
+COPY README.md LICENSE ./
+
+# Byte-compile once so runs stay fast; drop the source copies for a smaller layer.
+RUN python3 -m compileall -q pathscope path_detector.py \
+ && chmod -R a+rX /opt/pathscope
+
+USER pathscope
+WORKDIR /home/pathscope
+
+# Inputs are mounted read-only; the default run documents itself.
+VOLUME ["/data"]
+ENTRYPOINT ["python3", "/opt/pathscope/path_detector.py"]
+CMD ["--help"]
+
+# Sanity check used by CI and `docker run --rm pathscope --self-test`.
+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=1 \
+ CMD ["python3", "/opt/pathscope/path_detector.py", "--no-banner", "--self-test"]
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ecbebef
--- /dev/null
+++ b/README.md
@@ -0,0 +1,2560 @@
+
+
+

+
+# PathScope
+
+**Passive, offline triage of URL and request parameters that may be worth
+reviewing for path-traversal risk.**
+
+[](https://www.python.org/)
+[](#requirements)
+[](#requirements)
+[](LICENSE)
+
+[GitHub](https://github.com/mrdineshpathro) ·
+[Instagram](https://www.instagram.com/mr_dineshpatro) ·
+[Support](https://buymeacoffee.com/mrdineshpathro)
+
+
+
+---
+
+> **PathScope reports candidates for manual review. It does not find, prove, or
+> confirm vulnerabilities.** A finding means “this parameter’s name or existing
+> value looks path-like”. Whether it is used, validated, or remotely interesting
+> is a question for a human, in scope, with authorization.
+
+---
+
+## Table of contents
+
+1. [What it does](#what-it-does)
+2. [Safety model](#safety-model)
+3. [Requirements](#requirements)
+4. [Installation](#installation)
+5. [Inputs](#inputs)
+6. [Quick start](#quick-start)
+7. [Presets](#presets)
+8. [Baselines, diff and suppression](#baselines-diff-and-suppression)
+9. [Reports](#reports)
+10. [Live watch mode](#live-watch-mode)
+11. [Rule registry and tuning](#rule-registry-and-tuning)
+12. [Multilingual and folded names](#multilingual-and-folded-names)
+13. [Value-shape demotion](#value-shape-demotion)
+14. [CI integration](#ci-integration)
+15. [Scale and performance](#scale-and-performance)
+16. [Interactive HTML report](#interactive-html-report)
+17. [Terminal reviewer](#terminal-reviewer)
+18. [Review ledger](#review-ledger)
+19. [Analysis dashboard](#analysis-dashboard)
+20. [Cross-source correlation](#cross-source-correlation)
+21. [Remediation playbooks](#remediation-playbooks)
+22. [Run history and trends](#run-history-and-trends)
+23. [Streaming stdin](#streaming-stdin)
+24. [Reproducible bundles](#reproducible-bundles)
+25. [Secret scrubbing](#secret-scrubbing)
+26. [Capture-to-capture diff](#capture-to-capture-diff)
+27. [Offline URL extraction](#offline-url-extraction)
+28. [Value statistics](#value-statistics)
+29. [Rule coverage](#rule-coverage)
+30. [Term packs](#term-packs)
+31. [Preset comparison](#preset-comparison)
+32. [Score calibration](#score-calibration)
+33. [Project files](#project-files)
+34. [Reviewed-aware CI](#reviewed-aware-ci)
+35. [Acceptance expiry](#acceptance-expiry)
+36. [Path families](#path-families)
+37. [Review queue](#review-queue)
+38. [Scope files](#scope-files)
+39. [Deterministic sampling](#deterministic-sampling)
+40. [API description matching](#api-description-matching)
+41. [Policy shadow mode](#policy-shadow-mode)
+42. [Work-item export](#work-item-export)
+43. [Pull-request comments](#pull-request-comments)
+44. [Host redaction](#host-redaction)
+45. [Shell completion](#shell-completion)
+46. [Waivers](#waivers)
+47. [Suppression audit](#suppression-audit)
+48. [Rule precision](#rule-precision)
+49. [Rule impact](#rule-impact)
+50. [Weight simulation](#weight-simulation)
+51. [Score-change explanation](#score-change-explanation)
+52. [Filtering with --where](#filtering-with---where)
+53. [Run attestation](#run-attestation)
+54. [Owner assignment](#owner-assignment)
+55. [Ledger merge](#ledger-merge)
+56. [Exit codes](#exit-codes)
+57. [Detection rules](#detection-rules)
+58. [Configuration file](#configuration-file)
+59. [Tests](#tests)
+60. [Project layout](#project-layout)
+61. [Limitations](#limitations)
+62. [FAQ](#faq)
+63. [Authorization and legal](#authorization-and-legal)
+
+---
+
+## What it does
+
+Given URLs or a HAR capture **you already have**, PathScope:
+
+* parses query strings, form bodies and JSON bodies **locally**;
+* scores every parameter against a small, documented rule set
+ (name vocabulary + value shape);
+* prints a ranked list of *candidates* with the rule that fired, a plain-language
+ reason, and a heuristic score.
+
+It does **not** send a request, resolve a host, crawl, fuzz, inject, replay a HAR,
+or read any file named in a parameter. Parameter values are strings and nothing
+else.
+
+Typical use: you have a proxy history or a list of URLs from an authorized
+review, and you want the five parameters worth reading first instead of two
+hundred.
+
+---
+
+## Safety model
+
+| Guarantee | How it is enforced |
+|---|---|
+| No network I/O | No `socket`, `ssl`, `http`, `urllib.request`, `requests` imports anywhere in `pathscope/`; a test asserts this with an allow-list. |
+| No DNS | Same as above: nothing in the package can resolve a name. |
+| No crawling or scanning | Inputs are read exactly once from args, files or stdin. |
+| No test payloads | Values are only read, never generated or modified. |
+| No filesystem access via values | Values never reach `open`, `os.open`, `pathlib`; a test patches `open` to fail if a value is ever used as a path. |
+| No root | Nothing calls `setuid`, `sudo`, or privileged APIs. |
+| No third-party packages | Standard library only. |
+
+Additional hardening:
+
+* **Values hidden by default.** Reports show `` unless you pass
+ `--show-values`.
+* **No query strings or bodies in output.** The reported `resource` is
+ `scheme://host[:port]/path` only; `user:pass@` in URLs is masked.
+* **Terminal-safe output.** Every string from input is NFC-normalised and control
+ characters are removed before rendering, so a crafted value cannot inject ANSI
+ escapes or fake report lines.
+* **Deterministic output.** No timestamps, no machine names, stable sort order —
+ reports diff cleanly between runs.
+* **Bounded work.** Decoding is capped (default 3 passes, max 5), HAR entries and
+ JSON parameters are capped, and long values are truncated.
+
+---
+
+## Requirements
+
+| | |
+|---|---|
+| Python | 3.8 or newer (developed and tested on Python 3.11, which Kali ships) |
+| Packages | **none** — standard library only |
+| Privileges | ordinary user; **root is not required** (the Docker image is unprivileged too) |
+| Network | **never used** |
+
+---
+
+## Installation
+
+PathScope is a single Python package with **no third-party dependencies**.
+Pick whichever line matches your box.
+
+### Kali / Debian / Ubuntu / macOS / WSL (one command)
+
+```sh
+git clone https://github.com/mrdineshpathro/pathscope
+cd pathscope
+./install.sh # installs into ~/.local
+```
+
+`install.sh` is POSIX `sh`, prints every action, and is safe to re-run:
+
+| Command | Effect |
+|---|---|
+| `./install.sh` | install to `~/.local`, add it to the PATH in `~/.profile`/`~/.zshrc` |
+| `PREFIX=/opt/pathscope sudo ./install.sh` | system-wide install |
+| `./install.sh --no-path` | install files but leave shell rc files alone |
+| `./install.sh --dry-run` | print what would happen, change nothing |
+| `./install.sh --uninstall` | remove the launcher and program files |
+
+It refuses to run on Python older than 3.8, verifies the copied sources import,
+and finishes with `pathscope --version`. Nothing is downloaded and no Python
+packages are installed.
+
+### Windows
+
+```bat
+git clone https://github.com/mrdineshpathro/pathscope
+cd pathscope
+install.cmd
+```
+
+Installs to `%LOCALAPPDATA%\PathScope`, adds `...\bin` to the **user** PATH (no
+admin rights needed) and writes a `pathscope.cmd` launcher. Options:
+`--no-path`, `--dry-run`, `--help`; override the location with
+`set PREFIX=D:\tools ^& install.cmd`.
+
+The terminal reviewer (`--tui`) needs `curses`; on Windows it is unavailable, and
+every other feature works unchanged (PathScope reports this clearly instead of
+crashing — see `pathscope --doctor`).
+
+### Docker (one line)
+
+```sh
+docker build -t pathscope .
+cat requests.txt | docker run --rm -i pathscope --stream
+docker run --rm -v "$PWD:/data:ro" pathscope -i /data/requests.txt --format json
+```
+
+The image is `python:3.12-slim`, runs as an unprivileged user, contains no
+scanners or networking tools, and has a `HEALTHCHECK` that runs `--self-test`.
+
+### Verify any install
+
+```sh
+pathscope --doctor # interpreter, sqlite, zip, curses, package integrity
+pathscope --self-test # 16 behavioural checks, no network access
+```
+
+### Manual (no install)
+
+```sh
+python3 path_detector.py --help
+```
+
+### Kali Linux notes
+
+Kali ships Python 3.11; there is nothing to install.
+
+```bash
+git clone https://github.com/mrdineshpathro/pathscope.git
+cd pathscope
+
+python3 --version # expect 3.11.x
+chmod +x path_detector.py
+./path_detector.py --help
+
+# equivalent module form (no chmod needed)
+python3 -m pathscope --help
+```
+
+Optional: put it on your `PATH` without root.
+
+```bash
+mkdir -p ~/.local/bin
+ln -sf "$PWD/path_detector.py" ~/.local/bin/pathscope
+pathscope --version
+```
+
+If `~/.local/bin` is not on `PATH`, add it to your shell config
+(`~/.zshrc` on Kali by default):
+
+```bash
+echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && exec zsh
+```
+
+> Nothing in this project needs `sudo`. If a command fails, fix permissions in
+> your home directory rather than escalating.
+
+---
+
+## Inputs
+
+PathScope accepts three sources, which are merged and de-duplicated:
+
+| Source | Flag | Notes |
+|---|---|---|
+| One or more URLs | `--url URL` (repeatable) | Quote URLs containing `&`. |
+| URL list | `-i urls.txt` / `-i urls2.txt` | One URL per line; blank lines and `#` comments ignored; malformed lines warn and are skipped. |
+| HAR 1.2 capture | `-i capture.har` or `--format har` | Parsed locally; requests are **never replayed**. |
+| Burp proxy XML | `-i burp-history.xml` or `--format burp` | Base64 and plain request blocks; form/JSON/multipart bodies parsed. |
+| OpenAPI / Swagger | `-i openapi.json` or `--format openapi` | Declared parameters become a name-only inventory (no values). |
+| Raw HTTP request | `-i request.txt` or `--format raw` | `GET /path?x=1 HTTP/1.1` + `Host`; several requests via `###` lines. |
+| Recon output | `-i httpx.txt`, `-i nuclei.jsonl`, `--format recon` | httpx/ffuf/katana/nuclei lines or JSONL, reduced to their URLs. |
+| Postman | `-i collection.json` or `--format postman` | Collection v2.0/v2.1, nested folders, query/urlencoded/formdata/raw bodies. |
+| OWASP ZAP | `-i zap.json` or `--format zap` | JSON history (`site.messages`) or alert export (`alerts[].instances`). |
+| mitmproxy | `-i flows.json` or `--format mitmproxy` | A single flow or a list of flows; query and JSON/form bodies. |
+| GraphQL | `-i introspection.json` or `--format graphql` | Argument names of the root query/mutation fields, nested args as `a.b`. |
+| Cookie jar | `-i cookies.txt` or `--format cookies` | Netscape format; **names only**, values are discarded. |
+| stdin | `cat urls.txt \| pathscope`, `pathscope -i -` | Auto-detected when no other source is given. |
+
+### Input format
+
+* `--format auto` (default) — detects, in order: HAR (`.har`/`.har.json` or a
+ `log.entries` object), a plain URL list, Postman, ZAP, GraphQL, mitmproxy,
+ cookie jar, Burp XML, OpenAPI JSON, raw HTTP request, recon output.
+* `--format har|burp|openapi|raw|recon|postman|zap|mitmproxy|graphql|cookies|urls`
+ — force an input format.
+* `--input-format {...}` — the same selectors under an unambiguous name. Use
+ `--input-format` together with `--format json` when you want to force the
+ input **and** choose output.
+
+`--format json|csv|sarif|text` selects the **output** format instead (see below).
+
+### What is read from a HAR
+
+| HAR location | Parameters analysed |
+|---|---|
+| `request.url` query string and `request.queryString` | query parameters (repeated names kept) |
+| `request.postData.params` | multipart/form fields, using `value` or `fileName` |
+| `request.postData.text` + `mimeType` | `application/x-www-form-urlencoded` fields, or flattened JSON body (dotted paths, `[n]` for arrays) |
+
+Only the request side is read. Responses, cookies, headers and timings are
+ignored on purpose: they are noise for this question and may contain secrets.
+
+---
+
+## Quick start
+
+All examples work on Kali with the repository checked out.
+
+```bash
+# 1. A single URL
+python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
+
+# 2. A URL list (one per line)
+python3 path_detector.py -i urls.txt
+
+# 3. Piped stdin
+cat urls.txt | python3 path_detector.py
+
+# 4. A local HAR capture (auto-detected)
+python3 path_detector.py -i capture.har
+
+# 5. HAR with JSON output for a report pipeline
+python3 path_detector.py -i capture.har --format json > candidates.json
+
+# 6. Show existing values (they may contain secrets — be careful)
+python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values
+
+# 7. Ignore noisy parameters, in CI
+python3 path_detector.py -i urls.txt --ignore-param image --ignore-param avatar \
+ --fail-on-findings
+```
+
+Example terminal output (values hidden):
+
+```console
+$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
+PathScope 2.6.0 - passive path-parameter triage
+----------------------------------------------------------------
+GitHub: https://github.com/mrdineshpathro
+Instagram: https://www.instagram.com/mr_dineshpatro
+Support: https://buymeacoffee.com/mrdineshpathro
+Candidates for manual review only. No network requests are made; only analyze data you are authorized to review.
+
+PathScope candidates for manual review
+====================================================================================
+Analyzed 1 request(s) and 1 parameter(s); 1 candidate(s) at score >= 25.
+
+#1 file [MEDIUM score 43/100]
+ Host example.test
+ Source url (--url)
+ Request GET https://example.test/view
+ Location query
+ Rule name-exact
+ Value (use --show-values)
+ Why rules and evidence:
+ - parameter name contains path-related term 'file' (+35)
+ - value ends with a file-like extension '.pdf' (+8)
+
+Reminder: these are candidates for manual review, not confirmed vulnerabilities. No requests were sent.
+```
+
+---
+
+## Presets
+
+Three reporting postures, chosen with `--preset`. They change thresholds only —
+never what counts as a finding.
+
+| Preset | Score threshold | Weak-name evidence | Use it when |
+|---|---|---|---|
+| `minimal` (aliases `strict`, `high`) | 50 | off | you want a very short list |
+| `balanced` (alias `default`) | 25 | on | normal triage (default) |
+| `noisy` (aliases `loud`, `broad`) | 10 | on | first pass over a large capture |
+
+Precedence: **CLI flags > configuration file > preset**.
+
+```bash
+python3 path_detector.py -i capture.har --preset minimal
+
+# Write a validated starter config for the preset you use most
+python3 path_detector.py --init-config pathscope.json --preset minimal
+python3 path_detector.py -i capture.har --config pathscope.json
+```
+
+`--init-config` refuses to overwrite an existing file, so it is safe to re-run.
+
+## Baselines, diff and suppression
+
+Every finding carries a stable 16-hex **fingerprint** derived from
+`host + location + parameter name + primary rule + path`. Values, scores and the
+source file name are excluded, so a baseline survives new captures and new data.
+
+```bash
+# 1. Save a JSON baseline (any run can produce one)
+python3 path_detector.py -i capture.har --json > baseline.json
+
+# 2. Later: report only new candidates, and fail CI only on those
+python3 path_detector.py -i capture-new.har --baseline baseline.json \
+ --save-report triage.md --fail-on-findings
+```
+
+* `--baseline FILE` — known findings are marked `known` and hidden; `resolved`
+ entries (in the baseline but no longer present) are listed in text/Markdown/HTML.
+* `--show-known` — keep known findings in the output, labelled `KNOWN`.
+* `--suppress FILE` — hide reviewed fingerprints; accepts a PathScope JSON
+ report or a `{"suppressions": [{"fingerprint": "...", "note": "..."}]}` file.
+* `--mark-reviewed FILE` — append the current run's fingerprints (with any
+ baseline note) to a reviewed ledger that `--suppress` can read later.
+* `--fail-on-findings` in diff mode counts **new** candidates only, so a stable
+ baseline gives a quiet CI gate.
+
+Fingerprints appear in text, JSON (`"fingerprint"`, `"status"`), CSV and SARIF
+(`partialFingerprints`), so any of them can be used as a baseline.
+
+## Reports
+
+Every format contains the same fields: `host`, `source_type`, `source`,
+`method`, `location` (`query`/`form`/`json`), `parameter`, `occurrences`,
+`rule`, `rules`, `confidence`, `score`, `reasons`, `resource`, and — only with
+`--show-values` — `value`.
+
+### JSON (`--format json`, `--json`)
+
+```json
+{
+ "tool": "PathScope",
+ "version": "2.1.0",
+ "disclaimer": "Candidates for manual review only. ...",
+ "passive": true,
+ "network_requests_made": 0,
+ "min_score": 25,
+ "show_values": false,
+ "summary": {
+ "requests_analyzed": 1,
+ "parameters_analyzed": 3,
+ "candidates": 1,
+ "confidence": {"high": 0, "medium": 1, "low": 0},
+ "skipped": 0,
+ "sources": ["urls.txt"],
+ "mode": "scan",
+ "new": 1,
+ "known": 0,
+ "resolved": 0
+ },
+ "warnings": [],
+ "findings": [
+ {
+ "index": 1,
+ "host": "example.test",
+ "source_type": "file",
+ "source": "urls.txt",
+ "method": "GET",
+ "location": "query",
+ "parameter": "file",
+ "occurrences": 1,
+ "rule": "name-exact",
+ "rules": ["name-exact", "value-extension"],
+ "confidence": "medium",
+ "score": 43,
+ "reasons": [
+ "parameter name contains path-related term 'file' (+35)",
+ "value ends with a file-like extension '.pdf' (+8)"
+ ],
+ "resource": "https://example.test/view",
+ "value": null,
+ "fingerprint": "ec274fecea647284",
+ "status": "new",
+ "note": ""
+ }
+ ],
+ "links": {
+ "github": "https://github.com/mrdineshpathro",
+ "instagram": "https://www.instagram.com/mr_dineshpatro",
+ "support": "https://buymeacoffee.com/mrdineshpathro"
+ }
+}
+```
+
+### CSV (`--format csv`)
+
+Fixed column order, one finding per row, `values` empty unless `--show-values`:
+
+```
+index,host,source_type,source,method,location,parameter,rule,rules,confidence,score,reasons,resource,value
+1,example.test,file,urls.txt,GET,query,file,name-exact,name-exact;value-extension,medium,43,"parameter name contains path-related term 'file' (+35); value ends with a file-like extension '.pdf' (+8)",https://example.test/view,
+```
+
+### Markdown and HTML (`--format markdown|html`, `--save-report FILE`)
+
+Standalone reports for tickets and reviews: summary metadata, a candidate table
+with fingerprints and statuses, a "why each candidate was flagged" section, the
+resolved list in diff mode, and input warnings. HTML is fully escaped (a
+parameter named `", sources.SOURCE_URL, "--self-test"
+ )
+ report = detector.analyze_requests([request], detector.AnalysisOptions())
+ markup = writers.render_html(report)
+ assert "" not in markup, "unescaped markup in HTML"
+
+ def decode_bounded() -> None:
+ forms = textutil.decode_forms("%25252e%25252e", 1)
+ passes, text = forms[-1]
+ assert passes <= 1, passes
+ assert "%25" in text, text
+
+ def scrub_redacts_secrets() -> None:
+ from . import scrub
+
+ secret = "ghp_" + "a" * 36
+ assert scrub.should_scrub("file", secret), "vendor token not detected"
+ marker = scrub.scrub_value(secret)
+ assert marker.startswith(" None:
+ from . import playbooks
+ from .rules import DEFAULT_BOOK
+
+ missing = playbooks.validate_playbook_coverage()
+ assert not missing, f"rules without a playbook: {missing}"
+ assert DEFAULT_BOOK.as_dict(), "empty rule book"
+
+ def bundle_is_reproducible() -> None:
+ import tempfile, os
+ from . import bundle, detector
+
+ request = sources.request_from_url(
+ "https://a.test/?file=../../etc/passwd", sources.SOURCE_URL, "--self-test"
+ )
+ report = detector.analyze_requests([request], detector.AnalysisOptions())
+ first = tempfile.mktemp(suffix=".zip")
+ second = tempfile.mktemp(suffix=".zip")
+ try:
+ bundle.build_bundle(first, report)
+ bundle.build_bundle(second, report)
+ with open(first, "rb") as handle:
+ left = handle.read()
+ with open(second, "rb") as handle:
+ right = handle.read()
+ assert left == right, "bundles differ byte-for-byte"
+ finally:
+ for path in (first, second):
+ if os.path.exists(path):
+ os.unlink(path)
+
+ def ledger_roundtrip() -> None:
+ import tempfile, os
+ from . import ledger
+
+ path = tempfile.mktemp(suffix=".db")
+ try:
+ store = ledger.open_ledger(path)
+ store.record("fp-self-test", status="reviewed", host="a.test",
+ parameter="file", rule="name-exact", reviewer="self-test")
+ assert "fp-self-test" in store.fingerprints(), "record not stored"
+ stats = store.stats()
+ assert stats["total"] == 1, stats
+ assert stats["by_status"] == {"reviewed": 1}, stats
+ assert stats["reviewers"] == ["self-test"], stats
+ store.close()
+ finally:
+ if os.path.exists(path):
+ os.unlink(path)
+
+ def stream_is_bounded() -> None:
+ from . import detector, stream
+
+ text = "\n".join(f"https://h{i}.test/?file=../../x" for i in range(25))
+ result = stream.stream_text(text, detector.AnalysisOptions(), batch_size=10)
+ assert result.stats.batches == 3, result.stats.batches
+ assert result.report.requests_analyzed == 25, result.report.requests_analyzed
+ assert result.report.candidate_count == 25, result.report.candidate_count
+
+ def history_tracks_trends() -> None:
+ import tempfile, os
+ from . import detector, history
+
+ path = tempfile.mktemp(suffix=".json")
+ try:
+ for count in (3, 2):
+ requests = [
+ sources.request_from_url(
+ f"https://h{i}.test/?file=../../x", sources.SOURCE_URL, "t"
+ )
+ for i in range(count)
+ ]
+ report = detector.analyze_requests(requests, detector.AnalysisOptions())
+ history.append_run(path, history.run_record(report))
+ trend = history.analyze_history(history.load_history(path))
+ assert trend.runs == 2, trend.runs
+ assert trend.counts == [3, 2], trend.counts
+ assert len(trend.latest_resolved) == 1, trend.latest_resolved
+ finally:
+ if os.path.exists(path):
+ os.unlink(path)
+
+ def expiry_math_is_sound() -> None:
+ from . import ledger
+
+ stamp = ledger.parse_expiry("24h", now="2026-01-01T00:00:00Z")
+ assert stamp == "2026-01-02T00:00:00Z", stamp
+ assert ledger.parse_expiry("none") == "", "none must mean no expiry"
+ try:
+ ledger.parse_expiry("soon")
+ except ledger.LedgerError:
+ pass
+ else: # pragma: no cover - regression guard
+ raise AssertionError("a bad expiry spec was accepted")
+
+ def capture_diff_detects_renames() -> None:
+ from . import capturediff
+
+ old = sources.load_url_lines(
+ ["https://a.test/x?file=/a"], sources.SOURCE_URL, "selftest"
+ ).requests
+ new = sources.load_url_lines(
+ ["https://a.test/x?file_id=/b"], sources.SOURCE_URL, "selftest"
+ ).requests
+ diff = capturediff.compare(old, new)
+ assert [c.describe() for c in diff.renamed] == ["file -> file_id"], diff.renamed
+ # unrelated names must not be paired
+ other = capturediff.compare(
+ sources.load_url_lines(["https://a.test/x?q=/a"], sources.SOURCE_URL, "s").requests,
+ sources.load_url_lines(["https://a.test/x?file=/a"], sources.SOURCE_URL, "s").requests,
+ )
+ assert other.renamed == [], other.renamed
+
+ def extraction_is_local() -> None:
+ from . import extractor
+
+ found = extractor.extract_text(
+ 'fetch("https://app.test/api?file=/a");', "selftest.js"
+ )
+ assert any(entry.value.endswith("/api?file=/a") for entry in found), found
+
+ def term_packs_reject_regex() -> None:
+ from . import termpacks
+
+ try:
+ termpacks.validate_payload({"terms": ["file.*"]})
+ except termpacks.TermPackError:
+ pass
+ else: # pragma: no cover - regression guard
+ raise AssertionError("a regular expression was accepted as a term")
+ pack = termpacks.starter_pack("selftest")
+ assert pack.terms, "starter pack has no terms"
+
+ def project_paths_stay_inside() -> None:
+ from . import project
+
+ try:
+ project.validate_payload({"version": 1, "config": "/etc/passwd"}, source="/tmp/x")
+ except project.ProjectError:
+ pass
+ else: # pragma: no cover - regression guard
+ raise AssertionError("a project file escaped its directory")
+
+ def calibration_uses_the_rules_it_documents() -> None:
+ import tempfile, os
+ from . import calibrate, ledger
+
+ path = tempfile.mktemp(suffix=".db")
+ try:
+ store = ledger.open_ledger(path)
+ for index, score in enumerate([80, 75, 70, 65, 60, 55, 50, 45]):
+ store.record(f"a{index}", status="accepted", score=score)
+ for index, score in enumerate([40, 35, 30, 25, 20, 15, 12, 10]):
+ store.record(f"f{index}", status="false-positive", score=score)
+ result = calibrate.calibrate(store)
+ store.close()
+ assert result.recommended is not None, "no recommendation from clean data"
+ best = result.best()
+ assert best.recall >= calibrate.DEFAULT_MIN_RECALL, best.recall
+ assert best.fp_rate <= calibrate.DEFAULT_MAX_FP_RATE, best.fp_rate
+ finally:
+ if os.path.exists(path):
+ os.unlink(path)
+
+ def route_shapes_collapse_identifiers() -> None:
+ from . import families
+
+ assert families.route_shape("/items/1/view") == "/items/{id}/view"
+ assert families.route_shape("/items/2/view") == "/items/{id}/view"
+ assert families.route_shape("/v2/items") == "/v2/items"
+
+ def sampling_is_reproducible() -> None:
+ from . import sampling, sources
+
+ requests = sources.load_url_lines(
+ [f"https://h{i % 3}.test/p/{i}?file=/a/b" for i in range(30)],
+ "url",
+ "selftest",
+ ).requests
+ first = sampling.sample(requests, 6, seed=99)
+ second = sampling.sample(requests, 6, seed=99)
+ assert first.size == 6, first.size
+ assert [r.url.raw for r in first.requests] == [
+ r.url.raw for r in second.requests
+ ], "the same seed must select the same subset"
+ other = sampling.sample(requests, 6, seed=100)
+ assert [r.url.raw for r in other.requests] != [
+ r.url.raw for r in first.requests
+ ], "a different seed should select a different subset"
+
+ def scope_wildcard_stays_in_one_label() -> None:
+ from . import scope as scope_module
+
+ parsed = scope_module.from_payload({"in_scope": ["*.a.test"]})
+ assert parsed.allows("api.a.test"), "api.a.test should be in scope"
+ assert not parsed.allows("deep.api.a.test"), "a wildcard must not cross a dot"
+ assert not parsed.allows("a.test"), "a wildcard must match a label"
+
+ def redaction_is_keyed_and_stable() -> None:
+ from . import redact
+
+ first = redact.build_map("selftest-key")
+ second = redact.build_map("selftest-key")
+ other = redact.build_map("another-key")
+ name = first.pseudonym("a.test")
+ assert name == second.pseudonym("a.test"), "same key must give the same name"
+ assert name != other.pseudonym("a.test"), "a different key must differ"
+ assert "a.test" not in name, "the pseudonym must not contain the host"
+
+ def spec_templates_match_one_segment() -> None:
+ from . import openapi
+
+ spec = openapi.parse_spec(
+ {
+ "openapi": "3.0.0",
+ "info": {"title": "t", "version": "1"},
+ "paths": {"/d/{id}/v": {"get": {}}},
+ }
+ )
+ assert len(spec.operations) == 1, "one operation expected"
+
+ def pr_comment_states_the_truth() -> None:
+ from . import detector, prcomment, sources
+
+ report = detector.analyze_requests(
+ sources.load_url_lines(
+ ["https://a.test/view?file=../../etc/passwd"], "url", "selftest"
+ ).requests,
+ detector.AnalysisOptions(),
+ )
+ comment = prcomment.render_comment(report, exit_code=0)
+ assert comment.body.startswith(prcomment.MARKER), "marker must come first"
+ if report.findings:
+ assert "no new candidates" not in comment.body, (
+ "a report with findings must not claim there are none"
+ )
+
+ def waivers_demand_ownership() -> None:
+ from . import waivers
+
+ base = {"host": "a.test", "reason": "r", "owner": "o"}
+ waivers.parse_waivers({"waivers": [base]})
+ for missing in ("reason", "owner"):
+ payload = {k: v for k, v in base.items() if k != missing}
+ try:
+ waivers.parse_waivers({"waivers": [payload]})
+ except waivers.WaiverError:
+ continue
+ raise AssertionError(f"a waiver without '{missing}' was accepted")
+ try:
+ waivers.parse_waivers({"waivers": [{"reason": "r", "owner": "o"}]})
+ except waivers.WaiverError:
+ pass
+ else:
+ raise AssertionError("a waiver matching everything was accepted")
+
+ def expired_waiver_hides_nothing() -> None:
+ from . import detector, sources, waivers
+
+ report = detector.analyze_requests(
+ sources.load_url_lines(
+ ["https://a.test/view?file=../../etc/passwd"], "url", "selftest"
+ ).requests,
+ detector.AnalysisOptions(),
+ )
+ loaded = waivers.parse_waivers(
+ {
+ "waivers": [
+ {
+ "host": "a.test",
+ "parameter": "file",
+ "reason": "old",
+ "owner": "o",
+ "expires": "2000-01-01",
+ }
+ ]
+ }
+ )
+ hidden, skipped = waivers.apply_waivers(report.findings, loaded)
+ assert hidden == 0, f"an expired waiver hid {hidden} finding(s)"
+ assert skipped == 1, skipped
+ assert all(f.status != "waived" for f in report.findings)
+
+ def query_parser_never_evaluates() -> None:
+ from . import query
+
+ for expression in ("__import__('os')", "score > 1; import os"):
+ try:
+ query.parse(expression)
+ except query.QueryError:
+ continue
+ raise AssertionError(f"the query parser accepted {expression!r}")
+ node = query.parse("score > 20 and confidence = high")
+ assert query.describe(node), "a parsed filter must describe itself"
+
+ def simulation_cannot_alter_the_run() -> None:
+ from . import detector, simulate, sources
+
+ options = detector.AnalysisOptions()
+ before = dict(options.book.weights)
+ requests = sources.load_url_lines(
+ ["https://a.test/view?file=../../etc/passwd"], "url", "selftest"
+ ).requests
+ result = simulate.simulate(
+ requests, options, simulate.parse_changes("name-exact=off")
+ )
+ assert result.before is not None and result.after is not None
+ assert options.book.weights == before, "simulation mutated the real rule book"
+
+ def attestation_detects_edits() -> None:
+ import json as _json
+ import tempfile as _tempfile
+
+ from . import attest
+
+ built = attest.build(inputs=[], rendered="original body")
+ handle = _tempfile.NamedTemporaryFile(
+ "w", suffix=".json", delete=False, encoding="utf-8"
+ )
+ handle.write(built.render())
+ handle.close()
+ try:
+ assert attest.verify(handle.name, rendered="original body") == []
+ problems = attest.verify(handle.name, rendered="edited body")
+ assert problems, "an edited report must not verify"
+ payload = _json.loads(built.render())
+ assert payload["signature"] is None, "an attestation is not a signature"
+ finally:
+ import os as _os
+
+ _os.unlink(handle.name)
+
+ def merge_conflicts_are_visible() -> None:
+ import tempfile as _tempfile
+
+ from . import ledger, ledgermerge
+
+ directory = _tempfile.mkdtemp(prefix="pathscope-selftest-")
+ try:
+ left = ledger.open_ledger(_join(directory, "l.db"))
+ right = ledger.open_ledger(_join(directory, "r.db"))
+ left.record("fp", status="accepted", reviewer="a")
+ right.record("fp", status="false-positive", reviewer="b")
+ result = ledgermerge.plan(left, right)
+ left.close()
+ right.close()
+ assert len(result.conflicts) == 1, len(result.conflicts)
+ assert not result.applied, "plan() must never write"
+ assert "accepted" in result.conflicts[0].describe()
+ finally:
+ import shutil as _shutil
+
+ _shutil.rmtree(directory, ignore_errors=True)
+
+ def completion_tracks_the_parser() -> None:
+ from . import completion, cli
+
+ parser = cli.build_parser()
+ script = completion.render("bash", parser)
+ assert "--redact-hosts" in script, "completion must mention --redact-hosts"
+ assert "--cluster" in script, "completion must mention --cluster"
+ flags = completion.collect_flags(parser)
+ assert len(flags) > 50, f"expected many flags, found {len(flags)}"
+
+ return [
+ ("banner strings are exact", banner_exact),
+ ("URLs are parsed locally", url_parse),
+ ("query strings split literally", query_split),
+ ("traversal values score", traversal_scores),
+ ("ordinary parameters stay quiet", ordinary_ignored),
+ ("values are hidden by default", values_hidden),
+ ("configuration validates", config_roundtrip),
+ ("every renderer produces a report", report_renderers),
+ ("HTML output escapes input", html_escapes),
+ ("decoding is bounded", decode_bounded),
+ ("secret scrubbing redacts credentials", scrub_redacts_secrets),
+ ("every rule has a playbook", playbooks_cover_rules),
+ ("bundle export is reproducible", bundle_is_reproducible),
+ ("review ledger round-trips", ledger_roundtrip),
+ ("streaming is batched and bounded", stream_is_bounded),
+ ("run history tracks trends", history_tracks_trends),
+ ("acceptance expiry maths is sound", expiry_math_is_sound),
+ ("capture diffs detect real renames", capture_diff_detects_renames),
+ ("URL extraction is local", extraction_is_local),
+ ("term packs reject regular expressions", term_packs_reject_regex),
+ ("project paths stay inside the project", project_paths_stay_inside),
+ ("calibration obeys its own bounds", calibration_uses_the_rules_it_documents),
+ ("route shapes collapse identifiers", route_shapes_collapse_identifiers),
+ ("sampling is reproducible", sampling_is_reproducible),
+ ("scope wildcards stay in one label", scope_wildcard_stays_in_one_label),
+ ("redaction is keyed and stable", redaction_is_keyed_and_stable),
+ ("a spec template matches one segment", spec_templates_match_one_segment),
+ ("the PR comment states the truth", pr_comment_states_the_truth),
+ ("completion tracks the parser", completion_tracks_the_parser),
+ ("waivers demand a reason and an owner", waivers_demand_ownership),
+ ("an expired waiver hides nothing", expired_waiver_hides_nothing),
+ ("the query parser never evaluates", query_parser_never_evaluates),
+ ("simulation cannot alter the real run", simulation_cannot_alter_the_run),
+ ("attestation detects an edited report", attestation_detects_edits),
+ ("a merge conflict is never silent", merge_conflicts_are_visible),
+ ]
+
+
+def run_selftest() -> List[Dict[str, object]]:
+ """Run every built-in check. Returns ``[{name, passed, error}]``."""
+ results: List[Dict[str, object]] = []
+ for name, check in _selftest_checks():
+ try:
+ check()
+ except Exception as exc: # noqa: BLE001 - a failed check is data, not a crash
+ results.append({"name": name, "passed": False, "error": str(exc) or type(exc).__name__})
+ else:
+ results.append({"name": name, "passed": True, "error": ""})
+ return results
+
+
+def render_selftest(results: Sequence[Dict[str, object]]) -> str:
+ """Human-readable ``--self-test`` output."""
+ lines = [f"{PROGRAM} self-test ({__version__})"]
+ failures = 0
+ for entry in results:
+ status = "ok " if entry["passed"] else "FAIL"
+ suffix = "" if entry["passed"] else f" - {entry['error']}"
+ lines.append(f" [{status}] {entry['name']}{suffix}")
+ if not entry["passed"]:
+ failures += 1
+ lines.append("")
+ if failures:
+ lines.append(f"{failures} of {len(results)} checks failed.")
+ else:
+ lines.append(f"All {len(results)} checks passed. No network access was used.")
+ return "\n".join(lines)
+
+
+def run_doctor() -> List[Dict[str, object]]:
+ """Environment checks for ``--doctor``: is this install usable here?
+
+ Unlike :func:`run_selftest` (which proves the *analysis* behaves), this
+ looks outward: interpreter, terminal, filesystem and optional features.
+ Every check is local; nothing is downloaded or resolved.
+ """
+ import os
+ import platform
+ import sqlite3
+ import sys
+ import tempfile
+
+ results: List[Dict[str, object]] = []
+
+ def report(name: str, ok: bool, detail: str = "") -> None:
+ results.append({"name": name, "passed": ok, "detail": detail, "error": ""})
+
+ version = platform.python_version()
+ report(
+ "python version",
+ sys.version_info >= (3, 8),
+ f"{version} ({platform.python_implementation()})",
+ )
+ report("platform", True, f"{platform.system()} {platform.release()} ({platform.machine()})")
+ report("executable", True, os.path.abspath(sys.executable))
+
+ # curses: the TUI needs it, everything else does not.
+ try:
+ import curses # noqa: F401
+
+ has_curses = True
+ except ImportError: # pragma: no cover - platform dependent
+ has_curses = False
+ report("curses (for --tui)", has_curses, "available" if has_curses else "unavailable")
+
+ tty = False
+ try:
+ tty = bool(sys.stdout.isatty() and sys.stdin.isatty())
+ except Exception: # noqa: BLE001 - exotic streams
+ tty = False
+ report("interactive terminal", True, "yes" if tty else "no (fine for CI and pipes)")
+
+ # sqlite3 backs the review ledger; it is compiled into CPython normally.
+ try:
+ connection = sqlite3.connect(":memory:")
+ connection.execute("CREATE TABLE t (x INTEGER)")
+ connection.close()
+ report("sqlite3 (for --ledger)", True, f"SQLite {sqlite3.sqlite_version}")
+ except Exception as exc: # noqa: BLE001
+ report("sqlite3 (for --ledger)", False, str(exc))
+
+ # A writable temp dir is needed for bundles, history and the ledger.
+ try:
+ handle = tempfile.NamedTemporaryFile(prefix="pathscope-doctor-", delete=True)
+ handle.write(b"ok")
+ handle.close()
+ report("temporary directory", True, tempfile.gettempdir())
+ except Exception as exc: # noqa: BLE001
+ report("temporary directory", False, str(exc))
+
+ # zipfile backs --bundle. CPython can be built without zlib.
+ try:
+ import zipfile
+
+ buffer = tempfile.SpooledTemporaryFile()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("x.txt", "y")
+ report("zipfile with deflate (for --bundle)", True, "available")
+ buffer.close()
+ except Exception as exc: # noqa: BLE001
+ report("zipfile with deflate (for --bundle)", False, str(exc))
+
+ # The bundled sources must be complete, not just importable.
+ import pathlib
+
+ package_dir = pathlib.Path(__file__).resolve().parent
+ expected = [
+ "cli", "detector", "rules", "sources", "report", "writers", "analytics",
+ "history", "ledger", "playbooks", "scrub", "stream", "bundle", "tui",
+ ]
+ missing = [name for name in expected if not (package_dir / f"{name}.py").is_file()]
+ report("package integrity", not missing, ", ".join(missing) or "all modules present")
+
+ # Nothing in the environment should make PathScope reach the network.
+ proxies = [key for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY") if os.environ.get(key)]
+ report(
+ "network configuration",
+ True,
+ "proxy variables set but never used" if proxies else "no networking code",
+ )
+ return results
+
+
+def render_doctor(results: Sequence[Dict[str, object]]) -> str:
+ """Human-readable ``--doctor`` output."""
+ lines = [f"{PROGRAM} environment check ({__version__})"]
+ for entry in results:
+ mark = "ok " if entry["passed"] else "WARN"
+ detail = entry.get("detail") or entry.get("error") or ""
+ lines.append(f" [{mark}] {entry['name']:<38} {detail}")
+ warnings = sum(1 for entry in results if not entry["passed"])
+ lines.append("")
+ if warnings:
+ lines.append(f"{warnings} check(s) need attention; PathScope can still run.")
+ else:
+ lines.append(f"All {len(results)} environment checks passed.")
+ return "\n".join(lines)
+
+
+__all__ = [
+ "JUNIT_BANDS",
+ "render_doctor",
+ "render_github_annotations",
+ "render_junit",
+ "render_selftest",
+ "run_doctor",
+ "run_selftest",
+]
diff --git a/pathscope/cli.py b/pathscope/cli.py
new file mode 100644
index 0000000..0eb2fd0
--- /dev/null
+++ b/pathscope/cli.py
@@ -0,0 +1,3183 @@
+"""Command-line interface for PathScope.
+
+Exit codes (documented in ``--help`` and the README):
+
+ 0 analysis completed, no candidates found
+ 1 analysis completed, candidates found (only with --fail-on-findings)
+ 2 usage error, unreadable input, invalid configuration, or no usable input
+ 3 internal error while producing a report
+ 130 interrupted with Ctrl-C
+
+The CLI never opens a socket. Input is read from arguments, local files or
+stdin only.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from typing import Optional, Sequence
+
+from . import (
+ GITHUB_URL,
+ INSTAGRAM_URL,
+ PROGRAM,
+ SUPPORT_URL,
+ __version__,
+)
+from .presets import (
+ PRESET_NAMES,
+ STARTER_CONFIGS,
+ describe_presets,
+ resolve_preset,
+)
+from . import presets as presets_module
+from . import assign as assign_module
+from . import attest as attest_module
+from . import audit as audit_module
+from . import completion as completion_module
+from . import impact as impact_module
+from . import ledgermerge as ledgermerge_module
+from . import precision as precision_module
+from . import query as query_module
+from . import scorechange as scorechange_module
+from . import simulate as simulate_module
+from . import waivers as waivers_module
+from . import families as families_module
+from . import openapi as openapi_module
+from . import prcomment as prcomment_module
+from . import queue as queue_module
+from . import redact as redact_module
+from . import sampling as sampling_module
+from . import scope as scope_module
+from . import shadow as shadow_module
+from . import tickets as tickets_module
+from dataclasses import replace
+from .naming import describe_languages, parse_languages
+from . import ci as ci_module
+from .config import Config, ConfigError, describe_schema, load_config, merge_ignore
+from .policy import PolicyError, Policy, evaluate as evaluate_policy, load_policy, parse_inline_policy, starter_policy
+from .detector import (
+ DEFAULT_MIN_SCORE,
+ AnalysisOptions,
+ Baseline,
+ analyze_requests,
+ apply_baseline,
+ summarize,
+)
+from .heuristics import analyze_parameter
+from .report import (
+ FORMAT_CSV,
+ FORMAT_HTML,
+ FORMAT_JSON,
+ FORMAT_JUNIT,
+ FORMAT_MARKDOWN,
+ FORMAT_SARIF,
+ FORMAT_TEXT,
+ FORMATS,
+ Palette,
+ render,
+ render_banner,
+ render_text,
+ render_explanation,
+ supports_color,
+)
+from .progress import NullProgress, Progress
+from .rules import (
+ RuleBook,
+ RuleError,
+ format_rule_table,
+ load_rule_overrides,
+ normalize_rule_id,
+)
+from .valueshape import describe_shapes
+from . import analytics as analytics_module
+from . import history as history_module
+from . import ledger as ledger_module
+from . import playbooks as playbooks_module
+from . import scrub as scrub_module
+from . import bundle as bundle_module
+from . import stream as stream_module
+from . import tui as tui_module
+from . import capturediff as capturediff_module
+from . import calibrate as calibrate_module
+from . import extractor as extractor_module
+from . import project as project_module
+from . import termpacks as termpacks_module
+from .sources import (
+ INPUT_FORMAT_AUTO,
+ INPUT_FORMATS,
+ InputError,
+ LoadResult,
+ load_file,
+ load_stdin,
+ make_url_requests,
+)
+from .textutil import MAX_DECODE_PASSES
+from .writers import (
+ SUPPORTED_EXTENSIONS,
+ render_html_interactive,
+ write_report,
+ writer_supports_interactive,
+)
+
+EXIT_OK = 0
+EXIT_FINDINGS = 1
+EXIT_USAGE = 2
+EXIT_INTERNAL = 3
+EXIT_INTERRUPTED = 130
+
+#: ``--format`` accepts both input selectors and output formats, because the
+#: specification uses the same flag for ``--format har`` and ``--format json``.
+FORMAT_CHOICES = tuple(dict.fromkeys(INPUT_FORMATS + FORMATS))
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="path_detector.py",
+ description=(
+ "PathScope: passive, offline triage of URL and request parameters "
+ "that may be worth reviewing for path-traversal risk. Findings are "
+ "heuristic candidates for manual review, never proof of a "
+ "vulnerability. No requests are made and no values are sent."
+ ),
+ epilog=(
+ "examples:\n"
+ " python3 path_detector.py --url 'https://example.test/view?file=report.pdf'\n"
+ " python3 path_detector.py -i urls.txt\n"
+ " python3 path_detector.py -i capture.har --format json\n"
+ " cat urls.txt | python3 path_detector.py --format sarif\n"
+ " python3 path_detector.py -i capture.har --ignore-param image\n"
+ " python3 path_detector.py -i urls.txt --fail-on-findings\n"
+ "\n"
+ "note: --format selects a HAR/URLs *input* for har/urls/auto and a\n"
+ " report *output* for text/json/csv/sarif. Use --input-format or\n"
+ " --output-format to set both in one run.\n"
+ "\n"
+ "exit codes:\n"
+ " 0 no candidates 1 candidates with --fail-on-findings, or a\n"
+ " failed --policy 2 usage/input error\n"
+ " 3 internal error 130 interrupted (--self-test: 1 on failure)\n"
+ "\n"
+ "presets (--preset):\n"
+ + "\n".join(describe_presets())
+ + "\n\nconfiguration file (--config FILE, JSON, literal terms only):\n"
+ + "\n".join(describe_schema())
+ + "\n\nlinks (displayed only, never opened):\n"
+ f" GitHub: {GITHUB_URL}\n"
+ f" Instagram: {INSTAGRAM_URL}\n"
+ f" Support: {SUPPORT_URL}\n"
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ add_help=False,
+ allow_abbrev=False,
+ )
+ parser.add_argument(
+ "-h", "--help", action="help", help="show this help message and exit"
+ )
+ parser.add_argument(
+ "--version", action="version", version=f"{PROGRAM} {__version__}"
+ )
+
+ source = parser.add_argument_group("input (sources are merged and de-duplicated)")
+ source.add_argument(
+ "--url",
+ action="append",
+ default=[],
+ metavar="URL",
+ help="URL to analyze; repeat for multiple URLs. Quote URLs containing '&'.",
+ )
+ source.add_argument(
+ "-i",
+ "--input",
+ action="append",
+ default=[],
+ metavar="FILE",
+ help="read URLs (one per line) or a local HAR 1.2 file; may be repeated; "
+ "'-' reads stdin",
+ )
+ source.add_argument(
+ "--format",
+ dest="format",
+ choices=FORMAT_CHOICES,
+ default=None,
+ metavar="{auto,urls,har,text,json,csv,sarif,junit}",
+ help="input selector (har/urls/auto) or output format (text/json/csv/sarif)",
+ )
+ source.add_argument(
+ "--input-format",
+ choices=INPUT_FORMATS,
+ default=None,
+ metavar="{auto,urls,har,...}",
+ help="force the input format for files and stdin (default: auto-detect): "
+ + ",".join(INPUT_FORMATS),
+ )
+
+ output = parser.add_argument_group("output")
+ output.add_argument(
+ "--output-format",
+ choices=FORMATS,
+ default=None,
+ metavar="{text,json,csv,sarif,markdown,html,junit}",
+ help="report format written to stdout (default: text)",
+ )
+ output.add_argument(
+ "--json",
+ action="store_true",
+ help="shorthand for --output-format json",
+ )
+ output.add_argument(
+ "--show-values",
+ action="store_true",
+ help="reveal parameter values; hidden by default because they may hold secrets",
+ )
+ output.add_argument(
+ "--no-color",
+ action="store_true",
+ help="disable ANSI colour even on a terminal (NO_COLOR is also honoured)",
+ )
+ output.add_argument(
+ "--no-banner",
+ action="store_true",
+ help="do not print the startup banner and links",
+ )
+ output.add_argument(
+ "-q",
+ "--quiet",
+ action="store_true",
+ help="suppress warnings and the stderr summary (stdout is unaffected)",
+ )
+ output.add_argument(
+ "--save-report",
+ metavar="FILE",
+ help="also write a standalone Markdown (.md) or HTML (.html) report",
+ )
+ output.add_argument(
+ "--interactive",
+ action="store_true",
+ help="with an HTML --save-report, add sorting, filtering and review "
+ "checkboxes (stored in this browser only)",
+ )
+ output.add_argument(
+ "--progress",
+ action="store_true",
+ help="show phase progress on stderr (stdout stays machine-readable)",
+ )
+ output.add_argument(
+ "--stats",
+ action="store_true",
+ help="print parse/analyze timings and counts to stderr (and JSON)",
+ )
+ output.add_argument(
+ "--github-annotations",
+ action="store_true",
+ help="print GitHub Actions ::warning/::notice annotations on stdout",
+ )
+ output.add_argument(
+ "--top",
+ type=int,
+ default=0,
+ metavar="N",
+ help="only show the N highest-scoring candidates in text output (0 = all)",
+ )
+ output.add_argument(
+ "--group-by",
+ choices=("none", "host", "rule", "confidence", "location"),
+ default="none",
+ help="group text output by a field (default: none)",
+ )
+ output.add_argument(
+ "--summary-only",
+ action="store_true",
+ help="print only the summary line and a per-confidence table",
+ )
+
+ tuning = parser.add_argument_group("detection and configuration")
+ tuning.add_argument(
+ "--preset",
+ choices=tuple(PRESET_NAMES) + ("strict", "high", "default", "loud", "broad"),
+ default=None,
+ help="reporting posture: minimal (>=50, no weak names), balanced (>=25), "
+ "noisy (>=10); aliases: strict/high, default, loud/broad",
+ )
+ tuning.add_argument(
+ "--baseline",
+ metavar="FILE",
+ help="previous PathScope JSON report; mark its findings as known",
+ )
+ tuning.add_argument(
+ "--show-known",
+ action="store_true",
+ help="with --baseline/--suppress, still list already-known candidates",
+ )
+ tuning.add_argument(
+ "--suppress",
+ metavar="FILE",
+ help="JSON list of reviewed fingerprints (with optional notes) to hide",
+ )
+ tuning.add_argument(
+ "--mark-reviewed",
+ metavar="FILE",
+ help="write reviewed fingerprints (with --baseline notes) to FILE",
+ )
+ tuning.add_argument(
+ "--explain",
+ metavar="PARAM",
+ help="print the scoring trace for one parameter name and exit",
+ )
+ tuning.add_argument(
+ "--explain-value",
+ metavar="VALUE",
+ default="",
+ help="value to score with --explain (treated as an inert string)",
+ )
+ tuning.add_argument(
+ "--init-config",
+ metavar="FILE",
+ help="write a starter configuration (requires --preset, default balanced) and exit",
+ )
+ tuning.add_argument(
+ "--ignore-param",
+ action="append",
+ default=[],
+ metavar="NAME",
+ help="ignore a parameter name entirely; may be repeated",
+ )
+ tuning.add_argument(
+ "--config",
+ metavar="FILE",
+ help="JSON configuration with extra name terms, ignored names and defaults",
+ )
+ tuning.add_argument(
+ "--min-score",
+ type=int,
+ default=None,
+ metavar="N",
+ help=f"report parameters scoring at least N (0-100, default: {DEFAULT_MIN_SCORE})",
+ )
+ tuning.add_argument(
+ "--max-decode-passes",
+ type=int,
+ default=None,
+ metavar="N",
+ help=f"maximum percent-decoding passes per value (0-5, default: {MAX_DECODE_PASSES})",
+ )
+
+ behaviour = parser.add_argument_group("behaviour")
+ behaviour.add_argument(
+ "--fail-on-findings",
+ action="store_true",
+ help="exit 1 when candidates are found (useful in CI); 0 when none are",
+ )
+ behaviour.add_argument(
+ "--watch",
+ metavar="FILE",
+ help="re-analyze FILE whenever it changes and print only new candidates "
+ "(Ctrl-C to stop)",
+ )
+ behaviour.add_argument(
+ "--interval",
+ type=float,
+ default=2.0,
+ metavar="SECONDS",
+ help="polling interval for --watch (default: 2)",
+ )
+
+ rules_group = parser.add_argument_group("rules and tuning")
+ rules_group.add_argument(
+ "--list-rules",
+ action="store_true",
+ help="print every rule with its effective weight and exit",
+ )
+ rules_group.add_argument(
+ "--rules",
+ metavar="FILE",
+ help="JSON weight overrides, e.g. {\"weights\": {\"name-exact\": 30}, "
+ "\"disable\": [\"name-weak\"]}",
+ )
+ rules_group.add_argument(
+ "--disable-rule",
+ action="append",
+ default=[],
+ metavar="RULE",
+ help="remove a rule from scoring; may be repeated (see --list-rules)",
+ )
+ rules_group.add_argument(
+ "--name-lang",
+ metavar="LIST",
+ default=None,
+ help="term packs: de,es,fr,pt,it,nl, auto (all) or off (default: off)",
+ )
+ rules_group.add_argument(
+ "--no-fold",
+ action="store_true",
+ help="disable diacritic/compatibility folding of parameter names",
+ )
+ rules_group.add_argument(
+ "--no-demote",
+ action="store_true",
+ help="disable value-shape demotion (UUID/hash/JWT/base64/email/IP/scalar)",
+ )
+ rules_group.add_argument(
+ "--dedupe-by",
+ choices=("path", "param", "none"),
+ default="path",
+ help="collapse repeated findings by path (default), by parameter name, or not at all",
+ )
+ rules_group.add_argument(
+ "--max-entries",
+ type=int,
+ default=0,
+ metavar="N",
+ help="analyze at most N input entries (0 = unlimited)",
+ )
+
+ ci_group = parser.add_argument_group("CI integration")
+ ci_group.add_argument(
+ "--policy",
+ metavar="FILE|JSON",
+ help="policy file (max_high/max_medium/max_low/max_total/min_score/...) "
+ "or inline JSON; exit 1 when violated",
+ )
+ ci_group.add_argument(
+ "--init-policy",
+ metavar="FILE",
+ help="write a starter policy file and exit",
+ )
+ ci_group.add_argument(
+ "--self-test",
+ action="store_true",
+ help="run built-in environment checks and exit (1 if any fail)",
+ )
+
+ review = parser.add_argument_group("review workflow")
+ review.add_argument(
+ "--doctor",
+ action="store_true",
+ help="check this installation (interpreter, sqlite, zip, TUI) and exit",
+ )
+ review.add_argument(
+ "--tui",
+ action="store_true",
+ help="open an interactive terminal reviewer (needs a real terminal)",
+ )
+ review.add_argument(
+ "--ledger",
+ metavar="FILE",
+ help="SQLite review ledger: hides reviewed fingerprints and stores an audit trail",
+ )
+ review.add_argument(
+ "--ledger-mark-all",
+ action="store_true",
+ help="record every candidate in --ledger with --ledger-status",
+ )
+ review.add_argument(
+ "--ledger-status",
+ choices=("reviewed", "accepted", "false-positive", "resolved"),
+ default="reviewed",
+ # NOTE: default None in ``_USER_SET``; argparse fills "reviewed".
+ help="status recorded when marking (default: reviewed)",
+ )
+ review.add_argument(
+ "--reviewer",
+ metavar="NAME",
+ default="",
+ help="name recorded in the ledger audit trail (default: $USER)",
+ )
+ review.add_argument(
+ "--review-note",
+ metavar="TEXT",
+ default="",
+ help="note recorded with --mark-reviewed/--ledger-status",
+ )
+ review.add_argument(
+ "--ledger-query",
+ metavar="TEXT",
+ help="filter ledger reviews by host, parameter, rule or status and exit",
+ )
+ review.add_argument(
+ "--ledger-export",
+ metavar="FILE",
+ help="write the ledger as a --baseline compatible JSON file and exit",
+ )
+ review.add_argument(
+ "--import-ledger",
+ metavar="FILE",
+ help="import a 2.1 flat JSON ledger into --ledger and exit",
+ )
+
+ insight = parser.add_argument_group("analysis and reporting extras")
+ insight.add_argument(
+ "--dashboard",
+ action="store_true",
+ help="print score distribution, percentiles, coverage gaps and frequency",
+ )
+ insight.add_argument(
+ "--inventory",
+ action="store_true",
+ help="list endpoints by number of distinct parameters",
+ )
+ insight.add_argument(
+ "--correlate",
+ action="store_true",
+ help="show the parameter x host matrix, shared parameters and chains",
+ )
+ insight.add_argument(
+ "--playbook",
+ metavar="FILE",
+ help="write a Markdown remediation guide for this run",
+ )
+ insight.add_argument(
+ "--list-playbooks",
+ action="store_true",
+ help="list the remediation playbooks and exit",
+ )
+ insight.add_argument(
+ "--history",
+ metavar="FILE",
+ help="append this run to a JSON history file (values are never stored)",
+ )
+ insight.add_argument(
+ "--trend",
+ metavar="FILE",
+ help="analyse a JSON history file and print the trend, then exit",
+ )
+ scrub_group = insight.add_mutually_exclusive_group()
+ scrub_group.add_argument(
+ "--scrub",
+ action="store_true",
+ help="redact credential-shaped values when --show-values is used",
+ )
+ scrub_group.add_argument(
+ "--no-scrub",
+ action="store_true",
+ help="never redact values (bundle exports still scrub)",
+ )
+ insight.add_argument(
+ "--bundle",
+ metavar="FILE",
+ help="write a reproducible, scrubbed support bundle (.zip)",
+ )
+ insight.add_argument(
+ "--inspect-bundle",
+ metavar="FILE",
+ help="print the manifest of a bundle written by --bundle and exit",
+ )
+ insight.add_argument(
+ "--stream",
+ action="store_true",
+ help="read stdin line by line with bounded memory (URL lists and recon)",
+ )
+ insight.add_argument(
+ "--stream-batch",
+ type=int,
+ default=200,
+ metavar="N",
+ help="report every N streamed requests (default: 200)",
+ )
+ insight.add_argument(
+ "--stream-json",
+ action="store_true",
+ help="with --stream, emit one JSON object per batch instead of text",
+ )
+
+ project_group = parser.add_argument_group("project and workflow")
+ project_group.add_argument(
+ "--diff-capture",
+ metavar="FILE",
+ help="compare -i/--input against an earlier capture and show what changed",
+ )
+ project_group.add_argument(
+ "--diff-json",
+ action="store_true",
+ help="with --diff-capture, emit the diff as JSON instead of text",
+ )
+ project_group.add_argument(
+ "--extract",
+ metavar="FILE",
+ action="append",
+ default=[],
+ help="extract endpoint strings from a local HTML/JS file and analyse them "
+ "(repeatable; nothing is fetched)",
+ )
+ project_group.add_argument(
+ "--extract-host",
+ metavar="HOST",
+ help="resolve relative URLs in --extract files against this host",
+ )
+ project_group.add_argument(
+ "--extract-all-hosts",
+ action="store_true",
+ help="keep endpoints on every host found in --extract files (default: own origin)",
+ )
+ project_group.add_argument(
+ "--value-stats",
+ action="store_true",
+ help="profile value lengths/encoding/entropy without printing any value",
+ )
+ project_group.add_argument(
+ "--rule-coverage",
+ action="store_true",
+ help="show which rules fired and which stayed silent on this input",
+ )
+ project_group.add_argument(
+ "--terms",
+ metavar="FILE",
+ action="append",
+ default=[],
+ help="load extra literal terms from a term pack (repeatable)",
+ )
+ project_group.add_argument(
+ "--init-terms",
+ metavar="FILE",
+ help="write a starter term pack and exit",
+ )
+ project_group.add_argument(
+ "--list-terms",
+ metavar="FILE",
+ action="append",
+ default=[],
+ help="validate term pack(s) and print a summary, then exit",
+ )
+ project_group.add_argument(
+ "--compare-presets",
+ action="store_true",
+ help="show how minimal/balanced/noisy classify the same candidates",
+ )
+ project_group.add_argument(
+ "--calibrate",
+ action="store_true",
+ help="recommend a --min-score from accepted vs false-positive ledger reviews",
+ )
+ project_group.add_argument(
+ "--ledger-scores",
+ action="store_true",
+ help="print the score distribution of the ledger reviews and exit",
+ )
+ project_group.add_argument(
+ "--ledger-expire",
+ metavar="DURATION",
+ help="expiry for reviews written this run (30d/12h/2w, or 'none')",
+ )
+ project_group.add_argument(
+ "--ledger-stale",
+ action="store_true",
+ help="list expired reviews and exit (nothing is changed)",
+ )
+ project_group.add_argument(
+ "--ledger-refresh",
+ action="store_true",
+ help="clear the expiry on every stale review (audited) and exit",
+ )
+ project_group.add_argument(
+ "--policy-include-reviewed",
+ action="store_true",
+ help="let --policy fail on findings already reviewed in the ledger",
+ )
+ project_group.add_argument(
+ "--show-project",
+ action="store_true",
+ help="show the discovered .pathscope/project.json and what it supplies, then exit",
+ )
+ project_group.add_argument(
+ "--init-project",
+ metavar="DIR",
+ help="write DIR/.pathscope/project.json and exit",
+ )
+ project_group.add_argument(
+ "--no-project",
+ action="store_true",
+ help="ignore any .pathscope/project.json above the working directory",
+ )
+
+ v26 = parser.add_argument_group("governance and rule tuning")
+ v26.add_argument(
+ "--waivers",
+ metavar="FILE",
+ action="append",
+ default=[],
+ help="load committable JSON waivers (repeatable)",
+ )
+ v26.add_argument(
+ "--init-waivers",
+ metavar="FILE",
+ help="write a starter waiver file and exit",
+ )
+ v26.add_argument(
+ "--list-waivers",
+ action="store_true",
+ help="show the loaded waivers, what each matched, and then continue",
+ )
+ v26.add_argument(
+ "--suppression-audit",
+ action="store_true",
+ help="report dead, overbroad and expired suppressions",
+ )
+ v26.add_argument(
+ "--audit-json",
+ action="store_true",
+ help="with --suppression-audit, emit JSON",
+ )
+ v26.add_argument(
+ "--rule-precision",
+ action="store_true",
+ help="precision per rule from labelled ledger reviews, then exit",
+ )
+ v26.add_argument(
+ "--rule-impact",
+ action="store_true",
+ help="how much each rule contributes to what is reported",
+ )
+ v26.add_argument(
+ "--simulate",
+ metavar="CHANGES",
+ help="re-analyse under hypothetical weights, e.g. 'name-weak=-10,x=off'",
+ )
+ v26.add_argument(
+ "--simulate-json",
+ action="store_true",
+ help="with --simulate, emit JSON instead of text",
+ )
+ v26.add_argument(
+ "--explain-diff",
+ metavar="OLD.json",
+ action="append",
+ default=[],
+ help="with a second report, explain which scores moved and why; then exit",
+ )
+ v26.add_argument(
+ "--where",
+ metavar="EXPR",
+ help="filter findings, e.g. 'score > 60 and confidence = high'",
+ )
+ v26.add_argument(
+ "--where-json",
+ action="store_true",
+ help="with --where, emit the filtered findings as JSON and exit",
+ )
+ v26.add_argument(
+ "--attest",
+ metavar="FILE",
+ help="write a JSON digest of inputs, settings and output",
+ )
+ v26.add_argument(
+ "--verify-attest",
+ metavar="FILE",
+ help="check a report against an attestation",
+ )
+ v26.add_argument(
+ "--assign-owners",
+ metavar="LIST",
+ help="split open work across owners, e.g. alice,bob,carol",
+ )
+ v26.add_argument(
+ "--assign-by",
+ choices=("host", "path", "parameter", "rule", "foundry"),
+ default="host",
+ help="stratum for --assign-owners (default: host)",
+ )
+ v26.add_argument(
+ "--assign-dir",
+ metavar="DIR",
+ help="write one Markdown worklist per owner into DIR",
+ )
+ v26.add_argument(
+ "--ledger-merge",
+ metavar="OTHER",
+ help="plan a merge of OTHER into --ledger (dry run unless --merge-apply)",
+ )
+ v26.add_argument(
+ "--merge-apply",
+ action="store_true",
+ help="with --ledger-merge, actually write the merge",
+ )
+ v26.add_argument(
+ "--merge-prefer",
+ choices=("newer", "left", "right"),
+ default="newer",
+ help="which side wins a status conflict (default: newer)",
+ )
+ v26.add_argument(
+ "--merge-json",
+ action="store_true",
+ help="with --ledger-merge, emit the plan as JSON",
+ )
+
+ v25 = parser.add_argument_group("review workflow and safe sharing")
+ v25.add_argument(
+ "--cluster",
+ action="store_true",
+ help="collapse candidates into path families and review once per shape",
+ )
+ v25.add_argument(
+ "--queue",
+ action="store_true",
+ help="print unreviewed work ordered by score, novelty and leverage",
+ )
+ v25.add_argument(
+ "--queue-limit",
+ type=int,
+ default=20,
+ metavar="N",
+ help="items to show with --queue (default 20; 0 for all)",
+ )
+ v25.add_argument(
+ "--queue-all",
+ action="store_true",
+ help="with --queue, include known and reviewed candidates",
+ )
+ v25.add_argument(
+ "--policy-shadow",
+ metavar="FILE",
+ action="append",
+ default=[],
+ help="evaluate a proposed policy without failing the build (repeatable)",
+ )
+ v25.add_argument(
+ "--sample",
+ type=int,
+ default=0,
+ metavar="N",
+ help="analyse a deterministic subset of N requests (0 = everything)",
+ )
+ v25.add_argument(
+ "--sample-seed",
+ type=int,
+ default=sampling_module.DEFAULT_SEED,
+ metavar="K",
+ help="seed for --sample; the same seed always selects the same subset",
+ )
+ v25.add_argument(
+ "--sample-by",
+ choices=("host", "source", "none"),
+ default="host",
+ help="stratum for --sample (default: host)",
+ )
+ v25.add_argument(
+ "--scope-file",
+ metavar="FILE",
+ help="JSON file declaring in-scope and out-of-scope hosts",
+ )
+ v25.add_argument(
+ "--init-scope",
+ metavar="FILE",
+ help="write a starter scope file and exit",
+ )
+ v25.add_argument(
+ "--openapi",
+ metavar="FILE",
+ help="compare findings against a local OpenAPI/Swagger JSON file",
+ )
+ v25.add_argument(
+ "--openapi-json",
+ action="store_true",
+ help="with --openapi, emit the comparison as JSON",
+ )
+ v25.add_argument(
+ "--export-ticket",
+ metavar="DIR",
+ help="write one Markdown work item per family (or candidate) into DIR",
+ )
+ v25.add_argument(
+ "--ticket-per-candidate",
+ action="store_true",
+ help="with --export-ticket, one ticket per candidate instead of per family",
+ )
+ v25.add_argument(
+ "--ticket-limit",
+ type=int,
+ default=0,
+ metavar="N",
+ help="with --export-ticket, write at most N tickets (0 = all)",
+ )
+ v25.add_argument(
+ "--pr-comment",
+ metavar="FILE",
+ help="write a compact Markdown summary suitable for a pull-request comment",
+ )
+ v25.add_argument(
+ "--run-id",
+ metavar="TEXT",
+ help="identifier written into --pr-comment so a CI job can update in place",
+ )
+ v25.add_argument(
+ "--pr-rows",
+ type=int,
+ default=prcomment_module.DEFAULT_ROWS,
+ metavar="N",
+ help="table rows in --pr-comment (default 10)",
+ )
+ v25.add_argument(
+ "--redact-hosts",
+ action="store_true",
+ help="replace every host with a stable pseudonym in all outputs",
+ )
+ v25.add_argument(
+ "--redact-key",
+ metavar="SECRET",
+ help="key for --redact-hosts so pseudonyms are stable across runs",
+ )
+ v25.add_argument(
+ "--redact-prefix",
+ default=redact_module.PREFIX,
+ metavar="TEXT",
+ help="prefix for --redact-hosts pseudonyms (default: host-)",
+ )
+ v25.add_argument(
+ "--redact-length",
+ type=int,
+ default=redact_module.LENGTH,
+ metavar="N",
+ help="hex characters in --redact-hosts pseudonyms (default 8)",
+ )
+ v25.add_argument(
+ "--completion",
+ metavar="SHELL",
+ help="print a shell completion script generated from this parser and exit",
+ )
+ return parser
+
+
+def resolve_formats(args: argparse.Namespace) -> None:
+ """Map ``--format``/``--json`` onto the explicit input and output formats."""
+ args.input_format = args.input_format or INPUT_FORMAT_AUTO
+ args.output_format = args.output_format or FORMAT_TEXT
+
+ if args.format in INPUT_FORMATS:
+ args.input_format = args.format
+ elif args.format in FORMATS:
+ args.output_format = args.format
+
+ if args.json:
+ args.output_format = FORMAT_JSON
+
+
+def _handle_init_config(args: argparse.Namespace, stderr) -> int:
+ """--init-config: write a starter configuration and exit."""
+ preset = resolve_preset(args.preset) if args.preset else resolve_preset("balanced")
+ if preset is None: # pragma: no cover - argparse restricts choices
+ print("error: unknown preset", file=stderr)
+ return EXIT_USAGE
+ path = args.init_config
+ if os.path.exists(path):
+ print(f"error: refusing to overwrite existing file '{path}'", file=stderr)
+ return EXIT_USAGE
+ try:
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(STARTER_CONFIGS[preset.name])
+ except OSError as exc:
+ print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"wrote starter configuration for preset '{preset.name}' to {path}", file=stderr)
+ return EXIT_OK
+
+
+def _load_baseline(path: str, stderr):
+ """Load a baseline or suppression file. Returns (Baseline|None, code)."""
+ try:
+ with open(path, "r", encoding="utf-8-sig") as handle:
+ payload = json.load(handle)
+ except OSError as exc:
+ print(f"error: cannot read '{path}': {exc.strerror or exc}", file=stderr)
+ return None, EXIT_USAGE
+ except json.JSONDecodeError as exc:
+ print(f"error: '{path}' is not valid JSON: {exc.msg}", file=stderr)
+ return None, EXIT_USAGE
+ try:
+ return Baseline.from_payload(payload, source=path), EXIT_OK
+ except ValueError as exc:
+ print(f"error: '{path}' is not a usable baseline/suppression file: {exc}", file=stderr)
+ return None, EXIT_USAGE
+
+
+def _read_mark_reviewed(path: str) -> dict:
+ """Existing reviewed ledger (fingerprint -> note). Empty when absent."""
+ try:
+ with open(path, "r", encoding="utf-8-sig") as handle:
+ payload = json.load(handle)
+ except (OSError, ValueError):
+ return {}
+ entries = payload.get("suppressions") if isinstance(payload, dict) else None
+ if not isinstance(entries, list):
+ return {}
+ ledger = {}
+ for entry in entries:
+ if isinstance(entry, dict) and isinstance(entry.get("fingerprint"), str):
+ note = entry.get("note")
+ ledger[entry["fingerprint"]] = note if isinstance(note, str) else ""
+ return ledger
+
+
+def _write_reviewed(path: str, ledger: dict, stderr) -> int:
+ payload = {
+ "tool": PROGRAM,
+ "version": __version__,
+ "note": (
+ "Reviewed PathScope fingerprints. Use with --suppress FILE to hide "
+ "them from future runs."
+ ),
+ "suppressions": [
+ {"fingerprint": fp, "note": note}
+ for fp, note in sorted(ledger.items())
+ ],
+ }
+ try:
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
+ json.dump(payload, handle, indent=2)
+ handle.write("\n")
+ except OSError as exc:
+ print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"reviewed {len(ledger)} fingerprint(s) written to {path}", file=stderr)
+ return EXIT_OK
+
+
+def _apply_preset_and_config(args: argparse.Namespace):
+ """Resolve preset -> config file -> CLI overrides. Returns (Config, error)."""
+ config = Config()
+ preset = resolve_preset(args.preset)
+ if preset is not None:
+ config = preset.apply(config)
+
+ file_config = Config()
+ if args.config:
+ try:
+ file_config = load_config(args.config)
+ except ConfigError as exc:
+ return None, str(exc)
+ # A preset chosen on the command line is a base; file values win,
+ # except for CLI flags which are applied further down.
+ if preset is not None:
+ config = preset.apply(config)
+ config = _merge_config(config, file_config)
+
+ # CLI flags always win.
+ if args.min_score is not None:
+ config.min_score = args.min_score
+ config.explicit = frozenset(set(config.explicit) | {"min_score"})
+ if args.max_decode_passes is not None:
+ config.max_decode_passes = args.max_decode_passes
+ config.explicit = frozenset(set(config.explicit) | {"max_decode_passes"})
+ return config, None
+
+
+def _merge_config(base: Config, overlay: Config) -> Config:
+ """Overlay a file config on a preset base (file values win)."""
+ terms = list(dict.fromkeys(list(base.name_terms) + list(overlay.name_terms)))
+ ignored = list(dict.fromkeys(list(base.ignore_params) + list(overlay.ignore_params)))
+ languages = (
+ list(dict.fromkeys(list(base.name_lang) + list(overlay.name_lang)))
+ if overlay.is_explicit("name_lang")
+ else list(base.name_lang)
+ )
+ return Config(
+ name_terms=terms,
+ ignore_params=ignored,
+ name_lang=languages,
+ fold_names=(
+ overlay.fold_names if overlay.is_explicit("fold_names") else base.fold_names
+ ),
+ demote_shapes=(
+ overlay.demote_shapes
+ if overlay.is_explicit("demote_shapes")
+ else base.demote_shapes
+ ),
+ min_score=overlay.min_score if overlay.is_explicit("min_score") else base.min_score,
+ max_decode_passes=(
+ overlay.max_decode_passes
+ if overlay.is_explicit("max_decode_passes")
+ else base.max_decode_passes
+ ),
+ weak_names=(
+ overlay.weak_names if overlay.is_explicit("weak_names") else base.weak_names
+ ),
+ show_values=(
+ overlay.show_values if overlay.is_explicit("show_values") else base.show_values
+ ),
+ source=overlay.source or base.source,
+ extends=overlay.extends or base.extends,
+ explicit=frozenset(set(base.explicit) | set(overlay.explicit)),
+ )
+
+
+def _explain(
+ argv: argparse.Namespace,
+ config: Config,
+ stdout,
+ stderr,
+ book: Optional[RuleBook] = None,
+) -> int:
+ """--explain: show the scoring trace for one parameter name."""
+ name = argv.explain
+ min_score = config.min_score
+ book = book or RuleBook.default()
+ analysis = analyze_parameter(
+ name,
+ getattr(argv, "explain_value", "") or "",
+ max_decode_passes=config.max_decode_passes,
+ extra_terms=tuple(config.merged_terms()),
+ ignore=tuple(config.merged_ignore()),
+ min_score=0,
+ weak_names=config.weak_names,
+ book=book,
+ languages=tuple(config.name_lang),
+ fold=config.fold_names,
+ demote=config.demote_shapes,
+ )
+ colors = Palette(supports_color(stdout) and not argv.no_color)
+ print(
+ f"Preset/config: threshold {min_score}, max decode passes "
+ f"{config.max_decode_passes}, weak names {'on' if config.weak_names else 'off'}",
+ file=stdout,
+ )
+ print(
+ f"Rules: {book.source or 'defaults'}"
+ + (f"; {len(book.disabled)} disabled" if book.disabled else "")
+ + (f"; {', '.join(book.overridden())} overridden" if book.overridden() else ""),
+ file=stdout,
+ )
+ print(
+ "Name layer: fold="
+ + ("on" if config.fold_names else "off")
+ + ", langs="
+ + (",".join(config.name_lang) if config.name_lang else "en")
+ + "; value demotion="
+ + ("on" if config.demote_shapes else "off"),
+ file=stdout,
+ )
+ print(render_explanation(analysis, colors, name=name), file=stdout)
+ if analysis.score >= min_score:
+ print(f"\nAt the current threshold ({min_score}) this parameter WOULD be reported.",
+ file=stdout)
+ else:
+ print(
+ f"\nAt the current threshold ({min_score}) this parameter would NOT be reported "
+ f"(score {analysis.score}).",
+ file=stdout,
+ )
+ if not getattr(argv, "explain_value", ""):
+ print("Tip: add --explain-value VALUE to see value rules score too.", file=stdout)
+ return EXIT_OK
+
+
+def _print_banner(stream, no_banner: bool, no_color: bool) -> None:
+ if no_banner:
+ return
+ palette = Palette(supports_color(stream) and not no_color)
+ print(render_banner(palette), file=stream)
+ print("", file=stream)
+
+
+def _read_stdin() -> str:
+ try:
+ return sys.stdin.read()
+ except (OSError, ValueError): # pragma: no cover - exotic stdin
+ return ""
+
+
+def stdin_is_pipe() -> bool:
+ try:
+ return sys.stdin is not None and not sys.stdin.isatty()
+ except Exception: # pragma: no cover - defensive
+ return False
+
+
+def collect_inputs(
+ args: argparse.Namespace,
+ stdin_text: Optional[str],
+) -> LoadResult:
+ """Merge ``--url``, ``-i/--input`` and piped stdin into one :class:`LoadResult`.
+
+ Raises :class:`InputError` for unreadable or malformed files; recoverable
+ per-line problems become warnings instead of exceptions.
+ """
+ result = LoadResult()
+ result.extend(make_url_requests(args.url))
+
+ for path in args.input:
+ if path == "-":
+ if stdin_text is None:
+ raise InputError("--input '-' was requested but stdin is empty or a terminal")
+ result.extend(load_stdin(stdin_text, args.input_format))
+ stdin_text = None
+ continue
+ result.extend(load_file(path, args.input_format))
+
+ # Auto-piped stdin is used only when no other source was given.
+ if stdin_text is not None and not args.url and not args.input:
+ result.extend(load_stdin(stdin_text, args.input_format))
+
+ unique = LoadResult(warnings=list(result.warnings), skipped=result.skipped)
+ seen = set()
+ for request in result.requests:
+ key = request.dedupe_key
+ if key in seen:
+ continue
+ seen.add(key)
+ unique.requests.append(request)
+ return unique
+
+
+def _build_options(args, config: Config, book: RuleBook) -> "object":
+ """Translate parsed arguments + config into AnalysisOptions."""
+ return AnalysisOptions(
+ min_score=config.min_score,
+ max_decode_passes=config.max_decode_passes,
+ extra_terms=tuple(config.merged_terms()),
+ ignore_params=tuple(merge_ignore(args.ignore_param, config)),
+ show_values=bool(args.show_values or config.show_values),
+ weak_names=config.weak_names,
+ book=book,
+ name_lang=tuple(config.name_lang),
+ fold_names=config.fold_names,
+ demote_shapes=config.demote_shapes,
+ dedupe_by=args.dedupe_by,
+ max_entries=args.max_entries,
+ measure=args.stats,
+ )
+
+
+def _resolve_rule_book(args, stderr):
+ """Build the effective RuleBook. Returns (book, code)."""
+ overrides = {}
+ disabled = list(args.disable_rule or [])
+ source = "defaults"
+ if args.rules:
+ try:
+ weights, extra_disabled = load_rule_overrides(args.rules)
+ except RuleError as exc:
+ print(f"error: {exc}", file=stderr)
+ return None, EXIT_USAGE
+ overrides = weights
+ disabled.extend(extra_disabled)
+ source = args.rules
+ try:
+ book = RuleBook.with_overrides(
+ overrides, [normalize_rule_id(name) for name in disabled], source=source
+ )
+ except RuleError as exc:
+ print(f"error: {exc}", file=stderr)
+ return None, EXIT_USAGE
+ return book, EXIT_OK
+
+
+def _resolve_policy(args, stderr):
+ """Build the CI policy from --policy (file or inline JSON)."""
+ if not args.policy:
+ return None, EXIT_OK
+ try:
+ if os.path.exists(args.policy):
+ return load_policy(args.policy), EXIT_OK
+ if args.policy.lstrip().startswith("{"):
+ return parse_inline_policy(args.policy), EXIT_OK
+ raise PolicyError(f"policy file not found: {args.policy}")
+ except PolicyError as exc:
+ print(f"error: {exc}", file=stderr)
+ return None, EXIT_USAGE
+
+
+def _handle_init_policy(args, stderr) -> int:
+ path = args.init_policy
+ if os.path.exists(path):
+ print(f"error: refusing to overwrite existing file '{path}'", file=stderr)
+ return EXIT_USAGE
+ try:
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(starter_policy())
+ except OSError as exc:
+ print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"wrote starter CI policy to {path}", file=stderr)
+ return EXIT_OK
+
+
+def _handle_ledger_admin(args, stdout, stderr) -> int:
+ """--ledger-query / --ledger-export / --import-ledger (no analysis)."""
+ if not args.ledger:
+ print("error: --ledger-query, --ledger-export and --import-ledger "
+ "need --ledger FILE", file=stderr)
+ return EXIT_USAGE
+ try:
+ ledger = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ if args.import_ledger:
+ try:
+ with open(args.import_ledger, "r", encoding="utf-8-sig") as handle:
+ payload = json.load(handle)
+ except OSError as exc:
+ print(f"error: cannot read '{args.import_ledger}': "
+ f"{exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ except json.JSONDecodeError as exc:
+ print(f"error: '{args.import_ledger}' is not valid JSON: {exc.msg}",
+ file=stderr)
+ return EXIT_USAGE
+ try:
+ count = ledger.import_json_ledger(payload, reviewer=args.reviewer)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"imported {count} review(s) into {args.ledger}", file=stderr)
+ return EXIT_OK
+ if args.ledger_export:
+ payload = ledger.to_baseline_payload()
+ try:
+ with open(args.ledger_export, "w", encoding="utf-8", newline="\n") as handle:
+ json.dump(payload, handle, indent=2)
+ handle.write("\n")
+ except OSError as exc:
+ print(f"error: cannot write '{args.ledger_export}': "
+ f"{exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(
+ f"exported {len(payload['suppressions'])} review(s) to "
+ f"{args.ledger_export}",
+ file=stderr,
+ )
+ return EXIT_OK
+ # --ledger-query TEXT: substring match across the useful columns.
+ needle = (args.ledger_query or "").strip().lower()
+ reviews = [
+ review
+ for review in ledger.all_reviews()
+ if not needle
+ or needle in review.host.lower()
+ or needle in review.parameter.lower()
+ or needle in review.rule.lower()
+ or needle in review.status.lower()
+ or needle in review.reviewer.lower()
+ or needle in review.note.lower()
+ or needle in review.fingerprint.lower()
+ ]
+ print(render_ledger_query(reviews), file=stdout)
+ return EXIT_OK
+ finally:
+ ledger.close()
+
+
+def _reviewer_name(args) -> str:
+ """Resolve --reviewer, falling back to the OS user without leaking it."""
+ if args.reviewer:
+ return args.reviewer
+ return os.environ.get("USER") or os.environ.get("USERNAME") or ""
+
+
+def _validate_float_interval(parser, args) -> None:
+ if args.interval <= 0:
+ parser.error("--interval must be a positive number of seconds")
+
+
+def run(
+ argv: Optional[Sequence[str]] = None,
+ *,
+ stdout=None,
+ stderr=None,
+ stdin_text: Optional[str] = None,
+) -> int:
+ """Programmatic entry point. Returns the process exit code."""
+ stdout = stdout if stdout is not None else sys.stdout
+ stderr = stderr if stderr is not None else sys.stderr
+ argv_list = list(sys.argv[1:] if argv is None else argv)
+ parser = build_parser()
+
+ _print_banner(stderr, "--no-banner" in argv_list, "--no-color" in argv_list)
+
+ args = parser.parse_args(argv_list)
+ resolve_formats(args)
+ quiet = args.quiet
+
+ if args.completion:
+ try:
+ script = completion_module.render(args.completion, parser)
+ except completion_module.CompletionError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ stdout.write(script)
+ return EXIT_OK
+ progress = Progress(args.progress, stderr) if args.progress else NullProgress()
+
+ # -- early exits -----------------------------------------------------
+ if args.init_config:
+ return _handle_init_config(args, stderr)
+ if args.init_policy:
+ return _handle_init_policy(args, stderr)
+ if args.self_test:
+ results = ci_module.run_selftest()
+ print(ci_module.render_selftest(results), file=stdout)
+ return EXIT_OK if all(entry["passed"] for entry in results) else EXIT_FINDINGS
+ if args.doctor:
+ results = ci_module.run_doctor()
+ print(ci_module.render_doctor(results), file=stdout)
+ return EXIT_OK if all(entry["passed"] for entry in results) else EXIT_FINDINGS
+ if args.list_playbooks:
+ print(f"{PROGRAM} remediation playbooks", file=stdout)
+ for line in playbooks_module.describe_all():
+ print(line, file=stdout)
+ return EXIT_OK
+ if args.trend:
+ try:
+ history_doc = history_module.load_history(args.trend)
+ except history_module.HistoryError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(render_trend(history_module.analyze_history(history_doc)), file=stdout)
+ return EXIT_OK
+ if args.inspect_bundle:
+ try:
+ manifest = bundle_module.read_manifest(args.inspect_bundle)
+ members = bundle_module.list_bundle(args.inspect_bundle)
+ except bundle_module.BundleError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"{PROGRAM} bundle: {args.inspect_bundle}", file=stdout)
+ for key in sorted(manifest):
+ print(f" {key:<22} {manifest[key]}", file=stdout)
+ print(f" {'members':<22} {', '.join(sorted(members))}", file=stdout)
+ return EXIT_OK
+ if (
+ args.ledger_query is not None
+ or args.ledger_export
+ or args.import_ledger
+ ):
+ return _handle_ledger_admin(args, stdout, stderr)
+ if args.init_terms:
+ return _handle_init_terms(args, stderr)
+ if args.list_terms:
+ return _handle_list_terms(args, stdout, stderr)
+ if args.init_project:
+ return _handle_init_project(args, stderr)
+ if args.init_scope:
+ return _handle_init_scope(args, stderr)
+ if args.init_waivers:
+ return _handle_init_waivers(args, stderr)
+ if args.rule_precision:
+ return _handle_rule_precision(args, stdout, stderr)
+ if args.explain_diff:
+ return _handle_explain_diff(args, stdout, stderr)
+ if args.ledger_merge:
+ return _handle_ledger_merge(args, stdout, stderr)
+ if args.show_project:
+ return _handle_show_project(args, stdout, stderr)
+ if args.ledger_stale or args.ledger_refresh:
+ return _handle_ledger_expiry(args, stdout, stderr)
+ if args.ledger_scores:
+ return _handle_ledger_scores(args, stdout, stderr)
+ if args.calibrate:
+ return _handle_calibrate(args, stdout, stderr)
+
+ # -- 2.4 project discovery (command-line values always win) ------------
+ try:
+ project = project_module.discover(enabled=not args.no_project)
+ except project_module.ProjectError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ if project is not None:
+ supplied = _apply_project(args, project)
+ if not quiet and supplied:
+ print(
+ f"pathscope: using {project.path} ({', '.join(supplied)})",
+ file=stderr,
+ )
+ for missing in project.missing_files():
+ print(
+ f"warning: project references a missing file: {missing}",
+ file=stderr,
+ )
+
+ config, error = _apply_preset_and_config(args)
+ if error:
+ print(f"error: {error}", file=stderr)
+ return EXIT_USAGE
+
+ # -- 2.4 term packs merge into the effective term list -----------------
+ if args.terms:
+ try:
+ packs = termpacks_module.load_packs(args.terms)
+ merged_terms, merged_ignore = termpacks_module.merge_terms(
+ config.merged_terms(), packs
+ )
+ except termpacks_module.TermPackError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ config.name_terms = merged_terms
+ config.ignore_params = list(
+ dict.fromkeys(list(config.ignore_params) + merged_ignore)
+ )
+
+ if not 0 <= config.min_score <= 100:
+ parser.error("--min-score must be between 0 and 100")
+ if not 0 <= config.max_decode_passes <= 5:
+ parser.error("--max-decode-passes must be between 0 and 5")
+ if args.max_entries < 0:
+ parser.error("--max-entries must be 0 (unlimited) or a positive number")
+
+ # CLI name/fold/demote switches override the configuration file.
+ if args.name_lang is not None:
+ try:
+ config.name_lang = list(parse_languages(args.name_lang))
+ except ValueError as exc:
+ parser.error(f"--name-lang: {exc}")
+ if args.no_fold:
+ config.fold_names = False
+ if args.no_demote:
+ config.demote_shapes = False
+
+ where_filter = None
+ if args.where:
+ try:
+ where_filter = query_module.parse(args.where)
+ except query_module.QueryError as exc:
+ print(f"error: --where: {exc}", file=stderr)
+ return EXIT_USAGE
+
+ book, code = _resolve_rule_book(args, stderr)
+ if book is None:
+ return code
+
+ if args.list_rules:
+ for line in format_rule_table(book):
+ print(line, file=stdout)
+ reordered = book.overridden()
+ if reordered:
+ print(f"\nOverridden in this run ({book.source}): {', '.join(reordered)}")
+ return EXIT_OK
+
+ if args.explain:
+ return _explain(args, config, stdout, stderr, book=book)
+
+ if args.top is not None and args.top < 0:
+ parser.error("--top must be 0 (all) or a positive number")
+ if args.interactive and not (
+ args.save_report and writer_supports_interactive(args.save_report)
+ ):
+ parser.error("--interactive requires an HTML --save-report FILE")
+
+ policy, code = _resolve_policy(args, stderr)
+ if policy is None and args.policy:
+ return code
+
+ baseline = None
+ if args.baseline:
+ baseline, code = _load_baseline(args.baseline, stderr)
+ if baseline is None:
+ return code
+ if args.suppress:
+ suppression, code = _load_baseline(args.suppress, stderr)
+ if suppression is None:
+ return code
+ if baseline is None:
+ baseline = suppression
+ else:
+ merged = Baseline(source=f"{args.baseline} + {args.suppress}")
+ merged.fingerprints = dict(baseline.fingerprints)
+ merged.fingerprints.update(suppression.fingerprints)
+ merged.entries = list(baseline.entries) + list(suppression.entries)
+ baseline = merged
+
+ options = _build_options(args, config, book)
+
+ # -- 2.3 flag validation ---------------------------------------------
+ if args.stream_batch < 1:
+ parser.error("--stream-batch must be at least 1")
+ if args.tui:
+ if not tui_module.available():
+ print(
+ "error: --tui needs an interactive terminal "
+ "(stdin and stdout must be TTYs)",
+ file=stderr,
+ )
+ return EXIT_USAGE
+ if not args.ledger:
+ print("error: --tui needs --ledger FILE to save reviews", file=stderr)
+ return EXIT_USAGE
+ if "--ledger-status" in argv_list and not args.ledger:
+ print("error: --ledger-status needs --ledger FILE", file=stderr)
+ return EXIT_USAGE
+ if "--review-note" in argv_list and not args.ledger:
+ print("error: --review-note needs --ledger FILE", file=stderr)
+ return EXIT_USAGE
+ if args.ledger_mark_all and not args.ledger:
+ print("error: --ledger-mark-all needs --ledger FILE", file=stderr)
+ return EXIT_USAGE
+
+ # -- watch mode ------------------------------------------------------
+ if args.watch:
+ _validate_float_interval(parser, args)
+ from .watch import WatchError, watch_forever # local import keeps startup light
+
+ if not os.path.exists(args.watch):
+ print(f"error: --watch file not found: {args.watch}", file=stderr)
+ return EXIT_USAGE
+ try:
+ watch_forever(
+ args.watch,
+ options,
+ interval=args.interval,
+ input_format=args.input_format,
+ stdout=stdout,
+ stderr=stderr,
+ )
+ except WatchError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ return EXIT_OK
+
+ if args.diff_capture:
+ return _run_capture_diff(args, stdout, stderr)
+
+ if args.stream:
+ return _run_stream(args, options, stdout, stderr, stdin_text)
+
+ if args.extract:
+ return _run_extract(args, options, stdout, stderr)
+
+ needs_stdin = "-" in args.input
+ if stdin_text is None and needs_stdin:
+ stdin_text = _read_stdin()
+ elif stdin_text is None and not args.url and not args.input and stdin_is_pipe():
+ stdin_text = _read_stdin()
+
+ progress.start("reading input")
+ try:
+ loaded = collect_inputs(args, stdin_text)
+ except InputError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ except KeyboardInterrupt:
+ print("\ninterrupted", file=stderr)
+ return EXIT_INTERRUPTED
+ progress.finish(f"{len(loaded.requests)} request(s)")
+
+ if not quiet:
+ for warning in loaded.warnings:
+ print(f"warning: {warning}", file=stderr)
+
+ if args.scope_file:
+ try:
+ scope = scope_module.load_scope(args.scope_file)
+ except scope_module.ScopeError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ kept, scope_summary = scope_module.apply_scope(loaded.requests, scope)
+ message = scope_module.describe_drop(scope_summary, scope)
+ if scope_summary.get("dropped"):
+ # Never silent: a scope file that drops everything and a capture
+ # that was empty must not look the same in a pipeline log.
+ print(f"warning: {message}", file=stderr)
+ elif not quiet:
+ print(f"pathscope: {message}", file=stderr)
+ loaded.requests = kept
+ analysis_scope = scope
+ else:
+ analysis_scope = None
+
+ if args.sample:
+ try:
+ sampled = sampling_module.sample(
+ loaded.requests,
+ args.sample,
+ seed=args.sample_seed,
+ by=args.sample_by,
+ )
+ except sampling_module.SamplingError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ loaded.requests = sampled.requests
+ sample_result = sampled
+ if not quiet:
+ print(f"pathscope: {sampled.describe()}", file=stderr)
+ else:
+ sample_result = None
+
+ if not loaded.requests:
+ print("error: no usable input found.", file=stderr)
+ print(
+ " Use --url URL, -i/--input FILE (or - for stdin), "
+ "or pipe URLs/HAR on stdin.",
+ file=stderr,
+ )
+ if analysis_scope is not None:
+ print(
+ " Every request was out of scope for "
+ f"{args.scope_file}; check the in_scope patterns.",
+ file=stderr,
+ )
+ elif sample_result is not None and sample_result.population:
+ print(
+ " --sample selected 0 of "
+ f"{sample_result.population} request(s).",
+ file=stderr,
+ )
+ print(" Try: python3 path_detector.py --help", file=stderr)
+ return EXIT_USAGE
+
+ try:
+ progress.start("analyzing", len(loaded.requests))
+ report_data = analyze_requests(loaded.requests, options)
+ progress.finish(f"{report_data.candidate_count} candidate(s)")
+ analysis_warnings = list(report_data.warnings)
+ report_data.warnings = list(loaded.warnings) + analysis_warnings
+ report_data.skipped = loaded.skipped
+ if not quiet:
+ for warning in analysis_warnings:
+ print(f"warning: {warning}", file=stderr)
+ report_data.stats.setdefault("parse_seconds", 0.0)
+ report_data.rules = book.as_dict()
+ report_data.rules_source = book.source
+ report_data.name_lang = tuple(config.name_lang)
+ if baseline is not None:
+ apply_baseline(report_data, baseline, show_known=args.show_known)
+ if args.top:
+ report_data.findings = report_data.findings[: args.top]
+ for index, finding in enumerate(report_data.findings, start=1):
+ finding.index = index
+ colors = Palette(supports_color(stdout) and not args.no_color)
+ ledger_store = None
+ if args.ledger:
+ try:
+ ledger_store = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ hidden = 0
+ # Mark ledger decisions on the findings first: SARIF suppressions, JUnit
+ # and the policy gate all key off finding.status, so every
+ # output stays consistent with what the ledger says.
+ if ledger_store is not None:
+ reviewed_now = _mark_reviewed_status(report_data, ledger_store)
+ if reviewed_now and not quiet:
+ print(
+ f"pathscope: {reviewed_now} finding(s) already reviewed in "
+ f"{args.ledger}",
+ file=stderr,
+ )
+ # The TUI shows reviewed rows *marked* rather than hiding them, so the
+ # reviewer can see and undo a previous decision. The same applies when
+ # the policy is explicitly asked to fail on reviewed findings: hiding
+ # them first would make --policy-include-reviewed a no-op.
+ keep_reviewed_visible = (
+ args.tui
+ or args.policy_include_reviewed
+ or args.show_known
+ or bool(policy is not None and policy.fail_on_reviewed)
+ )
+ if ledger_store is not None and not keep_reviewed_visible:
+ hidden = _hide_reviewed(report_data, ledger_store)
+ if hidden:
+ # Never silent: the user must know results were filtered even
+ # with --quiet (a script reading stdout would otherwise see
+ # "0 candidates" and draw the wrong conclusion).
+ print(
+ f"pathscope: {hidden} candidate(s) already reviewed "
+ f"in {args.ledger} (use --show-known to include)",
+ file=stderr,
+ )
+ # -- waivers: applied after the ledger, before every renderer and the
+ # policy, so all outputs agree on what has been accepted. --------------
+ waiver_set = None
+ if args.waivers:
+ try:
+ waiver_set = waivers_module.merge(
+ [waivers_module.load_waivers(path) for path in args.waivers]
+ )
+ except waivers_module.WaiverError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ waived_count, expired_skipped = waivers_module.apply_waivers(
+ report_data.findings, waiver_set
+ )
+ if waived_count:
+ # Same contract as the ledger: filtered results are never
+ # silent, because a pipeline reading "0 candidates" from a
+ # fully-waived scan would draw exactly the wrong conclusion.
+ if args.show_known or args.list_waivers:
+ print(
+ f"pathscope: {waived_count} finding(s) waived by "
+ f"{len(args.waivers)} waiver file(s) (shown)",
+ file=stderr,
+ )
+ else:
+ print(
+ f"pathscope: {waived_count} finding(s) waived by "
+ f"{len(args.waivers)} waiver file(s) (hidden; "
+ "--show-known to include)",
+ file=stderr,
+ )
+ waived = [f for f in report_data.findings if f.status == "waived"]
+ report_data.findings = [
+ f for f in report_data.findings if f.status != "waived"
+ ]
+ for index, finding in enumerate(report_data.findings, start=1):
+ finding.index = index
+ del waived
+ if expired_skipped:
+ print(
+ f"warning: {expired_skipped} waiver(s) have expired and hide "
+ "nothing; run --suppression-audit",
+ file=stderr,
+ )
+ if args.list_waivers:
+ print("", file=stdout)
+ print(
+ waivers_module.render_waivers(waiver_set),
+ file=stdout,
+ )
+
+ should_scrub = not args.no_scrub and (
+ args.scrub or args.bundle or args.playbook or args.dashboard
+ )
+ if should_scrub:
+ report_data = scrub_module.scrub_report(report_data)
+ # Redaction is the last transformation before rendering: every format
+ # and every post-run artefact then sees pseudonyms only. It runs after
+ # status marking because fingerprints (which embed the host) must stay
+ # untouched for baselines and ledger rows to keep working.
+ host_map = None
+ if args.redact_hosts:
+ try:
+ host_map = redact_module.build_map(
+ args.redact_key,
+ prefix=args.redact_prefix,
+ length=args.redact_length,
+ )
+ except redact_module.RedactionError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ report_data = redact_module.redact_report(report_data, host_map)
+ loaded.requests = redact_module.redact_requests(loaded.requests, host_map)
+ # Redaction changes what every output means, so it is announced even
+ # with --quiet: a reader must know hosts are pseudonyms.
+ print(f"pathscope: {redact_module.describe(host_map)}", file=stderr)
+ # The gate must judge the whole picture, not the slice the user asked
+ # to look at: a --where that excludes everything would otherwise turn
+ # --fail-on-findings into a silent pass. Snapshot the count first.
+ gate_candidate_count = len(report_data.findings)
+ if where_filter is not None:
+ # Filtering is a view: the policy still sees everything it was
+ # asked to judge, and the exit code is unchanged by --where.
+ matched = query_module.filter_findings(report_data.findings, where_filter)
+ if not quiet:
+ print(
+ f"pathscope: --where matched {len(matched)} of "
+ f"{len(report_data.findings)} finding(s)",
+ file=stderr,
+ )
+ if args.where_json:
+ payload = {
+ "where": query_module.describe(where_filter),
+ "matched": len(matched),
+ "total": len(report_data.findings),
+ "findings": [finding.as_dict() for finding in matched],
+ }
+ rendered = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
+ report_data = replace(
+ report_data, findings=list(matched)
+ )
+ matched_only = True
+ else:
+ report_data = replace(report_data, findings=list(matched))
+ matched_only = False
+ else:
+ matched_only = False
+
+ if args.github_annotations:
+ rendered = ci_module.render_github_annotations(report_data)
+ elif matched_only:
+ pass # --where --where-json already produced the body
+ elif args.summary_only:
+ rendered = render_summary_only(report_data, colors)
+ elif args.output_format == FORMAT_TEXT:
+ rendered = render_text(report_data, colors, group_by=args.group_by)
+ else:
+ rendered = render(report_data, args.output_format, colors)
+ except Exception as exc: # noqa: BLE001 - last-resort guard, never crash
+ print(f"error: could not produce the report ({exc})", file=stderr)
+ return EXIT_INTERNAL
+
+ stdout.write(rendered)
+ if not rendered.endswith("\n"):
+ stdout.write("\n")
+ stdout.flush()
+
+ # -- 2.3 insight views (printed after the main report) ----------------
+ if args.dashboard and not args.summary_only:
+ print("", file=stdout)
+ print(render_dashboard(report_data, loaded.requests, colors), file=stdout)
+ if args.inventory:
+ print("", file=stdout)
+ print(render_inventory(loaded.requests), file=stdout)
+ if args.correlate:
+ print("", file=stdout)
+ print(render_correlation(report_data, loaded.requests), file=stdout)
+ if args.value_stats:
+ print("", file=stdout)
+ print(
+ analytics_module.render_value_stats(
+ analytics_module.value_stats(loaded.requests)
+ ),
+ file=stdout,
+ )
+ if args.rule_coverage:
+ print("", file=stdout)
+ print(
+ analytics_module.render_rule_coverage(
+ analytics_module.rule_coverage(report_data, book)
+ ),
+ file=stdout,
+ )
+ if args.compare_presets:
+ print("", file=stdout)
+ print(
+ presets_module.render_preset_comparison(
+ presets_module.compare_presets(report_data)
+ ),
+ file=stdout,
+ )
+ families = None
+ if args.cluster:
+ families = families_module.cluster(report_data.findings)
+ print("", file=stdout)
+ print(
+ families_module.render_clusters(families, len(report_data.findings)),
+ file=stdout,
+ )
+ if args.queue:
+ try:
+ if families is None:
+ families = families_module.cluster(report_data.findings)
+ items = queue_module.build_queue(
+ report_data.findings,
+ limit=args.queue_limit,
+ include_known=args.queue_all,
+ families=families,
+ )
+ except queue_module.QueueError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ settled = sum(
+ 1 for f in report_data.findings if f.status in queue_module.SETTLED
+ )
+ print("", file=stdout)
+ print(
+ queue_module.render_queue(
+ items, settled=settled, total=len(report_data.findings)
+ ),
+ file=stdout,
+ )
+ if args.openapi:
+ try:
+ spec = openapi_module.load_spec(args.openapi)
+ except openapi_module.SpecError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ spec_report = openapi_module.compare(report_data, spec)
+ print("", file=stdout)
+ if args.openapi_json:
+ print(
+ json.dumps(spec_report.as_dict(), indent=2, ensure_ascii=False),
+ file=stdout,
+ )
+ else:
+ print(openapi_module.render_spec_report(spec_report), file=stdout)
+ if args.simulate:
+ try:
+ changes = simulate_module.parse_changes(args.simulate)
+ simulation = simulate_module.simulate(loaded.requests, options, changes)
+ except simulate_module.SimulationError as exc:
+ print(f"error: --simulate: {exc}", file=stderr)
+ return EXIT_USAGE
+ print("", file=stdout)
+ if args.simulate_json:
+ print(
+ json.dumps(simulation.as_dict(), indent=2, ensure_ascii=False),
+ file=stdout,
+ )
+ else:
+ print(simulate_module.render_simulation(simulation), file=stdout)
+ if args.rule_impact:
+ print("", file=stdout)
+ print(
+ impact_module.render_impact(
+ impact_module.rule_impact(report_data, book),
+ threshold=config.min_score,
+ ),
+ file=stdout,
+ )
+ if args.suppression_audit:
+ ledger_reviews = None
+ if ledger_store is not None:
+ ledger_reviews = ledger_store.all_reviews()
+ audit_report = audit_module.audit(
+ report_data,
+ baseline=baseline,
+ waivers=waiver_set,
+ ledger_reviews=ledger_reviews,
+ )
+ print("", file=stdout)
+ if args.audit_json:
+ print(
+ json.dumps(audit_report.as_dict(), indent=2, ensure_ascii=False),
+ file=stdout,
+ )
+ else:
+ print(audit_module.render_audit(audit_report), file=stdout)
+ if args.assign_owners:
+ try:
+ owners = assign_module.parse_owners(args.assign_owners)
+ distribution = assign_module.assign(
+ [f for f in report_data.findings if f.status not in ("known", "waived")],
+ owners,
+ strategy=args.assign_by,
+ )
+ if args.assign_dir:
+ written = assign_module.write_slices(args.assign_dir, distribution)
+ except assign_module.AssignError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ except OSError as exc:
+ print(f"error: cannot write worklists: {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print("", file=stdout)
+ print(assign_module.render_distribution(distribution), file=stdout)
+ if args.assign_dir:
+ print(
+ f"pathscope: wrote {len(written)} worklist file(s) to {args.assign_dir}",
+ file=stderr,
+ )
+
+ if args.save_report:
+ try:
+ kind = write_report(
+ args.save_report, report_data, interactive=args.interactive
+ )
+ except (OSError, ValueError) as exc:
+ print(f"error: cannot write report: {exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ extra = " (interactive)" if args.interactive and kind == "html" else ""
+ print(
+ f"pathscope: wrote {kind} report{extra} to {args.save_report}",
+ file=stderr,
+ )
+
+ if args.playbook:
+ try:
+ markdown = playbooks_module.render_playbook_markdown(report_data)
+ with open(args.playbook, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(markdown)
+ if not markdown.endswith("\n"):
+ handle.write("\n")
+ except OSError as exc:
+ print(f"error: cannot write playbook: {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ print(f"pathscope: wrote remediation playbook to {args.playbook}", file=stderr)
+
+ if args.export_ticket:
+ try:
+ tickets = tickets_module.build_tickets(
+ report_data,
+ per_candidate=args.ticket_per_candidate,
+ limit=args.ticket_limit,
+ )
+ written = tickets_module.write_tickets(args.export_ticket, tickets)
+ index_path = os.path.join(args.export_ticket, "INDEX.md")
+ with open(index_path, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(
+ tickets_module.render_index(tickets, args.export_ticket)
+ )
+ except tickets_module.TicketError as exc:
+ print(f"error: cannot export tickets: {exc}", file=stderr)
+ return EXIT_USAGE
+ except OSError as exc:
+ print(f"error: cannot export tickets: {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ print(
+ f"pathscope: wrote {len(written)} work item(s) to "
+ f"{args.export_ticket} (values never included)",
+ file=stderr,
+ )
+
+ if args.pr_comment:
+ if args.pr_rows < 0:
+ print("error: --pr-rows must be 0 or a positive number", file=stderr)
+ return EXIT_USAGE
+ comment = prcomment_module.render_comment(
+ report_data,
+ exit_code=EXIT_OK,
+ rows=args.pr_rows,
+ run_id=args.run_id or "",
+ )
+ try:
+ with open(args.pr_comment, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(comment.body)
+ except OSError as exc:
+ print(f"error: cannot write PR comment: {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ note = f", {comment.omitted} row(s) left out" if comment.omitted else ""
+ print(
+ f"pathscope: wrote {comment.size} char(s) to {args.pr_comment}"
+ f"{note}",
+ file=stderr,
+ )
+
+ if args.bundle:
+ try:
+ manifest = bundle_module.build_bundle(
+ args.bundle,
+ report_data,
+ exit_code=EXIT_OK,
+ settings={
+ "min_score": config.min_score,
+ "name_lang": ",".join(config.name_lang),
+ "format": args.output_format,
+ },
+ )
+ except bundle_module.BundleError as exc:
+ print(f"error: cannot write bundle: {exc}", file=stderr)
+ return EXIT_USAGE
+ except OSError as exc:
+ print(f"error: cannot write bundle: {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ print(
+ f"pathscope: wrote bundle {args.bundle} "
+ f"({len(manifest.get('files', []))} files, values scrubbed)",
+ file=stderr,
+ )
+
+ if args.history:
+ try:
+ record = history_module.run_record(
+ report_data,
+ label=" ".join(argv_list) if argv_list else "",
+ settings={
+ "min_score": config.min_score,
+ "format": args.output_format,
+ "preset": args.preset or "",
+ },
+ )
+ document = history_module.append_run(args.history, record)
+ except history_module.HistoryError as exc:
+ print(f"error: cannot update history: {exc}", file=stderr)
+ return EXIT_USAGE
+ except OSError as exc:
+ print(f"error: cannot update history: {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ print(
+ f"pathscope: appended run to {args.history} "
+ f"({len(document.get('runs', []))} run(s) kept)",
+ file=stderr,
+ )
+
+ if args.attest:
+ try:
+ attestation = attest_module.build(
+ inputs=list(args.input),
+ rendered=rendered,
+ settings={
+ "min_score": config.min_score,
+ "preset": args.preset or "",
+ "format": args.output_format,
+ "dedupe_by": args.dedupe_by,
+ "name_lang": list(config.name_lang),
+ "rules": dict(report_data.rules),
+ "rules_source": report_data.rules_source,
+ "sample_seed": args.sample_seed if args.sample else 0,
+ "sample_size": args.sample,
+ "waivers": list(args.waivers),
+ "where": args.where or "",
+ },
+ counts={
+ "requests": report_data.requests_analyzed,
+ "parameters": report_data.parameters_analyzed,
+ "candidates": report_data.candidate_count,
+ },
+ )
+ with open(args.attest, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(attestation.render())
+ except (attest_module.AttestationError, OSError) as exc:
+ print(f"error: cannot write attestation: {exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ print(
+ f"pathscope: wrote attestation to {args.attest} "
+ f"(digests only; values are never included)",
+ file=stderr,
+ )
+
+ if args.verify_attest:
+ try:
+ problems = attest_module.verify(
+ args.verify_attest, rendered=rendered, inputs=list(args.input)
+ )
+ except attest_module.AttestationError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(
+ attest_module.render_verification(problems, args.verify_attest),
+ file=stderr,
+ )
+ if problems:
+ return EXIT_FINDINGS
+
+ if args.mark_reviewed:
+ ledger = _read_mark_reviewed(args.mark_reviewed)
+ for finding in report_data.findings:
+ note = ""
+ if baseline is not None:
+ note = baseline.fingerprints.get(finding.fingerprint, "")
+ ledger[finding.fingerprint] = note
+ code = _write_reviewed(args.mark_reviewed, ledger, stderr)
+ if code != EXIT_OK:
+ return code
+
+ if args.ledger_mark_all and ledger_store is not None:
+ try:
+ written = ledger_store.record_findings(
+ report_data.findings,
+ status=args.ledger_status,
+ reviewer=_reviewer_name(args),
+ note=args.review_note,
+ expire=args.ledger_expire or "",
+ owner=args.reviewer or "",
+ )
+ except ledger_module.LedgerError as exc:
+ print(f"error: ledger write failed: {exc}", file=stderr)
+ return EXIT_USAGE
+ if not quiet:
+ print(
+ f"pathscope: recorded {written} review(s) in {args.ledger}",
+ file=stderr,
+ )
+
+ # -- 2.3 terminal reviewer --------------------------------------------
+ if args.tui and ledger_store is not None:
+ reviewed_at_start = ledger_store.fingerprints()
+ # Rows already in the ledger start *marked*, so `s` is a no-op until
+ # the reviewer changes something; the audit trail records only diffs.
+ state = tui_module.build_state(report_data)
+ state.marked = {f.fingerprint for f in report_data.findings
+ if f.fingerprint in reviewed_at_start}
+ screen = tui_module.ReviewScreen(state)
+ try:
+ screen.open()
+ except tui_module.TuiUnavailable as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ def _save(fingerprints):
+ wanted = set(fingerprints)
+ changed = 0
+ for fingerprint in sorted(wanted - reviewed_at_start):
+ ledger_store.record(
+ fingerprint,
+ status=args.ledger_status,
+ reviewer=_reviewer_name(args),
+ note=args.review_note,
+ )
+ changed += 1
+ # Unmarked rows are removed from the ledger, but the audit
+ # trail keeps the "forgotten" event.
+ for fingerprint in sorted(reviewed_at_start - wanted):
+ if ledger_store.forget(
+ fingerprint,
+ reviewer=_reviewer_name(args),
+ note=args.review_note or "unmarked in --tui",
+ ):
+ changed += 1
+ return changed
+
+ screen.run(save=_save)
+ changed = len(state.marked - reviewed_at_start) + len(
+ reviewed_at_start - state.marked
+ )
+ except ledger_module.LedgerError as exc:
+ print(f"error: ledger write failed: {exc}", file=stderr)
+ return EXIT_USAGE
+ finally:
+ screen.close()
+ ledger_store.close()
+ ledger_store = None
+ print(
+ f"pathscope: {len(state.marked)} fingerprint(s) marked, "
+ f"{changed} ledger change(s) in {args.ledger}",
+ file=stderr,
+ )
+
+ if args.stats:
+ stats = report_data.stats
+ print(
+ "pathscope: stats "
+ f"analyze={stats.get('analyze_seconds', 0):.3f}s "
+ f"total={stats.get('total_seconds', 0):.3f}s "
+ f"entries={stats.get('input_entries', report_data.requests_analyzed)} "
+ f"findings={stats.get('findings', report_data.candidate_count)}",
+ file=stderr,
+ )
+ if not quiet:
+ print(f"pathscope: {summarize(report_data)}", file=stderr)
+ if args.interactive and args.save_report:
+ print(
+ "pathscope: review marks in the interactive report stay in your browser",
+ file=stderr,
+ )
+ if report_data.findings and args.output_format == FORMAT_TEXT and not args.summary_only:
+ print(
+ "pathscope: candidates are for manual review, not confirmed vulnerabilities",
+ file=stderr,
+ )
+
+ if ledger_store is not None:
+ ledger_store.close()
+
+ # -- shadow policies: reported, never enforced ------------------------
+ if args.policy_shadow:
+ shadows = []
+ for path in args.policy_shadow:
+ try:
+ candidate = load_policy(path)
+ except PolicyError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ # A shadow policy is reported only: it cannot change the exit code.
+ shadows.append(shadow_module.evaluate_shadow(report_data, candidate, label=path))
+ actual = (
+ shadow_module.evaluate_shadow(report_data, policy, label="active")
+ if policy is not None
+ else None
+ )
+ print("", file=stdout)
+ print(shadow_module.render_shadow(report_data, shadows, actual=actual), file=stdout)
+
+ # -- gates: --policy first (more specific), then --fail-on-findings --
+ if policy is not None:
+ if args.policy_include_reviewed:
+ policy = replace(policy, fail_on_reviewed=True)
+ result = evaluate_policy(report_data, policy)
+ if not quiet or not result.passed:
+ print(f"pathscope: {result.describe()}", file=stderr)
+ if not result.passed:
+ return EXIT_FINDINGS
+ return EXIT_OK
+
+ if args.fail_on_findings and gate_candidate_count:
+ return EXIT_FINDINGS
+ return EXIT_OK
+
+
+def render_summary_only(report_data, colors: Palette) -> str:
+ """Compact ``--summary-only`` view: counts per confidence and per host."""
+ lines = [colors.paint("bold", "PathScope summary")]
+ lines.append(f"Requests analysed : {report_data.requests_analyzed}")
+ lines.append(f"Parameters : {report_data.parameters_analyzed}")
+ lines.append(f"Candidates : {report_data.candidate_count}")
+ for band in ("high", "medium", "low"):
+ lines.append(f" {band:<6} : {report_data.confidence_counts.get(band, 0)}")
+ if report_data.findings:
+ lines.append("")
+ by_host = {}
+ for finding in report_data.findings:
+ by_host[finding.host] = by_host.get(finding.host, 0) + 1
+ lines.append(colors.paint("bold", "Candidates per host"))
+ for host in sorted(by_host):
+ lines.append(f" {host:<32} {by_host[host]}")
+ by_rule = {}
+ for finding in report_data.findings:
+ by_rule[finding.rule] = by_rule.get(finding.rule, 0) + 1
+ lines.append("")
+ lines.append(colors.paint("bold", "Candidates per rule"))
+ for rule in sorted(by_rule):
+ lines.append(f" {rule:<32} {by_rule[rule]}")
+ lines.append("")
+ lines.append(colors.paint("grey", "Candidates for manual review only."))
+ return "\n".join(lines)
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+ """Console entry point used by ``path_detector.py``."""
+ try:
+ return run(argv)
+ except KeyboardInterrupt:
+ print("\ninterrupted", file=sys.stderr)
+ return EXIT_INTERRUPTED
+ except BrokenPipeError: # e.g. `pathscope ... | head`
+ try:
+ sys.stdout.close()
+ except Exception: # pragma: no cover - defensive
+ pass
+ return EXIT_OK
+
+
+__all__ = [
+ "build_parser",
+ "collect_inputs",
+ "resolve_formats",
+ "main",
+ "run",
+ "EXIT_OK",
+ "EXIT_FINDINGS",
+ "EXIT_USAGE",
+ "EXIT_INTERNAL",
+ "EXIT_INTERRUPTED",
+]
+
+
+# ---------------------------------------------------------------------------
+# Renderers for the 2.3 insight views
+# ---------------------------------------------------------------------------
+def render_dashboard(report_data, requests=(), colors: Optional[Palette] = None) -> str:
+ """``--dashboard``: distribution, percentiles, gaps and frequency."""
+ colors = colors or Palette(False)
+ view = analytics_module.dashboard(report_data, requests)
+ lines = [colors.paint("bold", "PathScope dashboard")]
+ lines.append(f"Requests analysed : {view.requests}")
+ lines.append(f"Parameters analysed: {view.parameters}")
+ lines.append(f"Candidates : {view.findings}")
+ for band in analytics_module.BANDS:
+ lines.append(f" {band:<7} : {view.bands.get(band, 0)}")
+ if view.scores:
+ lines.append(f"Mean score : {view.mean_score:.1f}/100")
+ percentiles = " ".join(
+ f"p{rank}={value:.0f}" if value is not None else f"p{rank}=n/a"
+ for rank, value in view.percentiles.items()
+ )
+ lines.append(f"Percentiles : {percentiles}")
+ if view.locations:
+ lines.append(
+ "Locations : "
+ + ", ".join(f"{name}={count}" for name, count in sorted(view.locations.items()))
+ )
+ if view.frequent:
+ lines.append("")
+ lines.append(colors.paint("bold", "Most frequent candidates"))
+ for name, count in view.frequent:
+ lines.append(f" {name:<32} {count}")
+ if view.rules:
+ lines.append("")
+ lines.append(colors.paint("bold", "Rules that fired"))
+ for rule, count in sorted(view.rules.items(), key=lambda item: (-item[1], item[0])):
+ lines.append(f" {rule:<32} {count}")
+ if view.coverage_gaps:
+ lines.append("")
+ lines.append(colors.paint("bold", "Coverage gaps (hosts with no candidate)"))
+ for host in view.coverage_gaps[:analytics_module.MAX_TABLE_ROWS]:
+ lines.append(f" {host}")
+ lines.append("")
+ lines.append(colors.paint("grey", "Candidates for manual review only; counts are not risk ratings."))
+ return "\n".join(lines)
+
+
+def render_inventory(requests) -> str:
+ """``--inventory``: endpoints ordered by distinct parameters."""
+ entries = analytics_module.inventory(requests)
+ lines = ["PathScope endpoint inventory", "=" * 84]
+ lines.append(f"{len(entries)} endpoint(s), busiest first (distinct parameters):")
+ lines.append("")
+ for entry in entries[: analytics_module.MAX_TABLE_ROWS]:
+ names = ", ".join(entry.parameters) if entry.parameters else "-"
+ lines.append(f" {entry.weight:>2} {entry.method:<6} {entry.host:<24} {entry.resource}")
+ lines.append(f" parameters: {names[:150]}")
+ if len(entries) > analytics_module.MAX_TABLE_ROWS:
+ lines.append(f" ... {len(entries) - analytics_module.MAX_TABLE_ROWS} more endpoint(s)")
+ return "\n".join(lines)
+
+
+def render_correlation(report_data, requests=()) -> str:
+ """``--correlate``: matrix, shared parameters and chains."""
+ view = analytics_module.correlate(report_data, requests)
+ lines = ["PathScope cross-source correlation", "=" * 84]
+ if not view.matrix:
+ lines.append("No candidates to correlate.")
+ return "\n".join(lines)
+ lines.append("")
+ lines.append("Parameter x host matrix:")
+ for name, row in sorted(view.matrix.items()):
+ counts = ", ".join(f"{host} x{count}" for host, count in sorted(row.items()))
+ lines.append(f" {name:<28} {counts}")
+ if view.shared:
+ lines.append("")
+ lines.append("Shared across hosts (same component, different deployments?):")
+ for name, hosts in view.shared[: analytics_module.MAX_TABLE_ROWS]:
+ lines.append(f" {name:<28} {', '.join(hosts)}")
+ if view.clusters:
+ lines.append("")
+ lines.append("Clusters (parameters sharing the same host set):")
+ for signature, members in sorted(view.clusters.items()):
+ lines.append(f" [{signature}] {', '.join(members)}")
+ if view.chained:
+ lines.append("")
+ lines.append("Chained candidates (a value embeds another candidate):")
+ for outer, inner, host in view.chained[: analytics_module.MAX_TABLE_ROWS]:
+ lines.append(f" {host}: {outer} -> {inner}")
+ return "\n".join(lines)
+
+
+def render_trend(trend) -> str:
+ """``--trend``: counts, new/resolved and per-parameter history."""
+ lines = ["PathScope run trend", "=" * 84]
+ if not trend.runs:
+ lines.append("The history file contains no runs yet.")
+ return "\n".join(lines)
+ spark = history_module.sparkline(trend.counts)
+ lines.append(f"Runs : {trend.runs}")
+ lines.append(f"Candidates per run : {', '.join(str(c) for c in trend.counts)}")
+ if spark:
+ lines.append(f"Sparkline : {spark}")
+ lines.append(f"New per run : {', '.join(str(c) for c in trend.new_per_run)}")
+ lines.append(f"Resolved per run : {', '.join(str(c) for c in trend.resolved_per_run)}")
+ if trend.latest_new:
+ lines.append("New in last run : " + ", ".join(trend.latest_new[:20]))
+ if trend.latest_resolved:
+ lines.append("Resolved in last : " + ", ".join(trend.latest_resolved[:20]))
+ lines.append("")
+ lines.append("Per parameter (first -> last run, drift):")
+ for entry in sorted(
+ trend.parameters.values(), key=lambda item: (-item.runs_seen, item.parameter)
+ )[: analytics_module.MAX_TABLE_ROWS]:
+ drift = f"{entry.drift:+d}" if entry.drift else "0"
+ lines.append(
+ f" {entry.parameter:<24} {entry.host:<24} "
+ f"runs {entry.first_run}-{entry.last_run} ({entry.runs_seen}x) drift {drift}"
+ )
+ if trend.busiest_hosts:
+ lines.append("")
+ lines.append("Busiest hosts (total appearances):")
+ for host, count in trend.busiest_hosts:
+ lines.append(f" {host:<32} {count}")
+ return "\n".join(lines)
+
+
+def render_ledger_query(reviews) -> str:
+ """``--ledger-query``: a table of matching reviews."""
+ lines = ["PathScope ledger", "=" * 84]
+ if not reviews:
+ lines.append("No reviews matched.")
+ return "\n".join(lines)
+ lines.append(
+ f"{'status':<16} {'host':<22} {'parameter':<20} {'rule':<18} "
+ f"{'reviewer':<12} {'updated':<20} fingerprint"
+ )
+ for review in reviews[: analytics_module.MAX_TABLE_ROWS]:
+ lines.append(
+ f"{review.status:<16} {review.host[:22]:<22} {review.parameter[:20]:<20} "
+ f"{review.rule[:18]:<18} {review.reviewer[:12]:<12} "
+ f"{review.updated_at:<20} {review.fingerprint}"
+ )
+ if len(reviews) > analytics_module.MAX_TABLE_ROWS:
+ lines.append(f"... {len(reviews) - analytics_module.MAX_TABLE_ROWS} more")
+ return "\n".join(lines)
+
+
+def _hide_reviewed(report_data, ledger) -> int:
+ """Drop findings whose fingerprint is already in the ledger.
+
+ Returns the number hidden. The audit trail in the ledger is untouched;
+ this only affects what this run prints.
+ """
+ reviewed = ledger.fingerprints()
+ if not reviewed:
+ return 0
+ kept = [f for f in report_data.findings if f.fingerprint not in reviewed]
+ hidden = len(report_data.findings) - len(kept)
+ if hidden:
+ report_data.findings = kept
+ for index, finding in enumerate(report_data.findings, start=1):
+ finding.index = index
+ report_data.known_count = int(getattr(report_data, "known_count", 0)) + hidden
+ return hidden
+
+
+def _run_stream(args, options, stdout, stderr, stdin_text) -> int:
+ """``--stream``: bounded-memory analysis of a piped line list."""
+ if args.url:
+ print(
+ "error: --stream reads from stdin; drop --url or pass the URL on stdin",
+ file=stderr,
+ )
+ return EXIT_USAGE
+ if stdin_text is None:
+ try:
+ stream_module.check_streamable(args.input_format)
+ except stream_module.StreamError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ if not stream_module.stdin_is_a_pipe():
+ print(
+ "error: --stream reads URLs/recon lines from stdin; pipe into it "
+ "or pass --input -",
+ file=stderr,
+ )
+ return EXIT_USAGE
+
+ def emit(batch_number, cumulative):
+ if not args.stream_json:
+ print(
+ f"pathscope: batch {batch_number}: "
+ f"{cumulative.requests_analyzed} request(s), "
+ f"{cumulative.candidate_count} candidate(s)",
+ file=stderr,
+ )
+ return
+ payload = {
+ "batch": batch_number,
+ "requests": cumulative.requests_analyzed,
+ "candidates": cumulative.candidate_count,
+ "findings": [finding.as_dict() for finding in cumulative.findings],
+ }
+ stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
+ stdout.flush()
+
+ try:
+ if stdin_text is not None:
+ result = stream_module.stream_text(
+ stdin_text, options, batch_size=args.stream_batch, on_batch=emit
+ )
+ else:
+ result = stream_module.stream_stdin(
+ options, batch_size=args.stream_batch, on_batch=emit
+ )
+ except stream_module.StreamError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ except KeyboardInterrupt:
+ print("\ninterrupted", file=stderr)
+ return EXIT_INTERRUPTED
+
+ if args.stream_json:
+ stdout.write(
+ json.dumps(
+ {
+ "complete": True,
+ "requests": result.report.requests_analyzed,
+ "candidates": result.report.candidate_count,
+ },
+ ensure_ascii=False,
+ )
+ + "\n"
+ )
+ # Machine-readable output never implies a gate; only --fail-on-findings does.
+ return EXIT_FINDINGS if (args.fail_on_findings and result.report.new_count) else EXIT_OK
+
+ if not args.quiet:
+ for warning in result.warnings:
+ print(f"warning: {warning}", file=stderr)
+ colors = Palette(supports_color(stdout) and not args.no_color)
+ rendered = stream_module.render_stream_summary(result, colors)
+ print(rendered, file=stdout)
+
+ if args.save_report:
+ try:
+ write_report(args.save_report, result.report, interactive=args.interactive)
+ except (OSError, ValueError) as exc:
+ print(f"error: cannot write report: {exc}", file=stderr)
+ return EXIT_USAGE
+ if args.ledger:
+ try:
+ ledger = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ if args.ledger_mark_all:
+ ledger.record_findings(
+ result.report.findings,
+ status=args.ledger_status,
+ reviewer=_reviewer_name(args),
+ note=args.review_note,
+ )
+ except ledger_module.LedgerError as exc:
+ print(f"error: ledger write failed: {exc}", file=stderr)
+ return EXIT_USAGE
+ finally:
+ ledger.close()
+ if not args.quiet:
+ print(
+ "pathscope: candidates are for manual review, not confirmed vulnerabilities",
+ file=stderr,
+ )
+ if args.fail_on_findings and result.report.new_count:
+ return EXIT_FINDINGS
+ return EXIT_OK
+
+
+
+# ---------------------------------------------------------------------------
+# 2.4 handlers: term packs, projects, ledger expiry, calibration
+# ---------------------------------------------------------------------------
+def _handle_init_terms(args, stderr) -> int:
+ """``--init-terms FILE``: write a valid starter term pack."""
+ target = args.init_terms
+ directory = os.path.dirname(os.path.abspath(target))
+ if directory and not os.path.isdir(directory):
+ print(f"error: no such directory: {directory}", file=stderr)
+ return EXIT_USAGE
+ if os.path.exists(target):
+ print(f"error: '{target}' already exists; refusing to overwrite", file=stderr)
+ return EXIT_USAGE
+ name = os.path.splitext(os.path.basename(target))[0] or "my-project"
+ try:
+ with open(target, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(termpacks_module.starter_pack(name).to_json())
+ except OSError as exc:
+ print(f"error: cannot write '{target}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"pathscope: wrote a starter term pack to {target}", file=stderr)
+ print(
+ "pathscope: edit 'terms', then pass it with --terms FILE",
+ file=stderr,
+ )
+ return EXIT_OK
+
+
+def _handle_list_terms(args, stdout, stderr) -> int:
+ """``--list-terms FILE``: validate and summarise packs."""
+ print(f"{PROGRAM} term packs", file=stdout)
+ print(f" {'pack':<24} {'terms':>9} {'ignore':>10} description", file=stdout)
+ failed = False
+ for path in args.list_terms:
+ try:
+ pack = termpacks_module.load_pack(path)
+ except termpacks_module.TermPackError as exc:
+ print(f" error: {exc}", file=stderr)
+ failed = True
+ continue
+ print(f" {termpacks_module.describe(pack)}", file=stdout)
+ if pack.terms:
+ print(f" terms: {', '.join(pack.terms[:12])}", file=stdout)
+ if len(pack.terms) > 12:
+ print(f" ... {len(pack.terms) - 12} more", file=stdout)
+ return EXIT_USAGE if failed else EXIT_OK
+
+
+def _handle_init_scope(args, stderr) -> int:
+ """``--init-scope FILE``: write a starter scope file."""
+ path = args.init_scope
+ if os.path.exists(path):
+ print(f"error: refusing to overwrite existing file '{path}'", file=stderr)
+ return EXIT_USAGE
+ try:
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(scope_module.starter_scope())
+ except OSError as exc:
+ print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"wrote starter scope file to {path}", file=stderr)
+ print(
+ "note: a scope file records intent, it does not grant authorisation.",
+ file=stderr,
+ )
+ return EXIT_OK
+
+
+def _handle_init_waivers(args, stderr) -> int:
+ """``--init-waivers FILE``: write a starter waiver file."""
+ path = args.init_waivers
+ if os.path.exists(path):
+ print(f"error: refusing to overwrite existing file '{path}'", file=stderr)
+ return EXIT_USAGE
+ try:
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(waivers_module.starter_waivers())
+ except OSError as exc:
+ print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"wrote starter waivers to {path}", file=stderr)
+ print(
+ "note: every waiver needs a reason, an owner and (ideally) an expiry.",
+ file=stderr,
+ )
+ return EXIT_OK
+
+
+def _handle_rule_precision(args, stdout, stderr) -> int:
+ """``--rule-precision``: precision per rule from the ledger, then exit."""
+ if not args.ledger:
+ print("error: --rule-precision needs --ledger FILE", file=stderr)
+ return EXIT_USAGE
+ try:
+ store = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ reviews = store.all_reviews()
+ finally:
+ store.close()
+ report = precision_module.rule_precision(reviews)
+ print(precision_module.render_precision(report), file=stdout)
+ return EXIT_OK
+
+
+def _handle_explain_diff(args, stdout, stderr) -> int:
+ """``--explain-diff OLD.json NEW.json``: why scores moved, then exit."""
+ if len(args.explain_diff) != 2:
+ print(
+ "error: --explain-diff needs exactly two report files: "
+ "--explain-diff OLD.json --explain-diff NEW.json",
+ file=stderr,
+ )
+ return EXIT_USAGE
+ old_path, new_path = args.explain_diff
+ try:
+ diff = scorechange_module.compare(old_path, new_path)
+ except scorechange_module.ScoreDiffError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(scorechange_module.render_score_diff(diff), file=stdout)
+ return EXIT_OK
+
+
+def _handle_ledger_merge(args, stdout, stderr) -> int:
+ """``--ledger-merge OTHER --ledger INTO``: dry run unless --merge-apply."""
+ if not args.ledger:
+ print("error: --ledger-merge needs --ledger FILE (the destination)", file=stderr)
+ return EXIT_USAGE
+ if os.path.abspath(args.ledger) == os.path.abspath(args.ledger_merge):
+ print("error: cannot merge a ledger into itself", file=stderr)
+ return EXIT_USAGE
+ if not os.path.exists(args.ledger_merge):
+ print(
+ f"error: ledger to merge not found: {args.ledger_merge}", file=stderr
+ )
+ return EXIT_USAGE
+ try:
+ left = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ try:
+ right = ledger_module.open_ledger(args.ledger_merge)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ result = ledgermerge_module.plan(left, right, prefer=args.merge_prefer)
+ if args.merge_apply:
+ ledgermerge_module.apply_merge(left, right, result)
+ except ledgermerge_module.MergeError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ finally:
+ right.close()
+ finally:
+ left.close()
+ if args.merge_json:
+ print(
+ json.dumps(result.as_dict(), indent=2, ensure_ascii=False), file=stdout
+ )
+ else:
+ print(ledgermerge_module.render_merge(result), file=stdout)
+ return EXIT_OK
+
+
+def _handle_init_project(args, stderr) -> int:
+ """``--init-project DIR``: write DIR/.pathscope/project.json."""
+ base = os.path.abspath(args.init_project)
+ target_dir = os.path.join(base, project_module.PROJECT_DIR)
+ target = os.path.join(target_dir, project_module.PROJECT_FILE)
+ if os.path.exists(target):
+ print(f"error: '{target}' already exists; refusing to overwrite", file=stderr)
+ return EXIT_USAGE
+ try:
+ os.makedirs(target_dir, exist_ok=True)
+ payload = project_module.starter_project(os.path.basename(base) or "my-project")
+ with open(target, "w", encoding="utf-8", newline="\n") as handle:
+ json.dump(payload, handle, indent=2)
+ handle.write("\n")
+ except OSError as exc:
+ print(f"error: cannot write '{target}': {exc.strerror or exc}", file=stderr)
+ return EXIT_USAGE
+ print(f"pathscope: wrote {target}", file=stderr)
+ print(
+ "pathscope: paths in it are relative to the project root and must stay inside it",
+ file=stderr,
+ )
+ return EXIT_OK
+
+
+def _handle_show_project(args, stdout, stderr) -> int:
+ """``--show-project``: what discovery found and what it would apply."""
+ try:
+ discovered = project_module.discover(enabled=not args.no_project)
+ except project_module.ProjectError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(
+ project_module.render_project(
+ discovered,
+ searched_from=os.getcwd(),
+ ),
+ file=stdout,
+ )
+ return EXIT_OK
+
+
+def _handle_ledger_expiry(args, stdout, stderr) -> int:
+ """``--ledger-stale`` / ``--ledger-refresh``."""
+ if not args.ledger:
+ print("error: --ledger-stale and --ledger-refresh need --ledger FILE",
+ file=stderr)
+ return EXIT_USAGE
+ try:
+ store = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ stale = store.stale()
+ if args.ledger_refresh:
+ changed = 0
+ for review in stale:
+ if store.clear_expiry(review.fingerprint,
+ reviewer=_reviewer_name(args)):
+ changed += 1
+ print(
+ f"pathscope: cleared the expiry on {changed} review(s)",
+ file=stderr,
+ )
+ stale = store.stale()
+ print(render_stale_reviews(stale), file=stdout)
+ return EXIT_OK
+ finally:
+ store.close()
+
+
+def _handle_ledger_scores(args, stdout, stderr) -> int:
+ """``--ledger-scores``: score distribution of ledger reviews."""
+ if not args.ledger:
+ print("error: --ledger-scores needs --ledger FILE", file=stderr)
+ return EXIT_USAGE
+ try:
+ store = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ print(
+ calibrate_module.render_ledger_scores(store.all_reviews()),
+ file=stdout,
+ )
+ return EXIT_OK
+ finally:
+ store.close()
+
+
+def _handle_calibrate(args, stdout, stderr) -> int:
+ """``--calibrate``: recommend a threshold from the ledger."""
+ if not args.ledger:
+ print("error: --calibrate needs --ledger FILE", file=stderr)
+ return EXIT_USAGE
+ try:
+ store = ledger_module.open_ledger(args.ledger)
+ except ledger_module.LedgerError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ try:
+ result = calibrate_module.calibrate(store)
+ except calibrate_module.CalibrationError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ print(calibrate_module.render_calibration(result), file=stdout)
+ return EXIT_OK
+ finally:
+ store.close()
+
+
+def render_stale_reviews(reviews) -> str:
+ """Text table for ``--ledger-stale``."""
+ lines = ["PathScope stale reviews", "=" * 84]
+ if not reviews:
+ lines.append("No expired reviews: every acceptance is still current.")
+ return "\n".join(lines)
+ lines.append(
+ f"{len(reviews)} review(s) passed their expiry and need another look:"
+ )
+ lines.append("")
+ lines.append(
+ f"{'status':<16} {'host':<22} {'parameter':<20} {'expired':<12} "
+ f"{'reviewer':<12} fingerprint"
+ )
+ for review in reviews[: analytics_module.MAX_TABLE_ROWS]:
+ lines.append(
+ f"{review.status:<16} {review.host[:22]:<22} {review.parameter[:20]:<20} "
+ f"{review.expires_at[:10]:<12} {review.reviewer[:12]:<12} "
+ f"{review.fingerprint}"
+ )
+ if len(reviews) > analytics_module.MAX_TABLE_ROWS:
+ lines.append(f"... {len(reviews) - analytics_module.MAX_TABLE_ROWS} more")
+ lines.append("")
+ lines.append(
+ "These still hide their candidates. Re-review them, then either set a new "
+ )
+ lines.append("expiry or clear it with --ledger-refresh.")
+ return "\n".join(lines)
+
+
+def _apply_project(args, project) -> list:
+ """Fill unset command-line options from a discovered project.
+
+ Returns the list of option names the project supplied, for the stderr note.
+ A flag already on the command line is never touched.
+ """
+ supplied: list = []
+ pairs = (
+ ("config", "config"),
+ ("policy", "policy"),
+ ("rules", "rules"),
+ ("baseline", "baseline"),
+ ("ledger", "ledger"),
+ ("history", "history"),
+ )
+ for attribute, label in pairs:
+ if getattr(args, attribute, None):
+ continue
+ value = getattr(project, attribute, "")
+ if value:
+ setattr(args, attribute, value)
+ supplied.append(label)
+ if not args.terms and project.terms:
+ args.terms = list(project.terms)
+ supplied.append("terms")
+ return supplied
+
+
+# ---------------------------------------------------------------------------
+# 2.4: capture diff and HTML/JS extraction runners
+# ---------------------------------------------------------------------------
+def _load_capture(path: str, input_format: str):
+ """Load one capture file through the normal input pipeline."""
+ if not os.path.exists(path):
+ raise InputError(f"capture not found: {path}")
+ return load_file(path, input_format)
+
+
+def _run_capture_diff(args, stdout, stderr) -> int:
+ """``--diff-capture OLD``: compare an earlier capture with ``-i`` files."""
+ if not args.input:
+ print(
+ "error: --diff-capture needs the new capture via -i/--input "
+ f"(got {PROGRAM} --diff-capture old.har -i new.har)",
+ file=stderr,
+ )
+ return EXIT_USAGE
+ try:
+ old = _load_capture(args.diff_capture, args.input_format)
+ except (InputError, OSError) as exc:
+ print(f"error: cannot read '{args.diff_capture}': {exc}", file=stderr)
+ return EXIT_USAGE
+ new = LoadResult()
+ for path in args.input:
+ try:
+ new.extend(_load_capture(path, args.input_format))
+ except (InputError, OSError) as exc:
+ print(f"error: cannot read '{path}': {exc}", file=stderr)
+ return EXIT_USAGE
+ try:
+ diff = capturediff_module.compare(old.requests, new.requests)
+ except capturediff_module.CaptureDiffError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+
+ if args.diff_json:
+ payload = diff.as_dict()
+ payload["tool"] = PROGRAM
+ payload["version"] = __version__
+ payload["before"] = args.diff_capture
+ payload["after"] = list(args.input)
+ payload["network_requests_made"] = 0
+ print(json.dumps(payload, indent=2, ensure_ascii=False), file=stdout)
+ else:
+ print(
+ capturediff_module.render_diff(
+ diff, old_label=args.diff_capture, new_label=", ".join(args.input)
+ ),
+ file=stdout,
+ )
+ if not args.quiet:
+ print(
+ f"pathscope: {len(diff.changes)} parameter change(s), "
+ f"{len(diff.new_endpoints)} new endpoint(s)",
+ file=stderr,
+ )
+ return EXIT_FINDINGS if diff.has_differences else EXIT_OK
+
+
+def _run_extract(args, options, stdout, stderr) -> int:
+ """``--extract FILE``: analyse endpoint strings found in local HTML/JS."""
+ if args.url or args.input:
+ print(
+ "error: --extract reads local files; drop --url/-i or run them separately",
+ file=stderr,
+ )
+ return EXIT_USAGE
+ try:
+ found = extractor_module.extract_paths(
+ args.extract,
+ base_host=args.extract_host or "",
+ keep_all_hosts=args.extract_all_hosts,
+ )
+ except extractor_module.ExtractError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+ if not found.requests:
+ print(extractor_module.render_extract(found), file=stdout)
+ for warning in found.warnings:
+ print(f"warning: {warning}", file=stderr)
+ return EXIT_USAGE
+
+ report_data = analyze_requests(found.requests, options)
+ report_data.warnings = list(found.warnings) + list(report_data.warnings)
+ report_data.rules = options.book.as_dict()
+ report_data.rules_source = options.book.source
+ colors = Palette(supports_color(stdout) and not args.no_color)
+ print(extractor_module.render_extract(found), file=stdout)
+ print("", file=stdout)
+ if args.output_format == FORMAT_TEXT:
+ print(render_text(report_data, colors, group_by=args.group_by), file=stdout)
+ else:
+ print(render(report_data, args.output_format, colors), file=stdout)
+ if args.save_report:
+ try:
+ write_report(args.save_report, report_data, interactive=args.interactive)
+ except (OSError, ValueError) as exc:
+ print(f"error: cannot write report: {exc}", file=stderr)
+ return EXIT_USAGE
+ if not args.quiet:
+ print(f"pathscope: {summarize(report_data)}", file=stderr)
+ print(
+ "pathscope: candidates are for manual review, not confirmed vulnerabilities",
+ file=stderr,
+ )
+ if args.fail_on_findings and report_data.new_count:
+ return EXIT_FINDINGS
+ return EXIT_OK
+
+
+def _mark_reviewed_status(report_data, ledger_store) -> int:
+ """Set ``finding.status = "reviewed"`` for fingerprints in the ledger.
+
+ This is what makes ``--ledger`` consistent across *every* output: SARIF
+ suppressions, JUnit ````, the policy gate and the text report all
+ already understand the ``reviewed`` status, so marking happens once here
+ rather than in each renderer.
+ """
+ reviewed = ledger_store.fingerprints()
+ if not reviewed:
+ return 0
+ marked = 0
+ for finding in report_data.findings:
+ if finding.fingerprint in reviewed and finding.status != "reviewed":
+ finding.status = "reviewed"
+ marked += 1
+ return marked
diff --git a/pathscope/completion.py b/pathscope/completion.py
new file mode 100644
index 0000000..5a9eeb7
--- /dev/null
+++ b/pathscope/completion.py
@@ -0,0 +1,275 @@
+"""Shell completion (``--completion bash|zsh|fish``).
+
+Completion scripts go stale the moment a flag is added, and a stale completion
+is worse than none: it teaches the wrong flags. So nothing here is hand-written.
+The script is generated from the **real argument parser** every time, which
+means a new flag appears in completion the moment it exists in the parser, or
+it appears nowhere at all.
+
+Supported: bash, zsh, fish, and ``powershell``. Output goes to stdout so it can
+be piped:
+
+ pathscope --completion bash > /etc/bash_completion.d/pathscope
+ pathscope --completion zsh > "${fpath[1]}/_pathscope"
+ pathscope --completion fish > ~/.config/fish/completions/pathscope.fish
+
+Only flags are completed. Value choices are included where the parser declares
+them (``choices=`` for ``--format``, the status list for ``--ledger-status``),
+because those are the places a typo is most likely.
+"""
+
+from __future__ import annotations
+
+import shlex
+from dataclasses import dataclass
+from typing import Dict, List, Sequence, Tuple
+
+SHELLS = ("bash", "zsh", "fish", "powershell")
+
+
+class CompletionError(ValueError):
+ """Raised for an unsupported shell."""
+
+
+@dataclass(frozen=True)
+class Flag:
+ """One option, as the parser declares it."""
+
+ options: Tuple[str, ...]
+ help: str
+ metavar: str = ""
+ choices: Tuple[str, ...] = ()
+
+ @property
+ def primary(self) -> str:
+ """The longest long option, or the only option."""
+ longs = [option for option in self.options if option.startswith("--") and option != "--"]
+ if longs:
+ return max(longs, key=len)
+ return self.options[0]
+
+
+def _metavar(action) -> str:
+ if getattr(action, "choices", None):
+ return ""
+ metavar = action.metavar or ""
+ if isinstance(metavar, tuple):
+ metavar = metavar[0] if metavar else ""
+ if not metavar:
+ metavar = action.dest.upper()
+ return metavar
+
+
+def collect_flags(parser) -> List[Flag]:
+ """Turn argparse actions into a flat, sorted flag list."""
+ flags: List[Flag] = []
+ for action in parser._actions:
+ options = tuple(
+ option for option in action.option_strings if option not in ("-h", "--help")
+ )
+ if not options:
+ continue
+ choices = tuple(str(choice) for choice in (action.choices or ()))
+ flags.append(
+ Flag(
+ options=options,
+ help=(action.help or "").split("\n")[0].strip(),
+ metavar=_metavar(action),
+ choices=choices,
+ )
+ )
+ flags.sort(key=lambda flag: flag.primary)
+ return flags
+
+
+def _value_sets(flags: Sequence[Flag]) -> Dict[str, Tuple[str, ...]]:
+ return {flag.primary: flag.choices for flag in flags if flag.choices}
+
+
+def _bash_quote(text: str) -> str:
+ return shlex.quote(text)
+
+
+def render_bash(program: str, flags: Sequence[Flag]) -> str:
+ """A bash completion script generated from the parser."""
+ function = f"_{program.replace('-', '_').replace('.', '_')}"
+ options = " ".join(_bash_quote(flag.primary) for flag in flags)
+ values = _value_sets(flags)
+ lines = [
+ f"# {program} completion for bash -- generated by --completion, do not edit",
+ "# regenerate: " + program + " --completion bash",
+ "",
+ f"{function}() {{",
+ " local cur prev",
+ ' cur="${COMP_WORDS[COMP_CWORD]}"',
+ ' prev="${COMP_WORDS[COMP_CWORD-1]}"',
+ " case \"$prev\" in",
+ ]
+ for option, choices in sorted(values.items()):
+ lines.append(f" {_bash_quote(option)})")
+ lines.append(
+ f" COMPREPLY=( $(compgen -W \"{' '.join(choices)}\" -- \"$cur\") )"
+ )
+ lines.append(" return 0 ;;")
+ lines.append(" esac")
+ lines.append(" if [[ \"$cur\" == -* ]]; then")
+ lines.append(
+ f" COMPREPLY=( $(compgen -W {_bash_quote(options)} -- \"$cur\") )"
+ )
+ lines.append(" return 0")
+ lines.append(" fi")
+ lines.append(" COMPREPLY=( $(compgen -f -- \"$cur\") )")
+ lines.append("}")
+ lines.append("")
+ lines.append(f"complete -o bashdefault -o default -F {function} {_bash_quote(program)}")
+ return "\n".join(lines) + "\n"
+
+
+def render_zsh(program: str, flags: Sequence[Flag]) -> str:
+ """A zsh completion script generated from the parser."""
+ lines = [
+ f"#compdef {program}",
+ f"# {program} completion for zsh -- generated by --completion, do not edit",
+ "# regenerate: " + program + " --completion zsh",
+ "",
+ f"_{program.replace('-', '_').replace('.', '_')}() {{",
+ " _arguments -s \\",
+ ]
+ for flag in flags:
+ help_text = (flag.help or "").replace("'", "\\'").replace("[", "(").replace("]", ")")
+ if flag.choices:
+ spec = "(" + " ".join(flag.choices) + ")"
+ lines.append(f" '{flag.primary}[{help_text}]:value:{spec}' \\")
+ elif flag.options and any(
+ option.startswith("--") and option not in (
+ "--url", "--input", "--format", "--output-format", "--input-format",
+ "--config", "--rules", "--policy", "--baseline", "--suppress",
+ "--save-report", "--bundle", "--history", "--ledger", "--terms",
+ "--init-terms", "--list-terms", "--diff-capture", "--extract",
+ "--extract-host", "--openapi", "--scope-file", "--sample-seed",
+ "--sample-by", "--export-ticket", "--pr-comment", "--completion",
+ "--min-score", "--top", "--max-entries", "--ledger-status",
+ "--ledger-expire", "--reviewer", "--review-note", "--preset",
+ "--group-by", "--name-lang", "--interval", "--stream-batch",
+ "--redact-key", "--redact-prefix", "--redact-length",
+ "--policy-shadow", "--ticket-limit", "--queue-limit",
+ )
+ for option in flag.options
+ ):
+ lines.append(f" '{flag.primary}[{help_text}]' \\")
+ else:
+ lines.append(f" '{flag.primary}[{help_text}]:value:_files' \\")
+ lines.append(" '*:file:_files'")
+ lines.append("}")
+ lines.append("")
+ lines.append(f"_{program.replace('-', '_').replace('.', '_')} \"$@\"")
+ return "\n".join(lines) + "\n"
+
+
+def render_fish(program: str, flags: Sequence[Flag]) -> str:
+ """A fish completion script generated from the parser."""
+ lines = [
+ f"# {program} completion for fish -- generated by --completion, do not edit",
+ "# regenerate: " + program + " --completion fish",
+ "",
+ ]
+ for flag in flags:
+ conditions = " ".join(f"-l {option[2:]}" for option in flag.options if option.startswith("--"))
+ short = " ".join(f"-s {option[1:]}" for option in flag.options if len(option) == 2 and option.startswith("-"))
+ help_text = (flag.help or "").replace("'", "\\'")
+ prefix = " ".join(part for part in (conditions, short) if part)
+ if flag.choices:
+ choices = " ".join(f"-a {choice}" for choice in flag.choices)
+ lines.append(f"complete -c {program} {prefix} {choices} -d '{help_text}'")
+ elif flag.metavar:
+ lines.append(
+ f"complete -c {program} {prefix} -r -d '{help_text}'"
+ )
+ else:
+ lines.append(f"complete -c {program} {prefix} -d '{help_text}'")
+ lines.append(
+ f"complete -c {program} -f -a '(__fish_complete_path)' -d 'input file'"
+ )
+ return "\n".join(lines) + "\n"
+
+
+def render_powershell(program: str, flags: Sequence[Flag]) -> str:
+ """A PowerShell completion script generated from the parser."""
+ values = _value_sets(flags)
+ lines = [
+ f"# {program} completion for PowerShell -- generated by --completion, do not edit",
+ "# regenerate: " + program + " --completion powershell",
+ "# add to your profile: . ",
+ "",
+ f"Register-ArgumentCompleter -Native -CommandName {program} -ScriptBlock {{",
+ " param($wordToComplete, $commandAst, $cursorPosition)",
+ " $options = @(",
+ ]
+ for flag in flags:
+ help_text = (flag.help or "").replace("'", "''")
+ lines.append(f" @{{ Name = '{flag.primary}'; Description = '{help_text}' }}")
+ lines.append(" )")
+ if values:
+ lines.append(" $valueChoices = @{")
+ for option, choices in sorted(values.items()):
+ joined = "', '".join(choices)
+ lines.append(f" '{option}' = @('{joined}')")
+ lines.append(" }")
+ else:
+ lines.append(" $valueChoices = @{}")
+ lines.append(" $elements = $commandAst.CommandElements")
+ lines.append(" $previous = if ($elements.Count -ge 2) { $elements[$elements.Count - 2].ToString() } else { '' }")
+ lines.append(" if ($valueChoices.ContainsKey($previous)) {")
+ lines.append(" $valueChoices[$previous] | Where-Object { $_ -like \"$wordToComplete*\" } |")
+ lines.append(" ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }")
+ lines.append(" return")
+ lines.append(" }")
+ lines.append(" $options | Where-Object { $_.Name -like \"$wordToComplete*\" } |")
+ lines.append(" ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ParameterName', $_.Description) }")
+ lines.append("}")
+ return "\n".join(lines) + "\n"
+
+
+RENDERERS = {
+ "bash": render_bash,
+ "zsh": render_zsh,
+ "fish": render_fish,
+ "powershell": render_powershell,
+}
+
+
+def render(shell: str, parser) -> str:
+ """Render a completion script for ``shell`` from ``parser``."""
+ key = (shell or "").strip().lower()
+ if key not in RENDERERS:
+ raise CompletionError(
+ f"unsupported shell '{shell}' (choose from {', '.join(SHELLS)})"
+ )
+ flags = collect_flags(parser)
+ if not flags:
+ raise CompletionError("the parser exposed no options to complete")
+ program = parser.prog
+ return RENDERERS[key](program, flags)
+
+
+def describe() -> Tuple[str, ...]:
+ """Lines for ``--help``."""
+ return (
+ " --completion SHELL print a completion script generated from this parser",
+ " (bash, zsh, fish, powershell)",
+ )
+
+
+__all__ = [
+ "CompletionError",
+ "Flag",
+ "RENDERERS",
+ "SHELLS",
+ "collect_flags",
+ "describe",
+ "render",
+ "render_bash",
+ "render_fish",
+ "render_powershell",
+ "render_zsh",
+]
diff --git a/pathscope/config.py b/pathscope/config.py
new file mode 100644
index 0000000..dc855cd
--- /dev/null
+++ b/pathscope/config.py
@@ -0,0 +1,368 @@
+"""Optional JSON configuration for PathScope.
+
+Schema (all keys optional, unknown keys rejected)::
+
+ {
+ "extends": "balanced",
+ "name_terms": ["download", "media_file"],
+ "ignore_params": ["image", "avatar"],
+ "min_score": 25,
+ "max_decode_passes": 3,
+ "weak_names": true,
+ "show_values": false,
+ "name_lang": ["de", "es"],
+ "fold_names": true,
+ "demote_shapes": true
+ }
+
+Only literal terms are accepted. Regular expressions are deliberately not
+supported: a user-supplied pattern could turn this passive triage tool into a
+catastrophic-backtracking hazard, and literal terms keep results explainable.
+
+``extends`` names a base configuration file (relative to the including file)
+or a built-in preset (``minimal`` / ``balanced`` / ``noisy`` and their aliases).
+At most ``MAX_EXTENDS_DEPTH`` levels are followed, cycles are rejected.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional, Sequence, Tuple
+
+from .textutil import MAX_DECODE_PASSES
+
+#: Allowed keys and their validation rules.
+_TERM_PATTERN = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
+
+MIN_TERM_LEN = 2
+MAX_TERM_LEN = 48
+MAX_TERM_COUNT = 200
+#: ``extends`` may chain this many files deep (the including file is level 1).
+MAX_EXTENDS_DEPTH = 4
+
+
+class ConfigError(ValueError):
+ """Raised when a configuration file is missing, unreadable, or invalid."""
+
+
+@dataclass
+class Config:
+ """Validated configuration values."""
+
+ name_terms: List[str] = field(default_factory=list)
+ ignore_params: List[str] = field(default_factory=list)
+ min_score: int = 25
+ max_decode_passes: int = MAX_DECODE_PASSES
+ weak_names: bool = True
+ show_values: bool = False
+ #: Term-pack languages for the name layer (``()`` = English only).
+ name_lang: List[str] = field(default_factory=list)
+ #: Fold diacritics/compatibility characters before name matching.
+ fold_names: bool = True
+ #: Demote value shapes that do not look like paths (UUID, hash, ...).
+ demote_shapes: bool = True
+ source: str = ""
+ extends: str = ""
+ #: Which keys were present in the file (used so CLI > file > preset).
+ explicit: frozenset = field(default_factory=frozenset)
+
+ def is_explicit(self, key: str) -> bool:
+ return key in self.explicit
+
+ def merged_terms(self) -> List[str]:
+ return list(dict.fromkeys(self.name_terms))
+
+ def merged_ignore(self) -> List[str]:
+ return list(dict.fromkeys(self.ignore_params))
+
+
+ALLOWED_KEYS = {
+ "extends",
+ "name_terms",
+ "ignore_params",
+ "min_score",
+ "max_decode_passes",
+ "weak_names",
+ "show_values",
+ "name_lang",
+ "fold_names",
+ "demote_shapes",
+}
+
+#: Languages accepted in ``name_lang`` (mirrors :mod:`pathscope.naming`).
+_KNOWN_LANGUAGES = ("de", "es", "fr", "pt", "it", "nl")
+LANGUAGE_SELECTORS = ("auto", "all", "off")
+
+
+def _validate_terms(value: Any, key: str) -> List[str]:
+ if not isinstance(value, list):
+ raise ConfigError(f"'{key}' must be a JSON array of strings")
+ if len(value) > MAX_TERM_COUNT:
+ raise ConfigError(f"'{key}' may contain at most {MAX_TERM_COUNT} entries")
+ terms: List[str] = []
+ for index, item in enumerate(value):
+ where = f"'{key}'[{index}]"
+ if not isinstance(item, str):
+ raise ConfigError(f"{where} must be a string")
+ term = item.strip()
+ if not (MIN_TERM_LEN <= len(term) <= MAX_TERM_LEN):
+ raise ConfigError(
+ f"{where} must be {MIN_TERM_LEN}-{MAX_TERM_LEN} characters long"
+ )
+ if not set(term) <= _TERM_PATTERN:
+ raise ConfigError(
+ f"{where} may only contain letters, digits, '_' and '-' "
+ "(regular expressions and paths are not supported)"
+ )
+ terms.append(term)
+ return terms
+
+
+def validate_payload(payload: Any) -> Config:
+ """Validate an already-parsed JSON payload and return a :class:`Config`."""
+ if not isinstance(payload, dict):
+ raise ConfigError("configuration must be a JSON object")
+ unknown = sorted(set(payload) - ALLOWED_KEYS)
+ if unknown:
+ raise ConfigError(
+ "unknown configuration key(s): "
+ + ", ".join(unknown)
+ + f" (allowed: {', '.join(sorted(ALLOWED_KEYS))})"
+ )
+
+ config = Config(explicit=frozenset(payload))
+ if "extends" in payload:
+ value = payload["extends"]
+ if not isinstance(value, str) or not value.strip():
+ raise ConfigError("'extends' must be a non-empty string")
+ config.extends = value.strip()
+ if "name_terms" in payload:
+ config.name_terms = _validate_terms(payload["name_terms"], "name_terms")
+ if "ignore_params" in payload:
+ config.ignore_params = _validate_terms(payload["ignore_params"], "ignore_params")
+
+ if "min_score" in payload:
+ value = payload["min_score"]
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ConfigError("'min_score' must be an integer")
+ if not 0 <= value <= 100:
+ raise ConfigError("'min_score' must be between 0 and 100")
+ config.min_score = value
+
+ if "max_decode_passes" in payload:
+ value = payload["max_decode_passes"]
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ConfigError("'max_decode_passes' must be an integer")
+ if not 0 <= value <= 5:
+ raise ConfigError("'max_decode_passes' must be between 0 and 5")
+ config.max_decode_passes = value
+
+ if "weak_names" in payload:
+ value = payload["weak_names"]
+ if not isinstance(value, bool):
+ raise ConfigError("'weak_names' must be true or false")
+ config.weak_names = value
+
+ if "show_values" in payload:
+ value = payload["show_values"]
+ if not isinstance(value, bool):
+ raise ConfigError("'show_values' must be true or false")
+ config.show_values = value
+
+ if "name_lang" in payload:
+ value = payload["name_lang"]
+ if isinstance(value, str):
+ value = [value]
+ if not isinstance(value, list):
+ raise ConfigError("'name_lang' must be an array of language codes")
+ languages: List[str] = []
+ for index, item in enumerate(value):
+ if not isinstance(item, str):
+ raise ConfigError(f"'name_lang'[{index}] must be a string")
+ key = item.strip().lower()
+ if key in LANGUAGE_SELECTORS:
+ if key == "off":
+ continue
+ languages = list(_KNOWN_LANGUAGES)
+ continue
+ if key not in _KNOWN_LANGUAGES:
+ raise ConfigError(
+ f"'name_lang'[{index}]: unknown language '{item}' "
+ f"(choose from {', '.join(_KNOWN_LANGUAGES)}, auto or off)"
+ )
+ if key not in languages:
+ languages.append(key)
+ if len(languages) > 32:
+ raise ConfigError("'name_lang' may list at most 32 entries")
+ config.name_lang = languages
+
+ for boolean_key in ("fold_names", "demote_shapes"):
+ if boolean_key in payload:
+ value = payload[boolean_key]
+ if not isinstance(value, bool):
+ raise ConfigError(f"'{boolean_key}' must be true or false")
+ setattr(config, boolean_key, value)
+
+ return config
+
+
+def _read_payload(path: str) -> Dict[str, Any]:
+ try:
+ with open(path, "r", encoding="utf-8-sig") as handle:
+ raw = handle.read()
+ except OSError as exc:
+ raise ConfigError(
+ f"cannot read configuration '{path}': {exc.strerror or exc}"
+ ) from exc
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ConfigError(
+ f"configuration '{path}' is not valid JSON: line {exc.lineno}, "
+ f"column {exc.colno}: {exc.msg}"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise ConfigError(f"configuration '{path}' must be a JSON object")
+ return payload
+
+
+def merge_configs(base: Config, overlay: Config) -> Config:
+ """Overlay ``overlay`` onto ``base``: lists append, scalars override."""
+ terms: List[str] = []
+ for item in list(base.name_terms) + list(overlay.name_terms):
+ if item not in terms:
+ terms.append(item)
+ ignored: List[str] = []
+ for item in list(base.ignore_params) + list(overlay.ignore_params):
+ if item not in ignored:
+ ignored.append(item)
+ merged = Config(
+ name_terms=terms,
+ ignore_params=ignored,
+ min_score=overlay.min_score if overlay.is_explicit("min_score") else base.min_score,
+ max_decode_passes=(
+ overlay.max_decode_passes
+ if overlay.is_explicit("max_decode_passes")
+ else base.max_decode_passes
+ ),
+ weak_names=(
+ overlay.weak_names if overlay.is_explicit("weak_names") else base.weak_names
+ ),
+ show_values=(
+ overlay.show_values if overlay.is_explicit("show_values") else base.show_values
+ ),
+ name_lang=(
+ list(dict.fromkeys(list(base.name_lang) + list(overlay.name_lang)))
+ if overlay.is_explicit("name_lang")
+ else list(base.name_lang)
+ ),
+ fold_names=(
+ overlay.fold_names if overlay.is_explicit("fold_names") else base.fold_names
+ ),
+ demote_shapes=(
+ overlay.demote_shapes
+ if overlay.is_explicit("demote_shapes")
+ else base.demote_shapes
+ ),
+ source=overlay.source or base.source,
+ extends=overlay.extends or base.extends,
+ explicit=frozenset(set(base.explicit) | set(overlay.explicit)),
+ )
+ return merged
+
+
+def _load_with_extends(path: str, seen: Sequence[str], depth: int) -> Config:
+ """Load ``path``, resolving ``extends`` against files or presets."""
+ from .presets import resolve_preset # local import avoids a cycle
+
+ absolute = os.path.abspath(path)
+ if absolute in seen:
+ chain = " -> ".join(list(seen) + [absolute])
+ raise ConfigError(f"configuration cycle detected: {chain}")
+ if depth > MAX_EXTENDS_DEPTH:
+ raise ConfigError(
+ f"configuration 'extends' chain is deeper than {MAX_EXTENDS_DEPTH} levels"
+ )
+
+ payload = _read_payload(path)
+ config = validate_payload(payload)
+ config.source = path
+
+ if not config.extends:
+ return config
+
+ base: Optional[Config] = None
+ preset = resolve_preset(config.extends)
+ if preset is not None:
+ base = Config(
+ min_score=preset.min_score,
+ weak_names=preset.weak_names,
+ explicit=frozenset({"min_score", "weak_names"}),
+ source=f"preset:{preset.name}",
+ )
+ else:
+ base_path = config.extends
+ if not os.path.isabs(base_path):
+ base_path = os.path.join(os.path.dirname(absolute), base_path)
+ if not os.path.exists(base_path):
+ raise ConfigError(
+ f"configuration '{path}': 'extends' refers to unknown preset or "
+ f"missing file '{config.extends}'"
+ )
+ if not base_path.lower().endswith(".json"):
+ raise ConfigError(
+ f"configuration '{path}': 'extends' file must end with .json"
+ )
+ base = _load_with_extends(base_path, list(seen) + [absolute], depth + 1)
+
+ merged = merge_configs(base, config)
+ merged.source = path
+ merged.extends = config.extends
+ return merged
+
+
+def load_config(path: str) -> Config:
+ """Read and validate ``path``, following ``extends``. Raises ConfigError."""
+ return _load_with_extends(path, (), 1)
+
+
+def describe_schema() -> Tuple[str, ...]:
+ """Human-readable schema lines for ``--help`` and the README."""
+ return (
+ ' "extends": "balanced" base preset or .json file',
+ ' "name_terms": ["download", "media_file"] extra literal name terms',
+ ' "ignore_params": ["image", "avatar"] names to skip entirely',
+ ' "min_score": 25 integer 0-100',
+ ' "max_decode_passes": 3 integer 0-5',
+ ' "weak_names": true boolean',
+ ' "show_values": false boolean',
+ ' "name_lang": ["de", "es"] term packs (auto/off)',
+ ' "fold_names": true diacritic/compat folding',
+ ' "demote_shapes": true UUID/hash/scalar demotion',
+ )
+
+
+def dump_example() -> Dict[str, object]:
+ """Example configuration used in the README and tests."""
+ return {
+ "name_terms": ["download", "media_file"],
+ "ignore_params": ["image", "avatar"],
+ "min_score": 25,
+ "max_decode_passes": 3,
+ "weak_names": True,
+ "show_values": False,
+ "name_lang": ["de", "es"],
+ "fold_names": True,
+ "demote_shapes": True,
+ }
+
+
+def merge_ignore(cli_values: Sequence[str], config: Config) -> List[str]:
+ """Combine ``--ignore-param`` flags with the configuration's ignored names."""
+ combined: List[str] = []
+ for item in list(cli_values) + config.merged_ignore():
+ if item and item not in combined:
+ combined.append(item)
+ return combined
diff --git a/pathscope/detector.py b/pathscope/detector.py
new file mode 100644
index 0000000..36d1813
--- /dev/null
+++ b/pathscope/detector.py
@@ -0,0 +1,444 @@
+"""Turns parsed requests into ranked, explainable candidate findings.
+
+This module contains no I/O. It receives :class:`pathscope.sources.Request`
+objects, analyses their parameters as strings, and returns
+:class:`Finding` objects suitable for any renderer.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import time
+from dataclasses import dataclass, field, replace
+from typing import Dict, Iterable, List, Optional, Sequence, Tuple
+from urllib.parse import urlsplit, urlunsplit
+
+from .heuristics import Analysis, analyze_parameter, canonical_name
+from .rules import DEFAULT_BOOK, RuleBook
+from .sources import LOCATION_QUERY, Parameter, Request
+from .textutil import MAX_DECODE_PASSES, sanitize_text, truncate
+
+#: Default reporting thresholds. A score below this is not reported.
+DEFAULT_MIN_SCORE = 25
+
+CONFIDENCE_ORDER = {"high": 0, "medium": 1, "low": 2}
+
+
+#: How repeated findings are collapsed.
+DEDUPE_PATH = "path"
+DEDUPE_PARAM = "param"
+DEDUPE_NONE = "none"
+DEDUPE_MODES = (DEDUPE_PATH, DEDUPE_PARAM, DEDUPE_NONE)
+
+LOGICAL_RULE_PREFIXES = ("value-demote-",)
+
+
+@dataclass(frozen=True)
+class AnalysisOptions:
+ """Knobs for one analysis run."""
+
+ min_score: int = DEFAULT_MIN_SCORE
+ max_decode_passes: int = MAX_DECODE_PASSES
+ extra_terms: Tuple[str, ...] = ()
+ ignore_params: Tuple[str, ...] = ()
+ show_values: bool = False
+ weak_names: bool = True
+ #: Effective rule weights (see :mod:`pathscope.rules`).
+ book: RuleBook = DEFAULT_BOOK
+ #: Term-pack languages for the name layer (``()`` = English only).
+ name_lang: Tuple[str, ...] = ()
+ fold_names: bool = True
+ demote_shapes: bool = True
+ #: One of ``path`` (default), ``param`` or ``none``.
+ dedupe_by: str = DEDUPE_PATH
+ #: Maximum number of input entries to analyze (0 = unlimited).
+ max_entries: int = 0
+ #: Record phase timings on the report (``--stats``).
+ measure: bool = False
+
+ def with_book(self, book: RuleBook) -> "AnalysisOptions":
+ return replace(self, book=book)
+
+
+@dataclass
+class Finding:
+ """One candidate parameter, ready for any renderer."""
+
+ host: str
+ source_type: str
+ source_label: str
+ method: str
+ location: str
+ parameter: str
+ occurrences: int
+ rule: str
+ rules: List[str]
+ reasons: List[str]
+ score: int
+ confidence: str
+ resource: str
+ value: Optional[str] = None
+ index: int = 0
+ fingerprint: str = ""
+ #: One of ``new``, ``known`` (baseline/suppression), ``resolved`` (diff only).
+ status: str = "new"
+ note: str = ""
+
+ def as_dict(self) -> Dict[str, object]:
+ return {
+ "index": self.index,
+ "host": self.host,
+ "source_type": self.source_type,
+ "source": self.source_label,
+ "method": self.method,
+ "location": self.location,
+ "parameter": self.parameter,
+ "occurrences": self.occurrences,
+ "rule": self.rule,
+ "rules": list(self.rules),
+ "confidence": self.confidence,
+ "score": self.score,
+ "reasons": list(self.reasons),
+ "resource": self.resource,
+ "value": self.value,
+ "fingerprint": self.fingerprint,
+ "status": self.status,
+ "note": self.note,
+ }
+
+
+@dataclass
+class Report:
+ """Findings plus the metadata every output format needs."""
+
+ findings: List[Finding] = field(default_factory=list)
+ requests_analyzed: int = 0
+ parameters_analyzed: int = 0
+ sources: List[str] = field(default_factory=list)
+ warnings: List[str] = field(default_factory=list)
+ skipped: int = 0
+ min_score: int = DEFAULT_MIN_SCORE
+ show_values: bool = False
+ #: "diff" when a baseline or suppression file was applied.
+ mode: str = "scan"
+ known_count: int = 0
+ baseline_source: str = ""
+ #: Findings that were reported by the baseline but are no longer present.
+ resolved: List[Dict[str, object]] = field(default_factory=list)
+ #: Input entries ignored because of ``--max-entries``.
+ truncated_entries: int = 0
+ #: Phase timings (only filled when ``--stats`` was requested).
+ stats: Dict[str, float] = field(default_factory=dict)
+ #: Effective rule configuration, for the JSON payload.
+ rules: Dict[str, int] = field(default_factory=dict)
+ rules_source: str = ""
+ name_lang: Tuple[str, ...] = ()
+ #: Set by ``--redact-hosts`` so renderers can say hosts are pseudonyms.
+ hosts_redacted: bool = False
+
+ @property
+ def candidate_count(self) -> int:
+ """Candidates shown in this run (i.e. after baseline filtering)."""
+ return len(self.findings)
+
+ @property
+ def new_count(self) -> int:
+ return sum(1 for finding in self.findings if finding.status == "new")
+
+ @property
+ def known_findings(self) -> List[Finding]:
+ return [finding for finding in self.findings if finding.status == "known"]
+
+ @property
+ def confidence_counts(self) -> Dict[str, int]:
+ counts = {"high": 0, "medium": 0, "low": 0}
+ for finding in self.findings:
+ counts[finding.confidence] = counts.get(finding.confidence, 0) + 1
+ return counts
+
+
+def _mask_userinfo(url: str) -> str:
+ """Remove ``user:pass@`` from a URL's authority if present."""
+ parts = urlsplit(url)
+ if "@" not in parts.netloc:
+ return url
+ return urlunsplit(
+ (parts.scheme, "@" + parts.netloc.rsplit("@", 1)[1],
+ parts.path, "", "")
+ )
+
+
+def _safe_resource(request: Request) -> str:
+ """Scheme, host, port and path only: query strings are never included."""
+ return _mask_userinfo(request.url.display_resource)
+
+
+def _group_parameters(parameters: Sequence[Parameter]) -> List[Tuple[str, List[Parameter]]]:
+ """Group repeated parameters by location and canonical name, in order."""
+ groups: Dict[Tuple[str, str], List[Parameter]] = {}
+ order: List[Tuple[str, str]] = []
+ for parameter in parameters:
+ key = (parameter.location, canonical_name(parameter.name))
+ if key not in groups:
+ groups[key] = []
+ order.append(key)
+ groups[key].append(parameter)
+ return [(key[1], groups[key]) for key in order]
+
+
+def _dedupe_requests(requests: Iterable[Request]) -> List[Request]:
+ seen: set = set()
+ unique: List[Request] = []
+ for request in requests:
+ key = request.dedupe_key
+ if key in seen:
+ continue
+ seen.add(key)
+ unique.append(request)
+ return unique
+
+
+def analyze_requests(
+ requests: Sequence[Request], options: AnalysisOptions
+) -> Report:
+ """Analyse requests and return a deterministic :class:`Report`."""
+ report = Report(
+ min_score=options.min_score,
+ show_values=options.show_values,
+ sources=sorted({request.source_label for request in requests}),
+ rules=options.book.as_dict(),
+ rules_source=options.book.source or "defaults",
+ name_lang=tuple(options.name_lang),
+ )
+ ignored = {canonical_name(item) for item in options.ignore_params if item}
+
+ findings: List[Finding] = []
+ started = time.perf_counter()
+ entries = _dedupe_requests(requests)
+ if options.max_entries and len(entries) > options.max_entries:
+ entries = entries[: options.max_entries]
+ report.truncated_entries = len(_dedupe_requests(requests)) - options.max_entries
+ report.warnings.append(
+ f"--max-entries={options.max_entries}: analysis truncated; "
+ f"{report.truncated_entries} input entr(ies) ignored"
+ )
+ analyse_started = time.perf_counter()
+ for request in entries:
+ report.requests_analyzed += 1
+ resource = _safe_resource(request)
+ for canonical, occurrences in _group_parameters(request.parameters):
+ if canonical in ignored:
+ continue
+ report.parameters_analyzed += 1
+
+ best: Optional[Analysis] = None
+ best_value = ""
+ for parameter in occurrences:
+ analysis = analyze_parameter(
+ parameter.name,
+ parameter.value,
+ max_decode_passes=options.max_decode_passes,
+ extra_terms=options.extra_terms,
+ ignore=options.ignore_params,
+ min_score=options.min_score,
+ weak_names=options.weak_names,
+ book=options.book,
+ languages=options.name_lang,
+ fold=options.fold_names,
+ demote=options.demote_shapes,
+ )
+ if analysis.evidence and (best is None or analysis.score > best.score):
+ best = analysis
+ best_value = parameter.value
+ if best is None:
+ continue
+
+ first = occurrences[0]
+ location = first.location or LOCATION_QUERY
+ fp = fingerprint(
+ request.url.display_host,
+ location,
+ first.name,
+ best.primary_rule,
+ resource,
+ )
+ findings.append(
+ Finding(
+ fingerprint=fp,
+ host=request.url.display_host,
+ source_type=request.source_type,
+ source_label=request.source_label,
+ method=request.method,
+ location=location,
+ parameter=first.name,
+ occurrences=len(occurrences),
+ rule=best.primary_rule,
+ rules=list(best.rules),
+ reasons=list(best.reasons),
+ score=best.score,
+ confidence=best.confidence,
+ resource=resource,
+ value=sanitize_text(best_value) if options.show_values else None,
+ )
+ )
+
+ findings.sort(
+ key=lambda item: (
+ -item.score,
+ item.host,
+ item.location,
+ canonical_name(item.parameter),
+ item.source_label,
+ item.method,
+ truncate(item.resource, 300),
+ )
+ )
+ if options.dedupe_by != DEDUPE_NONE:
+ findings = _collapse_findings(findings, options.dedupe_by)
+ for index, finding in enumerate(findings, start=1):
+ finding.index = index
+ report.findings = findings
+ if options.measure:
+ report.stats = {
+ "parse_seconds": round(report.stats.get("parse_seconds", 0.0), 4),
+ "analyze_seconds": round(time.perf_counter() - analyse_started, 4),
+ "total_seconds": round(time.perf_counter() - started, 4),
+ "input_entries": len(entries),
+ "findings": len(findings),
+ }
+ return report
+
+
+def _collapse_findings(findings: List[Finding], mode: str) -> List[Finding]:
+ """Collapse the same parameter seen on several resources.
+
+ ``path`` one finding per host + location + parameter (default; the
+ occurrence count says how many resources mapped to it)
+ ``param`` one finding per parameter name, across hosts
+ ``none`` every (resource, parameter) pair stays separate
+ """
+ if mode == DEDUPE_PATH:
+ key = lambda f: (f.host, f.location, canonical_name(f.parameter)) # noqa: E731
+ elif mode == DEDUPE_PARAM:
+ key = lambda f: canonical_name(f.parameter) # noqa: E731
+ else: # pragma: no cover - guarded by the caller
+ return findings
+
+ collapsed: List[Finding] = []
+ seen: Dict[Tuple, Finding] = {}
+ for finding in findings:
+ lookup = key(finding)
+ existing = seen.get(lookup)
+ if existing is None:
+ seen[lookup] = finding
+ collapsed.append(finding)
+ continue
+ existing.occurrences += finding.occurrences
+ if finding.resource != existing.resource:
+ existing.note = (
+ f"also seen on {finding.resource}"
+ if not existing.note
+ else existing.note
+ )
+ return collapsed
+
+
+# ---------------------------------------------------------------------------
+# Stable fingerprints, baselines and suppression
+# ---------------------------------------------------------------------------
+def fingerprint(
+ host: str, location: str, parameter: str, rule: str, resource: str = ""
+) -> str:
+ """Deterministic 16-hex fingerprint for one finding identity.
+
+ Identity = host + parameter location + canonical parameter name + primary
+ rule + resource path. Values, scores and source labels are excluded so a
+ baseline stays valid when the same parameter reappears with new data or the
+ capture is taken from a different file.
+ """
+ material = "\x1f".join(
+ (
+ host.lower(),
+ location,
+ canonical_name(parameter),
+ rule,
+ resource,
+ )
+ )
+ return hashlib.sha256(material.encode("utf-8")).hexdigest()[:16]
+
+
+def _finding_identity(finding: Finding) -> Tuple[str, str, str, str, str]:
+ return (
+ finding.host,
+ finding.location,
+ canonical_name(finding.parameter),
+ finding.rule,
+ finding.resource,
+ )
+
+
+@dataclass
+class Baseline:
+ """A previous run's findings, plus review notes."""
+
+ source: str = ""
+ fingerprints: Dict[str, str] = field(default_factory=dict) # fp -> note
+ entries: List[Dict[str, object]] = field(default_factory=list)
+
+ @classmethod
+ def from_payload(cls, payload: object, source: str = "") -> "Baseline":
+ baseline = cls(source=source)
+ if not isinstance(payload, dict):
+ raise ValueError("baseline must be a JSON object")
+ raw = payload.get("findings", payload.get("suppressions", []))
+ if not isinstance(raw, list):
+ raise ValueError("baseline 'findings' must be an array")
+ for entry in raw:
+ if not isinstance(entry, dict):
+ continue
+ fp = entry.get("fingerprint")
+ if not isinstance(fp, str) or not fp:
+ continue
+ note = entry.get("note")
+ baseline.fingerprints[fp] = note if isinstance(note, str) else ""
+ baseline.entries.append(entry)
+ return baseline
+
+
+def apply_baseline(report: Report, baseline: Baseline, show_known: bool = False) -> Report:
+ """Mark findings present in ``baseline`` as known and (optionally) hide them."""
+ report.mode = "diff"
+ report.baseline_source = baseline.source
+ for finding in report.findings:
+ fp = finding.fingerprint
+ if fp in baseline.fingerprints:
+ finding.status = "known"
+ finding.note = baseline.fingerprints.get(fp, "") or ""
+ report.known_count += 1
+ seen = {finding.fingerprint for finding in report.findings}
+ for entry in baseline.entries:
+ fp = entry.get("fingerprint")
+ if fp not in seen:
+ report.resolved.append(dict(entry))
+ if not show_known:
+ report.findings = [f for f in report.findings if f.status == "new"]
+ return report
+
+
+def summarize(report: Report) -> str:
+ """One-line summary used by renderers and the CLI stderr trailer."""
+ counts = report.confidence_counts
+ text = (
+ f"{report.requests_analyzed} request(s), {report.parameters_analyzed} "
+ f"parameter(s), {report.candidate_count} candidate(s) "
+ f"(high {counts.get('high', 0)}, medium {counts.get('medium', 0)}, "
+ f"low {counts.get('low', 0)}), {report.skipped} input line(s) skipped"
+ )
+ if report.mode == "diff":
+ text += (
+ f"; diff vs {report.baseline_source or 'baseline'}: "
+ f"{report.new_count} new, {report.known_count} known, "
+ f"{len(report.resolved)} resolved"
+ )
+ return text
diff --git a/pathscope/extra_formats.py b/pathscope/extra_formats.py
new file mode 100644
index 0000000..322edd1
--- /dev/null
+++ b/pathscope/extra_formats.py
@@ -0,0 +1,693 @@
+"""Additional local input formats for PathScope.
+
+Everything here is pure parsing of files the user already has:
+
+``burp``
+ Burp Suite *proxy history* XML export (``- `` with a raw
+ request block). Only the request line, ``Host`` header and form/JSON body
+ are read. Responses are ignored.
+
+``openapi``
+ Swagger 2.0 / OpenAPI 3.x descriptions, reduced to a parameter inventory:
+ every declared query/form/path parameter name becomes an analyzed
+ parameter with no value of its own (only names can be judged).
+
+``raw``
+ A single raw HTTP request (``GET /path?file=x HTTP/1.1`` + headers).
+ Multiple requests in one file may be separated by a ``###`` line.
+ ``Host`` is taken from the header, so this works with curl ``--trace``
+ style copies, Repeater saves and hand-written snippets.
+
+``httpx`` / ``ffuf`` / ``gobuster`` / ``katana`` / ``nuclei``
+ Line-oriented recon output is reduced to the URLs it contains. JSONL export
+ modes (httpx ``-json``, nuclei ``-jsonl``, katana ``-jsonl``) are also
+ accepted; only URL-like fields are used.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import xml.etree.ElementTree as ET
+from typing import Any, Dict, List, Optional, Tuple
+from urllib.parse import unquote_plus, urlsplit
+
+from .sources import (
+ LOCATION_FORM,
+ LOCATION_JSON,
+ LOCATION_QUERY,
+ SOURCE_FILE,
+ HarError,
+ LoadResult,
+ Parameter,
+ Request,
+ URLInfo,
+ URLParseError,
+ _as_text,
+ _form_parameters,
+ _json_parameters,
+ canonical,
+ parse_url,
+ query_parameters,
+ split_query,
+)
+from .textutil import sanitize_text
+
+# Input format identifiers.
+INPUT_FORMAT_BURP = "burp"
+INPUT_FORMAT_OPENAPI = "openapi"
+INPUT_FORMAT_RAW = "raw"
+INPUT_FORMAT_HTTPX = "httpx"
+INPUT_FORMAT_FFUF = "ffuf"
+INPUT_FORMAT_NUCLEI = "nuclei"
+
+#: Identifier used in reports for every line-oriented recon export.
+SOURCE_RECON = "recon"
+
+#: Hard limits so a hostile or accidental huge file cannot exhaust memory.
+MAX_XML_BYTES = 64 * 1024 * 1024
+MAX_REQUEST_BYTES = 4 * 1024 * 1024
+
+URL_IN_TEXT_RE = re.compile(r"https?://[^\s\"'<>\\]+", re.IGNORECASE)
+STATUS_SUFFIX_RE = re.compile(
+ r"\s+\[(?:status[- ]?code:\s*)?\d{1,3}(?:,\s*\d+\s*(?:B|KB|MB))?\]\s*$",
+ re.IGNORECASE,
+)
+
+
+# ---------------------------------------------------------------------------
+# Burp Suite proxy-history XML
+# ---------------------------------------------------------------------------
+def looks_like_burp(text: str, path: str = "") -> bool:
+ head = text.lstrip("\ufeff \t\r\n")[:8192].lower()
+ if " Tuple[str, str, Optional[str]]:
+ """Return ``(request_target, host, body)`` from one Burp ``
- ``."""
+ request = item.find("request")
+ if request is None:
+ raise HarError("missing element")
+ if (request.get("base64") or "").lower() == "true":
+ import base64
+
+ try:
+ raw = base64.b64decode(request.text or "", validate=False).decode(
+ "latin-1", "replace"
+ )
+ except (ValueError, TypeError) as exc: # pragma: no cover - defensive
+ raise HarError(f"invalid base64 request ({exc})") from exc
+ else:
+ raw = request.text or ""
+ raw = raw[:MAX_REQUEST_BYTES]
+ if not raw.strip():
+ raise HarError("empty request block")
+
+ head, _sep, body = raw.replace("\r\n", "\n").partition("\n\n")
+ lines = head.split("\n")
+ request_line = lines[0].strip()
+ parts = request_line.split()
+ if len(parts) < 2:
+ raise HarError("malformed request line")
+ target = parts[1]
+
+ host = ""
+ for line in lines[1:]:
+ name, _colon, value = line.partition(":")
+ if name.strip().lower() == "host":
+ host = value.strip()
+ break
+
+ # Absolute-form targets (proxy style) already contain the host.
+ if target.lower().startswith("http://") or target.lower().startswith("https://"):
+ return target, "", body
+ if not host:
+ raise HarError("request has no Host header")
+ scheme = "https" if "https" in request_line.lower() else "http"
+ if not target.startswith("/"):
+ target = "/" + target
+ return f"{scheme}://{host}{target}", host, body
+
+
+def _burp_request_parameters(
+ body: str, content_type: str, label: str, warnings: List[str]
+) -> List[Parameter]:
+ if not body:
+ return []
+ lowered = (content_type or "").lower()
+ if "application/json" in lowered:
+ try:
+ payload = json.loads(body)
+ except ValueError as exc:
+ warnings.append(f"{label}: malformed JSON body skipped ({exc})")
+ return []
+ return _json_parameters(payload, warnings, label)
+ if "x-www-form-urlencoded" in lowered or not lowered:
+ pairs = split_query(body.strip())
+ if pairs and "=" in body:
+ decoded_pairs = []
+ for name, raw_value in pairs:
+ try:
+ decoded_value = unquote_plus(raw_value)
+ except (UnicodeError, ValueError): # pragma: no cover - defensive
+ decoded_value = raw_value
+ decoded_pairs.append((name, sanitize_text(decoded_value)[:20000]))
+ return [
+ Parameter(name=name, value=value, location=LOCATION_FORM)
+ for name, value in decoded_pairs
+ if name
+ ]
+ if "multipart/form-data" in lowered:
+ return _multipart_parameters(body, label)
+ return []
+
+
+BOUNDARY_RE = re.compile(r"boundary=\"?([^\";]+)\"?", re.IGNORECASE)
+PART_NAME_RE = re.compile(
+ r'content-disposition:[^\r\n]*\bname="([^"]+)"([^\r\n]*)', re.IGNORECASE
+)
+PART_FILENAME_RE = re.compile(r'\bfilename="([^"]*)"', re.IGNORECASE)
+
+
+def _multipart_parameters(body: str, label: str) -> List[Parameter]:
+ """Extract part names (and file names) from a multipart body."""
+ parameters: List[Parameter] = []
+ for part in re.split(r"\r?\n--[^\r\n]+", body):
+ match = PART_NAME_RE.search(part)
+ if not match:
+ continue
+ name = match.group(1)
+ filename = PART_FILENAME_RE.search(part)
+ if filename:
+ value = filename.group(1)
+ else:
+ _head, _sep, content = part.partition("\r\n\r\n")
+ if not _sep:
+ _head, _sep, content = part.partition("\n\n")
+ value = content.strip()
+ parameters.append(
+ Parameter(
+ name=sanitize_text(name),
+ value=sanitize_text(value)[:20000],
+ location=LOCATION_FORM,
+ )
+ )
+ return parameters
+
+
+def load_burp(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse a Burp proxy-history XML export. Raises :class:`HarError`."""
+ source_label = source_label or label
+ if len(text.encode("utf-8", "ignore")) > MAX_XML_BYTES:
+ raise HarError(f"{label}: file exceeds the {MAX_XML_BYTES // (1024 * 1024)} MB limit")
+ try:
+ root = ET.fromstring(text.lstrip("\ufeff"))
+ except ET.ParseError as exc:
+ raise HarError(f"{label}: not valid XML ({exc})") from exc
+
+ items = root.findall(".//item")
+ if not items:
+ raise HarError(f"{label}: no
- elements found (export Burp proxy history as XML)")
+
+ result = LoadResult()
+ seen = set()
+ for index, item in enumerate(items):
+ item_label = f"{label} item {index}"
+ try:
+ url, _host, body = _burp_raw_request(item)
+ info = parse_url(url)
+ content_type = ""
+ request_el = item.find("request")
+ if request_el is not None:
+ raw_text = request_el.text or ""
+ for line in raw_text.replace("\r\n", "\n").split("\n")[1:]:
+ name, _colon, value = line.partition(":")
+ if name.strip().lower() == "content-type":
+ content_type = value.strip()
+ break
+ parameters = query_parameters(info.query)
+ parameters.extend(
+ _burp_request_parameters(body, content_type, item_label, result.warnings)
+ )
+ method = (item.findtext("method") or "GET").strip().upper()
+ if not method:
+ raw_text = (item.findtext("request") or "").split("\n", 1)[0]
+ pieces = raw_text.split()
+ method = pieces[0].upper() if pieces else "GET"
+ except (HarError, URLParseError) as exc:
+ result.warnings.append(f"{item_label}: skipped ({exc})")
+ result.skipped += 1
+ continue
+ except Exception as exc: # noqa: BLE001 - never abort the run
+ result.warnings.append(f"{item_label}: skipped unreadable item ({exc})")
+ result.skipped += 1
+ continue
+
+ key = (method, info.raw, tuple((p.location, p.name, p.value) for p in parameters))
+ if key in seen:
+ continue
+ seen.add(key)
+ result.requests.append(
+ Request(
+ url=info,
+ source_type="burp",
+ source_label=source_label,
+ parameters=parameters,
+ method=method,
+ index=len(result.requests),
+ )
+ )
+ return result
+
+
+def load_burp_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_burp(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# OpenAPI / Swagger
+# ---------------------------------------------------------------------------
+HTTP_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
+
+
+def looks_like_openapi(payload: Any) -> bool:
+ return isinstance(payload, dict) and (
+ "openapi" in payload or "swagger" in payload
+ ) and isinstance(payload.get("paths"), dict)
+
+
+def _schema_parameter_names(schema: Any, warnings: List[str], label: str) -> List[Parameter]:
+ """Flatten an OpenAPI schema's properties into named parameters (no values)."""
+ parameters: List[Parameter] = []
+
+ def walk(node: Any, prefix: str, depth: int) -> None:
+ if depth > 8 or len(parameters) > 2000:
+ return
+ if not isinstance(node, dict):
+ return
+ properties = node.get("properties")
+ if isinstance(properties, dict):
+ for name, child in properties.items():
+ path = f"{prefix}.{name}" if prefix else str(name)
+ kind = child.get("type") if isinstance(child, dict) else None
+ if kind in (None, "object") and isinstance(child, dict) and "properties" in child:
+ walk(child, path, depth + 1)
+ else:
+ parameters.append(
+ Parameter(name=path, value="", location=LOCATION_JSON)
+ )
+ items = node.get("items")
+ if isinstance(items, dict):
+ walk(items, f"{prefix}[]" if prefix else "[]", depth + 1)
+
+ walk(schema, "", 0)
+ return parameters
+
+
+def _openapi_requests(payload: Any, warnings: List[str], label: str) -> List[Request]:
+ """Build one synthetic GET request per path+method with declared parameters."""
+ base_url = ""
+ servers = payload.get("servers")
+ if isinstance(servers, list) and servers and isinstance(servers[0], dict):
+ base_url = str(servers[0].get("url") or "")
+ if not base_url and isinstance(payload.get("host"), str):
+ scheme = "https"
+ if isinstance(payload.get("schemes"), list) and payload["schemes"]:
+ scheme = str(payload["schemes"][0])
+ base_url = f"{scheme}://{payload['host']}{payload.get('basePath') or ''}"
+ try:
+ parsed = urlsplit(base_url) if base_url else None
+ host = (parsed.hostname if parsed else "") or "openapi.local"
+ scheme = (parsed.scheme if parsed else "") or "https"
+ except ValueError:
+ host, scheme = "openapi.local", "https"
+
+ requests: List[Request] = []
+ paths = payload.get("paths") or {}
+ for raw_path, path_item in paths.items():
+ if not isinstance(path_item, dict):
+ continue
+ for method in HTTP_METHODS:
+ operation = path_item.get(method)
+ if not isinstance(operation, dict):
+ continue
+ parameters: List[Parameter] = []
+ declared = list(path_item.get("parameters") or []) + list(
+ operation.get("parameters") or []
+ )
+ for entry in declared:
+ if not isinstance(entry, dict):
+ continue
+ if "$ref" in entry and "name" not in entry:
+ # Unresolved $ref: name unknown, note it and move on.
+ warnings.append(
+ f"{label}: unresolved parameter $ref in {method.upper()} {raw_path}"
+ )
+ continue
+ name = entry.get("name")
+ if not isinstance(name, str) or not name:
+ continue
+ location = str(entry.get("in") or "query").lower()
+ if location not in ("query", "formData", "path", "header", "cookie"):
+ location = "query"
+ if location == "header":
+ # Header names are not path consumers in this model.
+ continue
+ parameters.append(
+ Parameter(
+ name=name,
+ value="",
+ location=LOCATION_FORM if location == "formData" else LOCATION_QUERY,
+ )
+ )
+
+ request_body = operation.get("requestBody")
+ if isinstance(request_body, dict):
+ content = request_body.get("content")
+ if isinstance(content, dict):
+ for mime, media in content.items():
+ if not isinstance(media, dict):
+ continue
+ if "json" in str(mime):
+ parameters.extend(
+ _schema_parameter_names(
+ media.get("schema"), warnings, label
+ )
+ )
+ elif "form" in str(mime):
+ schema = media.get("schema")
+ if isinstance(schema, dict):
+ properties = schema.get("properties")
+ if isinstance(properties, dict):
+ for prop in properties:
+ parameters.append(
+ Parameter(
+ name=str(prop),
+ value="",
+ location=LOCATION_FORM,
+ )
+ )
+ # Swagger 2.0 body parameter
+ for entry in declared:
+ if isinstance(entry, dict) and entry.get("in") == "body":
+ schema = entry.get("schema")
+ if isinstance(schema, dict):
+ parameters.extend(
+ _schema_parameter_names(schema, warnings, label)
+ )
+
+ path_with_params = raw_path or "/"
+ try:
+ info = URLInfo(
+ raw=f"{scheme}://{host}{path_with_params}",
+ scheme=scheme,
+ host=host,
+ port=None,
+ path=path_with_params,
+ query="",
+ )
+ except Exception: # pragma: no cover - defensive
+ continue
+ if not parameters:
+ continue
+ # de-duplicate declared names within the operation
+ unique: List[Parameter] = []
+ seen_names = set()
+ for parameter in parameters:
+ key = (parameter.location, canonical(parameter.name))
+ if key in seen_names:
+ continue
+ seen_names.add(key)
+ unique.append(parameter)
+ requests.append(
+ Request(
+ url=info,
+ source_type="openapi",
+ source_label=label,
+ parameters=unique,
+ method=method.upper(),
+ index=len(requests),
+ )
+ )
+ return requests
+
+
+def load_openapi(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse an OpenAPI/Swagger document into a parameter inventory."""
+ source_label = source_label or label
+ try:
+ payload = json.loads(text.lstrip("\ufeff"))
+ except ValueError as exc:
+ raise HarError(f"{label}: not valid JSON ({exc})") from exc
+ if not looks_like_openapi(payload):
+ raise HarError(
+ f"{label}: not an OpenAPI/Swagger document (expected 'openapi'/'swagger' "
+ "and a 'paths' object)"
+ )
+ result = LoadResult()
+ result.requests = _openapi_requests(payload, result.warnings, source_label)
+ if not result.requests:
+ result.warnings.append(f"{label}: document declares no usable parameters")
+ return result
+
+
+def load_openapi_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_openapi(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# Raw HTTP requests
+# ---------------------------------------------------------------------------
+def looks_like_raw_http(text: str, path: str = "") -> bool:
+ stripped = text.lstrip("\ufeff \t\r\n")
+ first = stripped.split("\n", 1)[0].strip()
+ return bool(re.match(r"^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\S+\s+HTTP/\d\.\d$", first))
+
+
+def load_raw_http(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse one or more raw HTTP requests separated by ``###`` lines."""
+ source_label = source_label or label
+ result = LoadResult()
+ chunks = re.split(r"(?m)^###+\s*$", text.lstrip("\ufeff"))
+ seen = set()
+ for index, chunk in enumerate(chunks):
+ chunk = chunk.strip("\r\n")
+ if not chunk.strip():
+ continue
+ chunk_label = f"{label} request {index + 1}"
+ try:
+ info, parameters, method = _parse_raw_http_chunk(chunk, chunk_label, result.warnings)
+ except (HarError, URLParseError) as exc:
+ result.warnings.append(f"{chunk_label}: skipped ({exc})")
+ result.skipped += 1
+ continue
+ key = (method, info.raw, tuple((p.location, p.name, p.value) for p in parameters))
+ if key in seen:
+ continue
+ seen.add(key)
+ result.requests.append(
+ Request(
+ url=info,
+ source_type="raw",
+ source_label=source_label,
+ parameters=parameters,
+ method=method,
+ index=len(result.requests),
+ )
+ )
+ if not result.requests:
+ raise HarError(f"{label}: no usable HTTP requests found")
+ return result
+
+
+def _parse_raw_http_chunk(
+ chunk: str, label: str, warnings: List[str]
+) -> Tuple[URLInfo, List[Parameter], str]:
+ chunk = chunk[:MAX_REQUEST_BYTES]
+ head, _sep, body = chunk.replace("\r\n", "\n").partition("\n\n")
+ lines = [line for line in head.split("\n")]
+ request_line = lines[0].strip() if lines else ""
+ match = re.match(r"^([A-Za-z]+)\s+(\S+)\s+HTTP/\d(?:\.\d)?$", request_line)
+ if not match:
+ raise HarError("malformed request line")
+ method = match.group(1).upper()
+ target = match.group(2)
+
+ headers: Dict[str, str] = {}
+ for line in lines[1:]:
+ if not line.strip():
+ continue
+ if line[:1] in (" ", "\t"): # folded header
+ continue
+ name, _colon, value = line.partition(":")
+ if not _colon:
+ continue
+ headers.setdefault(name.strip().lower(), value.strip())
+
+ host = headers.get("host", "")
+ if target.lower().startswith(("http://", "https://")):
+ url = target
+ else:
+ if not host:
+ raise HarError("request has no Host header")
+ scheme = "https" if "https" in headers.get("x-forwarded-proto", "").lower() else "http"
+ if not target.startswith("/"):
+ target = "/" + target
+ url = f"{scheme}://{host}{target}"
+
+ info = parse_url(url)
+ parameters = query_parameters(info.query)
+ content_type = headers.get("content-type", "")
+ parameters.extend(_burp_request_parameters(body, content_type, label, warnings))
+ return info, parameters, method
+
+
+def load_raw_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_raw_http(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# Recon / tool exports (httpx, ffuf, gobuster, katana, nuclei, ...)
+# ---------------------------------------------------------------------------
+def _urls_from_line(line: str) -> List[str]:
+ """Extract URL candidates from a tool-output line, including JSONL."""
+ stripped = line.strip()
+ if not stripped:
+ return []
+ if stripped.startswith("{"):
+ try:
+ payload = json.loads(stripped)
+ except ValueError:
+ pass
+ else:
+ found: List[str] = []
+ if isinstance(payload, dict):
+ for key in ("url", "input", "endpoint", "matched-at", "host"):
+ value = payload.get(key)
+ if isinstance(value, str) and value.lower().startswith(("http://", "https://")):
+ found.append(value)
+ break
+ return found
+ # Strip ffuf/gobuster status suffix, then find URL-looking tokens.
+ cleaned = STATUS_SUFFIX_RE.sub("", stripped)
+ urls = URL_IN_TEXT_RE.findall(cleaned)
+ if urls:
+ return [urls[0]]
+ return []
+
+
+def load_recon_text(
+ text: str, label: str, source_type: str = "recon", source_label: Optional[str] = None
+) -> LoadResult:
+ """Reduce line/JSONL recon output to analysable URLs."""
+ source_label = source_label or label
+ result = LoadResult()
+ urls: List[str] = []
+ for line_number, line in enumerate(text.splitlines(), start=1):
+ for url in _urls_from_line(line):
+ urls.append(url)
+ if not urls:
+ raise HarError(
+ f"{label}: no http(s) URLs found in {source_type} output"
+ )
+ seen = set()
+ for index, raw in enumerate(urls):
+ if raw in seen:
+ continue
+ try:
+ info = parse_url(raw)
+ except URLParseError as exc:
+ result.warnings.append(f"{label} line {index + 1}: skipped malformed URL ({exc})")
+ result.skipped += 1
+ continue
+ seen.add(raw)
+ result.requests.append(
+ Request(
+ url=info,
+ source_type=source_type,
+ source_label=source_label,
+ parameters=query_parameters(info.query),
+ method="GET",
+ index=len(result.requests),
+ )
+ )
+ return result
+
+
+def load_recon_file(path: str, source_type: str = "recon") -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_recon_text(
+ read_text(path), os.path.basename(path) or path, source_type, source_label=path
+ )
+
+
+# ---------------------------------------------------------------------------
+# Detection helpers
+# ---------------------------------------------------------------------------
+def detect_extra_format(text: str, path: str = "") -> Optional[str]:
+ """Return one of the extra format ids, or ``None`` if nothing matches."""
+ lowered_path = (path or "").lower()
+ stripped = text.lstrip("\ufeff \t\r\n")
+ if looks_like_burp(text, path):
+ return INPUT_FORMAT_BURP
+ if stripped.startswith("{"):
+ try:
+ payload = json.loads(stripped)
+ except ValueError:
+ payload = None
+ if looks_like_openapi(payload):
+ return INPUT_FORMAT_OPENAPI
+ if lowered_path.endswith((".yaml", ".yml")):
+ # YAML OpenAPI files cannot be parsed with the standard library.
+ if "openapi" in text[:2048].lower() or "swagger" in text[:2048].lower():
+ return "openapi-yaml"
+ if looks_like_raw_http(text, path):
+ return INPUT_FORMAT_RAW
+ if lowered_path.endswith((".xml",)):
+ return INPUT_FORMAT_BURP if " LoadResult:
+ if fmt == INPUT_FORMAT_BURP:
+ return load_burp_file(path)
+ if fmt == INPUT_FORMAT_OPENAPI:
+ return load_openapi_file(path)
+ if fmt == INPUT_FORMAT_RAW:
+ return load_raw_file(path)
+ if fmt == "openapi-yaml":
+ raise HarError(
+ f"{path}: YAML OpenAPI files are not supported (standard library only); "
+ "convert to JSON with `python3 -c \"import sys,json,yaml;"
+ "json.dump(yaml.safe_load(sys.stdin), sys.stdout)\" < spec.yaml > spec.json`"
+ )
+ return load_recon_file(path, fmt)
+
+
+def load_extra_text(text: str, fmt: str, label: str) -> LoadResult:
+ if fmt == INPUT_FORMAT_BURP:
+ return load_burp(text, label)
+ if fmt == INPUT_FORMAT_OPENAPI:
+ return load_openapi(text, label)
+ if fmt == INPUT_FORMAT_RAW:
+ return load_raw_http(text, label)
+ return load_recon_text(text, label, fmt)
diff --git a/pathscope/extractor.py b/pathscope/extractor.py
new file mode 100644
index 0000000..d128980
--- /dev/null
+++ b/pathscope/extractor.py
@@ -0,0 +1,373 @@
+"""Offline URL extraction from local HTML and JavaScript (``--extract``).
+
+The usual starting point for a review is "here is the front-end, what does it
+call?". Normally that means reading a bundle by hand or watching a proxy. This
+module reads **files you already have** and pulls the endpoint strings out:
+
+* ``fetch("…")``, ``axios.get("…")``, ``xhr.open("GET", "…")``, ``$.ajax``,
+* ``href`` / ``src`` / ``action`` / ``formaction`` attributes and ``